Sha256: 5610cbfd61d6be6cbbb01adc177b9a715b6ed4ba2baf7a3c664e3691e2a57ac8

Contents?: true

Size: 1.43 KB

Versions: 5

Compression:

Stored size: 1.43 KB

Contents

# frozen_string_literal: true

module Rails
  module RFC6570
    class Formatter
      attr_reader :route

      def initialize(route)
        @route = route
        @parts = Visitor.new(factory: method(:symbol)).accept(route.path.spec)
      end

      def evaluate(ctx:, ignore: %w[format], **kwargs)
        parts = @parts.reject do |part|
          part.is_a?(Subst) && ignore.include?(part.name)
        end

        if kwargs.fetch(:params, true) && route
          controller = route.defaults[:controller].to_s
          action     = route.defaults[:action].to_s

          if controller.present? && action.present?
            params = ::Rails::RFC6570.params_for(controller, action)
            parts << ("{?#{params.join(',')}}") if params&.any?
          end
        end

        if kwargs.fetch(:path_only, false)
          ::Addressable::Template.new parts.join
        else
          options = ctx.url_options.merge(kwargs)
          options[:path] = parts.join

          if (osn = options.delete(:original_script_name))
            options[:script_name] = osn + options[:script_name]
          end

          ::Addressable::Template.new \
            ActionDispatch::Http::URL.url_for(options)
        end
      end

      def symbol(node, prefix: nil, suffix: nil)
        Subst.new(node.name, "{#{prefix}#{node.name}#{suffix}}")
      end

      Subst = Struct.new(:name, :string) do
        alias_method :to_s, :string
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rails-rfc6570-3.3.0 lib/rails/rfc6570/formatter.rb
rails-rfc6570-3.2.0 lib/rails/rfc6570/formatter.rb
rails-rfc6570-3.1.0 lib/rails/rfc6570/formatter.rb
rails-rfc6570-3.0.0 lib/rails/rfc6570/formatter.rb
rails-rfc6570-2.6.0 lib/rails/rfc6570/formatter.rb