### Interactive Gem Installation Example Source: https://docs.ruby-lang.org/en/4.0/Gem.html Demonstrates how to install a gem interactively using the `Gem.install` method in IRB. ```ruby % irb >> Gem.install "minitest" Fetching: minitest-5.14.0.gem (100%) => [#] ``` -------------------------------- ### Setup Command Initialization Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/SetupCommand.html Initializes the setup command with various options for installing RubyGems. ```APIDOC ## Setup Command Initialization ### Description Initializes the `SetupCommand` with default options and customizes behavior through various command-line arguments. ### Method `initialize` ### Endpoint N/A (Class constructor) ### Parameters #### Request Body (Implicitly defined by command-line options) - **document** (Array of strings) - Optional - Specifies documentation types to generate (e.g., `rdoc`, `ri`). Defaults to `['ri']` if not specified. - **force** (Boolean) - Optional - Forces overwriting of binstubs. Defaults to `true`. - **site_or_vendor** (String) - Optional - Specifies installation directory (`sitelibdir` or `vendorlibdir`). Defaults to `sitelibdir`. - **destdir** (String) - Optional - Root directory for installation, mainly for packaging. Defaults to `""`. - **prefix** (String) - Optional - Prefix path for installation. Defaults to `""`. - **previous_version** (String) - Optional - Previous version of RubyGems, used for changelog processing. Defaults to `""`. - **regenerate_binstubs** (Boolean) - Optional - Whether to regenerate gem binstubs. Defaults to `true`. - **regenerate_plugins** (Boolean) - Optional - Whether to regenerate gem plugins. Defaults to `true`. - **env_shebang** (Boolean) - Optional - Rewrites executables with a shebang of `/usr/bin/env`. ### Request Example (Not applicable for initialization) ### Response (Not applicable for initialization) ### Error Handling (Not applicable for initialization) ``` -------------------------------- ### Example URI and Hostname Setup Source: https://docs.ruby-lang.org/en/4.0/Net/HTTP.html Sets up a URI object and extracts its hostname and path. The URI is frozen to prevent accidental modification in examples. ```ruby uri = URI('https://jsonplaceholder.typicode.com/') uri.freeze # Examples may not modify. hostname = uri.hostname # => "jsonplaceholder.typicode.com" path = uri.path # => "/" ``` -------------------------------- ### Setup Coverage Measurement in Ruby Source: https://docs.ruby-lang.org/en/4.0/Coverage.html Configures coverage measurement. Does not start it; use Coverage.resume. Coverage.start can be used for setup and immediate start. ```ruby me2counter = rb_ident_hash_new(); } else { me2counter = Qnil; } coverages = rb_get_coverages(); if (!RTEST(coverages)) { coverages = rb_hash_new(); rb_obj_hide(coverages); current_mode = mode; if (mode == 0) mode = COVERAGE_TARGET_LINES; rb_set_coverages(coverages, mode, me2counter); current_state = SUSPENDED; } else if (current_mode != mode) { rb_raise(rb_eRuntimeError, "cannot change the measuring target during coverage measurement"); } return Qnil; } ``` -------------------------------- ### Get Binary File Names for Setup Command Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/SetupCommand.html Returns an array of binary file names associated with the setup command. Initializes the array if it hasn't been set. ```ruby def bin_file_names @bin_file_names ||= [] end ``` -------------------------------- ### Gem Installation Source: https://docs.ruby-lang.org/en/4.0/Gem.html Installs a gem with the specified name and version, optionally with additional options. Provides an interactive example. ```APIDOC ## POST /api/install ### Description Installs a gem with the specified name and version, optionally with additional options. Allows interactive gem installation. ### Method POST ### Endpoint /api/install ### Parameters #### Request Body - **name** (string) - Required - The name of the gem to install. - **version** (string) - Optional - The version of the gem to install. Defaults to the latest version. - **options** (array) - Optional - Additional options for installation. ``` ```APIDOC ### Request Example ```ruby Gem.install "minitest" ``` ``` -------------------------------- ### Get Day of Year Example Source: https://docs.ruby-lang.org/en/4.0/Date.html Example of getting the day of the year for a specific date. ```ruby Date.new(2001, 2, 3).yday # => 34 ``` -------------------------------- ### Get Day of Week Example Source: https://docs.ruby-lang.org/en/4.0/Date.html Example of getting the day of the week for a specific date. ```ruby Date.new(2001, 2, 3).wday # => 6 ``` -------------------------------- ### Basic OptionParser Setup in Ruby Source: https://docs.ruby-lang.org/en/4.0/optparse/tutorial_rdoc.html Demonstrates the initial steps to use OptionParser: requiring the library, creating a parser instance, and defining simple options with descriptive strings and blocks. Each option prints its name and value when parsed. ```ruby # Require the OptionParser code. require 'optparse' # Create an OptionParser object. parser = OptionParser.new # Define one or more options. parser.on('-x', 'Whether to X') do |value| p ['x', value] end parser.on('-y', 'Whether to Y') do |value| p ['y', value] end parser.on('-z', 'Whether to Z') do |value| p ['z', value] end ``` -------------------------------- ### Get Year Example Source: https://docs.ruby-lang.org/en/4.0/Date.html Examples of getting the year from a Date object, including handling year 0. ```ruby Date.new(2001, 2, 3).year # => 2001 (Date.new(1, 1, 1) - 1).year # => 0 ``` -------------------------------- ### Public Instance Methods Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/SetupCommand.html Public methods available for the SetupCommand. ```APIDOC ## Public Instance Methods ### `bin_file_names` #### Description Returns an array of binary file names associated with the setup command. #### Method `GET` (Conceptual) #### Endpoint N/A (Instance method) #### Parameters None #### Request Example ```ruby setup_command.bin_file_names ``` #### Response - **Array of strings** - The list of binary file names. #### Response Example ```json [] ``` ### `default_dir` #### Description Determines the default directory for installing RubyGems, considering the prefix and destination directory. #### Method `GET` (Conceptual) #### Endpoint N/A (Instance method) #### Parameters None #### Request Example ```ruby setup_command.default_dir ``` #### Response - **String** - The calculated default installation directory. #### Response Example ```json "/path/to/gems/default" ``` ### `execute` #### Description Executes the setup command, performing the installation and configuration of RubyGems. #### Method `POST` (Conceptual) #### Endpoint N/A (Instance method) #### Parameters None #### Request Example ```ruby setup_command.execute ``` #### Response (Details of execution outcome would be here, typically success or error messages) #### Response Example (Success or error messages related to the execution) ``` -------------------------------- ### Gem::Installer::FakePackage#initialize Source: https://docs.ruby-lang.org/en/4.0/Gem/Installer/FakePackage.html Initializes a new instance of Gem::Installer::FakePackage. ```APIDOC ## Gem::Installer::FakePackage#initialize ### Description Initializes a new instance of Gem::Installer::FakePackage. ### Method `initialize` ### Parameters - **spec**: The specification object. ### Source ```ruby # File lib/rubygems/installer.rb, line 98 def initialize(spec) @spec = spec end ``` ``` -------------------------------- ### Get ARGF external encoding example Source: https://docs.ruby-lang.org/en/4.0/ARGF.html This example shows how to get the external encoding of files processed by `ARGF`. It returns an `Encoding` object. ```ruby ARGF.external_encoding #=> # ``` -------------------------------- ### Get Enumerator Size Examples Source: https://docs.ruby-lang.org/en/4.0/Enumerator.html Illustrates how to get the size of an enumerator in Ruby. Shows examples with ranges, infinite enumerators, and lazy enumerators where size might be `nil` or inaccurate. ```ruby (1..100).to_a.permutation(4).size # => 94109400 loop.size # => Float::INFINITY (1..100).drop_while.size # => nil ``` ```ruby e = Enumerator.new(5) { |y| 2.times { y << it} } e.size # => 5 e.to_a.size # => 2 ``` ```ruby e = Enumerator.produce(1) { it + 1 } e.size # => Infinity e = Enumerator.produce(1) { it > 3 ? raise(StopIteration) : it + 1 } e.size # => Infinity e.to_a.size # => 4 ``` -------------------------------- ### Gem::Commands::InstallCommand#initialize Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/InstallCommand.html Initializes the `InstallCommand` with default options and adds various command-line options for installation. ```APIDOC ## Gem::Commands::InstallCommand#initialize ### Description Initializes the `InstallCommand` with default options and adds various command-line options for installation. ### Method `initialize` ### Source ```ruby # File lib/rubygems/commands/install_command.rb, line 24 def initialize defaults = Gem::DependencyInstaller::DEFAULT_OPTIONS.merge({ format_executable: false, lock: true, suggest_alternate: true, version: Gem::Requirement.default, without_groups: [], }) defaults.merge!(install_update_options) super "install", "Install a gem into the local repository", defaults add_install_update_options add_local_remote_options add_platform_option add_version_option add_prerelease_option "to be installed. (Only for listed gems)" @installed_specs = [] end ``` ### Calls Calls superclass method `Gem::Command.new` ``` -------------------------------- ### Example Files for ARGF/ARGV Source: https://docs.ruby-lang.org/en/4.0/ARGF.html Content of example files 'foo.txt' and 'bar.txt' used in ARGF/ARGV demonstrations. ```text Foo 0 Foo 1 ``` ```text Bar 0 Bar 1 Bar 2 Bar 3 ``` -------------------------------- ### Get current file object in ARGF example Source: https://docs.ruby-lang.org/en/4.0/ARGF.html This example demonstrates how to get the current `IO` or `File` object using `ARGF.file`. It shows how the object changes when reading from different files. ```ruby ARGF.file #=> # ARGF.read(5) #=> "foo\nb" ARGF.file #=> # ``` -------------------------------- ### Example CLI Usage Source: https://docs.ruby-lang.org/en/4.0/SyntaxSuggest/Cli.html Demonstrates various ways to invoke the SyntaxSuggest CLI with different arguments, including help, file analysis, and recording options. ```ruby Cli.new(argv: ["--help"]).call Cli.new(argv: [".rb"]).call Cli.new(argv: [".rb", "--record=tmp"]).call Cli.new(argv: [".rb", "--terminal"]).call ``` -------------------------------- ### Get IP Address (Started) Source: https://docs.ruby-lang.org/en/4.0/Net/HTTP.html Returns the IP address from the socket if the session has been started. ```ruby http = Net::HTTP.new(hostname) http.start http.ipaddr ``` -------------------------------- ### Example: `cp` with `noop` and `verbose` options Source: https://docs.ruby-lang.org/en/4.0/FileUtils.html Demonstrates the output of `cp` when `noop` and `verbose` options are enabled. ```ruby FileUtils.cp('src0.txt', 'dest0.txt', noop: true, verbose: true) FileUtils.cp('src1.txt', 'dest1', noop: true, verbose: true) FileUtils.cp(src_file_paths, 'dest2', noop: true, verbose: true) ``` -------------------------------- ### Get Gem Installation Path Source: https://docs.ruby-lang.org/en/4.0/Gem.html Returns the path where gems are to be installed, which is determined by `paths.home`. ```ruby def self.dir paths.home end ``` -------------------------------- ### Build Example: Relative Directory Compilation Source: https://docs.ruby-lang.org/en/4.0/distribution/windows_md.html Illustrates building Ruby in a relative directory (`mswin32`) from the source directory, specifying the installation prefix. ```batch C: cd \ruby mkdir mswin32 cd mswin32 ..\win32\configure --prefix=/usr/local nmake nmake check nmake install ``` -------------------------------- ### DSA Initialization Examples Source: https://docs.ruby-lang.org/en/4.0/OpenSSL/PKey/DSA.html Demonstrates creating DSA instances using different methods: generating a new key with a specified size, reading a PEM-encoded key from a file, and reading a PEM-encoded key with a password. ```ruby p OpenSSL::PKey::DSA.new(1024) #=> # ``` ```ruby p OpenSSL::PKey::DSA.new(File.read('dsa.pem')) #=> # ``` ```ruby p OpenSSL::PKey::DSA.new(File.read('dsa.pem'), 'mypassword') #=> # ``` -------------------------------- ### Get Password by Name Example - Ruby Source: https://docs.ruby-lang.org/en/4.0/Etc.html Example of retrieving user information using the username. ```ruby Etc.getpwnam('root') #=> # ``` -------------------------------- ### Get Login Example - Ruby Source: https://docs.ruby-lang.org/en/4.0/Etc.html Example of retrieving the current logged-in user's name. ```ruby Etc.getlogin -> 'guest' ``` -------------------------------- ### Example of Connecting to a Web Server in Ruby Source: https://docs.ruby-lang.org/en/4.0/Socket.html This example demonstrates how to create a socket, pack a sockaddr for a specific port and host, and then connect to it to retrieve web page content. Ensure the 'socket' library is required and 'Socket::Constants' is included. ```ruby # Pull down Google's web page require 'socket' include Socket::Constants socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) sockaddr = Socket.pack_sockaddr_in( 80, 'www.google.com' ) socket.connect( sockaddr ) socket.write( "GET / HTTP/1.0\r\n\r\n" ) results = socket.read ``` -------------------------------- ### Example: Get Ancillary Data Type Source: https://docs.ruby-lang.org/en/4.0/Socket/AncillaryData.html This Ruby example demonstrates how to get the integer type of an `AncillaryData` object. It shows that the type for `Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "")` is 2. ```ruby p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "").type #=> 2 ``` -------------------------------- ### Socket Server Example Source: https://docs.ruby-lang.org/en/4.0/Socket.html This example demonstrates setting up a simple TCP server. It binds to a local address and port, listens for incoming connections, accepts a client, receives data, and then closes the socket. Ensure the client script is run in a separate process. ```Ruby # In one file, start this first require 'socket' include Socket::Constants socket = Socket.new( AF_INET, SOCK_STREAM, 0 ) sockaddr = Socket.pack_sockaddr_in( 2200, 'localhost' ) socket.bind( sockaddr ) socket.listen( 5 ) client, client_addrinfo = socket.accept data = client.recvfrom( 20 )[0].chomp puts "I only received 20 bytes '#{data}'" sleep 1 socket.close ``` -------------------------------- ### Example extconf.rb script Source: https://docs.ruby-lang.org/en/4.0/MakeMakefile.html This example demonstrates the usage of `have_func`, `have_header`, `create_header`, and `create_makefile` within an `extconf.rb` script to configure a C extension. ```ruby require 'mkmf' have_func('realpath') have_header('sys/utime.h') create_header create_makefile('foo') ``` -------------------------------- ### Get Start Line Slice Source: https://docs.ruby-lang.org/en/4.0/Prism/Location.html Extracts the content of the line where this location starts, specifically the part before the location itself. This is useful for context before the exact start point. ```ruby # File lib/prism/parse_result.rb, line 412 def start_line_slice offset = source.line_start(start_offset) source.slice(offset, start_offset - offset) end ``` -------------------------------- ### Example Operating System Defaults Source: https://docs.ruby-lang.org/en/4.0/Gem.html Provides an example structure for `operating_system_defaults`, mapping gem command names to default options. ```ruby def self.operating_system_defaults ``` { 'install' => '--no-rdoc --no-ri --env-shebang', 'update' => '--no-rdoc --no-ri --env-shebang' } ``` end ``` -------------------------------- ### Get All Installed Gem Stubs Source: https://docs.ruby-lang.org/en/4.0/Gem/Specification.html Retrieves a `Gem::StubSpecification` for every gem that is currently installed on the system. ```ruby def self.stubs specification_record.stubs end ``` -------------------------------- ### Get Group by Name Example - Ruby Source: https://docs.ruby-lang.org/en/4.0/Etc.html Example of retrieving group information using the group name. ```ruby Etc.getgrnam('users') #=> # ``` -------------------------------- ### Build Example: Native Compilation Source: https://docs.ruby-lang.org/en/4.0/distribution/windows_md.html Demonstrates a complete native build process for Ruby on Windows, starting from the source directory. ```batch C: cd \ruby win32\configure --prefix=/usr/local nmake nmake check nmake install ``` -------------------------------- ### Get Group by ID Example - Ruby Source: https://docs.ruby-lang.org/en/4.0/Etc.html Example of retrieving group information using the group ID. ```ruby Etc.getgrgid(100) #=> # ``` -------------------------------- ### Setting up example URIs and variables Source: https://docs.ruby-lang.org/en/4.0/Net/HTTPGenericRequest.html Defines common URI objects and associated variables like hostname, path, and port, which are used across multiple examples for consistency. ```ruby uri = URI('https://jsonplaceholder.typicode.com/') uri.freeze # Examples may not modify. hostname = uri.hostname # => "jsonplaceholder.typicode.com" path = uri.path # => "/" port = uri.port # => 443 ``` -------------------------------- ### Installer Initialization Source: https://docs.ruby-lang.org/en/4.0/Gem/Installer.html Constructs an Installer instance that will install the gem at package. The package can be a file path or a Gem::Package object. Options hash can be provided to customize the installation process. ```APIDOC ## Initialize Installer ### Description Constructs an `Installer` instance that will install the gem at `package` which can either be a path or an instance of `Gem::Package`. `options` is a `Hash` with the following keys: ### Method `initialize` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **package** (String or Gem::Package) - The gem to install. - **options** (Hash) - A hash of options for installation. - **:bin_dir** (String) - Where to put a bin wrapper if needed. - **:development** (Boolean) - Whether or not development dependencies should be installed. - **:env_shebang** (Boolean) - Use /usr/bin/env in bin wrappers. - **:force** (Boolean) - Overrides all version checks and security policy checks, except for a signed-gems-only policy. - **:format_executable** (Boolean) - Format the executable the same as the Ruby executable. - **:ignore_dependencies** (Boolean) - Don’t raise if a dependency is missing. - **:install_dir** (String) - The directory to install the gem into. - **:security_policy** (Object) - Use the specified security policy. See `Gem::Security`. - **:user_install** (Boolean) - Indicate that the gem should be unpacked into the users personal gem directory. - **:only_install_dir** (Boolean) - Only validate dependencies against what is in the install_dir. - **:wrappers** (Boolean) - Install wrappers if true, symlinks if false. - **:build_args** (Array) - An `Array` of arguments to pass to the extension builder process. - **:post_install_message** (Boolean) - Print gem post install message if true. ### Request Example ```ruby installer = Gem::Installer.new('/path/to/my.gem', :install_dir => '/usr/local/lib/ruby/gems/2.0.0', :force => true) ``` ### Response #### Success Response (200) An instance of `Gem::Installer`. #### Response Example ```ruby #"/usr/local/lib/ruby/gems/2.0.0", :force=>true}, @package=#, ...>> ...> ``` ``` -------------------------------- ### Install Gem with HighSecurity Policy Source: https://docs.ruby-lang.org/en/4.0/Gem/Security.html Use the `-P` option to specify a security policy when installing gems. This example installs a gem using the `HighSecurity` policy. ```bash $ sudo gem install your.gem -P HighSecurity ``` -------------------------------- ### Get IP Address (Not Started) Source: https://docs.ruby-lang.org/en/4.0/Net/HTTP.html Returns the IP address for the connection if the session has not been started. Otherwise, returns nil. ```ruby http = Net::HTTP.new(hostname) http.ipaddr ``` -------------------------------- ### Test New Ruby Installation Source: https://docs.ruby-lang.org/en/4.0/contributing/building_ruby_md.html Executes a simple 'Hello, World!' script using the newly installed Ruby executable. This verifies that the installation was successful. ```bash ~/.rubies/ruby-master/bin/ruby -e "puts 'Hello, World!'" ``` -------------------------------- ### Product Data Example Source: https://docs.ruby-lang.org/en/4.0/ERB.html Example of creating a `Product` instance and adding features. ```APIDOC ## Product Data Example ### Description This section demonstrates how to instantiate the `Product` class and populate it with data, including adding multiple features. ### Code ```ruby toy = Product.new('TZ-1002', 'Rubysapien', "Geek's Best Friend! Responds to Ruby commands...", 999.95 ) toy.add_feature('Listens for verbal commands in the Ruby language!') toy.add_feature('Ignores Perl, Java, and all C variants.') toy.add_feature('Karate-Chop Action!!!') toy.add_feature('Matz signature on left leg.') toy.add_feature('Gem studded eyes... Rubies, of course!') ``` ``` -------------------------------- ### Install Gem from Gist in Ruby Source: https://docs.ruby-lang.org/en/4.0/Gem/RequestSet/GemDependencyAPI.html Example of specifying a gem dependency to be installed from a GitHub Gist using its ID. ```ruby gem 'bang', gist: '1232884' ``` -------------------------------- ### Gem::Commands::HelpCommand Initialization Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/HelpCommand.html Initializes the HelpCommand with a name and description, setting up the command manager. ```APIDOC ## Gem::Commands::HelpCommand ### Description Initializes the HelpCommand with a name and description, setting up the command manager. ### Method `new` ### Parameters None ### Request Example ```ruby Gem::Commands::HelpCommand.new ``` ### Response None ### Response Example None ``` -------------------------------- ### Install Gem from Git Repository in Ruby Source: https://docs.ruby-lang.org/en/4.0/Gem/RequestSet/GemDependencyAPI.html Example of specifying a gem dependency to be installed directly from a git repository. ```ruby gem 'private_gem', git: 'git@my.company.example:private_gem.git' ``` -------------------------------- ### Get Cached Start Code Units Column Source: https://docs.ruby-lang.org/en/4.0/Prism/Location.html Calculates and retrieves the cached start column in code units using a provided cache. It subtracts the source's line start offset from the start offset. ```ruby # File lib/prism/parse_result.rb, line 442 def cached_start_code_units_column(cache) cache[start_offset] - cache[source.line_start(start_offset)] end ``` -------------------------------- ### Example Usage of ARGV.getopts (Symbol Keys) Source: https://docs.ruby-lang.org/en/4.0/OptionParser.html Demonstrates using ARGV.getopts with the `symbolize_names: true` option to parse arguments into a hash with symbol keys. Includes examples of various option formats. ```ruby params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option", symbolize_names: true) # params[:a] = true # -a # params[:b] = "1" # -b1 # params[:foo] = "1" # --foo # params[:bar] = "x" # --bar x # params[:zot] = "z" # --zot Z ``` -------------------------------- ### Create a hard link (Ruby Example) Source: https://docs.ruby-lang.org/en/4.0/File.html Demonstrates creating a hard link using `File.link`. The example shows creating a link and then reading from the linked file to verify content. ```ruby File.link("testfile", ".testfile") #=> 0 IO.readlines(".testfile")[0] #=> "This is line one\n" ``` -------------------------------- ### Get Gem Installation Directory Source: https://docs.ruby-lang.org/en/4.0/Gem/Installer.html Returns the target directory where the gem is intended to be installed. Note that this directory is not guaranteed to be populated. ```ruby def dir gem_dir.to_s end ``` -------------------------------- ### Get Gem Installation Path Source: https://docs.ruby-lang.org/en/4.0/Bundler.html Returns the absolute path on the filesystem where gems are installed. This path is determined by the Bundler configuration. ```ruby def bundle_path @bundle_path ||= Pathname.new(configured_bundle_path.path).expand_path(root) end ``` -------------------------------- ### OpenSSL Engine Examples Source: https://docs.ruby-lang.org/en/4.0/OpenSSL/Engine.html Demonstrates loading all available engines and accessing the name of the first engine in the list. ```ruby OpenSSL::Engine.load OpenSSL::Engine.engines #=> [#, ...] OpenSSL::Engine.engines.first.name #=> "RSAX engine support" ``` -------------------------------- ### Example Usage of ARGV.getopts (String Keys) Source: https://docs.ruby-lang.org/en/4.0/OptionParser.html Demonstrates how to use ARGV.getopts to parse command-line arguments into a hash with string keys. Shows parsing of single-character and long options with values. ```ruby params = ARGV.getopts("ab:", "foo", "bar:", "zot:Z;zot option") # params["a"] = true # -a # params["b"] = "1" # -b1 # params["foo"] = "1" # --foo # params["bar"] = "x" # --bar x # params["zot"] = "z" # --zot Z ``` -------------------------------- ### Get Cached Start Code Units Offset Source: https://docs.ruby-lang.org/en/4.0/Prism/Location.html Retrieves the cached start offset in code units from a given cache. This method provides direct access to pre-calculated start offsets. ```ruby # File lib/prism/parse_result.rb, line 380 def cached_start_code_units_offset(cache) cache[start_offset] end ``` -------------------------------- ### Initialize Gem::Installer::FakePackage Source: https://docs.ruby-lang.org/en/4.0/Gem/Installer/FakePackage.html Constructor for Gem::Installer::FakePackage. Requires a specification object. ```ruby def initialize(spec) @spec = spec end ``` -------------------------------- ### Get Start Line Source: https://docs.ruby-lang.org/en/4.0/Prism/Location.html Returns the line number where this location starts. This provides the absolute line number within the source file. ```ruby # File lib/prism/parse_result.rb, line 407 def start_line source.line(start_offset) end ``` -------------------------------- ### Get Start Column Source: https://docs.ruby-lang.org/en/4.0/Prism/Location.html Retrieves the column number in bytes where this location starts from the beginning of the line. This is a byte-based offset within the line. ```ruby # File lib/prism/parse_result.rb, line 424 def start_column source.column(start_offset) end ``` -------------------------------- ### Make-like Tool Example Source: https://docs.ruby-lang.org/en/4.0/TSort.html A practical example demonstrating how to implement a 'make'-like tool using the TSort module for dependency management. ```APIDOC ## Realistic Make-like Tool Example A very simple ‘make’ like tool can be implemented as follows: ```ruby require 'tsort' class Make def initialize @dep = {} @dep.default = [] end def rule(outputs, inputs=[], &block) triple = [outputs, inputs, block] outputs.each {|f| @dep[f] = [triple]} @dep[triple] = inputs end def build(target) each_strongly_connected_component_from(target) { |ns| if ns.length != 1 fs = ns.delete_if {|n| Array === n} raise TSort::Cyclic.new("cyclic dependencies: #{fs.join ', '}") end n = ns.first if Array === n outputs, inputs, block = n inputs_time = inputs.map {|f| File.mtime f}.max begin outputs_time = outputs.map {|f| File.mtime f}.min rescue Errno::ENOENT outputs_time = nil end if outputs_time == nil || inputs_time != nil && outputs_time <= inputs_time sleep 1 if inputs_time != nil && inputs_time.to_i == Time.now.to_i block.call end end } end def tsort_each_child(node, &block) @dep[node].each(&block) end include TSort end def command(arg) print arg, "\n" system arg end m = Make.new m.rule(%w[t1]) { command 'date > t1' } m.rule(%w[t2]) { command 'date > t2' } m.rule(%w[t3]) { command 'date > t3' } m.rule(%w[t4], %w[t1 t3]) { command 'cat t1 t3 > t4' } m.rule(%w[t5], %w[t4 t2]) { command 'cat t4 t2 > t5' } m.build('t5') ``` ``` -------------------------------- ### Get RubyGems Installation Prefix - RubyGems Source: https://docs.ruby-lang.org/en/4.0/Gem.html Returns the directory prefix where RubyGems was installed. Returns nil if the prefix is in a standard location. ```ruby # File lib/rubygems.rb, line 813 def self.prefix prefix = File.dirname RUBYGEMS_DIR if prefix != File.expand_path(RbConfig::CONFIG["sitelibdir"]) && prefix != File.expand_path(RbConfig::CONFIG["libdir"]) && File.basename(RUBYGEMS_DIR) == "lib" prefix end end ``` -------------------------------- ### Build Example: x64 Version Compilation Source: https://docs.ruby-lang.org/en/4.0/distribution/windows_md.html Demonstrates the process for building an x64 version of Ruby on Windows, requiring a native x64 VC++ compiler and specific configuration. ```batch C: cd \ruby win32\configure --prefix=/usr/local --target=x64-mswin64 nmake nmake check nmake install ``` -------------------------------- ### Basic OptionParser Setup Source: https://docs.ruby-lang.org/en/4.0/optparse/tutorial_rdoc.html Sets up an OptionParser with three distinct options: `--xxx`, `--yyy YYY`, and `--zzz [ZZZ]`. It then parses ARGV and prints the returned arguments and their class. ```ruby require 'optparse' parser = OptionParser.new parser.on('--xxx') do |value| p ['--xxx', value] end parser.on('--yyy YYY') do |value| p ['--yyy', value] end parser.on('--zzz [ZZZ]') do |value| p ['--zzz', value] end ret = parser.parse(ARGV) puts "Returned: #{ret} (#{ret.class})" ``` -------------------------------- ### Get Plugin Directory Path Source: https://docs.ruby-lang.org/en/4.0/Gem.html Constructs and returns the path where RubyGems plugins are installed. It defaults to the `Gem.dir` if no installation directory is provided. ```ruby # File lib/rubygems.rb, line 342 def self.plugindir(install_dir = Gem.dir) File.join install_dir, "plugins" end ``` -------------------------------- ### Get Gem Install Path Source: https://docs.ruby-lang.org/en/4.0/Bundler.html Returns the installation path for gems, which is a subdirectory named 'gems' within the Bundler home directory. ```ruby def install_path home.join("gems") end ``` -------------------------------- ### Build Example: Different Drive Compilation Source: https://docs.ruby-lang.org/en/4.0/distribution/windows_md.html Shows how to build Ruby when the source and build directories are on different drives. The `DESTDIR` is used for installation. ```batch D: cd D:\build\ruby C:\src\ruby\win32\configure --prefix=/usr/local nmake nmake check nmake install DESTDIR=C: ``` -------------------------------- ### Install Gem from GitHub Repository in Ruby Source: https://docs.ruby-lang.org/en/4.0/Gem/RequestSet/GemDependencyAPI.html Example of specifying a gem dependency to be installed from a GitHub repository using the 'owner/repo' format. ```ruby gem 'private_gem', github: 'my_company/private_gem' ``` -------------------------------- ### URI FTP Build Example Source: https://docs.ruby-lang.org/en/4.0/NEWS/NEWS-1_8_7.html Demonstrates how to build a URI for the FTP scheme using URI::FTP.build, specifying components like host and path. ```ruby URI::FTP.build([nil, 'example.com', nil, '/foo', 'i']).to_s #=> 'example.com/%2Ffoo;type=i' ``` -------------------------------- ### Install Gem from Local Path in Ruby Source: https://docs.ruby-lang.org/en/4.0/Gem/RequestSet/GemDependencyAPI.html Example of specifying a gem dependency to be installed from an unpacked gem located in a local directory. ```ruby gem 'modified_gem', path: 'vendor/modified_gem' ``` -------------------------------- ### Set Required Ruby Version Examples Source: https://docs.ruby-lang.org/en/4.0/Gem/Specification.html Examples demonstrating how to specify Ruby version requirements, including minimum versions, version ranges, and prereleases. ```ruby spec.required_ruby_version = '>= 1.8.6' ``` ```ruby spec.required_ruby_version = '~> 2.3' ``` ```ruby spec.required_ruby_version = '> 2.6.0.preview2' ``` ```ruby spec.required_ruby_version = '>= 2.3', '< 4' ``` -------------------------------- ### Example of initializing URI::LDAP Source: https://docs.ruby-lang.org/en/4.0/URI/LDAP.html Shows how to initialize a URI::LDAP object with specific components. ```ruby uri = URI::LDAP.new("ldap", nil, "ldap.example.com", nil, nil, "/dc=example;dc=com", nil, "query", nil) ``` -------------------------------- ### Get Node Start Offset Source: https://docs.ruby-lang.org/en/4.0/Prism/Node.html Retrieves the starting offset of the node in the source code. Delegates to the location object if it's a Location instance. ```ruby # File lib/prism/node.rb, line 56 def start_offset location = @location location.is_a?(Location) ? location.start_offset : location >> 32 end ``` -------------------------------- ### Get Start Character Column Source: https://docs.ruby-lang.org/en/4.0/Prism/Location.html Calculates the column number of characters from the start of the line where the location ends. This is useful for precise character-based positioning. ```ruby # File lib/prism/parse_result.rb, line 430 def start_character_column source.character_column(start_offset) end ``` -------------------------------- ### Examples of using MonitorMixin Source: https://docs.ruby-lang.org/en/4.0/MonitorMixin.html Demonstrates how to use MonitorMixin by extending an object or including it in a class. ```APIDOC ## Examples ### Simple object.extend ```ruby require 'monitor.rb' buf = [] buf.extend(MonitorMixin) empty_cond = buf.new_cond # consumer Thread.start do loop do buf.synchronize do empty_cond.wait_while { buf.empty? } print buf.shift end end end # producer while line = ARGF.gets buf.synchronize do buf.push(line) empty_cond.signal end end ``` The consumer thread waits for the producer thread to push a line to buf while `buf.empty?`. The producer thread (main thread) reads a line from `ARGF` and pushes it into buf then calls `empty_cond.signal` to notify the consumer thread of new data. ### Simple Class include ```ruby require 'monitor' class SynchronizedArray < Array include MonitorMixin def initialize(*args) super(*args) end alias :old_shift :shift alias :old_unshift :unshift def shift(n=1) self.synchronize do self.old_shift(n) end end def unshift(item) self.synchronize do self.old_unshift(item) end end # other methods ... end ``` `SynchronizedArray` implements an `Array` with synchronized access to items. This Class is implemented as subclass of `Array` which includes the `MonitorMixin` module. ``` -------------------------------- ### Initialize RubyGems Installer Source: https://docs.ruby-lang.org/en/4.0/Gem/Installer.html Constructs an Installer instance. The `package` can be a path or a Gem::Package object. `options` is a Hash controlling installation behavior, such as `install_dir`, `force`, and `wrappers`. ```ruby def initialize(package, options = {}) require "fileutils" @options = options @package = package process_options @package.dir_mode = options[:dir_mode] @package.prog_mode = options[:prog_mode] @package.data_mode = options[:data_mode] end ``` -------------------------------- ### Get Default Gem Installation Directory Source: https://docs.ruby-lang.org/en/4.0/Gem.html Returns the default directory where RubyGems installs its libraries. This path is constructed using `RbConfig::CONFIG`. ```ruby def self.default_dir @default_dir ||= File.join(RbConfig::CONFIG["rubylibprefix"], "gems", RbConfig::CONFIG["ruby_version"]) end ``` -------------------------------- ### Example: Copying a File with `copy_file` Source: https://docs.ruby-lang.org/en/4.0/FileUtils.html Demonstrates copying a file from 'src0.txt' to 'dest0.txt' using `copy_file`. ```ruby FileUtils.touch('src0.txt') FileUtils.copy_file('src0.txt', 'dest0.txt') File.file?('dest0.txt') # => true ``` -------------------------------- ### Struct Initialization Examples Source: https://docs.ruby-lang.org/en/4.0/Struct.html Demonstrates initializing Struct instances with positional and keyword arguments. Note the behavior with extra arguments or unknown keywords. ```ruby Foo = Struct.new(:foo, :bar) Foo.new(0) # => # Foo.new(0, 1) # => # Foo.new(0, 1, 2) # Raises ArgumentError: struct size differs # Initialization with keyword arguments: Foo.new(foo: 0) # => # Foo.new(foo: 0, bar: 1) # => # Foo.new(foo: 0, bar: 1, baz: 2) # Raises ArgumentError: unknown keywords: baz ``` -------------------------------- ### Get Line Start Byte Offset Source: https://docs.ruby-lang.org/en/4.0/Prism/Source.html Returns the byte offset of the start of the line corresponding to the given byte offset by looking up the pre-calculated offsets. ```ruby def line_start(byte_offset) offsets[find_line(byte_offset)] end ``` -------------------------------- ### Starting a Net::HTTP session Source: https://docs.ruby-lang.org/en/4.0/Net/HTTPGenericRequest.html Shows how to initiate an HTTP session using Net::HTTP.start and perform multiple requests within the same session, which is more efficient for multiple calls to the same host. ```ruby Net::HTTP.start(hostname) do |http| http.get('/todos/1') http.get('/todos/2') end ``` -------------------------------- ### Get Start and End Lines of a Value Source: https://docs.ruby-lang.org/en/4.0/Prism/Relocation/LinesField.html Fetches the start and end line of a given value. This method is part of the Prism::Relocation::LinesField class. ```ruby def fields(value) { start_line: value.start_line, end_line: value.end_line } end ``` -------------------------------- ### Initialize Gem::Commands::SigninCommand Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/SigninCommand.html Initializes the SigninCommand with a description and adds options for specifying a host and OTP. ```ruby def initialize super "signin", "Sign in to any gemcutter-compatible host. " \ "It defaults to https://rubygems.org" add_option("--host HOST", "Push to another gemcutter-compatible host") do |value, options| options[:host] = value end add_otp_option end ``` -------------------------------- ### Get Start Character Offset Source: https://docs.ruby-lang.org/en/4.0/Prism/Location.html Determines the character offset from the beginning of the source where this location starts. This provides the absolute position within the source string. ```ruby # File lib/prism/parse_result.rb, line 369 def start_character_offset source.character_offset(start_offset) end ``` -------------------------------- ### Get Prefix Source: https://docs.ruby-lang.org/en/4.0/Gem.html The directory prefix this RubyGems was installed at. If your prefix is in a standard location (ie, rubygems is installed where you’d expect it to be), then prefix returns nil. ```APIDOC ## GET /prefix ### Description Retrieves the installation directory prefix for RubyGems. ### Method GET ### Endpoint /prefix ### Response #### Success Response (200) - **prefix** (string | nil) - The directory prefix, or nil if in a standard location. ``` -------------------------------- ### Define Example Text, Russian, and Binary Data Source: https://docs.ruby-lang.org/en/4.0/IO.html Sets up example strings for text, Russian characters, and binary data, then writes them to respective files. Ensure files are closed after writing. ```ruby # English text with newlines. text = <<~EOT First line Second line Fourth line Fifth line EOT # Russian text. russian = "\u{442 435 441 442}" # => "тест" # Binary data. data = "\u9990\u9991\u9992\u9993\u9994" # Text file. File.write('t.txt', text) # File with Russian text. File.write('t.rus', russian) # File with binary data. f = File.new('t.dat', 'wb:UTF-16') f.write(data) f.close ``` -------------------------------- ### Public Class Methods: new Source: https://docs.ruby-lang.org/en/4.0/TCPServer.html Initializes a new TCPServer instance. ```APIDOC ## POST /new ### Description Creates a new server socket bound to _port_. If _hostname_ is given, the socket is bound to it. Internally, `TCPServer.new` calls getaddrinfo() function to obtain addresses. If getaddrinfo() returns multiple addresses, `TCPServer.new` tries to create a server socket for each address and returns first one that is successful. ### Method `new([hostname,] port)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "serv = TCPServer.new(\"127.0.0.1\", 28561)" } ``` ### Response #### Success Response (200) - **tcpserver** (object) - A new TCPServer instance. #### Response Example ```json { "example": "s = serv.accept\ns.puts Time.now\ns.close" } ``` ``` -------------------------------- ### Get Binstub Installation Path Source: https://docs.ruby-lang.org/en/4.0/Bundler.html Returns the absolute path where binstubs are installed. If not explicitly configured, it defaults to a 'bin' directory relative to the project root. ```ruby def bin_path @bin_path ||= begin path = Bundler.settings[:bin] || "bin" path = Pathname.new(path).expand_path(root).expand_path mkdir_p(path) path end end ``` -------------------------------- ### Ruby: Get Gem Path Source: https://docs.ruby-lang.org/en/4.0/Gem/Installer.html Returns the path of the gem being installed. ```ruby def gem @package.gem.path end ``` -------------------------------- ### Gem::Commands::InstallCommand#execute Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/InstallCommand.html Executes the gem installation process, handling different installation sources and providing feedback. ```APIDOC ## Gem::Commands::InstallCommand#execute ### Description Executes the gem installation process, handling different installation sources and providing feedback. ### Method `execute` ### Source ```ruby # File lib/rubygems/commands/install_command.rb, line 148 def execute if options.include? :gemdeps install_from_gemdeps return # not reached end @installed_specs = [] ENV.delete "GEM_PATH" if options[:install_dir].nil? check_version load_hooks exit_code = install_gems show_installed say update_suggestion if eligible_for_update? terminate_interaction exit_code end ``` ``` -------------------------------- ### Example Usage of get_path Source: https://docs.ruby-lang.org/en/4.0/Gem/Commands/UnpackCommand.html Demonstrates how to use the `get_path` function with different version requirements and name matching. ```ruby get_path 'rake', '> 0.4' # "/usr/lib/ruby/gems/1.8/cache/rake-0.4.2.gem" get_path 'rake', '< 0.1' # nil get_path 'rak' # nil (exact name required) ```