├── .rspec ├── logo.png ├── lib ├── safe_polymorphic │ ├── version.rb │ ├── locales │ │ └── en.yml │ └── associations.rb └── safe_polymorphic.rb ├── spec ├── support │ ├── models │ │ ├── user.rb │ │ ├── publisher.rb │ │ ├── other_thing.rb │ │ └── book.rb │ ├── models.rb │ └── schema.rb ├── safe_polymorphic │ ├── version_spec.rb │ └── associations_spec.rb └── spec_helper.rb ├── bin ├── setup └── console ├── .gitignore ├── Rakefile ├── .rubocop.yml ├── Gemfile ├── CHANGELOG.md ├── .github └── workflows │ └── main.yml ├── LICENSE.md ├── safe_polymorphic.gemspec ├── Gemfile.lock ├── README.md ├── CODE_OF_CONDUCT.md └── gogrow_logo.svg /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | --require spec_helper 4 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gogrow-dev/safe_polymorphic/HEAD/logo.png -------------------------------------------------------------------------------- /lib/safe_polymorphic/version.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module SafePolymorphic 4 | VERSION = '0.1.3' 5 | end 6 | -------------------------------------------------------------------------------- /spec/support/models/user.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class User < ActiveRecord::Base 4 | validates :username, presence: true 5 | end 6 | -------------------------------------------------------------------------------- /spec/support/models/publisher.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Publisher < ActiveRecord::Base 4 | validates :name, presence: true 5 | end 6 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | 8 | # Do any other automated setup that you need to do here 9 | -------------------------------------------------------------------------------- /lib/safe_polymorphic/locales/en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | safe_polymorphic: 3 | errors: 4 | messages: 5 | class_not_allowed: "%{class} is not an allowed class" 6 | -------------------------------------------------------------------------------- /spec/support/models/other_thing.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class OtherThing < ActiveRecord::Base 4 | belongs_to :thing, polymorphic: ['user', :publisher], optional: true 5 | end 6 | -------------------------------------------------------------------------------- /spec/support/models.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'models/user' 4 | require_relative 'models/publisher' 5 | require_relative 'models/book' 6 | require_relative 'models/other_thing' 7 | -------------------------------------------------------------------------------- /spec/support/models/book.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | class Book < ActiveRecord::Base 4 | validates :title, presence: true 5 | 6 | belongs_to :owner, polymorphic: [Publisher, User] 7 | end 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /_yardoc/ 4 | /coverage/ 5 | /doc/ 6 | /pkg/ 7 | /spec/reports/ 8 | /tmp/ 9 | 10 | # rspec failure tracking 11 | .rspec_status 12 | 13 | # Mac OS X 14 | .DS_Store 15 | -------------------------------------------------------------------------------- /spec/safe_polymorphic/version_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.describe SafePolymorphic::VERSION do 4 | it 'has a version number' do 5 | expect(SafePolymorphic::VERSION).not_to be nil 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'bundler/gem_tasks' 4 | require 'rspec/core/rake_task' 5 | 6 | RSpec::Core::RakeTask.new(:spec) 7 | 8 | require 'rubocop/rake_task' 9 | 10 | RuboCop::RakeTask.new 11 | 12 | task default: %i[spec rubocop] 13 | -------------------------------------------------------------------------------- /.rubocop.yml: -------------------------------------------------------------------------------- 1 | AllCops: 2 | TargetRubyVersion: 2.6 3 | NewCops: disable 4 | 5 | Style/Documentation: 6 | Enabled: false 7 | 8 | Metrics/BlockLength: 9 | Exclude: 10 | - "spec/**/*" 11 | 12 | Style/StringLiterals: 13 | Enabled: true 14 | EnforcedStyle: single_quotes 15 | 16 | Style/StringLiteralsInInterpolation: 17 | Enabled: true 18 | EnforcedStyle: double_quotes 19 | 20 | Layout/LineLength: 21 | Max: 120 -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # frozen_string_literal: true 3 | 4 | require 'bundler/setup' 5 | require 'safe_polymorphic' 6 | 7 | # You can add fixtures and/or initialization code here to make experimenting 8 | # with your gem easier. You can also use a different console, if you like. 9 | 10 | # (If you use this, don't forget to add pry to your Gemfile!) 11 | # require "pry" 12 | # Pry.start 13 | 14 | require 'irb' 15 | IRB.start(__FILE__) 16 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | source 'https://rubygems.org' 4 | 5 | # Specify your gem's dependencies in safe_polymorphic.gemspec 6 | gemspec 7 | 8 | gem 'database_cleaner-active_record', '~> 1.8.0', require: false, group: :test 9 | gem 'rake', '~> 13.0' 10 | gem 'rspec', '~> 3.0' 11 | gem 'rubocop', '~> 1.21' 12 | gem 'simplecov', '~> 0.17.1', require: false, group: :test 13 | gem 'sqlite3', '~> 1.4.2', require: false, group: :test 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [Unreleased] 2 | 3 | ## [0.1.0] - 2022-12-28 4 | 5 | - Initial release 6 | - Moved from [Belongs to Polymorphic](https://rubygems.org/gems/belongs_to_polymorphic) 7 | 8 | ## [0.1.1] - 2022-12-28 9 | 10 | - Fix finder method bug when searching using an instance of a class 11 | 12 | ## [0.1.2] - 2022-12-28 13 | 14 | - Fix issue that forced to declare the I18n locale (`class_not_allowed`) in each project using this gem instead of using the default locale included in the gem -------------------------------------------------------------------------------- /lib/safe_polymorphic.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'safe_polymorphic/version' 4 | require 'active_record' 5 | require_relative 'safe_polymorphic/associations' 6 | 7 | module SafePolymorphic 8 | class Error < StandardError; end 9 | end 10 | 11 | ActiveSupport.on_load(:i18n) do 12 | I18n.load_path << File.expand_path('safe_polymorphic/locales/en.yml', __dir__) 13 | end 14 | 15 | # Extend ActiveRecord::Base with belongs to polymorphic associations 16 | ActiveRecord::Base.include SafePolymorphic::Associations 17 | -------------------------------------------------------------------------------- /spec/support/schema.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | ActiveRecord::Schema.define do 4 | self.verbose = false 5 | 6 | create_table :books, force: true do |t| 7 | t.string :title 8 | t.integer :owner_id 9 | t.string :owner_type 10 | 11 | t.timestamps 12 | end 13 | 14 | create_table :publishers, force: true do |t| 15 | t.string :name 16 | 17 | t.timestamps 18 | end 19 | 20 | create_table :users, force: true do |t| 21 | t.string :username 22 | 23 | t.timestamps 24 | end 25 | 26 | create_table :other_things, force: true do |t| 27 | t.integer :thing_id 28 | t.string :thing_type 29 | 30 | t.timestamps 31 | end 32 | end 33 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Ruby 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | pull_request: 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | name: Ruby ${{ matrix.ruby }} 14 | strategy: 15 | matrix: 16 | ruby: 17 | - "2.6" 18 | - "2.7" 19 | - "3.0" 20 | - "3.1" 21 | 22 | steps: 23 | - uses: actions/checkout@v2 24 | - name: Set up Ruby 25 | uses: ruby/setup-ruby@v1 26 | with: 27 | ruby-version: ${{ matrix.ruby }} 28 | bundler-cache: true 29 | - name: Lint with rubocop 30 | run: bundle exec rubocop --parallel 31 | - name: Test & Publish code coverage 32 | uses: paambaati/codeclimate-action@v3.1.1 33 | env: 34 | CC_TEST_REPORTER_ID: ${{secrets.CC_TEST_REPORTER_ID}} 35 | with: 36 | coverageCommand: bundle exec rspec 37 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require 'simplecov' 4 | require 'active_record' 5 | require 'database_cleaner/active_record' 6 | 7 | ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:' 8 | 9 | SimpleCov.start do 10 | track_files '/lib/**/*.rb' 11 | add_filter '/spec/' 12 | end 13 | 14 | require 'safe_polymorphic' 15 | load "#{File.dirname(__FILE__)}/support/schema.rb" 16 | require "#{File.dirname(__FILE__)}/support/models.rb" 17 | 18 | RSpec.configure do |config| 19 | # Enable flags like --only-failures and --next-failure 20 | config.example_status_persistence_file_path = '.rspec_status' 21 | 22 | # Disable RSpec exposing methods globally on `Module` and `main` 23 | config.disable_monkey_patching! 24 | 25 | config.expect_with :rspec do |c| 26 | c.syntax = :expect 27 | end 28 | 29 | config.before(:suite) do 30 | DatabaseCleaner.strategy = :transaction 31 | DatabaseCleaner.clean_with(:truncation) 32 | end 33 | 34 | config.around(:each) do |example| 35 | DatabaseCleaner.cleaning do 36 | example.run 37 | end 38 | end 39 | end 40 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2022 Nicolas Erlichman, GoGrow 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /safe_polymorphic.gemspec: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require_relative 'lib/safe_polymorphic/version' 4 | 5 | Gem::Specification.new do |spec| 6 | spec.name = 'safe_polymorphic' 7 | spec.version = SafePolymorphic::VERSION 8 | spec.licenses = ['MIT'] 9 | spec.authors = ['Nicolas Erlichman'] 10 | spec.email = ['nicolas@gogrow.dev'] 11 | 12 | spec.summary = 'Safely use polymorphic associations by validating which classes are allowed to be related to.' 13 | spec.description = 'ActiveRecord extension which allows us to safely use polymorphic associations, by validating' \ 14 | 'which classes are allowed to be related to, while also adding scopes and helper methods.' 15 | spec.homepage = 'https://github.com/gogrow-dev/safe_polymorphic' 16 | spec.required_ruby_version = '>= 2.6.0' 17 | 18 | spec.metadata['homepage_uri'] = spec.homepage 19 | spec.metadata['source_code_uri'] = spec.homepage 20 | spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md" 21 | spec.metadata['rubygems_mfa_required'] = 'true' 22 | 23 | # Specify which files should be added to the gem when it is released. 24 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 25 | spec.files = Dir.chdir(__dir__) do 26 | `git ls-files -z`.split("\x0").reject do |f| 27 | (f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|circleci)|appveyor)}) 28 | end 29 | end 30 | spec.bindir = 'exe' 31 | spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } 32 | spec.require_paths = ['lib'] 33 | 34 | spec.add_dependency 'activerecord', '>= 5.2', '< 8.0' 35 | end 36 | -------------------------------------------------------------------------------- /Gemfile.lock: -------------------------------------------------------------------------------- 1 | PATH 2 | remote: . 3 | specs: 4 | safe_polymorphic (0.1.3) 5 | activerecord (>= 5.2, < 8.0) 6 | 7 | GEM 8 | remote: https://rubygems.org/ 9 | specs: 10 | activemodel (6.1.4.1) 11 | activesupport (= 6.1.4.1) 12 | activerecord (6.1.4.1) 13 | activemodel (= 6.1.4.1) 14 | activesupport (= 6.1.4.1) 15 | activesupport (6.1.4.1) 16 | concurrent-ruby (~> 1.0, >= 1.0.2) 17 | i18n (>= 1.6, < 2) 18 | minitest (>= 5.1) 19 | tzinfo (~> 2.0) 20 | zeitwerk (~> 2.3) 21 | ast (2.4.2) 22 | concurrent-ruby (1.1.10) 23 | database_cleaner (1.8.5) 24 | database_cleaner-active_record (1.8.0) 25 | activerecord 26 | database_cleaner (~> 1.8.0) 27 | diff-lcs (1.5.0) 28 | docile (1.4.0) 29 | i18n (1.12.0) 30 | concurrent-ruby (~> 1.0) 31 | json (2.6.3) 32 | minitest (5.16.3) 33 | parallel (1.22.1) 34 | parser (3.1.3.0) 35 | ast (~> 2.4.1) 36 | rainbow (3.1.1) 37 | rake (13.0.6) 38 | regexp_parser (2.6.1) 39 | rexml (3.2.5) 40 | rspec (3.12.0) 41 | rspec-core (~> 3.12.0) 42 | rspec-expectations (~> 3.12.0) 43 | rspec-mocks (~> 3.12.0) 44 | rspec-core (3.12.0) 45 | rspec-support (~> 3.12.0) 46 | rspec-expectations (3.12.1) 47 | diff-lcs (>= 1.2.0, < 2.0) 48 | rspec-support (~> 3.12.0) 49 | rspec-mocks (3.12.1) 50 | diff-lcs (>= 1.2.0, < 2.0) 51 | rspec-support (~> 3.12.0) 52 | rspec-support (3.12.0) 53 | rubocop (1.41.1) 54 | json (~> 2.3) 55 | parallel (~> 1.10) 56 | parser (>= 3.1.2.1) 57 | rainbow (>= 2.2.2, < 4.0) 58 | regexp_parser (>= 1.8, < 3.0) 59 | rexml (>= 3.2.5, < 4.0) 60 | rubocop-ast (>= 1.23.0, < 2.0) 61 | ruby-progressbar (~> 1.7) 62 | unicode-display_width (>= 1.4.0, < 3.0) 63 | rubocop-ast (1.24.0) 64 | parser (>= 3.1.1.0) 65 | ruby-progressbar (1.11.0) 66 | simplecov (0.17.1) 67 | docile (~> 1.1) 68 | json (>= 1.8, < 3) 69 | simplecov-html (~> 0.10.0) 70 | simplecov-html (0.10.2) 71 | sqlite3 (1.4.4) 72 | tzinfo (2.0.5) 73 | concurrent-ruby (~> 1.0) 74 | unicode-display_width (2.3.0) 75 | zeitwerk (2.6.0) 76 | 77 | PLATFORMS 78 | arm64-darwin-21 79 | arm64-darwin-23 80 | x86_64-linux 81 | 82 | DEPENDENCIES 83 | database_cleaner-active_record (~> 1.8.0) 84 | rake (~> 13.0) 85 | rspec (~> 3.0) 86 | rubocop (~> 1.21) 87 | safe_polymorphic! 88 | simplecov (~> 0.17.1) 89 | sqlite3 (~> 1.4.2) 90 | 91 | BUNDLED WITH 92 | 2.4.1 93 | -------------------------------------------------------------------------------- /lib/safe_polymorphic/associations.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | module SafePolymorphic 4 | module Associations 5 | def self.included(base) 6 | base.extend ClassMethods 7 | class << base 8 | alias_method :unsafe_polymorphic, :belongs_to 9 | alias_method :belongs_to, :safe_polymorphic 10 | end 11 | end 12 | 13 | module ClassMethods 14 | def safe_polymorphic(name, **options) 15 | unsafe_polymorphic name, **options 16 | polymorphic = options[:polymorphic] 17 | 18 | return unless polymorphic.present? && polymorphic.class != TrueClass 19 | 20 | allowed_classes = classify(polymorphic) 21 | 22 | validates "#{name}_type", inclusion: inclusion_validation(allowed_classes, options[:optional]) 23 | 24 | define_singleton_method("#{name}_types") { allowed_classes } 25 | define_generic_finder_method(name) 26 | define_scopes_and_instance_methods(name, allowed_classes) 27 | end 28 | 29 | private 30 | 31 | def inclusion_validation(allowed_classes, optional) 32 | { 33 | in: inclusion_classes(allowed_classes, optional), 34 | message: I18n.t('safe_polymorphic.errors.messages.class_not_allowed', 35 | class: '%s') 36 | } 37 | end 38 | 39 | def classify(classes) 40 | Array.wrap(classes).map do |klass| 41 | case klass 42 | when Class then klass 43 | else constantize(klass) 44 | end 45 | end 46 | end 47 | 48 | def constantize(klass) 49 | const_class = case klass 50 | when String then klass 51 | when Symbol then klass.to_s 52 | else klass.class.name 53 | end 54 | const_class.classify.constantize 55 | end 56 | 57 | def inclusion_classes(allowed_classes, optional) 58 | classes = allowed_classes.map(&:name) 59 | classes << nil if optional.present? 60 | classes 61 | end 62 | 63 | # Generates a generic finder method 64 | def define_generic_finder_method(name) 65 | define_singleton_method("with_#{name}") do |type| 66 | type = constantize(type) unless type.is_a?(Class) 67 | where("#{name}_type" => type.name) 68 | end 69 | end 70 | 71 | def define_scopes_and_instance_methods(name, allowed_classes) 72 | allowed_classes.each do |model| 73 | model_name = model.name 74 | model_name_sanitized = model_name.underscore.tr('/', '_') 75 | # generates scope for each allowed class 76 | scope "with_#{name}_#{model_name_sanitized}", 77 | -> { where("#{name}_type" => model_name) } 78 | 79 | # generates instance method for each allowed class to check if type is that class 80 | define_method("#{name}_type_#{model_name_sanitized}?") do 81 | public_send("#{name}_type") == model_name 82 | end 83 | end 84 | end 85 | end 86 | end 87 | end 88 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Gem Version](https://badge.fury.io/rb/safe_polymorphic.svg)](https://badge.fury.io/rb/safe_polymorphic.svg) 2 | [![Ruby](https://github.com/gogrow-dev/safe_polymorphic/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/gogrow-dev/safe_polymorphic/actions/workflows/main.yml) 3 | [![Maintainability](https://api.codeclimate.com/v1/badges/1b0a4b92bbee2be50dc1/maintainability)](https://codeclimate.com/github/gogrow-dev/safe_polymorphic/maintainability) 4 | [![Test Coverage](https://api.codeclimate.com/v1/badges/1b0a4b92bbee2be50dc1/test_coverage)](https://codeclimate.com/github/gogrow-dev/safe_polymorphic/test_coverage) 5 | 6 | # SafePolymorphic 7 | 8 | > The best way to keep your polymorphic relationships safe. 9 | 10 | 11 | 12 | An ActiveRecord extension for polymorphic associations. 13 | 14 | * **Simple.** It is as easy to use as it is to update. 15 | * **Safe.** It helps you avoid unintended usage of polymorphic classes. 16 | * **Powerful.** It packages some helpful scopes and helper methods. 17 | 18 | 19 | Built by GoGrow 20 | 21 | 22 | > Credits: [Improve ActiveRecord Polymorphic Associations](https://blog.rstankov.com/allowed-class-names-in-activerecord-polymorphic-associations/). 23 | 24 | ## Install 25 | 26 | Install the gem and add to the application's Gemfile by executing: 27 | 28 | $ bundle add safe_polymorphic 29 | 30 | If bundler is not being used to manage dependencies, install the gem by executing: 31 | 32 | $ gem install safe_polymorphic 33 | 34 | ## Usage 35 | 36 | In your model you can do the following: 37 | 38 | ```ruby 39 | class Address < ActiveRecord::Base 40 | belongs_to :addressabel, polymorphic: [User, Company] 41 | end 42 | ``` 43 | 44 | Define a `belongs_to` relatinoship and instead of just adding the option `polymorphic: true`, we are able to specify the allowed polymorphic classes. 45 | 46 | By using this, we will create a polymorphic relationship in `Address` called `addressable` which can only be a `User` or a `Company`. 47 | If we try to set an `addressable` from a class rather than the aforementioend ones, it will return the following error: 48 | ```ruby 49 | #ActiveRecord::RecordInvalid: Validation failed: Addressable type OtherThing class is not an allowed class. 50 | ``` 51 | 52 | We can also use strings and symbols instead of the classes themselves: 53 | ```ruby 54 | class Address < ActiveRecord::Base 55 | belongs_to :addressable, polymorphic: [:user, 'Company'] 56 | end 57 | ``` 58 | Provided that the strings and symbols translate to existing classes when used with `.classify.constantize`. 59 | 60 | ### Usage with namespaced models 61 | 62 | ```ruby 63 | class Address < ActiveRecord::Base 64 | belongs_to :addressable, polymorphic: [Company::User, Company] 65 | end 66 | ``` 67 | 68 | ### Helper methods 69 | 70 | Class methods: 71 | - `Address.addressable_types`: returns the allowed classes 72 | - `Address.with_addressable(#{type})`: generic finder method 73 | - `Address.with_addressable_#{allowed_class_name}`: scope for each allowed class 74 | 75 | Instance methods: 76 | - `Address.addressable_type_#{allowed_class_name}?`: check if it is from that specific class 77 | 78 | ### Helper methods with namespaced models 79 | 80 | Class methods: 81 | - `Address.with_addressable(Company::User)` 82 | - `Address.with_addressable_company_user` 83 | - `Address.addressable_type_company_user?` 84 | 85 | ## I18n 86 | 87 | Safe Polymoprhic uses I18n to define the not allowed class error. To customize it, you can set up your locale file: 88 | 89 | ```yaml 90 | en: 91 | safe_polymoprhic: 92 | errors: 93 | messages: 94 | class_not_allowed: "%{class} is not an allowed class" 95 | ``` 96 | 97 | ## Development 98 | 99 | After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment. 100 | 101 | To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org). 102 | 103 | ## Contributing 104 | 105 | Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](./CODE_OF_CONDUCT.md). 106 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to a positive environment for our community include: 12 | 13 | * Demonstrating empathy and kindness toward other people 14 | * Being respectful of differing opinions, viewpoints, and experiences 15 | * Giving and gracefully accepting constructive feedback 16 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 17 | * Focusing on what is best not just for us as individuals, but for the overall community 18 | 19 | Examples of unacceptable behavior include: 20 | 21 | * The use of sexualized language or imagery, and sexual attention or 22 | advances of any kind 23 | * Trolling, insulting or derogatory comments, and personal or political attacks 24 | * Public or private harassment 25 | * Publishing others' private information, such as a physical or email 26 | address, without their explicit permission 27 | * Other conduct which could reasonably be considered inappropriate in a 28 | professional setting 29 | 30 | ## Enforcement Responsibilities 31 | 32 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 33 | 34 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 35 | 36 | ## Scope 37 | 38 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 39 | 40 | ## Enforcement 41 | 42 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at nicolas@gogrow.dev. All complaints will be reviewed and investigated promptly and fairly. 43 | 44 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 45 | 46 | ## Enforcement Guidelines 47 | 48 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 49 | 50 | ### 1. Correction 51 | 52 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 53 | 54 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 55 | 56 | ### 2. Warning 57 | 58 | **Community Impact**: A violation through a single incident or series of actions. 59 | 60 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 61 | 62 | ### 3. Temporary Ban 63 | 64 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 65 | 66 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 67 | 68 | ### 4. Permanent Ban 69 | 70 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 71 | 72 | **Consequence**: A permanent ban from any sort of public interaction within the community. 73 | 74 | ## Attribution 75 | 76 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 77 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 78 | 79 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 80 | 81 | [homepage]: https://www.contributor-covenant.org 82 | 83 | For answers to common questions about this code of conduct, see the FAQ at 84 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 85 | -------------------------------------------------------------------------------- /spec/safe_polymorphic/associations_spec.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | RSpec.describe 'Safe Polymorphic Associations' do 4 | before do 5 | User.create(username: 'username') 6 | Publisher.create(name: 'Publisher') 7 | OtherThing.create 8 | end 9 | 10 | describe '#allowed_classes' do 11 | context 'when using classes' do 12 | context 'when the owner is a User' do 13 | it 'should be able to create a Book' do 14 | book = Book.create(title: 'Book', owner: User.first) 15 | expect(book.owner_type).to eq('User') 16 | end 17 | end 18 | 19 | context 'when the owner is a Publisher' do 20 | it 'should be able to create a Book' do 21 | book = Book.create(title: 'Book', owner: Publisher.first) 22 | expect(book.owner_type).to eq('Publisher') 23 | end 24 | end 25 | 26 | context 'when the owner is a OtherThing' do 27 | subject { Book.create(title: 'Book', owner: OtherThing.first) } 28 | 29 | it 'should not be able to create a Book' do 30 | expect(subject).to_not be_valid 31 | end 32 | 33 | it 'should have an error message' do 34 | subject.valid? 35 | expect(subject.errors[:owner_type]).to include('OtherThing is not an allowed class') 36 | end 37 | end 38 | end 39 | 40 | context 'when using strings or symbols' do 41 | context 'when the owner is a User' do 42 | it 'should be able to create a OtherThing' do 43 | other_thing = OtherThing.create(thing: User.first) 44 | expect(other_thing.thing_type).to eq('User') 45 | end 46 | end 47 | 48 | context 'when the owner is a Publisher' do 49 | it 'should be able to create a OtherThing' do 50 | other_thing = OtherThing.create(thing: Publisher.first) 51 | expect(other_thing.thing_type).to eq('Publisher') 52 | end 53 | end 54 | 55 | context 'when the owner is a Book' do 56 | before do 57 | Book.create(title: 'Book', owner: User.first) 58 | end 59 | 60 | subject { OtherThing.create(thing: Book.first) } 61 | 62 | it 'should not be able to create a OtherThing' do 63 | expect(subject).to_not be_valid 64 | end 65 | 66 | it 'should have an error message' do 67 | subject.valid? 68 | expect(subject.errors[:thing_type]).to include('Book is not an allowed class') 69 | end 70 | end 71 | end 72 | 73 | context 'when it is optional' do 74 | it 'should be able to create a OtherThing' do 75 | other_thing = OtherThing.create 76 | expect(other_thing.thing_type).to eq(nil) 77 | end 78 | end 79 | end 80 | 81 | describe '#allowed_types' do 82 | context 'when using classes' do 83 | it 'should return the allowed types' do 84 | expect(Book.owner_types).to match_array([User, Publisher]) 85 | end 86 | end 87 | 88 | context 'when using strings or symbols' do 89 | it 'should return the allowed types' do 90 | expect(OtherThing.thing_types).to match_array([User, Publisher]) 91 | end 92 | end 93 | end 94 | 95 | context 'with existing books' do 96 | let!(:user_book) { Book.create(title: 'User Book', owner: User.first) } 97 | let!(:publisher_book) { Book.create(title: 'Publisher Book', owner: Publisher.first) } 98 | 99 | describe '#finder_methods' do 100 | context 'when searching by class' do 101 | it 'should return the books with the given owner type count' do 102 | expect(Book.with_owner(User).count).to eq(1) 103 | expect(Book.with_owner(Publisher).count).to eq(1) 104 | end 105 | 106 | it 'should return the books with the given owner type' do 107 | expect(Book.with_owner(User).first).to eq(user_book) 108 | expect(Book.with_owner(Publisher).first).to eq(publisher_book) 109 | end 110 | end 111 | 112 | context 'when searching by string' do 113 | it 'should return the books with the given owner type count' do 114 | expect(Book.with_owner('User').count).to eq(1) 115 | expect(Book.with_owner('Publisher').count).to eq(1) 116 | end 117 | end 118 | 119 | context 'when searching by instance of class' do 120 | it 'should return the books with the given owner type count' do 121 | expect(Book.with_owner(User.first).count).to eq(1) 122 | expect(Book.with_owner(Publisher.first).count).to eq(1) 123 | end 124 | end 125 | end 126 | 127 | describe '#scopes' do 128 | it 'should return the books with the given owner type count' do 129 | expect(Book.with_owner_user.count).to eq(1) 130 | expect(Book.with_owner_publisher.count).to eq(1) 131 | end 132 | 133 | it 'should return the books with the given owner type' do 134 | expect(Book.with_owner_user.first).to eq(user_book) 135 | expect(Book.with_owner_publisher.first).to eq(publisher_book) 136 | end 137 | end 138 | 139 | describe '#instance_methods' do 140 | it 'should return true if the owner type is the given type' do 141 | expect(user_book.owner_type_user?).to be_truthy 142 | expect(publisher_book.owner_type_publisher?).to be_truthy 143 | end 144 | 145 | it 'should return false if the owner type is not the given type' do 146 | expect(user_book.owner_type_publisher?).to be_falsey 147 | expect(publisher_book.owner_type_user?).to be_falsey 148 | end 149 | end 150 | end 151 | 152 | context 'with existing other things' do 153 | let!(:user_other_thing) { OtherThing.create(thing: User.first) } 154 | let!(:publisher_other_thing) { OtherThing.create(thing: Publisher.first) } 155 | 156 | describe '#finder_methods' do 157 | context 'when searching by class' do 158 | it 'should return the other things with the given thing type count' do 159 | expect(OtherThing.with_thing(User).count).to eq(1) 160 | expect(OtherThing.with_thing(Publisher).count).to eq(1) 161 | end 162 | 163 | it 'should return the other things with the given thing type' do 164 | expect(OtherThing.with_thing(User).first).to eq(user_other_thing) 165 | expect(OtherThing.with_thing(Publisher).first).to eq(publisher_other_thing) 166 | end 167 | end 168 | 169 | context 'when searching by string' do 170 | it 'should return the other things with the given thing type count' do 171 | expect(OtherThing.with_thing('User').count).to eq(1) 172 | expect(OtherThing.with_thing('Publisher').count).to eq(1) 173 | end 174 | end 175 | 176 | context 'when searching by instance of class' do 177 | it 'should return the other things with the given thing type count' do 178 | expect(OtherThing.with_thing(User.first).count).to eq(1) 179 | expect(OtherThing.with_thing(Publisher.first).count).to eq(1) 180 | end 181 | end 182 | end 183 | 184 | describe '#scopes' do 185 | it 'should return the other things with the given thing type count' do 186 | expect(OtherThing.with_thing_user.count).to eq(1) 187 | expect(OtherThing.with_thing_publisher.count).to eq(1) 188 | end 189 | 190 | it 'should return the other things with the given thing type' do 191 | expect(OtherThing.with_thing_user.first).to eq(user_other_thing) 192 | expect(OtherThing.with_thing_publisher.first).to eq(publisher_other_thing) 193 | end 194 | end 195 | 196 | describe '#instance_methods' do 197 | it 'should return true if the thing type is the given type' do 198 | expect(user_other_thing.thing_type_user?).to be_truthy 199 | expect(publisher_other_thing.thing_type_publisher?).to be_truthy 200 | end 201 | 202 | it 'should return false if the thing type is not the given type' do 203 | expect(user_other_thing.thing_type_publisher?).to be_falsey 204 | expect(publisher_other_thing.thing_type_user?).to be_falsey 205 | end 206 | end 207 | end 208 | end 209 | -------------------------------------------------------------------------------- /gogrow_logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | --------------------------------------------------------------------------------