Created
January 12, 2010 14:36
-
-
Save diasjorge/275243 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# Usage: | |
# | |
# class Comment < ActiveRecord::Base | |
# when_assigning :subject do |value| | |
# value.strip! | |
# super value | |
# end | |
# end | |
# | |
module ActiveRecord::WhenAssigning | |
def when_reading(field, &block) | |
chain_attribute field, &block | |
end | |
def when_writing(field, &block) | |
when_assigning field, &block | |
end | |
def when_assigning(field, &block) | |
assignment_field = field.to_s.ends_with?('=') ? field : :"#{field}=" | |
chain_attribute assignment_field, &block | |
end | |
def chain_attribute(method, &block) | |
mod = Module.new do | |
define_method method, &block | |
end | |
class_eval do | |
include mod | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment