Module: Representable::Hash

Included in:
YAML
Defined in:
lib/representable/hash.rb,
lib/representable/bindings/hash_bindings.rb

Overview

The generic representer. Brings #to_hash and #from_hash to your object. If you plan to write your own representer for a new media type, try to use this module (e.g., check how JSON reuses Hash’s internal architecture).

Defined Under Namespace

Modules: ClassMethods, ObjectBinding Classes: CollectionBinding, HashBinding, PropertyBinding

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
13
14
15
# File 'lib/representable/hash.rb', line 10

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 = {}, format = :hash) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/representable/hash.rb', line 25

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

#to_hash(options = {}, format = :hash) ⇒ Object



33
34
35
36
37
38
39
# File 'lib/representable/hash.rb', line 33

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