Skip to content

Instantly share code, notes, and snippets.

@bgreenlee
Created February 5, 2009 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bgreenlee/59103 to your computer and use it in GitHub Desktop.
Save bgreenlee/59103 to your computer and use it in GitHub Desktop.
# base for "smart" constant classes
class OptionSet
def self.[](id)
if id.is_a?(Fixnum)
return local_constants.find {|c| id == const_get(c)}
else
return const_get(id.upcase)
end
end
def self.options_for_select
local_constants.map {|c| [c.titlecase, const_get(c)]}.sort_by {|c| c[1]}
end
private
def self.local_constants
constants - superclass.constants
end
end
class User
# values for status column
class Status < OptionSet
ACTIVE = 0
DELETED = 1
PANTS = 2
end
end
>User::Status::PANTS
# => 2
>User::Status["Pants"]
# => 2
>User::Status[2]
# => "PANTS"
>User::Status.options_for_select
# => [["Active", 0], ["Deleted", 1], ["Pants", 2]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment