Using Rails to build a GUI for an existing CLI Ruby script?
G'day guys,
Currently having a bit of a philsophical conundrum. Myself and a few mates have built a quite awesome ruby CLI script for parsing and managing data. It uses gems, responds to requests and is fully functional and great.
I was wondering if there was any way I could hold a singleton instance of this class and interact with it via a web i开发者_如何学Cnterface built in rails. I've got a decent amount of rails experience but can't for the life of me figure how how to create a singleton instance in a web-app and how to make that universally accessible to all of the classes/controllers.
The reason I need to create a singleton is that I need to load in a bunch of data that this little script chops and changes. It's class-based, but I don't want to port those classes over to using activerecord if I don't have to, as it keeps everything in memory (and it doesn't take up that much memory).
Is there any way I can just import the script, start it up with the requisite commands and then hold that object in memory for the life of the web application, or would I have to port over the classes/methods to AR or controller methods?
Cheers
You can add an initializer that contains a Singleton wrapper for your object:
config/initializers/foo_factory.rb:
require 'foo'
class FooFactory
class << self
def foo
@@foo ||= Foo.new(lots, of, params)
end
end
end
From anywhere else you can now use:
FooFactory.foo.do_something
Note that this is extremely horrible, and you probably should not do it. However, it will do what you want: establish a global singleton that only gets set up on server start.
An even shorter hack of similar horribleness is to just assign your single Foo instance to a constant:
config/initializers/foo_singleton.rb:
require 'foo'
FooSingleton = Foo.new(lots, of, params)
Elsewhere you can then use:
FooSingleton.do_something
Note that this is basically only slightly better than a global variable in that you can't (easily) change the value of FooSingleton.
精彩评论