aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/test/core_ext
diff options
context:
space:
mode:
authorGenadi Samokovarov <gsamokovarov@gmail.com>2016-02-27 19:23:42 +0200
committerGenadi Samokovarov <gsamokovarov@gmail.com>2016-02-27 19:26:27 +0200
commit335fcc214a4b7ea5e10b3610cce6faea4262e4f6 (patch)
tree56f70b4e0518aa5a33c30a05ad5021dc2e95c172 /activesupport/test/core_ext
parentecf6dc3dfbc0cdf1b0a86f48e030debd0f917cb6 (diff)
downloadrails-335fcc214a4b7ea5e10b3610cce6faea4262e4f6.tar.gz
rails-335fcc214a4b7ea5e10b3610cce6faea4262e4f6.tar.bz2
rails-335fcc214a4b7ea5e10b3610cce6faea4262e4f6.zip
Introduce Module#delegate_missing_to
When building decorators, a common pattern may emerge: class Partition def initialize(first_event) @events = [ first_event ] end def people if @events.first.detail.people.any? @events.collect { |e| Array(e.detail.people) }.flatten.uniq else @events.collect(&:creator).uniq end end private def respond_to_missing?(name, include_private = false) @events.respond_to?(name, include_private) end def method_missing(method, *args, &block) @events.send(method, *args, &block) end end With `Module#delegate_missing_to`, the above is condensed to: class Partition delegate_missing_to :@events def initialize(first_event) @events = [ first_event ] end def people if @events.first.detail.people.any? @events.collect { |e| Array(e.detail.people) }.flatten.uniq else @events.collect(&:creator).uniq end end end David suggested it in #23824.
Diffstat (limited to 'activesupport/test/core_ext')
-rw-r--r--activesupport/test/core_ext/module_test.rb22
1 files changed, 22 insertions, 0 deletions
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index 0ed66f8c37..ed9cf897a4 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -83,6 +83,20 @@ Product = Struct.new(:name) do
end
end
+DecoratedTester = Struct.new(:client) do
+ delegate_missing_to :client
+end
+
+class DecoratedReserved
+ delegate_missing_to :case
+
+ attr_reader :case
+
+ def initialize(kase)
+ @case = kase
+ end
+end
+
class Block
def hello?
true
@@ -316,6 +330,14 @@ class ModuleTest < ActiveSupport::TestCase
assert has_block.hello?
end
+ def test_delegate_to_missing_with_method
+ assert_equal "David", DecoratedTester.new(@david).name
+ end
+
+ def test_delegate_to_missing_with_reserved_methods
+ assert_equal "David", DecoratedReserved.new(@david).name
+ end
+
def test_parent
assert_equal Yz::Zy, Yz::Zy::Cd.parent
assert_equal Yz, Yz::Zy.parent