あかんわ

覚えたことをブログに書くようにすれば多少はやる気が出るかと思ったんです

guard-livereloadでブラウザをオートリロード

こちらの記事を参考に、Railsアプリのviewファイルを変更した際にブラウザをオートリロードしてくれるguard-livereloadgemを導入しました。

Guard::LiveReloadgemは2.5.2で、LiveReloadのBrowser ExtensionはFirefox extension2.1.1です。

Browser Extensionの使い方を把握するのに右往左往しましたが、基本的に、Guard::LiveReloadのREADMEの通りに作業するだけで動作しました。

目次

Gemfileにguard-livereloadを追加してbundle install

group :development do
・
・
・
  # Automatically reload browser when 'view' files are modified
  gem 'guard-livereload', '2.5.2', require: false
end
$bundle install                     
・
・
・
Installing guard-livereload 2.5.2
・
・
・

guard init livereloadで初期設定

$guard init livereload
・
・
・
14:26:23 - INFO - livereload guard added to Guardfile, feel free to edit it

guard init livereloadコマンドで、Guardfilelivereloadの設定*1が追加されます。

guard 'livereload' do
  extensions = {
    css: :css,
    scss: :css,
    sass: :css,
    js: :js,
    coffee: :js,
    html: :html,
    png: :png,
    gif: :gif,
    jpg: :jpg,
    jpeg: :jpeg,
    # less: :less, # uncomment if you want LESS stylesheets done in browser
  }

  rails_view_exts = %w(erb haml slim)

  # file types LiveReload may optimize refresh for
  compiled_exts = extensions.values.uniq
  watch(%r{public/.+\.(#{compiled_exts * '|'})})

  extensions.each do |ext, type|
    watch(%r{
          (?:app|vendor)
          (?:/assets/\w+/(?<path>[^.]+) # path+base without extension
           (?<ext>\.#{ext})) # matching extension (must be first encountered)
          (?:\.\w+|$) # other extensions
          }x) do |m|
      path = m[1]
      "/assets/#{path}.#{type}"
    end
  end

  # file needing a full reload of the page anyway
  watch(%r{app/views/.+\.(#{rails_view_exts * '|'})$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{config/locales/.+\.yml})
end

viewファイルの使い方によっては色々と設定があるようですが、初期設定のみでも概ね問題無く動作するようです。

ブラウザにLiveReloadエクステンションを追加してオートリロード

LiveReloadのBrowser Extensionを使用しているブラウザに導入し、Guardを起動*2します。

$guard
・
・
・
15:20:50 - INFO - LiveReload is waiting for a browser to connect.

ブラウザでLiveReloadのアイコンをクリックすると、アイコンの中心が赤くなりオートリロードが有効化されます。

f:id:b0npu:20170104184218p:plain

15:20:50 - INFO - LiveReload is waiting for a browser to connect.
・
・
・
[1] guard(main)> 15:21:56 - INFO - Browser connected.

オートリロードが有効化されている状態でviewファイルを変更すると、Guardが変更を検知し、LiveReloadがブラウザをリロードしてくれます٩( 'ω'

15:07:48 - INFO - Reloading browser: app/views/pages/index.html.erb

参考記事

*1:viewファイル等の変更を検知する旨の記述

*2:Guardが動いてないとブラウザにCould not connect to LiveReload serverが出ます