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
31
32
33
34
35
# 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|
    next [k, v] unless v.instance_of? Hash

    v =
      if object_class = schema[k.to_sym]
        object_class.new(v)
      else
        OpenStruct.new(v)
      end

    [k.to_sym, v]
  end.to_h
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



37
38
39
40
41
42
43
# File 'lib/easy_api/object.rb', line 37

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

Instance Method Details

#attribute_namesObject



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

def attribute_names
  required_attribute_names + optional_attribute_names
end

#attributesObject



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

def attributes
  @attributes ||= {}
end

#optional_attribute_namesObject

Please override



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

def optional_attribute_names
  []
end

#required_attribute_namesObject

Please override



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

def required_attribute_names
  []
end

#schemaObject

Please override



64
65
66
# File 'lib/easy_api/object.rb', line 64

def schema
  {}
end