Created
September 29, 2011 20:06
-
-
Save nakajima/1251781 to your computer and use it in GitHub Desktop.
activerecord after_set callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rubygems" | |
require "acts_as_fu" | |
require "test/unit" | |
include ActsAsFu | |
class ActiveRecord::Base | |
def self.after_set(attribute, callback) | |
after_save callback, :if => "#{attribute}_set?" | |
class_eval <<-END | |
def #{attribute}_set? | |
@#{attribute}_set | |
end | |
def #{attribute}=(val) | |
@#{attribute}_set = #{attribute}.blank? && val.present? | |
super(val) | |
end | |
END | |
end | |
end | |
class AfterSetTest < Test::Unit::TestCase | |
def setup | |
$CALLS = 0 | |
build_model :users do | |
string :name | |
string :status, :default => "OK" | |
after_set :name, :some_callback | |
validates_presence_of :status | |
def some_callback | |
$CALLS += 1 | |
end | |
end | |
end | |
def test_it_triggers_callback_when_set | |
user = User.new | |
user.save! | |
assert_equal 0, $CALLS | |
user.name = "Pat" | |
assert_equal 0, $CALLS # Does not get set until record saved | |
user.save! | |
assert_equal 1, $CALLS | |
end | |
def test_does_not_trigger_when_already_set | |
user = User.new(:name => "Pat") | |
user.save! | |
$CALLS = 0 # Reset this to make sure we don't call it again | |
user.name = "Neil" | |
user.save! | |
assert_equal 0, $CALLS | |
end | |
def test_does_not_trigger_when_set_to_nil | |
user = User.new | |
user.save! | |
user.name = nil | |
user.save! | |
assert_equal 0, $CALLS | |
end | |
def test_does_not_trigger_when_record_invalid | |
user = User.new(:status => nil) | |
user.name = "Pat" | |
assert ! user.valid? | |
assert ! user.save | |
assert_equal 0, $CALLS | |
end | |
def test_works_with_two_callbacks | |
User.class_eval do | |
after_set :name, :another_callback | |
def another_callback | |
$CALLS += 1 | |
end | |
end | |
user = User.create | |
assert_equal 0, $CALLS | |
user.name = "Pat" | |
assert_equal 0, $CALLS # Does not get set until record saved | |
user.save! | |
assert_equal 2, $CALLS | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment