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



31
32
33
# File 'lib/options_model/concerns/attribute_assignment.rb', line 31

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

#[]=(key, val) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/options_model/concerns/attribute_assignment.rb', line 35

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

#fetch(key, default = nil) ⇒ Object



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

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



5
6
7
# File 'lib/options_model/concerns/attribute_assignment.rb', line 5

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

#initialize_dup(other) ⇒ Object



9
10
11
12
13
# File 'lib/options_model/concerns/attribute_assignment.rb', line 9

def initialize_dup(other)
  super

  update_attributes(other)
end

#update_attributes(other) ⇒ Object



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

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