Last active
August 29, 2015 14:16
-
-
Save trepidity/ee5c0b0bf0cf5a1b7862 to your computer and use it in GitHub Desktop.
has_one example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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