I use Ruby 2.5.0, httparty gem My model
class FeedEntry
include Mongoid::Document
include Mongoid::Timestamps
field :guid, type: String
field :url, type: String
field :share_count, type: Integer, default: 2
before_update :share_info
def share_info
checked_url = self.url
json_stats = HTTParty.get("http://api.sharedcount.com/?url=#{checked_url}&apikey=#{Rails.application.credentials.socialshared_api_key}", timeout: 180, open_timeout: 1200)
self.share_count = json_stats['Facebook']['share_count']
end
end
And when I try to parse i have this error
NoMethodError: undefined method `[]' for nil:NilClass
/Users/ipatov/rails_projects/apps/tm/app/models/feed_entry.rb:71:in `share_info'
71 line self.share_count = json_stats['Facebook']['share_count']
This is one of most common errors regarding what Rollbar says
The problem must be than json_stats['Facebook']
is nil
, so accessing to ['share_count']
produces an error. I recommend you to use dig to prevent this undesired error and decide what to do when json_stats['Facebook']
is nil
.
self.share_count = json_stats.dig('Facebook', 'share_count')