Skip to content

Commit

Permalink
Fewer object allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremy committed Sep 9, 2010
1 parent cb67d16 commit d79b1aa
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 11 deletions.
14 changes: 6 additions & 8 deletions activemodel/lib/active_model/attribute_methods.rb
Expand Up @@ -317,30 +317,28 @@ def instance_method_already_implemented?(method_name)

private
class AttributeMethodMatcher
attr_reader :prefix, :suffix
attr_reader :prefix, :suffix, :method_missing_target

AttributeMethodMatch = Struct.new(:target, :attr_name)

def initialize(options = {})
options.symbolize_keys!
@prefix, @suffix = options[:prefix] || '', options[:suffix] || ''
@regex = /^(#{Regexp.escape(@prefix)})(.+?)(#{Regexp.escape(@suffix)})$/
@method_missing_target = :"#{@prefix}attribute#{@suffix}"
@method_name = "#{prefix}%s#{suffix}"
end

def match(method_name)
if matchdata = @regex.match(method_name)
AttributeMethodMatch.new(method_missing_target, matchdata[2])
if @regex =~ method_name
AttributeMethodMatch.new(method_missing_target, $2)
else
nil
end
end

def method_name(attr_name)
"#{prefix}#{attr_name}#{suffix}"
end

def method_missing_target
:"#{prefix}attribute#{suffix}"
@method_name % attr_name
end
end
end
Expand Down
6 changes: 3 additions & 3 deletions activerecord/test/cases/attribute_methods_test.rb
Expand Up @@ -541,7 +541,7 @@ def test_read_attributes_respect_access_control
topic = @target.new(:title => "The pros and cons of programming naked.")
assert !topic.respond_to?(:title)
exception = assert_raise(NoMethodError) { topic.title }
assert_equal "Attempt to call private method", exception.message
assert_match %r(^Attempt to call private method), exception.message
assert_equal "I'm private", topic.send(:title)
end

Expand All @@ -551,7 +551,7 @@ def test_write_attributes_respect_access_control
topic = @target.new
assert !topic.respond_to?(:title=)
exception = assert_raise(NoMethodError) { topic.title = "Pants"}
assert_equal "Attempt to call private method", exception.message
assert_match %r(^Attempt to call private method), exception.message
topic.send(:title=, "Very large pants")
end

Expand All @@ -561,7 +561,7 @@ def test_question_attributes_respect_access_control
topic = @target.new(:title => "Isaac Newton's pants")
assert !topic.respond_to?(:title?)
exception = assert_raise(NoMethodError) { topic.title? }
assert_equal "Attempt to call private method", exception.message
assert_match %r(^Attempt to call private method), exception.message
assert topic.send(:title?)
end

Expand Down

0 comments on commit d79b1aa

Please sign in to comment.