2017-01-26 1 views
0

클래스는 /lib/email_helper.rb에 정의되어 있습니다. 클래스는 컨트롤러 또는 백그라운드 작업에 의해 직접 사용될 수 있습니다./lib 디렉토리에 정의 된 클래스의 ActionView :: Helpers :: DateHelper에 액세스

time_ago_in_words가 호출
class EmailHelper 
    include ActionView::Helpers::DateHelper 

    def self.send_email(email_name, record) 
     # Figure out which email to send and send it 
     time = time_ago_in_words(Time.current + 7.days) 
     # Do some more stuff 
    end 
end 

, 작업이 다음 오류와 함께 실패합니다 :

undefined method `time_ago_in_words' for EmailHelper 

가 어떻게 내 EmailHelper 클래스의 컨텍스트에서 time_ago_in_words 도우미 메서드에 액세스 할 수 있습니다 그것은 다음과 같이 보입니다? 관련 모듈이 이미 포함되어 있습니다.

helper.time_ago_in_wordsActionView::Helpers::DateHelper.time_ago_in_words도 사용하지 않으려 고 시도했습니다.

답변

0

루비의 include는 클래스 예를ActionView::Helpers::DateHelper을 추가하고있다.

그러나 방법은 클래스 방법 (self.send_email)입니다. 그래서, 당신은 extend으로 include을 대체 할 수 있으며, 다음과 같이 self로 전화 : includeextend의 차이입니다

class EmailHelper 
    extend ActionView::Helpers::DateHelper 

    def self.send_email(email_name, record) 
     # Figure out which email to send and send it 
     time = self.time_ago_in_words(Time.current + 7.days) 

     # Do some more stuff 
    end 
end 

합니다. 이 같은

또는 ...

당신이 ApplicationController.helpers를 호출 할 수 있습니다, 지금 완전한 의미가

class EmailHelper 

    def self.send_email(email_name, record) 
     # Figure out which email to send and send it 
     time = ApplicationController.helpers.time_ago_in_words(Time.current + 7.days) 

     # Do some more stuff 
    end 
end 
+0

. 클래스 메서드 내에서'time_ago_in_words'를 사용하려고 시도했다는 사실을 간과했습니다. 일반적으로 인스턴스 메서드에서 다른 곳에서 사용한 적이 있습니다. 감사! – ACIDSTEALTH