Skip to content

Commit

Permalink
Refactoring code to split redis service and fetch actions inside the …
Browse files Browse the repository at this point in the history
…application
  • Loading branch information
ET33 committed Nov 3, 2015
1 parent 16deb9d commit 727fbeb
Show file tree
Hide file tree
Showing 10 changed files with 70 additions and 10 deletions.
1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ gem "jquery-rails"
gem "jbuilder", "~> 2.0"
gem "redis"
gem "friendly_id"
gem "connection_pool", "~> 2.2.0"

group :development, :test do
gem "byebug"
Expand Down
2 changes: 2 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ GEM
coffee-script-source
execjs
coffee-script-source (1.9.1.1)
connection_pool (2.2.0)
debug_inspector (0.0.2)
dotenv (2.0.2)
dotenv-rails (2.0.2)
Expand Down Expand Up @@ -159,6 +160,7 @@ DEPENDENCIES
better_errors
byebug
coffee-rails (~> 4.1.0)
connection_pool (~> 2.2.0)
dotenv-rails
friendly_id
immigrant
Expand Down
6 changes: 6 additions & 0 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,10 @@ class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception

before_action :set_most_read_news

def set_most_read_news
@most_read_news = ::MostReadNews.new.fetch
end
end
12 changes: 3 additions & 9 deletions app/controllers/news_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,9 @@ def index
# GET /news/1
# GET /news/1.json
def show
begin
# Using the ID column as a 'member' because the slug may change
$redis.zincrby(:page_counter, 1, News.find(params[:id]).id)
# Tag script <%= javascript_tag nil, src: count_page_path(request.original_fullpath) %>
# To get top read: `$redis.zrangebyscore(:page_counter, :'-inf', :'+inf').reverse`
# optional: `withscore: true`
@most_read = $redis.zrangebyscore(:page_counter, :'-inf', :'+inf', withscores: true).reverse
rescue
@most_read = nil
RedisPool.redis.with do |conn|
pageview_repository = PageViewRepository.new
pageview_repository.increment_news(News.find(params[:id]))
end
end

Expand Down
26 changes: 26 additions & 0 deletions app/repositories/page_view_repository.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
class PageViewRepository
def redis(options = {}, &block)
@redis ||= RedisPool.redis.with(options, &block)
end

def increment_news(news)
redis do |conn|
conn.zincrby(:news_counter, 1, news.id)
end

rescue => e
logger.tagged("PAGEVIEW") { logger.error("Error increment pageview: #{e.message} . Trace: #{e.backtrace.join(" | ")}") }
end

def most_read_ids
redis do |conn|
conn.zrevrangebyscore(:news_counter, "+inf", "-inf", limit: [0, 5]) || []
end
rescue => e
logger.tagged("PAGEVIEW") { logger.error("Error while retrieving most read news: #{e.message} . Trace: #{e.backtrace.join(" | ")}") }
end

def logger
@logger ||= ActiveSupport::TaggedLogging.new(Rails.logger)
end
end
11 changes: 11 additions & 0 deletions app/use_cases/most_read_news.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
class MostReadNews
def pageview_repository
@pageview_repository ||= PageViewRepository.new
end

def fetch
ids = PageViewRepository.new.most_read_ids
ids.any? ? News.where(id: ids).order("field(id, #{ids.join(",")})") : []
end
end

10 changes: 10 additions & 0 deletions app/views/news/index.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,16 @@
<td><%= link_to 'Destroy', news, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
<% if @most_read_news.any? %>
<tr>
<th>Most Read News</th>
</tr>
<% @most_read_news.each do |news| %>
<tr>
<td><%= news.name %></td>
</tr>
<% end -%>
<% end -%>
</tbody>
</table>

Expand Down
4 changes: 4 additions & 0 deletions config/application.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ class Application < Rails::Application
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de

# Loading lib directory
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += %W(#{config.root}/app/use_cases)

# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
Expand Down
1 change: 0 additions & 1 deletion config/initializers/redis.rb

This file was deleted.

7 changes: 7 additions & 0 deletions lib/redis_pool.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
class RedisPool
def self.redis
@redis ||= ConnectionPool.new(size: 5, timeout: 5) do
Redis.new(host: ENV["REDIS_HOST"], port: ENV["REDIS_PORT"])
end
end
end

0 comments on commit 727fbeb

Please sign in to comment.