public
Description: default values for ActiveRecord fields
Homepage:
Clone URL: git://github.com/scharfie/has_default.git
scharfie (author)
Wed May 20 11:34:33 -0700 2009
commit  8e7dce4e7cd35033ab3bb3056afec20c20669736
tree    61d2ca9ae0c9b56e3082fa4a9044c820ce28bd8f
parent  49a16b2a252531dfeea5cc04e869ca84febd5926
name age message
file README.textile Loading commit data...
file init.rb
directory lib/
README.textile

A snippet says a thousand words:


  class Post < ActiveRecord::Base
    has_default :permalink do |record|
      record[:permalink] = nil if record[:permalink].blank?
      record[:permalink] ||= (record[:name] || '').downcase.gsub(/^[a-z0-9]+/, '-')
    end
  end

A before_validation callback is added which will look at all has_default calls,
and invoke the block for each (passing self to the block). In addition, an
attribute reader for the attribute is added which calls the same block.

The above example would be something like this if written directly:


  class Post < ActiveRecord::Base
    def permalink_proc
      Proc.new { |record| 
        record[:permalink] = nil if record[:permalink].blank?
        record[:permalink] ||= (record[:name] || '').downcase.gsub(/^[a-z0-9]+/, '-')
      }
    end  
  
    def before_validation
      permalink_proc.call(self)
    end
    
    def permalink
      permalink_proc.call(self)
    end
  end