首页 > 解决方案 > 在 Rails 控制器操作中包含文件中的 js 代码

问题描述

我在控制器中有一个动作,它向第 3 方应用程序发送 api 调用。有效负载的一部分是应用程序存储的字符串格式的 js 代码。

这是一个插图:

def store_code_on_app
    myCode = "
        function hello(you){
            console.log("hello", you);
        }
    "

    RestClient.post(
    "http://theapp.com/codes/create",
        {
            code: myCode
        }
    )
end

由于我的实际代码很长,并且为了以后最好地管理多个代码,我想将这些代码存储在我的 rails 应用程序中某个文件夹内的文件中,并从控制器中调用它。我希望使用适当的扩展名 (mycode.js) 保存文件,以便更容易处理和调试。

你会如何建议我这样做?可能是通过要求或包含文件?也许在lib文件夹中?

标签: ruby-on-rails

解决方案


File.read如果您不想要任何动态内容,您可以将其保存在任何地方并加载它。

lib/something/code.js

function hello(you){
   console.log("hello", you);
}

控制器

def store_code_on_app
    myCode = File.read("#{Rails.root}/lib/something/code.js")

    RestClient.post(
    "http://theapp.com/codes/create",
        {
            code: myCode
        }
    )
end

如果它是动态的,你可以使用render_to_string,但我不确定,但沿着这条线的东西可能会起作用

app/views/shared_js_templates/code.js.erb

function <%= console_string %>(you){
  console.log("<%= console_string %>", you);
}

控制器

def store_code_on_app
    myCode = render_to_string(
      'shared_js_templates/code.js.erb',
      layout: false,
      locals: { console_string: 'hello' }
    )

    RestClient.post(
    "http://theapp.com/codes/create",
        {
            code: myCode
        }
    )
end

使用动态,您可以执行以下操作:

app/views/shared_js_templates/code.js.erb

<% 10.times do |index| %>
  function hello<%= index %>(you){
    console.log("hello<%= index %>", you);
  }
<% end %>

推荐阅读