Reputation: 3333
I am using Rails 3.2.12.
I would like to insert a ruby code in my asset JavaScript file:
function trim(string) {
return string.replace(/(^\s+)|(\s+$)/g, "");
}
function <%= controller_name %>() {
...
}
How can I do this?
Thanks in advance.
Upvotes: 3
Views: 10878
Reputation: 2352
I'm not sure why you would want to use the controller name when DEFINING your function, but if you really do, then
modify/use:
-link_to
-button_to
-form_tag
-form_for
with the remote: true
attribute: e.g.
<%= form_for(@article, remote: true) do |f| %>
Find more information:
ALTERNATIVELY,
You could predefine functions statically for each controller, e.g.:
function Users(param1, param3...){
....
}
function Friends(param1, param3...){
....
}
function Likes(param1, param3...){
....
}
function Posts(param1, param3...){
....
}
then add an additional JavaScript statement to launch the appropriate function depending on which controller is being called, e.g.:
<%= controller_name %>();
Upvotes: 1
Reputation: 2257
If variables you are going to pass are request-independent - then just give it a name *.js.erb
.
For request-specific data (like controller name in your example) that's impossible. Javascript files are loaded independently from application requests and normally they are served as static assets by application server (apache, nginx). Thus if you want some custom script that is request-dependent put it inside your view template (.html.erb).
Also you can definitely proxy request to your js file through application (define it's route in routes.rb
) but that will not be considered as good code.
Upvotes: 8
Reputation: 15089
I believe if you have a javascript file with the extension .js.erb
or .js.coffee.erb
, all the extensions would be parsed from right to left, thus your code should understand some erb
tags inside it, before parsing the coffeescript
and ultimately the js
part.
Upvotes: 2