When you have dates on your form you always want to present them in a usable format for your users but this means you must then parse them back into a SQL format before updating your model. I found the very cool gem Chronic that will do the parsing for us. The only thing left to do is make a method to easily use Chronic in our models. For this we will use meta programming. Oh, I use Sequel as my ORM of choice but this could be applied to any ORM and even just plain classes if you’d like.

require "chronic"

class Sequel::Model
  def self.smart_date_attr(*args)
    args.each do |a|
      define_method("#{a}=".to_sym) do |v|

That’s it! Now all we have to do on our models is specify which attributes should be a smart date:

class Person < Sequel::Model(:people)
  smart_date_attr :date_of_birth, :anniversary

Now we can make use of this right away. Here is an IRB session on one of my models:

irb(main):003:0> c.received_date = "today"
=> "today"
irb(main):004:0> c.received_date
=> #
irb(main):005:0> c.received_date = "3 days ago"
=> "3 days ago"
irb(main):006:0> c.received_date
=> #
irb(main):007:0> c.received_date = "5/5/1955"
=> "5/5/1955"
irb(main):008:0> c.received_date
=> #