Class: Justimmo::API::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/justimmo/api/v1/resource.rb

Overview

A generic resource. Automatically generates getters and setters for attributes.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) {|@attributes| ... } ⇒ Resource

Returns a new instance of Resource

Yields:

  • (@attributes)

31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/justimmo/api/v1/resource.rb', line 31

def initialize(options)
  options ||= {}

  @attributes = @attributes.zip([nil]).to_h.merge(options)

  yield(@attributes) if block_given?

  # build getters and setters
  @attributes.keys.each do |key|
    meth = [true, false].include?(@attributes[key]) ? "#{key}?" : key
    define_singleton_method(meth.to_sym) { @attributes[key] }
  end
end

Class Method Details

.class_nameObject


20
21
22
# File 'lib/justimmo/api/v1/resource.rb', line 20

def class_name
  name.split('::').last
end

.from_json(data) ⇒ Object


24
25
26
27
28
# File 'lib/justimmo/api/v1/resource.rb', line 24

def from_json(data)
  tmp = data.is_a?(String) ? JSON.parse(data) : data
  tmp.deep_symbolize_keys!
  new(tmp)
end

.mapperObject


16
17
18
# File 'lib/justimmo/api/v1/resource.rb', line 16

def mapper
  "Justimmo::API::#{class_name}Mapper".constantize
end

.queryObject


12
13
14
# File 'lib/justimmo/api/v1/resource.rb', line 12

def query
  "Justimmo::API::#{class_name}Query".constantize
end

Instance Method Details

#to_hObject


45
46
47
48
49
50
51
52
53
54
55
# File 'lib/justimmo/api/v1/resource.rb', line 45

def to_h
  tmp = {}
  @attributes.each do |key, value|
    tmp[key] =
      case value
      when Resource then value.to_h
      else value
      end
  end
  tmp
end

#to_json(options = nil) ⇒ Object


57
58
59
# File 'lib/justimmo/api/v1/resource.rb', line 57

def to_json(options = nil)
  JSON.generate(@attributes, options)
end