Sha256: 068e2b68c924d4d578a9a3b713676a2d8b231c6910303ebc961b4c9c73ef9444

Contents?: true

Size: 1.36 KB

Versions: 1

Compression:

Stored size: 1.36 KB

Contents

require 'rails_best_practices/checks/check'

module RailsBestPractices
  module Checks
    # Check a view file to make sure there is no complex logic call for model.
    #
    # Implementation: Check if a local variable or instance variable called more than 3 times in if statuement, then it should more code into model.
    class MoveCodeIntoModelCheck < Check

      def interesting_nodes
        [:if]
      end

      def interesting_files
        VIEW_FILES
      end

      def evaluate_start(node)
        @variables = {}
        node.grep_nodes(:node_type => :call).each { |call_node| remember_call(call_node) }
        check_errors
      end

      private

      def check_errors
        @variables.each do |node, count|
          add_error "move code into model (#{node.to_ruby})" if count > 2
        end
      end

      def remember_call(call_node)
        variable_node = variable(call_node)
        if variable_node
          @variables[variable_node] ||= 0
          @variables[variable_node] += 1
        end
      end

      def variable(call_node)
        while call_node.subject.node_type == :call
          call_node = call_node.subject
        end
        subject_node = call_node.subject
        if [:ivar, :lvar].include?(subject_node.node_type) and subject_node[1] != :_erbout
          subject_node
        else
          nil
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rails_best_practices-0.3.13 lib/rails_best_practices/checks/move_code_into_model_check.rb