Created
June 2, 2014 02:17
-
-
Save choonkeat/fb2f81daadd1083c40bc to your computer and use it in GitHub Desktop.
Inefficient but expressive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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