NR Time - Powerful time tracker for Mac OS X

Feel the ease of time tracking with NR Time. Log your time expenses in the billing-friendly format with minimal effort.

Rails: Creating associated objects in AR

Posted: May 18th, 2010 | Filed under: Programming, Tips | Tags: , | No Comments »

Assuming that you have an object Account like below

class Account < ActiveRecord::Base
  has_one :office
end

and you want to create an Office record when you create an account, you could do it in the after_create filter and it would be my way of doing that also. But the funny thing is that if you name the filter create_office, you don’t need to define the method itself. It will create the Office and link it to your Account model automagically. So here’s how the final class definition looks like:

class Account < ActiveRecord::Base
  has_one :office
  after_create :create_office
end

Amazing!


Ruby: Simple scripts with CGI

Posted: August 1st, 2009 | Filed under: Programming | Tags: , | No Comments »

I’m a big fan of Ruby, and still every time I need some simple server-side functionality — you know those go there, take that sort of tasks — I have to revert to good old PHP. It’s obvious that building a full-blown Rails app is an overkill.

This morning I need another tiny little script to parse the HTML page and get some info back in JSON. And all this for a static web-site, so that it can’t be hosted locally. So what do I do? Getting back to roots…

Many web servers let you run CGI scripts, which is nothing else but an ordinary script that is executed by an interpreter of your choice and the results are thrown back as the response. Of course, it’s a bit more complicated that that, but the gist is accurate, and what’s more important is it’s hilariously easy to write.

If you happen to have a site with CGI enabled, you can try it right away. If not, well, check the hosting docs, or your web server configuration to see if there’s anything you can do. Most often, you will find the cgi-bin directory where all magic happens sitting next to public_html or www in your web site location root. Don’t forget that everything you put into cgi-bin has to be executable by the web server. It means that either you need to give it the correct ownership and the owner execution permissions or simply let everyone run it (which is dangerous sometimes, but good enough for a couple of tests).

So, here’s what you can try throwing into /cgi-bin/ruby.cgi:

#!/usr/bin/ruby

puts 'Content-type: text/plain'
puts
puts 'Test Complete'

Now when you run it by entering http://your_site/cgi-bin/ruby.cgi in the address line, you will get the nice and shiny “Test Complete” string.

Note that content type declaration and the empty line after it. Two things are important about these:

  • Both lines are mandatory
  • You can set any content type you like, not just output things in plain text. It can be JSON, XML, HTML or GIF, PNG, PDF — anything you can think of.

Now why don’t you throw a couple of gems into the mix and build something cool, fast and breathing!


TextMate: More on Ruby code execution

Posted: August 1st, 2009 | Filed under: Programming | Tags: , | 4 Comments »

In one of my previous posts I mentioned how nice it is to execute Ruby code and get the results in comments. This is quite useful when you build documentation or quickly test some ideas.

There’s one other method of doing this which is based on the Textmate’s ability to execute the code line at cursor or the selected piece of text. It’s as easy as it sounds.

  • First, enter the piece of Ruby code to execute, having in mind that the result of the last line will be output below:

    a = 2
    b = 3
    a * b

  • Now select all three lines and press ⌃⇧E (Execute line as Ruby). The result will appear on the next line

One neat trick is that you can use printf(…) function to format your output and, in this case, the result of the last line won’t be displayed, but the printed output will.

I find it useful when there’s something to try right inside the document or there’s some formula to solve. It lets me stay where I am and not to open a separate document just for the Ruby snippet.

As a little bonus, I just want to mention that you can run unix commands in the same fashion and get the output right in your document. For example:

  • Enter the following line and leave the cursor at the end of it:

    ps -aux | grep nginx

  • Press ⌃R (Text / Execute Line Inserting Result) to execute it. The result will be placed below.

The list of all nginx processes will be dumped. Sweet, ha.


TextMate: Execute Ruby code

Posted: July 28th, 2009 | Filed under: Programming | Tags: , , | 3 Comments »

In my day-to-day development I keep IRB handy just to sketch some statement or check how some method works with a given data set. It’s all quick and helpful, but working in TextMate, I always forget about it also has a tiny small feature that lets us do the same in much more comfortable fashion. The next time I need to check something, I will:

  • Open an empty text document
  • Set type to Ruby with ⌃⌥⇧R
  • Enter my ruby code just like this:

    a = [1, 2, 3]
    b = [2, 3]
    a + b # =>

    a - b # =>
  • Finally, run it with ⌃⌘⇧E and get this as the result:

    a = [1, 2, 3]
    b = [2, 3]
    a + b # => [1, 2, 3, 2, 3]

    a - b # => [1]

See? Handy.

By the way, I may have noticed that this format is frequently used in Ruby docs. Now you know how do they do it, right?


Weekend Ruby: Coding Quality with Style

Posted: October 18th, 2008 | Filed under: Weekend | Tags: , , , , | No Comments »

Photo by pdxnielson

It seems the community has started to work towards a common set of guidelines for a beautiful and readable Ruby code. Nice…

The idea behind any style guide is largely based on aesthetics and readability. The number of spaces to use for indentation, how to break statements into several lines, when the chain of statements is to be broken into several clauses — all is simple, yet no less important than the code itself.

These days we have many self-taught programmers who neither have a taste nor any special education. What’s worse, many of them don’t really care about clarity and maintainability of their code, preferring to quickly throw some pieces together to get their payments quickly without any proper design, testing, formatting and anything else. It’s a “poor job” and a “job poorly done”. I encourage everyone who purchase code to demand The Quality, and I equally encourage everyone who produces code to do their homework — study the best code samples, read guidelines, do their testing and follow (if not all, but as many as possible of) the best established practices. It’s the hard work that eventually becomes fun.

Here’s one of the attempts to summarize good coding practices into a guideline that I stumbled upon this week: The Elements of Ruby Style. It’s obviously incomplete, but it’s a good start that has all chances to evolve. There always will be people who disagree with certain points (including me, who would rather use “boolean ? 3 : 5″ instead of “if boolean then 3 else 5 end”, which is redundantly complex), but if you need to start from somewhere, it still is a great starting point.

In the same vein, here’s Rails Code Quality Checklist and the Code Quality Checker. These are mostly for the code design control, but since we talk about code quality today…

Enjoy your weekend studies!


Ruby: Hash#fetch and More

Posted: September 10th, 2008 | Filed under: Programming, Tips | Tags: , , , | No Comments »

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!


Rails: When an Uninitialized Constant Hits the Vent

Posted: January 29th, 2008 | Filed under: Programming | Tags: , , , , , | 7 Comments »

Last two weeks I was seeing the production server of one of my clients hit the same error over and over with no visible pattern. This second it works, the next it fails and leaves the Mongrel cluster in an undefined state somewhere between this world and hell.

The error I’m referring to is:

NameError (uninitialized constant MyModule::Utils::NetSession)
... backtrace follows ...

I need to repeat that it comes and goes under some non-obvious circumstances, and is hard to recreate. Fortunately, I found the solution and here’s what it was.

I have a directory hierarchy like below. I’m sure when you see it, it all becomes obvious and simple, but it wasn’t for me at that time as there were many files that I omitted below.

/lib
  /my_module
    klass1.rb
    ...
    utils.rb
  /utils
    net_session.rb

The piece of code in klass1 that failed looks as follows:

def new_session
  Utils::NetSession.new
end

Simple, heh.

Utils.rb is a helper module which is included into MyModule, but apparently loaded only when really necessary (it’s the only explanation why it didn’t fail all the time, as you will see). When it is loaded and included, the MyModule::Utils becomes defined, and Utils::NetSession resolution starts to fail. It happens as Rails begins looking for Utils name space from MyModule, finds MyModule::Utils and doesn’t find any NetSession there. That’s pretty much all to it.

The solutions are:

  • Either rename utils.rb (which I did in favor of utilities.rb), or
  • Use “::Utils::NetSession.new” (which is not safe as one day you can forget about the leading “::”, and get back to roots)

Hope this helps someone like me fighting the way through these extremely infrequent but painful Rails gotchas.


RSpec: Hierarchical Specifications

Posted: January 1st, 2008 | Filed under: Programming | Tags: , , | No Comments »

RSpec is full of great features, but some of them either not very well documented or hidden to a naked eye. No wonder if you never discovered hierarchical specifications.

Traditionally, we write specifications like this:

describe AClass, "when doing this" do
    ...
end

describe AClass, "when doing that" do
    ...
end

Now imagine that you have some very similar specs with some common initialization:

describe AClass do
    before do
        ...
    end

    describe "when doing this" do
        before do
            ...
        end
        ...
    end

    describe "when doing that" do
        before do
            ...
        end
        ...
    end
end

You can see that you have common initializations for examples from both specifications and specific initializations for examples from each.

In the previous post I wrote that I prefer not to define helper methods outside the specification definition as they become global and tend to intersect with methods defined in other specs. So, what is the solution?

Assuming that you have a method “authenticate” that you need to call before every example in several specifications, you can define an upper-level specification “authenticated” and group other specs, like this:

describe AClass, "(authenticated)" do
    before do
        authenticate
    end

    describe "when doing this" do ... end
    describe "when doing that" do ... end

    def authenticate
        ...
    end
end

Now you have it all in a safe way!


RSpec: Three Things You May Not Know

Posted: December 31st, 2007 | Filed under: Programming | Tags: , , | No Comments »

RSpec is fantastic. It’s so phenomenal that I can’t imagine my development without it anymore. It’s extremely easy to use, fun to write specifications and see how they turn green as you progress. But… at some point, when you have several hundreds of specs, using almost all documented features and excited to max, you may start facing serious problems. They aren’t easy to debug and may lead to a disappointment, unless you are prepared and armed with knowledge.

Load first, then execute. What I discovered was that RSpec loads all specifications upon startup and then executes them one-by-one. It means several things to us, the developers:

  • All constants you define in your specifications are global. You will get Ruby warnings on constant redefinitions, but it may not save you from unexpected glitches, when you expect one value, but get a completely different one.
  • All methods you define outside your specifications are global. It may affect your specifications in the same way as global constants — the functionality you expect from your helper methods may not be as expected. There are several solutions to this: 1) use modules with unique names to hold your helper methods and include them into your specifications, 2) use specifications hierarchy (my next post is about it) to group specifications that need helper methods.

Partials on Classes and Modules are BAD. It may sound bizarre, but they are. When you stub your Classes and Modules, you do it globally. Whatever you do in one specification or an example is visible in every following. Yes, right, NO ISOLATION. So, when you stub your model’s finders to return a mock, they do return this mock later in other specifications and examples that follow, even though you don’t expect it, and especially when you don’t expect it. It was a huge AHA moment for me.

RSpec loads (runs) specifications in recently-changed last order. It means that it runs specifications you changed last at the end. Now take a break and mull it over. Having everything above in mind, do you still think that you really have a green light? What if you ran you first specification (that you wrote first and never changed since then) after everything else? The only way to know is to try running every specification in your collection last, but of course, it’s not possible. The lack of complete isolation of one spec from another puts a big question mark after “is RSpec as useful as it seems”. My own answer is “yes”, but you need to know about all this to be on the safe side.

To summarize, here’s a quick NO-NO list of mine:

  • Never use Partials with Classes and Modules
  • Never define constants in or outside specifications
  • Never define methods outside specifications

I hope sincerely that this information helps you make your RSpec experience smooth as silk and you’ll avoid the road blocks I experienced during the last few weeks.

Happy Holidays!


Rails: Haml and Sass

Posted: October 30th, 2007 | Filed under: Programming | Tags: , , , , , | 3 Comments »

Haml logoHey fans of everything concise. My finding of today is Haml and Sass which is a quickly growing replacement for Rhtml (and plain HTML) and CSS. Just check the syntax sample on their main page and admit it, it’s much simpler and cleaner than plain (R)HTML. Everything has a meaning, everything cuts to chase.

Haml can be used with Ruby on Rails as a plug-in that transparently adds the support to your ActiveViews. You simply rename your views from .rhtml to .haml and start deleting redundant code. In case of CSS, you place your .sass in the stylesheets folder and they are automatically compiled on demand. One thing I haven’t figured out yet is whether they do every time, or once per change to save performance.

Haml and Sass are also used in the StaticMatic toolkit, which is exactly how I discovered them. The toolkit lets you put together static sites lighting fast. You simply write your pages in Haml, model your stylesheets in Sass, preview and do a final build. As the result of building you get a bunch of little cute HTML files and CSS stylesheets ready for upload to the site. If you, like me, still like static sites and want to save time on bringing them up and maintaining, it’s your choice.

Let me know what you think. A couple of lines is fine.