Sha256: 7bd498ba2878a9bc1afd065f3fdbce30cef9ed30e6db063526653756ea791b5c

Contents?: true

Size: 1.61 KB

Versions: 1

Compression:

Stored size: 1.61 KB

Contents

require 'addressable/uri'

module RailsConnector
  class LinkParser
    def initialize(host, port)
      @host = host
      @port = port
    end

    def parse(url)
      uri = Addressable::URI.parse(url)
      link_params = {}

      if obj = find_obj(uri)
        link_params[:obj] = obj
      else
        if application_uri?(uri)
          uri.path = '/' unless uri.path.present?
          uri.port = nil
          uri.host = nil
          uri.scheme = nil
        end

        link_params[:url] = uri.to_s
      end

      link_params[:query] = uri.query
      link_params[:fragment] = uri.fragment

      Link.new(link_params)
    rescue Addressable::URI::InvalidURIError
      Link.new(url: url)
    end

    private

    def application_uri?(uri)
      uri.absolute? && internal_uri?(uri) || uri.relative? && uri.path.present?
    end

    def internal_uri?(uri)
      if uri.port.present?
        uri.host == @host && uri.port == Integer(@port)
      else
        uri.host == @host
      end
    end

    def find_obj(uri)
      return nil unless application_uri?(uri) && application_route?(uri)

      route_params = route(uri)

      if id = route_params[:id]
        Obj.find(id)
      elsif permalink = route_params[:permalink]
        Obj.find_by_permalink(permalink)
      end
    rescue RailsConnector::ResourceNotFound
    end

    def application_route?(uri)
      route_params = route(uri)
      route_params && route_params[:controller] == 'rails_connector/cms_dispatch'
    end

    def route(uri)
      Rails.application.routes.recognize_path(uri.to_s, method: :get)
    rescue ActionController::RoutingError
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
infopark_cloud_connector-7.1.0 lib/rails_connector/link_parser.rb