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

YuK*_*agi 1 ruby basic-authentication sinatra

相同的应用程序,不同的问 我正在使用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
Run Code Online (Sandbox Code Playgroud)

而实际的模块:

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
Run Code Online (Sandbox Code Playgroud)

然后,在我想要保护的任何处理程序上,我输入"require_admin".

Dyl*_*kow 9

假设您使用的是Ruby 1.9,默认情况下$LOAD_PATH不再包含当前目录.因此,尽管语句require 'sinatra'工作得很好(因为这些宝石都在$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'
Run Code Online (Sandbox Code Playgroud)


小智 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'
Run Code Online (Sandbox Code Playgroud)

但我永远不会检查如果我的代码再次适用于Ruby 1.8.6会发生什么.

  • 在我看来,这个应该是公认的答案.到目前为止,我一直在使用hack来取消加载路径,但它对我来说总是那么难看,这就是我一直在寻找的解决方案:) (2认同)