Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/mdub/another_enum
Support for defining enumerated types in Ruby
https://github.com/mdub/another_enum
Last synced: about 2 months ago
JSON representation
Support for defining enumerated types in Ruby
- Host: GitHub
- URL: https://github.com/mdub/another_enum
- Owner: mdub
- License: mit
- Created: 2013-11-17T10:46:48.000Z (about 11 years ago)
- Default Branch: master
- Last Pushed: 2020-04-21T01:01:37.000Z (over 4 years ago)
- Last Synced: 2024-04-23T22:19:24.862Z (8 months ago)
- Language: Ruby
- Size: 6.84 KB
- Stars: 0
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# AnotherEnum
`AnotherEnum` provides support for defining enumerated types in Ruby. An enumerated type (or "enum") is a class with a finite (and usually small) set of predefined, named values.
## Usage
Define a enumerated type by subclassing AnotherEnum. Use `.define` to define allowed values:
require 'another_enum'
class Colour < AnotherEnum
define :red
define :green
define :blue
endwhich become globally available:
Colour.red
Colour.green
Colour.blueEach value gets a code:
Colour.red.code #=> "red"
which can be used later to lookup the value:
Colour["red"] #=> Colour.red
It's easy to get all the defined values, or all the codes:
Colour.all #=> [Colour.red, Colour.green, Colour.blue]
Colour.codes #=> ["red", "green", "blue"]`AnotherEnum.define` takes a block, which can be used to define methods on the singleton values, e.g.
class CreditCardType < AnotherEnum
define :visa do
def surcharge
0.08
endend
define :amex do
def surcharge
0.16
endend
end
There's even a shortcut for defining methods that return predefined values:
class CreditCardType < AnotherEnum
define :visa do
hardcode name: "Visa"
hardcode surcharge: 0.08
enddefine :amex do
hardcode name: "American Express"
hardcode surcharge: 0.16
endend
## Contributing
It's on GitHub. You know what to do.