Saturday, September 27, 2014

Using Mongoid with devise for authentication

Install mongoid gem

gem install moped
gem install mongoid

Generating a new rails app

rails new rails3-mongoid-devise -m https://github.com/RailsApps/rails-composer/composer-Rails3_2.rb -T -O

and you will be asked which one you want to generate as a template project

question  Install an example application?
      1)  I want to build my own application
      2)  membership/subscription/saas
      3)  rails-prelaunch-signup
      4)  rails3-bootstrap-devise-cancan
      5)  rails3-devise-rspec-cucumber
      6)  rails3-mongoid-devise
      7)  rails3-mongoid-omniauth
      8)  rails3-subdomains

Choose rails3-mongoid-devise as preferred environment

The application generator template will ask you for additional preferences:

 question  Web server for development?
       1)  WEBrick (default)
       2)  Thin
       3)  Unicorn
       4)  Puma
 question  Web server for production?
       1)  Same as development
       2)  Thin
       3)  Unicorn
       4)  Puma
 question  Template engine?
       1)  ERB
       2)  Haml
       3)  Slim
   extras  Set a robots.txt file to ban spiders? (y/n)
   extras  Use or create a project-specific rvm gemset? (y/n)
   extras  Create a GitHub repository? (y/n)

Configure Devise


You can modify the configuration file for Devise if you want to use something other than the defaults:

config/initializers/devise.rb
Configuration File

The application uses the figaro gem to set environment variables. Credentials for your administrator account and email account are set in the config/application.yml file. The .gitignore file prevents the config/application.yml file from being saved in the git repository so your credentials are kept private. See the article Rails Environment Variables for more information.

Modify the file config/application.yml:


# Add account credentials and API keys here.
# See http://railsapps.github.io/rails-environment-variables.html
# This file should be listed in .gitignore to keep your settings secret!
# Each entry sets a local environment variable and overrides ENV variables in the Unix shell.
# For example, setting:
# GMAIL_USERNAME: Your_Gmail_Username
# makes 'Your_Gmail_Username' available as ENV["GMAIL_USERNAME"]
# Add application configuration variables here, as shown below.
#
GMAIL_USERNAME: Your_Username
GMAIL_PASSWORD: Your_Password
ADMIN_NAME: First User
ADMIN_EMAIL: user@example.com
ADMIN_PASSWORD: changeme
If you are planning to customize the application to send email using a Gmail account, you can add the user name and password needed for the application to send email. See the article Send Email with Rails.

If you wish, set your name, email address, and password for the first user’s account. If you prefer, you can use the default to sign in to the application and edit the account after deployment. It is always a good idea to change the password after the application is deployed.

All configuration values in the config/application.yml file are available anywhere in the application as environment variables. For example, ENV["GMAIL_USERNAME"] will return the string “Your_Username”.

If you prefer, you can delete the config/application.yml file and set each value as an environment variable in the Unix shell.

Set Up a Database Seed File


The db/seeds.rb file initializes the database with default values. To keep some data private, and consolidate configuration settings in a single location, we use the config/application.yml file to set environment variables and then use the environment variables in the db/seeds.rb file.

puts 'DEFAULT USERS'
user = User.create! :name => ENV['ADMIN_NAME'].dup, :email => ENV['ADMIN_EMAIL'].dup, :password => ENV['ADMIN_PASSWORD'].dup, :password_confirmation => ENV['ADMIN_PASSWORD'].dup
puts 'user: ' << user.name

Set the Database


Prepare the database and add the default user to the database by running the commands:

$ rake db:seed
Use rake db:reseed if you want to empty and reseed the database. Or you can use rake db:drop and rake db:setup. The equivalent task for Rails with ActiveRecord is rake db:reset which will be available in Mongoid 4.0.

Set the database for running tests:

$ rake db:test:prepare
If you’re not using rvm, the Ruby Version Manager, you should preface each rake command with bundle exec. You don’t need to use bundle exec if you are using rvm version 1.11.0 or newer.

Change your Application’s Secret Token


If you’ve used the Rails Composer tool to generate the application, the application’s secret token will be unique, just as with any Rails application generated with the rails new command.

However, if you’ve cloned the application directly from GitHub, it is crucial that you change the application’s secret token before deploying your application in production mode. Otherwise, people could change their session information, and potentially access your site without your permission. Your secret token should be at least 30 characters long and completely random.

Get a unique secret token:


rake secret
Edit your config/initializers/secret_token.rb file to add the secret token:

Rails3MongoidDevise::Application.config.secret_token = '...some really long, random string...'
Test the App

