Skip to content

Instantly share code, notes, and snippets.

@Widdershin
Created September 1, 2016 06:05
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Widdershin/b920a8a668f8030d4393e1870adaad7a to your computer and use it in GitHub Desktop.
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