Tuesday, 25 September 2007

MySQL Temporary Tables and Rails

Note: The RichText blog has moved to www.ricroberts.com

According to the Rails documentation, all active record classes by default use the same database connection.

As the Agile Web Development With Rails book rightly says, Ruby on rails is not thread safe (2nd Edtn p 649). A Mongrel server uses one thread per request (i.e. multithreaded), but is synchronised around the calls to Dispatcher.dispatch. This means that everything is threaded right before and right after Rails runs. While Rails is running there is only one controller in operation at a time. This is why people typically have to run a small set of Mongrel processes (a “Pack of Mongrels”) to get good concurrency (from Mongrel FAQs).

MySQL temporary tables are only visible inside the connection from which they are created, and they are automatically dropped when the connection is dropped (see the MySQL docs). Along with the above, this means that any rails active record class will be able to see temporary tables created by other active record classes (within the same server process).

However, since only one controller operation is running at a time within each server process (and therefore only one for each connection), I think you can safely do the following in a rails active record model class if you want to use temporary tables:

begin
connection.execute("DROP TEMPORARY TABLE IF EXISTS my_temp_table")
connection.execute("CREATE TEMPORARY TABLE my_temp_table")
# do stuff with temp table here
ensure
# this drop is here to help keep the size of the data base down
# between calls to this method
connection.execute("DROP TEMPORARY TABLE IF EXISTS my_temp_table")
end



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Monday, 10 September 2007

NetBeans Intervenes

Note: The RichText blog has moved to www.ricroberts.com

Regular readers of this blog will know that I'm not averse to trying new IDEs for my rails development.

I recently came across this post by George Cook about an app I hadn't considered.... NetBeans.

George does a great job of explaining NetBeans's virtues, so I won't repeat them all here, but to sum up, it does everything I need a rails IDE to do plus a little bit extra. The most impressive feature for me is the in-IDE fast debugging (more on how to set this up below).

NetBeans does have it's down points. With its default settings it doesn't look as slick as TextMate, but after some fiddling around with the preferences you can rectify this. It does use more memory than TextMate but even on my MacBook with 1GB RAM and lots of other applications open, I still have a little bit free. Besides, compared with something like Microsoft Visual Studio 2005 (which eats RAM for breakfast) NetBeans is a veritable size zero.

There is a ruby-only build of NetBeans available which helps to keep the memory footprint down. The exact version I installed was build 3533, which seems to work fine.

UPDATE (26 Sep 07): Netbeans 6 Beta 1 is now out! Get it from the Sun web-site.

Getting started with NetBeans

Here are few quick pointers to get you going.

To begin, all you have to do is do:
-> File -> New Project
.. and then choose "Ruby on Rails Application with Existing Sources"
and browse for your rails folder.

You need the ruby-debug-ide gem installed (sudo gem install ruby-
debug-ide) to do fast debugging.

Before trying to debug, you need to go to:
-> Preferences -> Ruby -> Platform
... then choose the location of your ruby interpreter (e.g. /usr/local/bin/ruby)
You should then be able to select the Fast Debugger radio button for the
Debugger engine. (If you can't, try restarting NetBeans - this worked for me).



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Wednesday, 5 September 2007

RedBox Rules!

Note: The RichText blog has moved to www.ricroberts.com

As you might have noticed from previous posts in this blog, I'm somewhat interested in modal dialogs in Ruby On Rails.

Up until now, I've been happily using the Prototype Window Class. However, it's quite a lot of js (a lot of which I don't use), and I've recently found a few small bugs in it. I'm not denying it's an impressive piece of work - it's just that there were a few niggles (Check out the forums).

Anyway, I've been investigating a few other options (namely: SubModal, ThickBox, LivePipe's Control.Modal, LightBox Gone Wild, StickyWin) and then I eventually found RedBox.

Most of the options I considered are variations on the LightBox theme, but RedBox stood out for me because of it's simplicity and ease of use with RoR. It doesn't do anything particularly fancy, but it ticked all my boxes (i.e. easily customisable, works well with Rails, small size of javascript, no obvious bugs).

It really couldn't be simpler to use RedBox with Rails.

To install the RedBox plugin, in Terminal just run:

script/plugin install svn://rubyforge.org/var/svn/ambroseplugins/redbox


...from your Rails project folder. This will stick stuff in your vendor folder. Then, from the vendor/plugins/redbox folder, you can run:

rake update_scripts


...to copy the files to the relevant places in your project. (i.e. the public/javascripts, stylesheets folders etc.).

Now all that's left is to stick the javascript and stylesheet links into your layout:

<%= stylesheet_link_tag 'redbox' %>
<%# we need to include prototype, etc... %>
<%= javascript_include_tag :defaults %>
<%= javascript_include_tag 'redbox' %>


To create a link to a RedBox, you can use the helpers that the author provides, the most useful of which I found to be the 'link_to_remote_redbox' helper. This allows you to launch a RedBox with some content from another page. For example:

<%= link_to_remote_redbox("redbox",
:url => {:controller=>'my_controller', :action=>'my_action',
:id=>'my_id'}) %>


Then, in the resulting RedBox dialog, you need some way of closing the it. To just close is very simple...

<%= link_to_close_redbox "Cancel" %>


It's also pretty easy to get it to do stuff after closing. For example, you could call a rails action, via an ajax call...

<%= link_to_close_redbox "OK", {:onclick => remote_function(
:url => {:controller=>'my_controller', :action=>'my_action',
:id=>'my_id'},
:complete => "$('spinner').hide();",
:before => "$('spinner').show();")
} %>


If you want, the rails action could do some rjs to update some of the main page.
(Of course, you could use a similar technique to submit a form on the dialog too).

One of my additional requirements was to be able to guide the users through a two-step process, within the constrains of the modal dialog (something I found fiddly with other modal dialog solutions). Here's how I did this with RedBox...

<%# to link to another page inside RedBox %>
<%= link_to_remote( 'hello',
:url => url_for(
:controller => "my_controller",
:action => "my_action",
:id => "my_id"),
:update => 'modal_content', # the div used by default for the dialog
:complete => 'RedBox.setWindowPosition();'#make sure it's centered
) %>


Notice how I call the RedBox's setWindowPosition() function once the update is complete. This is because the new page being shown might be a different size to the first one, and although the dialog automatically resizes to fit the content (which is nice), it doesn't automatically recenter itself. (Without this step, the dialog's top-left corner just stays in the same position).



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Tuesday, 4 September 2007

A new look

Note: The RichText blog has moved to www.ricroberts.com

I've decided to give my blog a new look, as I've been neglecting it recently.

I've got a few tasty computing morsels up my sleeve, so watch this space! ;)



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Tuesday, 10 July 2007

More on modal dialogs in rails

Note: The RichText blog has moved to www.ricroberts.com

Almost a year ago (blimey!), I posted about modal dialogs. For various reasons, the part of the application about which I wrote ended up being done a bit differently to how I described. I've recently had a lot more time to work on rails and the other day, I came across a different reason to use modal windows.

The Xilinus Prototype Window Library is now at version 1.3, and has some nice additions since I last used it. There is also a link to a rails helper for launching windows and dialogs, which although doesn't fully support all of the options, is a good point to build from.

Now, to finally answer Michael Kovacs's question from that original post, I found it handy to make use of the callbacks (onOK & onCancel for dialogs and closeCallback for windows) when dealing with ajax.

For example, suppose you want the user to impart some information in one of your modal dialogs. And then you would like to save this information and cause an update to a portion of the page from which you launched the dialog, as a result of what the user did...

One solution is, in the callback function, to interrogate the contents of the dialog for what the user entered (using prototype, say) and then call a remote_function to save the info to a database. This remote_function could then use rjs to update the original page.

The erb in your view to launch the dialog might look a bit like this...

<%=
url = (url_for :controller => 'my_controller', :action => 'dialog_action')
link_to_prototype_dialog(
"link text here",
{
#content
:url=>url,
:options=>{:method=>'get'}
},
'confirm', #dialog-kind
{
# dialog options
:className=>"alphacube",
:width=>680,
:height=>220,
:onOk="function(win)
{
val1 = $F('val1');
val2 = $F('val2');" +
remote_function(
:url => {:controller=>'my_controller', :action=>'do_something'},
:with => "'val1=' + val1 + '&val2=' + val2",
:complete => "$('spinner').hide();",
:before => "$('spinner').show();") +
";
return true; // remember to return true to allow the dialog to close
}"
}
%>



Note that in order to get this to work properly I had to tweak the rails helper to slightly to correctly format the generated javascript, but you get the general idea.

UPDATE: you might also want to try RedBox modal dialogs.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Wednesday, 6 June 2007

diagrams for your rails apps

Note: The RichText blog has moved to www.ricroberts.com

RailRoad lets you generate diagrams of your rails app.

Documentation often gets left to get out of date. With a tool such as this, you can just keep changing the code, automatically generating diagrams along the way.

The link above tells you how to set up a rake task to do just this, meaning that you'll never have to look at a redundant diagram again (or manually update one either)!



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Monday, 7 May 2007

Aptana with fast debugging

Note: The RichText blog has moved to www.ricroberts.com

I blogged a while back that Radrails was taken over by Aptana. Recently, someone entered a comment on this old post saying that Aptana now supports fast debugging. So I thought I'd give it a whirl.

To get it to work, you need to install the "ruby-debug" gem, the "ruby-debug-ide" gem, and follow these instructions.

This is a very useful feature, although having used TextMate for a while I prefer its clean look over Aptana's rather cluttered feel.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Sunday, 25 March 2007

Skype vs iChat

Note: The RichText blog has moved to www.ricroberts.com

Until recently, I'd been using Skype quite a lot for my VOIP phone calls.

However, unless both people in the conversation used headphones or some kind of headset, then I could hear a slightly delayed echo of my own voice. Although this didn't actually stop anything working it was very disconcerting. Also, if either party had the volume turned up beyond a whisper, then I got quite an annoying feedback whistle.

So, I decided to try the iChat application that came with my mac, with another of my mac-owner buddies. To use iChat, you need a .mac or aim name. (I found out by reading the .mac faq that if you sign up for the free .mac trial, then you can still use your .mac name for iChat after the trial expires.)

iChat suffers from neither of the problems that plague Skype. Even when using quite a high volume we experienced no feedback or echo, and both members of the conversation were just using the MacBook's built in iSight webcam, integrated mic and laptop speakers (i.e. with no headsets)



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Friday, 16 March 2007

Visibility in ruby

Note: The RichText blog has moved to www.ricroberts.com

Back in January, I made this post about ruby instance variables in derived classes.

I recently came across this post by Jamis Buck (one of the core Rails guys) with some more info about method visibility in ruby. Basically, he explains that private and protected methods are visible by all derived classes.

This seems a bit free and easy, coming from a C-sharp view point. In rails, this means, for example, that the controllers can't call the models' private methods and vice-versa. But all controllers can access all of the application controller's methods, so it's hard to hide it's inner workings from the other controllers if you want to.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Saturday, 10 March 2007

Radrails and Aptana

Note: The RichText blog has moved to www.ricroberts.com

Earlier this month, I wrote about the demise of Radrails.

Well, Aptana have stepped in to save the day. It's not clear exactly what will become of Radrails in its current form, but anything's got to be better than all of that great work just petering out into obscurity.

Here's what the Radrails site had to say about it all.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Thursday, 8 March 2007

NAS drive for Mac and PC

Note: The RichText blog has moved to www.ricroberts.com

Not so long ago, I went on the lookout for a Network Attached Storage (NAS) drive that I could use with my Mac and my PC.

This proved a little bit more awkward than I expected because many NAS drives only supported Macs by allowing you to format the disk in FAT32. This is all very well until you want to put files larger than 4GB on there, such as disk images.

I eventually settled on the LaCie Ethernet Disk Mini. This product uses the XFS file system, which has a maximum file size of 8 exabytes (should be enough!). It supports connections from Windows, Apple, HTTP and FTP. It lets you define shares and users, and even allows you to connect another USB disk for backups or extra storage.

Works a treat with both my PC and my Mac. Definitely recommended.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Sunday, 4 March 2007

TextMate for rails

Note: The RichText blog has moved to www.ricroberts.com

With the seemingly indefinite postponement of Radrails 0.8, I decided to go on the hunt for another Ruby on Rails IDE.

After scouring the web, I found that many people seem to favour TextMate, and according to this page the core Rails team use it for development, so I thought I'd give it a whirl.

I must say I am impressed. It features Subversion integration, and some built in support for developing Ruby on Rails applications. The only thing it doesn't have is a step-through ruby debugger, but there is a TextMate ruby-debug bundle which allows you to set breakpoints from within TextMate. (My previous blog post explains more about ruby-debug.)

Note that in order to get the Subversion integration to work, you need a Subversion client installed. There are now new instructions on Hivelogic.com for setting up rails on OS X which now feature how to install one.

TextMate is not free, but it is cheap at only 39 Euros.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Fast Ruby debugging

Note: The RichText blog has moved to www.ricroberts.com

Last September I described how to use Radrails for debugging rails apps. I mentioned in that post that it was slow and unresponsive, but bearable.

Today I discovered another way of debugging Ruby On Rails apps, but this time in a much speedier fashion.

Ruby-debug allows you to quickly debug your ruby on rails code. The debugger itself is not integrated into an IDE, but the command line interface is intuitive and adequate.

There is an excellent tutorial on the DataNoise website for how to use ruby-debug. Using this, I was able to get debugging literally within a few minutes.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Thursday, 1 March 2007

Visual studio rotting your mind?

Note: The RichText blog has moved to www.ricroberts.com

This is an interesting article by Charles Petzold that I came across recently discussing how good for you (or not) some of Visual Studio's features are.

I found the parts about intellisense and the graphical-designer particularly interesting.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Where are Kyle and Matt?

Note: The RichText blog has moved to www.ricroberts.com

The development of Radrails seems to have slowed to a crawl recently, which is a shame as I was eagerly awaiting features promised for version 0.8!

According to posts on the radrails community pages, it looks like the main members of the Radrails team are spending their time on other more profitable ventures.

All the same, for me Radrails is still the best value rails IDE. Some other IDEs have similar features but you have to pay for the privilege.

Where did the Radrails team go
Has Radrails disappeared off the face of the earth



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Monday, 29 January 2007

Pointers demystified

Note: The RichText blog has moved to www.ricroberts.com

Over the last few months, my day-job has required that I do a bit of C++ development. Previous to this, the last time I did commercial C++ was in one of my first developer roles back in 2002, so I've recently been rediscovering it's joys.

The thought of C++ often scares people, but that needn't be the case. I was lucky enough to come to C# after learning C++, but the transition the other way shouldn't be that difficult either. In fact, I would definitely recommend that C-sharpers get to know C++, if they don't already, as it provides a greater understanding of C#'s inner workings..

Much of the syntax is similar, and one of few big differences is memory management (in the form of pointers). This post hopes to demystify pointers and thus hopefully remove one of the final barriers from people having a go at C++.

What the heck is a pointer anyway?

A pointer is just a variable that holds a memory address. (i.e. the location of a value in memory). They perform a similar function to reference-types in C#, which have a value on the stack which is just an address of somewhere on the heap.

Making a pointer

To make a pointer, you just declare variable of a certain type, but precede the name with an asterisk:

int *pMyPointer = NULL;
(I just said that a pointer is a variable that holds a memory address, so you might be thinking: "Why do you need to give it a specific type?". Well, the type you specify is the type of the variable that will be stored at the memory address to which the pointer "points". This lets the compiler know how much space to reserve at that memory location e.g. 4 bytes for a 32 bit integer etc.)

Anyway, in the example above, I created a pointer which will point to an integer, and I gave it the value NULL. i.e. it points to nothing yet. (Note that NULL in C++ just means 0).

The opposite of a pointer

The opposite of a pointer, I suppose, is the address-of operator (&). This lets you get the memory address of a variable.
int myCount = 132;
pMyPointer = &myCount;
Here, the address of the myCount variable is stored in the pMyPointer pointer. So now, it points to our integer with value 132.

Assigning values at memory locations

You can assign to the location in memory to which you're pointer points by using the syntax:
*pMyPointer = 12;
Here I've asked to store the value 12 in the memory address of the pointer pMyPointer. i.e. where we've stored myCount. This is called indirection. (Notice that the asterisk means a different thing here, than when you declared your pointer. Here the asterisk means "the value held at...").

You can also use indirection to get stuff back out of addresses referenced by pointers. e.g. to get the value held at the address in pMyPointer:
int myNumber;
myNumber = *pMyPointer;
Since we've changed the value stored at the location to which pMyPointer points, myNumber will get assigned the value 12.

Heaping it up

In C++, when you use the 'new' keyword, it returns a memory address on the heap, and you need to assign it to a pointer. e.g. to assign enough space on the heap for an int, and put the memory address in a pointer called pYourPointer:
int *pYourPointer = new int;
Then you can assign a value like before.
*pYourPointer = 500;

My memory is leaking!

Now, when you're working with things on the heap, they don't go out of scope when your method ends, unlike variables on the stack. As pointers are variables like any other, if ones go out of scope you lose the only thing that told your program where to look in memory for your precious object. That memory is now unavailable until the program quits. Continuing with our example, adding the line:
delete pYourPointer;
deletes/frees up the memory that the pYourPointer pointer points to, so it can be used again. If we forgot to do that, and then pYourPointer went out of scope, we would have 'leaked' memory.

You can also leak memory if you reassign a pointer without calling delete first. e.g. if we didn't call delete on the 2nd line of this bit of code.
MyObject *pPointy = new MyObject(1,3);
delete pPointy;
pPointy = new MyObject(4,5);
The final line above sets pPointy to another memory address, and without deleting the contents at the original location, it would be lost forever! (or at least until the program ends). You might think: "My computer's got loads of memory, and the program will end soon enough!"... but what if it was a Windows Service that ran indefinitely? If there were lots of loops leaking memory then it might not be long until you ran out.

After you call delete on an object, for safety's sake you should always null-out the pointer to avoid leaving a pointer dangling, and accidentally using the deleted pointer again (which would cause your app to crash). Note that it's always safe to call delete on a null pointer.

pPointy = NULL;

Destructors

The example above illustrates another point (no pun intended). Calling delete on an object calls its destructor. If your class MyObject had member variables which themselves were stored on the heap, then you would delete them in the destructor. C++ destructor has the same syntax as a C# destructor i.e.
~MyObject()
{
// do cleaning up here!
}
but C++ destructors are called manually, rather than by the Garbage Collector as in C#.

Geting at your members

One of the weirdest things for me, coming back to C++ after years programming mainly C# was getting used the way you access members on objects on the heap again. Say you've got a pointer for a Person object, and the Person class had a GetNumberOfToes() method, you'd use the points-to operator (->) to call it. (Note that the familiar dot operator is used for objects on the stack). e.g.
Person *pMyPerson = new Person();
int toes = pMyPerson->GetNumberOfToes();
delete pMyPerson;
Note: You can actually call the method on the objected pointed to by pMyPerson like this:
(*pMyPerson).GetNumberOfToes();
i.e. call GetNumberOfToes() on the object held at the memory location pointed to by pMyPerson... but that just looks naff.

Another use for the Ampersand... References

Having read all that, you might start poking round some C++ projects that you've got access to, but were previously too scared to open. For completeness, I thought that I would continue to explain another use for the & operator, so you don't end up completely confused when you see it everywhere.

The & operator is also used for references. References are really just a way of giving an object another name. Anything done to the reference is done to the original. e.g.
int myInt;
int &refToMyInt = myInt;
Now assigning a value to either, will set the same value at a single memory location. e.g.
refToMyInt = 930; //actually sets myInt to 930


Passing by reference

This is a familiar concept to C# programmers, and is simple in C++ too. You just declare a function with the parameters that you want to pass by reference with preceding ampersands. e.g.
int DoSomething(int &intOne, int &intTwo)
{
intOne = intOne + intTwo;
return intOne;
}
and when you call it, just pass the values in 'as normal':
int anInt = 1, anotherInt = 2;
DoSomething(anInt, anotherInt);
The integers passed in can be changed by the body of the method, making anInt 3 and anotherInt 2.

Want more?

There's loads more I could talk about here (I'm getting a bit carried away!), but I'd be here all night if I carried on. If you want to know more, buy a book!



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Friday, 26 January 2007

Setting up rails on OS X (including radrails)

Note: The RichText blog has moved to www.ricroberts.com

Hello. This post documents how to get rails going on Mac OS X (I'm using 10.4.8, by the way).

Well, basically I followed these brilliant instructions on Hivelogic.com (except I used ruby 1.8.5 instead of 1.8.4) and it just worked! The only little quirk was getting the lightTPD web server to work properly. I had to tweak the paths on the first line of the dispatch.cgi, dispatch.fcgi and dispatch.rb files (in the public folder of my rails project) as they were pointing to a windows-style path.

Radrails pretty much just worked "out of the box" too, but to get radrails to start the lightTPD server properly, I set up a symbolic link like this...

ln -s /usr/local/sbin/lighttpd /usr/bin/lighttpd
...as radrails was having trouble finding it initially. (Credit for this last bit goes to Marc from the radrails community). Note that even after this link is setup, the radrails never reports the lightTPD server as 'started' - it just stays as 'starting...', but it does actually seem to start it properly. I also noticed that the lightTPD server starts on the last port you used for it, and it doesn't pay attention to the one that you specify in radrails.

Remember this post from September where I explained how to setup debugging in radrails on Windows XP? Setting up debugging for radrails in OS X is almost exactly the same, but in the interpreter arguments page of the debug dialog you'll want to put something like:

-I"/usr/local/lib/ruby/gems/1.8/gems/rails-1.2.1/bin"

Also, I had trouble getting debugging to work with lightTPD, so I've put the following in the program arguments to force it to use webrick instead.

webrick -p3001

That's it. enjoy!

UPDATES (March 07):
There are now updated instructions on Hivelogic.com.
You might also want to try Textmate and ruby-debug



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Thursday, 25 January 2007

when is private not private?

Note: The RichText blog has moved to www.ricroberts.com

If a method within a class is marked as 'private', one might expect that it is only accessible from inside of that instance. Well, you'd be wrong (at least you would in C# - and I assume the rest of Microsoft.NET too).

In C#, if you define a member as private, then it is indeed accessible only to that class. However, it isn't restricted to only that instance: Any instance of that type can access the private members of another instance of the same type. This is a bit counter intuitive to me, and freaked me out a bit when I first saw it, as it seems to break encapsulation! Try it if you don't believe me.

Ruby has a different approach, and one which goes some way towards placating my OO-purist tendencies. As you'd expect, public methods can be called by anyone. Protected methods can be invoked only by objects of the defining class and its subclasses (ANY instance of the defining class). Private methods can only be called in the current object's context. i.e. you can't invoke another object's private methods, no matter what it's type.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

ruby instance variables in derived classes

Note: The RichText blog has moved to www.ricroberts.com

I thought I would tell the world about something in the ruby language which surprised me a bit. Anyone who has used ruby for any length of time will no doubt already know this, but it took me off guard a little, coming from a C++, java and C# grounding in OO.

First a bit of background for the uninitiated... In ruby an instance variable is one preceded by an @ sign and, as with all variables in ruby, you can create one simply by assigning to it.

Anyway, in ruby, instance variables are automatically accessible to any derived classes. This is especially pertinent in rails, when dealing with the (base) ApplicationController. If you add a before_filter method to the ApplicationController, which assigns some instance variables, they are magically available in the derived controllers, without having to add accessor attributes to the base class.

Here is a very simple example...

class Parent
def parent_meth
@var = 'hello'
end
end

class Child < Parent
def child_meth
@var
end
end

>> child = Child.new
=> #
>> child.parent_meth
=> "hello"
>> child.child_meth
=> "hello"
As I said, I'm sure this is child's play for most rubyists, but I've read Dave Thomas's Ruby "Pick Axe" book, and don't remember seeing this explicitly said anywhere. In languages like C#, variables are private unless made otherwise (e.g. by use of an access modifier, or exposed by a property/method). It appears that in ruby, instance variables are by default protected. (Don't get me started on access modifiers - that's for another blog entry!).

I hope this post helps prevent some chin-scratching for other ruby newbies.

(If you're intersted in reading more about this topic, here's a discussion I started in the ruby forum).



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog

Friday, 5 January 2007

MacBook - Dead Pixel ...Day17

Note: The RichText blog has moved to www.ricroberts.com

In my last post I described how my new Apple MacBook arrived just before Christmas with a dead pixel in the screen. My replacement MacBook finally arrived last night, the screen is perfect and everything else seems to be fine with it too.

I've managed to get all my data/applications off the old one and onto the new one without much fuss. All I've got to do now is arrange for the defective one to be picked up by the courier.

Apple took their time with the replacement, but overall I'm pretty pleased with the way that this has been sorted out, considering some manufacturers would have just told me to live with the dead pixel.



Digg Technorati del.icio.us Stumbleupon Reddit Blinklist Furl Spurl Yahoo Simpy

Please also visit the Swirrl blog