Module: IronBank::Associations::ClassMethods

Included in:
Resource
Defined in:
lib/iron_bank/associations.rb

Overview

Define class methods

Instance Method Summary collapse

Instance Method Details

#with_many(name, options = {}) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/iron_bank/associations.rb', line 32

def with_many(name, options = {})
  resource_name = options.fetch(
    :resource_name,
    IronBank::Utils.camelize(name.to_s.chop)
  )

  foreign_key = options.fetch(
    :foreign_key,
    "#{IronBank::Utils.underscore(object_name)}_id"
  )

  define_method(name) do
    with_memoization(name) do
      # NOTE: we retrieve the constant here to prevent the need to order
      # our `require <file>` statements in `iron_bank.rb`
      klass      = IronBank::Resources.const_get(resource_name)
      conditions = options.fetch(:conditions, {}).
                   merge("#{foreign_key}": id)
      items      = klass.where(conditions)
      IronBank::Collection.new(klass, conditions, items)
    end
  end

  alias_name = options[:alias]
  alias_method alias_name, name if alias_name
end

#with_one(name, options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/iron_bank/associations.rb', line 10

def with_one(name, options = {})
  resource_name = options.fetch(
    :resource_name,
    IronBank::Utils.camelize(name)
  )
  foreign_key = options.fetch(:foreign_key, "#{name}_id")

  define_method(name) do
    return unless (foreign_key_value = public_send(foreign_key))

    with_memoization(name) do
      # NOTE: we retrieve the constant here to prevent the need to order
      # our `require <file>` statements in `iron_bank.rb`
      klass = IronBank::Resources.const_get(resource_name)
      klass.find(foreign_key_value)
    end
  end

  alias_name = options[:alias]
  alias_method alias_name, name if alias_name
end