1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

はじめに

実装をしているときにKlassという言葉がでてきました
それをきっかけにinclude周りで何をしているのかというところを理解したので軽くまとめていきます

問題

以下のようなコードがありました

sample_controller.rb
class Companies::SampleController < ApplicationController
  include Mixins::TestController
mixins/test_controller.rb
module Mixins::TestController
  module InstanceMethods
    def load_example


(省略)

  def self.included klass
    klass.send :include, InstanceMethods

    method_name = case klass.name
      when 'HogeContRoller' then :load_hoge
      when 'FugaController' then :load_fuga
      else :load_other
      end
    klass.before_filter method_name
  end
end

ここでsample_controllerMixins::TestControllerを読み込んでいるのはわかったのですが、そこで

def self.included klass

というのをやっておりそこからよくわからなくなりました

解決方法

def self.includedをすると、includesample_controller.rbで呼ばれた段階で、発火するようになります

そしてklassというのをがありますが、これは単に変数名でclassというのが予約後なために使っているものでした

klassにはincludeしたコントローラーの情報が渡ってくるため、klass.nameでコントローラー名で処理を変えることができます(whenの部分)

lass.send :include, InstanceMethods

この部分ですが、InstanceMethodsは上に書いてある

  module InstanceMethods
    def load_example

この部分を表しており、このモジュールをさらにincludeするようにしています。

klass.sendとしているのはプロテクトがされているためそれを突破するためにsendを利用して親であるsample_controllerInstanceMethodsを利用できるようにしていています(includeできるようにしています)

最後に

klass.before_filter method_name

をすることでコントローラーごとにbefore_filterするものを設定して、includeするだけで自動的にbefore_filterが行われるようになります

おわりに

なぜかコントローラーでbefore_filterしていないのにインスタンスが使えるよいうになっていて不思議に思いましたが、このようなからくりがありました

Ruby自体の仕組みを勉強することがなかったのですが、とても面白いなと感じました

1
1
0

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?