我想在 Rails 应用程序中运行 Assets 预编译任务,因为我有很多依赖项会更改代码,在这种情况下,每当它们更改时,我都需要运行脚本,因为我无法授予服务器访问它们的权限,所以我为他们提供 GUI,因为他们可以单独运行脚本,因此,我构建了 UI 来使用一些参数运行任务,例如
system("Template='#{params[:template]}' Theme='#{params[:theme]}' rake assets:precompile)
我从 UI (params[:template],params[:theme]) 获得两个值。我想在另一个路径(站点路径)中运行此任务的另一件事意味着管理端 UI 应该在其中执行该任务站点目录,
if(params[:theme_script] == "true")
template=Template.where(:name => params[:template]).first
if template
theme = template.themes.where(:name => params[:theme]).first
if theme
# Dir.chdir "#{THEMEPATH}"do
# `Template="#{template.name}" Theme="#{theme.name}" rake assets:precompile`
# end
# sleep 10
# system("#{Rails.root.to_s}/lib/shell_script.sh")
# RunRake.run_rake(template.name,theme.name)
# Dir.chdir "#{THEMEPATH}"do
# Rake::Task['assets:precompile'].invoke
# end
ENV["Template"] = template.name
ENV["Theme"] = theme.name
precompile_task = "bundle exec rake assets:precompile --trace 2>&1"
output = Dir.chdir(THEMEPATH) { %x[ #{precompile_task} ] }
flash[:notice] = "Asset created successfully"
else
flash[:notice] = "U have enter invalid data"
end
else
flash[:notice] = "U have enter invalid data"
end
end
这是我的代码,正在检查多个条件并允许执行任务。
我已经通过放入 Controller 和库来尝试此代码,但这不起作用。
我也尝试过使用 shell 脚本。
可以请任何人帮助我。
最佳答案
您可以为 rails 设置一个环境变量,然后从 Controller 发出 #invoke
方法。因此,准备文件:
gem 'rake'
config/initializers/rake.rb:
Rake.load_rakefile Rails.root.join( 'Rakefile' )
app/controllers/your_controller:
ENV["Template"] = template.name
ENV["Theme"] = theme.name
Rake::Task[ 'assets:precompile' ].invoke
发出 bundle install
,然后运行控制台 rails c
,然后输入:
Rake::Task.tasks.map(&:name).grep 'assets:precompile'
# => ["assets:precompile"]
如您所见,任务 assets:precompile
加载成功。然后只需为 Controller 发出操作即可。
为另一个人运行任务 rails你的应用程序也运行另一个ruby例如,类似于您所做的:
system( "other_app_run.sh '#{template.name}' '${theme.name}'" )
other_app_run.sh:
#!/bin/bash
source "$HOME/.rvm/scripts/rvm"
cd /other/app/path
export Template="$1"
export Theme="$2"
rake assets:precompile
关于ruby-on-rails - 在 Rails 应用程序中运行 rake 任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21456538/