# encoding: UTF-8 # frozen_string_literal: true # Refinements # ======================================================================= using NRSER using NRSER::Types # Definitions # ======================================================================= # these are functions mapping an `Object` to a `String` for printing. # their names can be used as values for `Object.rash_formatter` to indicate # Rash should use that function to print the object. # module NRSER::Rash::Formatters def self.yaml(obj) require 'yaml' YAML.dump(obj) end # print a white-space formatted key/value table given a hash. # keys and values are printed cast to strings, and nested # hashes are treated as sub-keys: # # NRSER::Rash::Formatters.kv({ # :scheme => "https", # :host => "www.google.com", # :port => 443, # :params => { # :q => "blah", # :oq => "blah", # :aqs => "chrome.0.57j60l4j59.468", # :sourceid => "chrome", # :ie => "UTF-8" # }, # :fragment => nil # }) # # scheme: https # host: www.google.com # port: 443 # params: # q: blah # oq: blah # aqs: chrome.0.57j60l4j59.468 # sourceid: chrome # ie: UTF-8 # fragment: # def self.kv(hash) find_width = lambda do |hash, indent| width = 0 hash.each do |key, value| this_width = if value.is_a? Hash find_width.call(value, indent + 2) else key.to_s.length + indent end if this_width > width width = this_width end end width end width = find_width.call(hash, 0) out = '' write_out = lambda do |hash, indent| hash.each do |key, value| out << ' ' * indent \ << "#{ key }: " \ << ' ' * (width - key.to_s.length - indent) if value.is_a? Hash out << "\n" write_out.call(value, indent + 2) else out << "#{ value }\n" end end end write_out.call(hash, 0) out end def self.json(obj) require 'json' JSON.dump(obj) end def self.json_pp(obj) require 'json' JSON.pretty_generate(obj) end def self.pp(obj) require 'pp' require 'stringio' sio = StringIO.new PP.pp(obj, sio) sio.string end end # module NRSER::Rash::Formatters