renum

Get Version

1.0.1

Renum provides a readable but terse enum facility for Ruby. Enums are sometimes called object constants and are analogous to the type-safe enum pattern in Java, though obviously Ruby’s flexibility means there’s no such thing as type-safety.

Installing

sudo gem install renum

Demonstration of usage

Renum allows you to do things like this:

enum :Status, %w( NOT_STARTED IN_PROGRESS COMPLETE )

enum :Size do
  Small("Really really tiny")
  Medium("Sort of in the middle")
  Large("Quite big")

  attr_reader :description

  def init description
    @description = description
  end
end

module MyNamespace
  enum :FooValue, [ :Bar, :Baz, :Bat ]
end

Giving you something that satisfies this spec, plus a bit more:

describe "enum" do
  
  it "creates a class for the value type" do
    Status.class.should == Class
  end
  
  it "makes each value an instance of the value type" do
    Status::NOT_STARTED.class.should == Status
  end
  
  it "exposes array of values" do
    Status.values.should == [Status::NOT_STARTED, Status::IN_PROGRESS, Status::COMPLETE]
  end

  it "provides an alternative means of declaring values where extra information can be provided for initialization" do
    Size::Small.description.should == "Really really tiny"
  end
  
  it "enumerates over values" do
    Status.map {|s| s.name}.should == %w[NOT_STARTED IN_PROGRESS COMPLETE]
  end
  
  it "indexes values" do
    Status[2].should == Status::COMPLETE
  end
  
  it "provides index lookup on values" do
    Status::IN_PROGRESS.index.should == 1
  end
  
  it "provides a reasonable to_s for values" do
    Status::NOT_STARTED.to_s.should == "Status::NOT_STARTED"
  end
  
  it "makes values comparable" do
    Status::NOT_STARTED.should < Status::COMPLETE
  end
  
  it "allows enums to be nested in other modules or classes" do
    MyNamespace::FooValue::Bar.class.should == MyNamespace::FooValue
  end
  
end

License

This code is free to use under the terms of the MIT license.

Contact

Renum was created by John D. Hume. Comments are welcome. Send an email to duelin dot markers at gmail or contact me via my blog.

John D. Hume, 25th January 2008
Theme extended from Paul Battley