lucascaton / enumerate_it

Enumerations for Ruby with some magic powers! 🎩

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Set a value to always be at the end of sorted list

moretoend opened this issue · comments

Sometimes, we need to keep a value at the end of a sorted list regardless its value.
For example, I have a list of movie types like ['comedy', 'romance', 'thiller', 'other'] and I need to keep the value 'other' always at the end even if I sort.

Hi @dfmoreto,

You can solve this using the following code:

class MovieType < EnumerateIt::Base
  associate_values(
    :comedy,
    :romance,
    :thiller,
    :other,
    :zzz
  )

  class << self
    alias original_list list

    def list
      original_list - [MovieType::OTHER] + [MovieType::OTHER]
    end
  end
end
MovieType.original_list
# [
#   "comedy",
#   "romance",
#   "thiller",
#   "other",
#   "zzz"
# ]
MovieType.list
# [
#   "comedy",
#   "romance",
#   "thiller",
#   "zzz",
#   "other"
# ]

Thanks a lot, @lucascaton !! 😄
So, before your answer, I forked and worked on a solution in the gem itself. It's working for me, but I'm having some problems when I try to execute RSpec. If you can help me with this, I can commit it.