check for user input and handle blanks
# If you have been programming for all these sickening years, you would have used something like this quite often. # You are reading user input and it might be having extra spaces, newlines god knows what at the ends, so you write code like this: foo_data = nil t_data = nil # your evil user may have entered only white spaces as input so better you strip them out if param[:from_data] t_data = param[:from_data].strip else t_data = param[:from_data] end unless t_data.empty? foo_data = param[:from_data].strip else foo_data = “Some other default value you want” end # now you can use foo_data without any fear. # Follows a real clean implementation of above code, checkout the number of lines reduced. # Lets first modify the ruby Object class system itself. class Object def nob if respond_to?(:empty?) return nil if empty? if respond_to?(:strip) return (strip.empty?) ? nil : (self.strip) end self else self end end end # Now above ruby_hack lets you write code like this: foo_data = param[:from_data].nob || “Some other default value” # it will detect if object is a string, then before checking whether string is empty or not, it will strip the white spaces # from the string. #nob method would return nil if your object was ‘blank’, otherwise it will return the object itself # by blank, i mean, if its a string, it shouldn’t be nil or ” ” or “n”, # by blank, i mean, not a empty array like: [] # method is polymorphic in nature and operates on any ruby data type. and thats why, i put it in Object class itself. # But above method is slightly costlier, that your hand cranked if, elses, because it uses ruby specific facility respond_to? for # giving polymorphic behaviour and so what will you choose?