2009-07-10 10 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 

ように私のモデルでそれを使用していますが、しかし、私は、次のモジュールを取得していると共有する1つの方法"未定義メソッド` 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

があるであろう他の方法で/ /ユーザ/アンディ/ rails_apps/TEST_APP /ベンダー/レール:このモジュールはので、上記をやっ をself.included使用して滞在したいと思い、今 プライベートメソッドは '」#<0x27416c8クラス>を呼びかけ含まれ、このエラーがスローされますactiverecord/lib/active_record/base.rb:1964年: 'metho d_missing ' /Users/andy/rails_apps/test_app/lib/shared_methods.rb:7:in 'included' –

+0

privateエラーはbase.includeから来ています。最も直接的な方法はsendを使って作業することです: 'base .__ send __(:include、InstanceMethods)' –

+0

あなたは正しいです。 send(:include、Module)またはclass_eval {include Module}のいずれかを使用する必要があります。 –

関連する問題