更改 Sinatra 视图目录位置

Change Sinatra views directory location

我想构建一个更像 Rails 具有以下结构的应用程序的 Sinatra 应用程序:

.
├── app
│  ├── models
│  │   └── a_model.rb
│  └── views
│      └── a_view.erb
└── app.rb

根据documentation,可以通过覆盖:views设置来完成:

:views - view template directory

A string specifying the directory where view templates are located. By default, this is assumed to be a directory named “views” within the application’s root directory (see the :root setting). The best way to specify an alternative directory name within the root of the application is to use a deferred value that references the :root setting:

set :views, Proc.new { File.join(root, "templates") }

我已经设置了 :root:views:

set :root,  File.dirname(__FILE__)
set :views, Proc.new { File.join(root, 'app', 'views') }

# Also tried some variations like:
# set :views,        'app/views/'
# set :views,         Proc.new { File.join(setting.root, 'app', 'views' }
# set :public_folder, Proc.new { File.join(root, 'app', 'views' }
# ...

class MyApp < Sinatra::Base
  get '/' do
    erb :a_view
  end
end

但我总是面临同样的错误信息:

No such file or directory @ rb_sysopen - /path/to/my/app/views/a_view.erb

确实,settings.views 被评估为 /path/to/my/app/views(而不是 /path/to/my/app/app/views

看来我无法控制 :views (settings.views) 变量的值。我知道我可以简单地将 views 文件夹移动到根位置。

谁能解释为什么我无法控制这些设置?

在 class 定义中移动设置,所有设置都从 Sinatra::Base

中继承
class MyApp < Sinatra::Base
  set :root,  File.dirname(__FILE__)
  set :views, Proc.new { File.join(root, 'app', 'views') }

  get '/' do
    erb :a_view
  end
end

或者

class MyApp < Sinatra::Base
  configure do
    set :root,  File.dirname(__FILE__)
    set :views, Proc.new { File.join(root, 'app', 'views') }
  end

  get '/' do
    erb :a_view
  end
end