Search code examples
rubysinatrapadrino

Most appropriate place to require library in Padrino/Sinatra


I'm using "therubyracer" in a model, and I'm requiring at the top of the model as so:

require 'v8'
class Thing
  def self.ctx; @@ctx ||= V8::Context.new; end;

  def self.eval(script); ctx.eval(script); end;
end

However, I intermittently get:

NameError - uninitialized constant Thing::V8: 
/app/thing.rb:3:in `ctx'

When testing requests through a local Padrino server, apparently after I modify code in Thing. This is corrected by restarting the padrino server. I'm assuming requiring v8 somewhere else would fix this problem, wheres the correct place?


Solution

  • This looks like it might be caused by the Padrino reloader getting confused when it reloads your thing.rb file, causing Ruby to look for V8 in the Thing namespace.

    Try explicitly specifying V8 is in the top level using the :: prefix:

    def self.ctx; @@ctx ||= ::V8::Context.new; end;