Wednesday, October 1, 2014

Configuring mongo id for rails

Add the following gems to your Gem file of your rails app

gem 'mongoid', github: 'mongoid/mongoid'
gem 'bson'
# gem 'bson_ext', '~> 1.9.2'

make bundle install

rails g mongoid:config

First in config/application.rb comment out the line and add the following to enable mongodb

# require 'rails/all'
require "action_controller/railtie"
require "action_mailer/railtie"
# require "active_resource/railtie"

require "sprockets/railtie"

In config/environments/development.rb, comment out this line
# config.active_record.migration_error = :page_load

Let’s generate our Post first, it will have 3 fields: a title, a body and it can be starred.
rails g scaffold post title:string body:string starred:boolean

Add fields to your model
class Post
  include Mongoid::Document
  include Mongoid::Timestamps

  field :title, type: String
  field :body, type: String
  field :starred, type: Boolean

  index({ starred: 1 })

end

Now we have a command to enforce indexes on the database
rake db:mongoid:create_indexes

if you've the database connection error, try doing the following two things 
uncomment 127.0.0.1 host line in C:\Windows\System32\drivers\etc\hosts
or
in mongoid.yml file, change the hosts to the following
hosts:

        - 127.0.0.1:27017

Read more at
http://requiremind.com/riding-rails-4-along-with-mongoid-and-ruby-2-dot-0/


Adding devise on Mongoid

Configure ActionMailer

Set up action_mailer in your development environment in the file
config/environments/development.rb
by commenting out the line in the file:

# Don't care if the mailer can't send
# config.action_mailer.raise_delivery_errors = false
and adding:
# ActionMailer Config
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
# A dummy setup for development - no deliveries, but logged
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = false
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default :charset => "utf-8"

Set up action_mailer in your production environment in the file
config/environments/production.rb
by adding:

config.action_mailer.default_url_options = { :host => 'yourhost.com' }
# ActionMailer Config
# Setup for production - deliveries, no errors raised
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = false
config.action_mailer.default :charset => "utf-8"

Installing devise

$ rails generate devise:install
which installs a configuration file:
config/initializers/devise.rb
and a localization file.
Devise will recognize that you already have Mongoid installed and it will set its ORM configuration in the config/initializers/devise.rb file to include:
require 'devise/orm/mongoid'

Adding devise users

Generate a Model and Routes for Users
Devise can manage users and administrators separately, allowing two (or more) roles to be implemented differently. For this example, we just implement Users.

Use Devise to generate models and routes for a User:

$ rails generate devise User
Devise will recognize that Mongoid is installed and set up the User model with

include Mongoid::Document
which must precede all other statements in the model.

Devise will modify the config/routes.rb file to add:
devise_for :users


Add these manually in developer.rb model class to generate routes

  # traditional devise need to manually place in mongodb generated devise
  devise :database_authenticatable, :registerable,

         :recoverable, :rememberable, :trackable, :validatable

Modify the file models/user.rb and add:

field :name
validates_presence_of :name
validates_uniqueness_of :name, :email, :case_sensitive => false
attr_accessible :name, :email, :password, :password_confirmation, :remember_me

rails g devise:views to add view files


Set Up a Demonstration of Devise


$ rails generate controller users show


Note that “users” is plural when you create the controller.

Modify the file app/controllers/users_controller.rb and add:

before_filter :authenticate_user!

def show
  @user = User.find(params[:id])
end
The file config/routes.rb has already been modified to include:

get "users/show"

Remove that and change the routes to:

root :to => "home#index"
devise_for :users
resources :users
Important note: The devise_for :users route must be placed above resources :users.

This line needs to be commented out in config/nitialiser/cookies_serialiser.rb or you will get cookies errors while logging in

# Rails.application.config.action_dispatch.cookies_serializer = :json


Comment out the following line to stop conflict with previous active records

# Do not dump schema after migrations.

  # config.active_record.dump_schema_after_migration = false

Add production config in config/mongoid.yml file

production:
  # Configure available database sessions. (required)
  sessions:
    # Defines the default session. (required)
    default:
      database: analytics_server_rails_production
      # Provides the hosts the default session can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - 127.0.0.1:27017
      options:
        # Change the default write concern. (default = { w: 1 })
        # write:
        # w: 1

        # Change the default consistency model to primary, secondary.
        # 'secondary' will send reads to secondaries, 'primary' sends everything
        # to master. (default: primary)
        # read: secondary_preferred

        # How many times Moped should attempt to retry an operation after
        # failure. (default: The number of nodes in the cluster)
        # max_retries: 20

        # The time in seconds that Moped should wait before retrying an
        # operation on failure. (default: 0.25)
        # retry_interval: 0.25
  # Configure Mongoid specific options. (optional)

  options:



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>

Tuesday, August 26, 2014

Useful rails methods

Links

<% link_to 'Name', name_path(:param=> 'variable'), :class => 'css' %>

Redirection

In Controller -> redirect_to name_path
In Views ->
<% if developer_signed_in? %>
    <script type="text/javascript">
        window.location.href="/dashboard"  // put your correct path in a string here
    </script>
<%else%>


Killing process in Linux

ps aux | grep (process name)
kill processID

Make Devise Authenticable to controller classes

class YourController < ApplicationController
  before_action :set_unlock_code, only: [:show, :edit, :update, :destroy]

  #Only signed in user can do the following (Devise)
  before_filter :authenticate_developer!
end

Parsing Form tag with parameters

Unlike form_for tag, this tag pass the values with params

In the View
    <%= form_tag generate_codes_path, :class => 'form-inline' do %>
        <div class="form-group">        <%= number_field_tag 'unlock_code[strAppId]', nil, :placeholder => 'App ID' %>              </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[batchNo]', nil, :placeholder => 'Batch No' %>             </div>
        <div class="form-group">        <%= text_field_tag 'unlock_code[strStatus]', nil, :placeholder => 'Status' %>               </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[priceUniversal]', nil, :placeholder => 'Price in USD' %>  </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[priceMMK]', nil, :placeholder => 'Price in MMK' %>        </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[num]', nil, :placeholder => 'Number of codes' %>          </div>

        <%=  submit_tag 'Generate', :class => "btn btn-primary md-trigger" %>
    <% end %>

In the controller tag
    strAppId = params[:strAppId]
    batchNo = params[:batchNo]
    strStatus = params[:strStatus]
    priceUniversal = params[:priceUniversal]
    priceMMK = params[:priceMMK]
    num = params[:num]

Field Parameters

<%= number_field_tag 'appID', '-1', :placeholder => 'App ID', :required => true , :disabled => true%>