Module: Roda::RodaPlugins::HashPaths

Defined in:
lib/roda/plugins/hash_paths.rb

Overview

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.

Defined Under Namespace

Modules: ClassMethods, RequestMethods

Class Method Summary collapse

Class Method Details

.configure(app) ⇒ Object



78
79
80
# File 'lib/roda/plugins/hash_paths.rb', line 78

def self.configure(app)
  app.opts[:hash_paths] ||= {}
end