我们需要同时需要require和Gemfile吗?

时间:2019-03-26 18:54:59

标签: ruby

在ruby程序中,有一个单独的Gem文件,其中包含以下定义:


source "https://rubygems.org" 
gem "typhoeus" 
gem "json" 
gem "pg" 
gem "google_drive" , "2.1.11" 
gem "mandrill-api"

如果由于某种原因我不想要这个gem文件,那么在ruby脚本中,我需要为所有库添加require, 例如:

 
require typhoeus
require json
require pg
require google_drive, 2.1.11
require mandrill-api 

这行得通吗?

1 个答案:

答案 0 :(得分:4)

Gemfile的目的可能会有所帮助,以便您可以使用bundler(它允许您运行bundle install)来确保您的代码能够正常工作,这将安装gems与当前版本的ruby一起使用您将使用您的代码。它还会添加一个Gemfile.lock文件,这是在版本控制中提交的一个好主意,以确保您拥有一个可以正常工作的堆栈,其中gem和ruby版本都兼容。

如果仅在脚本中需要文件,则不能保证将gems实际上安装在该脚本的运行器范围内。因此,通过拥有GemfileGemfile.lock并使用捆绑程序,您可以具有代码库的可移植性。

更新

根据@engineersmnky的评论,您可以使用此语法指定gem版本,只要安装了这些gem,它就应该起作用。您首先需要确保在终端中安装该版本:

gem install google_drive -v 2.1.11

然后您可以在红宝石文件中完成

require 'rubygems' 
gem 'google_drive', '2.1.11'; 
require 'google_drive' 
require 'typhoeus'
require 'json'
require 'pg' 
require 'mandrill-api'