Topics Covered in This Ruby on Rails Tutorial:
Installing the HTTParty Gem and Integrating Real-Time Bitcoin Pricing into Order Summaries
Learning Objectives
HTTParty Integration
Learn to install and configure the HTTParty gem for making external API calls in Rails applications.
Bitcoin API Implementation
Integrate real-time Bitcoin exchange rates from BitPay API to display dynamic pricing in your e-commerce site.
AJAX Updates
Implement dynamic Bitcoin total updates using AJAX to provide seamless user experience without page refreshes.
Exercise Overview
Modern web applications rarely exist in isolation—they thrive through strategic integration with third-party services and APIs. In this exercise, we'll explore web services from both perspectives: first, we'll integrate a live Bitcoin pricing API into our e-commerce platform, and in the next exercise, we'll learn to expose our own data for partner consumption. This dual approach will give you the complete toolkit for building interconnected, data-rich applications that leverage the broader web ecosystem.
If you completed the previous exercises, you can skip the following sidebar. We strongly recommend finishing exercises 8A–11A before starting this one, as they establish the foundational cart and order functionality we'll be extending. If you haven't completed them, follow the setup instructions below.
Web Services Integration Approach
Current ExerciseConsume Third-Party API
Integrate external web service (Bitcoin rates) into your Rails application
Next ExerciseSyndicate Your Data
Learn to expose your application data to external partners
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
cdand 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 nuttyto delete your copy of the nutty site. - Run
Git clone https://bitbucket.org/Noble Desktop/nutty.Gitto copy the That Nutty Guy Git repository. - Type
cd nuttyto enter the new directory. - Type
Git checkout 11Ato bring the site up to the end of the previous exercise. - Run
bundleto install any necessary gems. - Run
yarn install—check-filesto install JavaScript dependencies.
Repository Setup Process
Navigate and Prepare
Open Terminal, navigate to Class Files folder, and remove existing nutty directory
Clone and Configure
Clone the Noble Desktop nutty repository and checkout branch 11A
Install Dependencies
Run bundle and yarn install to set up all required gems and JavaScript dependencies
Getting Bitcoin Quotes with HTTParty
Cryptocurrency payment integration has become increasingly important for e-commerce platforms, especially as digital currencies gain mainstream adoption. We're going to enhance our site to support both traditional dollar payments and Bitcoin transactions. Since Bitcoin's exchange rate is notoriously volatile—often fluctuating significantly within hours—we need real-time pricing data to ensure accurate conversions.
For this integration, we'll use BitPay's robust API at bitpay.com/api/rates, which provides reliable, up-to-date exchange rates across multiple currencies. To interact with this external service efficiently within our Rails application, we'll leverage the HTTParty gem—a powerful, lightweight HTTP client that simplifies API consumption with an intuitive Ruby interface.
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). Having the entire project structure visible will help you navigate between files more efficiently.
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 to get your development environment properly configured.
Why Bitcoin Integration?Bitcoin's volatile exchange rate requires real-time API integration. The BitPay API at bitpay.com/api/rates provides reliable, free access to current exchange rates across 165 currencies.
API Response Data
0currencies supported by BitPay API
Restarting the Rails Server
- In Terminal,
cdinto the nutty folder:
- Type
cdand 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,
cdinto the nutty folder:
- Type
cdand 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 your code editor, open nutty > Gemfile.
Scroll to the bottom and add the HTTParty gem dependency:
# Use HTTParty to make remote API calls
gem 'httparty'
HTTParty is one of the most popular Ruby gems for HTTP requests, offering a clean, readable syntax that makes API integration straightforward. It handles JSON parsing automatically and provides helpful methods for common HTTP operations.
Save the file, then close it.
Switch to Terminal to install the new dependency.
Install the new gem by typing:
bundle
Bundler will download and install HTTParty along with any of its dependencies, ensuring version compatibility with your existing gems.
Switch to the tab running the server and hit CTRL–C to shut it down.
Start up the server again by typing:
rails s
Restarting the server ensures that the new gem is properly loaded into your application's runtime environment. This is a crucial step that many developers forget, leading to frustrating "uninitialized constant" errors.
Now let's explore HTTParty's capabilities using the Rails console—an invaluable tool for testing API interactions before implementing them in your application code. Switch back to the bash tab in Terminal and start the Rails console:
rails cType 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 comprehensive response—an array of hashes containing Bitcoin exchange rates for currencies worldwide. This real-time data is exactly what we need for accurate payment processing.
Let's examine the response structure. Type the following:
response.count
Terminal will return approximately 165, representing the number of currencies currently supported by BitPay's API. This extensive coverage makes the service suitable for global e-commerce applications.
Type the following to inspect the data format:
response.first
This shows us the structure of individual currency entries, helping us understand how to extract the specific data we need.
For better readability when working with complex data structures, type:
pp responseScroll up to see that this gives us a much cleaner, formatted response, making it easier to analyze the returned data structure.
pp is short for "Pretty Print"—a essential debugging tool that formats complex variables for human readability. You'll find yourself using this frequently when working with API responses and complex data structures.
Now let's extract the specific data we need. We need to find the U.S. dollar equivalent. Type the following command to search using its currency code:
response.find { |r| r['code'] == 'USD' }
This Ruby enumerable method efficiently searches through the array to locate the USD entry, returning all associated data for that currency.
To get just the exchange rate value, we can chain methods together—one of Ruby's most powerful features:
response.find { |r| r['code'] == 'USD' }['rate']
Perfect! This single line gives us the current Bitcoin-to-USD exchange rate, which is all we need for our payment integration. This demonstrates the elegance of API integration: calling the service with HTTParty, then parsing and utilizing the response. The implementation possibilities from here are limitless.
HTTParty Installation Process
Add Gem to Gemfile
Add 'gem httparty' to your Gemfile with appropriate comment
Install and Restart
Run bundle install, stop the server with Ctrl-C, then restart with rails s
Test in Console
Use Rails console to test HTTParty.get calls and explore the API response structure
Use 'pp response' for pretty printing complex API responses. The find method with code comparison helps locate specific currency data from the returned array of hashes.
Adding the Total in Bitcoin
Now that we understand how to fetch Bitcoin exchange rates, let's integrate this functionality into our application architecture. We'll add the Bitcoin conversion logic to our shared methods module, ensuring it can be reused across both cart and order objects—a key principle of maintainable Rails development.
In your code editor, open nutty > lib > checkout_shared_methods.rb
NOTE: Remember that earlier we extracted common functionality between cart and order objects into this shared module. This architectural decision now pays dividends as we can add Bitcoin support to both objects with a single implementation.
Add the following method after the existing
totalmethod:def total subtotal end def bitcoin_total bitcoin_rate = HTTParty.get('https://bitpay.com/api/rates').find { |r| r['code'] == 'USD'}['rate'] end endOne of Ruby's greatest strengths is its expressiveness—allowing complex operations to be written concisely. The
bitcoin_rateline could have been expanded into five separate lines, but method chaining lets us accomplish the entire API call, search, and data extraction in a single, readable statement.Now we need to calculate and return the Bitcoin equivalent price. Add the conversion logic:
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) endNOTE: We use
1.0rather than1to ensure floating-point arithmetic and preserve decimal precision. Bitcoin amounts are conventionally expressed to eight decimal places (the smallest unit being a "satoshi"), so we round accordingly for proper display and calculation accuracy.With our Bitcoin calculation logic complete, let's integrate it into the user interface. Save the file and move on to updating the cart display.
In your code editor, open nutty > app > views > cart > index.html.erb
Locate the total display section around lines 69–72 and copy this code:
<tr class="total-price"> <td>Total</td> <td id="total"><%= number_to_currency @cart.total %></td> </tr>Paste directly below the copied lines, then modify the new code to display the Bitcoin total:
<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 remove the
number_to_currencyhelper from the Bitcoin row, as we're displaying the raw Bitcoin amount with the "BTC" suffix.Save the file and prepare to test the initial implementation.
Open a browser and navigate to: localhost:,000
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.
Excellent! You should now see in the Order Summary that alongside the regular Total, there's a new Total in Bitcoin row showing the real-time cryptocurrency equivalent. However, we need to ensure this functionality works seamlessly with our AJAX-powered cart updates.
In your code editor, open nutty > app > views > line_items > update.js.erb
Copy the last line and paste it directly below the original to handle Bitcoin total updates.
Edit the duplicated code to update the Bitcoin display:
$('td#total').html('<%= number_to_currency @cart.total %>'); $('td#bitcoin- total').html('<%= @cart.bitcoin_ total %> BTC');NOTE: Remember to remove
number_to_currencyfrom the Bitcoin line. Notice the naming convention: we use hyphens for HTML IDs and CSS classes, but underscores for Ruby method names—following Rails conventions ensures consistency across your application.This architecture demonstrates the power of Rails' MVC pattern: our business logic resides in the model (the shared module), keeping our views clean and our calculations centralized. No code duplication, no scattered API calls—just clean, maintainable architecture.
Save the file and test the complete AJAX integration.
Go to the browser and reload the cart page: localhost:,000/cart
Change the quantity of an item in your cart to test the dynamic updates.
Click the update link. Both the dollar total and the Total in Bitcoin should update seamlessly in real-time, demonstrating a fully integrated cryptocurrency payment display system!
Clean up your Rails console session by switching back to Terminal and typing:
exitLeave Terminal, your code editor, and browser open as we will continue building upon this foundation in the following exercise, where we'll explore the flip side of API integration: exposing your own data for external consumption.
Ruby's method chaining allows complex operations in single lines. The bitcoin_rate calculation chains HTTParty.get, find, and hash access together for concise, readable code.
Implementation Steps
Ensures the method is available to both cart and order objects
Forces decimal precision in Ruby calculations
Matches standard Bitcoin precision formatting
Ensures Bitcoin totals update dynamically and on page load
Remember to update both the static HTML view and the AJAX update view. Use dashes for CSS IDs and underscores for Ruby method names following Rails conventions.