Skip to content

Instantly share code, notes, and snippets.

@mvalipour
Last active January 3, 2019 01:03
Show Gist options
  • Save mvalipour/5106d91de8bb156d3e550054d9fe4586 to your computer and use it in GitHub Desktop.
Save mvalipour/5106d91de8bb156d3e550054d9fe4586 to your computer and use it in GitHub Desktop.
A minimalistic enums implementation in ruby

Usage

class MyClass
  include Enums
  
  enum foo: [:x, :y]
end
me = MyClass.new
me.foo   # nil
me.foo_i # nil
me.foo = :y
me.foo   # :y
me.foo_i # 1
me.foo = :z # error!
module Enums
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def enum(maps)
maps.each do |key, options|
attr_reader "#{key}_i"
define_method("#{key}=") do |value|
unless (index = options.find_index(value))
raise "Invalid value '#{value}' for #{key}"
end
instance_variable_set("@#{key}_i", index)
end
define_method(key) do
return unless (index = send("#{key}_i"))
options[index]
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment