如何从不在 lib 目录下的 `gem` 中获取文件?
How to require file from `gem` which are not under `lib` directory?
我想为我的 rubocop custom cop. This gem has handy helpers defined 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
我被蒙蔽了双眼,我已经有了文件的路径,并且能够从中获取相关信息。
require 'pathname'
rubocop_path = Pathname.new(Gem.find_files('rubocop.rb').first).dirname
rubocop_path # => ...gems/rubocop-0.29.1/lib
require "#{rubocop_path}/../spec/support/cop_helper.rb"
我找到了一个我认为语法更优雅的解决方案:
gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"
我想为我的 rubocop custom cop. This gem has handy helpers defined 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
我被蒙蔽了双眼,我已经有了文件的路径,并且能够从中获取相关信息。
require 'pathname'
rubocop_path = Pathname.new(Gem.find_files('rubocop.rb').first).dirname
rubocop_path # => ...gems/rubocop-0.29.1/lib
require "#{rubocop_path}/../spec/support/cop_helper.rb"
我找到了一个我认为语法更优雅的解决方案:
gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"