Rails Three Little Hacks

Rails Three Little Hacks

As I’ve missed my last 2 posts, I’m going to now regale you with not 1, not 2, but 3 (three!) of my favorite little hacks ruby hacks.

Digg

Do you have a deeply nested structures you want 1 value from deep inside? Don’t care if the path is broken? Use digg! I especially love this to get deeply nested data out of a JSON response.

01 module Digg
02   def digg(*path)
03     path.inject(self) do |memo, key|
04       (memo.respond_to?(:[]) && (memo[key] || {})) || break
05     end
06   end
07 end
08
09 Array.send :include, Digg
10 Hash.send :include, Digg
11
12 # Use as
13 some_complex_json_rsponse.digg('preview''thumbnail', 0, 'id')
1 <span style="font-family:sans-serif,arial,verdana,trebuchet ms; font-size:13px; line-height:1.6em">(Would you believe there is no digging related emoji? Have a                     </span>