Class: LMRest::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/lm_rest/resource.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(properties) ⇒ Resource

Returns a new instance of Resource.



5
6
7
8
9
10
11
# File 'lib/lm_rest/resource.rb', line 5

def initialize(properties)
  @attributes = {}

  properties.each do |key, value|
    @attributes[key.to_s] = value
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/lm_rest/resource.rb', line 29

def method_missing(name, *args)
  attribute_name = name.to_s

  if attribute_name.end_with?('=')
    raise ArgumentError, "wrong number of arguments (#{args.count} for 1)" unless args.count == 1

    @attributes[attribute_name.delete_suffix('=')] = args.first
  elsif args.empty? && @attributes.key?(attribute_name)
    @attributes[attribute_name]
  else
    super
  end
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



3
4
5
# File 'lib/lm_rest/resource.rb', line 3

def attributes
  @attributes
end

Class Method Details

.parse(body) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/lm_rest/resource.rb', line 51

def parse(body)
  case body
  when nil
    nil
  when Array
    parse_collection(body)
  when Hash
    if body.key?('items')
      parse_collection(body['items'] || [])
    else
      parse_object(body)
    end
  when String
    body
  else
    body
  end
end

.parse_collection(items) ⇒ Object



70
71
72
73
74
# File 'lib/lm_rest/resource.rb', line 70

def parse_collection(items)
  items.map do |item|
    item.is_a?(Hash) ? new(item) : item
  end
end

.parse_object(item) ⇒ Object



76
77
78
# File 'lib/lm_rest/resource.rb', line 76

def parse_object(item)
  item.is_a?(Hash) ? new(item) : item
end

Instance Method Details

#[](key) ⇒ Object



13
14
15
# File 'lib/lm_rest/resource.rb', line 13

def [](key)
  @attributes[key.to_s]
end

#[]=(key, value) ⇒ Object



17
18
19
# File 'lib/lm_rest/resource.rb', line 17

def []=(key, value)
  @attributes[key.to_s] = value
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/lm_rest/resource.rb', line 21

def key?(key)
  @attributes.key?(key.to_s)
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
46
47
# File 'lib/lm_rest/resource.rb', line 43

def respond_to_missing?(name, include_private = false)
  attribute_name = name.to_s

  attribute_name.end_with?('=') || @attributes.key?(attribute_name) || super
end

#to_hObject



25
26
27
# File 'lib/lm_rest/resource.rb', line 25

def to_h
  deep_copy(@attributes)
end