Created
July 1, 2011 20:51
-
-
Save subelsky/1059375 to your computer and use it in GitHub Desktop.
using a null zero object
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
# I have a function that looks up a monthly report which may or may not exist yet (e.g. if | |
# you look at the start of a month, before I've gotten around to generating that month's | |
# report) | |
# | |
# where the report isn't generated I just want to return "0" for each column in this report; | |
# so what I do is return an instance of the below object whenever there's no report | |
# available (thus avoiding any "try" unpleasantness) - something about this slightly | |
# bothers me though. Is there a more elegant/simpler way I should consider? | |
class NullZeroObject | |
def method_missing(*args,&block) | |
0 | |
end | |
end |
I ended up doing this which felt a bit more expressive:
NULL_REPORT = Object.new
NULL_REPORT.define_singleton_method(:method_missing) { |*args| 0 }
@report = find_report_code_function_call || NULL_REPORT
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ooh those are all good. Did not realize nil.to_i == 0, I might be able to rejigger some things to take advantage! thanks man!