Build a Ruby application

Install the pg driver gem

Install the Ruby PostgreSQL driver (pg) using the following command. You can get further details for the driver here.

  1. $ gem install pg -- --with-pg-config=<yugabyte-install-dir>/postgres/bin/pg_config

Working example

Prerequisites

This tutorial assumes that you have:

  • installed YugabyteDB and created a universe with YSQL enabled. If not, please follow these steps in the Quick Start guide.

Writing the Ruby code

Create a file yb-sql-helloworld.rb and add the following content to it.

  1. #!/usr/bin/env ruby
  2. require 'pg'
  3. begin
  4. # Output a table of current connections to the DB
  5. conn = PG.connect(host: '127.0.0.1', port: '5433', dbname: 'yugabyte', user: 'yugabyte', password: 'yugabyte')
  6. # Create table
  7. conn.exec ("CREATE TABLE employee (id int PRIMARY KEY, \
  8. name varchar, age int, \
  9. language varchar)");
  10. puts "Created table employee\n";
  11. # Insert a row
  12. conn.exec ("INSERT INTO employee (id, name, age, language) \
  13. VALUES (1, 'John', 35, 'Ruby')");
  14. puts "Inserted data (1, 'John', 35, 'Ruby')\n";
  15. # Query the row
  16. rs = conn.exec ("SELECT name, age, language FROM employee WHERE id = 1");
  17. rs.each do |row|
  18. puts "Query returned: %s %s %s" % [ row['name'], row['age'], row['language'] ]
  19. end
  20. rescue PG::Error => e
  21. puts e.message
  22. ensure
  23. rs.clear if rs
  24. conn.close if conn
  25. end

Running the application

To run the application, type the following:

  1. $ ./yb-sql-helloworld.rb

You should see the following output.

  1. Created table employee
  2. Inserted data (1, 'John', 35, 'Ruby')
  3. Query returned: John 35 Ruby