Search code examples
ruby-on-railsrubysolidus

Ruby - Check if controller defined


I am using Solidus with Ruby on Rails to create a webshop and I have multiple modules for that webshop.

So, I defined a me controller into an module called 'solidus_jwt_auth' with the followin code:

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

      def orders
        ...
      end

      def addresses
        ...
      end
    end
  end
end

I want to extend this in another module called 'solidus_prescriptions' so I created a decorator for this with the following code 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

And for this I wrote unit tests in solidus_prescription module and integration tests in webshop. The unit tests are working fine, but the integration tests are giving the following error:

Error: MeEndpointsTest#test_me/prescriptions_post_endpoint_throws_an_error_when_wrong_params: AbstractController::ActionNotFound: The action 'create_prescription' could not be found for Spree::Api::MeController test/integration/me_endpoints_test.rb:68:in `block in '

Which means that he can not find the MeController defined in another module. How can I make the check if the MeController is defined since the code bellow does not help me with anything:

if defined? Spree::Api::MeController.class
end

Solution

  • This worked in the end:

    def class_defined?(klass)
      Object.const_get(klass)
    rescue
      false
    end
    
    if class_defined? 'Spree::Api::MeController'
     ....
    end