2011-07-07 40 views
1

相同的應用程序,不同的問題。我正在使用Dan Benjamin「Meet Sinatra」截屏視頻作爲參考。我試圖包含一個自定義身份驗證模塊,它位於一個lib文件夾(lib/authentication.rb)中。我在我的代碼頂部需要該行,但是當我嘗試加載頁面時,它宣稱沒有要加載的文件。試圖包含自定義模塊時加載錯誤

有什麼想法?

這是我的主要西納特拉文件的頂部:

require 'sinatra' 
require 'rubygems' 
require 'datamapper' 
require 'dm-core' 
require 'lib/authorization' 

DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/entries.db") 

class Entry 
include DataMapper::Resource 

property :id,   Serial 
property :first_name, String 
property :last_name, String 
property :email,  String 
property :created_at, DateTime  

end 

# create, upgrade, or migrate tables automatically 
DataMapper.auto_upgrade! 

helpers do 
include Sinatra::Authorization 
end 

和實際的模塊:

module Sinatra 
    module Authorization 

    def auth 
    @auth ||= Rack::Auth::Basic::Request.new(request.env) 
    end 

    def unauthorized!(realm="Short URL Generator") 
    headers 'WWW-Authenticate' => %(Basic realm="#{realm}") 
    throw :halt, [ 401, 'Authorization Required' ] 
    end 

    def bad_request! 
    throw :halt, [ 400, 'Bad Request' ] 
    end 

    def authorized? 
    request.env['REMOTE_USER'] 
    end 

    def authorize(username, password) 
    if (username=='topfunky' && password=='peepcode') then 
     true 
    else 
    false 
    end 
end 

def require_admin 
    return if authorized? 
    unauthorized! unless auth.provided? 
    bad_request! unless auth.basic? 
    unauthorized! unless authorize(*auth.credentials) 
    request.env['REMOTE_USER'] = auth.username 
end 

    def admin? 
    authorized? 
    end 

    end 
end 

然後,在任何我想要保護的處理程序,我把「require_admin。」

+0

你可以發佈你正在使用的確切代碼來嘗試和加載該文件嗎? –

+0

在文本的末尾和代碼的開頭之間添加了一個空白行,以便將所有代碼格式化爲代碼。 – 7stud

回答

9

假設您使用的是Ruby 1.9,則默認$LOAD_PATH不再包含當前目錄。因此,像require 'sinatra'這樣的語句工作得很好(因爲那些寶石在$LOAD_PATH),Ruby不知道你的lib/authorization文件相對於你的主Sinatra文件。

您可以添加西納特拉文件的目錄負載路徑,然後你require語句應該很好地工作:

$LOAD_PATH.unshift(File.dirname(__FILE__)) 
require 'sinatra' 
require 'rubygems' # Not actually needed on Ruby 1.9 
require 'datamapper' 
require 'dm-core' 
require 'lib/authorization' 
+0

這樣做。我想我所遵循的教程是在Ruby 1.8中完成的。非常感謝你! – YuKagi

7

Personnaly,我用的是「相對」的路徑,因爲我使用Ruby 1.9.2工作:

require 'sinatra' 
require 'rubygems' # Not actually needed on Ruby 1.9 
require 'datamapper' 
require 'dm-core' 
require './lib/authorization' 

但我從來沒有檢查如果我的代碼應該再次在Ruby 1.8.6上工作會發生什麼。

+2

在我看來,這個應該是被接受的答案。到目前爲止,我一直在使用hack來取消加載路徑,但它對我來說總是如此醜陋,這是我一直在尋找的解決方案:) –

+0

我喜歡這個選項,因爲它會減少代碼。 **但這兩個選項都有效!** –