2013-08-25 4 views
0

나는 이것으로부터 alredy 3 회색 머리카락을 가지고 있습니다. Rails4.0/ruby ​​1.9.3. /lib/moduletest/test 디렉토리에 test.rb 파일이 있습니다. test.rb는 다음과 같습니다.컨트롤러에서 생성 된 모듈을 사용하는 방법

module Moduletest 
    class test 
    end 
end 

컨트롤러에서이 클래스를 인스턴스화하려면 어떻게합니까? require 명령은 어떻게 사용해야합니까? Moduletest :: test.new()?

+0

로드 레일의 연장 후크하는 것입니다. – Mindbreaker

+0

컨트롤러에'moduletest/test'가 필요합니다. 자동로드는'config.autoload_paths + = Dir [ "# {config.root}/lib", "# {config.root}/lib/** /"]' – Ladiko

답변

1

내가 대신 "테스트"의 "는 foobar"를 사용하는 것이 좋습니다 수 있습니다. "시험"은 시험처럼 보입니다.

질문으로 돌아 가면, 코멘트 당 모듈을 올바르게로드 했으므로 제어기에서이를 사용하는 두 가지 방법이 있습니다.

첫 번째는 명시 적으로 포함하는 것입니다. 선호

class ApplicationController < ActionController::Base 
    include ModuleFoo 

    def index 
    bar # Use ModuleFoo's method directly 
    #... 
    end 
end 

두 번째는 당신은 자동로드 경로로이를 넣어야 할

# ModuleFoo 
module ModuleFoo 
    def bar 
    end 
end 

if defined? ActionController::Base 
    ActionController::Base.class_eval do 
    include ModuleFoo 
    end 
end 

# Controller 
class SomethingController < ApplicationController 
    def some_method 
    bar # use this directly 
    end 
end 
0

자동 채우기 경로에 lib 디렉토리를 넣어야합니다.

config/application.rb을 추가하십시오 : 그래서 레일은 시작시 파일을로드 처음에는

config.autoload_paths += %W(#{config.root}/lib)

+0

나는'config.root/lib/**/"]'config.autoload_paths + = Dir ["# {config.root}/lib "를 가지고있다. 그래서 문제는 클래스를 만드는 방법입니다. – Ladiko

+0

'Moduletest :: test.new'를 사용해보십시오. – Mindbreaker

관련 문제