Skip to content

Commit

Permalink
Merge pull request #5668 from plashchynski/validate_attribute_name_in…
Browse files Browse the repository at this point in the history
…_class_and_module_attribute_accessors

validate attribute names in class and module attribute accessors
  • Loading branch information
josevalim committed Mar 30, 2012
2 parents b69298e + 96b951c commit 34320cd
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class Class
def cattr_reader(*syms)
options = syms.extract_options!
syms.each do |sym|
raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
unless defined? @@#{sym}
@@#{sym} = nil
Expand All @@ -52,6 +53,7 @@ def #{sym}
def cattr_writer(*syms)
options = syms.extract_options!
syms.each do |sym|
raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
unless defined? @@#{sym}
@@#{sym} = nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ class Module
def mattr_reader(*syms)
options = syms.extract_options!
syms.each do |sym|
raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@#{sym} = nil unless defined? @@#{sym}
Expand All @@ -25,6 +26,7 @@ def #{sym}
def mattr_writer(*syms)
options = syms.extract_options!
syms.each do |sym|
raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def self.#{sym}=(obj)
@@#{sym} = obj
Expand Down
14 changes: 14 additions & 0 deletions activesupport/test/core_ext/class/attribute_accessor_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,18 @@ def test_should_not_create_instance_accessors
assert !@object.respond_to?(:camp)
assert !@object.respond_to?(:camp=)
end

def test_should_raise_name_error_if_attribute_name_is_invalid
assert_raises NameError do
Class.new do
cattr_reader "invalid attribute name"
end
end

assert_raises NameError do
Class.new do
cattr_writer "invalid attribute name"
end
end
end
end
14 changes: 14 additions & 0 deletions activesupport/test/core_ext/module/attribute_accessor_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,18 @@ def test_should_not_create_instance_accessors
assert !@object.respond_to?(:camp)
assert !@object.respond_to?(:camp=)
end

def test_should_raise_name_error_if_attribute_name_is_invalid
assert_raises NameError do
Class.new do
mattr_reader "invalid attribute name"
end
end

assert_raises NameError do
Class.new do
mattr_writer "invalid attribute name"
end
end
end
end

0 comments on commit 34320cd

Please sign in to comment.