Reputation: 2299
I want to check the price of a certain product on a certain webshop.
I'm using a constant to store a Hash of webshop data so editing is easier (more stores will be added).
Here's the code I'm using:
require 'httparty'
require 'nokogiri'
class Prijscheckr
STORES = {
:zara => {
'base_uri' => 'http://www.zara.com/nl/',
'normal_price_css' => 'p.price > span',
'css_normal_price_extract' => "[0].attr('data-price')",
'normal_price_xpath' => '/p[3]/span',
'xpath_normal_price_extract' => "[0].attr('data-price')"
}
}
def begin(args = {})
page = Nokogiri::HTML(HTTParty.get(args[:url]))
price = page.css(STORES[:zara]['normal_price_css'])STORES[:zara]['css_normal_price_extract']
end
end
When doing
p = Prijscheckr.new
p.begin(url: 'http://www.zara.com/nl/nl/collectie-aw14/dames/jacks/leren-bikerjack-c269184p2137577.html')
Here are the results:
# Works
# price = page.css('p.price > span')[0].attr('data-price')
# Works
# price = page.css(STORES[:zara]['normal_price_css'])[0].attr('data-price')
# Does not work
# price = page.css(STORES[:zara]['normal_price_css'])STORES[:zara]['css_normal_price_extract']
How can I concatenate price = page.css(STORES[:zara]['normal_price_css'])STORES[:zara]['css_normal_price_extract']
without hard coding it in the method?
Upvotes: 0
Views: 3503
Reputation: 1493
Ruby code cannot be created by concatenation of string. You might like to declare css_normal_price_extract
as a lamba
'css_normal_price_extract' => ->(val) {val[0].attr('data-price')}
price = STORES[:zara]['css_normal_price_extract'].call(page.css(STORES[:zara]['normal_price_css']))
Upvotes: 2