Rails:重构 - json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]
Rails: Refactoring - json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]
标题中的问题差不多。重构如下内容的最佳方法是什么?
json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]
我想 return nil
除非 json["data"]["counts"]["followed_by"]
存在。
您可以使用 try :
json.try(:[], 'data').try(:[], 'counts').try(:[], 'followed_by')
我倾向于 andand
gem 长 try
链,例如,
json.andand['data'].andand['counts'].andand['followed_by']
IMO 它看起来更好。
标题中的问题差不多。重构如下内容的最佳方法是什么?
json["data"]["counts"]["followed_by"] if json && json["data"] && json["data"]["counts"] && json["data"]["counts"]["followed_by"]
我想 return nil
除非 json["data"]["counts"]["followed_by"]
存在。
您可以使用 try :
json.try(:[], 'data').try(:[], 'counts').try(:[], 'followed_by')
我倾向于 andand
gem 长 try
链,例如,
json.andand['data'].andand['counts'].andand['followed_by']
IMO 它看起来更好。