Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As you already know signature of desired methods it might be better to define them instead of using <code>method_missing</code>. You can do it like that (inside you class definition):</p> <pre><code>[:bill_date, :registration_date, :some_other_date].each do |attr| define_method("#{attr}_human") do (send(attr) || Date.today).strftime('%b %d, %Y') end define_method("#{attr}_human=") do |date_string| self.send "#{attr}=", Date.strptime(date_string, '%b %d, %Y') end end </code></pre> <p>If listing all date attributes is not a problem this approach is better as you are dealing with regular methods instead of some magic inside <code>method_missing</code>. </p> <p>If you want to apply that to all attributes that have names ending with <code>_date</code> you can retrieve them like that (inside your class definition):</p> <pre><code>column_names.grep(/_date$/) </code></pre> <p>And here's <code>method_missing</code> solution (not tested, though the previous one is not tested either):</p> <pre><code>def method_missing(method_name, *args, &amp;block) # delegate to superclass if you're not handling that method_name return super unless /^(.*)_date(=?)/ =~ method_name # after match we have attribute name in $1 captured group and '' or '=' in $2 if $2.blank? (send($1) || Date.today).strftime('%b %d, %Y') else self.send "#{$1}=", Date.strptime(args[0], '%b %d, %Y') end end </code></pre> <p>In addition it's nice to override <code>respond_to?</code> method and return <code>true</code> for method names, that you handle inside <code>method_missing</code> (in 1.9 you should override <code>respond_to_missing?</code> instead).</p>
    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