Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Execute stored procedure
class StoredProcedureService
def self.instance
@instance ||= StoredProcedureService.new
end
def execute(name, *args)
results = []
begin
connection.execute("CALL #{name}(#{args.join(',')})").each(as: :hash, symbolize_keys: true) do |row|
results << OpenStruct.new(row)
end
ensure
connection.close
end
results
end
def connection
ActiveRecord::Base.connection
end
end
@jacaetevha
Copy link

jacaetevha commented Sep 14, 2012

I do it slightly differently, using the connection pool, and not instantiating the "service":

class DatabaseHelper
  def self.select name, *args, &blk
    execute "select", name, *args, &blk
  end

  def self.call name, *args, &blk
    execute "call", name, *args, &blk
  end

  def self.execute via, name, *args, &blk
    ActiveRecord::Base.connection_pool.with_connection do |connection|
      args = args.map{|e| connection.quote e}

      answer = connection.execute("#{via} #{name}(#{args.join(',')})").each(:as => :hash, :symbolize_keys => true) do |row|
        results << OpenStruct.new(row)
      end

      if blk
        blk.call(answer)
      else
        answer
      end
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment