1

The Rails command rails dev:cache toggles whether Rails caching features work in the local development environment. It does this by creating or destroying a file that acts as a flag for the features. However, for our dev setup script, I would like to run the command so that the caching features are always turned on instead of toggled.

The source code for rails dev:cache includes this 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

How do I run the rails dev:cache command so that it uses this argument? I've tried several variations, including rails dev:cache[true], rails dev:cache\[true\] and rails dev:cache true, but all of them have used the toggling behavior instead of the argument-controlled behavior.

This is not a duplicate of How to pass command line arguments to a rake task because that question is about passing arguments to Rake tasks. But this is a command built into Rails instead.

Kevin
  • 14,655
  • 24
  • 74
  • 124
  • Right now, in our script, we're checking for the existence of the file ourselves before running the command. I think it would be cleaner to avoid having to make that check if we can, though. – Kevin Aug 03 '20 at 22:12

1 Answers1

3

It is not possible to do it by default, because the original task does not take an argument at all.

However if we improve the task code a little bit, we can get it to do what you want.
Put this at the end of your 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

Now you can use any of these:

rails dev:cache
rails dev:cache[true]
rails dev:cache[false]
Casper
  • 33,403
  • 4
  • 84
  • 79