Sunday, August 26, 2007

model callbacks of Rails ActiveRecord


class Encrypter
def before_save(model)
model.name.tr! 'a-z', 'b-za'
end

def after_save(model)
model.name.tr! 'b-za', 'a-z'
end

# alias_method :after_find, :after_save
# alias_method
# Makes new_id a new copy of the method old_id. This can be used to retain access to
# methods that are overridden.

alias after_find after_save
# Aliasing
# alias new_name old_name
# creates a new name that refers to an existing method, operator, global variable, or reg-
# ular expression backreference ($&, $`, $', and $+). Local variables, instance variables,
# class variables, and constants may not be aliased. The parameters to alias may be
# names or symbols.

end

class ActiveRecord::Base
def self.encrypted
encrypt = Encrypter.new
before_save encrypt
after_save encrypt
after_find encrypt
module_eval <<-"end_eval"
def after_find
# Unlike all the other callbacks, after_find and after_initialize will only be run
# if an explicit implementation is defined (def after_find).
end
end_eval
end
end

class User < ActiveRecord::Base
encrypted
protected
def validate_on_create()
puts 'existed user name' if self.class.exists? :name => name
end
end

No comments :