Created
August 5, 2015 22:52
-
-
Save Widdershin/ddad1dde9c2c13839f11 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Message | |
| def initialize(method_name, *args, &block) | |
| @method_name = method_name | |
| @args = args | |
| @block = block | |
| end | |
| def call(value) | |
| value.send(@method_name, *@args, &@block) | |
| end | |
| end | |
| class ChainedLookup | |
| def initialize(messages = []) | |
| @messages = messages | |
| end | |
| def to_s | |
| ChainedLookup.new( | |
| @messages + [Message.new(:to_s)] | |
| ) | |
| end | |
| def method_missing(method_name, *args, &block) | |
| ChainedLookup.new( | |
| @messages + [ | |
| Message.new( | |
| method_name, | |
| *args, | |
| &block | |
| ) | |
| ] | |
| ) | |
| end | |
| def respond_to?(method_name, include_private = false) | |
| true | |
| end | |
| def to_proc | |
| Proc.new do |object| | |
| @messages.reduce(object) do |value, message| | |
| message.call(value) | |
| end | |
| end | |
| end | |
| end | |
| this = ChainedLookup.new | |
| p [1, 2, 3].map(&this * 5 / 2) # => [2, 5, 7] | |
| test_hash = { | |
| a: ['foo', 'baz', 'bar'] | |
| } | |
| other_hash = { | |
| a: ['snaz'] | |
| } | |
| p [test_hash, other_hash].map(&this[:a][0]) # => ["foo", "snaz"] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment