Search code examples
rubyperformancespork

Preloading classes without Rails?


I am working on a big project, and I realized that several of the components were groups of classes that I could turn into services and strip from Rails. But now that I've done that I realize that the slowness of loading classes without Spork isn't a function of Rails being slow, but a function of Ruby being slow. Is there something like Spork that will work in non Rails projects?


Solution

  • Spork should work just fine for any ruby project, it just requires a bit more setup.

    Assuming you're using rspec 2.x and spork 0.9, make a spec_helper.rb that looks something like:

    require 'spork'
    
    # the rspec require seems to be necessary, 
    # without it you get "Missing or uninitialized constant: Object::RSpec" errors
    require 'rspec' 
    
    Spork.prefork do
    
      # do expensive one-time setup here
      require 'mylibrary'
      MyLibrary.setup_lots_of_stuff
    
    end
    
    Spork.each_run do
    
      # do setup that must be done on each test run here (setting up external state, etc):
      MyLibrary.reset_db
    
    end
    

    Everything in the Spork.prefork block will only be run once (at spork startup), the rest will run on every test invocation.

    If you have lots of framework-specific setup, you'd probably be better off making an AppFramework for your library. See the padrino AppFramework for an example.