Repository: excid3/refer Branch: main Commit: 734e75777b9b Files: 107 Total size: 66.9 KB Directory structure: gitextract_iiyk70lc/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── config.yml │ │ └── issue_template.md │ ├── dependabot.yml │ ├── pull_request_template.md │ └── workflows/ │ └── ci.yml ├── .gitignore ├── .rubocop.yml ├── .ruby-version ├── Appraisals ├── CHANGELOG.md ├── Gemfile ├── MIT-LICENSE ├── README.md ├── Rakefile ├── app/ │ ├── controllers/ │ │ ├── .keep │ │ └── concerns/ │ │ └── .keep │ └── models/ │ ├── .keep │ └── refer/ │ ├── application_record.rb │ ├── referral.rb │ ├── referral_code.rb │ └── visit.rb ├── bin/ │ ├── rails │ └── rubocop ├── config/ │ └── routes.rb ├── db/ │ └── migrate/ │ ├── 20240611180738_create_refer_referrals.rb │ ├── 20240611183349_create_refer_referral_codes.rb │ └── 20240701172643_create_refer_visits.rb ├── gemfiles/ │ ├── rails_7.1.gemfile │ ├── rails_7.2.gemfile │ ├── rails_8.0.gemfile │ ├── rails_8.1.gemfile │ └── rails_main.gemfile ├── lib/ │ ├── generators/ │ │ └── refer/ │ │ ├── install/ │ │ │ ├── USAGE │ │ │ └── install_generator.rb │ │ └── model/ │ │ ├── USAGE │ │ └── model_generator.rb │ ├── refer/ │ │ ├── controller.rb │ │ ├── engine.rb │ │ ├── has_referrals.rb │ │ ├── model.rb │ │ └── version.rb │ ├── refer.rb │ └── tasks/ │ └── refer_tasks.rake ├── refer.gemspec └── test/ ├── dummy/ │ ├── Rakefile │ ├── app/ │ │ ├── assets/ │ │ │ ├── config/ │ │ │ │ └── manifest.js │ │ │ ├── images/ │ │ │ │ └── .keep │ │ │ └── stylesheets/ │ │ │ └── application.css │ │ ├── channels/ │ │ │ └── application_cable/ │ │ │ ├── channel.rb │ │ │ └── connection.rb │ │ ├── controllers/ │ │ │ ├── application_controller.rb │ │ │ ├── concerns/ │ │ │ │ └── .keep │ │ │ └── referrals_controller.rb │ │ ├── helpers/ │ │ │ └── application_helper.rb │ │ ├── jobs/ │ │ │ └── application_job.rb │ │ ├── mailers/ │ │ │ └── application_mailer.rb │ │ ├── models/ │ │ │ ├── application_record.rb │ │ │ ├── concerns/ │ │ │ │ └── .keep │ │ │ └── user.rb │ │ └── views/ │ │ ├── layouts/ │ │ │ ├── application.html.erb │ │ │ ├── mailer.html.erb │ │ │ └── mailer.text.erb │ │ └── pwa/ │ │ ├── manifest.json.erb │ │ └── service-worker.js │ ├── bin/ │ │ ├── rails │ │ ├── rake │ │ └── setup │ ├── config/ │ │ ├── application.rb │ │ ├── boot.rb │ │ ├── cable.yml │ │ ├── database.yml │ │ ├── environment.rb │ │ ├── environments/ │ │ │ ├── development.rb │ │ │ ├── production.rb │ │ │ └── test.rb │ │ ├── initializers/ │ │ │ ├── assets.rb │ │ │ ├── content_security_policy.rb │ │ │ ├── filter_parameter_logging.rb │ │ │ ├── inflections.rb │ │ │ └── permissions_policy.rb │ │ ├── locales/ │ │ │ └── en.yml │ │ ├── puma.rb │ │ ├── routes.rb │ │ └── storage.yml │ ├── config.ru │ ├── db/ │ │ ├── migrate/ │ │ │ └── 20240611180748_create_users.rb │ │ └── schema.rb │ ├── lib/ │ │ └── assets/ │ │ └── .keep │ ├── log/ │ │ └── .keep │ └── public/ │ ├── 404.html │ ├── 406-unsupported-browser.html │ ├── 422.html │ └── 500.html ├── fixtures/ │ ├── files/ │ │ └── .keep │ ├── refer/ │ │ ├── referral_codes.yml │ │ ├── referrals.yml │ │ └── visits.yml │ └── users.yml ├── integration/ │ ├── .keep │ └── referral_test.rb ├── models/ │ ├── .keep │ └── refer/ │ ├── referral_code_test.rb │ ├── referral_test.rb │ └── visit_test.rb ├── refer_test.rb └── test_helper.rb ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: [excid3] # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: Get Help url: https://github.com/excid3/refer/discussions/new?category=help about: If you can't get something to work the way you expect, open a question in our discussion forums. - name: Feature Request url: https://github.com/excid3/refer/discussions/new?category=ideas about: 'Suggest any ideas you have using our discussion forums.' - name: Bug Report url: https://github.com/excid3/refer/issues/new?body=%3C%21--%20Please%20provide%20all%20of%20the%20information%20requested%20below.%20We%27re%20a%20small%20team%20and%20without%20all%20of%20this%20information%20it%27s%20not%20possible%20for%20us%20to%20help%20and%20your%20bug%20report%20will%20be%20closed.%20--%3E%0A%0A%2A%2AWhat%20version%20of%20Noticed%20are%20you%20using%3F%2A%2A%0A%0AFor%20example%3A%20v2.0.4%0A%0A%2A%2AWhat%20version%20of%20Rails%20are%20you%20using%3F%2A%2A%0A%0AFor%20example%3A%20v7.1.1%0A%0A%2A%2ADescribe%20your%20issue%2A%2A%0A%0ADescribe%20the%20problem%20you%27re%20seeing%2C%20any%20important%20steps%20to%20reproduce%20and%20what%20behavior%20you%20expect%20instead. about: If you've already asked for help with a problem and confirmed something is broken with Noticed itself, create a bug report. ================================================ FILE: .github/ISSUE_TEMPLATE/issue_template.md ================================================ --- name: 🐞 Bug about: File a bug/issue title: '[BUG] ' labels: Bug, Needs Triage assignees: '' --- ## Bug Report **Describe the Bug:** <!-- A clear and concise description of the bug --> **To Reproduce:** <!-- Steps to reproduce the behavior --> 1. Step 1 2. Step 2 3. ... **Expected Behavior:** <!-- A clear and concise description of what you expected to happen --> **Actual Behavior:** <!-- A clear and concise description of what actually happened --> **Screenshots (if applicable):** <!-- If applicable, add screenshots to help explain your problem --> **Environment:** - Gem version: <!-- Specify the version of the Noticed gem where the bug occurred --> - Ruby version: <!-- Specify the version of Ruby you are using --> - Rails version: <!-- Specify the version of Rails you are using --> - Operating System: <!-- Specify your operating system --> **Additional Context:** <!-- Add any other context about the problem here --> **Possible Fix:** <!-- If you have suggestions on how to fix the bug, you can provide them here --> **Steps to Reproduce with Fix (if available):** <!-- If you have a fix, outline the steps to reproduce the bug using your fix --> **Related Issues:** <!-- If applicable, reference any related GitHub issues or pull requests --> **Labels to Apply:** <!-- Suggest labels that should be applied to this issue --> **Checklist:** <!-- Make sure all of these items are completed before submitting the issue --> - [ ] I have searched for similar issues and couldn't find any - [ ] I have checked the documentation for relevant information - [ ] I have included all the required information ================================================ FILE: .github/dependabot.yml ================================================ version: 2 updates: - package-ecosystem: bundler directory: "/" schedule: interval: daily open-pull-requests-limit: 10 - package-ecosystem: github-actions directory: "/" schedule: interval: daily open-pull-requests-limit: 10 ================================================ FILE: .github/pull_request_template.md ================================================ ## Pull Request **Summary:** <!-- Provide a brief summary of the changes in this pull request --> **Related Issue:** <!-- If applicable, reference the GitHub issue that this pull request resolves --> **Description:** <!-- Elaborate on the changes made in this pull request. What motivated these changes? --> **Testing:** <!-- Describe the steps you've taken to test the changes. Include relevant information for other contributors to verify the modifications --> **Screenshots (if applicable):** <!-- Include any relevant screenshots or GIFs that demonstrate the changes --> **Checklist:** <!-- Make sure all of these items are completed before submitting the pull request --> - [ ] Code follows the project's coding standards - [ ] Tests have been added or updated to cover the changes - [ ] Documentation has been updated (if applicable) - [ ] All existing tests pass - [ ] Conforms to the contributing guidelines **Additional Notes:** <!-- Any additional information or notes for the reviewers --> ================================================ FILE: .github/workflows/ci.yml ================================================ name: CI on: pull_request: push: branches: [ main ] jobs: lint: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: .ruby-version bundler-cache: true - name: Lint code for consistent style run: bin/rubocop -f github test: runs-on: ubuntu-latest strategy: matrix: gemfile: - rails_7.1 - rails_7.2 - rails_8.0 - rails_8.1 - rails_main steps: - name: Install packages run: sudo apt-get update && sudo apt-get install --no-install-recommends -y google-chrome-stable curl libjemalloc2 libsqlite3-0 libvips libsqlite3-0 - name: Checkout code uses: actions/checkout@v6 - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: .ruby-version bundler-cache: true - name: Run tests env: RAILS_ENV: test # REDIS_URL: redis://localhost:6379/0 run: bin/rails db:test:prepare && bin/rails test - name: Keep screenshots from failed system tests uses: actions/upload-artifact@v6 if: failure() with: name: screenshots path: ${{ github.workspace }}/tmp/screenshots if-no-files-found: ignore ================================================ FILE: .gitignore ================================================ /.bundle/ /doc/ /log/*.log /pkg/ /tmp/ /test/dummy/db/*.sqlite3 /test/dummy/db/*.sqlite3-* /test/dummy/log/*.log /test/dummy/storage/ /test/dummy/tmp/ ================================================ FILE: .rubocop.yml ================================================ # Omakase Ruby styling for Rails inherit_gem: { rubocop-rails-omakase: rubocop.yml } # Overwrite or add rules to create your own house style # # # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` # Layout/SpaceInsideArrayLiteralBrackets: # Enabled: false ================================================ FILE: .ruby-version ================================================ 3.4.5 ================================================ FILE: Appraisals ================================================ appraise "rails-7.1" do gem "rails", "~> 7.1.0" end appraise "rails-7.2" do gem "rails", "~> 7.2.0" end appraise "rails-8.0" do gem "rails", "~> 8.0.0" end appraise "rails-8.1" do gem "rails", "~> 8.1.0.beta1" end appraise "rails-main" do gem "rails", github: "rails/rails" end ================================================ FILE: CHANGELOG.md ================================================ ### Unreleased ### 1.0.4 * Remove deprecated `ActiveSupport::Configurable` and replace with mattr_accessor for global config options ### 1.0.3 * Add lazy load hooks for models #59 ### 1.0.2 * Ensure self-referrals aren't allowed #47 ### 1.0.1 * Use `as:` for polymorphic associations * Add tests against Rails 7.1, 7.2, 8.0 and Rails main ### 1.0.0 * Require Rails 7.1+ for `normalizes` support ### 0.5.3 * Only set ReferralCode#code if it is blank #20 ### 0.5.2 * Move controller constant to lib ### 0.5.1 * Fixes HasReferrals constant lookup ### 0.5.0 * Add `Refer.referral_completed = ->(referral) { }` callback that runs when a referral is marked as completed * `referral.complete!` does nothing if already completed ### 0.4.0 * Add `completed` scope to `Refer::Referral` ### 0.3.0 * Add visit tracking #5 * Configurable referral cookie overwrites #4 Choose between the original referral code or the most recent referral code to receive the referral * Fix referral code default generator ### 0.2.1 * Change migrations to use Rails 6.1 version for compatibility ### 0.2.0 * Add `set_referral_cookie` controller method * Add `rails g refer:install` generator to inject `set_referral_cookie` ### 0.1.1 * Added `dependent: :nullify` so ReferralCodes persist Referral records when deleted. * Added `dependent: :destroy` so Referrals and ReferralCodes are deleted when users are deleted. * Fixed missing `referral_codes` association on users ### 0.1.0 * Initial release ================================================ FILE: Gemfile ================================================ source "https://rubygems.org" # Specify your gem's dependencies in refer.gemspec. gemspec gem "puma" gem "sqlite3" gem "sprockets-rails" # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] gem "rubocop-rails-omakase", require: false # Start debugger with binding.b [https://github.com/ruby/debug] # gem "debug", ">= 1.0.0" gem "appraisal" ================================================ FILE: MIT-LICENSE ================================================ Copyright Chris Oliver Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Refer Referral codes and affiliate links for Ruby on Rails applications. ## 📦 Installation Add this line to your application's Gemfile: ```ruby gem "refer" ``` And then execute: ```bash $ bundle ``` Add Refer to your controllers to store referral cookies: ```bash bin/rails generate refer:install ``` And add Refer to your model: ```bash bin/rails generate refer:model User bin/rails db:migrate ``` ## 🧑‍💻 Usage Refer adds a model to your Rails application for tracking referrals and referral codes. To track referrals, you'll need to 1. Create a referral code 2. Set a cookie with the referral code 3. Create the referral 4. (Optional) Provide a reward for successful referral ##### Create a referral code You can create referral codes through the association: ```ruby user.referral_codes.create #=> randomly generated code user.referral_codes.create(code: "chris") ``` To customize the referral code generator: ```ruby Refer.code_generator = ->(referrer) { [referrer.id, SecureRandom.alphanumeric(8)].join("-") } #=> generates codes like "1-7frb5fUw" ``` By default, Refer will generate 8 character alphanumeric codes. ##### Set a referral cookie To track users, we need to stash the referral code in a cookie when present. By default, Refer will look for `?ref=code` and save this in a cookie. ```ruby class ApplicationController < ActionController::Base set_referral_cookie end ``` Move `set_referral_cookie` to specific controllers if you'd only like cookies set in certain areas like marketing pages for example. ```ruby class MarketingController < ActionController::Base set_referral_cookie except: [:about_us] end ``` You can customize the param name with: ```ruby Refer.param_name = :ref ``` You can customize the cookie name with: ```ruby Refer.cookie_name = :refer_code ``` ##### Refer a user: To create a referral, you can run the following ```ruby class RegistrationsController < ApplicationController def create @user = User.new(user_params) if @user.save refer @user #=> Looks up cookie and attempts referral redirect_to root_path else render :new, status: :unprocessable_entity end end end ``` You can also do this manually: ```ruby Refer.refer(code: "referral_code", referee: user) ``` Refer will make sure the user has not already been referred and create a Referral. ##### Check if a user was referred already: ```ruby Refer.referred?(user) #=> true/false ``` ##### Accessing Referrals To access a user's referrals, you can use the `referrals` association: ```ruby user.referrals #=> [Refer::Referral, Refer::Referral] ``` This returns a list of `Refer::Referral` objects. ##### Accessing Referral To access a user's referral, you can use the `referral` association: ```ruby user.referral #=> Refer::Referral ``` To access a user's referrer, you can use `referrer`: ```ruby user.referrer #=> User that referred this User ``` ## Refer with Devise To use Refer with Devise, you'll need to customize the Devise controller to track the referral after a successful registration. We can do this by telling Devise to use a custom controller in the routes and hooking into the `create` action to track the referral. ```ruby # config/routes.rb devise_for :users, controllers: { registrations: "users/registrations" } ``` ```ruby # app/controllers/users/registrations_controller.rb class Users::RegistrationsController < Devise::RegistrationsController def create super do refer resource if resource.persisted? end end end ``` ## Providing Referral Rewards There are several common ways of handling rewards for successful referrals: * Immediate rewards When the referral is successfully created, you can immediately credit the referrer with their reward. * Reward after user actions You can check if a user was referred after they complete the action and provide a reward to the referrer. * Time-based rewards To provide a reward X days after a successful referral, you can use a schedule job to check for referrals X days ago and provide rewards to those referrers. We recommend keeping records for each reward given to a referral so you can limit rewards. ## Customizing Models You can add features to Refer's models by using lazy load hooks. ```ruby # config/initializers/refer.rb ActiveSupport.on_load :refer_referral do # Add features to Refer::Referral model end ActiveSupport.on_load :refer_referral_code do # Add features to Refer::ReferralCode model end ActiveSupport.on_load :refer_visit do # Add features to Refer::Visit model end ``` ## 🙏 Contributing If you have an issue you'd like to submit, please do so using the issue tracker in GitHub. In order for us to help you in the best way possible, please be as detailed as you can. ## 📝 License The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). ================================================ FILE: Rakefile ================================================ require "bundler/setup" APP_RAKEFILE = File.expand_path("test/dummy/Rakefile", __dir__) load "rails/tasks/engine.rake" require "bundler/gem_tasks" ================================================ FILE: app/controllers/.keep ================================================ ================================================ FILE: app/controllers/concerns/.keep ================================================ ================================================ FILE: app/models/.keep ================================================ ================================================ FILE: app/models/refer/application_record.rb ================================================ module Refer class ApplicationRecord < ActiveRecord::Base self.abstract_class = true self.table_name_prefix = "refer_" end end ================================================ FILE: app/models/refer/referral.rb ================================================ module Refer class Referral < ApplicationRecord belongs_to :referrer, polymorphic: true belongs_to :referee, polymorphic: true belongs_to :referral_code, optional: true, counter_cache: true scope :completed, -> { where.not(completed_at: nil) } before_validation do self.referrer = referral_code&.referrer end validate :ensure_not_self_referral def ensure_not_self_referral errors.add(:base, "Self-referrals are not allowed") if referrer == referee end def complete!(**attributes) return if completed_at? update attributes.with_defaults(completed_at: Time.current) Refer.referral_completed&.call(self) end end end ActiveSupport.run_load_hooks :refer_referral, Refer::Referral ================================================ FILE: app/models/refer/referral_code.rb ================================================ module Refer class ReferralCode < ApplicationRecord belongs_to :referrer, polymorphic: true has_many :referrals, dependent: :nullify has_many :visits, dependent: :delete_all validates :code, presence: true, uniqueness: true before_validation if: -> { !code? && Refer.code_generator } do self.code = Refer.code_generator.call(referrer) end def to_param code end def track_visit(request) visits.from_request(request).save end end end ActiveSupport.run_load_hooks :refer_referral_code, Refer::ReferralCode ================================================ FILE: app/models/refer/visit.rb ================================================ module Refer class Visit < ApplicationRecord belongs_to :referral_code, counter_cache: true normalizes :ip, with: -> { Refer.mask_ip(_1) } def self.from_request(request) new( ip: request.ip, user_agent: request.user_agent, referrer: request.referrer, referring_domain: (URI.parse(request.referrer).try(:host) rescue nil) ) end end end ActiveSupport.run_load_hooks :refer_visit, Refer::Visit ================================================ FILE: bin/rails ================================================ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails gems # installed from the root of your application. ENGINE_ROOT = File.expand_path("..", __dir__) ENGINE_PATH = File.expand_path("../lib/refer/engine", __dir__) APP_PATH = File.expand_path("../test/dummy/config/application", __dir__) # Set up gems listed in the Gemfile. ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"]) require "rails/all" require "rails/engine/commands" ================================================ FILE: bin/rubocop ================================================ #!/usr/bin/env ruby require "rubygems" require "bundler/setup" # explicit rubocop config increases performance slightly while avoiding config confusion. ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) load Gem.bin_path("rubocop", "rubocop") ================================================ FILE: config/routes.rb ================================================ Rails.application.routes.draw do end ================================================ FILE: db/migrate/20240611180738_create_refer_referrals.rb ================================================ class CreateReferReferrals < ActiveRecord::Migration[6.1] def change create_table :refer_referrals do |t| t.belongs_to :referrer, polymorphic: true, null: false t.belongs_to :referee, polymorphic: true, null: false t.belongs_to :referral_code t.timestamps end end end ================================================ FILE: db/migrate/20240611183349_create_refer_referral_codes.rb ================================================ class CreateReferReferralCodes < ActiveRecord::Migration[6.1] def change create_table :refer_referral_codes do |t| t.belongs_to :referrer, polymorphic: true, null: false t.string :code, null: false, index: { unique: true } t.timestamps end end end ================================================ FILE: db/migrate/20240701172643_create_refer_visits.rb ================================================ class CreateReferVisits < ActiveRecord::Migration[6.1] def change create_table :refer_visits do |t| t.belongs_to :referral_code, null: false, foreign_key: { to_table: :refer_referral_codes } t.string :ip t.text :user_agent t.text :referrer t.string :referring_domain t.timestamps end add_column :refer_referral_codes, :referrals_count, :integer, default: 0 add_column :refer_referral_codes, :visits_count, :integer, default: 0 add_column :refer_referrals, :completed_at, :datetime end end ================================================ FILE: gemfiles/rails_7.1.gemfile ================================================ # This file was generated by Appraisal source "https://rubygems.org" gem "puma" gem "sqlite3" gem "sprockets-rails" gem "rubocop-rails-omakase", require: false gem "appraisal" gem "rails", "~> 7.1.0" gemspec path: "../" ================================================ FILE: gemfiles/rails_7.2.gemfile ================================================ # This file was generated by Appraisal source "https://rubygems.org" gem "puma" gem "sqlite3" gem "sprockets-rails" gem "rubocop-rails-omakase", require: false gem "appraisal" gem "rails", "~> 7.2.0" gemspec path: "../" ================================================ FILE: gemfiles/rails_8.0.gemfile ================================================ # This file was generated by Appraisal source "https://rubygems.org" gem "puma" gem "sqlite3" gem "sprockets-rails" gem "rubocop-rails-omakase", require: false gem "appraisal" gem "rails", "~> 8.0.0" gemspec path: "../" ================================================ FILE: gemfiles/rails_8.1.gemfile ================================================ # This file was generated by Appraisal source "https://rubygems.org" gem "puma" gem "sqlite3" gem "sprockets-rails" gem "rubocop-rails-omakase", require: false gem "appraisal" gem "rails", "~> 8.1.0.beta1" gemspec path: "../" ================================================ FILE: gemfiles/rails_main.gemfile ================================================ # This file was generated by Appraisal source "https://rubygems.org" gem "puma" gem "sqlite3" gem "sprockets-rails" gem "rubocop-rails-omakase", require: false gem "appraisal" gem "rails", github: "rails/rails" gemspec path: "../" ================================================ FILE: lib/generators/refer/install/USAGE ================================================ Description: Adds Refer to ApplicationController to set referral cookies Example: bin/rails generate refer:install This will add `sets_refer_cookie` to the ApplicationController class. ================================================ FILE: lib/generators/refer/install/install_generator.rb ================================================ class Refer::InstallGenerator < Rails::Generators::Base source_root File.expand_path("templates", __dir__) def add_refer inject_into_class File.join("app", "controllers", "application_controller.rb"), "ApplicationController", " set_referral_cookie\n" end end ================================================ FILE: lib/generators/refer/model/USAGE ================================================ Description: Adds Refer associations to a model Example: bin/rails generate refer:model User This will add `has_referrals` to the User class. ================================================ FILE: lib/generators/refer/model/model_generator.rb ================================================ class Refer::ModelGenerator < Rails::Generators::NamedBase source_root File.expand_path("templates", __dir__) def migrations rails_command "refer:install:migrations" end def add_refer inject_into_class File.join("app", "models", "#{file_path}.rb"), class_name, " has_referrals\n" end end ================================================ FILE: lib/refer/controller.rb ================================================ module Refer module Controller extend ActiveSupport::Concern class_methods do def set_referral_cookie(param_name: Refer.param_name, cookie_name: Refer.cookie_name, **options) before_action -> { set_refer_cookie(param_name: param_name, cookie_name: cookie_name) }, **options end end def refer(referee, cookie_name: Refer.cookie_name) Refer.refer(code: cookies[cookie_name], referee: referee) end private def set_refer_cookie(param_name: Refer.param_name, cookie_name: Refer.cookie_name, code: nil, track_visit: Refer.track_visits) code ||= params[param_name] return if code.blank? cookies[cookie_name] = Refer.cookie(code) if Refer.overwrite_cookie || cookies[cookie_name].blank? ReferralCode.find_by(code: code)&.track_visit(request) if track_visit end end end ================================================ FILE: lib/refer/engine.rb ================================================ module Refer class Engine < ::Rails::Engine isolate_namespace Refer initializer "refer.hooks" do ActiveSupport.on_load(:active_record) do include Refer::HasReferrals end ActiveSupport.on_load(:action_controller) do include Refer::Controller end end end end ================================================ FILE: lib/refer/has_referrals.rb ================================================ module Refer module HasReferrals extend ActiveSupport::Concern class_methods do def has_referrals include Refer::Model end end end end ================================================ FILE: lib/refer/model.rb ================================================ module Refer module Model extend ActiveSupport::Concern included do has_many :referral_codes, as: :referrer, class_name: "Refer::ReferralCode", dependent: :destroy has_many :referrals, as: :referrer, class_name: "Refer::Referral", dependent: :destroy has_one :referral, as: :referee, class_name: "Refer::Referral", dependent: :destroy delegate :referrer, to: :referral, allow_nil: true end end end ================================================ FILE: lib/refer/version.rb ================================================ module Refer VERSION = "1.0.4" end ================================================ FILE: lib/refer.rb ================================================ require "refer/version" require "refer/engine" require "securerandom" module Refer autoload :Controller, "refer/controller" autoload :HasReferrals, "refer/has_referrals" autoload :Model, "refer/model" mattr_accessor :code_generator, default: ->(referrer) { SecureRandom.alphanumeric(8) } mattr_accessor :cookie_length, default: 30.days mattr_accessor :cookie_name, default: :refer_code mattr_accessor :param_name, default: :ref mattr_accessor :overwrite_cookie, default: true mattr_accessor :track_visits, default: true mattr_accessor :mask_ips, default: true mattr_accessor :referral_completed class Error < StandardError; end class AlreadyReferred < Error; end def self.referred?(referee) Referral.where(referee: referee).exists? end def self.refer(code:, referee:) return if referred?(referee) ReferralCode.find_by(code: code)&.referrals&.create(referee: referee) end def self.refer!(code:, referee:) raise AlreadyReferred, "#{referee} has already been referred" if referred?(referee) ReferralCode.find_by!(code: code).referrals.create!(referee: referee) end def self.cookie(code) { value: code, expires: Refer.cookie_length.from_now } end # From Ahoy gem: https://github.com/ankane/ahoy/blob/v5.1.0/lib/ahoy.rb#L133-L142 def self.mask_ip(ip) return ip unless mask_ips addr = IPAddr.new(ip) if addr.ipv4? # set last octet to 0 addr.mask(24).to_s else # set last 80 bits to zeros addr.mask(48).to_s end end end ActiveSupport.run_load_hooks(:refer, Refer) ================================================ FILE: lib/tasks/refer_tasks.rake ================================================ # desc "Explaining what the task does" # task :refer do # # Task goes here # end ================================================ FILE: refer.gemspec ================================================ require_relative "lib/refer/version" Gem::Specification.new do |spec| spec.name = "refer" spec.version = Refer::VERSION spec.authors = [ "Chris Oliver" ] spec.email = [ "excid3@gmail.com" ] spec.homepage = "https://github.com/excid3/refer" spec.summary = "Referral codes & affiliate links for Ruby on Rails apps" spec.description = "Referral codes & affiliate links for Ruby on Rails apps" spec.license = "MIT" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = spec.homepage spec.metadata["changelog_uri"] = spec.homepage + "/blob/main/CHANGELOG.md" spec.files = Dir.chdir(File.expand_path(__dir__)) do Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] end spec.add_dependency "rails", ">= 7.1.0" end ================================================ FILE: test/dummy/Rakefile ================================================ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. require_relative "config/application" Rails.application.load_tasks ================================================ FILE: test/dummy/app/assets/config/manifest.js ================================================ //= link_tree ../images //= link_directory ../stylesheets .css ================================================ FILE: test/dummy/app/assets/images/.keep ================================================ ================================================ FILE: test/dummy/app/assets/stylesheets/application.css ================================================ /* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS * files in this directory. Styles in this file should be added after the last require_* statement. * It is generally better to create a new file per style scope. * *= require_tree . *= require_self */ ================================================ FILE: test/dummy/app/channels/application_cable/channel.rb ================================================ module ApplicationCable class Channel < ActionCable::Channel::Base end end ================================================ FILE: test/dummy/app/channels/application_cable/connection.rb ================================================ module ApplicationCable class Connection < ActionCable::Connection::Base end end ================================================ FILE: test/dummy/app/controllers/application_controller.rb ================================================ class ApplicationController < ActionController::Base end ================================================ FILE: test/dummy/app/controllers/concerns/.keep ================================================ ================================================ FILE: test/dummy/app/controllers/referrals_controller.rb ================================================ class ReferralsController < ApplicationController set_referral_cookie before_action :set_user, only: [ :create ] def show head :ok end def create refer @user head :ok end private def set_user @user = User.find(params[:user_id]) end end ================================================ FILE: test/dummy/app/helpers/application_helper.rb ================================================ module ApplicationHelper end ================================================ FILE: test/dummy/app/jobs/application_job.rb ================================================ class ApplicationJob < ActiveJob::Base # Automatically retry jobs that encountered a deadlock # retry_on ActiveRecord::Deadlocked # Most jobs are safe to ignore if the underlying records are no longer available # discard_on ActiveJob::DeserializationError end ================================================ FILE: test/dummy/app/mailers/application_mailer.rb ================================================ class ApplicationMailer < ActionMailer::Base default from: "from@example.com" layout "mailer" end ================================================ FILE: test/dummy/app/models/application_record.rb ================================================ class ApplicationRecord < ActiveRecord::Base primary_abstract_class end ================================================ FILE: test/dummy/app/models/concerns/.keep ================================================ ================================================ FILE: test/dummy/app/models/user.rb ================================================ class User < ApplicationRecord has_referrals end ================================================ FILE: test/dummy/app/views/layouts/application.html.erb ================================================ <!DOCTYPE html> <html> <head> <title><%= content_for(:title) || "Dummy" %> <%= csrf_meta_tags %> <%= csp_meta_tag %> <%= yield :head %> <%= stylesheet_link_tag "application" %> <%= yield %> ================================================ FILE: test/dummy/app/views/layouts/mailer.html.erb ================================================ <%= yield %> ================================================ FILE: test/dummy/app/views/layouts/mailer.text.erb ================================================ <%= yield %> ================================================ FILE: test/dummy/app/views/pwa/manifest.json.erb ================================================ { "name": "Dummy", "icons": [ { "src": "/icon.png", "type": "image/png", "sizes": "512x512" }, { "src": "/icon.png", "type": "image/png", "sizes": "512x512", "purpose": "maskable" } ], "start_url": "/", "display": "standalone", "scope": "/", "description": "Dummy.", "theme_color": "red", "background_color": "red" } ================================================ FILE: test/dummy/app/views/pwa/service-worker.js ================================================ // Add a service worker for processing Web Push notifications: // // self.addEventListener("push", async (event) => { // const { title, options } = await event.data.json() // event.waitUntil(self.registration.showNotification(title, options)) // }) // // self.addEventListener("notificationclick", function(event) { // event.notification.close() // event.waitUntil( // clients.matchAll({ type: "window" }).then((clientList) => { // for (let i = 0; i < clientList.length; i++) { // let client = clientList[i] // let clientPath = (new URL(client.url)).pathname // // if (clientPath == event.notification.data.path && "focus" in client) { // return client.focus() // } // } // // if (clients.openWindow) { // return clients.openWindow(event.notification.data.path) // } // }) // ) // }) ================================================ FILE: test/dummy/bin/rails ================================================ #!/usr/bin/env ruby APP_PATH = File.expand_path("../config/application", __dir__) require_relative "../config/boot" require "rails/commands" ================================================ FILE: test/dummy/bin/rake ================================================ #!/usr/bin/env ruby require_relative "../config/boot" require "rake" Rake.application.run ================================================ FILE: test/dummy/bin/setup ================================================ #!/usr/bin/env ruby require "fileutils" APP_ROOT = File.expand_path("..", __dir__) APP_NAME = "dummy" def system!(*args) system(*args, exception: true) end FileUtils.chdir APP_ROOT do # This script is a way to set up or update your development environment automatically. # This script is idempotent, so that you can run it at any time and get an expectable outcome. # Add necessary setup steps to this file. puts "== Installing dependencies ==" system! "gem install bundler --conservative" system("bundle check") || system!("bundle install") # puts "\n== Copying sample files ==" # unless File.exist?("config/database.yml") # FileUtils.cp "config/database.yml.sample", "config/database.yml" # end puts "\n== Preparing database ==" system! "bin/rails db:prepare" puts "\n== Removing old logs and tempfiles ==" system! "bin/rails log:clear tmp:clear" puts "\n== Restarting application server ==" system! "bin/rails restart" # puts "\n== Configuring puma-dev ==" # system "ln -nfs #{APP_ROOT} ~/.puma-dev/#{APP_NAME}" # system "curl -Is https://#{APP_NAME}.test/up | head -n 1" end ================================================ FILE: test/dummy/config/application.rb ================================================ require_relative "boot" require "rails/all" # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Dummy class Application < Rails::Application config.load_defaults Rails::VERSION::STRING.to_f # For compatibility with applications that use this config config.action_controller.include_all_helpers = false # Please, add to the `ignore` list any other `lib` subdirectories that do # not contain `.rb` files, or that should not be reloaded or eager loaded. # Common ones are `templates`, `generators`, or `middleware`, for example. config.autoload_lib(ignore: %w[assets tasks]) # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") end end ================================================ FILE: test/dummy/config/boot.rb ================================================ # Set up gems listed in the Gemfile. ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../../Gemfile", __dir__) require "bundler/setup" if File.exist?(ENV["BUNDLE_GEMFILE"]) $LOAD_PATH.unshift File.expand_path("../../../lib", __dir__) ================================================ FILE: test/dummy/config/cable.yml ================================================ development: adapter: async test: adapter: test production: adapter: redis url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> channel_prefix: dummy_production ================================================ FILE: test/dummy/config/database.yml ================================================ # SQLite. Versions 3.8.0 and up are supported. # gem install sqlite3 # # Ensure the SQLite 3 gem is defined in your Gemfile # gem "sqlite3" # default: &default adapter: sqlite3 pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> timeout: 5000 development: <<: *default database: storage/development.sqlite3 # Warning: The database defined as "test" will be erased and # re-generated from your development database when you run "rake". # Do not set this db to the same as development or production. test: <<: *default database: storage/test.sqlite3 # SQLite3 write its data on the local filesystem, as such it requires # persistent disks. If you are deploying to a managed service, you should # make sure it provides disk persistence, as many don't. # # Similarly, if you deploy your application as a Docker container, you must # ensure the database is located in a persisted volume. production: <<: *default # database: path/to/persistent/storage/production.sqlite3 ================================================ FILE: test/dummy/config/environment.rb ================================================ # Load the Rails application. require_relative "application" # Initialize the Rails application. Rails.application.initialize! ================================================ FILE: test/dummy/config/environments/development.rb ================================================ require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded any time # it changes. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.enable_reloading = true # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable server timing. config.server_timing = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join("tmp/caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :memory_store config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false config.action_mailer.default_url_options = { host: "localhost", port: 3000 } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Highlight code that enqueued background job in logs. config.active_job.verbose_enqueue_logs = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. config.action_view.annotate_rendered_view_with_filenames = true # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true end ================================================ FILE: test/dummy/config/environments/production.rb ================================================ require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.enable_reloading = false # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. # config.public_file_server.enabled = false # Compress CSS using a preprocessor. # config.assets.css_compressor = :sass # Do not fall back to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = "http://assets.example.com" # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = "wss://example.com/cable" # config.action_cable.allowed_request_origins = [ "http://example.com", /http:\/\/example.*/ ] # Assume all access to the app is happening through a SSL-terminating reverse proxy. # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. # config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. config.force_ssl = true # Skip http-to-https redirect for the default health check endpoint. # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } # Log to STDOUT by default config.logger = ActiveSupport::Logger.new(STDOUT) .tap { |logger| logger.formatter = ::Logger::Formatter.new } .then { |logger| ActiveSupport::TaggedLogging.new(logger) } # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # "info" includes generic and useful information about system operation, but avoids logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). If you # want to log everything, set the level to "debug". config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "dummy_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Don't log any deprecations. config.active_support.report_deprecations = false # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } end ================================================ FILE: test/dummy/config/environments/test.rb ================================================ require "active_support/core_ext/integer/time" # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # While tests run files are not watched, reloading is not necessary. config.enable_reloading = false # Eager loading loads your entire application. When running a single test locally, # this is usually not necessary, and can slow down your test suite. However, it's # recommended that you enable it in continuous integration systems to ensure eager # loading is working properly before deploying your code. config.eager_load = ENV["CI"].present? # Configure public file server for tests with Cache-Control for performance. config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # Render exception templates for rescuable exceptions and raise for other exceptions. config.action_dispatch.show_exceptions = :rescuable # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Store uploaded files on the local file system in a temporary directory. config.active_storage.service = :test config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Unlike controllers, the mailer instance doesn't have any context about the # incoming request so you'll need to provide the :host parameter yourself. config.action_mailer.default_url_options = { host: "www.example.com" } # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Raise error when a before_action's only/except options reference missing actions. config.action_controller.raise_on_missing_callback_actions = true end ================================================ FILE: test/dummy/config/initializers/assets.rb ================================================ # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = "1.0" # Add additional assets to the asset load path. # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css ) ================================================ FILE: test/dummy/config/initializers/content_security_policy.rb ================================================ # Be sure to restart your server when you modify this file. # Define an application-wide content security policy. # See the Securing Rails Applications Guide for more information: # https://guides.rubyonrails.org/security.html#content-security-policy-header # Rails.application.configure do # config.content_security_policy do |policy| # policy.default_src :self, :https # policy.font_src :self, :https, :data # policy.img_src :self, :https, :data # policy.object_src :none # policy.script_src :self, :https # policy.style_src :self, :https # # Specify URI for violation reports # # policy.report_uri "/csp-violation-report-endpoint" # end # # # Generate session nonces for permitted importmap, inline scripts, and inline styles. # config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } # config.content_security_policy_nonce_directives = %w(script-src style-src) # # # Report violations without enforcing the policy. # # config.content_security_policy_report_only = true # end ================================================ FILE: test/dummy/config/initializers/filter_parameter_logging.rb ================================================ # Be sure to restart your server when you modify this file. # Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. # Use this to limit dissemination of sensitive information. # See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. Rails.application.config.filter_parameters += [ :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn ] ================================================ FILE: test/dummy/config/initializers/inflections.rb ================================================ # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, "\\1en" # inflect.singular /^(ox)en/i, "\\1" # inflect.irregular "person", "people" # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym "RESTful" # end ================================================ FILE: test/dummy/config/initializers/permissions_policy.rb ================================================ # Be sure to restart your server when you modify this file. # Define an application-wide HTTP permissions policy. For further # information see: https://developers.google.com/web/updates/2018/06/feature-policy # Rails.application.config.permissions_policy do |policy| # policy.camera :none # policy.gyroscope :none # policy.microphone :none # policy.usb :none # policy.fullscreen :self # policy.payment :self, "https://secure.example.com" # end ================================================ FILE: test/dummy/config/locales/en.yml ================================================ # Files in the config/locales directory are used for internationalization and # are automatically loaded by Rails. If you want to use locales other than # English, add the necessary files in this directory. # # To use the locales, use `I18n.t`: # # I18n.t "hello" # # In views, this is aliased to just `t`: # # <%= t("hello") %> # # To use a different locale, set it with `I18n.locale`: # # I18n.locale = :es # # This would use the information in config/locales/es.yml. # # To learn more about the API, please read the Rails Internationalization guide # at https://guides.rubyonrails.org/i18n.html. # # Be aware that YAML interprets the following case-insensitive strings as # booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings # must be quoted to be interpreted as strings. For example: # # en: # "yes": yup # enabled: "ON" en: hello: "Hello world" ================================================ FILE: test/dummy/config/puma.rb ================================================ # This configuration file will be evaluated by Puma. The top-level methods that # are invoked here are part of Puma's configuration DSL. For more information # about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. # Puma starts a configurable number of processes (workers) and each process # serves each request in a thread from an internal thread pool. # # The ideal number of threads per worker depends both on how much time the # application spends waiting for IO operations and on how much you wish to # to prioritize throughput over latency. # # As a rule of thumb, increasing the number of threads will increase how much # traffic a given process can handle (throughput), but due to CRuby's # Global VM Lock (GVL) it has diminishing returns and will degrade the # response time (latency) of the application. # # The default is set to 3 threads as it's deemed a decent compromise between # throughput and latency for the average Rails application. # # Any libraries that use a connection pool or another resource pool should # be configured to provide at least as many connections as the number of # threads. This includes Active Record's `pool` parameter in `database.yml`. threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) threads threads_count, threads_count # Specifies the `environment` that Puma will run in. rails_env = ENV.fetch("RAILS_ENV", "development") environment rails_env case rails_env when "production" # If you are running more than 1 thread per process, the workers count # should be equal to the number of processors (CPU cores) in production. # # Automatically detect the number of available processors in production. require "concurrent-ruby" workers_count = Integer(ENV.fetch("WEB_CONCURRENCY") { Concurrent.available_processor_count }) workers workers_count if workers_count > 1 preload_app! when "development" # Specifies a very generous `worker_timeout` so that the worker # isn't killed by Puma when suspended by a debugger. worker_timeout 3600 end # Specifies the `port` that Puma will listen on to receive requests; default is 3000. port ENV.fetch("PORT", 3000) # Allow puma to be restarted by `bin/rails restart` command. plugin :tmp_restart # Only use a pidfile when requested pidfile ENV["PIDFILE"] if ENV["PIDFILE"] ================================================ FILE: test/dummy/config/routes.rb ================================================ Rails.application.routes.draw do # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html post :refer, to: "referrals#create" # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. # Can be used by load balancers and uptime monitors to verify that the app is live. get "up" => "rails/health#show", as: :rails_health_check # Render dynamic PWA files from app/views/pwa/* get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker get "manifest" => "rails/pwa#manifest", as: :pwa_manifest # Defines the root path route ("/") root to: "referrals#show" end ================================================ FILE: test/dummy/config/storage.yml ================================================ test: service: Disk root: <%= Rails.root.join("tmp/storage") %> local: service: Disk root: <%= Rails.root.join("storage") %> # Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) # amazon: # service: S3 # access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> # secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> # region: us-east-1 # bucket: your_own_bucket-<%= Rails.env %> # Remember not to checkin your GCS keyfile to a repository # google: # service: GCS # project: your_project # credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> # bucket: your_own_bucket-<%= Rails.env %> # Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) # microsoft: # service: AzureStorage # storage_account_name: your_account_name # storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> # container: your_container_name-<%= Rails.env %> # mirror: # service: Mirror # primary: local # mirrors: [ amazon, google, microsoft ] ================================================ FILE: test/dummy/config.ru ================================================ # This file is used by Rack-based servers to start the application. require_relative "config/environment" run Rails.application Rails.application.load_server ================================================ FILE: test/dummy/db/migrate/20240611180748_create_users.rb ================================================ class CreateUsers < ActiveRecord::Migration[7.2] def change create_table :users do |t| t.string :name t.timestamps end end end ================================================ FILE: test/dummy/db/schema.rb ================================================ # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema[7.2].define(version: 2024_07_01_172643) do create_table "refer_referral_codes", force: :cascade do |t| t.string "referrer_type", null: false t.integer "referrer_id", null: false t.string "code", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "referrals_count", default: 0 t.integer "visits_count", default: 0 t.index [ "code" ], name: "index_refer_referral_codes_on_code", unique: true t.index [ "referrer_type", "referrer_id" ], name: "index_refer_referral_codes_on_referrer" end create_table "refer_referrals", force: :cascade do |t| t.string "referrer_type", null: false t.integer "referrer_id", null: false t.string "referee_type", null: false t.integer "referee_id", null: false t.integer "referral_code_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.datetime "completed_at" t.index [ "referee_type", "referee_id" ], name: "index_refer_referrals_on_referee" t.index [ "referral_code_id" ], name: "index_refer_referrals_on_referral_code_id" t.index [ "referrer_type", "referrer_id" ], name: "index_refer_referrals_on_referrer" end create_table "refer_visits", force: :cascade do |t| t.integer "referral_code_id", null: false t.string "ip" t.text "user_agent" t.text "referrer" t.string "referring_domain" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index [ "referral_code_id" ], name: "index_refer_visits_on_referral_code_id" end create_table "users", force: :cascade do |t| t.string "name" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_foreign_key "refer_visits", "refer_referral_codes", column: "referral_code_id" end ================================================ FILE: test/dummy/lib/assets/.keep ================================================ ================================================ FILE: test/dummy/log/.keep ================================================ ================================================ FILE: test/dummy/public/404.html ================================================ The page you were looking for doesn't exist (404)

The page you were looking for doesn't exist.

You may have mistyped the address or the page may have moved.

If you are the application owner check the logs for more information.

================================================ FILE: test/dummy/public/406-unsupported-browser.html ================================================ Your browser is not supported (406)

Your browser is not supported.

Please upgrade your browser to continue.

================================================ FILE: test/dummy/public/422.html ================================================ The change you wanted was rejected (422)

The change you wanted was rejected.

Maybe you tried to change something you didn't have access to.

If you are the application owner check the logs for more information.

================================================ FILE: test/dummy/public/500.html ================================================ We're sorry, but something went wrong (500)

We're sorry, but something went wrong.

If you are the application owner check the logs for more information.

================================================ FILE: test/fixtures/files/.keep ================================================ ================================================ FILE: test/fixtures/refer/referral_codes.yml ================================================ # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: referrer: one (User) code: chris two: referrer: two (User) code: bob ================================================ FILE: test/fixtures/refer/referrals.yml ================================================ # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: referrer: one (User) referee: two (User) referral_code: one ================================================ FILE: test/fixtures/refer/visits.yml ================================================ # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: referral_code: one ip: MyString user_agent: MyText referrer: MyText referring_domain: MyString two: referral_code: two ip: MyString user_agent: MyText referrer: MyText referring_domain: MyString ================================================ FILE: test/fixtures/users.yml ================================================ # Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html one: name: Chris two: name: Bob new: name: David ================================================ FILE: test/integration/.keep ================================================ ================================================ FILE: test/integration/referral_test.rb ================================================ require "test_helper" class ReferralIntegrationTest < ActionDispatch::IntegrationTest test "referral is created" do assert_difference "Refer::Referral.count" do post refer_path(ref: refer_referral_codes(:one), user_id: users(:new).id) end end test "doesn't set referral cookie if param missing" do get root_path(other: "example") assert_nil cookies[Refer.cookie_name] end test "sets referral cookie" do referral_code = refer_referral_codes(:one) get root_path(ref: referral_code) assert_equal referral_code.to_param, cookies[Refer.cookie_name] end test "tracks visits" do referral_code = refer_referral_codes(:one) assert_difference "referral_code.reload.visits_count" do get root_path(ref: referral_code) end end end ================================================ FILE: test/models/.keep ================================================ ================================================ FILE: test/models/refer/referral_code_test.rb ================================================ require "test_helper" require "minitest/mock" class Refer::ReferralCodeTest < ActiveSupport::TestCase test "deleting referral code doesn't delete referral" do referral = refer_referrals(:one) assert_not_nil referral.referral_code assert_no_difference "Refer::Referral.count" do referral.referral_code.destroy end referral.reload assert_nil referral.referral_code end test "referral codes are dependent destroyed" do assert_difference "Refer::ReferralCode.count", -1 do users(:one).destroy end end test "generates referral codes automatically" do Refer.stub :code_generator, -> { ->(referrer) { SecureRandom.alphanumeric(8) } } do assert_not_nil users(:one).referral_codes.create!.code end end test "does not generate referral code automatically if empty generator config" do Refer.stub :code_generator, nil do assert_nil users(:one).referral_codes.create.code end end test "does not generate referral code automatically if using a custom code" do Refer.stub :code_generator, ->(referrer) { SecureRandom.alphanumeric(8) } do custom_referral = users(:one).referral_codes.create(code: "custom") assert_equal custom_referral.code, "custom" end end end ================================================ FILE: test/models/refer/referral_test.rb ================================================ require "test_helper" class Refer::ReferralTest < ActiveSupport::TestCase test "referrals are dependent destroyed" do assert_difference "Refer::Referral.count", -1 do users(:one).destroy end end test "can be associated with a referral code" do assert_equal refer_referral_codes(:one), refer_referrals(:one).referral_code end test "can be completed" do referral = refer_referrals(:one) assert_nil referral.completed_at travel_to Time.current do referral.complete! assert_equal Time.current, referral.completed_at end end test "complete with custom attributes" do referral = refer_referrals(:one) assert_nil referral.completed_at travel_to Time.current do referral.complete!(completed_at: 1.hour.ago) assert_equal 1.hour.ago, referral.completed_at end end test "complete! doesn't override previous completion" do referral = refer_referrals(:one) assert_nil referral.completed_at referral.complete! travel_to Time.current + 1.hour do assert_no_difference "referral.completed_at" do referral.complete! end end end end ================================================ FILE: test/models/refer/visit_test.rb ================================================ require "test_helper" module Refer class VisitTest < ActiveSupport::TestCase test "masks ips" do assert_equal "127.0.0.0", Refer::Visit.new(ip: "127.0.0.1").ip end test "referring_domain" do request = ActiveSupport::OrderedOptions.new.merge(referrer: "https://gorails.com/episodes/1") assert_equal "gorails.com", Refer::Visit.from_request(request).referring_domain end end end ================================================ FILE: test/refer_test.rb ================================================ require "test_helper" class ReferTest < ActiveSupport::TestCase test "it has a version number" do assert Refer::VERSION end test "refer" do assert_difference "Refer::Referral.count" do Refer.refer(code: refer_referral_codes(:one).code, referee: users(:new)) end end test "refer invalid code" do assert_raises ActiveRecord::RecordNotFound do Refer.refer!(code: "invalid", referee: users(:new)) end end test "refer self" do assert_no_difference "Refer::Referral.count" do Refer.refer(code: refer_referral_codes(:one).code, referee: users(:one)) end assert_raises ActiveRecord::RecordInvalid, "Validation failed: Self-referrals are not allowed" do Refer.refer!(code: refer_referral_codes(:one).code, referee: users(:one)) end end test "refer already referred" do assert_no_difference "Refer::Referral.count" do Refer.refer(code: refer_referral_codes(:one).code, referee: users(:two)) end assert_raises Refer::AlreadyReferred do Refer.refer!(code: refer_referral_codes(:one).code, referee: users(:two)) end end test "referred?" do assert Refer.referred?(users(:two)) assert_not Refer.referred?(users(:new)) end test "referral_codes" do assert_includes users(:one).referral_codes, refer_referral_codes(:one) end test "referrals" do assert_includes users(:one).referrals, refer_referrals(:one) end test "referral" do assert_equal refer_referrals(:one), users(:two).referral end test "referrer" do assert_equal users(:one), users(:two).referrer end test "referrer when nil" do assert_nil users(:new).referrer end test "referral_completed callback" do old_callback = Refer.referral_completed referral = refer_referrals(:one) assert_not referral.completed_at? completed = nil Refer.referral_completed = ->(referral) { completed = referral } # Called the first time a referral is completed referral.complete! assert_equal referral, completed # Does not get called second time because referral was already completed completed = nil referral.complete! assert_nil completed ensure Refer.referral_completed = old_callback end end ================================================ FILE: test/test_helper.rb ================================================ # Configure Rails Environment ENV["RAILS_ENV"] = "test" require_relative "../test/dummy/config/environment" ActiveRecord::Migrator.migrations_paths = [ File.expand_path("../test/dummy/db/migrate", __dir__) ] require "rails/test_help" # Load fixtures from the engine if ActiveSupport::TestCase.respond_to?(:fixture_paths=) ActiveSupport::TestCase.fixture_paths = [ File.expand_path("fixtures", __dir__) ] ActionDispatch::IntegrationTest.fixture_paths = ActiveSupport::TestCase.fixture_paths ActiveSupport::TestCase.file_fixture_path = File.expand_path("fixtures", __dir__) + "/files" ActiveSupport::TestCase.fixtures :all end