1
0
Fork 0
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:
John Hawthorn 2020-01-04 17:52:15 -08:00
parent 22115751f3
commit b5b1b02087
2 changed files with 16 additions and 0 deletions

View file

@ -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 = []

View file

@ -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