Module: HasMany

Included in:
Klarna::Checkout::Resource
Defined in:
lib/klarna/checkout/concerns/has_many.rb

Instance Method Summary collapse

Instance Method Details

#has_many(association, klass = nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/klarna/checkout/concerns/has_many.rb', line 2

def has_many(association, klass = nil)
  attr_accessor association

  define_method "#{association}=" do |new_value|
    new_value = Array(new_value)
    inst_var = "@#{association}"

    if new_value.empty?
      instance_variable_set(inst_var, [])
      return
    end

    case new_value.first
    when klass
      instance_variable_set(inst_var, new_value)
    when Hash
      new_value = new_value.map { |hash| klass.new(hash) }
      instance_variable_set(inst_var, new_value)
    else
      raise "Unsupported type for relation #{association}: #{new_value.first.class.to_s}"
    end
  end
end