Module: ControllerScaffolder

Included in:
ActionController::Base
Defined in:
lib/controller_scaffolder.rb

Instance Method Summary collapse

Instance Method Details

#scaffold!(user_options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# 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