23
Sat, Nov
1 New Articles

TechTip: Ruby Talks to DB2 for i

APIs
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Using the ibm_db gem, we can easily communicate with DB2 for i directory from Ruby.

 

In the article "Sinatra Sings, Ruby Plays," I introduced the Sinatra web framework , and we went through initial installation and a simple Hello World application. In this article, we will take that app further by introducing database access. Specifically, we will use the ibm_db Gem to query a DB2 table named USERS and display the contents back to the web page.

The ibm_db gem, included in the PowerRuby install, implements Rails' ActiveRecord pattern, which makes database interaction significantly simpler. As part of this exercise, we will install the sinatra-activerecord gem that "...extends Sinatra with extension methods and Rake tasks for dealing with an SQL database using the ActiveRecord ORM."

 

Instead of using the gem install command to install gems, we are going to use Bundler, which will provide a consistent environment for Ruby (i.e., Sinatra) projects by tracking and installing the exact gems and versions that are needed.

 

First, create the application directory if it doesn't yet exist, as shown below. Make sure to replace my name with your profile.

 

$ mkdir /home/aaron/git/sinatra_db

 

Change the directory into the new folder and run the bundle init command, which will create a file named Gemfile, as shown below.

 

$ cd /home/aaron/git/sinatra_db

$ bundle init

Writing new Gemfile to /home/aaron/git/sinatra_db/Gemfile

 

A Gemfile file is used to declare all of the gems our application requires. Occupy the Gemfile file with the contents below.

 

source "https://rubygems.org"

gem "activerecord", "4.0.12"

gem "sinatra"

gem "sinatra-activerecord"

 

The gems mentioned in Gemfile do not yet exist on the local machine, except for activerecord, which is delivered with PowerRuby. Before we install them using the bundle install command, we need to create a new folder for where the gems will be installed and set the GEM_HOME environment to that location, as shown below.

 

$ mkdir /home/aaron/gemsets/sinatra_db

$ export GEM_HOME=/home/aaron/gemsets/sinatra_db

 

Now run bundle install, which will review the Gemfile and check whether those gems already exist on the local machine. If gems don't exist, then they will be downloaded from RubyGems.org and placed into /home/aaron/gemsets/sinatra_db, as shown below. If it finds the gems, then it will state, "Using <gem name>", as shown below.

 

$ bundle install

Fetching gem metadata from https://rubygems.org/...........

Resolving dependencies...

Installing i18n 0.7.0

Using minitest 4.7.5

Using multi_json 1.10.1

Using thread_safe 0.3.4

Using tzinfo 0.3.42

Using activesupport 4.0.12

Using builder 3.1.4

Using activemodel 4.0.12

Using activerecord-deprecated_finders 1.0.3

Using arel 4.0.2

Using activerecord 4.0.12

Installing rack 1.6.0

Installing rack-protection 1.5.3

Using tilt 1.4.1

Installing sinatra 1.4.5

Installing sinatra-activerecord 2.0.4

Using bundler 1.7.6

Your bundle is complete!

Use `bundle show [gemname]` to see where a bundled gem is installed.

 

Now that the Gems are installed we need to alter our GEM_PATH environment variable to include our new folder, as shown below. If we didn't do this, when we started our application it would error out saying it couldn't find certain Gems.

 

$ export GEM_PATH=/home/aaron/gemsets/sinatra_db:/PowerRuby/prV2R0/lib/ruby/gems/2.0.0

 

Now it's time to put together the app.rb file, which will contain the entirety of the application's functionality minus the view, shown in the code listing below.

 

require 'sinatra'

require 'sinatra/activerecord'

require 'active_record'

require 'ibm_db'

ActiveRecord::Base.establish_connection(

adapter: 'ibm_db',

database: '*LOCAL',

schema: 'MYLIB',

username: 'MYUSER',

password: 'MYUSER4321'

)

class User < ActiveRecord::Base

end

get '/' do

@users = User.all

erb :index, :locals => {:users => @users}

end

Listing 1: File app.rb contains the database connection, model, and request routing.

 

The first things we see are the require statements to bring in the necessary gem capabilities. Next, we declare and establish the database connection using ActiveRecord. You can use your own schema (aka library), username, and password; or use the ones defined later in this article. Next in Listing 1 we see the model declaration for the yet-to-be-created User table. This is an interesting aspect of Ruby in that I can include my models (aka database access layer) right in the app.rb file. Or I could instead put it in a file named models/user.rb. We are including the User class in app.rb for example and brevity's sake, but the best practice would be a separate file. The last thing we see is a single routing entry that will monitor for requests that come into the root of the application, i.e., "/". When a request comes into the root, it will get all user rows using User.all and place them into an array variable named @users. More on @users and the next erb line in a little bit.

 

Next, create what's called a database migration. Migrations allow you to evolve your database over time by storing the incremental modifications in separate time-stamped files. To use ActiveRecord's database migrations, we first need to create a file named Rakefile (no file extension) and occupy it with the following contents. This is necessary so that when we run the rake command, it will be able to resolve to the command we pass it (i.e., db:create_migration).

 

require './app'

require 'sinatra/activerecord/rake'

 

Now we are ready to generate a migration skeleton with the following command. As you can see from the logged output, it creates a directory structure of db/migrate and a file with the name we specified on our command.

 

$ rake db:create_migration NAME=create_users

db/migrate/20150129202229_create_users.rb

 

The migration doesn't know the makeup of the table we wish to create, so it's necessary to open the file ending in create_users.rb and enter the below code.

 

