thoughtbot / ios-on-rails

A guide to building a Rails API and iOS app
Other
76 stars 6 forks source link

events_controller device_token explanation #54

Closed edwardloveall closed 10 years ago

edwardloveall commented 10 years ago

Loving the book so far. Thanks for writing it. :+1:

I was pretty confused about this method in the events_controller:

def device_token
  params[:owner].try(:[], :device_token)
end

I did some documentation diving and I figured out that it seems to call params[:owner][:device_token] with try which returns nil if it doesn't exist which will create a new user, or find the user with that token if it does exist. That's super smart but I had never seen the rails try method before. The array method made it all the more opaque to my brain.

I only mention it because it's the first time so far in the book that I've been confused on what the code did and didn't have an explanation conveniently right in front of me. Could have just been a mental hiccup too.

jessieay commented 10 years ago

Hi again @edwardloveall - The try above is being used as shorthand for:

if params[:owner] && params[:owner][:device_token]
    params[:owner][:device_token]
end 

The full if statement is more explicit, but try is nice and short. In some cases I would prefer the explicit, but since this method is unlikely to grow because all it is doing is returning a device_token, I am going to keep it as is for now.

If you would like to see this changed or explained more thoroughly in the book, definitely submit a PR and I will take a look! :)