Skip to content

Instantly share code, notes, and snippets.

@tompave
Created January 11, 2015 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tompave/b7136cb33ef10519165d to your computer and use it in GitHub Desktop.
Save tompave/b7136cb33ef10519165d to your computer and use it in GitHub Desktop.
Try Chain
require 'active_support/core_ext/object/try'
module TryChain
def try_chain
@proxy = Proxy.new(self)
end
class Proxy
def initialize(obj)
@base = obj
@chain = []
end
def execute
@chain.reduce(@base) do |memo, data|
memo.try data[0], *data[1]
end
end
def respond_to?(meth, include_all = false)
false
end
def to_s
method_missing :to_s
end
def try_chain
self
end
private
def method_missing(meth, *args)
add_to_chain(meth, args)
self
end
def add_to_chain(meth, args)
@chain << [meth, args]
end
end
end
Object.send :include, TryChain
=begin
('a'..'f').try_chain.to_a.shuffle.reverse[2,3].join('-')
# => #<TryChain::Proxy:0x007f935a8dad20
# @base="a".."f",
# @chain=[[:to_a, []], [:shuffle, []], [:reverse, []], [:[], [2, 3]], [:join, ["-"]]]>
('a'..'f').try_chain.to_a.shuffle.reverse[2,3].join('-').execute
# => "c-b-a"
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment