Sha256: ea3c1b1f66a17cacb77f1935249a83651bc513a93e0bec502f04375ec58edf28

Contents?: true

Size: 1.48 KB

Versions: 9

Compression:

Stored size: 1.48 KB

Contents

require 'page_magic/watcher'

module PageMagic
  # module Watchers - contains methods for adding watchers and checking them
  module Watchers
    ELEMENT_MISSING_MSG = 'Unable to defined watcher: Element or method with the name %s can not be found'.freeze

    # @param [Symbol] name - the name of the watcher
    # @return [Boolean] true if a change is detected
    def changed?(name)
      watched_element = watcher(name)
      watched_element.last != watched_element.check(self).last
    end

    # register a new watcher
    # @param [Object] name of the watcher/element
    # @param [Symbol] method - the method on the watched element to check
    # @yieldreturn [Object] the value that should be checked
    # @example
    #  watch(:price, :text)
    # @example
    #  watch(:something) do
    #   # more complicated code to get value
    # end
    def watch(name, method = nil, &block)
      raise ElementMissingException, (ELEMENT_MISSING_MSG % name) unless block || respond_to?(name)
      watched_element = block ? Watcher.new(name, &block) : Watcher.new(name, method)
      watchers.delete_if { |w| w.name == name }
      watchers << watched_element.check(self)
    end

    # retrieve a watcher given its name
    # @param [Symbol] name the name of the watcher
    # @return [Watcher] watcher with the given name
    def watcher(name)
      watchers.find { |watcher| watcher.name == name }
    end

    # @return [Array] registered watchers
    def watchers
      @watchers ||= []
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
page_magic-1.2.9 lib/page_magic/watchers.rb
page_magic-1.2.8 lib/page_magic/watchers.rb
page_magic-1.2.8.alpha lib/page_magic/watchers.rb
page_magic-1.2.7 lib/page_magic/watchers.rb
page_magic-1.2.6 lib/page_magic/watchers.rb
page_magic-1.2.5 lib/page_magic/watchers.rb
page_magic-1.2.5.alpha1 lib/page_magic/watchers.rb
page_magic-1.2.4 lib/page_magic/watchers.rb
page_magic-1.2.3 lib/page_magic/watchers.rb