Showing posts with label mongoid. Show all posts
Showing posts with label mongoid. Show all posts

Friday, February 4, 2011

Rails 3.0: Devise + Mongoid + RSpec

Devise removes the mundane job of writing all the code required to handle a user account. Plus, it supports Mongoid.

The following is a non-exhaustive list of tasks Devise takes care of for you:
  • signup
  • forgot/reset password (including emails)
  • confirmation emails
  • password encryption
  • login
  • logout
  • editing account info
  • locking accounts
  • session expiration

All this is available out of the box. Along with the goodies that are pre-packaged, Devise is fully customizable.

Installation

Open Gemfile
gem 'devise'

Install
bundle install
rails generate devise:install

You will need to setup your mailer if it isn't already setup. Devise depends on the default host being set, so ensure the following is set
# ... other mailer settings
config.action_mailer.default_url_options = { :host => 'localhost:3000' }

Don't worry! Devise is smart and has already detected that you are using Mongoid at this point and not ActiveRecord. It has also created config/initializers/devise.rb. This is where you can configure Devise. Take some time to familiarize yourself with all the options and uncomment any that you would like to use. I'll wait.

Test Helpers

If you are using RSpec, create spec/support/devise.rb with
RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :controller
end

Now you have access to things like
sign_in @user
sign_out @user

Create a User model

It is time to create a User!
rails generate devise user

This generates a user model at app/models/user.rb with some Devise specific lines of code. Include the modules that you want and remove the ones you don't.

Believe it or not, Devise is now properly hooked up and ready!

Routes

Devise automagically generates all the user routes required for handling the user account. If you look in config/routes.rb, you'll notice
devise_for :users

To see all the routes
rake routes

You will notice a bunch of user routes. Fire up your server and navigate to localhost:3000/users/sign_up. Voila!

As a quick reference, here are some useful routes:
  • signup: new_user_registration_url
  • edit account: edit_user_registration_url
  • login: new_user_session_url
  • logout: destroy_new_user_session_url

References

I encourage you to take a look at the Devise home page as there is a wealth of information there.

https://github.com/plataformatec/devise

Sunday, December 12, 2010

Mongoid: autocreate_indexes

Indexes help make your database reads faster, but has the downside of making your database writes slower. Either way, you will come across the need for indexes at some point.

Mongoid has a flag called autocreate_indexes. This flag tells MongoDB to create the indexes every time a class is loaded. This is set to false by default. However, when you add an index to a model, your application will complain since there is no index in MongoDB yet.

To get around this, you can set autocreate_indexes to true. You only want to do this for development and test since this can be slow. For staging and production, you will need to log into MongoDB and create an index manually before pushing your code.

Monday, October 25, 2010

Rails 3.0: MongoDB + Mongoid

Why Mongoid?

The de facto ORM for MongoDB in Rails is Mongo Mapper, so why choose Mongoid? You can ready why straight from the horses mouth here.

To summarize, Mongoid is built for Rails 3.0 and it handles larger documents better. It also feels like NoSQL when you use it. MongoMapper was built during Rails 2.x days and when MongoDB was young. It is modeled very closely to ActiveRecord to make the transition easier. Hence, it feels more like SQL. MongoMapper is more extensible though with a larger community.

MongoDB

Grab the latest build from MongoDB's download page. At this time, it is 1.6.3.

Download and install. We make a softlink. This way, if we upgrade, we just switch the softlink and everything else stays the same.
cd /usr/local/src/
sudo wget http://fastdl.mongodb.org/linux/mongodb-linux-i686-1.6.3.tgz
sudo tar xzf mongodb-linux-i686-1.6.3.tgz
sudo rm -rf mongodb-linux-i686-1.6.3.tgz
sudo ln -s mongodb-linux-i686-1.6.3 mongodb

Add /usr/local/src/mongodb/bin to your path.
PATH=$PATH:/usr/local/src/mongodb/bin

Make /data/db and give ownership to your user. There are obviously several ways to do this, but this is the easiest.
sudo mkdir -p /data/db
sudo chown -R wesley:wesley /data

Start your engines!
mongod

Mongoid

This builds on top of my previous post on installing Rails 3.0 with BDD. This assumes that the Rails application was created without ActiveRecord using -O. Check out Rails 3.0 agnosticism for an explanation.

Add mongoid to Gemfile. bson_ext is installed for a speed boost.
gem 'mongoid', '2.0.0.rc.6'
gem 'bson_ext', '~>1.2'

Install mongoid.
bundle install
rails generate mongoid:config

Cucumber

Add a cucumber environment to mongoid.yml.
cucumber:
  <<: *defaults
  database: myproject_cucumber 

Cucumber makes use of Database Cleaner. There are posts saying Database Cleaner doesn't work with Mongoid. However, it seems like it is now according to the official documentation. We need to modify features/support/env.rb this is not recommended as it is regenerated on a cucumber-rails upgrade. Instead, we will create features/support/local_env.rb.
require 'database_cleaner'
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.orm = "mongoid"
Before { DatabaseCleaner.clean }

RSpec 2

RSpec includes ActiveRecord specific lines in spec/spec_helper.rb. You need to comment out the following 2 lines.
# config.fixture_path = "#{::Rails.root}/spec/fixtures"
# config.use_transactional_fixtures = true

To properly clean the database, RSpec needs to know how to do that with Mongoid. Again, we can use Database Cleaner for this.

Open up spec/spec_helper.rb and add the following in the RSpec.configure block
RSpec.configure do |config|    
  # Other things

  # Clean up the database      
  require 'database_cleaner'   
  config.before(:suite) do     
    DatabaseCleaner.strategy = :truncation
    DatabaseCleaner.orm = "mongoid" 
  end

  config.before(:each) do
    DatabaseCleaner.clean      
  end
end 

References


Updates

December 2, 2010: Changed Cucumber local_env.rb for database cleaning.
December 2, 2010: Added a section for RSpec database cleaning.
February 1, 2011: Updated Mongoid version in the Gemfile
February 26, 2011: Added a note to clean out ActiveRecord specific lines in RSpec.