Class: Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/json_mapper/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, source_attributes, type, options = {}) ⇒ Attribute

Returns a new instance of Attribute.



5
6
7
8
9
10
11
12
# File 'lib/json_mapper/attribute.rb', line 5

def initialize(name, source_attributes, type, options = {})
  
  self.name = name
  self.source_attributes = source_attributes.is_a?(Array) ? source_attributes : [ source_attributes ]
  self.type = type
  self.options = options

end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



3
4
5
# File 'lib/json_mapper/attribute.rb', line 3

def name
  @name
end

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/json_mapper/attribute.rb', line 3

def options
  @options
end

#source_attributesObject

Returns the value of attribute source_attributes.



3
4
5
# File 'lib/json_mapper/attribute.rb', line 3

def source_attributes
  @source_attributes
end

#typeObject

Returns the value of attribute type.



3
4
5
# File 'lib/json_mapper/attribute.rb', line 3

def type
  @type
end

Instance Method Details

#method_nameObject



14
15
16
# File 'lib/json_mapper/attribute.rb', line 14

def method_name
  @method_name ||= self.name.to_s.tr("-", "_")
end

#self_referential?Boolean

Returns:



18
19
20
# File 'lib/json_mapper/attribute.rb', line 18

def self_referential?
  self.source_attributes.include?("self")
end

#typecast(value) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/json_mapper/attribute.rb', line 22

def typecast(value)

  return value if value.nil?

  if self.type == String then return value.to_s
  elsif self.type == DelimitedString
    self.options[:delimiter] ||= ","
    return value.split(self.options[:delimiter])
  elsif self.type == Integer
    begin
      return value.to_i
    rescue
      return nil
    end
  elsif self.type == Float
    begin
      return value.to_f
    rescue
      return nil
    end
  elsif self.type == Boolean then return %w(true t 1).include?(value.to_s.downcase)
  elsif self.type == DateTime then return Date.parse(value.to_s)
  else

    # If our type is a JSONMapper instance, delegate the
    # mapping to that class
    if self.type.new.is_a?(JSONMapper)
      return self.type.parse_json(value)
    else
      return value
    end

  end

end