module Nandi::Formatting

Public Class Methods

included(base) click to toggle source
# File lib/nandi/formatting.rb, line 48
def self.included(base)
  base.extend(ClassMethods)
end

Public Instance Methods

format_value(value, opts = {}) click to toggle source

Create a string representation of the value that is a valid and correct Ruby literal for that value. Please note that the exact representation is not guaranteed to be the same between different platforms and Ruby versions. The guarantee is merely that calling this method with any supported type will produce a string that produces an equal value when it is passed to Kernel::eval @param value [Hash, Array, String, Symbol, Integer, Float, NilClass]

value to format
# File lib/nandi/formatting.rb, line 34
def format_value(value, opts = {})
  case value
  when Hash
    format_hash(value, opts)
  when Array
    "[#{value.map { |v| format_value(v, opts) }.join(', ')}]"
  when String, Symbol, Integer, Float, NilClass, TrueClass, FalseClass
    value.inspect
  else
    raise UnsupportedValueError,
          "Cannot format value of type #{value.class.name}"
  end
end

Private Instance Methods

format_hash(value, opts) click to toggle source
# File lib/nandi/formatting.rb, line 54
def format_hash(value, opts)
  if opts[:as_argument]
    hash_pairs(value).join(", ")
  else
    "{\n  #{hash_pairs(value).join(",\n  ")}\n}"
  end
end
hash_pairs(value) click to toggle source
# File lib/nandi/formatting.rb, line 62
def hash_pairs(value)
  value.map do |k, v|
    key = if k.is_a?(Symbol)
            symbol_key(k)
          else
            "#{format_value(k)} =>"
          end
    "#{key} #{format_value(v)}"
  end
end
symbol_key(key) click to toggle source
# File lib/nandi/formatting.rb, line 73
def symbol_key(key)
  canonical = key.inspect

  "#{canonical[1..-1]}:"
end