2009-07-10 6 views
1

내가 양식을 제출 때마다 내가루비 - 2 개 모델

module SharedMethods 

    # Class method 
    module ClassMethods 

     # 
     # Remove white space from end of strings 
     def remove_whitespace 
      self.attributes.each do |key,value| 
       if value.kind_of?(String) && !value.blank? 
        write_attribute key, value.strip 
       end 
      end 
     end 


    end 

    # 
    # 
    def self.included(base) 
     base.extend(ClassMethods) 
    end 

end 

내가

include SharedMethods 
before_validation :remove_whitespace 

처럼 내 모델을 사용하고 그러나 나는를 다음과 같은 모듈을 얻을 수있다와 공유 하나의 방법 "정의되지 않은 메소드`remove_whitespace '"메시지

이 오류를 해결하려면 어떻게해야합니까?

답변

2

:remove_whitespace은 클래스 메소드가 아닌 인스턴스 메소드 여야하기 때문입니다.

module SharedMethods 

    def self.included(base) 
    base.send :include, InstanceMethods 
    end 

    module InstanceMethods 

    # Remove white space from end of strings 
    def remove_whitespace 
     self.attributes.each do |key,value| 
     if value.kind_of(String) && !value.blank? 
      write_attribute key, value.strip 
     end 
     end 
    end 

    end 

end 

둘 다 클래스 및 인스턴스 방법을 제공하는 모듈을 필요로하지 않는 한, 당신은 또한 self.included의 사용을 생략하고 이런 방식으로 모듈을 간소화 할 수 있습니다 :

module SharedMethods 

    # Remove white space from end of strings 
    def remove_whitespace 
    self.attributes.each do |key,value| 
     if value.kind_of(String) && !value.blank? 
     write_attribute key, value.strip 
     end 
    end 
    end 

end 
+0

이있을 것입니다 다른 방법에 이 모듈은 그래서 위의 지금이 오류 개인 방법을 던졌습니다 일 self.included 사용하여 머무르고 싶은 것 ''# 촉구 포함 <클래스 : 0x27416c8> /사용자/앤디/rails_apps/test_app/공급 업체/레일/activerecord/lib/active_record/base.rb : 1964 년 :'metho에서 d_missing ' /Users/andy/rails_apps/test_app/lib/shared_methods.rb:7:in' included' –

+0

개인 오류가 base.include에서 발생했습니다. 가장 직접적인 방법은 send를 통해 작업하는 것입니다.'base .__ send __ (: include, InstanceMethods)' –

+0

맞습니다. send (: include, Module) 또는 class_eval {include Module}을 사용해야합니다. –