ActiveSupport::Configurable default value option

Sometimes it can be very strange or long have to define default values
for config accessors as blocks, specially when config is a simple value
like 1, true, :symbol. This commit adds the ability to specify those
values by just passing a ` default` option when defining the accessor.

It also makes config accessor's interface similar to other Rails
methods like `class_attribute`, which also has the instance_reader,
instance_writer and instance_accessor options.
This commit is contained in:
Diego Toral 2021-07-20 10:36:58 -03:00
parent bc488431ae
commit 99525cb6ff
2 changed files with 16 additions and 4 deletions

View File

@ -94,17 +94,19 @@ module ActiveSupport
# User.new.allowed_access = true # => NoMethodError
# User.new.allowed_access # => NoMethodError
#
# Also you can pass a block to set up the attribute with a default value.
# Also you can pass <tt>default</tt> or a block to set up the attribute with a default value.
#
# class User
# include ActiveSupport::Configurable
# config_accessor :allowed_access, default: false
# config_accessor :hair_colors do
# [:brown, :black, :blonde, :red]
# end
# end
#
# User.allowed_access # => false
# User.hair_colors # => [:brown, :black, :blonde, :red]
def config_accessor(*names, instance_reader: true, instance_writer: true, instance_accessor: true) # :doc:
def config_accessor(*names, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil) # :doc:
names.each do |name|
raise NameError.new("invalid config attribute name") unless /\A[_A-Za-z]\w*\z/.match?(name)
@ -118,7 +120,8 @@ module ActiveSupport
class_eval reader, __FILE__, reader_line if instance_reader
class_eval writer, __FILE__, writer_line if instance_writer
end
send("#{name}=", yield) if block_given?
send("#{name}=", block_given? ? yield : default)
end
end
private :config_accessor

View File

@ -50,7 +50,7 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert_not_respond_to instance, :baz=
end
test "configuration accessors can take a default value" do
test "configuration accessors can take a default value as a block" do
parent = Class.new do
include ActiveSupport::Configurable
config_accessor :hair_colors, :tshirt_colors do
@ -62,6 +62,15 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert_equal [:black, :blue, :white], parent.tshirt_colors
end
test "configuration accessors can take a default value as an option" do
parent = Class.new do
include ActiveSupport::Configurable
config_accessor :foo, default: :bar
end
assert_equal :bar, parent.foo
end
test "configuration hash is available on instance" do
instance = Parent.new
assert_equal :bar, instance.config.foo