popularity_contest 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/.gitignore ADDED
@@ -0,0 +1,17 @@
1
+ *.gem
2
+ *.rbc
3
+ .bundle
4
+ .config
5
+ .yardoc
6
+ Gemfile.lock
7
+ InstalledFiles
8
+ _yardoc
9
+ coverage
10
+ doc/
11
+ lib/bundler/man
12
+ pkg
13
+ rdoc
14
+ spec/reports
15
+ test/tmp
16
+ test/version_tmp
17
+ tmp
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in popularity_contest.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2013 Kasper Grubbe
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # PopularityContest
2
+
3
+ ## Installation
4
+
5
+ Add this line to your application's Gemfile:
6
+
7
+ gem 'popularity_contest'
8
+
9
+ And then execute:
10
+
11
+ $ bundle
12
+
13
+ Or install it yourself as:
14
+
15
+ $ gem install popularity_contest
16
+
17
+ ## Usage
18
+
19
+ Add this rack application to your Rails routes:
20
+
21
+ ```ruby
22
+ require 'popularity_contest/web'
23
+ mount PopularityContest::Web, :at => "popularity"
24
+ ```
25
+
26
+ You can now reach it from `HOSTNAME/popularity`.
27
+
28
+ To use in your views you have a helper here:
29
+
30
+ ```ruby
31
+ <%= popular_count_hit_path('event', 1337) %>
32
+ # /popularity/event/1337
33
+ ```
34
+
35
+ Or if you have jQuery available you can use this:
36
+
37
+ ```ruby
38
+ <%= popular_count_hit_jquery('event', 1337) %>
39
+ # <script>
40
+ # (function(window, document, $, undefined) {
41
+ # $.ajax({
42
+ # url: '/popularity/event/1337',
43
+ # dataType: 'html',
44
+ # cache: false
45
+ # })
46
+ # }(window, document, jQuery));
47
+ # </script>
48
+ ```
49
+
50
+ ## Contributing
51
+
52
+ 1. Fork it
53
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
54
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
55
+ 4. Push to the branch (`git push origin my-new-feature`)
56
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1,5 @@
1
+ require "bundler/gem_tasks"
2
+
3
+ require 'rspec/core/rake_task'
4
+
5
+ RSpec::Core::RakeTask.new(:spec)
@@ -0,0 +1,9 @@
1
+ require 'popularity_contest/view_helpers'
2
+
3
+ module PopularityContest
4
+ class Railtie < Rails::Railtie
5
+ initializer "popularity_contest.view_helpers" do |app|
6
+ ActionView::Base.send :include, ViewHelpers
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,75 @@
1
+ module PopularityContest
2
+ module ViewHelpers
3
+ def popular_count_hit_path(content_type, content_id)
4
+ begin
5
+ build_path(content_type, content_id)
6
+ rescue
7
+ "<!-- error occurred in PopularityContest :| -->"
8
+ end
9
+ end
10
+
11
+ def popular_count_hit_jquery(content_type, content_id)
12
+ begin
13
+ url = build_path(content_type, content_id)
14
+ <<-SJS
15
+ <script>
16
+ (function(window, document, $, undefined) {
17
+ $.ajax({
18
+ url: '#{url}',
19
+ dataType: 'html',
20
+ cache: false
21
+ })
22
+ }(window, document, jQuery));
23
+ </script>
24
+ SJS
25
+ rescue
26
+ "<!-- error occurred in PopularityContest :| -->"
27
+ end
28
+ end
29
+
30
+ def popular_content(content_type, limit=10, date=Date.today.strftime("%y-%m-%d"))
31
+ begin
32
+ PopularityContest::most_popular(content_type, redis_connection, limit)
33
+ rescue
34
+ []
35
+ end
36
+ end
37
+
38
+ def all_popular_content(content_type)
39
+ begin
40
+ PopularityContest::all_popular(content_type, redis_connection)
41
+ rescue
42
+ []
43
+ end
44
+ end
45
+
46
+ private
47
+ def build_path(content_type, content_id)
48
+ content_type = content_type.to_s.downcase
49
+ uri = []
50
+ uri << "#{Rails.application.routes.url_helpers.popularity_contest_web_path}"
51
+ uri << "#{content_type}"
52
+ uri << "#{content_id}"
53
+
54
+ strip_locale_uri(uri.join("/"))
55
+ end
56
+ # Because Billetto have locales in URLs like billetto.dk/da and billetto.dk/en
57
+ # and the paths returned from Rails will include those, and this route:
58
+ # mount PopularityContest::Web, :at => "hit"
59
+ # will only bind on: billetto.dk/hit/our/app
60
+ # and not: billetto.dk/en/hit/our/app
61
+ def strip_locale_uri(path)
62
+ path.to_s.gsub(/\/(en|da|no|sv)/i, "")
63
+ end
64
+
65
+ def redis_connection
66
+ if $redis.present?
67
+ redis = $redis
68
+ elsif @redis.present?
69
+ redis = @redis
70
+ else
71
+ raise 'Unable to find a usable redis instance'
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,97 @@
1
+ require 'sinatra'
2
+ require "sinatra/reloader"
3
+ require "sinatra/json"
4
+
5
+ module PopularityContest
6
+ class Web < Sinatra::Base
7
+ helpers Sinatra::JSON
8
+
9
+ class BadRequest < StandardError; end
10
+
11
+ configure :development do
12
+ register Sinatra::Reloader # reload code when we develop
13
+
14
+ # For easier local development (act as production):
15
+ # set :raise_errors, false
16
+ # set :show_exceptions, false
17
+ # set :dump_errors, false
18
+ end
19
+
20
+ def initialize(app = nil)
21
+ super
22
+ @app = app
23
+ @redis = $redis
24
+
25
+ if @redis
26
+ puts "PopularityContest: Running in #{Sinatra::Base.environment} environment"
27
+ else
28
+ puts "=> Statistics Redis connection failure"
29
+ end
30
+ end
31
+
32
+ # For testing what is in the DB
33
+ # get '/pretty/:type' do
34
+ # PopularityContest::most_popular(params[:type], @redis, 10).to_json
35
+ # end
36
+
37
+ # For testing populating the keys
38
+ # get '/test' do
39
+ # 100.times do |event_id|
40
+ # Random.rand(1...1000).times do |hits|
41
+ # incr_key('event', event_id)
42
+ # end
43
+ # end
44
+ # end
45
+
46
+ # For incrementing a key:
47
+ get '/:type/:id' do
48
+ content_id = params[:id].to_i
49
+ if(content_id != 0) # check if ID is present as an integer
50
+ content_type :json
51
+ incr_key(params[:type], content_id)
52
+ {:content => "#{params[:type]}##{content_id}", :key => PopularityContest::key(params[:type], content_id)}.to_json
53
+ else
54
+ raise BadRequest, "invalid input format"
55
+ end
56
+ end
57
+
58
+ options '/:type/:id' do
59
+ headers cors_headers_list
60
+ halt
61
+ end
62
+
63
+ private
64
+ # Redis-helpers
65
+ def incr_key(content_type, content_id)
66
+ @redis.multi do
67
+ key = PopularityContest::key(content_type, content_id)
68
+ puts "PopularityContest: Incrementing key='#{key}'" if Sinatra::Base.development?
69
+ @redis.incr(key)
70
+ @redis.expire(key, 48*60*60) # each time we increment we expire 48 hours out in the future
71
+ end
72
+ end
73
+
74
+ # Error-handling
75
+ def error(statuscode, message)
76
+ content_type :json
77
+ status statuscode.to_i # or whatever
78
+
79
+ logger.info "#{statuscode} - #{message}"
80
+
81
+ {:error => message}.to_json
82
+ end
83
+
84
+ def cors_headers_list
85
+ {
86
+ 'Access-Control-Allow-Origin' => '*',
87
+ 'Access-Control-Allow-Methods' => %w(GET OPTIONS).join(', '),
88
+ 'Access-Control-Allow-Headers' => %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(', '),
89
+ }
90
+ end
91
+
92
+ error BadRequest do
93
+ e = env['sinatra.error']
94
+ error(500, e.message)
95
+ end
96
+ end
97
+ end
@@ -0,0 +1,53 @@
1
+ module PopularityContest
2
+ NAME = "PopularityContest"
3
+ LICENSE = 'See LICENSE for licensing details.'
4
+
5
+ private
6
+ # helpers
7
+ def self.key(content_type, content_id, date = Date.today.strftime("%y-%m-%d"))
8
+ key = []
9
+ key << "popular"
10
+ key << "type:#{content_type}"
11
+ key << "id:#{content_id}"
12
+ key << "date:#{date}"
13
+ key << "hits"
14
+ key.join(":")
15
+ end
16
+
17
+ def self.content_id_from_key(key)
18
+ # 'popular:type:#{content_type}:id:12456:date:#{Date.today.strftime("%y-%m-%d")}:count'.scan(/id:(\d+)/i).flatten.first
19
+ key.scan(/id:(\d+)/i).flatten.first.to_i
20
+ end
21
+
22
+ def self.most_popular(content_type, redis_connection, limit=10)
23
+ limit = 10 if limit.nil? || !limit.is_a?(Integer) # make sure limit is right, else default
24
+ all_popular(content_type, redis_connection).take(limit)
25
+ end
26
+
27
+ def self.all_popular(content_type, redis_connection)
28
+ keys = redis_connection.keys(PopularityContest::key(content_type, '*'))
29
+
30
+ hits = redis_connection.pipelined do
31
+ keys.each do |key|
32
+ redis_connection.mget(key)
33
+ end
34
+ end.flatten.collect{|hit| hit.to_i }
35
+ # each of these hits is an array, flatten that
36
+ # and convert the hits to integer
37
+ # unfortunately Redis doesn't support the integer datatype as default
38
+
39
+ # get all the content_ids
40
+ # TODO: Do this after sorting
41
+ content_ids = keys.collect{|key| PopularityContest::content_id_from_key(key) }
42
+
43
+
44
+ # merge the three arrays: [keys, hits, content_ids]
45
+ # [ "popular:type:event:id:66:date:13-04-18:count",
46
+ # "2",
47
+ # 1337 ]
48
+ # and sort them highest to lowest
49
+ [keys, hits, content_ids].transpose.sort! { |x,y| y[1].to_i <=> x[1].to_i }
50
+ end
51
+ end
52
+
53
+ require 'popularity_contest/railtie' if defined?(::Rails::Engine)
@@ -0,0 +1,29 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "popularity_contest"
7
+ spec.version = "0.0.6"
8
+ spec.authors = ["Kasper Grubbe"]
9
+ spec.email = ["kawsper@gmail.com"]
10
+ spec.description = "A Rack application to count and sort popular content on our websites"
11
+ spec.summary = "Count and sort popular content on our site"
12
+ spec.homepage = ""
13
+ spec.license = "MIT"
14
+
15
+ spec.files = `git ls-files`.split($/)
16
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
17
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
18
+ spec.require_paths = ["lib"]
19
+
20
+ spec.add_development_dependency "bundler", "~> 1.3"
21
+ spec.add_development_dependency "rake"
22
+ spec.add_development_dependency "pry"
23
+ spec.add_development_dependency "rspec"
24
+ spec.add_development_dependency "mock_redis"
25
+
26
+ spec.add_dependency "sinatra"
27
+ spec.add_dependency "sinatra-contrib"
28
+ spec.add_dependency "redis"
29
+ end
@@ -0,0 +1,23 @@
1
+ require 'rack/test'
2
+
3
+ require File.expand_path '../../../lib/popularity_contest/web.rb', __FILE__
4
+
5
+ ENV['RACK_ENV'] = 'test'
6
+
7
+ module RSpecMixin
8
+ include Rack::Test::Methods
9
+ def app() ::PopularityContest::Web end
10
+ end
11
+
12
+ RSpec.configure { |c| c.include RSpecMixin }
13
+
14
+ describe PopularityContest::Web do
15
+ it "handles cors options query" do
16
+ options '/event/123'
17
+ expect(last_response).to be_ok
18
+ expect(last_response.headers['Access-Control-Allow-Origin']).to eq('*')
19
+ expect(last_response.headers['Access-Control-Allow-Methods']).to eq('GET, OPTIONS')
20
+ expect(last_response.headers['Access-Control-Allow-Headers']).to eq('Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token')
21
+ end
22
+ end
23
+
@@ -0,0 +1,51 @@
1
+ require 'popularity_contest'
2
+ require 'mock_redis'
3
+ require 'date'
4
+
5
+ describe PopularityContest do
6
+ before :each do
7
+ @redis = MockRedis.new
8
+ end
9
+
10
+ describe "#all_popular" do
11
+ it "should return all popular" do
12
+ (0..9).each do |index|
13
+ add_event_with_id(index)
14
+ end
15
+
16
+ result = PopularityContest::all_popular("event", @redis)
17
+ expect(result.size).to eq 10
18
+
19
+ mapped_ids = result.map{|x| x[2]}
20
+ (0..9).each do |index|
21
+ expect(mapped_ids).to include(index)
22
+ end
23
+ end
24
+ end
25
+
26
+ describe "#most_popular" do
27
+ it "should return 10 items by default" do
28
+ (0..20).each do |index|
29
+ add_event_with_id(index)
30
+ end
31
+
32
+ result = PopularityContest::most_popular("event", @redis)
33
+ expect(result.size).to eq 10
34
+ end
35
+
36
+ it "should return limited count of items when it is passed" do
37
+ (0..20).each do |index|
38
+ add_event_with_id(index)
39
+ end
40
+
41
+ result = PopularityContest::most_popular("event", @redis, 5)
42
+ expect(result.size).to eq 5
43
+ end
44
+ end
45
+
46
+ private
47
+ def add_event_with_id(id)
48
+ key = PopularityContest::key("event", id)
49
+ @redis.incr(key)
50
+ end
51
+ end
metadata ADDED
@@ -0,0 +1,188 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: popularity_contest
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.6
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Kasper Grubbe
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2014-07-21 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: bundler
16
+ requirement: !ruby/object:Gem::Requirement
17
+ none: false
18
+ requirements:
19
+ - - ~>
20
+ - !ruby/object:Gem::Version
21
+ version: '1.3'
22
+ type: :development
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ~>
28
+ - !ruby/object:Gem::Version
29
+ version: '1.3'
30
+ - !ruby/object:Gem::Dependency
31
+ name: rake
32
+ requirement: !ruby/object:Gem::Requirement
33
+ none: false
34
+ requirements:
35
+ - - ! '>='
36
+ - !ruby/object:Gem::Version
37
+ version: '0'
38
+ type: :development
39
+ prerelease: false
40
+ version_requirements: !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ! '>='
44
+ - !ruby/object:Gem::Version
45
+ version: '0'
46
+ - !ruby/object:Gem::Dependency
47
+ name: pry
48
+ requirement: !ruby/object:Gem::Requirement
49
+ none: false
50
+ requirements:
51
+ - - ! '>='
52
+ - !ruby/object:Gem::Version
53
+ version: '0'
54
+ type: :development
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ none: false
58
+ requirements:
59
+ - - ! '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ - !ruby/object:Gem::Dependency
63
+ name: rspec
64
+ requirement: !ruby/object:Gem::Requirement
65
+ none: false
66
+ requirements:
67
+ - - ! '>='
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ type: :development
71
+ prerelease: false
72
+ version_requirements: !ruby/object:Gem::Requirement
73
+ none: false
74
+ requirements:
75
+ - - ! '>='
76
+ - !ruby/object:Gem::Version
77
+ version: '0'
78
+ - !ruby/object:Gem::Dependency
79
+ name: mock_redis
80
+ requirement: !ruby/object:Gem::Requirement
81
+ none: false
82
+ requirements:
83
+ - - ! '>='
84
+ - !ruby/object:Gem::Version
85
+ version: '0'
86
+ type: :development
87
+ prerelease: false
88
+ version_requirements: !ruby/object:Gem::Requirement
89
+ none: false
90
+ requirements:
91
+ - - ! '>='
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ - !ruby/object:Gem::Dependency
95
+ name: sinatra
96
+ requirement: !ruby/object:Gem::Requirement
97
+ none: false
98
+ requirements:
99
+ - - ! '>='
100
+ - !ruby/object:Gem::Version
101
+ version: '0'
102
+ type: :runtime
103
+ prerelease: false
104
+ version_requirements: !ruby/object:Gem::Requirement
105
+ none: false
106
+ requirements:
107
+ - - ! '>='
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ - !ruby/object:Gem::Dependency
111
+ name: sinatra-contrib
112
+ requirement: !ruby/object:Gem::Requirement
113
+ none: false
114
+ requirements:
115
+ - - ! '>='
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ none: false
122
+ requirements:
123
+ - - ! '>='
124
+ - !ruby/object:Gem::Version
125
+ version: '0'
126
+ - !ruby/object:Gem::Dependency
127
+ name: redis
128
+ requirement: !ruby/object:Gem::Requirement
129
+ none: false
130
+ requirements:
131
+ - - ! '>='
132
+ - !ruby/object:Gem::Version
133
+ version: '0'
134
+ type: :runtime
135
+ prerelease: false
136
+ version_requirements: !ruby/object:Gem::Requirement
137
+ none: false
138
+ requirements:
139
+ - - ! '>='
140
+ - !ruby/object:Gem::Version
141
+ version: '0'
142
+ description: A Rack application to count and sort popular content on our websites
143
+ email:
144
+ - kawsper@gmail.com
145
+ executables: []
146
+ extensions: []
147
+ extra_rdoc_files: []
148
+ files:
149
+ - .gitignore
150
+ - Gemfile
151
+ - LICENSE.txt
152
+ - README.md
153
+ - Rakefile
154
+ - lib/popularity_contest.rb
155
+ - lib/popularity_contest/railtie.rb
156
+ - lib/popularity_contest/view_helpers.rb
157
+ - lib/popularity_contest/web.rb
158
+ - popularity_contest.gemspec
159
+ - spec/popularity_contest/web.rb
160
+ - spec/popularity_contest_spec.rb
161
+ homepage: ''
162
+ licenses:
163
+ - MIT
164
+ post_install_message:
165
+ rdoc_options: []
166
+ require_paths:
167
+ - lib
168
+ required_ruby_version: !ruby/object:Gem::Requirement
169
+ none: false
170
+ requirements:
171
+ - - ! '>='
172
+ - !ruby/object:Gem::Version
173
+ version: '0'
174
+ required_rubygems_version: !ruby/object:Gem::Requirement
175
+ none: false
176
+ requirements:
177
+ - - ! '>='
178
+ - !ruby/object:Gem::Version
179
+ version: '0'
180
+ requirements: []
181
+ rubyforge_project:
182
+ rubygems_version: 1.8.23
183
+ signing_key:
184
+ specification_version: 3
185
+ summary: Count and sort popular content on our site
186
+ test_files:
187
+ - spec/popularity_contest/web.rb
188
+ - spec/popularity_contest_spec.rb