rb_import
adds an import
method to your Ruby VM that lets you
load a file that exposes a Ruby object. As long as the imported file
doesn't pollute the VM's constants table (ie: defines a constant),
the caller won't see any unwanted objects.
module Foo
import '/path/to/bar.rb' # this file defines a Bar class
end
Bar.new # => NameError: uninitialized constant Bar
Foo::Bar.new # => #<Foo::Bar:0x0000000206a390>
RATIONALE
require
-ing/load
-ing a file in Ruby works by assigning constructs
(classes, modules, functions, etc.) to constants, so that they could be
reused in other parts of your app.
The problem is: a library that you don't own can use any name for any of its construct that could potentially collide with your own app's construct names. Naming is hard and, namespacing with modules doesn't even work (colliding module names, crazy meta-programming, etc.).
With rb_import
, simply return a Ruby object from your files and
import
them only in classes that will need those objects.
HOW TO VERIFY THE AUTHENTICITY OF THIS GEM
rb_import
is cryptographically signed. Please make sure the gem you install hasn’t been tampered with.
Add my public key (if you haven’t already) as a trusted certificate:
gem cert --add <(curl -Ls https://raw.githubusercontent.com/franckverrot/rb_import/master/certs/franckverrot.pem)
gem install rb_import -P MediumSecurity
The MediumSecurity trust profile will verify signed gems, but allow the installation of unsigned dependencies.
This is necessary because not all of rb_import
’ dependencies are necessarily signed, so we cannot use HighSecurity.
INSTALLATION
Add this line to your application's Gemfile:
gem 'rb_import'
And then execute:
$ bundle
Or install it yourself as:
$ gem install rb_import
Alternatively, you can spawn a pry
console right away by just running:
$ rake console
USAGE
Standard mode
# foo.rb
class Foo
def bar
"bar"
end
end
# bar.rb
module SomeModule
Foo = import './foo.rb'
end
Foo # => NameError: uninitialized constant Foo
SomeModule::Foo # => SomeModule::Foo
Anonymous objects
# foo.rb
Class.new do
def bar
"bar"
end
end
# bar.rb
foo = import './foo.rb'
puts foo.new.bar # => outputs "bar"
See files in the test
directory for examples.
Is it any good?
Yes.
Is It "Production Ready™"?
Yes. I guess.
Contributing
- Fork it ( https://github.com/franckverrot/rb_import/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