Today I Learned

5 posts about #ruby

a Ruby Module is a Class that can be subclassed

Great article at http://tech.degica.com/en/2017/10/03/rubykaigi/ by Chris Salzberg

some of the most interesting features of a language are not the ones that are cleverly designed, but the ones that emerge out of a clever design

Ruby has a safe operator, no need to try anymore

Wow, how did I miss this memo? Ruby 2.3 introduced a safe operator

Instead of

current_user.try(:profile).try(:bio)

you can now do

current_user&.profile&.bio

Use fetch method to access ENV variables in Ruby

It's better for at least a couple of reasons, eloquently stated in this blog post by Michal Orman

...we can set default values or handle - providing a block - gracefully missing keys. Also using fetch with unknown key will raise KeyError that will tell us which exactly key is missing. That is in fact the behavior we are expecting from the app. Without required settings is just not working and complaining about missing setting and not about some random nil references.

Got that? Instead of this:

AWS.config(
  access_key_id:      ENV['S3_ACCESS_KEY'],
  secret_access_key:  ENV['S3_SECRET_KEY'],
  region:             ENV['S3_REGION']
)

Do this:

AWS.config(
  access_key_id:      ENV.fetch('S3_ACCESS_KEY'),
  secret_access_key:  ENV.fetch('S3_SECRET_KEY'),
  region:             ENV.fetch('S3_REGION')
)

Keyword arguments in Ruby 2

Ruby 2 gained keyword arguments while I was away in Javascript-land the last few years, and somehow I missed the memo. Loving the elegance of how you specify defaults and required parameters.

Thoughtbot has the best writeup.

I suspect I will not be using non-keyword arguments in my Ruby code anymore.

Don't try to modify strings that come out of ENV

Today I woke up to an exception RuntimeError: can't modify frozen String

I looked at the code that had raised the exception. It was doing a gsub! on a value out of params. It took me a bit of digging to figure out why it failed. Turns out there's an edge case that causes one of those values to get pulled out of ENV instead of the normal flow where it originates from the user.

Strings coming out of ENV are frozen. D'oh!