F10, F11 : Introducing a real gem of DB2 application development

Leon Katsnelson IBM Toronto Lab Wednesday, May 9, 2007 • 1:40 p.m. – 4:00 p.m.

Platform: Cross Platform

1 Attend this session and receive a CD-ROM that contains everything you need to get started with learning DB2 Ruby on Rails programming including: -“Programming Ruby” book (PDF) – a must have book for anybody learning Ruby -Flash tutorials so you can replay them after the conference -Presentation materials for this session -A free copy of DB2 Express–C 9 -Latest copy of Ruby -Latest copy of the Rails framework -DB2 Ruby driver and DB2 Rails adapter

Materials will also be made available for download on the “Members Area” of the IDUG website after the conference and from http://www.alphaworks.ibm.com/tech/db2onrails. 2

2 Agenda

• Ruby: a gem of a language • Rails: web-based framework for database applications • DB2 on Rails: everything you need to get started • Project Aurora: You really have to see it to believe it!

3

3 What is “Ruby”?

RubyRubyisis aa reflectivereflective,, object-orientedobject-oriented programmingprogramming languagelanguage.. ItIt combinescombines syntaxsyntax inspiredinspired byby PerlPerlwithwith SmalltalkSmalltalk-like-like object-object- orientedoriented features,features, andand alsoalso sharesshares somesome featuresfeatures withwith PythonPython,, LispLisp,, DylanDylanandand CLUCLU.. RubyRuby isis aa single-passsingle-pass interpretedinterpreted languagelanguage.. ItsIts mainmain implementationimplementation isis freefree softwaresoftware distributeddistributed underunder anan open-sourceopen-sourcelicense.license. Source: Wikipedia.org

4

Two most important facts about Ruby are the fact that it is a scripting language and that it is I an object-oriented language.

4 Sounds very similar to …

PerlPerl,, alsoalso PracticalPractical ExtractionExtraction andand ReportReport LanguageLanguage(a(a backronymbackronym,, seesee belowbelow)) isis aa dynamicdynamicproceduralprocedural progprogrammingramming languagelanguage designeddesigned byby LarryLarry WallWallandand firstfirst releasedreleased inin 19871987.. PerlPerl borrowsborrows featuresfeatures fromfrom CC,, shellshell scriptingscripting ((shsh),), AWKAWK,, sedsed,, LispLisp,, and,and, toto aa lesserlesser extent,extent, manymany otherother prprogrammingogramming languages.languages.

Source: Wikipedia.org

5

Perl is also a scripting language and it was a strong influence on Ruby. However, Perl is a procedural programming language and does not even pretend to be object-oriented.

5 And similar to …

PHPPHP((PPHP:HP: HHypertextypertext PPreprocessor)reprocessor) isis anan openopen sourcesource,, reflectivereflectiveprogrammingprogramming languagelanguage.. OriginallyOriginally designeddesigned asas aa highhigh levellevel scriptingscripting languagelanguageforfor producingproducing dynamicdynamic WebWeb pagespages,, PHPPHP isis usedused mainlymainly inin server-sideserver-side applicationapplication softwaresoftwarebutbut cancan bebe executedexecuted fromfrom aa commandcommand lineline interfaceinterfaceoror aa standstand alonealone GUIGUI.. ItIt isis thethe fifthfifth momostst popularpopular programmingprogramming languagelanguage inin useuse today.today.

Source: Wikipedia.org

6

PHP is another popular scripting language. While originally it was a pure procedural language, lately it has been given object-oriented features.

6 … and isn’t this the same as …

Python®Python® is is aa dynamicdynamic object-orientedobject-oriented programmingprogramming languagelanguagethatthat cancan bebe usedused forfor manymany kindskinds ofof softwaresoftware development.development. ItIt offersoffers strongstrong supportsupport forfor integrationintegration withwith otherother languageslanguages andand tools,tools, comescomes withwith extensiveextensive standardstandard libraries,libraries, andand cancan bebe learnedlearned inin aa fewfew days.days. ManyMany PythonPython programmersprogrammers reportreport substantialsubstantial productivityproductivity gainsgains andand feelfeel thethe languagelanguage encouragesencourages thethe developmentdevelopment ofof higherhigher quality,quality, moremore maintainablemaintainable code.code.

Source: python.org

7

Python is anohter scripting language

7 What is Rails?

full-stack framework for database-backed web applications implements the model-view-control (MVC) architecture written in Ruby incredibly productive easy to use, conventions over configuration one of the fastest emerging web framework since 2004

8

Then talk about rails

8 Number of developers has growing briskly with double digit growth expected to yield 13M developers worldwide in 2006. Through 2009, AP will drive the majority of growth as its WW share increases from 33% to 40% while overtaking EMEA.

2004 2005 2006 2007 2008 2009 Developers (000) 10,999 12,059 13,354 14,795 16,399 18,174 Growth (%) n/a 9.6% 10.7% 10.8% 10.8% 10.8%

Professional Developers By Geo 2006 Professional Developers By Geo 2009 18% 23% 36% 35% 7% 7%

40% 34% EMEA AP LA NA EMEA AP LA NA

Source: IDC Population Model9 2005-2006

India, China, Russia and Japan will constitute almost 30% of developer population.

9 The BIG THREE

10

10 TPC Index http://www.tiobe.com/tpci.htm

11

11 TIOBE – Popular programming languages (jobs)

12

12 Is Ruby on Rails the next Java?

• Some of the most respected Java people think so • Enterprise qualities (MVC) but several orders of magnitude more productive • All-n-one framework: no assembly required, batteries included

13

13 Is Ruby on Rails the next Java?

“(Bruce) Tate says it shook him to his Java-loving core when the Rails rewrite took four nights of coding when compared to four months for the Java build, then outperformed the Java version while weighing in at about the fifth the number of lines of code” -Michael Swaine, Dr. Dobb’s Journal

14

14 Is Ruby on Rails the next PHP?

• Many respected PHP people think so • Speed of development but with scalability, performance and discipline the enterprise needs • Similar demographic as PHP but much faster adoption curve • PHP community is trying to respond with their own MVC frameworks but most PHP programmers are not embracing MVC (skill impedance mismatch)

15

15 “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

“It is impossible not to notice Ruby on Rails. It has had a “Ruby on Rails is a breakthrough in lowering huge effect both in and outside the Ruby community... the barriers of entry to programming. Powerful Rails has become a standard to which even well- web applications that formerly might have established tools are comparing themselves to.” taken weeks or months to develop can be -Martin Fowler, Author of Refactoring, PoEAA, XP produced in a matter of days.” Explained -Tim O'Reilly, Founder of O'Reilly Media

“Ruby on Rails is astounding. Using it is like “After researching the market, Ruby on Rails stood out watching a kung-fu movie, where a dozen bad- as the best choice. We have been very happy with that ass frameworks prepare to beat up the little decision. We will continue building on Rails and newcomer only to be handed their asses in a consider it a key business advantage.” variety of imaginative ways.” -Evan Williams, Creator of Blogger and ODEO -Nathan Torkington, O'Reilly Program Chair for OSCON

16

16 Ruby on Rails Momentum: red hot! • Ruby invented by aka "Matz", 1995; • Rails: • invented by David Heinemeier Hansson (DHH), late 2004 while still in university • Rails 1.0 ships December 24, 2005 • Rails 1.1 ships 3 months later • Rails is only 10 month old and is already the hottest IT topic of today • In 2005 less then a dozen ISPs provide RoR hosting. In 2006, most major ISPs host RoR • Google buys RoR company in 2005; runs Summer of Code RoR projects in 2006

17

17 Ruby on Rails Momentum: red hot! • First Rails conference held in 2005, 90 people attended. RailsConf 2006 sold out in 5 days. Added 150 seats and sold them in 24 hours. We are a sponsor! • Other Rails and Ruby conferences sols out (eg. CanadaOnRails) • Rails won the Jolt Award for the best web framework. Rails book won the best book award. • Rails book sold 25K copies in less then a month. • Agile Development With Rails is one of the best selling programming books ever. Every major publisher is releasing a book(s) on RoR. • Over 500000 copies of Rails downloaded • DHH voted 2005 Hacker of the Year at the OSCON • DHH voted by Business 2.0 magazine as one of “the 50 who matter now” people 18

18 Ruby: a gem of a language

19

19 Ruby is a scripting language

Compiled languages Scripting languages •

COBOL, C, C++, • <xmp>PERL, PHP, Python, PLI Ruby • Source code is transformed • Source code is interpreted by a compiler in to byte code every time it is invoked that can be executed by a • Applications are distributed in particular machine the source form i.e. no architecture executable (code can be • Executable code is distributed obfuscated to protect to the application users intellectual property) • Changes made to the source • Changes to source are need to be recompiled reflected in the execution immediately

20

20 Ruby is object oriented

• Everything is an object; there are no base types • Every function is a method • Variables are references to objects • Single inheritance and mixins (a novel twist on single- multiple inheritance challenges)

-2006.abs # -> 2006 “IDUG”.length # -> 4 3.times {puts 'hello'} # writes hello 3 times 9.zero? # false 44.class # fixnum "hello" * 3 # hellohellohello

21

Matz (creator of Ruby) wanted to create a scripting language that was more object oriented then Python, another popular object oriented scripting language. Ruby is object oriented to its core. In Ruby, everything is an object and what you do is manipulate objects. Even base data types such as numbers are treated as objects. For example, you could write -2006.abs and get 2006. You called method abs on object -2006. Calling methods on base types … you don’t get any more object oriented than this.

21 Ruby is about Duck Typing

• No need to declare variables … just start using them • Value assigned to a ƒ“if it walks like a variable determines its type duck and quacks like a duck it must be a duck!”

22

Rubyists love Ruby for its syntax. It is very clean and easy to read and understand without being too “wordy”. No, Ruby is not COBOL. You don’t have to define variables, just use them. And Ruby philosophy embraces duck typing as in “if it walks like a duck and quacks like a duck it must be a duck!” In Ruby, the value assigned to the variable determines the data type of the variable and not the other way around as is the case in many programming languages. In other words, Ruby will figure the data type based on what you store in a variable … it is that smart.

22 Ruby likes conventions to make syntax readable • local variables, parameters, and method names start with a lower case letter or an underscore • Global variables start with a dollar sign ($). • Class variables start with @@ and instance variables begin with a single @ symbol. • Method names can end with ?, =, !.

while more_things_to_do? puts "sorry, I am not done yet!" end

23

One simple but important concept that makes Ruby syntax easy to read is its reliance on conventions. The Rails framework takes to whole different level … but more on that later. For example, in Ruby, local variables, parameters, and method names start with a lower case letter or an underscore. Global variables start with a dollar sign ($). Class variables start with @@ and instance variables begin with a single @ symbol. This is easy enough. But more interesting is that method names can end with ?, =, !.

23 Ruby has arrays and hashes

• Arrays are integer indexed starting with 0 • Hashes use objects as keys

food_group = { 'Bread' => 'grain products', 'Lettuce' => 'vegetables', 'Apple' => 'fruits', 'Cheese' => 'dairy products', 'Lamb' => 'meat and alternatives', 'Chocolate' => 'fats, oils and sugars', 'Ketchup' => 'ketchup' } food_group[‘bread’]would be ‘grain products’ and the value of food_group[‘Ketchup’]would be ‘ketchup’

24

24 Ruby has other easy to read syntax • if, unless, while, until, etc. may appear at the end of any statement. • Some key words are optional (the ''then'' in an ''if'' statement for example). • Parentheses in many cases can be omited in method calls.

puts 'Leon, stop working' if day_of_week == 'Saturday'

25

25 Ruby has blocks

• Supply a block (somewhat like a subroutine) to a method • Inside a method do a yield and block code is executed

authors = ['Chris', 'George', 'Leon', 'Paul'] authors.each { | author | puts author }

Chris George Leon Paul

9.times { puts 'Hello DB2 9' }

26

26 Ruby: Summary of features 1 of 3 ƒ purely object-oriented: everything is an object

ƒ dynamically typed

ƒ exception handling

ƒ iterators and blocks

ƒ native regular expressions

27

27 Ruby: Summary of features 2 of 3 ƒ principle of least surprise

ƒ operator overloading

ƒ automatic garbage collecting

ƒ classes, methods, modules, mixins

ƒ highly portable

28

28 Ruby: Summary of features 3 of 3 ƒ large standard library

ƒ I18n support (UTF-8)

ƒ continuations, generators, introspection, reflection and meta- programming

ƒ extensible in C

29

29 3030 Two important tools: 1) Interactive irbRubyis an interactive Shell shell excellent for trying out snippets of code, learning more about how Ruby works and cut down on the edit-run-debug cycle

31

31 Two important tools: 2) Ruby riinteractive Dir

32

32 Querying DB2 # Load the Ruby DB2 driver require 'ibm_db2'

# Connect to the local alias 'mydb' conn = DB2::connect("mydb","db2admin","db2password") sql = "SELECT * FROM Users" # Alternative connection through TCP/IP conn = DB2::connect "DRIVER={IBM DB2 ODBC begin DRIVER};DATABASE=#{database};HOSTNAME=#{hostname} # Execute the statement. ;PORT=#{port};PROTOCOL=TCPIP;UID=#{user};PWD=#{pa # It will return false if there are problems. ssword};", '', '' if stmt = DB2::exec(conn,sql) # Fetch all the records while row = DB2::fetch_assoc(stmt) # Records are Hashes, with columns name as keys puts row['USERNAME'] end # Free resources associated with the result set DB2::free_result(stmt) else # If the execution failed, raise an error using the CLI error info raise DB2::stmt_errormsg end ensure # Close the connection DB2::close(conn) end

33

33 Querying DB2 with parameterized queries # Load the Ruby DB2 driver require 'ibm_db2'

# Connect to the local alias 'mydb' conn = DB2::connect("mydb","db2admin","db2password")

sql = "INSERT INTO USERS (username, age, subscription) VALUES (?,?,?)"

stmt = DB2::prepare(conn,sql) values = ["antonio", 26, 2006]

begin # Check that the execution was performed correctly if DB2::execute(stmt, values) puts "Insert was successful" else # If the execution failed, raise an error using the CLI error info raise DB2::stmt_errormsg(stmt) end ensure # Close the connection DB2::close(conn) end

34

34 Rails

35

35 Model, View, Controller

controller

view model

DB2

36

The model part of MVC is designed to provide a representation for the real life objects that the application will implement. Basically, model is a representation of the domain of the application. For example, if you are building an application for insurance industry objects such as policy, customer, asset etc. may all be a part of your domain and each will need to have an associated model. As you would expect, the application will need to have a way to store the information that embodies each model and this is where DB2 comes in. DB2 and other data servers provide the persistence layer for the models used by an application. The view portion of the MVC represents all interactions with a user. And since the object of most user interactions is to view or modify domain objects (e.g. price out an auto insurance policy) we can safely assume that view allows users of the application to work with the model for the application. In the world of web applications, the view component is typically a collection of HTML pages that provide dynamic content (based on the model) to the user and allow users to modify contents of the model (by using HTML forms etc.) The controller is best described as a traffic cop that directs all interactions between the view and the model. It responds to events (typically generated by the user) and makes changes to the contents of the model. A typical interaction my look like this: 1. User clicks on a link or presses a button (this is a view generated event). 2. Controller listens for such events and responds to them using logic that was coded in to the controller. This logic will route view to the appropriate model and may take other actions (e.g. update model). 3. The view will get the data from the model and will generate user interface (e.g. HTML web page) and will send it to the browser for rendering.

36 Rails is what makes Ruby really shine • Rails is a framework for building web-based database applications • Rails = MVC: • Action Pack = View and Controller • Active Record = Model • What’s is different about Rails then: Rails makes MVC easy!

37

The Rails framework is what database people really care about. Ruby itself does provide connectivity to databases but Rails elevates to a whole new level. What is Rails? Rails is a framework that makes it much easier to build database web applications in Ruby. If you have done any significant amount of development in Java you are well familiar with the concept of a framework. Java web programmers use frameworks like Apache Struts, Spring, Hybernate, JavaServer Faces and many others to implement portions of their applications. .NET programmers are also very familiar with the framework concept as the whole .NET infrastructure is indeed called “Microsoft .NET Framework”. Most people think of a framework as some sort of an organized collection of classes. People also typically expect a set of patterns that describe the best practices for using the classes in the framework. Rails is all that. It is an open source web application framework that it self is written entirely in Ruby.

37 Rails: MVC made easy!

• Two most important principles of Rails: • DRY: Don’t Repeat Yourself • Convention over configuration

38

38 Model, View, Controller1. http://my.url/store/add_to_cart/123 2. Router finds Store controller 3. Controller interacts with model 4. Controller invokes view 5. View renders browser screen router

StoreControlle -add_to_cart()

model View ƒFind info for 123 ƒ Show cart ƒShipping cart: add item DB2 123 to yourself

39

The router receives the incoming request and disassembles it. It takes the first part of the path, store, as the name of the controller. And the second part, add_to_cart, as the name of the action to perform. The last part, 123, is by convention extracted in to an internal parameter called id. ) The ad_to_cart method() handles user request by finding the user’s shipping cart. It also asks the model to find information for

39 Rails: first pass

• David Heinemeier Hanson extracted this framework from his work on 37signals’ Basecamp (a hosted project collaboration tool) • Makes Web development easy through simple conventions (rather than extensive configuration), and the “Don’t Repeat Yourself” principle (localize change): • Examples: • the order records are known to be stored in an Orders table, no mapping required (in numerous .xml configuration files) • http://localhost/order/list/100 is pointing to an Order processing component, and its list() method will be called with a value = 100 • View partials contain reusable snippets to be reused over many web pages. • Makes maintenance and deployment easy through enforced code structure and built-in plumbing: MVC, ORM, testing.

40

40 Active Record is the way to the data • Active Record = Object Relational Mapping • Maps database tables in to Ruby classes (models) • Each row represents an instance of a class • Columns represent attributes of a model • Rails creates instance methods to operate on object attributes • Rails creates class methods to operate on entire tables (e.g. find)

41

41 Active Record does more then just ORM • Provides integration of Model with Vew and Controller • Performs validations (very very good stuff) • Let’s you do query by SQL

employees = Employee.find_by_sql("select * from employees")

42

42 • MovingJ2EE on Struts smooth versus Ruby on on Rails known tracks • stack comparison

Apache Tomcat Webrick Servlet Container

ActionServlet Controller DispatchServlet

Action ActionForm JSP View RHTML ActionController

Hibernate Model ActiveRecord

Datastore Datastore

• Controller: accepts HTTP requests, parses URL, extracts parameters, forwards to specific Action (bridge between Controller and Model) • Model: retrieves/persists data encapsulating access and domain logic • View: render and present the model in an HTML format

43

43 • MVCController the (DispatchServlet) Rails way orchestrates the application: • extracts parameters from request and interacts with the model through a specific action (ActionController subclass) based solely on the URL pattern: • Example: http://localhost/order/list/100 directs to OrderController (defined in order_controller.rb) and passes to the method list() the value 100. That would display row with id=100. Change list with delete and the same row gets deleted • invokes the view providing the presentation and rendering of the model • ActionController along with ActionView (the Action Pack) form the core processing of incoming requests and generating responses.

44

When http://localhost/order/list/100 directs to OrderController (defined in order_controller.rb) and passes to the method list() the value 100. That would display row with id=100. Change list with delete and the same row gets deleted

44 •MVCView: a combinationthe Rails of templates, way partials and layouts all using plain Ruby code tag libraries • It presents the user with various ways to display/input data but it never handles incoming data • ActionView module encapsulates required functionality to render templates (i.e. generate HTML or XML) in response to user requests • Writing a view = writing a template associated with an action result (i.e. HTML fragments interwoven with Ruby code statements placed between <% %>) • Controller instance variables are also available in templates (actions communicating data to templates), and a template can also call any public methods on the controller • .rxml templates render XML pages, while .rhtml templates render HTML pages

45

45 •MVCModel: ActiveRecordthe Rails wrapping way: framework • An ActiveRecord subclass wraps a row in a database table/view and encapsulates access and domain logic, and acts as the gatekeeper of the datastore. • Starts with the database table, as opposed to starting with the object model as mapping frameworks usually do (i.e. Hibernate) • Wraps class hierarchies to relational tables through single table inheritance: adding a string column ‘TYPE’ to the table persisting the hierarchy. • Note: column name can be overridden using inheritance_column() • Wraps the following table relationships (one-to-one, one-to- many, many-to-many) through declarations in the model (belongs-to, has-one, has-many, has-and-belongs-to-many), and also supports: acts_as_tree, acts_as_list • Differs from other ORM implementations through its “convention over configuration” principle which implies a sensible set of defaults

46

46 ActiveRecord:• A one-to-one association one-to-one (one-to-zero-or-one relationship) is implemented using a foreign key in one row in one table to reference at most a single row in another table. • In Rails one just adds a has_one declaration to the Order model, and adds a belongs_to declaration to the Invoice model:

class Invoice < ActiveRecord::Base belongs_to :order . . . end class Order < ActiveRecord::Base has_one :invoice . . . end

47

47 ActiveRecord:• A one-to-many aggregation one-to-many representing a collection: all the line item rows for a particular order contain a foreign key column referring to that order. • In Rails one just needs to add the has_many declaration in the parent object (logically containing the collection of child objects) showing its relationship to the child table declaring the belongs_to for its parent: class LineItem < ActiveRecord::Base belongs_to :order . . . end class Order < ActiveRecord::Base has_many :line_items . . . end

48

48 ActiveRecord: many-to-many • A many-to-many association where each side of the relationship contains a collection of things on the other side. • In Rails one just needs to add the has_and_belongs_to_many declaration to both models:

class Category< ActiveRecord::Base has_and_belongs_to_many :products . . . end class Product< ActiveRecord::Base has_and_belongs_to_many :categories . . . end

49

49 ActiveRecord: act-as-tree • An act-as-tree structure can be achieved by adding a single column (called parent_id) to a table. This column is a foreign key reference back into the same table, linking child rows to their parent row. • In Rails one just needs to declare such structure using acts_as_tree for a table which defines a parent_id column: create_table :categories, :force => true do |t| t.column :name, :string t.column :parent_id, :integer end class Category < ActiveRecord::Base acts_as_tree :order => "name" end

50

An act-as-tree structure can often be found in Category listings where entries have subentries, and those subentries may have their own subentries.

50 ActiveRecord: act-as-list • An act-as-list structure defines a relation between a parent table and some children tables containing a column to record their position in the list (allowing addition, removal, traversal, position change).

• In Rails one just needs to declare the belongs_to and has_many to define parent- child relation, and then add acts_as_list to define the list: create_table :parents, :force => true do |t| end create_table :children, :force => true do |t| t.column :parent_id, :integer t.column :name, :string t.column :position, :integer end

class Parent < ActiveRecord::Base has_many :children, :order => :position end class Child < ActiveRecord::Base belongs_to :parent acts_as_list :scope => :parent_id end

51

51 •ORMWrapping the an object Rails view ofway: some data ActiveRecord to certain tables in a relational database: • wraps tables to classes, rows to objects, and columns to object attributes • implicit conventions (customizable): • Active Record expects the name of the table to be the plural form for the class name • Active Record reflects on the database schema to configure the classes that wrap tables • Active Record instance attributes generally correspond to the data in the corresponding database table row • each table associated with a class has an integer primary key column named id • Active Record abstracts the concept of a database connection, delegating the details to a set of database- specific adapters

52

52 ActiveRecord:• Makes it easy to implement the the intermediator four basic operations on database tables: Create, Read, Update, Delete (CRUD) • Abstracts and generates dynamic SQL • where/like clause represented by :conditions parameter • Item.find(:all, :conditions => “item_type = ‘new‘” and "name like ?" , params[:name]+"%") • order clause represented by :order param • Item.find(:all, :order => “part_type, shipped_at DESC" ) • Similarly, it provides :limit, :offset, :joins, :select, :readonly, :from, :group, :lock • Built-in statistics: average, maximum, minimum, sum, count • Built-in common searches: find_by_, find_all_by_, etc.

53

53 Migrations• Rails encourages an agile, iterative style of development • in a Rails application the database schema constantly evolves (i.e. adding a new class/table, renaming an attribute/column), while in sync with the application’s code. • ActiveRecord::Migration abstracts the data manipulation in a database table and allows reversible actions: • creation: up() method • removal: down() method • A migration is simply a Ruby source file placed under version control alongside all our other application files. Each migration file’s name starts with (by default) three digits and an underscore, the version which defines the sequence in which the migrations are applied. • Warning: migrations do not currently feature transactional support (i.e. an atomic failure inside up() may not allow the migration to be reapplied or even rolled back)

54

54 Migrate• Example: up and down at will

class AddEmailColumnToCustomer < ActiveRecord::Migration def self.up • add_column :customers, :e_mail, :string end def self.down • remove_column :customers, :e_mail end end

• While the above code is in available in 022_add_email.rb • to apply: $ db:migrate VERSION=22 • to roll-back: $ rake db:migrate VERSION=21

55

55 Scaffolding• Scaffold, the ActionController feature providing a series of standardized actions for listing, showing, creating, updating, and destroying objects of a class/table. • Static scaffold: • $ ruby script/generate scaffold product admin • Scaffold generator takes the model and controller names and renders standardized actions containing both controller logic and default templates (introspection provides the fields to display and types) • Scaffold generator automatically creates code that will respond appropriate to requests for HTML or XML content. • Scaffold-generated applications use the scaffold.css stylesheet (public/stylesheets) which could be customized/replaced. • Dynamic scaffold: • scaffold :product declaration tells Rails to generate the application code at runtime for immediate use in testing of a newly added model and controller • web_service_scaffold( ) :invoke provides a way to execute web service methods from a web browser while in development. 56

56 From• $ ruby script/generatescaffold scaffoldto prototype product admin dependency model skip app/models/product.rb identical test/unit/product_test.rb identical test/fixtures/products.yml create app/views/admin/_form.rhtml create app/views/admin/list.rhtml create app/views/admin/show.rhtml create app/views/admin/new.rhtml create app/views/admin/edit.rhtml overwrite app/controllers/admin_controller.rb? [Ynaq] y force app/controllers/admin_controller.rb overwrite test/functional/admin_controller_test.rb? [Ynaq] y force test/functional/admin_controller_test.rb identical app/helpers/admin_helper.rb create app/views/layouts/admin.rhtml create public/stylesheets/scaffold.css

Source: Agile Web Development with Rails 2nd edition, Dave Thomas 57

57 Test• Applying environment “tough love” on our beloved applications even before they are written: • Rails framework has the support for testing baked right in from the start of every project (i.e. any top-level project directory created contains a subdirectory called test), plus a special database just for test (see database.yml) • By convention, Rails calls • things testing models: unit tests • things testing a single action in a controller: functional tests • things testing the flow through controllers: integration tests • Rails even creates the files to hold the unit tests for the models and the functional tests for the controllers created with the generate script • The testing starts from the data (unit test the models) and moves up closer to where the user interaction (functional and integration)

58

58 Assertion, test, case, suite… • Assertion: a method call that tells the framework what we resultsexpect to be true (i.e. the simplest assertion is the method assert( ), which expects its argument to be true).

• Unit Tests: collection of assertions that would validate a model

• Functional Tests: collection of assertion that would validate a specific controller action (method)

• Fixtures: simply a specification of the initial contents of a model(s) under test (test/fixtures directory).

• Mocks: a simple replacement for a known object that frees the tests from needing some sort of resource (network connection) while ensuring more consistent results.

59

59 Deployment: is there an easy • Webrick is sufficient in development for the single-threaded Rails way?• Highly concurrent production environments require a front-end server (i.e. Apache, Lighttpd, or Zeus), and a proxy to distribute requests to Rails processes running on any number of back-end machines: 1. FastCGI with its long-running processes can handle multiple sequential requests, therefore Ruby interpreter and Rails framework is loaded once per process and turn around requests for the host web server quickly. 2. (Ruby-based web-server) could be HTTP proxied by the front-end directly and makes for a better solution that is considered future proof and extensible • It’s better to start doing deployment: 1. early (as soon as few views already display) in order to identify any deployment issues 2. often (after any major commit) in order to have early feedback from management and customers • Capistrano, a RubyGem utility, provides reliable and repeatable deployment for Rails applications on remote servers.

60

60 Deployment: few real life lessons from • Make use of Capistrano, it’s better then you would first think James• Make use Duncan of before and after hooks for the various tasks in Capistrano, to avoid overloading the deploy task • Ruby versions change. Set RubyGems in a GEM_HOME (e.g. /usr/local//) to be able to reuse while upgrading Ruby • Don't even consider running your Rails app in CGI mode. Too slow. • The SCGI support in Rails is not quite ready for primetime, better use Lighty (with built in FastCGI and SCGI support) • For RubyGems that need to do native compilation of code the libraries should be kept in bundles outside of RubyGems if there is a need to manage multiple variants of the _same_ version. • If you do use Apache httpd, your options are 1.3.x or 2.0.x. • Don't use Ruby 1.8.3 with Rails on Mac OS X

Source: http://blog.duncandavidson.com/2005/12/real_lessons_fo.html 61

61 •CreditsMany thanks to andall of those References who wrote about Rails in books and blogs and articles: • David Heinemeier Hanson • Dave Thomas • James Duncan • Bruce Tate • Patrick Peak • Aaron Rustad • References: • Agile Web Development using Rails, 2nd edition • http://www.theserverside.com/tt/articles/article.tss?l=RailsHibernate • http://www-128.ibm.com/developerworks/java/library/j-cb03076/index.html • http://weblogs.java.net/blog/batate/archive/2006/01/we_should_learn.html • http://www-128.ibm.com/developerworks/web/library/wa-rubyonrails/

62

62 Announcing … Startup Toolkit for DB2 on Rails

63

63 Startup Toolkit for DB2 on Rails

• Version 1.1 available on IBM alphaWorks http://www.alphaworks.ibm.com/tech/db2onrails • IDUG Europe attendees get version 2.0 in this session. • Integrated installer that creates a complete DB2 Ruby on Rails development environment on a Windows PC • Source code available to do your own builds on other platforms • DB2 is now the only data server with vendor provided RoR enablement! 64

64 Startup Toolkit for DB2 on Rails What do you get • Integrated installer • Helps you install Ruby 1.8.4 and Rails 1.1.6 • Installs DB2 Express – C 9 and tools for managing database • IBM developed DB2 Ruby driver and DB2 Rails Adapter • Demos and tutorials – more to come soon!

65

65 Startup Toolkit for DB2 on Rails Getting Started • Learn Ruby • Start -> All Programs -> Ruby-184-20 -> Ruby Documentation • Learn DB2 on Rails • Start -> All Programs -> DB2 on Rails -> Information • Stay connected • DB2 on Rails on alphaWorks • Forum for DB2 on Rails •Blog: db2onrails.com

66

66 Keeps you up to date

67

67 Project Aurora Using DB2 on Rails to deliver business value

68

68 IT Spending Breakdown 2006

Source: Gartner Research 2005, “US IT Spending and Staffing Survey”

69

6969 Source: Gartner Research 2005, “US IT Spending and Staffing Survey” 70

7070 Productivity Application Market

71

7171 Project Aurora Value Proposition

Minus MS Access

MS Office 2003 Professional MS Office 2003 Standard $329 $239

• Reduce portion of budget spent on Productivity Applications by ~25% • Reduce security and compliance exposure by removing sensitive data from desktops and laptops • Maintain high level of programmer productivity while keeping data managed by IT

72

7272 Inspiration ƒ Departmental Applications – Created by a business user – Microsoft Excel and Microsoft Access – Sensitive data stores unsecured on laptops and desktops

73

Aurora is the solution. Think of it as a web based application builder. It’s IT-hosted software which provides the security, accessibility and persistence that is lacking in today’s internal applications. Aurora lights the way for a move from a complicated mess of applications to a managed infrastructure built on DB2.

73 74 74

74 “Wouldn’t it be nice to give the business users the power to create departmental applications quickly, with secured data, and which are easily deployable?”

75 75

75 ƒ Web based application builder

ƒ Allow the business user to: ƒ Create departmental applications ƒ IT manage data securely ƒ Deploy over the web

76

76 Project Aurora Demo

77 77

7777 Project Aurora Facts

• Created with Ruby on Rails and DB2

• Developed in 10 weeks

• Developed by 3 programmers who never have seen Ruby or Rails previously

78

That problem is that there is an increasing demand for departmental applications. These are applications which are not mission critical for an organization, but are required to ensure that a department is running efficiently and effectively.

The development of these tools falls outside the scope of corporate IT departments. As a result, business users seek other avenues to satisfy their needs such as Excel Spreadsheets and Access databases.

A number of issues arise as a result of these alternatives and they are of growing concern to organizations.

Access databases with sensitive information end up being stored unencrypted on laptops, which poses a major security threat. Legislation such as HIPPA and the Sarbanes Oxley Act puts tremendous pressure on CIOs to comply.

Not only is data dispersion a security risk, it is also very costly for the company to ensure that both back-office files and mobile data are in sync.

In addition, these applications are un-maintainable and it is next to impossible to upgrade them to satisfy new business requirements.

78 Ruby on Rails: Introducing a real gem of DB2 application development

Leon Katsnelson IBM Toronto Lab [email protected]

79

79 Session F10, F11 Ruby on Rails and Project Aurora

Leon Katsnelson IBM Toronto Lab [email protected]

80

80