Help refactoring this controller method

This is in a CMS type application, and the controller is for creating a ‘page’.

I have:

def create

category = Category.find( params[:categor_id] )

text = params[:article_body]

article = Article.new

article.category_id = category.id

article.ip_address = request.remote_ip

artcle.original_text = text

article.formatted_text = ## some markdown call here to parse text

article.user_id = current_user.id

article.is_approved = true

article.save

end

Now the problem is I do the same sort of thing for updates and other places, how would you suggest I refactor this?

You could create a method in the Article class that handles all this.

class Article

def self.custom_create(category, user, text, ip_address, is_approved) a = Article.new a.category_id = category.id a.ip_address = ip_address a.user_id = user.id a.original_text = text a.formatted_text = text.markdowned() a.is_approved = is_approved a.save end

end

Then you could just call this from your controller:

Article.custom_create(category, current_user, params[:article_body], request.remote_ip, true)

Maybe what you need is make use of rails_best_practices gem

https://github.com/flyerhzm/rails_best_practices

once you install it and run in your rails project it will discover this kind of problematic controllers and tell you about 'code smell'. Plus, it will point you to solution on http://rails-bestpractices.com/. Anyway, if you run this gem in console, then just search by 'problem message' on rails-bestpractices.com site and you will find post which explain how to remedy 'code smell' how they call it.

What Tim Shaffer replied you is called - Factory Method:

http://rails-bestpractices.com/posts/6-replace-complex-creation-with-factory-method