Skip to content

kjleitz/named_imports

Repository files navigation

NamedImports

Ever look at a class in a Ruby file and wonder "Where the hell did that come from?" If you have, then this might ease your pain.

Installation

Locally (to your application)

Add the gem to your application's Gemfile:

gem 'named_imports'

...and then run:

bundle install

Globally (to your system)

Alternatively, install it globally:

gem install named_imports

Usage

Require the named_imports gem in the entrypoint of your project, or at whatever point you know you will need named imports in Ruby files evaluated after that point:

require 'named_imports'

Then, use named imports:

# ~/your_project/lib/foo.rb

class Foo
  def self.some_bool
    true
  end
end
# ~/your_project/lib/example.rb

from 'foo', import { Foo }

Foo.some_bool
#=> true

You can also specify which constant to import, which provides some safety that you don't try to access constants you haven't specified:

# ~/your_project/lib/whatever/bar_and_baz.rb

class Bar
  def self.some_int
    123
  end
end

class Baz
  def self.some_str
    "hi"
  end
end
# ~/your_project/lib/example.rb

from './whatever/bar_and_baz', import { Baz }

Bar.some_int
#=> NameError (uninitialized constant Bar)

Baz.some_str
#=> "hi"

You can import multiple constants as well, by separating them with a semicolon in the import block:

# ~/your_project/lib/whatever/bam_and_bop.rb

class Bam
  def self.some_ary
    []
  end
end

class Bop
  def self.some_hash
    {}
  end
end
# ~/your_project/lib/example.rb

from 'whatever/bam_and_bop.rb', import { Bam; Bop }

Bam.some_ary
#=> []

Bop.some_hash
#=> {}

TODO

  • named constant imports
  • multiple constant imports
  • top-level function imports
  • namespace should not be polluted with non-specified constants (before the specified import is referenced/used)
  • namespace should not be polluted with non-specified constants (after the specified import is referenced/used)
  • namespace of child imports should not be polluted with constants from the parent's scope
  • cached imports so constants are always reused (as opposed to being redefined in a new anonymous module)

Development

Install dependencies

bin/setup

Run the tests

rake spec

Run the linter

rubocop

Create release

rake release

Contributing

Bug reports and pull requests for this project are welcome at its GitHub page. If you choose to contribute, please be nice so I don't have to run out of bubblegum, etc.

License

This project is open source, under the terms of the MIT license.

Code of Conduct

Everyone interacting in the NamedImports project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.

About

Named imports for Ruby

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published