mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
validate attribute names in class and module attribute accessors
This commit is contained in:
parent
84338aab90
commit
96b951ce24
4 changed files with 32 additions and 0 deletions
|
@ -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
|
||||
|
@ -52,6 +53,7 @@ class Class
|
|||
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
|
||||
|
|
|
@ -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}
|
||||
|
||||
|
@ -25,6 +26,7 @@ class Module
|
|||
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
|
||||
|
|
|
@ -42,4 +42,18 @@ class ClassAttributeAccessorTest < ActiveSupport::TestCase
|
|||
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
|
||||
|
|
|
@ -44,4 +44,18 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
|
|||
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
|
||||
|
|
Loading…
Reference in a new issue