├── .github ├── dependabot.yml └── workflows │ └── rspec.yml ├── .gitignore ├── .rspec ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Gemfile ├── LICENSE.txt ├── README.md ├── Rakefile ├── activestorage-validator.gemspec ├── bin ├── console └── setup ├── config.ru ├── config └── locales │ ├── de.yml │ ├── en.yml │ ├── es.yml │ ├── fr.yml │ ├── ja.yml │ ├── pl.yml │ └── pt-br.yml ├── gemfiles ├── rails61.gemfile ├── rails70.gemfile ├── rails71.gemfile ├── rails72.gemfile └── rails80.gemfile ├── lib └── activestorage │ ├── validator.rb │ └── validator │ ├── blob.rb │ └── version.rb └── spec ├── activestorage └── validator │ └── blob_spec.rb ├── fixtures └── files │ ├── 1_4MB.jpg │ ├── 600KB.jpg │ ├── dummy.txt │ └── sample.tiff ├── internal ├── app │ └── models │ │ └── user.rb ├── config │ ├── database.yml │ ├── routes.rb │ └── storage.yml ├── db │ └── schema.rb ├── log │ └── .gitignore └── public │ └── favicon.ico ├── spec_helper.rb └── support └── blob_helper.rb /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: github-actions 4 | directory: / 5 | schedule: 6 | interval: weekly 7 | -------------------------------------------------------------------------------- /.github/workflows/rspec.yml: -------------------------------------------------------------------------------- 1 | # This workflow uses actions that are not certified by GitHub. 2 | # They are provided by a third-party and are governed by 3 | # separate terms of service, privacy policy, and support 4 | # documentation. 5 | # This workflow will download a prebuilt Ruby version, install dependencies and run tests with Rake 6 | # For more information see: https://github.com/marketplace/actions/setup-ruby-jruby-and-truffleruby 7 | 8 | name: Build 9 | 10 | on: 11 | push: 12 | branches: [master] 13 | pull_request: 14 | 15 | jobs: 16 | rspec: 17 | runs-on: ubuntu-latest 18 | env: 19 | BUNDLE_JOBS: 4 20 | BUNDLE_RETRY: 3 21 | BUNDLE_GEMFILE: ${{ github.workspace }}/gemfiles/${{ matrix.gemfile }}.gemfile 22 | strategy: 23 | fail-fast: false 24 | matrix: 25 | include: 26 | - { ruby: "3.0", gemfile: "rails61" } 27 | - { ruby: "3.1", gemfile: "rails61" } 28 | - { ruby: "3.2", gemfile: "rails61" } 29 | - { ruby: "3.0", gemfile: "rails70" } 30 | - { ruby: "3.1", gemfile: "rails70" } 31 | - { ruby: "3.2", gemfile: "rails70" } 32 | - { ruby: "3.0", gemfile: "rails71" } 33 | - { ruby: "3.1", gemfile: "rails71" } 34 | - { ruby: "3.2", gemfile: "rails71" } 35 | - { ruby: "3.2", gemfile: "rails72" } 36 | - { ruby: "3.3", gemfile: "rails72" } 37 | - { ruby: "3.4", gemfile: "rails72" } 38 | - { ruby: "3.2", gemfile: "rails80" } 39 | - { ruby: "3.3", gemfile: "rails80" } 40 | - { ruby: "3.4", gemfile: "rails80" } 41 | steps: 42 | - name: Install packages 43 | run: | 44 | sudo apt update -y 45 | sudo apt install -y libsqlite3-dev 46 | 47 | - uses: actions/checkout@v4 48 | 49 | - name: Set up Ruby 50 | uses: ruby/setup-ruby@v1 51 | with: 52 | ruby-version: ${{ matrix.ruby }} 53 | bundler-cache: true 54 | 55 | - name: Run rspec 56 | run: bundle exec rspec 57 | -------------------------------------------------------------------------------- /.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 | /Gemfile.lock 13 | gemfiles/*.lock 14 | *.sqlite 15 | Gemfile.local 16 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | --require spec_helper 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## [Unreleased] 2 | 3 | ## 0.4.0 4 | 5 | - Add `content_type: :web_image` options 6 | 7 | ## 0.3.0 8 | 9 | - Drop support for rails 6.0 10 | 11 | ## 0.2.2 12 | 13 | - Add polish locale (#29) 14 | 15 | ## 0.2.1 16 | 17 | - Add spanish locale (#28) 18 | 19 | ## 0.2.0 20 | 21 | - Drop support for rails 5.2 22 | 23 | ## 0.1.5 24 | 25 | - Add French locale (#24) 26 | 27 | ## 0.1.4 28 | 29 | - Updated test environment to rails 6.0.0 30 | - Add pt-br locale (#22) 31 | 32 | ## 0.1.3 33 | 34 | - Update dependency 35 | - Add German locale 36 | 37 | ## 0.1.2 38 | 39 | - Fix typo 40 | 41 | ## 0.1.1 42 | 43 | - Add default error messages 44 | 45 | ## 0.1.0 46 | 47 | - First Release 48 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at lala.akira@gmail.com. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } 4 | 5 | # Specify your gem's dependencies in activestorage-validator.gemspec 6 | gemspec 7 | 8 | local_gemfile = "Gemfile.local" 9 | 10 | if File.exist?(local_gemfile) 11 | eval_gemfile(local_gemfile) # rubocop:disable Security/Eval 12 | else 13 | gem 'sqlite3' 14 | end 15 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2018 aki 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Gem Version](https://badge.fury.io/rb/activestorage-validator.svg)](https://rubygems.org/gems/activestorage-validator) 2 | [![Build](https://github.com/aki77/activestorage-validator/workflows/Build/badge.svg)](https://github.com/aki77/activestorage-validator/actions) 3 | 4 | # ActiveStorage Validator 5 | 6 | ActiveStorage blob validator. 7 | 8 | ## Installation 9 | 10 | Add this line to your application's Gemfile: 11 | 12 | ```ruby 13 | gem 'activestorage-validator' 14 | ``` 15 | 16 | And then execute: 17 | 18 | $ bundle 19 | 20 | Or install it yourself as: 21 | 22 | $ gem install activestorage-validator 23 | 24 | ## Usage 25 | 26 | ```ruby 27 | class User < ApplicationRecord 28 | has_one_attached :avatar 29 | has_many_attached :photos 30 | 31 | validates :avatar, presence: true, blob: { content_type: :web_image } # supported options: :web_image, :image, :audio, :video, :text 32 | validates :photos, presence: true, blob: { content_type: ['image/png', 'image/jpg', 'image/jpeg'], size_range: 1..(5.megabytes) } 33 | # validates :photos, presence: true, blob: { content_type: %r{^image/}, size_range: 1..(5.megabytes) } 34 | end 35 | ``` 36 | 37 | Note: For `has_many_attached`, size is validated on each file individually. In the code above, `:photos` validation allows any number of photos to be upload, each one being 5 MB or less in size. 38 | 39 | ## Contributing 40 | 41 | Bug reports and pull requests are welcome on GitHub at https://github.com/aki77/activestorage-validator. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. 42 | 43 | ## License 44 | 45 | The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT). 46 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | require "rspec/core/rake_task" 3 | 4 | RSpec::Core::RakeTask.new(:spec) 5 | 6 | task :default => :spec 7 | -------------------------------------------------------------------------------- /activestorage-validator.gemspec: -------------------------------------------------------------------------------- 1 | 2 | lib = File.expand_path("../lib", __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require "activestorage/validator/version" 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "activestorage-validator" 8 | spec.version = ActiveStorage::Validator::VERSION 9 | spec.authors = ["aki"] 10 | spec.email = ["aki77@users.noreply.github.com"] 11 | 12 | spec.summary = %q{ActiveStorage blob validator.} 13 | spec.description = %q{ActiveStorage blob validator.} 14 | spec.homepage = "https://github.com/aki77/activestorage-validator" 15 | spec.license = "MIT" 16 | 17 | # Specify which files should be added to the gem when it is released. 18 | # The `git ls-files -z` loads the files in the RubyGem that have been added into git. 19 | spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do 20 | `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } 21 | end 22 | spec.bindir = "exe" 23 | spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } 24 | spec.require_paths = ["lib"] 25 | 26 | spec.required_ruby_version = '>= 3.0.0' 27 | 28 | spec.add_dependency "rails", ">= 6.1.0" 29 | spec.add_development_dependency "bundler", "~> 2.0" 30 | spec.add_development_dependency "rake", ">= 12.3.3" 31 | spec.add_development_dependency "rspec", "~> 3.0" 32 | spec.add_development_dependency "combustion" 33 | end 34 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "activestorage/validator" 5 | 6 | # You can add fixtures and/or initialization code here to make experimenting 7 | # with your gem easier. You can also use a different console, if you like. 8 | 9 | # (If you use this, don't forget to add pry to your Gemfile!) 10 | # require "pry" 11 | # Pry.start 12 | 13 | require "irb" 14 | IRB.start(__FILE__) 15 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /config.ru: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | require "rubygems" 4 | require "bundler" 5 | 6 | Bundler.require :default, :development 7 | 8 | Combustion.initialize! :all 9 | run Combustion::Application 10 | -------------------------------------------------------------------------------- /config/locales/de.yml: -------------------------------------------------------------------------------- 1 | de: 2 | activerecord: 3 | errors: 4 | messages: 5 | content_type: "ist kein gültiges Dateiformat" 6 | min_size_error: "Dateigröße sollte weniger als %{min_size} betragen" 7 | max_size_error: "Dateigröße sollte weniger als %{max_size} betragen" 8 | -------------------------------------------------------------------------------- /config/locales/en.yml: -------------------------------------------------------------------------------- 1 | en: 2 | activerecord: 3 | errors: 4 | messages: 5 | content_type: "is not a valid file format" 6 | min_size_error: "File size should be greater than %{min_size}" 7 | max_size_error: "File size should be less than %{max_size}" 8 | -------------------------------------------------------------------------------- /config/locales/es.yml: -------------------------------------------------------------------------------- 1 | es: 2 | activerecord: 3 | errors: 4 | messages: 5 | content_type: "no es un formato válido" 6 | min_size_error: "tamaño de archivo debe ser mayor a %{min_size}" 7 | max_size_error: "tamaño de archivo debe ser menor a %{max_size}" 8 | -------------------------------------------------------------------------------- /config/locales/fr.yml: -------------------------------------------------------------------------------- 1 | fr: 2 | activerecord: 3 | errors: 4 | messages: 5 | content_type: "n'est pas un format de fichier valide" 6 | min_size_error: "La taille du fichier doit être supérieure à %{min_size}" 7 | max_size_error: "La taille du fichier doit être inférieure à %{max_size}" 8 | -------------------------------------------------------------------------------- /config/locales/ja.yml: -------------------------------------------------------------------------------- 1 | ja: 2 | activerecord: 3 | errors: 4 | messages: 5 | content_type: "のファイル形式が不正です。" 6 | min_size_error: "を%{min_size}以上のサイズにしてください。" 7 | max_size_error: "を%{max_size}以下のサイズにしてください。" 8 | -------------------------------------------------------------------------------- /config/locales/pl.yml: -------------------------------------------------------------------------------- 1 | pl: 2 | activerecord: 3 | errors: 4 | messages: 5 | content_type: "ma nieprawidłowy format" 6 | min_size_error: "Rozmiar pliku nie może być większy niż %{min_size}" 7 | max_size_error: "Rozmiar pliku nie może być mniejszy niż %{max_size}" 8 | -------------------------------------------------------------------------------- /config/locales/pt-br.yml: -------------------------------------------------------------------------------- 1 | pt-br: 2 | activerecord: 3 | errors: 4 | messages: 5 | content_type: "não é um formato válido" 6 | min_size_error: "tamanho do arquivo deve ser maior que %{min_size}" 7 | max_size_error: "tamanho do arquivo deve ser menor que %{max_size}" 8 | -------------------------------------------------------------------------------- /gemfiles/rails61.gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'rails', '6.1.4' 4 | gem 'sqlite3', '~> 1.4' 5 | gem 'concurrent-ruby', '< 1.3.5' 6 | 7 | gemspec path: '../' 8 | -------------------------------------------------------------------------------- /gemfiles/rails70.gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'rails', '~> 7.0.0' 4 | gem 'sqlite3', '~> 1.4' 5 | gem 'concurrent-ruby', '< 1.3.5' 6 | 7 | gemspec path: '../' 8 | -------------------------------------------------------------------------------- /gemfiles/rails71.gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'rails', '~> 7.1.0' 4 | gem 'sqlite3' 5 | 6 | gemspec path: '../' -------------------------------------------------------------------------------- /gemfiles/rails72.gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'rails', '~> 7.2.0' 4 | gem 'sqlite3' 5 | 6 | gemspec path: '../' -------------------------------------------------------------------------------- /gemfiles/rails80.gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gem 'rails', '~> 8.0.0' 4 | gem 'sqlite3' 5 | 6 | gemspec path: '../' -------------------------------------------------------------------------------- /lib/activestorage/validator.rb: -------------------------------------------------------------------------------- 1 | require 'activestorage/validator/version' 2 | 3 | ActiveSupport.on_load(:active_record) do 4 | require 'activestorage/validator/blob' 5 | end 6 | 7 | I18n.load_path += Dir[File.expand_path(File.join(__dir__, '../../config/locales', '*.yml')).to_s] 8 | -------------------------------------------------------------------------------- /lib/activestorage/validator/blob.rb: -------------------------------------------------------------------------------- 1 | module ActiveRecord 2 | module Validations 3 | class BlobValidator < ::ActiveModel::EachValidator 4 | def validate_each(record, attribute, values) # rubocop:disable Metrics/AbcSize 5 | return unless values.attached? 6 | 7 | Array(values).each do |value| 8 | if options[:size_range].present? 9 | if options[:size_range].min > value.blob.byte_size 10 | record.errors.add(attribute, :min_size_error, min_size: ActiveSupport::NumberHelper.number_to_human_size(options[:size_range].min)) 11 | elsif options[:size_range].max < value.blob.byte_size 12 | record.errors.add(attribute, :max_size_error, max_size: ActiveSupport::NumberHelper.number_to_human_size(options[:size_range].max)) 13 | end 14 | end 15 | 16 | unless valid_content_type?(value.blob) 17 | record.errors.add(attribute, :content_type) 18 | end 19 | end 20 | end 21 | 22 | private 23 | 24 | def valid_content_type?(blob) 25 | return true if options[:content_type].nil? 26 | 27 | case options[:content_type] 28 | when Regexp 29 | options[:content_type].match?(blob.content_type) 30 | when Array 31 | options[:content_type].include?(blob.content_type) 32 | when :web_image 33 | ActiveStorage.web_image_content_types.include?(blob.content_type) 34 | when Symbol 35 | blob.public_send("#{options[:content_type]}?") 36 | else 37 | options[:content_type] == blob.content_type 38 | end 39 | end 40 | end 41 | end 42 | end 43 | -------------------------------------------------------------------------------- /lib/activestorage/validator/version.rb: -------------------------------------------------------------------------------- 1 | module ActiveStorage 2 | module Validator 3 | VERSION = '0.4.0' 4 | end 5 | end 6 | -------------------------------------------------------------------------------- /spec/activestorage/validator/blob_spec.rb: -------------------------------------------------------------------------------- 1 | RSpec.describe ActiveRecord::Validations::BlobValidator do 2 | after { User.clear_validators! } 3 | 4 | describe 'presence: true' do 5 | context 'has_one_attached' do 6 | before do 7 | User.validates :file, presence: true 8 | end 9 | 10 | it { expect(User.new.valid?).to eq false } 11 | it { expect(User.new(file: create_file_blob(filename: 'dummy.txt')).valid?).to eq true } 12 | end 13 | 14 | context 'has_many_attached' do 15 | before do 16 | User.validates :files, presence: true 17 | end 18 | 19 | it { expect(User.new.valid?).to eq false } 20 | it { expect(User.new(files: [create_file_blob(filename: 'dummy.txt')]).valid?).to eq true } 21 | end 22 | end 23 | 24 | describe 'with size_range option' do 25 | before do 26 | User.validates :file, blob: { size_range: 1..1.megabyte } 27 | User.validates :files, blob: { size_range: 1..1.megabyte } 28 | end 29 | 30 | context '600KB' do 31 | it { expect(User.new(file: create_file_blob(filename: '600KB.jpg')).valid?).to eq true } 32 | it { expect(User.new(files: [create_file_blob(filename: '600KB.jpg')]).valid?).to eq true } 33 | end 34 | 35 | context '1.4MB' do 36 | it { expect(User.new(file: create_file_blob(filename: '1_4MB.jpg')).valid?).to eq false } 37 | it { expect(User.new(files: [create_file_blob(filename: '1_4MB.jpg')]).valid?).to eq false } 38 | 39 | it "should translate the validation error according to it's locale" do 40 | user = User.new(file: create_file_blob(filename: '1_4MB.jpg')) 41 | user.validate 42 | expect(user.errors.messages[:file][0]).to eq 'File size should be less than 1 MB' 43 | end 44 | end 45 | end 46 | 47 | describe 'with content_type option' do 48 | context 'regexp' do 49 | before do 50 | User.validates :file, blob: { content_type: /^image/ } 51 | User.validates :files, blob: { content_type: /^image/ } 52 | end 53 | 54 | it { expect(User.new(file: create_file_blob(filename: '600KB.jpg')).valid?).to eq true } 55 | it { expect(User.new(file: create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')).valid?).to eq false } 56 | 57 | it { expect(User.new(files: [create_file_blob(filename: '600KB.jpg')]).valid?).to eq true } 58 | it { expect(User.new(files: [create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')]).valid?).to eq false } 59 | end 60 | 61 | context 'array' do 62 | before do 63 | User.validates :file, blob: { content_type: %w[image/jpeg image/png] } 64 | User.validates :files, blob: { content_type: %w[image/jpeg image/png] } 65 | end 66 | 67 | it { expect(User.new(file: create_file_blob(filename: '600KB.jpg')).valid?).to eq true } 68 | it { expect(User.new(file: create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')).valid?).to eq false } 69 | 70 | it { expect(User.new(files: [create_file_blob(filename: '600KB.jpg')]).valid?).to eq true } 71 | it { expect(User.new(files: [create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')]).valid?).to eq false } 72 | end 73 | 74 | context ':web_image' do 75 | before do 76 | User.validates :file, blob: { content_type: :web_image } 77 | end 78 | 79 | it { expect(User.new(file: create_file_blob(filename: '600KB.jpg')).valid?).to eq true } 80 | it { expect(User.new(file: create_file_blob(filename: 'sample.tiff', content_type: 'image/tiff')).valid?).to eq false } 81 | end 82 | 83 | context 'symbol' do 84 | before do 85 | User.validates :file, blob: { content_type: :image } 86 | User.validates :files, blob: { content_type: :image } 87 | end 88 | 89 | it { expect(User.new(file: create_file_blob(filename: '600KB.jpg')).valid?).to eq true } 90 | it { expect(User.new(file: create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')).valid?).to eq false } 91 | 92 | it { expect(User.new(files: [create_file_blob(filename: '600KB.jpg')]).valid?).to eq true } 93 | it { expect(User.new(files: [create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')]).valid?).to eq false } 94 | end 95 | 96 | context 'string' do 97 | before do 98 | User.validates :file, blob: { content_type: 'image/jpeg' } 99 | User.validates :files, blob: { content_type: 'image/jpeg' } 100 | end 101 | 102 | it { expect(User.new(file: create_file_blob(filename: '600KB.jpg')).valid?).to eq true } 103 | it { expect(User.new(file: create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')).valid?).to eq false } 104 | 105 | it { expect(User.new(files: [create_file_blob(filename: '600KB.jpg')]).valid?).to eq true } 106 | it { expect(User.new(files: [create_file_blob(filename: 'dummy.txt', content_type: 'text/plain')]).valid?).to eq false } 107 | end 108 | end 109 | end 110 | -------------------------------------------------------------------------------- /spec/fixtures/files/1_4MB.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aki77/activestorage-validator/4737300779a660046df3a6304ff58efe8322b6e8/spec/fixtures/files/1_4MB.jpg -------------------------------------------------------------------------------- /spec/fixtures/files/600KB.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aki77/activestorage-validator/4737300779a660046df3a6304ff58efe8322b6e8/spec/fixtures/files/600KB.jpg -------------------------------------------------------------------------------- /spec/fixtures/files/dummy.txt: -------------------------------------------------------------------------------- 1 | dummy 2 | -------------------------------------------------------------------------------- /spec/fixtures/files/sample.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aki77/activestorage-validator/4737300779a660046df3a6304ff58efe8322b6e8/spec/fixtures/files/sample.tiff -------------------------------------------------------------------------------- /spec/internal/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | has_one_attached :file 3 | has_many_attached :files 4 | end 5 | -------------------------------------------------------------------------------- /spec/internal/config/database.yml: -------------------------------------------------------------------------------- 1 | test: 2 | adapter: sqlite3 3 | database: db/combustion_test.sqlite 4 | -------------------------------------------------------------------------------- /spec/internal/config/routes.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | Rails.application.routes.draw do 4 | # Add your own routes here, or remove this file if you don't have need for it. 5 | end 6 | -------------------------------------------------------------------------------- /spec/internal/config/storage.yml: -------------------------------------------------------------------------------- 1 | test: 2 | service: Disk 3 | root: /tmp/storage 4 | -------------------------------------------------------------------------------- /spec/internal/db/schema.rb: -------------------------------------------------------------------------------- 1 | # frozen_string_literal: true 2 | 3 | ActiveRecord::Schema.define do 4 | create_table :users do |t| 5 | t.timestamps null: false 6 | end 7 | 8 | create_table :active_storage_blobs do |t| 9 | t.string :key, null: false 10 | t.string :filename, null: false 11 | t.string :content_type 12 | t.text :metadata 13 | t.bigint :byte_size, null: false 14 | t.string :checksum, null: false 15 | t.datetime :created_at, null: false 16 | if Rails.version.to_f >= 6.1 17 | t.string :service_name, null: false 18 | end 19 | 20 | t.index [ :key ], unique: true 21 | end 22 | 23 | create_table :active_storage_attachments do |t| 24 | t.string :name, null: false 25 | t.references :record, null: false, polymorphic: true, index: false 26 | t.references :blob, null: false 27 | 28 | t.datetime :created_at, null: false 29 | 30 | t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true 31 | t.foreign_key :active_storage_blobs, column: :blob_id 32 | end 33 | 34 | create_table :active_storage_variant_records do |t| 35 | t.references :blob, null: false 36 | t.string :variation_digest, null: false 37 | 38 | t.index [ :blob_id, :variation_digest], name: 'index_active_storage_variant_records_uniqueness', unique: true 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /spec/internal/log/.gitignore: -------------------------------------------------------------------------------- 1 | *.log -------------------------------------------------------------------------------- /spec/internal/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aki77/activestorage-validator/4737300779a660046df3a6304ff58efe8322b6e8/spec/internal/public/favicon.ico -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | require "bundler/setup" 2 | require "active_storage/engine" 3 | Bundler.require :default, :development 4 | require "support/blob_helper" 5 | 6 | Combustion.initialize! :active_record, :active_job do 7 | if ActiveRecord::VERSION::MAJOR < 6 && config.active_record.sqlite3.respond_to?(:represent_boolean_as_integer) 8 | config.active_record.sqlite3.represent_boolean_as_integer = true 9 | end 10 | config.active_job.queue_adapter = :inline 11 | config.active_storage.service = :test 12 | end 13 | 14 | RSpec.configure do |config| 15 | # Enable flags like --only-failures and --next-failure 16 | config.example_status_persistence_file_path = ".rspec_status" 17 | 18 | # Disable RSpec exposing methods globally on `Module` and `main` 19 | config.disable_monkey_patching! 20 | 21 | config.expect_with :rspec do |c| 22 | c.syntax = :expect 23 | end 24 | 25 | config.include BlobHelper 26 | end 27 | -------------------------------------------------------------------------------- /spec/support/blob_helper.rb: -------------------------------------------------------------------------------- 1 | module BlobHelper 2 | def create_file_blob(filename:, content_type: "image/jpeg", metadata: nil) 3 | if Rails::VERSION::MAJOR < 6 || (Rails::VERSION::MAJOR == 6 && Rails::VERSION::MINOR == 0) 4 | ActiveStorage::Blob.create_after_upload! io: file_fixture(filename).open, filename: filename, content_type: content_type, metadata: metadata 5 | else 6 | ActiveStorage::Blob.create_and_upload! io: file_fixture(filename).open, filename: filename, content_type: content_type, metadata: metadata 7 | end 8 | end 9 | 10 | private 11 | 12 | def file_fixture(fixture_name) 13 | file_fixture_path = File.expand_path("../fixtures/files", __dir__) 14 | path = Pathname.new(File.join(file_fixture_path, fixture_name)) 15 | 16 | if path.exist? 17 | path 18 | else 19 | msg = "the directory '%s' does not contain a file named '%s'" 20 | raise ArgumentError, msg % [file_fixture_path, fixture_name] 21 | end 22 | end 23 | end 24 | --------------------------------------------------------------------------------