Implementing Devise in a New Rails App

Devise is wildly powerful but pretty overwhelming the first couple times you use it. I’m going to try and fuddle my way through that process on a new project and document it all here. This guide will start right after generating the new rails project. I’m going to go as slow as possible.

1. add Devise to your gem file.
Screen Shot 2015-04-14 at 5.59.28 PM

I’m using Postgres for my database instead of SQLite. It’s a little easier to deploy to live. That’s the ‘pg’ gem. If you’re starting a fresh project, generate the project with this code to make your life easy: “rails new myapp – -database=postgresql”

If you’re like me and always forget to do that, remove the sqlite gem, add the pg gem, and use this code for you “config/database.yml” file: Railscasts #342

2. Run “bundle install” in your terminal

3. Run “rails generate devise:install” in your terminal
This adds the devise.rb to your config directory among other things. That file has a ton of options that you may need to implement as you use Devise. If this command hangs, you probably have a problem with Spring running in another rails application. Killing that process should fix that.

4. Run “rails generate devise user”
You’ll now have a migration available that creates a user table with email and password fields. Don’t mess with this file. You can always add columns to that table later but the beauty of devise is largely dependent on this migration.

If you’re running Postgres:
4a. Start the Postgres program
You can get it here Postgress App .
4b. Run “rake db:create”

5. Run “rake db:migrate”
Create that Users table!

Optional but recommended:
6. Run “rails generate devise:views users”
This makes a ton of stuff. It creates log in/log out pages, registration pages, and edit user pages. You can edit or delete these as you’d like.

That’s it! You now have a very secure user account system that has easy integration with OmniAuth for other log in systems.



Implementing Services in Rails

I’ve been struggling with MVC for a while. There seems to be a problem that I can’t quite put my finger on.

Models describe data.
Controllers route data.
Views show data.

Where do things that don’t fall into those categories go? I’m working on a product right now that needs a search engine. I started working on it, but quickly came back to my doubts about MVC. A search engine is not the model. It has to search through multiple tables. The logic for it is going to be a little big. Putting it in a controller seems like a miss use of the controller as well. Where should it go?

The answer:

Services are amazing. It’s the fourth corner stone of MVC. It should be called MVCS. Everything becomes beautiful and makes sense as you implement services. I’m going to go over what I did from start to finish to on that search feature.

Make a search feature that reads searches different or multiple tables based on the first character in the string. @ searches the user table. # searches the posts table. The search field is stored in the nav bar and routes to Users#search. This is the Users#search method inside the UserController:

  def search
    @q = params[:query]
    @results =
    render :"/users/index"

That’s a clean looking controller! There’s a trick to it though. “” is the service. First create a folder called “services” in the “app” directory. From there we’re going to make a file that shares the name of the class of the service we’re creating. In my case, it was search.rb. Here’s a look at the file structure and how to set-up services in a Rails app:

Screen Shot 2015-04-14 at 3.01.32 PM


Once we’re in “services/search.rb,” it becomes pretty easy to implement the search function. To account for upper and lower case characters, we added a column to our tables for a search field.

class Search

    if query[0] == "@"
      clean_search = "%#{query[1..-1]}%".downcase
    elsif query[0] == "#"
      clean_search = "%#{query[1..-1]}%".downcase
      clean_search = "%#{query}%".downcase

  def self.search_user(q)
    User.where("search_handle LIKE ? or name LIKE ?", q, q) 

  def self.search_tag(q)
    Post.where("search_post_content LIKE ?", q) 

  def self.search_all(q)
    results = []
    results[0] = Search.search_user(q)
    results[1] = Search.search_tag(q)

That feels nice and clean. We have a class that searches. If we need to adjust details about the search, we go to the search service and adjust. It’s not the controller. It’s not the model.

Services are a very important part of the MVC idea. Services are a great way to spread out the logic and reduce complexity.

Lovin and learnin js and ruby

Yay! Javascript and ruby are amazing! Different but both are great! Let’s take some time to look at a fun programming problem and figure it out with both languages.

I’m going to tackle Project Euler’s problem 25:

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?

The best way to solve this problem is to right a single procedural set of code to spit out the answer. I don’t like doing that. It’s not practical. Let’s right a few methods/functions so we could use numbers other than 1000 if we wanted to.

First, let’s right a method/function to figure out Fibonacci numbers. We don’t need to return an array of Fibonacci numbers, we just return the Fibonacci number and the index it would be inside of the pretend array of all Fibonacci numbers.

Current goal:
Return a two element array with the first element being the Fibonacci number and the second the which Fibonacci it is. Something like [55, 10]. Because of the size of the number we’re searching for, the recursive solution is much too slow.

# Take in a number. Return that number and 
# return it's Fibonacci number.
def fib(num)
  previous_fib = 0
  current_fib = 1
  num.times do |num|
  	previous_fib, current_fib = current_fib, current_fib + previous_fib
  [previous_fib, num]

=> [5, 5]
=> [55, 10]
=> [6765, 20]

Sweet. That works. We’re going to be using that array when finding Fibonacci numbers by number of digits. Let’s do it with javascript:

function fib(num) {
  var previousFib = 0;
  var currentFib = 1; 
  for (var i = 0; i < num; i++) {
    var temp = previousFib;
    previousFib = currentFib;
    currentFib = currentFib + temp
  return [previousFib, num];

> fib(5);
[ 5, 5 ]
> fib(10);
[ 55, 10 ]
> fib(20);
[ 6765, 20 ]

Alright! We’ve got our Fibonacci calculators. The only real difference between the two versions is on line 7 of the ruby code. That allows us to avoid using a temporary value when doing assignments that have some dependence on each other. It kind of says previous_fib is equal the current value of current_fib and current_fib is equal to previous_fib’s previous value plus current value’s current value.

The next part is a pretty to write but much, much harder on the computer. Here we’ll write a function that returns the index of the Fibonacci number that has a total number of digits equal to a given number. Let’s start with some ruby:

def fib_digit_length(num)
  answers = [0,0]
  index = 1
  while answers[0].to_s.length < num
    index += 1
    answers = fib(index)

=> [13, 7]
=> [144, 12]
=> [1597, 17]
=> [10946, 21]

# That all works and helps for testing, but a 1000 digit number is going to be brutal
# in console, so I'm going to just return the index.

=> 4782

Sweet. Problem done and the computer didn’t explode. If it had been done recursively, given the increase in time per digit calculated, and that my computer wouldn’t run out of memory(it would have), my computer would have taken over a week to compute the first 1000 digit number.

Let’s get the same thing going with javascript:

function fibDigitLength(num) {
  var answers = [0,0];
  for (var i = 0; answers[0].toString().length < num; i++) 
     answers = fib(i);
  return answers;

> fibDigitLength(2)
[ 13, 7 ]
> fibDigitLength(3)
[ 144, 12 ]
> fibDigitLength(4)
[ 1597, 17 ]
> fibDigitLength(5)
[ 10946, 21 ]
> fibDigitLength(20)
[ 12200160415121877000, 93 ]
> fibDigitLength(21)
[ 135301852344706760000, 98 ]
> fibDigitLength(22)
[ 1.5005205362068963e+21, 103 ]
> fibDigitLength(23)
[ 1.0221638535413418e+101, 485 ]
> fibDigitLength(24)
... 4ever


And then it gets bad. Javascript ‘can’t even’ with numbers that big. I’m having trouble finding good answers on exactly what is going on here. I found a script for using really big numbers but will try to implement it another time. The function works well but the language has some limitations on what it can deal with. To be fair, I can’t even imagine when you’d really need to manipulate a number that is 1k digits long. For funsies, here’s that number:


Going back and forth between languages is a little challenging, but like everything else, it gets better and smoother with practice.


Getting Rid of the Smoke and Mirrors in Rails

cave man lawyer

Rails is crazy powerful. There is so much that can be done with so little effort due to the incredible library of methods and commands built in to this framework. That “magic” frightens and confuses me. I don’t like typing in a large command having it do it’s magic with out knowing at least part of what’s happening. Rails is not magic. It is fantastic. Here’s why:

Rails on Github

Wouldn’t it be great if magicians immediately explained how they did the trick? That’s what Rails gives us! What does “form_for” actually do when you call it? What does Rails actually do when I type in “rails generate model test”? It’s all there! It’s beautiful and understandable!

rails generate model

HOLY WOW! That’s some complex code, but it is readable. Take a look at this code:


<% module_namespacing do -%>
class <%= class_name %> < <%= parent_class_name.classify %>
<% do |attribute| -%>
  belongs_to :<%= %><%= ', polymorphic: true' if attribute.polymorphic? %><%= ', required: true' if attribute.required? %>
<% end -%>
<% do |attribute| -%>
  has_secure_token<% if != "token" %> :<%= %><% end %>
<% end -%>
<% if attributes.any?(&:password_digest?) -%>
<% end -%>
<% end -%>

When you call “rails generate model test name:string story:text age:integer” it uses that template to make this model:

class Test < ActiveRecord::Base

To generate the migration, it uses this template:

class <%= migration_class_name %> < ActiveRecord::Migration
  def change
    create_table :<%= table_name %> do |t|
<% attributes.each do |attribute| -%>
<% if attribute.password_digest? -%>
      t.string :password_digest<%= attribute.inject_options %>
<% elsif attribute.token? -%>
      t.string :<%= %><%= attribute.inject_options %>
<% else -%>
      t.<%= attribute.type %> :<%= %><%= attribute.inject_options %>
<% end -%>
<% end -%>
<% if options[:timestamps] %>
<% end -%>
<% do |attribute| -%>
    add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true
<% end -%>
<% attributes_with_index.each do |attribute| -%>
    add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>
<% end -%>

And creates this migration:

class CreateTests < ActiveRecord::Migration
  def change
    create_table :tests do |t|
      t.string :name
      t.text :story
      t.integer :age

      t.timestamps null: false

Isn’t that neat! The magic is slowly fading. Being a huge nerd, my favorite show is Star Trek: the Next Generation. In season 3 episode 4, Picard saves the day by explaining his advanced technology to someone from a bronze era civilization. I believe it’s particularly relevant here:

PICARD (cont’d)
Now suppose one of your cave-dwelling
ancestors could see you
as you are today. What would she

I don’t know.

Put yourself in her place. You
have a power she lacks. You can
kill a hornbuck from a great

Only because I have a bow.

She has never seen a bow — it
doesn’t yet exist in her world.
To you, it’s a simple tool. To
her, it’s magic.

I suppose she might think so.

And how would she react to you?

I think… she would fear me.

picard approves

The Power of Pure Methods

Pure methods are really amazing. There are three reasons to use pure methods whenever possible:

1. Easier to test
2. Reduce side effects
3. Easier to reuse

Let’s start with what a pure method is. A pure method is a method that does not use ANY instance or class data. To allow a pure method to do anything, we must pass it arguments.

Here’s a very basic example of two classes that have a simple method. One is pure and one is not.

class Dirty
  def initialize(num1, num2)
    @num1 = num1
    @num2 = num2

  #Add the two instance variables
  def dirty_adder
    @num1 + @num2

class Pure
  def initialize
  #Add two arguments
  def pure_adder(first_number, second_number)
    first_number + second_number

These classes add two numbers. One uses the instances variables assigned at initialization, the other requires the arguments to be passed in. Let’s take a look at my 3 reasons to favor the pure method.

1. Easier to test.
To test the dirty method, we need to do this:

dirty =,4)
=> #<Dirty:0x007f9aa2698f68 @num1=5, @num2=4>
=> 9
pure =
=> #<Pure:0x007f9aa26e11a0>
=> 10
pure.pure_adder("Cat", 5)
TypeError: no implicit conversion of Fixnum into String

Either work fine, but when we actually test the method, one method gives us more information. What if num1 was changed into a string “cat” in dirty_adder? We would need to follow that variable around the code until figure out where the error in assignment occurs. With pure_adder, we can make sure it works and never look to that method again.

On a very practical level, it is very easy to copy a method in to pry or IRB and messier to copy an entire class. Which leads to point #2.

Side effects are a concept in computer science. Side effects in methods can be thought of as roots going from the method into the class. Every time a method touches an instance variable, there is an opportunity for side effects to arise. If the method is removed or changed, it make have side effects on other methods. Side effects can change values, methods, and increase code inter dependency. Code inter dependency becomes a large problem. Changing a part of one method could invalidate the results of others. Side Effects

Lastly, let’s look at reason #3: Easier to reuse

  #Add two arguments
  def pure_adder(first_number, second_number)
    first_number + second_number

This code has no dependency on any part of our class. This method could be added to any class with out causing problems with existing code. Once I write a truly beautiful pure method, I get to reuse that over and over again with out fear across multiple classes or projects.

This does not mean you should not use instance variables in methods. There are many times when pure methods are not an option. The idea I am trying to impart, is if you can write a pure method with out affecting your functionality, do it. It will be easier to test, less likely to cause unpredictable problems, and reduce work going forward.


I learned about pure methods from this presentation. It’s done largely in haskel and python but is pretty easy to follow.

Side Effects Are Not Your Friend

Making Simple Methods for Data Structures

A great way to clean up your code and help clear your mind when looking through nested arrays and hashes is to make methods particular to your data structure for finding pieces of information. Let’s take a look at a great example.

Let’s say we have a Ruby hash with a series of nested hashes and arrays that looks like this:

holidays = {
  :new_years => {
    :date => "01/01",
    :supplies => ["booze","party hats"]
  :valentines_day => {
    :date => "02/14",
    :supplies => ["flowers","booze","Marvin Gaye"]
  :april_fools_day => {
    :date => "04/01",
    :supplies => ["whoppie cushion","fake news"]
  :july_fourth => {
    :date => "07/04",
    :supplies => ["fire works","booze","BBQ"]
  :thanksgiving => {
    :date => "fourth Thursday of November",
    :supplies => ["turkey","tofurkey","pumpkin pie","stuffing","booze"]

This is a pretty basic data structure. We have a hash with five holidays. Each holiday has a hash with the date and an array of supplies used in the celebration.

Accessing the data in our holidays is pretty easy:

 => [:new_years, :valentines_day, :april_fools_day, :july_fourth, :thanksgiving] 
 => [:date, :supplies] 
 => ["booze", "party hats"] 

We can easily explore our data structure by repeating these processes. This mode of exploring the hash assumes we don’t know where everything is yet.

When we begin to ask the hash questions, it starts getting a little uglier. When we need to find things in different nests, methods become quite valuable. Here’s a few simple examples:

def date(holiday_name, data)

def supplies(holiday_name, data)

The first method “date”, simply returns the date of the a holiday. The second returns the supplies. When we have such a small data structure, it becomes easily debatable as to whether or not these save us any time. However even at this level, these methods become easier to read. This is a bit of opinion but take a look at these two examples:

supplies(:thanksgiving, holidays) 
#Supplies from Thanksgiving in holidays.

#Holidays has a key called Thanksgiving that has a key called supplies.

The difference is subtle and debatable. Let’s search for all the holidays that have “booze” as a supply. Here’s where it starts to become a worthwhile endeavor: do |holiday_name, values| #select in holidays
    values[:supplies].include?("booze")     #hashes that have value inside of supplies
  end.keys                                  #but just the keys of those hashes
 => [:new_years, :valentines_day, :july_fourth, :thanksgiving] 

The code works! Hooray! It’s a pain to read and look at, but it works. It sure would be great if it was as easy to understand as either of the prior examples. Check out this alternative:

 => [:new_years, :valentines_day, :july_fourth, :thanksgiving]

That makes sense! I can read that single line and know what to expect! Which holiday has “booze” as a supply? Let’s implement that method:

def holidays_with_supply?(supply, data) do |holiday_name, values|

On such a small piece of data, the importance of custom methods for looking over the structure seems trivial. As the size increases and the depth of nesting becomes greater, the time saved and clarity in code will become invaluable.