ruby on rails tutorial

36
1 Ruby on Rails Tutorial By Yundong SUN

Upload: sunniboy

Post on 13-May-2015

4.194 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Ruby On Rails Tutorial

1

Ruby on Rails Tutorial

By Yundong SUN

Page 2: Ruby On Rails Tutorial

2

Ruby on Rails

Ruby on Rails is a web application framework – written in Ruby, a dynamically typed programming

language. – The amazing productivity claims of Rails – Web2.0

In this presentation:– Get an introduction to Ruby on Rails– Find out what’s behind the hype– See it in action by building a fully functional application in

minutes

Page 3: Ruby On Rails Tutorial

3

Ruby introduction– Ruby is a pure object-oriented programming language

with a super clean syntax that makes programming elegant and fun. • In Ruby, everything is an object

– Ruby is an interpreted scripting language, just like Perl, Python and PHP.

– Ruby successfully combines Smalltalk's conceptual elegance, Python's ease of use and learning and Perl's pragmatism.

– Ruby originated in Japan in 1993 by Yukihiro “matz” – Ruby is a metaprogramming language. Metaprogramming

is a means of writing software programs that write or manipulate other programs thereby making coding faster and more reliable.

What is Ruby?

Page 4: Ruby On Rails Tutorial

4

Must have tool #1: irb

Interactive ruby console:– Experiment on the fly– Tab complete object methods– …

# ~/.irbrc

require 'irb/completion'

use_readline=true

auto_indent_mode=true

Page 5: Ruby On Rails Tutorial

5

Must have tool #2: ri

Console-based Ruby doc tool

Page 6: Ruby On Rails Tutorial

6

Ruby in a nutshell – irb sessions follow

Like all interpreted scripting languages, you can put code into a file, chmod +x, then just execute it.

But, we’ll mostly use irb sessions in this presentation…

Page 7: Ruby On Rails Tutorial

7

Ruby in a nutshell – objects are everywhere

Some languages have built-in types that aren’t objects. Not so with Ruby. Everything’s an object:

Page 8: Ruby On Rails Tutorial

8

Ruby in a nutshell – objects have methods

Bang on the tab key in irb to see the methods that are available for each object.

Page 9: Ruby On Rails Tutorial

9

Ruby in a nutshell – Variables

Local variables - start with lower case:– foo– bar

Global variables - start with dollar sign:– $foo– $bar

Constants and Classes – start with capital letter:– CONSTANT– Class

Instance variables – start with at sign:– @foo– @bar

Class variables – start with double at sign:– @@foo– @@bar

Page 10: Ruby On Rails Tutorial

10

Ruby in a nutshell – Arrays

Page 11: Ruby On Rails Tutorial

11

Ruby in a nutshell – Hashes

Page 12: Ruby On Rails Tutorial

12

Ruby in a nutshell – Symbols

Starts with a ‘:’ Only one copy of a symbol kept in memory

Page 13: Ruby On Rails Tutorial

13

Ruby in a nutshell – Blocks & Iterators

Page 14: Ruby On Rails Tutorial

14

Ruby in a nutshell – It’s easy to build classes

Page 15: Ruby On Rails Tutorial

15

Ruby in a nutshell – It’s fun to play with classes (like the one we just made)

Page 16: Ruby On Rails Tutorial

16

Ruby in a nutshell – Classes are open

Example shown here uses our Hacker class, but what happens when the whole language is open?

Page 17: Ruby On Rails Tutorial

17

Rails in a nutshell

Page 18: Ruby On Rails Tutorial

18

Rails Tutorial

Create the Rails Application– Execute the script that creates a new Web application

project

>Rails projectname– This command executes an already provided Rails script

that creates the entire Web application directory structure and necessary configuration files.

Page 19: Ruby On Rails Tutorial

19

Hello World on Rails!

Need a controller and a view

>ruby script/generate controller Hello Edit app/controllers/hello_controller.rb Add an index method to your controller class

class HelloController < ApplicationController

def index

render :text => "<h1>Hello Rails World!</h1>"

end

end– Renders the content that will be returned to the browser

as the response body. Start the WEBrick server

>ruby script/server

http://localhost:3000

Page 20: Ruby On Rails Tutorial

20

Hello Rails!

Add another method to the controller

def hello

end

Add a template app/views/greeting>hello.rhtml

<html>

<head>

<title>Hello Rails World!</title>

</head>

<body>

<h1>Hello from the Rails View!</h1>

</body>

</html>

Page 21: Ruby On Rails Tutorial

21

Hello Rails!

ERb - Embedded Ruby. Embedding the Ruby programming language into HTML document. An erb file ends with .rhtml file extension.– Similar to ASP, JSP and PHP, requires an interpreter to

execute and replace it with designated HTML code and content.

Making it Dynamic

<p>Date/Time: <%= Time.now %></p> Making it Better by using an instance variable to the

controller

@time = Time.now.to_s– Reference it in .rhtml <%= @time %>

Linking Pages using the helper method link_to()

<p>Time to say <%= link_to "Goodbye!", :action => "goodbye" %>

Page 22: Ruby On Rails Tutorial

22

App> contains the core of the application• /models> Contains the models, which encapsulate application

business logic• /views/layouts> Contains master templates for each controller• /views/controllername> Contains templates for controller actions• /helpers> Contains helpers, which you can write to provide more

functionality to templates. Config> contains application configuration, plus per-

environment configurability - contains the database.yml file which provides details of the database to be used with the application

Db> contains a snapshot of the database schema and migrations

Log> application specific logs, contains a log for each environment

Public> contains all static files, such as images, javascripts, and style sheets

Script> contains Rails utility commands Test> contains test fixtures and code Vendor> contains add-in modules.

Rails Application Directory Structure

Page 23: Ruby On Rails Tutorial

23

Rails Strengths – It’s all about Productivity

Metaprogramming techniques use programs to write programs. – Metaprogramming replaces these two primitive

techniques and eliminates their disadvantages. – Ruby is one of the best languages for metaprogramming,

and Rails uses this capability well. Scaffolding

– You often create temporary code in the early stages of development to help get an application up quickly and see how major components work together. Rails automatically creates much of the scaffolding you'll need.

Page 24: Ruby On Rails Tutorial

24

Rails Strengths – Write Code not Configuration

Convention over configuration – Most Web development frameworks for .NET or Java force you to

write pages of configuration code. If you follow suggested naming conventions, Rails doesn't need much configuration. Naming your data model class with the same name as the corresponding database table• ‘id’ as the primary key name

Rails introduces the Active Record framework, which saves objects to the database. – Based on a design pattern cataloged by Martin Fowler, the Rails

version of Active Record discovers the columns in a database schema and automatically attaches them to your domain objects using metaprogramming.

– This approach to wrapping database tables is simple, elegant, and powerful.

Page 25: Ruby On Rails Tutorial

25

Rails Strengths – Full-Stack Web Framework

Rails implements the model-view-controller (MVC) architecture. The MVC design pattern separates the component parts of an application

– Model encapsulates data that the application manipulates, plus domain-specific logic

– View is a rendering of the model into the user interface

– Controller responds to events from the interface and causes actions to be performed on the model.

– MVC pattern allows rapid change and evolution of the user interface and controller separate from the data model

Page 26: Ruby On Rails Tutorial

26

Rails Strengths – Full-Stack Web Framework

Controller– http://www.example.com/product/show/1

– http://www.example.com/category/edit/1

– http://www.example.com/shopping/buy/1

app/controllers/product_controller.rb

class ProductController < ActiveController :: Base def show @product = Product.find(params[:id]) endend

Page 27: Ruby On Rails Tutorial

27

Rails Strengths – Full-Stack Web Framework

Model

/app/models/product.rb

class Product < ActiveRecord :: BaseEnd

Database:table products( id int, name string, price int)

Page 28: Ruby On Rails Tutorial

28

Rails Strengths – Full-Stack Web Framework

View

/app/views/products/

Show.rhtml…..<h2><%=name%></h2><b><%=price%></b>

Page 29: Ruby On Rails Tutorial

29

Active Record

Enhancing the Model– The model is where all the data-related rules are stored– Including data validation and relational integrity.– This means you can define a rule once and Rails will

automatically apply them wherever the data is accessed. Validations - Creating Data Validation Rules in the Model

validates_presence_of :name

validates_uniqueness_of :name

validates_length_of :name :maximum =>10

Add another Model Migrations

– Rake migrate

Page 30: Ruby On Rails Tutorial

30

ActiveRecord Relationships

Model Relations

– Has_one => One to One relationship

– Belongs_to => Many to One relationship (Many)

– Has_many => Many to One relationship (One)

– Has_and_belongs_to_many =>Many to Many relationships

Page 31: Ruby On Rails Tutorial

31

User Interface with Style

Layouts

/standard.rhtml

Add layout "layouts/standard" to controller

Partials

/_header.rhtml

/_footer.rhtml

Stylesheets– Publis/stylesheets/*.css

• NOTE: The old notation for rendering the view from a layout was to expose the magic @content_for_layout instance variable. The preferred notation now is to use yield

Page 32: Ruby On Rails Tutorial

32

AJAX and Rails

Add javascript include to standard.rhtml

<%= javascript_include_tag :defaults %>

Add to Event Controller

auto_complete_for :event, :location

Form Helper

<%= text_field_with_auto_complete :event, :location%>

Page 33: Ruby On Rails Tutorial

33

Console

debian:/home/trikr# ./script/consoleLoading development environment.

>> company = Company.find_by_name("test")=> #<Company:0xb6ea6b20 @attributes={"name"=>"test", "url"=>"test2", "id"=>"22","introduction"=>nil, "image"=>nil, "address"=>nil, "plan_id"=>"3", "created_at"=>"2006-08-22 23:21:00"}>>> company.projects.size=> 1>> company.users.size=> 1>> company.users.first=> #<User:0xb724f664 @attributes={"removed"=>nil, "login_at"=>nil, "role"=>"Administrator", "username"=>"asf", "tel"=>nil, "sn"=>nil, "id"=>"72", "work_start_time"=>nil, "report_to"=>nil, "company_id"=>"22","first_name"=>"asf", "work_end_time"=>nil, "general_info"=>"", "password"=>"asf", "last_name"=>"asf", "email"=>"asf", "created_at"=>"

Page 34: Ruby On Rails Tutorial

34

Rails Strengths

Three environments: development, testing, and production Database Support: Oracle, DB2, SQL Server, MySQL, PostgreSQL,

SQLite Action Mailer Action Web Service Prototype for AJAX

Page 35: Ruby On Rails Tutorial

35

Using logging

Page 36: Ruby On Rails Tutorial

36

Demo: Create a blog in 15mins