|
The example from the blog post is a classic error we've all made. There seems to be an obvious opportunity for Rails do something creative about that. I like the String? sugar and believe there is probably some opportunity in Rails to address it. For example make a new NillableObject class that wraps the real object or delegates method_missing. The idea would be to throw a warning, raise an error, etc. when accessing a nillable attribute. This could get obviously more robust than the below example, hook into read_attribute, leverage validations, log a warning instead of raise a runtime error, etc... but hopefully the point is made. class NillableObject
def initialize(obj = nil);@obj = obj;end
def method_missing(name, *args, &block)
raise "I'm nillable, don't call methods against me directly"
end
def try(&block)
return if @obj.nil?
block.call(@obj)
end
end
ns = NillableObject.new
ns.gsub("f","g") # RuntimeError: I'm nillable, don't call methods against me directly
ns.try{ |o| o.gsub("f","g") } # => nil
s = NillableObject.new("food")
s.gsub("f","g") # RuntimeError: I'm nillable, don't call methods against me directly
s.try{ |o| o.gsub("f","g") } # => "good"
|
My colleagues wrote a library that does something like this. You may want to check it out: https://github.com/thoughtbot/wrapped