LoginSignup
0
0

More than 1 year has passed since last update.

[Rails6] 5秒ごとにブラウザリロードをさせる + α

Last updated at Posted at 2021-11-11

手順

  1. 自動更新用のJavascriptを用意する
  2. 自動更新したいviewで読み込む

これだけの記事です。

やりかた: 自動更新用のJavascriptを用意する

以下のJavascriptを用意しておきます。

app/javascript/packs/autoreload.js
const interval = setInterval('location.reload()', 5000)
$(document).on('turbolinks:before-cache turbolinks:before-render', () => clearTimeout(interval))

やりかた: 自動更新したいviewで読み込む

app/views/**/*.erb.html
<%= javascript_pack_tag 'autoreload' %>

以上です。
とはいえ、「流石にreloadとか無いやろ...」という方には、以下の応用編も御覧ください。

応用編手順

  1. controllerでhtml以外のformatに対応させる(ajaxリクエストに対応)
  2. *.html.erb の一部をパーシャルに切り出す
  3. *.js.erb を用意
  4. autoreload.js を書き換える

やりかた: controllerでhtml以外のformatに対応させる(ajaxリクエストに対応)

app/controllers/**/*_controller.rb
...
def index
  ...
  @records = Record.all
  respond_to do |format|
    format.js
    format.html
  end
end
...

やりかた: *.html.erb の一部をパーシャルに切り出す

app/views/**/index.html.erb
<div id="records">
  <%= render 'record' %>
</div>
app/views/**/_record.html.erb
<%= record.name %>

やりかた: *.js.erb を用意

app/views/**/index.js.erb
$("#records").empty();
$("#records").append("<%= escape_javascript(render @records) %>");

やりかた: autoreload.js を書き換える

app/javascript/packs/autoreload.js
const milliseconds = 5000
const sync = () => {
  $.ajax({
    type: 'GET',
    url: $(location).attr('href'),
    dataType: 'script'
  })
}
const interval = setInterval(sync, milliseconds)
$(document).on('turbolinks:before-cache turbolinks:before-render', () => clearTimeout(interval))
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0