[Rails] Extend UrlHelper

I want to define my own UrlHelper

It's a good idea to create a Class that includes Rails.application.routes.url_helpers.


class MyUrlResolver
  class << self
    include Rails.application.routes.url_helpers
  end

  #Originally defined helper
  def self.custom_users_path(user)
    if user.admin?
      admin_users_path
    else
      users_path
    end
  end
end

with this,

> MyUrlResolver.admin_users
=> "/admin_users"
> MyUrlResolver.users_path
=> "/users"

In addition to the standard UrlHelper

> MyUrlResolver.custom_users_path(admin_user)
=> "/admin_users"
> MyUrlResolver.custom_users_path(normal_user)
=> "/users"

You can also use your own defined UrlHelper.

Recommended Posts

[Rails] Extend UrlHelper
[Rails g.error]
Rails basics
Rails Review 1
[Rails] first_or_initialize
rails tutorial
About Rails 6
Rails foundation
rails tutorial
rails tutorial
rails tutorial
[Rails] devise
rails tutorial
rails tutorial
Rails Tips
rails method
rails tutorial
[Rails] ActiveRecord
[Rails] form_with
Rails Review 2