Last active
August 29, 2015 14:24
-
-
Save bchase/09f5f4dd0f83fb0f9767 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
| require 'pathname' | |
| require 'pry' | |
| class Object | |
| def tap(msg=nil, with:nil, to:nil, &block) | |
| if block_given? # original Object#tap functionality | |
| return super &block | |
| else | |
| if msg || with # msg to self e.g. #mkdir #gsub! | |
| if msg | |
| args = with || [] | |
| self.send msg, *args | |
| else | |
| self.send with | |
| end | |
| elsif to # into method e.g. ::puts | |
| if to.is_a? Symbol | |
| method(to).call self | |
| else | |
| to.call self | |
| end | |
| else | |
| raise ArgumentError 'No `msg`, `with:`, `to:` provided.' | |
| end | |
| end | |
| self | |
| end | |
| end | |
| f = Pathname 'boof' | |
| f.rmdir if f.exist? | |
| puts 'Object#tap(&block) works'.tap {|str| puts str} | |
| puts | |
| puts 'Object#tap(to: method_sym) works'.tap to: :puts | |
| puts 'Object#tap(to: method) works'.tap to: method(:puts) | |
| puts 'Object#tap(to: proc) works'.tap to: ->(str) { puts str } | |
| f.tap with: :mkdir | |
| puts | |
| 2.times { puts "Object#tap(with:) works" } if f.exist? | |
| # :D | |
| puts | |
| puts "Object#tap(method_sym, with: args_arr) doesn't work" | |
| .tap(:gsub!, with: [/doesn't/,'']) | |
| .tap(:gsub!, with: [/ work/,'works']) | |
| .tap to: :puts | |
| f.rmdir | |
| # $ ruby tap.rb | |
| # | |
| # Object#tap(&block) works | |
| # Object#tap(&block) works | |
| # | |
| # Object#tap(to: method_sym) works | |
| # Object#tap(to: method_sym) works | |
| # Object#tap(to: method) works | |
| # Object#tap(to: method) works | |
| # Object#tap(to: proc) works | |
| # Object#tap(to: proc) works | |
| # | |
| # Object#tap(with:) works | |
| # Object#tap(with:) works | |
| # | |
| # Object#tap(method_sym, with: args_arr) works | |
| # Object#tap(method_sym, with: args_arr) works |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment