Q:

Interpolate Method Definition

This method does not have a description on the APIdock. I know instance_exec in Ruby is similar to the this binding mechanism in JavaScript.
def interpolate(sql, record = nil)
    if sql.respond_to?(:to_proc)
      owner.instance_exec(record, &sql)
    else
      sql
    end
  end

Could someone briefly describe it?

A:

First of all, the check for respond_to?(:to_proc) is necessary to make sure sql might be converted to lambda (by ampersand & to be passed to instance_exec. To simplify things, one might treat sql here as being a lambda already:
def interpolate(sql, record = nil) # assume sql is lambda
  owner.instance_exec(record, &sql)
end

As by documentation on instance_exec:

Executes the given block within the context of the receiver...

That said, lambda will be executed as it was the ordinal code, placed somewhere inside instance method of the receiver.
class Owner
  def initialize
    @records = [:zero, :one, :two]
  end
end

record_by_index = ->(idx) { @records[idx] }
Owner.new.instance_exec 1, &record_by_index #⇒ :one

The code above is [more or less] an equivalent to:
class Owner
  def initialize
    @records = [:zero, :one, :two]
  end
  def record_by_index idx
    @records[idx]
  end 
end

Owner.new.record_by_index(1) #⇒ :one

The actual parameters of call to instance_exec will be passed to the codeblock. In the context of Owner’s instance we have an access to instance variables, private methods, etc. Hope it helps.

