Last active
December 10, 2015 18:58
-
-
Save mdespuits/4478271 to your computer and use it in GitHub Desktop.
Example uses of Object#tap that I really like
This file contains 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
# Logging some action in the console or log file | |
# Prevents lots of references to a variable | |
# Maybe not the best example, but potentially cleaner than the alternative | |
class ApplicationController | |
after_filter :log_action_without_tap | |
after_filter :log_action_with_tap | |
private | |
def log_action_with_tap | |
"[ACTION LOG]: #{current_account.name} tried to #{action_name} #{controller_path}".tap{|l| | |
l << flash.map{|k,v| "#{k}: #{v}"}.join(',') if flash.any? | |
Rails.logger.info(l) | |
} | |
end | |
# vs | |
def log_action_without_tap | |
action_to_log = "[ACTION LOG]: #{current_account.name} tried to #{action_name} #{controller_path} " | |
if flash.any? | |
action_to_log << " || " | |
action_to_log << flash.map{|k,v| "#{k}: #{v}"}.join(',') | |
end | |
Rails.logger.debug(action_to_log) | |
end | |
end | |
# Debugging in a test | |
# No need to add a reference variable and new line to output | |
# to the console. Just tap it and call `puts` to see in the | |
# test output. | |
class LoggerTest < ActiveSupport::TestCase | |
def test_unknown_string_with_tap | |
# Just remove the tap when done | |
unknown_string.tap{|s| puts s} | |
end | |
def test_unknown_string_without_tap | |
# lots of stuff to clean up after checking console output | |
unknown_string = reference_to_output_being_tested | |
puts unknown_string # uncomment this to see output | |
end | |
end | |
# Use as a builder | |
# Allows for caching and simplifies | |
# of a potentially complicated object definition | |
@routes ||= Routes.new.tap do |route| | |
route.connect "some url", to: "SomeController#action" | |
route.connect "some other url", to: "AnotherController#action" | |
end.finish_and_cache! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment