如何从`lib'目录下的`gem`文件中请求文件? [英] How to require file from `gem` which are not under `lib` directory?
本文介绍了如何从`lib'目录下的`gem`文件中请求文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的 rubocop 定制警察编写规格.该宝石在此处中定义了一些方便的助手.我要这个如何实现?
I want to write spec for my rubocop custom cop. This gem has handy helpers defined here. I want to require it. How to achieve what?
我尝试使用Gem.find_files
,这使我能够要求该gem中的任何文件,但只能在lib
目录下.
I've tried to use Gem.find_files
, and this gives me ability to require any file in that gem, but only under lib
directory.
例如:
# 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
The following describes why I need it. I have 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
推荐答案
我找到了一个我认为在语法上更优雅的解决方案:
I found a solution that I think is a little more syntactically elegant:
gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"
这篇关于如何从`lib'目录下的`gem`文件中请求文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文