Johan Danforth's Blog


Carpe Diem

April 2008 - Posts

T4 Support in VS2008

Did you know there's T4 (Text Template Transformation Toolkit) support inside VS2008 now? Add a file with the .tt or .t4 extension to your project and you got a T4 template which VS2008 will automatically run when you save it. If you're into this and want to try it out, go to http://www.t4editor.net/ and download the T4-editor from Clarius. It gives you proper editing support from within Visual Studio. They got a version for vs2003 as well.

This may not be as attractive as it used to be, now that we got designer tools for Linq to Sql, entity framework and so on to help us generate boilerplat code for database access, but I'm sure I can come up with some good use for this. The ASP3-like syntax is very easy to grasp, so basically there is no excuse for not using this if you know you're going to produce lots of code that looks or behaves the same. As long as you have some metadata to work from, be it a database, xml file or text file, I'm sure this can be of help to you. Ah yes, you can write the templates in either c# or VB.

Some T4 resources for you maybe:

Hilton Giesenow blogs about T4 and you can download a couple of VS T4 templates from him!

Oleg Sych has a large number of very, very good blog posts about T4, Oleg is THE T4 blogger out there.

The T4-editor website by Clarius has a couple of videos.

The Text Template documentation for vs2008 on MSDN.

On MSDN there's also a good intro video on the topic that you might want to look at if this is of interest to you.

Posted: Apr 23 2008, 01:02 PM by jdanforth | with no comments
Filed under:
What Happened to the Rails Website?

I was going to look at some of the Ruby on Rails screencasts on www.rubyonrails.org site, but someone must have forgot to pay the right amount of money in time or something :)

image

 

I'm sure things will be working fine by the time you read this blog post :)

Posted: Apr 20 2008, 09:27 PM by jdanforth | with 2 comment(s)
Filed under:
Try Ruby in the Browser

There's a pretty awesome online "Ruby in your browser" tutorial that you could try. It has a built in Ruby console and everything is interactive. It's takes 15-30 minutes or so to go through, and it's good. Someone put a whole lot of effort and love into making this one for us Ruby newbies. Go check it out, but use a FireFox browser, because I couldn't make it work properly in IE in Vista.

http://tryruby.hobix.com/

Posted: Apr 20 2008, 04:34 PM by jdanforth | with 1 comment(s)
Filed under: ,
A .NET Guy Looking at Some Ruby (Part 2)

This is me continuing scribbling down notes as I go along relearning lost Ruby skills and at the same time comparing the Ruby syntax and way of writing code to .NET. In my previous post I very briefly went through the basics of variables, loops, iterators, conditionals and basic sorting. This post will look at classes, methods, inheritance and how to reuse Ruby code with include (require) statements.

Methods

Method or function declaration in Ruby is simple, perhaps even simpler than how VB does it:

def my_method(name)
    puts "Hello " + name.to_s
end

my_method "johan"
my_method("johan")

As you can see, you may call the method with or without parenthesis, to Ruby it doesn’t matter. I’ll have to read some more Ruby code to see if there are any exceptions or aesthetic rules to using parenthesis or not, but it seems that many Rubians use parenthesis when calling functions or methods on objects/classes, but leaving it when calling simple methods like puts and similar:

Oh, and Ruby doesn’t support method overloading! There are ways around this with default method parameters, add-ons to the language and so on, but basically – no method overloading. I’ll show some sample code later on when I get to class initialization.

Classes, Constructors and Properties

Ruby is of course object oriented, and very much so (without going into the “where everything is an object” speech). So, of course you can declare objects with properties and methods on them. Declaring a class is familiar:

class MyClass
end

You instantiate a class using a built in static “new” method on the class:

a_class = MyClass.new

Adding a (instance) method to the class is straight forward:

class MyClass
  def hello(name)
    puts name
  end
end

Static methods, or class methods, are declared by prefixing the method with “self.”, like this:

  def self.reverse_upcase(name)
    name.reverse.upcase
  end 

Adding a constructor or initializer to the class is done by declaring an initialize function:

  def initialize(name)
    @name = name
  end

As constructor overloading is not possible, you’ll have to add a default value to the parameter, making it optional in a VB-style of way:

  def initialize(name = "Anonymous")
    @name = name
  end

The @name variable is called an object variable and it is distinguished by the use of the ‘@’ sign. There is no need to declare the object variable in any other way, but to access the object variable (or property or attribute or…) you have to add property accessor code to the class:

  def name
    @name
  end

  def name=(name)
    @name = name
  end 

Now, class properties is used so much that there is a so called attribute accessor keyword available for you in Ruby, making things a bit simple to type:

attr_accessor :name

There are also other attribute keywords like attr_reader and attr_writer available for your pleasure.

Inheritance

Last thing to say about the basics around classes in Ruby is how to handle inheritance. The syntax is similar to c#, but instead of a colon (:), use the less than (<) operator. A very simple example of where the class Employee inherits from Person could look like this:

class Person
  attr_accessor :name

  def initialize(name)
    @name = name
    end
end

class Employee < Person
  attr_accessor :number

  def initialize(name, number)
    @name = name
    @number = number
  end

  def to_s
    @name + " (emp# " + @number + ")"
  end

end

e = Employee.new("Johan","123")

puts e
puts
e.is_a?(Person)
puts
e.is_a?(Employee)

Would print:

Johan (emp# 123)
true
true

Class Reuse

If you want to “use” or “include” Ruby code you’ve already written? Save your code (class) into a MyClass.rb file (as an example) and add a “require” statement to the top of your code where you want to reuse the MyClass class:

require "MyClass"

and classes in the MyClass.rb file will become available for you.

Wrapping Up

I guess that’s enough for now. I think this will be enough to be able to understand some Ruby code if you come across it, unless it contains too many weird class methods like Array#flatten and such J. Then there are a bunch of modules available to Ruby for doing a number of things. I may get into that in a later blog post, I’ll see.

All in all I think Ruby is cool. I’ve used dynamic languages and scripting languages before, but nothing as sleek as Ruby. Ruby is minimal code, fast to type and there’s a flow to the code which makes it quite easy to read.

Next

Next I’ll blog about downloading and building IronRuby and using it to call on .NET libraries, WPF and perhaps Silverlight (which seems to be all the buzz right now). I think I’ll look at exceptions and error handling after that and see if I can get some time to look at Rails again.

A .NET Guy Looking at Some Ruby

I’m thinking it would be nice to relearn the basics of Ruby (which seems to gain more and more popularity) and compare it to some of the dynamic features .NET 3.5 has been blessed with. I’m also interested in where the Microsoft version of the language, IronRuby, is now and how I can use the .NET libraries from it. I installed and looked at Rails some (long) time ago now, but I never got the chance to use it and my minimal Ruby skills have now faded to nil again. So this is me taking it up again, hoping I can use it for something real, perhaps for unit testing or just test driving some .NET code with the help of IronRuby.

What you’re reading is just me scratching down notes as I go along, it’s not an article or so, this is just for me to have something to get back to later on, so bear with me. I will probably write down things that are not right or make wrong assumptions, but I’m happy to get comments if you see something awfully wrong.

Edit: I had to change the section on line continuation, because I was wrong about what I first wrote.

Getting Started

So how do I get started? First I need a Ruby implementation for the platform I’m running on, in my case Windows Vista. On RubyForge there is a Windows installer for Ruby which contains everything you need to get going. It’s available on http://rubyforge.org/projects/rubyinstaller/ and I’m going for it. Later on I’m also going to download and build IronRuby and .NET applications using the Ruby language, but you will still need Ruby installed to build IronRuby. The IronRuby website www.ironruby.net has some notes on all this, but I’ll blog on that later I think.

The installer will give you the Ruby language, runtime and an editor called SciTE. It also includes a samples directory which may come in handy. With Ruby you got several options to create and test small console apps. After the installation completes, just open up a command prompt and type “irb” and you’ll get an interactive Ruby command prompt, which is very handy for both testing and learning. Another option is to go to the Start menu and use “fxri”, which is a graphical interface to the Ruby documentation and also includes an interactive Ruby console. I’ve used both today. Fxri is great when you’re looking at someone else’s Ruby code and you see a command or class you don’t recognize.

The Ruby installer also comes with an electronic version of the book “Programming Ruby - The Pragmatic Programmer's Guide” by Dave Thomas – which I can tell is also a great source for knowledge. I’ve not read it yet, but I’ve used it to look up certain things.

Tutorials

Next I need some getting started articles or such, and there are tons of it on the Internet. You could use the book above, but I’m looking for something which will get me into the dirt quickly.

I found a “Learning Ruby” website by Daniel Carrera which looks promising, and I’m using it to learn the very basics. You’ll find it at http://www.math.umd.edu/~dcarrera/ruby/0.3/index.html  and it’s using the “irb” console in its first steps, which works perfect with IronRuby. Just open up a command prompt and type:

irb --simple-prompt

You'll be greeted with a prompt like this…

>>

…and off you go. Just type your code and press enter. There are other great intros to Ruby on the Internet, and this one by Steve Litt looks good, http://www.troubleshooters.com/codecorn/ruby/basictutorial.htm

Variables and Strings

Most tutorials start with numbers, strings and variables. There’s not much to say about Ruby variables – you don’t have to declare them, just initialize the variable with a value and start using it:

i = 1

Exactly what I’m expecting from a dynamic language, and strings are very easy to work with:

name = "Johan"
name = name + " Danforth"
puts name

The string class in Ruby has a number of powerful methods you can use to work with, same as with the string class in .NET, but the Ruby string class has more than 100 methods on it (from counting the methods in fxri). The .NET string class has around 70 methods, but 45 of these are extension methods that are new to .NET 3.5, and I think many of them were inspired by dynamic languages just like Ruby. I have to say though that some of the methods in Ruby do the same things sort of and some methods are quite funny. Like squeeze, chomp, chop and such :) Methods for parsing, encoding, converting and such are also included in the Ruby string class, functionality that may be baked into other libraries in the .NET framework.

