My opinionated ruby on rails template
at main 82 lines 2.3 kB view raw
1# frozen_string_literal: true 2 3say 'Setting up soft deletes with acts_as_paranoid...', :green 4 5gem 'acts_as_paranoid' 6 7say ' Creating SoftDeletable concern...', :cyan 8file 'app/models/concerns/soft_deletable.rb', <<~RUBY 9 # frozen_string_literal: true 10 11 # Include this concern in models that should support soft deletes 12 # 13 # Migration: 14 # add_column :posts, :deleted_at, :datetime 15 # add_index :posts, :deleted_at 16 # 17 # Usage: 18 # class Post < ApplicationRecord 19 # include SoftDeletable 20 # end 21 # 22 # post.destroy # soft deletes (sets deleted_at) 23 # post.deleted? # => true 24 # post.recover # restores the record 25 # post.destroy_fully! # permanently deletes 26 # 27 # Post.all # excludes soft-deleted records 28 # Post.with_deleted # includes soft-deleted records 29 # Post.only_deleted # only soft-deleted records 30 # 31 module SoftDeletable 32 extend ActiveSupport::Concern 33 34 included do 35 acts_as_paranoid 36 end 37 38 # Permanently delete the record 39 def destroy_fully! 40 destroy_fully 41 end 42 end 43RUBY 44 45say ' Creating migration generator helper...', :cyan 46file 'lib/generators/soft_delete/soft_delete_generator.rb', <<~RUBY 47 # frozen_string_literal: true 48 49 class SoftDeleteGenerator < Rails::Generators::NamedBase 50 include Rails::Generators::Migration 51 52 source_root File.expand_path('templates', __dir__) 53 54 def self.next_migration_number(_dirname) 55 Time.now.utc.strftime('%Y%m%d%H%M%S') 56 end 57 58 def create_migration_file 59 migration_template 'migration.rb.erb', "db/migrate/add_deleted_at_to_\#{table_name}.rb" 60 end 61 62 private 63 64 def table_name 65 file_name.tableize 66 end 67 end 68RUBY 69 70file 'lib/generators/soft_delete/templates/migration.rb.erb', <<~ERB 71 class AddDeletedAtTo<%= table_name.camelize %> < ActiveRecord::Migration[<%= Rails::VERSION::MAJOR %>.<%= Rails::VERSION::MINOR %>] 72 def change 73 add_column :<%= table_name %>, :deleted_at, :datetime 74 add_index :<%= table_name %>, :deleted_at 75 end 76 end 77ERB 78 79say 'Soft deletes configured!', :green 80say ' Include `SoftDeletable` in models', :cyan 81say ' Generate migration: rails g soft_delete ModelName', :cyan 82say ' Or manually: add_column :table, :deleted_at, :datetime', :cyan