Skip to content

Instantly share code, notes, and snippets.

@trepidity
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save trepidity/ee5c0b0bf0cf5a1b7862 to your computer and use it in GitHub Desktop.

Select an option

Save trepidity/ee5c0b0bf0cf5a1b7862 to your computer and use it in GitHub Desktop.
has_one example
require 'byebug'
module AutotaskAPI
class Entity
class_attribute :fields, :client, :find_cache
attr_accessor :attributes, :raw_xml
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
def method_missing(method, *args, &block)
if attributes.include?(method.to_sym)
attributes[method.to_sym]
else
super
end
end
def self.find(id, field = nil)
raise "No initialized client!" unless client
self.find_cache ||= {}
query = AutotaskAPI::QueryXML.new do |query|
query.entity = self.to_s.demodulize
query.field = (field || 'id')
query.expression = id
end
find_cache[id] ||= client.entities_for(query).first
end
def self.belongs_to(name, options = {})
name = name.to_s
klass = "AutotaskAPI::#{(options[:class_name] || name).to_s.classify}".constantize
foreign_key = name.foreign_key
define_method name do
klass.find send(foreign_key)
end
end
def self.has_one(name, options = {})
name = name.to_s
klass = "AutotaskAPI::#{(name).to_s.classify}".constantize
define_method name do
klass.find(self.id, options[:foreign_key])
end
end
end
end
@trepidity
Copy link
Copy Markdown
Author

The has_one example works OK, but is there a better way of doing this? I had to remove the send() as I couldn't make it work.

service_call.rb
has_one :service_call_ticket, foreign_key: :ServiceCallID

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment