[ANN] Action Pack 0.7.5: On rails from request to response

  • Thread starter David Heinemeier Hansson
  • Start date
D

David Heinemeier Hansson

It's with great pleasure that I present to you the first public release
of
Action Pack. I've been working on the framework for close to a year
now, so
it's a great relief to finally feel ready to share with the world.
Alongside
Active Record, this almost completes the release of the technology used
to build
Basecamp[1] -- a highly succesful and acclaimed web-application from
the design
masters at 37signals.

Action Pack is a control-flow and template package for developing
MVC-style
web-applications. With Action Pack, you have the answer for the
Controler and
the View and is free to pick anything for the Model. If you were to
pick Active
Record, though, you'll enjoy a number of benefits from Action Pack,
such as
tailored view helpers and benchmarking integration.

Download and learn more at:
http://actionpack.rubyonrails.org (website, wiki)
http://actionpack.rubyonrails.org (api, detailed documentation)

P.S.: Tomorrow I'll release the first complete Rails package, which in
addition
to Action Pack and Active Record includes a ton of wiring to make it
extremely
easy to get started and follow best practices from day one.

[1] http://www.basecamphq.com/

/ David Heinemeier Hansson


How does Action Pack work?
==========================

Action Pack 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.

Action Pack implements these actions as public methods on Action
Controllers
and uses Action Views to implement the template rendering. Action
Controllers
are then 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
would be responsible for listing contacts, creating, deleting, and
updating
contacts. A WeblogController could be responsible for both posts and
comments.

Action View templates are written using embedded Ruby in tags 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. And it's
easy
to add specific helpers to keep the separation as the application
evolves.

Note: Some of the features, such as scaffolding and form building, are
tied to
ActiveRecord[http://activerecord.rubyonrails.org] (an object-relational
mapping package), but that doesn't mean that Action Pack depends on
Active
Record. Action Pack is an independent package that can be used with any
sort
of backend (Instiki[http://www.instiki.org], which is based on an older
version
of Action Pack, uses Madeleine for example). Read more about the role
Action
Pack can play when used together with Active Record on
http://www.rubyonrails.org.


A short rundown of the major features
=====================================

* Actions grouped in controller as methods instead of separate command
objects
and can therefore helper share methods.

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

private
def find_customer() Customer.find(@params["id"]) end
end

Learn more in link:classes/ActionController/Base.html


* Embedded Ruby for templates (no new "easy" template language)

<% 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 %>

Learn more in link:classes/ActionView.html


* Filters for pre and post processing of the response (as methods,
procs, and classes)

class WeblogController < ActionController::Base
before_filter :authenticate, :cache, :audit
after_filter proc{|c| c.response.body =
GZip::compress(c.response.body)}
after_filter LocalizeFilter

def list
# Before this action is run, the user will be authenticated,
the cache
# will be examined to see if a valid copy of the results already
# exist, and the action will be logged for auditing.

# After this action has run, the output will first be localized
then
# compressed to minimize bandwith usage
end

private
def authenticate
# Implement the filter will full access to both request and
response
end
end

Learn more in link:classes/ActionController/Filters/ClassMethods.html


* Helpers for forms, dates, action links, and text

<%= text_field "post", "title", "size" => 30 %>
<%= html_date_select(Date.today) %>
<%= link_to "New post", :controller => "post", :action => "new" %>
<%= truncate(post.title, 25) %>

Learn more in link:classes/ActionView/Helpers.html


* Layout sharing for template reuse (think simple version of Struts
Tiles[http://jakarta.apache.org/struts/userGuide/dev_tiles.html])

class WeblogController < ActionController::Base
layout "weblog_layout"

def hello_world
end
end

Layout file (called weblog_layout):
<html><body><%= @content_for_layout %></body></html>

Template for hello_world action:
<h1>Hello world</h1>

Result of running hello_world action:
<html><body><h1>Hello world</h1></body></html>

Learn more in link:classes/ActionController/Layout.html


* Advanced redirection that makes pretty urls easy

RewriteRule ^/library/books/([A-Z]+)([0-9]+)/([-_a-zA-Z0-9]+)$ \
/books_controller.cgi?action=$3&type=$1&code=$2 [QSA] [L]

Accessing /library/books/ISBN/0743536703/show calls
BooksController#show

From that URL, you can rewrite the redirect in a number of ways:

redirect_to:)action => "edit") =>
/library/books/ISBN/0743536703/edit

redirect_to:)path_params => { "type" => "XTC", "code" => "12354345"
}) =>
/library/books/XTC/12354345/show

redirect_to:)controller_prefix => "admin", :controller =>
"accounts") =>
/admin/accounts/

Learn more in link:classes/ActionController/Base.html


* Easy testing of both controller and template result through
TestRequest/Response

class LoginControllerTest < Test::Unit::TestCase
def setup
@request = ActionController::TestRequest.new
@request.host = "http://somewhere"
end

def test_succesful_authentication
@request.action = "authenticate"
@request.request_parameters["user_name"] = "david"
@request.request_parameters["password"] = "secret"

response = LoginController.process_test(@request)

assert_equal(
"http://somewhere/clients/", response.headers["location"])
assert_equal Person.find(1), response.session["person"]
assert(response.body.split("\n").include?(
"<h1>You've been logged in!</h1>"))
end
end

Learn more in link:classes/ActionController/TestRequest.html


* Automated benchmarking and integrated logging

Processing WeblogController#index (for 127.0.0.1 at Fri May 28
00:41:55)
Parameters: {"action"=>"index", "controller"=>"weblog"}
Rendering weblog/index (200 OK)
Completed in 0.029281 (34 reqs/sec)

If Active Record is used as the model, you'll have the database
debugging
as well:

Processing WeblogController#create (for 127.0.0.1 at Sat Jun 19
14:04:23)
Params: {"controller"=>"weblog", "action"=>"create",
"post"=>{"title"=>"this is good"} }
SQL (0.000627) INSERT INTO posts (title) VALUES('this is good')
Redirected to http://test/weblog/display/5
Completed in 0.221764 (4 reqs/sec) | DB: 0.059920 (27%)

You specify a logger through a class method, such as:

ActionController::Base.logger = Logger.new("Application Log")
ActionController::Base.logger = Log4r::Logger.new("Application Log")


* Powerful debugging mechanism for local requests

All exceptions raised on actions performed on the request of a
local user
will be presented with a tailored debugging screen that includes
exception
message, stack trace, request parameters, session contents, and the
half-finished response.

Learn more in link:classes/ActionController/Rescue.html


* Scaffolding for Action Record model objects

require 'account' # must be an Active Record class
class AccountController < AccountController::Base
scaffolding :account
end

The AccountController now has the full CRUD range of actions and
default
templates: list, show, destroy, new, create, edit, update

Learn more in
link:classes/ActionController/Scaffolding/ClassMethods.html


* Form building for Active Record model objects

The post object has a title (varchar), content (text), and
written_on (date)

<%= form "post" %>

...will generate something like (the selects will have more options
of
course):

<form action="create" method="POST">
<p>
<b>Title:</b><br/>
<input type="text" name="post[title]" value="<%= @post.title
%>" />
</p>
<p>
<b>Content:</b><br/>
<textarea name="post[content]"><%= @post.title %></textarea>
</p>
<p>
<b>Written on:</b><br/>
<select name='post[written_on(3i)]'><option>18</option></select>
<select name='post[written_on(2i)]'><option
value='7'>July</option></select>
<select
name='post[written_on(1i)]'><option>2004</option></select>
</p>

<input type="submit" value="Create">
</form>

This form generates a @params["post"] array that can be used
directly in a save action:

class WeblogController < ActionController::Base
def save
post = Post.create(@params["post"])
redirect_to :action => "display", :path_params => { "id" =>
post.id }
end
end

Learn more in link:classes/ActionView/Helpers/ActiveRecordHelper.html


* Automated mapping of URLs to controller/action pairs through Apache's
mod_rewrite

Requesting /blog/display/5 will call BlogController#display and
make 5 available as an instance variable through @params["id"]


* Runs on top of CGI, FCGI, and mod_ruby

See the address_book_controller example for all three forms
 
J

Jamis Buck

David said:
It's with great pleasure that I present to you the first public release of
Action Pack. I've been working on the framework for close to a year now, so
it's a great relief to finally feel ready to share with the world.
Alongside
Active Record, this almost completes the release of the technology used
to build
Basecamp[1] -- a highly succesful and acclaimed web-application from the
design
masters at 37signals.

Congrats, David! I know you've been working on this for awhile, and I
look forward to trying this out in some of my own projects. :)

Thanks for your hard work!

--
Jamis Buck
(e-mail address removed)
http://www.jamisbuck.org/jamis

"I use octal until I get to 8, and then I switch to decimal."
 
C

Carl Youngblood

Woohoo! I've been waiting for this for a while. Thanks David! Just
reading the brief overview makes me very excited to try it out.

Carl
 
G

gabriele renzi

il Sat, 24 Jul 2004 09:23:34 +0900, David Heinemeier Hansson
<[email protected]> ha scritto::

I could join the general 'woowoo' mood, but I'll wait for the release
of the full Rails pack :)

Anyway, great stuff thank you.
Oh, any plans to support WEBRick?
 
D

David Heinemeier Hansson

I could join the general 'woowoo' mood, but I'll wait for the release
of the full Rails pack :)

You need wait no longer :). It's out: http://www.rubyonrails.org.
Anyway, great stuff thank you.
Oh, any plans to support WEBRick?

Most certainly. Instiki runs on an early fork of Action Pack that uses
WEBrick, so it's certainly possible. The big stumbling block is that
the current Action Pack relies quite a lot on mod_rewrite (or a similar
URL rewriting mechanism), so I'd like to clone that for WEBrick to make
it possible to run an AP app on WEBrick or Apache without changes.
Ideas (or better yet, code) are very welcome.
--
David Heinemeier Hansson,
http://www.rubyonrails.org/ -- Web-application framework for Ruby
http://www.instiki.org/ -- A No-Step-Three Wiki in Ruby
http://www.basecamphq.com/ -- Web-based Project Management
http://www.loudthinking.com/ -- Broadcasting Brain
http://www.nextangle.com/ -- Development & Consulting Services
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top