سؤال

I have the following class:

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

The class above has the potential to have a lot more methods that need to be run without having to call each method individually... is there a way to run all instance methods in the initialize method?

هل كانت مفيدة؟

المحلول

It is possible:

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 مع الإسناد
لا تنتمي إلى StackOverflow
scroll top