1 / 88

Riding Rails to Ruby and Riches

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/

Télécharger la présentation

Riding Rails to Ruby and Riches

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Riding Rails to Ruby and Riches Dustin Marx Bill Jackson

  2. 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 RMOUG Training Days 2006

  3. 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” RMOUG Training Days 2006

  4. 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 RMOUG Training Days 2006

  5. 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) RMOUG Training Days 2006

  6. Ruby Rails AJAX AR/ORM Oracle DB Conclusion “if-then-else” “switch” if <conditional> then . . . elsif <conditional> then . . . else . . . end case . . . when <conditional> . . . when <conditional> . . . else . . . end Basics of Ruby: Control Syntax RMOUG Training Days 2006

  7. Ruby Rails AJAX AR/ORM Oracle DB Conclusion “while” loop “do-while” loop until <conditional> . . . end while <conditional> . . . end “for” loop for <var> in <expr> do . . . end Basics of Ruby: Loop Syntax Ruby also supports iterators and provides the advantages of iterators. RMOUG Training Days 2006

  8. 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 RMOUG Training Days 2006

  9. 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 RMOUG Training Days 2006

  10. 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__ RMOUG Training Days 2006

  11. 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) RMOUG Training Days 2006

  12. 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 RMOUG Training Days 2006

  13. 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 RMOUG Training Days 2006

  14. 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 RMOUG Training Days 2006

  15. Benchmark Delegator ERB and ERB::Util File IO Logger Math Regexp Signal String Test::Unit Thread URI and URI::xxxxx YAML Ruby Rails AJAX AR/ORM Oracle DB Conclusion Select Ruby Core/Standard Libraries RMOUG Training Days 2006

  16. 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 RMOUG Training Days 2006

  17. 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) RMOUG Training Days 2006

  18. Ruby Rails AJAX AR/ORM Oracle DB Conclusion .rhtml View Template rendered as HTML page The model classes are used by both the view templates and by the controllers Type in URL Render new web page Invoke method View Template invokes controller method pointed to by start_form_tag :action (form_tag :action) or link_to :action Model <model_name>.rb extends ActiveRecord::Base Controller renders new web page either through same-name implicit .rhtml or via render :action call Controller can call another controller method with redirect_to :action call Controller <model_name>s_controller.rb Invoke method RMOUG Training Days 2006

  19. 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 RMOUG Training Days 2006

  20. 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 RMOUG Training Days 2006

  21. 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 RMOUG Training Days 2006

  22. 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 RMOUG Training Days 2006

  23. 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 RMOUG Training Days 2006

  24. 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 RMOUG Training Days 2006

  25. 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 RMOUG Training Days 2006

  26. Ruby Rails AJAX AR/ORM Oracle DB Conclusion <yourApplicationName> app Application’s significant and specific code components Storage location for Rails components config Configuration files (database.yml, etc.) db doc Rails documentation (RDoc) lib Own,application-specific libraries log Storage location for Rails app’s log files public Available to web server script Rails generation and other scripts test Unit/functional tests; fixtures/mocks vendor Third-party/COTS libraries Rails Conventional Directory StructureApplication Root Level RMOUG Training Days 2006

  27. Ruby Rails AJAX AR/ORM Oracle DB Conclusion app test public images controllers test unit javascripts fixtures functional mocks development stylesheets helpers models views layouts Rails Conventional Directory Structureapp, public, and test Sub-Directories RMOUG Training Days 2006

  28. validates_acceptance_of validates_associated validates_confirmation_of validates_each validates_exclusion_of validates_format_of validates_inclusion_of validates_length_of validates_numericality_of validates_presence_of validates_size_of validates_uniqueness_of 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. All validations shown in blue are discussed in more detail in the slide notes. RMOUG Training Days 2006

  29. 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 RMOUG Training Days 2006

  30. 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 RMOUG Training Days 2006

  31. 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 RMOUG Training Days 2006

  32. 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 .htmlfiles) • Use components, partials, and layouts • Alternative approach is Builder approach • See later slide RMOUG Training Days 2006

  33. 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 RMOUG Training Days 2006

  34. 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 RMOUG Training Days 2006

  35. 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() RMOUG Training Days 2006

  36. 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 RMOUG Training Days 2006

  37. 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 RMOUG Training Days 2006

  38. 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 RMOUG Training Days 2006

  39. Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails – Action Mailer • Framework/layer supporting outgoing and incoming e-mail 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 RMOUG Training Days 2006

  40. 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 RMOUG Training Days 2006

  41. 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 See definition of term ‘scaffolding’ at http://www.answers.com/topic/scaffolding RMOUG Training Days 2006

  42. 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 RMOUG Training Days 2006

  43. 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 RMOUG Training Days 2006

  44. 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 RMOUG Training Days 2006

  45. 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 RMOUG Training Days 2006

  46. 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 RMOUG Training Days 2006

  47. 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 %> RMOUG Training Days 2006

  48. 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 RMOUG Training Days 2006

  49. 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 RMOUG Training Days 2006

  50. Ruby Rails AJAX AR/ORM Oracle DB Conclusion Rails: Models and Tables – 1:1 person.rb class Person < ActiveRecord::Base has_one :address end address.rb class Address < ActiveRecord::Base belongs_to :person end Oracle Database People id … Addresses person_id … One address per person and one person per address. RMOUG Training Days 2006

More Related