Rails: Cannot Parse JSON object neither with hash key or index - ruby-on-rails

Weird question tag but still wanted to ask because even though it looks easy no matter what I've tried I could not accomplish
I'm trying to parse duration between to points from a URL given by Google Maps directions API. Thanks an answer I've received from here I was able to capture the JSON object and get to the duration object however no matter what I did I could not get the inner values "text" or "value" from the "duration" attribute.
Here is the response;
{
"text" : "6 mins",
"value" : 373
}
And here is the code I've written in rails
#request = Net::HTTP.get(URI.parse('http://maps.googleapis.com/maps/api/directions/json?origin=40.983204,29.0216549&destination=40.99160908659266,29.02334690093994&sensor=false'))
hash = JSON.parse #request
duration = hash['routes'][0]['legs'][0]['duration']
respond_to do |format|
format.html {render :index}
format.json {render json: duration}
end
Note: Of course, the [0] and ['text'] methods have been tried.

As a first thing you need to define duration as an instance variable to have it available in your views (if this is where you need to use it)
#duration = hash['routes'][0]['legs'][0]['duration']

duration["text"] and duration["value"] didn't work?
1.9.3p194 :001 > require 'net/http'
=> true
1.9.3p194 :002 > require 'json'
=> true
1.9.3p194 :003 > #request = Net::HTTP.get(URI.parse('http://maps.googleapis.com/maps/api/directions/json?origin=40.983204,29.0216549&destination=40.99160908659266,29.02334690093994&sensor=false'));
1.9.3p194 :004 > hash = JSON.parse #request;
1.9.3p194 :005 > duration = hash['routes'][0]['legs'][0]['duration']
=> {"text"=>"6 mins", "value"=>373}
1.9.3p194 :006 > duration["text"]
=> "6 mins"
1.9.3p194 :007 > duration["value"]
=> 373

Related

Why I18n translations change when local variable with a selected translation key changes?

This is above me today. Hope someone can explain this to me!
Assume you have a rails project with a en.yml file with the following contents:
en:
foo:
foo: foo
bar: bar
Assigning the results of I18n.t(:foo) to a local variable, you get a Hash:
2.0.0-p353 :001 > a = I18n.t(:foo)
=> {:foo=>"foo", :bar=>"bar"}
And now, changing a value for a key in this Hash causes changes in I18n.t('foo.foo'):
2.0.0-p353 :005 > a[:foo] = 'bar'
=> "bar"
2.0.0-p353 :006 > I18n.t(:foo)
=> {:foo=>"bar", :bar=>"bar"}
So, for the question to be clear - why changing a[:foo] from 'foo' to 'bar', causes the changes in I18n.t('foo.foo')?
Thanks in advance!
After
a = I18n.t(:foo)
The reference a does not hold a copy, but reference to the same Hash. Altering the Hash at a modifies the same Hash at I18n.t(:foo).
This is not special behavior of I18n.t, rather this is normal behavior for Ruby.
> a
=> {:foo=>:bar, :baz=>:qux}
> b = a
=> {:foo=>:bar, :baz=>:qux}
> b[:foo] = 1
=> 1
> b
=> {:foo=>1, :baz=>:qux}
> a
=> {:foo=>1, :baz=>:qux}

How to integrate a simple bitcoin API into a Rails app

I am new to API's and backend development in general and have been trying for a few hours now to figure out how to do something simple like call the current bitcoin market price into my Rails app.
I tried referencing http://blockchain.info/ticker with the following code in my model
require 'rest-client'
require 'json'
base_url = "http://blockchain.info/ticker"
response = RestClient.get base_url
data = JSON.load response
cool = data[0]["CNY"]
#test = JSON.pretty_generate cool
and then put this in my view
<%= #test %>
I know this is way off but I'm at a loss and figured I would see if someone could provide a good resource or maybe get me going in the right direction. Many thanks
Dude, its all working good.
Replace data[0]["CNY"] with data["CNY"], thats all.
To get more handle, execute these lines 1 by 1 in irb,
Just like this,
1.9.3p385 :001 > require 'rest-client'
=> true
1.9.3p385 :002 > require 'json'
=> true
1.9.3p385 :004 > base_url = "http://blockchain.info/ticker"
=> "http://blockchain.info/ticker"
1.9.3p385 :005 > response = RestClient.get base_url
1.9.3p385 :006 > data = JSON.load response
1.9.3p385 :007 > cool = data["CNY"]
=> {"15m"=>5519.13613, "last"=>5519.13613, "buy"=>5578.16433, "sell"=>5853.54832, "24h"=>5616.47, "symbol"=>"¥"}
1.9.3p385 :008 > #test = JSON.pretty_generate cool
=> "{\n \"15m\": 5519.13613,\n \"last\": 5519.13613,\n \"buy\": 5578.16433,\n \"sell\": 5853.54832,\n \"24h\": 5616.47,\n \"symbol\": \"¥\"\n}"
1.9.3p385 :009 > p #test
"{\n \"15m\": 5519.13613,\n \"last\": 5519.13613,\n \"buy\": 5578.16433,\n \"sell\": 5853.54832,\n \"24h\": 5616.47,\n \"symbol\": \"¥\"\n}"
=> "{\n \"15m\": 5519.13613,\n \"last\": 5519.13613,\n \"buy\": 5578.16433,\n \"sell\": 5853.54832,\n \"24h\": 5616.47,\n \"symbol\": \"¥\"\n}"
I would recommend you use httparty which makes sending requests much simpler.
With regards to your example, you could do
require 'httparty'
require 'json'
base_url = "http://blockchain.info/ticker"
response = HTTParty.get(base_url)
data = JSON.parse(response.body)
data.each_pair do |ticker, stats|
pp "Ticker: #{ticker} - 15m: #{stats['15m']}"
end
Obviously I am pp (printing) out a string just to show the data. You would actually render the data in the view if you were to do a real implementation.

