1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #29294 from gsamokovarov/attributes-default

Introduce mattr_accessor default option
This commit is contained in:
Kasper Timm Hansen 2017-06-04 16:12:40 +02:00 committed by GitHub
commit 704209b017
39 changed files with 134 additions and 150 deletions

View file

@ -10,7 +10,7 @@ module ActionCable
include ActionCable::Server::Broadcasting
include ActionCable::Server::Connections
cattr_accessor(:config, instance_accessor: true) { ActionCable::Server::Configuration.new }
cattr_accessor :config, instance_accessor: true, default: ActionCable::Server::Configuration.new
def self.logger; config.logger; end
delegate :logger, to: :config

View file

@ -17,11 +17,11 @@ module ActionCable
# Overwrite this factory method for EventMachine Redis connections if you want to use a different Redis connection library than EM::Hiredis.
# This is needed, for example, when using Makara proxies for distributed Redis.
cattr_accessor(:em_redis_connector) { ->(config) { EM::Hiredis.connect(config[:url]) } }
cattr_accessor :em_redis_connector, default: ->(config) { EM::Hiredis.connect(config[:url]) }
# Overwrite this factory method for Redis connections if you want to use a different Redis connection library than Redis.
# This is needed, for example, when using Makara proxies for distributed Redis.
cattr_accessor(:redis_connector) { ->(config) { ::Redis.new(url: config[:url]) } }
cattr_accessor :redis_connector, default: ->(config) { ::Redis.new(url: config[:url]) }
def initialize(*)
ActiveSupport::Deprecation.warn(<<-MSG.squish)

View file

@ -10,7 +10,7 @@ module ActionCable
# Overwrite this factory method for redis connections if you want to use a different Redis library than Redis.
# This is needed, for example, when using Makara proxies for distributed Redis.
cattr_accessor(:redis_connector) { ->(config) { ::Redis.new(url: config[:url]) } }
cattr_accessor :redis_connector, default: ->(config) { ::Redis.new(url: config[:url]) }
def initialize(*)
super

View file

@ -8,14 +8,9 @@ module ActionMailer
included do
# Do not make this inheritable, because we always want it to propagate
cattr_accessor :raise_delivery_errors
self.raise_delivery_errors = true
cattr_accessor :perform_deliveries
self.perform_deliveries = true
cattr_accessor :deliver_later_queue_name
self.deliver_later_queue_name = :mailers
cattr_accessor :raise_delivery_errors, default: true
cattr_accessor :perform_deliveries, default: true
cattr_accessor :deliver_later_queue_name, default: :mailers
class_attribute :delivery_methods, default: {}.freeze
class_attribute :delivery_method, default: :smtp

View file

@ -20,8 +20,7 @@ module ActionMailer
mattr_accessor :show_previews, instance_writer: false
# :nodoc:
mattr_accessor :preview_interceptors, instance_writer: false
self.preview_interceptors = [ActionMailer::InlinePreviewInterceptor]
mattr_accessor :preview_interceptors, instance_writer: false, default: [ActionMailer::InlinePreviewInterceptor]
end
module ClassMethods

View file

@ -119,8 +119,7 @@ module ActionController
# params[:key] # => "value"
# params["key"] # => "value"
class Parameters
cattr_accessor :permit_all_parameters, instance_accessor: false
self.permit_all_parameters = false
cattr_accessor :permit_all_parameters, instance_accessor: false, default: false
cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false
@ -205,8 +204,7 @@ module ActionController
# config. For instance:
#
# config.always_permitted_parameters = %w( controller action format )
cattr_accessor :always_permitted_parameters
self.always_permitted_parameters = %w( controller action )
cattr_accessor :always_permitted_parameters, default: %w( controller action )
# Returns a new instance of <tt>ActionController::Parameters</tt>.
# Also, sets the +permitted+ attribute to the default value of

View file

@ -6,8 +6,7 @@ module ActionDispatch
extend ActiveSupport::Concern
included do
mattr_accessor :ignore_accept_header
self.ignore_accept_header = false
mattr_accessor :ignore_accept_header, default: false
end
# The MIME type of the HTTP request, such as Mime[:xml].

View file

@ -81,8 +81,8 @@ module ActionDispatch # :nodoc:
LOCATION = "Location".freeze
NO_CONTENT_CODES = [100, 101, 102, 204, 205, 304]
cattr_accessor(:default_charset) { "utf-8" }
cattr_accessor(:default_headers)
cattr_accessor :default_charset, default: "utf-8"
cattr_accessor :default_headers
include Rack::Response::Helpers
# Aliasing these off because AD::Http::Cache::Response defines them.

View file

@ -7,8 +7,7 @@ module ActionDispatch
HOST_REGEXP = /(^[^:]+:\/\/)?(\[[^\]]+\]|[^:]+)(?::(\d+$))?/
PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/
mattr_accessor :tld_length
self.tld_length = 1
mattr_accessor :tld_length, default: 1
class << self
# Returns the domain part of a host given the domain level.

View file

@ -432,8 +432,7 @@ module ActionDispatch
end
end
mattr_accessor :always_write_cookie
self.always_write_cookie = false
mattr_accessor :always_write_cookie, default: false
private

View file

@ -3,9 +3,7 @@ require "rack/utils"
module ActionDispatch
class ExceptionWrapper
cattr_accessor :rescue_responses
@@rescue_responses = Hash.new(:internal_server_error)
@@rescue_responses.merge!(
cattr_accessor :rescue_responses, default: Hash.new(:internal_server_error).merge!(
"ActionController::RoutingError" => :not_found,
"AbstractController::ActionNotFound" => :not_found,
"ActionController::MethodNotAllowed" => :method_not_allowed,
@ -21,9 +19,7 @@ module ActionDispatch
"Rack::QueryParser::InvalidParameterError" => :bad_request
)
cattr_accessor :rescue_templates
@@rescue_templates = Hash.new("diagnostics")
@@rescue_templates.merge!(
cattr_accessor :rescue_templates, default: Hash.new("diagnostics").merge!(
"ActionView::MissingTemplate" => "missing_template",
"ActionController::RoutingError" => "routing_error",
"AbstractController::ActionNotFound" => "unknown_action",

View file

@ -1,8 +1,7 @@
module ActionDispatch
class Request
class Utils # :nodoc:
mattr_accessor :perform_deep_munge
self.perform_deep_munge = true
mattr_accessor :perform_deep_munge, default: true
def self.each_param_value(params, &block)
case params

View file

@ -140,30 +140,25 @@ module ActionView #:nodoc:
include Helpers, ::ERB::Util, Context
# Specify the proc used to decorate input tags that refer to attributes with errors.
cattr_accessor :field_error_proc
@@field_error_proc = Proc.new { |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
cattr_accessor :field_error_proc, default: Proc.new { |html_tag, instance| "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe }
# How to complete the streaming when an exception occurs.
# This is our best guess: first try to close the attribute, then the tag.
cattr_accessor :streaming_completion_on_exception
@@streaming_completion_on_exception = %("><script>window.location = "/500.html"</script></html>)
cattr_accessor :streaming_completion_on_exception, default: %("><script>window.location = "/500.html"</script></html>)
# Specify whether rendering within namespaced controllers should prefix
# the partial paths for ActiveModel objects with the namespace.
# (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb)
cattr_accessor :prefix_partial_path_with_controller_namespace
@@prefix_partial_path_with_controller_namespace = true
cattr_accessor :prefix_partial_path_with_controller_namespace, default: true
# Specify default_formats that can be rendered.
cattr_accessor :default_formats
# Specify whether an error should be raised for missing translations
cattr_accessor :raise_on_missing_translations
@@raise_on_missing_translations = false
cattr_accessor :raise_on_missing_translations, default: false
# Specify whether submit_tag should automatically disable on click
cattr_accessor :automatically_disable_submit_tag
@@automatically_disable_submit_tag = true
cattr_accessor :automatically_disable_submit_tag, default: true
class_attribute :_routes
class_attribute :logger

View file

@ -474,7 +474,7 @@ module ActionView
end
private :apply_form_for_options!
mattr_accessor(:form_with_generates_remote_forms) { true }
mattr_accessor :form_with_generates_remote_forms, default: true
# Creates a form tag based on mixing URLs, scopes, or models.
#
@ -2318,8 +2318,6 @@ module ActionView
end
ActiveSupport.on_load(:action_view) do
cattr_accessor(:default_form_builder, instance_writer: false, instance_reader: false) do
::ActionView::Helpers::FormBuilder
end
cattr_accessor :default_form_builder, instance_writer: false, instance_reader: false, default: ::ActionView::Helpers::FormBuilder
end
end

View file

@ -11,8 +11,7 @@ module ActionView
include TagHelper
included do
mattr_accessor :debug_missing_translation
self.debug_missing_translation = true
mattr_accessor :debug_missing_translation, default: true
end
# Delegates to <tt>I18n#translate</tt> but also performs three additional

View file

@ -14,11 +14,9 @@ module ActionView
class LookupContext #:nodoc:
attr_accessor :prefixes, :rendered_format
mattr_accessor :fallbacks
@@fallbacks = FallbackFileSystemResolver.instances
mattr_accessor :fallbacks, default: FallbackFileSystemResolver.instances
mattr_accessor :registered_details
self.registered_details = []
mattr_accessor :registered_details, default: []
def self.register_detail(name, &block)
registered_details << name

View file

@ -5,7 +5,7 @@ module ActionView
included do
# Fallback cache store if Action View is used without Rails.
# Otherwise overridden in Railtie to use Rails.cache.
mattr_accessor(:collection_cache) { ActiveSupport::Cache::MemoryStore.new }
mattr_accessor :collection_cache, default: ActiveSupport::Cache::MemoryStore.new
end
private

View file

@ -125,8 +125,7 @@ module ActionView
end
end
cattr_accessor :caching
self.caching = true
cattr_accessor :caching, default: true
class << self
alias :caching? :caching

View file

@ -7,8 +7,7 @@ class UrlHelperTest < ActiveSupport::TestCase
# In those cases, we'll set up a simple mock
attr_accessor :controller, :request
cattr_accessor :request_forgery
self.request_forgery = false
cattr_accessor :request_forgery, default: false
routes = ActionDispatch::Routing::RouteSet.new
routes.draw do

View file

@ -8,7 +8,7 @@ module ActiveJob
extend ActiveSupport::Concern
included do
cattr_accessor(:logger) { ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT)) }
cattr_accessor :logger, default: ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT))
around_enqueue do |_, block, _|
tag_logger do

View file

@ -4,8 +4,8 @@ module ActiveJob
# Includes the ability to override the default queue name and prefix.
module ClassMethods
mattr_accessor(:queue_name_prefix)
mattr_accessor(:default_queue_name) { "default" }
mattr_accessor :queue_name_prefix
mattr_accessor :default_queue_name, default: "default"
# Specifies the name of the queue to process the job on.
#

View file

@ -4,7 +4,7 @@ module ActiveJob
# Includes the ability to override the default queue priority.
module ClassMethods
mattr_accessor(:default_priority)
mattr_accessor :default_priority
# Specifies the priority of the queue to create the job with.
#

View file

@ -19,8 +19,7 @@ module Delayed
include Delayed::Backend::Base
cattr_accessor :id
self.id = 0
cattr_accessor :id, default: 0
def initialize(hash = {})
self.attempts = 0

View file

@ -54,8 +54,7 @@ module ActiveRecord
extend ActiveSupport::Concern
included do
mattr_accessor :time_zone_aware_attributes, instance_writer: false
self.time_zone_aware_attributes = false
mattr_accessor :time_zone_aware_attributes, instance_writer: false, default: false
class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false, default: []
class_attribute :time_zone_aware_types, instance_writer: false, default: [ :datetime, :time ]

View file

@ -140,8 +140,7 @@ module ActiveRecord
included do
Associations::Builder::Association.extensions << AssociationBuilderExtension
mattr_accessor :index_nested_attribute_errors, instance_writer: false
self.index_nested_attribute_errors = false
mattr_accessor :index_nested_attribute_errors, instance_writer: false, default: false
end
module ClassMethods # :nodoc:

View file

@ -56,8 +56,7 @@ module ActiveRecord
# :singleton-method:
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
# dates and times from the database. This is set to :utc by default.
mattr_accessor :default_timezone, instance_writer: false
self.default_timezone = :utc
mattr_accessor :default_timezone, instance_writer: false, default: :utc
##
# :singleton-method:
@ -67,16 +66,14 @@ module ActiveRecord
# ActiveRecord::Schema file which can be loaded into any database that
# supports migrations. Use :ruby if you want to have different database
# adapters for, e.g., your development and test environments.
mattr_accessor :schema_format, instance_writer: false
self.schema_format = :ruby
mattr_accessor :schema_format, instance_writer: false, default: :ruby
##
# :singleton-method:
# Specifies if an error should be raised if the query has an order being
# ignored when doing batch queries. Useful in applications where the
# scope being ignored is error-worthy, rather than a warning.
mattr_accessor :error_on_ignored_order, instance_writer: false
self.error_on_ignored_order = false
mattr_accessor :error_on_ignored_order, instance_writer: false, default: false
def self.error_on_ignored_order_or_limit
ActiveSupport::Deprecation.warn(<<-MSG.squish)
@ -101,8 +98,7 @@ module ActiveRecord
##
# :singleton-method:
# Specify whether or not to use timestamps for migration versions
mattr_accessor :timestamped_migrations, instance_writer: false
self.timestamped_migrations = true
mattr_accessor :timestamped_migrations, instance_writer: false, default: true
##
# :singleton-method:
@ -110,8 +106,7 @@ module ActiveRecord
# db:migrate rake task. This is true by default, which is useful for the
# development environment. This should ideally be false in the production
# environment where dumping schema is rarely needed.
mattr_accessor :dump_schema_after_migration, instance_writer: false
self.dump_schema_after_migration = true
mattr_accessor :dump_schema_after_migration, instance_writer: false, default: true
##
# :singleton-method:
@ -120,8 +115,7 @@ module ActiveRecord
# schema_search_path are dumped. Use :all to dump all schemas regardless
# of schema_search_path, or a string of comma separated schemas for a
# custom list.
mattr_accessor :dump_schemas, instance_writer: false
self.dump_schemas = :schema_search_path
mattr_accessor :dump_schemas, instance_writer: false, default: :schema_search_path
##
# :singleton-method:
@ -130,7 +124,6 @@ module ActiveRecord
# be used to identify queries which load thousands of records and
# potentially cause memory bloat.
mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false
self.warn_on_records_fetched_greater_than = nil
mattr_accessor :maintain_test_schema, instance_accessor: false

View file

@ -492,8 +492,7 @@ module ActiveRecord
end
end
cattr_accessor :all_loaded_fixtures
self.all_loaded_fixtures = {}
cattr_accessor :all_loaded_fixtures, default: {}
class ClassCache
def initialize(class_names, config)

View file

@ -13,8 +13,7 @@ module ActiveRecord
# A list of tables which should not be dumped to the schema.
# Acceptable values are strings as well as regexp if ActiveRecord::Base.schema_format == :ruby.
# Only strings are accepted if ActiveRecord::Base.schema_format == :sql.
cattr_accessor :ignore_tables
@@ignore_tables = []
cattr_accessor :ignore_tables, default: []
class << self
def dump(connection = ActiveRecord::Base.connection, stream = STDOUT, config = ActiveRecord::Base)

View file

@ -1,3 +1,12 @@
* Add default option to module and class attribute accessors.
mattr_accessor :settings, default: {}
Works for `mattr_reader`, `mattr_writer`, `cattr_accessor`, `cattr_reader`,
and `cattr_writer` as well.
*Genadi Samokovarov*
* Add `Date#prev_occurring` and `Date#next_occurring` to return specified next/previous occurring day of week.
*Shota Iguchi*

View file

@ -9,6 +9,6 @@ module DateAndTime
# of the receiver. For backwards compatibility we're overriding
# this behavior, but new apps will have an initializer that sets
# this to true, because the new behavior is preferred.
mattr_accessor(:preserve_timezone, instance_writer: false) { false }
mattr_accessor :preserve_timezone, instance_writer: false, default: false
end
end

View file

@ -38,13 +38,10 @@ class Module
#
# Person.new.hair_colors # => NoMethodError
#
#
# Also, you can pass a block to set up the attribute with a default value.
# You can set a default value for the attribute.
#
# module HairColors
# mattr_reader :hair_colors do
# [:brown, :black, :blonde, :red]
# end
# mattr_reader :hair_colors, default: [:brown, :black, :blonde, :red]
# end
#
# class Person
@ -52,8 +49,7 @@ class Module
# end
#
# Person.new.hair_colors # => [:brown, :black, :blonde, :red]
def mattr_reader(*syms)
options = syms.extract_options!
def mattr_reader(*syms, instance_reader: true, instance_accessor: true, default: nil)
syms.each do |sym|
raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym)
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@ -64,14 +60,16 @@ class Module
end
EOS
unless options[:instance_reader] == false || options[:instance_accessor] == false
if instance_reader && instance_accessor
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}
@@#{sym}
end
EOS
end
class_variable_set("@@#{sym}", yield) if block_given?
sym_default_value = (block_given? && default.nil?) ? yield : default
class_variable_set("@@#{sym}", sym_default_value) unless sym_default_value.nil?
end
end
alias :cattr_reader :mattr_reader
@ -107,12 +105,10 @@ class Module
#
# Person.new.hair_colors = [:blonde, :red] # => NoMethodError
#
# Also, you can pass a block to set up the attribute with a default value.
# You can set a default value for the attribute.
#
# module HairColors
# mattr_writer :hair_colors do
# [:brown, :black, :blonde, :red]
# end
# mattr_writer :hair_colors, default: [:brown, :black, :blonde, :red]
# end
#
# class Person
@ -120,8 +116,7 @@ class Module
# end
#
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
def mattr_writer(*syms)
options = syms.extract_options!
def mattr_writer(*syms, instance_writer: true, instance_accessor: true, default: nil)
syms.each do |sym|
raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym)
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@ -132,14 +127,16 @@ class Module
end
EOS
unless options[:instance_writer] == false || options[:instance_accessor] == false
if instance_writer && instance_accessor
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def #{sym}=(obj)
@@#{sym} = obj
end
EOS
end
send("#{sym}=", yield) if block_given?
sym_default_value = (block_given? && default.nil?) ? yield : default
send("#{sym}=", sym_default_value) unless sym_default_value.nil?
end
end
alias :cattr_writer :mattr_writer
@ -197,12 +194,10 @@ class Module
# Person.new.hair_colors = [:brown] # => NoMethodError
# Person.new.hair_colors # => NoMethodError
#
# Also you can pass a block to set up the attribute with a default value.
# You can set a default value for the attribute.
#
# module HairColors
# mattr_accessor :hair_colors do
# [:brown, :black, :blonde, :red]
# end
# mattr_accessor :hair_colors, default: [:brown, :black, :blonde, :red]
# end
#
# class Person
@ -210,9 +205,9 @@ class Module
# end
#
# Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red]
def mattr_accessor(*syms, &blk)
mattr_reader(*syms, &blk)
mattr_writer(*syms)
def mattr_accessor(*syms, instance_reader: true, instance_writer: true, instance_accessor: true, default: nil, &blk)
mattr_reader(*syms, instance_reader: instance_reader, instance_accessor: instance_accessor, default: default, &blk)
mattr_writer(*syms, instance_writer: instance_writer, instance_accessor: instance_accessor, default: default)
end
alias :cattr_accessor :mattr_accessor
end

View file

@ -18,8 +18,7 @@ module ActiveSupport #:nodoc:
module Dependencies #:nodoc:
extend self
mattr_accessor :interlock
self.interlock = Interlock.new
mattr_accessor :interlock, default: Interlock.new
# :doc:
@ -46,46 +45,37 @@ module ActiveSupport #:nodoc:
# :nodoc:
# Should we turn on Ruby warnings on the first load of dependent files?
mattr_accessor :warnings_on_first_load
self.warnings_on_first_load = false
mattr_accessor :warnings_on_first_load, default: false
# All files ever loaded.
mattr_accessor :history
self.history = Set.new
mattr_accessor :history, default: Set.new
# All files currently loaded.
mattr_accessor :loaded
self.loaded = Set.new
mattr_accessor :loaded, default: Set.new
# Stack of files being loaded.
mattr_accessor :loading
self.loading = []
mattr_accessor :loading, default: []
# Should we load files or require them?
mattr_accessor :mechanism
self.mechanism = ENV["NO_RELOAD"] ? :require : :load
mattr_accessor :mechanism, default: ENV["NO_RELOAD"] ? :require : :load
# The set of directories from which we may automatically load files. Files
# under these directories will be reloaded on each request in development mode,
# unless the directory also appears in autoload_once_paths.
mattr_accessor :autoload_paths
self.autoload_paths = []
mattr_accessor :autoload_paths, default: []
# The set of directories from which automatically loaded constants are loaded
# only once. All directories in this set must also be present in +autoload_paths+.
mattr_accessor :autoload_once_paths
self.autoload_once_paths = []
mattr_accessor :autoload_once_paths, default: []
# An array of qualified constant names that have been loaded. Adding a name
# to this array will cause it to be unloaded the next time Dependencies are
# cleared.
mattr_accessor :autoloaded_constants
self.autoloaded_constants = []
mattr_accessor :autoloaded_constants, default: []
# An array of constant names that need to be unloaded on every request. Used
# to allow arbitrary constants to be marked for unloading.
mattr_accessor :explicitly_unloadable_constants
self.explicitly_unloadable_constants = []
mattr_accessor :explicitly_unloadable_constants, default: []
# The WatchStack keeps a stack of the modules being watched as files are
# loaded. If a file in the process of being loaded (parent.rb) triggers the
@ -175,8 +165,7 @@ module ActiveSupport #:nodoc:
end
# An internal stack used to record which constants are loaded by any block.
mattr_accessor :constant_watch_stack
self.constant_watch_stack = WatchStack.new
mattr_accessor :constant_watch_stack, default: WatchStack.new
# Module includes this module.
module ModuleConstMissing #:nodoc:

View file

@ -49,8 +49,7 @@ module ActiveSupport
CYAN = "\e[36m"
WHITE = "\e[37m"
mattr_accessor :colorize_logging
self.colorize_logging = true
mattr_accessor :colorize_logging, default: true
class << self
def logger

View file

@ -6,8 +6,7 @@ module LoggerSilence
extend ActiveSupport::Concern
included do
cattr_accessor :silencer
self.silencer = true
cattr_accessor :silencer, default: true
end
# Silences the logger for the duration of the block.

View file

@ -12,7 +12,14 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
cattr_accessor(:defa) { "default_accessor_value" }
cattr_reader(:defr) { "default_reader_value" }
cattr_writer(:defw) { "default_writer_value" }
cattr_accessor(:deff) { false }
cattr_accessor(:quux) { :quux }
cattr_accessor :def_accessor, default: "default_accessor_value"
cattr_reader :def_reader, default: "default_reader_value"
cattr_writer :def_writer, default: "default_writer_value"
cattr_accessor :def_false, default: false
cattr_accessor(:def_priority, default: false) { :no_priority }
end
@class = Class.new
@class.instance_eval { include m }
@ -24,6 +31,21 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
assert_nil @object.foo
end
def test_mattr_default_keyword_arguments
assert_equal "default_accessor_value", @module.def_accessor
assert_equal "default_reader_value", @module.def_reader
assert_equal "default_writer_value", @module.class_variable_get(:@@def_writer)
end
def test_mattr_can_default_to_false
assert_equal false, @module.def_false
assert_equal false, @module.deff
end
def test_mattr_default_priority
assert_equal false, @module.def_priority
end
def test_should_set_mattr_value
@module.foo = :test
assert_equal :test, @object.foo
@ -91,9 +113,23 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
assert_equal "default_writer_value", @module.class_variable_get("@@defw")
end
def test_should_not_invoke_default_value_block_multiple_times
def test_method_invocation_should_not_invoke_the_default_block
count = 0
@module.cattr_accessor(:defcount) { count += 1 }
assert_equal 1, count
assert_no_difference "count" do
@module.defcount
end
end
def test_declaring_multiple_attributes_at_once_invokes_the_block_multiple_times
count = 0
@module.cattr_accessor(:defn1, :defn2) { count += 1 }
assert_equal 1, @module.defn1
assert_equal 2, @module.defn2
end
end

