recommender 0.1.0

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.
Files changed (79) hide show
  1. checksums.yaml +7 -0
  2. data/.rspec +3 -0
  3. data/CHANGELOG.md +5 -0
  4. data/CODE_OF_CONDUCT.md +84 -0
  5. data/LICENSE.txt +21 -0
  6. data/README.md +39 -0
  7. data/Rakefile +10 -0
  8. data/lib/recommender/recommendation.rb +79 -0
  9. data/lib/recommender/version.rb +5 -0
  10. data/lib/recommender.rb +10 -0
  11. data/sig/recommender.rbs +4 -0
  12. data/spec/factories/albums.rb +23 -0
  13. data/spec/factories/movie_likes.rb +8 -0
  14. data/spec/factories/movies.rb +7 -0
  15. data/spec/factories/users.rb +27 -0
  16. data/spec/recommender/recommendation_spec.rb +99 -0
  17. data/spec/spec_helper.rb +43 -0
  18. data/spec/test_app/Dockerfile +58 -0
  19. data/spec/test_app/Gemfile +41 -0
  20. data/spec/test_app/Gemfile.lock +240 -0
  21. data/spec/test_app/Rakefile +6 -0
  22. data/spec/test_app/app/assets/config/manifest.js +2 -0
  23. data/spec/test_app/app/assets/stylesheets/application.css +15 -0
  24. data/spec/test_app/app/controllers/application_controller.rb +2 -0
  25. data/spec/test_app/app/helpers/application_helper.rb +2 -0
  26. data/spec/test_app/app/jobs/application_job.rb +7 -0
  27. data/spec/test_app/app/models/album.rb +8 -0
  28. data/spec/test_app/app/models/application_record.rb +3 -0
  29. data/spec/test_app/app/models/movie.rb +7 -0
  30. data/spec/test_app/app/models/movie_like.rb +4 -0
  31. data/spec/test_app/app/models/user.rb +10 -0
  32. data/spec/test_app/app/views/layouts/application.html.erb +15 -0
  33. data/spec/test_app/bin/bundle +109 -0
  34. data/spec/test_app/bin/docker-entrypoint +8 -0
  35. data/spec/test_app/bin/rails +4 -0
  36. data/spec/test_app/bin/rake +4 -0
  37. data/spec/test_app/bin/setup +33 -0
  38. data/spec/test_app/config/application.rb +42 -0
  39. data/spec/test_app/config/boot.rb +3 -0
  40. data/spec/test_app/config/credentials.yml.enc +1 -0
  41. data/spec/test_app/config/database.yml +84 -0
  42. data/spec/test_app/config/environment.rb +5 -0
  43. data/spec/test_app/config/environments/development.rb +65 -0
  44. data/spec/test_app/config/environments/production.rb +83 -0
  45. data/spec/test_app/config/environments/test.rb +54 -0
  46. data/spec/test_app/config/initializers/assets.rb +12 -0
  47. data/spec/test_app/config/initializers/content_security_policy.rb +25 -0
  48. data/spec/test_app/config/initializers/filter_parameter_logging.rb +8 -0
  49. data/spec/test_app/config/initializers/inflections.rb +16 -0
  50. data/spec/test_app/config/initializers/permissions_policy.rb +13 -0
  51. data/spec/test_app/config/locales/en.yml +31 -0
  52. data/spec/test_app/config/master.key +1 -0
  53. data/spec/test_app/config/puma.rb +35 -0
  54. data/spec/test_app/config/routes.rb +10 -0
  55. data/spec/test_app/config.ru +6 -0
  56. data/spec/test_app/db/migrate/20240619132144_create_users.rb +9 -0
  57. data/spec/test_app/db/migrate/20240619132155_create_movies.rb +9 -0
  58. data/spec/test_app/db/migrate/20240619190825_create_movie_likes.rb +10 -0
  59. data/spec/test_app/db/migrate/20240620062947_add_unique_index_to_movies.rb +5 -0
  60. data/spec/test_app/db/migrate/20240620063520_change_name_column_null_on_movies.rb +5 -0
  61. data/spec/test_app/db/migrate/20240620063651_change_name_column_null_on_users.rb +5 -0
  62. data/spec/test_app/db/migrate/20240620063952_add_unique_index_to_users.rb +5 -0
  63. data/spec/test_app/db/migrate/20240621102016_create_albums.rb +10 -0
  64. data/spec/test_app/db/migrate/20240621102359_create_join_table_album_user.rb +8 -0
  65. data/spec/test_app/db/migrate/20240621102813_change_column_null_on_albums.rb +5 -0
  66. data/spec/test_app/db/schema.rb +56 -0
  67. data/spec/test_app/db/seeds.rb +9 -0
  68. data/spec/test_app/log/development.log +23616 -0
  69. data/spec/test_app/log/test.log +0 -0
  70. data/spec/test_app/public/404.html +67 -0
  71. data/spec/test_app/public/422.html +67 -0
  72. data/spec/test_app/public/500.html +66 -0
  73. data/spec/test_app/public/apple-touch-icon-precomposed.png +0 -0
  74. data/spec/test_app/public/apple-touch-icon.png +0 -0
  75. data/spec/test_app/public/favicon.ico +0 -0
  76. data/spec/test_app/public/robots.txt +1 -0
  77. data/spec/test_app/tmp/local_secret.txt +1 -0
  78. data/spec/test_app/tmp/restart.txt +0 -0
  79. metadata +304 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 755889264ba0de9061b5c58e1eb8692f181338f08c2a770bed34ca74693e7142
4
+ data.tar.gz: 8968a8eeca32885854a5fc082d739377874edc3e1b826486e2cbc21560253e3f
5
+ SHA512:
6
+ metadata.gz: c9378374d88fc1b4e6d7ba84e3bd3a0fa6fe80a5f3c2e5e9d588f33c6254e04213d8880f9481c3e7dbed17bc265552a7b45c97a1d3fdb911e687f060f37b6d00
7
+ data.tar.gz: 8f1596d387176345185dd693399b3817279343e30ad03e6b73b42e0a8b0105caf91b9330f767384aa3aa98fa8578f80dea871499b961f184185acd9fe59bef3c
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-06-18
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at danielmutubait@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Mutuba
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,39 @@
1
+ # Recommender
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/recommender`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install UPDATE_WITH_YOUR_GEM_NAME_PRIOR_TO_RELEASE_TO_RUBYGEMS_ORG
18
+
19
+ ## Usage
20
+
21
+ TODO: Write usage instructions here
22
+
23
+ ## Development
24
+
25
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
26
+
27
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
28
+
29
+ ## Contributing
30
+
31
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/recommender. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/recommender/blob/main/CODE_OF_CONDUCT.md).
32
+
33
+ ## License
34
+
35
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
36
+
37
+ ## Code of Conduct
38
+
39
+ Everyone interacting in the Recommender project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/recommender/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec) do |task|
7
+ task.rspec_opts = ['--color', '--format', 'nested']
8
+ end
9
+
10
+ task default: :spec
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/concern"
4
+
5
+ module Recommender
6
+ module Recommendation
7
+ extend ActiveSupport::Concern
8
+
9
+ included do
10
+ extend ClassMethods
11
+ end
12
+
13
+ AssociationMetadata = Struct.new(:join_table, :foreign_key, :association_foreign_key, :reflection_name)
14
+
15
+ module ClassMethods
16
+ attr_accessor :association_metadata
17
+
18
+ def set_association(association_name)
19
+ reflection = reflect_on_association(association_name.to_sym)
20
+ raise ArgumentError, "Association '#{association_name}' not found" unless reflection
21
+
22
+ self.association_metadata = build_association_metadata(reflection)
23
+ end
24
+
25
+ private
26
+
27
+ def build_association_metadata(reflection)
28
+ case reflection
29
+ when ActiveRecord::Reflection::HasAndBelongsToManyReflection
30
+ AssociationMetadata.new(
31
+ reflection.join_table,
32
+ reflection.foreign_key,
33
+ reflection.association_foreign_key,
34
+ reflection.name
35
+ )
36
+ when ActiveRecord::Reflection::ThroughReflection
37
+ AssociationMetadata.new(
38
+ reflection.through_reflection.table_name,
39
+ reflection.through_reflection.foreign_key,
40
+ reflection.association_foreign_key,
41
+ reflection.name
42
+ )
43
+ when ActiveRecord::Reflection::HasManyReflection
44
+ AssociationMetadata.new(
45
+ reflection.klass.table_name, # reflection.name.to_s.pluralize,
46
+ reflection.foreign_key,
47
+ reflection.foreign_key,
48
+ reflection.name
49
+ )
50
+ else
51
+ raise ArgumentError, "Association '#{reflection.name}' is not a supported type"
52
+ end
53
+ end
54
+ end
55
+
56
+ def recommendations(results: 5)
57
+ other_instances = self.class.where.not(id: id)
58
+ self_items = send(self.class.association_metadata.reflection_name).pluck(:id).to_set
59
+
60
+ item_recommendations = other_instances.reduce(Hash.new(0)) do |acc, instance|
61
+ instance_items = instance.send(self.class.association_metadata.reflection_name).pluck(:id).to_set
62
+ common_items = instance_items & self_items
63
+ jaccard_index = common_items.size.to_f / (instance_items | self_items).size
64
+ dice_sorensen_coefficient = (2.0 * common_items.size) / (instance_items.size + self_items.size)
65
+ collaborative_weight = common_items.size.to_f / Math.sqrt(instance_items.size * self_items.size)
66
+ weight = (jaccard_index + dice_sorensen_coefficient + collaborative_weight) / 3.0
67
+ (instance_items - common_items).each do |item_id|
68
+ # Exclude items that are already liked by the user
69
+ acc[item_id] += weight unless self_items.include?(item_id)
70
+ end
71
+ acc
72
+ end
73
+
74
+ sorted_recommendation_ids = item_recommendations.keys.sort_by { |id| item_recommendations[id] }.reverse.take(results)
75
+ association_table = self.class.reflect_on_association(self.class.association_metadata.reflection_name).klass
76
+ sorted_recommendation_ids.map { |id| [association_table.find(id), item_recommendations[id]] }
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Recommender
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ # recommender/lib/recommender.rb
4
+ require_relative "recommender/version"
5
+ require 'recommender/recommendation'
6
+
7
+ module Recommender
8
+ class Error < StandardError; end
9
+
10
+ end
@@ -0,0 +1,4 @@
1
+ module Recommender
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ FactoryBot.define do
4
+ factory :album do
5
+ name { Faker::Music.album }
6
+ trait :with_default_names do
7
+ album_names = [
8
+ "The Very Best of Kool & The Gang",
9
+ "Born in the Wild",
10
+ "Where the Butterflies Go in the Rain",
11
+ "All the Best: The Hits",
12
+ "On the Radio: Greatest Hits, Vol. I & II",
13
+ "Confessions (Expanded Edition)",
14
+ "The Best Of Bill Withers: Lean On Me",
15
+ "The Ultimate Collection (Remastered)"
16
+ ]
17
+
18
+ album_names.each do |album_name|
19
+ Album.find_or_create_by(name: album_name)
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ FactoryBot.define do
4
+ factory :movie_like do
5
+ association :user
6
+ association :movie
7
+ end
8
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ FactoryBot.define do
4
+ factory :movie do
5
+ name { Faker::Movie.title }
6
+ end
7
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ FactoryBot.define do
4
+ factory :user do
5
+ name { Faker::TvShows::GameOfThrones.character }
6
+
7
+ trait :with_movie_likes do
8
+ after(:create) do |user|
9
+ movies = [
10
+ "Avengers: Infinity War",
11
+ "Star Wars: The Force Awakens",
12
+ "Marvel’s The Avengers",
13
+ "Star Wars: The Last Jedi",
14
+ "The Dark Knight",
15
+ "Beauty and the Beast",
16
+ "Finding Dory",
17
+ "Pirates of the Caribbean: Dead Man’s Chest"
18
+ ]
19
+
20
+ movies.each do |movie_name|
21
+ movie = Movie.find_or_create_by(name: movie_name)
22
+ user.movie_likes.create(movie: movie)
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+ # spec/recommender/recommendation_spec.rb
3
+
4
+ require_relative "../spec_helper"
5
+
6
+ RSpec.describe Recommender::Recommendation, type: :module do
7
+ describe "#recommendations ThroughReflection" do
8
+ let(:first_user_with_movies) { create(:user, :with_movie_likes) }
9
+ let(:second_user_with_movies) { create(:user, :with_movie_likes) }
10
+ let(:third_user_with_movies) { create(:user, :with_movie_likes) }
11
+ let(:first_movie) { create(:movie, name: "Stranger Things") }
12
+ let(:second_movie) { create(:movie, name: "3 Body Problem") }
13
+
14
+ it "has a version number" do
15
+ expect(Recommender::VERSION).not_to be nil
16
+ end
17
+ it "returns recommended movies based on similarity measures" do
18
+ first_user_with_movies.movies << first_movie
19
+ first_user_with_movies.movies << second_movie
20
+ recommendations = second_user_with_movies.recommendations
21
+ recommended_movies = recommendations.map { |recommendation| recommendation.first }
22
+ expect(recommended_movies).to include(first_movie)
23
+ expect(recommended_movies).to include(second_movie)
24
+ end
25
+
26
+ it "returns no recommendations if there are no similar users" do
27
+ third_user = create(:user)
28
+ expect(third_user.recommendations).to be_empty
29
+ end
30
+
31
+ it "returns no recommendations if the user has no liked movies" do
32
+ new_user = create(:user)
33
+ expect(new_user.recommendations).to be_empty
34
+ end
35
+
36
+ it "does not include duplicate movies in recommendations" do
37
+ first_user_with_movies.movies << first_movie
38
+ first_user_with_movies.movies << second_movie
39
+ recommendations = second_user_with_movies.recommendations
40
+ recommended_movie_ids = recommendations.map { |recommendation| recommendation.first.id }
41
+ expect(recommended_movie_ids.uniq.size).to eq(recommended_movie_ids.size)
42
+ end
43
+
44
+ it "respects the maximum number of recommendations limit" do
45
+ first_user_with_movies.movies << first_movie
46
+ first_user_with_movies.movies << second_movie
47
+ recommendations = second_user_with_movies.recommendations(results: 1)
48
+ expect(recommendations.size).to eq(1)
49
+ end
50
+
51
+ it "distributes similarity scores correctly" do
52
+ first_user_with_movies.movies << first_movie
53
+ first_user_with_movies.movies << second_movie
54
+ third_user_with_movies.movies << second_movie
55
+ recommendations = second_user_with_movies.recommendations()
56
+ expect(recommendations.size).to eq(2)
57
+ # Extract the ratings from the recommendations
58
+ recommended_movie_ratings = recommendations.map { |_, rating| [ rating] }.flatten
59
+ # Ensure the ratings are not the same
60
+ expect(recommended_movie_ratings[1]).not_to eq(recommended_movie_ratings[0])
61
+ expect(recommended_movie_ratings[0] > recommended_movie_ratings[1]).to be(true)
62
+ # Check that the second_movie appears first in the rating list
63
+ expect(recommendations[0][0]).to eq(second_movie)
64
+ end
65
+
66
+ it "handles edge cases gracefully" do
67
+ single_user = create(:user, :with_movie_likes)
68
+ expect(single_user.recommendations).to be_empty
69
+
70
+ empty_system = User.destroy_all
71
+ new_user = create(:user)
72
+ expect(new_user.recommendations).to be_empty
73
+ end
74
+ end
75
+
76
+ describe "#recommendations HasAndBelongsToManyReflection" do
77
+ let!(:first_user) { create(:user) }
78
+ let!(:second_user) { create(:user) }
79
+ let(:first_album) { create(:album, :with_default_names) }
80
+ let(:second_album) { create(:album, :with_default_names) }
81
+ let(:third_album) { create(:album, :with_default_names) }
82
+ let(:latest_album) { create(:album, name: "CRASH") }
83
+ let(:trending_album) { create(:album, name: "Gold: Lionel Richie / Commodores") }
84
+
85
+ before do
86
+ first_user.albums << first_album
87
+ first_user.albums << second_album
88
+ first_user.albums << trending_album
89
+ second_user.albums << first_album
90
+ second_user.albums << second_album
91
+ end
92
+
93
+ it "returns recommended albums based on similarity measures" do
94
+ recommendations = trending_album.recommendations
95
+ album_user_recommendations = recommendations.map { |recommendation| recommendation.first }
96
+ expect(album_user_recommendations).to include(second_user)
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "recommender"
4
+ require 'factory_bot_rails'
5
+ require "faker"
6
+ require 'database_cleaner/active_record'
7
+ ENV['RAILS_ENV'] ||= 'test'
8
+ require File.expand_path('../test_app/config/environment.rb', __FILE__)
9
+
10
+ factories_path = File.expand_path("../spec/factories/**/*.rb", __dir__)
11
+ Dir[factories_path].sort.each { |file| require file }
12
+ Dir[Rails.root.join('spec', '**', '*.rb')].sort.each { |file| require file }
13
+
14
+ RSpec.configure do |config|
15
+ config.example_status_persistence_file_path = ".rspec_status"
16
+
17
+ config.include FactoryBot::Syntax::Methods
18
+
19
+ config.before(:suite) do
20
+ FactoryBot.find_definitions
21
+ end
22
+
23
+ # Disable RSpec exposing methods globally on `Module` and `main`
24
+ config.disable_monkey_patching!
25
+
26
+ config.expect_with :rspec do |c|
27
+ c.syntax = :expect
28
+ end
29
+
30
+ config.before(:suite) do
31
+ FactoryBot.find_definitions
32
+ end
33
+
34
+ config.before(:each) do
35
+ # Ensure a clean state for each test
36
+ DatabaseCleaner.strategy = :transaction
37
+ DatabaseCleaner.start
38
+ end
39
+
40
+ config.after(:each) do
41
+ DatabaseCleaner.clean
42
+ end
43
+ end
@@ -0,0 +1,58 @@
1
+ # syntax = docker/dockerfile:1
2
+
3
+ # Make sure RUBY_VERSION matches the Ruby version in .ruby-version and Gemfile
4
+ ARG RUBY_VERSION=3.2.2
5
+ FROM registry.docker.com/library/ruby:$RUBY_VERSION-slim as base
6
+
7
+ # Rails app lives here
8
+ WORKDIR /rails
9
+
10
+ # Set production environment
11
+ ENV RAILS_ENV="production" \
12
+ BUNDLE_DEPLOYMENT="1" \
13
+ BUNDLE_PATH="/usr/local/bundle" \
14
+ BUNDLE_WITHOUT="development"
15
+
16
+
17
+ # Throw-away build stage to reduce size of final image
18
+ FROM base as build
19
+
20
+ # Install packages needed to build gems
21
+ RUN apt-get update -qq && \
22
+ apt-get install --no-install-recommends -y build-essential git libpq-dev pkg-config
23
+
24
+ # Install application gems
25
+ COPY Gemfile Gemfile.lock ./
26
+ RUN bundle install && \
27
+ rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git
28
+
29
+ # Copy application code
30
+ COPY . .
31
+
32
+ # Precompiling assets for production without requiring secret RAILS_MASTER_KEY
33
+ RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile
34
+
35
+
36
+ # Final stage for app image
37
+ FROM base
38
+
39
+ # Install packages needed for deployment
40
+ RUN apt-get update -qq && \
41
+ apt-get install --no-install-recommends -y curl postgresql-client && \
42
+ rm -rf /var/lib/apt/lists /var/cache/apt/archives
43
+
44
+ # Copy built artifacts: gems, application
45
+ COPY --from=build /usr/local/bundle /usr/local/bundle
46
+ COPY --from=build /rails /rails
47
+
48
+ # Run and own only the runtime files as a non-root user for security
49
+ RUN useradd rails --create-home --shell /bin/bash && \
50
+ chown -R rails:rails db log tmp
51
+ USER rails:rails
52
+
53
+ # Entrypoint prepares the database.
54
+ ENTRYPOINT ["/rails/bin/docker-entrypoint"]
55
+
56
+ # Start the server by default, this can be overwritten at runtime
57
+ EXPOSE 3000
58
+ CMD ["./bin/rails", "server"]
@@ -0,0 +1,41 @@
1
+ source "https://rubygems.org"
2
+
3
+ ruby "3.2.2"
4
+
5
+ # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
6
+ gem "rails", "~> 7.1.3", ">= 7.1.3.4"
7
+
8
+ # The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
9
+ gem "sprockets-rails"
10
+
11
+ # Use postgresql as the database for Active Record
12
+ gem "pg", "~> 1.1"
13
+
14
+ # Use the Puma web server [https://github.com/puma/puma]
15
+ gem "puma", ">= 5.0"
16
+
17
+ # Use Kredis to get higher-level data types in Redis [https://github.com/rails/kredis]
18
+ # gem "kredis"
19
+
20
+ # Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword]
21
+ # gem "bcrypt", "~> 3.1.7"
22
+ gem 'recommender', path: '../../../recommender'
23
+ # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
24
+ gem "tzinfo-data", platforms: %i[ windows jruby ]
25
+
26
+ group :development, :test do
27
+ # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem
28
+ gem "debug", platforms: %i[ mri windows ]
29
+ end
30
+
31
+ group :development do
32
+ # Use console on exceptions pages [https://github.com/rails/web-console]
33
+ gem "web-console"
34
+
35
+ # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
36
+ # gem "rack-mini-profiler"
37
+
38
+ # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
39
+ # gem "spring"
40
+ end
41
+