# encoding : utf-8 class BeautifulSorceryGenerator < Rails::Generators::Base require_relative 'beautiful_scaffold_common_methods' include BeautifulScaffoldCommonMethods source_root File.expand_path('../templates', __FILE__) #argument :model, :type => :string, :desc => "Name of model (ex: User)" def install_sorcery model = "User" view_path = "app/views/" if !File.read('Gemfile').include?("sorcery") gem("sorcery", "0.16.0") end Bundler.with_unbundled_env do run "bundle install" end raise "Model must be specified" if model.blank? # Install sorcery generate("sorcery:install", "remember_me reset_password user_activation brute_force_protection external --model #{model}") # If exist users migration just add columns create_user_migration = Dir.glob("db/migrate/*create_users.rb").first if create_user_migration already_email = File.read(create_user_migration).include?(":email") sorcery_core_file = Dir.glob("db/migrate/*sorcery_core.rb").first File.open(sorcery_core_file, "w+") do |f| f.write("class SorceryCore < ActiveRecord::Migration[6.1] def change #{(already_email ? '' : 'add_column :users, :email, :string')} add_column :users, :crypted_password, :string add_column :users, :salt, :string #{(already_email ? '' : 'add_index :users, :email, unique: true')} end end") end end # Generate mailer copy_file("app/mailers/user_mailer.rb") # Install controllers copy_file("app/controllers/user_sessions_controller.rb") # ===== Controller inject_into_file("app/controllers/users_controller.rb", "\n skip_before_action :require_login, only: [:new, :create, :activate] \n", after: "< BeautifulController") inject_into_file("app/controllers/users_controller.rb", "def activate if @user = User.load_from_activation_token(params[:id]) @user.activate! redirect_to(login_path, :notice => 'User was successfully activated.') else not_authenticated end end\n\n ", before: "private") # ====== Model # Add password & password_confirmation in model inject_into_file("app/models/user.rb", "\n validates :password, length: { minimum: 3 }, if: -> { new_record? || changes[:crypted_password] } validates :password, confirmation: true, if: -> { new_record? || changes[:crypted_password] } validates :password_confirmation, presence: true, if: -> { new_record? || changes[:crypted_password] } before_update :setup_activation, if: -> { email_changed? } after_update :send_activation_needed_email!, if: -> { previous_changes['email'].present? }\n", after: "ApplicationRecord") inject_into_file("app/models/user.rb", ":password,:password_confirmation,", :after => "def self.permitted_attributes\n return ") # ====== Views inject_into_file("app/views/users/_form.html.erb", '