+ All Categories
Home > Documents > Web Architecture : Week4 - Handouts

Web Architecture : Week4 - Handouts

Date post: 18-May-2017
Category:
Upload: ahm4me
View: 217 times
Download: 3 times
Share this document with a friend
40
Web Application Architectures Module 4: The Ruby Programming Language Lecture 1: Background c 2011-13 G.L. Heileman Module 4, Lecture 1 1/9
Transcript
Page 1: Web Architecture : Week4 - Handouts

Web Application ArchitecturesModule 4: The Ruby Programming Language

Lecture 1: Background

c© 2011-13 G.L. Heileman Module 4, Lecture 1 1 / 9

Page 2: Web Architecture : Week4 - Handouts

Ruby Programming Language

Rails was built using the Ruby programming language.

Ruby code shows up in models:class Post < ActiveRecord::Baseend

views:<%= @post.title %>

and controllers:def destroy

@post.destroyrespond_to do |format|format.html { redirect_to posts_url }format.json { head :no_content }

endend

c© 2011-13 G.L. Heileman Module 4, Lecture 1 2 / 9

Page 3: Web Architecture : Week4 - Handouts

Ruby – History

Yukihiro Matsumoto (“Matz”) created Ruby in the mid-1990s.

“I wanted a scripting language that was more powerful than Perl,and more OO than Python. That’s why I decided to design myown language.”

Matz developed Ruby with a focus on the programmer, rather thanthe machine. The design goal was to maximize programmer efficiency(i.e., productivity), not the runtime efficiency of the their programs.

“I hope to see Ruby help every programmer in the world to beproductive, and to enjoy programming, and to be happy. That isthe primary purpose of Ruby language.”

c© 2011-13 G.L. Heileman Module 4, Lecture 1 3 / 9

Page 4: Web Architecture : Week4 - Handouts

Ruby – Design

Matz’s guiding philosophy for Ruby:

“Ruby is designed to make programmers happy.”

Ruby is designed according to the Principle of Least Astonishment –the language should behave in a way that minimizes the confusion ofexperienced programmers (assuming you’re experienced in Ruby, notoperating with some other programming model in mind).

Ruby is an object-oriented interpreted scripting language – many findit intuitive, flexible and extensible.For more information, documentation and tutorials, visit:http://www.ruby-lang.org

c© 2011-13 G.L. Heileman Module 4, Lecture 1 4 / 9

Page 5: Web Architecture : Week4 - Handouts

Ruby – Installation

Recall that to find the version of Ruby you’re running, use:

$ ruby --version

Ruby gems is a package management system. To see the gems youhave installed, use:

$ gem list

Rails is a Ruby gem for building database-intensive web applicationframeworks. To install it, use:

$ gem install rails

c© 2011-13 G.L. Heileman Module 4, Lecture 1 5 / 9

Page 6: Web Architecture : Week4 - Handouts

The Ruby Interpreter

Ruby is an interpreted language. You invoke the interpreter using theruby command:Ex.

$ ruby -e ’puts "Hello World!"’Hello World!$

The -e prompt tells the interpreter to execute the line of Ruby codecontained in the single quotes.

Typically you will place your Ruby code in a file, with a .rb extension.E.g., put the previous code in the file hello.rb, and tell the interpreterto execute it using:

$ ruby hello.rbHello World!$

c© 2011-13 G.L. Heileman Module 4, Lecture 1 6 / 9

Page 7: Web Architecture : Week4 - Handouts

The Ruby Interpreter

Interactive Ruby Shell (IRB) is an interpreter shell that allows you toexecute Ruby code from a command prompt – a REPL. It’s veryuseful for debugging purposes.

To open up a Ruby shell, type:

$ irb2.0.0p195 :001 >

At the prompt provided by interactive ruby, you can type rubyexpressions, and they will be evaluated:

2.0.0p195 :001 > 2+2=> 42.0.0p195 :002 >

c© 2011-13 G.L. Heileman Module 4, Lecture 1 7 / 9

Page 8: Web Architecture : Week4 - Handouts

The Ruby Interpreter

You can invoke IRB from the root of a Rails application directory asfollows:

$ rails consoleLoading development environment (Rails 4.0.0.rc1)2.0.0-p195 :001 >

The Rails environment (including everything defined in the currentRails application) is loaded when you do this.

You can directly manipulate your rails application from the consolecommand line – add/delete database items, inspect and manipulateobject, etc.

This is very useful, and common, way to debug Rails applications.

c© 2011-13 G.L. Heileman Module 4, Lecture 1 8 / 9

Page 9: Web Architecture : Week4 - Handouts

Language Features

Ruby is a multi-paradigm programming language:Scripting – It can be used to write scripts that automate the executionof tasks within some environment.Imperative (procedure-oriented) programming – It has the traditionalcontrol structures found in imperative programs. You can createfunctions with variables (that store state); however, definingfunctions/variables outside classes actually makes them methods ofthe root Object class.Object-oriented programming – Everything is an object, derived fromthe Object class.Functional programming – Computation proceeds via the evaluation offunctions that depend only on their input, not the program state.

c© 2011-13 G.L. Heileman Module 4, Lecture 1 9 / 9

Page 10: Web Architecture : Week4 - Handouts

Web Application ArchitecturesModule 4: The Ruby Programming Language

Lecture 2: Classes and Inheritance

c© 2011-13 G.L. Heileman Module 4, Lecture 2 1 / 10

Page 11: Web Architecture : Week4 - Handouts

Classes

Classes are defined using the keyword class followed by the name ofthe class. The name must begin with a capital, and the convention isto use CamelCase.

To define a method, use the keyword def:Ex.

class MyClass@boo # an instance variabledef my_method

@foo = 2 # an instance variableend

end

> mc = MyClass.new # create a MyClass object> mc.my_method # => 2> mc.boo # => error

c© 2011-13 G.L. Heileman Module 4, Lecture 2 2 / 10

Page 12: Web Architecture : Week4 - Handouts

Methods

An instance variable can only be directly accessed or modified within amethod definition.Ex.

class MyClassdef boo # a getter methodreturn @boo

enddef boo=(val) # setter method@boo = val

endend

> mc = MyClass.new # create a MyClass object> boo = 1 # => 1> boo # => 1

c© 2011-13 G.L. Heileman Module 4, Lecture 2 3 / 10

Page 13: Web Architecture : Week4 - Handouts

Methods

Notice that there is no return value specified in the methods above.Ruby methods have implicit return values – the value of the lastexpression executed in a method is its return value.

The return statement still exists, but you don’t need to use it.

Ex.

def min(x,y)if x < y then x else y end

end

When invoking a method, parentheses are optional.

c© 2011-13 G.L. Heileman Module 4, Lecture 2 4 / 10

Page 14: Web Architecture : Week4 - Handouts

Class Methods

Class methods are created in the same way as normal methods, exceptthey are prefixed by the keyword self.

Ex.

class MyClassdef self.cls_method

"MyClass type"end

end

> MyClass.cls_method # => "MyClass type"

c© 2011-13 G.L. Heileman Module 4, Lecture 2 5 / 10

Page 15: Web Architecture : Week4 - Handouts

Methods

In Ruby the last character of a method name is often used to indicate itsbehavior:

If the method ends with a question mark it indicates that the returnvalue is boolean.If the method ends with an exclamation, it indicates that the methodcan change the state of the object.In the previous case, it is common to also provide a non-exclamationversion of the method, which indicates that the modifies a copy of theobject.The keyword self can be used inside an object’s methods in order torefer to the current object.

c© 2011-13 G.L. Heileman Module 4, Lecture 2 6 / 10

Page 16: Web Architecture : Week4 - Handouts

Inheritance, Mixins and Extending Classes

Only single inheritance is supported; however, the mixin capabilityassociated with modules basically gives you multiple inheritance.Classes are never closed, you can always add methods to an existingclass.

– This applies to the classes you write as well as the standard, built-inclasses.

– You simply open up a class definition for an existing class, and the newcontents you specify will be added to whatever’s already defined forthat class.

Ex.

class Fixnumdef previous

return self-1end

end

c© 2011-13 G.L. Heileman Module 4, Lecture 2 7 / 10

Page 17: Web Architecture : Week4 - Handouts

Specifying Access

Within a class definition you may specify access levels using thekeywords public, private and protected.

The behavior is a little different than in C++ or Java:– public – no access control, can be called by anyone.– protected – can be invoked only by objects of the defining class and

its subclasses.– private – can only be called in the context of the current object,

without on object reference on the LHS, i.e, two objects of the sameclass cannot invoke each others private methods. Thus, the receiver ofa private method is always self.

By default, every method in a class is public, and every instancevariable is protected.

c© 2011-13 G.L. Heileman Module 4, Lecture 2 8 / 10

Page 18: Web Architecture : Week4 - Handouts

Accessors

There is a shorthand way of providing accessors for an object’sattributes:

class Personattr_accessor :first_name, :last_name

end

will create attributes (instance variables) for first_name andlast_name, as well as getter and setter methods for each.

If you only want a getter method, use attr_reader, and if you onlywant a setter, use attr_writer

c© 2011-13 G.L. Heileman Module 4, Lecture 2 9 / 10

Page 19: Web Architecture : Week4 - Handouts

Inheritance

The syntax for inheritance is:class NewClass < SuperClass

...end

The initialize method, which is always private, is used to createa constructor that is invoked by calling new on a class name. E.g., a= Array.new

You can create a module with its own namespace by using thekeyword module, and include a number of classes within it. You caninclude a module within another program by using the keyworkrequire, e.g., require ’module_name’

Within a class, you use the keyword include to mixin a module.This makes all of the methods defined in that module a part of theclass that includes the module.

c© 2011-13 G.L. Heileman Module 4, Lecture 2 10 / 10

Page 20: Web Architecture : Week4 - Handouts

Web Application ArchitecturesModule 4: The Ruby Programming Language

Lecture 3: Objects and Variables

c© 2011-13 G.L. Heileman Module 4, Lecture 3 1 / 5

Page 21: Web Architecture : Week4 - Handouts

Objects

Everything is Ruby is an object, the Object class is the parent classof all classes in Ruby. Its methods are therefore available to all objectsunless explicitly overridden.

An important method in the Object class is class(). It returnsthe “type” of an object.

> 1.class() # => Fixnum> 1.class # => Fixnum> 1.0.class # => Float> "Foo".class # => String

Notice how parentheses are optional – they are commonly omitted.

The language syntax is sensitive to the capitalization of identifiers, inmost cases treating capitalized variables as constants.

c© 2011-13 G.L. Heileman Module 4, Lecture 3 2 / 5

Page 22: Web Architecture : Week4 - Handouts

Variables

Ruby does not use variable declarations, if you assign a value to a literal,an “appropriate” variable named after that literal is created.Ex.

> a = 2 # => 2> a # => 2

In this example, a has type Fixnum, this is an integer data in Ruby. Theother integer type is Bignum (represents numbers of arbitrary size).

Ex.

> a = "2" # => "2"> a # => "2"

Now a is a String variable.

c© 2011-13 G.L. Heileman Module 4, Lecture 3 3 / 5

Page 23: Web Architecture : Week4 - Handouts

Variables

Important: All assignments are done by reference in Ruby. I.e, avariable just holds a reference to an object, and does not care aboutthe type of the object.

Ruby supports parallel assignment.Ex. You can easily swap the values stored in two variables:

> a = 2 # => 2> b = 1 # => 1> puts a, b # 2

# 1# => nil

a, b = b, a # => [1, 2]

c© 2011-13 G.L. Heileman Module 4, Lecture 3 4 / 5

Page 24: Web Architecture : Week4 - Handouts

Variables

Ruby uses simple naming conventions to denote the scope of variables:name – could be a local variable.@name – an instance variable.@@name – a class variable.$name – a global variable.

The @ and $ sigils enhance readability by allowing the programmer toeasily identify the roles of each variable.Furthermore, local variables must begin with a lowercase letter, andthe convention is to use underscores, rather than camel case, formulti-word names.Constants are any name that starts with an uppercase letter, and theconvention is to use underscores.Classes and modules are treated as constants, so they begin withuppercase letters, and the convention is to use camel case.

c© 2011-13 G.L. Heileman Module 4, Lecture 3 5 / 5

Page 25: Web Architecture : Week4 - Handouts

Web Application ArchitecturesModule 4: The Ruby Programming Language

Lecture 4: Strings, Regular Expressions and Symbols

c© 2011-13 G.L. Heileman Module 4, Lecture 4 1 / 8

Page 26: Web Architecture : Week4 - Handouts

Strings

You can create string literals in Ruby using either single or doublequotes.You can do a little bit more with double quoted strings. E.g., you caninsert arbitrary Ruby expressions using string interpolation.Ex.

> "360 degrees=#{2*Math::PI} radians"=> "360 degrees=6.283185307179586 radians"

If you enclose a string in single backquotes (backticks), the string willbe executed as a command in the underlying OS.Ex.

> ‘date‘=> "Tue Oct 15 09:10:21 MDT 2013\n"

c© 2011-13 G.L. Heileman Module 4, Lecture 4 2 / 8

Page 27: Web Architecture : Week4 - Handouts

Strings

Strings in Ruby are mutable, as in C/C++, but unlike Java. Thus,each time Ruby encounters a new string literal, it create a new Stringobject. I.e, if you’re creating a string literal within a loop, eachiteration will create a new String object.The Ruby String class contains a number of methods which can beused to manipulate strings.

Ex.

> name = "Homer Blimpson" # => "Homer Blimpson"> name.length # => 14> name[6] # => "B"> name[6..14] # => "Blimpson"> "Bart " + name[6..14] # => "Bart Blimpson"> name.encoding # => #<Encoding:UTF-8>

c© 2011-13 G.L. Heileman Module 4, Lecture 4 3 / 8

Page 28: Web Architecture : Week4 - Handouts

Regular Expression Class

Ruby has a regular expression class, called Regexp, that is closelyrelated to strings.A regular expression provides a concise and flexible means formatching strings of text, such as particular characters, words, orpatterns of characters.In Ruby, a regular expression is written in the form of:

/pattern/modifierswhere “pattern” is the regular expression itself, and “modifiers” are aseries of characters indicating various options. The “modifiers” part isoptional. This syntax is borrowed from Perl.To test if a particular Regex matches (part of) a string, use the=∼ operator. This operator returns the character position in thestring of the start of the match (which evaluates to true in a booleantest), or nil if no match was found (which evaluates to false).Ex. "Homer" =~ /er/ # => 3

c© 2011-13 G.L. Heileman Module 4, Lecture 4 4 / 8

Page 29: Web Architecture : Week4 - Handouts

Regular Expressions

The following have special meanings in patterns:meaning

[ ] range specification, e.g., [a-z] means a letter between a and z\w word character, same as [0-9A-Za-z_]\W non-word character\s space character, same as [\t\n\r\f]\S non-space character\d digit character, same as [0-9]\D non-digit character\b backspace (if used in a range specification)\b word boundary (if not used in a range specification)\B non-word boundary* zero or more repetitions of the preceding+ one or more repetitions of the preceding

{m,n} at least m and at most n repetitions of the preceding? at most one repetition of the preceding, same as {0,1}| either preceding or next expression may match

( ) groupingc© 2011-13 G.L. Heileman Module 4, Lecture 4 5 / 8

Page 30: Web Architecture : Week4 - Handouts

Regular Expressions

The preceding table only contained a partial list of the specialcharacters that can be used in a Ruby regular expression. Consult aRuby reference for more details.Regular expression are often used to process strings.Ex. The following Ruby expression will replace all of the non-digitcharacters in phone with "". I.e., it will strip everything out of thephone number, except digits:

phone = phone.gsub!(/\D/, "")

Regular expression are commonly used to validate emails, phonenumbers, and other user-supplied input.Ex. The following regular expression can be used to validate emailaddresses:

/\A[\w\._%–]+@[\w\.-]+\.[a-zA-Z]{2,4}\z/(Note: We didn’t cover all of the characters used in this regularexpression.)

c© 2011-13 G.L. Heileman Module 4, Lecture 4 6 / 8

Page 31: Web Architecture : Week4 - Handouts

Symbols

Ruby symbols are also closely related to strings.A Ruby interpreter maintains a symbol table where it stores the namesof all classes, methods and variables.You can add your own symbols to this table. Specifically, a symbol iscreated if you precede a name with a colon.Ex.

attr_reader :row, :col

Ruby symbols are used to represent names and strings; however unlikeString objects, symbols of the same name are initialized and exist inmemory only once during a Ruby session.Ruby symbols are immutable, and cannot be modified during runtime.Ex.

:name = "Homer" # => will yield an error

c© 2011-13 G.L. Heileman Module 4, Lecture 4 7 / 8

Page 32: Web Architecture : Week4 - Handouts

Symbols

There’s a big space advantage associated with symbols, as eachunique is only stored once in memory. Multiple strings with the samename my exist in memory.Ex.

> puts :name.object_id # => yields 20488> puts :name.object_id # => yields 20488> puts "name".object_id # => yields 2168472820> puts "name".object_id # => yields 2168484060

When should you use a string and when should you use a symbol?General rules of thumb:

– If the contents (i.e., the sequence of characters) of the object isimportant, e.g., if you need to manipulate these characters, use astring.

– If the identity of the object is important (in which case you probablydon’t want to manipulate the characters), use a symbol.

c© 2011-13 G.L. Heileman Module 4, Lecture 4 8 / 8

Page 33: Web Architecture : Week4 - Handouts

Web Application ArchitecturesModule 4: The Ruby Programming LanguageLecture 5: Expressions and Control Structures

c© 2011-13 G.L. Heileman Module 4, Lecture 5 1 / 6

Page 34: Web Architecture : Week4 - Handouts

Expressions

The Ruby syntax is expression-oriented.

Everything in Ruby is treated as an expression and therefore evaluatesto something.

Ex. Control structures for conditional execution or looping, whichwould be treated as statements in other languages, are treated asexpressions in Ruby.

In Ruby, if, case and for structures return the value of the lastexpression evaluated within the structure.

c© 2011-13 G.L. Heileman Module 4, Lecture 5 2 / 6

Page 35: Web Architecture : Week4 - Handouts

Control Structures – Conditional Execution

Ruby has a rich syntax for expressing conditionals – the most basic is:if expression

codeend

where code is executed if and only if the conditional expressionevaluates to something other than false or nil.

Else clauses can be added to specify code that should be executed ifthe conditional expression is not true:

if expression1code

elsif expression2code

elsecode

end

c© 2011-13 G.L. Heileman Module 4, Lecture 5 3 / 6

Page 36: Web Architecture : Week4 - Handouts

Control Structures – Conditional Execution

There’s a shorthand way of expressing the if conditional that treats itas an expression modifier:

code if expression

Ruby also has a ?: operator, as in C/C++.

Comparison operators:==, !=, =∼, !∼, ===

There is a case structure in Ruby, === is the case-equality operator.

c© 2011-13 G.L. Heileman Module 4, Lecture 5 4 / 6

Page 37: Web Architecture : Week4 - Handouts

Control Structures – Conditional Execution

In addition to the “standard” set of conditionals, Ruby has added somethat are intended to increase the readability/understandability of code.E.g., the following is the opposite of an if statement:

until expressioncode

end

where code is executed until the conditional expression evaluates tosomething other than false or nil.

You cannot attach else clauses to the until conditional.

c© 2011-13 G.L. Heileman Module 4, Lecture 5 5 / 6

Page 38: Web Architecture : Week4 - Handouts

Control Structures – Iteration

The for/in loop iterates over an enumerable collection:for var in collection do

bodyend

Exit condition loop:while condition do

bodyend

Exit condition loop, opposite of while:until condition do

bodyend

In Ruby, it’s more common to use iterators (next lecture).

c© 2011-13 G.L. Heileman Module 4, Lecture 5 6 / 6

Page 39: Web Architecture : Week4 - Handouts

Web Application ArchitecturesModule 4: The Ruby Programming Language

Module Overview

c© 2011-13 G.L. Heileman Module 4: Overview 1 / 2

Page 40: Web Architecture : Week4 - Handouts

Module Overview

BackgroundClasses and InheritanceObjects and VariablesStrings, Regular Expressions and SymbolsExpressions and Control StructuresCollections, Blocks and Iterators

c© 2011-13 G.L. Heileman Module 4: Overview 2 / 2


Recommended