Module: Rack::App::InstanceMethods::PathTo

Included in:
Rack::App::InstanceMethods
Defined in:
lib/rack/app/instance_methods/path_to.rb

Instance Method Summary collapse

Instance Method Details

#path_to(defined_path, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rack/app/instance_methods/path_to.rb', line 3

def path_to(defined_path, options = {})
  app_class = options[:class] || self.class

  query_string_hash = options[:params] || {}
  options.each do |k, v|
    k.is_a?(String) && query_string_hash[k] = v
  end

  router = request.env[Rack::App::Constants::ENV::ROUTER]
  final_path = router.path_to(app_class, defined_path)

  path_keys = final_path.scan(/:(\w+)/).flatten

  path_keys.each do |key|
    value = query_string_hash.delete(key) || params[key] || raise("missing path-key value for #{key}!")
    final_path.gsub!(/:#{key}/, value.to_s)
  end

  unless query_string_hash.empty?
    final_path.concat("?" + Rack::Utils.build_nested_query(query_string_hash))
  end

  final_path
end