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.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/easy_api/object.rb', line 13

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



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

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

Instance Method Details

#attribute_namesObject



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

def attribute_names
  required_attribute_names + optional_attribute_names
end

#attributesObject



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

def attributes
  @attributes ||= {}
end

#optional_attribute_namesObject

Please override



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

def optional_attribute_names
  []
end

#required_attribute_namesObject

Please override



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

def required_attribute_names
  []
end

#schemaObject

Please override



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

def schema
  {}
end