2017-08-01 13 views
0

Ruby on RailsでSolidusを使用してWebショップを作成していて、そのWebショップ用に複数のモジュールがあります。Ruby - コントローラが定義されているか確認する

だから、私はfollowinコードで「solidus_jwt_auth」と呼ばれるモジュールに私のコントローラを定義した:ので、私はこれのためにデコレータを作成し、私は「solidus_prescriptions」と呼ばれる別のモジュールでこれを延長したい

module Spree 
    module Api 
    class MeController < Spree::Api::BaseController 
     def index 
     ... 
     end 

     def orders 
     ... 
     end 

     def addresses 
     ... 
     end 
    end 
    end 
end 

次のコードme_decorator

if defined? Spree::Api::MeController.class 
    Spree::Api::MeController.class_eval do 
    def prescriptions 
     ... 
    end 

    def create_prescription 
     ... 
    end 

    private 

    def prescription_params 
     params.require(:prescription).permit(
      *Spree::CustomerPrescription.permitted_attributes 
    ) 
    end 
    end 
end 

そして、このために、私はウェブショップでsolidus_prescriptionモジュール内のユニットテストと統合テストを書きました。ユニットテストは正常に動作しているが、統合テストは、次のエラーを与えている:

エラー: MeEndpointsTest#1 test_me/prescriptions_post_endpoint_throws_an_error_when_wrong_params: AbstractController :: ActionNotFound:アクション「create_prescriptionは」シュプレー川が見つかりませんでした:: Apier :: MeController test/integration/me_endpoints_test.rb:68: `ブロックイン '

つまり、彼は別のモジュールで定義されたMeControllerを見つけることができません。

def class_defined?(klass) 
    Object.const_get(klass) 
rescue 
    false 
end 

if class_defined? 'Spree::Api::MeController' 
.... 
end 
+0

class_evalのブロック内で定義されたメソッドを見つけることができません。どのようにこれらのメソッドを追加するためにデコレータを呼びますか?モジュールを使用してそれらを含める必要があります。 –

答えて

0

:MeControllerが定義されている場合、私はチェックを行うことができますどのようにコード怒鳴るは何で私を助けていないので、理論的にする。問題はif defined? Spree::Api::MeController.classをチェックしていることです。あなたのクラスの#classClassです。あなたが本当に得ているものは、常に真実になるif defined? Classです!

この問題は、条件付きが失敗しているが、決して読み上げられていない可能性が高いです。 Railsはあなたが書いたコードのほとんどを読み込みません。つまり、ファイルは実行中のどこかで呼び出されるまで読み込まれません。

デコレータモジュールには、条件付きでもclass_evalも使わずに、追加したいメソッドだけを入れる必要があります。元のclassに含めることができます。

module Spree 
    module Api 
    class MeController < Spree::Api::BaseController 
     include MeDecorator 
    end 
    end 
end 

defined? MeDecoratorが実際にそれが定義されていない場合は、それを探しに行くと、必要なファイルをロードしませんので、あなたがMeDecoratorが定義される特定のじゃない何らかの理由で、defined?使用しない場合。定数に値がない場合はnilを返します。ただrescue a NameError

module Spree 
    module Api 
    class MeController < Spree::Api::BaseController 
     begin 
     include MeDecorator 
     rescue NameError => e 
     logger.error e 
     end 
    end 
    end 
end 
0

if defined?は正確にあなたがそれをやりたいはずです。これで終わりで働いていた

if defined? Spree::Api::MeController.class 
end 
関連する問題