Thursday, March 9, 2017

Require All Ruby Files Under a File in Vanilla Ruby Without Dependencies

If you want to require all Ruby files under a particular file in a vanilla Ruby project, you can do something like:


  def self.auto_require_all
    @@pathnames_required_successfully ||= {}
    @@require_attempts ||= 0
    requires_failed = {}
    Dir["#{File.dirname(__FILE__)}/**/*.rb"].each do |pathname|
      begin
        if !@@pathnames_required_successfully[pathname] && pathname.end_with?('.rb')
          pathname_to_require = pathname.chomp('.rb')
          require(pathname_to_require)
          @@pathnames_required_successfully[pathname] = ''
        end
      rescue NameError => e
        # optionally uncomment this to show which require failed immediately
        #puts "request #{pathname.inspect} failed: #{e.message}\n#{e.backtrace.join("\n")}"
        requires_failed["request #{pathname.inspect} failed: #{e.message}\n#{e.backtrace.join("\n")}"] = ''
        @@require_attempts += 1
      end
    end

    if requires_failed.length > 0
      if @@require_attempts > 1000
        raise requires_failed.keys.join("\n")
      else
        require_tools
      end
    end
  end
  self.auto_require_all

There are gems out there to do this, but it's pretty simple to implement and you can reduce dependencies on other gems.

No comments: