It is rather a matter of style, I wonder what other people are doing.
Say I have a field in my database called a “status” for a blog post. And I want it to have several possible meanings, such as "draft", "waiting for review" and "sent", as an example.
Obviously, we don’t want to “hard code” these magic values every time, it would not be DRY.
So sometimes I do something like this:
class Post STATUS = { :draft => "draft", :awaiting_review => "awaiting review", :posted => "posted" } ... end
Then I can write code that references it later as STATUS[:draft] or Post::STATUS[:draft] , etc.
This works fine, but there are a few things that I don't like.
- If you have a typo and something like
STATUS[:something_that_does_not_exist] is called, it won’t cause an error, it just returns zero and can finish setting it up in the database, etc., before you notice the error - It doesn’t look clean or ruby to write things like
if some_var == Post::STATUS[:draft] ...
I don’t know, something tells me that there is a better way, but I just wanted to see what other people are doing. Thank you
ruby ruby-on-rails
Brian armstrong
source share