You can check that your app runs properly by entering the command

$ rails server

To see your application in action, open a browser window and navigate to http://localhost:3000/. You should see the default user listed on the home page. When you click on the user’s name, you should be required to log in before seeing the user’s detail page.

To sign in as the default user, (unless you’ve changed it) use

email: user@example.com
password: changeme
You should delete or change the pre-configured logins before you deploy your application.

If you test the app by starting the web server and then leave the server running while you install new gems, you’ll have to restart the server to see any changes. The same is true for changes to configuration files in the config folder. This can be confusing to new Rails developers because you can change files in the app folders without restarting the server. Stop the server each time after testing and you will avoid this issue.

Testing MongoDB from sinatra

gem install mongo_kerberos

require 'mongo'
# require 'bson_ext'

include Mongo

MONGO_CLIENT = MongoClient.new # defaults to localhost:27017
# mongo_client = MongoClient.new("localhost", 27017)
# db = client['analytics-learning']

# coll = db['collection-scene-abc']

# CRUD
10.times { |i| coll.insert({ :count => i+1 }) }
puts “There are #collcoll.count total documents. Here they are:” coll.find.each { |doc| puts doc.inspect }
coll.update({ :count => 5 }, { :count => ‘foobar’ })

coll.remove({ :count => 8 }) coll.remove ```

Working with Mongodb on Rails

Installing and running on Windows

Download and installl the mogodb for windows from the following link. If you're using 64bit, choose the 64bit ones.

http://www.mongodb.org/downloads

Now you need to install related gem files

gem install bson
gem install mongo
gem install bson_ext

if the installing of bson_ext failed, trying updating the gems and then t
gem update  --system
gem install bson_ext

if it still doesn't work, try installing the lower version
gem install bson_ext -v=1.9.2

Now set the database path to any place, in this example, I set it to c:/mongodb/data/

mongod.exe --dbpath C:\mongodb\data\
or
mongod.exe if the above command is already run

and by now, the data path will create and you will start seeing the waiting for connections

Running the mongodb shell for testing

C:\mongodb\bin\mongo.exe

Now try running the following command and your mongodb environment is set up successfully.

db.test.save( { a: 1 } )
db.test.find()

Setting up mongodb as a windows service


Configure the System

md C:\mongodb\log
echo logpath=C:\mongodb\log\mongo.log > C:\mongodb\mongod.cfg

Running as service

C:\mongodb\bin\mongod.exe --config C:\mongodb\mongod.cfg --install
net start MongoDB

Stop/Removing the service

net stop MongoDB
C:\mongodb\bin\mongod.exe --remove

Installing and running on Linux/Ununtu

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
Create a /etc/apt/sources.list.d/10gen.list file using the following command

echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/10gen.list
Now you can update your repository

sudo apt-get update
And then install the package

sudo apt-get install mongodb-10gen
To check that it works, just issue a mongo in your shell and you should see something like

MongoDB shell version: x.x.x
connecting to: test
>

Download and install the mongodb for linux
curl -O http://downloads.mongodb.org/linux/mongodb-linux-x86_64-2.6.4.tgz
curl -O http://downloads.mongodb.org/linux/mongodb-linux-i686-2.6.4.tgz (32Bit)
tar -zxvf mongodb-linux-x86_64-2.6.4.tgz

(Copy to target directory - Optional)
mkdir -p mongodb 
cp -R -n mongodb-linux-i686-2.6.4/ mongodb

Configure Search path (Optional)

To ensure that the downloaded binaries are in your PATH, you can modify your PATH and/or create symbolic links to the MongoDB binaries in your /usr/local/bin directory (/usr/local/bin is already in your PATH). You can find the MongoDB binaries in the bin/ directory within the archive.

Running the MongoDB

mkdir -p /data/db
chown mongodb /data/db
Note : You must create the user manually

Starting the MongoDB

mongod or 
mongod --dbpath <some alternate directory>

Ctrl + C to stop the server as usual

Friday, September 26, 2014

Deploying rails application

Before deploying the rails application for the first time, you need to do the following

1 - Comment out the bitnami default include path and use httpd-vhosts.conf instead
#Include "/opt/rubystack-1.9.3-25/apache2/conf/bitnami/bitnami.conf" Include "/opt/rubystack-1.9.3-25/apache2/conf/extra/httpd-vhosts.conf"

2 - chomd 775 your project directory

How to configure Apache with Phusion Passenger

Make sure you have the Phussion Passenger enabled. Check if the following line is uncommented in Apache config file /installdir/apache2/con/httpd.conf:
Include conf/bitnami/passenger.conf
Assuming you have your application running in /application location, substitute the content of the file /installdir/apps/application/conf/application.conf with the following:
<VirtualHost *:80>
  PassengerEnabled on
  RailsBaseURI /application
  <Directory /installdir/apache2/htdocs/application>
    Options -MultiViews
  </Directory>
</VirtualHost>
Then ssh to your machine and create a symbolic link:
sudo ln -s /installdir/apps/application/public /installdir/apache2/htdocs/application
(You should make sure that the 'public' and 'config' application folders and their parent directories are readable and executable by Apache).

How to change the default URL with Phusion Passenger


Please make sure you have the Phussion Passenger enabled (check the previous section for the details). Then substitute the content of the file /installdir/apps/application/conf/application.conf with the following:
<VirtualHost *:80>
  DocumentRoot /installdir/apps/application/public
  <Directory /installdir/apps/application/public/>
    PassengerEnabled on
    Options -MultiViews
    <IfVersion < 2.3 >
    Order allow,deny
    Allow from all
    </IfVersion>
    <IfVersion >= 2.3>
    Require all granted
    </IfVersion>
  </Directory>
</VirtualHost>

Enabling Passenger in bitnami

Finally you have to enable passenger fusion in bitnami config file located in /opt/rubystack/apache2/conf/bitnami/passenger.conf

LoadModule passenger_module /opt/rubystack-1.9.3-25/ruby/lib/ruby/gems/1.9.1/gems/passenger-4.0.45/buildout/apache2/mod_passenger.so
PassengerRoot /opt/rubystack-1.9.3-25/ruby/lib/ruby/gems/1.9.1/gems/passenger-4.0.45
PassengerRuby /opt/rubystack-1.9.3-25/ruby/bin/ruby
PassengerEnabled on
PassengerFriendlyErrorPages off
PassengerUser daemon
PassengerGroup daemon

Restart Apache server:
sudo /installdir/ctlscript.sh restart apache
Using Apache with Thin
This approach consists on having multiple Thin processes running in different ports. Once they are running, Apache will be set up as a proxy balancer, sending the Rails requests to those ports. It is based in Thin parser, Event Machine and Rack.
On Linux and OS X, you can store the configuration in a yml file and use it to start an  stop the group easily. For example:
$ cd your_project_folder
$ thin -s 5 -p 3000 -e production --prefix /appname -C config/thin.yml config
Which will configure 5 processes in ports 3000 to 3004, running in a production environment and using prefix /appname. Once the configuration file has been generated, you can start, stop or restart the by running:
$ thin -C ${rails_application_dir}/config/thin.yml start/stop/restart
If you are using Ruby Stack on Windows, you can't start multiple servers using "-s" option. You will need to call a command for each instance:
$ cd your_project_folder
$ thin -p 3000 -e production --prefix /appname start thin -p 3001 -e production --prefix /appname start
Regarding Apache, you may include the following lines to apache2/conf/httpd.conf:
ProxyPass /appname balancer://appcluster
ProxyPassReverse /appname balancer://appcluster
<Proxy balancer://appcluster>
   BalancerMember http://127.0.0.1:3001/appname
   BalancerMember http://127.0.0.1:3002/appname
   ...
</Proxy>

Using Apache with Passenger

Note: Before installing Apache and Passenger, make sure to disable (or remove) Nginx if you have it installed; or configure it to not to block Apache's way (i.e. port / socket collisions).
Note: If your droplet has less than 1 GB of RAM, you will need to perform the below simple procedure to prepare a SWAP disk space to be used as a temporary data holder (i.e. RAM substitute) for Passenger. Since DigitalOcean virtual servers come with fast SSD disks, this does not really constitute an issue whilst performing the server application installation tasks.
# Create a 1024 MB SWAP space
# The process should complete within less than a minute

sudo dd if=/dev/zero of=/swap bs=1M count=1024
sudo mkswap /swap
sudo swapon /swap
Passenger is only available for OS X and Linux. To use this method, you just need to include a virtual host which DocumentRoot points to 'public' directory in Rails application.
<VirtualHost *:80>
    ServerName myapplication.com
    DocumentRoot your_project_folder/public
    <Directory your_project_folder/public>
        Options -MultiViews
        <IfVersion < 2.3 >
        Order allow,deny
        Allow from all
        </IfVersion>
        <IfVersion >= 2.3>
        Require all granted
        </IfVersion>
    </Directory>
</VirtualHost>