views:

222

answers:

1

I have no idea how to "metatize" this method, but I know it should be simple. The method looks like this

  def check_sent=(value)
      Date.parse(value) rescue  @dates_bad = true
      self.write_attribute(:check_sent, value)
  end

This is for an ActiveRecord subclass. I would like to have these methods for all fields that I specify. Is there any way to do this in Ruby?

+3  A: 
class Foo < ActiveRecord::Base
  def self.define_date_setters(*fields)
    fields.each do |field|
      define_method("#{ field }=") do |value|
        Date.parse(value) rescue @dates_bad = true
        self.write_attribute(field, value)
      end
    end
  end

  define_date_setters :check_sent, :other_field, :yet_another_field
end

If you need that functionality for more than one class, you can move define_setters into a module that you extend your classes with.

sepp2k
Wow. I'll be checking this out right now. Thanks for the rapid response.
Yar
Okay, that is awesome and works perfectly. I guess then I could do it automatically for all date fields, but that seems slightly annoying to me.
Yar