1

The problem: There is a list of enum values, say status. But every status needs more information per key than just passed or failed.

I'm looking for a more graceful solution to what I have now:

class Result < ActiveRecord::Base
  enum status: {passed: 0, failed: 1}, _default: :passed

  def icon
    Result.icons[status]
  end

  def text
    Result.texts[status]
  end

  def self.icons
    {passed: 'fa-check', failed: 'fa-cross'}.with_indifferent_access
  end

  def self.texts
    {passed: 'Your result has passed', failed: 'Your result has failed'}.with_indifferent_access
  end
end

So in the view I can do something like:

result = Result.new(status: :passed)
result.icon
result.text

I found a response here with a seemingly graceful solution with ActiveModel::Serializer, but it's not a working example. At least, I didn't get it to work in Rails 6.

My solution works okay, but when you start getting 5 attributes per status with 8 different statuses, it's getting quite tedious.

Maybe I should actually map it to a yaml file? Or use i18n?

Anyway, hope my question is clear, looking forward seeing your solutions to this.

Gijs P
  • 1,325
  • 12
  • 28

0 Answers0