Class: Paggio::Formatter
- Inherits:
-
Object
- Object
- Paggio::Formatter
- Defined in:
- lib/paggio/formatter.rb
Constant Summary collapse
- OPTIONS =
{ indent: { level: 0, with: "\t" } }
Class Method Summary collapse
Instance Method Summary collapse
- #deindent ⇒ Object
- #escape(string) ⇒ Object
- #format(item) ⇒ Object
- #indent(&block) ⇒ Object
- #indent?(&block) ⇒ Boolean
-
#initialize(io = nil, options = {}) ⇒ Formatter
constructor
A new instance of Formatter.
- #print(text) ⇒ Object
- #to_s ⇒ Object
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, = {}) if Hash === io @io = StringIO.new @options = io else @io = io || StringIO.new @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.(, &block) old = OPTIONS.dup Utils.deep_merge!(OPTIONS, ) result = block.call OPTIONS.replace(old) result end |
.to_h ⇒ Object
16 17 18 |
# File 'lib/paggio/formatter.rb', line 16 def self.to_h @formatters ||= {} end |
Instance Method Details
#deindent ⇒ Object
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+));)/, { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }) 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
73 74 75 76 77 |
# File 'lib/paggio/formatter.rb', line 73 def indent?(&block) @options[:indent][:level] rescue false end |
#print(text) ⇒ Object
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_s ⇒ Object
69 70 71 |
# File 'lib/paggio/formatter.rb', line 69 def to_s @io.string end |