SlideShare a Scribd company logo
Introduction to RoR: A beautiful framework for today’s web. Presented By Code71 Bangladesh Ltd. Organized by BASIS
Preview Background Business Implication Introduction ROR and MVC Convention over configuration in rails ActiveRecord - The Rails ORM framework ActionView - The ROR view renderer ActionController - The core of a web request in ROR Data Migration Ajax Built in test framework Logging framework REST support Gems and plugins - Package manager for ruby Demo application - Build a web application in minutes Demo of a real life web application built on rails Future of rails Q&A
Background of RoR Created in 2003 by David Heinemeier Hansson  Extended by the Rails core team, more than 1,400 contributors First public release in July 2004. David Heinemeier Hansson had won the "Hacker of the Year" award for this software package in 2005. Rails won the 2006 Jolt Award for best Web development tool. 
Background of RoR Ruby:  a language, comparable to Python or Perl born in 1993! Ruby on Rails : a framework, written in Ruby built in 2003 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. 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.
Why Ruby on Rails? Out of the box architecture for persistence, logging, build scripts, test, web-tier components. Pragmatic philosophy of convention over configuration Built on Ruby, fully featured object-oriented language. Built in templating engine to generate web pages, emails, xml and text documents. Well thought out object relationship mapping tool, ActiveRecord. Built in AJAX, REST, Web service, configuration for development, test and production environment. Migration for applying or roll back database changes. Comprehensive test framework
Why Ruby on Rails? Contd. class Project < ActiveRecord::Base belongs_to :portfolio has_one :project_manager has_many :milestones has_many :deliverables, :through => :milestones validates_presence_of :name, :description validates_acceptance_of :non_disclosure_agreement validates_uniqueness_of :short_name end
Cons of Ruby on Rails As Ruby is a dynamic language, more automated testing is required.  Developers will need to become more disciplined and rigorous in creating unit tests as part of their development process. Rails is optimized for building web applications .
Delivering Business Values Ruby on Rails simplifies the web development process through its  convention over configuration  and Don’t repeat yourself it fundamentally changes the role of the programmer in web development. 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. This is why Ruby on Rails and the Agile software development   movement go hand in hand.
  Delivering Business Values Rails provides an  integrated application testing framework  that will help find errors before your users find them which saves money in the long run. Rails redefined RAD ( Rapid Application Development ) for the web. Leveraging this speed of development has shown to save both time and money. Rails also  simplifies AJAX  to allow for enhanced usability and a more satisfying end user experience. 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. 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. 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.
Rails is Agile  Individuals and interactions over processes and tools No complex configuration, no heavy toolsets Working software over comprehensive documentation Customer collaboration over contract negotiation 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.   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. Responding to change over following a plan DRY principal- easy maintenance Ruby dynamic language more expressive Comprehensive tests -regression
  Delivering Business Values Do not compile. In Ruby, there is no concept of compilation. Everything runs at runtime.  Dynamically enhance the behavior of a class - without a Decorator Slim down your code base 10-20% by stripping off all type declarations and interface declarations. Ajax it in no time. With Rails, you don’t need an O/R Mapper. Using Ruby script to build/deploy/release is better than using NAnt. No pain no gain.
Great user quotes “ 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.” -James Duncan Davidson, Creator of Tomcat and Ant    “ 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.” -Tim O'Reilly, Founder of O'Reilly Media
Great user quotes -contd. “ 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.” -Martin Fowler, Author of Refactoring, PoEAA, XP Explained    “ Rails is the killer app for Ruby.” Yukihiro Matsumoto, Creator of Ruby
Great user quotes -contd. “ 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.” -Evan Williams, Creator of Blogger, ODEO, and Twitter    “ 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
Great user quotes-contd. What sets this framework apart from all of the others is the preference for convention over configuration making applications easier to develop and understand.” -Sam Ruby, ASF(Apache Software Foundation) board of directors
Great sites built on Rails(Contd.) News Unlimited Yes, New york times!!  http://www.nytimes.com
Great sites built on Rails(Contd.) Document Sharing Yes, Scribd!!     http://www.scribd.com/
Great sites built on Rails(Contd.) Create an online store! Yes, Shopify!!     http://www.shopify.com/
Great sites built on Rails(Contd.) Check fashion. Yes, MTV Style!!     http://www.mtv.com/
Great sites built on Rails(Contd.) Social coding. Yes, Github!!     http://github.com/
Great sites built on Rails(Contd.) Box office in Home.   Yes, HBO!!     http://www.hbosouthasia.com/
Great sites built on Rails(Contd.) Presentation sharing. Yes, Slideshare!!     http://www.slideshare.net/
BREAK
MVC  
Rails and MVC   
Directory structure in rails: •   app  - Controllers  - Helpers  - Models  Views  •   config  - environment.rb  routes.rb  •   db  - database.yml    migrations  •   components  •   doc  •   lib  •   log  •   public  •   script  •   test  •   vendor
Routes Connects URLs to Code GET /patients/17  The application would end up running the  show   action  within the  patients   controller Generates URLs from Code @patient = Patient.find(17)  <%= link_to &quot;Patient Record&quot;,  patient_path(@patient)  %> Translates that to a link to a URL such as http://example.com /patients/17
Routes Default route map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format'
Sample Controller, Action & View Controller and Action(app/controllers/hello_controller.rb): class HelloController < ApplicationController def say_hello @user_name = “John Doe” end end View(app/views/hello/say_hello.rhtml): <b>Hello <%=@user_name%>!</b>  Welcome to demo app.
Sample Request & Response Browser Request: http://localhost:3000/hello/say_hello Browser Response: Hello John Doe!  Welcome to demo app.
What is migration and why? What ?   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   Why ?   Allows incremental development of database  Allows easy roll out of a new version of a database   Allows easy roll back to previous versions  Allows to change the database anytime 
Understanding Migration Script Generating a migration script ruby script/generate migration create_companies  Name of the generated migration script db/migrate/001_create_companies.rb   In this file we will get a class called  “CreateCompanies” having two methods  “self.up”  and  “self.down”  self.up - is used when migrating to a new version     self.down - is used to roll back  changes made in self.up
Understanding Migration Script class CreateCompanies < ActiveRecord::Migration  def self.up     create_table :companies do |table| table.column :name, :string  end end     def self.down  drop_table :companies  end  end Migrate to specific version      rake db:migrate VERSION=3 Migration on different environment   rake  db:migrate  RAILS_ENV=production
ActiveRecord Object-relational mapping (ORM) layer supplied with Rails Connects business objects and database tables  Creates a persistent domain model where logic and data are presented in one place Plays the role of  model in MVC architecture.
ActiveRecord contd. ActiveRecord closely follows the standard ORM model Tables map to classes Rows to objects Columns to object attributes ActiveRecord minimizes the amount of configuration that developers perform
ActiveRecord Contd. Tables and classes Convention: Table is the underscored plural form of the name of the class. Example: 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
ActiveRecord Contd. Columns and attributes Active Record objects correspond to rows in a database table. The objects have attributes corresponding to the columns in the table. ActiveRecord determines columns in tables dynamically at runtime.
ActiveRecord Contd. Columns and attributes users table: User class in models/user.rb class User < ActiveRecord::Base end Objects of user class dynamically contains setter and getter methods for the columns of users table. Users id integer first_name string last_name string user_name string password string
ActiveRecord Contd. Create a model object u = User.create(:first_name => “John”, :last_name=>”Doe”,  :user_name=>”scrumpad”, :password => “anything” This will execute sql: INSERT INTO users(first_name, last_name, user_name, password) VALUES(‘John’, ‘Doe’, ’scrumpad’, ’anything’) ‏ u.first_name will produce “John” u.last_name will produce “Doe”
ActiveRecord Contd. Find a model object By Id: u = User.find(1) ‏ By Name: u = User.find_by_first_name(“John”) ‏ Update a model object u.first_name = “John1” u.save
ActiveRecord Contd. Conditions to find ActiveRecord Find all records having first name = “John” users =  User.find(:all, :conditions=>”first_name = ‘John’”) ‏
ActiveRecord associations Models : 1. Company 2. User 3. Address 4. Role 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
ActiveRecord Validations Validations are methods to validate the contents of a model object If validation fails an object will not be written to the db. It will be left in memory with its current invalid state. Validations can be performed on save, create or update
ActiveRecord Validation Helpers class User < ActiveRecord::Base validates_presence_of :user_name, :email validates_uniqueness_of :user_name end
ActiveRecord Callbacks Allows to write code to be invoked at a particular part of AR lifecycle.
ActiveRecord Callbacks Contd. Directly class Order < ActiveRecord::Base #...... def  before_save self.payment_due ||= Time.now + 30.days end end Using a handler class Order < ActiveRecord::Base before_validation :normalize_credit_card_number after_create do |order| logger.info &quot;Order #{order.id} created“ end protected def normalize_credit_card_number self.cc_number.gsub!(/-\w/, '' ) end end
Break
ActionController A controller object processes a request It looks for a public instance method with the same name as the incoming action 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 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 If none of these things happen, an  ‘ Unknown Action’
ActionController Contd. Responding to users Controllers respond to users in four basic ways Render a template – a template is a view.  Takes info provided by controller and uses it to generate response Return a string to the browser without rendering a view – rarely used. Can return nothing – for example during AJAX calls Can return ‘other’ data to client (other then html) like a pdf, or word document.
ActionController Contd. Responding to users Controllers always respond once – that means every controller method only has one call to render – throws multiple render error otherwise. Because it must respond once, controller checks to see if a response has been generated before it finishes handling a request. If it finds no calls to the above methods – it looks for a template named after the controller and action and renders it You can have multiple templates with the same name – but different extensions. – ie. .rhtml, .rxml, .rjs. Searches in the order above for tempates.
ActionController Contd. Render method At the heart of rendering in Rails Takes a hash of options that tell it what to render and how. For example: def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) render :action => :show else render :template => &quot;fix_user_errors“ end end
Templates A Template is a file that defines the content of a response. 3 formats  rhtml – html with imbedded ruby rxml – a programmatic way of constructing xml content Rjs – generates javascript.
Helpers A helper is a module that contains methods that assist a view.  They are output-centric and exist to output html (or view code) Why use them?  Easier to edit your RHTML, easier to test your helper files. By default each controller gets a helper modlue in the app/helpers directory.
Helpers Contd. <h3><%= @page_title || “My charity&quot; %></h3> This is a simple example, but if you had this code in each template you begin to let duplication slip in.  Say you wanted to modify the title of your store to ‘Chrismas Charity’! You have to edit every template.
Helper Contd. module CharityHelper def page_title @page_title || &quot;Pragmatic Store&quot; end end ---- <h3><%= page_title %></h3>
Form form_tag (url_for_options = {}, options = {}, *parameters_for_url, &block) Options: 1 :multipart - If set to true, the enctype is set to &quot;multipart/form-data&quot;. 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. 3  A list of parameters to feed to the URL the form will be posted to. Example: <%  form_tag  {:controller=>”product”, :action=>”create” } do %>  <%= text_field_tag(:product_name) %>  <%= submit_tag(“Save&quot;) %>  <% end %> Generated Code: <form action=&quot;/product/create&quot; method=&quot;post&quot;>  <input id=&quot;my_name&quot; name=“product_name&quot; type=&quot;text&quot; />  <input name=&quot;commit&quot; type=&quot;submit&quot; value=“Save&quot; />  </form>
Advanced Form(form_for) Contd. form_for (record_or_name_or_array, *args, &proc) Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields. Example: <%  form_for  @product do |f| %> <%= f.text_field :name %>  <%= f.text_field :price, :size => 10 %> <%= f.text_field :amount, :size =>5 %>  <%= submit_tag &quot;New Product&quot; %>  <% end %> Generated Code: <form action=&quot;/products“ id=&quot;new_product&quot; method=&quot;post&quot;>  <input id=&quot;product_name&quot; name=“product[name]“ type=&quot;text&quot; />  <input id=&quot;product_price&quot; name=“product[price]&quot; size=&quot;10&quot; type=&quot;text&quot; />  <input id=&quot;product_amount&quot; name=“product[amount]&quot; size=&quot;5&quot; type=&quot;text&quot; />  <input id=&quot;product_submit&quot; name=&quot;commit&quot; type=&quot;submit&quot; value=&quot;Update&quot; />  </form>
Handling errors in form error_messages and error_messages_for Example: Display all of the error messages <% form_for(@product) do |f| %>  <%=  f.error_messages  %>  <!-- different form tags -->  <% end %> Display error message of a specific field <% form_for(@product) do |f| %>  <%=  error_messages_for :name  %> <!-- different form tags -->  <% end %>
Ajax Links <%= link_to_remote &quot;Check Time&quot;,  :url => { :action => 'get_time' }, :update => 'current_time', %>  <div id=&quot;current_time&quot;> </div>
Ajax Callbacks <%= link_to_remote &quot;Check Time&quot;, :url => { :action => 'get_time' }, :update => 'current_time',  :before => &quot;$('current_time').update('Loading...')&quot; %>   <div id=&quot;current_time&quot;> </div>
Ajax Callbacks <%= link_to_remote &quot;Check Time&quot;,  :update => 'current_time',  :url => { :action => 'get_time' },  :before => &quot;$('indicator').show( )&quot;,  :success => &quot;$('current_time').visualEffect('highlight')&quot;,  :failure => &quot;alert('There was an error. ')&quot;,  :complete => &quot;$('indicator').hide( )&quot;   %>  <span id=&quot;indicator&quot; style=&quot;display: none;&quot;>Loading...</span>  <div id=&quot;current_time&quot;></div>
Ajax Ajax Forms <% form_remote_tag :url => { :action => 'reverse' }, :update => &quot; reversed ” do %>  <p>Text to reverse:  <%= text_field_tag 'text_to_reverse' %></p>  <p id=&quot; reversed &quot;></p>  <p><%= submit_tag 'Reverse!' %></p>  <% end %>
Ajax Ajax Buttons <% form_tag :action => 'reverse' do%>  <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p>  <p id=&quot; reversed &quot;></p>  <p><%=  submit_to_remote  'submit', 'Submit via Ajax',  :update => ' reversed ', :url => {  :action => 'reverse'  } %> </p>  <p> <%= submit_tag &quot;Submit non-Ajax&quot; %></p>  <% end %>
Ajax Buttons for arbitrary functions <%= button_to_function &quot;Greet&quot;, &quot;alert('Hello world!')&quot; %> <%= button_to_function &quot;Check Time&quot;,  remote_function(:url => { :action => 'get_time' }, :update => &quot;current_time&quot;) %>
Ajax RJS RJS is Ruby code that generates JavaScript code
Ajax RJS def alert_without_rjs  render  :text => &quot;alert('Hello without RJS')&quot; ,  :content_type => &quot;text/javascript&quot; end def alert_with_rjs  render :update do | page |  page.alert &quot;Hello from inline RJS&quot;   end  end <%= link_to_remote &quot;Alert without RJS&quot;, :url => { :action => &quot;alert_without_rjs&quot; } %> <%= link_to_remote &quot;Alert with RJS&quot;, :url => { :action => &quot;alert_with_rjs&quot; } %>
Ajax RJS files 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; } %>
Ajax Element proxies <div id=&quot;my_div&quot; class=&quot;green box&quot;>DIV</div> page[:my_div].show Generates javascript $('my_div').show();
Ajax replace and replace_html 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)
Ajax replace and replace_html replace_html.rjs page[:my_div].replace_html &quot;New Text“ replace.rjs : page[:my_div].replace &quot;New Text&quot;
Ajax Effects of replace and replace_html 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>
Logger Log levels: Debug Info Warn Error Fatal  Ruby's Logger supports masking levels so the types of messages recorded in the log can be controlled.  By default, Rails will log all levels (debug and higher) in every environment except production.  In the production environment, it will only log info and higher. This behavior can be changed in the configuration for each environment.
Testing Has built-in framework for Unit and Functional test Use different database for testing which allows testing without any danger of production data. Generate test file while creating models and controllers Rails tests can simulate browser requests and thus you can test response without having to test it through browser.
Testing Fixtures Human readable data representations of a table. File name like table_name.yml Allow to populate testing database with predefined data before tests run. While running test framework remove all existing data from database and dump the fixture data into database Stored in test/fixtures/
Testing Unit Test Written for Models Testing library is placed on test/unit/ and file name like model_name_test.rb Functional Test Written against controller instance, simulate request against it, and make assertions about the responses Testing library placed on test/functional/ and file name like controller_name_test.rb
Unit test example class UserTest < Test::Unit::TestCase fixtures :companies, :users, :projects def test_get_user_by_company users = User.get_user_by_company(companies(:one).id) ‏ assert_not_nil users assert_equal 3,users.length end end
Assertions used in unit testing assert(actual, comment) assert_equal(expected, actual, comment) ‏ assert_match(pattern, string, message) ‏ assert_nil(object, message)/assert_not_nil assert_raise(Exception, ..., message) { block ... } assert_difference(expressions, difference = 1, &block) ‏
Functional test example class UserControllerTest < Test::Unit::TestCase fixtures :companies, :users, :projects  def setup @controller = UserController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.env['HTTP_HOST'] = &quot;localhost&quot; end def test_get_user get :show, :id => users(:admin).id assert_response :success assert_not_nil assigns(:user) ‏ end end
Functional test assertions assert_response :success|:redirect|:missing|:error assert_redirected_to(:controller => ‘blog’, :action =>‘list’) ‏ assert_template ‘store/index’
Gem/Plugin 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 Command to install a gem: $ gem install gem_with_opotion
ActiveSupport Utility classes and standard library extensions Examples: 20.minutes.ago  Time_ago_in_words 1.gigabyte Titelize Humanize
Future of ROR-Rails 3 Rails 3 = Rails + Merb   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.    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”).
Future of ROR-Rails 3 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.    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.
Future of Rails-Rails 3 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.
Demo How a small idea turns into an application, in Ruby on Rails way
Demo – Live rails application ScrumPad www.scrumpad.com
Ruby on Rails For further queries or interest in RoR training contact: [email_address] www.code71.com/training.aspx
Ruby on Rails Q & A
Presenters Arifur Rahman Sr. Software Engineer http://wannabesoftwareengineer.blogspot.com/ Fuad Bin Omar Sr. Software Engineer http://www.fuadcse.blogspot.com Md. Fattahul Alam http://fattahulalam.blogspot.com/ Sr. Software Engineer
Ruby on Rails Thank You
Ad

More Related Content

What's hot (20)

JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
Vipin Yadav
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Project Presentation on Advance Java
Project Presentation on Advance JavaProject Presentation on Advance Java
Project Presentation on Advance Java
Vikas Goyal
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Open Social Summit Korea
Open Social Summit KoreaOpen Social Summit Korea
Open Social Summit Korea
Arne Roomann-Kurrik
 
Java server pages
Java server pagesJava server pages
Java server pages
Tanmoy Barman
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
yuvalb
 
Servlets
ServletsServlets
Servlets
Ravi Kant Sahu
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
BG Java EE Course
 
Jsp
JspJsp
Jsp
Pooja Verma
 
Advanced java
Advanced java Advanced java
Advanced java
NA
 
JSP
JSPJSP
JSP
vikram singh
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
Arun Gupta
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 
Jsp element
Jsp elementJsp element
Jsp element
kamal kotecha
 
Advance Java
Advance JavaAdvance Java
Advance Java
Vidyacenter
 
Java presentation
Java presentationJava presentation
Java presentation
Karan Sareen
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
Vipin Yadav
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Project Presentation on Advance Java
Project Presentation on Advance JavaProject Presentation on Advance Java
Project Presentation on Advance Java
Vikas Goyal
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
yuvalb
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
Knoldus Inc.
 
Advanced java
Advanced java Advanced java
Advanced java
NA
 
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
S313265 - Advanced Java API for RESTful Web Services at JavaOne Brazil 2010
Arun Gupta
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
Joshua Long
 

Viewers also liked (9)

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
adamcookeuk
 
Rails Plugins
Rails PluginsRails Plugins
Rails Plugins
Wen-Tien Chang
 
Rails2's template and respond_to method
Rails2's template and respond_to methodRails2's template and respond_to method
Rails2's template and respond_to method
Wen-Tien Chang
 
Ruby On Rails Basics
Ruby On Rails BasicsRuby On Rails Basics
Ruby On Rails Basics
Amit Solanki
 
Ruby On Rails Presentation
Ruby On Rails PresentationRuby On Rails Presentation
Ruby On Rails Presentation
ChanHan Hy
 
Ruby on Rails for beginners
Ruby on Rails for beginnersRuby on Rails for beginners
Ruby on Rails for beginners
Vysakh Sreenivasan
 
Interior Designer PowerPoint
Interior Designer PowerPointInterior Designer PowerPoint
Interior Designer PowerPoint
hannahxbanana
 
Interior design seminar presentation
Interior design seminar presentationInterior design seminar presentation
Interior design seminar presentation
highcraft
 
Principles of Interior Design
Principles of Interior DesignPrinciples of Interior Design
Principles of Interior Design
Sumit Ranjan
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
adamcookeuk
 
Rails2's template and respond_to method
Rails2's template and respond_to methodRails2's template and respond_to method
Rails2's template and respond_to method
Wen-Tien Chang
 
Ruby On Rails Basics
Ruby On Rails BasicsRuby On Rails Basics
Ruby On Rails Basics
Amit Solanki
 
Ruby On Rails Presentation
Ruby On Rails PresentationRuby On Rails Presentation
Ruby On Rails Presentation
ChanHan Hy
 
Interior Designer PowerPoint
Interior Designer PowerPointInterior Designer PowerPoint
Interior Designer PowerPoint
hannahxbanana
 
Interior design seminar presentation
Interior design seminar presentationInterior design seminar presentation
Interior design seminar presentation
highcraft
 
Principles of Interior Design
Principles of Interior DesignPrinciples of Interior Design
Principles of Interior Design
Sumit Ranjan
 
Ad

Similar to Ruby On Rails Seminar Basis Softexpo Feb2010 (20)

Ror Seminar With agilebd.org on 23 Jan09
Ror Seminar With agilebd.org on 23 Jan09Ror Seminar With agilebd.org on 23 Jan09
Ror Seminar With agilebd.org on 23 Jan09
Shaer Hassan
 
Ruby Rails Web Development.pdf
Ruby Rails Web Development.pdfRuby Rails Web Development.pdf
Ruby Rails Web Development.pdf
Ayesha Siddika
 
Things you must know on ruby on rails single page application
Things you must know on ruby on rails single page applicationThings you must know on ruby on rails single page application
Things you must know on ruby on rails single page application
Andolasoft Inc
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development 8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development
rorbitssoftware
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
Ruby On Rails Presentation
Ruby On Rails PresentationRuby On Rails Presentation
Ruby On Rails Presentation
Paul Pajo
 
React with rails a perfect combination to build modern web application
React with rails a perfect combination to build modern web applicationReact with rails a perfect combination to build modern web application
React with rails a perfect combination to build modern web application
Katy Slemon
 
Ruby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product ownersRuby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product owners
Katy Slemon
 
Global Logic sMash Overview And Experiences
Global Logic   sMash  Overview And  ExperiencesGlobal Logic   sMash  Overview And  Experiences
Global Logic sMash Overview And Experiences
Project Zero
 
8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoid8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoid
rorbitssoftware
 
Ruby vs Ruby on Rails: Find Out The Differences - RORBits
Ruby vs Ruby on Rails: Find Out The Differences - RORBitsRuby vs Ruby on Rails: Find Out The Differences - RORBits
Ruby vs Ruby on Rails: Find Out The Differences - RORBits
rorbitssoftware
 
React with Ruby on Rails: Perfect Pair to Build Web Apps
React with Ruby on Rails: Perfect Pair to Build Web AppsReact with Ruby on Rails: Perfect Pair to Build Web Apps
React with Ruby on Rails: Perfect Pair to Build Web Apps
rorbitssoftware
 
Ruby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdfRuby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdf
lubnayasminsebl
 
Ruby on Rails best resources for self
Ruby on Rails best resources for selfRuby on Rails best resources for self
Ruby on Rails best resources for self
Durga Prasad Tumu
 
Instruments ruby on rails
Instruments ruby on railsInstruments ruby on rails
Instruments ruby on rails
pmashchak
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On Rails
David Keener
 
Ruby on Rails Scaffold_ Create Your App In Minutes
Ruby on Rails Scaffold_ Create Your App In MinutesRuby on Rails Scaffold_ Create Your App In Minutes
Ruby on Rails Scaffold_ Create Your App In Minutes
rorbitssoftware
 
Install Ruby on Rails Like a Pro: Effortless Guide
Install Ruby on Rails Like a Pro: Effortless GuideInstall Ruby on Rails Like a Pro: Effortless Guide
Install Ruby on Rails Like a Pro: Effortless Guide
rorbitssoftware
 
Rails Concept
Rails ConceptRails Concept
Rails Concept
Javed Hussain
 
Ror Seminar With agilebd.org on 23 Jan09
Ror Seminar With agilebd.org on 23 Jan09Ror Seminar With agilebd.org on 23 Jan09
Ror Seminar With agilebd.org on 23 Jan09
Shaer Hassan
 
Ruby Rails Web Development.pdf
Ruby Rails Web Development.pdfRuby Rails Web Development.pdf
Ruby Rails Web Development.pdf
Ayesha Siddika
 
Things you must know on ruby on rails single page application
Things you must know on ruby on rails single page applicationThings you must know on ruby on rails single page application
Things you must know on ruby on rails single page application
Andolasoft Inc
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development 8 awesome benefits of ruby on rails application development
8 awesome benefits of ruby on rails application development
rorbitssoftware
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
Ruby On Rails Presentation
Ruby On Rails PresentationRuby On Rails Presentation
Ruby On Rails Presentation
Paul Pajo
 
React with rails a perfect combination to build modern web application
React with rails a perfect combination to build modern web applicationReact with rails a perfect combination to build modern web application
React with rails a perfect combination to build modern web application
Katy Slemon
 
Ruby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product ownersRuby on rails backend development preferred choice for product owners
Ruby on rails backend development preferred choice for product owners
Katy Slemon
 
Global Logic sMash Overview And Experiences
Global Logic   sMash  Overview And  ExperiencesGlobal Logic   sMash  Overview And  Experiences
Global Logic sMash Overview And Experiences
Project Zero
 
8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoid8 Common Ruby on Rails Development Mistakes to Avoid
8 Common Ruby on Rails Development Mistakes to Avoid
rorbitssoftware
 
Ruby vs Ruby on Rails: Find Out The Differences - RORBits
Ruby vs Ruby on Rails: Find Out The Differences - RORBitsRuby vs Ruby on Rails: Find Out The Differences - RORBits
Ruby vs Ruby on Rails: Find Out The Differences - RORBits
rorbitssoftware
 
React with Ruby on Rails: Perfect Pair to Build Web Apps
React with Ruby on Rails: Perfect Pair to Build Web AppsReact with Ruby on Rails: Perfect Pair to Build Web Apps
React with Ruby on Rails: Perfect Pair to Build Web Apps
rorbitssoftware
 
Ruby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdfRuby on Rails Web Development Best Practices and Tips.pdf
Ruby on Rails Web Development Best Practices and Tips.pdf
lubnayasminsebl
 
Ruby on Rails best resources for self
Ruby on Rails best resources for selfRuby on Rails best resources for self
Ruby on Rails best resources for self
Durga Prasad Tumu
 
Instruments ruby on rails
Instruments ruby on railsInstruments ruby on rails
Instruments ruby on rails
pmashchak
 
A Tour of Ruby On Rails
A Tour of Ruby On RailsA Tour of Ruby On Rails
A Tour of Ruby On Rails
David Keener
 
Ruby on Rails Scaffold_ Create Your App In Minutes
Ruby on Rails Scaffold_ Create Your App In MinutesRuby on Rails Scaffold_ Create Your App In Minutes
Ruby on Rails Scaffold_ Create Your App In Minutes
rorbitssoftware
 
Install Ruby on Rails Like a Pro: Effortless Guide
Install Ruby on Rails Like a Pro: Effortless GuideInstall Ruby on Rails Like a Pro: Effortless Guide
Install Ruby on Rails Like a Pro: Effortless Guide
rorbitssoftware
 
Ad

Ruby On Rails Seminar Basis Softexpo Feb2010

  • 1. Introduction to RoR: A beautiful framework for today’s web. Presented By Code71 Bangladesh Ltd. Organized by BASIS
  • 2. Preview Background Business Implication Introduction ROR and MVC Convention over configuration in rails ActiveRecord - The Rails ORM framework ActionView - The ROR view renderer ActionController - The core of a web request in ROR Data Migration Ajax Built in test framework Logging framework REST support Gems and plugins - Package manager for ruby Demo application - Build a web application in minutes Demo of a real life web application built on rails Future of rails Q&A
  • 3. Background of RoR Created in 2003 by David Heinemeier Hansson Extended by the Rails core team, more than 1,400 contributors First public release in July 2004. David Heinemeier Hansson had won the &quot;Hacker of the Year&quot; award for this software package in 2005. Rails won the 2006 Jolt Award for best Web development tool. 
  • 4. Background of RoR Ruby:  a language, comparable to Python or Perl born in 1993! Ruby on Rails : a framework, written in Ruby built in 2003 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. 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.
  • 5. Why Ruby on Rails? Out of the box architecture for persistence, logging, build scripts, test, web-tier components. Pragmatic philosophy of convention over configuration Built on Ruby, fully featured object-oriented language. Built in templating engine to generate web pages, emails, xml and text documents. Well thought out object relationship mapping tool, ActiveRecord. Built in AJAX, REST, Web service, configuration for development, test and production environment. Migration for applying or roll back database changes. Comprehensive test framework
  • 6. Why Ruby on Rails? Contd. class Project < ActiveRecord::Base belongs_to :portfolio has_one :project_manager has_many :milestones has_many :deliverables, :through => :milestones validates_presence_of :name, :description validates_acceptance_of :non_disclosure_agreement validates_uniqueness_of :short_name end
  • 7. Cons of Ruby on Rails As Ruby is a dynamic language, more automated testing is required. Developers will need to become more disciplined and rigorous in creating unit tests as part of their development process. Rails is optimized for building web applications .
  • 8. Delivering Business Values Ruby on Rails simplifies the web development process through its convention over configuration and Don’t repeat yourself it fundamentally changes the role of the programmer in web development. 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. This is why Ruby on Rails and the Agile software development movement go hand in hand.
  • 9.   Delivering Business Values Rails provides an integrated application testing framework that will help find errors before your users find them which saves money in the long run. Rails redefined RAD ( Rapid Application Development ) for the web. Leveraging this speed of development has shown to save both time and money. Rails also simplifies AJAX to allow for enhanced usability and a more satisfying end user experience. 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. 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. 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.
  • 10. Rails is Agile Individuals and interactions over processes and tools No complex configuration, no heavy toolsets Working software over comprehensive documentation Customer collaboration over contract negotiation 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.   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. Responding to change over following a plan DRY principal- easy maintenance Ruby dynamic language more expressive Comprehensive tests -regression
  • 11.   Delivering Business Values Do not compile. In Ruby, there is no concept of compilation. Everything runs at runtime.  Dynamically enhance the behavior of a class - without a Decorator Slim down your code base 10-20% by stripping off all type declarations and interface declarations. Ajax it in no time. With Rails, you don’t need an O/R Mapper. Using Ruby script to build/deploy/release is better than using NAnt. No pain no gain.
  • 12. Great user quotes “ 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.” -James Duncan Davidson, Creator of Tomcat and Ant   “ 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.” -Tim O'Reilly, Founder of O'Reilly Media
  • 13. Great user quotes -contd. “ 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.” -Martin Fowler, Author of Refactoring, PoEAA, XP Explained   “ Rails is the killer app for Ruby.” Yukihiro Matsumoto, Creator of Ruby
  • 14. Great user quotes -contd. “ 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.” -Evan Williams, Creator of Blogger, ODEO, and Twitter   “ 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
  • 15. Great user quotes-contd. What sets this framework apart from all of the others is the preference for convention over configuration making applications easier to develop and understand.” -Sam Ruby, ASF(Apache Software Foundation) board of directors
  • 16. Great sites built on Rails(Contd.) News Unlimited Yes, New york times!! http://www.nytimes.com
  • 17. Great sites built on Rails(Contd.) Document Sharing Yes, Scribd!!     http://www.scribd.com/
  • 18. Great sites built on Rails(Contd.) Create an online store! Yes, Shopify!!     http://www.shopify.com/
  • 19. Great sites built on Rails(Contd.) Check fashion. Yes, MTV Style!!     http://www.mtv.com/
  • 20. Great sites built on Rails(Contd.) Social coding. Yes, Github!!     http://github.com/
  • 21. Great sites built on Rails(Contd.) Box office in Home. Yes, HBO!!     http://www.hbosouthasia.com/
  • 22. Great sites built on Rails(Contd.) Presentation sharing. Yes, Slideshare!!     http://www.slideshare.net/
  • 23. BREAK
  • 26. Directory structure in rails: •   app - Controllers - Helpers - Models Views •   config - environment.rb routes.rb •   db - database.yml   migrations •   components •   doc •   lib •   log •   public •   script •   test •   vendor
  • 27. Routes Connects URLs to Code GET /patients/17 The application would end up running the show action within the patients controller Generates URLs from Code @patient = Patient.find(17) <%= link_to &quot;Patient Record&quot;, patient_path(@patient) %> Translates that to a link to a URL such as http://example.com /patients/17
  • 28. Routes Default route map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format'
  • 29. Sample Controller, Action & View Controller and Action(app/controllers/hello_controller.rb): class HelloController < ApplicationController def say_hello @user_name = “John Doe” end end View(app/views/hello/say_hello.rhtml): <b>Hello <%=@user_name%>!</b> Welcome to demo app.
  • 30. Sample Request & Response Browser Request: http://localhost:3000/hello/say_hello Browser Response: Hello John Doe! Welcome to demo app.
  • 31. What is migration and why? What ? 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 Why ? Allows incremental development of database  Allows easy roll out of a new version of a database   Allows easy roll back to previous versions  Allows to change the database anytime 
  • 32. Understanding Migration Script Generating a migration script ruby script/generate migration create_companies Name of the generated migration script db/migrate/001_create_companies.rb In this file we will get a class called “CreateCompanies” having two methods “self.up” and “self.down” self.up - is used when migrating to a new version     self.down - is used to roll back  changes made in self.up
  • 33. Understanding Migration Script class CreateCompanies < ActiveRecord::Migration def self.up    create_table :companies do |table| table.column :name, :string end end   def self.down drop_table :companies end end Migrate to specific version     rake db:migrate VERSION=3 Migration on different environment rake  db:migrate  RAILS_ENV=production
  • 34. ActiveRecord Object-relational mapping (ORM) layer supplied with Rails Connects business objects and database tables Creates a persistent domain model where logic and data are presented in one place Plays the role of model in MVC architecture.
  • 35. ActiveRecord contd. ActiveRecord closely follows the standard ORM model Tables map to classes Rows to objects Columns to object attributes ActiveRecord minimizes the amount of configuration that developers perform
  • 36. ActiveRecord Contd. Tables and classes Convention: Table is the underscored plural form of the name of the class. Example: 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. ActiveRecord Contd. Columns and attributes Active Record objects correspond to rows in a database table. The objects have attributes corresponding to the columns in the table. ActiveRecord determines columns in tables dynamically at runtime.
  • 38. ActiveRecord Contd. Columns and attributes users table: User class in models/user.rb class User < ActiveRecord::Base end Objects of user class dynamically contains setter and getter methods for the columns of users table. Users id integer first_name string last_name string user_name string password string
  • 39. ActiveRecord Contd. Create a model object u = User.create(:first_name => “John”, :last_name=>”Doe”, :user_name=>”scrumpad”, :password => “anything” This will execute sql: INSERT INTO users(first_name, last_name, user_name, password) VALUES(‘John’, ‘Doe’, ’scrumpad’, ’anything’) ‏ u.first_name will produce “John” u.last_name will produce “Doe”
  • 40. ActiveRecord Contd. Find a model object By Id: u = User.find(1) ‏ By Name: u = User.find_by_first_name(“John”) ‏ Update a model object u.first_name = “John1” u.save
  • 41. ActiveRecord Contd. Conditions to find ActiveRecord Find all records having first name = “John” users = User.find(:all, :conditions=>”first_name = ‘John’”) ‏
  • 42. ActiveRecord associations Models : 1. Company 2. User 3. Address 4. Role 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. ActiveRecord Validations Validations are methods to validate the contents of a model object If validation fails an object will not be written to the db. It will be left in memory with its current invalid state. Validations can be performed on save, create or update
  • 44. ActiveRecord Validation Helpers class User < ActiveRecord::Base validates_presence_of :user_name, :email validates_uniqueness_of :user_name end
  • 45. ActiveRecord Callbacks Allows to write code to be invoked at a particular part of AR lifecycle.
  • 46. ActiveRecord Callbacks Contd. Directly class Order < ActiveRecord::Base #...... def before_save self.payment_due ||= Time.now + 30.days end end Using a handler class Order < ActiveRecord::Base before_validation :normalize_credit_card_number after_create do |order| logger.info &quot;Order #{order.id} created“ end protected def normalize_credit_card_number self.cc_number.gsub!(/-\w/, '' ) end end
  • 47. Break
  • 48. ActionController A controller object processes a request It looks for a public instance method with the same name as the incoming action 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 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 If none of these things happen, an ‘ Unknown Action’
  • 49. ActionController Contd. Responding to users Controllers respond to users in four basic ways Render a template – a template is a view. Takes info provided by controller and uses it to generate response Return a string to the browser without rendering a view – rarely used. Can return nothing – for example during AJAX calls Can return ‘other’ data to client (other then html) like a pdf, or word document.
  • 50. ActionController Contd. Responding to users Controllers always respond once – that means every controller method only has one call to render – throws multiple render error otherwise. Because it must respond once, controller checks to see if a response has been generated before it finishes handling a request. If it finds no calls to the above methods – it looks for a template named after the controller and action and renders it You can have multiple templates with the same name – but different extensions. – ie. .rhtml, .rxml, .rjs. Searches in the order above for tempates.
  • 51. ActionController Contd. Render method At the heart of rendering in Rails Takes a hash of options that tell it what to render and how. For example: def update @user = User.find(params[:id]) if @user.update_attributes(params[:user]) render :action => :show else render :template => &quot;fix_user_errors“ end end
  • 52. Templates A Template is a file that defines the content of a response. 3 formats rhtml – html with imbedded ruby rxml – a programmatic way of constructing xml content Rjs – generates javascript.
  • 53. Helpers A helper is a module that contains methods that assist a view. They are output-centric and exist to output html (or view code) Why use them? Easier to edit your RHTML, easier to test your helper files. By default each controller gets a helper modlue in the app/helpers directory.
  • 54. Helpers Contd. <h3><%= @page_title || “My charity&quot; %></h3> This is a simple example, but if you had this code in each template you begin to let duplication slip in. Say you wanted to modify the title of your store to ‘Chrismas Charity’! You have to edit every template.
  • 55. Helper Contd. module CharityHelper def page_title @page_title || &quot;Pragmatic Store&quot; end end ---- <h3><%= page_title %></h3>
  • 56. Form form_tag (url_for_options = {}, options = {}, *parameters_for_url, &block) Options: 1 :multipart - If set to true, the enctype is set to &quot;multipart/form-data&quot;. 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. 3 A list of parameters to feed to the URL the form will be posted to. Example: <% form_tag {:controller=>”product”, :action=>”create” } do %> <%= text_field_tag(:product_name) %> <%= submit_tag(“Save&quot;) %> <% end %> Generated Code: <form action=&quot;/product/create&quot; method=&quot;post&quot;> <input id=&quot;my_name&quot; name=“product_name&quot; type=&quot;text&quot; /> <input name=&quot;commit&quot; type=&quot;submit&quot; value=“Save&quot; /> </form>
  • 57. Advanced Form(form_for) Contd. form_for (record_or_name_or_array, *args, &proc) Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields. Example: <% form_for @product do |f| %> <%= f.text_field :name %> <%= f.text_field :price, :size => 10 %> <%= f.text_field :amount, :size =>5 %> <%= submit_tag &quot;New Product&quot; %> <% end %> Generated Code: <form action=&quot;/products“ id=&quot;new_product&quot; method=&quot;post&quot;> <input id=&quot;product_name&quot; name=“product[name]“ type=&quot;text&quot; /> <input id=&quot;product_price&quot; name=“product[price]&quot; size=&quot;10&quot; type=&quot;text&quot; /> <input id=&quot;product_amount&quot; name=“product[amount]&quot; size=&quot;5&quot; type=&quot;text&quot; /> <input id=&quot;product_submit&quot; name=&quot;commit&quot; type=&quot;submit&quot; value=&quot;Update&quot; /> </form>
  • 58. Handling errors in form error_messages and error_messages_for Example: Display all of the error messages <% form_for(@product) do |f| %> <%= f.error_messages %> <!-- different form tags --> <% end %> Display error message of a specific field <% form_for(@product) do |f| %> <%= error_messages_for :name %> <!-- different form tags --> <% end %>
  • 59. Ajax Links <%= link_to_remote &quot;Check Time&quot;, :url => { :action => 'get_time' }, :update => 'current_time', %> <div id=&quot;current_time&quot;> </div>
  • 60. Ajax Callbacks <%= link_to_remote &quot;Check Time&quot;, :url => { :action => 'get_time' }, :update => 'current_time', :before => &quot;$('current_time').update('Loading...')&quot; %> <div id=&quot;current_time&quot;> </div>
  • 61. Ajax Callbacks <%= link_to_remote &quot;Check Time&quot;, :update => 'current_time', :url => { :action => 'get_time' }, :before => &quot;$('indicator').show( )&quot;, :success => &quot;$('current_time').visualEffect('highlight')&quot;, :failure => &quot;alert('There was an error. ')&quot;, :complete => &quot;$('indicator').hide( )&quot; %> <span id=&quot;indicator&quot; style=&quot;display: none;&quot;>Loading...</span> <div id=&quot;current_time&quot;></div>
  • 62. Ajax Ajax Forms <% form_remote_tag :url => { :action => 'reverse' }, :update => &quot; reversed ” do %> <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p> <p id=&quot; reversed &quot;></p> <p><%= submit_tag 'Reverse!' %></p> <% end %>
  • 63. Ajax Ajax Buttons <% form_tag :action => 'reverse' do%> <p>Text to reverse: <%= text_field_tag 'text_to_reverse' %></p> <p id=&quot; reversed &quot;></p> <p><%= submit_to_remote 'submit', 'Submit via Ajax', :update => ' reversed ', :url => { :action => 'reverse' } %> </p> <p> <%= submit_tag &quot;Submit non-Ajax&quot; %></p> <% end %>
  • 64. Ajax Buttons for arbitrary functions <%= button_to_function &quot;Greet&quot;, &quot;alert('Hello world!')&quot; %> <%= button_to_function &quot;Check Time&quot;, remote_function(:url => { :action => 'get_time' }, :update => &quot;current_time&quot;) %>
  • 65. Ajax RJS RJS is Ruby code that generates JavaScript code
  • 66. Ajax RJS def alert_without_rjs render :text => &quot;alert('Hello without RJS')&quot; , :content_type => &quot;text/javascript&quot; end def alert_with_rjs render :update do | page | page.alert &quot;Hello from inline RJS&quot; end end <%= link_to_remote &quot;Alert without RJS&quot;, :url => { :action => &quot;alert_without_rjs&quot; } %> <%= link_to_remote &quot;Alert with RJS&quot;, :url => { :action => &quot;alert_with_rjs&quot; } %>
  • 67. Ajax RJS files 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. Ajax Element proxies <div id=&quot;my_div&quot; class=&quot;green box&quot;>DIV</div> page[:my_div].show Generates javascript $('my_div').show();
  • 69. Ajax replace and replace_html 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. Ajax replace and replace_html replace_html.rjs page[:my_div].replace_html &quot;New Text“ replace.rjs : page[:my_div].replace &quot;New Text&quot;
  • 71. Ajax Effects of replace and replace_html 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. Logger Log levels: Debug Info Warn Error Fatal  Ruby's Logger supports masking levels so the types of messages recorded in the log can be controlled. By default, Rails will log all levels (debug and higher) in every environment except production. In the production environment, it will only log info and higher. This behavior can be changed in the configuration for each environment.
  • 73. Testing Has built-in framework for Unit and Functional test Use different database for testing which allows testing without any danger of production data. Generate test file while creating models and controllers Rails tests can simulate browser requests and thus you can test response without having to test it through browser.
  • 74. Testing Fixtures Human readable data representations of a table. File name like table_name.yml Allow to populate testing database with predefined data before tests run. While running test framework remove all existing data from database and dump the fixture data into database Stored in test/fixtures/
  • 75. Testing Unit Test Written for Models Testing library is placed on test/unit/ and file name like model_name_test.rb Functional Test Written against controller instance, simulate request against it, and make assertions about the responses Testing library placed on test/functional/ and file name like controller_name_test.rb
  • 76. Unit test example class UserTest < Test::Unit::TestCase fixtures :companies, :users, :projects def test_get_user_by_company users = User.get_user_by_company(companies(:one).id) ‏ assert_not_nil users assert_equal 3,users.length end end
  • 77. Assertions used in unit testing assert(actual, comment) assert_equal(expected, actual, comment) ‏ assert_match(pattern, string, message) ‏ assert_nil(object, message)/assert_not_nil assert_raise(Exception, ..., message) { block ... } assert_difference(expressions, difference = 1, &block) ‏
  • 78. Functional test example class UserControllerTest < Test::Unit::TestCase fixtures :companies, :users, :projects def setup @controller = UserController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new @request.env['HTTP_HOST'] = &quot;localhost&quot; end def test_get_user get :show, :id => users(:admin).id assert_response :success assert_not_nil assigns(:user) ‏ end end
  • 79. Functional test assertions assert_response :success|:redirect|:missing|:error assert_redirected_to(:controller => ‘blog’, :action =>‘list’) ‏ assert_template ‘store/index’
  • 80. Gem/Plugin 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 Command to install a gem: $ gem install gem_with_opotion
  • 81. ActiveSupport Utility classes and standard library extensions Examples: 20.minutes.ago Time_ago_in_words 1.gigabyte Titelize Humanize
  • 82. Future of ROR-Rails 3 Rails 3 = Rails + Merb   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.   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”).
  • 83. Future of ROR-Rails 3 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.   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.
  • 84. Future of Rails-Rails 3 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.
  • 85. Demo How a small idea turns into an application, in Ruby on Rails way
  • 86. Demo – Live rails application ScrumPad www.scrumpad.com
  • 87. Ruby on Rails For further queries or interest in RoR training contact: [email_address] www.code71.com/training.aspx
  • 88. Ruby on Rails Q & A
  • 89. Presenters Arifur Rahman Sr. Software Engineer http://wannabesoftwareengineer.blogspot.com/ Fuad Bin Omar Sr. Software Engineer http://www.fuadcse.blogspot.com Md. Fattahul Alam http://fattahulalam.blogspot.com/ Sr. Software Engineer
  • 90. Ruby on Rails Thank You

Editor's Notes

  • #12: source: http://www.infoq.com/articles/Netter-on-Rails http://docs.google.com/viewer?url=https://koshevoy.com/presentations/business_rails.pdf
  • #43: Discuss about the dynamically generated accessor methods because of association.
  • #46: There are 20 callbacks. 18 are before/after pairs, 2 are after_find and after_initialize
  • #47: 2 ways to define callback
  • #57: 1 :multipart - If set to true, the enctype is set to &amp;quot;multipart/form-data&amp;quot;. 2 :method - The method to use when submitting the form, usually either &amp;quot;get&amp;quot; or &amp;quot;post&amp;quot;. If &amp;quot;put&amp;quot;, &amp;quot;delete&amp;quot;, 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.