WEEK 8: RAILS

“Try being informed instead of just opinionated.”

Lawrence Hunt
9 min readDec 20, 2016

I rounded off the weekend with the ‘Ruby Refresher’ questions — there are a hell of a lot of them, but I managed to properly re-acquaint myself with a fair bit of the juiciest Ruby syntax and learn lots of new stuff too. Here are some of my favourites:

Convert array to hash with Hash[*array]

Amazingly short way of separating an element into key value pairs.

Another hash function: swap keys and values with hash.invert

And then one that combines these last two to create a hash from array_with_index:

array = ["Adult", "Family", "Single", "Child"]
Hash[[*array.map.with_index]].invert
# => {0=>"Adult", 1=>"Family", 2=>"Single", 3=>"Child"}

And now for some Regular Expressions!

The long successions of punctuation that precisely pluck the characters you need out of an argument. I have finally stopped running away screaming and taken the time to understand and accept them. Hopefully with the following explanation you will do the same.

To break that down:

gsub returns a copy of email with all instances of the first argument replaced with the second argument.

/ forward slashes denote the beginning and end of the regexp.

All of the following are metacharacters and have specific meanings when you place them after a term. (If you want to search for these characters literally you’ll need an escaping backslash):

(, ), [, ], {, }, ., ?, +, *

( ) Parentheses create a capture group — this is the domain bit we’re capturing.

‘\1’ (in our second argument) denotes ‘the first thing to be captured (put between brackets)

[ ] Square brackets denotes a section that may or may not be there.

. Period denotes any character except a line break

* Star denotes a character appearing zero or more times

+ Plus sign one or more times

? Question mark zero or one times

^ Caret says ‘NOT this’

So overall what we’re saying is: an ‘email address’ has ‘one or more characters followed by an @ symbol, followed by (start recording!) one or more of anything EXCEPT a dot (stop recording!), followed by one or more characters. Now replace what you find in ‘email’ that matches this email expression criteria, and return me a copy with JUST the first instance where I was recording.

Just one more! group_by

Neato, you can split an array into more arrays by way of how it responds to a block!

Now all aboard the Rails Train!

Rails was created by a well-known Danish technologist and all-round baller, David “DHH” Heinemeier Hansson. He happened to feature on a Tim Ferris podcast I listened to recently—an interesting four hours if you have that kind of time.

He’s also the founder of Basecamp, a project management startup and author of two popular books aimed at entrepreneurs, Rework and Remote.

I find some of Tim Ferris’s guests almost unlistenably glib, but DHH is definitely an exception. He’s full of cool hyper-logical trains of thought on all kinds of interesting topics, from what he loves about Ruby, to car racing, to stoic philosophy and finding ‘flow’ in your work. I particularly enjoyed a point he made about work-life balance: why put 100% of yourself into being in the top 5% at one thing, when you could enjoy being good at several things? This article has similarly contrarian thinking about the world of Silicon Valley entrepreneurship.

The podcast’s titled ‘The Power of Being Outspoken’, which corresponds to what I would agree was probably the most powerful point DHH made. About 1 hour in, he starts talking about the importance of being opinionated. In business, he says, if you’re not prioritising in a discussion, if your judgements don’t sacrifice anything, then you’re not really contributing anything of value.

And now I see how that philosophy maps straight onto the Rails framework he built, with the ‘convention over configuration’ principle — a term that he coined himself.

It’s like a fine-tuned race car—everything has to be structured and labelled stringently according to the Rails pattern. But in return, it saves you a huge amount of time by automating much of the set up and configuration process.

Coming from Sinatra where you create every file yourself, we had a bit of a Jeremy Clarkson moment when we first saw the the Rails command line scaffolding in action.

Need a Posts model with a description: text property? One line.

rails g model Post description:text

Need a Welcome page at /index? Ok, so we’re going to need a controller file, a view…oh no wait:

bin/rails generate controller Welcome index

Done. (It creates your controller AND your view, along with helpers, testing and supporting javascript and css files too!)

And it all handles surprisingly easily, thanks to the clear and friendly documentation—reading through the page on Active Record Associations felt like a big step up in my learning.

Not that there weren’t complications — in fact there were a fair few, I’ll list off the two main ones and hopefully save you a bit of time…

Adding Facebook Login to your Rails app.

I’m going to assume you’re following the instructions for the Makers Yelp app, and you’ve gotten as far as adding the Devise gem and creating the User model already. The guide linked in the instructions for the Facebook side of things takes you as far as the hiding of secrets, but that’s where a few people got a bit stuck. So to supplement that, here’s a quick walkthrough of the whole process from start to finish.

Add the Omniauth-facebook gem and run ‘bundle install’.

Now use the Rails migration methods covered in the guide:

rails g migration AddOmniauthToUsers provider:string uid:string
rake db:migrate

Add omniauth config to config > initializers > devise.rb

Line 12 below.

Make your User model ‘Omniauthable’.

Line 10.

Add omniauth to config > routes.rb

Line 4.

Add the ‘sign in with facebook’ link to your view

Add your controller

This is your controllers > users >omniauth_callbacks_controller.rb file. You can find the code on the guide here.

Go back to your User model…

and add your self.from_omniauth method here.

Getting your Facebook Dev Tools app ID and secret

Go here, set up your account and find them in dashboard, top of the left menu.

Then head a little further down on the left to the Facebook Login product menu. Add http://localhost:3000 to the field under Valid OAuth redirect URIs (when you push to heroku you’ll need to add that URL too).

Remember, you can only have one set of credentials per app — so if you’re doing it again for the weekend homework, you need to add another app to the menu on the left and repeat the process.

Adding your references to your secrets in config>secrets.yml

These are just references to a hidden file, which is next:

And finally, the bit where people got confused: creating somewhere to store these credentials that won’t get uploaded to github.

The envyable gem is a good solution — it creates a hidden env.yml file in the config folder. So: start by adding the gem and hitting ‘bundle install’.

Then run envyable install in the command line. This will automatically create the env.yml file and add it to gitignore so it won’t get uploaded to github.

Now hit atom config/env.yml in your command line to open the file, and save your info inside as follows, using the same environment variables that you’ve specified in config>initializers>devise.rb (in my case FB_APP_ID and FB_APP_SECRET). Just the top 2 lines there — the other stuff is for the similar process involved in configuring Amazon Web Services so you can store images.

And that’s it! You’re hooked up to the Zuckerberg empire.

And now for another of this week’s problems: an issue with Spring

We all noticed an irritating bug while running certain rake commands where the process just wouldn’t finish. Turned out to be an issue with Spring, which is a Rails application preloader. Apparently, Spring speeds up development by keeping your application running in the background so you don’t need to boot it every time you run a test, rake task or migration.

For our purposes all you need to do is run spring stop in the command line whenever it happens and the problem’s fixed. I enjoyed this command: sounds kind of like you’re the Ice Queen.

But what’s actually happening? Well, I looked into it and according to jafrog on Stack Overflow, it’s caused when we switch branches: “Spring hangs when checking out a branch that has changes in one of the monitored files: Gemfile or config files. In this case Spring reloads an application on background. If your application prints any warnings on initialise the process will wait to access STDOUT which never happens as Spring's application process runs on background. In my case the solution was to disable warnings with $VERBOSE=nil on top of the config/application.rb because the app wasn't trying to print anything but warnings. But of course it won't do if you want to keep seeing warnings.”

Finally: adding Bootstrap to Rails

Not really so much of a problem, this one, more of just a simple how-to.

Thanks to Rails’s zero-to-app-in-5-seconds speed, I finally found the time to have a fiddle with CSS this weekend while building an Instagram clone.

And I figured I might as well give Bootstrap a go too… It’s a CSS framework which adds a bunch of pre-written CSS classes that you can use on your content. Really useful for quickly adding things like nav menus — I managed to create the below in a matter of minutes.

This is how I added Bootstrap:

1. Add ‘bootstrap-sass’ to your gem file and hit ‘bundle install'

2. Go to assets > stylesheets > applications.css…

…and add the following two import lines to the bottom of it:

@import "bootstrap-sprockets";
@import "bootstrap";

Note that you don’t need to add anything extra to the corresponding application.html.erb file.

3. Rename the file application.scss, not .css

4. Go to assets > javascripts > application.js…

…and add the following line somewhere to the commented out require lines:

//= require bootstrap-sprockets

5. Now you’re ready to start bringing in template elements!

I downloaded a template called Bare and just took the body elements from the index.html page.

10/10 for fun app development with Rails this week. I want to build another one!

--

--