• Save
Ruby on Rails Training - Module 1
Upcoming SlideShare
Loading in...5
×
 

Ruby on Rails Training - Module 1

on

  • 2,352 views

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

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

Statistics

Views

Total Views
2,352
Views on SlideShare
2,298
Embed Views
54

Actions

Likes
1
Downloads
0
Comments
0

3 Embeds 54

http://taimoorchangaizpucitian.wordpress.com 52
http://www.docshut.com 1
https://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \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 Ruby on Rails Training - Module 1 Presentation Transcript

  • 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 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
  • Examples of Dynamic LanguagesLispSchemeSmalltalkPerlLuaPHPJavascriptGroovyRubyPython 3
  • 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.
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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"
  • 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
  • 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
  • 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!"class Foo def escape puts "Not so fast!" endendfoo.escape #=> prints ”Not so fast!"
  • 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
  • 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.
  • 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"
  • 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.
  • 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.
  • 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)
  • 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"
  • 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, Creator of “Extreme Programming” 23
  • 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
  • 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
  • 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
  • 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
  • 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
  • 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
  • MigrationsManaging SchemaEvolution
  • 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
  • Typical Migration Taskscreate_tableadd_columnchange_columnrename_columnrename_tableadd_index 32
  • 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
  • Active RecordModeling 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 35
  • 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
  • CRUDCreate: create, newRead: find, find_by_<attribute>Update: save, update_attributesDelete: destroy 37
  • 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
  • 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 commonly used. 43
  • 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
  • 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
  • Active RecordValidationsKeeping Your Data Safe
  • 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
  • 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 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
  • 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
  • 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
  • ActionControllerThe “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 53
  • 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
  • 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
  • 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
  • ActionViewOur Face to the World
  • 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
  • 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
  • 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
  • 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
  • Example View<p> <b>Name:</b> <%=h @category.name %></p><%= link_to Edit, edit_category_path(@category) %><%= link_to Back, categories_path %> 62
  • 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
  • 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 RailsTest Driven DevelopmentBehavior Driven DevelopmentTest Anything with CucumberAdvanced Domain Modeling with ActiveRecordDomain Driven Development with Rails 65
  • 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
  • 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