我正在创建一个简单的 Ruby Gem,它目前按照制作自己的 gem文档中的示例进行布局。
我的目录结构:
.
├── Gemfile
├── Gemfile.lock
├── lib
│ ├── go_run
│ │ ├── parser.rb
│ │ └── runner.rb
│ └── go_run.rb
└── spec
├── go_run_spec.rb
├── parser_spec.rb
└── runner_spec.rb
我最初Runner
在lib/go_run/runner.rb
just 中调用了该类Runner
,但现在,根据记录的示例,我将其命名为GoRun::Runner
. 该代码有效。问题是现在运行bundle exec rspec spec/parser_spec.rb
没有。它失败了:
/home/smurf/dev/ruby/go_run/lib/go_run/parser.rb:3:in `<top (required)>': uninitialized constant GoRun (NameError)
该文件的第三行是:
class GoRun::Parser
我正在使用require
库代码。spec/parser_spec.rb
require 'go_run/parser'
我尝试将它包含在 中require_relative '../lib/go_run/parser'
,但这产生了相同的错误。
有谁知道我做错了什么?
更新:我已经在这个分支上上传了完整的代码:https : //github.com/henrytk/go_run/tree/stackoverflow-43155117
问题lib/go_run/parser.rb
出在测试本身而不是测试本身。每当 Ruby 找到GoRun::Parser
定义时,它就会GoRun
在常量查找表中查找,但它不会在那里,因此程序退出并出现错误。
请注意,lib/go_run.rb
用作入口点也不起作用,因为在定义之前是go_run/parser.rb
必需的。 GoRun
部分问题是同时GoRun
用作项目级命名空间和入口点。class
您应该考虑使用几个习语来解决这种情况:
制作GoRun
一个顶级module
,纯粹用于命名空间。移动生活在目前的逻辑放到了自己的逻辑class
,例如go_run/cli.rb
。go_run.rb
然后将该文件保存为一种清单文件,它需要项目的类。
使用嵌套的module
- andclass
语法。这将定义外部模块(如果尚未定义)。
使用使用spec_helper.rb
, 引导项目的文件require 'go_run'
,以确保在运行测试之前正确加载所有内容。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句