Skip to content
J. Mark Locklear edited this page May 1, 2019 · 2 revisions

Saving and Retrieving Data in Firebase

In this tutorial I will show you how to retrieve data from an API, and then save and retrieve that data from a Firebase database. Now, we could come up with some contrived premise for creating data to store in our database, and boring old Lorem Ipsum simply will not do. Everyone loves beer, so we will search our favoriate breweries using BreweryDB and write that data to our database. We will be using Ruby 1.9.3 or greater to write this script.

We will be using the brewery_db and firebase gems in this tutorial. The first thing we'll need to do is install the gems locally.

    ruby-1.9.3-p551$ gem install firebase
    Fetching: firebase-0.2.6.gem (100%)
    Successfully installed firebase-0.2.6
    Installing ri documentation for firebase-0.2.6
    1 gem installed
    ruby-1.9.3-p551$ <b>gem install brewery_db</b>
    Fetching: brewery_db-0.2.4.gem (100%)
    Successfully installed brewery_db-0.2.4
    Installing ri documentation for brewery_db-0.2.4
    1 gem installed

Now let's create a new ruby script. The first thing we will want to do in the script is require these gems at the top.

require 'brewery_db'
require 'firebase'

Next lets set up connections to both Firebase and BreweryDB.

require 'brewery_db'
require 'firebase'

#connect to Firebase
firebase_uri = <your firebase url> 
@firebase = Firebase::Client.new(firebase_uri)

#connect to BreweryDB
@brewery_db = BreweryDB::Client.new do |config|
    config.api_key = '<your BreweryDB key here>'
end

Be sure to enter your private API key in the config.api_key... line above. Its quick and easy to sign up here.

Now might be a good time to sanity check the script. If you run the script now you should not get any errors.

OK, so far so good! Now let's search the BreweryDB database for a particular Brewery. Based on the brewery_db gem documentation we can do something like name = brewery_db.search.breweries(q: 'urban') to search all brewerys with the name "urban" in them. Lets give that a try along with a simple loop to display any results we find.

require 'brewery_db'
require 'firebase'

#connect to Firebase
firebase_uri = <your firebase url> 
@firebase = Firebase::Client.new(firebase_uri)

#connect to BreweryDB
@brewery_db = BreweryDB::Client.new do |config|
    config.api_key = '<your BreweryDB key here>'
end

breweries = @brewery_db.search.breweries(q: 'urban')

breweries.each do |b|
	puts b.name
end

Go ahead and try the names of some of your favorite craft breweries around the country. The database is pretty comprehensive. When I run the script above I get:

ruby-1.9.3-p551$ ruby brewery.rb
Hopworks Urban Brewery
Urban Artifact
Urban Legend Brewing Company
Urban Family Brewing
Urban Farm Fermentory
Urban Growler Brewing Company
Big Rock Urban Brewery
Urban Chestnut Brewing Company

You should see something similar. Also, when querying data in ruby like this I like using inspect to look at the entire object being returned. You can do this by using puts b.inspect in your loop rather than puts b.name.

Hopefully you are getting a sense of how the BreweryDB API works. Before we go any farther let's begin breaking the script up into simple Ruby Methods, and also allow the user to submit a query from the console.

In the code below I have moved the search code into a method called search_breweries and also added a simple console prompt so the user can enter a search term.

require 'brewery_db'
require 'firebase'

#connect to Firebase
firebase_uri = <your firebase url> 
@firebase = Firebase::Client.new(firebase_uri)

#connect to BreweryDB
@brewery_db = BreweryDB::Client.new do |config|
    config.api_key = <your BreweryDB API key>
end

def search_breweries(search_term)
	@hash = Hash.new
	breweries = @brewery_db.search.breweries(q: search_term)

	if breweries.count < 1
		puts "No breweries found named #{search_term}"
		exit
	else
		breweries.each_with_index do |b, index|
			index += 1
			@hash[index] = b.name
			puts index.to_s + "-" + b.name
		end
	end
end

#prompt for search term
puts "Enter a search term:"
search_term = gets.chomp
search_breweries search_term

Go ahead and give this a try. When you run the script, you should be able to enter a word, then see any results that are returned. A couple of things to mention in the search_breweries method. First, I am creating a hash at the beginning of the method, and second, I am using each_with_index when displaying the search results, then saving each result into an element in the hash. This will allow the user to choose a brewery to save in the next step.

Now that we can search for Breweries, lets allow the user to save their favorite brewery to the database. First we will ask the user which brewery they would like to save and pass that input to a new method called db_save:

puts "Enter the number of the brewery would you like to save"
search_term = gets.chomp
db_save(search_term)

Here is the db_save method:

def db_save(search_term)
	response = @firebase.push("favorite_breweries", { 
			:name => @hash[search_term.to_i].to_s,})
	if response.success?
		puts @hash[search_term.to_i].to_s + " successfully saved to the database"
	else
		puts "I am sorry an error occurred saving to the database"
	end
end

In the db_save method we are calling the push method on our @firebase object to access our favorite_breweries database, then save the term associated with the hash key to the :name field. Next, we verify our data was saved, and if so we display a success message, and if not, we display an error.

Finally, let's add a method that will retrieve a list of our favorite breweries each time we run the script. We will create a method called get_favorite_breweries where we will use the get method to get a list of breweries we have saved to the database. Then we will use a simple loop and some parsing to display the data.

def get_favorite_breweries
	favorites =  @firebase.get("favorite_breweries")
	parsed = JSON.parse(favorites.raw_body)

	parsed.each do |p|
		puts p[1]['name']
	end
end

Now all we need to do is call get_favorite_breweries in the last line of the script. Here is the entire final script:

require 'brewery_db'
require 'firebase'

#connect to Firebase
firebase_uri = <your firebase url> 
@firebase = Firebase::Client.new(firebase_uri)

#connect to BreweryDB
@brewery_db = BreweryDB::Client.new do |config|
    config.api_key = <your BreweryDB API key>
end

def search_breweries(search_term)
	@hash = Hash.new
	breweries = @brewery_db.search.breweries(q: search_term)

	if breweries.count < 1
		puts "No breweries found named #{search_term}"
		exit
	else
		breweries.each_with_index do |b, index|
			index += 1
			@hash[index] = b.name
			puts index.to_s + "-" + b.name
		end
	end
end

def db_save(search_term)
    response = @firebase.push("favorite_breweries", { 
    	:name => @hash[search_term.to_i].to_s,})
    if response.success?
    	puts @hash[search_term.to_i].to_s + " successfully saved to the database"
    else
    	puts "I am sorry an error occurred saving to the database"
    end
end

def get_favorite_breweries
	favorites =  @firebase.get("favorite_breweries")
	parsed = JSON.parse(favorites.raw_body)

	parsed.each do |p|
		puts p[1]['name']
	end
end

#prompt for search term
puts "Enter a search term:"
search_term = gets.chomp
search_breweries search_term

puts "Enter the number of the brewery would you like to save"
search_term = gets.chomp
db_save(search_term)
get_favorite_breweries
Clone this wiki locally