Search code examples
ruby-on-railsbefore-filter

Rails before_filter with parameter from methods


I have a series of methods, with similar structure and sharing a common parameter:

  • def deposit (amount)

  • def transfer (amount, to)

  • def refund (amount)

I would like to check if the balance is greater than amount before calling these actions. Otherwise, I have to repeat check_balance in every method

Is there a way I can user before_filter to call check_balance(amount) with amount passed from the methods I want to apply to?

Thank you.


Solution

  • It seems you're not really looking for some before_filter since you want to pass arguments (unless arguments are taken directly from params but then the syntax would be wrong).

    You should create a new method in you controller

    private
    def check_balance amount
      # whatever you need
    end
    

    An call this as you need in your action

    def index
      #some code
      check_balance(current_amount)
      #other code
    end
    

    But you're sure this kind of code isn't related directly to the model? If so, it should be refactored inside the model itself.