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

Parameters:

  • model_name (Symbol)
  • options (#to_hash) (defaults to: {})

    options for setting up the relationship

Options Hash (options):

  • :class_name (String)

    Override the default class name

  • :readonly (String) — default: false

    Whether to serialize this attribute

Returns:

  • (undefined)


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

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

Parameters:

  • model_name (Symbol)
  • options (#to_hash) (defaults to: {})

    options for setting up the relationship

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

Returns:

  • (undefined)


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

def has_many(association_name, options = {}) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
  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 # rubocop:disable Metrics/MethodLength
    collection_proxies[association_name] ||= begin
      ids = attributes[foreign_key]
      collection = if ids.any?
                     @client.adapter_for(class_name).find_many(ids)
                   else
                     []
                   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