Joe McGlynn

Learning Ruby

Since I started working with Rails I’ve of course gotten more and more exposure to Ruby.  I’m no Ruby expert by any stretch, but I’ve been learning some really cool things.  Rails is awesome, it makes building Java-based web apps positively medieval.  I’m not even slightly exaggerating.

 But, Rails completely aside, Ruby is a really cool and amazing programming language.  It’s terse but totally readable.  It’s actually very English-like.  It has some really sexy language features. 

 I just published a short video on a basic introduction to Ruby here: http://dn.codegear.com/article/37087

One of the first things you’ll learn when you start playing with Ruby is that everything is evaluated as an expression.  Things that look like statements return their value as an expression.  So a simple quoted string returns itself as the evaluated value. 

The next thing you’ll see is that everything is an object.  You can call methods on a quoted string, for example:

blog1

And of course that shows that method calls (Ruby developers often call them "messages" sent to a "receiver") don’t require parenthesis.  This is more than a convenience, it makes programs more readable in a lot of cases.

Another interesting effect of the expression evaluation is that you can directly chain methods together, thusly:

blog 2

These examples are running in Interactive RuBy or IRB.  The green letters are a throwback to my VT terminal days…sorry.

This reads "take the time right now, make it into a string, split it up (default is on whitespace), convert it to an array and give me the 5th element (zero-based)".  It’s not they way you would write Ruby code to get this kind of result, but it’s a neat example of expression evaluation.

There are several other neat Ruby-isms in the video, I won’t repeat it all here.  One of the things that I mention in the video is that Ruby supports operator overloading — after a fashion.  In reality, operators are methods and you can redefine them to act appropriately for your particular object.

In this example you can see that using the plus sign (+) to concatenate two strings is really just syntactic sugar for a method call:

blog 3

I’m going to do another video to look at some other cool elements of the Ruby language.

Posted by Joe McGlynn on September 27th, 2007 under 3rdRail, Ruby and Rails | 1 Comment »


Rocking in Berlin

A few of us from the 3rdRail team were lucky enough to be able to attend RailsConf Europe in Berlin this week as part of the launch activities for 3rdRail.

I can’t even begin to convey the excitement here.  It’s infectious.  Conference attendees are passionate about Rails, they are hungry for information; and eager and willing to share what they know.  There was a keynote this afternoon by Roy T. Fielding on REST. It was a great talk by a guy who knows a thing or two about http. DHH talked about Rails 2.0 in his keynote this morning, which will have to be a subject unto itself.

Shelby, Mark and I are here to talk about 3rdRail, and there is a lot of interest.  That feels great, the team worked really hard to build an outstanding product and this is the fruits of their labor.

People are pretty knocked out when we show them our refactoring and code completion for Rails.  It’s a lot of fun to show the product to people and see their face light up.  The more I use it the more I appreciate what it does.

Go Team!

3rdRail Team in Berlin

Posted by Joe McGlynn on September 18th, 2007 under 3rdRail, Ruby and Rails | 1 Comment »


Charged Up about 3rdRail

This morning we sent out the press release announcing the commercial release of 3rdRail.  Man does it feel good to have shipped this product and be able to talk about it publicly.

We started less than 9 months ago after a few of us started experimenting with Rails  - and were totally knocked out with the productivity and simplicity.  If you’re building web applications you really need to know about Rails.  And if you’re building Rails apps you really need to be using 3rdRail — granted I’m less than impartial on this particular point.

I did a more in-depth video which shows off some of the core functionality in 3rdRail.  This goes into a little more detail than the sneak peek that I showed earlier.  We also set up an independent site for folks to congregate and talk about Ruby and RoR (and 3rdRail of course).  Go to http://www.GrabTheRail.com.

Trial downloads are available here: http://cc.codegear.com/trial/3rdrail, and you can buy the product through the shop site for an introductory price of $299.

We’re doing something completely new (for CodeGear) with the licensing on 3rdRail.  We are selling it as a subscription.  The initial purchase price includes a perpetual license and a one year update subscription.  We will be updating the product on a quarterly basis with new features and (of course) bug fixes.  Our focus for Q4 is, first and foremost, to respond to input from customers.  We have a few cool new features planned too.  Watch for the official 3rdRail roadmap.

The subscription pricing keeps the purchase cost down and lets us update it with features more often.  Personally, I’m really jazzed to be able to do this.  In the past our model was to have a major release once a year with only critical bug fixes between releases.  With 3rdRail we will be making the product better every 3 months based on your feedback.

Grab The Rail

3rdRail Screenshot

Posted by Joe McGlynn on September 17th, 2007 under 3rdRail, Ruby and Rails | 3 Comments »


Gone Dark

I’ve had quite a few emails asking "what is up with the Ruby Thing"?

I have to admit that I’ve been pretty quiet about it, and I can’t really say much yet, but…I don’t suppose a sneak peak could hurt:

Sneak Peak

Posted by Joe McGlynn on September 12th, 2007 under Ruby and Rails | 1 Comment »


RailsConf Totally Rocked

Last week several of us from CodeGear were at RailsConf in Portland, CodeGear was a Gold Sponsor for the conference. It was a great event from several perspectives.

First off, the conference was very high energy and very fun. Between sessions I saw groups of developers spontaneously coming together to code and problem solve. Matz, the inventor of Ruby, claims that having more fun coding is one of the philosophies behind Ruby, and that is carried over into Rails.

People that came by the booth were very positive about what we’re doing with "the Ruby product". As a side note, we had a very cool code name for the project, but the lawyers made us pull it before we went public. I guess they know the Carl Sagen code name story:

Apple got into a legal battle in 1993 with the late astronomer Carl Sagan, when Mr. Sagan objected (via his lawyers) to a project within Apple with the code name Carl Sagan (apparently chosen under the belief that it would earn Apple "billions and billions" of dollars). The project was renamed BHA (short for "Butt-head Astronomer"). Sagan sued Apple for libel, claiming that the pejorative "Butt-head" was defamatory, and lost.

We won’t be calling this "Ruby IDE from CodeGear" (or BHA for that matter) when we launch it.

An interesting thing that we saw repeated over and over at presentations at RailsConf was the lack of a solid IDE for Rails (and Ruby). We saw several presenters make mistakes that just wouldn’t have happened if they were using an IDE. Leaving out a keyword, closing curly brace or "end", or having a typo in a method name. None of these are hard to identify and fix, but they are annoying and totally avoidable. The IDE can prevent or at least visually identify the problems for you as you’re working. We’ve had this in JBuilder for 10 years, red squiggles underlining a typo, an error icon in the margin in the text editor, code completion to save a few keystrokes and avoid a few typos. All this stuff puts a damper of fun and productivity, the IDE can make your code clearer at a micro level and can help manage and visualize complex projects at a macro level.

One other thing that was pretty cool to see was a new feature springing to life. Two of the developers on our team, Shelby and Mark, were at the conference. Between sessions, over lunch (during a few sessions) and late into the nights they were pair programming a pretty cool new capability that will show up in this weeks field test build. These guys are really talented engineers and it was awesome to see them work through some really gnarley problems ranging from event handling to dealing with parse trees. Nice job guys!

I’m going to start building a Rails application in my next blog post to try and illustrate some of the power of Rails development. In particular I want to exercise several capabilities in Rails I haven’t spent a lot of time with: RJS Templates, RESTful services and higher level testing.

Here is a shot of a bunch of us at the booth, including Jim Douglas our CEO.

Posted by Joe McGlynn on May 24th, 2007 under Ruby and Rails | 5 Comments »


Rails Magic and Code Completion

As you may have seen in our press release, CodeGear has announced that we’re working on a new IDE product for Ruby and Ruby on Rails. Anyone who has read my past blog posts probably wasn’t all that surprised by the announcement.

As a side note, "Ruby on Rails" is something of an unfortunate name, as it’s really "Rails on Ruby", but the point is that our product fully supports both straight-ahead Ruby coding, and Web 2.0 development using Ruby on Rails.

I can’t say much about the product, other than it’s in beta testing right now and is progressing really nicely. Code completion is a key feature for any IDE, and for something like Rails which has a lot of magic going on it is crucial. It’s somewhat trivial to do basic code completion — calling the "methods" method on any class or instance will give you the basics. That turns out to me of pretty limited use, and typically results in information overload. Limited use because the results don’t include methods added dynamically, either as new method definitions added at runtime, or methods added via the method_missing hook. Information overload because the shear number of methods returned is too many to read through unless you know what your looking for — and if you knew what you wanted you probably wouldn’t have pressed ctrl-space in the first place.

Good code completion, especially for Rails, is a bit tougher. The code completion algorythms need to understand the context that the method is being called in, they need to understand how the language and framework interoperate, and then use that information to give the user an intelligently-sorted list of choices. With staticly-typed languages like Java it is much more straightfoward. With Dynamically typed languages like Ruby it requires some magic. Dynamic typing, or duck typing, means that if the instance responds to a particular method call ("quacks like a duck") then you can treat it like a duck.

I came across a great example of this last night when I was building (another) simple Rails application. I want the application to manage some data, but I need to have a audit log of changes to the data so I can see what it was like at any point in time. There are a number of common patterns that people use to model this in their database, but Rails makes it dead-simple.

Using the acts_as_versioned Rails plugin you can add row versioning to a model easily. Here are the steps:

  1. Let’s assume we want a model/database table that stores a project name and a release date. We want to keep track of any changes to the release date — obviously this is a contrived example, projects never change release dates. We can create the model and migration easily froom the command line as follows:
    C:\project>ruby script/generate model Project projectname:string, releasedate:date
    exists app/models/
    exists test/unit/
    exists test/fixtures/
    create app/models/project.rb
    create test/unit/project_test.rb
    create test/fixtures/projects.yml
    exists db/migrate
    create db/migrate/003_create_projects.rb
  2. OK, no biggie so far. One of the typical patterns to implement versioning is to add a new table to store the old versions with a foreign key to the primary table. Then add code all over your application so that when you edit a row you first save off the original row into the "version history" table. Again, not rocket science, but extra work. If you wanted every model in your application to be versioned (or wanted to add versioning to an existing application) this would quickly turn into a load of work.
    Enter acts_as_versioned. From the command line add the acts_as versioned plugin to your application:
    C:\project>ruby script/plugin install acts_as_versioned
    + ./acts_as_versioned/CHANGELOG
    + ./acts_as_versioned/MIT-LICENSE
    + ./acts_as_versioned/README
    + ./acts_as_versioned/RUNNING_UNIT_TESTS
    + ./acts_as_versioned/Rakefile
    + ./acts_as_versioned/init.rb
    [snip - output ommited]
  3. Next edit the migration we created in step 1. This was all created by the Rails generator. Let’s implement versioning… Add calls to create_versioned_table and drop_versioned_table to the "up" and "down" methods in the migration to create and drop the versioned table so that the migration now looks like this:
     1 class CreateProjects < ActiveRecord::Migration
     2   def self.up
     3     create_table :projects do |t|
     4       t.column :projectname, :string,
     5       t.column :releasedate, :date
     6     end
     7     Project.create_versioned_table # added!
     8   end
     9
    10   def self.down
    11     Project.drop_versioned_table  # added!
    12     drop_table :projects
    13   end
    14 end
  4. In the migration above, the "Project" object is our model class. How did it get those methods? Well in truth we have to add them, so let’s do that now:
    1 class Project < ActiveRecord::Base
    2   acts_as_versioned  # Added!
    3 end
    

    Not too bad so far…

  5. After running the migration with "rake db:migrate" we’re done.
    No, Really.

    If we pop into SQL and take a look we’ll see that we have our projects table, as well as a project_versions table. Note that the call to create_versioned_table added a version column to project, and completely created project_versions.

  6. But where it gets really cool is the methods that are added to our model. Let’s drop into the Rails console and play with our model:
    Create a new project record and save it:
    C:\project>ruby script/console Loading development environment. >> Project.find :all => [] >> p = Project.new => #nil, "projectname"=>nil, "releasedate"=>nil}, @new_re cord=true> >> p.projectname = "Ruby IDE from CodeGear" => "Ruby IDE from CodeGear" >> p.releasedate = "01/01/2008" => "01/01/2008" >> p.save => true

    Now change the record and save it again:

    > p.releasedate = "05/05/2005" => "05/05/2005" >> p.save => true >> p.version => 2

    This shows that our record is now at revision 2. If we look at p.versions.count we would see that there are two versions. If we wanted to revert to an older version we just call it out by the version number:

    >> p.releasedate.to_s => "2005-05-05" >> p.revert_to! 1 => true >> p.releasedate >> p.releasedate.to_s => "2008-01-01" >> p.version => 1 >> p.versions.count => 2

    Pretty cool eh?

This is a great example of both the power of Rails and the sort of thing that makes code completion tricky to do well. Rails does a lot of magic on our behalf, all with the intent of saving us from mundane coding. Understanding that magic and providing top notch code completion in our IDE goes one step further in saving us from mundane coding.

Posted by Joe McGlynn on May 22nd, 2007 under Ruby and Rails | 3 Comments »


Rails Scaffolding

One of the (many) handy things about Rails is scaffolding, this is a super quick way to get a quick-and-dirty UI to interact with your data models. I don’t think it is intended to be anything more that a starting point, and certainly never part of a "real" application. I’ve used it as a starting off point, and it allows you to replace it piecemeal, one action at a time.

One obvious limitation of scaffolding is that it doesn’t support relationships between models, it only lets you edit the individual table data, not the related data. Since it isn’t a production thing, that’s cool. There are some bolt-ons for Rails that do address the problems of dynamically creating prettier and more functional UIs.

AjaxScaffold is one I’d looked at briefly in the past, today I spent some time looking at ActiveScaffold (http://activescaffold.com/). This project just hit their RC1 status, my first impression is very positive.

For products we build here at CodeGear we have to develop icons, decorators, splash screens, installer billboards and other graphics. We collect everyone’s needs and then work with a graphics artist to get the images composed and reviewed. Using this as a basis for an application (and an opportunity to take ActiveScaffold for a spin), I decided to see what I could do to build a little app to manage this data.

I’ll give you the punch line first, I really didn’t write much code at all. 31 lines total, most of that is auto-generated stuff too. I decided to keep my schema simplistic. I have requests, which have information about the image request like size, what it will be used for, when it’s needed and so forth. It has relations to "lookup tables" for things like status, project name, requester name, etc. It also has a list of images that come back from the artist for each request. It’s not uncommon that the first image isn’t spot-on, the developer give feedback and the artist produces another image. So I have an items model to store the image, comments and feedback. All pretty simple.

So my application consists of 5 models, which just contain the has_many and belongs_to relationship maps. It has one controller which reads as follows:

class RequestsController < ApplicationController layout "default" active_scaffold end

Through the power of ActiveScaffold my app is up and running, and within a stones-throw of being finished

ActiveScaffold gives me all of the CRUD forms that I need for my little application. The screen shot is of the edit form for an existing record. It has the master-detail relationship from my request model to my item model, it has the selectors for my lookup tables for status, user, and project, and it even has the ability to add rows to my lookup tables on the fly.

It’s not perfect, but it is already very useful. There is an extension mechanism so that I can add the functionality to upload an image and store it in the DB — which is the next task for me to implement. Let me re-phrase that…the functionality to upload the image is the first real code I’ll need to write for this app (grin)


By the way, if you haven’t taken time to fill out our Ruby and Ruby on Rails survey we’d really like your input. The survey is here: http://www.surveymonkey.com/s.asp?u=187863298831

Technorati Profile

Add to Technorati Favorites

Posted by Joe McGlynn on March 14th, 2007 under Ruby and Rails | 4 Comments »


Ruby and Ruby on Rails at CodeRage

CodeRage: Ruby Rules!

Next Week, March 12-16, CodeGear will be hosting a "live virtual developer conference". This is totally free, no cost or obligation — and you don’t have to travel to attend.

There are four talks that should be of particular interest to Ruby and Rails developers, as well as sessions on Ajax, Java, Databases, Delphi, .Net and many other topics.

Pre-register at http://www.TheCodeRage.com

Of particular interest:

A First Look at Ruby, by Jeremy McAnally

Wednesday, March 14, 2007 — 2:00pm-3:15pm

Ruby’s popularity is growing day by day, but so are the questions surrounding it: What’s so great about it? Why use Ruby? How do I use Ruby? What can I use Ruby for? This session will attempt to answer some of those, by not only teaching attendees how to use the Ruby language, but also when and why.

Introduction to Ruby on Rails by Tim Breitkreutz

Thursday, March 15, 2007 — 6:15am-7:30am

An overview of the Ruby on Rails Web development framework, including the Ruby language, Rails model-view-controller structure, and the principles behind Rails. Find out why so many people find Rails development so fun and fast!

Maps on Rails New Session by Lori Olson

Friday, March 16, 2007 — 11:00am-12:15pm

This session will provide an overview of the Web-based mapping alternatives (Google Maps, Virtual Earth, Yahoo Maps). We will also demonstrate how to add such maps, using your own location- based data, to your Ruby on Rails application.

Advancing Ruby: Hacking Java Language Tools in Ruby by Bob Evans

Tuesday, March 13, 2007 — 2:00pm-3:15pm

This session will assume that the user has at least a minimal knowledge of Ruby and a medium Java knowledge, though the techniques will be apparent regardless. This session explores building custom Java bytecode analysis tools using Ruby and the Java Virtual Machine Specification and how Ruby makes it a joy. We’ll look at the various features of Ruby that make it good for language hacking from the looser syntax, to blocks and then to some meta-programming to reduce tedium. We’ll also see how easy it is to test your code in Ruby. After this session, developers should have a good sense of some of the unique strengths of Ruby and how some of it’s advanced features can be applied easily and practically.


By the way, if you haven’t taken time to fill out our Ruby and Ruby on Rails survey we’d really like your input. The survey is here: http://www.surveymonkey.com/s.asp?u=187863298831

Posted by Joe McGlynn on March 9th, 2007 under Open Source, Ruby and Rails | 5 Comments »


Frustrated with your development processes? Get M.A.D.

In the last JBuilder hour I talked about the evolution of the development process used by the JBuilder team. In the past we followed a fairly traditional waterfall model, and over the past two years we’ve been slowly moving to a more agile approach.

Our current processes is based on SCRUM. We actually started with textbook SCRUM while building JBuilder 2007, and modified it to better suit our needs. We call the current variation "Modified Agile Development", or "MAD". It’s very pragmatic, and is based on our experiences. In my opinion, the "right" processes varies based on several factors. Some of the key forces that drive processes adoption include the maturity/cohesiveness of the team, the type of development projects they are working on and their familiarity with the domain.

Of course, the TeamInsight feature in JBuilder 2007 is built specifically to enable teams to adopt agile processes easily.

The video is recorded for playback here, I’d love to hear your feedback on how your team works!

Posted by Joe McGlynn on February 27th, 2007 under Cool JBuilder Features, Open Source, Software Engineering and ALM | 3 Comments »


(Poignant) Ruby Snippet

If you’re learning Ruby and haven’t come across Why’s (Poignant) Guide to Ruby you really should take an evening and read through this. Besides being highly entertaining there are some excellent examples of nice, terse, expressive Ruby code. Not everyone will probably enjoy Why’s style as much as I do, but you owe it to yourself to take a look. If you’ve seen references to "Chunky Bacon" somewhere this is the origin:

The newest chapter "When You Wish Upon a Beard" has a crafty snippet to split an array into N-sized pieces.

But first, close your eyes and imagine how you’d code it in your favorite language. Probably head-first, walk the array stripping out elements and stuffing them elsewhere. Maybe with some bottom tested loop if you’re peeling the elements out of the original array. Not a hard task, but seeing the solution in Ruby is enlightening.

(OK, you can open your eyes now)

1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
16
17

# define "/"
class Array
  def / len
    a = []
    each_with_index do |x,i|
        a << [] if i % len == 0
        a.last << x
    end
    a
  end

end
        
[:now, :is, :the, :time, :for, :all, :good, :men, :to, :come, :to, :the, :aid] / 3


gives

=> [[:now, :is, :the], [:time, :for, :all], [:good, :men, :to], [:come, :to, :the], [:aid]]

OK, whatsitdo?

Since Ruby is "dynamic", we’re adding functionality to the Array class, defining the "/" operator, which will take a param called "len" - the length of the sub-arrays we want to make. Next we defining a blank array called "a". The "each_with_index" line may look a little strange. You would assume it was an instance method on Array, but looking at the rdoc there is no mention of it. Odd.

Ruby has a concept called "modules", which can be mixed-in to other classes. It is similar conceptually to multiple inheritance.

The call to "each_with_index" actually is defined in the Enumerable module, which is in turn mixed into Array. It takes a block as it’s param, and will actually call back into that block internally via "yield", passing each element and its index to the block (x and i, respectively).

The first line in the block a << [] if i % len == 0 adds a blank array to "a" if the element index modulo "len" is zero. The << operator is part of Array, and it means "append to".

The next line, a.last << x appends the current element (x) to the last element of "a", which is of course an array too. Later we return the computed value from our new function by just listing it on a line. Ruby will return the last expression evaluated in a method.

All in all, pretty crafty I’d say. Learning the Ruby syntax is not difficult, but learning to use it effectively will take a bit more focus — at least for me.

By the way, if you haven’t taken time to fill out our Ruby and Ruby on Rails survey we’d really like your input. The survey is here: http://www.surveymonkey.com/s.asp?u=187863298831

Posted by Joe McGlynn on February 15th, 2007 under Open Source, Ruby and Rails | 3 Comments »




Server Response from: blog2.codegear.com