Archive for the 'Programming' Category

Ruby: Hash#fetch and More

Wednesday, September 10th, 2008

Sometimes you rediscover little features that make your life whole lot easier. Today when reviewing the code of my co-worker I stumbled upon the use of the “fetch” on the Hash object. Check it:

h = { :existing_key => "value" }

h.fetch(:existing_key)  # returns "value"

h.fetch(:some_key)  # raises exception
h.fetch(:some_key, "default") # returns "default"
h.fetch(:some_key) { ...some math... }  # returns some math

One other related technique is:

h[:existing_key]   # returns "value"
h[:some_key]  # returns nil
h[:some_key] || "default"  # returns "default"

Armed and ready!

P.S. Thanks for a great tip, Craig!

Ubuntu and Passenger has Just Married

Sunday, June 1st, 2008

My gosh, I can’t believe I missed this. On May 21 Brightbox has announced a happy marriage of a revolutionary mod_rails (Passenger) project from Phusion to the excellent user-friendly Linux for the mere mortals — Ubuntu.

It means that the deployment and management of Rails applications becomes a breeze. I personally still prefer my very custom deployment setup — Nginx-Mongrel (for Rails) + Nginx-Apache (for PHP), but for those planning to unroll massive Rails hosting, it may be a famous Red Pill.

Love Rails!

Rails 2.1 is Out

Sunday, June 1st, 2008

3 hours ago Rails 2.1 was finally released into the wild, and there’s the officials report for your reading pleasure. I’m still a bit concerned about the RSpec compatibility, but since I already found a sufficient replacement — Shoulda and Mocha — there may not be as many worries.

So, let’s give it a round of aplause. Great job!

Little Luck With Rails 2.1 Yet

Tuesday, May 20th, 2008

Following the concise yet complete instructions on how to start using the Rails 2.1.0 release candidate from the awesome Getting Rails 2.1 RC1 podcast, I gave it a very quick spin today in one of my projects.

Right after the installation one of the gems refused to work. It was HAML — an excellent HTML builder extension — that blamed Rails for not having some hook registration function call. Taking the latest master copy from github of HAML (which is 1.9.0 there at the moment) solved the problem, but then something else jumped out. RSpec doesn’t work very well with Rails 2.1 at its present state, and every controller test was yelling at me.

Let’s say, it was a bad luck and hopefully I’ll do better next time when they finally release the thing. Got back to Rails 2.0.2 for now.

Firebug crashes Firefox3

Monday, May 12th, 2008

I’m a huge fan of Firebug — the top notch JavaScript / CSS debugging plug-in for Firefox — but recently it became completely unusable to me.

With the release of Ubuntu 8.04 the main browser now is Firefox 3 that comes as the default. Official Firebug doesn’t work with FF3, but there’s a development branch that does, well kind of. There are many sharp corners and rough edges in this latest development, but it was fantastic. Several days away from the installation I noticed my FF3 to begin crashing every now and then.

Today I finally had to remove the extension since the browser could crash 2-5 times a minute. I literally spent half a day trying to work on the site for my client. That’s unaffordable luxury.

For now I’ll be using the excellent Web Developer extension (ah, I miss that sexy JavaScript console of Firebug), but will be monitoring the Firebug development progress with a hope to get back to it soon.

Further thoughts on Git and Rails

Friday, April 18th, 2008

The idea of replacing (or augmenting) Subversion with Git in the development practice is quite fascinating. It’s a part of an agile development methodology to respond to client feedback and changes of mind quickly. Sometimes they ask for a small change that has to go before that monstrous feature you are already working for quite a while, and it hammers on the head. What on Earth do I need to do now? Roll everything back, apply a change, deploy and then paste my changes back and move on? That’s fine once, twice, but hey when it’s a habit… It’s a reality and this is how it is most of the time in development, in real life, everywhere.

Because of its ridiculously expensive and slow nature in a centralized version control environments, branching was always considered as a no-no for such “stupid” applications. You use branches for a Real Job only and, yes, never check in until it’s fully tested!

With the distributed version control things change dramatically. I still have very little experience with Git, but several resources I discovered today gave a lot of food for thought.

  • It’s no longer a taboo to fork a branch for an experimental feature, a quick test, a bug fix to be tested independently and merged later, for literally anything you may need to do with sources
  • It’s cheap to create, cheap to maintain and easy as it never was before to merge back
  • You check in, check in and check in like crazy to your private branch and no one cares until you push (or they pull) your changes to the trunk (master)
  • You can use both Subversion for the centralized code versioning and Git for your local development until the global migration of the project to Git is finally discussed and performed (it’s inevitable, calm down)
  • Finally, Capistrano works with Git as well as it does with Subversion / CVS and your Rails development is still in good hands

Here’s a couple of resources for your reading and watching pleasure. I found both intriguing and invaluable at the same time.

The last one could be two times shorter, but still is well-put and leaves a pleasant aftertaste.

Enjoy your weekend!

Rails, TinyMCE and JavaScript in IFrame

Thursday, April 17th, 2008

Browsers developed some really bizarre means of user data protection over the year of evolution. One of many is the JavaScript cross-domain protection. If you load a web-page into an IFRAME and access its DOM model or the model of the parent document from the loaded page, you get what you deserve — a permissions violation error that looks like “Permissions Exception” (in IE) and “uncaught exception: Permission denied to get property …” or similar in (FireFox). All is simple and clear once you know what to expect. It’s all logical. Today however I faced something different, really different and odd.

In the application I work on we need to upload images from the post editing page (right, much like a regular blog). As all sane people, we have an editor (Tiny MCE), an IFRAME to post files being uploaded through and some code to glue it all together. Previously we were using a different WYSIWYG editor, but recently replaced that with Tiny MCE for its Safari 3 support.

When the first “permissions” error showed up upon receiving the on-upload-completed GUI update code, the immediate reaction was “hey, there must be a port number somewhere, since I know we talk to the same domain, or otherwise it wouldn’t breathe at all”. A quick check showed that no, there was no explicit port number either in the main document URL or in the URL of the IFRAME part. Ouch.

Next few hours I spent reading the code of the editor, experimenting, scanning forums, playing with JS console in FireBug and no matter what I did the result remained the same. Finally, I decided to make a copy of the sources and remove HTML / JavaScript of the page piece by piece until a bare minimum of stuff stays, then analyze it under the looking glass. The bare minimum appeared to be two Rails javascript_include_tag lines (for Prototype and Tiny MCE) and one text field with the submit button. Not much, but fairly sufficient.

What I need to mention here is that we use an asset distribution plug-in for Rails (distributed_assets by Ezra Zygmuntovicz) to load static files from 4 different domains (which in fact are the same server with 4 different names). Every time you call image_tag, javascript_include_tag and any other helper returning the static asset tag code, the plug-in intercepts the call and uses the domain name of one of these servers to spread the load between them.

When there was nothing but few <script> tags and 2 lines of HTML, the answer became excitingly obvious. Here’s the short rule of thumb derived from this lesson:

When you use Tiny MCE and planning to access parent DOM from within an IFRAME somewhere on the same page, make sure that:

  • The code you load into IFRAME comes from the domain with the name that matches the domain name of the main document to the last letter
  • JavaScript of the Tiny MCE editor is loaded from exactly the same domain
  • Port numbers matter

The end of the story.

Thoughts on Git

Monday, April 14th, 2008

Many of you, my readers, do programming for a living. Those who started early used CVS before they switched to Subversion, and there are many who still use it thinking it’s the best this world can offer. We, as lazy beings, look for faster and easier ways to accomplish things. We use version control systems that fit our needs, and personally, I felt that I’m doing the right thing when migrated to Subversion several years ago. So far, working mostly solely on the code base of the projects, I find it sufficient and convincingly simple.

Lately the magical word “git” made its way into the vocabulary of the programmers community. It’s an SCM system that aids project development in a highly distributed environment and makes all branching and merging chores a breeze. It’s built by Linus Torvalds for the Kernel project and didn’t received any popularity before now for its geeky user interface. Now as the latest develops quickly, the project started to occupy more and more minds. I’m still on the fence, but here are some notes for your consideration.

What I liked to hear:

  • I have all repository locally at any given moment, which makes it easy to diff, commit continuously without waiting for the code to become stable (days and weeks on some complex tasks), work offline (e.g. in the forest or on the sea side — a dream, isn’t it?).
  • The first point also inspires having any number of branches (versions) of the code for testing new features, making refactoring etc
  • The same makes it easy to have any number of repositories for any number of environments separately (dev, stable, production) and to build a flexible workflow around the setup
  • The internal data structures are extremely optimized and take times less disk space than competitive systems
  • The emphasis of the system is on the content rather than on files. A good example is when you move two lines of code from one file to another, git can tell you the migration path of these two lines instead of the changes in two separate files. In other words, content matters more than individual local changes.

What I didn’t like:

  • IMO, multi-node distributed version control may not be worth for mid-sized teams. When there is a single author, it’s great to keep several branches / nodes to test things, work offline etc — it becomes a convenience and aids the development seriously. In large companies with multiple nodes it’s much easier to merge chunks of code and it along is a great plus since none of existing systems handle it easily. For the mid-sized teams, I can see the the maintenance costs defeat the benefits. I must be awfully ignorant, but it’s what my gut says.
  • Even though the content-over-files concept sounds great, I don’t feel really comfortable with it (yet). Probably I just need to go deeper into these waters to judge, but that’s how I feel right now.

Hopefully it gave you some food for thought. See if you find it useful and let’s discuss. Here’s a good place to start looking for more info — Git and Ruby: Git tutorials, articles and links for Rubyists.

Productivity Tip

Wednesday, March 19th, 2008

Today, as I was playing with ideas after a big chunk of work, one interesting thought came, and it’s worth sharing. Everybody likes when the job is simple, straightforward and easy to do. Sometimes though times come when an assignment is … well, different.

I like to shoot these tasks first and, speaking in the context of PROgramming, like to make everything possible to never get back. If it implies writing a hundred of tests, that’s fine, just never again… you hear me? It’s not that I hate what I do, it’s that I, as a living being, hate stress.

Usually, I took the rest of the day off right after dealing with a complex or mundane to refresh the mind. It worked well, but took a lot of time and had a bitter taste of excuse to skip working hours. Today I invented something different for myself.

Here the summary of points that I (and hope you) usually keep in mind when working:

  • Focus on the task
  • Stop watching the clock
  • Keep a clear plan of attack with very small sub-tasks to cross them out as quickly as possible
  • Do whatever it takes to protect yourself from getting back (comprehensive tests suite, clear design etc)
  • Make a lot of comments to give you a hand if you still need to change something later

And now something new:

  • When the task is over, check in the sources, run all tests, and finish anything else that attaches you to the task, and then
  • Take a coffee break and detach yourself from it and the results as if somebody else did the job and you are left with an easy part (calling the module, using freshly designed database etc)
  • Start (not continue) working refreshed and, possibly, give you some easy and fun tasks to get the happy feeling of great job you always did

These are all simple steps, but I know no one who would follow them. I read many standard advices, like 50 minutes of work / 10 minutes of rest that are far from a silver bullet. They sound like a quick and dirty rule for those (or by those) who don’t really want to think WHY these breaks are important and, what’s more important, what to do during them.

With this last summary I feel I got closer to a better understanding of my own brain and how it works. Now I know how to reset that anxiety and stress to continue moving on without passively waiting for the same effect first.

Hope I induced some fresh ideas and insights. Feel free to share back.

Cheers!

JSP and Servlets Feel Bad on Return

Friday, February 22nd, 2008

For the last two weeks I’ve been writing a database editor application with JSP / Servlets. I’m a returning JSP / Servlet programmer with a 7+ year background, but with a 1 year Rails pause. Now that I finished the task, I can share my feelings. Sorry, Java world. It’s not your day.

My work started with reading through 400 pages of the Headstart with JSP / Servlets book just to refresh memories and get enough confidence to begin coding away. This fact speaks for itself. Even with the help of a top notch IDE it took 3 hours to configure the environment for a new project, install all necessary libraries, set paths etc, and I even didn’t try all these Struts, Springs, Hibernates and other complicated stuff. I knew it will be a pain and the whole perspective wetting my feet sounded scary and promised days of learning, lots of pitfalls, foruming, Googling and god knows what else. Hard things made simpler, and simple things made impossible, as someone said once about modern Java. Now throw a stone at me if I’m wrong.

To me, as a freelancing programmer, a waste of time (which is with capital ‘W’) equals to misery in slums. I never charge for my own preparations, learning and anything else that is not directly connected with a client or a project. With J2EE the preparations phase is much longer than expected. Then the developing phase comes, bug fixing (which shouldn’t be there in the first place, but with endless XML descriptors you never know when trouble calls your name), and all this time my clients are waiting. It’s nowhere near the Agile methodology if you ask me. It’s much more suited for RUP or aging enterprise level waterfall design. So, even if I don’t charge, every project has a deadline, and to be in time I have to deliberately stretch my estimates to incorporate the unexpected.

You may argue that I just need to learn it once and forever, apply some polish wax over time and revise every now and then. Not really, my answer would be. When freelancing, you need many tools in your kit and often you don’t get back to a technology until your next assignment. Returning to JSP and Servlets always gives me a shake in the knees.

The bottom line is I’m seriously considering to “forget” about it (after 7+ years of Java experience, to remind). It isn’t worth the time to me, it brings little satisfaction even though my clients are happy as a rule. To make it worse, it takes longer to get it right, multiple wheels are reinvented every time, testing is a headache when it comes to DB fixtures, page layouts aren’t present and an includes mess is everywhere, routing and filtering feels like a patch, not a native feature. Well, you got the idea…

For all of you who know me and value my advice, it’s time to move on. Pick the right book, pick the right coach, exercise your brain, evolve and thrive. Don’t be lazy or you risk to miss the right turn. The world is spinning even when you stand for years.

Personally, I found a very nice replacement — Rails — but don’t take it as an advert. I mentioned it only twice in this writing as it’s not the point. The point is the world is changing and there’s no reason to become dinosaurs that young!

Oh yes, and value your time. Cheers!