Full Code of excid3/refer for AI

main 734e75777b9b cached
107 files
66.9 KB
20.9k tokens
69 symbols
1 requests
Download .txt
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] <title>'
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" %></title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= yield :head %>

    <link rel="manifest" href="/manifest.json">
    <link rel="icon" href="/icon.png" type="image/png">
    <link rel="icon" href="/icon.svg" type="image/svg+xml">
    <link rel="apple-touch-icon" href="/icon.png">
    <%= stylesheet_link_tag "application" %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>


================================================
FILE: test/dummy/app/views/layouts/mailer.html.erb
================================================
<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style>
      /* Email styles need to be inline */
    </style>
  </head>

  <body>
    <%= yield %>
  </body>
</html>


================================================
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
================================================
<!DOCTYPE html>
<html>
<head>
  <title>The page you were looking for doesn't exist (404)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
  .rails-default-error-page {
    background-color: #EFEFEF;
    color: #2E2F30;
    text-align: center;
    font-family: arial, sans-serif;
    margin: 0;
  }

  .rails-default-error-page div.dialog {
    width: 95%;
    max-width: 33em;
    margin: 4em auto 0;
  }

  .rails-default-error-page div.dialog > div {
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #BBB;
    border-top: #B00100 solid 4px;
    border-top-left-radius: 9px;
    border-top-right-radius: 9px;
    background-color: white;
    padding: 7px 12% 0;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }

  .rails-default-error-page h1 {
    font-size: 100%;
    color: #730E15;
    line-height: 1.5em;
  }

  .rails-default-error-page div.dialog > p {
    margin: 0 0 1em;
    padding: 1em;
    background-color: #F7F7F7;
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #999;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-top-color: #DADADA;
    color: #666;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }
  </style>
</head>

<body class="rails-default-error-page">
  <!-- This file lives in public/404.html -->
  <div class="dialog">
    <div>
      <h1>The page you were looking for doesn't exist.</h1>
      <p>You may have mistyped the address or the page may have moved.</p>
    </div>
    <p>If you are the application owner check the logs for more information.</p>
  </div>
</body>
</html>


================================================
FILE: test/dummy/public/406-unsupported-browser.html
================================================
<!DOCTYPE html>
<html>
<head>
  <title>Your browser is not supported (406)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
  .rails-default-error-page {
    background-color: #EFEFEF;
    color: #2E2F30;
    text-align: center;
    font-family: arial, sans-serif;
    margin: 0;
  }

  .rails-default-error-page div.dialog {
    width: 95%;
    max-width: 33em;
    margin: 4em auto 0;
  }

  .rails-default-error-page div.dialog > div {
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #BBB;
    border-top: #B00100 solid 4px;
    border-top-left-radius: 9px;
    border-top-right-radius: 9px;
    background-color: white;
    padding: 7px 12% 0;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }

  .rails-default-error-page h1 {
    font-size: 100%;
    color: #730E15;
    line-height: 1.5em;
  }

  .rails-default-error-page div.dialog > p {
    margin: 0 0 1em;
    padding: 1em;
    background-color: #F7F7F7;
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #999;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-top-color: #DADADA;
    color: #666;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }
  </style>
</head>

<body class="rails-default-error-page">
  <!-- This file lives in public/406-unsupported-browser.html -->
  <div class="dialog">
    <div>
      <h1>Your browser is not supported.</h1>
      <p>Please upgrade your browser to continue.</p>
    </div>
  </div>
</body>
</html>


================================================
FILE: test/dummy/public/422.html
================================================
<!DOCTYPE html>
<html>
<head>
  <title>The change you wanted was rejected (422)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
  .rails-default-error-page {
    background-color: #EFEFEF;
    color: #2E2F30;
    text-align: center;
    font-family: arial, sans-serif;
    margin: 0;
  }

  .rails-default-error-page div.dialog {
    width: 95%;
    max-width: 33em;
    margin: 4em auto 0;
  }

  .rails-default-error-page div.dialog > div {
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #BBB;
    border-top: #B00100 solid 4px;
    border-top-left-radius: 9px;
    border-top-right-radius: 9px;
    background-color: white;
    padding: 7px 12% 0;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }

  .rails-default-error-page h1 {
    font-size: 100%;
    color: #730E15;
    line-height: 1.5em;
  }

  .rails-default-error-page div.dialog > p {
    margin: 0 0 1em;
    padding: 1em;
    background-color: #F7F7F7;
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #999;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-top-color: #DADADA;
    color: #666;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }
  </style>
</head>

<body class="rails-default-error-page">
  <!-- This file lives in public/422.html -->
  <div class="dialog">
    <div>
      <h1>The change you wanted was rejected.</h1>
      <p>Maybe you tried to change something you didn't have access to.</p>
    </div>
    <p>If you are the application owner check the logs for more information.</p>
  </div>
</body>
</html>


================================================
FILE: test/dummy/public/500.html
================================================
<!DOCTYPE html>
<html>
<head>
  <title>We're sorry, but something went wrong (500)</title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
  .rails-default-error-page {
    background-color: #EFEFEF;
    color: #2E2F30;
    text-align: center;
    font-family: arial, sans-serif;
    margin: 0;
  }

  .rails-default-error-page div.dialog {
    width: 95%;
    max-width: 33em;
    margin: 4em auto 0;
  }

  .rails-default-error-page div.dialog > div {
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #BBB;
    border-top: #B00100 solid 4px;
    border-top-left-radius: 9px;
    border-top-right-radius: 9px;
    background-color: white;
    padding: 7px 12% 0;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }

  .rails-default-error-page h1 {
    font-size: 100%;
    color: #730E15;
    line-height: 1.5em;
  }

  .rails-default-error-page div.dialog > p {
    margin: 0 0 1em;
    padding: 1em;
    background-color: #F7F7F7;
    border: 1px solid #CCC;
    border-right-color: #999;
    border-left-color: #999;
    border-bottom-color: #999;
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    border-top-color: #DADADA;
    color: #666;
    box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17);
  }
  </style>
</head>

<body class="rails-default-error-page">
  <!-- This file lives in public/500.html -->
  <div class="dialog">
    <div>
      <h1>We're sorry, but something went wrong.</h1>
    </div>
    <p>If you are the application owner check the logs for more information.</p>
  </div>
</body>
</html>


================================================
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
Download .txt
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
Download .txt
SYMBOL INDEX (69 symbols across 31 files)

FILE: app/models/refer/application_record.rb
  type Refer (line 1) | module Refer
    class ApplicationRecord (line 2) | class ApplicationRecord < ActiveRecord::Base

FILE: app/models/refer/referral.rb
  type Refer (line 1) | module Refer
    class Referral (line 2) | class Referral < ApplicationRecord
      method ensure_not_self_referral (line 15) | def ensure_not_self_referral
      method complete! (line 19) | def complete!(**attributes)

FILE: app/models/refer/referral_code.rb
  type Refer (line 1) | module Refer
    class ReferralCode (line 2) | class ReferralCode < ApplicationRecord
      method to_param (line 13) | def to_param
      method track_visit (line 17) | def track_visit(request)

FILE: app/models/refer/visit.rb
  type Refer (line 1) | module Refer
    class Visit (line 2) | class Visit < ApplicationRecord
      method from_request (line 7) | def self.from_request(request)

FILE: db/migrate/20240611180738_create_refer_referrals.rb
  class CreateReferReferrals (line 1) | class CreateReferReferrals < ActiveRecord::Migration[6.1]
    method change (line 2) | def change

FILE: db/migrate/20240611183349_create_refer_referral_codes.rb
  class CreateReferReferralCodes (line 1) | class CreateReferReferralCodes < ActiveRecord::Migration[6.1]
    method change (line 2) | def change

FILE: db/migrate/20240701172643_create_refer_visits.rb
  class CreateReferVisits (line 1) | class CreateReferVisits < ActiveRecord::Migration[6.1]
    method change (line 2) | def change

FILE: lib/generators/refer/install/install_generator.rb
  class Refer::InstallGenerator (line 1) | class Refer::InstallGenerator < Rails::Generators::Base
    method add_refer (line 4) | def add_refer

FILE: lib/generators/refer/model/model_generator.rb
  class Refer::ModelGenerator (line 1) | class Refer::ModelGenerator < Rails::Generators::NamedBase
    method migrations (line 4) | def migrations
    method add_refer (line 8) | def add_refer

FILE: lib/refer.rb
  type Refer (line 5) | module Refer
    class Error (line 19) | class Error < StandardError; end
    class AlreadyReferred (line 20) | class AlreadyReferred < Error; end
    function referred? (line 22) | def self.referred?(referee)
    function refer (line 26) | def self.refer(code:, referee:)
    function refer! (line 31) | def self.refer!(code:, referee:)
    function cookie (line 36) | def self.cookie(code)
    function mask_ip (line 44) | def self.mask_ip(ip)

FILE: lib/refer/controller.rb
  type Refer (line 1) | module Refer
    type Controller (line 2) | module Controller
      function set_referral_cookie (line 6) | def set_referral_cookie(param_name: Refer.param_name, cookie_name: R...
      function refer (line 11) | def refer(referee, cookie_name: Refer.cookie_name)
      function set_refer_cookie (line 17) | def set_refer_cookie(param_name: Refer.param_name, cookie_name: Refe...

FILE: lib/refer/engine.rb
  type Refer (line 1) | module Refer
    class Engine (line 2) | class Engine < ::Rails::Engine

FILE: lib/refer/has_referrals.rb
  type Refer (line 1) | module Refer
    type HasReferrals (line 2) | module HasReferrals
      function has_referrals (line 6) | def has_referrals

FILE: lib/refer/model.rb
  type Refer (line 1) | module Refer
    type Model (line 2) | module Model

FILE: lib/refer/version.rb
  type Refer (line 1) | module Refer

FILE: test/dummy/app/channels/application_cable/channel.rb
  type ApplicationCable (line 1) | module ApplicationCable
    class Channel (line 2) | class Channel < ActionCable::Channel::Base

FILE: test/dummy/app/channels/application_cable/connection.rb
  type ApplicationCable (line 1) | module ApplicationCable
    class Connection (line 2) | class Connection < ActionCable::Connection::Base

FILE: test/dummy/app/controllers/application_controller.rb
  class ApplicationController (line 1) | class ApplicationController < ActionController::Base

FILE: test/dummy/app/controllers/referrals_controller.rb
  class ReferralsController (line 1) | class ReferralsController < ApplicationController
    method show (line 5) | def show
    method create (line 9) | def create
    method set_user (line 16) | def set_user

FILE: test/dummy/app/helpers/application_helper.rb
  type ApplicationHelper (line 1) | module ApplicationHelper

FILE: test/dummy/app/jobs/application_job.rb
  class ApplicationJob (line 1) | class ApplicationJob < ActiveJob::Base

FILE: test/dummy/app/mailers/application_mailer.rb
  class ApplicationMailer (line 1) | class ApplicationMailer < ActionMailer::Base

FILE: test/dummy/app/models/application_record.rb
  class ApplicationRecord (line 1) | class ApplicationRecord < ActiveRecord::Base

FILE: test/dummy/app/models/user.rb
  class User (line 1) | class User < ApplicationRecord

FILE: test/dummy/config/application.rb
  type Dummy (line 9) | module Dummy
    class Application (line 10) | class Application < Rails::Application

FILE: test/dummy/db/migrate/20240611180748_create_users.rb
  class CreateUsers (line 1) | class CreateUsers < ActiveRecord::Migration[7.2]
    method change (line 2) | def change

FILE: test/integration/referral_test.rb
  class ReferralIntegrationTest (line 3) | class ReferralIntegrationTest < ActionDispatch::IntegrationTest

FILE: test/models/refer/referral_code_test.rb
  class Refer::ReferralCodeTest (line 5) | class Refer::ReferralCodeTest < ActiveSupport::TestCase

FILE: test/models/refer/referral_test.rb
  class Refer::ReferralTest (line 3) | class Refer::ReferralTest < ActiveSupport::TestCase

FILE: test/models/refer/visit_test.rb
  type Refer (line 3) | module Refer
    class VisitTest (line 4) | class VisitTest < ActiveSupport::TestCase

FILE: test/refer_test.rb
  class ReferTest (line 3) | class ReferTest < ActiveSupport::TestCase
Condensed preview — 107 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (78K chars).
[
  {
    "path": ".github/FUNDING.yml",
    "chars": 720,
    "preview": "# These are supported funding model platforms\n\ngithub: [excid3] # Replace with up to 4 GitHub Sponsors-enabled usernames"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "chars": 1272,
    "preview": "blank_issues_enabled: false\ncontact_links:\n  - name: Get Help\n    url: https://github.com/excid3/refer/discussions/new?c"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/issue_template.md",
    "chars": 1640,
    "preview": "---\nname: 🐞 Bug\nabout: File a bug/issue\ntitle: '[BUG] <title>'\nlabels: Bug, Needs Triage\nassignees: ''\n\n---\n\n## Bug Repo"
  },
  {
    "path": ".github/dependabot.yml",
    "chars": 245,
    "preview": "version: 2\nupdates:\n- package-ecosystem: bundler\n  directory: \"/\"\n  schedule:\n    interval: daily\n  open-pull-requests-l"
  },
  {
    "path": ".github/pull_request_template.md",
    "chars": 1009,
    "preview": "## Pull Request\n\n**Summary:**\n<!-- Provide a brief summary of the changes in this pull request -->\n\n**Related Issue:**\n<"
  },
  {
    "path": ".github/workflows/ci.yml",
    "chars": 1420,
    "preview": "name: CI\n\non:\n  pull_request:\n  push:\n    branches: [ main ]\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    steps:\n      "
  },
  {
    "path": ".gitignore",
    "chars": 151,
    "preview": "/.bundle/\n/doc/\n/log/*.log\n/pkg/\n/tmp/\n/test/dummy/db/*.sqlite3\n/test/dummy/db/*.sqlite3-*\n/test/dummy/log/*.log\n/test/d"
  },
  {
    "path": ".rubocop.yml",
    "chars": 249,
    "preview": "# Omakase Ruby styling for Rails\ninherit_gem: { rubocop-rails-omakase: rubocop.yml }\n\n# Overwrite or add rules to create"
  },
  {
    "path": ".ruby-version",
    "chars": 6,
    "preview": "3.4.5\n"
  },
  {
    "path": "Appraisals",
    "chars": 292,
    "preview": "appraise \"rails-7.1\" do\n  gem \"rails\", \"~> 7.1.0\"\nend\n\nappraise \"rails-7.2\" do\n  gem \"rails\", \"~> 7.2.0\"\nend\n\nappraise \""
  },
  {
    "path": "CHANGELOG.md",
    "chars": 1500,
    "preview": "### Unreleased\n\n### 1.0.4\n\n* Remove deprecated `ActiveSupport::Configurable` and replace with mattr_accessor for global "
  },
  {
    "path": "Gemfile",
    "chars": 367,
    "preview": "source \"https://rubygems.org\"\n\n# Specify your gem's dependencies in refer.gemspec.\ngemspec\n\ngem \"puma\"\n\ngem \"sqlite3\"\n\ng"
  },
  {
    "path": "MIT-LICENSE",
    "chars": 1047,
    "preview": "Copyright Chris Oliver\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software an"
  },
  {
    "path": "README.md",
    "chars": 4902,
    "preview": "# Refer\n\nReferral codes and affiliate links for Ruby on Rails applications.\n\n## 📦 Installation\nAdd this line to your app"
  },
  {
    "path": "Rakefile",
    "chars": 149,
    "preview": "require \"bundler/setup\"\n\nAPP_RAKEFILE = File.expand_path(\"test/dummy/Rakefile\", __dir__)\nload \"rails/tasks/engine.rake\"\n"
  },
  {
    "path": "app/controllers/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "app/controllers/concerns/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "app/models/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "app/models/refer/application_record.rb",
    "chars": 139,
    "preview": "module Refer\n  class ApplicationRecord < ActiveRecord::Base\n    self.abstract_class = true\n    self.table_name_prefix = "
  },
  {
    "path": "app/models/refer/referral.rb",
    "chars": 760,
    "preview": "module Refer\n  class Referral < ApplicationRecord\n    belongs_to :referrer, polymorphic: true\n    belongs_to :referee, p"
  },
  {
    "path": "app/models/refer/referral_code.rb",
    "chars": 570,
    "preview": "module Refer\n  class ReferralCode < ApplicationRecord\n    belongs_to :referrer, polymorphic: true\n    has_many :referral"
  },
  {
    "path": "app/models/refer/visit.rb",
    "chars": 458,
    "preview": "module Refer\n  class Visit < ApplicationRecord\n    belongs_to :referral_code, counter_cache: true\n\n    normalizes :ip, w"
  },
  {
    "path": "bin/rails",
    "chars": 547,
    "preview": "#!/usr/bin/env ruby\n# This command will automatically be run when you run \"rails\" with Rails gems\n# installed from the r"
  },
  {
    "path": "bin/rubocop",
    "chars": 266,
    "preview": "#!/usr/bin/env ruby\nrequire \"rubygems\"\nrequire \"bundler/setup\"\n\n# explicit rubocop config increases performance slightly"
  },
  {
    "path": "config/routes.rb",
    "chars": 37,
    "preview": "Rails.application.routes.draw do\nend\n"
  },
  {
    "path": "db/migrate/20240611180738_create_refer_referrals.rb",
    "chars": 305,
    "preview": "class CreateReferReferrals < ActiveRecord::Migration[6.1]\n  def change\n    create_table :refer_referrals do |t|\n      t."
  },
  {
    "path": "db/migrate/20240611183349_create_refer_referral_codes.rb",
    "chars": 279,
    "preview": "class CreateReferReferralCodes < ActiveRecord::Migration[6.1]\n  def change\n    create_table :refer_referral_codes do |t|"
  },
  {
    "path": "db/migrate/20240701172643_create_refer_visits.rb",
    "chars": 551,
    "preview": "class CreateReferVisits < ActiveRecord::Migration[6.1]\n  def change\n    create_table :refer_visits do |t|\n      t.belong"
  },
  {
    "path": "gemfiles/rails_7.1.gemfile",
    "chars": 223,
    "preview": "# This file was generated by Appraisal\n\nsource \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"sqlite3\"\ngem \"sprockets-rails\"\nge"
  },
  {
    "path": "gemfiles/rails_7.2.gemfile",
    "chars": 223,
    "preview": "# This file was generated by Appraisal\n\nsource \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"sqlite3\"\ngem \"sprockets-rails\"\nge"
  },
  {
    "path": "gemfiles/rails_8.0.gemfile",
    "chars": 223,
    "preview": "# This file was generated by Appraisal\n\nsource \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"sqlite3\"\ngem \"sprockets-rails\"\nge"
  },
  {
    "path": "gemfiles/rails_8.1.gemfile",
    "chars": 229,
    "preview": "# This file was generated by Appraisal\n\nsource \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"sqlite3\"\ngem \"sprockets-rails\"\nge"
  },
  {
    "path": "gemfiles/rails_main.gemfile",
    "chars": 234,
    "preview": "# This file was generated by Appraisal\n\nsource \"https://rubygems.org\"\n\ngem \"puma\"\ngem \"sqlite3\"\ngem \"sprockets-rails\"\nge"
  },
  {
    "path": "lib/generators/refer/install/USAGE",
    "chars": 200,
    "preview": "Description:\n    Adds Refer to ApplicationController to set referral cookies\n\nExample:\n    bin/rails generate refer:inst"
  },
  {
    "path": "lib/generators/refer/install/install_generator.rb",
    "chars": 271,
    "preview": "class Refer::InstallGenerator < Rails::Generators::Base\n  source_root File.expand_path(\"templates\", __dir__)\n\n  def add_"
  },
  {
    "path": "lib/generators/refer/model/USAGE",
    "chars": 156,
    "preview": "Description:\n    Adds Refer associations to a model\n\nExample:\n    bin/rails generate refer:model User\n\n    This will add"
  },
  {
    "path": "lib/generators/refer/model/model_generator.rb",
    "chars": 309,
    "preview": "class Refer::ModelGenerator < Rails::Generators::NamedBase\n  source_root File.expand_path(\"templates\", __dir__)\n\n  def m"
  },
  {
    "path": "lib/refer/controller.rb",
    "chars": 852,
    "preview": "module Refer\n  module Controller\n    extend ActiveSupport::Concern\n\n    class_methods do\n      def set_referral_cookie(p"
  },
  {
    "path": "lib/refer/engine.rb",
    "chars": 315,
    "preview": "module Refer\n  class Engine < ::Rails::Engine\n    isolate_namespace Refer\n\n    initializer \"refer.hooks\" do\n      Active"
  },
  {
    "path": "lib/refer/has_referrals.rb",
    "chars": 172,
    "preview": "module Refer\n  module HasReferrals\n    extend ActiveSupport::Concern\n\n    class_methods do\n      def has_referrals\n     "
  },
  {
    "path": "lib/refer/model.rb",
    "chars": 439,
    "preview": "module Refer\n  module Model\n    extend ActiveSupport::Concern\n\n    included do\n      has_many :referral_codes, as: :refe"
  },
  {
    "path": "lib/refer/version.rb",
    "chars": 37,
    "preview": "module Refer\n  VERSION = \"1.0.4\"\nend\n"
  },
  {
    "path": "lib/refer.rb",
    "chars": 1599,
    "preview": "require \"refer/version\"\nrequire \"refer/engine\"\nrequire \"securerandom\"\n\nmodule Refer\n  autoload :Controller, \"refer/contr"
  },
  {
    "path": "lib/tasks/refer_tasks.rake",
    "chars": 83,
    "preview": "# desc \"Explaining what the task does\"\n# task :refer do\n#   # Task goes here\n# end\n"
  },
  {
    "path": "refer.gemspec",
    "chars": 822,
    "preview": "require_relative \"lib/refer/version\"\n\nGem::Specification.new do |spec|\n  spec.name        = \"refer\"\n  spec.version     ="
  },
  {
    "path": "test/dummy/Rakefile",
    "chars": 227,
    "preview": "# Add your own tasks in files placed in lib/tasks ending in .rake,\n# for example lib/tasks/capistrano.rake, and they wil"
  },
  {
    "path": "test/dummy/app/assets/config/manifest.js",
    "chars": 63,
    "preview": "//= link_tree ../images\n//= link_directory ../stylesheets .css\n"
  },
  {
    "path": "test/dummy/app/assets/images/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/dummy/app/assets/stylesheets/application.css",
    "chars": 736,
    "preview": "/*\n * This is a manifest file that'll be compiled into application.css, which will include all the files\n * listed below"
  },
  {
    "path": "test/dummy/app/channels/application_cable/channel.rb",
    "chars": 79,
    "preview": "module ApplicationCable\n  class Channel < ActionCable::Channel::Base\n  end\nend\n"
  },
  {
    "path": "test/dummy/app/channels/application_cable/connection.rb",
    "chars": 85,
    "preview": "module ApplicationCable\n  class Connection < ActionCable::Connection::Base\n  end\nend\n"
  },
  {
    "path": "test/dummy/app/controllers/application_controller.rb",
    "chars": 57,
    "preview": "class ApplicationController < ActionController::Base\nend\n"
  },
  {
    "path": "test/dummy/app/controllers/concerns/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/dummy/app/controllers/referrals_controller.rb",
    "chars": 274,
    "preview": "class ReferralsController < ApplicationController\n  set_referral_cookie\n  before_action :set_user, only: [ :create ]\n\n  "
  },
  {
    "path": "test/dummy/app/helpers/application_helper.rb",
    "chars": 29,
    "preview": "module ApplicationHelper\nend\n"
  },
  {
    "path": "test/dummy/app/jobs/application_job.rb",
    "chars": 269,
    "preview": "class ApplicationJob < ActiveJob::Base\n  # Automatically retry jobs that encountered a deadlock\n  # retry_on ActiveRecor"
  },
  {
    "path": "test/dummy/app/mailers/application_mailer.rb",
    "chars": 102,
    "preview": "class ApplicationMailer < ActionMailer::Base\n  default from: \"from@example.com\"\n  layout \"mailer\"\nend\n"
  },
  {
    "path": "test/dummy/app/models/application_record.rb",
    "chars": 74,
    "preview": "class ApplicationRecord < ActiveRecord::Base\n  primary_abstract_class\nend\n"
  },
  {
    "path": "test/dummy/app/models/concerns/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/dummy/app/models/user.rb",
    "chars": 51,
    "preview": "class User < ApplicationRecord\n  has_referrals\nend\n"
  },
  {
    "path": "test/dummy/app/views/layouts/application.html.erb",
    "chars": 612,
    "preview": "<!DOCTYPE html>\n<html>\n  <head>\n    <title><%= content_for(:title) || \"Dummy\" %></title>\n    <meta name=\"viewport\" conte"
  },
  {
    "path": "test/dummy/app/views/layouts/mailer.html.erb",
    "chars": 227,
    "preview": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n    <style>\n    "
  },
  {
    "path": "test/dummy/app/views/layouts/mailer.text.erb",
    "chars": 13,
    "preview": "<%= yield %>\n"
  },
  {
    "path": "test/dummy/app/views/pwa/manifest.json.erb",
    "chars": 393,
    "preview": "{\n  \"name\": \"Dummy\",\n  \"icons\": [\n    {\n      \"src\": \"/icon.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"512x512\"\n  "
  },
  {
    "path": "test/dummy/app/views/pwa/service-worker.js",
    "chars": 879,
    "preview": "// Add a service worker for processing Web Push notifications:\n//\n// self.addEventListener(\"push\", async (event) => {\n//"
  },
  {
    "path": "test/dummy/bin/rails",
    "chars": 141,
    "preview": "#!/usr/bin/env ruby\nAPP_PATH = File.expand_path(\"../config/application\", __dir__)\nrequire_relative \"../config/boot\"\nrequ"
  },
  {
    "path": "test/dummy/bin/rake",
    "chars": 90,
    "preview": "#!/usr/bin/env ruby\nrequire_relative \"../config/boot\"\nrequire \"rake\"\nRake.application.run\n"
  },
  {
    "path": "test/dummy/bin/setup",
    "chars": 1130,
    "preview": "#!/usr/bin/env ruby\nrequire \"fileutils\"\n\nAPP_ROOT = File.expand_path(\"..\", __dir__)\nAPP_NAME = \"dummy\"\n\ndef system!(*arg"
  },
  {
    "path": "test/dummy/config/application.rb",
    "chars": 1054,
    "preview": "require_relative \"boot\"\n\nrequire \"rails/all\"\n\n# Require the gems listed in Gemfile, including any gems\n# you've limited "
  },
  {
    "path": "test/dummy/config/boot.rb",
    "chars": 233,
    "preview": "# Set up gems listed in the Gemfile.\nENV[\"BUNDLE_GEMFILE\"] ||= File.expand_path(\"../../../Gemfile\", __dir__)\n\nrequire \"b"
  },
  {
    "path": "test/dummy/config/cable.yml",
    "chars": 186,
    "preview": "development:\n  adapter: async\n\ntest:\n  adapter: test\n\nproduction:\n  adapter: redis\n  url: <%= ENV.fetch(\"REDIS_URL\") { \""
  },
  {
    "path": "test/dummy/config/database.yml",
    "chars": 992,
    "preview": "# SQLite. Versions 3.8.0 and up are supported.\n#   gem install sqlite3\n#\n#   Ensure the SQLite 3 gem is defined in your "
  },
  {
    "path": "test/dummy/config/environment.rb",
    "chars": 128,
    "preview": "# Load the Rails application.\nrequire_relative \"application\"\n\n# Initialize the Rails application.\nRails.application.init"
  },
  {
    "path": "test/dummy/config/environments/development.rb",
    "chars": 2742,
    "preview": "require \"active_support/core_ext/integer/time\"\n\nRails.application.configure do\n  # Settings specified here will take pre"
  },
  {
    "path": "test/dummy/config/environments/production.rb",
    "chars": 4451,
    "preview": "require \"active_support/core_ext/integer/time\"\n\nRails.application.configure do\n  # Settings specified here will take pre"
  },
  {
    "path": "test/dummy/config/environments/test.rb",
    "chars": 2825,
    "preview": "require \"active_support/core_ext/integer/time\"\n\n# The test environment is used exclusively to run your application's\n# t"
  },
  {
    "path": "test/dummy/config/initializers/assets.rb",
    "chars": 502,
    "preview": "# Be sure to restart your server when you modify this file.\n\n# Version of your assets, change this if you want to expire"
  },
  {
    "path": "test/dummy/config/initializers/content_security_policy.rb",
    "chars": 1071,
    "preview": "# Be sure to restart your server when you modify this file.\n\n# Define an application-wide content security policy.\n# See"
  },
  {
    "path": "test/dummy/config/initializers/filter_parameter_logging.rb",
    "chars": 456,
    "preview": "# Be sure to restart your server when you modify this file.\n\n# Configure parameters to be partially matched (e.g. passw "
  },
  {
    "path": "test/dummy/config/initializers/inflections.rb",
    "chars": 649,
    "preview": "# Be sure to restart your server when you modify this file.\n\n# Add new inflection rules using the following format. Infl"
  },
  {
    "path": "test/dummy/config/initializers/permissions_policy.rb",
    "chars": 480,
    "preview": "# Be sure to restart your server when you modify this file.\n\n# Define an application-wide HTTP permissions policy. For f"
  },
  {
    "path": "test/dummy/config/locales/en.yml",
    "chars": 908,
    "preview": "# Files in the config/locales directory are used for internationalization and\n# are automatically loaded by Rails. If yo"
  },
  {
    "path": "test/dummy/config/puma.rb",
    "chars": 2304,
    "preview": "# This configuration file will be evaluated by Puma. The top-level methods that\n# are invoked here are part of Puma's co"
  },
  {
    "path": "test/dummy/config/routes.rb",
    "chars": 672,
    "preview": "Rails.application.routes.draw do\n  # Define your application routes per the DSL in https://guides.rubyonrails.org/routin"
  },
  {
    "path": "test/dummy/config/storage.yml",
    "chars": 1152,
    "preview": "test:\n  service: Disk\n  root: <%= Rails.root.join(\"tmp/storage\") %>\n\nlocal:\n  service: Disk\n  root: <%= Rails.root.join("
  },
  {
    "path": "test/dummy/config.ru",
    "chars": 160,
    "preview": "# This file is used by Rack-based servers to start the application.\n\nrequire_relative \"config/environment\"\n\nrun Rails.ap"
  },
  {
    "path": "test/dummy/db/migrate/20240611180748_create_users.rb",
    "chars": 152,
    "preview": "class CreateUsers < ActiveRecord::Migration[7.2]\n  def change\n    create_table :users do |t|\n      t.string :name\n\n     "
  },
  {
    "path": "test/dummy/db/schema.rb",
    "chars": 2551,
    "preview": "# This file is auto-generated from the current state of the database. Instead\n# of editing this file, please use the mig"
  },
  {
    "path": "test/dummy/lib/assets/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/dummy/log/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/dummy/public/404.html",
    "chars": 1722,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The page you were looking for doesn't exist (404)</title>\n  <meta name=\"viewport\""
  },
  {
    "path": "test/dummy/public/406-unsupported-browser.html",
    "chars": 1612,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n  <title>Your browser is not supported (406)</title>\n  <meta name=\"viewport\" content=\"widt"
  },
  {
    "path": "test/dummy/public/422.html",
    "chars": 1705,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n  <title>The change you wanted was rejected (422)</title>\n  <meta name=\"viewport\" content="
  },
  {
    "path": "test/dummy/public/500.html",
    "chars": 1635,
    "preview": "<!DOCTYPE html>\n<html>\n<head>\n  <title>We're sorry, but something went wrong (500)</title>\n  <meta name=\"viewport\" conte"
  },
  {
    "path": "test/fixtures/files/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/fixtures/refer/referral_codes.yml",
    "chars": 174,
    "preview": "# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\none:\n  referrer: one (User)\n "
  },
  {
    "path": "test/fixtures/refer/referrals.yml",
    "chars": 162,
    "preview": "# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\none:\n  referrer: one (User)\n "
  },
  {
    "path": "test/fixtures/refer/visits.yml",
    "chars": 312,
    "preview": "# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\none:\n  referral_code: one\n  i"
  },
  {
    "path": "test/fixtures/users.yml",
    "chars": 148,
    "preview": "# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html\n\none:\n  name: Chris\n\ntwo:\n  na"
  },
  {
    "path": "test/integration/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/integration/referral_test.rb",
    "chars": 790,
    "preview": "require \"test_helper\"\n\nclass ReferralIntegrationTest < ActionDispatch::IntegrationTest\n  test \"referral is created\" do\n "
  },
  {
    "path": "test/models/.keep",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "test/models/refer/referral_code_test.rb",
    "chars": 1266,
    "preview": "require \"test_helper\"\nrequire \"minitest/mock\"\n\n\nclass Refer::ReferralCodeTest < ActiveSupport::TestCase\n  test \"deleting"
  },
  {
    "path": "test/models/refer/referral_test.rb",
    "chars": 1157,
    "preview": "require \"test_helper\"\n\nclass Refer::ReferralTest < ActiveSupport::TestCase\n  test \"referrals are dependent destroyed\" do"
  },
  {
    "path": "test/models/refer/visit_test.rb",
    "chars": 417,
    "preview": "require \"test_helper\"\n\nmodule Refer\n  class VisitTest < ActiveSupport::TestCase\n    test \"masks ips\" do\n      assert_equ"
  },
  {
    "path": "test/refer_test.rb",
    "chars": 2261,
    "preview": "require \"test_helper\"\n\nclass ReferTest < ActiveSupport::TestCase\n  test \"it has a version number\" do\n    assert Refer::V"
  },
  {
    "path": "test/test_helper.rb",
    "chars": 635,
    "preview": "# Configure Rails Environment\nENV[\"RAILS_ENV\"] = \"test\"\n\nrequire_relative \"../test/dummy/config/environment\"\nActiveRecor"
  }
]

About this extraction

This page contains the full source code of the excid3/refer GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 107 files (66.9 KB), approximately 20.9k tokens, and a symbol index with 69 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!