Class: Paggio::Formatter

Inherits:
Object
  • Object
show all
Defined in:
lib/paggio/formatter.rb

Constant Summary collapse

OPTIONS =
{
  indent: {
    level: 0,
    with:  "\t"
  }
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io = nil, options = {}) ⇒ Formatter

Returns a new instance of Formatter.



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/paggio/formatter.rb', line 46

def initialize(io = nil, options = {})
  if Hash === io
    @io      = StringIO.new
    @options = io
  else
    @io      = io || StringIO.new
    @options = options
  end

  @options = OPTIONS.merge(@options)
end

Class Method Details

.for(klass, &block) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/paggio/formatter.rb', line 20

def self.for(klass, &block)
  if block
    to_h[klass] = block
  else
    to_h[klass]
  end
end

.options(options, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
# File 'lib/paggio/formatter.rb', line 28

def self.options(options, &block)
  old = OPTIONS.dup
  Utils.deep_merge!(OPTIONS, options)

  result = block.call

  OPTIONS.replace(old)

  result
end

.to_hObject



16
17
18
# File 'lib/paggio/formatter.rb', line 16

def self.to_h
  @formatters ||= {}
end

Instance Method Details

#deindentObject



93
94
95
96
97
# File 'lib/paggio/formatter.rb', line 93

def deindent
  if indent?
    @options[:indent][:level] -= 1
  end
end

#escape(string) ⇒ Object



109
110
111
112
113
114
115
116
# File 'lib/paggio/formatter.rb', line 109

def escape(string)
  string.to_s.gsub(/["><']|&(?!([a-zA-Z]+|(#\d+));)/, {
    '&' => '&amp;',
    '>' => '&gt;',
    '<' => '&lt;',
    '"' => '&quot;',
    "'" => '&#39;' })
end

#format(item) ⇒ Object



58
59
60
61
62
63
64
65
66
67
# File 'lib/paggio/formatter.rb', line 58

def format(item)
  Formatter.to_h.each {|klass, block|
    if klass === item
      block.call(self, item)
      break
    end
  }

  self
end

#indent(&block) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/paggio/formatter.rb', line 79

def indent(&block)
  if indent?
    if block
      @options[:indent][:level] += 1
      block.call
      @options[:indent][:level] -= 1
    else
      @options[:indent][:level] += 1
    end
  else
    block.call if block
  end
end

#indent?(&block) ⇒ Boolean

Returns:

  • (Boolean)


73
74
75
76
77
# File 'lib/paggio/formatter.rb', line 73

def indent?(&block)
  @options[:indent][:level]
rescue
  false
end


99
100
101
102
103
104
105
106
107
# File 'lib/paggio/formatter.rb', line 99

def print(text)
  if level = indent?
    text.lines.each {|line|
      @io.puts "#{@options[:indent][:with] * level}#{line.chomp}"
    }
  else
    @io.print text
  end
end

#to_sObject



69
70
71
# File 'lib/paggio/formatter.rb', line 69

def to_s
  @io.string
end