SlideShare a Scribd company logo
Intro to Ruby on Rails by Mark Menard Vita Rara, Inc.
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”
Ruby on Rails 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.  -Nathan Torkington,    O'Reilly Program Chair for OSCON   © Vita Rara, Inc.
The Elevator Pitch 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. © Vita Rara, Inc.
Overview Rails is a full stack web framework Model: ActiveRecord ORM database connectivity Database schema management View: ActiveView View layer Templates Controller: ActionController Web controller framework Manages web integration Active Support Extensions to Ruby to support web development Integrated Ajax support © Vita Rara, Inc.
The Rails Philosophy Ruby - less and more readable code, shorter development times, simple but powerful, no compilation cycle. Convention over configuration Predefined directory structure, and naming conventions Best practices: MVC, DRY, Testing Almost everything in Rails is Ruby code (SQL and JavaScript are abstracted) Integrated AJAX support. Web services with REST. Good community, tools, and documentation Extracted from a real application: Basecamp © Vita Rara, Inc.
Rake: The Ruby Make Rake lets you define a dependency tree of tasks to be executed. Rake tasks are loaded from the file Rakefile Rake automates and simplifies creating and managing the development of a Rails project. © Vita Rara, Inc.
Environments Rails has support for multiple execution environments. Environments encapsulate database settings and other configuration. Typical environments Development Test Production Additional environments are easy to add. © Vita Rara, Inc.
Migrations Managing Schema Evolution
Managing Data Schemas Rails includes support for migrations to manage the evolution of your database schema. No need to write SQL.  Migrations use a database independent Ruby API. Migrations are Ruby scripts giving you access to the full power of the language. © Vita Rara, Inc.
Migrations Typical migration functions: create_table add_column change_column rename_column rename_table add_index © Vita Rara, Inc.
Migration Example © Vita Rara, Inc. create_table  "users" , :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
ActiveRecord Modeling the World
Fundamentals One database table maps to one Ruby class Table names are plural and class names are singular Database columns map to attributes, i.e. get and set methods, in the model class All tables have an integer primary key called id Database tables are created with migrations   © Vita Rara, Inc.
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 = Person.new p.first_name = ‘Mark’ p.last_name = ‘Menard’ p.save
CRUD Create: create, new Read: find, find_by_<attribute> Update: save, update_attributes Delete: destroy © Vita Rara, Inc.
Finding Models User.find(:first) User.find(:all) User.find(1) User.find_by_login(‘mark’) User.find(:all, :conditions => [ “login = ? AND password = ?”, login, password]) © Vita Rara, Inc.
Advanced Finding Finders also support: :limit :offset :order :joins :select :group © Vita Rara, Inc.
Update user = User.find(1) user.first_name = ‘Mark’ user.last_name = ‘Menard’ user.save! © Vita Rara, Inc.
Transactions Account.transaction do account1.deposit(100) account2.withdraw(100) end © Vita Rara, Inc.
ActiveRecord Associations Joining Things Together
ActiveRecord Associations Two primary types of associations: belongs_to has_one / has_many There are others, but they are not commonly used. © Vita Rara, Inc.
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
Association Methods Associations add methods to the class. This is an excellent example of meta-programming. Added methods allow easy management of the associated models. order.order_line_items << line_item order.order_line_items.create() © Vita Rara, Inc.
ActiveRecord Validations Keeping Your Data Safe
Validation Validations are rules in your model objects to help protect the integrity of your data Validation is invoked by the save method. Save returns true if validations pass and false otherwise. If you invoke save! then a RecordInvalid exception is raised if the object is not valid Use save(false) if you need to turn off validation  © Vita Rara, Inc.
Validation Callback Methods validate validate_on_create validate_on_update © Vita Rara, Inc.
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”  peter.save # => validate_on_update invoked
Validation Macros validates_acceptance_of  validate_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  © Vita Rara, Inc.
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
ActionController The “C” in MVC
Controllers Controllers are Ruby classes that live under app/ controllers Controller classes extend ActionController::Base An action is a public method and/or a corresponding view template  © Vita Rara, Inc.
Rendering a Response A response is rendered with the render command An action can only render a response once Rails invokes render automatically if you don’t Redirects are made with the redirect_to command  © Vita Rara, Inc.
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  @priority.save flash[:notice]  =   'The priority was successfully created.' redirect_to account_url else render :action =>  &quot;new&quot; end end ... end
Sessions A hash stored on the server, typically in a database table or in the file system. Keyed by the cookie _session_id 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]   © Vita Rara, Inc.
ActionView Our Face to the World
What is ActionView? ActionView is the module in the ActionPack library that deals with rendering a response to the client. The controller decides which template and/or partial and layout to use in the response Templates use helper methods to generate links, forms, and JavaScript, and to format text.  © Vita Rara, Inc.
Where do templates live? 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 Templates shared across controllers are put under app/views/shared. You can render them with render :template => ‘shared/my_template’ You can have templates shared across Rails applications and render them with render :file => ‘path/to/template’ © Vita Rara, Inc.
Template Environment Templates have access to the controller object’s flash, headers, logger, params, request, response, and session. Instance variables (i.e. @variable) in the controller are available in templates The current controller is available as the attribute controller.   © Vita Rara, Inc.
Embedded Ruby <%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page. <% ruby code here %> - Evaluates Ruby code without outputting anything to the page. © Vita Rara, Inc.
Example View © Vita Rara, Inc. <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to  'Edit' , edit_category_path(@category) %> | <%= link_to  'Back' , categories_path %>
A Check Book Ledger Example
Basic Requirements The System should allow the management of multiple accounts The system should maintain an account ledger for every account in the system. Each account ledger should consist of ledger entries. Each ledger entry can be either a positive or negative value. Ledger entries can be associated with a payee and a category. © Vita Rara, Inc.
Implementing a Check Book Ledger Create a new project Theme the project Define our resources using:  script/generate scaffold Account Ledger Entry Payee Category Theme models Implement  © Vita Rara, Inc.
Shameless Self Promotion
Ruby and Rail Training One day to three day programs. Introduction to Ruby Advanced Ruby Introduction to Rails Advanced Rails Test Driven Development Behavior Driven Development Test Anything with Cucumber Advanced Domain Modeling with ActiveRecord Domain Driven Development with Rails © Vita Rara, Inc.
Ruby on Rails Consulting Full Life Cycle Project Development Inception Implementation Deployment Long Term Support Ruby on Rails Mentoring Get your team up to speed using Rails © Vita Rara, Inc.
Contact Information Mark Menard [email_address] http://www.vitarara.net / 518 369 7356 © Vita Rara, Inc.

More Related Content

PDF
Project Fedena and Why Ruby on Rails - ArvindArvind G S
PPT
Ruby on Rails workshop for beginner
ODP
A Toda Maquina Con Ruby on Rails
PDF
Be Happy With Ruby on Rails - Ecosystem
PPTX
Ruby on Rails - An overview
ODP
Introduction to Ruby on Rails
DOCX
Rails Concept
PDF
The Evolution of Airbnb's Frontend
Project Fedena and Why Ruby on Rails - ArvindArvind G S
Ruby on Rails workshop for beginner
A Toda Maquina Con Ruby on Rails
Be Happy With Ruby on Rails - Ecosystem
Ruby on Rails - An overview
Introduction to Ruby on Rails
Rails Concept
The Evolution of Airbnb's Frontend

What's hot (20)

PDF
React.js for Rails Developers
PDF
React on rails v6.1 at LA Ruby, November 2016
PDF
RESTful Web Applications with Apache Sling
PDF
Introduction to Ruby on Rails
PDF
Web a Quebec - JS Debugging
PDF
An Intense Overview of the React Ecosystem
PPTX
Rails Engine Patterns
PDF
PLAT-8 Spring Web Scripts and Spring Surf
PPTX
API Development with Laravel
PPTX
Rails Engine | Modular application
PPT
Build Your Own CMS with Apache Sling
PPTX
Rails Engine :: modularize you app
PPTX
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
PDF
AngularJS meets Rails
PDF
How angularjs saves rails
PDF
RoR 101: Session 5
PPTX
Laravel Eloquent ORM
PPTX
Laravel overview
PPTX
Laravel introduction
PPTX
Rails Request & Middlewares
React.js for Rails Developers
React on rails v6.1 at LA Ruby, November 2016
RESTful Web Applications with Apache Sling
Introduction to Ruby on Rails
Web a Quebec - JS Debugging
An Intense Overview of the React Ecosystem
Rails Engine Patterns
PLAT-8 Spring Web Scripts and Spring Surf
API Development with Laravel
Rails Engine | Modular application
Build Your Own CMS with Apache Sling
Rails Engine :: modularize you app
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
AngularJS meets Rails
How angularjs saves rails
RoR 101: Session 5
Laravel Eloquent ORM
Laravel overview
Laravel introduction
Rails Request & Middlewares
Ad

Similar to Intro to Ruby on Rails (20)

PDF
Apex Enterprise Patterns: Building Strong Foundations
PDF
AGADOS function & feature Chapter-02 biz logic define
PDF
OSDC 2009 Rails Turtorial
KEY
Ruby For Startups
PPT
Multi-tenancy with Rails
ODP
DynamicRecord Presentation
PPT
Intro to Rails ActiveRecord
KEY
Working Effectively With Legacy Code
PDF
2011-02-03 LA RubyConf Rails3 TDD Workshop
PDF
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
PDF
Rails antipattern-public
PDF
Rails antipatterns
PPT
Ruby On Rails
ODP
Pyramid deployment
PDF
Phoenix for Rails Devs
PPTX
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
ODP
Practical catalyst
PDF
Building Mobile Friendly APIs in Rails
PDF
SproutCore and the Future of Web Apps
PPT
Introduction To Code Igniter
Apex Enterprise Patterns: Building Strong Foundations
AGADOS function & feature Chapter-02 biz logic define
OSDC 2009 Rails Turtorial
Ruby For Startups
Multi-tenancy with Rails
DynamicRecord Presentation
Intro to Rails ActiveRecord
Working Effectively With Legacy Code
2011-02-03 LA RubyConf Rails3 TDD Workshop
Um roadmap do Framework Ruby on Rails, do Rails 1 ao Rails 4 - DevDay 2013
Rails antipattern-public
Rails antipatterns
Ruby On Rails
Pyramid deployment
Phoenix for Rails Devs
RightScale API: How To Build Your Own IT Vending Machine - RightScale Compute...
Practical catalyst
Building Mobile Friendly APIs in Rails
SproutCore and the Future of Web Apps
Introduction To Code Igniter
Ad

More from Mark Menard (14)

PDF
Let's Do Some Upfront Design - WindyCityRails 2014
PDF
A Tour of Wyriki
PDF
Small Code - RailsConf 2014
PDF
Small Code - Ruby on Ales 2014
PDF
Write Small Things (Code)
PDF
JRuby 6 Years in Production
PDF
Conference of Grand Masters Tech Talk 2013
KEY
Startup Lessons Learned
PDF
Mobile Platforms and App Development
KEY
Ruby on Rails Training - Module 2
KEY
Ruby on Rails Training - Module 1
KEY
Introduction to Ruby
PPT
Behavior Driven Development with Rails
PPT
JRuby in a Java World
Let's Do Some Upfront Design - WindyCityRails 2014
A Tour of Wyriki
Small Code - RailsConf 2014
Small Code - Ruby on Ales 2014
Write Small Things (Code)
JRuby 6 Years in Production
Conference of Grand Masters Tech Talk 2013
Startup Lessons Learned
Mobile Platforms and App Development
Ruby on Rails Training - Module 2
Ruby on Rails Training - Module 1
Introduction to Ruby
Behavior Driven Development with Rails
JRuby in a Java World

Recently uploaded (20)

PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
cuic standard and advanced reporting.pdf
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Big Data Technologies - Introduction.pptx
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
Electronic commerce courselecture one. Pdf
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Cloud computing and distributed systems.
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Advanced IT Governance
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
NewMind AI Weekly Chronicles - August'25 Week I
cuic standard and advanced reporting.pdf
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Big Data Technologies - Introduction.pptx
madgavkar20181017ppt McKinsey Presentation.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Chapter 3 Spatial Domain Image Processing.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Advanced methodologies resolving dimensionality complications for autism neur...
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
Electronic commerce courselecture one. Pdf
Per capita expenditure prediction using model stacking based on satellite ima...
Review of recent advances in non-invasive hemoglobin estimation
Cloud computing and distributed systems.
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Advanced IT Governance
Reach Out and Touch Someone: Haptics and Empathic Computing

Intro to Ruby on Rails

  • 1. Intro to Ruby on Rails by Mark Menard Vita Rara, Inc.
  • 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. Ruby on Rails 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. -Nathan Torkington, O'Reilly Program Chair for OSCON © Vita Rara, Inc.
  • 4. The Elevator Pitch 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. © Vita Rara, Inc.
  • 5. Overview Rails is a full stack web framework Model: ActiveRecord ORM database connectivity Database schema management View: ActiveView View layer Templates Controller: ActionController Web controller framework Manages web integration Active Support Extensions to Ruby to support web development Integrated Ajax support © Vita Rara, Inc.
  • 6. The Rails Philosophy Ruby - less and more readable code, shorter development times, simple but powerful, no compilation cycle. Convention over configuration Predefined directory structure, and naming conventions Best practices: MVC, DRY, Testing Almost everything in Rails is Ruby code (SQL and JavaScript are abstracted) Integrated AJAX support. Web services with REST. Good community, tools, and documentation Extracted from a real application: Basecamp © Vita Rara, Inc.
  • 7. Rake: The Ruby Make Rake lets you define a dependency tree of tasks to be executed. Rake tasks are loaded from the file Rakefile Rake automates and simplifies creating and managing the development of a Rails project. © Vita Rara, Inc.
  • 8. Environments Rails has support for multiple execution environments. Environments encapsulate database settings and other configuration. Typical environments Development Test Production Additional environments are easy to add. © Vita Rara, Inc.
  • 10. Managing Data Schemas Rails includes support for migrations to manage the evolution of your database schema. No need to write SQL. Migrations use a database independent Ruby API. Migrations are Ruby scripts giving you access to the full power of the language. © Vita Rara, Inc.
  • 11. Migrations Typical migration functions: create_table add_column change_column rename_column rename_table add_index © Vita Rara, Inc.
  • 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
  • 14. Fundamentals One database table maps to one Ruby class Table names are plural and class names are singular Database columns map to attributes, i.e. get and set methods, in the model class All tables have an integer primary key called id Database tables are created with migrations © Vita Rara, Inc.
  • 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 = Person.new p.first_name = ‘Mark’ p.last_name = ‘Menard’ p.save
  • 16. CRUD Create: create, new Read: find, find_by_<attribute> Update: save, update_attributes Delete: destroy © Vita Rara, Inc.
  • 17. Finding Models User.find(:first) User.find(:all) User.find(1) User.find_by_login(‘mark’) User.find(:all, :conditions => [ “login = ? AND password = ?”, login, password]) © Vita Rara, Inc.
  • 18. Advanced Finding Finders also support: :limit :offset :order :joins :select :group © Vita Rara, Inc.
  • 19. Update user = User.find(1) user.first_name = ‘Mark’ user.last_name = ‘Menard’ user.save! © Vita Rara, Inc.
  • 20. Transactions Account.transaction do account1.deposit(100) account2.withdraw(100) end © Vita Rara, Inc.
  • 22. ActiveRecord Associations Two primary types of associations: belongs_to has_one / has_many There are others, but they are not commonly used. © Vita Rara, Inc.
  • 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. Association Methods Associations add methods to the class. This is an excellent example of meta-programming. Added methods allow easy management of the associated models. order.order_line_items << line_item order.order_line_items.create() © Vita Rara, Inc.
  • 26. Validation Validations are rules in your model objects to help protect the integrity of your data Validation is invoked by the save method. Save returns true if validations pass and false otherwise. If you invoke save! then a RecordInvalid exception is raised if the object is not valid Use save(false) if you need to turn off validation © Vita Rara, Inc.
  • 27. Validation Callback Methods validate validate_on_create validate_on_update © Vita Rara, Inc.
  • 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” peter.save # => validate_on_update invoked
  • 29. Validation Macros validates_acceptance_of validate_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 © Vita Rara, Inc.
  • 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
  • 32. Controllers Controllers are Ruby classes that live under app/ controllers Controller classes extend ActionController::Base An action is a public method and/or a corresponding view template © Vita Rara, Inc.
  • 33. Rendering a Response A response is rendered with the render command An action can only render a response once Rails invokes render automatically if you don’t Redirects are made with the redirect_to command © Vita Rara, Inc.
  • 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 @priority.save flash[:notice] = 'The priority was successfully created.' redirect_to account_url else render :action => &quot;new&quot; end end ... end
  • 35. Sessions A hash stored on the server, typically in a database table or in the file system. Keyed by the cookie _session_id 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] © Vita Rara, Inc.
  • 36. ActionView Our Face to the World
  • 37. What is ActionView? ActionView is the module in the ActionPack library that deals with rendering a response to the client. The controller decides which template and/or partial and layout to use in the response Templates use helper methods to generate links, forms, and JavaScript, and to format text. © Vita Rara, Inc.
  • 38. Where do templates live? 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 Templates shared across controllers are put under app/views/shared. You can render them with render :template => ‘shared/my_template’ You can have templates shared across Rails applications and render them with render :file => ‘path/to/template’ © Vita Rara, Inc.
  • 39. Template Environment Templates have access to the controller object’s flash, headers, logger, params, request, response, and session. Instance variables (i.e. @variable) in the controller are available in templates The current controller is available as the attribute controller. © Vita Rara, Inc.
  • 40. Embedded Ruby <%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page. <% ruby code here %> - Evaluates Ruby code without outputting anything to the page. © Vita Rara, Inc.
  • 41. Example View © Vita Rara, Inc. <p> <b>Name:</b> <%=h @category.name %> </p> <%= link_to 'Edit' , edit_category_path(@category) %> | <%= link_to 'Back' , categories_path %>
  • 42. A Check Book Ledger Example
  • 43. Basic Requirements The System should allow the management of multiple accounts The system should maintain an account ledger for every account in the system. Each account ledger should consist of ledger entries. Each ledger entry can be either a positive or negative value. Ledger entries can be associated with a payee and a category. © Vita Rara, Inc.
  • 44. Implementing a Check Book Ledger Create a new project Theme the project Define our resources using: script/generate scaffold Account Ledger Entry Payee Category Theme models Implement © Vita Rara, Inc.
  • 46. Ruby and Rail Training One day to three day programs. Introduction to Ruby Advanced Ruby Introduction to Rails Advanced Rails Test Driven Development Behavior Driven Development Test Anything with Cucumber Advanced Domain Modeling with ActiveRecord Domain Driven Development with Rails © Vita Rara, Inc.
  • 47. Ruby on Rails Consulting Full Life Cycle Project Development Inception Implementation Deployment Long Term Support Ruby on Rails Mentoring Get your team up to speed using Rails © Vita Rara, Inc.
  • 48. Contact Information Mark Menard [email_address] http://www.vitarara.net / 518 369 7356 © Vita Rara, Inc.