Class: EasyApi::Object
- Inherits:
-
Object
- Object
- EasyApi::Object
- Extended by:
- Forwardable
- Includes:
- Enumerable
- Defined in:
- lib/easy_api/object.rb
Instance Method Summary collapse
- #attribute_names ⇒ Object
- #attributes ⇒ Object
-
#initialize(data) ⇒ Object
constructor
A new instance of Object.
- #method_missing(m, *args, &block) ⇒ Object
-
#optional_attribute_names ⇒ Object
Please override.
-
#required_attribute_names ⇒ Object
Please override.
-
#schema ⇒ Object
Please override.
Constructor Details
#initialize(data) ⇒ Object
Returns a new instance of Object.
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/easy_api/object.rb', line 14 def initialize(data) raise EasyApi::MissingRequiredAttributeError unless required_attribute_names.all? do |name| data.keys.include?(name) || data.keys.include?(name.to_s) end raise EasyApi::UnknownAttributeError if data.keys.any? do |key| !attribute_names.include?(key) && !attribute_names.include?(key.to_sym) end @attributes = data.map do |k, v| [k.to_sym, v] end.map do |k, v| next [k, v] unless v.instance_of? Hash v = if object_class = schema[k] object_class.new(v) else OpenStruct.new(v) end [k, v] end.to_h @attributes = empty_optional_attributes.merge(@attributes) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(m, *args, &block) ⇒ Object
41 42 43 44 45 46 47 |
# File 'lib/easy_api/object.rb', line 41 def method_missing(m, *args, &block) if attributes.has_key?(m) attributes[m] else raise UnknownAttributeError end end |
Instance Method Details
#attribute_names ⇒ Object
53 54 55 |
# File 'lib/easy_api/object.rb', line 53 def attribute_names required_attribute_names + optional_attribute_names end |
#attributes ⇒ Object
49 50 51 |
# File 'lib/easy_api/object.rb', line 49 def attributes @attributes ||= {} end |
#optional_attribute_names ⇒ Object
Please override
63 64 65 |
# File 'lib/easy_api/object.rb', line 63 def optional_attribute_names [] end |
#required_attribute_names ⇒ Object
Please override
58 59 60 |
# File 'lib/easy_api/object.rb', line 58 def required_attribute_names [] end |
#schema ⇒ Object
Please override
68 69 70 |
# File 'lib/easy_api/object.rb', line 68 def schema {} end |