Module: JSONMapper::ClassMethods
- Defined in:
- lib/json_mapper.rb
Instance Method Summary collapse
- #attributes ⇒ Object
- #json_attribute(name, *args) ⇒ Object
- #json_attributes(name, *args) ⇒ Object
- #parse(data) ⇒ Object
- #parse_json(json) ⇒ Object
Instance Method Details
#attributes ⇒ Object
36 37 38 |
# File 'lib/json_mapper.rb', line 36 def attributes @attributes[to_s] || [] end |
#json_attribute(name, *args) ⇒ Object
14 15 16 17 18 19 20 21 22 23 |
# File 'lib/json_mapper.rb', line 14 def json_attribute(name, *args) source_attributes, type = extract_attribute_data(name, *args) attribute = Attribute.new(name, source_attributes, type) @attributes[to_s] ||= [] @attributes[to_s] << attribute attr_accessor attribute.method_name.to_sym end |
#json_attributes(name, *args) ⇒ Object
25 26 27 28 29 30 31 32 33 34 |
# File 'lib/json_mapper.rb', line 25 def json_attributes(name, *args) source_attributes, type = extract_attribute_data(name, *args) attribute = AttributeList.new(name, source_attributes, type) @attributes[to_s] ||= [] @attributes[to_s] << attribute attr_accessor attribute.method_name.to_sym end |
#parse(data) ⇒ Object
40 41 42 43 44 45 46 47 48 |
# File 'lib/json_mapper.rb', line 40 def parse(data) # Parse the data into a hash json = JSON.parse(data, { :symbolize_names => true }) # Parse the JSON data structure parse_json(json) end |
#parse_json(json) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/json_mapper.rb', line 50 def parse_json(json) # Create a new instance of ourselves instance = new # Instantiate all AttributeList instances attributes.each do |attribute| if attribute.is_a?(AttributeList) instance.send("#{attribute.name}=", attribute.dup) end end # Traverse all defined attributes and assign data from the # JSON data structure attributes.each do |attribute| if is_mapped?(attribute, json) value = mapping_value(attribute, json) if attribute.is_a?(AttributeList) value = [ value ] unless value.is_a?(Array) value.each do |v| instance.send("#{attribute.name}") << build_attribute(attribute.name, attribute.type).typecast(v) end else instance.send("#{attribute.name}=".to_sym, attribute.typecast(value)) end end end instance end |