39
Ruby on Rails

Ruby on Rails. What's Ruby A programming language Developed by Yukihiro Matsumoto (aka Matz) in the 1990s A programming language Developed by

  • View
    226

  • Download
    2

Embed Size (px)

Citation preview

Ruby on RailsRuby on Rails

What's RubyWhat's Ruby

A programming languageDeveloped by Yukihiro Matsumoto (aka Matz) in the 1990s

A programming languageDeveloped by Yukihiro Matsumoto (aka Matz) in the 1990s

What's RailsWhat's Rails

Initially developed by David Heinemeier Hansson, out of his work on Basecamp, a project management system

It is a framework of scripts in ruby that provide for rapid development of web applications, esp those with a database back end

Rails can build the skeleton of an application, including the database tables, in just a few commands

Initially developed by David Heinemeier Hansson, out of his work on Basecamp, a project management system

It is a framework of scripts in ruby that provide for rapid development of web applications, esp those with a database back end

Rails can build the skeleton of an application, including the database tables, in just a few commands

RubyRuby

SyntaxSyntax

Ruby is largely and loosely based on perl (hence the name, according to lore)

Completely object oriented

Ruby is largely and loosely based on perl (hence the name, according to lore)

Completely object oriented

Some Important differences

Some Important differences

Unlike PHP, scope in variables is defined by the leading sigilthe $ sign denotes global scope, not a variable

an @ represents local scope within an object instance

@@ represents local scope within a class

A capitalized name is a constant

Unlike PHP, scope in variables is defined by the leading sigilthe $ sign denotes global scope, not a variable

an @ represents local scope within an object instance

@@ represents local scope within a class

A capitalized name is a constant

Historical DifferencesHistorical Differences

Javascript--born of the competition between two companies

PHP--created by a varied communityRuby--the vision of a single personRails--the vision of another single person

When you compare these, you can see how the starting point influences the process of development

Javascript--born of the competition between two companies

PHP--created by a varied communityRuby--the vision of a single personRails--the vision of another single person

When you compare these, you can see how the starting point influences the process of development

Playing on the Command Line

Playing on the Command Line

Ruby is an interpreter, just like php or bash:Avatar:~ hays$ rubyprint "howdy world!"^d

Or, use ruby -e "command":ruby -e 'puts "hello\n"'

Or, you can just use irb, which is easier:Avatar:~ hays$ irb>> print "howdy world!"howdy world!=> nil>>

Ruby is an interpreter, just like php or bash:Avatar:~ hays$ rubyprint "howdy world!"^d

Or, use ruby -e "command":ruby -e 'puts "hello\n"'

Or, you can just use irb, which is easier:Avatar:~ hays$ irb>> print "howdy world!"howdy world!=> nil>>

Object OrientedObject Oriented

TrulyNot a prototyping language like javascript

Nor a procedural language with OOP bolted on

TrulyNot a prototyping language like javascript

Nor a procedural language with OOP bolted on

ClassesClasses

A class is a kind of master object

Can contain constants and methods

Instances of object can be created from a class, inheriting the traits of the class

A class is a kind of master object

Can contain constants and methods

Instances of object can be created from a class, inheriting the traits of the class

A simple classA simple class

class Catend

(but this class doesn't do or mean anything)

class Catend

(but this class doesn't do or mean anything)

the class examples are derived from http://www.juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/

cat classcat class

I want four attributes for a cat; name, color, type, and attribute

I want four attributes for a cat; name, color, type, and attribute

class Cat # must be capitalized attr_accessor :name, :type, :color, :attribute

def initialize(name, type, color, attribute) @name = name @type = type @color = color @attribute = attribute end

creating a new catcreating a new cat

Now, I can create an instance of the cat class:gc = Cat.new("GC", "short hair", "black", "gimpy")lc = Cat.new("LC", "short hair", "black", "little")

Now, I can create an instance of the cat class:gc = Cat.new("GC", "short hair", "black", "gimpy")lc = Cat.new("LC", "short hair", "black", "little")

add a methodadd a method

I'd like to be able to describe my cats easily

So I add a method to the cat class: def describe @name + " is a " + @color + " " + @type + " who is " + @attribute + ".\n" end

I'd like to be able to describe my cats easily

So I add a method to the cat class: def describe @name + " is a " + @color + " " + @type + " who is " + @attribute + ".\n" end

eliminating con-cat-ination

eliminating con-cat-ination

The concatenation is a bit awkward

Like php, ruby has a structure for calling variables within a string:"#{@name} is a #{@color} #{@type} who is #{@attribute}.\n"

The concatenation is a bit awkward

Like php, ruby has a structure for calling variables within a string:"#{@name} is a #{@color} #{@type} who is #{@attribute}.\n"

calling the methodcalling the method

If I call a cat with the describe method attached, I can get the description of that cat: my_string= gc.describe puts my_string

or: puts gc.describe

If I call a cat with the describe method attached, I can get the description of that cat: my_string= gc.describe puts my_string

or: puts gc.describe

finding cats by namefinding cats by name

A second method, find_by_name:def self.find_by_name(name)

found = nil ObjectSpace.each_object(Cat) { |o|

found = o if o.name == name } found end

A second method, find_by_name:def self.find_by_name(name)

found = nil ObjectSpace.each_object(Cat) { |o|

found = o if o.name == name } found end

Access ControlAccess Control

Methods in a class are public by default

Private methods are known only to the individual object

Protected methods can only be called by members of the class in which is was defined

Methods in a class are public by default

Private methods are known only to the individual object

Protected methods can only be called by members of the class in which is was defined

VariablesVariables

In ruby, vars are references to objects, not objects themselves

So:a = "my value"b = a

a[0] = "n" will change both a and b--but if you reassign a, eg a="new value", a is linked to a new object (this might bite you, but it's not likely)

In ruby, vars are references to objects, not objects themselves

So:a = "my value"b = a

a[0] = "n" will change both a and b--but if you reassign a, eg a="new value", a is linked to a new object (this might bite you, but it's not likely)

ArraysArrays

Create an array by assignment:my_array = [ "one", "two", 3, 4 ]

Referencing the array:puts "my_array[0] is: #{my_array[0]}\n"

The brackets are methods of the array class…

Create an array by assignment:my_array = [ "one", "two", 3, 4 ]

Referencing the array:puts "my_array[0] is: #{my_array[0]}\n"

The brackets are methods of the array class…

HashesHashes

What in php is called an associative array is called a hash in ruby

Creating a hash by assignment:my_hash = { 'tree' => 'pine', 'bird' => 'mocking'}puts "\n"puts "my_hash['tree'] is: #{my_hash['tree']}\n"puts "my_hash['bird'] is: #{my_hash['bird']}\n"

Notice that the syntax is different

What in php is called an associative array is called a hash in ruby

Creating a hash by assignment:my_hash = { 'tree' => 'pine', 'bird' => 'mocking'}puts "\n"puts "my_hash['tree'] is: #{my_hash['tree']}\n"puts "my_hash['bird'] is: #{my_hash['bird']}\n"

Notice that the syntax is different

walking a hash or array

walking a hash or array

use the each method:use the each method:

a = 1 my_hash.each do |key, value| puts "#{a} #{key} is: #{value}" a = a +1 end

conditionalconditional

much like php and javascript, but simpler syntax:

much like php and javascript, but simpler syntax:

a = 1 my_hash.each do |key, value| if key == "tree" puts "#{a} #{key} is: #{value}" end a = a +1 end

In summaryIn summary

Ruby's syntax is prettyRuby is all about structureClasses are easy to work with, if you're new, start with simple examples

Ruby's syntax is prettyRuby is all about structureClasses are easy to work with, if you're new, start with simple examples

RailsRails

Model View Controller (MVC)

Model View Controller (MVC)

Layering againMVC allows a project team to work on different aspects of the application without stepping on each other's toes quite so often

Note that neither PHP nor Javascript encourage this, but it can be done in PHP (not so much in Javascript)

Rails enforces MVC

Layering againMVC allows a project team to work on different aspects of the application without stepping on each other's toes quite so often

Note that neither PHP nor Javascript encourage this, but it can be done in PHP (not so much in Javascript)

Rails enforces MVC

ModelModel

Contains the data of the applicationTransientStored (eg Database)

Enforces "business" rules of the applicationAttributesWork flow

Contains the data of the applicationTransientStored (eg Database)

Enforces "business" rules of the applicationAttributesWork flow

ViewsViews

Provides the user interfaceDynamic content rendered through templates

Three major typesRuby code in erb (embedded ruby) templates

xml.builder templatesrjs templates (for javascript, and thus ajax)

Provides the user interfaceDynamic content rendered through templates

Three major typesRuby code in erb (embedded ruby) templates

xml.builder templatesrjs templates (for javascript, and thus ajax)

ControllersControllers

Perform the bulk of the heavy lifting

Handles web requestsMaintains session statePerforms cachingManages helper modules

Perform the bulk of the heavy lifting

Handles web requestsMaintains session statePerforms cachingManages helper modules

Convention over Configuration

Convention over Configuration

Notion that coding is reduced if we adopt a standard way of doing things

Eg., if we have a class "Pet" in our model that defines the characteristic of domestic animal, in rails, the database table created for us will be named "pets"

Other chunks of code look for each other by their common names

Notion that coding is reduced if we adopt a standard way of doing things

Eg., if we have a class "Pet" in our model that defines the characteristic of domestic animal, in rails, the database table created for us will be named "pets"

Other chunks of code look for each other by their common names

Action PackAction Pack

Since views and controllers interact so tightly, in rails they are combined in Action Pack

Action pack breaks a web request into view components and controller compoents

So an action usually involves a controller request to create, read, update, or delete (CRUD) some part of the model, followed by a view request to render a page

Since views and controllers interact so tightly, in rails they are combined in Action Pack

Action pack breaks a web request into view components and controller compoents

So an action usually involves a controller request to create, read, update, or delete (CRUD) some part of the model, followed by a view request to render a page

Processing URLsProcessing URLs

The basic url used to access a controller is of the form: http://server/controller/action

The controller will be one you generate, and the action will be one you've defined in your controller

So if you have a controller named "filer" and that controller has an action named "upload", the url will be something like http://127.0.0.1/filer/upload

The basic url used to access a controller is of the form: http://server/controller/action

The controller will be one you generate, and the action will be one you've defined in your controller

So if you have a controller named "filer" and that controller has an action named "upload", the url will be something like http://127.0.0.1/filer/upload

The ViewThe View

The controller will have a folder in app/view named after it, and in that will be the view templates associated with the action methods

These templates are usually html with some inserted ruby code

While code can be executed in these templates, keep that simple--any data controls should be made in the controller's files

The controller will have a folder in app/view named after it, and in that will be the view templates associated with the action methods

These templates are usually html with some inserted ruby code

While code can be executed in these templates, keep that simple--any data controls should be made in the controller's files

Creating a basic siteCreating a basic site

Three commandsrails democd demoruby script/generate controller Bark

This creates the framework

Three commandsrails democd demoruby script/generate controller Bark

This creates the framework

Making it say something

Making it say something

A def in the app/controller/bark_controller.rb file:def helloend

And some html in the app/views/bark folder, hello.html.erb:

A def in the app/controller/bark_controller.rb file:def helloend

And some html in the app/views/bark folder, hello.html.erb:

<html><head></head><body><h3>Howdy</h3></body></html>

Directory StructureDirectory Structure

app: most of your code lives hereconfig: information environment and database linkdatabase.ymldevelopment, test and production versions

doc, log, tmplib: your code, just a place to stick things that don't have a good home elsewhere

app: most of your code lives hereconfig: information environment and database linkdatabase.ymldevelopment, test and production versions

doc, log, tmplib: your code, just a place to stick things that don't have a good home elsewhere

Directory StructureDirectory Structure

public: images, javascripts, stylesheets go here

script: script that rails uses, most of these are short and reference files in the lib dir for rails

vendor: 3rd party code

public: images, javascripts, stylesheets go here

script: script that rails uses, most of these are short and reference files in the lib dir for rails

vendor: 3rd party code

Generating a database site

Generating a database site

MagicMagic

rails tempcd temprake db:create:allruby script/generate scaffold Person lname:string fname:string email:stringrake db:migrateruby script/server

SourcesSources

http://github.com/rails/rails/tree/master/actionpack

http://en.wikipedia.org/wiki/Ruby_on_Railshttp://www.whytheluckystiff.net/ruby/pickaxe/

http://www.pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition

http://www.juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/

http://github.com/rails/rails/tree/master/actionpack

http://en.wikipedia.org/wiki/Ruby_on_Railshttp://www.whytheluckystiff.net/ruby/pickaxe/

http://www.pragprog.com/titles/rails3/agile-web-development-with-rails-third-edition

http://www.juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/