refactoring - Rails refactor: Duplicate code in some controllers. Where does it belong? -


i have similar (duplicate?) code appearing in few controllers. it's in #update action, it's in #update_multiple action...and it's in both.

in cases it's code that's primary purpose set belongs_to relationship, setting product_id on controller's model. uses first_or_create if referenced product not exist created first.

duplicate code:

product = product.where(params[:product]).first_or_create if params[:product] if product && params[:project][:code].present?   project = project.where(params[:project]).first_or_create    product.project = project if project end product.save if product 

quick overview or relationships: _items & _files belong_to product. products can belong_to project.

where can/should extract to? i'm not sure if should go product (and project) models? or perhaps in applicationcontroller? or helper?

here's examples of code in 'wild':

#disk_files_controller.rb   ...   def update     product = product.where(params[:product]).first_or_create if params[:product]     if product && params[:project][:code].present?       project = project.where(params[:project]).first_or_create       product.project = project if project     end     product.save if product      respond_to |format|       if @disk_file.update(disk_file_params)         format.html { redirect_to @disk_file, notice: 'disk_file updated.' }         format.json { head :no_content }       else         format.html { render action: 'edit' }         format.json { render json: @disk_file.errors, status: :unprocessable_entity }       end     end   end 

example of update_multiple

#inventory_items_controller.rb   ...   def update_multiple     product = product.where(params[:product]).first_or_create if params[:product]     if product && params[:project][:code].present?       project = project.where(params[:project]).first_or_create        product.project = project if project     end     product.save if product      @inventory_items = inventoryitem.find(params[:inventory_item_ids])     update_hash = {product_id: product.id}     update_hash.merge({project_code: params[:project][:code]}) unless params[:project][:code].blank?     inventoryitem.update_all(update_hash, {id: params[:inventory_item_ids]})     redirect_to inventory_items_url   end   ... 

i'd extract product model:

class product   def self.first_or_create_by_params(params)     # code here, return product   end end 

then in controller:

product.first_or_create_by_params(params) 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -