aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/core_ext/object
diff options
context:
space:
mode:
Diffstat (limited to 'activesupport/lib/active_support/core_ext/object')
-rw-r--r--activesupport/lib/active_support/core_ext/object/itself.rb12
-rw-r--r--activesupport/lib/active_support/core_ext/object/with_options.rb17
2 files changed, 27 insertions, 2 deletions
diff --git a/activesupport/lib/active_support/core_ext/object/itself.rb b/activesupport/lib/active_support/core_ext/object/itself.rb
new file mode 100644
index 0000000000..adedc20169
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/object/itself.rb
@@ -0,0 +1,12 @@
+class Object
+ unless respond_to?(:itself) # TODO: Remove this file when we drop support for Ruby < 2.2
+ # Returns the object itself. Useful when dealing with a chaining scenario, like Active Record scopes:
+ #
+ # Event.public_send(state.presence_in([ :trashed, :drafted ]) || :itself).order(:created_at)
+ #
+ # @return Object
+ def itself
+ self
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb
index 42e388b065..42e87c4424 100644
--- a/activesupport/lib/active_support/core_ext/object/with_options.rb
+++ b/activesupport/lib/active_support/core_ext/object/with_options.rb
@@ -34,9 +34,22 @@ class Object
# body i18n.t :body, user_name: user.name
# end
#
+ # When you don't pass an explicit receiver, it executes the whole block
+ # in merging options context:
+ #
+ # class Account < ActiveRecord::Base
+ # with_options dependent: :destroy do
+ # has_many :customers
+ # has_many :products
+ # has_many :invoices
+ # has_many :expenses
+ # end
+ # end
+ #
# <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
# Each nesting level will merge inherited defaults in addition to their own.
- def with_options(options)
- yield ActiveSupport::OptionMerger.new(self, options)
+ def with_options(options, &block)
+ option_merger = ActiveSupport::OptionMerger.new(self, options)
+ block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
end
end