Ruby Style Question: storing hash constant with different possible values
ruby, ruby-on-rails
Solution
This is a common problem. Consider something like this:
class Post < ActiveRecord::Base
validates_inclusion_of :status, :in => [:draft, :awaiting_review, :posted]
def status
read_attribute(:status).to_sym
end
def status= (value)
write_attribute(:status, value.to_s)
end
end
You can use a third-party ActiveRecord plugin called symbolize to make this even easier:
class Post < ActiveRecord::Base
symbolize :status
end
Problem
This is more of a style question, I'm wondering what other people do. Let's say I have a field in my database called "status" for a blog post. And I want it to have several possible values, like "draft", "awaiting review", and "posted", just as an example. Obviously we don't want to "hard code" in these magic values each time, that wouldn't be DRY. So what I sometimes do is something like this: ``` class Post STATUS = { :draft => "draft", :awaiting_review => "awaiting review", :posted => "posted" } ... end ``` Then I can write code referring to it later as `STATUS[:draft]` or `Post::STATUS[:draft]` etc. This works ok, but there are a few things I don't like about it. - If you have a typo and call something like `STATUS[:something_that_does_not_exist]` it won't throw an error, it just returns nil, and may end up setting this in the database, etc before you ever notice a bug - It doesn't look clean or ruby-ish to write stuff like `if some_var == Post::STATUS[:draft]` ... I dunno, something tells me there is a better way, but just wanted to see what other people do. Thanks!