Module: OptionsModel::Concerns::AttributeAssignment

Extended by:
ActiveSupport::Concern
Included in:
Base
Defined in:
lib/options_model/concerns/attribute_assignment.rb

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object



34
35
36
# File 'lib/options_model/concerns/attribute_assignment.rb', line 34

def [](key)
  public_send(key) if respond_to?(key)
end

#[]=(key, val) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/options_model/concerns/attribute_assignment.rb', line 38

def []=(key, val)
  setter = "#{key}="
  if respond_to?(setter)
    public_send(setter, val)
  else
    unused_attributes[key] = val
  end
end

#attributesObject



60
61
62
# File 'lib/options_model/concerns/attribute_assignment.rb', line 60

def attributes
  @attributes ||= ActiveSupport::HashWithIndifferentAccess.new
end

#fetch(key, default = nil) ⇒ Object

Raises:

  • (KeyError)


47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/options_model/concerns/attribute_assignment.rb', line 47

def fetch(key, default = nil)
  raise KeyError, "attribute not found" if self.class.attribute_names.exclude?(key.to_sym) && default.nil? && !block_given?

  value = respond_to?(key) ? public_send(key) : nil
  return value if value

  if default
    default
  elsif block_given?
    yield
  end
end

#initialize(attributes = {}) ⇒ Object



8
9
10
# File 'lib/options_model/concerns/attribute_assignment.rb', line 8

def initialize(attributes = {})
  update_attributes(attributes)
end

#initialize_dup(other) ⇒ Object



12
13
14
15
16
# File 'lib/options_model/concerns/attribute_assignment.rb', line 12

def initialize_dup(other)
  super

  update_attributes(other)
end

#nested_attributesObject



64
65
66
# File 'lib/options_model/concerns/attribute_assignment.rb', line 64

def nested_attributes
  @nested_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
end

#replace(other) ⇒ Object Also known as: update_attributes

Raises:

  • (ArgumentError)


18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/options_model/concerns/attribute_assignment.rb', line 18

def replace(other)
  return unless other

  raise ArgumentError, "#{other} must be respond to `to_h`" unless other.respond_to?(:to_h)

  other.to_h.each do |k, v|
    if respond_to?("#{k}=")
      public_send("#{k}=", v)
    else
      unused_attributes[k] = v
    end
  end
end

#unused_attributesObject



68
69
70
# File 'lib/options_model/concerns/attribute_assignment.rb', line 68

def unused_attributes
  @unused_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
end