ruby-on-rails - 在 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文件夹中?
解决方案
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 %>
推荐阅读
- css - RWD 和智能手机的屏幕 x 浏览器窗口大小
- python - Python 字典迭代:d 与 d.viewkeys()
- r - check.length("fill") 中的错误:'gpar' 元素 'fill' 的长度不得为 0
- php - Google Drive API 上传/下载 - PHP 到客户端
- autoencoder - keras 中的成本函数
- c++ - C++ 节点分配错误:线程 1:EXC_BAD_ACCESS(代码=1,地址=0x0)
- python - 无法在 OS X 上将 MySQL 导入 python
- laravel - Laravel 架构列
- c# - 如何在 C# 运行时更改用户控件的控件属性?
- react-native - React Native Flatlist zIndex 不适用于溢出:iOS 上的“可见”