most_related 0.0.2

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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: f43d6f1133f821173a90f7acfbe012d5d9e74185
4
+ data.tar.gz: 711e311cf7fe8e068710bdef6143599cae2716e4
5
+ SHA512:
6
+ metadata.gz: a886a99974f9ec4eb0708b06b69e7eff11a4a94cdc5f0270910d60d3a298434b61a2f8d0c2c3588c33d3cafc47de52eb389f0f0b6f60d6891685cb0a4fd44463
7
+ data.tar.gz: 8d3f4bb699c3223b112165a8754aa23e3e61e2515a6638c165d4493f2f588977fcef8634d04de323a8412b22e07ee19ecad23a35bdc46582586e070987dd12cb
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/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --format progress
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.0.0-p247
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in most_related.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,69 @@
1
+ # MostRelated
2
+
3
+ `most_related` returns models that have the most many to many associated models in common
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ gem 'most_related'
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install most_related
18
+
19
+ ## Usage
20
+
21
+ Post example
22
+
23
+ class Post < ActiveRecord::Base
24
+ has_most_related :authors
25
+ has_most_related :tags, as: :most_related_by_tags
26
+ has_most_related [:authors, :tags], as: :most_related_by_author_or_tag
27
+
28
+ has_many :author_posts
29
+ has_many :authors, through: :author_posts
30
+ end
31
+
32
+ class Author < ActiveRecord::Base
33
+ has_many :author_posts
34
+ end
35
+
36
+ class AuthorPosts < ActiveRecord::Base
37
+ belongs_to :author
38
+ belongs_to :post
39
+ end
40
+
41
+ To return the posts with the most authors in common with post, in descending order:
42
+
43
+ post.most_related
44
+
45
+ To return the posts with the most tags in common with post, in descending order:
46
+
47
+ post.most_related_by_tag
48
+
49
+ To return the posts with the most authors and tags in common with post, in descending order:
50
+
51
+ post.most_related_by_author_or_tag
52
+
53
+ The count of the many to many associated models in common is accessible on each returned model
54
+
55
+ post.most_related_count
56
+ post.most_related_by_tag_count
57
+ post.most_related_by_author_or_tag
58
+
59
+ If multiple many to many associations are used, the syntax is specific to MySql.
60
+
61
+ Because of the use of 'group', pagination is not supported.
62
+
63
+ ## Contributing
64
+
65
+ 1. Fork it
66
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
67
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
68
+ 4. Push to the branch (`git push origin my-new-feature`)
69
+ 5. Create new Pull Request
data/Rakefile ADDED
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,3 @@
1
+ module MostRelated
2
+ VERSION = "0.0.2"
3
+ end
@@ -0,0 +1,91 @@
1
+ require "most_related/version"
2
+
3
+ module MostRelated
4
+
5
+ # `most_related` returns those models that have the most
6
+ # many to many associated models in common
7
+ #
8
+ # Post example:
9
+ #
10
+ # class Post < ActiveRecord::Base
11
+ # has_most_related :authors
12
+ # has_most_related :tags, as: :most_related_by_tags
13
+ # has_most_related [:authors, :tags], as: :most_related_by_author_or_tag
14
+ #
15
+ # has_many :author_posts
16
+ # has_many :authors, through: :author_posts
17
+ # end
18
+ #
19
+ # class Author < ActiveRecord::Base
20
+ # has_many :author_posts
21
+ # end
22
+ #
23
+ # class AuthorPosts < ActiveRecord::Base
24
+ # belongs_to :author
25
+ # belongs_to :post
26
+ # end
27
+ #
28
+ # To return the posts with the most authors in common with post, in descending order:
29
+ # post.most_related
30
+ #
31
+ # To return the posts with the most tags in common with post, in descending order:
32
+ # post.most_related_by_tag
33
+ #
34
+ # To return the posts with the most authors and tags in common with post, in descending order:
35
+ # post.most_related_by_author_or_tag
36
+ #
37
+ # The count of the many to many associated models in common is accessible on each returned model
38
+ # eg post.most_related_count, post.most_related_by_tag_count and post.most_related_by_author_or_tag
39
+ #
40
+ def has_most_related(many_to_many_associations, as: :most_related)
41
+
42
+ # defaults to 'def most_related'
43
+ define_method as do
44
+ table_name = self.class.table_name
45
+ association_scopes = []
46
+
47
+ many_to_many_associations = if many_to_many_associations.is_a?(Array)
48
+ many_to_many_associations
49
+ else
50
+ [many_to_many_associations]
51
+ end
52
+
53
+ many_to_many_associations.each do |many_to_many_association|
54
+ assocation = self.class.reflect_on_association(many_to_many_association)
55
+ join_table, foreign_key, association_foreign_key = self.class.join_table_values(assocation)
56
+
57
+ association_scopes << self.class.where("#{join_table}.#{association_foreign_key} IN " +
58
+ "(select #{join_table}.#{association_foreign_key} from #{join_table} " +
59
+ "where #{join_table}.#{foreign_key} = :foreign_key)", foreign_key: self.id).
60
+ joins("INNER JOIN #{join_table} ON #{join_table}.#{foreign_key} = #{table_name}.id")
61
+ end
62
+
63
+ scope = self.class.select("#{table_name}.*, count(#{table_name}.id) AS #{as}_count").
64
+ where.not(id: self.id).group("#{table_name}.id").order("#{as}_count DESC")
65
+
66
+ # if there is only one many-to-many association no need to use UNION sql syntax
67
+ if association_scopes.size == 1
68
+ scope.merge(association_scopes.first)
69
+ else
70
+ # see http://blog.ubersense.com/2013/09/27/tech-talk-unioning-scoped-queries-in-rails/
71
+ scope.from("((#{association_scopes.map(&:to_sql).join(') UNION ALL (')})) #{table_name}")
72
+ end
73
+ end
74
+
75
+ def self.join_table_values(many_to_many_assocation)
76
+ if many_to_many_assocation.macro == :has_and_belongs_to_many
77
+ join_table = many_to_many_assocation.join_table
78
+ foreign_key = many_to_many_assocation.foreign_key
79
+ association_foreign_key = many_to_many_assocation.association_foreign_key
80
+ elsif many_to_many_assocation.macro == :has_many
81
+ join_table = many_to_many_assocation.through_reflection.table_name
82
+ foreign_key = many_to_many_assocation.through_reflection.foreign_key
83
+ association_foreign_key = many_to_many_assocation.foreign_key
84
+ end
85
+ [join_table, foreign_key, association_foreign_key]
86
+ end
87
+ end
88
+ end
89
+
90
+ # Extend ActiveRecord functionality
91
+ ActiveRecord::Base.extend MostRelated
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'most_related/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "most_related"
8
+ spec.version = MostRelated::VERSION
9
+ spec.authors = ["Jolyon Pawlyn"]
10
+ spec.email = ["jolyon.pawlyn@unboxedconsulting.com"]
11
+ spec.description = %q{Adds an instance method to a active record model that returns the most related models based on many to many associated models in common}
12
+ spec.summary = %q{Returns models that have the most many to many associated models in common}
13
+ spec.homepage = "https://github.com/jpawlyn/most_related"
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.add_development_dependency "bundler", "~> 1.3"
22
+ spec.add_development_dependency "rspec', '~> 2.14.1"
23
+ spec.add_development_dependency "activerecord", "~> 4.0.0"
24
+ spec.add_development_dependency "sqlite3"
25
+ end
data/spec/post_spec.rb ADDED
@@ -0,0 +1,66 @@
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.most_related.map(&:most_related_count)).to eq([3, 2, 1])
22
+ expect(post.most_related).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.most_related_by_tag.map(&:most_related_by_tag_count)).to eq([3, 2, 1])
35
+ expect(post.most_related_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
+ pending 'Does not work with sqlite - mysql only perhaps?'
48
+ expect(post.most_related_by_author_or_tag.map(&:most_related_by_author_or_tag_count)).to eq([5, 4, 1])
49
+ expect(post.most_related_by_author_or_tag).to eq([post1, post4, post2])
50
+ end
51
+
52
+ it 'sql check' do
53
+ expect(post.most_related_by_author_or_tag.where_clauses).to eq(["(\"posts\".\"id\" != #{post.id})"])
54
+ expect(post.most_related_by_author_or_tag.order_clauses).to eq(["most_related_by_author_or_tag_count DESC"])
55
+ sql = <<-eos
56
+ SELECT posts.*, count(posts.id) AS most_related_by_author_or_tag_count FROM
57
+ ((SELECT \"posts\".* FROM \"posts\" INNER JOIN author_posts ON author_posts.post_id = posts.id WHERE
58
+ (author_posts.author_id IN (select author_posts.author_id from author_posts where author_posts.post_id = #{post.id})))
59
+ UNION ALL (SELECT \"posts\".* FROM \"posts\" INNER JOIN posts_tags ON posts_tags.post_id = posts.id WHERE
60
+ (posts_tags.tag_id IN (select posts_tags.tag_id from posts_tags where posts_tags.post_id = #{post.id})))) posts
61
+ WHERE (\"posts\".\"id\" != #{post.id}) GROUP BY posts.id ORDER BY most_related_by_author_or_tag_count DESC
62
+ eos
63
+ expect(post.most_related_by_author_or_tag.to_sql.squish!).to eq(sql.squish!)
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,28 @@
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
+ ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
10
+ load 'support/schema.rb'
11
+
12
+ require 'most_related'
13
+ require 'support/models'
14
+ require 'support/string'
15
+
16
+
17
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
18
+ RSpec.configure do |config|
19
+ config.treat_symbols_as_metadata_keys_with_true_values = true
20
+ config.run_all_when_everything_filtered = true
21
+ config.filter_run :focus
22
+
23
+ # Run specs in random order to surface order dependencies. If you find an
24
+ # order dependency and want to debug it, you can fix the order by providing
25
+ # the seed, which is printed after each run.
26
+ # --seed 1234
27
+ config.order = 'random'
28
+ end
@@ -0,0 +1,20 @@
1
+ class Post < ActiveRecord::Base
2
+ has_most_related :authors
3
+ has_most_related :tags, as: :most_related_by_tag
4
+ has_most_related [:authors, :tags], as: :most_related_by_author_or_tag
5
+
6
+ has_and_belongs_to_many :tags
7
+ has_many :author_posts
8
+ has_many :authors, through: :author_posts
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
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
12
+ end
13
+
14
+ create_table :posts, force: true do |t|
15
+ t.timestamps
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
@@ -0,0 +1,8 @@
1
+ class String
2
+ def squish!
3
+ gsub!(/\A[[:space:]]+/, '')
4
+ gsub!(/[[:space:]]+\z/, '')
5
+ gsub!(/[[:space:]]+/, ' ')
6
+ self
7
+ end
8
+ end
metadata ADDED
@@ -0,0 +1,121 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: most_related
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.2
5
+ platform: ruby
6
+ authors:
7
+ - Jolyon Pawlyn
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2014-02-09 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ~>
18
+ - !ruby/object:Gem::Version
19
+ version: '1.3'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '1.3'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec', '~> 2.14.1
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - '>='
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: activerecord
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ~>
46
+ - !ruby/object:Gem::Version
47
+ version: 4.0.0
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ~>
53
+ - !ruby/object:Gem::Version
54
+ version: 4.0.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: sqlite3
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - '>='
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - '>='
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ description: Adds an instance method to a active record model that returns the most
70
+ related models based on many to many associated models in common
71
+ email:
72
+ - jolyon.pawlyn@unboxedconsulting.com
73
+ executables: []
74
+ extensions: []
75
+ extra_rdoc_files: []
76
+ files:
77
+ - .gitignore
78
+ - .rspec
79
+ - .ruby-version
80
+ - Gemfile
81
+ - LICENSE.txt
82
+ - README.md
83
+ - Rakefile
84
+ - lib/most_related.rb
85
+ - lib/most_related/version.rb
86
+ - most_related.gemspec
87
+ - spec/post_spec.rb
88
+ - spec/spec_helper.rb
89
+ - spec/support/models.rb
90
+ - spec/support/schema.rb
91
+ - spec/support/string.rb
92
+ homepage: https://github.com/jpawlyn/most_related
93
+ licenses:
94
+ - MIT
95
+ metadata: {}
96
+ post_install_message:
97
+ rdoc_options: []
98
+ require_paths:
99
+ - lib
100
+ required_ruby_version: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - '>='
103
+ - !ruby/object:Gem::Version
104
+ version: '0'
105
+ required_rubygems_version: !ruby/object:Gem::Requirement
106
+ requirements:
107
+ - - '>='
108
+ - !ruby/object:Gem::Version
109
+ version: '0'
110
+ requirements: []
111
+ rubyforge_project:
112
+ rubygems_version: 2.0.3
113
+ signing_key:
114
+ specification_version: 4
115
+ summary: Returns models that have the most many to many associated models in common
116
+ test_files:
117
+ - spec/post_spec.rb
118
+ - spec/spec_helper.rb
119
+ - spec/support/models.rb
120
+ - spec/support/schema.rb
121
+ - spec/support/string.rb