class Stairwell::BindTransformer

Attributes

bind_hash[RW]
converted_sql[RW]
depleting_bind_hash[RW]
sql[RW]

Public Class Methods

new(sql, bind_hash) click to toggle source
# File lib/stairwell/bind_transformer.rb, line 6
def initialize(sql, bind_hash)
  @sql = sql
  @bind_hash = bind_hash
  @depleting_bind_hash = bind_hash.dup
end

Public Instance Methods

convert_sql() click to toggle source
# File lib/stairwell/bind_transformer.rb, line 26
def convert_sql
  @converted_sql ||= sql.gsub(/(:?):([a-zA-Z]\w*)/) do |_|
    replace = $2.to_sym
    validate_sql(replace)
    bind_hash[replace].quote
  end
end
transform() click to toggle source

taking the sql string like “SELECT * WHERE name = :name AND id = :id” and confirming that the bind_hash has all the named binds like { name: “First”, id: 22 } if the sql string or the bind_hash have incorrect or extra values and error will raise The sql string will then have the appropropriate values substituted with quoted values to ensure safety. Note: $2 is The match for the first, second, etc. parenthesized groups in the last regex

# File lib/stairwell/bind_transformer.rb, line 20
def transform
  convert_sql
  validate_bind_hash
  converted_sql
end

Private Instance Methods

validate_bind_hash() click to toggle source
# File lib/stairwell/bind_transformer.rb, line 42
def validate_bind_hash
  raise SqlBindMismatch, ":#{depleting_bind_hash.keys.join(', ')} in your bind hash is missing from your query: #{sql}" unless depleting_bind_hash.empty?
end
validate_sql(attr) click to toggle source
# File lib/stairwell/bind_transformer.rb, line 36
def validate_sql(attr)
  raise SqlBindMismatch, ":#{attr} in your query is missing from your args" unless bind_hash[attr]

  depleting_bind_hash.delete(attr)
end