Sha256: 8fed636c158c93d9144d80919e961dcc034f87d42b29d3fb3ac5a44ca13d4491

Contents?: true

Size: 1.4 KB

Versions: 6

Compression:

Stored size: 1.4 KB

Contents

# encoding: utf-8
require 'rails_best_practices/checks/check'

module RailsBestPractices
  module Checks
    # Check a model file to make sure mail deliver method is in observer not callback.
    #
    # Implementation: 
    # Record :after_create callback
    # Check method define, if it is a callback and call deliver_xxx message in method body, then it should use observer.
    class UseObserverCheck < Check

      def interesting_nodes
        [:defn, :call]
      end

      def interesting_files
        MODLE_FILES
      end

      def initialize
        super
        @callbacks = []
      end

      def evaluate_start(node)
        if :after_create == node.message
          remember_callbacks(node)
        elsif :defn == node.node_type and @callbacks.find { |callback| equal?(callback, node.message_name) }
          add_error "use observer" if use_observer?(node)
        end
      end

      private

      def remember_callbacks(node)
        node.arguments[1..-1].each do |argument|
          # ignore callback like after_create Comment.new
          if :lit == argument.node_type
            @callbacks << argument.to_s
          end
        end
      end

      def use_observer?(node)
        node.recursive_children do |child|
          return true if :call == child.node_type and :const == child.subject.node_type and child.message.to_s =~ /^deliver_/
        end
        false
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rails_best_practices-0.5.6 lib/rails_best_practices/checks/use_observer_check.rb
rails_best_practices-0.5.5 lib/rails_best_practices/checks/use_observer_check.rb
rails_best_practices-0.5.3 lib/rails_best_practices/checks/use_observer_check.rb
rails_best_practices-0.5.2 lib/rails_best_practices/checks/use_observer_check.rb
rails_best_practices-0.5.1 lib/rails_best_practices/checks/use_observer_check.rb
rails_best_practices-0.5.0 lib/rails_best_practices/checks/use_observer_check.rb