#author("2017-05-08T13:46:28+09:00","default:wikiwriter","wikiwriter")
&tag(Rails/オブザーバー);
*目次 [#t1ce7024]
#contents
*関連ページ [#t5c5f91e]
*参考情報 [#ucdbad7f]

*基本 [#g9055b5f]
-モデルやコントローラーでイベントが発生したタイミングで何かの処理を実行したいときに使用する。
-Rails 4.0からは本体から切りはなされたので、[[GitHub - rails/rails-observers: Rails observer (removed from core in Rails 4.0):https://github.com/rails/rails-observers]]を使わないと行けないかもしれない。
-ただし2017/05/08(月)現在、rails-observersはRails 5では動かず、[[Railsアプリを66%スピードアップ ― Railsキャッシュの完全ガイド | プログラミング | POSTD:http://postd.cc/the-complete-guide-to-rails-caching/]]のように、キーベースのキャッシュを使う方法に切り替えたほうがよいのかも。

*Rails::Observersの基本 [#c9af0017]

**Active Record Observer [#m6458cc1]
-未使用なので省略。

**Action Controller Sweeper [#jd2ca30d]
-コントローラーで保存や更新実行時にキャッシュをクリアしたいときに使う。
-まずActionController::Caching::Sweeperを継承したSweeperクラスを作成する。
#pre{{
class ListSweeper < ActionController::Caching::Sweeper
  observe List, Item #監視したいモデル(この場合、List、Itemモデルが保存された後処理が走る)

  def after_save(record)
    list = record.is_a?(List) ? record : record.list
    expire_page(controller: "lists", action: %w( show public feed ), id: list.id)
    expire_action(controller: "lists", action: "all")
    list.shares.each { |share| expire_page(controller: "lists", action: "show", id: share.url_key) }
  end
end
}}
-コントローラーに設定する。
#pre{{
class ListsController < ApplicationController
  caches_action :index, :show, :public, :feed
  cache_sweeper :list_sweeper, only: [ :edit, :destroy, :share ]
end
}}
-index、show、public、feedはキャッシュされ、edit、destroy、shareが呼ばれた場合キャッシュがクリアされる。


トップ   編集 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS