Class: Domino

Inherits:
Object
  • Object
show all
Extended by:
Capybara::DSL, Enumerable
Includes:
Capybara::DSL
Defined in:
lib/domino.rb

Overview

assert_nil Dom::Post.find_by_title(‘First Post’)

Defined Under Namespace

Classes: Error

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#nodeObject (readonly)

Direct access to the capybara node, in case you need anything special



45
46
47
# File 'lib/domino.rb', line 45

def node
  @node
end

Class Method Details

.allObject

Get an array of all the Dominos



58
59
60
# File 'lib/domino.rb', line 58

def all
  map{|node| node}
end

.attribute(attribute, selector = nil, &callback) ⇒ Object

Define an attribute for this Domino

module Dom
  class Post
    attribute :title # defaults to selector '.title'
    attribute :body, '.post-body' # use a custom selector
  end
end

This will define an attr_reader on the Domino and also a find_by_attribute method:

Dom::Post.all.first.title
Dom::Post.find_by_title("First Post")
Dom::Post.find_by_title(/^First/)


96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/domino.rb', line 96

def attribute(attribute, selector = nil, &callback)
  attributes << attribute
  callbacks[attribute] = callback

  selector ||= %{.#{attribute.to_s.gsub("_", "-")}}

  class_eval %{
    def #{attribute}
      value = attribute(%{#{selector}})
      if value && self.class.callbacks[:#{attribute}].is_a?(Proc)
        self.class.callbacks[:#{attribute}].call(value)
      else
        value
      end
    end
    def self.find_by_#{attribute}(value)
      find_by_attribute(%{#{selector}}, value)
    end
  }
end

.attributesObject



73
74
75
# File 'lib/domino.rb', line 73

def attributes
  @attributes ||= []
end

.callbacksObject



77
78
79
# File 'lib/domino.rb', line 77

def callbacks
  @callbacks ||= {}
end

.eachObject

Iterate over all the Dominos



51
52
53
54
55
# File 'lib/domino.rb', line 51

def each
  nodes.each do |node|
    yield new(node)
  end
end

.selector(s) ⇒ Object

Define the selector for this Domino

module Dom
  class Post
    selector '#posts .post'
  end
end


69
70
71
# File 'lib/domino.rb', line 69

def selector(s)
  @selector = s
end

Instance Method Details

#attribute(selector) ⇒ Object

Get the text of the first dom element matching a selector

Dom::Post.all.first.attribute('.title')


136
137
138
139
140
# File 'lib/domino.rb', line 136

def attribute(selector)
  @node.find(selector).text
rescue Capybara::ElementNotFound
  nil
end

#attributesObject



147
148
149
150
151
152
# File 'lib/domino.rb', line 147

def attributes
  self.class.attributes.inject({}) do |memo, attribute|
    memo[attribute] = send(attribute)
    memo
  end
end

#idObject

Dom id for this object.



143
144
145
# File 'lib/domino.rb', line 143

def id
  @node['id'].nil? ? nil : %{##{@node['id']}}
end