Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

a readable but terse enum for Ruby

branch: master
README.textile

renum

Build Status

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.

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

Rails Integration

[This feature is brand new and should be considered beta-quality.]

Use Renum::NameSerializer with ActiveRecord’s `serialize` method to store enum values as strings.

class Vehicle < ActiveRecord::Base
  enum :Status do
    New()
    Used()
    Salvage(true)

    def init(warn = false)
      @warn = warn
    end

    def requires_warning_buyer?
      @warn
    end
  end

  serialize :status, Renum::NameSerializer.new(Status)

end

v = Vehicle.create! :status => Vehicle::Status::New
# Now the database has the string "New",
# but your record object exposes the Status object:
v.status.requires_warning_buyer?          # => false

v.update_attribute :status, Vehicle::Status::Salvage
# Now the database has the string "Salvage".
v.status.requires_warning_buyer?          # => true

# Note that if you assign a String, the value will remain a String until you save.
v.status = "Used"
v.status.requires_warning_buyer?          # => raises NoMethodError

Before ActiveRecord had such flexible serialization support, I wrote a Rails plugin called constantize_attribute that would store the fully qualified name of your value in a string column. It hasn’t been tested against a recent version of Rails, but it should still work. It’s not packaged as a gem, so if you want to use it, I’d recommend you just grab the code. (It’s quite tiny.)

class Vehicle < ActiveRecord::Base
  enum :Status do
    New()
    Used()
    Salvage(true)

    def init(warn = false)
      @warn = warn
    end

    def requires_warning_buyer?
      @warn
    end
  end

  constantize_attribute :status

end

v = Vehicle.create! :status => Vehicle::Status::New
# Now the database has the string "Vehicle::Status::New",
# but your record object exposes the Status object:
v.status.requires_warning_buyer?          # => false

v.update_attribute :status, Vehicle::Status::Salvage
# Now the database has the string "Vehicle::Status::Salvage".
v.status.requires_warning_buyer?          # => true

# Since constantize_attribute also accepts strings, it's easy
# to use enumerated values with forms.
v.status = "Vehicle::Status::Used"
v.status.requires_warning_buyer?          # => false

License

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

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
“Software”), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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.

Something went wrong with that request. Please try again.