From b5b1b02087cac08d43a3174cfb8c0909ec6bb6ea Mon Sep 17 00:00:00 2001 From: John Hawthorn Date: Sat, 4 Jan 2020 17:52:15 -0800 Subject: [PATCH] Error if mattr_accessor is called on singleton --- .../core_ext/module/attribute_accessors.rb | 3 +++ .../test/core_ext/module/attribute_accessor_test.rb | 13 +++++++++++++ 2 files changed, 16 insertions(+) diff --git a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb index f9cf38dd50..1db905ff65 100644 --- a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb +++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb @@ -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 = [] diff --git a/activesupport/test/core_ext/module/attribute_accessor_test.rb b/activesupport/test/core_ext/module/attribute_accessor_test.rb index 7ac76251df..a6af1ea11d 100644 --- a/activesupport/test/core_ext/module/attribute_accessor_test.rb +++ b/activesupport/test/core_ext/module/attribute_accessor_test.rb @@ -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