Module: Representable::JSON

Defined in:
lib/representable/json.rb,
lib/representable/bindings/json_bindings.rb

Overview

Brings #to_xml, #to_hash, #from_xml and #from_hash to your object.

Note: The authorative methods are #to_hash and #from_hash, if you override #to_json instead, things might work as expected.

Defined Under Namespace

Modules: ClassMethods Classes: Binding, ObjectBinding, TextBinding

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.binding_for_definition(definition) ⇒ Object



11
12
13
14
# File 'lib/representable/json.rb', line 11

def self.binding_for_definition(definition)
  return ObjectBinding.new(definition) if definition.typed?
  TextBinding.new(definition)
end

.included(base) ⇒ Object



16
17
18
19
20
21
# File 'lib/representable/json.rb', line 16

def self.included(base)
  base.class_eval do
    include Representable # either in Hero or HeroRepresentation.
    extend ClassMethods # DISCUSS: do that only for classes?
  end
end

Instance Method Details

#from_hash(data, options = {}) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/representable/json.rb', line 42

def from_hash(data, options={})
  if wrap = options[:wrap] || representation_wrap
    data = data[wrap.to_s]
  end
  
  update_properties_from(data, options, JSON)
end

#from_json(data, *args) ⇒ Object

Parses the body as JSON and delegates to #from_hash.



37
38
39
40
# File 'lib/representable/json.rb', line 37

def from_json(data, *args)
  data = ::JSON[data]
  from_hash(data, *args)
end

#to_hash(options = {}) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/representable/json.rb', line 50

def to_hash(options={})
  hash = create_representation_with({}, options, JSON)
  
  return hash unless wrap = options[:wrap] || representation_wrap
  
  {wrap => hash}
end

#to_json(*args) ⇒ Object

Returns a JSON string representing this object.



59
60
61
# File 'lib/representable/json.rb', line 59

def to_json(*args)
  to_hash(*args).to_json
end