How to call a model method immediately after my application loads in Ruby on Rails
How do I call a models method just after my application loads. This sets up some of the business rules in my applicat开发者_如何学编程ion and I want to run this method every time my server is restarted or changes have been made to my production.
What would be the best way to do this
Use the after_initialize callback.
Unlike before/after filters, it's executed only once after the bootstrap. Here's a short tutorial.
You can put in a before_filter
into the ApplicationController.
before_filter :load_business_rules
That will call the load_business_rules
method each time.
I think you would want to do this in your environment file instead of as a before_filter. The reason being a before_filter will create a performance hit as the method is ran before every action on your site. What you could do instead is simply call it with an initializer or if you need to store those business rules as a static object you could declare it as a constant in your environment:
Rails::Initializer.run do |config|
...
end
BUSINESS_RULES = load_business_rules
It really depends on what that method does. If you're just storing a bunch of constants in a static object you could just create a simple class and drop it in your models directory.
For example on an e-commerce site I recently built I created a Store model:
class Store
# Constants
MAX_QUANTITY = 10
SALES_TAX_RATE = 0.081
SALES_TAX_STATES = ["AZ","Arizona"]
SHIPPING_METHODS = {"Standard" => "standard", "2nd Day (add $18)" => "2nd day"}
SHIPPING_COSTS = {"standard" => 0, "2nd day" => 18}
SHIPPING_MINIMUM = 6
SHIPPING_RATES = [[25,6],[50,8],[70,9],[100,11],[150,13],[200,15],[200,18]]
...
end
Then in my controllers, views, or models I could reference these constants easily just by:
Store::MAX_QUANTITY
I hope that helps!
精彩评论