Skip to content

jah2488/namespacing

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Namespacing Build Status Code Climate Dependency Status

Gem Version

Namespacing adds namespaces to Ruby by taking inspiration from how Clojure handles its namespaces. It is primarly a simplification of the existing module syntax. Great for deeply nested modules or for attempting a more functional approach to writing Ruby code. I wrote a blog post about the inspiration and process of creating this code.

Installation

Add this line to your application's Gemfile:

gem 'namespacing'

And then execute:

$ bundle

Or install it yourself as:

$ gem install namespacing

Usage

Simply require the gem and decide the scope you'd like to have it at. To use it in the global scope, you'll want to extend Object

require 'namespacing'

class Object
  include Namespacing
end

ns 'my_app.dojo.util.options' do
  def names
    %w(on off maybe 7 42 tuesday)
  end
end

Then this code can be called with:

MyApp::Dojo::Util::Options.names 
#=> ['on', 'off', 'maybe', '7', '42', 'tuesday']

An optional delimiter can be passed in when defining your namespace. (I would recommend against using _ as that delimiter.)

ns 'github|repositories|settings', '|' do
  def destroy!
    confirm
  end
end

Github::Repositories::Settings.destroy!

Gotchas

There is at least one known and unexpected side effect.

Defining constants inside the ns block does not work as expected. Any constants set will be at the top level namespace.

ns 'rails.active_support.version' do
  VERSION = '1.0.0'
end

Rails::ActiveSupport::Version #=> NameError: uninitialized constant Kernel::Rails::ActiveSupport::Version::VERSION
VERSION #=> '1.0.0'

There are currently two ways to define constants in the proper scoping to avoid this issue.

Define the full scope of the constant

ns 'rails.active.version' do
  Rails::Active::Version::MAJOR = 1
end

Rails::Active::Version::MAJOR #=> 1

Use const_set

ns 'rails.support.version' do
  const_set(:MAJOR, 1)
end

Rails::Support::Version::MAJOR #=> 1

Contributing

  1. Fork it ( http://github.com//namespacing/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

About

Clojure like namespaces for Ruby

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages