My application is a form builder: forms are defined, and activated ones are then presented in the usual CRUD manner. The process of activating a form triggers the FormManager
to create a subclass of the main Form object (I use STI in ActiveRecord
to create a subclass of type
, using Object.const_set()
). Active forms can be deactivated, which involves killing that subclass definition (using Object.const_send(:remove...)
)
I require only 1 FormManager
object for my application. What is the best way to go abo开发者_运维知识库ut this? I am currently using a class variable in ApplicationController
to achieve this... it works, but seems a bit clunky:
require 'lib/form_manager.rb'
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
attr_reader :registry
protect_from_forgery
@@registry = FormManager.new
end
I'm running ruby 1.8.7, rails 2.3.11 in development mode - am I seeing this just because I'm in development mode?
No, it just works that way. Rails has request-response model, and for every request it creates new instance of some controller (which probably inherits from your ApplicationController), sets some request params and then fires your action method. If you want to share state between requests, you need to put it outside of controller, for example as constant (it's just Ruby) initialized while your application is started by server.
If you need single instance of registry, just put it in "config/initializers/registry.rb":
require 'lib/form_manager.rb'
REGISTRY = FormManager.new
Template.all(:conditions => { :is_active => false }).each do |t|
REGISTRY.loadForm(t.id)
end
and then in ApplicationController:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery
def registry
REGISTRY
end
end
You might want to make your FormManager a singleton:
http://dalibornasevic.com/posts/9-ruby-singleton-pattern-again
Yes, a new ApplicationController object will be created for every request (you can check this by adding a before_filter that runs "puts self.id" to check the object id for your controller object. You'll notice it's different for every request).
Why would you want a single object across requests? what are you trying to achieve?
精彩评论