{ |one, step, back| } 117 to 126 of 182 articles WikiSyndicate: full/short

Ruby in five E's   31 May 04
[ print link all ]
I’ve been listening to David Heinemeier Hansson talk on the "Ruby on Rails" project (download the talk here). I really like his summary of Ruby slide which he calls "Ruby in five E’s".

I’ll reproduce his summary here:

  • Everything is an object
      5.times do print "hello world".capitalize end
    
  • Elegant blocks gives inline power
      db.select_all(sql).inject([]) do |objects, row|
        objects << instantiate(row)
      end
    
  • Exploring with reflection
  • Extending at runtime (even standard lib!)
  • Extensive standard library
    • XML, Test/Unit, Distributed Ruby, XML-RPC, WEBrick

Starting with a Blank Slate   21 May 04
[ print link all ]
Here’s a quick Ruby tip. All Ruby classes ultimately inherit from the Object class. This means that every object gets about 40 methods from the Object class without doing anything extra.

Sometimes, however, you don’t want to start with all those methods. I’m thinking of proxy classes that use method_missing to forward messages to another object. Methods defined by Object (actually Kernel, but lets not worry about that) will not be forwarded because they are not missing in the proxy.

This is easy to fix. Create a BlankSlate class like this …

  class BlankSlate
    instance_methods.each { |m| undef_method m unless m =~ /^__/ }
  end

BlankSlate is a class with no instance methods except for __send__ and __id__.

Now we can create a proxy object by inheriting from BlankSlate

  class Proxy < BlankSlate
    def initialize(obj)
      @obj = obj
    end
    def method_missing(sym, *args, &block)
      puts "Sending #{sym}(#{args.join(',')}) to obj"
      @obj.__send__(sym, *args, &block)
    end
  end

Now, try this with the proxy object:

  n = Proxy.new(1)
  puts (n+5)
  puts "1.id = #{1.id}"
  puts "n.id = #{n.id}"
  puts "n.__id__ = #{n.__id__}"

Here’s the output:

  $ ruby blankslatedemo.rb
  Sending +(5) to obj
  6
  1.id = 3
  Sending id() to obj
  n.id = 3
  n.__id__ = 537806934

Miller on Mock Objects   07 May 04
[ print link all ]
Charles Miller reminds us that there are two reasons for using mock objects.
  1. To create an environment where the object under test can live.
  2. To test that the object under test correctly modifies the environment.

Each use requires a slightly different API (#1 sytle APIs tend to be more flexible than style #2). I’ve used both styles of APIs in the past (and had been frustrated trying to use a style #2 API in a style #1 situation), but I hadn’t connected the differences with the reason for the differences before.

RubyGems 0.3.0 Release   07 May 04
[ print link all ]
This is a bit late (but Hey! I’ve been busy). Chad Fowler has a good writeup on the new features in the latest RubyGems alpha release. We’ve put a lot of effort into this project and it is looking pretty good. This version is fairly feature complete, but we expect some do some tuning and adjustments. Check it out and provide some feedback.

Ruby Module Spotlight: Instiki -- There is no step three.   22 Apr 04
[ print link all ]
Instiki is a really cool wiki server from David Heinemeier Hansson. It is one of the easiest wiki servers to setup and run that I have seen.

Here’s what I did. First download the tar or zip file (as you need) from here. Then …

  $ tar zxvf instiki-0.3.1.tgz
  (lot of output omitted)
  $ ruby instiki.rb 2500

Now you have a wiki server running locally on your computer. To see it, direct your browser to localhost:2500 and edit away.

What is a Wiki you ask? A Wiki is a set of web pages that can be easily edited from a browser. Hyperlinks within a Wiki are easy to setup and generally are keyed off of words with special capitalization. New pages can be created at the drop of a hat and the pages are always live and changable. Formatting rule are usually very simple, for example asterisks surrounding a word can make it *bold*.

Wikis are great for collaborative web sites, where everyone contributes a bit here and a bit to build the site. I’ve used Wikis to coordinate software projects and provide documentation.

Instiki uses RedCloth, a Ruby implementation of Textile to handle the formatting. Although a bit different from the formatting rules used by traditional Wikis, Textile looks to be very flexible in the kind of HTML it is able to produce. Yet it doesn’t seem to get in the way of just entering text.


Update: Instiki now as its own domain: www.instiki.org. I’ve updated the home page link in article.


Weird CSS Problem with New Site Look   18 Apr 04
[ print link all ]
Ok, this is weird.

I was using Internet Explorer at work (that’s not the weird part), and today I used it to browse to my blog. Imagine my surprise when I discovered that the new CSS look for my site was gone! The site was being rendered in the old-style CSS! I switched back to FireFox (mozilla) and sure enough, the new look was still showing up there. It is only under Internet Explorer that the new CSS fails to show up.

I’m not even sure how it is possible to IE to screw up? I mean, the old CSS files weren’t even on my server anymore (unless I screwed up somewhere). The new CSS file has a different name and is in a different location, so a cache problem seems unlikely. This is just bizarre.

Since I don’t run IE at home (I’m Linux only at home), I don’t know if this is a work related proxy/caching anomoly, or if IE everywhere has this problem.

So … If you are using Internet Explorer to view this site, let me know if it looks like the new style or the old style. (Click on the links to see screen shots).

Thanks. You can drop me an email at jim@weirichhouse.org or use the Wiki feedback link below.


UPDATE!

For some reason, I got it in my head that a "#" character was a comment in CSS. Evidently it is not, it is just bad syntax. Mozilla based browsers tend to drop the line that contains the hash mark. IE just skips the hash mark and continues. As I was reworking the CSS file, I commented out the old colors and added the new stuff. IE overrode the new colors with the old "not quite commented out" colors. Mystery explained.

FYI, apparently CSS uses C style /* … */ comments. Well, now I know.

Thanks to Gabriele Renzi who pointed out the problem and to Andrew Johnson who supplied the link www.danvine.com/iecapture that I used for testing IE from home.


Perl 6 -- Apocalypse 12   17 Apr 04
[ print link all ]

The Once and Future Perl

In February 2001, Larry Wall came to Cincinnati to (amoung other things) give a talk on the future directions that the Perl language would be taking in version 6.

I had switched to using Ruby (from Perl) about 6 months earlier at that time, and I had a chance to talk to Larry about the changes in OO support that he wanted in Perl. I remember him commenting that Perl5 made OO possible, but not necessarily convenient.

In his Apocalypse series, Larry describes the direction Perl 6 will be taking in several areas. Three years after that talk, Apocalypse 12 is available, and it addresses the details of Object Orientation in Perl 6.

I just want to point out that all the examples in this blog entry are directly from the apocalypse.

Objects in Perl 6

I skimmed the article last night and jotted down some notes. You will need to read the apocalypse yourself for any substantial details (its a long article, 20 pages in all). I’m just going touch on some highlights and first impressions.

Objects in Perl 5 were built out of the existing language framework. Blessing was the only new piece added to Perl to support objects, hash, packages and namespaces were all existing Perl concepts. And although it worked, it left the Object Model of Perl very open to variations.

Perl 6 adds more language support for direct support of objects, and leave less to programmer choice. Here is a point object in Perl 6:

    class Point {
        has $.x;
        has $.y is rw;
        method clear () { $.x = 0; $.y = 0; }
    }

Notice the keywords for class and the declaration of attributes $.x and $.y. The $.x attribute is publicly readable, and the $.y is publically writable as well. Private attributes can be declared with a colon instead of a period (e.g. $:z).

Methods are part of the class declaration now and are syntactically differentiated from normal subroutines by using the "method" keyword.

ISA vs HASA

In OO circles it is said that HASA relationships should be modeled by composition and ISA relations by inheritance. Although I find that saying to be a bit simplistic, it is cool that Larry makes that connection explicit by his choice of keywords. Did you notice in the above example that the attributes were introduced by the keyword has?

So its not surprising that inheritance is introduced with the is keyword. Here’s another simple example building on the previous one:

    class Point3d is Point {
        has $:z = 123;
        method clear () { $:z = 0; next; }
    }

The is keyword is overloaded (this is Perl after all). Traits are also declared using the is keyword. That leads to interesting code like:

    class Moose is Mammal is stuffed is really(Hatrack) is spy(Russian) {...}

Roles

Although Perl 6 will support inheritance (single or multiple), it also contains the idea of Roles. My impression of a Role is that is a cross between Ruby modules and Java interfaces.

Roles look a lot like classes, but they cannot be instantiated. Roles cannot inherit from classes, but they can be composed with other roles.

Here is an example role. Notice that the method feed depends upon the method call should should be defined in the final objects.

    role Pet {
        method feed ($food) {
            $food.open_can();
            $food.put_in_bowl();
            .call();
        }
    }

Roles are attached to classes with the does keyword:

    class Dog {
        is Mammal;
        does Pet;
        does Servant;
        does Best::Friend[Man];
        does Drool;
        ...
    }

So far Roles look very much like Ruby modules. However, here is a twist. If the methods in roles are only declared instead of defined, then the Role specifies the methods expected to be implemented in the class. One final example.

    role Pet {
        method feed ($food) {...}
        method groom () {...}
        method scratch (+$where) {...}
    }

The {…} construction means that the body of the method is defined elsewhere.

Stuff I Left Out

This Apocalypse runs 20 pages. Its obvious that I skipped over a lot of material. It seems like the OO support in Perl 6 is much better than Perl 5. The object module is very flexible (a good thing), but also rather complex (a not so good thing). Larry addresses some really interesting problems (such as multiple dispatch), and it will be interesting to watch to see if the features really work together or not.

Am I switching? No, not really. I really much prefer the much simplier object model (and syntax!) provide by Ruby. But I will be watching.

Some Great Quotes

Larry is great for generating good quotes. I’ll end this entry with a few quotes that struck me.

It has often been claimed that Perl 5 OO was "bolted on", but that’s inaccurate. It was "bolted through", at right angles to all other reference types, such that any reference could be blessed into being an object. That’s way cool, but it’s often a little too cool.

Here’s another one:

Some people will be surprised to hear it, but Perl is a minimalist language at heart. It’s just minimalistic about weird things compared to your average language.

And speaking of chosing a keyword to distinguish typing from subtyping:

On the other hand, a bit confusingly, it looks like subtyping will be done with the "type" keyword, since we aren’t using that word yet.

Closing Joke

For some reason, I found this extremely funny:

Biologist :What’s worse than being chased by a Velociraptor?
Physicist :Obviously, being chased by an Acceloraptor.

More New Looks   14 Apr 04
[ print link all ]
I was chatting with Chad Fowler last night on AIM. Amoung other things, Chad demonstrated his MovableStyle template for Rublog. It is pretty neat. You can download stylesheets from MovableStyle intended for MovableType and use them with the latest version of Rublog. Chad’s website uses a MovableStyle stylesheet.

Today Dave Thomas mentions the Moveable Style support in a blog entry. So at this point, I had to experiment!

The following links demonstrate the MovableStyles stylesheets for this website. Click on the link and see this site transformed using the stylesheet. Have fun.

  • ModernLines — Very nice looking.
  • Trendy — I like this one, except for the strange super-sized calendar.
  • Boxed — This one is too busy for my taste.
  • SlashDot — Yes, it is a copy of our favororite geek website.
  • Chad Fowler — Ok, I stole Chad’s style sheet just to show it could be done. I really like this style.
  • Original Rublog — This is the original, out of the box color scheme that comes with Rublog. I find the colors a bit … jarring. But my daughter likes it.
  • Default — The default look and feel for this site. It feels a bit plain now.

All but the last two styles were downloaded from MovableStyles.

Correction: Chad tells me that his style is a MovableType style, but it was not downloaded from the MovableStyle web site.


New Site Look   09 Apr 04
[ print link all ]
I’ve updated the site with several new items.
  • First, a new CSS scheme. I think it makes the pages look a little sharper.
  • A wiki is now available for feedback. See it at onestepback.org/cgi-bin/osbwiki.pl. There’s not much in the wiki yet, but I intend to use it for feedback and posting sample code snippets. Someone on the Rake mailing list wished to have a place for collecting sample Rakefiles, and the wiki would work nicely for that.
  • The wiki supports an RSS feed at onestepback.org/cgi-bin/osbwiki.pl?action=rss

Hey! Look below! We already have a feedback link for this article.


Ruby Module Spotlight: Session   27 Mar 04
[ print link all ]
Here’s a sweet little module from Ara T. Howard. It is called Session and will run a shell session under the control of a Ruby script. Standard output and standard error are captured by the session object and made available to the script.

How about a quick example …

  bash = Session::Bash.new
  stdout, stderr = bash.execute "ls"
  p stdout     # prints "trysession.rb\n"

The shell session created is persistent. Executing multiple commands in the session is like typing multiple lines into a real shell, the state is remembered from one command to the next. If you change the current directory, subsequent commands will execute in the new location. Environment variables set in the session will be remembered in later commands.

  bash = Session::Bash.new
  bash.execute "export GREETING=hi"
  out, err = bash.execute "echo $GREETING"
  p out    # print "hi\n"

If you pass an IO object to the session, it will append its output to that object.

  out = StringIO.new
  bash = Session::Bash.new
  bash.execute "ls", :stdout=>out
  bash.execute "ls ..", :stdout=>out
  p out  # prints the output from both "ls" commands.

One possible use of Session is to test command line scripts where you wish to check both standard output and standard error independently.

  class TestVersion < Test::Unit::TestCase
    def test_install
      out = StringIO.new
      bash = Session::Bash.new
      bash.execute "export GEMPATH=#{TESTDIR}"
      out, err = bash.execute "bin/gem --install testgem"
      assert_equals 0, bash.exit_status
      assert_equals "", err
      assert_equals EXPECTED_OUTPUT, out
      assert_test_gem_installed
    end
  end

You can find Session at www.codeforpeople.com/lib/ruby/session/

 

Formatted: 08-Sep-08 15:03
Feedback: jim@weirichhouse.org