module Roda::RodaPlugins::HashPaths

  1. lib/roda/plugins/hash_paths.rb

The hash_paths plugin allows for O(1) dispatch to multiple routes at any point in the routing tree. It is useful when you have a large number of specific routes to dispatch to at any point in the routing tree.

You configure the hash paths to dispatch to using the hash_path class method, specifying the remaining path, with a block to handle that path. Then you dispatch to the configured paths using r.hash_paths:

class App < Roda
  plugin :hash_paths

  hash_path("/a") do |r|
    # /a path
  end

  hash_path("/a/b") do |r|
    # /a/b path
  end

  route do |r|
    r.hash_paths
  end
end

With the above routing tree, the r.hash_paths call will dispatch requests for the /a and /a/b request paths.

The hash_path class method supports namespaces, which allows r.hash_paths to be used at any level of the routing tree. Here is an example that uses namespaces for sub-branches:

class App < Roda
  plugin :hash_paths

  # Two arguments provided, so first argument is the namespace
  hash_path("/a", "/b") do |r|
    # /a/b path
  end

  hash_path("/a", "/c") do |r|
    # /a/c path
  end

  hash_path(:b, "/b") do |r|
    # /b/b path
  end

  hash_path(:b, "/c") do |r|
    # /b/c path
  end

  route do |r|
    r.on 'a' do
      # No argument given, so uses the already matched path as the namespace,
      # which is '/a' in this case.
      r.hash_paths
    end

    r.on 'b' do
      # uses :b as the namespace when looking up routes, as that was explicitly specified
      r.hash_paths(:b)
    end
  end
end

With the above routing tree, requests for the /a branch will be handled by the first r.hash_paths call, and requests for the /b branch will be handled by the second r.hash_paths call. Those will dispatch to the configured hash paths for the /a and :b namespaces.

It is best for performance to explicitly specify the namespace when calling r.hash_paths.

Methods

Public Class

  1. configure

Public Class methods

configure(app)
[show source]
   # File lib/roda/plugins/hash_paths.rb
78 def self.configure(app)
79   app.opts[:hash_paths] ||= {}
80 end