开发者

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

开发者 https://www.devze.com 2023-03-04 16:52 出处:网络
If I have a config.ru file like this: def my_method 1+2 end require \'my_sinatra_app\' run 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开发者_StackOverflow is my_method not accessible from within my_sinatra_app.rb?


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,{},[""]]}


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
0

精彩评论

暂无评论...
验证码 换一张
取 消