lazy_const

A simple way of defining lazy evaluated, const-like instances of a class.

Installation

gem 'lazy_const'

Example

Basic Usage

class Group
  extend LazyConst
  lazy_const :EVERYONE do
    new("Everyone")
  end
  def initialize(name)
    @name = name
    @members = []
  end
  def add_user(user)
    @members << user
  end
end

class User; end

class Registrar
  def new_user(name)
    user = User.new(name)
    Group.EVERYONE.add_user(user)
    user
  end
end

Testing with RSpec

spec/spec_helper.rb:

require 'lazy_const/spec'

lib/some_class.rb:

class SomeClass
  extend LazyConst
  lazy_const :IMPORTANT_INSTACE do
    new(:hotness)
  end
end

spec/some_spec.rb:

describe MyClass do
  defines_const :IMPORTANT_INSTANCE
  # ...
end

Contributing to lazy_const

  • Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet.

  • Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it.

  • Fork the project.

  • Start a feature/bugfix branch.

  • Commit and push until you are happy with your contribution.

  • Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Please try not to mess with the Rakefile, version, or history. If you want to have your own version, or is otherwise necessary, that is fine, but please isolate to its own commit so I can cherry-pick around it.

Copyright © 2013 Ryan Graham. See LICENSE.txt for further details. (TL;DR: MIT license)