mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Use an empty AttributeMethodMatcher by default.
This means that attribute methods which don't exist will get generated when define_attribute_methods is called, so we don't have to use hacks like `attribute_method_suffix ''`.
This commit is contained in:
parent
8d59e0b263
commit
8b8b7143ef
2 changed files with 26 additions and 2 deletions
|
@ -60,7 +60,7 @@ module ActiveModel
|
|||
|
||||
included do
|
||||
class_attribute :attribute_method_matchers, :instance_writer => false
|
||||
self.attribute_method_matchers = []
|
||||
self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new]
|
||||
end
|
||||
|
||||
module ClassMethods
|
||||
|
@ -357,8 +357,11 @@ module ActiveModel
|
|||
if attribute_method_matchers_cache.key?(method_name)
|
||||
attribute_method_matchers_cache[method_name]
|
||||
else
|
||||
# Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
|
||||
# will match every time.
|
||||
matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
|
||||
match = nil
|
||||
attribute_method_matchers.detect { |method| match = method.match(method_name) }
|
||||
matchers.detect { |method| match = method.match(method_name) }
|
||||
attribute_method_matchers_cache[method_name] = match
|
||||
end
|
||||
end
|
||||
|
@ -387,6 +390,10 @@ module ActiveModel
|
|||
def method_name(attr_name)
|
||||
@method_name % attr_name
|
||||
end
|
||||
|
||||
def plain?
|
||||
prefix.empty? && suffix.empty?
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
|
|
|
@ -24,7 +24,16 @@ end
|
|||
class ModelWithAttributes2
|
||||
include ActiveModel::AttributeMethods
|
||||
|
||||
attr_accessor :attributes
|
||||
|
||||
attribute_method_suffix '_test'
|
||||
|
||||
private
|
||||
def attribute(name)
|
||||
attributes[name.to_s]
|
||||
end
|
||||
|
||||
alias attribute_test attribute
|
||||
end
|
||||
|
||||
class ModelWithAttributesWithSpaces
|
||||
|
@ -129,4 +138,12 @@ class AttributeMethodsTest < ActiveModel::TestCase
|
|||
assert !ModelWithAttributes.new.respond_to?(:foo)
|
||||
assert_raises(NoMethodError) { ModelWithAttributes.new.foo }
|
||||
end
|
||||
|
||||
test 'acessing a suffixed attribute' do
|
||||
m = ModelWithAttributes2.new
|
||||
m.attributes = { 'foo' => 'bar' }
|
||||
|
||||
assert_equal 'bar', m.foo
|
||||
assert_equal 'bar', m.foo_test
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue