Created
March 9, 2016 12:35
-
-
Save theHamdiz/12a9e3f699d4810f59bf to your computer and use it in GitHub Desktop.
In this gist we will try to add the logging functionality to the pre-existing Fixnum '/' method and learn how to do so in the process thro alias_method technique.
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 'logger' | |
| # Generally its a good practice to avoid global variables, but a good use of them would be in a logger constant | |
| # you can try other Logger creation options such as | |
| # Keep data for the current month only | |
| # Logger.new('this_month.log', 'monthly') | |
| # Keep data for today and the past 20 days. | |
| # Logger.new('application.log', 20, 'daily') | |
| # Start the log over whenever the log exceeds 100 megabytes in size. | |
| # Logger.new('application.log', 0, 100 * 1024 * 1024) | |
| $LOG = Logger.new('app.log', 'monthly') | |
| class Fixnum | |
| # alias the original Fixnum division method | |
| alias_method :divide, :/ | |
| # overriding division method to add logger functionality | |
| def /(denominator) | |
| $LOG.debug("Trying to divide #{self} By #{denominator}") | |
| begin | |
| return self.divide denominator | |
| rescue Exception => ex | |
| $LOG.error("Error occured (#{ex})") | |
| return nil | |
| end | |
| end | |
| end | |
| # trying it out... | |
| (0..10).to_a.each { |i| puts 1 / i } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment