Skip to content

yyandrew/require_problem

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commits
 
 
 
 
 
 
 
 

Repository files navigation

不同gem包的同文件名加载问题

报错场景

这个项目包含两个gem包foo、bar,它们的lib目录都有一个hello.rb文件。

  1. 运行bundle exec irb进入irb环境
  2. 运行require 'hello' 加载hello.rb文件
  3. 运行Foo::Hello.new.say_hello。输出hello from foo,这是我们想要的结果。
  4. 运行Bar::Hello.new.say_hello。报错了,这不是我们想要的结果,为什么?

报错原因

在irb运行$LOAD_PATH可以看到自动加载目录列表包含了require_problem/gems/bar/librequire_problem/gems/foo/lib。从加载顺序可以看到foo/lib覆盖了bar/lib,所以require 'hello'加载的是foo/lib/hello.rb文件

解决方法

将两个gem包的hello.rb分别移到foo/lib/foo/hello.rbbar/lib/bar/hello.rb,然后使用require 'foo/hello'require 'bar/hello'加载对应的hello.rb文件。再次在irb里运行Foo::Hello.new.say_helloBar::Hello.new.say_hello输出了正确的结果。

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published