ActiveRecord object marked as dirty when old value and new value are both numeric zero

I have a model called Day that represents a day in a timesheet. I've noticed that whenever I call #day.save it's writing to the database, even though none of the object's properties have had their values changed.
#day = Day.last
=> #<Day lunch_minutes: 0, updated_at: "2012-08-19 12:09:40", work_hours: 5.5>
A day has its length in hours, and the length of its lunch break in minutes, stored. I've cropped out some properties that aren't relevant.
#day.lunch_minutes
=> 0
#day.lunch_minutes = 0
=> 0
#day.changes
=> {"lunch_minutes"=>[0, 0]}
#day.lunch_minutes_changed?
=> true
That should be false. Compare to a value that isn't zero:
#day.work_hours = 5.5
=> 5.5
#day.work_hours_changed?
=> false
So if I call save, this gets called. Ideally there would be no unnecessary database interaction here.
#day.save
(0.5ms) UPDATE "days" SET "lunch_minutes" = 0, "updated_at" = '2012-08-19 12:22:59.586860' WHERE "days"."id" = 48
I'm not sure if this is a Rails bug or if I'm doing some incorrectly somewhere. It looks like it could be an issue in "changes_from_zero_to_string?" - I think adding a && value != 0 to that method would fix it - but I want to know if anyone else has seen this/a fix for this before?
What version of rails are you using? I just had a go in my app (3.1.5/1.8.7) and it doesn't behave this way.. I just used a random integer property on one of my models to test with:
1.8.7 :006 > o = Order.first
=> <Order id:...>
1.8.7 :007 > o.order_items_count
=> 0
1.8.7 :008 > o.order_items_count = 0
=> 0
1.8.7 :009 > o.changes
=> {}
1.8.7 :010 > o.order_items_count = '0'
=> "0"
1.8.7 :011 > o.changes
=> {}
1.8.7 :012 > o.save
(0.1ms) BEGIN
(0.1ms) COMMIT
=> true
It appears to be a bug.
Interestingly, according to the code, if you do:
#day.lunch_minutes = '0'
It will probably think it has not changed!
Try that, and if indeed this change causes #day.lunch_minutes_changed? to be false, then make sure it is reported as an issue to https://github.com/rails/rails.

Rails to_json uses different DATE_FORMATS that .to_s

With the following in my rails_defaults.rb:
Date::DATE_FORMATS[:default] = '%m/%d/%Y'
Time::DATE_FORMATS[:default]= '%m/%d/%Y %H:%M:%S'
Why do the following results differ:
ruby-1.9.2-p180 :005 > MyModel.find(2).to_json(:only => :start_date)
=> "{\"start_date\":\"2012-02-03\"}"
ruby-1.9.2-p180 :006 > MyModel.find(2).start_date.to_s
=> "02/03/2012"
And more importantly, how do I get to_json to use %m/%d/%Y?
Because the standard JSON format for a date is %Y-%m-%d and there's no way to change it unless you override Date#as_json (don't do so or your application will start misbehaving).
See https://github.com/rails/rails/blob/master/activesupport/lib/active_support/json/encoding.rb#L265-273
class Date
def as_json(options = nil) #:nodoc:
if ActiveSupport.use_standard_json_time_format
strftime("%Y-%m-%d")
else
strftime("%Y/%m/%d")
end
end
end

opening Array in ruby on rails console v. irb

I wish to make my code a little more readable by calling #rando on any array and retrieve a random element (rando because a rand() method already exists and I don't want there to be any confusion).
So I opened up the class and wrote a method:
class Array
def rando
self[ rand(length) ]
end
end
This seems far too straightforward.
When I open up irb, and type arr = %w(hi bye) and then arr.rando I get either hi or bye back. That's expected. However, in my rails console, when I do the same thing, I get ArgumentError: wrong number of arguments (1 for 0)
I've been tracing Array up the rails chain and can't figure it out. Any idea?
FWIW, I'm using rails 2.3.11 and ruby 1.8.7
Works fine in my case :
Loading development environment (Rails 3.0.3)
ruby-1.9.2-p180 :001 > class Array
ruby-1.9.2-p180 :002?> def rando
ruby-1.9.2-p180 :003?> self[ rand(length) ]
ruby-1.9.2-p180 :004?> end
ruby-1.9.2-p180 :005?> end
=> nil
ruby-1.9.2-p180 :006 > arr = %w(hi bye)
=> ["hi", "bye"]
ruby-1.9.2-p180 :007 > arr.rando
=> "bye"

Resources