Live Reload With Octopress

My first tech post youhouuu

Ok this one is about the way to have live-reload enable for octopress (the framework blog I use for this blog). Because when I was studying programming my teachers always told me I have to be lazy so now I’m lazy even to refresh a page.

Live reload do this job and with octopress, you just have to watch when a file (like your post for exemple) is modified and then send the signal to live reload to refresh the page. To watch for any modifications in a file you can use guard, there is even guard-livereload to use guard with live reload. So let’s do it.

In your Gemfile you just have to put the folowing gem in the development group

Gemfile
1
gem 'guard-livereload'

and then create a Guardfile to say which files you want to watch, you can just run the command guard init livereload and you’ve got this

Guardfile
1
2
3
4
5
6
7
8
guard 'livereload' do
  watch(%r{app/views/.+\.(erb|haml|slim)$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{public/.+\.(css|js|html)})
  watch(%r{config/locales/.+\.yml})
  # Rails Assets Pipeline
  watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html))).*}) { |m| "/assets/#{m[3]}" }
end

more than expected because it generate a file for Ruby on Rails and octopress use Sinatra. We just need the line which watch the public folder because when you run your rake preview to work on your blog this compile automatically your sources in the public folder.

Here is the final Guardfile

Guardfile
1
2
3
guard 'livereload' do
  watch(%r{public/.+\.(css|js|html)})
end

Now two solutions, you have to run the command guard every time you start to work on your blog or you can edit the preview task in your Rakefile like that

Rakefile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
desc "preview the site in a web browser"
task :preview do
  raise "### You haven't set anything up yet. First run `rake install` to set up an Octopress theme." unless File.directory?(source_dir)
  puts "Starting to watch source with Jekyll and Compass. Starting Rack on port #{server_port}"
  system "compass compile --css-dir #{source_dir}/stylesheets" unless File.exist?("#{source_dir}/stylesheets/screen.css")
  jekyllPid = Process.spawn({"OCTOPRESS_ENV"=>"preview"}, "jekyll --auto")
  compassPid = Process.spawn("compass watch")
  rackupPid = Process.spawn("rackup --port #{server_port}")
  guardPid = Process.spawn("guard")

  trap("INT") {
    [jekyllPid, compassPid, rackupPid, guardPid].each { |pid| Process.kill(9, pid) rescue Errno::ESRCH }
    exit 0
  }

  [jekyllPid, compassPid, rackupPid, guardPid].each { |pid| Process.wait(pid) }
end

Ok here it is, now just run the command bundle install, restart your server then every time you will modify or create a file your blog will be refresh :)

Comments

Copyright © 2014 - Anthony Estebe -