SlideShare a Scribd company logo
Ruby On Rails
       Basics

      Amit Solanki
 http://amitsolanki.com
Introduction



Web-application framework - includes everything needed to create
database-backed web applications according to the Model-View-
Control(MVC) pattern
Built on Ruby - Language of the year 2006
Extracted by David Heinemeier Hansson(DHH) from his work on
Basecamp, a project management tool by 37signals
Released as open source in July 2004 - more than 1400 contributors
Showcase
More at http://rubyonrails.org/applications
Framework - Why do we need it?

Consider following Python Code:
#!/usr/bin/env python


import MySQLdb


print "Content-Type: text/htmln"
print "<html><head><title>Books</title></head>"
print "<body>"
print "<h1>Books</h1>"
print "<ul>"


connection = MySQLdb.connect(user='mysql_user', passwd='mysql_pass', db='my_database')
cursor = connection.cursor()
cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10")


for row in cursor.fetchall():
  print "<li>%s</li>" % row[0]


print "</ul>"
print "</body></html>"


connection.close()
Framework - Why do we need it?
What happens when multiple parts of your application need to connect to the
database?
-     database-connecting code need to be duplicated in each individual CGI script.
      Instead, we could refactor it into a shared function
Should a developer really have to worry about printing the “Content-Type”
line and remembering to close the database connection?
-     this reduces programmer productivity and introduces opportunities for mistakes. These
      setup- and teardown-related tasks would best be handled by some common
      infrastructure

What happens when this code is reused in multiple environments, each with a
separate database and password?
-    some environment-specific configuration becomes essential

What happens when a Web designer who has no experience coding Python
wishes to redesign the page?
-    one wrong character could crash the entire application. Ideally, the logic of the page — the
      retrieval of book titles from the database — would be separate from the HTML display of
      the page, so that a designer could edit the latter without affecting the former.
Framework - Why do we need it?
The MVC Implementation:
 # models.py (the database tables)
 from django.db import models
 class Book(models.Model):
     name = models.CharField(max_length=50)
     pub_date = models.DateField()

 # views.py (the business logic)
 from django.shortcuts import render_to_response
 from models import Book
 def latest_books(request):
     book_list = Book.objects.order_by('-pub_date')[:10]
     return render_to_response('latest_books.html', {'book_list': book_list})

 # urls.py (the URL configuration)
 from django.conf.urls.defaults import *
 import views
 urlpatterns = patterns('',
     (r'^latest/$', views.latest_books),
 )

 # latest_books.html (the template)
 <html><head><title>Books</title></head>
 <body>
 <h1>Books</h1>
 <ul>
 {% for book in book_list %}
 <li>{{ book.name }}</li>
 {% endfor %}
 </ul>
 </body></html>
Framework - Why do we need it?

The models.py file contains a description of the database table, represented by
a Python class. This class is called a model. Using it, you can create, retrieve,
update and delete records in your database using simple Python code rather
than writing repetitive SQL statements
The views.py file contains the business logic for the page. The latest_books()
function is called a view
The urls.py file specifies which view is called for a given URL pattern. In this
case, the URL /latest/ will be handled by the latest_books() function. In other
words, if your domain is example.com, any visit to the URL http://
example.com/latest/ will call the latest_books() function
The latest_books.html file is an HTML template that describes the design of
the page. It uses a template language with basic logic statements — e.g., {%
for book in book_list %}
Running Rails on your machine

Install ruby - http://ruby-lang.org/
    Windows: One click installer
    Linux: Installer tools such as apt-get and yum
    Mac OS X: Macports
    Best practice is to install by compiling from source
Install rubygems - http://rubyforge.org
Install rails gem - http://rubyonrails.org/download
    gem install rails
    may require sudo access on unix/linux based OS
Editors: TextMate, VIM, Emacs, jEdit, SciTE
IDE: RadRails, RubyMine, 3rd Rail, NetBeans, Komodo
Features

Convention over Configuration
Don't Repeat Yourself (DRY)
Agile
    Individuals and interactions over processes and tools
    Working software over comprehensive documentation
    Customer collaboration over contract negotiation
    Responding to change over following a plan
Easy integration with features with AJAX and RESTful
Connects to most of the databases - just install DB driver
Latest stable release is 2.3 => 3.0 Coming soon
Rails is FUN
Model-View-Controller Architecture


        1      Controller


    4          3            2


        View            Model    Database   1
Framework Structure
ActiveRecord
    an object relationship mapping (ORM) system for database access
ActiveResource
    provides web services
    before 2.0 => ActionWeb
ActionPack
    ActionController
    ActionView
ActiveSupport
    Utility classes and standard library extensions from Rails
ActionMailer
Plugins to extend capability
Directory Structure
     .
     |-- README                 Installation and usage information
     |-- Rakefile               Build script
     |-- app                    Model, view and controller files go here
     | |-- controllers
     | |-- helpers
     | |-- models
     | |-- views
     |-- config                 Configuration and database connection parameters
     | |-- boot.rb
     | |-- database.yml
     | |-- environment.rb
     | |-- environments
     | |-- initializers
     | `-- routes.rb
     |-- db                     Schema and migration information
     | |-- migrate
     |-- doc                    Autogenerated documentation
     |-- lib                    Shared code
     |-- log                    Log files produced by your application
     |-- public                 Web-acccessible directory. Your application runs from here
     |-- script                 Utility scripts
     |-- test                   Unit, functional, and integration tests, fixtures, and mocks
     |-- tmp                    Runtime temporary files
     |-- vendor Imported code
       `-- plugins
Demo
config/

Every environment has a database configuration in database.yml
Global configuration file - environment.rb
Individual configuration file under config/environments
    production.rb
    development.rb
    test.rb
Easy to add custom environments
    e.g. for a staging server create staging.rb
Start server by passing RAILS_ENV
    ruby script/server RAILS_ENV=‘production’
    mongrel_rails start
script/


 about
 breakpointer
 console
 dbconsole
 destroy
 generate
 plugin
 runner
 server
Rake


db:migrate
doc:app
doc:rails
log:clear
rails:freeze:gems
rails:freeze:edge
rails:update
test
stats
Some Quotes
“Rails is the most well thought-out web development framework I’ve ever used.
And that’s in a decade of doing web applications for a living. I’ve built my
own frameworks, helped develop the Servlet API, and have created more than a
few web servers from scratch. Nobody has done it like this before.”
-James Duncan Davidson, Creator of Tomcat and Ant
“Ruby on Rails is a breakthrough in lowering the barriers of entry to
programming. Powerful web applications that formerly might have taken
weeks or months to develop can be produced in a matter of days.”
-Tim O'Reilly, Founder of O'Reilly Media
“It is impossible not to notice Ruby on Rails. It has had a huge effect both in
and outside the Ruby community... Rails has become a standard to which
even well-established tools are comparing themselves to.”
-Martin Fowler, Author of Refactoring, PoEAA, XP Explained
“What sets this framework apart from all of the others is the preference for
convention over configuration making applications easier to develop and
understand.”
-Sam Ruby, ASF board of directors
Some Quotes (contd.)

“Before Ruby on Rails, web programming required a lot of verbiage, steps and
time. Now, web designers and software engineers can develop a website much
faster and more simply, enabling them to be more productive and effective in
their work.”
-Bruce Perens, Open Source Luminary
“After researching the market, Ruby on Rails stood out as the best choice. We
have been very happy with that decision. We will continue building on Rails
and consider it a key business advantage.”
-Evan Williams, Creator of Blogger, ODEO, and Twitter
“Ruby on Rails is astounding. Using it is like watching a kung-fu movie,
where a dozen bad-ass frameworks prepare to beat up the little newcomer only
to be handed their asses in a variety of imaginative ways.”
-Nathan Torkington, O'Reilly Program Chair for OSCON
“Rails is the killer app for Ruby.”
Yukihiro Matsumoto, Creator of Ruby
Resources

guides.rubyonrails.org
weblog.rubyonrails.com
loudthinking.com
rubyinside.com
therailsway.com
weblog.jamisbuck.com
errtheblog.com
nubyonrails.com
planetrubyonrails.org
blog.caboo.se
Thanks
Amit Solanki
amit@vinsol.com

More Related Content

What's hot

Styled Components & React.js
Styled Components & React.jsStyled Components & React.js
Styled Components & React.js
Grayson Hicks
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
Anand Kumar Rajana
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
Jason Terpko
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
NexThoughts Technologies
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
mithunsasidharan
 
Jsf presentation
Jsf presentationJsf presentation
Jsf presentation
Ashish Gupta
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Front-End Frameworks: a quick overview
Front-End Frameworks: a quick overviewFront-End Frameworks: a quick overview
Front-End Frameworks: a quick overview
Diacode
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
Purbarun Chakrabarti
 
Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실
Taewan Kim
 
Web api
Web apiWeb api
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
Chandrasekar G
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
PradeepDyavannanavar
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
Apaichon Punopas
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
Bui Kiet
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Pei-Tang Huang
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
L&T Technology Services Limited
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
Naphachara Rattanawilai
 

