Permalink
Browse files

Change controller generator template

Now it is more like the rails 4 controller template, using
before_(filter|action) to set the instance variable @resource and with
strong parameters.
  • Loading branch information...
1 parent c7479d6 commit 4111fb5d7dbb2bd55b22d58ec2504a70650969e3 @MarceloCajueiro MarceloCajueiro committed Jul 9, 2013
View
22 lib/generators/rails/responders_controller_generator.rb
@@ -22,6 +22,26 @@ def orm_instance_update(params)
orm_instance.update_attributes params
end
end
+
+ def controller_before_filter
+ if defined?(ApplicationController) && ApplicationController.respond_to?(:before_action)
+ "before_action"
+ else
+ "before_filter"
+ end
+ end
+
+ def attributes_params
+ if strong_parameters_defined?
+ "#{file_name}_params"
+ else
+ "params[:#{file_name}]"
+ end
+ end
+
+ def strong_parameters_defined?
+ defined?(ActionController::StrongParameters)
+ end
end
end
-end
+end
View
27 lib/generators/rails/templates/controller.rb
@@ -1,5 +1,7 @@
<% module_namespacing do -%>
class <%= controller_class_name %>Controller < ApplicationController
+ <%= controller_before_filter %> :set_<%= file_name %>, only: [:show, :edit, :update, :destroy]
+
<% unless options[:singleton] -%>
def index
@<%= table_name %> = <%= orm_class.all(class_name) %>
@@ -8,7 +10,6 @@ def index
<% end -%>
def show
- @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
respond_with(@<%= file_name %>)
end
@@ -18,25 +19,37 @@ def new
end
def edit
- @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
end
def create
- @<%= file_name %> = <%= orm_class.build(class_name, "params[:#{file_name}]") %>
+ @<%= file_name %> = <%= orm_class.build(class_name, attributes_params) %>
<%= "flash[:notice] = '#{class_name} was successfully created.' if " if flash? %>@<%= orm_instance.save %>
respond_with(@<%= file_name %>)
end
def update
- @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
- <%= "flash[:notice] = '#{class_name} was successfully updated.' if " if flash? %>@<%= orm_instance_update("params[:#{file_name}]") %>
+ <%= "flash[:notice] = '#{class_name} was successfully updated.' if " if flash? %>@<%= orm_instance_update(attributes_params) %>
respond_with(@<%= file_name %>)
end
def destroy
- @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
@<%= orm_instance.destroy %>
respond_with(@<%= file_name %>)
end
+
+ private
+ def set_<%= file_name %>
+ @<%= file_name %> = <%= orm_class.find(class_name, "params[:id]") %>
+ end
+ <%- if strong_parameters_defined? -%>
+
+ def <%= "#{file_name}_params" %>
+ <%- if attributes_names.empty? -%>
+ params[:<%= file_name %>]
+ <%- else -%>
+ params.require(:<%= file_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>)
+ <%- end -%>
+ end
+ <%- end -%>
end
-<% end -%>
+<% end -%>

0 comments on commit 4111fb5

Please sign in to comment.