Project

General

Profile

Feature #11148 ยป try_require.patch

tenderlovemaking (Aaron Patterson), 05/12/2015 10:47 PM

View differences:

load.c
818 818
}
819 819

  
820 820
/*
821
 *  call-seq:
822
 *     require(name)    -> true or false
823
 *
824
 *  Loads the given +name+, returning +true+ if successful, +false+ if the
825
 *  feature is already loaded, and +nil+ if the file can't be found.
826
 *
827
 *  If the filename does not resolve to an absolute path, it will be searched
828
 *  for in the directories listed in <code>$LOAD_PATH</code> (<code>$:</code>).
829
 *
830
 *  If the filename has the extension ".rb", it is loaded as a source file; if
831
 *  the extension is ".so", ".o", or ".dll", or the default shared library
832
 *  extension on the current platform, Ruby loads the shared library as a
833
 *  Ruby extension.  Otherwise, Ruby tries adding ".rb", ".so", and so on
834
 *  to the name until found.  If the file named cannot be found, a +nil+ will
835
 *  be returned.
836
 *
837
 *  For Ruby extensions the filename given may use any shared library
838
 *  extension.  For example, on Linux the socket extension is "socket.so" and
839
 *  <code>require 'socket.dll'</code> will load the socket extension.
840
 *
841
 *  The absolute path of the loaded file is added to
842
 *  <code>$LOADED_FEATURES</code> (<code>$"</code>).  A file will not be
843
 *  loaded again if its path already appears in <code>$"</code>.  For example,
844
 *  <code>require 'a'; require './a'</code> will not load <code>a.rb</code>
845
 *  again.
846
 *
847
 *    require "my-library.rb"
848
 *    require "db-driver"
849
 *
850
 *  Any constants or globals within the loaded source file will be available
851
 *  in the calling program's global namespace. However, local variables will
852
 *  not be propagated to the loading environment.
853
 *
854
 */
855
VALUE
856
rb_f_try_require(VALUE obj, VALUE fname)
857
{
858
    int result = rb_require_internal(fname, rb_safe_level());
859

  
860
    if (result > 1) {
861
	JUMP_TAG(result);
862
    }
863
    if (result < 0) {
864
	return Qnil;
865
    }
866

  
867
    return result ? Qtrue : Qfalse;
868
}
869

  
870
/*
821 871
 * call-seq:
822 872
 *   require_relative(string) -> true or false
823 873
 *
......
1211 1261

  
1212 1262
    rb_define_global_function("load", rb_f_load, -1);
1213 1263
    rb_define_global_function("require", rb_f_require, 1);
1264
    rb_define_global_function("try_require", rb_f_try_require, 1);
1214 1265
    rb_define_global_function("require_relative", rb_f_require_relative, 1);
1215 1266
    rb_define_method(rb_cModule, "autoload", rb_mod_autoload, 2);
1216 1267
    rb_define_method(rb_cModule, "autoload?", rb_mod_autoload_p, 1);