What's hot (20)

Styled Components & React.js
Styled Components & React.jsStyled Components & React.js
Styled Components & React.js
 
jQuery Ajax
jQuery AjaxjQuery Ajax
jQuery Ajax
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
MongoDB - Aggregation Pipeline
MongoDB - Aggregation PipelineMongoDB - Aggregation Pipeline
MongoDB - Aggregation Pipeline
 
An Introduction to Redux
An Introduction to ReduxAn Introduction to Redux
An Introduction to Redux
 
Introduction to Ruby on Rails
Introduction to Ruby on RailsIntroduction to Ruby on Rails
Introduction to Ruby on Rails
 
Jsf presentation
Jsf presentationJsf presentation
Jsf presentation
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Front-End Frameworks: a quick overview
Front-End Frameworks: a quick overviewFront-End Frameworks: a quick overview
Front-End Frameworks: a quick overview
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실Cloud Native Java GraalVM 이상과 현실
Cloud Native Java GraalVM 이상과 현실
 
Web api
Web apiWeb api
Web api
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 

Similar to Ruby On Rails Basics

Aspose pdf
Aspose pdfAspose pdf
Aspose pdf
Jim Jones
 
Ruby Rails Web Development
Ruby Rails Web DevelopmentRuby Rails Web Development
Ruby Rails Web Development
Sonia Simi
 
Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arp
Gary Pedretti
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On Rails
David Keener
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
Siddhesh Bhobe
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
Ido Flatow
 
Rails
RailsRails
RailsSHC
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp Atlanta
Jason Noble
 
Ruby On Rails - Rochester K Linux User Group
Ruby On Rails - Rochester K Linux User GroupRuby On Rails - Rochester K Linux User Group
Ruby On Rails - Rochester K Linux User Group
Jose de Leon
 
Rails interview questions
Rails interview questionsRails interview questions
Rails interview questions
Durgesh Tripathi
 
Dev streams2
Dev streams2Dev streams2
Dev streams2
David Mc Donagh
 
Intro to Sails.js
Intro to Sails.jsIntro to Sails.js
Intro to Sails.js
DevOpsDays Austin 2014
 
Ruby on Rails workshop for beginner
Ruby on Rails workshop for beginnerRuby on Rails workshop for beginner
Ruby on Rails workshop for beginner
Umair Amjad
 
Getting Started with MariaDB with Docker
Getting Started with MariaDB with DockerGetting Started with MariaDB with Docker
Getting Started with MariaDB with Docker
MariaDB plc
 
Building Application with Ruby On Rails Framework
Building Application with Ruby On Rails FrameworkBuilding Application with Ruby On Rails Framework
Building Application with Ruby On Rails Framework
Edureka!
 
Intro lift
Intro liftIntro lift
Intro lift
Knoldus Inc.
 
Ruby on Rails
Ruby on RailsRuby on Rails

Similar to Ruby On Rails Basics (20)

Aspose pdf
Aspose pdfAspose pdf
Aspose pdf
 
Ruby Rails Web Development
Ruby Rails Web DevelopmentRuby Rails Web Development
Ruby Rails Web Development
 
Onion Architecture with S#arp
Onion Architecture with S#arpOnion Architecture with S#arp
Onion Architecture with S#arp
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On Rails
 
Ruby On Rails Siddhesh
Ruby On Rails SiddheshRuby On Rails Siddhesh
Ruby On Rails Siddhesh
 
Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6Learning ASP.NET 5 and MVC 6
Learning ASP.NET 5 and MVC 6
 
Rails
RailsRails
Rails
 
Ruby on rails for beginers
Ruby on rails for beginersRuby on rails for beginers
Ruby on rails for beginers
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp Atlanta
 
RoR guide_p1
RoR guide_p1RoR guide_p1
RoR guide_p1
 
Ruby on rails RAD
Ruby on rails RADRuby on rails RAD
Ruby on rails RAD
 
Ruby On Rails - Rochester K Linux User Group
Ruby On Rails - Rochester K Linux User GroupRuby On Rails - Rochester K Linux User Group
Ruby On Rails - Rochester K Linux User Group
 
Rails interview questions
Rails interview questionsRails interview questions
Rails interview questions
 
Dev streams2
Dev streams2Dev streams2
Dev streams2
 
Intro to Sails.js
Intro to Sails.jsIntro to Sails.js
Intro to Sails.js
 
Ruby on Rails workshop for beginner
Ruby on Rails workshop for beginnerRuby on Rails workshop for beginner
Ruby on Rails workshop for beginner
 
Getting Started with MariaDB with Docker
Getting Started with MariaDB with DockerGetting Started with MariaDB with Docker
Getting Started with MariaDB with Docker
 
Building Application with Ruby On Rails Framework
Building Application with Ruby On Rails FrameworkBuilding Application with Ruby On Rails Framework
Building Application with Ruby On Rails Framework
 
Intro lift
Intro liftIntro lift
Intro lift
 
Ruby on Rails
Ruby on RailsRuby on Rails
Ruby on Rails
 

Recently uploaded

Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
Atul Kumar Singh
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
GeoBlogs
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
Celine George
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
Steve Thomason
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
Nguyen Thanh Tu Collection
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
siemaillard
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
bennyroshan06
 

Recently uploaded (20)

Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
Language Across the Curriculm LAC B.Ed.
Language Across the  Curriculm LAC B.Ed.Language Across the  Curriculm LAC B.Ed.
Language Across the Curriculm LAC B.Ed.
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Fish and Chips - have they had their chips
Fish and Chips - have they had their chipsFish and Chips - have they had their chips
Fish and Chips - have they had their chips
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
How to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS ModuleHow to Split Bills in the Odoo 17 POS Module
How to Split Bills in the Odoo 17 POS Module
 
The Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve ThomasonThe Art Pastor's Guide to Sabbath | Steve Thomason
The Art Pastor's Guide to Sabbath | Steve Thomason
 
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
GIÁO ÁN DẠY THÊM (KẾ HOẠCH BÀI BUỔI 2) - TIẾNG ANH 8 GLOBAL SUCCESS (2 CỘT) N...
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptxMARUTI SUZUKI- A Successful Joint Venture in India.pptx
MARUTI SUZUKI- A Successful Joint Venture in India.pptx
 

