jignesh jignesh - 4 months ago 16
Ruby Question

Ruby Constant Lookup

This is probably a simple question, but I'm trying to lookup the constant name in Ruby from the value. For example:

class Xyz < ActiveRecord::Base
ACTIVE = 1
PENDING = 2
CANCELED = 3
SENT = 4
SUSPENDED = 5
end


I have a status of
1
in my db. I want to retrieve
ACTIVE
based on this so that I can display it in a view.

What's a good way to do that?

Answer
class Module
  def constant_by_value( val )
    constants.find{ |name| const_get(name)==val }
  end
end

class Xyz
  ACTIVE    = 1
  PENDING   = 2
  CANCELED  = 3
  SENT      = 4
  SUSPENDED = 5
end

p Xyz.constant_by_value(4)
#=> :SENT

However, I wouldn't do this: using programmatic names as values for a view seems like a bad idea. You're likely to run into a situation where you want to change the display name (maybe "suspended" should be shown as "on hold") and then you have to refactor your code.

I'd put a mapping in your view or controller, using the constants from the model:

status_name = {
  Xyz::ACTIVE    => "Active",
  Xyz::PENDING   => "Pending", 
  Xyz::CANCELED  => "Canceled", 
  Xyz::SENT      => "Away!", 
  Xyz::Suspended => "On Hold"
}
@status = status_name[@xyz.status_id]