Module: Unchained::Client::Mixins::Resource::ClassMethods

Defined in:
lib/unchained/client/mixins/resource.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



68
69
70
# File 'lib/unchained/client/mixins/resource.rb', line 68

def attributes
  @attributes
end

Instance Method Details

#attribute(name, type, opts = {}) ⇒ Object



70
71
72
73
74
75
76
77
# File 'lib/unchained/client/mixins/resource.rb', line 70

def attribute(name, type, opts={})
  instance_eval do
    attr_accessor name
  end

  @attributes ||= []
  @attributes << Attribute.new(name, type, opts)
end

#from_json(json) ⇒ Object

This is a pretty naive implementation of parsing JSON. It will loop through all of ‘@attributes` to find the right one, then do some very minimal validation, before setting the attribute on the instance.

Returns an instance of the class that uses this mixin.



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/unchained/client/mixins/resource.rb', line 85

def from_json(json)
  res = self.new

  json.each do |k, v|
    # TODO: Better way to do this?
    attr = @attributes.find{|a| a.json_field == k.to_s}
    raise InvalidAttribute.new(
      "`#{self.name.split('::').last}` did not define a `#{k}`."
    ) if attr.nil?

    # TODO: Better way to do this?
    case attr.type.to_s
    when Integer.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(Fixnum)
      value = v.to_i
    when Float.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(Float)
      value = v.to_f
    when String.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(String)
      value = v
    when Hash.to_s
      maybe_raise_invalid_value(attr, k, v) unless v.is_a?(Hash)
      value = v
    end

    res.send("#{attr.name}=", value)
  end

  res
end