Skip to content

Commit

Permalink
improve reliability to google changes
Browse files Browse the repository at this point in the history
  • Loading branch information
mcansky committed Oct 8, 2012
1 parent 6e83907 commit 5796e04
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 18 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
rate_man (0.0.6)
rate_man (0.0.8)
active_support

GEM
Expand Down
22 changes: 9 additions & 13 deletions lib/rate_man.rb
Expand Up @@ -10,6 +10,14 @@ module RateMan

mattr_accessor :api_key, :google_api_url, :custom_search_id

def self.proper_line(snippet)
snippet.split('...').select { |l| RateMan.match(l.gsub(/^\s/,'').gsub(/\s$/,'')) }.first
end

def self.match(string)
string =~ /\d EUR = \d*\.\d* CHF [-\+]?\d*\.\d* \([-\+]?\d*\.\d*\%\)/
end

def self.query_url(from_cur, to_cur)
"#{@@google_api_url}?key=#{self.api_key}&cx=#{@@custom_search_id}&q=1%20#{from_cur}%20to%20#{to_cur}"
end
Expand All @@ -30,19 +38,7 @@ def self.raw_response(from_cur, to_cur)
end

def self.query(from_cur, to_cur)
incorrect = true
acceptable_time = true
i = 0
while incorrect && acceptable_time
string = JSON.parse(RateMan.raw_response(from_cur, to_cur))['items'].first['snippet'].split('...')[1]
incorrect = false if string =~ /\d EUR = \d*\.\d* CHF [-\+]?\d*\.\d* \([-\+]?\d*\.\d*\%\)/
i += 1
acceptable_time = false if i > 5
end
if incorrect
raise ArgumentError, "incorrect json"
end
string.split(' ')
RateMan.proper_line(JSON.parse(RateMan.raw_response(from_cur, to_cur))['items'].first['snippet']).split(' ')
end

def self.get(from_cur, to_cur)
Expand Down
2 changes: 1 addition & 1 deletion lib/rate_man/version.rb
@@ -1,3 +1,3 @@
module RateMan
VERSION = "0.0.6"
VERSION = "0.0.8"
end
6 changes: 3 additions & 3 deletions spec/lib/rate_man_spec.rb
Expand Up @@ -82,11 +82,11 @@
it "should get an answer from google" do
open(RateMan.query_url('EUR', 'CHF')).class.should eq Tempfile
end
it { RateMan.match("1 EUR = 1.2114 CHF -0.00017 (-0.014%)").should be_true }
it "should get an answer from google" do
items = JSON.parse(RateMan.raw_response('EUR', 'CHF'))['items']
items.first['snippet'].split('...')[1].split(' ').class.should eq Array
result = items.first['snippet'].split('...')[1].gsub(/^\s/,'').gsub(/\s$/,'')
result.should match /\d EUR = \d*\.\d* CHF [-\+]?\d*\.\d* \([-\+]?\d*\.\d*\%\)/
RateMan.proper_line(items.first['snippet']).class.should eq String
RateMan.proper_line(items.first['snippet']).should match /\d EUR = \d*\.\d* CHF [-\+]?\d*\.\d* \([-\+]?\d*\.\d*\%\)/
# ["1", "EUR", "=", "1.2114", "CHF", "-0.00017", "(-0.014%)"]
end
it "should get a json" do
Expand Down

0 comments on commit 5796e04

Please sign in to comment.