|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# For showcasing the reading time of a user |
| 4 | +# Should we show book covers or just the names? |
| 5 | +module DiscourseRewind |
| 6 | + class Rewind::Action::ReadingTime < Service::ActionBase |
| 7 | + option :user |
| 8 | + option :date |
| 9 | + |
| 10 | + def call |
| 11 | + reading_time = UserVisit.where(user: user).where(visited_at: date).sum(:time_read) |
| 12 | + |
| 13 | + { |
| 14 | + data: { |
| 15 | + reading_time: reading_time, |
| 16 | + books: best_book_fit(reading_time), |
| 17 | + }, |
| 18 | + identifier: "reading-time", |
| 19 | + } |
| 20 | + end |
| 21 | + |
| 22 | + def popular_book_reading_time |
| 23 | + { |
| 24 | + "The Hunger Games" => 19_740, |
| 25 | + "The Metamorphosis" => 3120, |
| 26 | + "To Kill a Mockingbird" => 22_800, |
| 27 | + "Pride and Prejudice" => 25_200, |
| 28 | + "1984" => 16_800, |
| 29 | + "The Lord of the Rings" => 108_000, |
| 30 | + "Harry Potter and the Sorcerer's Stone" => 24_600, |
| 31 | + "The Great Gatsby" => 12_600, |
| 32 | + "The Little Prince" => 5400, |
| 33 | + "Animal Farm" => 7200, |
| 34 | + "The Catcher in the Rye" => 18_000, |
| 35 | + "Jane Eyre" => 34_200, |
| 36 | + "Fahrenheit 451" => 15_000, |
| 37 | + "The Hobbit" => 27_000, |
| 38 | + "The Da Vinci Code" => 37_800, |
| 39 | + "Little Women" => 30_000, |
| 40 | + "One Hundred Years of Solitude" => 46_800, |
| 41 | + "And Then There Were None" => 16_200, |
| 42 | + "The Alchemist" => 10_800, |
| 43 | + "The Hitchhiker's Guide to the Galaxy" => 12_600, |
| 44 | + } |
| 45 | + end |
| 46 | + |
| 47 | + def best_book_fit(reading_time) |
| 48 | + reading_time_rest = reading_time |
| 49 | + books = [] |
| 50 | + while reading_time_rest > 0 |
| 51 | + books << popular_book_reading_time.min_by { |_, v| (v - reading_time_rest).abs }.first |
| 52 | + reading_time_rest -= popular_book_reading_time[books.last] |
| 53 | + end |
| 54 | + books.group_by(&:itself).transform_values(&:count) |
| 55 | + end |
| 56 | + end |
| 57 | +end |
0 commit comments