Skip to content

Instantly share code, notes, and snippets.

@subelsky
Created July 1, 2011 20:51
Show Gist options
  • Save subelsky/1059375 to your computer and use it in GitHub Desktop.
Save subelsky/1059375 to your computer and use it in GitHub Desktop.
using a null zero object
# 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
@avdi
Copy link

avdi commented Jul 1, 2011

Thoughts:

  • There's nothing wrong with this as it stands.
  • Unless I really thought I'd be using it for more than reports, I'd probably call it NullReport or MissingReport to better express what's going on.
  • Zero is an interesting case because nil.to_i == 0, so depending on what your code looks like you could just use an empty OpenStruct and use to_i religiously on the members.

@subelsky
Copy link
Author

subelsky commented Jul 1, 2011

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!

@subelsky
Copy link
Author

subelsky commented Jul 3, 2011

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