### Install Amazing Print gem and clone repository Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Installation commands for the AmazingPrint Ruby gem and cloning its repository from GitHub. ```shell # Installing as Ruby gem $ gem install amazing_print ``` ```shell # Cloning the repository $ git clone git://github.com/amazing-print/amazing_print.git ``` -------------------------------- ### Run all specs with rake Source: https://github.com/amazing-print/amazing_print/blob/main/CONTRIBUTING.md Run the full test suite across all gemfiles. Execute from the project root. ```bash $ rake ``` -------------------------------- ### Example dotfile (~/.config/aprc) setting AmazingPrint.defaults Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/configuration.md Assigns `AmazingPrint.defaults` with custom indent, color, and log_level options. The file is loaded as plain Ruby from `${XDG_CONFIG_HOME}/aprc` (default `~/.config/aprc`) or `~/.aprc`; it is loaded at most once per process, and any `StandardError` during merging is rescued and reported with a warning. ```ruby AmazingPrint.defaults = { indent: -2, color: { hash: :whiteish, class: :white }, log_level: :info } ``` -------------------------------- ### Direct usage example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/colors.md Shows how to call the color methods directly. The cyan method with html: true returns an HTML kbd tag, as shown in the comment output. ```ruby require "amazing_print" puts AmazingPrint::Colors.red("red text") puts AmazingPrint::Colors.greenish("green-ish text") puts AmazingPrint::Colors.cyan("cyan", html: true) # => cyan ``` -------------------------------- ### Use Object#ai to return ASCII string Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Example of using `Object#ai` to get an ASCII-encoded string representation of an object. ```ruby irb> "awesome print".ai => "\e[0;33m\"awesome print\"\e[0m" ``` -------------------------------- ### AmazingPrint.reload! usage example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Shows how to invoke the reload functionality, which uses Inspector.reload_dotfile behind the scenes. ```ruby AmazingPrint.reload! # uses Inspector.reload_dotfile behind the scenes ``` -------------------------------- ### Run specs for a single gemfile with appraisal Source: https://github.com/amazing-print/amazing_print/blob/main/CONTRIBUTING.md Run all specs for a specific gemfile using appraisal. Replace 'rails-3.2' with the desired gemfile name. ```bash $ appraisal rails-3.2 rake ``` -------------------------------- ### limited method with example output Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Limits data to a windowed array with a separator when length exceeds the limit. The example shows output for `ap [1..1000], limit: 5`. ```ruby def limited(data, width, is_hash: false) limit = get_limit_size if data.length <= limit data else head = limit / 2 tail = head - ((limit - 1) % 2) temp = data[0, head] + [nil] + data[-tail, tail] temp[head] = if is_hash "#{indent}#{data[head].strip} .. #{data[data.length - tail - 1].strip}" else "#{indent}[#{head.to_s.rjust(width)}] .. [#{data.length - tail - 1}]" end temp end end ``` ```ruby # ap [1..1000], limit: 5 → # [ [0] 1, [1] 2, [2] .. [997], [998] 999, [999] 1000 ] ``` -------------------------------- ### Create Inspector with custom options Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Example of instantiating an Inspector with indent: 2 and hash_format: :rocket, then using the awesome method to format a hash. ```ruby inspector = AmazingPrint::Inspector.new(indent: 2, hash_format: :rocket) puts inspector.awesome({ a: 1 }) ``` -------------------------------- ### AmazingPrint::Sequel usage examples Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/extensions.md Shows how to print a Sequel model instance, model class, and dataset. The dataset output includes rows plus SQL via `amazing_print(dataset.sql)`. ```ruby ap Album.first # document values ap Album # model class schema ap Album.dataset # rows + SQL ``` -------------------------------- ### HashFormatter usage examples Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows how to call ap with different hash_format options: default symbol syntax, sorted keys, rocket syntax, and JSON syntax. ```ruby ap({ b: 2, a: 1 }) # :symbol syntax, sorted? no ap({ b: 2, a: 1 }, sort_keys: true) # sorted keys ap({ a: 1, b: 2 }, hash_format: :rocket) ap({ a: 1, b: 2 }, hash_format: :json) ``` -------------------------------- ### Usage examples: ap [].methods - Object.methods and ap ''.methods.grep(/!|\?/) Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Shows how to use the patched method arrays with AmazingPrint: subtracting Object.methods from an array's methods and grepping string methods for punctuation. These pipelines rely on the AwesomeMethodArray extension to print as method tuples. ```ruby ap [].methods - Object.methods ap ''.methods.grep(/!|\?/) ``` -------------------------------- ### MethodFormatter usage example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows the output of formatting a bound method with ap. The result is #. ```ruby ap "abc".method(:upcase) # # ``` -------------------------------- ### Usage examples for Logger#ap Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Shows how to call `ap` on a `Logger` instance with different level specifications: default debug, positional symbol shorthand, keyword level, and a hash with additional options like `sort_keys`. ```ruby require "logger" require "amazing_print" logger = Logger.new($stdout) logger.ap({ a: 1 }) # debug level logger.ap({ a: 1 }, :warn) # warn level, positional shorthand logger.ap({ a: 1 }, level: :info) # keyword level logger.ap({ a: 1 }, { level: :info, sort_keys: true }) ``` -------------------------------- ### Kernel#ai usage examples Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Shows typical usage of `ai` after requiring the library. The first call prints a string with ANSI color codes; the second formats a hash with `indent: 2` and `hash_format: :json`. The output for the first call is shown as a comment. ```ruby require "amazing_print" "awesome print".ai # => "\e[0;33m\"awesome print\"\e[0m" { a: 1, b: [1, 2] }.ai(indent: 2, hash_format: :json) ``` -------------------------------- ### DirFormatter usage example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows how to use `DirFormatter` via `ap` on a `Dir` object. The output prints the directory path followed by the `ls -alF` listing. ```ruby ap Dir.new('~') # prints dir path + ls -alF output ``` -------------------------------- ### Indentator usage example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/support-classes.md Shows how `Indentator` tracks indentation. After `indent { ... }`, the indentation is restored to its original value (4). ```ruby ind = AmazingPrint::Indentator.new(4) ind.indentation # => 4 ind.indent { ind.indentation } # => 8 ind.indentation # => 4 (restored) ``` -------------------------------- ### SimpleFormatter usage examples Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows the colorized output for scalar types: integers are blue, times are greenish, and nil is red. ```ruby ap 42 # blue integer ap Time.now # greenish time ap nil # red nil ``` -------------------------------- ### ClassFormatter usage example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows the output of formatting String and BasicObject with ap. String displays as String < Object, while BasicObject displays as BasicObject. ```ruby ap String # => String < Object ap BasicObject # => BasicObject ``` -------------------------------- ### Check colorize on terminal Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Example showing that colorize? returns true on a real terminal. ```ruby puts AmazingPrint::Inspector.new.colorize? # true on a real terminal ``` -------------------------------- ### StructFormatter usage example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows the output format for a Struct instance: prints the struct class name and each member as attr_accessor with its value. ```ruby Point = Struct.new(:x, :y) ap Point.new(3, 4) # # # attr_accessor :x = 3, # attr_accessor :y = 4 ``` -------------------------------- ### Run a specific spec in a gemfile with appraisal Source: https://github.com/amazing-print/amazing_print/blob/main/CONTRIBUTING.md Run a single spec file within a specific gemfile. Adjust the gemfile name and spec path as needed. ```bash $ appraisal rails-3.2 rspec spec/colors_spec.rb ``` -------------------------------- ### Colorize usage examples: colorize with :string type Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/colors.md Shows example calls to colorize inside a formatter subclass. The first call returns an ANSI escape sequence for yellowish text on a TTY. The second call, when options[:html] is true, returns an HTML span with a yellow color style. ```ruby # Inside any formatter subclass (BaseFormatter includes Colorize): colorize("hello", :string) # => "\e[0;33mhello\e[0m" (yellowish, on a TTY) colorize("hello", :string, ) if options[:html] # => "hello" ``` -------------------------------- ### HashFormatter error handling example Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Demonstrates rescuing InvalidHashFormatError when an unsupported hash_format (e.g., :xml) is passed to ap. ```ruby begin ap({ a: 1 }, hash_format: :xml) rescue AmazingPrint::Formatters::HashFormatter::InvalidHashFormatError => e warn e.message end ``` -------------------------------- ### Use increase_indentation Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Example showing that inside the block, indentation is increased by 4 (the default shift width). ```ruby inspector.increase_indentation do # indentation is now +4 inside here end ``` -------------------------------- ### Reload dotfile with AmazingPrint.reload! Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/configuration.md Resets the cached dotfile path so the configuration is reloaded after editing, for example inside IRB. The cache is also reset by `Inspector.reload_dotfile`. ```ruby AmazingPrint.reload! ``` -------------------------------- ### Colorize strings with AmazingPrint::Colors.red Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Use methods like `.red` to set string color. The example shows the output `red text` (which is red). ```ruby irb> puts AmazingPrint::Colors.red("red text") red text # (it's red) ``` -------------------------------- ### Example usage of ObjectFormatter with Point class Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows how to use the formatter with a Point class and various options: raw, sort_vars, and class_name/object_id. The comment notes that raw: true follows the same path for ActiveRecord objects. ```ruby class Point attr_accessor :x, :y def initialize(x, y) = (@x, @y = x, y) end ap Point.new(1, 2) # instance vars only ap Point.new(1, 2), raw: true # same path for AR objects ap Point.new(1, 2), sort_vars: false ap Point.new(1, 2), class_name: :to_s, object_id: false ``` -------------------------------- ### Left-align hash keys with :indent => -2 Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Uses `ap data, :indent => -2` to left-align hash keys in the output. The example shows the resulting output for a hash with Time and class values. ```ruby $ cat > 2.rb require "amazing_print" data = { :now => Time.now, :class => Time.now.class, :distance => 42e42 } ap data, :indent => -2 # <-- Left align hash keys. ^D $ ruby 2.rb { :class => Time < Object, :now => Fri Apr 02 19:55:53 -0700 2010, :distance => 4.2e+43 } ``` -------------------------------- ### ArrayFormatter usage examples Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Shows common invocations of ArrayFormatter via `ap`. The first uses default multiline with indices, the second disables indices, the third disables multiline, and the fourth limits output to 2 items. ```ruby ap [1, 2, 3] # multiline with indices ap [1, 2, 3], index: false # no indices ap [1, 2, 3], multiline: false ap [1, 2, 3], limit: 2 ``` -------------------------------- ### Formatter#format usage examples Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatter.md Shows calling format with an explicit :array type and with a Time object where type is nil, causing cast to return :self and use the inspect path. ```ruby formatter.format([1, 2], :array) # => "[\n [0] 1,\n [1] 2\n]" formatter.format(Time.now) # type nil → cast → :self → inspect path ``` -------------------------------- ### Setting up AmazingPrint.pry! in ~/.pryrc Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Shows the recommended ~/.pryrc configuration to enable AmazingPrint as the default Pry printer. ```ruby # ~/.pryrc require "amazing_print" AmazingPrint.pry! ``` -------------------------------- ### Per-call configuration with AmazingPrint Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/configuration.md Shows how to use per-call options to override global defaults, set programmatic defaults via AmazingPrint.defaults, and force colorized output with AmazingPrint.force_colors! even when stdout is not a TTY. Requires the amazing_print gem. Per-call options override every layer above; force_colors! is useful for forked subprocesses. ```ruby require "amazing_print" data = { b: 2, a: 1 } # Per-call options override every layer above. ap data, indent: 2, sort_keys: true, hash_format: :rocket, colors: :all # Programmatic global default (equivalent to an aprc assignment). AmazingPrint.defaults = { indent: -2, object_id: false } # Force colorized output even when stdout is not a TTY (e.g. forked subprocess). AmazingPrint.force_colors!(colors: true) ``` -------------------------------- ### Get current indentation Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Returns the current indentation depth managed by the Indentator. ```ruby def current_indentation indentator.indentation end ``` -------------------------------- ### #initialize(options = {}) Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Creates a new Inspector instance with configurable options for formatting output. Options are merged from built-in defaults, the `aprc` dotfile, and explicit parameters. ```APIDOC ## #initialize(options = {}) ### Description Creates a new Inspector instance with configurable options for formatting output. Options are merged from built-in defaults, the `aprc` dotfile, and explicit parameters. ### Method Constructor ### Parameters - **options** (Hash) - Optional - Configuration options. See full table in configuration documentation. ### Return New `Inspector` instance. ### Behavior - Options merge order: built-ins → `AmazingPrint.defaults` (via `merge_custom_defaults!`, which loads the `aprc` dotfile once) → explicit `options` (via `merge_options!`, which special-cases `:color` merging and the deprecated `:plain` → `colors: :none`). - The `Indentator` is created with `options[:indent].abs`. - `Thread.current[AP]` recursion stack is lazily initialized. - `ExtLoader.call` retries loading ORM extensions (guarded by its own attempt limit). ### Example ```ruby inspector = AmazingPrint::Inspector.new(indent: 2, hash_format: :rocket) puts inspector.awesome({ a: 1 }) ``` ``` -------------------------------- ### Setting up AmazingPrint.irb! in ~/.irbrc Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Shows the recommended ~/.irbrc configuration to enable AmazingPrint as the default IRB formatter. ```ruby # ~/.irbrc require "amazing_print" AmazingPrint.irb! ``` -------------------------------- ### Format self-referential array Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Example showing that a self-referential array is formatted with a placeholder [...] for the nested reference. ```ruby arr = [1, 2] arr << arr puts AmazingPrint::Inspector.new.awesome(arr) # [ # [0] 1, # [1] 2, # [2] [...] # ] ``` -------------------------------- ### Set custom defaults in ~/.config/aprc file Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Create an `aprc` file in `$XDG_CONFIG_HOME` (defaults to `~/.config`) and assign defaults to `AmazingPrint.defaults`. The previous `~/.aprc` location is still supported as a fallback. ```ruby # ~/.config/aprc file. AmazingPrint.defaults = { :indent => -2, :color => { :hash => :whiteish, :class => :white } } ``` -------------------------------- ### Basic usage of Kernel#ap with options Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Requires amazing_print and shows ap printing an array with mixed types. Demonstrates options indent, multiline, and limit for windowed output, and that ap returns the object in scripts (prints 42, true). ```ruby require "amazing_print" data = [false, 42, %w[forty two], { now: Time.now, distance: 42e42 }] ap data ap data, indent: -2 # left-align hash keys ap data, multiline: false # single line ap data, limit: true # windowed output ap (1..1000).to_a, limit: 5 # integer window ap 42 == ap(42) # ap returns the object in scripts => prints 42, true ``` -------------------------------- ### #initialize(inspector) Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatter.md Creates a new Formatter instance, storing the inspector and aliasing options to the inspector's options hash. ```APIDOC ## #initialize(inspector) ### Description Creates a new Formatter instance, storing the inspector and aliasing options to the inspector's options hash. ### Method initialize ### Parameters - **inspector** (AmazingPrint::Inspector) - Required - The inspector instance. ### Return New Formatter instance. ### Example ```ruby inspector = AmazingPrint::Inspector.new formatter = AmazingPrint::Formatter.new(inspector) ``` ``` -------------------------------- ### AmazingPrint.defaults, .force_colors, .force_colors!, .console?, .rails_console?, .diet_rb, .usual_rb, .irb!, .pry!, .rdbg!, .reload!, .version Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Module functions on AmazingPrint that control configuration, environment detection, and version information. ```APIDOC ## AmazingPrint.defaults, .force_colors, .force_colors!, .console?, .rails_console?, .diet_rb, .usual_rb, .irb!, .pry!, .rdbg!, .reload!, .version ### Description Module functions on AmazingPrint that control configuration, environment detection, and version information. ### Functions - defaults - force_colors - force_colors! - console? - rails_console? - diet_rb - usual_rb - irb! - pry! - rdbg! - reload! - version ### Usage Call these functions to manage AmazingPrint behavior. ``` -------------------------------- ### Kernel#ai(options = {}) Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Formats the receiver (self) using AmazingPrint and returns the formatted string. Accepts configuration options, including html: true to wrap output in
 tags and mark it html_safe when ActiveSupport is present. Aliased as awesome_inspect.

```APIDOC
## Kernel#ai(options = {})

### Description
Formats the receiver (self) using AmazingPrint and returns the formatted string. Accepts configuration options, including `html: true` to wrap output in `
…
` and mark it `html_safe` when ActiveSupport is present. Aliased as `awesome_inspect`. ### Method `ai` (instance method on Kernel) ### Signature `ai(options = {})` ### Parameters - `options` (Hash) - Optional - Any option from the configuration table. `html: true` wraps output in `
…
` and marks it `html_safe` when ActiveSupport is present. ### Return String - The ASCII/ANSI formatted representation of `self` (no trailing newline). ### Aliases - `awesome_inspect` ### Errors - Propagates `AmazingPrint::Formatters::HashFormatter::InvalidHashFormatError` and `NoMethodError` from formatting internals. ### Example ```ruby require "amazing_print" "awesome print".ai # => "\e[0;33m\"awesome print\"\e[0m" { a: 1, b: [1, 2] }.ai(indent: 2, hash_format: :json) ``` ### Error Handling Example ```ruby begin [1, 2, 3].ai(hash_format: :bogus) rescue AmazingPrint::Formatters::HashFormatter::InvalidHashFormatError => e puts e.message end ``` ``` -------------------------------- ### Setting AmazingPrint.defaults and using ap Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Shows setting custom default options and calling ap with an option. The comment notes this can be done in a script. ```ruby AmazingPrint.defaults = { indent: -2, color: { hash: :whiteish } } # In a script you can also do: ap(123, object_id: false) ``` -------------------------------- ### Default options for AmazingPrint Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Shows the default configuration options for AmazingPrint, including indentation, colors, and formatting settings. ```ruby indent: 4, # Number of spaces for indenting. index: true, # Display array indices. html: false, # Use ANSI color codes rather than HTML. multiline: true, # Display in multiple lines. colors: :values_only, # Controls what should be colored. Can be one of :all, :values_only, or :none raw: false, # Do not recursively format instance variables. sort_keys: false, # Do not sort hash keys. sort_vars: true, # Sort instance variables. limit: false, # Limit arrays & hashes. Accepts bool or int. hash_format: :symbol, # The format for printing hashes. Can be one of :json, :rocket, or :symbol class_name: :class, # Method called to report the instance class name. (e.g. :to_s) object_id: true, # Show object id. color: { args: :whiteish, array: :white, bigdecimal: :blue, class: :yellow, date: :greenish, falseclass: :red, integer: :blue, float: :blue, hash: :whiteish, keyword: :cyan, method: :purpleish, nilclass: :red, rational: :blue, string: :yellowish, struct: :whiteish, symbol: :cyanish, time: :greenish, trueclass: :green, variable: :cyanish } ``` -------------------------------- ### Initialize Inspector with options Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Constructor for the Inspector class. Sets default options including indent, index, html, multiline, colors, raw, sort_keys, sort_vars, limit, hash_format, class_name, object_id, and a color map. Merges custom defaults from AmazingPrint.defaults and explicit options, creates Formatter and Indentator instances, initializes the thread-local recursion stack, and calls ExtLoader to retry loading ORM extensions. ```ruby def initialize(options = {}) @options = { indent: 4, # Number of spaces for indenting. index: true, # Display array indices. html: false, # Use ANSI color codes rather than HTML. multiline: true, # Display in multiple lines. colors: :values_only, # Controls what should be colored. Can be one of :all, :values_only, or :none raw: false, # Do not recursively format instance variables. sort_keys: false, # Do not sort hash keys. sort_vars: true, # Sort instance variables. limit: false, # Limit arrays & hashes. Accepts bool or int. hash_format: :symbol, # The format for printing hashes. Can be one of :json, :rocket, or :symbol class_name: :class, # Method used to get Instance class name. object_id: true, # Show object_id. color: { args: :whiteish, array: :white, bigdecimal: :blue, class: :yellow, date: :greenish, falseclass: :red, fixnum: :blue, integer: :blue, float: :blue, hash: :whiteish, keyword: :cyan, method: :purpleish, nilclass: :red, rational: :blue, string: :yellowish, struct: :whiteish, symbol: :cyanish, time: :greenish, trueclass: :green, variable: :cyanish } } # Merge custom defaults and let explicit options parameter override them. merge_custom_defaults! merge_options!(options) @formatter = AmazingPrint::Formatter.new(self) @indentator = AmazingPrint::Indentator.new(@options[:indent].abs) Thread.current[AP] ||= [] ExtLoader.call end ``` -------------------------------- ### Use ap in ERB and HAML templates Source: https://github.com/amazing-print/amazing_print/blob/main/README.md amazing_print adds `ap` to `ActionView::Base` for use in Rails templates. The ERB and HAML examples are shown together as equivalent renderings. ```erb <%= ap @accounts.first %> # ERB ``` ```haml != ap @accounts.first # HAML ``` -------------------------------- ### Call ap with additional options and level Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Pass additional options to `ap`; providing `nil` or omitting `level` logs at the default level. ```ruby logger.ap object, { level: :info, sort_keys: true } ``` -------------------------------- ### PRY integration with AmazingPrint.pry! Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Add this code to `~/.pryrc` to use amazing_print's formatting in place of pry's default output. ```ruby require "amazing_print" AmazingPrint.pry! ``` -------------------------------- ### Disable multiline output with :multiline => false Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Shows how `ap data, :multiline => false` prints a nested array on a single line. The example includes a self-referential array, which is displayed as `[...]`. ```ruby $ cat > 3.rb require "amazing_print" data = [ false, 42, %w(forty two) ] data << data # <-- Nested array. ap data, :multiline => false ^D $ ruby 3.rb [ false, 42, [ "forty", "two" ], [...] ] ``` -------------------------------- ### AmazingPrint::Indentator, AmazingPrint::JSONHelper, AmazingPrint::ExtLoader Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Internal helper classes for indentation, JSON handling, and extension loading. ```APIDOC ## AmazingPrint::Indentator, AmazingPrint::JSONHelper, AmazingPrint::ExtLoader ### Description Internal helper classes for indentation, JSON handling, and extension loading. ### Classes - Indentator - JSONHelper - ExtLoader ### Usage These are internal helpers used by AmazingPrint. ``` -------------------------------- ### Display method signatures with ap Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Prints the result of `Hello.methods - Class.methods` to show method signatures. The output includes the method name, parameters, and the class name. ```ruby $ cat > 4.rb require "amazing_print" class Hello def self.world(x, y, z = nil, &blk) end end ap Hello.methods - Class.methods ^D $ ruby 4.rb [ [0] world(x, y, *z, &blk) Hello ] ``` -------------------------------- ### Indentation helpers Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatters.md Provides methods to get current indentation, yield with increased indentation, generate indentation strings (cached 0–100), and outdent by one indent unit. ```ruby def indentation inspector.current_indentation end def indented(&) inspector.increase_indentation(&) end INDENT_CACHE = (0..100).map { |i| ' ' * i }.map(&:freeze).freeze def indent(n = indentation) INDENT_CACHE[n] || (' ' * n) end def outdent i = indentation - options[:indent].abs INDENT_CACHE[i] || (' ' * i) end ``` -------------------------------- ### AmazingPrint::Colorize, AmazingPrint::Colors Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Color modules that provide colorization support for output. ```APIDOC ## AmazingPrint::Colorize, AmazingPrint::Colors ### Description Color modules that provide colorization support for output. ### Modules - Colorize - Colors ### Usage Use these modules to apply colors to output. ``` -------------------------------- ### Using ap with grep on method array Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Shows ap printing the result of filtering methods with grep, demonstrating the method-array extension output. ```ruby ap [1, 2, 3].methods.grep(/^su/) ``` -------------------------------- ### Using AmazingPrint.version Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Requires amazing_print and prints the version, outputting 3.0.0. ```ruby require "amazing_print" puts AmazingPrint.version # => 3.0.0 ``` -------------------------------- ### Backwards-compatibility shim in lib/ap.rb Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/support-classes.md Entry point that allows `require "ap"` with identical behavior to `require "amazing_print"`. ```ruby require_relative 'amazing_print' ``` -------------------------------- ### Object#methods, private_methods, protected_methods, public_methods, singleton_methods Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Patched instance methods on Object that return arrays of method names. These are enhanced to provide better formatting and filtering capabilities. ```APIDOC ## Object#methods, private_methods, protected_methods, public_methods, singleton_methods ### Description Patched instance methods on Object that return arrays of method names. These are enhanced to provide better formatting and filtering capabilities. ### Methods - methods - private_methods - protected_methods - public_methods - singleton_methods ### Returns Array of method names. ``` -------------------------------- ### Kernel#ai implementation with html option Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Defines the primary user-facing method `Kernel#ai`, which creates an `AmazingPrint::Inspector`, formats `self`, and optionally wraps output in `
` tags and marks it `html_safe` when ActiveSupport is present. Aliased as `awesome_inspect`. Loaded by `require "amazing_print"` or `require "ap"`.

```ruby
def ai(options = {})
  ap = AmazingPrint::Inspector.new(options)
  awesome = ap.awesome self
  if options[:html]
    awesome = "
#{awesome}
" awesome = awesome.html_safe if defined? ActiveSupport end awesome end alias awesome_inspect ai ``` -------------------------------- ### Kernel32 Fiddle import for GetFileAttributesA Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/support-classes.md mswin-only Fiddle-based import of the Win32 GetFileAttributesA function, used for ls-style output on Windows. Source: lib/amazing_print/formatters/mswin_helper.rb. ```ruby module Kernel32 extend Fiddle::Importer dlload 'kernel32' extern 'unsigned long GetFileAttributesA(const char*)' end ``` -------------------------------- ### Request HTML formatting in Sinatra templates Source: https://github.com/amazing-print/amazing_print/blob/main/README.md For other web frameworks like Sinatra, explicitly request HTML formatting with `:html => true`. ```erb <%= ap @accounts.first, :html => true %> ``` -------------------------------- ### Initialize Formatter with Inspector Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/formatter.md Creates a new Formatter instance by passing an AmazingPrint::Inspector. The formatter stores the inspector and aliases options to inspector.options. ```ruby inspector = AmazingPrint::Inspector.new formatter = AmazingPrint::Formatter.new(inspector) ``` -------------------------------- ### JSONHelper usage with custom to_json Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/support-classes.md Demonstrates `json_awesome` with `hash_format: :json`. The key `"order"` is printed as a string, and the `Order` value is JSON-stringified via its custom `to_json` method. ```ruby require "amazing_print" require "json" class Order def to_json(*) = '{"custom":1}' def inspect = "#" end ap({ order: Order.new }, hash_format: :json) # key "order" is printed as a string; the Order value is JSON-stringified ``` -------------------------------- ### AmazingPrint.defaults Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Allows setting custom default options for AmazingPrint by assigning a hash to `AmazingPrint.defaults`. This is typically done in an `aprc` file. ```APIDOC ## AmazingPrint.defaults ### Description Allows setting custom default options for AmazingPrint by assigning a hash to `AmazingPrint.defaults`. This is typically done in an `aprc` file. ### Method AmazingPrint.defaults= ### Signature AmazingPrint.defaults = { ... } ### Parameters - **options** (Hash) - Required - A hash of default options. Supported keys include `:indent` and `:color`. ### Example ```ruby AmazingPrint.defaults = { :indent => -2, :color => { :hash => :whiteish, :class => :white } } ``` ### Notes - The `aprc` file should be placed in `$XDG_CONFIG_HOME` (defaults to `~/.config`). - The previous `~/.aprc` location is still supported as a fallback. ``` -------------------------------- ### AmazingPrint.pry! Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Sets Pry.print to a proc that pages value.ai. Returns nil when Pry is not defined. ```APIDOC ## AmazingPrint.pry! ### Description Sets Pry.print to a proc that pages value.ai. Returns nil when Pry is not defined. ### Method `AmazingPrint.pry!` ### Return - **nil** if Pry is not defined. - The assigned proc otherwise. ### Example ```ruby # ~/.pryrc require "amazing_print" AmazingPrint.pry! ``` ``` -------------------------------- ### ActionView::Base#ap / #ap_debug Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Patched instance methods on ActionView::Base that provide pretty-printing and debugging output in views. ```APIDOC ## ActionView::Base#ap / #ap_debug ### Description Patched instance methods on ActionView::Base that provide pretty-printing and debugging output in views. ### Methods - ap - ap_debug ### Usage Call these methods within view templates to output formatted object representations. ``` -------------------------------- ### merge_custom_defaults! Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Loads the dotfile and merges AmazingPrint.defaults if it is a Hash. Rescues StandardError and prints a warning if the '.aprc' file cannot be loaded from ENV['HOME']. ```ruby def merge_custom_defaults! load_dotfile merge_options!(AmazingPrint.defaults.dup) if AmazingPrint.defaults.is_a?(Hash) rescue StandardError => e warn "Could not load '.aprc' from ENV['HOME']: #{e}" end ``` -------------------------------- ### Using ap with method arrays Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Shows ap printing arrays of methods, relying on the method-array extension to display name(args) Owner tuples. Works with the patched Object methods. ```ruby ap Hello.methods - Class.methods ap ''.methods.grep(/!/) ``` -------------------------------- ### AmazingPrint::ActiveRecord, ActiveSupport, MongoMapper, Mongoid, NoBrainer, Nokogiri, OpenStruct, Ripple, Sequel Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Extension modules that are included into Formatter to provide support for various frameworks and libraries. ```APIDOC ## AmazingPrint::ActiveRecord, ActiveSupport, MongoMapper, Mongoid, NoBrainer, Nokogiri, OpenStruct, Ripple, Sequel ### Description Extension modules that are included into Formatter to provide support for various frameworks and libraries. ### Modules - ActiveRecord - ActiveSupport - MongoMapper - Mongoid - NoBrainer - Nokogiri - OpenStruct - Ripple - Sequel ### Usage These modules extend the Formatter to handle specific object types. ``` -------------------------------- ### Kernel#ap implementation with alias and module_function Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Defines Kernel#ap to print object.ai(options) via puts and return the object unless AmazingPrint.console? is true. Aliased as amazing_print and exposed as a module function, making it available as a private instance method and Kernel.ap. ```ruby def ap(object, options = {}) puts object.ai(options) object unless AmazingPrint.console? end alias amazing_print ap module_function :ap ``` -------------------------------- ### Require and use AmazingPrint with ap Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Basic usage: require the library and call `ap` with an object and optional options hash. ```ruby require "amazing_print" ap object, options = {} ``` -------------------------------- ### List String methods with ap Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Shows the output of `ap (''.methods - Object.methods).grep(/!/)` which lists all String methods ending with `!`. The output includes method names, parameters, and the class name. ```ruby $ cat > 5.rb require "amazing_print" ap (''.methods - Object.methods).grep(/!/) ^D $ ruby 5.rb [ [ 0] capitalize!() String [ 1] chomp!(*arg1) String [ 2] chop!() String [ 3] delete!(*arg1) String [ 4] downcase!() String [ 5] encode!(*arg1) String [ 6] gsub!(*arg1) String [ 7] lstrip!() String [ 8] next!() String [ 9] reverse!() String [10] rstrip!() String [11] slice!(*arg1) String [12] squeeze!(*arg1) String [13] strip!() String [14] sub!(*arg1) String [15] succ!() String [16] swapcase!() String [17] tr!(arg1, arg2) String [18] tr_s!(arg1, arg2) String [19] upcase!() String ] ``` -------------------------------- ### Class#instance_methods, private_instance_methods, protected_instance_methods, public_instance_methods Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Patched instance methods on Class that return arrays of instance method names. These are enhanced to provide better formatting and filtering capabilities. ```APIDOC ## Class#instance_methods, private_instance_methods, protected_instance_methods, public_instance_methods ### Description Patched instance methods on Class that return arrays of instance method names. These are enhanced to provide better formatting and filtering capabilities. ### Methods - instance_methods - private_instance_methods - protected_instance_methods - public_instance_methods ### Returns Array of instance method names. ``` -------------------------------- ### Kernel#ai(options = {}) Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Instance method that provides an alias for awesome_inspect. It returns a string representation of the object using AmazingPrint's formatting. ```APIDOC ## Kernel#ai(options = {}) ### Description Instance method that provides an alias for awesome_inspect. It returns a string representation of the object using AmazingPrint's formatting. ### Method ai ### Parameters #### Options - **options** (Hash) - Optional - Options to customize the output. ### Returns String representation of the object. ``` -------------------------------- ### AwesomeMethodArray#-&grep Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/index.md Module mixed into method arrays that provides a `-` operator and `grep` method for filtering method names. ```APIDOC ## AwesomeMethodArray#-&grep ### Description Module mixed into method arrays that provides a `-` operator and `grep` method for filtering method names. ### Methods - `-` (subtraction) - grep ### Usage Filter method arrays using these methods. ``` -------------------------------- ### AmazingPrint::Logger#ap implementation Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Defines the `ap` method for `Logger` and `ActiveSupport::BufferedLogger` (when defined). It accepts an object and options, resolves the log level from `options[:level]`, `AmazingPrint.defaults[:log_level]`, or defaults to `:debug`, then sends the level to the logger with the object's `ai` output. ```ruby module AmazingPrint module Logger def ap(object, options = {}) if options.is_a?(Hash) level = options.delete(:level) else level = options options = {} end level ||= AmazingPrint.defaults[:log_level] if AmazingPrint.defaults level ||= :debug send level, object.ai(options) end end end Logger.include AmazingPrint::Logger ActiveSupport::BufferedLogger.include AmazingPrint::Logger if defined?(ActiveSupport::BufferedLogger) ``` -------------------------------- ### Logger#ap(object, options = {}) Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/kernel-and-core-ext.md Logs an object using AmazingPrint's pretty printer at a configurable log level. The level is resolved from the options hash, global defaults, or defaults to :debug. ```APIDOC ## Logger#ap(object, options = {}) ### Description Logs an object using AmazingPrint's pretty printer at a configurable log level. The level is resolved from the options hash, global defaults, or defaults to :debug. ### Method ap ### Signature `ap(object, options = {})` ### Parameters - **object** (Object) - Required - Object to log. - **options** (Hash or Symbol) - Optional - Either a Hash (level taken from the `:level` key, remaining keys passed to `ai`) or a Symbol (used directly as the log level). ### Level Resolution Order 1. `options[:level]` 2. `AmazingPrint.defaults[:log_level]` 3. `:debug` ### Return Value Result of `logger.send level, string` (normally `true` for Logger). ### Example ```ruby require "logger" require "amazing_print" logger = Logger.new($stdout) logger.ap({ a: 1 }) # debug level logger.ap({ a: 1 }, :warn) # warn level, positional shorthand logger.ap({ a: 1 }, level: :info) # keyword level logger.ap({ a: 1 }, { level: :info, sort_keys: true }) ``` ``` -------------------------------- ### ap returns its argument Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Demonstrates that `ap` returns its argument, as shown by `ap 42 == ap(42)` printing `42` and then `true`. ```ruby $ cat > 6.rb require "amazing_print" ap 42 == ap(42) ^D $ ruby 6.rb 42 true ``` -------------------------------- ### Using AmazingPrint.force_colors! in a forked subprocess Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Forces colorized output in a forked child process where TERM might be dumb, then prints a string with ap. ```ruby begin pid = fork do AmazingPrint.force_colors! ap "still colored in the child" end Process.wait(pid) end ``` -------------------------------- ### find_dotfile Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/inspector.md Locates the configuration dotfile. Returns ${XDG_CONFIG_HOME}/aprc if it exists, otherwise falls back to ~/.aprc. Uses XDG_CONFIG_HOME environment variable or defaults to ~/.config. ```ruby def find_dotfile xdg_config_home = File.expand_path(ENV.fetch('XDG_CONFIG_HOME', '~/.config')) xdg_config_path = File.join(xdg_config_home, 'aprc') # ${XDG_CONFIG_HOME}/aprc return xdg_config_path if File.exist?(xdg_config_path) File.join(Dir.home, '.aprc') end ``` -------------------------------- ### AmazingPrint.force_colors! Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Forces colorized output, useful for forked subprocesses where TERM might be dumb. Accepts an optional keyword argument to set the force_colors flag. ```APIDOC ## AmazingPrint.force_colors! ### Description Forces colorized output, useful for forked subprocesses where TERM might be dumb. ### Method `AmazingPrint.force_colors!` ### Parameters - **colors** (Boolean, keyword, default: true) - Whether to force colors. ### Return - The assigned value. ### Example ```ruby begin pid = fork do AmazingPrint.force_colors! ap "still colored in the child" end Process.wait(pid) end ``` ``` -------------------------------- ### Using colors as configuration values Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/colors.md The color method names (e.g., :whiteish, :white) are accepted as values for the color: option in the ap method, keyed by type. ```ruby ap data, color: { hash: :whiteish, class: :white } ``` -------------------------------- ### Supported color names for AmazingPrint Source: https://github.com/amazing-print/amazing_print/blob/main/README.md Lists the color names that can be used in the `color` option. ```ruby :gray, :red, :green, :yellow, :blue, :purple, :cyan, :white :grayish, :redish, :greenish, :yellowish, :blueish, :purpleish, :cyanish, :whiteish ``` -------------------------------- ### AmazingPrint.version method definition Source: https://github.com/amazing-print/amazing_print/blob/main/_autodocs/api-reference/amazing-print-module.md Returns the gem version as a String. Defined in lib/amazing_print/version.rb. ```ruby def self.version '3.0.0' end ```