Sinatra方法`开发?`undefined

Ema*_*ani 6 ruby sinatra

Sinatra文档说development?当环境开发时会返回true,但是我收到一个错误,指出该方法development?未定义.

我尝试跳过速记并测试ENV['RAKE_ENV']变量本身,但它只是零.

这是我得到的错误:

undefined method `development?' for main:Object (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

这是触发错误的代码:

require 'dm-sqlite-adapter' if development?
Run Code Online (Sandbox Code Playgroud)

我正在使用模块化风格的应用程序.上面的行是一个单独的文件,只管理模型.这是怎么回事?

小智 5

我也在这个问题上挣扎。这是我一路上发现的。

您需要在从 Sinatra::Base 继承的类(例如从 Base 继承的 Sinatra::Application)“内部”才能使用development?base.rb 中定义的 方法。

在经典的 Sinatra 应用程序中,您已经在“内部”编码一个继承自 Sinatra::Base 的类。所以development?只会在“任何地方”工作。

在模块化 Sinatra 中,development?只适用于 Sinatra::Base 子类,例如:

require 'sinatra/base'

# Placing
# require 'dm-sqlite-adapter' if development?
# here will not work.

class ApplicationController < Sinatra::Base
require 'dm-sqlite-adapter' if development? # But here it works
...
end

# Placing 
# require 'dm-sqlite-adapter' if development?` 
# AFTER the above class will still not work

class SomethingElse 
# nor will `development?` work here, since it is called inside
# a class without Sinatra::Base inheritance
...
end
Run Code Online (Sandbox Code Playgroud)

所以基本上你可以使用从 Sinatra::Base 继承的 ApplicationController 类,并在这里检查development?. 继承自 ApplicationController 类的子类也是如此:

class UserController < ApplicationController
  require 'dotenv' if development?
  ...
end
Run Code Online (Sandbox Code Playgroud)

对于模块化 Sinatra,在 (main:Object) 代码文本“outside” Sinatra::Base 子类中,您需要遵循Arup 的说明:

if Sinatra::Base.environment == :development
    require 'awesome_print'
    require 'dotenv'
    Dotenv.load
    ...
end
Run Code Online (Sandbox Code Playgroud)


Luc*_*ila 5

由于您使用的是模块化风格,因此您需要Sinatra::Base在方法之前添加模块命名空间。

因此,您将能够访问Sinatra::Base.development?应用程序中的任何位置。