Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Instance reader method on class_attribute - 3-1-stable #1773

Merged
merged 1 commit into from
Jun 19, 2011
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions activesupport/lib/active_support/core_ext/class/attribute.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/module/remove_method'
require 'active_support/core_ext/array/extract_options'

class Class
# Declare a class-level attribute whose value is inheritable by subclasses.
Expand Down Expand Up @@ -56,11 +57,18 @@ class Class
# object.setting # => false
# Base.setting # => true
#
# To opt out of the instance reader method, pass :instance_reader => false.
#
# object.setting # => NoMethodError
# object.setting? # => NoMethodError
#
# To opt out of the instance writer method, pass :instance_writer => false.
#
# object.setting = false # => NoMethodError
def class_attribute(*attrs)
instance_writer = !attrs.last.is_a?(Hash) || attrs.pop[:instance_writer]
options = attrs.extract_options!
instance_reader = options.fetch(:instance_reader, true)
instance_writer = options.fetch(:instance_writer, true)

attrs.each do |name|
class_eval <<-RUBY, __FILE__, __LINE__ + 1
Expand All @@ -84,13 +92,15 @@ def #{name}
val
end

remove_possible_method :#{name}
def #{name}
defined?(@#{name}) ? @#{name} : self.class.#{name}
end
if instance_reader
remove_possible_method :#{name}
def #{name}
defined?(@#{name}) ? @#{name} : self.class.#{name}
end

def #{name}?
!!#{name}
def #{name}?
!!#{name}
end
end
RUBY

Expand Down
6 changes: 6 additions & 0 deletions activesupport/test/core_ext/class/attribute_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,12 @@ def setup
assert_raise(NoMethodError) { object.setting = 'boom' }
end

test 'disabling instance reader' do
object = Class.new { class_attribute :setting, :instance_reader => false }.new
assert_raise(NoMethodError) { object.setting }
assert_raise(NoMethodError) { object.setting? }
end

test 'works well with singleton classes' do
object = @klass.new
object.singleton_class.setting = 'foo'
Expand Down