Module: DynamicAttributes

Extended by:
ActiveSupport::Concern
Defined in:
app/models/concerns/dynamic_attributes.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/models/concerns/dynamic_attributes.rb', line 23

def method_missing(method, *args, &block)
  if self.class.define_attribute_methods && respond_to_without_attributes?(method)
    # this reproduces some behavior from AR's method_missing, as a safeguard
    # against dynamic attributes shadowing real ones
    send(method, *args, &block)
  elsif has_dynamic_attribute?(method)
    read_dynamic_attribute(method)
  elsif method =~ /^([\w]+)\=$/
    write_dynamic_attribute($1, args[0])
  else
    super
  end
end

Instance Method Details

#[](attr_name) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'app/models/concerns/dynamic_attributes.rb', line 5

def [](attr_name)
  if @attributes.has_key?(attr_name.to_s)
    super
  elsif has_dynamic_attribute?(attr_name)
    read_dynamic_attribute(attr_name)
  else
    super
  end
end

#[]=(key, value) ⇒ Object



15
16
17
18
19
20
21
# File 'app/models/concerns/dynamic_attributes.rb', line 15

def []=(key, value)
  begin
    super
  rescue ActiveModel::MissingAttributeError
    write_dynamic_attribute(key, value)
  end
end

#attributesObject



37
38
39
40
41
# File 'app/models/concerns/dynamic_attributes.rb', line 37

def attributes
  attrs = super
  dynamic_attrs = attrs.delete('dynamic_attributes') || {}
  dynamic_attrs.merge(attrs)
end

#dynamic_attributesObject



43
44
45
# File 'app/models/concerns/dynamic_attributes.rb', line 43

def dynamic_attributes
  self['dynamic_attributes'].blank? ? {} : self['dynamic_attributes']
end

#has_attribute?(attr_name) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
# File 'app/models/concerns/dynamic_attributes.rb', line 47

def has_attribute?(attr_name)
  super || has_dynamic_attribute?(attr_name)
end