Sha256: 9c6a74ab925a6a2bb3e96e97359c1aeb3212027be7e8ca47a343612ab24b80c3

Contents?: true

Size: 1.91 KB

Versions: 27

Compression:

Stored size: 1.91 KB

Contents

module Xcake
  # This namespace provides all of methods for
  # implementing the Vistor in the  Visitor pattern.
  #
  # This implementation has a slight twist where
  # a visitor knows when it has "left" an object
  # it is visiting.
  #
  # Classes implementing these methods should
  # add methods `visit_<visitable classname>`
  # and `leave_<visitable classname>` for each
  # visitable they intend to use that class with.
  #
  # @example Implementing Visitor Pattern
  #
  #          class Writer
  #
  #             include Visitor
  #
  #             def visit_page
  #               #Write Page
  #             end
  #
  #             def leave_page
  #               #Append Footer
  #             end
  #          end
  #
  module Visitor
    # This is called when a visitor is visiting a
    # visitable item.
    #
    # By default this method calls the method
    # `visit_<visitable classname>` so make sure
    # you've created a method for each visitable you
    # intend to visit.
    #
    # @param [Visitable] visitable
    #                    the visitable item the visitor is visiting
    #
    def visit(item)
      item_name = item_name(item)

      method = "visit_#{item_name}"
      send(method, item) if respond_to? method
    end

    # This is called when a visitor is leaving a
    # visitable item.
    #
    # By default this method calls the method
    # `leave_<visitable classname>` so make sure
    # you've created a method for each visitable you
    # intend to visit.
    #
    # @param [Visitable] visitable
    #                    the visitable item the visitor has left
    #
    def leave(item)
      item_name = item_name(item)

      method = "leave_#{item_name}"
      send(method, item) if respond_to? method
    end

    private

    def item_name(item)
      class_name = item.class.to_s

      class_name.gsub!('Xcake::', '')
      class_name.gsub!('::', '_')

      class_name.downcase!
    end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
xcake-0.13.0 lib/xcake/visitor.rb
xcake-0.12.1 lib/xcake/visitor.rb
xcake-0.12.0 lib/xcake/visitor.rb
xcake-0.11.0 lib/xcake/visitor.rb
xcake-0.10.0 lib/xcake/visitor.rb
xcake-0.9.4 lib/xcake/visitor.rb
xcake-0.9.3 lib/xcake/visitor.rb
xcake-0.9.2 lib/xcake/visitor.rb
xcake-0.9.1 lib/xcake/visitor.rb
xcake-0.9.0 lib/xcake/visitor.rb
xcake-0.8.13 lib/xcake/visitor.rb
xcake-0.8.12 lib/xcake/visitor.rb
xcake-0.8.10 lib/xcake/visitor.rb
xcake-0.8.9 lib/xcake/visitor.rb
xcake-0.8.8 lib/xcake/visitor.rb
xcake-0.8.7 lib/xcake/visitor.rb
xcake-0.8.6 lib/xcake/visitor.rb
xcake-0.8.3 lib/xcake/visitor.rb
xcake-0.8.1 lib/xcake/visitor.rb
xcake-0.7.1 lib/xcake/visitor.rb