Advertisement
Guest User

Untitled

a guest
Apr 18th, 2015
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. require 'byebug'
  2.  
  3. module AutotaskAPI
  4. class Entity
  5. class_attribute :fields, :client, :find_cache
  6. attr_accessor :attributes, :raw_xml
  7.  
  8. def initialize(xml)
  9. self.raw_xml = xml
  10. self.attributes = {}
  11. fields.each do |field|
  12. attributes[field] = xml.at_xpath("Autotask:#{field.to_s == 'id' ? 'id' : field.to_s.camelize.gsub(/Id$/, 'ID')}",
  13. Autotask: Client::NAMESPACE).text.strip rescue ''
  14. end
  15. attributes
  16. end
  17.  
  18. def method_missing(method, *args, &block)
  19. if attributes.include?(method.to_sym)
  20. attributes[method.to_sym]
  21. else
  22. super
  23. end
  24. end
  25.  
  26. def self.find(id, field = nil)
  27. raise "No initialized client!" unless client
  28. self.find_cache ||= {}
  29.  
  30. query = AutotaskAPI::QueryXML.new do |query|
  31. query.entity = self.to_s.demodulize
  32. query.field = (field || 'id')
  33. query.expression = id
  34. end
  35. find_cache[id] ||= client.entities_for(query).first
  36. end
  37.  
  38. def self.belongs_to(name, options = {})
  39. name = name.to_s
  40. klass = "AutotaskAPI::#{(options[:class_name] || name).to_s.classify}".constantize
  41. foreign_key = name.foreign_key
  42. define_method name do
  43. klass.find send(foreign_key)
  44. end
  45. end
  46.  
  47. def self.has_one(name, options = {})
  48. name = name.to_s
  49. klass = "AutotaskAPI::#{(name).to_s.classify}".constantize
  50. define_method name do
  51. klass.find(self.id, options[:foreign_key])
  52. end
  53. end
  54. end
  55. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement