diff --git a/load.c b/load.c index 39315df..59739fa 100644 --- a/load.c +++ b/load.c @@ -818,6 +818,56 @@ rb_f_require(VALUE obj, VALUE fname) } /* + * call-seq: + * require(name) -> true or false + * + * Loads the given +name+, returning +true+ if successful, +false+ if the + * feature is already loaded, and +nil+ if the file can't be found. + * + * If the filename does not resolve to an absolute path, it will be searched + * for in the directories listed in $LOAD_PATH ($:). + * + * If the filename has the extension ".rb", it is loaded as a source file; if + * the extension is ".so", ".o", or ".dll", or the default shared library + * extension on the current platform, Ruby loads the shared library as a + * Ruby extension. Otherwise, Ruby tries adding ".rb", ".so", and so on + * to the name until found. If the file named cannot be found, a +nil+ will + * be returned. + * + * For Ruby extensions the filename given may use any shared library + * extension. For example, on Linux the socket extension is "socket.so" and + * require 'socket.dll' will load the socket extension. + * + * The absolute path of the loaded file is added to + * $LOADED_FEATURES ($"). A file will not be + * loaded again if its path already appears in $". For example, + * require 'a'; require './a' will not load a.rb + * again. + * + * require "my-library.rb" + * require "db-driver" + * + * Any constants or globals within the loaded source file will be available + * in the calling program's global namespace. However, local variables will + * not be propagated to the loading environment. + * + */ +VALUE +rb_f_try_require(VALUE obj, VALUE fname) +{ + int result = rb_require_internal(fname, rb_safe_level()); + + if (result > 1) { + JUMP_TAG(result); + } + if (result < 0) { + return Qnil; + } + + return result ? Qtrue : Qfalse; +} + +/* * call-seq: * require_relative(string) -> true or false * @@ -1211,6 +1261,7 @@ Init_load(void) rb_define_global_function("load", rb_f_load, -1); rb_define_global_function("require", rb_f_require, 1); + rb_define_global_function("try_require", rb_f_try_require, 1); rb_define_global_function("require_relative", rb_f_require_relative, 1); rb_define_method(rb_cModule, "autoload", rb_mod_autoload, 2); rb_define_method(rb_cModule, "autoload?", rb_mod_autoload_p, 1);