Steph Thirion
Steph Thirion

Reputation: 9423

Why are top-level methods defined in config.ru not accessible to Sinatra::Application?

If I have a config.ru file like this:

def my_method
  1+2
end

require 'my_sinatra_app'

run Sinatra::Application

Calling my_method from within my_sinatra_app.rb returns "undefined method `my_method' for main:Object".

As a top-level method it should be accessible from everywhere; why is my_method not accessible from within my_sinatra_app.rb?

Upvotes: 1

Views: 292

Answers (2)

Daniel O'Hara
Daniel O'Hara

Reputation: 13438

I think you could define it as a module:

module MyMethodsModule

  def self.my_method
    #Method body
  end

end

And then call its methods:

::MyMethodsModule.my_method

Upvotes: 1

BaroqueBobcat
BaroqueBobcat

Reputation: 10150

config.ru is instance_evaled in a Rack::Builder, so the methods you define there are not in the Top level scope. If you want to have them as top level methods, you could try putting them in another file and requireing them from config.ru.

ex config.ru

p self # => #<Rack::Builder:0x1234123412 @ins=[]>

run lambda {|e|[200,{},[""]]}

Upvotes: 4

Related Questions