I use something like this:
def javascript_variables(variables = nil)
@inline_js_variables ||= {}
@inline_js_variables.merge!(variables) and return if !variables.nil?
output = ''
@inline_js_variables.each do |variable, value|
output << "var #{variable} = #{value.to_json};\n"
end
output.strip.html_safe
end
You might put the above in app/helpers/application_helper.rb
. Then in your ApplicationController
, you can put this at the top of the class.
helper :all
Now, in your action you can do something like
def your_activities_action
javascript_variables({ ajax_route_path: sort_activities_path })
end
def your_articles_action
javascript_variables({ ajax_route_path: sort_articles_path })
end
In your app/views/layouts/application.html.erb
you can put the following in the <head>
<script>
<%= javascript_variables %>
</script>
Finally, in your .js
file you can use ajax_route_path
in your url
parameter.
url: ajax_route_path,
Based on this answer and my other one, you should be able to piece together what you're trying to accomplish. For example, if you need both sort_activities_path
and sort_articles_path
included in the same action
def your_articles_action
javascript_variables({ ajax_activities_route_path: sort_activities_path,
ajax_articles_route_path: sort_articles_path })
end
and then modify your Javascript file to use each accordingly (for example, by wrapping the Ajax method in your Question in a function, accepting the route for url
as an argument).