Attr_accessor, which converts nil to string when writing

I have a data object that contains dozens of attr_accessor fields for various input data. Can I somehow define a class so that all setters for all fields, for example. set value as empty string instead of nil attempt?

+5
source share
2 answers

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        # => "abc"

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
+9

,

object.foo = given_input

object.foo = given_input.nil? ? "" : given_input

false "",

object.foo = given_input || ""
+1

All Articles