[go: up one dir, main page]

0% found this document useful (0 votes)
87 views53 pages

Ruby On Rails

The document discusses Ruby on Rails, an open source web application framework written in Ruby. It provides an overview of what Ruby and Rails are, demonstrates Rails features like Active Record for object-relational mapping, and shares testimonials from developers who praise Rails for its productivity and ability to build full-stack web applications with less code.

Uploaded by

mcastilho
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views53 pages

Ruby On Rails

The document discusses Ruby on Rails, an open source web application framework written in Ruby. It provides an overview of what Ruby and Rails are, demonstrates Rails features like Active Record for object-relational mapping, and shares testimonials from developers who praise Rails for its productivity and ability to build full-stack web applications with less code.

Uploaded by

mcastilho
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Ruby on Rails

or,
why are you wasting your…

www.rubyonrails.org Curt Hibbs <curt@hibbs.com>


Agenda

Š What is Ruby?
Š What is Rails?
Š Live Demonstration
Š Development Metrics for Real Rails
Applications
Š Rails Features
Š Resources for more information
What is Ruby?

Š Short Answer:
ƒ Ruby is the successful combination
SmallTalk's conceptual elegance, Python's
ease of use and learning, and Perl's
pragmatism.

Š Long Answer:
ƒ Well… see the following slides.
What is Ruby?

“Ruby is a very object oriented language with a


super clean syntax that makes programming
elegant and enjoyable.”
- James Edward Gray II

“Ruby is an elegant language in which it's easy


and natural to express solutions. It's simple
enough that a beginner can start using it
immediately, yet powerful enough to deal with
sophisticated needs. It's so fun that the
Puritans would have banned it had they known
about it.”
- Paul Sanchez
What is Ruby?

“Ruby is a language that's like the best parts of


Smalltalk, Perl and Lisp, all in one, and no line
noise.”
- Aredridel

“Ruby is the programming language that makes


you have more time for your girlfriend .. or
less, if you fall in love with Ruby instead.”
- Jan Krüger
What is Ruby?

“I use Ruby because it:


• is easy and fun to learn and use
• strongly encourages structured, expressive and
readable code
• makes object-orientation a natural approach of
solving problems
• lets you solve the problem at hand instead of
fighting against shortcomings of the language
• is highly addictive… once you’ve tried it you
cannot imagine life without”
- Josef Schugt
What is Ruby?

And my personal favorite:

“Ruby? Oh, you won't like this language.


(Slides Pickaxe II book out of view.)
It's entirely too fun and productive for
most people.”
- Mike Clark
Why Ruby?

Š Easy to learn and maintain


Š Powerful
Š Language stays out of your way
Š Rich libraries
Š Rapid development
Š Helpful community
Š Open Source
Š Fun
Why Not?

Š Performance
ƒ although it rivals Perl and Python
Š Threading model
ƒ Does not use native threads
Who Uses Ruby?
Š Well Known Developer’s Using Ruby
ƒ Evangelists
• Dave Thomas & Andrew Hunt
– Authors of “The Pragmatic Programmer”
ƒ Enthusiasts
• Ron Jefferies *
• Martin Fowler *
• Jack Herrington

ƒ Positive Mentions
• Alistair Cockburn *
• Kent Beck *
• Ward Cunningham *
• Bret Pettichord *
• Brian Marick *
• Paul Graham * Notice the heavy
• Doug Lea representation from
• Bjarne Stroustrup Agile Software
• Brad Cox Development
• Bruce Perens community.
• Howard Lewis Ship
What is Rails?

Š Short Answer:
ƒ An extremely productive web-application
framework that is written in Ruby by
David Heinemeier Hansson.

Š Long Answer:
ƒ Well… see the following slides.
What is Rails?

Š An open source web-application


framework.
Š It ships with an answer for every letter
in MVC:
ƒ Action Controller
ƒ Action View
ƒ Active Record (for the model)
What is Rails?

Š Less Code
ƒ Requires fewer total lines of code than
other frameworks spend setting up their
XML configuration files.

Š Full Stack
ƒ Being a full-stack framework means that all
layers are built to work seamlessly
together. That way you Don’t Repeat
Yourself (DRY).
What is Rails?
Š Convention over Configuration
ƒ Rails shuns configuration files in favor of
conventions, reflection and dynamic run-
time extensions.
Š Configure your application by making it
ƒ Your code is the configuration!
ƒ This means the end of XML files telling a
story that has already been told in your
code.
ƒ It means no compilation phase: Make a
change, see it work.
ƒ Meta-data is an implementation detail left
for the framework to handle.
Rails Demonstration
The Finished Forum Example
Š RubyBB
ƒ by Russ Smith
ƒ http://rubybb.readbim.com/

ƒ 384 Lines of Code


Development Metrics
Š StoryCards
ƒ Web app to support XP-style development
by Jim Weirich
ƒ http://onestepback.org:3030/

ƒ 1,250 Lines of code


ƒ 8 hours of
development
time
Development Metrics
Š RubyFAQ
ƒ User contributed and commented FAQs
(a production web-app) by David Black
ƒ http://www.rubygarden.org/faq/main/index

ƒ 573 Lines of code


ƒ 5 hours of
development
time.
Development Metrics
Š Basecamp: A commercial Rails web-
app with over 10,000 users.
ƒ “Web-based project management the way
it should be”
ƒ http://www.basecamphq.com/

ƒ Launched after
ƒ 4,000 Lines of Code.
ƒ 2 man-months of
programming by a
single developer
(the Rails author).
Rails Testimonials
“I'm absolutely floored by how fast I'm developing with
Rails. Stuff that would have taken me over a week in
Java + Web Work2 + Velocity + Hibernate has taken me
a little over a day with Rails. I'm not even going to try to
compare it to my current client's project which requires
Struts.”
- Anoop Ranganath

“I was but a lowly PHP programmer, slogging through


thousands of lines of less-than-maintainable code. I was
coercing Smarty, an innocent templating engine, to my
evil whims. The innards of my latest PHP project looked
like a multi-car accident.
Cue RubyOnRails. The sheer elegance of the thing has
freed my mind from the mires of PHP. No longer is my
vision limited by the tedium of PHP. Writing web-
applications has become a pure joy.”
- Jorgen Hahn
Rails Testimonials

“I'm planning to demonstrate Rails to Amazon next week.”


- Dave Thomas
Author: The Pragmatic Programmer
Active Record
Š Object-relation mapping put on rails
ƒ Active Record connects business objects
and database tables to create a
persistable domain model where logic and
data is presented in one wrapping.
ƒ Active Record’s main contribution to the
ORM pattern is to relieve two stunting
problems: lack of associations and
inheritance.
ƒ A simple domain language-like set of
macros describe associations.
ƒ Single Table inheritance narrows the gap
of functionality between the data mapper
and the active record approach.
Active Record Features

Active Record Features


Active Record
Š Automated mapping between classes
and tables, attributes and columns.

class Product < ActiveRecord::Base


end

...is automatically mapped to the table named


"products", such as:

CREATE TABLE products (


id int(11) NOT NULL auto_increment,
name varchar(255),
PRIMARY KEY (id)
);
Active Record
Š Associations between objects
controlled by simple meta-
programming macros.

class Firm < ActiveRecord::Base


has_many :clients
has_one :account
belongs_to :conglomorate
end

…adds methods that allows code like this:

firm = Firm.find(id);
firm.clients.each do |client|
...some-interesting-processing...
end
Active Record
Š Validation rules can differ for new or existing
objects.

class Post < ActiveRecord::Base

def validate # validates on both creates and updates


errors.add_on_empty "title"
end

def validate_on_update
errors.add_on_empty "password"
end

end
Active Record
Š Callbacks as methods or queues on the entire
lifecycle (instantiation, saving, destroying,
validating, etc).

class Subscription < ActiveRecord::Base


# Automatically assign the signup date
def before_create
self.signed_up_on = Date.today
end
end

class Firm < ActiveRecord::Base


# Destroys the associated clients and people when
# the firm is destroyed
def before_destroy
Client.destroy_all "client_of = #{id}"
Person.destroy_all "firm_id = #{id}"
end
end
Active Record
Š Inheritance hierarchies

class Company < ActiveRecord::Base; end

class Firm < Company; end


class Client < Company; end
class PriorityClient < Client; end
Active Record
Š Transaction support on both a
database and object level.

# Just database transaction


Account.transaction do
david.withdrawal(100)
mary.deposit(100)
end

# Object transaction
Account.transaction(david, mary) do
david.withdrawal(100)
mary.deposit(100)
end
Active Record
Š Reflections on columns, associations, and
aggregations

reflection = Firm.reflect_on_association(:clients)

reflection.klass # => Client (class)

Firm.columns # Returns an array of column


# descriptors for the firms table
Active Record
Š Database abstraction through simple
adapters
ƒ About 100 lines of code.

ActiveRecord::Base.establish_connection(
:adapter => "sqlite",
:dbfile => "dbfile“
)

ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "me",
:password => "secret",
:database => "activerecord"
)
Active Record
Š Data definitions are specified only in
the database.
ƒ Active Record queries the database for the
column names.
ƒ When an database object is instantiated,
attributes are created for each column
name.

# CREATE TABLE companies (


# id int(11) unsigned NOT NULL auto_increment,
# client_of int(11),
# name varchar(255),
# type varchar(100),
# PRIMARY KEY (id)
# )
Active Record automatically links the "Company"
object to the "companies" table
Active Record Sample Code

# SQL: INSERT INTO companies (name) VALUES ("Next Angle")


firm = Firm.new("name" => "Next Angle")
firm.save

Lots of different finders:

# SQL: SELECT * FROM companies WHERE id = 1


next_angle = Company.find(1)

# SQL: SELECT * FROM companies WHERE id = 1 AND


# name = 'Next Angle'
next_angle = Company.find_first "name = 'Next Angle'"

Dynamic methods are added by the has_many macro:

next_angle.has_clients? # true
next_angle.clients_count # total number of clients
all_clients = next_angle.clients
Action Controller Features

Action Controller Features


Actions
Š Actions: from request to response
ƒ Rails splits the response to a web request
into a controller part (performing the logic)
and a view part (rendering a template).
ƒ This two-step approach is known as an
action, which will normally create, read,
update, or delete (CRUD for short) some
sort of model part (often backed by a
database) before choosing either to render
a template or redirecting to another action.
ƒ Rails implements these actions as public
methods on Action Controllers and uses
Action Views to implement the template
rendering.
Action Controllers
Š Actions are grouped in the controller
as methods instead of separate
command objects and can therefore
share helper methods.
ƒ Responsible for handling all the actions
relating to a certain part of an application.
ƒ This grouping usually consists of actions
for lists and for CRUDs revolving around a
single (or a few) model objects.
ƒ So ContactController might be responsible
for listing contacts, creating, deleting, and
updating contacts.
ƒ A WeblogController could be responsible
for both posts and comments to a blog.
Action Controllers
Š Example:
class BlogController < ActionController::Base
def display
@customer = find_customer
end
def update
@customer = find_customer
@customer.attributes = @params["customer"]
@customer.save ?
redirect_to(:action => "display") :
render("customer/edit")
end
def find_customer()
Customer.find(@params["id"])
end
end
Action View Features

Action View Features


Action Views
Š Rails templates are written using
embedded Ruby
ƒ Like JSP or ASP, Ruby code is
embedded in tags that are mingled in
with the HTML.
ƒ To avoid cluttering the templates
with code, a bunch of helper classes
provide common behavior for forms,
dates, and strings.
ƒ It’s easy to add your own specific
helpers to keep the separation as the
application evolves.
Action Views
Š Example template:
<html>
<body>
<% for post in @posts %>
Title: <%= post.title %>
<% end %>
All post titles:
<%= @post.collect{ |p| p.title }.join ", " %>
<% unless @person.is_client? %>
Not for clients to see...
<% end %>
</body>
</html>
Rails vs. Struts

Rails vs. Struts


Rails vs. Struts
Š Rails is more focused on the goal (a
web-application) than the means.
ƒ Rails is a full, integrated solution and has
an answer for all three letters in MVC.
ƒ Struts is squarely focused on providing the
controller.
ƒ Hibernate (often used with Struts) is just an
ORM.
ƒ Honorable mention: Spring is designed to
be more of a full solution.
Rails vs. Struts
Š Actions and return values
ƒ All actions in Struts must be mapped in an
XML file.
ƒ All return values use indirection
(SUCCESS/FAILURE) that must be mapped
in an XML file.
ƒ In Rails, this is all handled by reflection
(the framework figures out how the
configuration should look).
Rails vs. Struts
Š Pretty URLs
ƒ Rails cares deeply about Pretty URLs, such
as /customers/show/154. It's baked right into
the framework.
ƒ Struts exposes technology in the URLs and
generally doesn't work hard to care for the
beauty of the URL.
ƒ (Third-party add-ons can alleviate that to
some degree).
Rails vs. Struts
Š Actions
ƒ Struts' actions are full-fledged classes.
ƒ Rails actions are just methods.

Š For example:
ƒ The average code lines of code for an
action in Basecamp[1] is 5.
ƒ Look at any struts example and find any
action. It's not even funny.

[1] Basecamp is a commercial, production web-app written with


Rails: http://www.basecamphq.com/
Rails vs. Struts
Š Layouts
ƒ Rails supports the concept of layouts
natively.
ƒ Struts requires the aid of Tiles,
which in turn requires its own set of XML
files for configuration -- on top of what's
already required in Struts!
Rails vs. Struts
Š Validation
ƒ Validation in Struts requires the use of
ActionForms.
• These "model mirrors" have a 1-1 mapping to
your model files (most of the time), but use a
different syntax. This means you are “Repeating
Yourself”.
ƒ In Rails, validation is pushed to the model.
• The presentation of validation errors are kept in
the Action Controller.
Rails vs. Struts
Š Filters and Interceptors
ƒ Rails has deep support for filters and
interceptors (running shared code before
and after all actions).
ƒ Struts has a research project called SAIF
to get this type of support, but nothing in
the main framework.
Rails vs. Struts
Š Scaffolding
ƒ Rails has scaffolding to quickly bring a
model class "online" (provides CRUD
operations without writing any code).
ƒ Struts has no equivalent.
Rails vs. Struts
Š Lines of Code
ƒ Rails is implemented in about 2,000 lines of
Ruby code.
• This is easily understandable by us mere
mortals.
ƒ Struts is implemented in about ??? Lines of
Java code.
• Is there anyone here that actually understands
the internal implementation of Struts?
Rails vs. Struts
Š What I like about Struts
ƒ How it (somehow) positioned itself as the
default controller in the majority of run-of-
the-mill J2EE apps.
ƒ That's a freaking awesome piece of PR
work!
Resources for more information
Š Ruby
ƒ Main Ruby Site
• http://www.ruby-lang.org/en/
ƒ Ruby Documentation
• http://www.ruby-doc.org/
ƒ One-Click Ruby Installer for Windows
• http://rubyinstaller.rubyforge.org/
ƒ RubyForge – open source project repository
• http://rubyforge.org/

Š Rails
ƒ Main Rails Site
• http://www.rubyonrails.org/
Installing Rails
1. Install Ruby
ƒ On Windows you can use the One-Click
installer. For other platforms, see the main
Ruby web site.
2. Install RubyGems
(a ruby package management system)
ƒ Download from
http://rubyforge.org/projects/rubygems/
ƒ Unpack the downloaded archive and in
that directory run the command:
ruby install.rb
3. Install Rails
ƒ From the command line execute:
gem install rails

You might also like