Class: Billogram::Resource

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Resource

Returns a new instance of Resource.



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/billogram/resource.rb', line 26

def initialize(attributes = {})
  Hash(attributes).each do |key, value|
    if respond_to?("#{key}=")
      public_send("#{key}=", value)
    else
      warn("#{self.class}: unknown attribute #{key}")
    end
  end

  RelationBuilder.new(self, attributes).call
end

Class Method Details

.build_objects(data) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/billogram/resource.rb', line 17

def build_objects(data)
  case data
  when Hash then new(data)
  when Array then data.map { |item| build_objects(item) }
  else data
  end
end

.relation(name, type, class_override: nil) ⇒ Object



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

def relation(name, type, class_override: nil)
  relations << Relation.new(name, type, class_override: class_override)
  attr_accessor name
end

.relationsObject



8
9
10
# File 'lib/billogram/resource.rb', line 8

def relations
  @relations ||= []
end

Instance Method Details

#to_hashObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/billogram/resource.rb', line 42

def to_hash
  instance_variables.each_with_object({}) do |variable, obj|
    value = instance_variable_get(variable)

    case value
    when Resource
      value = value.to_hash
    when Array
      value = value.map(&:to_hash)
    end

    obj[variable[1..-1]] = value
  end
end

#to_json(*args) ⇒ Object



38
39
40
# File 'lib/billogram/resource.rb', line 38

def to_json(*args)
  to_hash.to_json(*args)
end