【问题标题】:Run rails dev:cache with an argument使用参数运行 rails dev:cache
【发布时间】:2020-11-24 00:01:16
【问题描述】:

Rails 命令rails dev:cache 切换Rails 缓存功能是否在本地开发环境中工作。它通过创建或销毁作为功能标志的文件来做到这一点。但是,对于我们的开发设置脚本,我想运行该命令,以便始终打开而不是切换缓存功能。

rails dev:cache 的源代码包括这个enable_by_argument function

def enable_by_argument(caching)
  FileUtils.mkdir_p("tmp")

  if caching
    create_cache_file
  elsif caching == false && File.exist?(FILE)
    delete_cache_file
  end
end

如何运行rails dev:cache 命令以使其使用此参数?我尝试了几种变体,包括rails dev:cache[true]rails dev:cache\[true\]rails dev:cache true,但所有这些变体使用了切换行为而不是参数控制的行为。

这不是How to pass command line arguments to a rake task 的重复,因为这个问题是关于将参数传递给 Rake 任务。但这是 Rails 内置的命令。

【问题讨论】:

  • 现在,在我们的脚本中,我们在运行命令之前自己检查文件是否存在。不过,我认为如果可以的话,避免进行检查会更干净。

标签: ruby-on-rails ruby caching ruby-on-rails-5


【解决方案1】:

默认情况下不可能这样做,因为the original task 根本不带参数。

但是,如果我们稍微改进一下任务代码,我们就可以让它做你想做的事情。
把这个放在Rakefile的末尾:

# Remove original task
Rake::Task["dev:cache"].clear

# Reimplement task with new and improved behavior
namespace :dev do
  desc "Toggle development mode caching on/off"
  task :cache, [:enable] do |task, args|
    enable = ActiveModel::Type::Boolean.new.cast(args[:enable])
    if enable.nil?
      # Old behavior: toggle
      Rails::DevCaching.enable_by_file
    else
      # New behavior: by argument
      Rails::DevCaching.enable_by_argument(enable)
      puts "Development mode is #{enable ? 'now' : 'no longer'} being cached."
    end
  end
end

现在您可以使用以下任何一种:

rails dev:cache
rails dev:cache[true]
rails dev:cache[false]

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 2023-03-12
    • 2010-09-20
    • 1970-01-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2016-12-28
    相关资源
    最近更新 更多