Archive for the tag 'Seaside'

Rails vs Seaside

Sometimes a small sample is really helpful in showing the differences between two approaches. Ruby on Rails is a slick web framework for building web applications the old way. When I say the old way, I mean building URLs manually and passing parameters through query strings manually, i.e. marshaling session data manually.

Rails automatically maps URLs to controllers and methods in those controllers to setup the appropriate models, and automatically binds the correct view for that method, based on naming conventions of the files. It’s a great method and saves much of the hassle of writing a web app while enforcing a nice model view controller paradigm. Here’s a sample any Rails programmer will probably recognize, first list.rhtml…

<% @recipes.each do |recipe| %>
  <tr>
   <td><%= link_to recipe.title, :action => “edit”, :id => recipe.id %></td>
   <td><%= recipe.category.name %></td>
   <td><%= recipe.date %></td>
  </tr>
<% end %>
<p><%= link_to "Create new recipe", :action => “new” %></p>

and its controller…

class RecipieController < ApplicationController
    def list
        @recipies = Recipie.find(:all)
    end

    def edit
        @recipie = Recipie.find(@params[:id])
    end
end

Nice and clean, but the programmer is still working in a template language, requiring constant context switching between Ruby and HTML, and still manually building anchor tag URLs by calling a method and passing in the recipe’s id. Passing around ids requires that the next view, bound to the edit method in the controller, needs to look up the object from the database with that id from reading the request parameters. You can see this in the edit method of the controller, it sets up data in an instance variable in the controller so the view will have access to it.

This is classic web development done very cleanly, and honestly very Smalltalk’ish, however, passing around an object id isn’t very object oriented (it’s rather relational actually), and context switching between two languages while working in the view isn’t very fun. Instead of passing around an objects id why not pass around the object instead?

Enter Seaside, same code, different approach, more object oriented…

renderListOn: html
    self recipes do: [:recipe |
        self renderRecipe: recipe on: html ].

    html paragraph:
        [html anchor
            callback:[self editRecipe: Recipe new];
            with: ‘Create new Recipe’]

renderRecipe: aRecipe on: html
    html tableRow id: #recipie, aRecipe id; with:
            [html tableData:
                [html anchor
                    callback:[self editRecipe: aRecipe];
                    with: aRecipe title];
                tableData: aRecipe category name;
                tableData: aRecipe date ]

and the controller code…

recipies
    ^recipes ifNil:[recipes := Recipe findAll]

editRecipe: aRecipe
    self call: (RecipeEditor for: aRecipe)

Seaside puts the view and controller together in one class, the component, and it can do so cleanly because there is no templating language, rendering views are simply method calls in pure Smalltalk. So instead of having a controller, with a bunch of RHTML files and partials, we have components (aka view/controllers), with rendering methods (aka partial views).

It’s important to note however, that view code and controller code are still normally kept quite separate and organized using Smalltalk’s method categories. View methods are normally categorized as “rendering”, or something more specific like “rendering ajax”, while controller code is categorized in categories like “actions”, “queries”, “accessing”, or whatever categories you make up to keep your code organized. This is one of those Smalltalk things that no other language really has, and only exists in its environment so it doesn’t translate to sample code.

Now, the main thing to note here, is that objects are passed between views as actual objects using a constructor on the view (RecipeEditor for: recipe). One component simply creates and calls another. The components are also rendered in pure Smalltalk, which means they can be factored into smaller more reusable methods (aka partials), using all of Smalltalk’s existing tools, i.e. the refactoring browser. This is amazingly productive.

The anchor tag has a closure attached to it via its #callback: method, containing the actual code we want to execute when the user clicks the link. This closure, or block as Smalltalkers call them, gets turned into a URL automatically by Seaside and stored as a continuation on the current session. This means that RecipieEditor view doesn’t need to go back to the database and look up the recipe by its id, because it was given the actual recipe object directly (less load on the database). In essence, instead of passing a bunch of state through a URL manually, you simply say when this link is pressed, execute this code. This is a technique discussed by Paul Graham in his essay Beating the Averages that he used in ViaWeb. This one change drastically changes the way one thinks about, and builds, web applications and makes programming much simpler.

Notice how I’ve factored out the rendering of a single row into its own method. This sets me up to do some nice simple Ajax updates of individual row by being able to pass an Ajax rendering canvas through that same #renderRecipeOn: method. For example, I could re-render just that row, via Ajax, when a hyper link is clicked with just this…

html anchor
    onClick: (html updater id: #recipe, self randomRecipe id;
                    callback:[:ajax | self renderRecipe: self randomRecipe on: ajax]);
    with: ‘Replace random recipe with another random recipe’

So when I write a page, I break it up into rendering methods based on which parts of the screen I want to update via Ajax. This is similar to what Rails does with partials, except Seaside does it with ordinary objects and methods. Top to bottom, objects and method calls in pure Smalltalk, no web stuff.

This is what Seaside gives you, complete abstraction of the http request response cycle so you can program normally, as you would any desktop application, without all the extra hassles that web development introduced. Even abstracting away JavaScript for the most part. This translates into much faster application development, yes, even faster than Rails. It also means if you have to port a desktop application to the web, Seaside may allow you to do so without having to completely rework the existing design.

The price you pay… sessions and a little memory on the server. Yes it’s harder to scale than a session-less approach like Rails, but it will scale, and memory is cheap these days, far cheaper than programmers. Seaside, like Rails, is a very opinionated framework. Seaside’s opinion is that programming is the most expensive part of application development, so let’s optimize development time instead of CPU memory and cycles and throw out the (stateless/templated html) model of web development in favor of simpler web development in one language, where you have all of your tools available and aren’t constantly context switching between several languages.

A Smalltalk ActiveRecord using Magritte, Seaside, and Glorp

I’ve been working on a side project that’s given me reason to want to use Glorp with Seaside. Having just mapped the sample blog written from my screencast into Glorp manually, by writing Glorp descriptors, I decided that I wanted something simpler, something more like Ruby on Rails, automatic persistence, with almost no configuration.

Having used Magritte for a while to describe my Seaside UI’s, I decided that those same descriptions contained all the necessary meta data to write Glorp descriptions from. Unlike the ActiveRecord in Rails, or the one Alan Knight is working on, I’m not using the database as the source of my metadata, I’m using the objects themselves with meta data from Magritte instead.

I sat down and started hacking out my own ActiveRecord implementation, which is really just a small framework that glues these three existing frameworks together for me and makes using Seaside against a Postgres database easy for me. Needless to say, knowledge of Magritte is a prerequisite for using this code.

I just open sourced the code I’ve been using on SqueakSource, just add this repository to Monticello to get a copy

MCHttpRepository
    location: 'http://www.squeaksource.com/MagritteGlorp'
    user: ''
    password: ''

This is a first cut Alpha release, I make no guarantees, only the brave need attempt using it. To use it, simply requires the following.

subclass MGActiveRecord, this will be your root class, all your biz classes can descend from this.

MGActiveRecord subclass: #SBActiveRecord
	instanceVariableNames: ''
	classVariableNames: ''
	poolDictionaries: ''
	category: 'SeasideBlog-Glorp'

subclass MGDescriptorSystem and override #rootClass, returning the class above, like so…

rootClass
	^SBActiveRecord

and on the class side, override #defaultLogin

defaultLogin
    ^(Login new)
        database: PostgreSQLPlatform new;
        username: 'xxxx';
        password: 'xxxx';
        connectString: '127.0.0.1_yourDatabaseName'

and optionally #initializeDatabase: if you want to insert some test data on creation of the schema…

initializeDatabase: aSession
    aSession inUnitOfWorkDo: [aSession register: SBPost testPost]

Now, describe your classes with Magritte, here’s an example…

descriptionCategories
    ^ (MAMultipleOptionDescription selector: #categories label: 'Categories' priority: 1000)
        options: [SBCategory findAll execute] dynamicallyRefreshed ;
        classes:{SBCategory};
        reference: SBCategory description;
        componentClass: MACheckboxGroupComponent;
        yourself

[SBCategory findAll execute] dynamicallyRefreshed is a shortcut for (MADynamicObject on:[SBCategory findAll execute]) that I implemented, since Magritte descriptions are cached, I do this to ensure each time a UI is rendered, a fresh query is done against the database.

You must manually create your database in Postgres. Once created, to create your schema, simply call #createSchema on your MGDescriptorSystem subclass like so…

SBGlorpDescriptions createSchema.

It will use your default connection to infer and create the schema necessary to support your object model. I’ve only used this on two schemas so far, but it seems to work OK, though I’m sure there must be bugs.

Now, to use this all in Seaside, subclass MGGlorpSession and override #glorpDescriptionClass like so…

glorpDescriptionClass
    ^SBGlorpDescriptions

Once done, from Seaside, I can execute queries like so…

blogPosts
    "Grab published blog posts from database and return them in reverse order"

    ^(SBPost findAll)
        limit: self numberOfPostsToShow;
        where: [:each | each isPublished];
        orderBy: [:each | each timestamp descending];
        execute

And have the full power of Glorp available from two class methods, #find and #findAll which return Glorp queries wrapped in a decorator that allows you to call execute on them for the current Seaside context. All classes are commented. If anyone is brave enough to use this, I’d appreciate any feedback on any trouble you run into, or just general discussion about the approach. As I said before, I make no guarantees, but I’m using this code myself, and so far, it seems OK.

UPDATE: The tests included in the package are there to demonstrate a missing feature, automatic inheritance mapping. They do not need to be ran and have nothing to do with the base package. If createSchema works, you’re done, just start using it.

Composeable Views in Seaside

So I was talking to a Ruby on Rails buddy of mine today, and he asked me if Seaside could do views composed from other views like Rails. I thought I’d throw up a quick sample in case any one else wonders how this is done. It’s a very common thing to do, so common, I’d never considered writing about it until today.

It’s very basic, contains a header, footer, main control, and a result control to show how lists of items can each be their own views. MVC is so ordinary in Seaside I forget how novel it is to some other frameworks.

I start off creating a simple header control with one method…

Header>>renderContentOn: html
    html div: 'Header'

Then a footer control doing the same, though each could be much more complex…

Footer>>renderContentOn: html
    html div: 'Footer'

Ok, now I’ll create a class for showing the results of a query, with each result being a component of its own…

ClassResult>>modelClass: aModel
    modelClass := aModel

ClassResult>renderContentOn: html
    html heading: modelClass name level: 3.
    html div: ((modelClass allSubclasses
        collect: [:each | each name]) join: ‘, ‘)

I just printed the class name, and under it, all its subclasses names separated by a comma.

Now for the main root component that will be composed of these subcomponents…

ClassUsage class>>canBeRoot
    ^true

ClassUsage>>initialize
    "setup sub components in instance variables, for the results,
    I'm grabbing all the subclasses of WAComponent that have subclasses
    themselves and then sorting them by how many subclasses they have,
    and then using them as the model in a view, and storing the list of
    views for later rendering."

    super initialize.
    header := Header new.
    footer := Footer new.
    results := ((WAComponent allSubclasses
                reject: [:each | each allSubclasses isEmpty])
                    asSortedCollection: [:a :b |
                        a allSubclasses size > b allSubclasses size])
                    collect: [:each | ClassResult new modelClass: each]

ClassUsage>>children
    “return all sub components as a list”

    ^{ header. footer } , results asOrderedCollection

ClassUsage>>renderContentOn: html
    html render: header.
    (html div)
        class: #body;
        with: [results do: [:each | html render: each]].
    html render: footer

That’s about it. I setup the subcomponents in the initialize, and then by explicitly not calling super renderContentOn, I then have the option of when and where to render subcomponents.

Making a Connection Pool for Glorp in Seaside

First let me say…. Glorp rocks! Kudos to Alan Knight for this framework. I’m really liking it, having written two home brew O/R frameworks in the past (mostly to learn how, and in less capable languages than Smalltalk), I can appreciate the flexibility of its design. This is going on my list of programs to read thoroughly from time to time. It’s a very well written and very nice example of a well written OO system that anyone could learn a lot from. I’d add both Seaside and Magritte to that list as well. Reading great code is a lost art too few programmers do these days.

Glorp really gives me that object oriented feel and allows me to at least pretend I’m working with an object database, while keeping all the benefits of a relational database like constraints, indexing, and random queries. It’s far more capable than I thought it’d be and totally pluggable if you need to add any capabilities. It’ll do things Rails couldn’t dream of as far as mapping and querying goes, and it does it in native Smalltalk syntax.

OK, enough of the Glorp envy. I’ve been working to get Glorp, Seaside, and Magritte all tied together so I can have a full stack framework to work with that allows me to work in Smalltalk at every level. I’ve used many languages and nothing comes close to the productivity I feel in Smalltalk, so naturally, I’m looking forward to finally using it from top to bottom, html, biz objects, and sql queries, all in Smalltalk.

While working on an implementation of a sort of ActiveRecord, but using Magritte for the meta data instead of the database, I quickly found I needed to mary one Glorp session to one Seaside session to keep everything simple and intuitive. It’s a good match, however, I don’t want to keep a connection to PostgreSQL, they’re too valuable a resource to keep sitting idle and unused for 10 minutes while a session times out.

I played around a bit and found, at least so far, that within Glorp, the Squeak and Postgres adapters don’t really maintain any state and can be swapped in and out of an existing GlorpSession. I decided that I’d write a connection pool for Glorp’s SqueakDatabaseAccessor allowing me to tie a PostgreSQL connection to a request allowing much more scalability in the web scenario without risking running out of connections during peak loads. So, after a bit of playing around, I came up with a class called MGConnectionPool. I’m using the class side for all this code, taking advantage of the simple fact that in Smalltalk a class “is” a singleton ensuring there’s only one instance of the pool in the image.

MGConnectionPool class>>initialize
    lock := Monitor new.
    connections := Dictionary new.

MGConnectionPool class>>poolTimeout
    ^30 seconds

MGConnectionPool class>>withUser: aUser password: aPassword
    server: aServer database: aDatabase in: aBlock

    | connection result expired |
    "Grab a connection from the pool util you find one that
    isn't expired, logout the expired ones"
    expired := true.
    [expired]
        whileTrue: [connection := self
                        getConnectionUser: aUser
                        password: aPassword
                        server: aServer
                        database: aDatabase.
            expired := DateAndTime now - connection value > self poolTimeout.
            expired ifTrue: [connection key logout]].

    “pass the connection through the block, which will be the page
    request, and ensure it’s returned to the pool when done”
    [result := aBlock value: connection key]
        ensure: [self
                returnConnection: connection
                forKey: (self
                        makeKeyUser: aUser
                        password: aPassword
                        server: aServer
                        database: aDatabase)].
    ^result

MGConnectionPool class>>getConnectionUser: aUser password: aPassword
    server: aServer database: aDatabase 

    | key matchingConnections |
    ^ lock
        critical: [key := self
                        makeKeyUser: aUser
                        password: aPassword
                        server: aServer
                        database: aDatabase.
            matchingConnections := connections
                        at: key
                        ifAbsentPut: [OrderedCollection new].
            matchingConnections
                ifEmpty: [matchingConnections add: (self
                            newLoginForUser: aUser
                            password: aPassword
                            server: aServer
                            database: aDatabase)
                            -> DateAndTime now].
            matchingConnections removeFirst]

MGConnectionPool class>>makeKeyUser: aUser password: aPassword
    server: aServer database: aDatabase 

    ^aUser , ‘~’ , aPassword , ‘~’ , aServer , ‘~’ , aDatabase

MGConnectionPool class>>newLoginForUser: aUser password: aPassword
    server: aServer database: aDatabase 

    ^ (SqueakDatabaseAccessor forLogin:
        (Login new database: PostgreSQLPlatform new;
             username: aUser;
             password: aPassword;
             connectString: aServer , ‘_’ , aDatabase))
         login;
         yourself

MGConnectionPool class>>returnConnection: aConnection forKey: aKey
    lock
        critical: [aConnection value: DateAndTime now.
            (connections at: aKey)
                add: aConnection]

This allows me to create a subclass of a Seaside session and glue Glorp and Seaside together like this.

MGGlorpSession>>commit: aBlock
	^database inUnitOfWorkDo: aBlock

MGGlorpSession>>execute: aQuery
	^database execute: aQuery

MGGlorpSession>>register: anObject
	^database register: anObject

MGGlorpSession>>ensureGlorpSessionOn: aDbAccessor
	database
		ifNil: [database := GlorpSession new
						 system: (SBGlorpDescriptions
                            forPlatform: aDbAccessor
                                currentLogin database);
						 accessor: aDbAccessor;
						 yourself]

MGGlorpSession>>responseForRequest: aRequest
	^ MGConnectionPool
		withUser: (self application preferenceAt: #glorpUserName)
		password: (self application preferenceAt: #glorpPassword)
		server: (self application preferenceAt: #glorpServer)
		database: (self application preferenceAt: #glorpDatabase)
		in: [:dbAccessor |
			self ensureGlorpSessionOn: dbAccessor.
			database accessor: dbAccessor.
			super responseForRequest: aRequest]

Reading in the authentication from the current application config. Now I can feel safe using Glorp from Seaside, and from within any Seaside component, run Glorp queries with ease in a scalable manner. The code is totally generic and can reused for every future application by simply subclassing. Programming is getting more fun by the day; it’s going to be a good year for Seaside. All the necessary frameworks exist to build a truly awesome and “fully” object oriented web stack that doesn’t drag you down into the request response cycle inherent to other frameworks, even Rails. Glorp + PostgreSQL + Seaside + Magritte + Scriptaculous + Albatross + a little glue == Slick totally object oriented full stack Ajax web framework of the future, today!

« Previous PageNext Page »