class CreateUsers < ActiveRecord::Migration

def change

   create_table :users do |t|

     t.string :first_name

     t.string :last_name

     t.string :address

     t.string :city

     t.string :state

     t.string :zip

     t.text :note

     t.timestamps

   end

end

end

 

Migrations use what's called a Ruby DSL, or Domain Specific Language. The create_table line is actually a Ruby method being invoked, and the content of the Ruby blockfrom do to endis where columns are defined for the new table. I consider this incredibly slick and a big timesaver over having to manually write out platform-specific SQL statements.

 

Before we can run this database migration, we first need to create the database using the below CREATE COLLECTION command within the STRSQL interface. I've also included CRTUSRPRF and CHGAUT commands for ease of setup, though feel free to use your own profile.

 

5250-STRSQL> CREATE COLLECTION MYLIB

5250> CRTUSRPRF USRPRF(myuser) PASSWORD() INLMNU(*SIGNOFF) USRCLS(*USER)

5250> CHGAUT OBJ('/qsys.lib/mylib.lib') USER(myuser) DTAAUT(*RWX) OBJAUT(*ALL)

 

Now that the schema defined in app.rb exists, we can run the below rake db:migrate command. This will look for table MYLIB/SCHEMA_MIGRATIONS and compare the migrations in it to what exists in the applications db/migrate folder. It will then run any outstanding migrations.

 

$ rake db:migrate

== 20150129202229 CreateUsers: migrating ======================================

-- create_table(:users)

   -> 0.1460s

== 20150129202229 CreateUsers: migrated (0.1463s) =============================

 

At this point, we've set up the database and the controller and model layers, but we haven't yet touched the view layer, where we define the HTML. First create a views folder, as shown below.

 

$ mkdir views

 

Next, create a file named index.erb in the views folder and occupy it with the code in Listing 2. Here's where the previously mentioned @users array variable comes back into play. Variables starting with an @ symbol in the Ruby language are considered instance variables and when created in a controller (i.e., app.rb) can be made available to the view layer (i.e., index.erb).

 

<table>

<thead>

   <tr>

     <th>First Name</th>

     <th>Last Name</th>

   </tr>

</thead>

<tbody>

   <% @users.each do |user| %>

     <tr>

       <td><%= user.first_name %></td>

       <td><%= user.last_name %></td>

     </tr>

   <% end %>

</tbody>

</table>

Listing 2: File views/index.erb contains the HTML.

 

Going back to Listing 1, you'll remember the following line. This is declaring the name of the erb file to look fornamely, indexand what local variables to make available to itnamely, @users.

 

erb :index, :locals => {:users => @users}

 

At this point, the application is ready to be run, except for one issue. We have no data in the USERS table! We could add DB2 rows using UPDDTA or another tool, but I want to show you how it can be done using Interactive Ruby Shell (IRB). You can copy and paste the below into an irb session and it will effectively configure that session to be similar to the actual web application being invoked by a user from the browser. It loads the active_record and ibm_db gems, establishes a connection, declares the Ruby model, and finally it runs a small bit of code that will generate 10 new rows using the User.create method.

 

require 'active_record'

require 'ibm_db'

ActiveRecord::Base.establish_connection(

adapter: 'ibm_db',

database: '*LOCAL',

schema: 'MYLIB',

username: 'MYUSER',

password: 'MYUSER4321'

)

class User < ActiveRecord::Base

end

10.times.each { |i| User.create first_name: "Name#{i}", last_name:"Last#{i}" }

 

Now it is finally time to start the application using the following command:

 

$ ruby app.rb -o0.0.0.0

== Sinatra/1.4.5 has taken the stage on 4567 for development with backup from Thin

Thin web server (v1.6.2 codename Doc Brown)

Maximum connections set to 1024

Listening on 0.0.0.0:4567, CTRL+C to stop

 

To see if it's working point your browser at http://<machine_ip>:4567 and you should see something similar to Figure 1.

 

20150401BartellFigure3

Figure 1: The browser displays rows from the USERS table.

 

If you've done Rails before, you'll notice Sinatra requires a lot of the same things yet doesn't lay out as much infrastructure. For example, when you run the rails new command, it fleshes out an entire application's infrastructure in seconds, including folders for models, views, and controllers. It also creates files to hold things like database configurations. In Sinatra, that is all created by hand.

 

So why use Sinatra? There might be times where Rails is overkill. For example, maybe you just need a simple API + JSON server for responding to AJAX or non-browser web service calls. It is worth noting that Rails is very componentized, so there is the opportunity to remove components you don't need. I'd highly recommend playing with both and making your own determination.

Aaron Bartell

Aaron Bartell is Director of IBM i Innovation for Krengel Technology, Inc. Aaron facilitates adoption of open-source technologies on IBM i through professional services, staff training, speaking engagements, and the authoring of best practices within industry publications andwww.litmis.comWith a strong background in RPG application development, Aaron covers topics that enable IBM i shops to embrace today's leading technologies, including Ruby on Rails, Node.js, Git for RPG source change management, and RSpec for unit testing RPG. Aaron is a passionate advocate of vibrant technology communities and the corresponding benefits available for today's modern application developers. Connect with Aaron via email atThis email address is being protected from spambots. You need JavaScript enabled to view it..

Aaron lives with his wife and five children in southern Minnesota. He enjoys the vast amounts of laughter that having a young family brings, along with camping and music. He believes there's no greater purpose than to give of our life and time to help others.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: