Basic Ruby on Rails Tutorial

Ruby on Rails Logo [Source]
Rails is a web application framework running on the Ruby programming language.
The Rails philosophy includes several guiding principles:

  1. DRY – “Don’t Repeat Yourself” – suggests that writing the same code over and over again is a bad thing.
  2. Convention Over Configuration – means that Rails makes assumptions about what you want to do and how you’re going to do it, rather than requiring you to specify every little thing through endless configuration files.
  3. REST is the best pattern for web applications – organizing your application around resources and standard HTTP verbs is the fastest way to go.

The MVC Architecture

At the core of Rails is the Model, View, Controller architecture (MVC). MVC benefits include:
Isolation of business logic from the user interface
Ease of keeping code DRY
Making it clear where different types of code belong for easier maintenance

Models

A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table.

Views

Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that perform tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.

Controllers

Controllers provide the “glue” between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.

The Components of Rails

Rails ships as many individual components
  • Action Pack
  • Action Controller
  • Action Dispatch
  • Action View
  • Action Mailer
  • Active Model
  • Active Record
  • Active Resource
  • Active Support
  • Railties

REST

Rest stands for Representational State Transfer and is the foundation of the RESTful architecture.
REST in terms of Rails boils down to two main principles:

  • Using resource identifiers such as URLs to represent resources.
  • Transferring representations of the state of that resource between system components.

For example, the following HTTP request:
DELETE /photos/17
would be understood to refer to a photo resource with the ID of 17, and to indicate a desired action – deleting that resource. REST is a natural style for the architecture of web applications, and Rails hooks into this shielding you from many of the RESTful complexities and browser quirks.

Create new app

the following command creates a ruby application.
rails new myapp

Rails App Hierarchy


|-- app
|   |-- assets
|       |-- images
|       |-- javascripts
|       `-- stylesheets
|   |-- controllers
|   |-- helpers
|   |-- mailers
|   |-- models
|   `-- views
|       `-- layouts
|-- config
|   |-- environments
|   |-- initializers
|   `-- locales
|-- db
|-- doc
|-- lib
|   `-- tasks
|-- log
|-- public
|-- script
|-- test
|   |-- fixtures
|   |-- functional
|   |-- integration
|   |-- performance
|   `-- unit
|-- tmp
|   |-- cache
|   |-- pids
|   |-- sessions
|   `-- sockets
`-- vendor
    |-- assets
        `-- stylesheets
    `-- plugins

Run Application Server

The following command change the directory and start rails server.
cd myapp; rails server

Database Configuration 

Database configuration of the application stays in config file of the project hierarchy with the name database.yml. A default database configured to use SQLite3. The file contains sections for three different environments in which Rails can run by default:

  1. The development environment is used on your development/local computer as you interact manually with the application.
  2. The test environment is used when running automated tests.
  3. The production environment is used when you deploy your application for the world to use.

Run Application with MySQL

rails new myapp -d mysql

Create Database for Application

rake db:create
Note: you’ve to add libmysql.dll in bin folder of ruby to create mysql database and to run this command your mysql server should be running. After this command this will create databases mentioned in databases.yml

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: blog_development
  pool: 5
  username: root
  password:
  host: localhost

Creating controller and write in view

The following command creates a controller.
rails generate controller home index
Rails will create several files for you, including app/views/home/index.html.erb. This is the template that will be used to display the results of the index action (method) in the home controller.

Setting Application Home Page

The command below will remove the default home page
del public\index.html
We need to do this as Rails will deliver any static file in the public directory in preference to any dynamic content we generate from the controllers.

Routes.rb

This is your application’s routing file which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions.
The command below will set index page as home.
root :to => 'home#index'

Rails Scaffolding

Rails scaffolding is a quick way to generate some of the major pieces of an application. If you want to create the models, views, and controllers for a new resource in a single operation, scaffolding is the tool for the job.

Creating a Resource

The scaffold generator will build several files (model, view and controller) in your application, along with some folders, and editconfig/routes.rb
rails generate scaffold EntityName name:string title:string content:text
Migration
The below command will migrate fields from C:\Sites\blog\db\migrate\ 20130206072034_create_entityName.rb to database)
rake db:migrate

Model Class & Validations

class Post < ActiveRecord::Base
 attr_accessible :content, :name, :title

  validates :name,  :presence => true
  validates :title, :presence => true,
                    :length => { :minimum => 5 }
End

Rails Console

Rails console uses for validations in action. The console is a command-line tool that lets you execute Ruby code in the context of your application.
>> p = Post.new(:content => "A new post")
=> #<Post id: nil, name: nil, title: nil,
     content: "A new post", created_at: nil,
     updated_at: nil>
>> p.save
=> false
>> p.errors.full_messages
=> ["Name can't be blank", "Title can't be blank", "Title is too short (minimum is 5 characters)"]

Options:


  • Passing the -s, --sandbox argument will rollback any modifications made to the database.
  • Passing an environment name as an argument will load the corresponding environment. Example: rails console production.
  • To reload your controllers and models after launching the console run reload!


Note:
rb extension is ruby code file
erb extension is scripting ruby file

Controller Methods


  • All
  • Show
  • New
  • Create
  • Delete
  • Edit
  • Update

Controller defines above methods and views use all methods.

Note:

  • link_to builds a hyperlink to a particular destination
  • edit_post_path and new_post_path are helpers that Rails provides as part of RESTful routing. 

Customizing Layouts


  1. Application.html.erb defines application specific layout
  2. Scaffold.css.css is the global css

Basic Http Security


  • http_basic_authenticate_with :name => "123", :password => "123", :only => :destroy
  • http_basic_authenticate_with :name => "123", :password => "123", :except => [:index, :show]

Debugging 

The following command will help in debugging:
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")

Debugger

The following command to run debugger:
debugger

Callbacks

Callbacks are methods that get called at certain moments of an object’s life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

Creating an Object


  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_create
  • around_create
  • after_create
  • after_save

Updating an Object


  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_update
  • around_update
  • after_update
  • after_save

Destroying an Object


  • before_destroy
  • around_destroy
  • after_destroy

Others


  • after_initialize 
  • after_find

Running Callbacks

The following methods trigger callbacks:

  • create
  • create!
  • decrement!
  • destroy
  • destroy_all
  • increment!
  • save
  • save!
  • save(:validate => false)
  • toggle!
  • update
  • update_attribute
  • update_attributes
  • update_attributes!
  • valid?

Additionally, the after_find callback is triggered by the following finder methods:

  • all
  • first
  • find
  • find_all_by_attribute
  • find_by_attribute
  • find_by_attribute!
  • Last

Skipping Callbacks

Just as with validations, it is also possible to skip callbacks. These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.

  • decrement
  • decrement_counter
  • delete
  • delete_all
  • find_by_sql
  • increment
  • increment_counter
  • toggle
  • touch
  • update_column
  • update_all
  • update_counters

Halting Execution
Relational Callbacks
Conditional Callbacks
Transaction Callbacks


  • after_commit
  • after_rollback.
  • after_save

Gems

RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries. [Source]

Install Gem

INSTALLgem install will_paginate
gem 'will_paginate', '~> 3.0.0'
 in gem file

Environment File 

require 'will_paginate'

Why Ruby?


  • Quick Launcher
  • Time saving
  • Easier Changes
  • Code effective

Why not Ruby?


  • Not mature as Java or PHP
  • Not performant as .NET or Java
  • Doesn’t work well on Windows
  • Less support on community

[For a complete and comprehensive document, visit the Source.]

No comments:

Post a Comment