module <%= module_name %>
  class <%= controller_class_name %>Controller < <%= module_name %>::BaseController
    before_action :set_<%= singularized_name %>, only: [:show, :edit, :update, :destroy]

    def index
      authorize <%= class_name %>

      @<%= pluralized_name %> = <%= class_name %>.scoped
      @<%= pluralized_name %> = @<%= pluralized_name %>.where(params[:<%= singularized_name %>]) if params[:<%= singularized_name %>].present?
      @<%= pluralized_name %> = @<%= pluralized_name %>.page(params[:page]).per_page(params[:per_page])
      @<%= pluralized_name %> = @<%= pluralized_name %>.all
    end

    def show
    end

    def new
      @<%= singularized_name %> = <%= class_name %>.new
      authorize @<%= singularized_name %>
    end

    def create
      @<%= singularized_name %> = <%= class_name %>.new <%= singularized_name %>_params
      authorize @<%= singularized_name %>

      if @<%= singularized_name %>.save
        flash[:success] = "Success"
        redirect_to <%= module_variable_name %>_<%= pluralized_name %>_path
      else
        flash.now[:danger] = @<%= singularized_name %>.errors.full_messages.to_sentence
        render :new
      end
    end

    def edit
    end

    def update
      @<%= singularized_name %>.attributes = <%= singularized_name %>_params

      if @<%= singularized_name %>.save
        flash[:success] = "Success"
        redirect_to <%= module_variable_name %>_<%= pluralized_name %>_path
      else
        flash.now[:danger] = @<%= singularized_name %>.errors.full_messages.to_sentence
        render :edit
      end
    end

    def destroy
      if @<%= singularized_name %>.destroy
        flash[:success] = "Success"
      else
        flash[:error] = @<%= singularized_name %>.errors.full_messages.to_sentence
      end

      redirect_back
    end

    protected

    def set_<%= singularized_name %>
      @<%= singularized_name %> = <%= class_name %>.find params[:id]
      authorize @<%= singularized_name %>
    end

    def <%= singularized_name %>_params
      <%- if attributes.any? -%>
      params.require(:<%= module_variable_name %>_<%= singularized_name %>).permit(<%= attributes.map {|a| ":#{a.name}"}.join(", ") %>)
      <%- else -%>
      # params.require(:<%= module_variable_name %>_<%= singularized_name %>).permit(:attribute1, :attribute2, :attribute3)
      <%- end -%>
    end
  end
end
