Skip to content

Instantly share code, notes, and snippets.

@mnelson
Created December 28, 2010 21:33
Show Gist options
  • Save mnelson/757756 to your computer and use it in GitHub Desktop.
Save mnelson/757756 to your computer and use it in GitHub Desktop.
Allows you to access static values by human names. eg. Browser::Firefox => 5
class EnumerableClass
UNKNOWN_ENUMERABLE = "Unknown"
class << self
def all
self.to_a.collect{|g| g[1]}
end
def add_item(key,value)
@hash ||= {}
@hash[key]=value
end
def const_missing(key)
@hash[key]
end
def each
to_a.each{|arr| yield(arr[0], arr[1])}
end
def to_a
@hash.to_a.sort{|a,b| a[1].nil? && 1 || b[1].nil? && -1 || a[1] <=> b[1]}
end
def for_select
sel = []
@hash.values.each do |val|
sel << [pretty_print(val), val]
end
sel.sort{|a,b| a[1].nil? && -1 || b[1].nil? && 1 || a[1] <=> b[1]}
end
def pretty_print(symbol_or_value)
symbol = self[symbol_or_value].to_s
if symbol =~ /_\d{1,}$/
arr = symbol.split('_')
"#{arr.last} #{arr[0...arr.length-1].join(' ')}"
else
symbol.underscore.humanize
end
end
def [](value)
if value.class == String && @hash.keys.include?(value.to_sym)
@hash[value.to_sym]
else
matches = @hash.to_a.select{|a| a[1] == value}.first
matches ? matches.first.to_s : UNKNOWN_ENUMERABLE
end
end
end
end
class Gender < EnumerableClass; end
class Browser < EnumerableClass; end
class EventType < EnumerableClass; end
class Source < EnumerableClass; end
class ShareType < EnumerableClass; end
Gender.add_item :Male, 0
Gender.add_item :Female, 1
Browser.add_item :Unknown, 0
Browser.add_item :IE9, 1
Browser.add_item :IE8, 2
Browser.add_item :IE7, 3
Browser.add_item :IE6, 4
Browser.add_item :Firefox, 5
Browser.add_item :Safari, 6
Browser.add_item :Chrome, 7
Browser.add_item :Opera, 8
Browser.add_item :Iphone, 9
Browser.add_item :Android, 10
Browser.add_item :Blackberry, 11
EventType.add_item :Login, 1
EventType.add_item :Registration, 2
EventType.add_item :Purchase, 3
EventType.add_item :Share, 4
EventType.add_item :Redeem, 5
EventType.add_item :Question, 6
EventType.add_item :Application, 7
Source.add_item :GS, 0
Source.add_item :AG, 1
Source.add_item :FB, 2
Source.add_item :TW, 3
ShareType.add_item :PerReferral, 0
ShareType.add_item :Avalanche, 1
ShareType.add_item :EarlyBird, 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment