Ruby On Rails Seminar Basis Softexpo Feb2010


Published on

  • Be the first to comment

  • Be the first to like this

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

No notes for slide
  • source:
  • Discuss about the dynamically generated accessor methods because of association.
  • There are 20 callbacks. 18 are before/after pairs, 2 are after_find and after_initialize
  • 2 ways to define callback
  • 1 :multipart - If set to true, the enctype is set to "multipart/form-data". 2 :method - The method to use when submitting the form, usually either "get" or "post". If "put", "delete", or another verb is used, a hidden input with name _method is added to simulate the verb over post. 3 A list of parameters to feed to the URL the form will be posted to.
  • Ruby On Rails Seminar Basis Softexpo Feb2010

    1. 1. Introduction to RoR: A beautiful framework for today’s web. Presented By Code71 Bangladesh Ltd. Organized by BASIS
    2. 2. Preview <ul><li>Background </li></ul><ul><li>Business Implication </li></ul><ul><li>Introduction </li></ul><ul><li>ROR and MVC </li></ul><ul><li>Convention over configuration in rails </li></ul><ul><li>ActiveRecord - The Rails ORM framework </li></ul><ul><li>ActionView - The ROR view renderer </li></ul><ul><li>ActionController - The core of a web request in ROR </li></ul><ul><li>Data Migration </li></ul><ul><li>Ajax </li></ul><ul><li>Built in test framework </li></ul><ul><li>Logging framework </li></ul><ul><li>REST support </li></ul><ul><li>Gems and plugins - Package manager for ruby </li></ul><ul><li>Demo application - Build a web application in minutes </li></ul><ul><li>Demo of a real life web application built on rails </li></ul><ul><li>Future of rails </li></ul><ul><li>Q&A </li></ul>
    3. 3. Background of RoR <ul><li>Created in 2003 by David Heinemeier Hansson </li></ul><ul><li>Extended by the Rails core team, more than 1,400 contributors </li></ul><ul><li>First public release in July 2004. </li></ul><ul><li>David Heinemeier Hansson had won the &quot;Hacker of the Year&quot; award for this software package in 2005. </li></ul><ul><li>Rails won the 2006 Jolt Award for best Web development tool.  </li></ul>
    4. 4. Background of RoR <ul><li>Ruby:  a language, comparable to Python or Perl born in 1993! </li></ul><ul><li>Ruby on Rails : a framework, written in Ruby built in 2003 </li></ul><ul><li>Extracted from real world application:  As Hansson and others worked on the application, they found out—for the hundredth time—that Web development is painful, time-consuming, repetitive and detail-oriented. This made it a good candidate for coding in Ruby. Goal was to build an application - Basecamp. </li></ul><ul><li>In the process of writing this high-level, condensed Ruby code, Hansson started to abstract away the essentials of the interface, and the result became Ruby on Rails. It was born from real-world needs, from working code and from the everyday experiences of developers. </li></ul>
    5. 5. Why Ruby on Rails? <ul><li>Out of the box architecture for persistence, logging, build scripts, test, web-tier components. </li></ul><ul><li>Pragmatic philosophy of convention over configuration </li></ul><ul><li>Built on Ruby, fully featured object-oriented language. </li></ul><ul><li>Built in templating engine to generate web pages, emails, xml and text documents. </li></ul><ul><li>Well thought out object relationship mapping tool, ActiveRecord. </li></ul><ul><li>Built in AJAX, REST, Web service, configuration for development, test and production environment. </li></ul><ul><li>Migration for applying or roll back database changes. </li></ul><ul><li>Comprehensive test framework </li></ul>
    6. 6. Why Ruby on Rails? Contd. <ul><li>class Project < ActiveRecord::Base </li></ul><ul><li>belongs_to :portfolio has_one :project_manager has_many :milestones has_many :deliverables, :through => :milestones </li></ul><ul><li>validates_presence_of :name, :description validates_acceptance_of :non_disclosure_agreement validates_uniqueness_of :short_name </li></ul><ul><li>end </li></ul>
    7. 7. Cons of Ruby on Rails <ul><li>As Ruby is a dynamic language, more automated testing is required. </li></ul><ul><li>Developers will need to become more disciplined and rigorous in creating unit tests as part of their development process. </li></ul><ul><li>Rails is optimized for building web applications . </li></ul>
    8. 8. Delivering Business Values <ul><li>Ruby on Rails simplifies the web development process through its </li></ul><ul><li>convention over configuration and Don’t repeat yourself it fundamentally changes the role of the programmer in web development. </li></ul><ul><li>Instead of asking questions like “How do I get function x to call method y?”, he is able to focus or  how to do something , he is freed to focus more on the general business logic of the application. </li></ul><ul><li>This is why Ruby on Rails and the Agile software development movement go hand in hand. </li></ul>
    9. 9.   Delivering Business Values <ul><ul><li>Rails provides an integrated application testing framework that will help find errors before your users find them which saves money in the long run. </li></ul></ul><ul><ul><li>Rails redefined RAD ( Rapid Application Development ) for the web. Leveraging this speed of development has shown to save both time and money. </li></ul></ul><ul><ul><li>Rails also simplifies AJAX to allow for enhanced usability and a more satisfying end user experience. </li></ul></ul><ul><ul><li>Due to Rails mantra of &quot; convention over configuration &quot;, those familiar with the Rails framework can easily anticipate how the application works resulting in a highly maintainable code base. </li></ul></ul><ul><ul><li>When Rails first emerged, Rails had a reputation for not being scalable , but newer versions of Rails have overcome that reputation and now power some of the largest sites on the internet. </li></ul></ul><ul><ul><li>Rails has a wealth of plugins and third party (commercial and open source) solutions which prevent developers having to spend time and money reinventing the wheel for each application. </li></ul></ul>
    10. 10. Rails is Agile <ul><li>Individuals and interactions over processes and tools </li></ul><ul><li>No complex configuration, no heavy toolsets </li></ul><ul><li>Working software over comprehensive documentation </li></ul><ul><li>Customer collaboration over contract negotiation </li></ul><ul><li>a framework that delivers working software early in the development cycle.This software may be rough around the edges, but it lets the users start to get a glimpse of what you’ll be delivering.   </li></ul><ul><li>In this way, Rails encourages customer collaboration. When customers seejust how quickly a Rails project can respond to change, they start to trust that the team can deliver what’s required. </li></ul><ul><li>Responding to change over following a plan </li></ul><ul><li>DRY principal- easy maintenance </li></ul><ul><li>Ruby dynamic language more expressive </li></ul><ul><li>Comprehensive tests -regression </li></ul>
    11. 11.   Delivering Business Values <ul><li>Do not compile. In Ruby, there is no concept of compilation. Everything runs at runtime.  </li></ul><ul><li>Dynamically enhance the behavior of a class - without a Decorator </li></ul><ul><li>Slim down your code base 10-20% by stripping off all type declarations and interface declarations. </li></ul><ul><li>Ajax it in no time. </li></ul><ul><li>With Rails, you don’t need an O/R Mapper. </li></ul><ul><li>Using Ruby script to build/deploy/release is better than using NAnt. </li></ul><ul><li>No pain no gain. </li></ul>
    12. 12. Great user quotes <ul><li>“ Rails is the most well thought-out web development framework I’ve ever used. And that’s in a decade of doing web applications for a living. I’ve built my own frameworks, helped develop the Servlet API, and have created more than a few web servers from scratch. Nobody has done it like this before.” </li></ul><ul><li>-James Duncan Davidson, Creator of Tomcat and Ant </li></ul><ul><li>  </li></ul><ul><li>“ Ruby on Rails is a breakthrough in lowering the barriers of entry to programming. Powerful web applications that formerly might have taken weeks or months to develop can be produced in a matter of days.” </li></ul><ul><li>-Tim O'Reilly, Founder of O'Reilly Media </li></ul>
    13. 13. Great user quotes -contd. <ul><li>“ It is impossible not to notice Ruby on Rails. It has had a huge effect both in and outside the Ruby community... Rails has become a standard to which even well-established tools are comparing themselves to.” </li></ul><ul><li>-Martin Fowler, Author of Refactoring, PoEAA, XP Explained </li></ul><ul><li>  </li></ul><ul><li>“ Rails is the killer app for Ruby.” </li></ul><ul><li>Yukihiro Matsumoto, Creator of Ruby </li></ul>
    14. 14. Great user quotes -contd. <ul><li>“ After researching the market, Ruby on Rails stood out as the best choice. We have been very happy with that decision. We will continue building on Rails and consider it a key business advantage.” </li></ul><ul><li>-Evan Williams, Creator of Blogger, ODEO, and Twitter </li></ul><ul><li>  </li></ul><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, O'Reilly Program Chair for OSCON </li></ul>
    15. 15. Great user quotes-contd. <ul><li>What sets this framework apart from all of the others is the preference for convention over configuration making applications easier to develop and understand.” </li></ul><ul><li>-Sam Ruby, ASF(Apache Software Foundation) board of directors </li></ul>
    16. 16. Great sites built on Rails(Contd.) <ul><li>News Unlimited </li></ul><ul><li>Yes, New york times!! </li></ul>
    17. 17. Great sites built on Rails(Contd.) <ul><li>Document Sharing </li></ul><ul><li>Yes, Scribd!! </li></ul>
    18. 18. Great sites built on Rails(Contd.) <ul><li>Create an online store! </li></ul><ul><li>Yes, Shopify!! </li></ul>
    19. 19. Great sites built on Rails(Contd.) <ul><li>Check fashion. </li></ul><ul><li>Yes, MTV Style!! </li></ul>
    20. 20. Great sites built on Rails(Contd.) <ul><li>Social coding. </li></ul><ul><li>Yes, Github!! </li></ul>
    21. 21. Great sites built on Rails(Contd.) <ul><li>Box office in Home. </li></ul><ul><li>Yes, HBO!! </li></ul>
    22. 22. Great sites built on Rails(Contd.) <ul><li>Presentation sharing. </li></ul><ul><li>Yes, Slideshare!! </li></ul>
    23. 23. <ul><li>BREAK </li></ul>
    24. 24. MVC  
    25. 25. Rails and MVC  
    26. 26. Directory structure in rails: <ul><li>•   app </li></ul><ul><ul><li>- Controllers </li></ul></ul><ul><ul><li>- Helpers </li></ul></ul><ul><ul><li>- Models </li></ul></ul><ul><ul><li>Views </li></ul></ul><ul><li>•   config </li></ul><ul><ul><li>- environment.rb </li></ul></ul><ul><ul><li>routes.rb </li></ul></ul><ul><li>•   db </li></ul><ul><ul><li>- database.yml </li></ul></ul><ul><ul><li>  migrations </li></ul></ul><ul><li>•   components </li></ul><ul><li>•   doc </li></ul><ul><li>•   lib </li></ul><ul><li>•   log </li></ul><ul><li>•   public </li></ul><ul><li>•   script </li></ul><ul><li>•   test </li></ul><ul><li>•   vendor </li></ul>
    27. 27. Routes <ul><li>Connects URLs to Code </li></ul><ul><li>GET /patients/17 </li></ul><ul><li>The application would end up running the show action within the patients controller </li></ul><ul><li>Generates URLs from Code </li></ul><ul><li>@patient = Patient.find(17) </li></ul><ul><li><%= link_to &quot;Patient Record&quot;, patient_path(@patient) %> </li></ul><ul><li>Translates that to a link to a URL such as /patients/17 </li></ul>
    28. 28. Routes <ul><li>Default route </li></ul><ul><li>map.connect ':controller/:action/:id' </li></ul><ul><li>map.connect ':controller/:action/:id.:format' </li></ul>
    29. 29. Sample Controller, Action & View <ul><li>Controller and Action(app/controllers/hello_controller.rb): </li></ul><ul><li>class HelloController < ApplicationController </li></ul><ul><li>def say_hello </li></ul><ul><li>@user_name = “John Doe” </li></ul><ul><li>end </li></ul><ul><li>end </li></ul><ul><li>View(app/views/hello/say_hello.rhtml): </li></ul><ul><li><b>Hello <%=@user_name%>!</b> Welcome to demo app. </li></ul>
    30. 30. Sample Request & Response <ul><li>Browser Request: </li></ul><ul><li>http://localhost:3000/hello/say_hello </li></ul><ul><li>Browser Response: </li></ul><ul><li>Hello John Doe! Welcome to demo app. </li></ul>
    31. 31. What is migration and why? <ul><li>What ? </li></ul><ul><li>Migration allows us to use Ruby to define changes to our database schema incrementally, making it possible to use a version control system to keep things synchronized with the actual code </li></ul><ul><li>Why ? </li></ul><ul><ul><li>Allows incremental development of database  </li></ul></ul><ul><ul><li>Allows easy roll out of a new version of a database   </li></ul></ul><ul><ul><li>Allows easy roll back to previous versions  </li></ul></ul><ul><ul><li>Allows to change the database anytime  </li></ul></ul>
    32. 32. Understanding Migration Script <ul><li>Generating a migration script </li></ul><ul><li>ruby script/generate migration create_companies </li></ul><ul><li>Name of the generated migration script </li></ul><ul><ul><li>db/migrate/001_create_companies.rb </li></ul></ul><ul><li>In this file we will get a class called “CreateCompanies” </li></ul><ul><li>having two methods “self.up” and “self.down” </li></ul><ul><ul><li>self.up - is used when migrating to a new version     </li></ul></ul><ul><ul><li>self.down - is used to roll back  changes made in self.up </li></ul></ul>
    33. 33. Understanding Migration Script <ul><li>class CreateCompanies < ActiveRecord::Migration </li></ul><ul><li>def self.up </li></ul><ul><li>   create_table :companies do |table| </li></ul><ul><ul><ul><li>table.column :name, :string </li></ul></ul></ul><ul><ul><ul><li>end </li></ul></ul></ul><ul><li>end </li></ul><ul><li>  </li></ul><ul><li>def self.down </li></ul><ul><ul><li>drop_table :companies </li></ul></ul><ul><li>end </li></ul><ul><li>end </li></ul><ul><li>Migrate to specific version     </li></ul><ul><ul><li>rake db:migrate VERSION=3 </li></ul></ul><ul><li>Migration on different environment </li></ul><ul><ul><li>rake  db:migrate  RAILS_ENV=production </li></ul></ul>
    34. 34. ActiveRecord <ul><li>Object-relational mapping (ORM) layer supplied with Rails </li></ul><ul><li>Connects business objects and database tables </li></ul><ul><li>Creates a persistent domain model where logic and data are presented in one place </li></ul><ul><li>Plays the role of model in MVC architecture. </li></ul>
    35. 35. ActiveRecord contd. <ul><li>ActiveRecord closely follows the standard ORM model </li></ul><ul><ul><li>Tables map to classes </li></ul></ul><ul><ul><li>Rows to objects </li></ul></ul><ul><ul><li>Columns to object attributes </li></ul></ul><ul><li>ActiveRecord minimizes the amount of configuration that developers perform </li></ul>
    36. 36. ActiveRecord Contd. <ul><li>Tables and classes </li></ul><ul><li>Convention: </li></ul><ul><li>Table is the underscored plural form of the name of the class. </li></ul><ul><li>Example: </li></ul>Class Name Table Name Class Name Table Name Order orders Person people TaxAgency tax_agencies Datum data Batch batches Quantity quantities Diagnosis diagnoses LineItem line_items
    37. 37. ActiveRecord Contd. <ul><li>Columns and attributes </li></ul><ul><li>Active Record objects correspond to rows in a database table. </li></ul><ul><li>The objects have attributes corresponding to the columns in the table. </li></ul><ul><li>ActiveRecord determines columns in tables dynamically at runtime. </li></ul>
    38. 38. ActiveRecord Contd. <ul><li>Columns and attributes </li></ul><ul><li>users table: </li></ul><ul><li>User class in models/user.rb </li></ul><ul><li>class User < ActiveRecord::Base </li></ul><ul><li>end </li></ul><ul><li>Objects of user class dynamically contains setter and getter methods for the columns of users table. </li></ul>Users id integer first_name string last_name string user_name string password string
    39. 39. ActiveRecord Contd. <ul><li>Create a model object </li></ul><ul><li>u = User.create(:first_name => “John”, :last_name=>”Doe”, </li></ul><ul><li>:user_name=>”scrumpad”, :password => “anything” </li></ul><ul><li>This will execute sql: </li></ul><ul><li>INSERT INTO users(first_name, last_name, user_name, </li></ul><ul><li>password) VALUES(‘John’, ‘Doe’, ’scrumpad’, ’anything’) ‏ </li></ul><ul><li>u.first_name will produce “John” </li></ul><ul><li>u.last_name will produce “Doe” </li></ul>
    40. 40. ActiveRecord Contd. <ul><li>Find a model object </li></ul><ul><li>By Id: </li></ul><ul><li>u = User.find(1) ‏ </li></ul><ul><li>By Name: </li></ul><ul><li>u = User.find_by_first_name(“John”) ‏ </li></ul><ul><li>Update a model object </li></ul><ul><li>u.first_name = “John1” </li></ul><ul><li> </li></ul>
    41. 41. ActiveRecord Contd. <ul><li>Conditions to find ActiveRecord </li></ul><ul><li>Find all records having first name = “John” </li></ul><ul><li>users = User.find(:all, :conditions=>”first_name = ‘John’”) ‏ </li></ul>
    42. 42. ActiveRecord associations <ul><li>Models : </li></ul><ul><li>1. Company </li></ul><ul><li>2. User </li></ul><ul><li>3. Address </li></ul><ul><li>4. Role </li></ul>Class A Class B Foreign Keys Mapping class User has_one :address end class Address belongs_to :user end addresses.user_id One user maps to zero or one address class Company has_many :users end class User belongs_to :company end users.company_id One company maps to zero or more user s class Role has_and_belongs_to_many :users end class User has_and_belongs_to_many :roles end roles_users.role_id roles_users.user_id Any number of role s maps to any number of user s
    43. 43. ActiveRecord Validations <ul><li>Validations are methods to validate the contents of a model object </li></ul><ul><li>If validation fails an object will not be written to the db. It will be left in memory with its current invalid state. </li></ul><ul><li>Validations can be performed on save, create or update </li></ul>
    44. 44. ActiveRecord Validation Helpers <ul><li>class User < ActiveRecord::Base </li></ul><ul><li>validates_presence_of :user_name, :email </li></ul><ul><li>validates_uniqueness_of :user_name </li></ul><ul><li>end </li></ul>
    45. 45. ActiveRecord Callbacks <ul><li>Allows to write code to be invoked at a particular part of AR lifecycle. </li></ul>
    46. 46. ActiveRecord Callbacks Contd. <ul><li>Directly </li></ul><ul><li>class Order < ActiveRecord::Base </li></ul><ul><li>#...... </li></ul><ul><li>def before_save </li></ul><ul><li>self.payment_due ||= + 30.days </li></ul><ul><li>end </li></ul><ul><li>end </li></ul><ul><li>Using a handler </li></ul><ul><li>class Order < ActiveRecord::Base </li></ul><ul><li>before_validation :normalize_credit_card_number </li></ul><ul><li>after_create do |order| </li></ul><ul><li> &quot;Order #{} created“ </li></ul><ul><li>end </li></ul><ul><li>protected </li></ul><ul><li>def normalize_credit_card_number </li></ul><ul><li>self.cc_number.gsub!(/-w/, '' ) </li></ul><ul><li>end </li></ul><ul><li>end </li></ul>
    47. 47. <ul><li>Break </li></ul>
    48. 48. ActionController <ul><li>A controller object processes a request </li></ul><ul><li>It looks for a public instance method with the same name as the incoming action </li></ul><ul><li>If it finds one, that method is invoked - if not, but the controller implements method_missing, that method is called, passing in the action name as the first parameter and an empty argument list </li></ul><ul><li>If no method can be called, the controller looks for a template named after the current controller and action if found, this template is rendered </li></ul><ul><li>If none of these things happen, an ‘ Unknown Action’ </li></ul>
    49. 49. ActionController Contd. <ul><li>Responding to users </li></ul><ul><li>Controllers respond to users in four basic ways </li></ul><ul><li>Render a template – a template is a view. Takes info provided by controller and uses it to generate response </li></ul><ul><li>Return a string to the browser without rendering a view – rarely used. </li></ul><ul><li>Can return nothing – for example during AJAX calls </li></ul><ul><li>Can return ‘other’ data to client (other then html) like a pdf, or word document. </li></ul>
    50. 50. ActionController Contd. <ul><li>Responding to users </li></ul><ul><li>Controllers always respond once – that means every controller method only has one call to render – throws multiple render error otherwise. </li></ul><ul><li>Because it must respond once, controller checks to see if a response has been generated before it finishes handling a request. </li></ul><ul><li>If it finds no calls to the above methods – it looks for a template named after the controller and action and renders it </li></ul><ul><li>You can have multiple templates with the same name – but different extensions. – ie. .rhtml, .rxml, .rjs. </li></ul><ul><li>Searches in the order above for tempates. </li></ul>
    51. 51. ActionController Contd. <ul><li>Render method </li></ul><ul><li>At the heart of rendering in Rails </li></ul><ul><li>Takes a hash of options that tell it what to render and how. </li></ul><ul><li>For example: </li></ul><ul><li>def update </li></ul><ul><li>@user = User.find(params[:id]) </li></ul><ul><li>if @user.update_attributes(params[:user]) </li></ul><ul><li>render :action => :show </li></ul><ul><li>else </li></ul><ul><li>render :template => &quot;fix_user_errors“ </li></ul><ul><li>end </li></ul><ul><li>end </li></ul>
    52. 52. Templates <ul><li>A Template is a file that defines the content of a response. </li></ul><ul><li>3 formats </li></ul><ul><ul><li>rhtml – html with imbedded ruby </li></ul></ul><ul><ul><li>rxml – a programmatic way of constructing xml content </li></ul></ul><ul><ul><li>Rjs – generates javascript. </li></ul></ul>
    53. 53. Helpers <ul><li>A helper is a module that contains methods that assist a view. </li></ul><ul><li>They are output-centric and exist to output html (or view code) </li></ul><ul><li>Why use them? Easier to edit your RHTML, easier to test your helper files. </li></ul><ul><li>By default each controller gets a helper modlue in the app/helpers directory. </li></ul>
    54. 54. Helpers Contd. <ul><li><h3><%= @page_title || “My charity&quot; %></h3> </li></ul><ul><li>This is a simple example, but if you had this code in each template you begin to let duplication slip in. </li></ul><ul><li>Say you wanted to modify the title of your store to ‘Chrismas Charity’! </li></ul><ul><li>You have to edit every template. </li></ul>
    55. 55. Helper Contd. <ul><ul><li>module CharityHelper </li></ul></ul><ul><ul><ul><li>def page_title </li></ul></ul></ul><ul><ul><ul><ul><li>@page_title || &quot;Pragmatic Store&quot; </li></ul></ul></ul></ul><ul><ul><ul><li>end </li></ul></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>---- </li></ul></ul><ul><ul><li><h3><%= page_title %></h3> </li></ul></ul>
    56. 56. Form <ul><li>form_tag (url_for_options = {}, options = {}, *parameters_for_url, &block) </li></ul><ul><li>Options: </li></ul><ul><li>1 :multipart - If set to true, the enctype is set to &quot;multipart/form-data&quot;. </li></ul><ul><li>2 :method - Usually either &quot;get&quot; or &quot;post&quot;. If &quot;put&quot;, &quot;delete&quot; or another verb is used, a hidden input with name _method is added to simulate the verb over post. </li></ul><ul><li>3 A list of parameters to feed to the URL the form will be posted to. </li></ul><ul><li>Example: </li></ul><ul><li><% form_tag {:controller=>”product”, :action=>”create” } do %> </li></ul><ul><li><%= text_field_tag(:product_name) %> </li></ul><ul><li><%= submit_tag(“Save&quot;) %> </li></ul><ul><li><% end %> </li></ul><ul><li>Generated Code: </li></ul><ul><li><form action=&quot;/product/create&quot; method=&quot;post&quot;> </li></ul><ul><li><input id=&quot;my_name&quot; name=“product_name&quot; type=&quot;text&quot; /> </li></ul><ul><li><input name=&quot;commit&quot; type=&quot;submit&quot; value=“Save&quot; /> </li></ul><ul><li></form> </li></ul>
    57. 57. Advanced Form(form_for) Contd. <ul><li>form_for (record_or_name_or_array, *args, &proc) </li></ul><ul><li>Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields. </li></ul><ul><li>Example: </li></ul><ul><li><% form_for @product do |f| %> </li></ul><ul><li><%= f.text_field :name %> </li></ul><ul><li><%= f.text_field :price, :size => 10 %> </li></ul><ul><li><%= f.text_field :amount, :size =>5 %> </li></ul><ul><li><%= submit_tag &quot;New Product&quot; %> </li></ul><ul><li><% end %> </li></ul><ul><li>Generated Code: </li></ul><ul><li><form action=&quot;/products“ id=&quot;new_product&quot; method=&quot;post&quot;> </li></ul><ul><li><input id=&quot;product_name&quot; name=“product[name]“ type=&quot;text&quot; /> </li></ul><ul><li><input id=&quot;product_price&quot; name=“product[price]&quot; size=&quot;10&quot; type=&quot;text&quot; /> </li></ul><ul><li><input id=&quot;product_amount&quot; name=“product[amount]&quot; size=&quot;5&quot; type=&quot;text&quot; /> </li></ul><ul><li><input id=&quot;product_submit&quot; name=&quot;commit&quot; type=&quot;submit&quot; value=&quot;Update&quot; /> </li></ul><ul><li></form> </li></ul>
    58. 58. Handling errors in form <ul><li>error_messages and error_messages_for </li></ul><ul><li>Example: </li></ul><ul><li>Display all of the error messages </li></ul><ul><li><% form_for(@product) do |f| %> </li></ul><ul><li><%= f.error_messages %> </li></ul><ul><li><!-- different form tags --> </li></ul><ul><li><% end %> </li></ul><ul><li>Display error message of a specific field </li></ul><ul><li><% form_for(@product) do |f| %> </li></ul><ul><li><%= error_messages_for :name %> </li></ul><ul><li><!-- different form tags --> </li></ul><ul><li><% end %> </li></ul>
    59. 59. Ajax <ul><li>Links </li></ul><ul><li><%= link_to_remote &quot;Check Time&quot;, :url => { :action => 'get_time' }, :update => 'current_time', %> </li></ul><ul><li><div id=&quot;current_time&quot;> </li></ul><ul><li></div> </li></ul>
    60. 60. Ajax <ul><li>Callbacks </li></ul><ul><li><%= link_to_remote &quot;Check Time&quot;, :url => { :action => 'get_time' }, </li></ul><ul><li>:update => 'current_time', </li></ul><ul><li>:before => &quot;$('current_time').update('Loading...')&quot; %> </li></ul><ul><li><div id=&quot;current_time&quot;> </li></ul><ul><li></div> </li></ul>
    61. 61. Ajax <ul><li>Callbacks </li></ul><ul><li><%= link_to_remote &quot;Check Time&quot;, </li></ul><ul><li>:update => 'current_time', </li></ul><ul><li>:url => { :action => 'get_time' }, </li></ul><ul><li>:before => &quot;$('indicator').show( )&quot;, </li></ul><ul><li>:success => &quot;$('current_time').visualEffect('highlight')&quot;, </li></ul><ul><li>:failure => &quot;alert('There was an error. ')&quot;, </li></ul><ul><li>:complete => &quot;$('indicator').hide( )&quot; %> </li></ul><ul><li><span id=&quot;indicator&quot; style=&quot;display: none;&quot;>Loading...</span> </li></ul><ul><li><div id=&quot;current_time&quot;></div> </li></ul>
    62. 62. Ajax <ul><li>Ajax Forms </li></ul><ul><li><% form_remote_tag :url => { :action => 'reverse' }, </li></ul><ul><li>:update => &quot; reversed ” do %> </li></ul><ul><li><p>Text to reverse: </li></ul><ul><li><%= text_field_tag 'text_to_reverse' %></p> </li></ul><ul><li><p id=&quot; reversed &quot;></p> </li></ul><ul><li><p><%= submit_tag 'Reverse!' %></p> </li></ul><ul><li><% end %> </li></ul>
    63. 63. Ajax <ul><li>Ajax Buttons </li></ul><ul><li><% form_tag :action => 'reverse' do%> </li></ul><ul><li><p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p> </li></ul><ul><li><p id=&quot; reversed &quot;></p> </li></ul><ul><li><p><%= submit_to_remote 'submit', 'Submit via Ajax', </li></ul><ul><li>:update => ' reversed ', :url => { :action => 'reverse' } %> </li></ul><ul><li></p> </li></ul><ul><li><p> <%= submit_tag &quot;Submit non-Ajax&quot; %></p> </li></ul><ul><li><% end %> </li></ul>
    64. 64. Ajax <ul><li>Buttons for arbitrary functions </li></ul><ul><li><%= button_to_function &quot;Greet&quot;, &quot;alert('Hello world!')&quot; %> </li></ul><ul><li><%= button_to_function &quot;Check Time&quot;, </li></ul><ul><li>remote_function(:url => { :action => 'get_time' }, :update => &quot;current_time&quot;) %> </li></ul>
    65. 65. Ajax <ul><li>RJS </li></ul>RJS is Ruby code that generates JavaScript code
    66. 66. Ajax <ul><li>RJS </li></ul><ul><li>def alert_without_rjs </li></ul><ul><li>render :text => &quot;alert('Hello without RJS')&quot; , </li></ul><ul><li>:content_type => &quot;text/javascript&quot; </li></ul><ul><li>end </li></ul><ul><li>def alert_with_rjs </li></ul><ul><li>render :update do | page | </li></ul><ul><li>page.alert &quot;Hello from inline RJS&quot; </li></ul><ul><li>end </li></ul><ul><li>end </li></ul><ul><li><%= link_to_remote &quot;Alert without RJS&quot;, :url => { :action => &quot;alert_without_rjs&quot; } %> </li></ul><ul><li><%= link_to_remote &quot;Alert with RJS&quot;, :url => { :action => &quot;alert_with_rjs&quot; } %> </li></ul>
    67. 67. Ajax <ul><li>RJS files </li></ul>Controller.rb: def alert_with_rjs end Views/controller/alert_with_rjs.rjs page.alert &quot;Hello from RJS file&quot; <%= link_to_remote &quot;Alert with RJS&quot;, :url => { :action => &quot;alert_with_rjs&quot; } %>
    68. 68. Ajax <ul><li>Element proxies </li></ul><div id=&quot;my_div&quot; class=&quot;green box&quot;>DIV</div> page[:my_div].show Generates javascript $('my_div').show();
    69. 69. Ajax <ul><li>replace and replace_html </li></ul>replace_html replaces the contents of an element (accessed as innerHTML) replace replaces the whole element, including its start and end tags (accessed as outerHTML)
    70. 70. Ajax <ul><li>replace and replace_html </li></ul>replace_html.rjs page[:my_div].replace_html &quot;New Text“ replace.rjs : page[:my_div].replace &quot;New Text&quot;
    71. 71. Ajax <ul><li>Effects of replace and replace_html </li></ul>replace_html replace Original <body> <div id=&quot;my_div&quot;> DIV </div> </body> <body> <div id=&quot;my_div&quot;> DIV </div> </body> RJS page[:my_div].replace_html &quot;New Text&quot; page[:my_div].replace &quot;New Text&quot; Result <body> <div id=&quot;my_div&quot;> New Text </div> </body> <body> New Text </body>
    72. 72. Logger <ul><li>Log levels: </li></ul><ul><ul><li>Debug </li></ul></ul><ul><ul><li>Info </li></ul></ul><ul><ul><li>Warn </li></ul></ul><ul><ul><li>Error </li></ul></ul><ul><ul><li>Fatal  </li></ul></ul><ul><li>Ruby's Logger supports masking levels so the types of messages recorded in the log can be controlled. </li></ul><ul><li>By default, Rails will log all levels (debug and higher) in every environment except production. </li></ul><ul><li>In the production environment, it will only log info and higher. This behavior can be changed in the configuration for each environment. </li></ul>
    73. 73. Testing <ul><ul><li>Has built-in framework for Unit and Functional test </li></ul></ul><ul><ul><li>Use different database for testing which allows testing without any danger of production data. </li></ul></ul><ul><ul><li>Generate test file while creating models and controllers </li></ul></ul><ul><ul><li>Rails tests can simulate browser requests and thus you can test response without having to test it through browser. </li></ul></ul>
    74. 74. Testing <ul><li>Fixtures </li></ul><ul><ul><li>Human readable data representations of a table. File name like table_name.yml </li></ul></ul><ul><ul><li>Allow to populate testing database with predefined data before tests run. </li></ul></ul><ul><ul><li>While running test framework remove all existing data from database and dump the fixture data into database </li></ul></ul><ul><ul><li>Stored in test/fixtures/ </li></ul></ul>
    75. 75. Testing <ul><li>Unit Test </li></ul><ul><ul><li>Written for Models </li></ul></ul><ul><ul><li>Testing library is placed on test/unit/ and file name like model_name_test.rb </li></ul></ul><ul><li>Functional Test </li></ul><ul><ul><li>Written against controller instance, simulate request against it, and make assertions about the responses </li></ul></ul><ul><ul><li>Testing library placed on test/functional/ and file name like controller_name_test.rb </li></ul></ul>
    76. 76. Unit test example <ul><li>class UserTest < Test::Unit::TestCase </li></ul><ul><li>fixtures :companies, :users, :projects </li></ul><ul><li>def test_get_user_by_company </li></ul><ul><li>users = User.get_user_by_company(companies(:one).id) ‏ </li></ul><ul><li>assert_not_nil users </li></ul><ul><li>assert_equal 3,users.length </li></ul><ul><ul><li>end </li></ul></ul><ul><li>end </li></ul>
    77. 77. Assertions used in unit testing <ul><li>assert(actual, comment) </li></ul><ul><li>assert_equal(expected, actual, comment) ‏ </li></ul><ul><li>assert_match(pattern, string, message) ‏ </li></ul><ul><li>assert_nil(object, message)/assert_not_nil </li></ul><ul><li>assert_raise(Exception, ..., message) { block ... } </li></ul><ul><li>assert_difference(expressions, difference = 1, &block) ‏ </li></ul>
    78. 78. Functional test example <ul><li>class UserControllerTest < Test::Unit::TestCase </li></ul><ul><ul><li>fixtures :companies, :users, :projects </li></ul></ul><ul><ul><li>def setup </li></ul></ul><ul><ul><li>@controller = </li></ul></ul><ul><ul><li>@request = </li></ul></ul><ul><ul><li>@response = </li></ul></ul><ul><ul><li>@request.env['HTTP_HOST'] = &quot;localhost&quot; </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><ul><li>def test_get_user </li></ul></ul><ul><ul><li>get :show, :id => users(:admin).id </li></ul></ul><ul><ul><li>assert_response :success </li></ul></ul><ul><ul><li>assert_not_nil assigns(:user) ‏ </li></ul></ul><ul><ul><li>end </li></ul></ul><ul><li>end </li></ul>
    79. 79. Functional test assertions <ul><li>assert_response :success|:redirect|:missing|:error </li></ul><ul><li>assert_redirected_to(:controller => ‘blog’, :action =>‘list’) ‏ </li></ul><ul><li>assert_template ‘store/index’ </li></ul>
    80. 80. Gem/Plugin <ul><li>A gem/plugin is a component that can add to your application to extend its functionality. You can write your own and publish and can use existing one. Command to install a plugin: $ ruby script/plugin install plugin_url </li></ul><ul><li>Command to install a gem: $ gem install gem_with_opotion </li></ul>
    81. 81. ActiveSupport <ul><li>Utility classes and standard library extensions </li></ul><ul><li>Examples: </li></ul><ul><li>20.minutes.ago </li></ul><ul><li>Time_ago_in_words </li></ul><ul><li>1.gigabyte </li></ul><ul><li>Titelize </li></ul><ul><li>Humanize </li></ul>
    82. 82. Future of ROR-Rails 3 <ul><li>Rails 3 = Rails + Merb </li></ul><ul><li>  </li></ul><ul><li>Merb was started two years ago by Ezra Zygmuntowicz as a tiny framework to serve ERb templates from Mongrel. This quickly grew into much more and carved out a niche as an alternative Rails stack. Merbists focused on among other things a small speedy core, being ORM/JavaScript agnostic, and having a rigorous API for extensions. </li></ul><ul><li>  </li></ul><ul><ul><li>Rails core: Yes, Rails is a full-stack framework and will remain so, but there’s no reason we shouldn’t also make it possible to run with less than the full monty. Rails 3 will make it easy to run just a bare minimum and then allow you to opt in just the stuff you want, if that’s necessary for your particular situation. Think “rails myapp—core” (and “rails myapp—flat”). </li></ul></ul>
    83. 83. Future of ROR-Rails 3 <ul><li>Performance optimizations: Merb has a lot of Rails pieces rewritten to be faster. We’ll be bringing all that good stuff over. We’ll also bend the architecture in the places where that’s necessary for a big yield. In short, Rails 3 will get all the performance attention that the Merb guys are known for. </li></ul><ul><li>  </li></ul><ul><ul><li>Framework agnosticism: Rails will always have a default answer to every question within the stack. If you don’t care about testing frameworks, you’ll get test/unit. If you don’t care about which ORM, you’ll get Active Record. But some people do care and want something else. Some people want RSpec for testing, others want to use Sequel or Data Mapper for ORM, others again prefer Haml for templating, and some might prefer jQuery for Ajax. All these people should feel like Rails is welcoming them with open arms. Yes, we’ll have a default, but we shouldn’t have any form of discrimination against alternatives. </li></ul></ul>
    84. 84. Future of Rails-Rails 3 <ul><li>Rigorous API: Too many plugins break when Rails is updated because it’s not clear where they can safely hook into the internals and when they’re monkeypatching and should expect things to break. The Merb guys committed to a public API with tests to ensure that it wouldn’t break. They’ll bring over that line of thinking and give Rails 3 a tested and documented API for extensions that won’t break willy-nilly with upgrades. </li></ul>
    85. 85. Demo <ul><li>How a small idea turns into an application, in Ruby on Rails way </li></ul>
    86. 86. Demo – Live rails application <ul><li>ScrumPad </li></ul><ul><li> </li></ul>
    87. 87. Ruby on Rails <ul><li>For further queries or interest in RoR training contact: </li></ul><ul><li>[email_address] </li></ul><ul><li> </li></ul>
    88. 88. Ruby on Rails <ul><li>Q & A </li></ul>
    89. 89. Presenters <ul><li>Arifur Rahman </li></ul><ul><li>Sr. Software Engineer </li></ul><ul><li> </li></ul><ul><li>Fuad Bin Omar </li></ul><ul><li>Sr. Software Engineer </li></ul><ul><li> </li></ul><ul><li>Md. Fattahul Alam </li></ul><ul><li> </li></ul><ul><li>Sr. Software Engineer </li></ul>
    90. 90. Ruby on Rails <ul><li>Thank You </li></ul>