Intro to Ruby on Rails


Published on

A brief introduction to Ruby on Rails.

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Intro to Ruby on Rails

  1. 1. Intro to Ruby on Rails <ul><li>by Mark Menard </li></ul><ul><li>Vita Rara, Inc. </li></ul>
  2. 2. Ruby © Vita Rara, Inc. “ I always knew one day Smalltalk would replace Java. I just didn’t know it would be called Ruby.” - Kent Beck, Creator of “Extreme Programming”
  3. 3. Ruby on Rails <ul><li>Ruby on Rails is astounding. Using it is like watching a kung-fu movie, where a dozen bad-ass frameworks prepare to beat up the little newcomer only to be handed their asses in a variety of imaginative ways. </li></ul><ul><li>-Nathan Torkington, </li></ul><ul><li> O'Reilly Program Chair for OSCON </li></ul>© Vita Rara, Inc.
  4. 4. The Elevator Pitch <ul><li>Ruby on Rails is an open-source web framework that is optimized for programmer happiness and sustainable productivity. It lets you write beautiful code by favoring convention over configuration. </li></ul>© Vita Rara, Inc.
  5. 5. Overview <ul><li>Rails is a full stack web framework </li></ul><ul><ul><li>Model: ActiveRecord </li></ul></ul><ul><ul><ul><li>ORM </li></ul></ul></ul><ul><ul><ul><li>database connectivity </li></ul></ul></ul><ul><ul><ul><li>Database schema management </li></ul></ul></ul><ul><ul><li>View: ActiveView </li></ul></ul><ul><ul><ul><li>View layer </li></ul></ul></ul><ul><ul><ul><li>Templates </li></ul></ul></ul><ul><ul><li>Controller: ActionController </li></ul></ul><ul><ul><ul><li>Web controller framework </li></ul></ul></ul><ul><ul><ul><li>Manages web integration </li></ul></ul></ul><ul><ul><li>Active Support </li></ul></ul><ul><ul><ul><li>Extensions to Ruby to support web development </li></ul></ul></ul><ul><ul><li>Integrated Ajax support </li></ul></ul>© Vita Rara, Inc.
  6. 6. The Rails Philosophy <ul><li>Ruby - less and more readable code, shorter development times, simple but powerful, no compilation cycle. </li></ul><ul><li>Convention over configuration </li></ul><ul><li>Predefined directory structure, and naming conventions </li></ul><ul><li>Best practices: MVC, DRY, Testing </li></ul><ul><li>Almost everything in Rails is Ruby code (SQL and JavaScript are abstracted) </li></ul><ul><li>Integrated AJAX support. Web services with REST. </li></ul><ul><li>Good community, tools, and documentation </li></ul><ul><li>Extracted from a real application: Basecamp </li></ul>© Vita Rara, Inc.
  7. 7. Rake: The Ruby Make <ul><li>Rake lets you define a dependency tree of tasks to be executed. </li></ul><ul><li>Rake tasks are loaded from the file Rakefile </li></ul><ul><li>Rake automates and simplifies creating and managing the development of a Rails project. </li></ul>© Vita Rara, Inc.
  8. 8. Environments <ul><li>Rails has support for multiple execution environments. </li></ul><ul><li>Environments encapsulate database settings and other configuration. </li></ul><ul><li>Typical environments </li></ul><ul><ul><li>Development </li></ul></ul><ul><ul><li>Test </li></ul></ul><ul><ul><li>Production </li></ul></ul><ul><li>Additional environments are easy to add. </li></ul>© Vita Rara, Inc.
  9. 9. Migrations <ul><li>Managing Schema Evolution </li></ul>
  10. 10. Managing Data Schemas <ul><li>Rails includes support for migrations to manage the evolution of your database schema. </li></ul><ul><ul><li>No need to write SQL. </li></ul></ul><ul><ul><li>Migrations use a database independent Ruby API. </li></ul></ul><ul><ul><li>Migrations are Ruby scripts giving you access to the full power of the language. </li></ul></ul>© Vita Rara, Inc.
  11. 11. Migrations <ul><li>Typical migration functions: </li></ul><ul><ul><li>create_table </li></ul></ul><ul><ul><li>add_column </li></ul></ul><ul><ul><li>change_column </li></ul></ul><ul><ul><li>rename_column </li></ul></ul><ul><ul><li>rename_table </li></ul></ul><ul><ul><li>add_index </li></ul></ul>© Vita Rara, Inc.
  12. 12. Migration Example © Vita Rara, Inc. create_table &quot;users&quot; , :force => true do |t| t.string :login, :email, :remember_token t.string :salt, :crypted_password, :limit => 40 t.timestamps t.datetime :remember_token_expires_at end
  13. 13. ActiveRecord <ul><li>Modeling the World </li></ul>
  14. 14. Fundamentals <ul><li>One database table maps to one Ruby class </li></ul><ul><li>Table names are plural and class names are singular </li></ul><ul><li>Database columns map to attributes, i.e. get and set methods, in the model class </li></ul><ul><li>All tables have an integer primary key called id </li></ul><ul><li>Database tables are created with migrations </li></ul>© Vita Rara, Inc.
  15. 15. ActiveRecord Model Example © Vita Rara, Inc. create_table &quot;persons&quot; do |t| t.string :first_name, last_name t.timestamps end class Person < ActiveRecord::Base end p = p.first_name = ‘Mark’ p.last_name = ‘Menard’
  16. 16. CRUD <ul><li>Create: create, new </li></ul><ul><li>Read: find, find_by_<attribute> </li></ul><ul><li>Update: save, update_attributes </li></ul><ul><li>Delete: destroy </li></ul>© Vita Rara, Inc.
  17. 17. Finding Models <ul><li>User.find(:first) </li></ul><ul><li>User.find(:all) </li></ul><ul><li>User.find(1) </li></ul><ul><li>User.find_by_login(‘mark’) </li></ul><ul><li>User.find(:all, :conditions => [ “login = ? AND password = ?”, login, password]) </li></ul>© Vita Rara, Inc.
  18. 18. Advanced Finding <ul><li>Finders also support: </li></ul><ul><ul><li>:limit </li></ul></ul><ul><ul><li>:offset </li></ul></ul><ul><ul><li>:order </li></ul></ul><ul><ul><li>:joins </li></ul></ul><ul><ul><li>:select </li></ul></ul><ul><ul><li>:group </li></ul></ul>© Vita Rara, Inc.
  19. 19. Update <ul><li>user = User.find(1) </li></ul><ul><li>user.first_name = ‘Mark’ </li></ul><ul><li>user.last_name = ‘Menard’ </li></ul><ul><li>! </li></ul>© Vita Rara, Inc.
  20. 20. Transactions <ul><li>Account.transaction do </li></ul><ul><li>account1.deposit(100) </li></ul><ul><li>account2.withdraw(100) </li></ul><ul><li>end </li></ul>© Vita Rara, Inc.
  21. 21. ActiveRecord Associations <ul><li>Joining Things Together </li></ul>
  22. 22. ActiveRecord Associations <ul><li>Two primary types of associations: </li></ul><ul><ul><li>belongs_to </li></ul></ul><ul><ul><li>has_one / has_many </li></ul></ul><ul><li>There are others, but they are not commonly used. </li></ul>© Vita Rara, Inc.
  23. 23. ActiveRecord Associations © Vita Rara, Inc. # Has Many class Order < ActiveRecord::Base has_many :order_line_items end class OrderLineItem < ActiveRecord::Base belongs_to :order end # Has One class Party < ActiveRecord::Base has_one :login_credential end class LoginCredential < ActiveRecord::Base belongs_to :party end
  24. 24. Association Methods <ul><li>Associations add methods to the class. </li></ul><ul><ul><li>This is an excellent example of meta-programming. </li></ul></ul><ul><li>Added methods allow easy management of the associated models. </li></ul><ul><ul><li>order.order_line_items << line_item </li></ul></ul><ul><ul><li>order.order_line_items.create() </li></ul></ul>© Vita Rara, Inc.
  25. 25. ActiveRecord Validations <ul><li>Keeping Your Data Safe </li></ul>
  26. 26. Validation <ul><li>Validations are rules in your model objects to help protect the integrity of your data </li></ul><ul><li>Validation is invoked by the save method. Save returns true if validations pass and false otherwise. </li></ul><ul><li>If you invoke save! then a RecordInvalid exception is raised if the object is not valid </li></ul><ul><li>Use save(false) if you need to turn off validation </li></ul>© Vita Rara, Inc.
  27. 27. Validation Callback Methods <ul><li>validate </li></ul><ul><li>validate_on_create </li></ul><ul><li>validate_on_update </li></ul>© Vita Rara, Inc.
  28. 28. Validation Example © Vita Rara, Inc. class Person < ActiveRecord::Base def validate puts “validate invoked” end def validate_on_create puts “validate_on_create invoked” end def validate_on_update puts “validate_on_update invoked” end end peter = Person.create(:name => “Peter”) # => validate, validate_on_create invoked peter.last_name = “Forsberg” # => validate_on_update invoked
  29. 29. Validation Macros <ul><li>validates_acceptance_of </li></ul><ul><li>validate_associated </li></ul><ul><li>validates_confirmation_of validates_each </li></ul><ul><li>validates_exclusion_of </li></ul><ul><li>validates_format_of </li></ul><ul><li>validates_inclusion_of </li></ul><ul><li>validates_length_of </li></ul><ul><li>validates_numericality_of </li></ul><ul><li>validates_presence_of </li></ul><ul><li>validates_size_of </li></ul><ul><li>validates_uniqueness_of </li></ul>© Vita Rara, Inc.
  30. 30. Validation Macro Example © Vita Rara, Inc. class User < ActiveRecord::Base validates_presence_of :name, :email, :password validates_format_of :name, :with => /^ w +$/ , :message => “may only contain word characters” validates_uniqueness_of :name, :message => “is already in use” validates_length_of :password, :within => 4 .. 40 validates_confirmation_of :password validates_inclusion_of :role, :in => %w(super admin user) , :message => “must be super , admin, or user”, :allow_nil => true validates_presence_of :customer_id, :if => Proc. new { |u| %w(admin user) .include?(u.role) } validates_numericality_of :weight, :only_integer => true, :allow_nil => true end
  31. 31. ActionController <ul><li>The “C” in MVC </li></ul>
  32. 32. Controllers <ul><li>Controllers are Ruby classes that live under app/ controllers </li></ul><ul><li>Controller classes extend ActionController::Base </li></ul><ul><li>An action is a public method and/or a corresponding view template </li></ul>© Vita Rara, Inc.
  33. 33. Rendering a Response <ul><li>A response is rendered with the render command </li></ul><ul><li>An action can only render a response once </li></ul><ul><li>Rails invokes render automatically if you don’t </li></ul><ul><li>Redirects are made with the redirect_to command </li></ul>© Vita Rara, Inc.
  34. 34. A Simple Controller © Vita Rara, Inc. class PrioritiesController < InternalController def show @priority = current_account.priorities.find(params[:id]) end def new @priority = Priority. new end def create @priority = Priority. new (params[:priority]) if flash[:notice] = 'The priority was successfully created.' redirect_to account_url else render :action => &quot;new&quot; end end ... end
  35. 35. Sessions <ul><li>A hash stored on the server, typically in a database table or in the file system. </li></ul><ul><li>Keyed by the cookie _session_id </li></ul><ul><li>Avoid storing complex Ruby objects, instead put id:s in the session and keep data in the database, i.e. use session[:user_id] rather than session[:user] </li></ul>© Vita Rara, Inc.
  36. 36. ActionView <ul><li>Our Face to the World </li></ul>
  37. 37. What is ActionView? <ul><li>ActionView is the module in the ActionPack library that deals with rendering a response to the client. </li></ul><ul><li>The controller decides which template and/or partial and layout to use in the response </li></ul><ul><li>Templates use helper methods to generate links, forms, and JavaScript, and to format text. </li></ul>© Vita Rara, Inc.
  38. 38. Where do templates live? <ul><li>Templates that belong to a certain controller typically live under app/view/controller_name, i.e. templates for Admin::UsersController would live under app/ views/admin/users </li></ul><ul><li>Templates shared across controllers are put under app/views/shared. You can render them with render :template => ‘shared/my_template’ </li></ul><ul><li>You can have templates shared across Rails applications and render them with render :file => ‘path/to/template’ </li></ul>© Vita Rara, Inc.
  39. 39. Template Environment <ul><li>Templates have access to the controller object’s flash, headers, logger, params, request, response, and session. </li></ul><ul><li>Instance variables (i.e. @variable) in the controller are available in templates </li></ul><ul><li>The current controller is available as the attribute controller. </li></ul>© Vita Rara, Inc.
  40. 40. Embedded Ruby <ul><li><%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page. </li></ul><ul><li><% ruby code here %> - Evaluates Ruby code without outputting anything to the page. </li></ul>© Vita Rara, Inc.
  41. 41. Example View © Vita Rara, Inc. <p> <b>Name:</b> <%=h %> </p> <%= link_to 'Edit' , edit_category_path(@category) %> | <%= link_to 'Back' , categories_path %>
  42. 42. A Check Book Ledger Example
  43. 43. Basic Requirements <ul><li>The System should allow the management of multiple accounts </li></ul><ul><li>The system should maintain an account ledger for every account in the system. </li></ul><ul><li>Each account ledger should consist of ledger entries. </li></ul><ul><li>Each ledger entry can be either a positive or negative value. </li></ul><ul><li>Ledger entries can be associated with a payee and a category. </li></ul>© Vita Rara, Inc.
  44. 44. Implementing a Check Book Ledger <ul><li>Create a new project </li></ul><ul><li>Theme the project </li></ul><ul><li>Define our resources using: script/generate scaffold </li></ul><ul><ul><li>Account </li></ul></ul><ul><ul><li>Ledger Entry </li></ul></ul><ul><ul><li>Payee </li></ul></ul><ul><ul><li>Category </li></ul></ul><ul><li>Theme models </li></ul><ul><li>Implement </li></ul>© Vita Rara, Inc.
  45. 45. Shameless Self Promotion
  46. 46. Ruby and Rail Training <ul><li>One day to three day programs. </li></ul><ul><li>Introduction to Ruby </li></ul><ul><li>Advanced Ruby </li></ul><ul><li>Introduction to Rails </li></ul><ul><li>Advanced Rails </li></ul><ul><li>Test Driven Development </li></ul><ul><li>Behavior Driven Development </li></ul><ul><li>Test Anything with Cucumber </li></ul><ul><li>Advanced Domain Modeling with ActiveRecord </li></ul><ul><li>Domain Driven Development with Rails </li></ul>© Vita Rara, Inc.
  47. 47. Ruby on Rails Consulting <ul><li>Full Life Cycle Project Development </li></ul><ul><ul><li>Inception </li></ul></ul><ul><ul><li>Implementation </li></ul></ul><ul><ul><li>Deployment </li></ul></ul><ul><ul><li>Long Term Support </li></ul></ul><ul><li>Ruby on Rails Mentoring </li></ul><ul><ul><li>Get your team up to speed using Rails </li></ul></ul>© Vita Rara, Inc.
  48. 48. Contact Information <ul><li>Mark Menard </li></ul><ul><ul><li>[email_address] </li></ul></ul><ul><ul><li> / </li></ul></ul><ul><ul><li>518 369 7356 </li></ul></ul>© Vita Rara, Inc.