在Sinatra中配置erb目录

时间:2012-12-04 05:08:45

标签: ruby sinatra erb

应用程序/控制器/ app.rb

require 'sinatra'
get '/' do
  erb :index
end

应用程序/视图/ index.erb

<html>
    <body>
        <p>Hello World</p>
    </body>
</html>

错误:

Errno::ENOENT at /
No such file or directory - .../app/controllers/views/index.erb

如何配置erb以查看app/views而不是app/controllers/views

2 个答案:

答案 0 :(得分:10)

您可以通过调整配置设置来实现此目的。由于您使用的是非标准设置,因此您需要告诉Sinatra应用程序的实际根目录以及查找视图的位置。在app/controllers/app.rb文件的顶部添加:

# sets root as the parent-directory of the current file
set :root, File.join(File.dirname(__FILE__), '..')
# sets the view directory correctly
set :views, Proc.new { File.join(root, "views") } 

您可以在configuration options中了解有关Sinatra Sinatra Documentation的更多信息。

答案 1 :(得分:3)

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

来自http://www.sinatrarb.com/configuration.html#__view_template_directory

编辑:很明显,什么也没做,呵呵。最好在app/中有一个需要你的控制器的文件:

Dir.glob("controllers/*.rb").each { |r| require_relative r }

然后,app/views将成为默认的视图目录。