Created
April 26, 2019 09:18
-
-
Save troelskn/d4f2b19687b0f73dcbba5f40111b445c to your computer and use it in GitHub Desktop.
Ruby pretty print with rubocop standard syntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RubyPrint | |
def self.pp(mixed) | |
puts new.transform(mixed) | |
end | |
def transform(mixed, indentation = 1) | |
if mixed.is_a?(Hash) | |
transform_hash mixed, indentation | |
elsif mixed.is_a?(Array) | |
transform_array mixed, indentation | |
elsif mixed.is_a?(Date) | |
"Date.parse(#{mixed.inspect.inspect})" | |
elsif mixed.is_a?(Time) | |
"Time.parse(#{mixed.inspect.inspect})" | |
else | |
mixed.inspect | |
end | |
end | |
def transform_hash(hash, indentation = 1) | |
indent_string = " " * indentation | |
buffer = [] | |
buffer << "{" | |
compiled = hash.map do |key, item| | |
indent_string + key.to_s + ": " + transform(item, indentation + 1) | |
end | |
buffer << compiled.join(",\n") | |
buffer << (" " * (indentation - 1)) + "}" | |
buffer.join("\n") | |
end | |
def transform_array(array, indentation = 1) | |
return "[]" if array.empty? | |
return "[#{transform(array.first, indentation)}]" \ | |
if array.size == 1 | |
indent_string = " " * indentation | |
buffer = [] | |
buffer << "[" | |
compiled = array.map do |item| | |
indent_string + transform(item, indentation + 1) | |
end | |
buffer << compiled.join(",\n") | |
buffer << (" " * (indentation - 1)) + "]" | |
buffer.join("\n") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment