Module: AttributeDefaults

Extended by:
ActiveSupport::Concern
Included in:
ActiveRecord::Base
Defined in:
lib/attribute_defaults.rb,
lib/attribute_defaults/default.rb,
lib/attribute_defaults/version.rb

Defined Under Namespace

Modules: ClassMethods Classes: Default

Constant Summary collapse

VERSION =
"0.3"

Instance Method Summary collapse

Instance Method Details

#apply_default_attribute_values(specific_attributes) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/attribute_defaults.rb', line 102

def apply_default_attribute_values(specific_attributes)
  specific_attributes = (specific_attributes || {}).stringify_keys

  # Rails 3.1 deprecates #primary_key_name in favour of :foreign_key
  foreign_key_method = if ActiveRecord::VERSION::STRING >= "3.1"
    :foreign_key
  else
    :primary_key_name
  end

  self.class.attribute_defaults.each do |default|
    next if specific_attributes.include?(default.attribute)

    # Ignore a default value for association_id if association has been specified
    reflection = self.class.reflections[default.attribute.to_sym]
    if reflection and reflection.macro == :belongs_to and specific_attributes.include?(reflection.send(foreign_key_method).to_s)
      next
    end

    # Ignore a default value for association if association_id has been specified
    reflection = self.class.reflections.values.find { |r| r.macro == :belongs_to && r.send(foreign_key_method).to_s == default.attribute }
    if reflection and specific_attributes.include?(reflection.name.to_s)
      next
    end

    send("#{default.attribute}=", default.value(self))
  end
end

#initialize_with_defaults(attributes = nil) ⇒ Object



87
88
89
90
91
92
# File 'lib/attribute_defaults.rb', line 87

def initialize_with_defaults(attributes = nil, options = {})
  initialize_without_defaults(attributes, options) do |record|
    record.apply_default_attribute_values(attributes)
    yield record if block_given?
  end
end