LoginSignup
0
0

More than 5 years have passed since last update.

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

Last updated at Posted at 2017-09-11

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

0
0
2

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