Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Riding Rails to Ruby and Riches Dustin Marx Bill Jackson $ $ Presentation Changes Since Printing • Many slides have been added since hard copy was printed – these are marked with this image: • Find latest version of these slides at http://www.geocities.com/dustinmarx/SW/ • Note that many of these slides have notes and links to related resources − See notes in electronic version of presentation $ $ 15 February 2006 RMOUG Training Days 2006 2 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Agenda • Introduction to the Ruby Language • Introduction to the Rails Framework • Rails AJAX Support • Active Record • Rails with Oracle Database • When Rails Leads to “Riches” $ $ 15 February 2006 RMOUG Training Days 2006 3 Ruby Rails AJAX AR/ORM Oracle DB Conclusion What is Ruby? • Dynamic, Object-oriented Scripting Language − No primitives – everything is an object − No globals – simulate with methods on Object − Mix-ins allow functionality of multiple inheritance − Supports exception throwing and handling − Can name methods with operator symbols − Garbage Collector • Ruby Has Been Around for Some Time − 1993 Japan 1995/2000 World $ $ 15 February 2006 RMOUG Training Days 2006 4 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Basics of Ruby – Variables • Ruby’s Basic Variable Types − Instance Variables • @variableName − Class Variables • @@variableName − Global Variables • $variableName − Local Variables • variableName (begin with lowercase letter or _) − “Constants” • VariableName (begin with uppercase letter) $ $ 15 February 2006 RMOUG Training Days 2006 5 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Basics of Ruby: Control Syntax “if-then-else” “switch” case if <conditional> then . . . . . . elsif <conditional> then . . . else . . . end when <conditional> . . . when <conditional> . . . else . . . end $ $ 15 February 2006 RMOUG Training Days 2006 6 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Basics of Ruby: Loop Syntax “while” loop while <conditional> . . . end Ruby also supports iterators and provides the advantages of iterators. “do-while” loop until <conditional> . . . end “for” loop for <var> in <expr> do . . . end $ $ 15 February 2006 RMOUG Training Days 2006 7 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Basics of Ruby - Syntax • Methods − Use def keyword to define methods − Prefix “class” methods with self. • “Object” methods have no prefix on name − Convenience Accessor Methods • attr_accessor, attr_reader, attr_writer • Allowed But Not Required − Semicolons − Parentheses − Curly Braces $ $ 15 February 2006 RMOUG Training Days 2006 8 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Basics of Ruby – Comments • Single-line comments − # I am a comment. − Comment from # to end of line • Multi-line comments − =begin − I am a comment. − =end − =begin and =end must begin their respective lines $ $ 15 February 2006 RMOUG Training Days 2006 9 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Basics of Ruby – Reserved Words • These are some of Ruby’s Reserved Words − BEGIN, END, begin, end − if, else, elsif, case, then − and, or, not − false, true − do, redo, while − self, super − nil − __FILE__, __LINE__ $ $ 15 February 2006 RMOUG Training Days 2006 10 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Conventions of Ruby • Rails is heavily convention-based, but so is the language upon which it is based (Ruby) • Conventional Ruby − Variables (all types) begin with lowercase letter • Applies to global ($), instance (@), or class (@@) variables • Multiple words in name separated by underscore (_) − Class names and Constants begin with uppercase letter • Multiple words separated by each new word starting with uppercase letter − Method names treated like variable names (above) $ $ 15 February 2006 RMOUG Training Days 2006 11 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Basics of Ruby: Features of Dynamic Scripting Languages • Extensive regular expression support • Extensive string manipulation • Dynamic language features − Reflection − Add methods to objects at runtime − Add data members to objects at runtime $ $ 15 February 2006 RMOUG Training Days 2006 12 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Ruby Graphical Libraries • Non-web Graphical Libraries for Ruby − Tk − OpenGL − GTK − Fox − QT − VTK • No graphical libraries necessary for Rails! − You only need a standard web browser $ $ 15 February 2006 RMOUG Training Days 2006 13 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Ruby-Provided Libraries and Tools • Several of Rails’ strong points are actually directly or indirectly provided by Ruby − Core API / Built-in Functions/Library • http://www.ruby-doc.org/core/ − Ruby Standard Libraries • http://www.ruby-doc.org/stdlib/ − Ruby Standard Tools • Debugger, Profiler, irb − Other Ruby Tools • Ruby/DBI, Ruby Coverage, Ruby Interactive (ri), DamageControl, Builder, Distributed Ruby (DRb), REXML $ $ 15 February 2006 RMOUG Training Days 2006 14 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Select Ruby Core/Standard Libraries • Benchmark • Regexp • Delegator • Signal • ERB and ERB::Util • String • File • Test::Unit • IO • Thread • Logger • URI and URI::xxxxx • Math • YAML $ $ 15 February 2006 RMOUG Training Days 2006 15 Ruby Rails AJAX AR/ORM Oracle DB Conclusion What is Rails? • Database-driven Web Framework • Runs on Ruby • Open Source – MIT License • Stresses Convention over Configuration • Sub-Frameworks − Active Record − Action Pack • Action Controllers • Action Views − Action Mailer $ $ 15 February 2006 RMOUG Training Days 2006 16 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Do We Need Another Web Framework? • There are many web frameworks in many different programming languages: − Java • Struts, Tapestry, Velocity, Spring Framework, WebWork, Cocoon, Mentawai, RIFE, … many more … − PHP • PHP on TRAX, php.MVC, AjaxAC, blueshoes, … more … − Perl • Maypole, Catalyst, Mind Web, … more … − Python • Subway, CherryPy, Django, Zope, Webware for Python, Quixote − Ruby – Something other than Rails? • Nitro − Oracle-specific Alternatives • HTML DB, Project Raptor (SQL Developer) $ $ 15 February 2006 RMOUG Training Days 2006 17 Ruby Rails AJAX Type in URL Controller can call another controller method with redirect_to :action call Oracle DB Conclusion .rhtml View Template rendered as HTML page Invoke method View Template invokes controller method pointed to by start_form_tag :action (form_tag :action) or link_to :action AR/ORM Rende r new web page Model <model_name>.rb extends ActiveRecord::Base Controller <model_name>s_controller.rb $ Invoke method $ 15 February 2006 RMOUG Training Days 2006 The model classes are used by both the view templates and by the controllers Controller renders new web page either through same-name implicit .rhtml or via render :action call 18 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Convention Over Configuration • Rails generally favors assumed conventions over explicit configuration − Rails uses introspection when developers follow conventions • Effects of Emphasis on Convention − Dramatically reduces configuration files − Must know Rails’ assumptions/conventions − Rails most productive if your code and database schemas can conform to Rails’ conventions $ $ 15 February 2006 RMOUG Training Days 2006 19 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Some Rails Expected Conventions: Database and ActiveRecord • Several examples of convention over configuration in Database/ActiveRecord − Database table name is plural form of model name − Database primary key column named ‘id’ − Expected DB sequence for each table • <table_name>_seq − DB columns ending with _at and _on treated as TimeStamp and Date respectively $ $ 15 February 2006 RMOUG Training Days 2006 20 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Some Rails Expected Conventions: More Database and ActiveRecord • Several more examples of convention over configuration in Database/ActiveRecord − Name foreign key column in table with name of model upon which it depends followed by “_id” • Example: If table “programs” has foreign key to table “networks”, foreign key in “programs” pointing to “networks” should be named “network_id” − Join/Intersection table name combines names of two joined/intersected tables • Separate the table names with underscore • Table names being joined appear in alphabetical order $ $ 15 February 2006 RMOUG Training Days 2006 21 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Additional Rails Expected Conventions • Not all Rails conventions are DB/ActiveRecord − Template (.rhtml) matches calling action method name − Layout (.rhtml) matches calling controller − Directory structure of Rails applications − Test Files (Unit/Functional/Fixtures) • See this web page for more details on these Rails conventions − http://www.geocities.com/dustinmarx/SW/rails/conventions.html $ $ 15 February 2006 RMOUG Training Days 2006 22 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails URL Routing • Rails handles URL-based requests as specified in config/routes.rb • Default setting − map.connect ‘:controller/:action/:id’ movies_controller.rb class show() action method Model/DB Row ID $ $ 15 February 2006 RMOUG Training Days 2006 23 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails All-Application Functionality: Make Methods Available to Entire App • Provide filters/methods to all Controllers − …\app\controllers\application.rb − ApplicationController < ActionController::Base • Provide methods to all View Template helpers − …\app\helpers\application_helper.rb − module ApplicationHelper • Provide functions to all Models − Place functions in file in lib − Place reference to file in config/environment.rb − Include module in ActiveRecord::Base $ $ 15 February 2006 RMOUG Training Days 2006 24 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Configuration • Rails has very little configuration − Convention/introspection more commonly used − .yml files rather than .xml files − database.yml, Test Fixture .yml files, etc. • database.yml development: adapter: oci host: orcl username: scott password: tiger $ $ 15 February 2006 RMOUG Training Days 2006 25 AJAX AR/ORM Oracle DB Conclusion RailsRails Conventional Directory Structure Application Root Level Ruby <yourApplicationName> app Application’s significant and specific code components Storage location for Rails components $ config db doc lib Configuration files (database.yml, etc.) log public script test vendor Storage location for Rails app’s log files Available to web server Rails generation and other scripts Unit/functional tests; fixtures/mocks Third-party/COTS libraries Rails documentation (RDoc) Own, application-specific libraries $ 15 February 2006 RMOUG Training Days 2006 26 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Conventional Directory Structure app, public, and test Sub-Directories app controllers helpers models views public images javascripts stylesheets test fixtures functional mocks development layouts test unit $ $ 15 February 2006 RMOUG Training Days 2006 27 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Models: Standard Validations Rails supports many common validations with the standard validations below. Override the model’s validate() method to implement your own custom validation. • validates_acceptance_of • validates_inclusion_of • validates_associated • validates_length_of • validates_confirmation_of • validates_numericality_of • validates_each • validates_presence_of • validates_exclusion_of • validates_size_of • validates_format_of • validates_uniqueness_of All validations shown in blue are discussed in more detail in the slide notes. $ $ 15 February 2006 RMOUG Training Days 2006 28 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Controller • “Controls” flow − Methods in Controller class are “actions” − Renders view or redirects to another action − Actions should end with single render or redirect_to • The render Possibilities − − − − − Render action Render partial Render template Render file Render text $ $ 15 February 2006 RMOUG Training Days 2006 29 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Some Objects of the Controller • Requests − request Accessor • Parameters − params Hash • Write/read cookies − cookies Attribute • Rails Sessions − @session Hash $ $ 15 February 2006 RMOUG Training Days 2006 30 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Controllers: Filters • Share before (pre) and after (post) processing between multiple controllers • Filter Methods − after_filter, prepend_after_filter − before_filter, prepend_before_filter − around_filter, prepend_around_filter • Filter Conditions $ − :only − :except $ 15 February 2006 RMOUG Training Days 2006 31 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Template Files – View • “Ruby/Rails Server Pages” − Embed Ruby script in HTML with <% and <%= tags • • • • Referred to as “Embedded Ruby” (ERb) Similar to JSP and ASP! Normally close scriptlet/ERb code with %> Close ERb code with (hyphen) -%> to ignore white space − .rhtml files (rather than .html files) − Use components, partials, and layouts − Alternative approach is Builder approach • See later slide $ $ 15 February 2006 RMOUG Training Days 2006 32 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Templates/Controller Connection • Controller renders similarly named view or … − :action − :template − :file • View shares access to all of controller’s instance variables • View shares access to significant objects: − headers, params, request, response, session • View’s controller object allows access to all of controller’s methods $ $ 15 February 2006 RMOUG Training Days 2006 33 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Built-in HTML Aids • html_escape() or h() method − Escapes HTML characters • sanitize() − Escapes HTML tags and JavaScript links that are most often associated with malicious code $ $ 15 February 2006 RMOUG Training Days 2006 34 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Views: Formatting Helpers • Numerous built-in view helpers for common view- and format-related functionality • Small sampling of these built-in view helpers: − number_to_concurrency() − number_to_percentage() − number_with_delimiter() − number_with_precision() − markdown() − textile() $ $ 15 February 2006 RMOUG Training Days 2006 35 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Views: More Helpers • link_to_unless_current − Render links for all site pages except one currently displayed • Pagination for multiple entries − Controller’s paginate() − View’s pagination_links() • Form Helpers • Field Helpers − Including file upload support $ $ 15 February 2006 RMOUG Training Days 2006 36 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Views and DRY: Layout, Partials, and Components • Layouts − Provide layout/format of web page − Think Struts’ early template library • Partials − Partial templates designed to be used by multiple pages • Components − Shared template/controller functionality $ $ 15 February 2006 RMOUG Training Days 2006 37 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Views: Builder Approach • Templates are not only Rails approach for views • Use Builder to write XML − Programmatically build up view − API produces XML similar to approach PL/SQL Web Toolkit uses to produce HTML • Ruby’s dynamic method support required for XML production − Method names you specify for builder generally produce XML tags with same name • Use tag! in cases of reserved method names $ $ 15 February 2006 RMOUG Training Days 2006 38 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails – Action Mailer • Framework/layer supporting outgoing and incoming email services • Configuring Action Mailer − …/config/environment.rb − …/config/environments/ • development.rb, production.rb, and test.rb • Sending E-mail − ruby script/generate mailer … − Mailer is stored in models directory − E-mail templates stored in views directory • Receiving E-mail − Implement receive() method to receive e-mail messages $ $ 15 February 2006 RMOUG Training Days 2006 39 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails – Web Services • Rails Action Web Service − SOAP / XML-RPC − Create API Definition • Extend ActionWebService::API::Base • api_method (:expects and :returns) − Dispatching ties client requests to Rails implementation − Not fully compliant with W3C specifications • Rails and REST − “REST on Rails” • http://www.xml.com/pub/a/2005/11/02/rest-on-rails.html $ $ 15 February 2006 RMOUG Training Days 2006 40 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Scaffolding • Temporary framework to support construction of new web application • Rapidly build simple web-based CRUD support • Can add features and appearance/presentation improvements as desired $ $ 15 February 2006 See definition of term ‘scaffolding’ at http://www.answers.com/topic/scaffolding RMOUG Training Days 2006 41 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails Built-in Testing Framework • Extends Ruby’s Test::Unit testing framework − Think JUnit, utPLSQL, and other “N”-Unit Test Frameworks • Scripts generate test classes automatically • Test-specific Database specified in database.yml • Standard and custom assertions • Fixtures • Mock Objects • A Guide to Testing Rails − http://manuals.rubyonrails.com/read/book/5 $ $ 15 February 2006 RMOUG Training Days 2006 42 Ruby Rails AJAX AR/ORM Oracle DB Conclusion More on Rails Built-in Testing • “Unit” Testing − Refers to testing of Rails’ model classes − Fixtures describe initial contents of model − setup Method • “Functional” Testing − Refers to testing of Rails’ controller classes − setup and teardown Methods − HTTP Request methods (such as get and post) − Controller Assertions and Controller Variables $ $ 15 February 2006 RMOUG Training Days 2006 43 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails/Ruby and rake • rake: Something like make − Implemented in Ruby programming language − http://rake.rubyforge.org/ • Using rake − rake --tasks • Show options available with rake − rake appdoc • Produces Rails application’s documentation − rake stats • Displays lines, LOC, # Classes, # Methods, M/C, LOC/M for Helpers, Controllers, Components, Models, Unit Tests, and Libraries $ $ 15 February 2006 RMOUG Training Days 2006 44 Ruby Rails AJAX AR/ORM Oracle DB Conclusion AJAX • AJAX is … − Asynchronous JavaScript And XML − Collections of technologies for creating interactive web applications • HTML/XHTML/CSS • XMLHttpRequest − “de facto” Standard (MSIE, Mozilla Browsers, Safari, Opera) • Significant Piece of “Web 2.0” / DHTML − Catchy term for the above combination of technologies $ $ 15 February 2006 RMOUG Training Days 2006 45 Ruby Rails AJAX AR/ORM Oracle DB Conclusion So What’s the Big Deal about AJAX? • Richer and more dynamic web applications − Asynchronous means non-blocking − Small portion of page can update based on server query without complete reloading of the page − Change appearance/behavior of portion of web page • Server can pass XML, HTTP, JavaScript, or other text back to client − Hides some of the rigidness of the request/response model $ $ 15 February 2006 RMOUG Training Days 2006 46 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails: AJAX • Makes use of Prototype and script.aculo.us JavaScript libraries − http://prototype.conio.net/ − http://script.aculo.us/ • Use one of these three options: − <%= javascript_include_tag :defaults %> − <%= javascript_include_tag ‘prototype’ %> − <%= define_javascript_functions %> $ $ 15 February 2006 RMOUG Training Days 2006 47 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails and AJAX: Key Methods • link_to_remote − Link pointing to action to be invoked • form_remote_tag − Send entire form’s information to server • observe_field − Invoke server action based on certain form element − observe_form is similar but for entire form • periodically_call_remote − Periodically invoke server action $ $ 15 February 2006 RMOUG Training Days 2006 48 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails ORM: Active Record • Active Record − Rails Object-Relational Mapping − Based on Martin Fowler’s Active Record architecture pattern − Uses Single Table Inheritance ORM Approach − Makes heavy use of database schema conventions • Can override most of these in Ruby classes − Built-in support for standard CRUD operations • No SQL needed – even very little Ruby code required − Allows for customized SQL $ $ 15 February 2006 RMOUG Training Days 2006 49 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails: Models and Tables – 1:1 person.rb address.rb class Person < ActiveRecord::Base has_one :address end class Address < ActiveRecord::Base belongs_to :person end Oracle Database People id … $ $ 15 February 2006 Addresses person_id … One address per person and one person per address. RMOUG Training Days 2006 50 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails: Models and Tables – 1:M person.rb address.rb class Person < ActiveRecord::Base has_many :addresses end class Address < ActiveRecord::Base belongs_to :person end Oracle Database People id … $ $ 15 February 2006 Addresses person_id … Each person may have more than one address, but there is only one person at a particular address. RMOUG Training Days 2006 51 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails: Models and Tables – M:N person.rb address.rb class Person < ActiveRecord::Base has_and_belongs_to_many :addresses end class Address < ActiveRecord::Base has_and_belongs_to_many :people end Oracle Database People id … $ $ 15 February 2006 Addresses_People address_id person_id Addresses id … Many people may live at a particular address and a person may have many addresses. RMOUG Training Days 2006 52 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails and ActiveRecord: SQL Flexibility • Finder Methods − find (set your WHERE :conditions) − find_by_sql (specify entire SQL select) • Module ActiveRecord::ConnectionAdapter s::DatabaseStatements.rb − execute(), insert(), update(), delete() − select_all(), select_one(), select_value(), select_values() $ $ 15 February 2006 RMOUG Training Days 2006 53 Ruby Rails AJAX AR/ORM Oracle DB Conclusion ActiveRecord Transactions • ActiveRecord supports ACID transactions • Examples ModelClass.transaction do . . . model/DB operations . . . end ModelClass.transaction (ObjectA, ObjectB) do . . . model/DB operations . . . end DB-only Transaction DB and Objects Transaction • Distributed two-phase transactions NOT supported $ $ 15 February 2006 RMOUG Training Days 2006 54 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Database “Limitations” of Rails/ActiveRecord Approach • No standard support for stored procedures − Not the “Rails way” • Requires single column primary key − Integer column named ‘id’ − No composite keys allowed • Rails Assumptions can make some DB features ‘more tricky’ to use in the Rails applications − No triggers or constraints (including referential integrity) considered in ActiveRecord conventions • Lacks distributed two-phase commit support $ $ 15 February 2006 RMOUG Training Days 2006 55 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails and the Oracle Database • Rails is typically presented in conjunction with MySQL database − But can support any database with Ruby adapter • Oracle OCI8 adapter for Ruby is available − http://rubyforge.org/projects/ruby-oci8/ • Rails support for Oracle doesn’t seem (at least to me) to be as robust as that for MySQL − Many features of Rails are supported on Oracle DB $ $ 15 February 2006 RMOUG Training Days 2006 56 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle 1. Download RubyGems 2. Install Rails with RubyGems 3. Create structure for new Rails web application 4. Run Web Server 5. Modify database.yml file for Oracle DB 6. Ensure Availability of Ruby/Oracle interface 7. Verify OCI client library in appropriate path 8. Create model and controller classes in Ruby 9. Employ Rails Scaffolding 10. Create necessary database sequences 11. Ensure column (preferably primary key) is named ID Single Step Possible $ $ 15 February 2006 RMOUG Training Days 2006 57 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #1: Download RubyGems • RubyGems is packaging and distribution format for Ruby libraries and applications • Access download and the instructions at http://download.rubyonrails.com/ • RubyGems Manuals − http://docs.rubygems.org/ − http://docs.rubygems.org/read/chapter/3 $ $ 15 February 2006 RMOUG Training Days 2006 58 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #2: Install Rails with RubyGems • gem install rails --includedependencies • Ensure that Ruby executable is correctly included in path − I had to add \bin (for c:\ruby\bin) and place semicolon to separate entries $ $ 15 February 2006 RMOUG Training Days 2006 59 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #3: Create Structure for New Rails App • Rails will create necessary directory structure and key files for your new application − Syntax: rails /<<directories>>/<app_dir> − Example: rails /rmoug/td2006/simpleapp • Creates (among other things): − Folders for application’s controllers, models, and views − Scripts for running Rails and the application on Rails − Configuration and environment support − Test support directories and files $ $ 15 February 2006 RMOUG Training Days 2006 60 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #4: Running the Web Server • WEBrick Web Server comes with Rails • RunWEBrick with this command from newly created Rails application directory: − ruby script/server • Verify successful web server start with URL: − Syntax: http://<IP_Address>:<port>/ − Example: http://127.0.0.1:3000/ • IP address is of machine on which server is run and likely will differ from that shown above • Port may differ (default is 3000) − Use –p or --port for different port $ $ 15 February 2006 ruby script/server --help displays help RMOUG Training Days 2006 61 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #5: Modify database.yml File • database.yml file located in new Rails application’s config directory • Default database specified in this file is MySQL • Set file similarly to that shown below: Default database.yml for MySQL development: adapter: mysql database: rails_development host: localhost username: root password: $ database.yml for Oracle development: adapter: oci host: orcl username: scott password: tiger $ 15 February 2006 RMOUG Training Days 2006 62 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #6: Access Ruby/Oracle Interface • Ruby/OCI8 − Ruby interface for Oracle using OCI8 − Download relatively small file with Ruby code − Run this downloaded Ruby script with Ruby executable − http://rubyforge.org/projects/ruby-oci8/ $ $ 15 February 2006 RMOUG Training Days 2006 63 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #7: OCI Client Library • Ensure that OCI client library is in appropriate location: − Windows • Directory with oci.dll added to PATH environment variable − Unix/Linux • Directory with libclntsh.so added to LD_LIBRARY_PATH $ $ 15 February 2006 RMOUG Training Days 2006 64 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #8: Create Model and Controller • Use Rails scripts to create model and controller classes in Ruby language − Model • ruby script/generate model <model_class> − Controller • ruby script/generate controller <model_class> − Examples • ruby script/generate model dvd • ruby script/generate controller dvd $ $ 15 February 2006 RMOUG Training Days 2006 65 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #9: Employ Rails Scaffolding • Rails Scaffolding does the heavy lifting for you! − Though the view leaves something to be desired • Automatically supports CRUD operations for models Create and database tables meeting Rails conventions Read − Model and database tables mapped together by names • Table name plural version of singular model name Update Delete − Appropriate sequences exist − Tables have column called ‘ID’ • Employ Rails scaffolding with single Ruby statement in controller class: $ − scaffold :<model_class> − Example: scaffold :dvd $ 15 February 2006 RMOUG Training Days 2006 66 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: Combine Steps #8 and #9 • Now can perform steps #8 and #9 all at once: − ruby script/generate scaffold <model_class> • This single statement does all of the following: − Creates Model • Same as ruby script/generate model <model_class> − Creates Controller • Same as ruby script/generate controller <model_class> − Creates Scaffold and Views • Similar to adding scaffold: <model_class> in controller • Advantage: Can inspect scaffold/view code with newer approach $ $ 15 February 2006 RMOUG Training Days 2006 67 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #10: Add Necessary DB Sequences • Need to create sequences in Oracle database − This is another Rails-expected convention − Through Rails 0.13… • CREATE SEQUENCE rails_sequence; − After Rails 0.13… • CREATE SEQUENCE <tablename>_seq; − (for each table) • See Rails Ticket #1798 − http://dev.rubyonrails.org/ticket/1798 $ $ 15 February 2006 RMOUG Training Days 2006 68 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Starting with Rails and Oracle: #11: Name Column ‘ID’ • Name at least one column, preferably the primary key, of table(s) with name ‘ID’ − Another Rails convention − Can be overridden with set_primary_key in Ruby model class $ $ 15 February 2006 RMOUG Training Days 2006 69 Ruby Rails AJAX AR/ORM Oracle DB Conclusion The Rails to Riches: Application Characteristics • Rails Is Best For: − Prototypes − Web-only or Web-dominant applications − Web-based database access tools • Rails is Not As Preferable When: − Application is not web-based − Developers have little control over fairly complex database and database conventions • Legacy database systems often fit into this category $ $ 15 February 2006 RMOUG Training Days 2006 70 Ruby Rails AJAX AR/ORM Oracle DB Conclusion The Rails to Riches: Organizational Characteristics Organization/Personnel Skills/Preferences Play Role in Success with Rails Traits Favoring Use of Rails Traits Favoring Rails Alternatives Prefer agile development Prefer traditional development Prefer open source Prefer commercial products/support Prefer dynamic languages Prefer statically typed languages Prefer “bleeding edge” Prefer time-tested / proven Prefer/Enforce naming conventions Prefer/Enforce configuration Common coupled SW/DB control No common SW/DB control Prefer Simple DB Features Prefer rich/complex DB Features $ $ 15 February 2006 RMOUG Training Days 2006 71 Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails and the Future • Rails’ popularity is rapidly growing − Expect it to continue to grow in future • Rails (hopefully) will impact web development − J2EE/.NET can adopt some ideas from Rails − Rails can provide J2EE/.NET developers with own inspiration • Biggest threat to Rails’ success − The ‘Next Rails’ (do we know what that will be?) $ $ 15 February 2006 RMOUG Training Days 2006 72 APPENDIX Riding Rails to Ruby and Riches Background Materials and Supplemental Slides $ $ Please see the 24-page white paper associated with this presentation for an extensive list of references and resources related to Ruby on Rails. APPENDIX: Acronyms Acronyms • CRUD – Create, Retrieve, Update, Delete • DIY – Do It Yourself • DRY – Don’t Repeat Yourself • ERb – Embedded Ruby • LAMP – Linux, Apache, MySQL, Perl/PHP/Python • MVC – Model-View-Controller • POLS – Principle of Least Surprise • RoR – Ruby on Rails • YAML – YAML Ain’t Markup Language $ $ 15 February 2006 RMOUG Training Days 2006 74 APPENDIX: References and Resources Riding Rails to Ruby and Riches: References and Resources • The following set of slides contain links to online articles that describe different aspects of Rails − See associated white paper for another set of references and resources − See notes for individual slides in this presentation for relevant online references − These links are good for exposure to Rails • For thorough background on Rails, see book: $ − Agile Web Development with Rails $ 15 February 2006 RMOUG Training Days 2006 75 APPENDIX: References and Resources References and Resources: Ruby on Rails How-Tos/Licenses • Rails Documentation − http://documentation.rubyonrails.com/ • Howtos Database in Rails Wiki − http://wiki.rubyonrails.com/rails/show/HowtosDatabase • Howtos File Access in Rails Wiki − http://wiki.rubyonrails.com/rails/show/HowtosFiles • MIT License − http://www.opensource.org/licenses/mit-license.php $ $ 15 February 2006 RMOUG Training Days 2006 76 APPENDIX: References and Resources References and Resources: Curt Hibbs on Ruby on Rails • Rolling With Ruby on Rails, Part 1 − http://www.onlamp.com/pub/a/onlamp/2005/01/20/rails.html • Rolling With Ruby on Rails, Part 2 − http://www.onlamp.com/pub/a/onlamp/2005/03/03/rails.html • What is Ruby on Rails − http://www.onlamp.com/pub/a/onlamp/2005/10/13/what_is_rai ls.html • AJAX on Rails $ − http://www.onlamp.com/pub/a/onlamp/2005/06/09/rails_ajax.ht ml $ 15 February 2006 RMOUG Training Days 2006 77 APPENDIX: References and Resources References and Resources: More on Rails • Ruby on Rails in the Enterprise Toolbox − http://www.javaranch.com/journal/200601/rails.htm l • Ruby on Rails E-mail Forum − http://www.ruby-forum.com/forum/3 • Ruby on Rails Newcomers FAQ − http://www.railsfaq.org/ $ $ 15 February 2006 RMOUG Training Days 2006 78 APPENDIX: References and Resources References and Resources: Rails API Documentation • Ruby on Rails Edge Documentation: Files − http://railsmanual.org/doc/list?type=files • Ruby on Rails Edge Documentation: Classes − http://railsmanual.org/doc/list?type=classes • Ruby on Rails Edge Documentation: Methods − http://railsmanual.org/doc/list?type=methods • Rails Manual: ActiveRecord − http://railsmanual.org/class/ActiveRecord::Base $ $ 15 February 2006 RMOUG Training Days 2006 79 APPENDIX: References and Resources References and Resources: Rails Deployment • This topic was not covered in the presentation, but is very important − Real Lessons for Rails Deployment • http://duncandavidson.com/essay/2005/12/railsdeployme nt − Deploying Rails with Apache 2 • http://duncandavidson.com/essay/2006/01/railsonapache − Deploying Rails with LightTPD • http://duncandavidson.com/essay/2005/12/railsonlighty $ $ 15 February 2006 RMOUG Training Days 2006 80 APPENDIX: References and Resources References and Resources: Ruby • Programming Ruby: The Pragmatic Programmer’s Guide − http://whytheluckystiff.net/ruby/pickaxe/ • The Ruby Programming Language − http://www.informit.com/articles/article.asp?p=18225 • Why’s (poignant) guide to Ruby − http://poignantguide.net/ruby/ • Ruby off the Rails − http://www-128.ibm.com/developerworks/library/jruby/?ca=dgr-lnxw01RubyOffRails $ $ 15 February 2006 RMOUG Training Days 2006 81 APPENDIX: Cheat Sheets References and Resources: Rails-Related Cheat Sheets • Ruby on Rails – A Cheat Sheet (Blaine Kendall) − http://www.blainekendall.com/uploads/RubyOnRails-CheatsheetBlaineKendall.pdf • What Goes Where (Amy Hoy) − http://www.slash7.com/cheats/rails_files_cheatsheet.pdf • ActiveRecord Relationships (Amy Hoy) − http://www.slash7.com/cheats/activerecord_cheatsheet.pdf • Form Helpers (Amy Hoy) − http://www.slash7.com/cheats/form_helpers.pdf • What’s Ajax? (Amy Hoy) − http://www.slash7.com/cheats/whats_ajax_cheatsheet.pdf $ $ 15 February 2006 RMOUG Training Days 2006 82 APPENDIX: Cheat Sheets References and Resources: More Rails-Related Cheat Sheets • Ruby on Rails Cheat Sheet − http://www.ilovejackdaniels.com/ruby-on-rails/ruby-on-railscheat-sheet/ • Rails Migration Cheat Sheet − http://garrettsnider.backpackit.com/pub/367902 • JavaScript Cheat Sheet − http://www.ilovejackdaniels.com/javascript/javascript-cheatsheet/ • CSS Cheat Sheet − http://www.ilovejackdaniels.com/css/css-cheat-sheet/ $ $ 15 February 2006 RMOUG Training Days 2006 83 APPENDIX: Q&A Is Rails Only Hype? • No. • There are many substantial and innovative features of Rails. These include scaffolding, built-in Ajax support, simple object-relational mapping (ORM), and convenient MVC support. • Enthusiasm in Rails will likely lead to enhancements in these and other areas. $ $ 15 February 2006 RMOUG Training Days 2006 84 APPENDIX: Q&A Will Rails Replace Java / .NET? • In some niche areas – DB-driven web apps • Rails addresses some aspects of web development commonly implemented in Java/J2EE or .NET, but it does not readily and completely replace all of the enterprise functionality these frameworks provide. For example, not everything is web-based! • Rails will likely be used in some parts of applications along with J2EE, .NET, and other technologies. SOA makes this even more likely. • C/C++, Java, .NET, Perl, PHP, Python, etc. are not going away $ $ 15 February 2006 RMOUG Training Days 2006 85 APPENDIX: Q&A Is Rails Just the Flavor of the Month? • Time will tell for certain, but I think it is more than the “flavor of the month” • Rails offers enough innovative features that it will likely continue to have success similar to other technologies that were once the “hottest” thing around and are still widely used: − Java / J2EE, .NET, Python − Spring Framework − Struts $ $ 15 February 2006 RMOUG Training Days 2006 86 APPENDIX: Q&A What is the Best Thing About Rails? • Depends who you ask: − Built-in Ajax support − ActiveRecord ORM − Scaffolding − Tightly integrated stack − Not having to compile − No license cost − Encouragement of best practices − Convention over configuration − Many common “web things” made simple $ $ 15 February 2006 RMOUG Training Days 2006 87 APPENDIX: Q&A What’s the Best Way to Learn Rails? • Introducing Self to Rails / Curiosity − Paper associated with this presentation − Curt Hibbs’ articles listed on previous slide • Possibly consider Rails for web development − Read links in this presentation and paper, especially in areas of Rails that most appeal to you • Likely to use Rails for significant web development − Read book Agile Web Development with Ruby on Rails • SoftPro has copies of this book for sale in conference’s Exhibition Hall − Additional books to be available soon $ $ 15 February 2006 RMOUG Training Days 2006 88