Pros and cons of using callbacks for domain logic in Rails

前端 未结 6 577
春和景丽
春和景丽 2021-01-30 04:50

What do you see as the pros and cons of using callbacks for domain logic? (I\'m talking in the context of Rails and/or Ruby projects.)

To start the discussion, I wanted

6条回答
  •  孤街浪徒
    2021-01-30 05:18

    This question right here ( Ignore the validation failures in rspec ) is an excellent reason why to not put logic in your callbacks: Testability.

    Your code can have a tendency to develop many dependencies over time, where you start adding unless Rails.test? into your methods.

    I recommend only keeping formatting logic in your before_validation callback, and moving things that touch multiple classes out into a Service object.

    So in your case, I would move the normalize_card_number to a before_validation, and then you can validate that the card number is normalized.

    But if you needed to go off and create a PaymentProfile somewhere, I would do that in another service workflow object:

    class CreatesCustomer
      def create(new_customer_object)
        return new_customer_object unless new_customer_object.valid?
        ActiveRecord::Base.transaction do
          new_customer_object.save!
          PaymentProfile.create!(new_customer_object)
        end
        new_customer_object
      end
    end
    

    You could then easily test certain conditions, such as if it is not-valid, if the save doesn't happen, or if the payment gateway throws an exception.

提交回复
热议问题