Wednesday, July 15, 2009

Installing Ruby on Rails, Apache2 And Passenger in Linux

1. Installing Ruby on Rails:

i. Download the latest ruby source and rubygems source to /usr/local/src/ and

extract them. At the time of this writing, those commands were:

ii. cd /usr/local/src

iii. wget ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.7-p72.tar.gz (wget is the

cmd which downloads the tar.gz file)

iv. tar xzf ruby-1.8.7-p72.tar.gz

v. wget http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz

vi. tar xzf rubygems-1.3.1.tgz

2. Go into the Ruby directory and compile it, like so:

cd ruby-1.8.7-p72

./configure

make

NOTE: This was the key part to watch. This time around, you should see

compile messages stating that zlib was compiled successfully at the end of the

log on your screen.

3. Now install Ruby, if all went well:

make install

4. Now go setup RubyGems, like so:

cd ../rubygems-1.3.1

ruby setup.rb

5. Update the gem system for good measure

gem update --system

6. Install Rails

gem install rails

How to Install the Apache Web Server?

Apache is one of the most popular Web servers on the Web right now, and

part of its charm is that it's free. It also has a lot of features that make it very

extensible and useful for many different types of Web sites. It is a server that

is used for personal Web pages up to enterprise level sites.

This article will discuss how to install Apache on a Linux system. Before we

start you should be at least comfortable working in Linux - changing

directories, using tar and gunzip, and compiling with make (I'll discuss where

to get binaries if you don't want to mess with compiling your own). You should

also have access to the root account on the server machine.

Download Apache:

I recommend downloading the latest stable release. At the time of this

writing, that was Apache 2.0. The best place to get Apache is from the

Apache HTTP Server download site. Download the sources appropriate to

your system. Binary releases are available as well.

Extract the Files:

Once you've downloaded the files you need to uncompress them and

untarring:

i. gunzip -d httpd-2_0_NN.tar.gz

ii. tar xvf httpd-2_0_NN.tar

This creates a new directory under the current directory with the source

files.

Configuring:

Once you've got the files, you need to tell your machine where to find

everything by configuring the source files. The easiest way is to accept all

the defaults and just type:

./configure

Of course, most people don't want to accept just the default choices. The most

important option is the prefix= option. This specifies the directory where the

Apache files will be installed. You can also set specific environment variables

and modules. Some of the modules I like to have installed are:

* mod_alias - to map different parts of the URL tree

* mod_include - to parse Server Side Includes

* mod_mime - to associate file extensions with its MIME-type

* mod_rewrite - to rewrite URLs on the fly

* mod_speling (sic) - to help your readers who might misspell URLs

* mod_ssl - to allow for strong cryptography using SSL

* mod_userdir - to allow system users to have their own Web page directories

Please keep in mind that these aren't all the modules I might install on a given

system. Read the details about the modules to determine which ones you

need.

Build:

As with any source installation, you'll then need to build the installation:

make

make install

Customize:

Assuming that there were no problems, you are ready to customize your

Apache configuration. This really just amounts to editing the httpd.conf file.

This file is located in the PREFIX/conf directory. I generally edit it with vi:

vi PREFIX/conf/httpd.conf

Note: you'll need to be root to edit this file.

Follow the instructions in this file to edit your configuration the way you want

it. More help is available on the Apache Web site.

Test Your Server:

Open a Web browser on the same machine and type http://localhost/ in the

address box. You should see a page similar to the one in the partial screen

shot above. Specifically, it will say in big letters "Seeing this instead of the

website you expected?" This is good news, as it means your server installed

correctly.

Start Editing/Uploading Pages

Once your server is up and running you can start posting pages. Have fun

building your Web site.


Easiest way to install Passenger:

# Open a terminal, and type:

gem install passenger

# Type:

passenger-install-apache2-module

Or, if you want to install the Nginx version instead:

passenger-install-nginx-module

Installing a Crontab File

What is cron?

Crontab is a simple text file that holds a list of commands that are to be run at specified times.Cron is a that executes shell commands periodically on a given schedule. Cron is driven by a crontab, a configuration file that holds details of what commands are to be run along with a timetable of when to run them.

Description:

crontab -e [Edits a copy of the user's crontab file]

crontab -r [Remove the user's crontab files]

crontab -l [Lists the user's crontab file]

Crontab syntax:

A crontab file has six fields for specifying minute, hour, day of month, month, day of week and the command to be run at that interval. See below:

*     *     *     *     *  command to be executed
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)

Any line beginning with a ``#'' is a comment and is ignored.

Crontab examples:

* * * * *  #Runs every minute
*/2 * * * * #Runs every 2 minutes
35 * * * * #Runs at 35 minutes past the hour
30 5 * * * #Runs at 5:30 am every day
45 18 * * * #Runs at 6:45 pm every day
00 3 * * 0 #Runs at 3:00 am every Sunday
00 2 * * 6 #Runs at 2:00 am every Satuday
00 1 * * Sun #Runs at 1:00 am every Sunday
30 5 1 * * #Runs at 5:30 am on the first day of every month
00 0-23/2 03 08 * #Runs every other hour on the 3rd of August


There are also special strings that can be used:
@reboot #Runs at boot
@yearly #Runs once a year [0 0 1 1 *]
@annually #Runs once a year [0 0 1 1 *]
@monthly #Runs once a month [0 0 1 * *]
@weekly #Runs once a week [0 0 * * 0]
@daily #Runs once a day [0 0 * * *]
@midnight #Runs once a day [0 0 * * *]
@hourly #Runs once an hour [0 * * * *]

Monday, July 6, 2009

RailRoad (Ruby on Rails diagrams generator)

What is RailRoad?

RailRoad is a class diagrams generator for Ruby on Rails applications. It's a Ruby script that loads the application classes and analyzes its properties (attributes, methods) and relationships (inheritance, model associations like has_many, etc.) The output is a graph description in the DOT language, suitable to be handled with tools like Graphviz.

RailRoad can produce:

  • Model diagrams, showing both inheritance hierarchy and models associations. You can choose to show the model "content columns" and its types.
  • Controller diagrams, showing inheritance hierarchy. You can include the controllers' methods, grouped by its visibility (public, protected, private.)
  • State machine diagramas (for use with the "acts_as_state_machine" plugin.)

Download RailRoad

If you're using gem, you can install RailRoad by issuing:

gem install railroad

Usage

Run RailRoad on the Rails application's root directory. You can redirect its output to a .dot file or pipe it to the dot or neato utilities to produce a graphic. Model diagrams are intended to be processed using dot and controller diagrams are best processed using neato.

railroad [options] command

Common options

  • -b, --brief
    Generate compact diagram (no attributes nor methods)
  • -e, --exclude file1[,fileN]
    Exclude given files
  • -i, --inheritance
    Include inheritance relations
  • -l, --label
    Add a label with diagram information (type, date, migration, version)
  • -o, --output FILE
    Write diagram to file FILE
  • -r, --root PATH
    Set PATH as the application root
  • -v, --verbose
    Enable verbose output (produce messages to STDOUT)

Models diagram options

  • -a, --all
    Include all models (not only ActiveRecord::Base derived)
  • --hide-magic
    Hide magic field names
  • --hide-types
    Hide attributes type
  • -j, --join
    Concentrate edges
  • -m, --modules
    Include modules
  • -p, --plugins-models
    Include plugins models
  • -t, --transitive
    Include transitive associations (through inheritance)

Controllers diagram options

  • --hide-public
    Hide public methods
  • --hide-protected
    Hide protected methods
  • --hide-private
    Hide private methods

Other options

  • -h, --help
    Show this message
  • --version
    Show version and copyright

Commands

(You must supply one of these)

  • -M, --models
    Generate models diagram
  • -C, --controllers
    Generate controllers diagram
  • -A, --aasm
    Generate "acts as state machine" diagram

Examples

  • railroad -o models.dot -M
    Produces a models diagram to the file 'models.dot'
  • railroad -a -i -o full_models.dot -M
    Models diagram with all classes showing inheritance relations
  • railroad -M | dot -Tsvg > models.svg
    Model diagram in SVG format
  • railroad -C | neato -Tpng > controllers.png
    Controller diagram in PNG format
  • railroad -h
    Shows usage help


Thursday, June 4, 2009

Validating the Credit Card, Without Processing Credit Card.

# THIS MODULE IS USED TO CHECK FROM http://www.trynt.com/creditcard-validation-api
# API TO CHECK WHETHER CREDIT CARD NUMBER IS NOT A DUMMY CARD NUMBER.
require 'net/http'
require 'uri'
require 'rexml/document'

module CreditCardVarification

include REXML


def is_credit_card_valid?(credit_card_no, year, month)

begin

dummy_card = %w(371449635398431 378734493671000 5610591081018250 30569309025904 38520000023237 6011111111111117 6011000990139424

3530111333300000 3566002020360505 5555555555554444 5105105105105100 4111111111111111 4012888888881881 4222222222222 76009244561
5019717010103742 6331101999990016)

action = get_body_from_url(credit_card_no, year, month)


if defined? Document.new(action).elements['Trynt/Credit-Card-Validation/Result'].text


result = Document.new(action).elements['Trynt/Credit-Card-Validation/Result'].text


unless result.nil?

if result.eql?("Appears Valid") && !dummy_card.include?credit_card_no.to_s)
return true
end
end
end
return false
rescue
return false
end
end

def get_body_from_url(credit_card_no, year, month)
url = "http://www.trynt.com/credit-card-validation-api/v1/?cc=#{credit_card_no}&y=#{year}&m=#{month}"
url = URI.parse(url)
res = Net::HTTP.get_response(url)
return res.body
end
end

Using Thread to store session variable

# THE BELOW MENTIONED FUNCTION WILL BE USED TO STORE THE SESSION VALUE SO THAT SESSION VARIABLES CAN BE USED IN MODEL...

module UserInfo
def get_current_user_in_model
Thread.current[:user]
end

def self.get_current_user_in_model=(user)
Thread.current[:user] = user
end
end

Tuesday, May 26, 2009

Insert At Cursor -- Javascript


function insertAtCursor(myField, myValue) {

//IE support

if (document.selection) {

myField.focus();

sel = document.selection.createRange();

sel.text = myValue;

}

//MOZILLA/NETSCAPE support

else if (myField.selectionStart || myField.selectionStart == '0') {

var startPos = myField.selectionStart;

var endPos = myField.selectionEnd;

myField.value = myField.value.substring(0, startPos)

+ myValue

+ myField.value.substring(endPos, myField.value.length);

} else {

myField.value += myValue;

}

}
// calling the function

insertAtCursor(document.formName.fieldName, 'this value');

Friday, May 15, 2009

Different ways of Validating Date of Birth in Model

def validate
if (date_of_birth.month==2 && date_of_birth.month.day > 29)
errors.add(:birthdate, "Invalida date")
end
end

OR

validates_each :date_of_birth do |record, attr, value|
record.errors.add attr, "is not a valid date. You must be at least 18 years old to sign in." if value.blank?
end

OR

def validate
if date_of_birth.month.blank? || date_of_birth.day.blank? || date_of_birth.year.blank?
errors.add_to_base "day, month and year cannot be blank."
end
end

Validates_presence_of : customise field name

validates_presence_of :id_country, :message => "Country can't be blank"

class Adresse < ActiveRecord::Base

HUMANIZED_COLLUMNS = {:id_country => "Country"}

def self.human_attribute_name(attribute)
HUMANIZED_COLLUMNS[attribute.to_sym] || super
end
end

Monday, April 27, 2009

Gets Days from the difference between two dates.

Example:
> a = "2009-04-01 18:33:05"
> b = Time.now
> c = b.to_date - a.to_date
O/P: Rational(4, 1)
> c.to_i
=> 4
OR
> c = (b.to_date - a.to_date).to_i
=> 4

Generate Unique id

class Unique
def self.generate_unique_id(len)
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
generate_unique_id = ""
1.upto(len) { |i| generate_unique_id << chars[rand(chars.size-1)] }
return generate_unique_id
end
end

Example:
irb> Unique.generate_unique_id(18)
=> "CCDCa6Fv1AKsIaYAAA"

Ruby Chop vs Chomp

When you receive user input from textareas or console input you may get some newline characters. One way to remove newline characters is the String#chop method, it will remove any trailing newline or carriage return characters “\r\n”. But it’s tricky. Because here it works like it’s suppose to.

full_name = "My Name is Ravikanth\r\n" 

full_name.chop! # => "My Name is
Ravikanth"

Now if you run chop and there are no newline characters.

puts full_name    #=> "My Name is Ravikanth"

full_name.chop! #=> "My Name is
Ravikant"

Disaster Strikes!

That’s why there is chomp.

puts full_name       #=> "My Name is Ravikanth\r\n"

full_name.chomp! #=> "My Name is
Ravikanth"
full_name.chomp! #=> "My Name is
Ravikanth"

So chomp is our recommended way of removing trailing newline characters.


Saturday, March 21, 2009

Finding remote ip address

We can fine remote ip address with

request.env['HTTP_USER_AGENT']