Sha256: f570f61fc691dd7444c7de28b619066b010de0c0f44f05704270b627302ae158

Contents?: true

Size: 1.63 KB

Versions: 6

Compression:

Stored size: 1.63 KB

Contents

# encoding: utf-8
require 'rails_best_practices/checks/check'

module RailsBestPractices
  module Checks
    # Check a controller file to make sure that complex model creation should not exist in controller, move it to model factory method
    #
    # Implementation: check the count of variable attribute assignment calling before saving, 
    # if more than defined attribute assignment count, then it's a complex creation.
    class ReplaceComplexCreationWithFactoryMethodCheck < Check
      
      def interesting_nodes
        [:defn]
      end
      
      def interesting_files
        CONTROLLER_FILES
      end
      
      def initialize(options = {})
        super()
        @attrasgn_count = options['attribute_assignment_count'] || 2
      end
      
      def evaluate_start(node)
        @variables = {}
        node.recursive_children do |child|
          case child.node_type
          when :attrasgn
            attribute_assignment(child)
          when :call
            call_assignment(child)
          else
          end
        end
        @variables = nil
      end
      
      private
      
      def attribute_assignment(node)
        variable = node.subject
        return if variable.nil? or ![:lvar, :ivar].include? node.subject.node_type
        @variables[variable] ||= 0
        @variables[variable] += 1
      end
      
      def call_assignment(node)
        if node.message == :save
          variable = node.subject
          add_error "replace complex creation with factory method (#{variable} attribute_assignment_count > #{@attrasgn_count})" if @variables[variable] > @attrasgn_count
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rails_best_practices-0.5.6 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb
rails_best_practices-0.5.5 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb
rails_best_practices-0.5.3 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb
rails_best_practices-0.5.2 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb
rails_best_practices-0.5.1 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb
rails_best_practices-0.5.0 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb