Here is a small module for this:
module NilToBlankAttrAccessor
def nil_to_blank_attr_accessor(attr)
attr_reader attr
define_method "#{attr}=" do |value|
value = '' if value.nil?
instance_variable_set "@#{attr}", value
end
end
end
Just add it to:
class Foo
extend NilToBlankAttrAccessor
nil_to_blank_attr_accessor :bar
end
And use it:
foo = Foo.new
foo.bar = nil
p foo.bar
foo.bar = 'abc'
p foo.bar
How it works
NilToBlankAttrAccessor#nil_to_blank_attr_accessor usually defines attr_reader first:
attr_reader attr
He then defines the author, defining a method with the same name as accessor, only with "=" at the end. So, for an attribute, the :barmethod is calledbar=
define_method "#{attr}=" do |value|
...
end
Now he needs to set a variable. First, it turns into an empty string:
value = '' if value.nil?
instance_variable_set, , .
instance_variable_set "@#{attr}", value
Foo , nil_to_blank_attr_accessor , , extend include:
class Foo
extend NilToBlankAttrAccessor
...
end