Permalink
Browse files

Add ability to pass block to attribute

This allows for the ability to modify/typecast the string coming back
from Capybara.
  • Loading branch information...
ersatzryan committed Mar 16, 2013
1 parent 2ef9823 commit d5443cc469256982917a2c1c74f8cb98a8f72edb
Showing with 37 additions and 4 deletions.
  1. +9 −0 README.md
  2. +18 −3 lib/domino.rb
  3. +10 −1 test/domino_test.rb
View
@@ -12,6 +12,15 @@ define a selector and attributes:
selector '#posts .post'
attribute :title # selector defaults to .title
attribute :body, '.post-body' # example of selector override
+
+ # pass a block if you want to modify the value
+ attribute :comments do |text|
+ text.to_i
+ end
+
+ attribute :posted_at do |text|
+ Date.parse(text)
+ end
end
end
View
@@ -7,6 +7,11 @@
# selector '#posts .post'
# attribute :title # selector defaults to .title
# attribute :body, '.post-body' # example of selector override
+#
+# # accepts blocks as callbacks these are run only if attribute exists
+# attribute :comments do |text|
+# text.to_i
+# end
# end
# end
#
@@ -69,6 +74,10 @@ def attributes
@attributes ||= []
end
+ def callbacks
+ @callbacks ||= {}
+ end
+
# Define an attribute for this Domino
#
# module Dom
@@ -84,14 +93,20 @@ def attributes
# Dom::Post.all.first.title
# Dom::Post.find_by_title("First Post")
# Dom::Post.find_by_title(/^First/)
- def attribute(attribute, selector = nil)
- attributes << attribute.to_sym
+ def attribute(attribute, selector = nil, &callback)
+ attributes << attribute
+ callbacks[attribute] = callback
selector ||= %{.#{attribute.to_s}}
class_eval %{
def #{attribute}
- attribute(%{#{selector}})
+ 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)
View
@@ -18,11 +18,13 @@ def call(env)
<h2 class='name'>Alice</h2>
<p class='bio'>Alice is fun</p>
<p class='fav-color'>Blue</p>
+ <p class='age'>23</p>
</div>
<div class='person'>
<h2 class='name'>Bob</h2>
<p class='bio'>Bob is smart</p>
<p class='fav-color'>Red</p>
+ <p class='age'>52</p>
</div>
<div class='person'>
<h2 class='name'>Charlie</h2>
@@ -55,6 +57,9 @@ class Person < Domino
attribute :name
attribute :biography, '.bio'
attribute :favorite_color, '.fav-color'
+ attribute :age do |text|
+ text.to_i
+ end
end
class Animal < Domino
@@ -123,6 +128,10 @@ def test_node_properties
end
def test_attributes
- assert_equal({name: 'Alice', biography: 'Alice is fun', favorite_color: 'Blue'}, Dom::Person.first.attributes)
+ assert_equal({name: 'Alice', biography: 'Alice is fun', favorite_color: 'Blue', age: 23}, Dom::Person.first.attributes)
+ end
+
+ def test_callback
+ assert_equal 23, Dom::Person.find_by_name("Alice").age
end
end

0 comments on commit d5443cc

Please sign in to comment.