[Ruby] [Rails] Extend UrlHelper

less than 1 minute read

I want to define my own UrlHelper

It is good to create a Class that includes Rails.application.routes.url_helpers.


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

   #Self-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 UrlHelper.

Tags: ,

Updated: