尝试包含自定义模块时加载错误

时间:2011-07-07 02:13:52

标签: ruby sinatra basic-authentication

相同的应用程序,不同的问题。我正在使用Dan Benjamin“Meet Sinatra”截屏视频作为参考。我正在尝试包含一个自定义身份验证模块,它位于lib文件夹(lib / authentication.rb)中。我要求代码顶部的那行,但是当我尝试加载页面时,它声称没有这样的文件要加载。

有什么想法?

这是我的主要Sinatra文件的顶部:

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。”

2 个答案:

答案 0 :(得分:9)

假设您使用的是Ruby 1.9,默认的$LOAD_PATH不再包含当前目录。因此,虽然像require 'sinatra'这样的语句工作得很好(因为这些gems在$LOAD_PATH中),但Ruby并不知道你的lib/authorization文件是相对于主Sinatra文件的。

您可以将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'

答案 1 :(得分: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会发生什么。

相关问题