Here is how to do what you want. To warn other readers: doing this is just asking for trouble. It is very fragile and and I can't think of why you would knowingly add something so fragile to your code, especially when a strong alternative is readily available. If you don't care about this warning, read on.
To implement this in Rails 3, you simply create a new module to store your common validator, and then use the include call back to use the validator on any class that includes the module.
First, create a module directory if you haven't already. I prefer lib/modules
. Next, add the modules directory to your load path by editing config/application.rb
# config/application.rb
require File.expand_path('../boot', __FILE__)
# Pick the frameworks you want:
# ...
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module AppName
class Application < Rails::Application
config.autoload_paths += %W(#{config.root}/lib) # <- Add this line
# ...
end
end
Next, create the module. For this example, I will name it the file common_validator.rb
. Remember to place it in lib/modules
.
# lib/modules/common_validator.rb
module CommonValidator
def CommonValidator.included(mod)
mod.validates :name, :what, :ever, :params
end
end
Finally, you just include this module in your models. Like so:
class Place < ActiveRecord::Base
attr_accessible :address, :name, :latitude, :longitude
include CommonValidator # <- Add this
etc...
end
There you have it. Just make sure to restart your Rails server in order to pick up the load path changes. You also have to restart the server whenever you make a change to the module. (Edit: Read this question to see how to reload the module on every request). Rails 4 has a nicer syntax for doing this type of thing in ActiveSupport::Concern
. If you understand the example above, porting it into a concern is trivial.