Open PeterTKY opened 6 years ago
It needs some kind of reference to connect a model with the desired Rails route, an object may often have more than one route (or just one unique route).
@skalee would you have time to help here?
I should be able to do this one, and EnMail in parallel.
@PeterTKY How does it differ from stock Rails' url_for
/path_for
method?
They should be quite similar. But I just tested a little bit in my Rails console. The url_for method seems not working in places other than ActionView.
class Tester
include ActionView::RoutingUrlFor
end
Tester.new.url_for(Restaurant.last)
It will result in error:
NoMethodError: undefined method `_routes' for #<Tester:0x0000561f8de70088 @_routes=nil>
Unfortunately that's our major use case for object path...
@skalee indeed as mentioned by @PeterTKY, the use case is to use object path outside of ActionView.
u = User.create
#=> #<User id: 1, email: nil, created_at: "2018-03-23 19:01:39", updated_at: "2018-03-23 19:01:39">
Rails.application.routes.url_helpers.polymorphic_url(u, :only_path => true)
#=> "/users/1"
Rails.application.routes.url_helpers.polymorphic_url(u, :host => "example.com")
#=> "http://example.com/users/1"
I'm not sure if this one-liner is worth extraction into a separate gem. Even though it's bit hackish.
cc @PeterTKY
There are actually some use cases can't be handled easily by polymorphic_url.
Example: We have three model classes, Restaurant::Chinese, Restaurant::Japanese and Restaurant::Western. In config/routes.rb:
namespace :restaurants do
resources :chinese do
# some routes for chinese
end
resources :japanese do
# some routes for japanese
end
resources :western do
# some routes for western
end
end
In console:
Rails.application.routes.url_helpers.polymorphic_url([Restaurant::Chinese.last], only_path: true)
# => NoMethodError: undefined method `restaurant_chinese_url' for #<#<Class:0x000055a3a34ab220>:0x000055a3a34aa730>
We have to call:
Rails.application.routes.url_helpers.polymorphic_url([:restaurants_chinese], id: 1, only_path: true)
But then the :restaurants_chinese is not intuitive to have. We can't simply use the model instance in polymorphic_url like other cases.
The object_path/object_url method should generate correct path/url as the routes defined in a Rails application. It should handle properly even if the routes are actually defined in a Rails engine and mounted in the application.