Module: Rufus::Dollar

Defined in:
lib/rufus/dollar.rb

Constant Summary collapse

VERSION =
'1.0.3'

Class Method Summary collapse

Class Method Details

.dsub(text, dict, offset = nil) ⇒ Object

Performs ‘dollar substitution’ on a piece of text with a given dictionary.

require 'rubygems'
require 'rufus/dollar'

h = {
  "name" => "Fred Brooke",
  "title" => "Silver Bullet"
}

puts Rufus::Dollar.dsub "${name} wrote '${title}'", h
  # => "Fred Brooke wrote 'Silver Bullet'"

$‘key or $“key

puts Rufus::Dollar.dsub "${name} wrote ${title}", h
  # => "Fred Brooke wrote Silver Bullet"

puts Rufus::Dollar.dsub "${name} wrote ${'title}", h
  # => 'Fred Brooke wrote "Silver Bullet"'


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/rufus/dollar.rb', line 63

def self.dsub(text, dict, offset=nil)

  text = text.to_s

  j = text.index('}', offset || 0)

  return text unless j

  t = text[0, j]

  i = t.rindex('${')
  ii = t.rindex("\\${")

  iii = t.rindex('{')
  iii = nil if offset

  return text unless i
  return dsub(text, dict, j+1) if (iii) and (iii-1 > i)

  return unescape(text) if (i) and (i != 0) and (ii == i-1)
    #
    # found "\${"

  key = text[i+2..j-1]
  quote = false

  if m = key.match(/^['"](.+)$/)
    key = m[1]
    quote = true
  end

  value = dict[key]
  value = value.nil? ? '' : value.to_s
  value = value.inspect if quote

  pre = (i > 0) ? text[0..i-1] : ''

  dsub("#{pre}#{value}#{text[j+1..-1]}", dict)
end