Search code examples
ruby-on-railsrubymoduleruby-on-rails-5

undefined method `render' for module in rails


module UserCheck
  def self.status(onboarding, params)
    if onboarding && params[:process].present?
      render json: { status: :ok }
    else
      render json: { error: 'You have already finished your onboarding.'  }, status: :not_implemented
    end
  end
end


module MyAccount::User
  class UserController < MyAccountController
    def update
      UserCheck.status(wizard_onboarding, params)
    end
  end
end

In the users_controller, I am using the module UserCheck to check the onboarding status and return an error in the else case. But when the else condition runs it doesn’t render json error message but instead returns the undefined method 'render' for UserCheck:Module. Could you help me fix this issue?


Solution

  • I would pass the controller to that method and call then render on that controller, like this:

    module UserCheck
      def self.status(onboarding, params, controller)
        if onboarding && params[:process].present?
          controller.render json: { status: :ok }
        else
          controller.render json: { error: 'You have already finished your onboarding.'  }, status: :not_implemented
        end
      end
    end
    
    
    module MyAccount::User
      class UserController < MyAccountController
        def update
          UserCheck.status(wizard_onboarding, params, self)
        end
      end
    end
    

    Personally, I see no benefit in extracting such simple code from the controller into a module. It makes the controller much harder to understand and to debug. And to understand what the controller is returning, you need to look into a different file.