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.
Add this line to your application's Gemfile:
And then execute:
Or install it yourself as:
$ gem install namespacing
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
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!
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
ns 'rails.support.version' do const_set(:MAJOR, 1) end Rails::Support::Version::MAJOR #=> 1
- Fork it ( http://github.com//namespacing/fork )
- Create your feature branch (
git checkout -b my-new-feature)
- Commit your changes (
git commit -am 'Add some feature')
- Push to the branch (
git push origin my-new-feature)
- Create new Pull Request