Class: Journey::Formatter

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

Overview

The Formatter class is used for formatting URLs. For example, parameters passed to url_for in rails will eventually call Formatter#generate

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(routes) ⇒ Formatter

Returns a new instance of Formatter.



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

def initialize routes
  @routes = routes
  @cache  = nil
end

Instance Attribute Details

#routesObject (readonly)

Returns the value of attribute routes.



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

def routes
  @routes
end

Instance Method Details

#clearObject



47
48
49
# File 'lib/journey/formatter.rb', line 47

def clear
  @cache = nil
end

#generate(key, name, options, recall = {}, parameterize = nil) ⇒ 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
42
43
44
45
# File 'lib/journey/formatter.rb', line 13

def generate key, name, options, recall = {}, parameterize = nil
  constraints = recall.merge options

  match_route(name, constraints) do |route|
    data = constraints.dup

    keys_to_keep = route.parts.reverse.drop_while { |part|
      !options.key?(part) || (options[part] || recall[part]).nil?
    } | route.required_parts

    (data.keys - keys_to_keep).each do |bad_key|
      data.delete bad_key
    end

    parameterized_parts = data.dup

    if parameterize
      parameterized_parts.each do |k,v|
        parameterized_parts[k] = parameterize.call(k, v)
      end
    end

    parameterized_parts.keep_if { |_,v| v  }

    next unless verify_required_parts!(route, parameterized_parts)

    z = Hash[options.to_a - data.to_a - route.defaults.to_a]

    return [route.format(parameterized_parts), z]
  end

  raise Router::RoutingError
end