Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

support regex attrs #65

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ repository = "https://github.com/utkarshkukreti/select.rs"
bit-set = "0.5"
html5ever = "0.25"
markup5ever_rcdom = "0.1"
regex = "1.3.9"

[dev-dependencies]
speculate = "0.1.2"
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
extern crate regex;

pub mod document;
pub mod node;
pub mod predicate;
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 crate::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 @@ -70,6 +70,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