mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Error if mattr_accessor is called on singleton
This commit is contained in:
parent
22115751f3
commit
b5b1b02087
2 changed files with 16 additions and 0 deletions
|
@ -49,11 +49,13 @@ class Module
|
|||
#
|
||||
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
|
||||
def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil, location: nil)
|
||||
raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class?
|
||||
location ||= caller_locations(1, 1).first
|
||||
|
||||
definition = []
|
||||
syms.each do |sym|
|
||||
raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym)
|
||||
|
||||
definition << "def self.#{sym}; @@#{sym}; end"
|
||||
|
||||
if instance_reader && instance_accessor
|
||||
|
@ -111,6 +113,7 @@ class Module
|
|||
#
|
||||
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
|
||||
def mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil, location: nil)
|
||||
raise TypeError, "module attributes should be defined directly on class, not singleton" if singleton_class?
|
||||
location ||= caller_locations(1, 1).first
|
||||
|
||||
definition = []
|
||||
|
|
|
@ -134,4 +134,17 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
|
|||
assert_equal 1, @module.defn1
|
||||
assert_equal 2, @module.defn2
|
||||
end
|
||||
|
||||
def test_declaring_attributes_on_singleton_errors
|
||||
klass = Class.new
|
||||
|
||||
ex = assert_raises TypeError do
|
||||
class << klass
|
||||
mattr_accessor :my_attr
|
||||
end
|
||||
end
|
||||
assert_equal "module attributes should be defined directly on class, not singleton", ex.message
|
||||
|
||||
assert_not_includes Module.class_variables, :@@my_attr
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue