Skip to content

Commit 8543974

Browse files
jasonkarnskaspth
authored andcommitted
concerning learns how to prepend the concern
In rare instances, a module needs to be prepended into the ancestor hierarchy, not simply included. In cases where this is necessary, and it is desirable to use an inline concern, it would be beneficial to be able to instruct `concerning` that the concern should be prepended. This is now possible, by providing `prepend: true` kwarg to `concerning`. (It is false by default.)
1 parent 5bd29af commit 8543974

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

activesupport/lib/active_support/core_ext/module/concerning.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,9 @@ class Module
106106
# * stop leaning on protected/private for crude "this is internal stuff" modularity.
107107
module Concerning
108108
# Define a new concern and mix it in.
109-
def concerning(topic, &block)
110-
include concern(topic, &block)
109+
def concerning(topic, prepend: false, &block)
110+
method = prepend ? :prepend : :include
111+
__send__(method, concern(topic, &block))
111112
end
112113

113114
# A low-cruft shortcut to define a concern.

activesupport/test/core_ext/module/concerning_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,18 @@ def test_concerning_declares_a_concern_and_includes_it_immediately
88
klass = Class.new { concerning(:Foo) { } }
99
assert_includes klass.ancestors, klass::Foo, klass.ancestors.inspect
1010
end
11+
12+
def test_concerning_can_prepend_concern
13+
klass = Class.new do
14+
def hi; "self"; end
15+
16+
concerning(:Foo, prepend: true) do
17+
def hi; "hello, #{super}"; end
18+
end
19+
end
20+
21+
assert_equal "hello, self", klass.new.hi
22+
end
1123
end
1224

1325
class ModuleConcernTest < ActiveSupport::TestCase

0 commit comments

Comments
 (0)