DRYing up conditional validation in a Ruby class

dry, ruby, ruby-on-rails

Solution

`:inclusion :in` accepts a lambda itself:

validates :status, inclusion: { in: lambda { |o| STATUSES[o.category.to_sym] } }

Documentation: http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of

Problem

How can I dry up my validation code? I have a `Discussion` model that has a a `category` and `status` fields. The status value depends on the category value. A discussion where `category == 'question'` can only have a status in `STATUSES[:question]`, for example. ``` STATUSES = { question: %w[answered], suggestion: %w[pending planned started completed declined], problem: %w[started solved] } validates :status, allow_blank: true, inclusion: { in: STATUSES[:question] }, if: lambda { self.category == 'question' } validates :status, allow_blank: true, inclusion: { in: STATUSES[:suggestion] }, if: lambda { self.category == 'suggestion' } validates :status, allow_blank: true, inclusion: { in: STATUSES[:problem] }, if: lambda { self.category == 'problem' } ``` I'm using Rails 3.

Original source