module ControllerScaffolder

Public Instance Methods

scaffold!(user_options = {}) click to toggle source
# File lib/controller_scaffolder.rb, line 3
def scaffold! user_options = {}
  resource = user_options[:resource] || self.to_s.underscore.split("/").last.split("_")[0..-2].join("_")

  options = {
    singular: resource.singularize,
    plural: resource.pluralize,
    instance_member: "@#{resource.singularize}",
    instance_collection: "@#{resource.pluralize}",
    model_name: resource.singularize.camelize
  }

  options.merge!(user_options)

  class_eval %{
    before_action :set_#{options[:singular]}, only: [ :show, :edit, :update, :destroy ]

    def index
      #{options[:instance_collection]} = #{options[:model_name]}.all
    end

    def show
    end

    def new
      #{options[:instance_member]} = #{options[:model_name]}.new
    end

    def edit
    end

    def create
      #{options[:instance_member]} = #{options[:model_name]}.new(#{options[:singular]}_params)

      if #{options[:instance_member]}.save
        redirect_to #{options[:instance_member]}, notice: '#{options[:singular].humanize} was successfully created.'
      else
        render action: 'new'
      end
    end

    def update
      if #{options[:instance_member]}.update(#{options[:singular]}_params)
        redirect_to #{options[:instance_member]}, notice: '#{options[:singular].humanize} was successfully updated.'
      else
        render action: 'edit'
      end
    end

    def destroy
      #{options[:instance_member]}.destroy
      redirect_to #{options[:plural]}_path, notice: '#{options[:singular].humanize} was successfully destroyed.'
    end

    private

    def set_#{options[:singular]}
      #{options[:instance_member]} = #{options[:model_name]}.find(params[:id])
    end

    def #{options[:singular]}_params
      params.require(:#{options[:singular]}).permit(#{options[:permitted_fields]})
    end
  }
end