/
conversion.rb
75 lines (67 loc) · 1.84 KB
/
conversion.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
module ClassyEnum
module Conversion
# Returns an integer representing the order that this element was defined in.
# Also used internally for sorting.
#
# ==== Example
# # Create an Enum with some elements
# class Priority < ClassyEnum::Base
# end
#
# class Priority::Low < Priority; end
# class Priority::Medium < Priority; end
# class Priority::High < Priority; end
#
# @priority = Priority::Medium.new
# @priority.to_i # => 2
def to_i
self.class.instance_variable_get('@index')
end
alias :index :to_i
# Returns the name or string corresponding to element
#
# ==== Example
# # Create an Enum with some elements
# class Priority < ClassyEnum::Base
# end
#
# class Priority::Low < Priority; end
# class Priority::Medium < Priority; end
# class Priority::High < Priority; end
#
# @priority = Priority::Low.new
# @priority.to_s # => 'low'
def to_s
option.to_s
end
# Returns a Symbol corresponding to a string representation of element,
# creating the symbol if it did not previously exist
#
# ==== Example
# # Create an Enum with some elements
# class Priority < ClassyEnum::Base
# end
#
# class Priority::Low < Priority; end
# class Priority::Medium < Priority; end
# class Priority::High < Priority; end
#
# @priority = Priority::Low.new
# @priority.to_sym # => :low
def to_sym
to_s.to_sym
end
# Overrides as_json to remove owner reference recursion issues
def as_json(options=nil)
return to_s unless serialize_as_json
json = super(options)
json.delete('owner')
json.delete('serialize_as_json')
json
end
private
def option
self.class.instance_variable_get(:@option)
end
end
end