ruby on rails

Download Ruby On Rails

Post on 11-Sep-2014

7 views

Category:

Documents

1 download

Embed Size (px)

DESCRIPTION

Ruby On Rails basics

TRANSCRIPT

  • Ruby On RailsGautam RegeJosh Software Pvt. Ltd.

    Rails Training Programme

  • Speaker Introduction9 years Software ExperienceBE PICTWorking in rails since 2006Co-founded Josh Software 2007Previous Experience Cybage, Zensar, Symantec

    Rails Training Programme

  • Part 1 Ruby on Rails Introduction

    Rails Training Programme

  • History of RubyFather of Ruby Yukihiro Matsumoto, a.k.a. Matz, Japan, 1995Ruby is an Object Oriented Scripting LanguageObject Oriented helps in designing applicationsScripting makes it faster and quicker to develop and redeploy.

    Rails Training Programme

  • Ruby Vs PythonPython was the first OO script but its not a pure OO. There is no real encapsulation.Indentation !!def foo: print This is the first line print This is second line print This is a syntax errorSerious Ruby CompetitorLots of python plugins and auto-install featuresVery popular todayCaveats:Python Why the name?

    Rails Training Programme

  • Ruby Vs PerlPerl is really a procedural language. OO Perl was introduced later.Syntax difficult to understand: $ \ @ % Excellent stream parser.. That was the original purpose.Caveats:Perl - Practical Extraction and Report Language

    Rails Training Programme

  • Ruby Vs Perl contd..foreach$item(@fields){ if($db{$item}){ print"conflicton$item\n"; $err++; next; } $db{$item}=\@fields; } fields.each { |item| puts conflict on #{item} if fields.include?(item) }

    Rails Training Programme

  • Features of RubyPure Object Oriented ScriptNo indentation issues.Readable code.Blocks and IteratorsInstance and Class variablesCaveats:What is the difference between, Proc, Lamda, a normal function

    Rails Training Programme

  • What do I choose anyway??Perl is for people who believe that old is gold and are set in their ways. Python is for veterans: people more comfortable on unix and vi than on Windows and Word!Ruby is for enthusiasts. You treat Ruby like you pet. You code because you enjoy it, watch it grow AND groom it as you like.

    Rails Training Programme

  • Overall Comparison

    Rails Training Programme

  • Web TechnologiesJava J2EEPython Pylons, CGIPHPPerl CGIRuby Rails.NET ASP, C#

    Rails Training Programme

  • J2EE, .NET Web DevelopmentJ2EE. .NET are very evolved and very good for robust and heavy applications.They support different levels of tier architecture EJB, databases Excellent Security application and codeExcellent Load Balancing and clustering support

    Deployment is complicatedDevelopment is slowVery expensive for commercial deployment

    Rails Training Programme

  • CGI / Perl & PHPSimple architecture so very fastWordPress is a PHP (XML-RPC) siteFacebook

    Very difficult to support multi-tier architectureSecurity is weakPoor clustering supportSQL centric codeTypically procedural in natureNot suited for complicated web applicationsVery good for simple websites with small dynamic content

    Rails Training Programme

  • PylonsPylons is the Python Web-frameworkFollows MVC patternRelatively very new.

    Based on Rails architecture

    Rails Training Programme

  • Ruby on RailsPure MVC frameworkModelViewControllerEvolved over the past 4 yearsAuthentication / Authorization very strongBeing slowly adopted for heavy web applications

    Rails Training Programme

  • Ruby On Rails contd..Support simple multi-tier architectureWebserverDatabaseApplication ServerGood clustering support with Nginx + thin, Apache + passengerSecurity at code level is weak i.e. no source code encryption support yet.

    Rails Training Programme

  • Rails in the Real WorldWho uses Rails today?Twitter, Facebook ApplicationsVastly used as automated QA in large companiesOne of the pioneers of Agile MethodologyJRuby Java Ruby interpreter

    Rails Training Programme

  • Part 2 Rails Architecture

    Rails Training Programme

  • TerminologiesMVCModel - View Controller Design PatternRESTRepresentational State TransferORMObject Relational MappingScaffoldBuilding code skeletons.MigrationsManaging the database tables and columns

    Rails Training Programme

  • Model View Controller

    Rails Training Programme

  • Model - OverviewMaintains state of an object / application.Manages the actual data involved.Validates object informationIn Rails:It is directly mapped to the database table via ORMIt is independent of Database nuances.Models supports relationshipsModels have bulk of rails codeActiveRecord

    Rails Training Programme

  • Controller OverviewControl the logical flow of the request.Interact with model and render the viewsIn Rails:Controllers manage authorization, sessions.Controllers decide how the request is processed.Render view according to business logic.ActionController

    Rails Training Programme

  • View OverviewViews are HTML renderersRender dynamic pages based on templates.XMLJsonHTMLJS (Ajax)In RailsShould contain very less or NO logicErb (Embedded Ruby ) is supported.ActionView

    Rails Training Programme

  • MVC in Rails

    Rails Training Programme

  • Routing in Railshttp://host:port/:controller/:action/:idThey determineWhich controllerWhich actionWhich objectCustom routes can also be setup.

    Rails Training Programme

  • A word about RESTfull RailsRoutes: map.resources :teams

    Rails Training Programme

  • Session BreakCoffee ?

    Rails Training Programme

  • Part 2.1 ActiveRecordDatabase ConnectorsMysql, pgsql, sqliteORMValidationsRelationships

    Rails Training Programme

  • Object Relational MappingDatabasecreate table `customers` (`id` int(11) auto_increment, `name` varchar(64),`age`int,primary key `id`)

    Modelclass Customer < ActiveRecord::Baseend

    Object accesscust = Customer.createputs #{cust.name}, #{cust.age}

    Rails Training Programme

  • Database rulesRules would mean guidelines. They help in writing lesser code and allow easier access from Rails codeAll table names should be plural:customers, products, categories, peopleAll tables should have `id` as primary key which is an auto_incrementAll tables should have _id` suffix as foreign keys. Example: `customer_id` in `products` table

    Rails Training Programme

  • Database rules contd..All datetime fields should have `_at` suffix. Example: `created_at`Avoid composite keysuse model validations insteadThey are new supported in Rails 2.1.2 onwardsModel name should be singular.Model Customer maps to `customers` tableModel Category maps to `categories` table (!!)Model Person maps to `people` table (!!)

    Rails Training Programme

  • Part 2.4 MigrationsMigrations are routines which help us manage the database.Versions are maintained in the database itself in a table called schema_migrations This controls relationships at model level and not database level. rake db:migrate

    Rails Training Programme

  • Example of Migrationclass CreateAddresses < ActiveRecord::Migrationdef self.up create_table :addresses do |t| t.string :street t.integer :zip, :default => 0 t.references :customert.timestamps endend

    def self.downdrop_table :addressesendendThis creates customer_id field in database.

    Relation between Customer and Address is determined by the models.

    i.e. class Customer has_one :address

    Rails Training Programme

  • RakeRuby build program similar to makeRakefiles (rakes version of Makefiles) are completely defined in standard Ruby syntax. No XML files to edit. No quirky Makefile syntax to worry about (tab or space issues!) rake T in rails environment show default tasksUser can add new tasks in lib/tasks/filename.rakeIt loads the rails environment development, production or test or custom.

    Rails Training Programme

  • Part 3 Hands-on workBuilding a Rails Application

    Rails Training Programme

  • Ruby on Rails InstallationInstall ruby on Windows / Linux.Latest stable version: Ruby 1.8.6 , 1.8.7Latest version: Ruby 1.9http://rubyonrails.org/downloadInstall rubygemsLink: http://rubyforge.org/frs/?group_id=126Latest stable version: 1.3.3gem install railsLatest stable version: 2.3.2Recommended: 2.1.2Install MySQL 5.xLink: http://dev.mysql.com/downloads/mysql/5.1.html#downloads

    Rails Training Programme

  • Setup the EnvironmentEnsure installation is good and versions are correct.ruby v>= 1.8.6gem v>= 1.3.2rails v>= 2.1.0mysql version >= 5.0.xEditor: SciteCreate the rails project cmd> rails -d mysql

    Rails Training Programme

  • Rails Project Layout..../app ......../controller ......../helpers ......../models ......../views ............/layouts ..../config ..../components..../db ..../doc ..../lib ..../log ..../public ..../script ..../test ..../tmp ..../vendor......../pluginsCore Application code:Controllers, Helpers, Models, Views

    Configuration for database, initializers,routesDatabase migrationsAdditional or custom libraries, rake tasks etc.The HTDOC for this web project. This contains JS, CSS, images etc.External plugins for this project.

    Rails Training Programme

  • Session BreakCoffee ?

    Rails Training Programme

  • ActiveRecord ValidationsvalidateGeneric validation method that can be used for custom validationvalidates_uniqueness_of :namevalidates_numericality_of :agevalidates_presence_of :addressvalidates_format_of :email, :with =>

    Rails Training Programme

  • ActiveRecord Callbacksbefore_createafter_createbefore_saveafter_savebefore_updateafter_updatebefore_destroyafter_destroybefore_validationafter_validation

    Ra