If you are brand new to MongoDB and Rails 4, take a quick look at my very basic rails 4 mongodb tutorial before diving into this one.

Gems: mongoid, omniauth, figaro

Let’s get started

Make sure you have Rails 4 (rails -v). We’ll make a Rails app skipping test-unit (-T), since I prefer RSpec, and omitting ActiveRecord (-O) since we’ll be using MongoDB.

rails new parakeet -T -O
cd parakeet

Add the following to the Gemfile

gem "mongoid", git: 'git://github.com/mongoid/mongoid.git'
gem "omniauth-twitter"
gem "figaro"    # key configuration using ENV 

Now some auto-code generation for quick setup:

rails g mongoid:config
#      create  config/mongoid.yml

rails generate figaro:install
#      create  config/application.yml
#      append  .gitignore

I’ve decided to use figaro which allows me to easily configure my API keys without committing them to my source repo, which is very helpful when posting open source code. We need to set up the app for an API key in order to auth with Twitter.

Get Developer Key from Twitter

Sign in using your regular Twitter account at: https://dev.twitter.com/

Then in the upper-right, select “my applications”

Click “Create a new application” and fill in the form. I called my app blue-parakeet for uniqueness — you’ll have to make up your own name.

Make sure you put in a callback URL, even though you won’t use it for development (since omniauth tells twitter the callback URL to override this setting) — if you don’t supply one you will get a 401 unauthorized error.

Read and Accept the Terms, then click “Create Your Twitter Application”

Now you have a “key” and “secret” (called “consumer key” and “consumer secret”) which you will need to configure your rails app.

Using Figaro gem for Configuring API keys

Edit config/application.yml

# config via Figaro gem, see: https://github.com/laserlemon/figaro
# rake figaro:heroku to push these to Heroku
TWITTER_KEY: ABCLConsumerKeyCopiedFromTwitterDevPortal
TWITTER_SECRET: XYZConsumerSecretCopiedFromTwitterDevPortal

Configuring Omniauth

Edit config/initializers/omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
end

Now Omniauth is already setup to auth with twitter. Let’s run the server. Install mongo with brew install mongodb if you haven’t already. Also, if you don’t have mongo set up to run automatically at startup, then run Mongo:

mongod

Then run Rails server:

rails s

Go to http://localhost:3000/auth/twitter and you’ll be presented with twitter auth

However, when we authenticate, we get an error, since we have’t configured our routes yet:

Create a Sessions Controller, Add Routes

Next step is a sessions controller and a route for the OAuth callback. We’ll make a placeholder create action that just reports the auth info we get back from Twitter.

On the command line:

rails generate controller sessions

Edit the newly created file, app/controllers/sessions_controller.rb

require 'json'
class SessionsController  request.env["omniauth.auth"]
  end
end

add the following to config/routes.rb

get '/auth/:provider/callback' => 'sessions#create'
get '/auth/failure' => 'sessions#failure'
get '/signout' => 'sessions#destroy', :as => :signout
root :to => redirect("/auth/twitter")  # for convenience

Now go to http://localhost:3000/auth/twitter — after authenticating with Twitter, you will see the user info that Twitter sends to the app from the authentication request (see docs for explanation of each field). The general stuff which is more consistent across providers is in the ‘info’ section, and most of the interesting twitter-specific info is in the “extra” section:

User Registration

For this app, we’ll use a simple user model, just to show that there’s no magic here — we’re only using Twitter auth not storing our own passwords, so we don’t really need the full features of the lovely Devise gem.

rails generate scaffold user provider:string uid:string name:string

Add to app/models/user.rb

  def self.create_with_omniauth(auth)
    create! do |user|
      user.provider = auth['provider']
      user.uid = auth['uid']
      if auth['info']
        user.name = auth['info']['name'] || ""
      end
    end
  end

With Rails 4 the recommended pattern to lock down model attributes that we don’t want changed from form submits (or malicious attacks) is in the controller. In app/controllers/users_controller.rb change:

    def user_params
      params.require(:user).permit(:provider, :uid, :name)
    end

to:

    def user_params
      params.require(:user).permit(:name)
    end

and then remove the corresponding fields from app/views/users/_form.html.erb

Finally, the real create action for the sessions controller, plus a destroy action for the /signout url we defined earlier:

  def create
    auth = request.env["omniauth.auth"]
    user = User.where(:provider => auth['provider'],
                      :uid => auth['uid']).first || User.create_with_omniauth(auth)
    session[:user_id] = user.id
    redirect_to user_path(user), :notice => "Signed in!"
  end

  def destroy
    reset_session
    redirect_to root_url
  end

With this app, we’ve got a basic understanding to Twitter OAuth using Rails 4 and the OmniAuth gem. We didn’t actually do anything specific to MongoDB and no testing yet. It is important to understand the technology we’re working with before testing or even writing production code.

Special thanks to Daniel Kehoe of RailsApps. His Rails 3 OmniAuth Mongoid tutorial provided a helpful foundation.

This post covers getting started with Rails 4 and Mongodb, using the Mongoid gem. As part of getting up to speed, I enjoyed reading Rails + Mongo take on the object-relational mismatch by Emily Stolfo from MongoDB.

For starters, here’s a how to create a super simple toy app. I assume Ruby is installed via rvm, but you are new to Mongo.

Install Mongodb on Mac OSX

brew update
brew install mongodb

To have launchd start mongodb at login:
ln -sfv /usr/local/opt/mongodb/*.plist ~/Library/LaunchAgents
Then to load mongodb now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mongodb.plist
Or, if you don’t want/need launchctl, you can just run:
mongod

Rails 4 with Mongoid

I chose Mongoid over MongoMapper (see quora, stackoverflow)
I used MRI 1.9.3 (at this writing, Mongoid supports HEAD but not 2.0)
rvmrc:

rvm use ruby-1.9.3-p429@rails4 --create

added to Gemfile:

gem "mongoid", git: 'git://github.com/mongoid/mongoid.git'

on the command-line:

rails new mongo-people --skip-active-record
rails generate mongoid:config
rails generate scaffold person name street city state
rails s

Woo hoo! We’ve got an app — looks like a vanilla Rails app from the outside, but it is different on the inside:

class Person
  include Mongoid::Document
  field :name, type: String
  field :street, type: String
  field :city, type: String
  field :state, type: String
end

No database migrations needed. If we want a new field, we could just declare one in the model and add it to our views. I assume migrations could be used for data migration, but that would be a subject of another post.

References

Rails 4 with MongoDB Tutorial

It sucks to read about more shitty behavior at a tech conference. The sad truth of our society is that shitty conduct is common in every industry, especially those dominated by old power structures of white, straight men. I don’t like to hear those stories, but they don’t make me want to leave. They make me want to stand up and be counted. They make me proud to be part of a community where brave people speak up.

There are times when I’ve stood in awkward silence or simply left an uncomfortable situation.  I’m human and flawed and sometimes weak or just plain tired. Other times, I hope more frequently, I speak up. I rarely call people out publicly. I think it is important to focus on the inappropriate behavior, rather than vilify the person.  We need to focus on how we can all notice it a little sooner before it gets out of hand, and how we can each act to eliminate or mitigate the behavior, especially when we are not the target.

I can understand someone who has been abused not forgiving the abuser.  I can understand wanting to exile that person from our society.  However, they are going to hang out somewhere and there are other people like them whose stories have not been told in blog posts and broadcast via twitter.   We need to do the hard work of staying alert to make our conferences and workplaces safe for everyone.

I’m so proud of all friends who are allies, especially the straight, white guys.  I try to be an ally for the folks who don’t have my privilege and power as well.  More of us need to speak out in the moment, to be on the lookout.  These stories need to be told until we grow up as a community and learn how to eliminate this behavior.