0

Question is pretty much in the title. What's the best way to refactor something like below?

json["data"]["counts"]["followed_by"] if json &&  json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]

I want to return nil unless json["data"]["counts"]["followed_by"] exists.

Baldrick
  • 23,882
  • 6
  • 74
  • 79
Jackson Cunningham
  • 4,973
  • 3
  • 30
  • 80

2 Answers2

1

You can use try :

json.try(:[], 'data').try(:[], 'counts').try(:[], 'followed_by')
Baldrick
  • 23,882
  • 6
  • 74
  • 79
1

I tend towards the andand gem over long try chains, e.g.,

 json.andand['data'].andand['counts'].andand['followed_by']

IMO it just looks nicer.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302