Skip to content
Browse files

default value via association for Rails 3.1

pass given block to #initialize (aka initialize_without_defaults) and then process
  • Loading branch information...
1 parent 227ade8 commit be6f6b72564a44303d98c99a44f68cf347388f43 @firien firien committed
Showing with 29 additions and 31 deletions.
  1. +17 −18 lib/default_value_for.rb
  2. +12 −13 test.rb
View
35 lib/default_value_for.rb
@@ -79,27 +79,26 @@ def default_values(values)
end
module InstanceMethods
- def initialize_with_defaults(attrs = nil, *args)
- initialize_without_defaults(attrs, *args) do
- if attrs
- stringified_attrs = attrs.stringify_keys
- safe_attrs = if respond_to? :sanitize_for_mass_assignment
- sanitize_for_mass_assignment(stringified_attrs)
- else
- remove_attributes_protected_from_mass_assignment(stringified_attrs)
- end
- safe_attribute_names = safe_attrs.keys.map do |x|
- x.to_s
- end
+ def initialize_with_defaults(attrs = nil, *args, &block)
+ initialize_without_defaults(attrs, *args, &block)
+ if attrs
+ stringified_attrs = attrs.stringify_keys
+ safe_attrs = if respond_to? :sanitize_for_mass_assignment
+ sanitize_for_mass_assignment(stringified_attrs)
+ else
+ remove_attributes_protected_from_mass_assignment(stringified_attrs)
+ end
+ safe_attribute_names = safe_attrs.keys.map do |x|
+ x.to_s
end
- self.class._default_attribute_values.each do |attribute, container|
- if safe_attribute_names.nil? || !safe_attribute_names.any? { |attr_name| attr_name =~ /^#{attribute}($|\()/ }
- __send__("#{attribute}=", container.evaluate(self))
- changed_attributes.delete(attribute)
- end
+ end
+ self.class._default_attribute_values.each do |attribute, container|
+ if safe_attribute_names.nil? || !safe_attribute_names.any? { |attr_name| attr_name =~ /^#{attribute}($|\()/ }
+ __send__("#{attribute}=", container.evaluate(self))
+ changed_attributes.delete(attribute)
end
- yield(self) if block_given?
end
+ yield(self) if block_given?
end
end
end
View
25 test.rb
@@ -220,19 +220,18 @@ def test_model_instance_is_passed_to_the_given_block
assert_same object, $instance
end
- # This is no longer supported starting from Rails 3.1 thanks to ActiveRecord changes.
- # def test_can_specify_default_value_via_association
- # user = User.create(:username => 'Kanako', :default_number => 123)
- # define_model_class do
- # belongs_to :user
- #
- # default_value_for :number do |n|
- # n.user.default_number
- # end
- # end
- # object = user.numbers.create
- # assert_equal 123, object.number
- # end
+ def test_can_specify_default_value_via_association
+ user = User.create(:username => 'Kanako', :default_number => 123)
+ define_model_class do
+ belongs_to :user
+
+ default_value_for :number do |n|
+ n.user.default_number
+ end
+ end
+ object = user.numbers.create
+ assert_equal 123, object.number
+ end
def test_default_values
define_model_class do

0 comments on commit be6f6b7

Please sign in to comment.
Something went wrong with that request. Please try again.