Class: GsubFilter

Inherits:
Object
  • Object
show all
Defined in:
lib/gsub_filter.rb,
lib/gsub_filter/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input = nil) ⇒ GsubFilter

Returns a new instance of GsubFilter.



6
7
8
9
10
# File 'lib/gsub_filter.rb', line 6

def initialize(input=nil)
  @input = input
  @filters = []
  @stocks = Hash.new{ |h,k| h[k] = [] }
end

Instance Attribute Details

#filtersObject (readonly)

Returns the value of attribute filters.



5
6
7
# File 'lib/gsub_filter.rb', line 5

def filters
  @filters
end

#stocksObject (readonly)

Returns the value of attribute stocks.



5
6
7
# File 'lib/gsub_filter.rb', line 5

def stocks
  @stocks
end

Instance Method Details

#clear_stocksObject



32
33
34
# File 'lib/gsub_filter.rb', line 32

def clear_stocks
  @stocks.clear
end

#filter(pattern, opt = {}, &replace) ⇒ Object

default opt: true, at: -1, replace: false



13
14
15
16
17
# File 'lib/gsub_filter.rb', line 13

def filter(pattern, opt={}, &replace)
  opt = opt_parse_for_filter(opt)
  @filters[opt[:at], opt[:replace]] = [[pattern, replace, opt[:global]]]
  nil
end

#replace(at, pattern, opt = {}, &replace) ⇒ Object



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

def replace(at, pattern, opt={}, &replace)
  opt = {at: at, replace: true}.update(opt)
  filter(pattern, opt, &replace)
end

#run(str = nil) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/gsub_filter.rb', line 24

def run(str=nil)
  str ||= @input
  @filters.compact.each do |pattern, replace, meth|
    str = str.send(meth, pattern) { replace[$~, @stocks] }
  end
  str
end