Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create an app-wide object

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 about 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?

like image 718
smcphill Avatar asked Dec 12 '22 11:12

smcphill


2 Answers

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
like image 113
MBO Avatar answered Dec 26 '22 22:12

MBO


You might want to make your FormManager a singleton:

http://dalibornasevic.com/posts/9-ruby-singleton-pattern-again

like image 24
Pavling Avatar answered Dec 26 '22 22:12

Pavling