-
-
Save romikoops/5222837 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 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}) | |
]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
красава!