2017-08-24 39 views
0

當試圖用sinatra運行這個應用程序時,它會拋出一個錯誤,稱它找不到json文件。當我測試Sinatra以外的方法時,它們工作正常。 文件database.json位於與app.rb相同的文件夾中。當我不執行「閱讀」方法時,sinatra運作良好。Sinatra Errno :: ENOENT - 找不到文件

這是app.rb

require 'sinatra' 
require 'json' 

class Articles 
attr_reader :read 

def read 
    JSON.parse(File.read('database.json')) 
end 

def create 
    "Here I am!" 
end 

def update(title, content) 
    added_art = {"title": title, "content": content} 
    json = File.read('database.json') 
    secondJsonArray = JSON.parse(json) 
    secondJsonArray << added_ar 
    File.open("database.json","w") do |f| 
    f.puts JSON.pretty_generate(secondJsonArray) 
    end 

end 

end 


get '/' do 
    @all = Articles.new.read 
erb :index 
end 

post '/' do 
    @title = params[:title] 
    @content = params[:content] 
    Articles.new.update(@title, @content) 
    redirect 'http://localhost:4567/' 
end 

該錯誤消息我得到的是以下幾點:

No such file or directory @ rb_sysopen - database.json 
JSON.parse(File.read('database.json')) 

然而,當我執行從崇高文本個別app.rb文件,它的工作我可以得到的網址就好了。

額外

+0

您是否知道,你可以只用'重定向「/ ''也適用於不同的主機和端口 –

回答

0

,因爲你在不同的上下文啓動您可能正在使用錯誤的路徑嘗試使用這樣的路徑:

def read 
    path = File.expand_path(File.dirname(__FILE__) + "/database.json") 
    JSON.parse(File.read(path)) 
end  
相關問題