Module: PageMagic::Watchers

Included in:
Element, InstanceMethods
Defined in:
lib/page_magic/watchers.rb

Overview

module Watchers - contains methods for adding watchers and checking them

Constant Summary collapse

ELEMENT_MISSING_MSG =
'Unable to defined watcher: Element or method with the name %s can not be found'.freeze

Instance Method Summary collapse

Instance Method Details

#changed?(name) ⇒ Boolean

Returns true if a change is detected.

Parameters:

  • name (Symbol)
    • the name of the watcher

Returns:

  • (Boolean)

    true if a change is detected



10
11
12
13
# File 'lib/page_magic/watchers.rb', line 10

def changed?(name)
  watched_element = watcher(name)
  watched_element.last != watched_element.check(self).last
end

#watch(name, method = nil, &block) ⇒ Object

register a new watcher end

Examples:

watch(:price, :text)
watch(:something) do
 # more complicated code to get value

Parameters:

  • name (Object)

    of the watcher/element

  • method (Symbol) (defaults to: nil)
    • the method on the watched element to check

Yield Returns:

  • (Object)

    the value that should be checked

Raises:



25
26
27
28
29
30
# File 'lib/page_magic/watchers.rb', line 25

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

#watcher(name) ⇒ Watcher

retrieve a watcher given its name

Parameters:

  • name (Symbol)

    the name of the watcher

Returns:

  • (Watcher)

    watcher with the given name



35
36
37
# File 'lib/page_magic/watchers.rb', line 35

def watcher(name)
  watchers.find { |watcher| watcher.name == name }
end

#watchersArray

Returns registered watchers.

Returns:

  • (Array)

    registered watchers



40
41
42
# File 'lib/page_magic/watchers.rb', line 40

def watchers
  @watchers ||= []
end