Q:

Rails link_to helper relative to namespace

Let's say I have a blog engine with a backend, where the backend routes are namespaced under admin and the frontend under public. Now I would like to share some of the views between the two namespaces.
Is there a DRY way to instruct link_to to generate urls relative to the current namespace (e.g. a link made with posts_path() where the controller is admin/home#index should point to /admin/posts, but the same link under the controller public/home#index should point to /public/posts), so I can use the same view for both controllers?
I see I could solve it using conditionals, and using admin_posts_path and public_posts_path respectively, but that adds a lot of clutter to the views.

A:

Something we did in an API project was not to use namespace, rather to use scopes like this:
scope '/:type', constraints: { type: /(admin|public)/ } do
  resources :posts
end

Then in your views, you'd do:
# The :type param should be inferred from the route, but you could be explicit as such:
link_to 'Posts', posts_path(type: params[:type])

That should always link appropriately to your public and admin posts

