【问题标题】:How to require file from `gem` which are not under `lib` directory?如何从 `gem` 中获取不在`lib` 目录下的文件?
【发布时间】:2015-06-03 14:50:38
【问题描述】:

我想为我的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

【问题讨论】:

  • 你想要什么?如果您需要预先加载的自定义功能,您应该将其放在初始化程序中或将所需的文件添加到 autoload_paths。否则,这个问题没有太多可继续讨论的地方。
  • 我想在我的spec/rubocop/my_custom_cop_spec.rb 中要求rubocop gem 中的rubocop/spec/support/cop_helper.rb
  • 你试过只需要那个文件吗?例如require rubocop/spec/support/cop_helper
  • @engineersmnky,我已经更新了问题。
  • rubocop 安装了吗?

标签: ruby rspec rubygems rubocop


【解决方案1】:

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

gem_dir = Gem::Specification.find_by_name("my_gem").gem_dir
require "#{gem_dir}/spec"

【讨论】:

    【解决方案2】:

    我被蒙蔽了,我已经有了文件的路径,并且能够从中获取相关信息。

    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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      相关资源
      最近更新 更多