method

direct

Importance_2
v5.2.3 - Show latest stable - 0 notes - Class: CustomUrls
  • 1.0.0
  • 1.1.6
  • 1.2.6
  • 2.0.3
  • 2.1.0
  • 2.2.1
  • 2.3.8
  • 3.0.0
  • 3.0.9
  • 3.1.0
  • 3.2.1
  • 3.2.8
  • 3.2.13
  • 4.0.2
  • 4.1.8
  • 4.2.1
  • 4.2.7
  • 4.2.9
  • 5.0.0.1
  • 5.1.7 (0)
  • 5.2.3 (0)
  • 6.0.0 (0)
  • 6.1.3.1
  • 6.1.7.7
  • 7.0.0
  • 7.1.3.2
  • 7.1.3.4
  • What's this?
direct(name, options = {}, &block) public

Define custom URL helpers that will be added to the application’s routes. This allows you to override and/or replace the default behavior of routing helpers, e.g:

direct :homepage do
  "http://www.rubyonrails.org"
end

direct :commentable do |model|
  [ model, anchor: model.dom_id ]
end

direct :main do
  { controller: "pages", action: "index", subdomain: "www" }
end

The return value from the block passed to direct must be a valid set of arguments for url_for which will actually build the URL string. This can be one of the following:

  • A string, which is treated as a generated URL

  • A hash, e.g. { controller: "pages", action: "index" }

  • An array, which is passed to polymorphic_url

  • An Active Model instance

  • An Active Model class

NOTE: Other URL helpers can be called in the block but be careful not to invoke your custom URL helper again otherwise it will result in a stack overflow error.

You can also specify default options that will be passed through to your URL helper definition, e.g:

direct :browse, page: 1, size: 10 do |options|
  [ :products, options.merge(params.permit(:page, :size).to_h.symbolize_keys) ]
end

In this instance the params object comes from the context in which the block is executed, e.g. generating a URL inside a controller action or a view. If the block is executed where there isn’t a params object such as this:

Rails.application.routes.url_helpers.browse_path

then it will raise a NameError. Because of this you need to be aware of the context in which you will use your custom URL helper when defining it.

NOTE: The direct method can’t be used inside of a scope block such as namespace or scope and will raise an error if it detects that it is.

Show source
Register or log in to add new notes.