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



62
63
64
# File 'lib/options_model/concerns/attribute_assignment.rb', line 62

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

#fetch(key, default = nil) ⇒ Object



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

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

  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



66
67
68
# File 'lib/options_model/concerns/attribute_assignment.rb', line 66

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

#unused_attributesObject



70
71
72
# File 'lib/options_model/concerns/attribute_assignment.rb', line 70

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

#update_attributes(other) ⇒ Object



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

def update_attributes(other)
  return unless other

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

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