Ruby以编程方式安装gem

时间:2016-04-12 08:12:58

标签: ruby rubygems

如果我使用带有CGFLOAT_MAX的脚本中的Backticks以编程方式安装gem:

gem install gem_name

然后需要宝石,if not_gem_installed `gem install my_gem` end require 'my_gem' 出现。有什么方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

我尝试用反引号安装宝石,发现我遇到了与上述问题相同的问题。我发现它并不是这项工作的最佳选择。 我建议使用Gem搜索宝石和安装。

require 'rubygems/commands/install_command'

def find_or_install(gem_name)
  Gem::Specification::find_by_name(gem_name)
rescue Gem::LoadError
  install_gem(gem_name)
end

def install_gem(gem_name)
  cmd = Gem::Commands::InstallCommand.new
  cmd.handle_options [gem_name]     

  cmd.execute
rescue Gem::SystemExitException => e
  puts "FAILURE: #{e.exit_code}"
end

https://gist.github.com/adamjmurray/3154437 - 有好例子的要点

答案 1 :(得分:-1)

由于您没有使用RubyGems,因此您需要从gem的路径中获取特定文件。 RubyGems会覆盖require方法,以便它查找要包含在Gemfile中的gem路径的路径文件。因此,请确保指定gem的主.rb文件的正确路径。

if not_gem_installed
  `gem install my_gem`
end

require 'path/to/my_gem'

您可以通过在文件/ irb中打印$:的值或在命令行中运行gem environment命令来检查ruby将查看的路径。

uzbekjon@mini:~$ gem environment
RubyGems Environment:
  - RUBYGEMS VERSION: 2.5.1
  - RUBY VERSION: 2.3.0 (2015-12-25 patchlevel 0) [x86_64-darwin15]
  - INSTALLATION DIRECTORY: /Users/uzbekjon/.rvm/gems/ruby-2.3.0
  - USER INSTALLATION DIRECTORY: /Users/uzbekjon/.gem/ruby/2.3.0
  - RUBY EXECUTABLE: /Users/uzbekjon/.rvm/rubies/ruby-2.3.0/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/uzbekjon/.rvm/gems/ruby-2.3.0/bin
  - SPEC CACHE DIRECTORY: /Users/uzbekjon/.gem/specs
  - SYSTEM CONFIGURATION DIRECTORY: /Users/uzbekjon/.rvm/rubies/ruby-2.3.0/etc
  - GEM PATHS:
     - /Users/uzbekjon/.rvm/gems/ruby-2.3.0
     - /Users/uzbekjon/.rvm/gems/ruby-2.3.0@global
  - GEM CONFIGURATION:
     ...

=== OR with $: ===

uzbekjon@mini:~$ irb
2.3.0 :001 > $:
 => ["/Users/uzbekjon/.rvm/gems/ruby-2.3.0@global/gems/did_you_mean-1.0.0/lib", "/Users/uzbekjon/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0", "..."]

替代地

您只需在脚本中使用bundler即可。

if not_gem_installed
  `gem install my_gem`
end

require 'rubygems'         # <= This line here
require 'path/to/my_gem'