Storing voting results
Data persistence with YAML Store
So far we have played with static dummy data.
Let’s store the voting result and update the count whenever we vote for the specific dish.
Adding YAML Store library
Add following code at the top of voting.rb
file:
require 'yaml/store'
Update cast and result route handlers
Now, update the post '/cast'
and get /results
handlers as below:
post '/cast' do
@title = 'Thanks for casting your vote!'
@vote = params['vote']
# create a votes.yml file and update the particular votes
@store = YAML::Store.new 'votes.yml'
@store.transaction do
@store['votes'] ||= {}
@store['votes'][@vote] ||= 0
@store['votes'][@vote] += 1
end
erb :cast
end
get '/results' do
@title = 'Results so far:'
@store = YAML::Store.new 'votes.yml'
@votes = @store.transaction { @store['votes'] }
erb :results
end
We are using YAML here to easily manage our voting data.
YAML stands for YAML Ain't Markup Language. It is a data serialization language that matches user’s expectations about data. It designed to be human friendly and works perfectly with other programming languages. It is highly useful in manage data.
App preview
The web app now will functionally look like below:
There are many areas of improvement here which I leave up to you. This is quite basic and serve as the base for
further development.
Help me to improve BRG Trainings.