lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Having skimmed Programming in Ruby but never really coded in Ruby, I was
intrigued by this when I started looking at Rails for ideas. It took a
little while for it to dawn on me what this is doing and why it works:

class ... end in Ruby temporarily adjusts the global environment. Hence, a
function like has_many can add whatever fields and other operations it would
like. The Lua equivalent would be something like:

    class( "Book", ActiveRecord.Base, function()
        belongs_to( 'publisher' )
        has_and_belongs_to_many( 'authors' )
    end ) 

    class( "Publisher", ActiveRecord.Base, function()
        has_many( 'books' )
    end )

    class( "Author", ActiveRecord.Base, function()
        has_and_belongs_to_many( 'books' )
    end )

That's not that much longer, but it seems much more convoluted thanks to the
function declaration and the parentheses. Imagine for a moment that Lua had
a lighter weight syntax for parameterless functions and supported these as
arguments to functions much as it supports tables and strings...

    class "Book" ( ActiveRecord.Base ) do
        belongs_to( 'publisher' )
        has_and_belongs_to_many( 'authors' )
    end

    class "Publisher" ( ActiveRecord.Base ) do
        has_many( 'books' )
    end

    class "Author" ( ActiveRecord.Base ) do
        has_and_belongs_to_many( 'books' )
    end

The syntax rule I'm using is that if do appears in a position where we could
expect a function argument, it defines a parameterless function that gets
passed to the function from the preceding sequence. This doesn't reconcile
with the existing definition for do, but I didn't want to invent a new
keyword and I wanted to be able to use end as the closer.

Side note: It might be nice to have an easier way to write routines that
parse parameters received in sequence like this. Right now, one would have
to write:

    function class( name )
        return function( basetype )
            return function( body )
                -- construct class using name, basetype, and body
            end
        end
    end

This gets even messier if one wants to allow pieces to be optional by
testing the parameters.

Mark

on 3/22/06 2:55 PM, PA at petite.abeille@gmail.com wrote:

> [Ruby on Rails]
> http://www.loudthinking.com/arc/000297.html
> 
> class Book < ActiveRecord::Base
>  belongs_to :publisher
>  has_and_belongs_to_many :authors
> end
> 
> class Publisher < ActiveRecord::Base
>  has_many :books
> end
> 
> class Author < ActiveRecord::Base
>  has_and_belongs_to_many :books
> end