class RailsBestPractices::Reviews::ReplaceComplexCreationWithFactoryMethodReview

Review a controller file to make sure that complex model creation should not exist in controller, should be replaced with factory method.

See the best practice details here rails-bestpractices.com/posts/2010/07/21/replace-complex-creation-with-factory-method/

Implementation:

Review process:

check all method defines in the controller files,
if there are multiple attribute assignments apply to one receiver,
and the receiver is a variable,
and after them there is a call node with message "save" or "save!",
then these attribute assignments are complex creation, should be replaced with factory method.

Public Class Methods

new(options = {}) click to toggle source
Calls superclass method
# File lib/rails_best_practices/reviews/replace_complex_creation_with_factory_method_review.rb, line 23
def initialize(options = {})
  super(options)
  @assigns_count = options['attribute_assignment_count'] || 2
end

Private Instance Methods

check_variable_save(node) click to toggle source

check the call node to see if it is with message “save” or “save!”, and the count attribute assignment on the receiver of the call node is greater than @assign_count defined, then it is a complex creation, should be replaced with factory method.

# File lib/rails_best_practices/reviews/replace_complex_creation_with_factory_method_review.rb, line 55
def check_variable_save(node)
  if ['save', 'save!'].include? node.message.to_s
    variable = node.receiver.to_s
    if variable_use_count[variable].to_i > @assigns_count
      hint = "#{variable} attribute_assignment_count > #{@assigns_count}"
      add_error "replace complex creation with factory method (#{hint})"
    end
  end
end