View file

@ -940,8 +940,7 @@ The macros `cattr_reader`, `cattr_writer`, and `cattr_accessor` are analogous to
```ruby
class MysqlAdapter < AbstractAdapter
# Generates class methods to access @@emulate_booleans.
cattr_accessor :emulate_booleans
self.emulate_booleans = true
cattr_accessor :emulate_booleans, default: true
end
```
@ -950,8 +949,7 @@ Instance methods are created as well for convenience, they are just proxies to t
```ruby
module ActionView
class Base
cattr_accessor :field_error_proc
@@field_error_proc = Proc.new{ ... }
cattr_accessor :field_error_proc, default: Proc.new { ... }
end
end
```
@ -963,7 +961,7 @@ Also, you can pass a block to `cattr_*` to set up the attribute with a default v
```ruby
class MysqlAdapter < AbstractAdapter
# Generates class methods to access @@emulate_booleans with default value of true.
cattr_accessor(:emulate_booleans) { true }
cattr_accessor :emulate_booleans, default: true
end
```

View file

@ -340,8 +340,7 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
cattr_accessor :yaffle_text_field, default: (options[:yaffle_text_field] || :last_squawk).to_s
end
end
end
@ -411,8 +410,7 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
cattr_accessor :yaffle_text_field, default: (options[:yaffle_text_field] || :last_squawk).to_s
include Yaffle::ActsAsYaffle::LocalInstanceMethods
end

View file

@ -5,8 +5,9 @@ module Rails
# Rails::InfoController responses. These include the active Rails version,
# Ruby version, Rack version, and so on.
module Info
mattr_accessor :properties
class << (@@properties = [])
mattr_accessor :properties, default: []
class << @@properties
def names
map(&:first)
end

View file

@ -134,7 +134,7 @@ module Minitest
end
end
mattr_reader(:run_via) { RunVia.new }
mattr_reader :run_via, default: RunVia.new
end
# Put Rails as the first plugin minitest initializes so other plugins