0

我有以下课程:

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

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

4

1 回答 1

2

有可能的:

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
于 2013-06-07T02:06:00.537 回答