Class: Babel::Deserializer

Inherits:
Object
  • Object
show all
Defined in:
lib/babel/deserializer.rb

Instance Method Summary collapse

Constructor Details

#initialize(model_class) ⇒ Deserializer

Returns a new instance of Deserializer.



4
5
6
# File 'lib/babel/deserializer.rb', line 4

def initialize(model_class)
  @model_class = model_class
end

Instance Method Details

#from_hash(data, options = nil) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/babel/deserializer.rb', line 35

def from_hash(data, options = nil)
  filter.use(options) if options
  if root = filter.options[:root]
    if data.is_a? Array
      root = root.to_s
      data.collect{ |d| @model_class.new(filter.filter(d[root])) }
    else
      @model_class.new(filter.filter(data[root.to_s]))
    end
  else
    if data.is_a? Array
      data.collect{ |d| @model_class.new(filter.filter(d)) }
    else
      @model_class.new(filter.filter(data))
    end
  end
end

#from_json(json, options = nil) ⇒ Object



53
54
55
56
# File 'lib/babel/deserializer.rb', line 53

def from_json(json, options = nil)
  data = JSON.parse(json)
  from_hash(data, options)
end

#from_yaml(yaml, options = nil) ⇒ Object



58
59
60
61
# File 'lib/babel/deserializer.rb', line 58

def from_yaml(yaml, options = nil)
  data = YAML.load_stream(StringIO.new(yaml)).documents
  from_hash(data, options)
end

#use(context_or_options) ⇒ Object



30
31
32
33
# File 'lib/babel/deserializer.rb', line 30

def use(context_or_options)
  filter.use(context_or_options)
  self
end