Skip to content

Instantly share code, notes, and snippets.

@azisaka
Created December 10, 2008 16:05
Show Gist options
  • Save azisaka/34356 to your computer and use it in GitHub Desktop.
Save azisaka/34356 to your computer and use it in GitHub Desktop.
class Contact < ActiveRecord::Base
validates_presence_of :start_at, :message=>"<strong>Data de Ida</strong> deve ser preenchida corretamente."
validates_presence_of :finish_at, :message=>"<strong>Data de Volta</strong> deve ser preenchida corretamente."
validate :check_dates
def start_at=(start_at)
super(format_date(start_at))
end
def finish_at=(finish_at)
super(format_date(finish_at))
end
def start_at
super.strftime("%d/%m/%Y")
rescue
nil
end
def finish_at
super.strftime("%d/%m/%Y")
rescue
nil
end
protected
def format_date(date)
if date.class.eql? String
if date =~ /^[0-9]+\/[0-9]+\/[0-9]{4}$/
time = date.split('/')
[time[1],time[0],time[2]].join('/')
else
nil
end
else
date
end
end
def check_dates
if !finish_at.nil? and !start_at.nil? and finish_at < start_at
@errors.add(:start_at, "<strong>Data de Volta</strong> não pode ser anterior à <strong>Data de Ida</strong>.")
end
end
end
require File.dirname(__FILE__) + '/../test_helper'
class ContactTest < Test::Unit::TestCase
def test_getting_start_at
c = Contact.new
c.start_at = "10/02/2008"
assert_equal(c.start_at, "10/02/2008")
end
def test_getting_finish_at
c = Contact.new
c.finish_at = "10/02/2008"
assert_equal(c.finish_at, "10/02/2008")
end
def test_validating_dates
c = Contact.new
c.start_at = "10/02/2008"
c.finish_at = "09/02/2008"
assert(!c.valid?)
assert_equal("<strong>Data de Volta</strong> não pode ser anterior à <strong>Data de Ida</strong>.", c.errors.on(:start_at))
end
def test_validating_format_of_dates
c = Contact.new
c.start_at = "a/02/2008"
assert_equal(nil, c.start_at)
c.finish_at = "a/02/2008"
assert_equal(nil, c.finish_at)
assert(!c.valid?)
assert_equal("<strong>Data de Ida</strong> deve ser preenchida corretamente.", c.errors.on(:start_at))
assert_equal("<strong>Data de Volta</strong> deve ser preenchida corretamente.", c.errors.on(:finish_at))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment