Skip to content

Instantly share code, notes, and snippets.

@paulbaker3
Last active February 9, 2016 22:20
Show Gist options
  • Save paulbaker3/27c29e5ebf768ebae949 to your computer and use it in GitHub Desktop.
Save paulbaker3/27c29e5ebf768ebae949 to your computer and use it in GitHub Desktop.
Extracting the create action from the ProductsController. Found in Fearless Refactoring Rails Controllers, pg 31
# Declare the new route in routes.rb
post 'products' => 'create_product#create'
resources :products
# Intermediate state depending on inheritance to pass tests
class CreateProductController < ProductsController
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render “products/show”, status: :created, location: @product }
else
format.html { render “products/new” }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
end
# Extracted dependencies from ProductsController. No longer relying on inheritance
class CreateProductController < ApplicationController
before_filter :filter_the_things
def create
@product = Product.new(product_params)
respond_to do |format|
if @product.save
format.html { redirect_to @product, notice: 'Product was successfully created.' }
format.json { render “products/show”, status: :created, location: @product }
else
format.html { render “products/new” }
format.json { render json: @product.errors, status: :unprocessable_entity }
end
end
end
private
def product_params
params.require(:product).permit(:name, :description)
end
def filter_the_things
# contrived example code here
end
end
# Kill the original :create route in routes.rb
post 'products' => 'create_product#create'
resources :products, except: [:create]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment