Created
March 9, 2016 20:03
-
-
Save hrom512/a84f3a1ed6946501d7e5 to your computer and use it in GitHub Desktop.
Ruby Enum type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Enum | |
| attr_reader :name | |
| attr_reader :value | |
| def initialize(name, value) | |
| @name = name | |
| @value = value | |
| end | |
| def to_i | |
| value.to_i | |
| end | |
| def to_sym | |
| name.to_sym | |
| end | |
| def to_s | |
| "<#{self.class.name}::#{name} value=#{value}>" | |
| end | |
| class << self | |
| def enum_value(name, value) | |
| @@values ||= [] | |
| raise 'Name already exists' if @@values.detect { |item| item.name == name } | |
| raise 'Value already exists' if @@values.detect { |item| item.value == value } | |
| new_value = new(name, value) | |
| @@values << new_value | |
| const_set(name, new_value) | |
| end | |
| def values | |
| @@values ||= [] | |
| end | |
| private | |
| def new(*args) | |
| super | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Country < Enum | |
| enum_value :RUSSIA, 1 | |
| enum_value :USA, 2 | |
| end | |
| puts Country::RUSSIA # <Country::RUSSIA value=1> | |
| p Country::RUSSIA.is_a?(Country) # true | |
| p Country.values | |
| country1 = Country::RUSSIA | |
| country2 = Country::RUSSIA | |
| p country1 == country2 # true | |
| # Errors | |
| class Country < Enum | |
| enum_value :RUSSIA, 1 | |
| enum_value :RUSSIA, 2 # raise | |
| end | |
| class Country < Enum | |
| enum_value :RUSSIA, 1 | |
| enum_value :USA, 1 # raise | |
| end | |
| Country.new(:China, 3) # raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment