From d8455d2867356a527713b887729b962c8c07f8ad Mon Sep 17 00:00:00 2001 From: Aaro Koivukangas Date: Wed, 16 Aug 2023 10:05:14 +0300 Subject: [PATCH] rubocop fixing + helper methods --- app/models/user.rb | 22 ++++++++++++++-------- spec/models/user_spec.rb | 2 ++ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 1bb392d..45abd4b 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -22,21 +22,27 @@ class User < ApplicationRecord def favorite_style # create hash with key being style name and value first 0 and then the score styles = {} - self.ratings.each do |rating| - styles[rating.beer.style] = 0 + ratings.each do |rating| + if styles[rating.beer.style].nil? + styles[rating.beer.style] = rating.score + else + styles[rating.beer.style] += rating.score + end end - self.ratings.each do |rating| - styles[rating.beer.style] += rating.score - end - # determine which style hast the most points - highest = {name: "", total: 0} + style_with_most_points(styles) + end + + private + + def style_with_most_points(styles) + highest = { name: "", total: 0 } styles.each do |style| if style[1] > highest[:total] highest[:name] = style[0] highest[:total] = style[1] end end - return highest[:name] + highest[:name] end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 1308d60..8ca78ed 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -52,6 +52,8 @@ RSpec.describe User, type: :model do create_beer_with_many_ratings({user: user}, 20, 30, 20) beer_with_favorite_style = FactoryBot.create(:beer, style: "No") FactoryBot.create(:rating, beer: beer_with_favorite_style, score: 50, user: user) + + expect(user.favorite_style).to eq "Yes" end end end