Class: RailsBestPractices::Reviews::LawOfDemeterReview

Inherits:
Review show all
Defined in:
lib/rails_best_practices/reviews/law_of_demeter_review.rb

Overview

Review to make sure not to avoid the law of demeter.

See the best practice details here rails-bestpractices.com/posts/15-the-law-of-demeter.

Implementation:

Review process:

check all method calls to see if there is method call to the association object.
if there is a call node whose subject is an object of model (compare by name),
and whose message is an association of that model (also compare by name),
and outer the call node, it is also a call node,
then it violate the law of demeter.

Constant Summary

Constants inherited from Core::Check

Core::Check::CONTROLLER_FILES, Core::Check::HELPER_FILES, Core::Check::MAILER_FILES, Core::Check::MIGRATION_FILES, Core::Check::MODEL_FILES, Core::Check::NODE_TYPES, Core::Check::PARTIAL_VIEW_FILES, Core::Check::ROUTE_FILE, Core::Check::SCHEMA_FILE, Core::Check::VIEW_FILES

Instance Attribute Summary

Attributes inherited from Core::Check

#errors

Instance Method Summary collapse

Methods inherited from Review

#equal?, #model_associations, #model_attributes, #models, #remember_variable_use_count, #reset_variable_use_count, #variable, #variable_use_count

Methods inherited from Core::Check

#add_error, #initialize, #interesting_files, #method_missing, #node_end, #node_start

Constructor Details

This class inherits a constructor from RailsBestPractices::Core::Check

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class RailsBestPractices::Core::Check

Instance Method Details

#interesting_nodesObject



24
25
26
# File 'lib/rails_best_practices/reviews/law_of_demeter_review.rb', line 24

def interesting_nodes
  [:call]
end

#start_call(node) ⇒ Object

check the call node,

if the subject of the call node is also a call node, and the subject of the subject call node matchs one of the class names, and the message of the subject call node matchs one of the association name with the class name, like

s(:call,
  s(:call, s(:ivar, :@invoice), :user, s(:arglist)),
  :name,
  s(:arglist)
)

then it violates the law of demeter.



41
42
43
44
45
# File 'lib/rails_best_practices/reviews/law_of_demeter_review.rb', line 41

def start_call(node)
  if [:lvar, :ivar].include?(node.subject.subject.node_type) && need_delegate?(node)
    add_error "law of demeter"
  end
end

#urlObject



20
21
22
# File 'lib/rails_best_practices/reviews/law_of_demeter_review.rb', line 20

def url
  "http://rails-bestpractices.com/posts/15-the-law-of-demeter"
end