Class: OccamsRecord::BindsConverter::Named

Inherits:
Object
  • Object
show all
Defined in:
lib/occams-record/binds_converter/named.rb

Overview

Converts Rails-style named binds (:foo) into native Ruby format (%foo).

Instance Method Summary collapse

Constructor Details

#initialize(sql, binds) ⇒ Named

Returns a new instance of Named.



7
8
9
10
11
# File 'lib/occams-record/binds_converter/named.rb', line 7

def initialize(sql, binds)
  @sql = sql
  @binds = binds
  @found = []
end

Instance Method Details

#to_sObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/occams-record/binds_converter/named.rb', line 13

def to_s
  sql = @sql.gsub(/([:\\]?):([a-zA-Z]\w*)/) do |match|
    if $1 == ":".freeze # skip PostgreSQL casts
      match # return the whole match
    elsif $1 == "\\".freeze # escaped literal colon
      match[1..-1] # return match with escaping backslash char removed
    else
      @found << $2
      "%{#{$2}}"
    end
  end
  raise MissingBindValuesError.new(sql, missing_bind_values_msg) if @binds.size < @found.uniq.size
  sql
end