Class: EasyApi::Object

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/easy_api/object.rb

Instance Method Summary collapse

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
# File 'lib/easy_api/object.rb', line 14

def initialize(data)
  raise EasyApi::MissingRequiredAttributeError unless required_attribute_names.all? { |name| data.keys.include? name }
  raise EasyApi::UnknownAttributeError if data.keys.any? { |key| !attribute_names.include? key }

  @attributes = data.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) # TODO: maybe create OpenStructObject which creates OpenStruct instance and parses
      end

    [k, v]
  end.to_h
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/easy_api/object.rb', line 32

def method_missing(m, *args, &block)
  if v = attributes[m]
    v
  else
    raise UnknownAttributeError
  end
end

Instance Method Details

#attribute_namesObject



44
45
46
# File 'lib/easy_api/object.rb', line 44

def attribute_names
  required_attribute_names + optional_attribute_names
end

#attributesObject



40
41
42
# File 'lib/easy_api/object.rb', line 40

def attributes
  @attributes ||= {}
end

#optional_attribute_namesObject

Please override



54
55
56
# File 'lib/easy_api/object.rb', line 54

def optional_attribute_names
  []
end

#required_attribute_namesObject

Please override



49
50
51
# File 'lib/easy_api/object.rb', line 49

def required_attribute_names
  []
end

#schemaObject

Please override



59
60
61
# File 'lib/easy_api/object.rb', line 59

def schema
  {}
end