2014年11月1日土曜日

ruby moduleのまとめ その1

今更ながらrubyのmoduleのまとめ。
railsでのアプリ開発作成数も10を超えたので、もう一度足元から固めるための再学習メモ。
まさかこんなにrubyを長く使うようになるとは思わなかったなあ。chefを含めると、javaより利用してる時間長いです。

  • mac
  • ruby 2.0.0

Moduleとは

  • クラスと同じくメソッドを定義できる。
  • オブジェクトは作成できない
  • クラスメソッドが利用できない

Basic sample. Good Method.

 

    # coding: utf-8
    module Test

      def test
        puts 'test'
      end

      def self.test1
        puts 'test1'
      end

    end

    class ModukeTest
      include Test
    end

    modukeTest = ModukeTest.new
    modukeTest.test

    # test

    

Basic sample. Module instance is not able to create.

 

    test = Test.new
    test.test

    undefined method `new' for Test:Module (NoMethodError)

    

Basic sample. Module class method is not able to call.

 

    modukeTest = ModukeTest.new
    modukeTest.test1

    undefined method `test1' for # (NoMethodError)

    

使い方

  • include
  • extend

includeは上記の通り。extendはクラスメソッドしてモジュールを使えるようになる。

 

    # coding: utf-8
    module Test2

      def test2
        puts 'test2'
      end

    end

    class ModukeTest
      extend Test2
    end

    ModukeTest.test2

    # test2

    

色々なオープンソースを読んでいる人はわかると思いますが、extendはほとんど使われていない。80%くらいはinclude。よくある実装パターンは以下のような感じ。

 

    # coding: utf-8
    module Test

      def test
        puts 'test'
      end

      class Taro
        def introduce
          puts "may name is taro"
        end
      end

    end

    class ModukeTest
      include Test
    end

    taro = ModukeTest::Taro.new
    taro.introduce

    # may name is taro

    

railsなんかはこういったパターンでよく記述されていますね。

参考

この記事がお役にたちましたらシェアをお願いします

このエントリーをはてなブックマークに追加

0 件のコメント:

コメントを投稿

Related Posts Plugin for WordPress, Blogger...