2013-06-27 4 views
2

다른 파일에 모듈이 필요한 Sinatra 앱이 있습니다. 해당 모듈에서 Sinatra 명령을 사용할 때 NoMethodError이 표시됩니다 (예 : redirect "http://facebook.com"). 문제를 설명하기 위해, 나는 단순화 된 버전 만든 :Sinatra 명령이 모듈에서 작동하지 않습니다.

--- mainapp.rb ---

#config 
require './redirector.rb' 

get '/' do 
    Redirector::redirect_to_stackoverflow 
end 

을 --- redirector.rb ---

module Redirector 
    require 'sinatra' 

    def self.redirect_to_stackoverflow 
    redirect "http://stackoverflow.com" 
    end 
end 

- - config.ru ---

require 'rubygems' 
require 'sinatra' 
require File.dirname(__FILE__) + "/ptt.rb" 

run Sinatra::Application 

무엇이 잘못 되었습니까? 내가 뭔가를 제대로 요구하지 않은 곳이 있습니까?

답변

2

Redirector 모듈 내의 redirect에 대한 호출은 Redirector 모듈 개체로 보내지는데,이 메서드는 존재하지 않습니다. require 'sinatra' 안에 module Redirector이 필요하지 않으며 어떤 종류의 방법 구성도 수행하지 않습니다.

아마도 은 Sinatra 메서드를 리디렉터 모듈에 포함시킬 수 있지만 이는 일반적인 방법이 아닙니다. 일반적으로 다른 방법입니다 - Sinatra 응용 프로그램에 다양한 방법으로 구성된 "도우미"모듈을 작성합니다.

app.rb

require 'sinatra' 
require_relative 'redirect.rb' 

class MyApp < Sinatra::Application 
    include Redirector 
    get '/' do 
     redirect_to_stackoverflow 
    end 
end 

redirect.rb

module Redirector 
    def redirect_to_stackoverflow 
    redirect "http://stackoverflow.com" 
    end 
end 

구성 :

이 조성물에 대한보다 일반적인 접근 방법과 유사한 응용 예이다. 루

require File.dirname(__FILE__) + "/app.rb" 
run MyApp 
2

@ Neeil 슬레이터의 설명은 정확하지만, Sinatra extension으로도 설정하는 것이 좋습니다.

require 'sinatra/base' 

module Sinatra 
    module Redirector 
    def redirect_to_stackoverflow 
     redirect "http://stackoverflow.com" 
    end 
    end 
    helpers Redirector 
end 

그런 다음 (기존 앱의 경우) require해야합니다.

require 'sinatra/redirector' 
get "/" do 
    redirect_to_stackoverflow 
end 
관련 문제