你如何检查是否已加载库/ ruby​​-gem?

Nei*_*eil 27 ruby gem

在ruby代码中,我如何检查加载了哪些外部库?例如,

require 'some-library'
if is-loaded?('some-library')
  puts "this will run"
end
Run Code Online (Sandbox Code Playgroud)

要么

# require 'some-library' Don't load it in here
if is-loaded?('some-library')
  puts "this will not run"
end
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

请注意我为什么需要这个:我正在研究繁荣,在Windows上,它将尝试包含'Win32/Console/ANSI',以启用ANSI颜色代码,如\ e [36m.我要做的是,如果系统是Windows并且未加载"Win32/Console/ANSI",它将附加颜色代码,因此不输出颜色代码.这是文件.

yfe*_*lum 27

大多数库通常会定义顶级常量.通常要做的是检查是否定义了常量.

> defined?(CSV)
#=> nil

> require "csv"
#=> true

> defined?(CSV)
#=> "constant"

> puts "loaded!" if defined?(CSV)
loaded!
#=> nil
Run Code Online (Sandbox Code Playgroud)

  • const_defined?甚至 (2认同)

dec*_*lan 11

require如果找不到您要加载的库,将抛出LoadError.所以你可以这样检查一下

begin
  require 'some-library'
  puts 'This will run.'
rescue LoadError
  puts 'This will not run'
  # error handling code here
end
Run Code Online (Sandbox Code Playgroud)


Car*_*auf 6

如果您想安全地尝试要求可能有或没有可用的gem /库,请使用以下内容:

begin
  require 'securerandom'
rescue LoadError
  # We just won't get securerandom
end
Run Code Online (Sandbox Code Playgroud)

即使已经要求有问题的宝石,这也有效.在那种情况下,require语句将不执行任何操作,并且rescue块将永远不会执行.

如果您只是对已经加载的gem /库感兴趣,请检查其中是否存在其中一个常量.如果加载了ActiveSupport,我会这样做以动态加载其他功能:

if defined?(ActiveSupport)
  require "active_support/cache/redis_store"
end
Run Code Online (Sandbox Code Playgroud)

如果gem/library不存在,您也可以使用相反的方法加载兼容层.例如,我使用了HashRuby核心Hash实现中不存在的一些方法,但是由ActiveSupport添加.因此,当我的gem在不存在ActiveSupport的环境中运行时,我定义了这些方法.

require 'core_ext/hash' unless defined?(ActiveSupport)
Run Code Online (Sandbox Code Playgroud)


Jos*_*ter 6

除非已加载,否则需要库

为简单起见,这里是如何加载库,除非它已经加载:

require 'RMagick' unless defined?(Magick)
Run Code Online (Sandbox Code Playgroud)


bar*_*can 5

尝试这个 :

def loaded?(name)
  r = Regexp.new("#{name}.rb$")
  $LOADED_FEATURES.select{|t| t.match(r) }.any?
end
Run Code Online (Sandbox Code Playgroud)

确保您的模块的名称(在此处搜索$LOADED_FEATURES)。