Class: WikiWah::Subst
- Inherits:
-
Object
- Object
- WikiWah::Subst
- Defined in:
- lib/wikiwah/subst.rb
Overview
Subst handles text-transformation using a series of regular-expression substitutions. It encapsulates a number of “patterns”, and associated blocks. Each block is invoked with a MatchData object when it’s associated pattern matches, and is expected to return a replacement string.
The difference between using Subst and applying a series of gsub’s is that replacement values are protected from subsequent transformations.
Instance Method Summary collapse
- #add_transformation(regexp, &proc) ⇒ Object
-
#initialize ⇒ Subst
constructor
A new instance of Subst.
- #transform(s) ⇒ Object
Constructor Details
#initialize ⇒ Subst
Returns a new instance of Subst.
15 16 17 |
# File 'lib/wikiwah/subst.rb', line 15 def initialize @transforms = [] end |
Instance Method Details
#add_transformation(regexp, &proc) ⇒ Object
19 20 21 |
# File 'lib/wikiwah/subst.rb', line 19 def add_transformation(regexp, &proc) @transforms << [regexp, proc] end |
#transform(s) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/wikiwah/subst.rb', line 23 def transform(s) s = s.dup store = [] @transforms.each do |transform| (regexp, proc) = *transform s.gsub!(regexp) { store << proc.call($~) "\001#{store.size - 1}\002" } end s.gsub!(/\001(\d+)\002/) { store[$1.to_i] } s end |