Class: CiviCrm::Resource

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Dirty
Defined in:
lib/civicrm/resource.rb

Direct Known Subclasses

BaseResource

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values = {}) ⇒ Resource

Returns a new instance of Resource.



8
9
10
11
12
13
# File 'lib/civicrm/resource.rb', line 8

def initialize(values = {})
  @values = {}
  @id = values['id'] if values['id']
  refresh_from(values)
  self.class.define_attribute_methods(attributes.keys)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *opts) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/civicrm/resource.rb', line 31

def method_missing(name, *opts)
  if name[-1] == '='
    name = name.to_s.gsub(/\=$/, '')
    send(:"#{name}_will_change!")
    @values[name.to_s] = opts.first if @values.has_key?(name.to_s)
  else
    @values[name.to_s] if @values.has_key?(name.to_s)
  end
end

Class Method Details

.build_from(resp, request_params = {}) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/civicrm/resource.rb', line 70

def build_from(resp, request_params = {})
  entity = request_params['entity']
  case resp
  when Array
    resp.map { |values| build_from(values, request_params) }
  when Hash
    klass = "CiviCrm::#{entity.classify}".constantize
    resource = klass.new(resp)
    resource
  else
    resp
  end
end

.entity(name = nil) ⇒ Object



62
63
64
# File 'lib/civicrm/resource.rb', line 62

def entity(name = nil)
  self.entity_name = name
end

.entity_class_nameObject



66
67
68
# File 'lib/civicrm/resource.rb', line 66

def entity_class_name
  self.entity_name.to_s.classify
end

Instance Method Details

#as_json(*opts) ⇒ Object



45
46
47
# File 'lib/civicrm/resource.rb', line 45

def as_json(*opts)
  @values.as_json(*a)
end

#attribute(key) ⇒ Object



57
58
59
# File 'lib/civicrm/resource.rb', line 57

def attribute(key)
  to_hash[key]
end

#attributesObject



53
54
55
# File 'lib/civicrm/resource.rb', line 53

def attributes
  to_hash.reject{ |k, v| v.is_a? (CiviCrm::Resource)}
end

#inspectObject



26
27
28
29
# File 'lib/civicrm/resource.rb', line 26

def inspect
  id_string = !@id.nil? ? " id=#{@id}" : ""
  "#<#{self.class}:0x#{self.object_id.to_s(16)}#{id_string}> #{attributes}"
end

#refresh_from(values) ⇒ Object

we will use this method for creating nested resources



16
17
18
19
20
# File 'lib/civicrm/resource.rb', line 16

def refresh_from(values)
  values.each do |key, value|
    @values[key.to_s] = value
  end
end

#to_hashObject



49
50
51
# File 'lib/civicrm/resource.rb', line 49

def to_hash
  @values
end

#to_json(*opts) ⇒ Object



41
42
43
# File 'lib/civicrm/resource.rb', line 41

def to_json(*opts)
  CiviCrm::JSON.encode(@values)
end

#to_s(*opts) ⇒ Object



22
23
24
# File 'lib/civicrm/resource.rb', line 22

def to_s(*opts)
  @values.to_json
end