Skip to content

Instantly share code, notes, and snippets.

@agarie
Created May 23, 2015 04:08
Show Gist options
  • Save agarie/49302350395f334a6323 to your computer and use it in GitHub Desktop.
Save agarie/49302350395f334a6323 to your computer and use it in GitHub Desktop.
A function for inquiring if a library is available. Automatically requires the library if it is available.
# Create a method `has_<library>?` on Module that requires the library and
# return a boolean indicating if the library is available.
#
# @param library [String] The library name.
# @return [Boolean] Whether the library is available or not.
def create_has_library(library) #:nodoc:
define_singleton_method("has_#{library}?") do
cv = "@@#{library}"
unless class_variable_defined? cv
begin
require library.to_s
class_variable_set(cv, true)
rescue LoadError
class_variable_set(cv, false)
end
end
class_variable_get(cv)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment