簡體   English   中英

在模塊化模式下使用 Sinatra

[英]Using Sinatra in modular mode

我有以下 server.rb 文件:

require 'sinatra/base'

Dir.glob('./controllers/*').each { |r| require r }
Dir.glob('./models/*').each { |r| require r }

class SinatraServer < Sinatra::Base
  set :port, 3000
  set :app_file, __FILE__

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

  before do
    @currency = '&pound;'
  end

  get '/' do
    redirect '/dashboard'
    erb :'layouts/index'
  end

  get '/dashboard' do
    erb :'layouts/dashboard'
  end

  not_found do
    erb :'/404'
  end

  use InvoicesController
  run!
end

和以下 invoices_controller.rb 文件:

require 'sinatra/base'

class InvoicesController < Sinatra::Base
  get '/invoices/all' do
    @title = 'All Invoices'
    @invoices = InvoicesModel.new.all
    erb :'layouts/invoices'
  end

  get '/invoices/submitted' do
    @title = 'Submitted Invoices'
    @invoices = InvoicesModel.new.submitted
    erb :'layouts/invoices'
  end

  get '/invoices/pending' do
    @title = 'Pending Invoices'
    @invoices = InvoicesModel.new.pending
    erb :'layouts/invoices'
  end

  get '/invoices/paid' do
    @title = 'Paid Invoices'
    @invoices = InvoicesModel.new.paid
    erb :'layouts/invoices'
  end
end

但是當我嘗試運行服務器時,出現以下錯誤:

沒有這樣的文件或目錄@ rb_sysopen - /Users/julian/Documents/Projects/Websites/Ruby/Invoice/controllers/views/layouts/invoices.erb

如何確保 Sinatra 使用“app/views”中的“layouts”目錄?

對於那些正在尋找答案的人...根據 Holger Just 的建議,我最終在 invoices_controller.rb 文件的頂部添加了一個“set:views”指令。 這使應用程序能夠將 controller 作為一個模塊。 請注意,您需要在“運行”之前添加“使用 InvoicesController”。 執行腳本末尾的指令。

這是代碼:

服務器.rb

require 'sinatra/base'

Dir.glob('./controllers/*').each { |r| require r }
Dir.glob('./models/*').each { |r| require r }

class SinatraServer < Sinatra::Base
  set :port, 3000

  before do
    @currency = '&pound;'
  end

  get '/' do
    redirect '/dashboard'
    erb :'layouts/index'
  end

  get '/dashboard' do
    erb :'layouts/dashboard'
  end

  not_found do
    erb :'/404'
  end

  use InvoicesController
  run!
end

控制器/invoices_controller.rb

require 'sinatra/base'

class InvoicesController < Sinatra::Base
  set :views, File.expand_path('app/views')

  get '/invoices/all' do
    @title = 'All Invoices'
    @invoices = InvoicesModel.new.all
    erb :'layouts/invoices'
  end

  get '/invoices/submitted' do
    @title = 'Submitted Invoices'
    @invoices = InvoicesModel.new.submitted
    erb :'layouts/invoices'
  end

  get '/invoices/pending' do
    @title = 'Pending Invoices'
    @invoices = InvoicesModel.new.pending
    erb :'layouts/invoices'
  end

  get '/invoices/paid' do
    @title = 'Paid Invoices'
    @invoices = InvoicesModel.new.paid
    erb :'layouts/invoices'
  end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM