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 # ################################################################## included do before_action :init_resource before_action :load_resources, only: [:index] before_action :load_resource, only: [:new, :edit, :update, :delete, :create, :show] end def index end def new end def show end def create instance_variable_get("@#{@resource}").save(send("#{@resource}_params")) redirect_to send("#{@resources}_path") end def edit end def update instance_variable_get("@#{@resource}").update_attributes(send("#{@resource}_params")) redirect_to send("#{@resources}_path") end def destroy instance_variable_get("@#{@resource}").destroy redirect_to send("#{@resources}_path") 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 instance_variable_set "@#{@resources}", @resources.classify.constantize.all.page(params[:page]) end end