Class: Rails::RFC6570::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/rails/rfc6570/formatter.rb

Defined Under Namespace

Classes: Subst

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(route) ⇒ Formatter

Returns a new instance of Formatter.



8
9
10
11
# File 'lib/rails/rfc6570/formatter.rb', line 8

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

Instance Attribute Details

#routeObject (readonly)

Returns the value of attribute route.



6
7
8
# File 'lib/rails/rfc6570/formatter.rb', line 6

def route
  @route
end

Instance Method Details

#evaluate(ctx:, ignore: %w[format],, **kwargs) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/rails/rfc6570/formatter.rb', line 13

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

#symbol(node, prefix: nil, suffix: nil) ⇒ Object



43
44
45
# File 'lib/rails/rfc6570/formatter.rb', line 43

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