Class: Deserializer::Base

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.attrsObject

Returns the value of attribute attrs.



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

def attrs
  @attrs
end

Instance Attribute Details

#objectObject

Returns the value of attribute object.



51
52
53
# File 'lib/deserializer/base.rb', line 51

def object
  @object
end

Class Method Details

.attribute(attr, options = {}) ⇒ Object



15
16
17
18
19
# File 'lib/deserializer/base.rb', line 15

def attribute(attr, options = {})
  self.attrs ||= {}
  key = options.fetch(:key, attr)
  self.attrs[key] = {attr: attr, options: options}
end

.attributes(*attrs) ⇒ Object

deserializer interface functions



8
9
10
11
12
13
# File 'lib/deserializer/base.rb', line 8

def attributes(*attrs)
  self.attrs ||= {}
  attrs.each do |attr|
    self.attrs[attr] = {attr: attr, options: {}}
  end
end

.belongs_to(*args) ⇒ Object

Raises:



35
36
37
# File 'lib/deserializer/base.rb', line 35

def belongs_to(*args)
  raise DeserializerError, class: self, message: "belongs_to is currently unsupported."
end

.from_params(params = {}) ⇒ Object

deserializer usage functions



41
42
43
# File 'lib/deserializer/base.rb', line 41

def from_params( params = {} )
  self.new({}, params).deserialize
end

.has_many(*args) ⇒ Object

Raises:



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

def has_many(*args)
  raise DeserializerError, class: self, message: "has_many is currently unsupported."
end

.has_one(target, opts = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/deserializer/base.rb', line 21

def has_one( target, opts = {})
  deserializer = opts[:deserializer]

  unless deserializer
    raise DeserializerError, class: self, message: "has_one associations need a deserilaizer" 
  end

  self.attrs[target] = {attr: nil, deserializer: deserializer}
end

.permitted_paramsObject



45
46
47
# File 'lib/deserializer/base.rb', line 45

def permitted_params
  self.attrs.keys
end

Instance Method Details

#deserializeObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/deserializer/base.rb', line 53

def deserialize
  self.class.attrs.each do |param_key, object_key|
    # don't bother with keys that aren't in params
    next unless params.has_key? param_key

    # this checks if the object_key is a class that inherits from Deserializer
    if object_key[:deserializer]
      deseralize_nested(param_key, object_key[:deserializer])
    else
      attribute = object_key[:attr]
      options   = object_key[:options]

      assign_value attribute, params[param_key], options
    end
  end
  object
end