Skip to content

Commit

Permalink
support regex attrs
Browse files Browse the repository at this point in the history
  • Loading branch information
Антон Спицын committed Aug 15, 2020
1 parent 52f6304 commit 4d5407b
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ speculate = "0.1.2"
html5ever = "0.25"
bit-set = "0.5"
markup5ever_rcdom = "0.1"
regex = "1.3.9"

[badges]
travis-ci = { repository = "utkarshkukreti/select.rs" }
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
extern crate bit_set;
extern crate html5ever;
extern crate markup5ever_rcdom;
extern crate regex;

pub mod document;
pub mod node;
Expand Down
11 changes: 11 additions & 0 deletions src/predicate.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use node::{self, Node};
use regex::Regex;

/// A trait implemented by all `Node` matchers.
pub trait Predicate {
Expand Down Expand Up @@ -94,6 +95,16 @@ impl<'a> Predicate for Attr<&'a str, ()> {
}
}

impl<'a> Predicate for Attr<&'a str, Regex> {
fn matches(&self, node: &Node) -> bool {
if let Some(attr) = node.attr(self.0) {
return self.1.is_match(attr)
}
false
}
}


/// Matches if the function returns true.
impl<F: Fn(&Node) -> bool> Predicate for F {
fn matches(&self, node: &Node) -> bool {
Expand Down
3 changes: 3 additions & 0 deletions tests/predicate_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ speculate! {
assert_eq!(Attr("id", "post-0").matches(&article), true);
assert_eq!(Attr("id", ()).matches(&html), false);
assert_eq!(Attr("id", ()).matches(&article), true);
assert_eq!(Attr("id", regex::Regex::new("post").unwrap()).matches(&article), true);
assert_eq!(Attr("class", regex::Regex::new("^category$").unwrap()).matches(&article), false);
assert_eq!(Attr("class", regex::Regex::new("category").unwrap()).matches(&article), true);
}

test "Fn(&Node) -> bool" {
Expand Down

0 comments on commit 4d5407b

Please sign in to comment.