Dive into this comprehensive tutorial on integrating third-party web services into your Ruby on Rails site, specifically focusing on incorporating real-time Bitcoin price quotes into your application.
This exercise is excerpted from Noble Desktop’s past web development training materials. Noble Desktop now teaches JavaScript and the MERN Stack in our Full Stack Development Certificate. To learn current skills in web development, check out our coding bootcamps in NYC and live online.
Topics covered in this Ruby on Rails tutorial:
Installing the HTTParty gem, Adding Bitcoin total to the order summary
Exercise Overview
Let’s approach web services from two ends. First, in this exercise, we’ll look at how to integrate a third-party web service into our site. In the next exercise, we’ll learn how we can syndicate our data out to a partner.
-
If you completed the previous exercises, you can skip the following sidebar. We recommend you finish the previous exercises (8A–11A) before starting this one. If you haven’t finished them, do the following sidebar.
If You Did Not Do the Previous Exercises (8A–11A)
- Close any files you may have open.
- Open the Finder and navigate to Class Files > yourname-Rails Class
- Open Terminal.
- Type
cd
and a single space (do NOT press Return yet). - Drag the yourname-Rails Class folder from the Finder to the Terminal window and press ENTER.
- Run
rm -rf nutty
to delete your copy of the nutty site. - Run
git clone https://bitbucket.org/noble-desktop/nutty.git
to copy the That Nutty Guy git repository. - Type
cd nutty
to enter the new directory. - Type
git checkout 11A
to bring the site up to the end of the previous exercise. - Run
bundle
to install any necessary gems. - Run
yarn install --check-files
to install JavaScript dependencies.
Getting Bitcoin Quotes with HTTParty
We’re going to set up our site so that users can pay with either dollars or bitcoin. The exchange rate of Bitcoin is pretty volatile and its value relative to the dollar fluctuates all the time. Fortunately there are lots of free APIs out there; one of the best is at bitpay.com/api/rates
We’re going to need a good tool for interacting with it in our Rails application.
-
For this exercise we’ll continue working with the nutty folder located in Desktop > Class Files > yourname-Rails Class > nutty
If you haven’t already done so, we suggest opening the nutty folder in your code editor if it allows you to (like Sublime Text does).
-
You should still have a window with two tabs open in Terminal from the last exercise, the first of which is running the server. If you don’t, complete the following sidebar.
Restarting the Rails Server
- In Terminal,
cd
into the nutty folder:
- Type
cd
and a space. - Drag the nutty folder from Desktop > Class Files > yourname-Rails Class onto the Terminal window (so it will type out the path for you).
- In Terminal, hit Return to change directory.
-
In Terminal, type the following:
rails s
- Open a new tab (Cmd–T) leaving our server running in the old tab.
- In the new tab,
cd
into the nutty folder:
- Type
cd
and a space. - Drag the nutty folder from Desktop > Class Files > yourname-Rails Class onto the Terminal window (so it will type out the path for you).
- In Terminal, hit Return to change directory.
- In Terminal,
In your code editor, open nutty > Gemfile.
-
Scroll to the bottom and add:
# Use HTTParty to make remote API calls gem 'httparty'
Save the file, then close it.
Switch to Terminal.
-
Install the new gem by typing:
bundle
Switch to the tab running the server and hit Ctrl–C to shut it down.
-
Start up the server again by typing:
rails s
This is actually a good opportunity to use the Rails console a bit and get a feel for what HTTParty does and how it returns responses to you.
-
Switch back to the bash tab in Terminal and start the Rails console:
rails c
-
Type the following, making sure to write HTTParty as written (it is case-sensitive):
response = HTTParty.get('https://bitpay.com/api/rates')
You will get a long response, an array of hashes, which shows the Bitcoin exchange rate in various countries.
-
Type the following:
response.count
Terminal will return
165
, the number of currencies that were just returned. -
Type the following:
response.first
This just gives us the first returned entry.
-
Type the following:
pp response
-
Scroll up to see that this gives us a cleaner response, making it much easier to see the data that’s been returned.
pp
is short for “Pretty Print”. This command makes it possible to inspect large & complex variables. -
We need to find the U.S. dollar equivalent. Type the following command to search using its code:
response.find { |r| r['code'] == 'USD' }
That gives us back all the U.S. dollar info, but what if we really wanted to pare down so we only see the U.S. dollar rate?
-
We can do that by typing:
response.find { |r| r['code'] == 'USD' }['rate']
Great, that’s all the info we’ll need to incorporate into our application to show customers a real-time price quote in Bitcoin. That’s basically all there is to integrating a third-party service: calling out to it using HTTParty, then parsing and using the response. The rest is up to your imagination!
Adding the Total in Bitcoin
The code that we just wrote is going to go into our shared_method module so that it can be reused by both carts and orders.
-
In your code editor, open nutty > lib > checkout_shared_methods.rb
NOTE: Remember that earlier we broke out methods that are shared between cart and order objects into this file.
-
Add the following three lines of code shown in bold:
def total subtotal end def bitcoin_total bitcoin_rate = HTTParty.get('https://bitpay.com/api/rates').find { |r| r['code'] == 'USD'}['rate'] end end
One of the great things about Ruby is that you can be very concise with it. The
bitcoin_rate
line could have been five lines of code, but instead we are able to write it all in one line by chaining methods together. -
Now we need to return the price in Bitcoin. Add:
def bitcoin_total bitcoin_rate = HTTParty.get('https://bitpay.com/api/rates').detect { |r| r['code'] == 'USD'}['rate'] (total * (1.0 / bitcoin_rate)).round(8) end
NOTE: We put
1.0
rather than1
so that it will return decimals. Bitcoin balances are often written out to eight decimal places, so we set it to round to8
. That should be all we need to get the Bitcoin total for any given object, so let’s move on to adding the Bitcoin total to the cart screen. Save the file.
In your code editor, open nutty > app > views > cart > index.html.erb
-
Copy the code around lines 69–72:
<tr class="total-price"> <td>Total</td> <td id="total"><%= number_to_currency @cart.total %></td> </tr>
-
Paste directly below the copied lines, then edit the new code as shown in bold:
<tr class="total-price"> <td>Total</td> <td id="total"><%= number_to_currency @cart.total %></td> </tr> <tr class="total-price"> <td>Total in Bitcoin</td> <td id="bitcoin- total"><%= @cart.bitcoin_total %> BTC</td> </tr>
NOTE: Don’t forget to delete the second instance of
number_to_currency
. Save the file.
Open a browser and navigate to: localhost:3000
Click on a product then click the Add To Cart button.
Sign in if prompted. If you did not create an account in a previous exercise, click the Sign up link, enter an email and password, then click Sign Up.
-
You should see in the Order Summary that in addition to the regular Total, there is now Total in Bitcoin.
We need to get this working with our AJAX as well.
In your code editor, open nutty > app > views > line_items > update.js.erb
Copy the last line and paste it directly below the original.
-
Edit the code as shown in bold:
$('td#total').html('<%= number_to_currency @cart.total %>'); $('td#bitcoin- total').html('<%= @cart.bitcoin_ total %> BTC');
NOTE: Don’t forget to delete
number_to_currency
in the new line.The convention is to use a dash for the class and an underscore for the method.
Isn’t it great that we can put our logic in the model, rather than having to duplicate the whole Bitcoin calculation or API call?
Save the file.
Go to the browser and reload the cart page: localhost:3000/cart
Change the Quantity of an item in your cart.
Click the update link. The Total in Bitcoin should update in the Order Summary!
-
Switch back to Terminal and type the following to exit the Rails console.
exit
Leave Terminal, your code editor, and browser open as we will continue to work with them in the following exercise.