Module: VersacommerceAPI::Associatable

Included in:
Linklist, Order, Product, Shipment
Defined in:
lib/versacommerce_api/associatable.rb

Instance Method Summary collapse

Instance Method Details

#associated_resource(association, pluralize = true) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/versacommerce_api/associatable.rb', line 5

def associated_resource association, pluralize=true
  association = association.pluralize if pluralize

  if self.new? or attributes[association]
    attributes[association]
  else
    # dont create traffic if we know already there are no associated records...
    return [] if self.respond_to?("#{association}_count") && self.send("#{association}_count") == 0 && pluralize
    klass = "VersacommerceAPI::#{association.classify}".constantize
    # ensure we donĀ“t have the association already included
    attributes[association] ||= begin
      resource_name = self.class.name.split("::").last.tableize
      klass.prefix = "/api/#{resource_name}/#{self.id}/"
      pluralize ? klass.find(:all) : klass.find(:one)
    end
    klass.root!
    attributes[association]
  end
end