繁体   English   中英

Ruby循环实例方法并运行它们

[英]Ruby loop through instance methods and run them

我有以下课程:

module StatCalculators
  class Passing
    def initialize(user_id, game_id)
      @user_id = user_id
      @game_id = game_id
    end

    def save_completion_percentage
      completions = StatType.find_by_name("Completions").stats.where(athlete_id: @user_id).sum(:float_value)
      attempts = StatType.find_by_name("Pass Attempts").stats.where(athlete_id: @user_id).sum(:float_value)
      value = completions/attempts
      stat = Stat.new(value: value, game_id: @game_id, athlete_id: @user_id, float_value: value)
      stat.save(validate: false)
    end
  end
end

上面的类有可能有更多的方法需要运行而不必单独调用每个方法...有没有办法在initialize方法中运行所有实例方法?

有可能的:

module StatCalculators
  class Passing
    def initialize(user_id, game_id)
      @user_id = user_id
      @game_id = game_id

      klass = self.class
      klass.instance_methods(false).each do |method|
        klass.instance_method(method).bind(self).call
      end
    end

    ...

  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM