Last active
August 29, 2015 14:19
-
-
Save camertron/1472e09500606c8da342 to your computer and use it in GitHub Desktop.
Provides a way to perform Ruby `require` statements at the file (really the block) level
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'find' | |
def provide(*requires, &block) | |
modules = requires.map do |req| | |
Module.new do | |
file_fragment = "#{req}.rb" | |
file = Find.find(*($: + ['.'])) do |f| | |
break f if f =~ /#{file_fragment}\z/ | |
end | |
module_eval(File.read("#{req}.rb")) | |
end | |
end | |
runner = Module.new | |
runner.module_exec(*modules, &block) | |
end | |
provide('my_class') do |my_class| | |
my_class::MyClass.new.print | |
end | |
MyClass # => should raise an error |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyClass | |
def print | |
puts 'hello world' | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment