Are there any reasons why Rails doesn't have any route helpers available for the JS/CS assets?
We're doing more and more client-side code and it is very likely that you'll need to do something like "$.post products_path, params" somewhere in your code.
Currently for doing that you'd need to create a file like asset.js.coffee.erb and then do something like:
$.post <%= Rails.application.routes.url_helpers.send(:products_path) %>, params
This is not only ugly and impractical, but I also don't want my files to be processed with ERB. This is not even possible inside my ECO templates.
So I decided a while back to create a routes.js.coffee.erb to export my named routes in some way to my other scripts. But as I needed more and more features it got a lot messy now:
<% h = Rails.application.routes.url_helpers { sections_json: :json, fields_from_parent: :json_id, move_field: :json, field: :json_id, field_save: :json, remove_field: :html_id, field_aggregates_autocomplete: [:json_id, :data_type], field_dependents_autocomplete: :json_id, field_set_aggregator: [:html_id, :aggregator_id], field_remove_aggregate: :html_id, field_add_dependent: [:html_id, :dependent_id], field_remove_dependent: [:html_id, :dependent_id], section_update: :html_id, section_create: :json, }.each do |named_route, options| options = Array(options) format = options.shift format_options = {} format_options[:format] = :json if format =~ /json/ options.push format_options if format =~ /_id/ %> window.<%= named_route %>_path = (id, options)-> path = "<%= h.send :"#{named_route}_path", '999', *options %>".replace('999', id) <% if options.size > 1 %> path = path.replace(k, v) for k, v of options path <% end %> <% else %> window.<%= named_route %>_path = '<%= h.send :"#{named_route}_path", format_options %>' <% end %>
See how to maintain something like this can become complicated?
Couldn't Rails provide an easier built-in way for the named routes to be easily exported as JS functions/variables?
This way, instead of each application define their own helpers for such a common requirement, an official way would exist and developers moving their jobs or projects would be aware where to look for.
I just feel there is some convention missing here.
Cheers, Rodrigo.