From a0a03f2ed922c423eaf0c1c2df13ffd80717d981 Mon Sep 17 00:00:00 2001 From: Amit Sharma Date: Sun, 6 Oct 2024 12:56:34 -0400 Subject: [PATCH 1/4] initial commit --- .idea/.gitignore | 8 + .idea/dataSources.xml | 32 ++ .idea/misc.xml | 4 + .idea/topnews.iml | 533 ++++++++++++++++++ .idea/vcs.xml | 6 + Gemfile | 11 +- Gemfile.lock | 42 ++ app/controllers/application_controller.rb | 4 + app/controllers/stories_controller.rb | 7 + app/helpers/stories_helper.rb | 27 + app/models/story.rb | 2 + app/models/user.rb | 4 + app/services/story_fetcher_service.rb | 32 ++ app/views/devise/confirmations/new.html.erb | 16 + .../mailer/confirmation_instructions.html.erb | 5 + .../devise/mailer/email_changed.html.erb | 7 + .../devise/mailer/password_change.html.erb | 3 + .../reset_password_instructions.html.erb | 8 + .../mailer/unlock_instructions.html.erb | 7 + app/views/devise/passwords/edit.html.erb | 25 + app/views/devise/passwords/new.html.erb | 16 + app/views/devise/registrations/edit.html.erb | 43 ++ app/views/devise/registrations/new.html.erb | 29 + app/views/devise/sessions/new.html.erb | 26 + .../devise/shared/_error_messages.html.erb | 15 + app/views/devise/shared/_links.html.erb | 25 + app/views/devise/unlocks/new.html.erb | 16 + app/views/layouts/application.html.erb | 97 +++- app/views/stories/index.html.erb | 96 ++++ config/routes.rb | 12 +- config/schedule.rb | 3 + .../20241006144718_add_devise_to_users.rb | 41 ++ db/schema.rb | 12 +- spec/factories/stories.rb | 7 + spec/helpers/stories_helper_spec.rb | 15 + spec/jobs/update_stories_job_spec.rb | 5 + spec/models/story_spec.rb | 5 + spec/requests/stories_spec.rb | 11 + spec/views/stories/index.html.erb_spec.rb | 5 + 39 files changed, 1239 insertions(+), 23 deletions(-) create mode 100644 .idea/.gitignore create mode 100644 .idea/dataSources.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/topnews.iml create mode 100644 .idea/vcs.xml create mode 100644 app/controllers/stories_controller.rb create mode 100644 app/helpers/stories_helper.rb create mode 100644 app/models/story.rb create mode 100644 app/services/story_fetcher_service.rb create mode 100644 app/views/devise/confirmations/new.html.erb create mode 100644 app/views/devise/mailer/confirmation_instructions.html.erb create mode 100644 app/views/devise/mailer/email_changed.html.erb create mode 100644 app/views/devise/mailer/password_change.html.erb create mode 100644 app/views/devise/mailer/reset_password_instructions.html.erb create mode 100644 app/views/devise/mailer/unlock_instructions.html.erb create mode 100644 app/views/devise/passwords/edit.html.erb create mode 100644 app/views/devise/passwords/new.html.erb create mode 100644 app/views/devise/registrations/edit.html.erb create mode 100644 app/views/devise/registrations/new.html.erb create mode 100644 app/views/devise/sessions/new.html.erb create mode 100644 app/views/devise/shared/_error_messages.html.erb create mode 100644 app/views/devise/shared/_links.html.erb create mode 100644 app/views/devise/unlocks/new.html.erb create mode 100644 app/views/stories/index.html.erb create mode 100644 config/schedule.rb create mode 100644 db/migrate/20241006144718_add_devise_to_users.rb create mode 100644 spec/factories/stories.rb create mode 100644 spec/helpers/stories_helper_spec.rb create mode 100644 spec/jobs/update_stories_job_spec.rb create mode 100644 spec/models/story_spec.rb create mode 100644 spec/requests/stories_spec.rb create mode 100644 spec/views/stories/index.html.erb_spec.rb diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 00000000..13566b81 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml new file mode 100644 index 00000000..d994ff1f --- /dev/null +++ b/.idea/dataSources.xml @@ -0,0 +1,32 @@ + + + + + postgresql + true + true + $PROJECT_DIR$/config/database.yml + org.postgresql.Driver + jdbc:postgresql://127.0.0.1:5432/topnews_production + $ProjectFileDir$ + + + postgresql + true + true + $PROJECT_DIR$/config/database.yml + org.postgresql.Driver + jdbc:postgresql://127.0.0.1:5432/topnews_development + $ProjectFileDir$ + + + postgresql + true + true + $PROJECT_DIR$/config/database.yml + org.postgresql.Driver + jdbc:postgresql://127.0.0.1:5432/topnews_test + $ProjectFileDir$ + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 00000000..3205808e --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/.idea/topnews.iml b/.idea/topnews.iml new file mode 100644 index 00000000..641a91f6 --- /dev/null +++ b/.idea/topnews.iml @@ -0,0 +1,533 @@ + + + + + + + + + + + + + + + + file://$MODULE_DIR$/app + + + file://$MODULE_DIR$/app/assets + + + file://$MODULE_DIR$/app/channels + + + file://$MODULE_DIR$/app/controllers + + + file://$MODULE_DIR$/app/helpers + + + file://$MODULE_DIR$/app/mailers + + + file://$MODULE_DIR$/app/models + + + file://$MODULE_DIR$/app/views + + + file://$MODULE_DIR$/config + + + file://$MODULE_DIR$/config/cable.yml + + + file://$MODULE_DIR$/config/database.yml + + + file://$MODULE_DIR$/config/environment.rb + + + file://$MODULE_DIR$/config/environments + + + file://$MODULE_DIR$/config/initializers + + + file://$MODULE_DIR$/config/locales + + + file://$MODULE_DIR$/config/routes + + + file://$MODULE_DIR$/config/routes.rb + + + file://$MODULE_DIR$/config + + + file://$MODULE_DIR$/db + + + file://$MODULE_DIR$/db/migrate + + + file://$MODULE_DIR$/db/seeds.rb + + + file://$MODULE_DIR$/lib + + + file://$MODULE_DIR$/lib/assets + + + file://$MODULE_DIR$/lib/tasks + + + file://$MODULE_DIR$/lib/templates + + + file://$MODULE_DIR$/log/development.log + + + file://$MODULE_DIR$/public + + + file://$MODULE_DIR$/public/javascripts + + + file://$MODULE_DIR$/public/stylesheets + + + file://$MODULE_DIR$/tmp + + + file://$MODULE_DIR$/vendor + + + file://$MODULE_DIR$/vendor/assets + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 00000000..35eb1ddf --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Gemfile b/Gemfile index fd2e2b45..62db1a3b 100644 --- a/Gemfile +++ b/Gemfile @@ -2,11 +2,12 @@ source 'https://rubygems.org' ruby File.read('.ruby-version').chomp -gem 'byebug', platforms: [:mri, :mingw, :x64_mingw], group: [:development, :test] -gem 'capybara', group: [:development, :test] +gem 'byebug', platforms: %i[mri mingw x64_mingw], group: %i[development test] +gem 'capybara', group: %i[development test] gem 'coffee-rails' gem 'devise' gem 'factory_bot_rails' +gem 'httparty' gem 'jbuilder' gem 'listen', group: :development gem 'pg' @@ -14,10 +15,12 @@ gem 'pry-rails' gem 'puma' gem 'rails', '~> 7.0.8' gem 'rspec-rails' +gem 'rubocop', group: 'development', require: false gem 'sass-rails' -gem 'selenium-webdriver', group: [:development, :test] +gem 'selenium-webdriver', group: %i[development test] +gem 'sidekiq' gem 'spring', group: :development gem 'turbolinks' -gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] +gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] gem 'uglifier' gem 'web-console', group: :development diff --git a/Gemfile.lock b/Gemfile.lock index 7d7a3577..c1a59cb7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -68,8 +68,10 @@ GEM tzinfo (~> 2.0) addressable (2.8.7) public_suffix (>= 2.0.2, < 7.0) + ast (2.4.2) base64 (0.2.0) bcrypt (3.1.20) + bigdecimal (3.1.8) bindex (0.8.1) builder (3.3.0) byebug (11.1.3) @@ -91,7 +93,9 @@ GEM execjs coffee-script-source (1.12.2) concurrent-ruby (1.3.4) + connection_pool (2.4.1) crass (1.0.6) + csv (3.3.0) date (3.3.4) devise (4.9.4) bcrypt (~> 3.0) @@ -110,11 +114,17 @@ GEM ffi (1.17.0) globalid (1.2.1) activesupport (>= 6.1) + httparty (0.22.0) + csv + mini_mime (>= 1.0.0) + multi_xml (>= 0.5.2) i18n (1.14.5) concurrent-ruby (~> 1.0) jbuilder (2.12.0) actionview (>= 5.0.0) activesupport (>= 5.0.0) + json (2.7.2) + language_server-protocol (3.17.0.3) listen (3.9.0) rb-fsevent (~> 0.10, >= 0.10.3) rb-inotify (~> 0.9, >= 0.9.10) @@ -133,6 +143,8 @@ GEM mini_mime (1.1.5) mini_portile2 (2.8.7) minitest (5.25.1) + multi_xml (0.7.1) + bigdecimal (~> 3.1) net-imap (0.4.14) date net-protocol @@ -147,6 +159,10 @@ GEM mini_portile2 (~> 2.8.2) racc (~> 1.4) orm_adapter (0.5.0) + parallel (1.26.3) + parser (3.3.5.0) + ast (~> 2.4.1) + racc pg (1.5.7) pry (0.14.2) coderay (~> 1.1) @@ -188,10 +204,13 @@ GEM rake (>= 12.2) thor (~> 1.0) zeitwerk (~> 2.5) + rainbow (3.1.1) rake (13.2.1) rb-fsevent (0.11.2) rb-inotify (0.11.1) ffi (~> 1.0) + redis-client (0.22.2) + connection_pool regexp_parser (2.9.2) responders (3.1.1) actionpack (>= 5.2) @@ -215,6 +234,19 @@ GEM rspec-mocks (~> 3.13) rspec-support (~> 3.13) rspec-support (3.13.1) + rubocop (1.66.1) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.4, < 3.0) + rubocop-ast (>= 1.32.2, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.32.3) + parser (>= 3.3.1.0) + ruby-progressbar (1.13.0) rubyzip (2.3.2) sass-rails (6.0.0) sassc-rails (~> 2.1, >= 2.1.1) @@ -232,6 +264,12 @@ GEM rexml (~> 3.2, >= 3.2.5) rubyzip (>= 1.2.2, < 3.0) websocket (~> 1.0) + sidekiq (7.3.2) + concurrent-ruby (< 2) + connection_pool (>= 2.3.0) + logger + rack (>= 2.2.4) + redis-client (>= 0.22.2) spring (4.2.1) sprockets (4.2.1) concurrent-ruby (~> 1.0) @@ -251,6 +289,7 @@ GEM concurrent-ruby (~> 1.0) uglifier (4.2.0) execjs (>= 0.3.0, < 3) + unicode-display_width (2.6.0) warden (1.2.9) rack (>= 2.0.9) web-console (4.2.1) @@ -275,6 +314,7 @@ DEPENDENCIES coffee-rails devise factory_bot_rails + httparty jbuilder listen pg @@ -282,8 +322,10 @@ DEPENDENCIES puma rails (~> 7.0.8) rspec-rails + rubocop sass-rails selenium-webdriver + sidekiq spring turbolinks tzinfo-data diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 1c07694e..542c2e6a 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -1,3 +1,7 @@ class ApplicationController < ActionController::Base protect_from_forgery with: :exception + + def after_sign_in_path_for(resource) + user_root_path + end end diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb new file mode 100644 index 00000000..44dd3b84 --- /dev/null +++ b/app/controllers/stories_controller.rb @@ -0,0 +1,7 @@ +class StoriesController < ApplicationController + before_action :authenticate_user! + + def index + @stories = StoryFetcherService.fetch_top_stories(10) + end +end diff --git a/app/helpers/stories_helper.rb b/app/helpers/stories_helper.rb new file mode 100644 index 00000000..774bdbe0 --- /dev/null +++ b/app/helpers/stories_helper.rb @@ -0,0 +1,27 @@ +module StoriesHelper + def story_url(story) + story.respond_to?(:url) ? story.url : story[:url] + end + + def story_title(story) + story.respond_to?(:title) ? story.title : story[:title] + end + + def story_author(story) + story.respond_to?(:author) ? story.author : story[:author] + end + + def story_type(story) + story.respond_to?(:story_type) ? story.story_type : story[:type] + end + + def story_published_at(story) + if story.respond_to?(:published_at) && story.published_at + story.published_at.strftime("%Y-%m-%d %H:%M:%S") + elsif story[:published_at] + Time.at(story[:published_at]).strftime("%Y-%m-%d %H:%M:%S") + else + 'Not available' + end + end +end \ No newline at end of file diff --git a/app/models/story.rb b/app/models/story.rb new file mode 100644 index 00000000..7ecb37c4 --- /dev/null +++ b/app/models/story.rb @@ -0,0 +1,2 @@ +class Story < ApplicationRecord +end \ No newline at end of file diff --git a/app/models/user.rb b/app/models/user.rb index b2091f9a..332b63a2 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,5 +1,9 @@ class User < ApplicationRecord # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable + # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable diff --git a/app/services/story_fetcher_service.rb b/app/services/story_fetcher_service.rb new file mode 100644 index 00000000..8e89a363 --- /dev/null +++ b/app/services/story_fetcher_service.rb @@ -0,0 +1,32 @@ +class StoryFetcherService + require 'httparty' + + TOP_STORIES_URL = 'https://hacker-news.firebaseio.com/v0/topstories.json'.freeze + STORY_DETAILS_URL = 'https://hacker-news.firebaseio.com/v0/item/%{id}.json'.freeze + + def self.fetch_top_stories(limit = 10) + story_ids = fetch_top_story_ids.take(limit) + story_ids.map { |id| fetch_story_details(id) } + end + + def self.fetch_top_story_ids + response = HTTParty.get(TOP_STORIES_URL) + response.parsed_response + end + + def self.fetch_story_details(id) + response = HTTParty.get(STORY_DETAILS_URL % { id: id }) + transform_story_data(response.parsed_response) + end + + def self.transform_story_data(story_data) + { + id: story_data['id'], + title: story_data['title'], + author: story_data['by'], + type: story_data['type'], + published_at: Time.at(story_data['time']), + url: story_data['url'] + } + end +end diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb new file mode 100644 index 00000000..b12dd0cb --- /dev/null +++ b/app/views/devise/confirmations/new.html.erb @@ -0,0 +1,16 @@ +

Resend confirmation instructions

+ +<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email", value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email) %> +
+ +
+ <%= f.submit "Resend confirmation instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb new file mode 100644 index 00000000..dc55f64f --- /dev/null +++ b/app/views/devise/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/app/views/devise/mailer/email_changed.html.erb b/app/views/devise/mailer/email_changed.html.erb new file mode 100644 index 00000000..32f4ba80 --- /dev/null +++ b/app/views/devise/mailer/email_changed.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @email %>!

+ +<% if @resource.try(:unconfirmed_email?) %> +

We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.

+<% else %> +

We're contacting you to notify you that your email has been changed to <%= @resource.email %>.

+<% end %> diff --git a/app/views/devise/mailer/password_change.html.erb b/app/views/devise/mailer/password_change.html.erb new file mode 100644 index 00000000..b41daf47 --- /dev/null +++ b/app/views/devise/mailer/password_change.html.erb @@ -0,0 +1,3 @@ +

Hello <%= @resource.email %>!

+ +

We're contacting you to notify you that your password has been changed.

diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb new file mode 100644 index 00000000..f667dc12 --- /dev/null +++ b/app/views/devise/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password. You can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

+ +

If you didn't request this, please ignore this email.

+

Your password won't change until you access the link above and create a new one.

diff --git a/app/views/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb new file mode 100644 index 00000000..41e148bf --- /dev/null +++ b/app/views/devise/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb new file mode 100644 index 00000000..5fbb9ff0 --- /dev/null +++ b/app/views/devise/passwords/edit.html.erb @@ -0,0 +1,25 @@ +

Change your password

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + <%= f.hidden_field :reset_password_token %> + +
+ <%= f.label :password, "New password" %>
+ <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum)
+ <% end %> + <%= f.password_field :password, autofocus: true, autocomplete: "new-password" %> +
+ +
+ <%= f.label :password_confirmation, "Confirm new password" %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Change my password" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb new file mode 100644 index 00000000..9b486b81 --- /dev/null +++ b/app/views/devise/passwords/new.html.erb @@ -0,0 +1,16 @@ +

Forgot your password?

+ +<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.submit "Send me reset password instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb new file mode 100644 index 00000000..b82e3365 --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,43 @@ +

Edit <%= resource_name.to_s.humanize %>

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +
Currently waiting confirmation for: <%= resource.unconfirmed_email %>
+ <% end %> + +
+ <%= f.label :password %> (leave blank if you don't want to change it)
+ <%= f.password_field :password, autocomplete: "new-password" %> + <% if @minimum_password_length %> +
+ <%= @minimum_password_length %> characters minimum + <% end %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.label :current_password %> (we need your current password to confirm your changes)
+ <%= f.password_field :current_password, autocomplete: "current-password" %> +
+ +
+ <%= f.submit "Update" %> +
+<% end %> + +

Cancel my account

+ +
Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?", turbo_confirm: "Are you sure?" }, method: :delete %>
+ +<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb new file mode 100644 index 00000000..d655b66f --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,29 @@ +

Sign up

+ +<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.label :password %> + <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum) + <% end %>
+ <%= f.password_field :password, autocomplete: "new-password" %> +
+ +
+ <%= f.label :password_confirmation %>
+ <%= f.password_field :password_confirmation, autocomplete: "new-password" %> +
+ +
+ <%= f.submit "Sign up" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 00000000..5ede9648 --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,26 @@ +

Log in

+ +<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.label :password %>
+ <%= f.password_field :password, autocomplete: "current-password" %> +
+ + <% if devise_mapping.rememberable? %> +
+ <%= f.check_box :remember_me %> + <%= f.label :remember_me %> +
+ <% end %> + +
+ <%= f.submit "Log in" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/shared/_error_messages.html.erb b/app/views/devise/shared/_error_messages.html.erb new file mode 100644 index 00000000..cabfe307 --- /dev/null +++ b/app/views/devise/shared/_error_messages.html.erb @@ -0,0 +1,15 @@ +<% if resource.errors.any? %> +
+

+ <%= I18n.t("errors.messages.not_saved", + count: resource.errors.count, + resource: resource.class.model_name.human.downcase) + %> +

+ +
+<% end %> diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb new file mode 100644 index 00000000..7a75304b --- /dev/null +++ b/app/views/devise/shared/_links.html.erb @@ -0,0 +1,25 @@ +<%- if controller_name != 'sessions' %> + <%= link_to "Log in", new_session_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to "Sign up", new_registration_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> + <%= link_to "Forgot your password?", new_password_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> + <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> + <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %>
+<% end %> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= button_to "Sign in with #{OmniAuth::Utils.camelize(provider)}", omniauth_authorize_path(resource_name, provider), data: { turbo: false } %>
+ <% end %> +<% end %> diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb new file mode 100644 index 00000000..ffc34de8 --- /dev/null +++ b/app/views/devise/unlocks/new.html.erb @@ -0,0 +1,16 @@ +

Resend unlock instructions

+ +<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= render "devise/shared/error_messages", resource: resource %> + +
+ <%= f.label :email %>
+ <%= f.email_field :email, autofocus: true, autocomplete: "email" %> +
+ +
+ <%= f.submit "Resend unlock instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 331a7ed0..29a3f7a3 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,19 +1,82 @@ - - - Top News - <%= csrf_meta_tags %> - <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> - <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> - - -

- <%= notice %> -

-

- <%= alert %> -

- <%= yield %> - - + + + Top News + <%= csrf_meta_tags %> + <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> + <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> + + + + + +
+

<%= notice %>

+

<%= alert %>

+ <%= yield %> +
+ + \ No newline at end of file diff --git a/app/views/stories/index.html.erb b/app/views/stories/index.html.erb new file mode 100644 index 00000000..00c01003 --- /dev/null +++ b/app/views/stories/index.html.erb @@ -0,0 +1,96 @@ + + + + Top Hacker News Stories + + + +
+

Top Hacker News Stories

+ +
+ + \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index c12ef082..a98e5924 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,4 +1,14 @@ Rails.application.routes.draw do devise_for :users - root to: 'pages#home' + + authenticated :user do + get 'stories', to: 'stories#index', as: :user_root + end + + unauthenticated do + root to: 'pages#home' + end + + resources :stories, only: [:index] + get 'stories/index' end diff --git a/config/schedule.rb b/config/schedule.rb new file mode 100644 index 00000000..fd0a9113 --- /dev/null +++ b/config/schedule.rb @@ -0,0 +1,3 @@ + every 1.hour do + runner 'UpdateStoriesJob.perform_later' + end diff --git a/db/migrate/20241006144718_add_devise_to_users.rb b/db/migrate/20241006144718_add_devise_to_users.rb new file mode 100644 index 00000000..bc2b4271 --- /dev/null +++ b/db/migrate/20241006144718_add_devise_to_users.rb @@ -0,0 +1,41 @@ +# db/migrate/20241006144718_add_devise_to_users.rb +class AddDeviseToUsers < ActiveRecord::Migration[6.0] + def up + change_table :users do |t| + ## Database authenticatable + t.string :email, null: false, default: "" unless column_exists? :users, :email + t.string :encrypted_password, null: false, default: "" unless column_exists? :users, :encrypted_password + + ## Recoverable + t.string :reset_password_token unless column_exists? :users, :reset_password_token + t.datetime :reset_password_sent_at unless column_exists? :users, :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at unless column_exists? :users, :remember_created_at + + ## Trackable + # t.integer :sign_in_count, default: 0, null: false unless column_exists? :users, :sign_in_count + # t.datetime :current_sign_in_at unless column_exists? :users, :current_sign_in_at + # t.datetime :last_sign_in_at unless column_exists? :users, :last_sign_in_at + # t.string :current_sign_in_ip unless column_exists? :users, :current_sign_in_ip + # t.string :last_sign_in_ip unless column_exists? :users, :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token unless column_exists? :users, :confirmation_token + # t.datetime :confirmed_at unless column_exists? :users, :confirmed_at + # t.datetime :confirmation_sent_at unless column_exists? :users, :confirmation_sent_at + # t.string :unconfirmed_email unless column_exists? :users, :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false unless column_exists? :users, :failed_attempts # Only if lock strategy is :failed_attempts + # t.string :unlock_token unless column_exists? :users, :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at unless column_exists? :users, :locked_at + end + + add_index :users, :email, unique: true unless index_exists? :users, :email + add_index :users, :reset_password_token, unique: true unless index_exists? :users, :reset_password_token + # add_index :users, :confirmation_token, unique: true unless index_exists? :users, :confirmation_token + # add_index :users, :unlock_token, unique: true unless index_exists? :users, :unlock_token + end + +end diff --git a/db/schema.rb b/db/schema.rb index acc34f3b..500e4150 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,10 +10,20 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 2018_02_28_212101) do +ActiveRecord::Schema[7.0].define(version: 2024_10_06_152139) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" + create_table "stories", force: :cascade do |t| + t.string "title" + t.string "author" + t.text "type" + t.datetime "published_at" + t.string "url" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + create_table "users", force: :cascade do |t| t.string "first_name" t.string "last_name" diff --git a/spec/factories/stories.rb b/spec/factories/stories.rb new file mode 100644 index 00000000..6a261b09 --- /dev/null +++ b/spec/factories/stories.rb @@ -0,0 +1,7 @@ +FactoryBot.define do + factory :story do + title { "MyString" } + content { "MyText" } + published_at { "2024-10-06 11:21:39" } + end +end diff --git a/spec/helpers/stories_helper_spec.rb b/spec/helpers/stories_helper_spec.rb new file mode 100644 index 00000000..954b93e7 --- /dev/null +++ b/spec/helpers/stories_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the StoriesHelper. For example: +# +# describe StoriesHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe StoriesHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/jobs/update_stories_job_spec.rb b/spec/jobs/update_stories_job_spec.rb new file mode 100644 index 00000000..a4c2390b --- /dev/null +++ b/spec/jobs/update_stories_job_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe UpdateStoriesJob, type: :job do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/story_spec.rb b/spec/models/story_spec.rb new file mode 100644 index 00000000..dd70e5ba --- /dev/null +++ b/spec/models/story_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Story, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/requests/stories_spec.rb b/spec/requests/stories_spec.rb new file mode 100644 index 00000000..c6713353 --- /dev/null +++ b/spec/requests/stories_spec.rb @@ -0,0 +1,11 @@ +require 'rails_helper' + +RSpec.describe "Stories", type: :request do + describe "GET /index" do + it "returns http success" do + get "/stories/index" + expect(response).to have_http_status(:success) + end + end + +end diff --git a/spec/views/stories/index.html.erb_spec.rb b/spec/views/stories/index.html.erb_spec.rb new file mode 100644 index 00000000..7227ec6d --- /dev/null +++ b/spec/views/stories/index.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "stories/index.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end From 7583168ab2fb7583792573c7e454e899d1930dfb Mon Sep 17 00:00:00 2001 From: Amit Sharma Date: Sun, 6 Oct 2024 15:22:59 -0400 Subject: [PATCH 2/4] added sidekiq and redis --- .idea/dataSources.xml | 7 ++ Gemfile | 4 + Gemfile.lock | 45 +++++-- app/controllers/stories_controller.rb | 15 ++- app/helpers/stories_helper.rb | 31 +++-- app/models/user.rb | 8 +- app/services/story_fetcher_service.rb | 31 ++++- app/workers/fetch_and_store_stories_worker.rb | 8 ++ bin/bundle | 110 +++++++++++++++++- bin/sidekiq | 27 +++++ bin/sidekiqmon | 27 +++++ config/application.rb | 2 + config/initializers/redis.rb | 2 + config/initializers/sidekiq.rb | 10 ++ config/routes.rb | 5 + config/schedule.rb | 3 - config/sidekiq.yml | 15 +++ .../20241006173046_add_admin_to_users.rb | 5 + db/schema.rb | 13 +-- 19 files changed, 324 insertions(+), 44 deletions(-) create mode 100644 app/workers/fetch_and_store_stories_worker.rb create mode 100755 bin/sidekiq create mode 100755 bin/sidekiqmon create mode 100644 config/initializers/redis.rb create mode 100644 config/initializers/sidekiq.rb delete mode 100644 config/schedule.rb create mode 100644 config/sidekiq.yml create mode 100644 db/migrate/20241006173046_add_admin_to_users.rb diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml index d994ff1f..8eadcd12 100644 --- a/.idea/dataSources.xml +++ b/.idea/dataSources.xml @@ -28,5 +28,12 @@ jdbc:postgresql://127.0.0.1:5432/topnews_test $ProjectFileDir$ + + redis + true + jdbc.RedisDriver + jdbc:redis://localhost:6379/0 + $ProjectFileDir$ + \ No newline at end of file diff --git a/Gemfile b/Gemfile index 62db1a3b..1cee0897 100644 --- a/Gemfile +++ b/Gemfile @@ -14,11 +14,15 @@ gem 'pg' gem 'pry-rails' gem 'puma' gem 'rails', '~> 7.0.8' +gem 'redis' gem 'rspec-rails' gem 'rubocop', group: 'development', require: false gem 'sass-rails' gem 'selenium-webdriver', group: %i[development test] gem 'sidekiq' +gem 'sidekiq-cron', '~> 1.2' +gem 'sidekiq-scheduler' +gem 'sinatra', require: nil gem 'spring', group: :development gem 'turbolinks' gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] diff --git a/Gemfile.lock b/Gemfile.lock index c1a59cb7..448d61dc 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -105,13 +105,18 @@ GEM warden (~> 1.2.3) diff-lcs (1.5.1) erubi (1.13.0) + et-orbi (1.2.11) + tzinfo execjs (2.9.1) factory_bot (6.4.2) activesupport (>= 5.0.0) factory_bot_rails (6.4.3) factory_bot (~> 6.4) railties (>= 5.0.0) - ffi (1.17.0) + ffi (1.17.0-arm64-darwin) + fugit (1.11.1) + et-orbi (~> 1, >= 1.2.11) + raabro (~> 1.4) globalid (1.2.1) activesupport (>= 6.1) httparty (0.22.0) @@ -128,7 +133,7 @@ GEM listen (3.9.0) rb-fsevent (~> 0.10, >= 0.10.3) rb-inotify (~> 0.9, >= 0.9.10) - logger (1.6.0) + logger (1.6.1) loofah (2.22.0) crass (~> 1.0.2) nokogiri (>= 1.12.0) @@ -141,10 +146,11 @@ GEM matrix (0.4.2) method_source (1.1.0) mini_mime (1.1.5) - mini_portile2 (2.8.7) minitest (5.25.1) multi_xml (0.7.1) bigdecimal (~> 3.1) + mustermann (3.0.3) + ruby2_keywords (~> 0.0.1) net-imap (0.4.14) date net-protocol @@ -155,8 +161,7 @@ GEM net-smtp (0.5.0) net-protocol nio4r (2.7.3) - nokogiri (1.16.7) - mini_portile2 (~> 2.8.2) + nokogiri (1.16.7-arm64-darwin) racc (~> 1.4) orm_adapter (0.5.0) parallel (1.26.3) @@ -172,8 +177,12 @@ GEM public_suffix (6.0.1) puma (6.4.2) nio4r (~> 2.0) + raabro (1.4.0) racc (1.8.1) rack (2.2.9) + rack-protection (3.2.0) + base64 (>= 0.1.0) + rack (~> 2.2, >= 2.2.4) rack-test (2.1.0) rack (>= 1.3) rails (7.0.8.4) @@ -209,6 +218,8 @@ GEM rb-fsevent (0.11.2) rb-inotify (0.11.1) ffi (~> 1.0) + redis (5.3.0) + redis-client (>= 0.22.0) redis-client (0.22.2) connection_pool regexp_parser (2.9.2) @@ -247,7 +258,10 @@ GEM rubocop-ast (1.32.3) parser (>= 3.3.1.0) ruby-progressbar (1.13.0) + ruby2_keywords (0.0.5) rubyzip (2.3.2) + rufus-scheduler (3.9.2) + fugit (~> 1.1, >= 1.11.1) sass-rails (6.0.0) sassc-rails (~> 2.1, >= 2.1.1) sassc (2.4.0) @@ -270,6 +284,19 @@ GEM logger rack (>= 2.2.4) redis-client (>= 0.22.2) + sidekiq-cron (1.12.0) + fugit (~> 1.8) + globalid (>= 1.0.1) + sidekiq (>= 6) + sidekiq-scheduler (5.0.6) + rufus-scheduler (~> 3.2) + sidekiq (>= 6, < 8) + tilt (>= 1.4.0, < 3) + sinatra (3.2.0) + mustermann (~> 3.0) + rack (~> 2.2, >= 2.2.4) + rack-protection (= 3.2.0) + tilt (~> 2.0) spring (4.2.1) sprockets (4.2.1) concurrent-ruby (~> 1.0) @@ -306,7 +333,7 @@ GEM zeitwerk (2.6.17) PLATFORMS - ruby + arm64-darwin-24 DEPENDENCIES byebug @@ -321,11 +348,15 @@ DEPENDENCIES pry-rails puma rails (~> 7.0.8) + redis rspec-rails rubocop sass-rails selenium-webdriver sidekiq + sidekiq-cron (~> 1.2) + sidekiq-scheduler + sinatra spring turbolinks tzinfo-data @@ -336,4 +367,4 @@ RUBY VERSION ruby 3.2.3p157 BUNDLED WITH - 2.3.22 + 2.4.19 diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb index 44dd3b84..9e5f941f 100644 --- a/app/controllers/stories_controller.rb +++ b/app/controllers/stories_controller.rb @@ -2,6 +2,19 @@ class StoriesController < ApplicationController before_action :authenticate_user! def index - @stories = StoryFetcherService.fetch_top_stories(10) + @stories = fetch_stories_from_redis + @stories.empty? ? fetch_stories_from_service : @stories + end + + private + + def fetch_stories_from_redis + stories_json = $redis.lrange(StoryFetcherService::STORY_LIST_KEY, 0, -1) + stories_json.map { |story| JSON.parse(story, symbolize_names: true) } + end + + def fetch_stories_from_service + service = StoryFetcherService.new + service.perform end end diff --git a/app/helpers/stories_helper.rb b/app/helpers/stories_helper.rb index 774bdbe0..e61e7a94 100644 --- a/app/helpers/stories_helper.rb +++ b/app/helpers/stories_helper.rb @@ -1,27 +1,36 @@ module StoriesHelper def story_url(story) - story.respond_to?(:url) ? story.url : story[:url] + fetch_story_attribute(story, :url) end def story_title(story) - story.respond_to?(:title) ? story.title : story[:title] + fetch_story_attribute(story, :title) end def story_author(story) - story.respond_to?(:author) ? story.author : story[:author] + fetch_story_attribute(story, :author) end def story_type(story) - story.respond_to?(:story_type) ? story.story_type : story[:type] + fetch_story_attribute(story, :type) end def story_published_at(story) - if story.respond_to?(:published_at) && story.published_at - story.published_at.strftime("%Y-%m-%d %H:%M:%S") - elsif story[:published_at] - Time.at(story[:published_at]).strftime("%Y-%m-%d %H:%M:%S") - else - 'Not available' - end + published_at = fetch_story_attribute(story, :published_at) + + story_published_time = if published_at.is_a?(Integer) + Time.at(published_at) + else + Time.parse(published_at.to_s) + end + + story_published_time.strftime('%B %d, %Y %I:%M %p %Z') + end + + + private + + def fetch_story_attribute(story, attribute) + story.respond_to?(attribute) ? story.public_send(attribute) : story[attribute] end end \ No newline at end of file diff --git a/app/models/user.rb b/app/models/user.rb index 332b63a2..3715f258 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,10 +1,10 @@ class User < ApplicationRecord - # Include default devise modules. Others available are: - # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable - # Include default devise modules. Others available are: - # :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable + + def admin? + admin + end end diff --git a/app/services/story_fetcher_service.rb b/app/services/story_fetcher_service.rb index 8e89a363..33c74e9c 100644 --- a/app/services/story_fetcher_service.rb +++ b/app/services/story_fetcher_service.rb @@ -1,32 +1,53 @@ class StoryFetcherService require 'httparty' + STORY_LIST_KEY = 'stories:top_news'.freeze TOP_STORIES_URL = 'https://hacker-news.firebaseio.com/v0/topstories.json'.freeze STORY_DETAILS_URL = 'https://hacker-news.firebaseio.com/v0/item/%{id}.json'.freeze - def self.fetch_top_stories(limit = 10) + def self.perform + new.perform + end + + def perform + stories = fetch_top_stories + store_stories_in_redis(stories) + end + + private + + def fetch_top_stories(limit = 10) story_ids = fetch_top_story_ids.take(limit) story_ids.map { |id| fetch_story_details(id) } end - def self.fetch_top_story_ids + def fetch_top_story_ids response = HTTParty.get(TOP_STORIES_URL) response.parsed_response end - def self.fetch_story_details(id) + def fetch_story_details(id) response = HTTParty.get(STORY_DETAILS_URL % { id: id }) transform_story_data(response.parsed_response) end - def self.transform_story_data(story_data) + def transform_story_data(story_data) { id: story_data['id'], title: story_data['title'], author: story_data['by'], type: story_data['type'], - published_at: Time.at(story_data['time']), + published_at: story_data['time'], url: story_data['url'] } end + + def store_stories_in_redis(stories) + $redis.multi do + $redis.del(STORY_LIST_KEY) + stories.each do |story| + $redis.rpush(STORY_LIST_KEY, story.to_json) + end + end + end end diff --git a/app/workers/fetch_and_store_stories_worker.rb b/app/workers/fetch_and_store_stories_worker.rb new file mode 100644 index 00000000..58211cd6 --- /dev/null +++ b/app/workers/fetch_and_store_stories_worker.rb @@ -0,0 +1,8 @@ +# app/workers/fetch_and_store_stories_worker.rb +class FetchAndStoreStoriesWorker + include Sidekiq::Worker + + def perform + StoryFetcherService.perform + end +end diff --git a/bin/bundle b/bin/bundle index 66e9889e..42c7fd7c 100755 --- a/bin/bundle +++ b/bin/bundle @@ -1,3 +1,109 @@ #!/usr/bin/env ruby -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) -load Gem.bin_path('bundler', 'bundle') +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a =~ Gem::Version::ANCHORED_VERSION_PATTERN + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/bin/sidekiq b/bin/sidekiq new file mode 100755 index 00000000..e7af7e7e --- /dev/null +++ b/bin/sidekiq @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'sidekiq' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("sidekiq", "sidekiq") diff --git a/bin/sidekiqmon b/bin/sidekiqmon new file mode 100755 index 00000000..0c907984 --- /dev/null +++ b/bin/sidekiqmon @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'sidekiqmon' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("sidekiq", "sidekiqmon") diff --git a/config/application.rb b/config/application.rb index 569fba1e..13c7e61d 100644 --- a/config/application.rb +++ b/config/application.rb @@ -16,5 +16,7 @@ class Application < Rails::Application # -- all .rb files in that directory are automatically loaded. config.active_record.legacy_connection_handling = false + config.active_job.queue_adapter = :sidekiq + end end diff --git a/config/initializers/redis.rb b/config/initializers/redis.rb new file mode 100644 index 00000000..0f71961d --- /dev/null +++ b/config/initializers/redis.rb @@ -0,0 +1,2 @@ +# config/initializers/redis.rb +$redis = Redis.new(url: ENV['REDIS_URL'] || 'redis://localhost:6379/1') diff --git a/config/initializers/sidekiq.rb b/config/initializers/sidekiq.rb new file mode 100644 index 00000000..235b63ad --- /dev/null +++ b/config/initializers/sidekiq.rb @@ -0,0 +1,10 @@ +# config/initializers/sidekiq.rb +require 'sidekiq' +require 'sidekiq-cron' + +# Create a new cron job for fetching and storing stories +Sidekiq::Cron::Job.create( + name: 'Fetch and Store Stories - every 1 minute', + cron: '*/1 * * * *', # Cron schedule (every 1 minute) + class: 'FetchAndStoreStoriesWorker' # The worker class to run +) diff --git a/config/routes.rb b/config/routes.rb index a98e5924..26199a57 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -9,6 +9,11 @@ root to: 'pages#home' end + require 'sidekiq/web' + authenticate :user, lambda { |u| u.admin? } do + mount Sidekiq::Web => '/sidekiq' + end + resources :stories, only: [:index] get 'stories/index' end diff --git a/config/schedule.rb b/config/schedule.rb deleted file mode 100644 index fd0a9113..00000000 --- a/config/schedule.rb +++ /dev/null @@ -1,3 +0,0 @@ - every 1.hour do - runner 'UpdateStoriesJob.perform_later' - end diff --git a/config/sidekiq.yml b/config/sidekiq.yml new file mode 100644 index 00000000..b56d4705 --- /dev/null +++ b/config/sidekiq.yml @@ -0,0 +1,15 @@ +# config/sidekiq.yml +#:scheduler: +# :schedule: +# fetch_and_store_stories: +# every: ["1m"] +# class: "FetchAndStoreStoriesWorker" +# queue: default + +:scheduler: + :schedule: + fetch_and_store_stories: + cron: "* * * * *" # Every minute + class: FetchAndStoreStoriesWorker + queue: default + diff --git a/db/migrate/20241006173046_add_admin_to_users.rb b/db/migrate/20241006173046_add_admin_to_users.rb new file mode 100644 index 00000000..892a30e9 --- /dev/null +++ b/db/migrate/20241006173046_add_admin_to_users.rb @@ -0,0 +1,5 @@ +class AddAdminToUsers < ActiveRecord::Migration[7.0] + def change + add_column :users, :admin, :boolean, default: false, null: false + end +end diff --git a/db/schema.rb b/db/schema.rb index 500e4150..caf42949 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,20 +10,10 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 2024_10_06_152139) do +ActiveRecord::Schema[7.0].define(version: 2024_10_06_173046) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" - create_table "stories", force: :cascade do |t| - t.string "title" - t.string "author" - t.text "type" - t.datetime "published_at" - t.string "url" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false - end - create_table "users", force: :cascade do |t| t.string "first_name" t.string "last_name" @@ -39,6 +29,7 @@ t.inet "last_sign_in_ip" t.datetime "created_at", precision: nil, null: false t.datetime "updated_at", precision: nil, null: false + t.boolean "admin", default: false, null: false t.index ["email"], name: "index_users_on_email", unique: true t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end From 1b1de38113bc621091290e5d489aecc687d02cac Mon Sep 17 00:00:00 2001 From: Amit Sharma Date: Sun, 6 Oct 2024 18:23:03 -0400 Subject: [PATCH 3/4] added star functionality --- app/assets/javascripts/application.js | 5 ++ app/controllers/stories_controller.rb | 47 +++++++++++++- app/helpers/stories_helper.rb | 9 ++- app/models/starred_story.rb | 7 +++ app/models/story.rb | 7 ++- app/models/user.rb | 10 ++- app/services/story_fetcher_service.rb | 14 +++++ app/views/stories/index.html.erb | 61 +++++++++++++++++++ config/routes.rb | 10 ++- .../20241006193300_create_starred_stories.rb | 12 ++++ db/migrate/20241006210100_create_stories.rb | 13 ++++ db/schema.rb | 22 ++++++- spec/factories/stories.rb | 6 +- 13 files changed, 210 insertions(+), 13 deletions(-) create mode 100644 app/models/starred_story.rb create mode 100644 db/migrate/20241006193300_create_starred_stories.rb create mode 100644 db/migrate/20241006210100_create_stories.rb diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js index 46b20359..bf60aa40 100644 --- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -13,3 +13,8 @@ //= require rails-ujs //= require turbolinks //= require_tree . +// app/assets/javascripts/application.js + +//= require rails-ujs +//= require turbolinks +//= require_tree . \ No newline at end of file diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb index 9e5f941f..aab6f3c5 100644 --- a/app/controllers/stories_controller.rb +++ b/app/controllers/stories_controller.rb @@ -1,9 +1,40 @@ class StoriesController < ApplicationController before_action :authenticate_user! + skip_before_action :verify_authenticity_token, only: [:star, :unstar] def index @stories = fetch_stories_from_redis - @stories.empty? ? fetch_stories_from_service : @stories + @stories = fetch_stories_from_service if @stories.empty? + add_starred_data_to_stories(@stories) + end + + def star + story_id = params[:id] + story = Story.find_by(id: story_id) + + if story + if current_user.starred_stories.exists?(story_id:) + render json: { success: false, message: 'Story already starred' }, status: :unprocessable_entity + else + current_user.starred_stories.create!(story_id:) + render json: { success: true, starred_by: story.starred_by_names } + end + else + render json: { success: false }, status: :not_found + end + end + + def unstar + story_id = params[:id] + starred_story = current_user.starred_stories.find_by(story_id:) + + if starred_story + starred_story.destroy + story = Story.find_by(id: story_id) + render json: { success: true, starred_by: story.starred_by_names } + else + render json: { success: false, message: 'Story not starred' }, status: :not_found + end end private @@ -17,4 +48,16 @@ def fetch_stories_from_service service = StoryFetcherService.new service.perform end -end + + def add_starred_data_to_stories(stories) + # Get all starred story IDs for the current user + starred_story_ids = current_user.starred_stories.pluck(:story_id) + + # Mark stories as starred if they are in the user's starred stories + stories.each do |story| + story['is_starred'] = starred_story_ids.include?(story['id'].to_s) + end + + stories + end +end \ No newline at end of file diff --git a/app/helpers/stories_helper.rb b/app/helpers/stories_helper.rb index e61e7a94..3f6db7ac 100644 --- a/app/helpers/stories_helper.rb +++ b/app/helpers/stories_helper.rb @@ -17,16 +17,21 @@ def story_type(story) def story_published_at(story) published_at = fetch_story_attribute(story, :published_at) - story_published_time = if published_at.is_a?(Integer) Time.at(published_at) else Time.parse(published_at.to_s) end - story_published_time.strftime('%B %d, %Y %I:%M %p %Z') end + def story_starred?(story, user) + user.starred_stories.exists?(story_id: story[:id]) + end + + def story_starred_by(story) + (story[:starred_by] || []).map { |name| name.join(' ') }.join(', ') + end private diff --git a/app/models/starred_story.rb b/app/models/starred_story.rb new file mode 100644 index 00000000..da78d97c --- /dev/null +++ b/app/models/starred_story.rb @@ -0,0 +1,7 @@ +class StarredStory < ApplicationRecord + belongs_to :user + belongs_to :story + + validates :story_id, presence: true + validates :user_id, uniqueness: { scope: :story_id } +end diff --git a/app/models/story.rb b/app/models/story.rb index 7ecb37c4..3dadda01 100644 --- a/app/models/story.rb +++ b/app/models/story.rb @@ -1,2 +1,7 @@ class Story < ApplicationRecord -end \ No newline at end of file + has_many :starred_stories, dependent: :destroy + + def starred_by_names + starred_stories.joins(:user).pluck('users.first_name', 'users.last_name').map { |name| name.join(' ') } + end +end diff --git a/app/models/user.rb b/app/models/user.rb index 3715f258..f7adc1ab 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -1,10 +1,14 @@ +# file: user.rb class User < ApplicationRecord - devise :database_authenticatable, :registerable, - :recoverable, :rememberable, :validatable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable + has_many :starred_stories, dependent: :destroy + has_many :stories, through: :starred_stories + + validates :email, presence: true + def admin? admin end -end +end \ No newline at end of file diff --git a/app/services/story_fetcher_service.rb b/app/services/story_fetcher_service.rb index 33c74e9c..e782e46c 100644 --- a/app/services/story_fetcher_service.rb +++ b/app/services/story_fetcher_service.rb @@ -12,6 +12,7 @@ def self.perform def perform stories = fetch_top_stories store_stories_in_redis(stories) + store_stories_in_db(stories) end private @@ -50,4 +51,17 @@ def store_stories_in_redis(stories) end end end + + def store_stories_in_db(stories) + stories.each do |story| + db_story = Story.find_or_initialize_by(id: story[:id]) + db_story.update( + title: story[:title], + url: story[:url], + author: story[:author], + story_type: story[:type], + published_at: Time.at(story[:published_at]) + ) + end + end end diff --git a/app/views/stories/index.html.erb b/app/views/stories/index.html.erb index 00c01003..221b39b4 100644 --- a/app/views/stories/index.html.erb +++ b/app/views/stories/index.html.erb @@ -1,7 +1,10 @@ + Top Hacker News Stories + <%= csrf_meta_tags %> + <%= csp_meta_tag %> @@ -82,9 +95,13 @@ <%= story_title(story) %> + + <%= story_starred?(story, current_user) ? '★' : '☆' %> +

By: <%= story_author(story) %>

Published at: <%= story_published_at(story) %> + Starred by: <%= story_starred_by(story) %> <% end %> <% else %> @@ -92,5 +109,49 @@ <% end %> + + + \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index 26199a57..6d5edaac 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -10,10 +10,16 @@ end require 'sidekiq/web' - authenticate :user, lambda { |u| u.admin? } do + authenticate :user, lambda(&:admin?) do mount Sidekiq::Web => '/sidekiq' end - resources :stories, only: [:index] + resources :stories, only: [:index] do + member do + patch :star + patch :unstar + end + end + get 'stories/index' end diff --git a/db/migrate/20241006193300_create_starred_stories.rb b/db/migrate/20241006193300_create_starred_stories.rb new file mode 100644 index 00000000..231717fa --- /dev/null +++ b/db/migrate/20241006193300_create_starred_stories.rb @@ -0,0 +1,12 @@ +class CreateStarredStories < ActiveRecord::Migration[7.0] + def change + create_table :starred_stories do |t| + t.references :user, null: false, foreign_key: true + t.string :story_id, null: false + + t.timestamps + end + + add_index :starred_stories, [:user_id, :story_id], unique: true + end +end diff --git a/db/migrate/20241006210100_create_stories.rb b/db/migrate/20241006210100_create_stories.rb new file mode 100644 index 00000000..2660717a --- /dev/null +++ b/db/migrate/20241006210100_create_stories.rb @@ -0,0 +1,13 @@ +class CreateStories < ActiveRecord::Migration[7.0] + def change + create_table :stories do |t| + t.string :title + t.string :url + t.string :author + t.datetime :published_at + t.string :story_type + + t.timestamps + end + end +end diff --git a/db/schema.rb b/db/schema.rb index caf42949..513b566c 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,10 +10,29 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.0].define(version: 2024_10_06_173046) do +ActiveRecord::Schema[7.0].define(version: 2024_10_06_210100) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" + create_table "starred_stories", force: :cascade do |t| + t.bigint "user_id", null: false + t.string "story_id", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["user_id", "story_id"], name: "index_starred_stories_on_user_id_and_story_id", unique: true + t.index ["user_id"], name: "index_starred_stories_on_user_id" + end + + create_table "stories", force: :cascade do |t| + t.string "title" + t.string "url" + t.string "author" + t.datetime "published_at" + t.string "story_type" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + end + create_table "users", force: :cascade do |t| t.string "first_name" t.string "last_name" @@ -34,4 +53,5 @@ t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true end + add_foreign_key "starred_stories", "users" end diff --git a/spec/factories/stories.rb b/spec/factories/stories.rb index 6a261b09..9b89eafc 100644 --- a/spec/factories/stories.rb +++ b/spec/factories/stories.rb @@ -1,7 +1,9 @@ FactoryBot.define do factory :story do title { "MyString" } - content { "MyText" } - published_at { "2024-10-06 11:21:39" } + url { "MyString" } + author { "MyString" } + published_at { "2024-10-06 17:01:00" } + story_type { "MyString" } end end From 63c46ede5008f1c32b7ccb8423f06e8ccd1b3e81 Mon Sep 17 00:00:00 2001 From: Amit Sharma Date: Sun, 6 Oct 2024 20:03:23 -0400 Subject: [PATCH 4/4] list for starred stories added --- app/assets/javascripts/application.js | 3 +- app/assets/javascripts/stories.js | 45 +++++++++ app/controllers/stories_controller.rb | 11 ++- app/helpers/stories_helper.rb | 3 +- app/views/layouts/application.html.erb | 23 ++++- app/views/stories/index.html.erb | 124 ++++++++++++------------- config/sidekiq.yml | 10 +- 7 files changed, 134 insertions(+), 85 deletions(-) create mode 100644 app/assets/javascripts/stories.js diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js index bf60aa40..427149e9 100644 --- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -17,4 +17,5 @@ //= require rails-ujs //= require turbolinks -//= require_tree . \ No newline at end of file +//= require_tree . +//= require stories \ No newline at end of file diff --git a/app/assets/javascripts/stories.js b/app/assets/javascripts/stories.js new file mode 100644 index 00000000..49b28ed2 --- /dev/null +++ b/app/assets/javascripts/stories.js @@ -0,0 +1,45 @@ +document.addEventListener('DOMContentLoaded', () => { + const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content'); + + document.querySelectorAll('.star').forEach(starElement => { + starElement.addEventListener('click', async (event) => { + const storyId = starElement.getAttribute('data-id'); + const isStarred = starElement.classList.contains('starred'); + const response = await fetch(`/stories/${storyId}/${isStarred ? 'unstar' : 'star'}`, { + method: 'PATCH', + headers: { + 'Content-Type': 'application/json', + 'X-CSRF-Token': csrfToken + } + }); + + if (response.ok) { + const json = await response.json(); + if (json.success) { + starElement.classList.toggle('starred'); + const isStarred = starElement.classList.contains('starred'); + starElement.textContent = isStarred ? '★' : '☆'; + updateStarredBy(starElement, json.starred_by); + window.location.reload(); + } else { + console.error(json.message || 'Failed to star/unstar the story'); + } + } else { + console.error('Failed to star/unstar the story'); + } + }); + }); + + function updateStarredBy(starElement, starredBy) { + const storyNode = starElement.closest('li'); + const starredByElement = storyNode.querySelector('.starred-by'); + if (starredByElement) { + if (starredBy.length > 0) { + starredByElement.textContent = `Starred by: ${starredBy.join(', ')}`; + } else { + starredByElement.textContent = 'Starred by: No one yet'; + } + } + } + +}); \ No newline at end of file diff --git a/app/controllers/stories_controller.rb b/app/controllers/stories_controller.rb index aab6f3c5..7a231024 100644 --- a/app/controllers/stories_controller.rb +++ b/app/controllers/stories_controller.rb @@ -3,6 +3,7 @@ class StoriesController < ApplicationController skip_before_action :verify_authenticity_token, only: [:star, :unstar] def index + @starred_stories = StarredStory.includes(:user, :story).map(&:story).uniq @stories = fetch_stories_from_redis @stories = fetch_stories_from_service if @stories.empty? add_starred_data_to_stories(@stories) @@ -13,11 +14,11 @@ def star story = Story.find_by(id: story_id) if story - if current_user.starred_stories.exists?(story_id:) + if current_user.starred_stories.exists?(story_id: story_id) render json: { success: false, message: 'Story already starred' }, status: :unprocessable_entity else - current_user.starred_stories.create!(story_id:) - render json: { success: true, starred_by: story.starred_by_names } + current_user.starred_stories.create!(story_id: story_id) + render json: { success: true, starred_by: story.starred_by_names, story: story } end else render json: { success: false }, status: :not_found @@ -26,12 +27,12 @@ def star def unstar story_id = params[:id] - starred_story = current_user.starred_stories.find_by(story_id:) + starred_story = current_user.starred_stories.find_by(story_id: story_id) if starred_story starred_story.destroy story = Story.find_by(id: story_id) - render json: { success: true, starred_by: story.starred_by_names } + render json: { success: true, starred_by: story.starred_by_names, story: story } else render json: { success: false, message: 'Story not starred' }, status: :not_found end diff --git a/app/helpers/stories_helper.rb b/app/helpers/stories_helper.rb index 3f6db7ac..20391ba1 100644 --- a/app/helpers/stories_helper.rb +++ b/app/helpers/stories_helper.rb @@ -30,7 +30,8 @@ def story_starred?(story, user) end def story_starred_by(story) - (story[:starred_by] || []).map { |name| name.join(' ') }.join(', ') + starred_stories = StarredStory.includes(:user).where(story_id: story[:id]) + starred_stories.map { |star| "#{star.user.first_name} #{star.user.last_name}" }.join(', ') end private diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 29a3f7a3..41b6ba1d 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,4 +1,4 @@ - + @@ -15,18 +15,32 @@ .navbar { display: flex; - justify-content: space-between; + justify-content: center; /* Center items horizontally */ align-items: center; background-color: #2d3748; color: white; - padding: 1rem; + padding: 0.3rem 1rem; /* Reduced height */ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); + width: calc(100% - 1.5rem); /* Full width minus the margin */ + position: fixed; /* Fixed to the top */ + top: 0; + left: 0; /* Remove left space */ + margin-right: 0.75rem; /* Reduce space to the right */ + z-index: 1000; /* Ensure it stays above other elements */ + height: 3rem; /* Reduced height to 3rem */ + } + + .navbar h1 { + flex: 1; /* Allow h1 to take available space */ + text-align: center; /* Center text within its flexbox */ + font-size: 1.5rem; /* Adjusted to fit reduced navbar height */ + margin: 0; /* Remove default margin */ } .navbar a { color: white; text-decoration: none; - padding: 0.5rem 1rem; + padding: 0.3rem 0.5rem; /* Adjusted padding for reduced height */ border-radius: 4px; transition: background-color 0.3s, transform 0.2s ease; display: inline-block; @@ -54,6 +68,7 @@ .content { padding: 1rem; + margin-top: 3.5rem; /* Adjust for fixed navbar height and margin */ } .menu { diff --git a/app/views/stories/index.html.erb b/app/views/stories/index.html.erb index 221b39b4..a281f5c9 100644 --- a/app/views/stories/index.html.erb +++ b/app/views/stories/index.html.erb @@ -13,14 +13,25 @@ min-height: 100vh; margin: 0; padding: 0; + display: flex; + flex-direction: column; + align-items: center; } .container { - width: 100%; - padding: 1rem 2rem; /* Add padding to left and right */ + display: flex; + width: 100%; /* Full-width content */ + max-width: 1200px; /* Optional max-width for readability */ + padding: 1rem; background: rgba(255, 255, 255, 0.9); color: #333; - box-sizing: border-box; /* Include padding and border in the element's total width and height */ + box-sizing: border-box; + gap: 2rem; + margin-top: 1rem; /* Gap between header and content */ + } + + .story-list { + flex: 1; } h1 { @@ -86,72 +97,55 @@
-

Top Hacker News Stories

-
    - <% if @stories.any? %> - <% @stories.each do |story| %> -
  • -

    - - <%= story_title(story) %> - - - <%= story_starred?(story, current_user) ? '★' : '☆' %> - -

    -

    By: <%= story_author(story) %>

    - Published at: <%= story_published_at(story) %> - Starred by: <%= story_starred_by(story) %> -
  • +
    +

    Top Hacker News Stories

    +
      + <% if @stories.any? %> + <% @stories.each do |story| %> +
    • +

      + + <%= story_title(story) %> + + + <%= story_starred?(story, current_user) ? '★' : '☆' %> + +

      +

      By: <%= story_author(story) %>

      + Published at: <%= story_published_at(story) %> + +
    • + <% end %> + <% else %> +

      No stories available

      + <% end %> +
    +
    +
    +

    Starred Stories

    +
      + <% if @starred_stories.any? %> + <% @starred_stories.each do |story| %> +
    • +

      + + <%= story_title(story) %> + +

      +

      By: <%= story_author(story) %>

      + Published at: <%= story_published_at(story) %> + Starred by: <%= story_starred_by(story) %> +
    • + <% end %> + <% else %> +

      No starred stories available

      <% end %> - <% else %> -

      No stories available

      - <% end %> -
    +
+
- \ No newline at end of file diff --git a/config/sidekiq.yml b/config/sidekiq.yml index b56d4705..b17aa2d0 100644 --- a/config/sidekiq.yml +++ b/config/sidekiq.yml @@ -1,15 +1,7 @@ -# config/sidekiq.yml -#:scheduler: -# :schedule: -# fetch_and_store_stories: -# every: ["1m"] -# class: "FetchAndStoreStoriesWorker" -# queue: default - :scheduler: :schedule: fetch_and_store_stories: - cron: "* * * * *" # Every minute + cron: "* * * * *" # Every minute for testing class: FetchAndStoreStoriesWorker queue: default