Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Require returns an array instead of a boolean

Tags:

ruby

require

According to the documentation for Kernel#require the method returns a boolean value. I noticed in a IRB session however that for some files require returns an array.

ruby-1.8.7-p330 :001 > require 'net/http'
=> true 
ruby-1.8.7-p330 :002 > require 'date'
=> true 
ruby-1.8.7-p330 :003 > require 'lib/data_provider'
=> ["DataProviders"] 

The returned array contains the name of a module defined in data_provider.rb:

module DataProviders
  module Cached
    class Foo
    # ...
    end
  end

  class Foo
  # ...
  end
end

Is this a sign of me doing something wrong or some undocumented behavior of require?

like image 318
FilipK Avatar asked Jun 13 '11 09:06

FilipK


1 Answers

I can't reproduce it too. But it's possible that some gem overrides Kernel#require:

module Kernel
  alias_method :old_require, :require
  def require(str)
    old_modules = []
    ObjectSpace.each_object(Module) {|m| old_modules << m }

    old_require(str)

    new_modules = []
    ObjectSpace.each_object(Module) {|m| new_modules << m unless old_modules.include?(m) }
    new_modules
  end
end

and when you try to require

module DataProviders
  module Cached
    class Foo
    end
  end
  class Foo
  end
end

you will get

irb(main):012:0> require 'data_provider'
=> [DataProviders::Cached::Foo, DataProviders::Foo, DataProviders::Cached, DataProviders]
like image 174
Vasiliy Ermolovich Avatar answered Oct 28 '22 09:10

Vasiliy Ermolovich