<%% if namespaced? -%> require_dependency “<%%= namespaced_path %>/application_controller”
<%% end -%> <%% module_namespacing do -%> class <%%= controller_class_name %>Controller < ApplicationController <%%-
# Generate scaffold with name or title, and a `slug:uniq` field to enable friendly_id using_friendly_id = attributes_names.any? { |name| %w(name title).include?(name) } && attributes_names.any? { |name| %w(slug).include?(name) }
-%>
before_action :authenticate_user! before_action :assign_<%%= singular_table_name %>, only: [:show, :update, :destroy]
<%- if pundit? -%>
after_action :verify_authorized after_action :verify_policy_scoped, except: [:new, :create]
<%- end -%>
# GET <%%= route_url %> def index
<%- if pundit? -%>
authorize <%%= class_name %> @<%%= plural_table_name %> = policy_scope(<%%= class_name %>)
<%- else -%>
@<%%= plural_table_name %> = <%%= orm_class.all(class_name) %>
<%- end -%>
render json: <%%= "@#{plural_table_name}" %> end # GET <%%= route_url %>/1 def show
<%- if pundit? -%>
authorize @<%%= singular_table_name %>
<%- end -%>
render json: <%%= "@#{singular_table_name}" %> end # POST <%%= route_url %> def create @<%%= singular_table_name %> = <%%= orm_class.build(class_name, "#{singular_table_name}_params") %>
<%- if pundit? -%>
authorize @<%%= singular_table_name %>
<%- end -%>
if @<%%= orm_instance.save %> render json: <%%= "@#{singular_table_name}" %>, status: :created, location: <%%= "@#{singular_table_name}" %> else render json: <%%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity end end # PATCH/PUT <%%= route_url %>/1 def update
<%- if pundit? -%>
authorize @<%%= singular_table_name %>
<%- end -%>
if @<%%= orm_instance.update("#{singular_table_name}_params") %> render json: <%%= "@#{singular_table_name}" %> else render json: <%%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity end end # DELETE <%%= route_url %>/1 def destroy
<%- if pundit? -%>
authorize @<%%= singular_table_name %>
<%- end -%>
@<%%= orm_instance.destroy %> end private # Use callbacks to share common setup or constraints between actions. def assign_<%%= singular_table_name %> <%%- <%- if pundit? -%> finder_class = "policy_scope(#{class_name})" <%- else -%> finder_class = class_name <%- end -%> # Use friendly_id for slug lookup finder_class += ".friendly" if using_friendly_id -%> @<%%= singular_table_name %> = <%%= orm_class.find(finder_class, "params[:id]") %> end # Only allow a trusted parameter "white list" through. def <%%= "#{singular_table_name}_params" %>
<%- if pundit? -%>
permitted_attributes(@<%%= singular_table_name %> || <%%= class_name %>)
<%- else -%>
<%%- if attributes_names.empty? -%> params.fetch(:<%%= singular_table_name %>, {}) <%%- else -%> params.require(:<%%= singular_table_name %>).permit(<%%= permitted_params %>) <%%- end -%>
<%- end -%>
end
end <%% end -%>