similar_models 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a937276a3ad548a1941029abfdedbb6696c14e39
4
+ data.tar.gz: 90d95999b118943e34ae960fce17be495918b30b
5
+ SHA512:
6
+ metadata.gz: 5d0cd374a49fbc5f1ee85433d38463eabdbdad9990ad81bb94efd142caea0a922f5fb8e7d12bf7622f96718976264be6d47fd13fa6f369a7e036fdec63a59095
7
+ data.tar.gz: c6df39065597cbf583c8311564b15854ddee418eb5fdcee5337aa52685523f2fd12df8d5aab6079842742d1c91e97feb0f5e4bbd2485917587bb9aeb97215e39
data/.gitignore ADDED
@@ -0,0 +1,18 @@
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
18
+ .byebug_history
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format progress
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.3.3
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in similar_models.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2014 Jolyon Pawlyn
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,79 @@
1
+ # Similar Models
2
+
3
+ Adds a `similar_{model name plural}` method to an active record model, but can be set to any name using `as: {method name}`. It returns the most similar models of the same class based on associated models in common.
4
+
5
+ The association(s) have to be many to many, so either habtm or 'has_many though'.
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ gem 'similar_models'
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install similar_models
20
+
21
+ ## Usage
22
+
23
+ Post example
24
+
25
+ class Post < ActiveRecord::Base
26
+ has_many :author_posts
27
+ has_many :authors, through: :author_posts
28
+ has_and_belongs_to_many :tags
29
+
30
+ has_similar_models :authors
31
+ has_similar_models :tags, as: :similar_posts_by_tags
32
+ has_similar_models :authors, :tags, as: :similar_posts_by_author_or_tag
33
+ end
34
+
35
+ class Tag < ActiveRecord::Base
36
+ end
37
+
38
+ class Author < ActiveRecord::Base
39
+ has_many :author_posts
40
+ end
41
+
42
+ class AuthorPosts < ActiveRecord::Base
43
+ belongs_to :author
44
+ belongs_to :post
45
+ end
46
+
47
+ To return the posts with the most authors in common with `post` in descending order:
48
+
49
+ post.similar_posts
50
+
51
+ The returned object is an ActiveRecord::Relation and so chaining of other query methods is possible:
52
+
53
+ post.similar_posts.where('posts.created_at > ?', 10.days.ago).limit(5)
54
+
55
+ To return the posts with the most tags in common with `post` in descending order:
56
+
57
+ post.similar_posts_by_tag
58
+
59
+ To return the posts with the most authors and tags in common with `post` in descending order:
60
+
61
+ post.similar_posts_by_author_and_tag
62
+
63
+ The count of the associated models in common is accessible on each returned model:
64
+
65
+ post.similar_posts_model_count
66
+ post.similar_posts_by_tag_model_count
67
+ post.similar_posts_by_author_and_tag_model_count
68
+
69
+ Note multiple associations do not work with sqlite.
70
+
71
+ Because of the use of `group`, pagination is not supported.
72
+
73
+ ## Contributing
74
+
75
+ 1. Fork it
76
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
77
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
78
+ 4. Push to the branch (`git push origin my-new-feature`)
79
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,3 @@
1
+ module SimilarModels
2
+ VERSION = '0.1.0'
3
+ end
@@ -0,0 +1,58 @@
1
+ require 'similar_models/version'
2
+
3
+ module SimilarModels
4
+
5
+ def has_similar_models(*many_to_many_associations, as: nil)
6
+ as = "similar_#{model_name.plural}" unless as
7
+
8
+ # defaults to 'def similar_{model name}'
9
+ define_method as do
10
+ table_name = self.class.table_name
11
+ association_scopes = []
12
+
13
+ many_to_many_associations.each do |many_to_many_association|
14
+ assocation = self.class.reflect_on_association(many_to_many_association)
15
+ join_table, foreign_key, association_foreign_key = self.class.join_table_values(assocation)
16
+
17
+ association_scopes << self.class.where("#{join_table}.#{association_foreign_key} IN " +
18
+ "(select #{join_table}.#{association_foreign_key} from #{join_table} " +
19
+ "where #{join_table}.#{foreign_key} = :foreign_key)", foreign_key: self.id).
20
+ joins("INNER JOIN #{join_table} ON #{join_table}.#{foreign_key} = #{table_name}.id")
21
+ end
22
+
23
+ scope = self.class.select("#{table_name}.*, count(#{table_name}.id) AS #{as}_model_count").
24
+ where.not(id: self.id).order("#{as}_model_count DESC")
25
+ group_by_clause = 'id'
26
+
27
+ # if there is only one many-to-many association no need to use UNION sql syntax
28
+ if association_scopes.one?
29
+ scope.merge(association_scopes.first).group(group_by_clause)
30
+ else
31
+ # with postgres the group by clause has to be different
32
+ # http://dba.stackexchange.com/questions/88988/postgres-error-column-must-appear-in-the-group-by-clause-or-be-used-in-an-aggre
33
+ if ActiveRecord::Base.connection.adapter_name == 'PostgreSQL'
34
+ group_by_clause = self.class.column_names.join(', ')
35
+ end
36
+
37
+ # see http://blog.ubersense.com/2013/09/27/tech-talk-unioning-scoped-queries-in-rails/
38
+ scope.from("((#{association_scopes.map(&:to_sql).join(') UNION ALL (')})) AS #{table_name}").group(group_by_clause)
39
+ end
40
+ end
41
+
42
+ def self.join_table_values(many_to_many_assocation)
43
+ if many_to_many_assocation.macro == :has_and_belongs_to_many
44
+ join_table = many_to_many_assocation.join_table
45
+ foreign_key = many_to_many_assocation.foreign_key
46
+ association_foreign_key = many_to_many_assocation.association_foreign_key
47
+ elsif many_to_many_assocation.macro == :has_many
48
+ join_table = many_to_many_assocation.through_reflection.table_name
49
+ foreign_key = many_to_many_assocation.through_reflection.foreign_key
50
+ association_foreign_key = many_to_many_assocation.foreign_key
51
+ end
52
+ [join_table, foreign_key, association_foreign_key]
53
+ end
54
+ end
55
+ end
56
+
57
+ # Extend ActiveRecord functionality
58
+ ActiveRecord::Base.extend SimilarModels
@@ -0,0 +1,30 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'similar_models/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "similar_models"
8
+ spec.version = SimilarModels::VERSION
9
+ spec.authors = ["Jolyon Pawlyn"]
10
+ spec.email = ["jpawlyn@gmail.com"]
11
+ spec.description = %q{Adds an instance method to an active record model that returns the most similar models based on associated models in common}
12
+ spec.summary = %q{Returns models that have the most associated models in common}
13
+ spec.homepage = "https://github.com/jpawlyn/similar_models"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files`.split($/)
17
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.required_ruby_version = '>= 2.1'
22
+ spec.add_runtime_dependency 'activerecord', '~> 4.2'
23
+ spec.add_development_dependency 'bundler', '~> 1.13'
24
+ spec.add_development_dependency 'rspec', '~> 3.5'
25
+ spec.add_development_dependency 'database_cleaner', '~>1.5'
26
+ spec.add_development_dependency 'sqlite3', '~>1.3'
27
+ spec.add_development_dependency 'mysql2', '~>0.4'
28
+ spec.add_development_dependency 'pg', '~>0.19'
29
+ spec.add_development_dependency 'byebug', '~>9.0'
30
+ end
data/spec/post_spec.rb ADDED
@@ -0,0 +1,51 @@
1
+ require 'spec_helper'
2
+
3
+ describe Post do
4
+ let(:author1) { Author.create! }
5
+ let(:author2) { Author.create! }
6
+ let(:author3) { Author.create! }
7
+ let(:author4) { Author.create! }
8
+ let(:tag1) { Tag.create! }
9
+ let(:tag2) { Tag.create! }
10
+ let(:tag3) { Tag.create! }
11
+ let(:tag4) { Tag.create! }
12
+
13
+ context 'has_many through:' do
14
+ it 'return posts that have the most authors in common with post' do
15
+ post = Post.create! authors: [author1, author2, author3]
16
+ post1 = Post.create! authors: [author1, author4]
17
+ post2 = Post.create! authors: [author1, author2]
18
+ post3 = Post.create! authors: [author4]
19
+ post4 = Post.create! authors: [author1, author2, author3]
20
+
21
+ expect(post.similar_posts.map(&:similar_posts_model_count)).to eq([3, 2, 1])
22
+ expect(post.similar_posts).to eq([post4, post2, post1])
23
+ end
24
+ end
25
+
26
+ context 'has_and_belongs_to_many' do
27
+ it 'return posts that have the most tags in common with post' do
28
+ post = Post.create! tags: [tag1, tag2, tag3]
29
+ post1 = Post.create! tags: [tag1, tag4]
30
+ post2 = Post.create! tags: [tag1, tag2]
31
+ post3 = Post.create! tags: [tag4]
32
+ post4 = Post.create! tags: [tag1, tag2, tag3]
33
+
34
+ expect(post.similar_posts_by_tag.map(&:similar_posts_by_tag_model_count)).to eq([3, 2, 1])
35
+ expect(post.similar_posts_by_tag).to eq([post4, post2, post1])
36
+ end
37
+ end
38
+
39
+ context "combination of 'has_many through:' and habtm" do
40
+ let!(:post) { Post.create! authors: [author1, author2, author3], tags: [tag1, tag2, tag3] }
41
+ let!(:post1) { Post.create! authors: [author1, author2, author3], tags: [tag1, tag2, tag4] }
42
+ let!(:post2) { Post.create! authors: [author1, author4] }
43
+ let!(:post3) { Post.create! tags: [tag4] }
44
+ let!(:post4) { Post.create! authors: [author1], tags: [tag1, tag2, tag3] }
45
+
46
+ it 'return posts that have the most authors and tags in common with post' do
47
+ expect(post.similar_posts_by_author_and_tag.map(&:similar_posts_by_author_and_tag_model_count)).to eq([5, 4, 1])
48
+ expect(post.similar_posts_by_author_and_tag).to eq([post1, post4, post2])
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,40 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # Require this file using `require "spec_helper"` to ensure that it is only
4
+ # loaded once.
5
+ #
6
+
7
+ # see http://blog.markstarkman.com/blog/2013/01/23/using-sqlite-to-test-active-record-models/
8
+ require 'active_record'
9
+
10
+ ActiveRecord::Base.establish_connection adapter: 'postgresql', database: 'similar_models'
11
+ # ActiveRecord::Base.establish_connection adapter: 'mysql2', database: 'similar_models'
12
+ # ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
13
+ load 'support/schema.rb'
14
+
15
+ require 'similar_models'
16
+ require 'support/models'
17
+ require 'database_cleaner'
18
+ require 'byebug'
19
+
20
+ DatabaseCleaner.strategy = :transaction
21
+
22
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
23
+ RSpec.configure do |config|
24
+ config.run_all_when_everything_filtered = true
25
+ config.filter_run :focus
26
+
27
+ # Run specs in random order to surface order dependencies. If you find an
28
+ # order dependency and want to debug it, you can fix the order by providing
29
+ # the seed, which is printed after each run.
30
+ # --seed 1234
31
+ config.order = 'random'
32
+
33
+ config.before :each do
34
+ DatabaseCleaner.start
35
+ end
36
+
37
+ config.after :each do
38
+ DatabaseCleaner.clean
39
+ end
40
+ end
@@ -0,0 +1,20 @@
1
+ class Post < ActiveRecord::Base
2
+ has_many :author_posts
3
+ has_many :authors, through: :author_posts
4
+ has_and_belongs_to_many :tags
5
+
6
+ has_similar_models :authors
7
+ has_similar_models :tags, as: :similar_posts_by_tag
8
+ has_similar_models :authors, :tags, as: :similar_posts_by_author_and_tag
9
+ end
10
+
11
+ class Tag < ActiveRecord::Base
12
+ end
13
+
14
+ class Author < ActiveRecord::Base
15
+ end
16
+
17
+ class AuthorPost < ActiveRecord::Base
18
+ belongs_to :author
19
+ belongs_to :post
20
+ end
@@ -0,0 +1,25 @@
1
+ ActiveRecord::Schema.define do
2
+ self.verbose = false
3
+
4
+ create_table :authors, force: true do |t|
5
+ t.timestamps null: false
6
+ end
7
+
8
+ create_table :author_posts, force: true do |t|
9
+ t.integer :author_id, null: false
10
+ t.integer :post_id, null: false
11
+ t.timestamps null: false
12
+ end
13
+
14
+ create_table :posts, force: true do |t|
15
+ t.timestamps null: false
16
+ end
17
+
18
+ create_table :posts_tags, force: true do |t|
19
+ t.integer :post_id, null: false
20
+ t.integer :tag_id, null: false
21
+ end
22
+
23
+ create_table :tags, force: true do |t|
24
+ end
25
+ end
metadata ADDED
@@ -0,0 +1,175 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: similar_models
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jolyon Pawlyn
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2017-01-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4.2'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4.2'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '1.13'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '1.13'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.5'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.5'
55
+ - !ruby/object:Gem::Dependency
56
+ name: database_cleaner
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.5'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.5'
69
+ - !ruby/object:Gem::Dependency
70
+ name: sqlite3
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '1.3'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '1.3'
83
+ - !ruby/object:Gem::Dependency
84
+ name: mysql2
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.4'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.4'
97
+ - !ruby/object:Gem::Dependency
98
+ name: pg
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0.19'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0.19'
111
+ - !ruby/object:Gem::Dependency
112
+ name: byebug
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - "~>"
116
+ - !ruby/object:Gem::Version
117
+ version: '9.0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - "~>"
123
+ - !ruby/object:Gem::Version
124
+ version: '9.0'
125
+ description: Adds an instance method to an active record model that returns the most
126
+ similar models based on associated models in common
127
+ email:
128
+ - jpawlyn@gmail.com
129
+ executables: []
130
+ extensions: []
131
+ extra_rdoc_files: []
132
+ files:
133
+ - ".gitignore"
134
+ - ".rspec"
135
+ - ".ruby-version"
136
+ - Gemfile
137
+ - LICENSE.txt
138
+ - README.md
139
+ - Rakefile
140
+ - lib/similar_models.rb
141
+ - lib/similar_models/version.rb
142
+ - similar_models.gemspec
143
+ - spec/post_spec.rb
144
+ - spec/spec_helper.rb
145
+ - spec/support/models.rb
146
+ - spec/support/schema.rb
147
+ homepage: https://github.com/jpawlyn/similar_models
148
+ licenses:
149
+ - MIT
150
+ metadata: {}
151
+ post_install_message:
152
+ rdoc_options: []
153
+ require_paths:
154
+ - lib
155
+ required_ruby_version: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - ">="
158
+ - !ruby/object:Gem::Version
159
+ version: '2.1'
160
+ required_rubygems_version: !ruby/object:Gem::Requirement
161
+ requirements:
162
+ - - ">="
163
+ - !ruby/object:Gem::Version
164
+ version: '0'
165
+ requirements: []
166
+ rubyforge_project:
167
+ rubygems_version: 2.5.2
168
+ signing_key:
169
+ specification_version: 4
170
+ summary: Returns models that have the most associated models in common
171
+ test_files:
172
+ - spec/post_spec.rb
173
+ - spec/spec_helper.rb
174
+ - spec/support/models.rb
175
+ - spec/support/schema.rb