Sha256: b574b0d63d3b0a6f54017ee8203e9524f4765d11407d58bf1d4109bf57418815

Contents?: true

Size: 1.02 KB

Versions: 3

Compression:

Stored size: 1.02 KB

Contents

module Museo
  class Formatter
    def initialize(options = {})
      @indent = options.delete(:indent) || "  ".freeze
    end

    def format(object, indent_level = 0)
      case object
      when Hash
        format_hash(object, indent_level)
      when Array
        format_array(object, indent_level)
      else
        format_value(object)
      end
    end

    private

    def format_hash(hash, indent_level)
      [
        "{",
        hash.map do |key, value|
          "#{@indent * (indent_level + 1)}#{format(key)} => #{format(value, indent_level + 1)},"
        end,
        "#{@indent * indent_level}}",
      ].join("\n")
    end

    def format_array(array, indent_level)
      [
        "[",
        array.map do |value|
          "#{@indent * (indent_level + 1)}#{format(value, indent_level + 1)},"
        end,
        "#{@indent * indent_level}]",
      ].join("\n")
    end

    def format_value(value)
      case value
      when Symbol
        value.inspect
      else
        value.to_s
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
museo-0.3.0 lib/museo/formatter.rb
museo-0.2.0 lib/museo/formatter.rb
museo-0.1.0 lib/museo/formatter.rb