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