Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here's a little module to do it:</p> <pre><code>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 </code></pre> <p>Just mix it in:</p> <pre><code>class Foo extend NilToBlankAttrAccessor nil_to_blank_attr_accessor :bar end </code></pre> <p>And use it:</p> <pre><code>foo = Foo.new foo.bar = nil p foo.bar # =&gt; "" foo.bar = 'abc' p foo.bar # =&gt; "abc" </code></pre> <p><strong>How it works</strong></p> <p><code>NilToBlankAttrAccessor#nil_to_blank_attr_accessor</code> first defines the attr_reader normally:</p> <pre><code> attr_reader attr </code></pre> <p>Then it defines the writer by defining a method with the same name as the accessor, only with an "=" at the end. So, for attribute <code>:bar</code>, the method is named <code>bar=</code></p> <pre><code> define_method "#{attr}=" do |value| ... end </code></pre> <p>Now it needs to set the variable. First it turns nil into an empty string:</p> <pre><code> value = '' if value.nil? </code></pre> <p>Then use instance_variable_set, which does an instance variable assignment where the instance variable isn't known until runtime.</p> <pre><code> instance_variable_set "@#{attr}", value </code></pre> <p>Class Foo needs nil_to_blank_attr_accessor to be a class method, not an instance method, so it uses <code>extend</code> instead of <code>include</code>:</p> <pre><code>class Foo extend NilToBlankAttrAccessor ... end </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload