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 filtering Items Arrays by Regex #458
Conversation
@@ -34,6 +34,8 @@ def freeze | |||
def [](*args) | |||
if 1 == args.size && args.first.is_a?(String) | |||
item_with_identifier(args.first) | |||
elsif 1 == args.size && args.first.is_a?(Regexp) | |||
@items.select { |i| i.identifier[args.first] } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ewww. that's possibly the ugliest way of checking for a regex match :P
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't write nearly enough Ruby to know any better :P What would you recommend?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i.identifier =~ args.first
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah, okay. Fixed.
I'm curious: is this purely stylistic or is there some performance consideration as well?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't know, I've never benchmarked it.
rb_str_aref_m(int argc, VALUE *argv, VALUE str)
{
if (argc == 2) {
if (RB_TYPE_P(argv[0], T_REGEXP)) {
return rb_str_subpat(str, argv[0], argv[1]);
}
return rb_str_substr(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]));
}
rb_check_arity(argc, 1, 2);
return rb_str_aref(str, argv[0]);
}
I imagine it's ever so slightly slower, since it has to check the number of arguments and check whether the first is a regexp before calling it, but mostly it's because it doesn't look right.
This is a convenience API for working with the `@items` array in nanoc's `preprocess` block. In that context, it is common to manipulate items according to a shared part of their identifier. For example, with this change in place, users could succinctly create a collection of all authors for a given site's weblog: @Items[%r{^/weblog/authors/}].each { |author| # etc... }
LGTM |
Support filtering Items Arrays by Regex
Sweet! |
This is a convenience API for working with the
@items
array in nanoc'spreprocess
block. In that context, it is common to manipulate itemsaccording to a shared part of their identifier.
For example, with this change in place, users could succinctly create a
collection of all authors for a given site's weblog: