### Making Basic GET Requests with Net::HTTP Source: https://docs.ruby-lang.org/en/master/Net This snippet shows how to perform simple GET requests using the Net::HTTP class. It includes examples of fetching content from a given URI and also from a hostname and path combination. It also illustrates how to start an HTTP session to make multiple requests. ```ruby # Net::HTTP.get(uri)\n# Net::HTTP.get(hostname, '/index.html')\nNet::HTTP.start(hostname) do |http|\n http.get('/todos/1')\n http.get('/todos/2')\nend ``` -------------------------------- ### Example: Installing to a directory - Ruby Source: https://docs.ruby-lang.org/en/master/FileUtils Shows how to install a file to a directory. The file is copied into the directory with its original name. ```Ruby File.read('src2.txt') # => "aaa\n" File.read('dest2/src2.txt') # => "bbb\n" FileUtils.install('src2.txt', 'dest2') File.read('dest2/src2.txt') # => "aaa\n" ``` -------------------------------- ### Execute RubyGems Setup Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand The main execution function for the setup command. It configures verbosity, extends FileUtils and MakeDirs, generates destination directories, installs libraries and executables, removes old files, and provides feedback on the installation process. ```ruby def execute @verbose = Gem.configuration.really_verbose require "fileutils" if Gem.configuration.really_verbose extend FileUtils::Verbose else extend FileUtils end extend MakeDirs lib_dir, bin_dir = make_destination_dirs man_dir = generate_default_man_dir install_lib lib_dir install_executables bin_dir remove_old_bin_files bin_dir remove_old_lib_files lib_dir # Can be removed one we drop support for bundler 2.2.3 (the last version installing man files to man_dir) remove_old_man_files man_dir if man_dir && File.exist?(man_dir) install_default_bundler_gem bin_dir if mode = options[:dir_mode] @mkdirs.uniq! File.chmod(mode, @mkdirs) end say "RubyGems #{Gem::VERSION} installed" regenerate_binstubs(bin_dir) if options[:regenerate_binstubs] regenerate_plugins(bin_dir) if options[:regenerate_plugins] uninstall_old_gemcutter documentation_success = install_rdoc say if @verbose say "-" * 78 say end if options[:previous_version].empty? options[:previous_version] = Gem::VERSION.sub(/[0-9]+$/, "0") end options[:previous_version] = Gem::Version.new(options[:previous_version]) show_release_notes say say "-" * 78 say say "RubyGems installed the following executables:" say bin_file_names.map {|name| "\t#{name}\n" } say unless bin_file_names.grep(/#{File::SEPARATOR}gem$/) say "If `gem` was installed by a previous RubyGems installation, you may need" say "to remove it by hand." say end if documentation_success if options[:document].include? "rdoc" say "Rdoc documentation was installed. You may now invoke:" say " gem server" say "and then peruse beautifully formatted documentation for your gems" say "with your web browser. If you do not wish to install this documentation in the future, use the" say "--no-document flag, or set it as the default in your ~/.gemrc file. See" say "'gem help env' for details." say end if options[:document].include? "ri" say "Ruby Interactive (ri) documentation was installed. ri is kind of like man " say "pages for Ruby libraries. You may access it like this:" say " ri Classname" say " ri Classname.class_method" say " ri Classname#instance_method" say "If you do not wish to install this documentation in the future, use the" say "--no-document flag, or set it as the default in your ~/.gemrc file. See" say "'gem help env' for details." say end end end ``` -------------------------------- ### Setup Coverage Measurement (Ruby) Source: https://docs.ruby-lang.org/en/master/Coverage Initializes coverage measurement. Does not start it; use Coverage.resume. Coverage.start can be used for both setup and start. ```ruby 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; } ``` -------------------------------- ### Example: Basic file installation - Ruby Source: https://docs.ruby-lang.org/en/master/FileUtils Demonstrates a basic file installation where a source file is copied to a destination file, overwriting if the destination exists. ```Ruby File.read('src0.txt') # => "aaa\n" File.exist?('dest0.txt') # => false FileUtils.install('src0.txt', 'dest0.txt') File.read('dest0.txt') # => "aaa\n" ``` -------------------------------- ### Making GET Requests with Net::HTTP Source: https://docs.ruby-lang.org/en/master/Net/HTTPResponse Provides examples of making GET requests using Net::HTTP. It shows both direct requests using a URI and requests specifying the hostname and path. It also demonstrates starting an HTTP session and making multiple requests within it. ```ruby Net::HTTP.get(uri)\nNet::HTTP.get(hostname, '/index.html')\nNet::HTTP.start(hostname) do |http|\n http.get('/todos/1')\n http.get('/todos/2')\nend ``` -------------------------------- ### GET Request Examples Source: https://docs.ruby-lang.org/en/master/Net/HTTP Examples of making simple GET requests using Net::HTTP, including retrieving data as a string or as a response object. ```APIDOC ## GET Request Examples ### Description Examples of making simple GET requests using Net::HTTP, including retrieving data as a string or as a response object. ### Method GET ### Endpoint Various (depends on URI provided) ### Parameters #### Query Parameters - **uri** (URI) - Required - The URI object for the request. - **hostname** (String) - Required - The hostname for the request. - **path** (String) - Required - The path for the request. ### Request Example ```ruby require 'net/http' # Example using URI object hostname = 'jsonplaceholder.typicode.com' path = '/todos/1' uri = URI("https://#{hostname}#{path}") # Get response as string response_body = Net::HTTP.get(uri) puts response_body # Get response as Net::HTTPResponse object response = Net::HTTP.get_response(uri) puts response.body # Get response using hostname and path response_body_alt = Net::HTTP.get(hostname, path) puts response_body_alt ``` ### Response #### Success Response (200) - **body** (String) - The response body content. - **code** (String) - The HTTP status code (e.g., "200"). #### Response Example ```json { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } ``` ``` -------------------------------- ### Example: Installing multiple files to a directory - Ruby Source: https://docs.ruby-lang.org/en/master/FileUtils Illustrates installing multiple files from an array of paths to a specified directory. Each file is placed directly within the destination directory. ```Ruby File.file?('src3.txt') # => true File.file?('src3.dat') # => true FileUtils.mkdir('dest3') FileUtils.install(['src3.txt', 'src3.dat'], 'dest3') File.file?('dest3/src3.txt') # => true File.file?('dest3/src3.dat') # => true ``` -------------------------------- ### Generate HTML Documentation (Shell) Source: https://docs.ruby-lang.org/en/master/contributing/documentation_guide_md Command to generate HTML documentation from source files. Assumes a build directory exists; otherwise, follow the quick start guide. ```shell make html ``` -------------------------------- ### Basic OptionParser Setup in Ruby Source: https://docs.ruby-lang.org/en/master/optparse/tutorial_rdoc Demonstrates the basic setup for `OptionParser` in Ruby: requiring the library, creating a parser instance, defining simple options with descriptions and blocks, and parsing the command line using `parse!`. ```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 # Parse the command line and return pared-down ARGV. p parser.parse! ``` -------------------------------- ### Example usage of FileUtils.install with verbose and noop options Source: https://docs.ruby-lang.org/en/master/FileUtils Demonstrates how to use the `install` method with `noop: true` and `verbose: true` to see the commands that would be executed without actually performing the file operations. ```ruby FileUtils.install('src0.txt', 'dest0.txt', noop: true, verbose: true) FileUtils.install('src1.txt', 'dest1.txt', noop: true, verbose: true) FileUtils.install('src2.txt', 'dest2', noop: true, verbose: true) ``` -------------------------------- ### CLI Execution Examples (Ruby) Source: https://docs.ruby-lang.org/en/master/SyntaxSuggest/Cli Demonstrates various ways to invoke the SyntaxSuggest CLI with different arguments, including help, file paths, 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 ``` -------------------------------- ### Build Ruby from Source Directory Source: https://docs.ruby-lang.org/en/master/windows_md This example demonstrates the standard process of building Ruby from its source directory on Windows. It outlines the necessary steps from configuring the build environment to installation. ```batch C: cd \ruby win32\configure --prefix=/usr/local nmake nmake check nmake install ``` -------------------------------- ### Get String Representation of Path (Ruby Example) Source: https://docs.ruby-lang.org/en/master/File Provides examples of using `File.path` to get the string representation of file paths, including special paths like `/dev/null` and `Pathname` objects. ```ruby File.path(File::NULL) #=> "/dev/null" File.path(Pathname.new("/tmp")) #=> "/tmp" ``` -------------------------------- ### Ruby Compilation and Installation Steps Source: https://docs.ruby-lang.org/en/master/README_ja_md This outlines the essential steps for compiling and installing Ruby from source. It includes running autogen.sh, configuring the build, editing configuration files, making, testing, and installing the compiled binaries. ```bash ./autogen.sh configure make make check make install ``` -------------------------------- ### Initialize Gem::Commands::SetupCommand Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand Initializes the SetupCommand with various options for installing RubyGems. It configures options such as executable formatting, documentation types, installation directories, and binstub regeneration. Dependencies include the superclass `Gem::Command`. ```ruby # File lib/rubygems/commands/setup_command.rb, line 15 def initialize super "setup", "Install RubyGems", format_executable: false, document: %w[ri], force: true, site_or_vendor: "sitelibdir", destdir: "", prefix: "", previous_version: "", regenerate_binstubs: true, regenerate_plugins: true add_option "--previous-version=VERSION", "Previous version of RubyGems", "Used for changelog processing" do |version, options| options[:previous_version] = version end add_option "--prefix=PREFIX", "Prefix path for installing RubyGems", "Will not affect gem repository location" do |prefix, options| options[:prefix] = File.expand_path prefix end add_option "--destdir=DESTDIR", "Root directory to install RubyGems into", "Mainly used for packaging RubyGems" do |destdir, options| options[:destdir] = File.expand_path destdir end add_option "--[no-]vendor", "Install into vendorlibdir not sitelibdir" do |vendor, options| options[:site_or_vendor] = vendor ? "vendorlibdir" : "sitelibdir" end add_option "--[no-]format-executable", "Makes `gem` match ruby", "If Ruby is ruby18, gem will be gem18" do |value, options| options[:format_executable] = value end add_option "--[no-]document [TYPES]", Array, "Generate documentation for RubyGems", "List the documentation types you wish to", "generate. For example: rdoc,ri" do |value, options| options[:document] = case value when nil then %w[rdoc ri] when false then [] else value end end add_option "--[no-]rdoc", "Generate RDoc documentation for RubyGems" do |value, options| if value options[:document] << "rdoc" else options[:document].delete "rdoc" end options[:document].uniq! end add_option "--[no-]ri", "Generate RI documentation for RubyGems" do |value, options| if value options[:document] << "ri" else options[:document].delete "ri" end options[:document].uniq! end add_option "--[no-]regenerate-binstubs", "Regenerate gem binstubs" do |value, options| options[:regenerate_binstubs] = value end add_option "--[no-]regenerate-plugins", "Regenerate gem plugins" do |value, options| options[:regenerate_plugins] = value end add_option "-f", "--[no-]force", "Forcefully overwrite binstubs" do |value, options| options[:force] = value end add_option("-E", "--[no-]env-shebang", "Rewrite executables with a shebang", "of /usr/bin/env") do |value, options| options[:env_shebang] = value end @verbose = nil end ``` -------------------------------- ### Execute Gem Installation Source: https://docs.ruby-lang.org/en/master/Gem/Commands/InstallCommand Executes the gem installation process, handling gem dependencies, environment setup, version checks, and reporting installation results. ```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 ``` -------------------------------- ### Ruby Example: Getting Ancillary Data Type Source: https://docs.ruby-lang.org/en/master/Socket/AncillaryData This Ruby example shows how to get the type of socket ancillary data. It creates a new `AncillaryData` object with specific parameters and then retrieves its type, printing the resulting integer. ```ruby p Socket::AncillaryData.new(:INET6, :IPV6, :PKTINFO, "").type #=> 2 ``` -------------------------------- ### Get Gem Installation Directory (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem Returns the primary path where gems are installed. This method delegates to `paths.home`. ```Ruby def self.dir paths.home end ``` -------------------------------- ### Get Instruction Sequence Examples Source: https://docs.ruby-lang.org/en/master/RubyVM/InstructionSequence Illustrates how to use `RubyVM::InstructionSequence.of` to obtain the instruction sequence for both procs and methods, showing how to inspect them in IRB and after requiring a file. ```ruby # a proc > p = proc { num = 1 + 2 } > RubyVM::InstructionSequence.of(p) > #=> # for a method > def foo(bar); puts bar; end > RubyVM::InstructionSequence.of(method(:foo)) > #=> ``` ```ruby # /tmp/iseq_of.rb def hello puts "hello, world" end $a_global_proc = proc { str = 'a' + 'b' } # in irb > require '/tmp/iseq_of.rb' # first the method hello > RubyVM::InstructionSequence.of(method(:hello)) > #=> # # then the global proc > RubyVM::InstructionSequence.of($a_global_proc) > #=> # ``` -------------------------------- ### Install File List (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand Installs multiple files by iterating through a list and calling the 'install_file' function for each file. This is a utility function to simplify the installation of multiple files. ```Ruby def install_file_list(files, dest_dir) files.each do |file| install_file file, dest_dir end end ``` -------------------------------- ### Example: Get Block Size Source: https://docs.ruby-lang.org/en/master/File/Stat Illustrates how to get the block size of the file system for a given file. ```ruby File.stat("testfile").blksize #=> 4096 ``` -------------------------------- ### Install File (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand Installs a single file to a specified destination directory. It ensures the destination directory exists by creating it if necessary, and then copies the file with appropriate permissions. ```Ruby def install_file(file, dest_dir) dest_file = File.join dest_dir, file dest_dir = File.dirname dest_file unless File.directory? dest_dir mkdir_p dest_dir, mode: 0o755 end install file, dest_file, mode: options[:data_mode] || 0o644 end ``` -------------------------------- ### Get Start Line (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Location Retrieves the line number where the location starts within the source. ```ruby def start_line source.line(start_offset) end ``` -------------------------------- ### Install Library Files (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand Installs library files for RubyGems and Bundler. It identifies library directories for each tool, retrieves a list of files within those directories, and then uses 'install_file_list' to copy them to the target library directory. ```Ruby def install_lib(lib_dir) libs = { "RubyGems" => "lib" } libs["Bundler"] = "bundler/lib" libs.each do |tool, path| say "Installing #{tool}" if @verbose lib_files = files_in path Dir.chdir path do install_file_list(lib_files, lib_dir) end end end ``` -------------------------------- ### Configure Ruby Build with Visual C++ Source: https://docs.ruby-lang.org/en/master/windows_md Example of running the configure script for Visual C++ builds, specifying the target platform and installation directory. It also shows how to use --program-prefix and --program-suffix. ```batch win32\configure.bat --target=i686-mswin32 win32\configure.bat --prefix= win32\configure.bat --program-suffix=-$(MAJOR)$(MINOR) win32\configure.bat --install-name=$(RUBY_BASE_NAME)-$(MAJOR)$(MINOR) ``` -------------------------------- ### Get Cached Start Code Units Column Source: https://docs.ruby-lang.org/en/master/Prism/Location Calculates the start column of the location in code units, using a provided cache. The column is measured from the start of the line. ```Ruby def cached_start_code_units_column(cache) cache[start_offset] - cache[source.line_start(start_offset)] end ``` -------------------------------- ### Get Start Line Slice (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Location Extracts the portion of the starting line that appears before this location begins. ```ruby def start_line_slice offset = source.line_start(start_offset) source.slice(offset, start_offset - offset) end ``` -------------------------------- ### Setup Bundler Environment Source: https://docs.ruby-lang.org/en/master/Bundler This snippet demonstrates how to set up the Bundler environment in a Ruby project. It requires the 'bundler/setup' library to ensure that only the specified gems and their versions from the gemfile are used. ```ruby require 'bundler/setup' ``` -------------------------------- ### Get RubyGems Installation Prefix (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem Determines the directory prefix where RubyGems was installed. Returns nil if RubyGems is in a standard location. ```ruby 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 ``` -------------------------------- ### Initialize Gem::Installer (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/Installer Initializes a Gem::Installer instance. It takes a package (either a path or Gem::Package object) and options. It sets up file modes and processes installation options. ```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 Path Examples Source: https://docs.ruby-lang.org/en/master/Gem/Commands/UnpackCommand Demonstrates the usage of the `get_path` method with different arguments, showing successful retrieval of gem paths and cases where `nil` is returned. ```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) ``` -------------------------------- ### OptionParser Execution Examples in Ruby Source: https://docs.ruby-lang.org/en/master/optparse/tutorial_rdoc Illustrates various execution scenarios for a Ruby script using `OptionParser`, showing how options are parsed, arguments are handled, and how the remaining arguments are returned after `parse!` is called. Includes examples with valid options, invalid options, and arguments mixed with options. ```Shell $ ruby basic.rb -x -z ["x", true] ["z", true] [] $ ruby basic.rb -z -y -x ["z", true] ["y", true] ["x", true] [] $ ruby basic.rb -x input_file.txt output_file.txt ["x", true] ["input_file.txt", "output_file.txt"] $ ruby basic.rb -a basic.rb:16:in '
': invalid option: -a (OptionParser::InvalidOption) ``` -------------------------------- ### Get OpenSSL Digest Name Example (Ruby) Source: https://docs.ruby-lang.org/en/master/OpenSSL/Digest Demonstrates how to get the name of a SHA512 digest using the OpenSSL library in Ruby. ```ruby digest = OpenSSL::Digest.new('SHA512') puts digest.name # => SHA512 ``` -------------------------------- ### Get Start Column (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Location Calculates the column number in bytes where the location starts, relative to the beginning of the line. ```ruby def start_column source.column(start_offset) end ``` -------------------------------- ### Bundler Module Overview Source: https://docs.ruby-lang.org/en/master/Bundler Provides an overview of the Bundler module and its basic usage for setting up project environments. ```APIDOC ## Bundler Module Overview `Bundler` provides a consistent environment for Ruby projects by tracking and installing the exact gems and versions that are needed. `Bundler` is a part of Ruby’s standard library. `Bundler` is used by creating _gemfiles_ listing all the project dependencies and (optionally) their versions and then using: ```ruby require 'bundler/setup' ``` or `Bundler.setup` to setup environment where only specified gems and their specified versions could be used. See Bundler website for extensive documentation on gemfiles creation and `Bundler` usage. As a standard library inside project, `Bundler` could be used for introspection of loaded and required modules. ``` -------------------------------- ### Get Binary Installation Directory Source: https://docs.ruby-lang.org/en/master/Gem Determines the path where gem executables are installed. It defaults to the standard Gem directory's 'bin' subdirectory, unless a custom install directory is specified or it matches the default gem directory. ```ruby def self.bindir(install_dir = Gem.dir) return File.join install_dir, "bin" unless install_dir.to_s == Gem.default_dir.to_s Gem.default_bindir end ``` -------------------------------- ### Example: Verbose output for symbolic link creation Source: https://docs.ruby-lang.org/en/master/FileUtils Illustrates how to get verbose output, showing the equivalent command-line operations for symbolic link creation. ```ruby FileUtils.ln_s('src0.txt', 'dest0.txt', noop: true, verbose: true) FileUtils.ln_s('src1.txt', 'destdir1', noop: true, verbose: true) FileUtils.ln_s('src2.txt', 'dest2.txt', force: true, noop: true, verbose: true) FileUtils.ln_s(['srcdir3/src0.txt', 'srcdir3/src1.txt'], 'destdir3', noop: true, verbose: true) ``` -------------------------------- ### Install Default Bundler Gem (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand Installs the default Bundler gem, handling existing installations by removing old specs and executables. It rebuilds and installs the Bundler gem, ensuring the latest version is set as default. ```Ruby def install_default_bundler_gem(bin_dir) current_default_spec = Gem::Specification.default_stubs.find {|s| s.name == "bundler" } specs_dir = if current_default_spec && default_dir == Gem.default_dir all_specs_current_version = Gem::Specification.stubs.select {|s| s.full_name == current_default_spec.full_name } Gem::Specification.remove_spec current_default_spec loaded_from = current_default_spec.loaded_from File.delete(loaded_from) # Remove previous default gem executables if they were not shadowed by a regular gem FileUtils.rm_rf current_default_spec.full_gem_path if all_specs_current_version.size == 1 File.dirname(loaded_from) else target_specs_dir = File.join(default_dir, "specifications", "default") mkdir_p target_specs_dir, mode: 0o755 target_specs_dir end new_bundler_spec = Dir.chdir("bundler") { Gem::Specification.load("bundler.gemspec") } full_name = new_bundler_spec.full_name gemspec_path = "#{full_name}.gemspec" default_spec_path = File.join(specs_dir, gemspec_path) Gem.write_binary(default_spec_path, new_bundler_spec.to_ruby) bundler_spec = Gem::Specification.load(default_spec_path) # Remove gemspec that was same version of vendored bundler. normal_gemspec = File.join(default_dir, "specifications", gemspec_path) if File.file? normal_gemspec File.delete normal_gemspec end # Remove gem files that were same version of vendored bundler. if File.directory? bundler_spec.gems_dir Dir.entries(bundler_spec.gems_dir). select {|default_gem| File.basename(default_gem) == full_name }. each {|default_gem| rm_r File.join(bundler_spec.gems_dir, default_gem) } end require_relative "../installer" Dir.chdir("bundler") do built_gem = Gem::Package.build(new_bundler_spec) begin Gem::Installer.at( built_gem, env_shebang: options[:env_shebang], format_executable: options[:format_executable], force: options[:force], install_as_default: true, bin_dir: bin_dir, install_dir: default_dir, wrappers: true ).install ensure FileUtils.rm_f built_gem end end new_bundler_spec.executables.each {|executable| bin_file_names << target_bin_path(bin_dir, executable) } say "Bundler #{new_bundler_spec.version} installed" end ``` -------------------------------- ### Get OpenSSL Digest Size Example (Ruby) Source: https://docs.ruby-lang.org/en/master/OpenSSL/Digest Demonstrates how to get the digest length of a SHA1 digest using the OpenSSL library in Ruby. ```ruby digest = OpenSSL::Digest.new('SHA1') puts digest.digest_length # => 20 ``` -------------------------------- ### Get Start Column of Node (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Node Returns the starting column of the node. This is a delegate method to the `start_column` of the associated location object. ```ruby def start_column location.start_column end ``` -------------------------------- ### Initialize and Add to Gem::SourceList (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/SourceList Shows the process of creating a new Gem::SourceList and adding sources to it one by one. ```Ruby sources = Gem::SourceList.new sources << 'https://rubygems.example' ``` -------------------------------- ### Get Start Character Column (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Location Calculates the column number in characters where this location starts, relative to the beginning of the line. ```ruby def start_character_column source.character_column(start_offset) end ``` -------------------------------- ### Install Executables (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand Installs executables for RubyGems, specifically 'gem'. It handles both Unix-like systems and Windows by creating necessary executable files and batch files for Windows. Dependencies include Ruby's built-in modules like 'tmpdir'. ```Ruby def install_executables(bin_dir) prog_mode = options[:prog_mode] || 0o755 executables = { "gem" => "exe" } executables.each do |tool, path| say "Installing #{tool} executable" if @verbose Dir.chdir path do bin_file = "gem" require "tmpdir" dest_file = target_bin_path(bin_dir, bin_file) bin_tmp_file = File.join Dir.tmpdir, "#{bin_file}.$$" begin bin = File.readlines bin_file bin[0] = shebang File.open bin_tmp_file, "w" do |fp| fp.puts bin.join end install bin_tmp_file, dest_file, mode: prog_mode bin_file_names << dest_file ensure rm bin_tmp_file end next unless Gem.win_platform? begin bin_cmd_file = File.join Dir.tmpdir, "#{bin_file}.bat" File.open bin_cmd_file, "w" do |file| file.puts <<-TEXT @ECHO OFF @"%~dp0#{File.basename(Gem.ruby).chomp('"')}" "%~dpn0" %* TEXT end install bin_cmd_file, "#{dest_file}.bat", mode: prog_mode ensure rm bin_cmd_file end end end end ``` -------------------------------- ### Get Ruby Install Name (Ruby) Source: https://docs.ruby-lang.org/en/master/Gem/Installer Returns the installation name for the Ruby executable. This is derived from the Ruby configuration. ```Ruby def ruby_install_name rb_config["ruby_install_name"] end ``` -------------------------------- ### Setup Gem Signing - Ruby Source: https://docs.ruby-lang.org/en/master/Gem/Package Prepares the gem for signing and checksum generation. It sets up a `Gem::Security::Signer` instance using the signing key, certificate chain, and passphrase from the environment. If no signing key is present, it defaults to setting up for checksum generation only. ```ruby def setup_signer(signer_options: {}) passphrase = ENV["GEM_PRIVATE_KEY_PASSPHRASE"] if @spec.signing_key @signer = Gem::Security::Signer.new( @spec.signing_key, @spec.cert_chain, passphrase, signer_options ) @spec.signing_key = nil @spec.cert_chain = @signer.cert_chain.map(&:to_s) else @signer = Gem::Security::Signer.new nil, nil, passphrase @spec.cert_chain = @signer.cert_chain.map(&:to_pem) if @signer.cert_chain end end ``` -------------------------------- ### Aligning IRB Output in Examples (Ruby) Source: https://docs.ruby-lang.org/en/master/contributing/documentation_guide_md Shows how to align the output (`# => ...`) from `irb` sessions in code examples for improved readability. ```ruby a = [1, 2, 3] #=> [1, 2, 3] a.shuffle! #=> [2, 3, 1] a #=> [2, 3, 1] ``` -------------------------------- ### Get OpenSSL Digest Block Length Example (Ruby) Source: https://docs.ruby-lang.org/en/master/OpenSSL/Digest Demonstrates how to get the block length of a SHA1 digest using the OpenSSL library in Ruby. ```ruby digest = OpenSSL::Digest.new('SHA1') puts digest.block_length # => 64 ``` -------------------------------- ### Get Start Line of Node (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Node Returns the starting line number of the node. This method delegates to the `start_line` of the associated location object. ```ruby def start_line location.start_line end ``` -------------------------------- ### Sample Ruby File Source: https://docs.ruby-lang.org/en/master/RubyVM/InstructionSequence A simple 'Hello, world!' Ruby program that can be compiled using `RubyVM::InstructionSequence.compile_file`. ```ruby puts "Hello, world!" ``` -------------------------------- ### Ruby MonitorMixin: Public Class Methods - initialize Source: https://docs.ruby-lang.org/en/master/MonitorMixin Illustrates the initialization of MonitorMixin. It's noted that 'extend MonitorMixin' or 'include MonitorMixin' should be used instead of directly calling this constructor. This method ensures the monitor is properly set up. ```ruby # File ext/monitor/lib/monitor.rb, line 222 def initialize(...) super mon_initialize end ``` -------------------------------- ### Get the directory for installed gems Source: https://docs.ruby-lang.org/en/master/Gem/Specification Determines and returns the directory where gems are installed. It constructs this path by joining the base directory with 'gems'. ```ruby def gems_dir @gems_dir ||= File.join(base_dir, "gems") end ``` -------------------------------- ### Get Gem Installation Directory Source: https://docs.ruby-lang.org/en/master/Gem/Commands/ContentsCommand Retrieves and displays the installation directory for a specified gem. It finds the gem's specification and then prints the `gem_dir` attribute. ```ruby def gem_install_dir(name) spec = spec_for name return false unless spec say spec.gem_dir true end ``` -------------------------------- ### Ruby: Managing HTTP Sessions Source: https://docs.ruby-lang.org/en/master/Net/HTTP Provides an example of managing HTTP sessions using `Net::HTTP.start`. This approach is more efficient for making multiple requests to the same host, as it reuses the connection. ```ruby Net::HTTP.start(hostname) do |http| # Session started automatically before block execution. http.get(path) http.head(path) body = 'Some text' http.post(path, body) # Can also have a block. http.put(path, body) http.delete(path) http.options(path) http.trace(path) http.patch(path, body) # Can also have a block. http.copy(path) http.lock(path, body) http.mkcol(path, body) http.move(path) http.propfind(path, body) http.proppatch(path, body) http.unlock(path, body) # Session finished automatically at block exit. end ``` -------------------------------- ### Get Start Character Offset of Node (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Node Returns the starting character offset of the node from the beginning of the source. This delegates to the associated location object. ```ruby def start_character_offset location.start_character_offset end ``` -------------------------------- ### SyntaxSuggest::Cli Initialization (Ruby) Source: https://docs.ruby-lang.org/en/master/SyntaxSuggest/Cli Shows the constructor for SyntaxSuggest::Cli, highlighting dependency injection for testing and how environment variables or debug flags influence options like record directory and terminal highlighting. ```ruby # File lib/syntax_suggest/cli.rb, line 20 def initialize(argv:, exit_obj: Kernel, io: $stdout, env: ENV) @options = {} @parser = nil options[:record_dir] = env["SYNTAX_SUGGEST_RECORD_DIR"] options[:record_dir] = "tmp" if env["DEBUG"] options[:terminal] = SyntaxSuggest::DEFAULT_VALUE @io = io @argv = argv @exit_obj = exit_obj end ``` -------------------------------- ### Minimal OptionParser Example Source: https://docs.ruby-lang.org/en/master/OptionParser A basic example demonstrating how to create and parse command-line options using OptionParser. It sets up a verbose flag and prints the parsed options and remaining arguments. ```ruby require 'optparse' options = {} OptionParser.new do |parser| parser.banner = "Usage: example.rb [options]" parser.on("-v", "--[no-]verbose", "Run verbosely") do |v| options[:verbose] = v end end.parse! p options p ARGV ``` -------------------------------- ### Get Start Character Column of Node (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Node Returns the starting character column of the node within its line. This delegates to the associated location object. ```ruby def start_character_column location.start_character_column end ``` -------------------------------- ### Get Bundler Gems Install Path (Ruby) Source: https://docs.ruby-lang.org/en/master/Bundler Returns the path where gems are installed by Bundler, usually located within the Bundler home directory. ```ruby def install_path home.join("gems") end ``` -------------------------------- ### Install Git and Ruby with Scoop Source: https://docs.ruby-lang.org/en/master/windows_md Instructions for installing Git and Ruby using the Scoop package manager, a common method for managing development tools on Windows. ```shell scoop install git ruby ``` -------------------------------- ### WebauthnListener Example - RubyGems Source: https://docs.ruby-lang.org/en/master/Gem/GemcutterUtilities Example usage of the WebauthnListener to retrieve an OTP. It starts a listener thread, joins it, and then accesses the OTP or error from the thread's data. ```Ruby thread = Gem::WebauthnListener.listener_thread("https://rubygems.example", server) thread.join otp = thread[:otp] error = thread[:error] ``` -------------------------------- ### Display Release Notes in RubyGems Setup Command Source: https://docs.ruby-lang.org/en/master/Gem/Commands/SetupCommand Displays the release notes by reading the 'CHANGELOG.md' file. It parses the file to extract version information and changes made since the previous version, formatting the output for the user. It handles cases where the changelog file might not exist. ```ruby def show_release_notes release_notes = File.join Dir.pwd, "CHANGELOG.md" release_notes = if File.exist? release_notes history = File.read release_notes history.force_encoding Encoding::UTF_8 text = history.split(HISTORY_HEADER) text.shift # correct an off-by-one generated by split version_lines = history.scan(HISTORY_HEADER) versions = history.scan(VERSION_MATCHER).flatten.map do |x| Gem::Version.new(x) end history_string = "" until versions.length == 0 || versions.shift <= options[:previous_version] do history_string += version_lines.shift + text.shift end history_string else "Oh-no! Unable to find release notes!" end say release_notes end ``` -------------------------------- ### Set up SSL Server and Handle Connections (Ruby) Source: https://docs.ruby-lang.org/en/master/OpenSSL Establishes an SSL server using Ruby's OpenSSL library. It configures an SSL context with a certificate and private key, then binds to a TCP port. The server listens for incoming connections, accepts them, reads data, sends a response, and closes the connection. ```ruby require 'socket' context = OpenSSL::SSL::SSLContext.new context.cert = cert context.key = key tcp_server = TCPServer.new 5000 ssl_server = OpenSSL::SSL::SSLServer.new tcp_server, context loop do ssl_connection = ssl_server.accept data = ssl_connection.gets response = "I got #{data.dump}" puts response ssl_connection.puts "I got #{data.dump}" ssl_connection.close end ``` -------------------------------- ### Get Line Start Offset in Ruby Source: https://docs.ruby-lang.org/en/master/Prism/Source Returns the byte offset of the start of a line given its byte offset. It uses the `find_line` method and the `offsets` array. ```ruby # File lib/prism/parse_result.rb, line 87 def line_start(byte_offset) offsets[find_line(byte_offset)] end ``` -------------------------------- ### Get Start Offset of Node (Ruby) Source: https://docs.ruby-lang.org/en/master/Prism/Node Calculates and returns the starting offset of the node in the source. It handles cases where the location might not be a standard Location object. ```ruby def start_offset location = @location location.is_a?(Location) ? location.start_offset : location >> 32 end ```