Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.13 KB  |  hits: 10  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Using method missing in Rails
  2. def bill_date_human
  3.     date = self.bill_date || Date.today
  4.     date.strftime('%b %d, %Y')
  5.   end
  6.   def bill_date_human=(date_string)
  7.     self.bill_date = Date.strptime(date_string, '%b %d, %Y')
  8.   end
  9.        
  10. [:bill_date, :registration_date, :some_other_date].each do |attr|
  11.   define_method("#{attr}_human") do
  12.     (send(attr) || Date.today).strftime('%b %d, %Y')
  13.   end  
  14.  
  15.   define_method("#{attr}_human=") do |date_string|
  16.     self.send "#{attr}=", Date.strptime(date_string, '%b %d, %Y')
  17.   end
  18. end
  19.        
  20. column_names.grep(/_date$/)
  21.        
  22. def method_missing(method_name, *args, &block)
  23.   # delegate to superclass if you're not handling that method_name
  24.   return super unless /^(.*)_date(=?)/ =~ method_name
  25.  
  26.   # after match we have attribute name in $1 captured group and '' or '=' in $2
  27.   if $2.blank?
  28.     (send($1) || Date.today).strftime('%b %d, %Y')
  29.   else
  30.     self.send "#{$1}=", Date.strptime(args[0], '%b %d, %Y')
  31.   end
  32. end
  33.        
  34. class MyModel < ActiveRecord::Base
  35.  
  36.   attribute_method_suffix '_human'
  37.  
  38.   def attribute_human(attr_name)
  39.     date = self.send(attr_name) || Date.today
  40.     date.strftime('%b %d, %Y')
  41.   end
  42. end