LibInject

LibInject is a developer tool for injecting external dependencies into a Ruby file. More specifically, it finds require statements that point to files that aren’t in the standard library, expands those files, and drops the raw text into the original file.

Why would somebody do this instead of just using a plain old require statement? One reason might be because you want to write a one-file script that can also have external dependencies. I wrote LibInject for use with FeedBlender, which is intended as a one-file script aimed at Ruby newbies who might not even know how to install from .tar.gz files or from RubyGems. With LibInject, I can have external dependencies in FeedBlender, use a Rake task to inject those libraries into feedblender.rb, and then distribute the end result.

The project page for LibInject is http://rubyforge.org/projects/libinject/.

Example

Let’s say you’ve three files, a.rb, b.rb, and c.rb. a.rb requires b.rb and c.rb, and b.rb requires c.rb:

a.rb

require 'b'
require 'c'

class A; end

b.rb

require 'c'

class B; end

c.rb

class C; end

If you wanted to distribute a version of a.rb without any external dependencies, this is how you’d run LibInject:

require 'libinject'

puts LibInject.lib_inject( File.open( 'a.rb' ) )

# We could also pass LibInject.lib_inject a String, like so:
#   contents = File.open( 'a.rb' ) do |f| f.gets( nil ); end
#   puts LibInject.lib_inject( contents )

And this is what you’ll get:


# v---------v---------v---------v---------v---------v---------v---------v
# LibInject: begin 'b' library injection
# v---------v---------v---------v---------v---------v---------v---------v

# v---------v---------v---------v---------v---------v---------v---------v
# LibInject: begin 'c' library injection
# v---------v---------v---------v---------v---------v---------v---------v

class C; end

# ^---------^---------^---------^---------^---------^---------^---------^
# LibInject: end 'c' library injection
# ^---------^---------^---------^---------^---------^---------^---------^

class B; end

# ^---------^---------^---------^---------^---------^---------^---------^
# LibInject: end 'b' library injection
# ^---------^---------^---------^---------^---------^---------^---------^

class A; end

The code looks sort of messy, but now it’s all in one file.

About

LibInject is by Francis Hwang, and is available under the LGPL.


Last edited August 11, 2005