Skip to content

Commit

Permalink
activesupport: Simplify class_attribute implementation (#35454)
Browse files Browse the repository at this point in the history
* activesupport(class_attribute): Use redefine_singleton_method

* activesupport(class_attribute): Use keyword arguments

* activesupport(class_attribute): Avoid unnecessary redefinition for default
  • Loading branch information
dylanahsmith authored and kamipo committed Mar 3, 2019
1 parent f4a30d2 commit dfa439e
Showing 1 changed file with 10 additions and 15 deletions.
25 changes: 10 additions & 15 deletions activesupport/lib/active_support/core_ext/class/attribute.rb
Expand Up @@ -84,16 +84,17 @@ class Class
# To set a default value for the attribute, pass <tt>default:</tt>, like so:
#
# class_attribute :settings, default: {}
def class_attribute(*attrs)
options = attrs.extract_options!
instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true)
instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true)
instance_predicate = options.fetch(:instance_predicate, true)
default_value = options.fetch(:default, nil)

def class_attribute(
*attrs,
instance_accessor: true,
instance_reader: instance_accessor,
instance_writer: instance_accessor,
instance_predicate: true,
default: nil
)
attrs.each do |name|
singleton_class.silence_redefinition_of_method(name)
define_singleton_method(name) { nil }
define_singleton_method(name) { default }

singleton_class.silence_redefinition_of_method("#{name}?")
define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate
Expand All @@ -102,9 +103,7 @@ def class_attribute(*attrs)

singleton_class.silence_redefinition_of_method("#{name}=")
define_singleton_method("#{name}=") do |val|
singleton_class.class_eval do
redefine_method(name) { val }
end
redefine_singleton_method(name) { val }

if singleton_class?
class_eval do
Expand Down Expand Up @@ -137,10 +136,6 @@ def class_attribute(*attrs)
instance_variable_set ivar, val
end
end

unless default_value.nil?
self.send("#{name}=", default_value)
end
end
end
end

0 comments on commit dfa439e

Please sign in to comment.