Module: NRSER::Rash::Formatters
- Defined in:
- lib/nrser/rash/formatters.rb
Overview
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.
Class Method Summary collapse
- .json(obj) ⇒ Object
- .json_pp(obj) ⇒ Object
-
.kv(hash) ⇒ Object
print a white-space formatted key/value table given a hash.
- .lines(obj) ⇒ Object
- .pp(obj) ⇒ Object
- .yaml(obj) ⇒ Object
Class Method Details
.json(obj) ⇒ Object
87 88 89 90 |
# File 'lib/nrser/rash/formatters.rb', line 87 def self.json(obj) require 'json' JSON.dump(obj) end |
.json_pp(obj) ⇒ Object
92 93 94 95 |
# File 'lib/nrser/rash/formatters.rb', line 92 def self.json_pp(obj) require 'json' JSON.pretty_generate(obj) end |
.kv(hash) ⇒ Object
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:
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/nrser/rash/formatters.rb', line 53 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 |
.lines(obj) ⇒ Object
105 106 107 |
# File 'lib/nrser/rash/formatters.rb', line 105 def self.lines obj obj.join "\n" end |
.pp(obj) ⇒ Object
97 98 99 100 101 102 103 |
# File 'lib/nrser/rash/formatters.rb', line 97 def self.pp(obj) require 'pp' require 'stringio' sio = StringIO.new PP.pp(obj, sio) sio.string end |
.yaml(obj) ⇒ Object
19 20 21 22 |
# File 'lib/nrser/rash/formatters.rb', line 19 def self.yaml(obj) require 'yaml' YAML.dump(obj) end |