Module: FmRest::Spyke::Model::Associations

Extended by:
ActiveSupport::Concern
Included in:
FmRest::Spyke::Model
Defined in:
lib/fmrest/spyke/model/associations.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

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

Based on +has_many+, but creates a special Portal association instead.

Custom options:

  • :portal_key - The key used for the portal in the FM Data JSON portalData.
  • :attribute_prefix - The prefix used for portal attributes in the FM Data JSON.

Example:

has_portal :jobs, portal_key: "JobsTable", attribute_prefix: "Job"



37
38
39
40
41
42
43
44
45
46
47
# File 'lib/fmrest/spyke/model/associations.rb', line 37

def has_portal(name, options = {})
  create_association(name, Portal, options)

  # Store options for SpykeFormatter to use if needed
  portal_key = options[:portal_key] || name
  self.portal_options = portal_options.merge(portal_key.to_s => options.dup.merge(name: name.to_s)).freeze

  define_method "#{name.to_s.singularize}_ids" do
    association(name).map(&:id)
  end
end

Instance Method Details

#association(name) ⇒ Object

Override Spyke's association reader to keep a cache of loaded portals. Spyke's default behavior is to reload the association each time.



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/fmrest/spyke/model/associations.rb', line 54

def association(name)
  @loaded_portals ||= {}

  if @loaded_portals.has_key?(name.to_sym)
    return @loaded_portals[name.to_sym]
  end

  super.tap do |assoc|
    next unless assoc.kind_of?(FmRest::Spyke::Portal)
    @loaded_portals[name.to_sym] = assoc
  end
end

#portalsObject



71
72
73
74
75
76
77
# File 'lib/fmrest/spyke/model/associations.rb', line 71

def portals
  self.class.associations.each_with_object([]) do |(key, _), portals|
    candidate = association(key)
    next unless candidate.kind_of?(FmRest::Spyke::Portal)
    portals << candidate
  end
end

#reload(*_) ⇒ Object



67
68
69
# File 'lib/fmrest/spyke/model/associations.rb', line 67

def reload(*_)
  super.tap { @loaded_portals = nil }
end