简体   繁体   中英

Ruby loop through instance methods and run them

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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