Created
April 11, 2011 14:21
-
-
Save mark/913594 to your computer and use it in GitHub Desktop.
Detecting unspecified arguments in Ruby, inspired by http://www.harukizaemon.com/2011/04/detecting-unspecified-method-arguments-in-ruby.html
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
class Object | |
def default! | |
@__is_default = true | |
self | |
end | |
def default? | |
@__is_default | |
end | |
end | |
def my_method(param = nil.default!) | |
puts "Parameter = #{ param.inspect }, is default? #{ !!(param.default?) }" | |
end | |
# With a real argument: | |
my_method 123 # => Parameter = 123, is default? false | |
# With a real nil argument: | |
my_method nil # => Parameter = nil, is default? false | |
# With no argument: | |
my_method # => Parameter = nil, is default? true | |
# PROBLEM WITH THIS IMPLEMENTATION: | |
# Call with a real nil argument again: | |
my_method nil # => Parameter = nil, is_default? true |
Yeah, you're totally right... I had forgotten about that until one of my coworkers pointed it out to me. In that case, I'd probably keep the api (which I like), and instead have default! return a proxy around an object, that defines default?.
Of course, using a proxy runs into problems with passing that proxied object into other methods that check for default-ness.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nil is a singleton, so once you sent :default! to it, it will always return true to :default? message.
Try to change order of calls and you'll see.