Archive for the ‘Ruby on Rails’ Category

Single Sign-On In Rails Application

Single sign-on (SSO) is a property of access control of multiple related, but independent software systems. With this property a user logs in once and gains access to all systems without being prompted to log in again at each of them. Such as we once log in to google, we are permitted to access the Youtube, Docs, Google Drive etc. dnd1999110501 We may think about sharing the session cookies among the all domains but its generally not a good idea. One can steal cookies to sign in from other system or browser. Single SignOn Helps us in getting around this problem and implement a much robust system. How do we implement Single Sign-On in Rails App? We will try to get our hand around on how to build a prototype around a rails app to implement single sign-on. We will be looking a sample rails application powered by CASino gem Why we are using CASino ?
  1. Distributed under MIT LIcense
  2. Active Development since
  3. External authentication sources (LDAP, SQL)
  4. Two-factor authentication
  5. Session-overview for logged-in users
  6. Full localization support
  7. REST-API
So what is CASino exactly? CASino is a simple Single sign-on server application. It supports the CAS protocol and can therefore be used in combination with almost every web programming language out there. CAS is an authentication system originally created by Yale University to provide a trusted way for an application to authenticate a user. CAS centralizes authentication: It allows all your applications to ask users to login to a single sign-on server The implementation. Here we have two apps client and server. We assume that the app is using devise for the demonstration purposes. The Logic can easily be extended to other authentication methods though. The app is as simple as configuring a few variables in the CASino gem.
  1. user request to client domain .
  2. it redirects to the server if not authorised.
  3. Start with adding the gems client app
  4. redirects to back url to whichever client request url is
Step #1 Implementing the client application. Gemfile # If You face some compatability issues then use ruby 2.1

gem 'devise_cas_authenticatable', git: '<a href="https://github.com/jpamaya/devise_cas_authenticatable">https://github.com/jpamaya/devise_cas_authenticatable</a>'

routes.rb

devise_for :users, skip: [:sessions], controllers: { cas_sessions: 'sso_cas' }

devise_scope :user do

get "sign_in", to: "devise/cas_sessions#new"

delete "sign_out", to: "devise/cas_sessions#destroy"

end

devise.rb # ==> Configuration for SSO server authentication

config.cas_base_url = "http://localhost:4000/"

config.cas_create_user = false

config.cas_destination_logout_param_name = 'service'

config.cas_enable_single_sign_out = true

User.rb

devise :cas_authenticatable

Now run client application on localhost:3000 and begin with typing users/sign_in Since we overwrote devise’s sign in mechanism, so instead of presenting devise’s normal sign in page, we are redirected to localhost:4000 which is the backend app to authenticate the users. Lets prepare the backend app to authenticate the users.  Step #2 Start with implementing code in server app limitation use ruby ruby “2.1.5” and rails “3.2.11” check rails -v ‘~>(‘ 3.2.11′). for server app Gemfile #It users these db to store sessions and some tokens. casino will take care all about these

gem 'sqlite3'   # for sqlite support

gem 'mysql2'    # for mysql support

gem 'pg'        # for postgresql support

gem 'casino'

Run bundle install and rails g casino:install The CAS configuration is stored under config/cas.yml. This is where you configure how your SSO handles logins. An example configuration can be found in the file config/cas.yml.example provide the valid db credentials and run the migrations. Run this app on localhost:4000 , Just follow the old steps
  1. Goto localhost:3000/users/sign_in
  2. You will redirected to localhost:4000 enter credentials click sign in
  3. You will be redirected back on successful login
In the links below you can find some ready made examples for you to clone these  apps and have better understanding of SSO.
Server exampleruby “2.1.5”git clone https://github.com/codescrum/casino-sso-server-example.gitRails 4 client examplegit clone https://github.com/codescrum/casino-sso-client-rails4-example.gitRails 3 client example git clone https://github.com/codescrum/casino-sso-client-rails3-example.git
Let us know in comments if you face any troubles in the implementation !! PS: Single Sign-out has been left as a thought for another day and we will discuss that in a follow up blog.

The technology stack powering the on demand applications

Uber and Ola have given rise to a slew of Ondemand applications which claim themselves to be Uber/Ola of X. Some of the verticals where these applications have found their usability include but not limited to taxi, transportation, Logistics, Home Services, Health apps and so on. In this blog we will go deeper into the various components and technology involved in on Demand Apps. Components Involved in Building and On Demand App In most of the cases there are 3 components involved in building an On-Demand App:
  • A cloud backend for Data Interaction APIs and live dispatch of Jobs
  • An Android/iOS App user to make a job(e.g book a ride with Uber/Ola)
  • An app with the drivers to receive the jobs created by the users and attend to them.
  Lets analyze each of these components in detail and how one can go around building each of them. Web Backend Web Backend is the most critical part of the On Demand applications because backend is what powers both the consumer and the driver apps. The web backend must meet the following requirements for a successful implementation:
  • A Light footprint to dispatch the jobs on fly.
  • A Good dispatch components to maximize the efficiency of the field workers(drivers in case of uber).
  • A Socket connectivity to enable the jobs dispatch and job information to the user.
  • A Good structure for a flexible and structured development
  We have recently worked on Bodhik which is an Ondemand Application for Financial Advisory Services.

Capybara Basics For Automated testing of Ruby on Rails Application

Automated Testing is an integral part of large scale production Ruby on Rails applications. A solid Integration test suite ensures that the integration between various components of the application is smooth and seamless. An integration test generally spans multiple controllers and actions, tying them all together to ensure they work together as expected. It tests more completely than either unit or functional tests do, exercising the entire stack, from the dispatcher to the database. Capybara comes in handy in simulating the testing in real user environment. In this blog we will explore various ways by which we can strengthen our apps with Capybara.

    • Capybara is an integration testing tool for rack based web applications. It simulates how a user would interact with a website.
    • Capybara helps in testing your web application as a real user would do. It is independent of the driver that is running your tests and comes with Rack::Test and Selenium support built in. For other drivers, you need to include their respective gem.
Capybara requires Ruby 1.9.3 or later and can be installed as a gem by listing in your gem file and then installing bundle or it may be installed directly by typing:
gem install capybara
  • Include capybara in your helper file:
    require 'capybara/rails'
Using Capybara with Rspec
Integrating capybara with rspec is fairly simple. Lets go through a step by step process to understand the integration. The following test simulates a login in a real user environment.
  • Include capybara’s rspec directory
    require 'capybara/rspec'
  • Capybara specs are required to be placed in spec/features
  • Here is a simple test to test the login page working.
    describe "Login" do
    before :each do
    user = User.create(:email =&gt; 'RoR@enbake.com'”,:password =&gt; 'password')
    end
    it "logs the user in" do
    visit login_path
    fill_in "Email", with: user.email
    fill_in "Password", with: 'kanwal_enbake'
    click_button "Sign in"
    page.should have_content "success"
    end
    end
    
    The test source code is fairly simple to understand and implement so I will not be going into the details here.
Testing Javascript with Capybara
  • By default Capybara uses the :rack_test driver, which is fast but limited as it does not support JavaScript. So you need to switch to Capybara.javascript_driver(:selenium by default) by using :js => true. For instance: describe “example of testing js”, :js => true do it “tests js with default js driver” do end it “tests js with one specific driver” , :driver => :webkit do end end
  • To make Capybara available in all test cases deriving fromActionDispatch::IntegrationTest : describe ActionDispatch::IntegrationTest include Capybara::DSL end
Drivers
  • You may sometimes, want to switch default driver and want to run everything in selenium, you could do:Capybara.default_driver = :selenium
  • In any case – provided you are using Rspec or Cucumber – if you want use faster :rack_test as your default_driver, and use JavaScript-capable driver only for selective test cases, you can use :js => true for Rspec and @javascript for Cucumber. By default, JavaScript tests are run using the :selenium driver. You can change this setting by Capybara.javascript_driver.
  • You can also, particularly in before or after blocks, change driver temporarily: Capybara.current_driver = :webkit
  • Capybara.use_default_driver would switch back to default driver
Note: switching the driver creates a new session, so you may not be able to switch in the middle of a test.
Techniques and Trivial Testing Tasks
Navigating
  • visit(‘/projects’)
  • visit(post_comments_path(post))
Clicking links and buttons
  • click_link(‘id-of-link’)
  • click_link(‘Link Text’)
  • click_button(‘Save’)
  • click(‘Link Text’) # Click either a link or a button
  • click(‘Button Value’)
Interacting with forms
  • fill_in(‘First Name’, :with => ‘John’)
  • fill_in(‘Password’, :with => ‘Seekrit’)
  • fill_in(‘Description’, :with => ‘Really Long Text…’)
  • choose(‘A Radio Button’)
  • check(‘A Checkbox’)
  • uncheck(‘A Checkbox’)
  • attach_file(‘Image’, ‘/path/to/image.jpg’)
  • select(‘Option’, :from => ‘Select Box’)
Scoping
  • within(“//li[@id=’employee’]”) do fill_in ‘Name’, :with => ‘Jimmy’ end
  • within(:css, “li#employee”) do fill_in ‘Name’, :with => ‘Jimmy’ end
  • within_fieldset(‘Employee’) do fill_in ‘Name’, :with => ‘Jimmy’ end
  • within_table(‘Employee’) do fill_in ‘Name’, :with => ‘Jimmy’ end
Querying
  • page.has_xpath?(‘//table/tr’)
  • page.has_css?(‘table tr.foo’)
  • page.has_content?(‘foo’)
  • page.should have_xpath(‘//table/tr’)
  • page.should have_css(‘table tr.foo’)
  • page.should have_content(‘foo’)
  • page.should have_no_content(‘foo’)
  • find_field(‘First Name’).value
  • find_link(‘Hello’).visible?
  • find_button(‘Send’).click
  • find(‘//table/tr’).click
  • locate(“//*[@id=’overlay'”).find(“//h1″).click
  • all(‘a’).each { |a| a[:href] }
  • current_path.should == post_comments_path(post)
Scripting
    • result = page.evaluate_script(‘4 + 4′)
    • page.execute_script(“$(‘#id_of_anything’)”).click
Note: unlike page.evaluate_script, page.execute_script do not return anything. You have to explicitly perform action to make it return a value Debugging
  • save_and_open_page
  • page.save_screenshot(‘screenshot.png’) *driver specfic
Asynchronous JavaScript
  • click_link(‘foo’)
  • click_link(‘bar’)
  • page.should have_content(‘baz’)
  • page.should_not have_xpath(‘//a’)
  • page.should have_no_xpath(‘//a’)
XPath and CSS
  • within(:css, ‘ul li’) { … }
  • find(:css, ‘ul li’).text
  • locate(:css, ‘input#name’).value
  • Capybara.default_selector = :css
  • within(‘ul li’) { … }
  • find(‘ul li’).text
  • locate(‘input#name’).value
Calling remote servers
  • Normally Capybara expects to be testing an in-process Rack application, but you can also use it to talk to a web server running anywhere on the internet, by setting app_host: Capybara.current_driver = :selenium Capybara.app_host =https://www.google.com
I hope the blog gives a good introduction of adding capybara tests to your rails apps. Its just the tip of the iceberg and the possibilities are endless. Lets make our apps more robust and flexible .. :).

Embedly Integration in Rails

Embedly is a powerful tool to embed multimedia content or images or even blogs in your application. It comes in handy especially to make your content easier to share.
Embedly provides an easy to use official ruby gem to integrate Embedly into your RoR app. The usage of the gem is fairly straight forward. I will try to go step by step on how to integrate embedly API into an RoR app.
  • Add the gem in your gem file
    gem "embedly"
    Bundle the Gems
  • Get the API key from “https://app.embed.ly/login”. For the purpose of the blog we assume that the API key is accessible through the config variable AppConfig.embedly[:api_key]
  • Mostly the embeds will stay the view side logic so lets create a small helper to generate an embed from a Youtube Video. The call to the API is pretty straight forward and intuitive as we can see from the following code.
  • require 'embedly'
    require 'json'def display
    embedly_api =Embedly::API.new AppConfig.embedly[:api_key]
    obj = embedly_api.oembed :url => 'http://www.youtube.com/watch?v=sPbJ4Z5D-n4&feature=topvideos'
    obj.first.html
    end
  • The code calls the embedly API to generate an ombed for the youtube url and returns the html for the embed. This html can be used directly to embed the content into your blog or app.
  • Thats it !!

Enjoy supercharged content with your app and feel free to post any comments in the comments section.

A Step by Step Guide to Setup Rails application on Ec2 instance (Ubuntu Server)

Sometimes the Bitnami or other Rails AMIs doesn’t fit your needs directly and you will feel the need of building the Server yourself.Here I go step by step in building such a stack on top of Amaon EC2 Ubuntu Server.
  • Rails applications are a little bit different to install on servers but the process is very easy.Rails application needs a web server and an application server to run with. For development, it comes with default Webrick server that serve as application server on local machine. For setting it up on production server, we have the following choices on Web and application servers :-

    • Web servers

      1. Apache

      2. Nginx

    • Application Servers

      1. Passenger

      2. Thin

      3. Puma

      4. Unicorn

  • The simplest and best combination consists of Nginx + Passenger. It allows greater flexibility for configuration and also allows good speed over other combinations. So we are going to setup an Rails application using Nginx + passenger configuration on a bare Ubuntu server. Here are the steps :-

  1. Launch an Ec2 instance with ubuntu AMI. Make sure you have HTTP and SSH access to the server.

  2. SSH into the server by using private key (.pem) used while launching the instance and install the available updates by running :-

    sudo apt-get install updates
  3. Now you need to setup ruby on your server, so install the single user rvm ruby by following this blog.
  4. Load the rvm and make the installed ruby as default by running the following commands :-

    source ~/.rvm/scripts/rvm
    rvm use 2.1.0 –default
  5. Install the version control to clone your rails application to server. We generally use Git with rails application which can be installed by running the following command :-

    sudo apt-get install git
  6. Now clone your application on the server :-

    git clone yourepo.git

    Note:- In case of private git repository, you need to add public key of server to deploy keys of your repository, otherwise you will be promped with an permission denied error.

    OR

    Deploy using application to this server using Capistrano script. Please read this blog for more details on deploying your application using Capistrano.

  7. Now go to your application and install the gems by running bundle install command. If you want to setup your database on the same server, you can do the same by using the following commands 😐

    • In case of MYSQL

      sudo apt-get install mysql-server mysql-client
      sudo apt-get install libmysql++-dev
    • In case of POSTGRESQL, follow this blog for installation and then install the development headers

      sudo apt-get install libpq-dev

      After setting this up, migrate your databases in whichever environment you want to launch the server.

  8. Now install the Passenger gem by running :-

    gem install passenger

  9. Next step is to install the Nginx server, but we have some pre-requisits for this.

      1. It needs curl development headers which can be installed by :-

        sudo apt-get install libcurl4-openssl-dev

      2. It will be installed under /opt directory and your user should have permissions to that folder, so make your user as user owner for /opt directory by :-

        sudo chown -R ubuntu /opt

  10. Now install the Nginx server with passenger extension by running the following command :-

    passenger-install-nginx-module

  11. Set your Nginx server as service in init script by using the following commands :-

    wget -O init-deb.sh http://library.linode.com/assets/660-init-deb.sh
    sudo mv init-deb.sh /etc/init.d/nginx
    sudo chmod  +x /etc/init.d/nginx
    sudo /usr/sbin/update-rc.d -f nginx defaults
  12. Setup your application path in the nginx configuration file i.e. /opt/nginx/conf/nginx.conf.

    server {

    listen 80;

    server_name localhost;

    root /home/ubuntu/my_application/public #<-- be sure to point to 'public'

    passenger_enabled on;

    rails_env production;

    }

  13. Lastly start your server by running the following command :-

    sudo service nginx start

     


Braintree Integration In Rails Application

Braintree is one gateway that is getting a lot of traction and user love these days due to its ease of use and getting started easily. I have indicated here a few things that should get you started with braintree in rails quickly. In this Blog, we’ll securely process a credit card transaction using the official braintree gem and the Client-side encryption method, utilizing Braintree.js library. The blog covers the case where the form to accept the payments is rendered on the client side only.     Note: Before starting you’ll need to sign up for a Sandbox account. That will provide us with the required braintree API keys. There are two parts to the problem. First one is setting up the form and securing the data to be sent to the server. The next is to process the transaction the server side. Payment Form A simple payment form captures the credit card information along with amount of payment to be made. Here goes a very simple HTML form which asks for all the required info:
</pre>
<h1>Braintree Credit Card Transaction Form</h1>
<div><form id="braintree- payment-form" action="/create_transaction" method="POST"><label>Card Number</label>
<input type="text" autocomplete="off" size="20" data-encrypted-name="number" />

<label>CVV</label>
<input type="text" autocomplete="off" size="4" data-encrypted-name="cvv" />

<label>Expiration (MM/YYYY)</label>
<input type="text" name="month" size="2" /> / <input type="text" name="year" size="4" />

<input id="submit" type="submit" /></form></div>
<pre>
Next up, we need to encrypt the payment that is being sent from client side to our server for processing. Braintree provides a nice JS library to encrypt the data that is being sent from your form. The integration is as simple as including the library and calling a do it all method.
<script type="text/javascript" src="https://js.braintreegateway.com/v1/braintree.js"></script><script type="text/javascript">// <![CDATA[
var braintree = Braintree.create("YourClientSideEncryptionKey"); braintree.onSubmitEncryptForm('braintree-payment-form');
// ]]></script>
As you can see, we just did couple of steps to secure the data being sent to the server.
  • We initialized the Braintree.js with client-side encryption key.
  • We then called the Braintree.js onSubmitEncryptForm method with the id of the form to encrypt the form before sending it to the server.
Thats it, your data is being securely sent to your server now for processing. Lets move on to the server side of the things. First up install the official braintree gem in your Gemfile. Setting up Rails Controller to commit a transaction with Braintree
  • Every Braintree user receives a unique set of API keys. These need to available in your application.
  • To retrieve the keys, first sign in your Sandbox account.
  • On the sandbox home page, you can get the API keys required to execute transactions with BrainTree.
  • The code will look like this(for sandbox environment)
  • 	Braintree::Configuration.environment = :sandbox
    	Braintree::Configuration.merchant_id = “use_your_merchant_id”
    	Braintree::Configuration.public_key = “use your public key”
    	Braintree::Configuration.private_key = “use your private key”
  • Next Up, lets call up the API call to make the transaction. Braintree gem comes with exhaustive set of method calls to interact with the gateway. Here we initiate a sale with Braintree.
  • 	result = Braintree::Transaction.sale(:amount => “1000.00”,
    :credit_card => {:number => params[:number], :cvv => params[:cvv], :expiration_month => params[:month], :expiration_year => params[:year]},
    :options => {:submit_for_settlement => params[:settlement]})
  • Thats it !! The result object will tell us whether initiating the payment succeeded or not. The object comes loaded with methods to test the result like result.success? and result.failed?
This is not the end to the whole payment process in Braintree. Braintree will send calls/hooks informing your application about the various payment states but that is out of scope for the purpose of this blog and will better taken up as a post for separate. I hope the blog helps you get up with Braintree Quickly. Please feel free to drop in comments if any.

Uploading Files to Amazon S3 with Paperclip

Paperclip is a very basic and useful ruby gem which is used in almost every rails application. Basically it allows user to upload images and other attachments for storage and processing. Storing Files/Attachments to Amazon S3 with paperclip is rather a simple job but i will still give a dig on out just if it comes out useful to anyone. There are two parts to the uploading. First Storge, Second Retrieval. We will take them one by one: Storage:
    • Apart from uploading files to your application server, paperclip also allows you to store your files on some external storage services such as Amazon S3 so as to provide your application better scalability, reliability, and speed than just storing files on the filesystem.
    • To upload your files to amazon s3 using paperclip, We can go through the following steps(assuming that you are already using paperclip to store files to your filesystem):-
    • Add the following gems to your Gemfile (This is the gem for including the Amazon SDK support):-
       gem 'aws-s3', :require => 'aws/s3'
       gem 'aws-sdk'
    • Run the ‘bundle install’ command.
    • Lets configure the model for paperclip :-
       class Post < ActiveRecord::Base
       attr_accessible :avatar
       has_attached_file :avatar,
       :styles => { :medium => "300x300>"},
       :storage => :s3,
       :s3_credentials=>{:access_key_id=>"AWS_ACCESS_KEY_ID",
       :secret_access_key => "AWS_SECRET_ACCESS_KEY"},
       :s3_permissions => "public-read",
       :path => ":id",
       :bucket => "AWS_BUCKET"
       end
    • Lets deciper the parameters above :
    1. s3_credentials : Takes a path, a File, or a Hash containing the access_key_id and secret_access_key that Amazon gives you.
    2. s3_permissions: This is a String that should be one of the access policies that S3 provides. The default for Paperclip is :public_read.
    3. bucket: This is the name of the S3 bucket that will store your files. Remember that the bucket must be unique across all of Amazon S3. If the bucket does not exist Paperclip will attempt to create it.
    4. path: This is the key under the bucket in which the file will be stored. The URL will be constructed from the bucket and the path. This is what you will want to interpolate. Keys should be unique, like filenames.
Retrieval Now, the Files that have been uploaded with Paperclip are stored in S3. However, metadata such as the file’s name, location on S3, and last updated timestamp are all stored in the model’s table in the database. Paperclip provides convenience methods to access the stored objects. e.g. To access the file’s url through the url method on the model’s file attribute (avatar in this example), you can use post.avatar.url (http://bucket.s3.amazonaws.com/…) Hope the blog comes in handy for someone looking to integrate paperclip with Amazon S3 pretty quickly.

Stripe Integration with Ruby on Rails

Stripe is a payment gateway that is easy to set up with your ROR app. It only charges fees on a per-transaction basis and that fee is very reasonable due to which it has been gaining foot in the market and is choice for many internet based stores as a defacto payment processor. Stripe is currently only available in the United States so you’ll need an account at a U.S. bank if you want to use it in your app. In this blog we will see how one can integrate strip in an RoR app:-
  1. First of all create your account at Stripe(stripe.com)
  2. You will get stripe keys(api and publishable) after creating an account, to retrieve. Go to Your Stipe Account -> Account Settings -> API Keys and note down the keys.
  3. Now add the stripe gem in your Gemfile as
  4. gem 'stripe', :git => https://github.com/stripe/stripe-ruby
  5. Place the api key in a configuration file to use them globally. For the simplicity of the blog, I assume we have an AppConfig struct which contains the application level globals
  6. Stripe.api_key = AppConfig.stripe[:api_key]
  7. Now Create a view page which will accept the card information from the user that contains the card information like name on card, card number, card id, exp_month and exp_year.
  8. <%= content_tag :tr do %>
     <%= label_tag "Name on Card:"%>
     <% end %>
     <%= content_tag :td do%>
     <%= f.text_field :name_on_card, :required => true%>
     <% end %>
     <% end %>
     <%= content_tag :tr do%>
     <%= content_tag :td do%>
     <%= label_tag "Card Number:"%>
     <% end %>
     <%= content_tag :td do%>
     <%= f.text_field :card_number, :required => true%>
     <% end %>
     <% end %>
    
  9. Create a stripe token to initiate a payment process
  10. card_token = Stripe::Token.create(:card => {:number => params[:card_number], :exp_month => params[:exp_month],
    :exp_year => params[:exp_year], :cvc => params[:card_id] })
    
  11. And then charge the card with the token obtained above. Thats it !! Isn’t it damn simple ?
  12. stripe_charge = Stripe::Charge.create(:amount => amoumt_in_cents, :currency => "usd", :card => card_token[:id],:description=> your_email_id )
    
  13. Stripe takes the amount in cents and your email is required to link the transaction. Now, the charge deducted from the user’s credit card will be added to your account excluding stripe charges.
  14. You can also retrieve the charge information as follows for the record purposes as:
  15. Stripe::Charge.retrieve(stripe_charge[:id])
    
  16. To Refund the Charge
charge = Stripe::Charge.retrieve(stripe_charge[:id])</pre>
charge.refund
Meanwhile, The Stripe API’s Documentation is available at https://stripe.com/docs/api/ruby. Important Note: Please note that blog is just meant to illustrate the usage of Stripe in an RoR app. There are many security considerations that must be taken into account while implementing a payment processor in the application. All that is topic for another day and we will suggest to research on proper security methods before implementing any payment processor in the application.

Migrating from MySQL to PostgreSQL In RoR Application

Since the day Heroku has made Postgres as the default database, the popularity of Postgres has gone through the roof. A lot of developers however feel that its quite a task to move from mysql to Postgres, so we thought of putting up a small writeup on how one can go about migrating from mysql from Postgres. PostgreSQL
  • Often simply Postgres, is an object-relational database management system (ORDBMS) available for many platforms including Linux, FreeBSD, Solaris, MS Windows and Mac OS X.
  • It implements the majority of the SQL:2008 standard, is ACID-compliant, is fully transactional (including all DDL statements), has extensible data types, operators, and indexes, and has a large number of extensions written by third parties
Migrating from MySQL to PostgreSQL – Why ?
  • One of the reasons is definitely for engineers developing on Heroku platform since postgres is now the default database on Heroku.
  • MySQL is faster and easier to use than PostgreSQL but PostgreSQL is perceived as more powerful, more focused on data integrity, and stricter at complying with SQL specifications.
Installing Postgres: For the purpose of blog, we will assume that the operating system is ubuntu, it should be equally easier to install it on other operating systems. Open the terminal and type following command to install postgresql :-
sudo apt-get install postgresql postgresql-client /*For Ubuntu Operating System*/
Now your postgresql server and client is installed. You can verify the installation by logging into the postgresql console by using this command:-
sudo -u postgres psql
NOTE:- use ‘\q’ to exit from the postgresql console. Creating the user This step is something different from mysql and developers migrating from mysql found this to be quite difficult to understand. We will try to decipher it here. Postgresql creates default superuser called “postgres” but we can’t use it in our application because of postgres security reasons . So, we need to create a new user that our application can use to login to postgres. To do so, go to terminal and type the following command to create a new user :-
sudo -u postgres createuser
Pressing ENTER after writing this command will ask you some questions like name of user and basic privileges to be given. Simply type the name of the user and answer of other questions in y/n like:- Enter name of role to add: user_name /*name of the user to be created*/ Shall the new role be a superuser? (y/n) /*Type y to make the user Superuser, otherwise type n*/ You are done creating the user, we will now create the database and assign the privileges for this database to the given user. This is almost similar like we do in mysql. Read More

Deploying RoR Apps using Capistrano – An Introduction

Capistrano is a Ruby gem or we can say a set of Ruby programs that gives you a set of advanced tools to deploy web applications to web servers. In other words, Capistrano allows you to copy code from your source control repository (SVN/Git) to your server via SSH, and perform pre and post-deploy functions like restarting a web server, renaming files, running database migrations and so on. With Capistrano you can also deploy to many machines at once.
    • Capistrano offers many advanced options but for the purpose of this introductory blog, we will focus only on the essential things that need to be taken care of while deploying a simple app. We will setup a simple recipe(fancy name for capistrano scripts) for deploying a Rails application to a single server from either SVN or Git repositories. We will cover a common work flow that allows you to deploy multiple environments: in this case, staging and production.
    • This tutorial has three steps for deployment
    • Installing Capistrano
    • Configure
    • Deployment
So Let’s start with the steps:- 1. Installing Capistrano:- In order to install Capistrano you will need Ruby and RubyGems installed on your computer. Then, just open the Gemfile of your Rails application and add the following line to include the capistrano gem:-
gem 'capistrano'
After configuring the gemfile, run ‘bundle install‘ command. 2. Configure: 2.1. Capification :- Capification refers to generating the necessary files in your Rails application needed for the deployment and this can be done by firing the following command in your rails app directory:- ubuntu:~/app_directory$ capify This command will create two files:
    • Capfile: this is the “main” file that Capistrano needs. Capistrano looks for and loads “Capfile” by default. All it does is load “config/deploy.rb”.
    • config/deploy.rb: this is the file that contains your Rails application’s deployment configuration. Rails prefers that all configuration go under the config directory, and so Capistrano tries to abide by that as much as it can by just pointing the Capfile to config/deploy.rb.
2.2. Configuration :- In general, you’ll leave the Capfile alone and do all your tweaking in config/deploy.rb. So for now just leave the Capfile and start working with the deploy.rb file. The following are the essential elements which are needed to be include for basic deployment:-
    • set :application, “App_Name” /* The name of your application to be deployed*/
    • set :repository, “repository_address” /*address of the repository where the application resides. This repository must be accessible to the server(where we are deploying) as well as the local machine*/
    • set :scm, :git /*we need to tell capistrano about which SCM we are using e.g. GIT, SVN or any other SCM. In above example we are using GIT. if we don’t write the SCM then by default it takes it as SVN. if you use username and password to access your repository then you need to mention that also by using the following two attributes also*/
    • set :scm_username, ‘your_scm_username’
    • set :scm_password, ‘your_scm_password’
    • set :deploy_to, “/data/#{application}” /*the address on the server where you want to deploy your application*/
    • set :user, “username” /*username for ssh login into remote server where you want to deploy your application*/
    • set :password, “password” /* for ssh login into remote server where you want to deploy your application. If you are not having the password you can you your public key to login into the server by giving the following option*/
    • ssh_options[:keys] = [“Your ssh key full path and name”]
    • server “abcd.com”, :app, :web, :db, :primary => true /*name or IP address of server where we want to deploy our application. But if we want to deploy the application on mltiple servers, then we need to add the following */
    • role :app, “tutorial.com”
    • role :web, “tutorial.com”
    • role :db, “tutorial.com”, :primary => true
Those three roles (app, web, and db) are the three that Capistrano needs for Rails deployment. You can always add your own roles, too, for tasks of your own, but make sure you declare at least one server in each of app, web, and db when you’re deploying Rails applications.
    • web: this is where your web server software runs. Requests from the web go straight here. For sites with lots of traffic, you might have two or three (or more!) web servers running behind a load balancer.
    • app: this is where your application layer runs. You might need only a single web server, and have it send requests to any of four or five different app servers, via a load balancer.
    • db: this is where migrations are run. Some prefer not to actually run code on the server where the database lives, so you can just set this to one of the app servers if you prefer. Capistrano will deploy your application to servers in this role. The “:primary => true” bit just says that this is our “primary” database server—you can have as many as you want (for database slaves and so forth), but Capistrano will only run migrations on the one you designate as “primary”.
The addresses you place in each role are the addresses that Capistrano will SSH to, in order to execute the commands you give. By using these parameters one can easily deploy a simple app to server. And there are some parameter which gives you additional options like:
  • use_sudo: Defines for the default Rails deployment recipes whether we want to use sudo or not. Sudo is a unix tool for executing commands as the root_user . To use it, your user must have passwordless sudo access enabled. If you’re using shared hosting where sudo access may not be enabled for your user, you should set :use_sudo to false. In general, if you can get away without using sudo, you should avoid it.
  • keep_releases: The number of old releases to keep, defaults to 5, can be overridden with any positive integer, negative values will produce undefined behavior. 0 means zero.
  • git_enable_submodules: If you’re using git submodules you must tell cap to fetch them or not. You can set its value 1 to include it and 0 to not include it.
  • branch:- You need to tell cap the branch to checkout during deployment. For example we have two branches i.e master and production and you want to check out from master branch, then you will be write it as: set :branch, “master”
  • deploy_via:- This option is used to tell capistrano that which deployment strategy we are using for deployment. There are various options available with deploy_via and we can chose between them as our convenience.
  • :checkout will do a full SCM checkout.
  • :copy will checkout locally, then tar and gzip the copy and sftp it to the remote servers.
  • :remote_cache will keep a local git repo on the server you’re deploying to and simply run a fetch from that rather than an entire clone. This is probably the best option as it will only fetch the changes since the last deploy.
  • Deployment Everything is ready to try our recipe for the first time and let Capistrano create the initial directory structure on your server for future deployments. Run the following command from the root directory of your application:
  • cap deploy:setup cap deploy:setup
  • When you run this command, Capistrano will SSH to your server, enter the directory that you specified in the deploy_to variable, and create a special directory structure that’s required for Capistrano to work properly. If something is wrong with the permissions or SSH access, you will get error messages. Look closely at the output Capistrano gives you while the command is running. The last step before we can do an actual deployment with Capistrano is to make sure that everything is set up correctly on the server from the setup command. There’s a simple way to verify, with the command: cap deploy:check cap deploy:check This command will check your local environment and your server and locate likely problems. If you see any error messages, fix them and run the command again. Once you can run without errors, you can proceed!Once you’ve verified your local and server configuration, run the following command: cap production deploy:migrations This command just log in to production and deploy the latest code from the master branch and run all the pending migrations. cap deploy This will perform a deployment to your default stage, which is staging. If you want to deploy to production, you’d run the following: cap production deploy production deploy While these commands are performed, you will see a lot of output. Capistrano print all commands it runs on your server as well as their output, making it possible for you to debug any problems. Enjoy the dynamic deployments using capistrano !!