0

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?

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.