Ruby On Rails Basics

  • 1. Ruby On Rails Basics Amit Solanki http://amitsolanki.com
  • 2. Introduction Web-application framework - includes everything needed to create database-backed web applications according to the Model-View- Control(MVC) pattern Built on Ruby - Language of the year 2006 Extracted by David Heinemeier Hansson(DHH) from his work on Basecamp, a project management tool by 37signals Released as open source in July 2004 - more than 1400 contributors
  • 4. Framework - Why do we need it? Consider following Python Code: #!/usr/bin/env python import MySQLdb print "Content-Type: text/htmln" print "<html><head><title>Books</title></head>" print "<body>" print "<h1>Books</h1>" print "<ul>" connection = MySQLdb.connect(user='mysql_user', passwd='mysql_pass', db='my_database') cursor = connection.cursor() cursor.execute("SELECT name FROM books ORDER BY pub_date DESC LIMIT 10") for row in cursor.fetchall(): print "<li>%s</li>" % row[0] print "</ul>" print "</body></html>" connection.close()
  • 5. Framework - Why do we need it? What happens when multiple parts of your application need to connect to the database? - database-connecting code need to be duplicated in each individual CGI script. Instead, we could refactor it into a shared function Should a developer really have to worry about printing the “Content-Type” line and remembering to close the database connection? - this reduces programmer productivity and introduces opportunities for mistakes. These setup- and teardown-related tasks would best be handled by some common infrastructure What happens when this code is reused in multiple environments, each with a separate database and password? - some environment-specific configuration becomes essential What happens when a Web designer who has no experience coding Python wishes to redesign the page? - one wrong character could crash the entire application. Ideally, the logic of the page — the retrieval of book titles from the database — would be separate from the HTML display of the page, so that a designer could edit the latter without affecting the former.
  • 6. Framework - Why do we need it? The MVC Implementation: # models.py (the database tables) from django.db import models class Book(models.Model): name = models.CharField(max_length=50) pub_date = models.DateField() # views.py (the business logic) from django.shortcuts import render_to_response from models import Book def latest_books(request): book_list = Book.objects.order_by('-pub_date')[:10] return render_to_response('latest_books.html', {'book_list': book_list}) # urls.py (the URL configuration) from django.conf.urls.defaults import * import views urlpatterns = patterns('', (r'^latest/$', views.latest_books), ) # latest_books.html (the template) <html><head><title>Books</title></head> <body> <h1>Books</h1> <ul> {% for book in book_list %} <li>{{ book.name }}</li> {% endfor %} </ul> </body></html>
  • 7. Framework - Why do we need it? The models.py file contains a description of the database table, represented by a Python class. This class is called a model. Using it, you can create, retrieve, update and delete records in your database using simple Python code rather than writing repetitive SQL statements The views.py file contains the business logic for the page. The latest_books() function is called a view The urls.py file specifies which view is called for a given URL pattern. In this case, the URL /latest/ will be handled by the latest_books() function. In other words, if your domain is example.com, any visit to the URL http:// example.com/latest/ will call the latest_books() function The latest_books.html file is an HTML template that describes the design of the page. It uses a template language with basic logic statements — e.g., {% for book in book_list %}
  • 8. Running Rails on your machine Install ruby - http://ruby-lang.org/ Windows: One click installer Linux: Installer tools such as apt-get and yum Mac OS X: Macports Best practice is to install by compiling from source Install rubygems - http://rubyforge.org Install rails gem - http://rubyonrails.org/download gem install rails may require sudo access on unix/linux based OS Editors: TextMate, VIM, Emacs, jEdit, SciTE IDE: RadRails, RubyMine, 3rd Rail, NetBeans, Komodo
  • 9. Features Convention over Configuration Don't Repeat Yourself (DRY) Agile Individuals and interactions over processes and tools Working software over comprehensive documentation Customer collaboration over contract negotiation Responding to change over following a plan Easy integration with features with AJAX and RESTful Connects to most of the databases - just install DB driver Latest stable release is 2.3 => 3.0 Coming soon Rails is FUN
  • 10. Model-View-Controller Architecture 1 Controller 4 3 2 View Model Database 1
  • 11. Framework Structure ActiveRecord an object relationship mapping (ORM) system for database access ActiveResource provides web services before 2.0 => ActionWeb ActionPack ActionController ActionView ActiveSupport Utility classes and standard library extensions from Rails ActionMailer Plugins to extend capability
  • 12. Directory Structure . |-- README Installation and usage information |-- Rakefile Build script |-- app Model, view and controller files go here | |-- controllers | |-- helpers | |-- models | |-- views |-- config Configuration and database connection parameters | |-- boot.rb | |-- database.yml | |-- environment.rb | |-- environments | |-- initializers | `-- routes.rb |-- db Schema and migration information | |-- migrate |-- doc Autogenerated documentation |-- lib Shared code |-- log Log files produced by your application |-- public Web-acccessible directory. Your application runs from here |-- script Utility scripts |-- test Unit, functional, and integration tests, fixtures, and mocks |-- tmp Runtime temporary files |-- vendor Imported code `-- plugins
  • 13. Demo
  • 14. config/ Every environment has a database configuration in database.yml Global configuration file - environment.rb Individual configuration file under config/environments production.rb development.rb test.rb Easy to add custom environments e.g. for a staging server create staging.rb Start server by passing RAILS_ENV ruby script/server RAILS_ENV=‘production’ mongrel_rails start
  • 15. script/ about breakpointer console dbconsole destroy generate plugin runner server
  • 17. Some Quotes “Rails is the most well thought-out web development framework I’ve ever used. And that’s in a decade of doing web applications for a living. I’ve built my own frameworks, helped develop the Servlet API, and have created more than a few web servers from scratch. Nobody has done it like this before.” -James Duncan Davidson, Creator of Tomcat and Ant “Ruby on Rails is a breakthrough in lowering the barriers of entry to programming. Powerful web applications that formerly might have taken weeks or months to develop can be produced in a matter of days.” -Tim O'Reilly, Founder of O'Reilly Media “It is impossible not to notice Ruby on Rails. It has had a huge effect both in and outside the Ruby community... Rails has become a standard to which even well-established tools are comparing themselves to.” -Martin Fowler, Author of Refactoring, PoEAA, XP Explained “What sets this framework apart from all of the others is the preference for convention over configuration making applications easier to develop and understand.” -Sam Ruby, ASF board of directors
  • 18. Some Quotes (contd.) “Before Ruby on Rails, web programming required a lot of verbiage, steps and time. Now, web designers and software engineers can develop a website much faster and more simply, enabling them to be more productive and effective in their work.” -Bruce Perens, Open Source Luminary “After researching the market, Ruby on Rails stood out as the best choice. We have been very happy with that decision. We will continue building on Rails and consider it a key business advantage.” -Evan Williams, Creator of Blogger, ODEO, and Twitter “Ruby on Rails is astounding. Using it is like watching a kung-fu movie, where a dozen bad-ass frameworks prepare to beat up the little newcomer only to be handed their asses in a variety of imaginative ways.” -Nathan Torkington, O'Reilly Program Chair for OSCON “Rails is the killer app for Ruby.” Yukihiro Matsumoto, Creator of Ruby