Class: Iugu::Object

Inherits:
Object
  • Object
show all
Defined in:
lib/iugu/object.rb

Direct Known Subclasses

APIResource

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Object

Returns a new instance of Object.



11
12
13
14
# File 'lib/iugu/object.rb', line 11

def initialize(attributes = {})
  @unsaved_attributes = Set.new
  set_attributes attributes
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



28
29
30
31
32
33
34
# File 'lib/iugu/object.rb', line 28

def method_missing(name, *args)
  return super unless name.to_s.end_with? "="
  return super if name.to_s.start_with? "id"

  add_accessor(name.to_s[0...-1])
  send(name, args[0])
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



36
37
38
# File 'lib/iugu/object.rb', line 36

def attributes
  @attributes
end

#errorsObject

Returns the value of attribute errors.



7
8
9
# File 'lib/iugu/object.rb', line 7

def errors
  @errors
end

#unsaved_attributesObject (readonly)

Returns the value of attribute unsaved_attributes.



36
37
38
# File 'lib/iugu/object.rb', line 36

def unsaved_attributes
  @unsaved_attributes
end

Instance Method Details

#add_accessor(name) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/iugu/object.rb', line 16

def add_accessor(name)
  singleton_class.class_eval do
    define_method(name.to_s) { attributes[name.to_s] }
    unless name.to_s == "id"
      define_method("#{name}=") do |value|
        attributes[name.to_s] = value
        unsaved_attributes.add name.to_s
      end
    end
  end
end

#copy(object) ⇒ Object



42
43
44
45
46
# File 'lib/iugu/object.rb', line 42

def copy(object)
  @unsaved_attributes = Set.new
  @attributes = {}
  set_attributes object.attributes
end

#modified_attributesObject



38
39
40
# File 'lib/iugu/object.rb', line 38

def modified_attributes
  Iugu::Utils.intersect @unsaved_attributes, @attributes
end

#set_attributes(attributes, unsaved = false) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/iugu/object.rb', line 48

def set_attributes(attributes, unsaved = false)
  @attributes = Iugu::Utils.stringify_keys(attributes)
  @attributes.each do |k, _v|
    add_accessor(k)
  end
  @unsaved_attributes = @attributes.keys.to_set if unsaved
end