Module: Gecko::Helpers::AssociationHelper::ClassMethods

Defined in:
lib/gecko/helpers/association_helper.rb

Instance Method Summary collapse

Instance Method Details

#belongs_to(model_name, options = {}) ⇒ undefined

Set up a belongs_to relationship between two classes based on a JSON key of class_name_id.

Examples:

class Gecko::Record::Variant
  belongs_to :product
end

Options Hash (options):

  • :class_name (String)

    Override the default class name

  • :readonly (String) — default: false

    Whether to serialize this attribute



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/gecko/helpers/association_helper.rb', line 27

def belongs_to(model_name, options={})
  class_name  = options[:class_name] || model_name.to_s.classify
  foreign_key = model_name.to_s.foreign_key.to_sym

  define_method model_name do
    if (id = attributes[foreign_key])
      @client.adapter_for(class_name).find(id)
    end
  end
  attribute foreign_key, Integer, readonly: options[:readonly]
end

#has_many(association_name, options = {}) ⇒ undefined

Set up a has_many relationship between two classes based on a JSON key of class_name_ids.

Examples:

class Gecko::Record::Product
  has_many :variants
end

Options Hash (options):

  • :class_name (String)

    Override the default class name

  • :readonly (Boolean) — default: true

    Whether to serialize this attribute

  • :embedded (Boolean) — default: false

    Whether this relation should persisted inside it’s parent record



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/gecko/helpers/association_helper.rb', line 58

def has_many(association_name, options={})
  model_name = association_name.to_s.singularize
  class_name = options[:class_name] || model_name.classify
  foreign_key = model_name.foreign_key.pluralize.to_sym
  readonly    = options.key?(:readonly) ? options[:readonly] : true

  define_method association_name do
    collection_proxies[association_name] ||= begin
      ids = self.attributes[foreign_key]
      if ids.any?
        collection = @client.adapter_for(class_name).find_many(ids)
      else
        collection = []
      end

      build_collection_proxy(collection, {
        embedded:         options[:embedded],
        class_name:       class_name,
        association_name: association_name
      })
    end
  end
  attribute foreign_key, Array[Integer], readonly: readonly
end