简体   繁体   English

Rails 3.1在JavaScript文件中插入ruby代码

[英]Rails 3.1 insert ruby code in JavaScript file

I am using Rails 3.2.12. 我正在使用Rails 3.2.12。
I would like to insert a ruby code in my asset JavaScript file: 我想在我的资产JavaScript文件中插入一个ruby代码:

function trim(string) {
  return string.replace(/(^\s+)|(\s+$)/g, "");
}

function <%= controller_name %>() {
...    
}

How can I do this? 我怎样才能做到这一点?
Thanks in advance. 提前致谢。

If variables you are going to pass are request-independent - then just give it a name *.js.erb . 如果要传递的变量是与请求无关的 - 那么只需给它命名*.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). Javascript文件独立于应用程序请求加载,通常它们由应用程序服务器(apache,nginx)作为静态资产提供。 Thus if you want some custom script that is request-dependent put it inside your view template (.html.erb). 因此,如果您想要一些依赖于请求的自定义脚本,请将其放在视图模板(.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. 你也可以通过应用程序代理请求你的js文件(在routes.rb定义它的路由),但这不会被认为是好的代码。

我相信如果你有一个扩展名为.js.erb.js.coffee.erb的javascript文件,所有的扩展都会从右到左解析,因此你的代码应该在解析coffeescript之前理解其中的一些erb标签。最终是js一部分。

I'm not sure why you would want to use the controller name when DEFINING your function, but if you really do, then 我不确定为什么在DEFINING你的函数时你想要使用控制器名称,但如果你真的这样做,那么

ALTERNATIVELY, 或者,

You could predefine functions statically for each controller, eg: 您可以为每个控制器静态预定义函数,例如:

  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, eg: 然后根据正在调用的控制器添加一个额外的JavaScript语句来启动相应的函数,例如:

  <%= controller_name %>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM