Skip to content

Programmatic use of Guard

Rémy Coutable edited this page Jun 15, 2020 · 5 revisions

Guard 3.x

You can run Guard programmatically and optionally give it an inline Guardfile or a custom Guardfile location. Available options are as follow:

  • :guardfile - The path to a valid Guardfile.
  • :inline - A string representing the content of a valid Guardfile.

Remember, without any options given, Guard will look for a Guardfile in your current directory and if it does not find one, it will look for it in your $HOME directory.

Guard::Engine#run_all can be used to run all Guard plugins. You can pass a scope to it with the :plugins or :groups options. Run Guard plugins, e.g. from a Rakefile:

require 'guard/engine'

engine = Guard::Engine.new.setup

engine.run_all(:features)

# or with multiple groups
engine.run_all(:features, :documentation)

Specify a custom Guardfile path:

require 'guard/engine'

engine = Guard::Engine.new(guardfile: 'Guardfile.custom').setup

engine.run_all(:rspec)

Start Guard and with a Guardfile as a string:

require 'guard/engine'

guardfile = <<-EOF
  guard 'rspec', cmd: "bundle exec rspec -f progress" do
    watch(%r{^spec/.+_spec\.rb$})
  end
EOF

engine = Guard::Engine.new(inline: guardfile).setup

engine.run_all(:rspec)

Guard 2.x

You can pass a Guardfile content or a Guardfile location programmatically when calling Guard.start. Available options are as follow:

  • :guardfile - The path to a valid Guardfile.
  • :contents - A string representing the content of a valid Guardfile.

Remember, without any options given, Guard will look for a Guardfile in your current directory and if it does not find one, it will look for it in your $HOME directory.

Guard.run_all can be used to run all Guard plugins. You can pass a scope to it with the :plugins / :plugin or :groups / :group options. Run Guard plugins, e.g. from a Rakefile:

require 'guard'
require 'guard/commander' # needed because of https://github.com/guard/guard/issues/793

Guard.run_all group: :features

# or with multiple groups
Guard.run_all groups: [:features, :documentation]

Specify a custom Guardfile path:

require 'guard'
require 'guard/commander' # needed because of https://github.com/guard/guard/issues/793

Guard.start(guardfile: '/path/to/Guardfile')

Start Guard and with a Guardfile as a string:

require 'guard'
require 'guard/commander' # needed because of https://github.com/guard/guard/issues/793

guardfile = <<-EOF
  guard 'rspec' do
    watch(%r{^spec/.+_spec\.rb$})
  end
EOF

Guard.start(contents: guardfile)