Intro to Ruby andRailsBy Mark MenardEnable Labs
What is a dynamic language? “…a class of high-level programming languages that execute at runtime many common behaviors th...
Examples of Dynamic LanguagesLispSchemeSmalltalkPerlLuaPHPJavascriptGroovyRubyPython                            ...
Dynamic vs. StaticDynamic Languages                                Static LanguagesVariable types do not have to be specif...
Intro to RubyDynamic Object Oriented        Closures Language                       Literal arrays, hashes and Everyth...
ScriptingMany dynamic languages are easily at home scripting.Allows easy proof of concept before committing to a large p...
Terse / Low CeremonyRuby uses unchecked exceptions. No more try…catch…finally blocks everyplace. No more throws stateme...
REPL: irbAccess to the entire language and functionality in an interactive environment.Prototype new functionality.Expl...
VariablesDo not need to be declared, just use it and it springs into existence. Instance variables start with @ (ie: @na...
Literal Arrays, Hashes and Regex in Ruby# Create an arrayarray = [ 1, 2, 3, 4, 5 ]puts array.inspect# Create a hashhash = ...
Classes in Rubyclass Foo def do_something   puts "Foo#do_something" endendclass Bar < Foo def do_something   puts "Bar#do_...
Open ClassesClasses are open for modification at runtime. Methods can be added. Methods can be redefined. Methods can ...
Open Classesclass String  def url_decode    CGI::unescape(self)  end  def url_encode    CGI::escape(self)  endend
Open Classes in Rubyclass Foo def escape   puts "Whee! Im free!" endendfoo = Foo.newfoo.escape #=> prints "Whee! Im free!"...
Mixins in Rubymodule Logging def log (msg)  puts msg endendclass OrderDispatcher include Logging def dispatch_internationa...
Duck Typing“If it walks like a duck, quacks like a duck and has feathers then it’s a duck.”Interfaces are conceptual, no...
Duck Typing in Rubyclass Cat               end  def talk            end    puts "Meow"  end                 [ Cat.new, Dog...
Closures in Rubydef create_closure (name) # Create a closure closing over the scope which contains name lambda do |job|   ...
Method Missing in Rubyclass MethodMissing def method_missing (name, *args)   puts "Oops! Method #{name} does not exist." e...
Metaprogramming in Rubyclass MethodMissing def method_missing (name, *args)   puts "method_missing called the first time." ...
Operator Overloading in Rubyclass Person def initialize (name)   @name = name end def + (other)  "#{@name} and #{other.to_...
Intro to Ruby onRails
Ruby Wins! “I always knew one day Smalltalk would replace Java. I just didn’t know it would be called Ruby.” - Kent Beck, ...
Ruby on RailsRuby on Rails is astounding. Using it is like watching akung-fu movie, where a dozen bad-ass frameworksprepar...
The Elevator Pitch Ruby on Rails is an open-source web framework that is optimized for programmer happiness and sustainabl...
OverviewRails is a full stack web framework Model: ActiveRecord  ORM  database connectivity  Database schema manageme...
The Rails PhilosophyRuby - less and more readable code, shorter development times, simple but powerful, no compilation cy...
Rake: The Ruby MakeRake lets you define a dependency tree of tasks to be executed.Rake tasks are loaded from the file Rake...
EnvironmentsRails has support for multiple execution environments.Environments encapsulate database settings and other c...
MigrationsManaging SchemaEvolution
Managing Data SchemasRails includes support for migrations to manage the evolution of your database schema. No need to w...
Typical Migration Taskscreate_tableadd_columnchange_columnrename_columnrename_tableadd_index                        ...
Migration Examplecreate_table "users", :force => true do |t|  t.string :login t.string :email t.string :remember_token  t....
Active RecordModeling the World
FundamentalsOne database table maps to one Ruby classTable names are plural and class names are singularDatabase column...
Active Record Model Examplecreate_table "persons" do |t|  t.string :first_name, last_name  t.timestampsendclass Person < A...
CRUDCreate: create, newRead: find, find_by_<attribute>Update: save, update_attributesDelete: destroy                  ...
Finding ModelsUser.find(:first)User.find(:all)User.find(1)User.find_by_login(‘mark’)User.find(:all, :conditions => [ ...
Advanced Finding:limit:offset:order:joins:select:group                   39
Updating Modelsuser = User.find(1)user.first_name = ‘Mark’user.last_name = ‘Menard’user.save!                            40
TransactionsAccount.transaction do  account1.deposit(100)  account2.withdraw(100)end                           41
Active RecordAssociationsJoining Things Together
Association TypesTwo primary types of associations: belongs_to has_one / has_manyThere are others, but they are not co...
Association Example# Has Manyclass Order < ActiveRecord::Base  has_many :order_line_itemsendclass OrderLineItem < ActiveRe...
Dynamic Association MethodsAssociations add methods to the class. This is an excellent example of meta-programming.Adde...
Active RecordValidationsKeeping Your Data Safe
ValidationsValidations are rules in your model objects to help protect the integrity of your dataValidation is invoked b...
Validation Call Back Methodsvalidatevalidate_on_createvalidate_on_update                               48
Validation Exampleclass Person < ActiveRecord::Base  def validate    puts “validate invoked”  end  def validate_on_create ...
Validation Macrosvalidates_acceptance_ofvalidate_associatedvalidates_confirmation_of validates_eachvalidates_exclusion...
Validation Macro Examplesclass User < ActiveRecord::Base  validates_presence_of :name, :email, :password  validates_format...
ActionControllerThe “C” in MVC
ControllersControllers are Ruby classes that live under app/ controllersController classes extend ActionController::Base...
Rendering a ResponseA response is rendered with the render commandAn action can only render a response onceRails invoke...
A Simple Controllerclass PrioritiesController < InternalController  def show    @priority = current_account.priorities.fin...
SessionsA hash stored on the server, typically in a database table or on the file system.Keyed by the cookie _session_id...
ActionViewOur Face to the World
ActionViewActionView is the module in the ActionPack library that deals with rendering a response to the client.The cont...
Where do templates live?Templates that belong to a certain controller typically live under app/view/controller_name, i.e....
Template EnvironmentTemplates have access to the controller object’s flash, headers, logger, params, request, response, an...
Embedded Ruby<%= ruby code here %> - Evaluates the Ruby code and prints the last evaluated value to the page.<% ruby cod...
Example View<p>  <b>Name:</b>  <%=h @category.name %></p><%= link_to Edit, edit_category_path(@category) %><%= link_to Bac...
Haml#profile  .left.column                                       Haml    #date= print_date    #address= current_user.addre...
Shameless SelfPromotionWe do Ruby on RailsDevelopment andTraining
Ruby and Rails TrainingOne day to three day programs.Introduction to RubyAdvanced RubyIntroduction to RailsAdvanced R...
Ruby on Rails DevelopmentFull Life Cycle Project Development Inception Implementation Deployment Long Term SupportRu...
Want to do Rails professionally?We’re addicted to the success of our clients.We’re addicted to quality.We’re addicted t...
Upcoming SlideShare
Loading in...5
×

Ruby on Rails Training - Module 1

2,466

Published on

This is the first module of an in depth training session that I do. This session covers Ruby, basic Rails and much more.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,466
On Slideshare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Ruby on Rails Training - Module 1

    1. 1. Intro to Ruby andRailsBy Mark MenardEnable Labs
    2. 2. What is a dynamic language? “…a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution.” -Dynamic Programming Languages from Wikipedia
    3. 3. Examples of Dynamic LanguagesLispSchemeSmalltalkPerlLuaPHPJavascriptGroovyRubyPython 3
    4. 4. Dynamic vs. StaticDynamic Languages Static LanguagesVariable types do not have to be specified. Variable types generally have to be specified.Class definitions can be modified at run time. Class definitions are frozen at time of specification.Standard library can be augmented. Standard library is frozen.Generally terse. Generally more verbose.Frequently used for scripting. Generally not used for scripting.Usually aren’t compiled. Generally are compiled.Commonly run on a Virtual Machine. Some are Can run on a VM or on bare metal.interpreted.Typically support reflection. Can support reflection.
    5. 5. Intro to RubyDynamic Object Oriented Closures Language Literal arrays, hashes and Everything is an object regexesDuck typed Operator overloadingHas open classes Runs on Windows, Linux, *nix,Uses dynamic method dispatch OS X, Java, and .NetSupports method_missing functionalitySupport meta-programmingExecutable Class DefinitionsREPLMixinsEverything is an expression
    6. 6. ScriptingMany dynamic languages are easily at home scripting.Allows easy proof of concept before committing to a large project.Can be used for many system administration needs. Full power of a multi-purpose language. 6
    7. 7. Terse / Low CeremonyRuby uses unchecked exceptions. No more try…catch…finally blocks everyplace. No more throws statements.Cleaner syntax.No type declarations.See the solution not the noise. 7
    8. 8. REPL: irbAccess to the entire language and functionality in an interactive environment.Prototype new functionality.Explore functionality of new libraries.Bug test problems in your code.Interact with your application while it is running. 8
    9. 9. VariablesDo not need to be declared, just use it and it springs into existence. Instance variables start with @ (ie: @name) Method variables are just the name (ie: name = ) Class variables start with @@ (ie: @@class_var = 1) 9
    10. 10. Literal Arrays, Hashes and Regex in Ruby# Create an arrayarray = [ 1, 2, 3, 4, 5 ]puts array.inspect# Create a hashhash = { :a => a, :b => b, 1 => 1, "a" => "string a" }puts hash.inspectstring = "abcd"puts string =~ /abcd/ ? ”match" : ”no match" #=> ”match"puts string =~ /dcba/ ? ”match" : ”no match" #=> ”no match"
    11. 11. Classes in Rubyclass Foo def do_something puts "Foo#do_something" endendclass Bar < Foo def do_something puts "Bar#do_something" endendfoo = Foo.newfoo.do_something #=> prints Foo#do_somethingbar = Bar.newbar.do_something #=> prints Bar#do_something
    12. 12. Open ClassesClasses are open for modification at runtime. Methods can be added. Methods can be redefined. Methods can be added to an instance. Methods can be redefined on an instance.Allows you to closely adapt the language to your problem domain. It’s like sculpting in clay instead of stone.Mocking and stubbing become trivial. 12
    13. 13. Open Classesclass String def url_decode CGI::unescape(self) end def url_encode CGI::escape(self) endend
    14. 14. Open Classes in Rubyclass Foo def escape puts "Whee! Im free!" endendfoo = Foo.newfoo.escape #=> prints "Whee! Im free!"class Foo def escape puts "Not so fast!" endendfoo.escape #=> prints ”Not so fast!"
    15. 15. Mixins in Rubymodule Logging def log (msg) puts msg endendclass OrderDispatcher include Logging def dispatch_international_order (order) destination = DistinationService.find(order.foreign_party) log("Sending #{order.number} to #{destination.name}") ... endend
    16. 16. Duck Typing“If it walks like a duck, quacks like a duck and has feathers then it’s a duck.”Interfaces are conceptual, not actual.An object’s type is defined by the messages it responds to.
    17. 17. Duck Typing in Rubyclass Cat end def talk end puts "Meow" end [ Cat.new, Dog.new, Duck.new,end Person.new ].each do |ob| ob.talkclass Dog end def talk puts "Woof" endendclass Duck def talk puts "Quack!" endendclass Person def talk puts "Hi"
    18. 18. Closures in Rubydef create_closure (name) # Create a closure closing over the scope which contains name lambda do |job| puts "#{name} has a new job doing #{job}." endendclosure = create_closure("Mark")closure.call("web development") #=> Mark has a new job doing web development.closure.call("goat milking") #=> Mark has a new job doing goat milking.
    19. 19. Method Missing in Rubyclass MethodMissing def method_missing (name, *args) puts "Oops! Method #{name} does not exist." endendmm = MethodMissing.newmm.foo #=> prints “Oops! Method foo does not exist.
    20. 20. Metaprogramming in Rubyclass MethodMissing def method_missing (name, *args) puts "method_missing called the first time." puts "Defining #{name} method." instance_eval %Q{ def #{name.to_s} (args) puts "Inside the dynamically defined foo method." end } send(name, args) endendmm = MethodMissing.newmm.foo(nil)mm.foo(nil)
    21. 21. Operator Overloading in Rubyclass Person def initialize (name) @name = name end def + (other) "#{@name} and #{other.to_s} have gotten together" end def to_s @name endendmark = Person.new("Mark")sylva = Person.new("Sylva")puts mark + sylva #=> "Mark and Sylva have gotten together"
    22. 22. Intro to Ruby onRails
    23. 23. Ruby Wins! “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” 23
    24. 24. Ruby on RailsRuby on Rails is astounding. Using it is like watching akung-fu movie, where a dozen bad-ass frameworksprepare to beat up the little newcomer only to behanded their asses in a variety of imaginative ways.-Nathan Torkington,OReilly Program Chair for OSCON 24
    25. 25. 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. 25
    26. 26. 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 26
    27. 27. 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 27
    28. 28. Rake: The Ruby MakeRake lets you define a dependency tree of tasks to be executed.Rake tasks are loaded from the file Rakefile, and other .rake files in the source of the project.Rake automates and simplifies creating and managing the development of a Rails project. 28
    29. 29. 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. 29
    30. 30. MigrationsManaging SchemaEvolution
    31. 31. 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. 31
    32. 32. Typical Migration Taskscreate_tableadd_columnchange_columnrename_columnrename_tableadd_index 32
    33. 33. Migration Examplecreate_table "users", :force => true do |t| t.string :login t.string :email t.string :remember_token t.string :salt, :crypted_password, :limit => 40 t.datetime :remember_token_expires_at t.timestampsend 33
    34. 34. Active RecordModeling the World
    35. 35. 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 35
    36. 36. Active Record Model Examplecreate_table "persons" do |t| t.string :first_name, last_name t.timestampsendclass Person < ActiveRecord::Baseendp = Person.newp.first_name = ‘Mark’p.last_name = ‘Menard’p.save 36
    37. 37. CRUDCreate: create, newRead: find, find_by_<attribute>Update: save, update_attributesDelete: destroy 37
    38. 38. 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]) 38
    39. 39. Advanced Finding:limit:offset:order:joins:select:group 39
    40. 40. Updating Modelsuser = User.find(1)user.first_name = ‘Mark’user.last_name = ‘Menard’user.save! 40
    41. 41. TransactionsAccount.transaction do account1.deposit(100) account2.withdraw(100)end 41
    42. 42. Active RecordAssociationsJoining Things Together
    43. 43. Association TypesTwo primary types of associations: belongs_to has_one / has_manyThere are others, but they are not commonly used. 43
    44. 44. Association Example# Has Manyclass Order < ActiveRecord::Base has_many :order_line_itemsendclass OrderLineItem < ActiveRecord::Base belongs_to :orderend# Has Oneclass Party < ActiveRecord::Base has_one :login_credentialendclass LoginCredential < ActiveRecord::Base belongs_to :partyend 44
    45. 45. Dynamic 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() 45
    46. 46. Active RecordValidationsKeeping Your Data Safe
    47. 47. Validations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 47
    48. 48. Validation Call Back Methodsvalidatevalidate_on_createvalidate_on_update 48
    49. 49. Validation Exampleclass 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” endendpeter = Person.create(:name => “Peter”) # => validate, validate_on_create invokedpeter.last_name = “Forsberg”peter.save # => validate_on_update invoked 49
    50. 50. 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 50
    51. 51. Validation Macro Examplesclass 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 => trueend 51
    52. 52. ActionControllerThe “C” in MVC
    53. 53. 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 53
    54. 54. 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 54
    55. 55. A Simple Controllerclass 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 => "new" end endend 55
    56. 56. SessionsA hash stored on the server, typically in a database table or on 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] 56
    57. 57. ActionViewOur Face to the World
    58. 58. 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 58
    59. 59. 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’ 59
    60. 60. 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. 60
    61. 61. 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. 61
    62. 62. Example View<p> <b>Name:</b> <%=h @category.name %></p><%= link_to Edit, edit_category_path(@category) %><%= link_to Back, categories_path %> 62
    63. 63. Haml#profile .left.column Haml #date= print_date #address= current_user.address vs .right.column #email= current_user.email HTML with ERB #bio= current_user.bio<div id="profile"> <div class="left column"> <div id="date"><%= print_date %></div> <div id="address"><%= current_user.address %></div> </div> <div class="right column"> <div id="email"><%= current_user.email %></div> <div id="bio"><%= current_user.bio %></div> </div></div> 63
    64. 64. Shameless SelfPromotionWe do Ruby on RailsDevelopment andTraining
    65. 65. Ruby and Rails 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 65
    66. 66. Ruby on Rails DevelopmentFull Life Cycle Project Development Inception Implementation Deployment Long Term SupportRuby on Rails Mentoring Get your team up to speed using Rails 66
    67. 67. Want to do Rails professionally?We’re addicted to the success of our clients.We’re addicted to quality.We’re addicted to craftsmanship.We’re addicted to being the best.You’re dedicated to life long improvement.You thrive under a challenge.You’re a team player.You work hard to be the best. Not your best. THE BEST.Do well in the training. It’s an audition. 67

    ×