### Install Gem Dependencies with Bones Source: https://github.com/twp/inifile/blob/master/README.md Commands to install the 'bones' gem and then use it to install project dependencies for the IniFile gem. ```bash gem install bones rake gem:install_dependencies ``` -------------------------------- ### Install IniFile Gem Source: https://github.com/twp/inifile/blob/master/README.md Command to install the IniFile Ruby gem using the RubyGems package manager. ```bash gem install inifile ``` -------------------------------- ### IniFile Gem Usage Example Source: https://github.com/twp/inifile/blob/master/README.md A Ruby code snippet demonstrating how to load an INI file using the IniFile gem and iterate through its sections to access values. ```ruby require 'inifile' myini = IniFile.load('mytest.ini') myini.each_section do |section| puts "I want #{myini[section]['somevar']} printed here!" end ``` -------------------------------- ### IniFile Value Type Casting Examples Source: https://github.com/twp/inifile/blob/master/README.md Demonstrates how the IniFile gem automatically casts string values to their appropriate types (nil, integer, float, boolean) when parsing. Non-castable strings remain as strings. ```text "" --> nil "42" --> 42 "3.14159" --> 3.14159 "true" --> true "false" --> false "normal string" --> "normal string" ``` -------------------------------- ### Create New IniFile Instance Source: https://context7.com/twp/inifile/llms.txt Creates a new IniFile instance from various sources including a filename, string content, a hash, or as an empty configuration. Allows for flexible initialization of INI data with optional configuration parameters. ```ruby require 'inifile' # Create empty INI file ini = IniFile.new # Create from filename (parses file immediately) ini = IniFile.new(:filename => 'config.ini') # Create from string content content = <<-INI [database] host = localhost port = 5432 name = myapp_production [cache] enabled = true ttl = 3600 INI ini = IniFile.new(:content => content) puts ini['database']['host'] #=> "localhost" puts ini['database']['port'] #=> 5432 (Integer) puts ini['cache']['enabled'] #=> true (Boolean) # Create from hash ini = IniFile.new(:content => { 'server' => { 'host' => '0.0.0.0', 'port' => 8080 }, 'logging' => { 'level' => 'info', 'file' => '/var/log/app.log' } }) # Create with all options ini = IniFile.new( :filename => 'config.ini', :comment => ';#', # Allow both ; and # as comments :parameter => '=', # Key-value separator :encoding => 'UTF-8', :default => 'global' # Section name for properties without section header ) ``` -------------------------------- ### Access INI Sections and Properties Source: https://context7.com/twp/inifile/llms.txt Demonstrates accessing INI file sections and properties using bracket notation. Supports accessing entire sections as hashes, individual properties, and allows for setting and deleting sections and properties. Non-existent sections are auto-created. ```ruby require 'inifile' ini = IniFile.load('config.ini') # Access entire section (returns Hash) database_config = ini['database'] #=> {"host" => "localhost", "port" => 5432, "name" => "myapp"} # Access specific property host = ini['database']['host'] #=> "localhost" # Sections can be accessed with symbols too ini[:database]['port'] #=> 5432 # Non-existent sections return empty hash ini['nonexistent'] #=> {} # Set entire section at once ini['new_section'] = { 'key1' => 'value1', 'key2' => 'value2' } # Set individual property ini['database']['timeout'] = 30 # Check if section exists ini.has_section?('database') #=> true ini.has_section?('missing') #=> false # Get all section names ini.sections #=> ["database", "cache", "logging", "new_section"] # Delete a section deleted = ini.delete_section('old_section') #=> {"key" => "value"} or nil if section didn't exist ``` -------------------------------- ### Run IniFile Gem Tests Source: https://github.com/twp/inifile/blob/master/README.md Command to execute the test suite for the IniFile gem using the Rake build tool. ```bash rake ``` -------------------------------- ### Iterate Over INI Content Source: https://context7.com/twp/inifile/llms.txt Shows how to iterate over INI file content using `each`, `each_section`, and Enumerable methods. Allows processing all properties, sections, or applying collection methods like `map` and `select`. ```ruby require 'inifile' ini = IniFile.load('config.ini') # Iterate over all properties (yields section, key, value) ini.each do |section, parameter, value| puts "#{section}.#{parameter} = #{value}" end # Output: database.host = localhost database.port = 5432 cache.enabled = true # Iterate over sections only ini.each_section do |section| puts "Processing section: #{section}" puts ini[section].inspect end # Using Enumerable methods all_values = ini.map { |section, key, value| value } ``` -------------------------------- ### Load INI File from Filesystem Source: https://context7.com/twp/inifile/llms.txt Loads an INI file from the filesystem into an IniFile instance. Supports custom options for comments, parameter separators, encoding, and default section names. Returns nil if the file does not exist. ```ruby require 'inifile' # Basic file loading ini = IniFile.load('config.ini') # Load with custom options ini = IniFile.load('config.ini', :comment => '#', # Use # as comment character only :parameter => ':', # Use : instead of = for key-value separator :encoding => 'UTF-8', # File encoding :default => 'main' # Name for global section (properties without section) ) # Returns nil for non-existent files ini = IniFile.load('does_not_exist.ini') #=> nil ``` -------------------------------- ### Handling Global Sections and Customizing IniFile Parsing in Ruby Source: https://context7.com/twp/inifile/llms.txt Illustrates how to load INI files with global properties (outside of any section) and customize parsing behavior. The gem defaults to a 'global' section for these properties but allows specifying a custom default section name. It also supports custom parameter separators, comment characters, and file encodings. ```ruby require 'inifile' # INI file with global properties (no section header): # host = localhost # port = 8080 # [database] # name = myapp # Default global section name is "global" ini = IniFile.load('config.ini') ini['global']['host'] #=> "localhost" ini['global']['port'] #=> 8080 ini['database']['name'] #=> "myapp" # Custom global section name ini = IniFile.load('config.ini', :default => 'main') ini['main']['host'] #=> "localhost" # Custom parameter separator (use : instead of =) # [section] # key: value ini = IniFile.load('config.ini', :parameter => ':') # Custom comment character # [section] # // this is a comment # key = value ini = IniFile.load('config.ini', :comment => '//') # File encoding ini = IniFile.load('config.ini', :encoding => 'ISO-8859-1') ini.encoding #=> "ISO-8859-1" ``` -------------------------------- ### Cloning, Duplicating, and Freezing INI Files (Ruby) Source: https://context7.com/twp/inifile/llms.txt This snippet illustrates how to create independent copies of INI file objects using standard Ruby methods like `clone` and `dup`. It also touches upon freezing objects to prevent further modifications, ensuring immutability. ```ruby require 'inifile' ini = IniFile.load('config.ini') # Create a shallow copy duplicated_ini = ini.dup # Create a deep copy (if IniFile supports it, otherwise dup is often sufficient for simple structures) cloned_ini = ini.clone # Modify the original and check if copies are affected ini['new_section'] = {'key' => 'value'} # Check if duplicated_ini or cloned_ini were modified (they should not be if dup/clone worked as expected) # Freezing the object to make it immutable ini.freeze # Attempting to modify a frozen object will raise an error # ini['another_section'] = {'key' => 'value'} # This would raise FrozenError ``` -------------------------------- ### Merging INI Files (Ruby) Source: https://context7.com/twp/inifile/llms.txt This demonstrates merging two INI files, combining sections and overwriting duplicate properties. It's useful for layering configurations, like system defaults with user-specific settings. Merging can be done into a new file or in place. ```ruby require 'inifile' # Load base configuration defaults = IniFile.load('defaults.ini') # Contents: [app] debug=false, timeout=30 # Load user overrides user_config = IniFile.load('user.ini') # Contents: [app] debug=true, [custom] feature=enabled # Merge returns new IniFile (originals unchanged) merged = defaults.merge(user_config) puts merged['app']['debug'] #=> true (overridden) puts merged['app']['timeout'] #=> 30 (from defaults) puts merged['custom']['feature'] #=> "enabled" (new section) puts defaults['app']['debug'] #=> false (unchanged) # Merge in place (modifies receiver) defaults.merge!(user_config) puts defaults['app']['debug'] #=> true # Merge with hash directly ini = IniFile.load('config.ini') ini.merge!({ 'overrides' => { 'enabled' => true }, 'database' => { 'pool' => 20 # Override specific property } }) # Merge nil is safe (returns self) ini.merge!(nil) ``` -------------------------------- ### Copying and Freezing IniFile Objects in Ruby Source: https://context7.com/twp/inifile/llms.txt Demonstrates how to create independent copies of IniFile objects using `dup` and `clone`. `dup` creates a mutable copy, while `clone` creates an immutable copy that preserves the frozen state. Freezing an IniFile object makes it immutable, preventing further modifications and raising a `FrozenError` if attempted. ```ruby require 'inifile' # Load an INI file ini = IniFile.load('config.ini') # dup creates independent copy (tainted state copied, not frozen) copy = ini.dup copy['new_section']['key'] = 'value' ini.has_section?('new_section') #=> false (original unchanged) # clone creates copy with frozen state preserved ini.freeze clone = ini.clone clone.frozen? #=> true # Freeze makes INI immutable ini = IniFile.load('config.ini') ini.freeze # ini['section']['key'] = 'value' # Raises FrozenError # Check equality ini1 = IniFile.load('config.ini') ini2 = IniFile.load('config.ini') ini1 == ini2 #=> true ini1.eql?(ini2) #=> true ``` -------------------------------- ### Find Sections Matching Pattern (Ruby) Source: https://context7.com/twp/inifile/llms.txt This snippet demonstrates how to find INI sections that match a given regular expression pattern. It returns a filtered Hash containing only the matching sections and their contents. This is useful for selectively loading or processing parts of a configuration. ```ruby require 'inifile' # Assume 'ini' is an IniFile object loaded with data # Example: ini = IniFile.load('config.ini') # Find sections starting with 'db_' matching = ini.match(/^db_/) #=> {"db_primary" => {...}, "db_replica" => {...}} # Find sections matching 'cache' or 'session' matching = ini.match(/(cache|session)/) #=> {"cache" => {"enabled" => true}, "session" => {"timeout" => 3600}} ``` -------------------------------- ### Reading and Writing INI Files (Ruby) Source: https://context7.com/twp/inifile/llms.txt This section covers saving INI content to the filesystem and reloading it from disk. It supports custom filenames and encodings for both operations. Changes made in memory can be persisted or discarded by reloading. ```ruby require 'inifile' # Create and populate INI file ini = IniFile.new(:filename => 'app.ini') ini['server'] = { 'host' => '0.0.0.0', 'port' => 3000, 'workers' => 4 } ini['database'] = { 'adapter' => 'postgresql', 'host' => 'localhost', 'database' => 'myapp_prod', 'pool' => 10 } # Save to configured filename ini.write # or ini.save # Save to different file ini.write(:filename => 'backup.ini') # Save with specific encoding ini.write(:filename => 'config.ini', :encoding => 'UTF-8') # Reload file from disk (discards in-memory changes) ini['server']['port'] = 9999 # Change in memory ini.read # Reload from disk puts ini['server']['port'] #=> 3000 (original value restored) # Read from different file (replaces current content) ini.read(:filename => 'other_config.ini') # Convert to string (for manual saving or debugging) ini_string = ini.to_s #=> "[server]\nhost = 0.0.0.0\nport = 3000\n..." # Convert to hash config_hash = ini.to_h #=> {"server" => {"host" => "0.0.0.0", "port" => 3000}, ...} ``` -------------------------------- ### Multiline Values and Special Characters (Ruby) Source: https://context7.com/twp/inifile/llms.txt IniFile supports multiline values using backslash continuation or quoted strings. It also handles escape sequences within values, automatically processing them into their literal forms (e.g., tabs, newlines). Comments are also supported. ```ruby require 'inifile' # INI file with multiline values: # [messages] # greeting = Hello \ # World # description = "Line 1 # Line 2 # Line 3" ini = IniFile.load('messages.ini') # Backslash continuation (newlines removed) ini['messages']['greeting'] #=> "Hello World" # Quoted multiline (newlines preserved) ini['messages']['description'] #=> "Line 1\nLine 2\nLine 3" # Escape sequences in values # [special] # with_tab = Hello\tWorld # with_newline = Line1\nLine2 # literal = Use \\t for tab ini = IniFile.load('special.ini') ini['special']['with_tab'] #=> "Hello\tWorld" (actual tab) ini['special']['with_newline'] #=> "Line1\nLine2" (actual newline) ini['special']['literal'] #=> "Use \\t for tab" (literal backslash-t) # Comments can appear inline # [section] # key = value # this is a comment # key2 = "value # not a comment" # but this is ini['section']['key'] #=> "value" ini['section']['key2'] #=> "value # not a comment" ``` -------------------------------- ### Type Casting and Value Handling (Ruby) Source: https://context7.com/twp/inifile/llms.txt Values from INI files are automatically type cast to their corresponding Ruby types (Boolean, Integer, Float, String, nil). Empty strings are converted to nil. When writing, values are properly escaped to maintain their original format. ```ruby require 'inifile' # INI content with various types: content = <<-INI [settings] enabled = true disabled = false count = 42 rate = 3.14159 empty = name = John Doe INI ini = IniFile.new(:content => content) # Automatic type casting ini['settings']['enabled'] #=> true (Boolean) ini['settings']['disabled'] #=> false (Boolean) ini['settings']['count'] #=> 42 (Integer) ini['settings']['rate'] #=> 3.14159 (Float) ini['settings']['empty'] #=> nil (empty string becomes nil) ini['settings']['name'] #=> "John Doe" (String) # Type checking ini['settings']['enabled'].is_a?(TrueClass) #=> true ini['settings']['count'].is_a?(Integer) #=> true ini['settings']['rate'].is_a?(Float) #=> true # Values are escaped when writing ini['output'] = { 'multiline' => "Line1\nLine2", 'with_tab' => "Col1\tCol2" } ini.to_s # [output] # multiline = Line1\nLine2 # with_tab = Col1\tCol2 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.