Ruby

rubyのinclude moduleでパラメータを渡す

More than 1 year has passed since last update.

sample1

module Examples
  module MixInSay1
    def self.included(base)
      base.define_singleton_method :define_greeter do |method_name, output|
        # A dynamically defined method that dynamically defines another
        # method. What a crazy world!
        define_method(method_name) { output }
      end
    end

    def say
      # puts :test
      puts config[:info]
    end
  end


  class MyIncludeParam1
    include MixInSay1
    # define_greeter :config, 'Good morning, '
    define_greeter :config, {test: '1', info: 'good.'}

  end
end
Examples::MyIncludeParam1.new.say

感想

なんかinclude MixInSay1と
define_greeterの関係が嫌。

sample2

module Examples
  class MixInSay3 < Module
    def initialize(config)
      @config = config
      define_methods
      freeze
    end

    private

    def define_methods
      define_say_method
    end

    # sayメソッド追加
    def define_say_method
      config = @config
      define_method(:say) do | |
        puts config[:info]
      end
    end

  end


  class MyIncludeParam3
    include MixInSay3.new({test: '1', info: 'good.'})
  end
end
Examples::MyIncludeParam3.new.say

感想

sayの補完が効かない。
module名でのミス。

まとめ

まだruby初めて3ヶ月なので暖かく見てほしい・・・
- MyIncludeParam3の書き方でMixInSay1の補完ができるようなのが理想。
- そもそもrubyでこういう書き方するんじゃねぇ。

参考URL