Module: Representable::JSON

Extended by:
Hash::ClassMethods
Includes:
Hash
Included in:
Collection
Defined in:
lib/representable/json.rb,
lib/representable/json/hash.rb,
lib/representable/json/collection.rb

Overview

Brings #to_json and #from_json to your object.

Defined Under Namespace

Modules: ClassMethods, Collection, Hash

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Hash::ClassMethods

collection_representer_class, format_engine

Class Method Details

.included(base) ⇒ Object



16
17
18
19
20
21
22
# 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?
    register_feature Representable::JSON
  end
end

Instance Method Details

#from_json(data, *args) ⇒ Object Also known as: parse

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 = MultiJson.load(data)
  from_hash(data, *args)
end

#to_json(*args) ⇒ Object Also known as: render

Returns a JSON string representing this object.



43
44
45
# File 'lib/representable/json.rb', line 43

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