Sha256: de0e1fc6a37419d4cd05958d79267333ed959252d96bcfe400ba140b72e65fa7

Contents?: true

Size: 1.5 KB

Versions: 3

Compression:

Stored size: 1.5 KB

Contents

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.rb$/
      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?
        @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" if @variables[variable] > @attrasgn_count
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rails_best_practices-0.1.2 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb
rails_best_practices-0.1.1 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb
rails_best_practices-0.1.0 lib/rails_best_practices/checks/replace_complex_creation_with_factory_method_check.rb