Guard With Ruby on Rails

Yesturday I talked about Guard, this tool is very usefull when you don’t want to loose time to type again and again the same commands.

For exemple you create a website and you want to use Coffee and SASS. This is a good but our browsers cannot read coffee and sass/scss files so we have to convert them into js and css files. So every times you update one file you have to compile it in js or css… boring…

And now Guard comes, it will let you define actions you want to execute each times one file is modified so for our example we see really quickly the benefits but lets look for a Rails application.

In Rails no need to compile the coffee or scss files (or whatever engine you use), the framework already do it for us ♡ So why it can be good to use Guard ? Like I say, you can run any tasks for any files modified so why not restarting the server when it’s needed.

So if it’s not done yet you have to install Guard gem install guard

there is also one gem to manage rails tasks so lets add it too gem install guard-rails

Now we just have to create the Guardfile needed to list all the files to watch

Guardfile
1
2
3
4
5
6
guard 'rails' do
  watch('Gemfile.lock')
  watch(%r{^config/(initializers|environments)/.*})
  watch('config/application.rb')
  watch(%r{^lib/.*})
end

Thats all now instead of run rails server you can just run the command guard and you can forget to think about restarting your server and I’m sure I’m not the only one who already loose time to find why something doesn’t works just because I didn’t restart my server…

Small bonus like with Octopress you can of course use the gem 'guard-livereload' and like in this post just run the command guard init livereload and now you have your browser automatically refresh every time you change a file required for the view of your application.

Bonus #2 if you want to see the list of all Guard’s gems you can go here of here

Comments

Copyright © 2014 - Anthony Estebe -