Skip to content

Instantly share code, notes, and snippets.

@cheald
Created January 4, 2015 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cheald/7250694096dc2d6ff8ca to your computer and use it in GitHub Desktop.
Save cheald/7250694096dc2d6ff8ca to your computer and use it in GitHub Desktop.
# This extends the Jsoup elements collection with #nonblank_attr. Extending Java classes from Ruby == awesome
class ::Java::OrgJsoupSelect::Elements
def nonblank_attr(attr, default = nil)
attr = attr.to_s
e = find { |el| el.attr(attr).present? }
e ? e.attr(attr) : default
end
end
include_package 'org.jsoup'
document = Jsoup.parse(body, uri)
title = document.select('title').text
document.select('meta[itemprop=title], meta[name=og:title], meta[name=twitter:title]').nonblank_attr('content')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment