Module: Unchained::Client::Mixins::Resource::ClassMethods
- Defined in:
- lib/unchained/client/mixins/resource.rb
Instance Attribute Summary collapse
-
#attributes ⇒ Object
readonly
Returns the value of attribute attributes.
Instance Method Summary collapse
- #attribute(name, type, opts = {}) ⇒ Object
-
#from_hash(json, client: nil) ⇒ Object
This is a pretty naive implementation of parsing JSON.
Instance Attribute Details
#attributes ⇒ Object (readonly)
Returns the value of attribute attributes.
74 75 76 |
# File 'lib/unchained/client/mixins/resource.rb', line 74 def attributes @attributes end |
Instance Method Details
#attribute(name, type, opts = {}) ⇒ Object
76 77 78 79 80 81 82 83 |
# File 'lib/unchained/client/mixins/resource.rb', line 76 def attribute(name, type, opts={}) instance_eval do attr_accessor name end @attributes ||= [] @attributes << Attribute.new(name, type, opts) end |
#from_hash(json, client: nil) ⇒ 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.
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 116 117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/unchained/client/mixins/resource.rb', line 91 def from_hash(json, client: nil) 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 # Lurk, there is probably a better way to do this. if !attr..nil? client ||= Unchained::Client.new value = client.send(attr., value) end res.send("#{attr.name}=", value) end res end |