Skip to content

Commit 83ce6e3

Browse files
authored
Merge pull request rails#42682 from seanpdoyle/active-support-with-options-no-block
Support `Object#with_options` without a block
2 parents 66c9a2c + 8dc27b5 commit 83ce6e3

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed

activesupport/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
* Invoking `Object#with_options` without a `&block` argument returns the
2+
`ActiveSupport::OptionMerger` instance.
3+
4+
*Sean Doyle*
5+
16
* `Rails.application.executor` hooks are now called around every tests.
27

38
This helps to better simulate request or job local state being reset around tests and prevent state

activesupport/lib/active_support/core_ext/object/with_options.rb

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,8 +75,27 @@ class Object
7575
# end
7676
# end
7777
#
78+
# When the block argument is omitted, the decorated Object instance is returned:
79+
#
80+
# module MyStyledHelpers
81+
# def styled
82+
# with_options style: "color: red;"
83+
# end
84+
# end
85+
#
86+
# # styled.link_to "I'm red", "/"
87+
# # #=> <a href="/" style="color: red;">I'm red</a>
88+
#
89+
# # styled.button_tag "I'm red too!"
90+
# # #=> <button style="color: red;">I'm red too!</button>
91+
#
7892
def with_options(options, &block)
7993
option_merger = ActiveSupport::OptionMerger.new(self, options)
80-
block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
94+
95+
if block.nil?
96+
option_merger
97+
else
98+
block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
99+
end
81100
end
82101
end

activesupport/lib/active_support/option_merger.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,9 @@ def method_missing(method, *arguments, &block)
3030
@context.__send__(method, *arguments, &block)
3131
end
3232
end
33+
34+
def respond_to_missing?(*arguments)
35+
@context.respond_to?(*arguments)
36+
end
3337
end
3438
end

activesupport/test/option_merger_test.rb

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,14 @@ def test_option_merger_implicit_receiver
105105
assert_equal expected, @options
106106
end
107107

108+
def test_with_options_no_block
109+
local_options = { "cool" => true }
110+
scope = with_options(@options)
111+
112+
assert_equal local_options, method_with_options(local_options)
113+
assert_equal @options.merge(local_options), scope.method_with_options(local_options)
114+
end
115+
108116
private
109117
def method_with_options(options = {})
110118
options

0 commit comments

Comments
 (0)