【问题标题】:"Attaching" a gem to Rails to prevent "require" everywhere?将宝石“附加”到 Rails 以防止无处不在的“需要”?
【发布时间】:2019-09-18 18:06:25
【问题描述】:

gem 的名称与模块的名称不同。现在我需要require它和include在各种类型的文件中,比如控制器和模型。这相当于许多requires,我不必为其他宝石做这些。这是我可以更新的宝石。有没有一种方法需要配置 gem 以使其“附加”到 Rails,如果是这样,我在哪里可以找到执行此操作的说明?

更新:在 Gemfile 中使用 required: "name-of-module" 消除了对 require 的需求。仍然想知道,是否可以将 gem 配置为在 Gemfile 中不需要这个?

【问题讨论】:

  • 也许你能告诉我们你在说什么宝石?
  • 这有助于解决问题 - stackoverflow.com/questions/21029195/…
  • “如果 gem 可以配置为在 Gemfile 中不需要这个”是什么意思?
  • @lacostenycoder - 在使用 gem 的文件中不使用“require”

标签: ruby-on-rails ruby rubygems


【解决方案1】:

在 Gemfile 中,您可以执行以下操作:

# Require a different file than the gem's name
gem 'foo', require: 'bar'

# Install but not require anything.
# You need to manually require the gem somewhere.
gem 'foo', require: false

如果需要,您仍然可以添加版本和平台规范。

现实世界的例子是ActiveSupportrspec

gem 'activesupport', '~> 5.2', require: 'active_support/all'

gem 'rspec', '~> 3.1', group: :test, require: false

【讨论】:

    【解决方案2】:

    您需要指定希望 Ruby 为您加载哪些文件,因此您需要在 Gemfile 中指定 gem(并运行 bundle exec ...)或将 require 放在代码中的正确位置。没有办法。

    如果它是您在另一个项目中同时使用它的 gem,那么您可以指定 gem 的路径。喜欢

    # Gemfile
    source "https://rubygems.org"
    ruby '2.6.1'
    
    gem 'my_gem', path: '/home/user/Development/my_gem'
    

    这样,您可以更改您的 gem 并直接使用它,而无需构建和安装它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2016-04-07
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多