How To Setup Nginx On Server For Rails Application?


How To Setup Nginx On Server For Rails Application?Ruby on Rails is a popular rapid development web framework. It allows web designers and developers to quickly implement dynamic and fully featured Ruby on Rails application. This article describes procedures for installing Ruby on Rails in conjunction with the nginx setup and Passenger module.

Nginx (pronounced “engine X”) is a lightweight, high-performance Web server/reverse proxy and e-mail (IMAP/POP3) proxy. It is licensed under a BSD-like license. It runs on UNIX, GNU/Linux, BSD variants, Mac OS X, Solaris, and Microsoft Windows .  Unlike traditional servers, it doesn’t rely on threads to handle requests.

Instead it uses a much more scalable event-driven (asynchronous) architecture. This architecture uses small, but more importantly, predictable amounts of memory under load.

Even if you don’t expect to handle thousands of simultaneous requests, you can still benefit from its’s high-performance and small memory footprint. It scales in all directions: from the smallest VPS all the way up to clusters of servers.

To install nginx you would require passenger first:

Install passenger:

$ gem install passenger

$ passenger -v

In order to let Passenger install it, you need to install a dependency first.

$ sudo apt-get install libcurl4-openssl-dev

use rvmsudo than regular sudo to install it

$rvmsudo passenger-install-nginx-module

start nginx

$ sudo /opt/nginx/sbin/nginx

Configuration

$ sudo nano /opt/nginx/conf/nginx.conf (VPS)

$ sudo /etc/init.d/nginx reload (VPS)

configuration file example

server {

listen 80;

server_name http://www.yourdomain.com;

root /home/Nagakiran/test_app/current/public;

passenger_enabled on;

#charset koi8-r;

#access_log logs/host.access.log main;

#location / {

# root html;

# index index.html index.htm;

#}

Source : RailsCarma

Advertisements

Scraping of Websites Using Mechanize Gem


Web scraping (web harvesting or web data extraction) is a computer software technique of extracting information from websites. The Mechanize library is used for automating interaction with websites. Mechanize gem automatically stores and sends cookies, follows redirects, and can follow links and submit forms.

Form fields can be populated and submitted. It also keeps track of the sites that you have visited as a history. It  leverages Nokogiri to parse a page for the relevant forms and buttons and provides a simplified interface for manipulating a webform.

Dependencies

  • ruby 1.8.7, 1.9.2, or 1.9.3
  • Nokogiri

Getting started with Mechanize:

Let’s Fetch a Page!

First thing is first. Make sure that you’ve required mechanize and that you instantiate a new mechanize object:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
Now we’ll use the agent we’ve created to fetch a page. Let’s fetch google with our mechanize agent:
page = agent.get ('http://google.com/')
Finding Links

Scraping of Websites using Mechanize Gem

Mechanize returns a page object whenever you get a page, post, or submit a form. When a page is fetched, the agent will parse the page and put a list of links on the page object.

Now that we’ve fetched google’s homepage, lets try listing all of the links:

page.links.each do |link|
  puts link.text
end

We can list the links, but Mechanize gives a few shortcuts to help us find a link to click on. Lets say we wanted to click the link whose text is ‘News’. Normally, we would have to do this:

page = agent.page.links.find { |l| l.text == 'News' }.click (or)
page = agent.page.link_with(:text => 'News').click (or)
agent.page.links_with(:text => 'News')[1].click (or)
page.link_with(:href => '/something').
Filling Out Forms

Lets continue with our google example. Here’s the code we have so far:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
page = agent.get('http://google.com/')

If we pretty print the page, we can see that there is one form named ‘f’, that has a couple buttons and a few fields:

pp page

Now that we know the name of the form, lets fetch it off the page:

google_form = page.form('f')

Lets take a look at the code all together:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
page = agent.get('http://google.com/')
google_form = page.form('f')
google_form.q = 'ruby mechanize'
page = agent.submit(google_form)
pp page
Scraping Data 
Mechanize uses Nokogiri to parse HTML. What does this mean for you? You can treat a mechanize page like an nokogiri object. After you have used Mechanize to navigate to the page that you need to scrape, then scrape it using nokogiri methods:
agent.get('http://someurl.com/').search("p.posted")

The expression given to Mechanize::Page#search may be a CSS expression or an XPath expression:

agent.get('http://someurl.com/').search(".//p[@class='posted']")

The Mechanize library is used for automating interaction with websites. Mechanize gem automatically stores and sends cookies, follows redirects, and can follow links and submit forms. Form fields can be populated and submitted. It also keeps track of the sites that you have visited as a history. leverages Nokogiri to parse a page for the relevant forms and buttons and provides a simplified interface for manipulating a webform.

Dependencies

  • ruby 1.8.7, 1.9.2, or 1.9.3
  • Nokogiri

Getting started with Mechanize:

Let’s Fetch a Page!

First thing is first. Make sure that you’ve required mechanize and that you instantiate a new mechanize object:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
Now we’ll use the agent we’ve created to fetch a page. Let’s fetch google with our mechanize agent:
page = agent.get ('http://google.com/')
Finding Links

Mechanize returns a page object whenever you get a page, post, or submit a form. When a page is fetched, the agent will parse the page and put a list of links on the page object.

Now that we’ve fetched google’s homepage, lets try listing all of the links:

page.links.each do |link|
  puts link.text
end

We can list the links, but Mechanize gives a few shortcuts to help us find a link to click on. Lets say we wanted to click the link whose text is ‘News’. Normally, we would have to do this:

page = agent.page.links.find { |l| l.text == 'News' }.click (or)
page = agent.page.link_with(:text => 'News').click (or)
agent.page.links_with(:text => 'News')[1].click (or)
page.link_with(:href => '/something').
Filling Out Forms

Lets continue with our google example. Here’s the code we have so far:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
page = agent.get('http://google.com/')

If we pretty print the page, we can see that there is one form named ‘f’, that has a couple buttons and a few fields:

pp page

Now that we know the name of the form, lets fetch it off the page:

google_form = page.form('f')

Lets take a look at the code all together:

require 'rubygems'
require 'mechanize'

agent = Mechanize.new
page = agent.get('http://google.com/')
google_form = page.form('f')
google_form.q = 'ruby mechanize'
page = agent.submit(google_form)
pp page
Scraping Data 
Mechanize uses Nokogiri to parse HTML. What does this mean for you? You can treat a mechanize page like an nokogiri object. After you have used Mechanize to navigate to the page that you need to scrape, then scrape it using nokogiri methods:
agent.get('http://someurl.com/').search("p.posted")

The expression given to Mechanize::Page#search may be a CSS expression or an XPath expression:

agent.get('http://someurl.com/').search(".//p[@class='posted']")

Source : RailsCarma


Asset Pipeline In Rails 3.1.0


Asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as Coffee Script, Sass and ERB. In Rails 3.1, the rails asset pipeline is enabled by default. It can be disabled in config/application.rb by putting this line inside the application class definition:

config.assets.enabled = false

we can also disable the asset pipeline while creating a new application by passing the —skip-sprockets option.

rails new appname –skip-sprockets

Features of asset pipeline:
1.Concatenate assets

This feature is important in a production environment, because it can reduce the number of requests that a browser must make to render a web page. Web browsers are limited in the number of requests that they can make in parallel, so fewer requests can mean faster loading for application.

Rails 2.x introduced the ability to concatenate JavaScript and CSS assets by placing :cache => true at the end of the javascript_include_tag and stylesheet_link_tag methods. But this technique has some limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries.

Asset Pipeline In Rails 3.1.0

2.Asset minification or compression

For CSS files, compression is done by removing whitespace and comments. For JavaScript, more complex processes can be applied. we can choose from a set of built-in options or specify our own.

3.It allows coding assets via a higher-level language, with precompilation down to the actual assets.Supported languages include Sass for CSS, CoffeeScript for JavaScript, and ERB for both by default. In older versions of Rails asset pipeline, all assets are located in subdirectories of public such as images, javascripts and stylesheets.

With the asset pipeline, the preferred location for these assets is now the app/assets directory. Files in this directory are served by the Sprockets middleware included in the sprockets gem. Assets can still be placed in the public hierarchy. Any assets under public will be served as static files by the application or web server. we should use app/assets for files that must undergo some pre-processing before they are served.

In production, Rails precompiles these files to public/assets by default. The precompiled copies are then served as static assets by the web server. The files in app/assets are never served directly in production.

When we generate a scaffold or a controller, Rails also generates a JavaScript file (or CoffeeScript file if the coffee-rails gem is in the Gemfile) and a Cascading Style Sheet file (or SCSS file if sass-rails is in the Gemfile) for that controller.

Asset Organization:

The biggest practical difference between Rails 3.0 and Rails 3.1 apps is a change in the location of asset files such as images, stylesheets, and JavaScript files. In previous versions of Rails asset pipeline, these files all lived in the public/ directory:

public/images/

public/stylesheets/

public/javascripts/

In Rails 3.1, and Rails 3.2.3 the location of these files differs based on whether they are created by us or come from an external vendor. In this case the files live in the app/assets directory:

app/assets/images/

app/assets/stylesheets/

app/assets/javascripts/

In the case of code or images from external vendors, we use the vendor/assets directory:

vendor/assets/images/

vendor/assets/stylesheets/

vendor/assets/javascripts/

Manifest files

These are plain js or css files containing directive processors, comment lines followed by a =

// …

//= require jquery

//= require jquery_ujs

//= require_tree .

Or:

/* …

*= require_self

*= require_tree .

These manifest files reference and include other assets that they depend on. require_directory and require_tree lets we require whole directories and their children, require_self also includes any js or css in the manifest file itself.

Source : RailsCarma

Testing Rails 3.2.3 Application Using Cucumber (BDD)


What is Cucumber?

Cucumber is used for Behavior Driven Development. Cucumber lets software development teams describe how software should behave in plain text. The text is written in a business-readable domain-specific language and serves as documentation, automated tests and development-aid – all rolled into one format.

Cucumber works with Ruby on Rails, Java, .NET, Flex or web applications written in any language. It has been translated to over 40 spoken languages. Cucumber also supports more succinct tests in tables – similar to what FIT does.

Ruby_on_Rails_logo

Install cucumber for Rails 3:

Install Cucumber, Rspec-rails and capybara gem

sudo gem install cucumber-rails
sudo gem install database_cleaner
sudo gem install rspec-rails
sudo gem install capybara
  • Cucumber is a behavior driven development (BDD) framework in particular good for integration and functional tests

  • RSpec is a behavior driven development (BDD) framework for low-level testing in the Ruby language
  • database_cleaner performs DB cleanup in testing
  • capybara simulating a browser, automating a browser or setting expectations using the matchers.

Using Cucumber to test rails 3 application:

1. Create a new Rails application store

$rails new store -d mysql

2. Edit the Gemfile

Include the Cucumber gems in a Rails 3 application

   group :test, :development do
        gem 'rspec-rails'
        gem 'cucumber-rails'
        gem 'capybara'
        gem 'database_cleaner'
 end
3. bundle install

4. Install the cucumber skeleton files to a Rails 3 application.

$ rails generate cucumber:install 

The cucumber-rails generator creates the directories:

features/step_definitions

features/support

The cucumber-rails generator creates the files:

config/cucumber.yml

features/support/env.rb

lib/tasks/cucumber.rake

script/cucumber

5. rake db:create
6. rake db:migrate

7. Run the Cucumber features

$rake cucumber

Create cucumber features:
  • Create a Cucumber Feature for RoR 3 application testing

$vi features/manage_store.feature

  • Cucumber Feature is the business user testing specification written in plain English with a specific format

Feature Format

 Feature: ...
   In order ...
     Some Actor ...
     Should ...

    Scenarior: ...
       Given ...
       And ...

     When ...
     AND ...

     Then ...
     AND ...

Implement the testing steps and Ruby on Rails model code for Cucumber on Rails :

  • Create Cucumber step definitions

$vi features/step_definitions/order_steps.rb

  • Cucumber uses regular expression to match string and pass it to the step definitions
  • Run Cucumber
$rake cucumber
An example might be the ability to manage companies:
Feature: Manage companies

 In order to keep track of companies user should be able to manage companies

Scenario: Create a new company

 Given I am logged in

 When I create a new company named Acme

 Then I should see that a company named Acme exists 

features/

companies.feature

steps/

company_steps.rb

Given == Setup

Given "I am logged in" do

user = Factory(:user)

visits new_session_path

fills_in ‘Login’,

:with => user.login

fills_in ‘Password’, :with => user.password

clicks_button ‘Login’

end

Given "I am logged in" do

user = Factory(:user)

visits new_session_path

fills_in 'Login',

:with => user.login

fills_in 'Password', :with => user.password

clicks_button 'Login'

end

When == Change

When "I create a new company named $name" do |name|

visits new_company_path

fills_in 'Name', :with => name

clicks_button 'Create'

end

Then == Outcome

Then "I should see that a company named $name exists" do |name|

response.body.should =~ Regexp.new(name)

end

At every step you need to run cucumber and check for the result.



Source:RailsCarma 

Integrating Spree In Rails 3.1 Application


Spree is a complete open source e-commerce solution built with Ruby on Rails. It was originally developed by Sean Schofield and is now maintained by a dedicated core team. You can find out more by visiting the Spree e-commerce project page.

It actually consists of several different gems, each of which are maintained in a single repository and documented in a single set of online documentation.

By requiring the Spree gem you automatically require all of the necessary gem dependencies which are:

  • spree_api
  • spree_cmd
  • spree_core
  • spree_dash
  • spree_promo
  • spree_sample

All of the gems are designed to work together to provide a fully functional e-commerce platform. It is also possible, however, to use only the pieces you are interested in. So for example, you could use just the barebones spree_core gem and perhaps combine it with your own custom promotion scheme instead of using spree_promo.

rails_on_rubyInstallation:- It depends on ImageMagick to handle the image processing it does, so we’ll need to install it before we can install Spree. If its not installed already,install it using apt-get(for ubuntu). Once imagemagick is installed,we will create a new rails 3.1 application with the following coSpree In Rails 3.1mmand from terminal. e.g – rails new gps -d mysql (-d mysql specifies that we are going to use mysql as our database)

To install it and all its dependencies, we need to add it in our gemfile. My gemfile looks like this:- source ‘http://rubygems.org’

gem ‘rails’, ‘3.1.3’

Bundle edge Rails instead:

gem ‘rails’, :git => ‘git://github.com/rails/rails.git’

gem ‘capistrano’ gem ‘mysql2′ gem ‘therubyracer’ gem ‘paperclip’, “~> 2.3″ gem ‘tinymce-rails’

Gems used only for assets and not required

in production environments by default.

group :assets do gem ‘sass-rails’, ‘~> 3.1.5′ gem ‘coffee-rails’, ‘~> 3.1.1′ gem ‘uglifier’, ‘>= 1.0.3′ end

gem ‘jquery-rails’

Source : Railscarma

Application Deployment On Heroku


 

heroku

Heroku offers Ruby web developers instant deployment, fast & easy scaling, and vast tool selection. Now we can concentrate on building our applications and forget the tedious deployment and server administration tasks that used to strangle our productivity. We can deploy fast, scale quickly, and adjust to circumstance as needs arise.

This article will explain to you how to deploy your applications on the popular platform. It is cloud based application platform for easy deployment of your applications. The integration with Cloud9 IDE makes your development process even more agile.

When you use the platform for deploying your application you need to make sure of the following

1. B y default the cloud platform will have shared database and it will be postgresql database.

2. All your migrations must be postgresql compatible.

3. Use pg gem in your application

4. You need to have suitable addons of heroku for deploying your application

Specify heroku gem in your gem file of app that you want to deploy

gem ‘heroku’

$ bundle install

SSH key generation:

$ ssh-keygen -t rsa

The above command will generate public key inside /home/Username/.ssh/id_rsa.pub

$ heroku accounts:add

Account name should be your heroku login

Steps:

1. Initialize pg gem in your Gemfile in order to use postgresql database.

gem ‘pg’

2. Bundle install after initializing the gem

$ bundle install

3. Even though you are using SVN repository, it’s better to use git repository for deploying your applications to the cloud platform. If you are using SVN and if you would like to initialize git repository only to push updates to heroku then follow the steps below

$ git init

$ git add .

$ git commit -m “init”

This creates a local git repository where you will be adding the files which you update or add from your svn repository.

If you have to work with the cloud platform from your application you should generate ssh keys and add the public key to the heroku.

You can do it from the steps given here:

https://devcenter.heroku.com/articles/keys

4.After adding the keys login to the cloud platform using the command below with the credentials and check whether you are able to login.

$ heroku login
Enter your Heroku credentials.
Email: adam@example.com
Password: 
Could not find an existing public key.
Would you like to generate one? [Yn] 
Generating new SSH public key.
Uploading ssh public key /Users/name/.ssh/id_rsa.pub

5. If you are able to login to the cloud application, then from your application folder create an application in heroku using

 ceder rack of heroku
 $ heroku create --stack cedar myap
6. After creating the application you need have a remote repository and one remote git repository should be 
added to heroku also.
 $ git remote -v
 $ git remote add heroku git@heroku.com:myapp.
 $ git init

This creates a remote repository in heroku and will be initialized with the local repository

7. Since you will be using SVN repository you need to add this in order to ignore the .svn hidden files which comes into application 
after updating from repository and you can do that here by using the things below.
 $ echo .svn > .gitignore 
 $ svn propset svn:ignore .gi 
8. After executing this you need to add the files to local repository and commit them
 $ git add .
 $ git commit -m "using git for heroku deployment"

9. After you commit the updates to heroku repository and create the application, you can push the updates to the application with this command

$ git push heroku master

10. Migrate the database migrations into heroku shared database using

$ heroku run rake db:create

$ heroku run rake db:migrate

For all the commands available with heroku you can check the commands here.

Push updates to heroku ( Default Environment: production already set)

->Update code from subversion repository

$ svn update

->Check the status of the files

$ git status

->Manage the added and removed files from the git using git commands

$ git rm file # to remove the file

->Add files to local git repository

$ git add .

->Push updates of code to local repository

$ git commit -m “Message”

The above command commits all the files, if you want to push only specific files into git repository then you should specify the file name after the commit.

After you commit the code to local git repository, you need to push to heroku

$ git push heroku master

This pushes the code which was updated after the last push and launches the instance on heroku server.

->To check the application logs use

$ heroku logs –tail

->To run application console use

$ heroku run console

->To check the heroku configuration of your application

$ heroku config

->To start start| stop| restart application use

$ heroku restart | stop | start

Set Your Domain Name

This command tells Heroku that your app should respond to requests to “www.mydomain.com”:

$heroku domains:add http://www.mydomain.com

 

Source : RailsCarma