Skip to content

Commit

Permalink
Merge pull request #42030 from diegotoral/configurable-default-option
Browse files Browse the repository at this point in the history
Add support for defining default values as option for ActiveSupport::Configurable accessors
  • Loading branch information
rafaelfranca authored Jul 29, 2021
2 parents 336af2e + 99525cb commit 646e9d3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
9 changes: 6 additions & 3 deletions activesupport/lib/active_support/configurable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,19 @@ def configure
# 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)

Expand All @@ -118,7 +120,8 @@ def config_accessor(*names, instance_reader: true, instance_writer: true, instan
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
Expand Down
11 changes: 10 additions & 1 deletion activesupport/test/configurable_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class Child < Parent
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
Expand All @@ -62,6 +62,15 @@ class Child < Parent
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
Expand Down

0 comments on commit 646e9d3

Please sign in to comment.