module CrudConcern extend ActiveSupport::Concern # rails version >= 5 ################################################################## # This module take cares the CRUD controller methods # # # # Note: add skip_before_action if you want to ignore any of the # # above action to be loaded from module # # additional feature has confirm verification before deleting a # # record. # # # ################################################################## included do before_action :init_resource before_action :load_resources, only: [:index, :filter] before_action :load_resource, only: [:new, :edit, :update, :destroy, :create, :show] end def index end def filter render 'index' end def new end def show end def create if instance_variable_get("@#{@resource}").save(send("#{@resource}_params")) flash[:success] = "Created a #{@resource.camelize} successfully" redirect_to send("#{@resources}_path") else flash[:alert] = instance_variable_get("@#{@resource}").errors.full_messages.first redirect_back fallback_location: send("#{@resources}_path") end end def edit end def update if instance_variable_get("@#{@resource}").update!(send("#{@resource}_params")) flash[:success] = "Updated a #{@resource.camelize} successfully" end redirect_back fallback_location: send("edit_#{@resource}_path", instance_variable_get("@#{@resource}")) end def destroy respond_to do |format| format.html { if current_user.valid_password?(authenticate_params[:password]) instance_variable_get("@#{@resource}").destroy flash[:success] = "Deleted a #{@resource.camelize} successfully" else flash[:error] = 'Invalid Password' end redirect_to send("#{@resources}_path") } format.js { @path = send("#{@resource}_path", instance_variable_get("@#{@resource}")) render 'shared/delete' } end end private def init_resource @resources = controller_name @resource = @resources.singularize end def load_resource if params[:action] == "create" instance_variable_set "@#{@resource}", @resources.classify.constantize.new(send("#{@resource}_params")) else instance_variable_set "@#{@resource}", @resources.classify.constantize.find_or_initialize_by(id: params[:id]) end end def load_resources if params[:action] == 'filter' instance_variable_set "@#{@resources}", @resources.classify.constantize.unscoped.filter(send("#{@resource}_filter_params")).page(params[:page]) else instance_variable_set "@#{@resources}", @resources.classify.constantize.unscoped.all.page(params[:page]) end end def authenticate_params params.require(:authenticate).permit(:password) end end