Running a Ruby Program File

Running a Ruby program from a file is dead easy. From the console type “ruby myprogram.rb” and press enter. The installer also associates the .rb file extension with the Ruby executable, so it’s possible to just type “myprogram.rb” or click the file from Windows Explorer.

A good editor for your .rb programs seems to be SciTE which also comes with the Ruby installer. Just open up the editor, type the program and press F5 to run it (make sure you have saved it with the .rb file type). The results will be shown in the right pane of the SciTE editor. Nifty.

Type Conversion

What strikes me as odd is that Ruby is a dynamic language, but automatic type conversion is sometimes not as good as I would think, and something as simple as this will give you an error:

sum = 1 + 2
puts "The sum is " + sum

test.rb:2:in `+': can't convert Fixnum into String (TypeError)

So, in a print statement like the above, Ruby won’t convert the number variable into a string like c# or VB does:

Dim sum = 1 + 2
Console.WriteLine("The sum is " & sum)

You’ll have to convert the sum variable to a string like this:

puts "The sum is " + sum.to_s

Aesthetic Code

Ruby seems to be much about the aesthetics of the code you write. Most Ruby tutorials seem to bring up naming of variables, classes and methods in an early state. What is funny is that the casing of a variable matters to the interpreter, because if you uppercase a variable, it’s treated as a constant. You can change the value of a constant, but the runtime will give you a warning:

PI = 3.14
puts PI
PI = 3.14159265
puts PI

test.rb:3: warning: already initialized constant PI
3.14
3.14159265

But what about code statements that are too long? In c# you can make a line break after almost any statement, and it's the same thing in Ruby. I was wrong about this at first, because in Ruby (as in VB) you can put a backslash (underscore in VB) at the end of the line to do break up a line of code: 

 puts "this is a " + "very " +
  "long statement"

Be careful not to put a space after the backslash, or you’ll get a strange looking error:

test2.rb:1: syntax error, unexpected $undefined
puts "this is a " + "very " + \
                               ^

I’m not fond of the line continuation underscore thing in VB, and I’m thinking the same of the backslash in Ruby, so you won't see me use it.

Loops

Ruby seems to be good at this, and the most common syntax for-loops is easy to read and pretty nice:

i = 1
4.times do 
  puts "pass " + i.to_s 
  i += 1
end

Well, this is just like any other for-loop out there, but the syntax is nicer. There are other ways to type the same thing in Ruby but I’ll get back to that later. I know people have tried to come up with a similar syntax using .NET 3.5 method extension and lambda expressions, but I think it’s hard to make it as compact as in Ruby. My 10 minute feeble attempt at making a c# version of the Ruby times-method would probably be an extension method like this:

        public static void times(this int number, Action codeblock) 
       
            while (number-- > 0) 
                codeblock(); 
        }

And I could call it with a one-liner lambda expression like this:

            var i = 1; 
            4.times(() => Console.WriteLine("hi! " + i++));

Or with a delegate (with some richer code inside) like this:

            var i = 1; 
            4.times(delegate(){ 
                Console.WriteLine("pass " + i); 
                i += 1; 
            });

Not as nice as the Ruby variant, but close :) The System.Action Delegate class in .NET 3.5 is pretty awesome btw, and you got a generic version of it as well if you need to pass arguments on to the delegate.

Of course Ruby has the traditional VB-like “for” statement as well, with a couple of variations. A 1-5 for-loop looks like this:

for x in 1..5 
  puts x
end

But a 1-4 for-loop looks like this, see the difference?

for x in 1...5 
  puts x
end

2 periods mean as long as the variable is less than or equal to the “to” value (inclusive), 3 periods mean as long as the variable is less than the “to” value (exclusive). I’m sure this is a common coding mistake, as it’s easy to miss. And as you can see, no braces/brackets like in c#, so I guess VB programmers feel a bit more comfortable with this syntax, but the for-loop statement in Ruby is, I believe, syntax sugar for this statement, which involves braces/brackets but equally valid:

(1...5).each {|i|