Demian Sims
Demian Sims

Reputation: 921

Conversion of String into DateTime works in console but not in request (Rails)?

I'm building a wrapper from an API and if I convert a string to datetime using DateTime.parse(), it works fine when checking in console but not in a controller method index request. I get the classic 'no implicit conversion of nil into String datetime' error.

Here's my code:

class SodaApi < ApplicationRecord
  include HTTParty 

  def self.opportunities_api 
    client = SODA::Client.new({:domain => "data.cityofnewyork.us", :app_token => "<my api key>"})
    response = HTTParty.get("https://data.cityofnewyork.us/resource/n4ac-3636.json") 
      result = response.map do |r| 
      created_date = DateTime.parse(r['created_date'])
      end_date = DateTime.parse(r['end_date'])

      ### I build my wrapper here ###
    end
  end 
end

in rails c, using byebug, I'm able to create a variable of created_date and convert from a string to Datetime no problem.

Upvotes: 1

Views: 49

Answers (1)

mrzasa
mrzasa

Reputation: 23347

There are over 600 elements in the returned JSON that doesn't have end_date or start_date

response = HTTParty.get("https://data.cityofnewyork.us/resource/n4ac-3636.json")
response.find_all{|r| r['start_date'].nil? }.count
# => 665
response.find_all{|r| r['end_date'].nil? }.count
# => 665

You need to handle those cases, e.g. by setting a default or by not parsing the date in this case:

  def parse_date(string)
     return nil unless string
     DateTime.parse(string)
  end

  result = response.map do |r| 
    created_date = parse_date(r['created_date'])
    end_date = parse_date(r['end_date'])
    # ...
  end

Upvotes: 1

Related Questions