From: "jeromedalbert (Jerome Dalbert) via ruby-core" Date: 2025-04-02T06:43:41+00:00 Subject: [ruby-core:121510] [Ruby Feature#14565] Simpler, one-liner, failsafe require in ruby? [Suggested names: require_failsafe, require_safe, require_try, require_add) Issue #14565 has been updated by jeromedalbert (Jerome Dalbert). I like this feature request, a non-failing require would be great for gems that optionally depend on another gem. For example: ```ruby begin require 'rubocop-rspec' rescue LoadError end if defined?(RuboCop::RSpec) # ... end ``` could be turned into something like this ```ruby if require('rubocop-rspec', exception: false) # ... end ``` ---------------------------------------- Feature #14565: Simpler, one-liner, failsafe require in ruby? [Suggested names: require_failsafe, require_safe, require_try, require_add) https://bugs.ruby-lang.org/issues/14565#change-112532 * Author: shevegen (Robert A. Heiler) * Status: Open ---------------------------------------- I have quite a bit of code like this: ```ruby begin require 'x/tools/cdrskin.rb' rescue LoadError; end ``` I also use the longer variant, e.g., ```ruby begin require 'foobar' rescue LoadError puts 'project foobar is not available - consider '\ 'installing it via gem install foobar' end ``` Often, I do not need to inform the user about missing gems/projects that are tiny and not very important. In my larger ruby projects, I handle cases where a smaller project is not available or available, so I can proceed either way. It is a bit pointless to notify the user when that is me; that is why I would like to have a one-liner. I am thinking of an API such as any of the following: require_failsafe require_safe require_try require_add This is for loading with a rescue LoadError without notification. If I need to notify a user then I am fine with the longer variant. If anyone has better names, feel free to add them! I think people are more likely to remember the require-family, e. g. require 'foo.rb' or require_relative 'bar.rb' and so forth. --- I also wanted to propose a stronger `require`/`import`, including the possibility to refer to `.rb` files without a hardcoded path (if the .rb file is moved, all explicit requires to it, in particular from external projects, would have to change; and my vague idea is to replace this with some kind of project-specific way to "label" files and load these files based on these "labels", but that is for another suggestion; I only want to mention it because Hiroshi Shibata made some suggestion as extension to require, and I think the use case he mentioned may also be useful to see whether ruby may get a stronger "load code in files" functionality for ruby 3.x eventually). -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/