如何从“gem”中获取不在“lib”目录下的文件?

2023-11-27

我想为我的rubocop定制警察。这个 gem 定义了方便的助手here。我想要求它。如何实现什么?

我尝试过使用Gem.find_files,这使我能够要求该 gem 中的任何文件,但仅限于lib目录。

例如:

# this requires ...gems/rubocop-0.29.1/lib/rubocop/formatter/formatter_set.rb
require Gem.find_files('rubocop/formatter/formatter_set.rb').first
# but I need ...gems/rubocop-0.29.1/spec/support/cop_helper.rb

下面描述了我为什么需要它。我有spec/rubocop/my_custom_cop_spec.rb

require 'spec_helper'
require ? # What I should I write?

RSpec.describe RuboCop::Cop::Style::MyCustomCop do
  it 'some test' do
    inspect_source(cop, 'method(arg1, arg2)') # This helper I want to use from rubocop spec helpers
  end
end

当我尝试简单的要求时:

require 'rubocop/spec/support/cop_helper'

我收到错误:

/home/user/.gem/ruby/2.0.0/gems/activesupport-4.2.0/lib/active_support/dependencies.rb:274
:in `require': cannot load such file -- rubocop/spec/support/cop_helper

我找到了一个我认为语法上更优雅的解决方案:

gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从“gem”中获取不在“lib”目录下的文件? 的相关文章

随机推荐