Module: DynamicAttributes

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

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'app/models/concerns/dynamic_attributes.rb', line 54

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



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

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



46
47
48
49
50
51
52
# File 'app/models/concerns/dynamic_attributes.rb', line 46

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

#attributesObject



68
69
70
71
72
# File 'app/models/concerns/dynamic_attributes.rb', line 68

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

#dynamic_attributesObject



74
75
76
# File 'app/models/concerns/dynamic_attributes.rb', line 74

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

#has_attribute?(attr_name) ⇒ Boolean

Returns:

  • (Boolean)


78
79
80
# File 'app/models/concerns/dynamic_attributes.rb', line 78

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