Skip to content

Instantly share code, notes, and snippets.

@ys
Created September 13, 2012 12:50
Show Gist options
  • Save ys/3714101 to your computer and use it in GitHub Desktop.
Save ys/3714101 to your computer and use it in GitHub Desktop.
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

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