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.

App preview

The web app now will functionally look like below:

Voting app final view

Help me to improve BRG Trainings.