Search code examples
ruby-on-railsrubyirb

What all things can you access when you require a gem?


Let us take Rails gem for example

Before require 'rails'

irb(main):001:0> Rails
NameError: uninitialized constant Rails

irb(main):002:0> ActionPack
NameError: uninitialized constant ActionPack

After require 'rails'

irb(main):005:0> require 'rails'
true
irb(main):007:0> Rails.constants
[:Railtie, :Rack, :Initializable, :Configuration, :WelcomeController, :InfoController, :VERSION, :Paths, :Info, :MailersController, :Application, :Engine]

irb(main):009:0> ActionPack.methods-Object.methods
[:gem_version, :version, :initialize_copy]

So now the ActionPack module is available in the console, what other modules or class (if any) are available and how to know about those modules?


Solution

  • Thats up to the gem developer. To see how your Name- and Objectspace changed there should be many clever ways.

    I answer shortly how to find out which new Module (-Constants) there are:

      initial_modules = Module.constants
      # -> [:Object, :Module, :Class, :BasicObject, :Kernel, :NilClass, ...]
    
      require 'rails'
    
      Module.constants - initial_modules # all NEW constants
      # -> [:Pathname, :OpenSSL, :Digest, :SecureRandom, :Concurrent, :I18n, :CGI, :ActiveSupport, :Set, :SortedSet, :Timeout, :TimeoutError, :Logger, :LoggerSilence, :DateAndTime, :Psych, :StringScanner, :ScanError, :Date, :DateTime, :YAML, :Base64, :TSort, :Rails, :BigDecimal, :BigMath, :TZInfo, :ThreadSafe, :Threadsafe, :SynchronizedDelegator, :JSON, :OpenStruct, :Singleton, :Mutex_m, :ActionPack, :Rack, :ActionDispatch, :Mime]
    

    As you see, this also comes with a lot of new stuff that is required (but not provided) by Rails, like Date, OpenSSL, etc.pp. Actually, requirements can happen at runtime, too, such that this lists grows as you use the code. Hope that helps a bit.