Class: StringBuilder

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/string_builder.rb,
lib/string_builder/version.rb,
lib/string_builder/concat/default.rb

Direct Known Subclasses

InnerStringBuilder, ScopedStringBuilder

Defined Under Namespace

Modules: Concat Classes: Buffer

Constant Summary collapse

VERSION =
"1.2.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&custom_concat) ⇒ StringBuilder

Returns a new instance of StringBuilder.



21
22
23
24
# File 'lib/string_builder.rb', line 21

def initialize(&custom_concat)
  @buffer = Buffer.new
  @concat_handler = custom_concat || Concat::Default
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, **kwargs, &_block) ⇒ Object (private)



56
57
58
59
60
61
62
63
64
# File 'lib/string_builder.rb', line 56

def method_missing(name, *args, **kwargs, &_block)
  tap do
    if kwargs.empty?
      @buffer << [name.to_s, args]
    else
      @buffer << [name.to_s, [*args, kwargs]]
    end
  end
end

Instance Attribute Details

#concat_handlerObject

Returns the value of attribute concat_handler.



19
20
21
# File 'lib/string_builder.rb', line 19

def concat_handler
  @concat_handler
end

Instance Method Details

#call(token) ⇒ Object



46
47
48
49
50
# File 'lib/string_builder.rb', line 46

def call(token)
  tap do
    @buffer << [token.to_s, []]
  end
end

#each(&block) ⇒ Object



42
43
44
# File 'lib/string_builder.rb', line 42

def each(&block)
  @buffer.each(&block)
end

#to_s(&block) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/string_builder.rb', line 34

def to_s(&block)
  if block_given?
    block.call(self)
  else
    @concat_handler.call(self)
  end
end

#wrap(&block) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/string_builder.rb', line 26

def wrap(&block)
  tap do
    ScopedStringBuilder.new.instance_eval(&block).each do |token|
      @buffer << token
    end
  end
end