I am working with a third party API and it seems like it unexpectedly returns null fields for what should be numeric attributes.
My application is using a lot of Model.whatever_attribute checks throughout its views and I suddenly started to get errors like "undefined method `>' for nil:NilClass" and similar errors where whatever_attribute is nil.
I have view code like this for example:
.stat{ :class => ((@obj.value > 1.2 and @obj.vaue > 0) ? 'green-font': 'red-font')}
Which comes back with the aforementioned exception if value = nil.
Now, I cannot really assume value to be 0 and have a default in the database for that, because it could be the wrong value. I would have to test whether I got null back from the API and maybe present a "N/A" or "-" to the end user.
I can do that all sorts of ways of course, my initial thinking was to setup a helper method and pretty much do the nil? check in there and return accordingly, but I am wondering.
Is there some sort of ruby idiom that can be used to handle such situations more gracefully ?
CodePudding user response:
I think it must be a model-based method
In app/models
file model_name.rb
Method like:
def get_font_class
self.value.nil? || self.value < 0 ? "green-font" : "red-font"
end
You can add any checks you want
NOTE: ||
checks first expression(self.value.nil?
) and if it's true
dont's checks the second(self.value < 0
)
And in view use this method:
class: @model_object.get_font_class