Today I Learned

Installing the pg gem with the Postgres app

Everytime I need to install the pg gem to use Postgres with Rails I see the following error, and everytime I forget the solution.

An error occurred while installing pg (1.1.3), and Bundler cannot continue.
Make sure that gem install pg -v '1.1.3' --source 'https://rubygems.org/' succeeds before bundling.

Well, hey there, future self. Nice to see you. I think this is what you’re looking for.

gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/latest/bin/pg_config

Using pattern matching to compare two strings

Elixir’s pattern matching feature is the gift that keeps on giving. I love this neat trick to check if two strings are the same. It is an easy way to check if a password and password confirmation match.

def passwords_match?(password, password), do: true

def passwords_match?(_, _), do: false

passwords_match?("password", "password") # true
passwords_match?("password", "notpassword") # false

Named arguments in Ruby

Using Ruby’s keyword arguments you can avoid the pitfalls of positional arguments as well as the extra code needed to extract values from a hash.

def total(subtotal:, tax:, discount:)
    subtotal + tax - discount
end

Default values can be provided if a named argument is not given to a method call.

def total(subtotal: 0, tax: 0, discount: 0)
  subtotal + tax - discount
end