thanikkal
thanikkal

Reputation: 3356

Ruby. Calling Super from the overriden method

I am trying to override a the redirect_to method to add an additional param to the get requests (if thats present)

The redirect_to method is here

module ActionController
...................

  module Redirecting
    extend ActiveSupport::Concern
    include AbstractController::Logger
    ...........................

    def redirect_to(options = {}, response_status = {}) #:doc:
      ............................
      self.status        = _extract_redirect_to_status(options, response_status)
      self.location      = _compute_redirect_to_location(options)
      self.response_body = "<html><body>You are being <a href=\"#    {ERB::Util.h(location)}\">redirected</a>.</body></html>"
    end

  end

end

Here is how I am trying to override

module ActionController

    module Redirecting
      def redirect_to(options = {}, response_status = {})

        if options
          if options.is_a?(Hash)
            options["custom_param"] = @custom_param
          else
            if options.include? "?" 
              options = options + "&custom_param=true"
            else
              options = options + "?custom_param=true"
            end 
          end
        end 

        super 

      end

  end

end 

I am apparently doing it wrong, and the super method call fails to work the way I wanted it. Hope someone could help.

Upvotes: 0

Views: 684

Answers (1)

fullsailor
fullsailor

Reputation: 886

I believe the problem here is that you are redefining the redirect_to method, not defining in a new place. super cannot call the original because it no longer exists.

The method you are looking for is alias_method_chain

module ActionController
  module Redirecting

    alias_method_chain :redirect_to, :extra_option

    def redirect_to_with_extra_option(options = {}, response_status = {})

      if options
        ...
      end

      redirect_to_without_extra_option(options, response_status)
    end
  end
end

Though, I think the more Rails friendly way would be to override redirect_to in your ApplicationController

class ApplicationController
  ....
  protected
    def redirect_to(...)
      if options
        ....
      end
      super
    end
end

The benefits to this approach are that you aren't patching rails and the application specific param is now set in your application controller.

Upvotes: 4

Related Questions