Skip to content

Instantly share code, notes, and snippets.

@romikoops
Forked from mikhailbortnyk/chainmethods.rb
Last active December 15, 2015 07:19
Show Gist options
  • Save romikoops/5222837 to your computer and use it in GitHub Desktop.
Save romikoops/5222837 to your computer and use it in GitHub Desktop.
class ChainMethod
def initialize(method_name, params = [], callbacks = {})
@method_name = method_name
@params = params.to_a
@callbacks = callbacks
end
def call(base_object)
# calling before_callback if passed
@callbacks[:before_callback].call(@params, base_object) if @callbacks[:before_callback].is_a?(Proc)
# main stuff
result = if @params.last.is_a? Proc
base_object.send(@method_name, *@params[0...-1], &@params.last)
else
base_object.send(@method_name, *@params.to_a)
end
# calling after_callback
@callbacks[:after_callback].call(@params, result) if @callbacks[:after_callback].is_a?(Proc)
# returning value
result
end
end
class Object
def chain_methods(chain)
chain.inject(self) { |result, chain_method| chain_method.call(result) }
end
end
callback_proc = Proc.new do |params, result|
puts "params = #{params.inspect}"
puts "result = #{result.inspect}"
end
p ["a", "b", "c"].chain_methods([
ChainMethod.new("reverse"),
ChainMethod.new("uniq"),
ChainMethod.new("map", [proc{|x| x.upcase}], {:after_callback => callback_proc}),
ChainMethod.new("map", [proc{|x| x.downcase}], {:before_callback => proc{ |params| p params}, :after_callback => callback_proc})
])
@mikhailbortnyk
Copy link

 result = if @params.last.is_a? Proc
      base_object.send(@method_name, *@params[0...-1], &@params.last)
    else
      base_object.send(@method_name, *@params.to_a)  
    end

красава!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment