# desc "Explaining what the task does" # task :self-auth-rails do # # Task goes here # end desc 'Creates the self-auth-rails initializer on your application' namespace :self_auth_rails do task :init do # Getting model to be used as authentication puts "What model do you want to use for authentication? (Defaults to \"User\")" model_name = STDIN.gets.strip model_name = 'User' if model_name.empty? log 'Generating migrations' if Object.const_defined? model_name log "#{model_name} already initialized, adding necessary columns" system "SKIP_SELF=1 bin/rails g migration add_auth_to_#{model_name.downcase}s selfid:string name:string token:string" else system "SKIP_SELF=1 bin/rails g model #{model_name.downcase} selfid:string name:string token:string" end log 'migration file created!' # Adding initializer to your application log 'Creating self-auth-rails initializer from template' body = File.read(__FILE__.gsub('self_auth_rails_tasks.rake', 'initializer.rb.tpl')) body.gsub!("{{AuthModel}}", model_name) File.open("#{Dir.pwd}/config/initializers/self_auth_rails.rb", 'w') { |file| file << body } log 'config/initializers/self_auth_rails.rb created' # Adding routes to your application puts "What alias do you want to use to mount this rails engine? (Defaults to \"auth\")" as = STDIN.gets.strip as = 'auth' if as.empty? log 'Adding routes to config/routes.rb' file_path = "#{Dir.pwd}/config/routes.rb" body = File.read(file_path) if body.include? 'SelfAuthRails' log 'skipping... (self-auth-rails routes already added)' else pattern = 'Rails.application.routes.draw do' content = body.gsub(pattern, "#{pattern}\n # Mounting self-auth-rails engine\n mount SelfAuthRails::Engine => \"/auth\", as: \"#{as}\"") File.open(file_path, 'w') { |file| file << content } log 'self-auth-rails routes added' end puts 'Adding assets headers' assets_file_path = "#{Dir.pwd}/app/views/layouts/application.html.erb" body = File.read(assets_file_path) header1 = '<%= javascript_include_tag "self-auth-rails/manifest" %>' header2 = '<%= stylesheet_link_tag "self-auth-rails/application.css" %>' body.gsub!("", "#{header1}\n\t#{header2}\n\t") File.open(assets_file_path, 'w') { |file| file << body } log 'asset headers set' manifest_file_path = "#{Dir.pwd}/app/assets/config/manifest.js" body = File.read(manifest_file_path) body += "\n//= link self-auth-rails/manifest.js" File.open(manifest_file_path, 'w') { |file| file << body } log 'All set!' puts 'Remember to run `bin/rails db:migrate` to create your authentication table' end end def log(str) str = "[self_auth_rails::init] #{str}" puts "\e[#{36}m#{str}\e[0m" end