The ideal would be to access Rails route helpers verbatim just as you would in backend views or helpers. But the routing code is pretty tangled so I think it won't be possible to run it directly on the frontend without effort.
A workaround is to add .erb to component files and interpolate the route on the backend with static placeholder values, then gsub in real values on the frontend.
First, make it easier to access route helpers:
# config/initializers/routes.rbclassRoutesincludeSingletonincludeRails.application.routes.url_helpersdefself.method_missing(name, *args, &block)ifinstance.respond_to?(name)instance.send(name, *args, &block)elsesuperendenddefself.respond_to_missing?(name,include_all=false)instance.respond_to?(name,include_all)endend
Then in your ApplicationComponent add this helper to do the substitution:
classApplicationComponent < Hyperloop::Componentdefrails_route(route, *positional, **named)route=route.split("/").reverse.join("/")positional.each_with_indexdo |replacement,i|
route=route.sub(i.to_s,replacement.to_s)endnamed.eachdo |key,replacement|
route=route.sub(key.to_s,replacement.to_s)end"/" + route.split("/").reverse.join("/")endendAnd finally use the mechanism in your components:
classCommentLink < ApplicationComponentparam:commentrenderdoA(href: rails_route("<%= Routes.user_posts_comments_path(0, 1, "xyz") %>",User.current.id,params.comment.post.id,xyz: params.comment.id)){"View Comment"}endendUsing positional arguments is the easiest, but if your route contains numbers it won't work so explicitly name your arguments with placeholders that won't clash. The above example shows both.
The ideal would be to access Rails route helpers verbatim just as you would in backend views or helpers. But the routing code is pretty tangled so I think it won't be possible to run it directly on the frontend without effort.
A workaround is to add .erb to component files and interpolate the route on the backend with static placeholder values, then gsub in real values on the frontend.
First, make it easier to access route helpers:
Then in your ApplicationComponent add this helper to do the substitution:
And finally use the mechanism in your components:
Using positional arguments is the easiest, but if your route contains numbers it won't work so explicitly name your arguments with placeholders that won't clash. The above example shows both.