class Contrackt::Props::Prop

Attributes

key[R]

Public Class Methods

new(key) click to toggle source
# File lib/contrackt/props.rb, line 5
def initialize(key)
  unpack(key)
end

Public Instance Methods

hashify(value) click to toggle source
# File lib/contrackt/props.rb, line 20
def hashify(value)
  { key => hashify_value(value) }
end
parse(json) click to toggle source
# File lib/contrackt/props.rb, line 9
def parse(json)
  target = json[key]
  if @custom_parser
    @custom_parser[target]
  elsif @klass
    @klass.new(target)
  else
    target
  end
end
with_custom_parser(&block) click to toggle source
# File lib/contrackt/props.rb, line 24
def with_custom_parser(&block)
  @custom_parser = block
end

Private Instance Methods

hashify_value(value) click to toggle source
# File lib/contrackt/props.rb, line 44
def hashify_value(value)
  if (value.is_a? Array)
    value.map {|value| hashify_value(value)}
  elsif value.respond_to?(:to_hash)
    value.to_hash
  else
    value
  end
end
unpack(key) click to toggle source
# File lib/contrackt/props.rb, line 29
def unpack(key)
  case key
  when String
    @key = key
  when Symbol
    @key = key
  when Hash
    raise ArgumentError, "Prop can only take one key-value pair" unless key.length == 1
    @key = key.keys[0]
    @klass = key.values[0]
  else
    raise ArgumentError, "Prop can only take a string or a hash"
  end
end