PageRenderTime 21ms CodeModel.GetById 1ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/rails_best_practices/reviews/simplify_render_in_views_review.rb

http://github.com/flyerhzm/rails_best_practices
Ruby | 47 lines | 28 code | 6 blank | 13 comment | 7 complexity | 5f3e65647f0101d02c058e5def7ffa5d MD5 | raw file
 1# frozen_string_literal: true
 2
 3module RailsBestPractices
 4  module Reviews
 5    # Review a view file to make sure using simplified syntax for render.
 6    #
 7    # See the best practice details here https://rails-bestpractices.com/posts/2010/12/04/simplify-render-in-views/
 8    #
 9    # Implementation:
10    #
11    # Review process:
12    #   check all render method commands in view files,
13    #   if there is a key 'partial' in the argument, then they should be replaced by simplified syntax.
14    class SimplifyRenderInViewsReview < Review
15      interesting_nodes :command
16      interesting_files VIEW_FILES
17      url 'https://rails-bestpractices.com/posts/2010/12/04/simplify-render-in-views/'
18
19      VALID_KEYS = %w[object collection locals].freeze
20
21      # check command node in view file,
22      # if its message is render and the arguments contain a key partial,
23      # then it should be replaced by simplified syntax.
24      add_callback :start_command do |node|
25        if node.message.to_s == 'render'
26          hash_node = node.arguments.all.first
27          if hash_node && hash_node.sexp_type == :bare_assoc_hash && include_partial?(hash_node) &&
28               valid_hash?(hash_node)
29            add_error 'simplify render in views'
30          end
31        end
32      end
33
34      protected
35
36      def include_partial?(hash_node)
37        hash_node.hash_keys.include?('partial') && !hash_node.hash_value('partial').to_s.include?('/')
38      end
39
40      def valid_hash?(hash_node)
41        keys = hash_node.hash_keys
42        keys.delete('partial')
43        (keys - VALID_KEYS).empty?
44      end
45    end
46  end
47end