Class: AutotaskAPI::Entity

Inherits:
Object
  • Object
show all
Defined in:
lib/autotask_api/entity.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(xml) ⇒ Entity

Returns a new instance of Entity


6
7
8
9
10
11
12
13
14
# File 'lib/autotask_api/entity.rb', line 6

def initialize(xml)
  self.raw_xml = xml
  self.attributes = {}
  fields.each do |field|
    attributes[field] = xml.at_xpath("Autotask:#{field.to_s == 'id' ? 'id' : field.to_s.camelize.gsub(/Id$/, 'ID')}",
      Autotask: Client::NAMESPACE).text.strip rescue ''
  end
  attributes
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object


16
17
18
19
20
21
22
# File 'lib/autotask_api/entity.rb', line 16

def method_missing(method, *args, &block)
  if attributes.include?(method.to_sym)
    attributes[method.to_sym]
  else
    super
  end
end

Instance Attribute Details

#attributesObject

Returns the value of attribute attributes


4
5
6
# File 'lib/autotask_api/entity.rb', line 4

def attributes
  @attributes
end

#raw_xmlObject

Returns the value of attribute raw_xml


4
5
6
# File 'lib/autotask_api/entity.rb', line 4

def raw_xml
  @raw_xml
end

Class Method Details

.belongs_to(name, options = {}) ⇒ Object


36
37
38
39
40
41
42
43
# File 'lib/autotask_api/entity.rb', line 36

def self.belongs_to(name, options = {})
  name = name.to_s
  klass = "AutotaskAPI::#{(options[:class_name] || name).to_s.classify}"
  foreign_key = name.foreign_key
  define_method name do
    klass.constantize.find send(foreign_key)
  end
end

.find(id, field = 'id') ⇒ Object


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/autotask_api/entity.rb', line 24

def self.find(id, field = 'id')
  raise "No initialized client!" unless client
  self.find_cache ||= {}

  query = AutotaskAPI::QueryXML.new do |query|
    query.entity = self.to_s.demodulize
    query.field = field
    query.expression = id
  end
  find_cache[id] ||= client.entities_for(query).first
end

.has_one(name, options = {}) ⇒ Object


45
46
47
48
49
50
51
52
# File 'lib/autotask_api/entity.rb', line 45

def self.has_one(name, options = {})
  name = name.to_s
  options.reverse_merge! foreign_key: self.to_s.foreign_key.camelize
  klass = "AutotaskAPI::#{(options[:class_name] || name).to_s.classify}"
  define_method name do
    klass.constantize.find id, options[:foreign_key]
  end
end