Sha256: 34b392fd7b683e19e50fd24c7e8bf1d588e2e4ab2d459b3f0fe36395f85c7cb5

Contents?: true

Size: 1.32 KB

Versions: 70

Compression:

Stored size: 1.32 KB

Contents

# If the app catches a 404, check Redirect records for a match.

# Use -> Add the following to application_controller.rb:
# rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
# private
# def record_not_found
#   redirect_to Tenon::Redirector.new(request.env['PATH_INFO']).redirect
# end

module Tenon
  class Redirector
    def initialize(path, redirects = Tenon::Redirect.active)
      @path = path
      @redirects = redirects
    end

    def redirect
      # If 404 -> Compare the path to all Redirect records:
      @destination = get_destination
      # raise @destination.inspect
      if @destination.present?
        # If there is a match return destination:
        return @destination
      else
        # Else -> trigger the 404 again:
        raise ActiveRecord::RecordNotFound
      end
    end

    private

    def get_destination
      @redirects.each do |redirect|
        if @path.match(/#{redirect.in}/).present?
          return redirect_match(redirect)
        end
      end
      nil
    end

    def redirect_match(redirect)
      @destination = redirect.out
      captures = @path.match(/#{redirect.in}/).captures
      if captures.present?
        captures.each_with_index do |capture, i|
          @destination = @destination.gsub(/\{#{i}\}/, capture)
        end
      end
      @destination
    end
  end
end

Version data entries

70 entries across 70 versions & 1 rubygems

Version Path
tenon-1.1.8 app/services/tenon/redirector.rb
tenon-1.1.7 app/services/tenon/redirector.rb
tenon-1.1.6 app/services/tenon/redirector.rb
tenon-2.1.0 app/services/tenon/redirector.rb
tenon-2.0.8 app/services/tenon/redirector.rb
tenon-2.0.7 app/services/tenon/redirector.rb
tenon-2.0.6 app/services/tenon/redirector.rb
tenon-2.0.5 app/services/tenon/redirector.rb
tenon-2.0.4 app/services/tenon/redirector.rb
tenon-2.0.3 app/services/tenon/redirector.rb
tenon-2.0.2 app/services/tenon/redirector.rb
tenon-2.0.1 app/services/tenon/redirector.rb
tenon-2.0.0 app/services/tenon/redirector.rb
tenon-1.1.5 app/services/tenon/redirector.rb
tenon-1.1.4 app/services/tenon/redirector.rb
tenon-1.1.3 app/services/tenon/redirector.rb
tenon-1.1.2 app/services/tenon/redirector.rb
tenon-1.1.1 app/services/tenon/redirector.rb
tenon-1.0.76 app/services/tenon/redirector.rb
tenon-1.0.75 app/services/tenon/redirector.rb