set up config_accessor with a default value by block

* ActiveSupport::Configurable should allow config_accessor to take
  default value by block, just like cattr_accessor.

    class User
      include ActiveSupport::Configurable
      config_accessor :hair_colors do
        [:brown, :black, :blonde, :red]
      end
    end

    User.hair_colors # => [:brown, :black, :blonde, :red]

* remove trailing whitespaces in configurable.rb and its test file.

* Update ActiveSupport CHANGELOG.
This commit is contained in:
Larry Lv 2012-09-15 03:25:21 +08:00
parent 82efe8943b
commit 1efe30ebce
3 changed files with 45 additions and 8 deletions

View File

@ -1,5 +1,18 @@
## Rails 4.0.0 (unreleased) ##
* An optional block can be passed to `config_accessor` to set its default value
class User
include ActiveSupport::Configurable
config_accessor :hair_colors do
[:brown, :black, :blonde, :red]
end
end
User.hair_colors # => [:brown, :black, :blonde, :red]
*Larry Lv*
* ActiveSupport::Benchmarkable#silence has been deprecated due to its lack of
thread safety. It will be removed without replacement in Rails 4.1. *Steve
Klabnik*

View File

@ -92,6 +92,17 @@ 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.
#
# class User
# include ActiveSupport::Configurable
# config_accessor :hair_colors do
# [:brown, :black, :blonde, :red]
# end
# end
#
# User.hair_colors # => [:brown, :black, :blonde, :red]
def config_accessor(*names)
options = names.extract_options!
@ -108,6 +119,7 @@ module ActiveSupport
class_eval reader, __FILE__, reader_line unless options[:instance_reader] == false
class_eval writer, __FILE__, writer_line unless options[:instance_writer] == false
end
send("#{name}=", yield) if block_given?
end
end
end

View File

@ -48,6 +48,18 @@ class ConfigurableActiveSupport < ActiveSupport::TestCase
assert !instance.respond_to?(:baz=)
end
test "configuration accessors can take a default value" do
parent = Class.new do
include ActiveSupport::Configurable
config_accessor :hair_colors, :tshirt_colors do
[:black, :blue, :white]
end
end
assert_equal [:black, :blue, :white], parent.hair_colors
assert_equal [:black, :blue, :white], parent.tshirt_colors
end
test "configuration hash is available on instance" do
instance = Parent.new
assert_equal :bar, instance.config.foo