Skip to content

Instantly share code, notes, and snippets.

@choonkeat
Created June 2, 2014 02:17
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 choonkeat/fb2f81daadd1083c40bc to your computer and use it in GitHub Desktop.
Save choonkeat/fb2f81daadd1083c40bc to your computer and use it in GitHub Desktop.
Inefficient but expressive
Hash.class_eval do
# returns an array of values
def csspath(path, options = {})
Nokogiri::HTML(self.to_xml).css(path.dasherize).collect {|element|
result = Hash.from_xml(element.to_s)
(options[:include_keys] ? result : result.values.first)
}
end
end
hash = {
cart: {
created_at: "2014-05-16 04:51:13 UTC",
id: "cart:1234",
line_items: [
{
title: "Item A",
price: "123.45"
},
{
title: "Item B",
price: "234.56"
}
]
},
customer: {
name: "John",
email: "john.appleseed@example.com"
}
}
hash.csspath('cart created_at, nothing here, line_items title, customer name')
# => ["2014-05-16 04:51:13 UTC", "Item A", "Item B", "John"]
hash.csspath('cart created_at, nothing here, line_items title, customer name', include_keys: true)
# => [{"created_at"=>"2014-05-16 04:51:13 UTC"}, {"title"=>"Item A"}, {"title"=>"Item B"}, {"name"=>"John"}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment