Friday, February 23, 2007

Metaprogramming @ Ruby

Metaprogramming is the writing of programs that write or manipulate other programs (or themselves) as their data or that do part of the work that is otherwise done at run time during compile time. In many cases, this allows programmers to get more done in the same amount of time as they would take to write all the code manually.

The language in which the metaprogram is written is called the metalanguage. The language of the programs that are manipulated is called the object-language. The capacity of a programming language to be its own meta-language is called reflexivity.

Not all metaprogramming involves generative programming. If programs are modifiable at runtime (as in Lisp, Python, Smalltalk, Ruby, PHP, Perl, Tcl and other languages), then techniques can be used to accomplish metaprogramming without actually generating source code.

Thursday, February 22, 2007

still more rails

URL routing
An incoming URL always maps to some action within a controller. A controller is simply a Ruby class, and each action implemented by the controller is a public method within the controller class. The default mapping from URL to action method is (in "Rails-speak"):

/:controller/:action/:id

If the default URL routing does not meet your needs, you can easily specify your own routing rules, even using regular expressions

Rails routing rules are Ruby code. Here is an example:

map.connect 'date/:year/:month/:day',
:controller => 'blog',
:action => 'by_date',
:month => nil,
:day => nil,
:requirements => {:year => /\d{4}/,
:day => /\d{1,2}/,
:month => /\d{1,2}/}With this routing rule, the following URLs are valid:

http://myblog.com/date/2005
http://myblog.com/date/2005/08
http://myblog.com/date/2005/08/01

This rule decomposes a URL containing a date that, perhaps, a blog might use to display the postings for a particular date. A URL that matches this form will map to the BlogController class and the by_date method. The parameter hash will contain values for a four-digit year (/\d{4}/ is a Ruby regular expression), a two-digit month, and a two-digit day. Further, the month and day are optional; if no values are present, the parameter hash will contain the default value of nil.

Filters allow you to run preprocessing code before Rails executes an action and post-processing code after it completes an action. They are useful for such things as caching or authentication before calling the action, and compression or localization of the response after calling an action. The before_filter processing can either allow the action to be called normally by returning true, or abort the action by returning false (or by performing a render or redirect operation).





http://www.onlamp.com/pub/a/onlamp/2005/10/13/what_is_rails.html?page=5

Tuesday, February 20, 2007

More Rails

Class names are mixed case (each word
starts with a capital letter, and there are no breaks). Table names (and, as
we’ll see later, variable names and symbols) are lowercase, with an underscore
between words

Over in app/controllers you’ll find a file called application.
rb. This file is used to establish a context for the entire application.
By default, it contains an empty definition of class ApplicationController.

If we end a piece of
embedded Ruby with -%> (note the extra minus sign), ERb will suppress the
newline that follows. That means embedded Ruby that doesn’t generate
any output won’t end up leaving extraneous blank lines in the output.

A commonly used method of array objects is <<, which appends a value to
its receiver.

The session construct stores the objects that you want to keep around
between browser requests. To make this work, Rails has to take these
objects and store them at the end of one request, loading them back
in when a subsequent request comes in from the same browser. To
store objects outside the running application, Rails uses Ruby’s serialization
mechanism, which converts objects to data that can be loaded back in.

Rails has a convenient way of dealing with
errors and error reporting. It defines a structure called a flash. A flash is a
bucket (actually closer to a Hash), into which you can store stuff as you process
a request. The contents of the flash are available to the next request
in this session before being deleted automatically. Typically the flash is
used to collect error messages

The flash information is accessible within the views by using the @flash instance variable.

Why couldn’t we just store the error in any old instance variable? Remember
that a redirect is sent by our application to the browser, which then
sends a new request back to our application. By the time we receive that
request, our application has moved on—all the instance variables from
previous requests are long gone. The flash data is stored in the session in
order to make it available between requests.

A helper is simply code in a module that is automatically included into your views.
You define helper files in app/helpers. A helper named xyz_helper.rb defines
methods that will be available to views invoked by the xyz controller. If
you define helper methods in the file app/helpers/application_helper.rb, those
methods will be available in all views.

model objects perform two roles: they map data into and out of the
database, but they are also just regular objects that hold business data.
They affect the database only when you tell them to, typically by calling
save( ).

The render_component( ) method invokes the given action and substitutes
the output it renders into the current view.


one way of handling subroutines at the view level is by using components to show the contents of a page on some other page. A lighter-weight way of doing the same thing is using a partial template. Unlike the component-based approach, a partial template
has no corresponding action; it’s simply a chunk of template code
that has been factored into a separate file

We know how to create new rows in a database table; we create an action,
put a form into a view, and invoke the model to save data away.

Inside a Rails controller, the request information is available in the attribute request. We can check the request type using the methods get?( ) and post?( ).

form_tag needs no parameters, as it defaults to submitting the form back
to the action and controller that rendered the template

Ruby’s attr_accessor creates a read/write attribute in the model.

Monday, February 19, 2007

rails

A Rails scaffold is an autogenerated framework for manipulating a model.
When we run the generator, we tell it that we want a scaffold for a particular
model (which it creates) and that we want to access it through a given
controller (which it also creates).

All scaffold-generated applications use the stylesheet scaffold.css in the
directory public/stylesheets.

The scaffold generator automatically makes use of Rails’ built-in
pagination helper. This breaks the lists of products into pages of 10 entries
each and automatically handles navigation between pages

In Rails, a model is automatically mapped to a database table whose name is the plural form of the model’s class.


The model layer is the gatekeeper between the world of code and the
database. Nothing to do with our application comes out of the database or
gets stored back into the database that doesn’t first go through the model.
This makes it an ideal place to put all validation; it doesn’t matter whether
the data comes from a form or from some programmatic manipulation in
our application. If the model checks it before writing to the database, then
the database will be protected from bad data.