Class: Habakiri
- Inherits:
-
Object
- Object
- Habakiri
- Defined in:
- lib/habakiri.rb,
lib/habakiri/version.rb
Constant Summary collapse
- VERSION =
'0.1.0'.freeze
Class Method Summary collapse
Instance Method Summary collapse
- #exec(template, text) ⇒ Object
-
#initialize(prefix = '{{', suffix = '}}') ⇒ Habakiri
constructor
A new instance of Habakiri.
Constructor Details
#initialize(prefix = '{{', suffix = '}}') ⇒ Habakiri
Returns a new instance of Habakiri.
5 6 7 8 |
# File 'lib/habakiri.rb', line 5 def initialize(prefix = '{{', suffix = '}}') @prefix = prefix @suffix = suffix end |
Class Method Details
.exec(template, text) ⇒ Object
40 41 42 |
# File 'lib/habakiri.rb', line 40 def exec(template, text) new.exec(template, text) end |
Instance Method Details
#exec(template, text) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/habakiri.rb', line 10 def exec(template, text) diffs = Diff::LCS.sdiff(template.to_s, text.to_s) matches = template.to_enum(:scan, /#{@prefix}.+?#{@suffix}/).map{ Regexp.last_match } matches.each.with_object({}){|match, object| start = match.begin(0) last = match.end(0) range = start...last list = diffs.select{|d| range.include?(d.old_position) } # 改行後の追加要素も対応する文字列とみなす i = diffs.index{|d| d.old_position == last } if i loop do diff = diffs[i] if diff && (diff.action == '+' || (diff.action == '=' && /\R/.match?(diff.old_element))) list.push(diff) i += 1 else break end end end key = match[0].delete_prefix(@prefix).delete_suffix(@suffix).chomp object[key] = list.map(&:new_element).join.strip } end |