Module: SafeInterpolate

Defined in:
lib/dolzenko/safe_interpolate.rb

Overview

Instance Method Summary collapse

Instance Method Details

#generic_interpolate(string_block, interpolator) ⇒ Object

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
# File 'lib/dolzenko/safe_interpolate.rb', line 7

def generic_interpolate(string_block, interpolator)
  raise ArgumentError, "block returning string to interpolate must be provided" unless string_block 
  string_with_interpolations = string_block.call
  string_with_interpolations.gsub(/\#\{([^}]*)\}/) do
    result = eval($1, string_block.binding)
    interpolator[result]
  end
end

#html_interpolate(&string_block) ⇒ Object



25
26
27
# File 'lib/dolzenko/safe_interpolate.rb', line 25

def html_interpolate(&string_block)
  generic_interpolate(string_block, ERB::Util.method(:html_escape))
end

#sql_interpolate(&string_block) ⇒ Object

Examples

include SafeInterpolate
...
sql_interpolate { 'name = #{ name }' } # => "name = 'Bob'"


21
22
23
# File 'lib/dolzenko/safe_interpolate.rb', line 21

def sql_interpolate(&string_block)
  generic_interpolate(string_block, ActiveRecord::Base.connection.method(:quote))
end

#uri_interpolate(&string_block) ⇒ Object



29
30
31
# File 'lib/dolzenko/safe_interpolate.rb', line 29

def uri_interpolate(&string_block)
  generic_interpolate(string_block, CGI.method(:escape))
end