InquiryLabs

Politics, Programming and Possibilities

Ruby Gotcha: "or" Precedence

This one got me today:

feed_bridge_is_valid = !state[:feed] or (state[:feed] and @feed_bridge.valid?)

It turns out that the “=” assignment has a higher precedence than the “or” operator, so if (in the example above) !state[:feed] turns out to be false then feed_bridge_is_valid will be assigned a false value, and the entire expression will return the value of (state[:feed] and @feed_bridge.valid?).

Here’s one solution:

feed_bridge_is_valid = (!state[:feed] or (state[:feed] and @feed_bridge.valid?))

And I think you can also solve the problem by using the “||” version of the “or” operator too.

Textmate Footnotes Plugin 1.0

This plugin saves you time when moving between your browser and Textmate. It adds clickable links to the Rails backtrace when an error occurs, and clickable “footnotes” to the bottom of each page (in development mode only). When clicked, these links open the correct file in Textmate and move your cursor to the precise line of interest.

In your plugins directory, install with:

svn export \\
svn://syncid.textdriven.com/svn/opensource/textmate_footnotes/trunk \\
textmate_footnotes

This plugin was also featured in the syncPEOPLE on Rails bundle for Textmate.

Simple URI Validation

Here’s a way to validate a url if you really want to make sure it’s real (i.e. this goes above and beyond merely checking that a regexp says it’s ok–instead, it goes out and pings the server.)

Create a file, validates_uri_existence_of.rb in your app’s lib folder:

require 'open-uri'

class ActiveRecord::Base
  def self.validates_uri_existence_of(*attr_names)
    configuration = { :message => "is not a valid web address" }
    configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
    validates_each attr_names do |m, a, v|
      begin
        # Try to open the URI
        open v
      rescue
        # Report the error if it throws an exception
        m.errors.add(a, configuration[:message])
      end
    end
  end
end

Add ” require ‘validates_uri_existence_of’ ” to your environment.rb. Then in your model:

class Repository < ActiveRecord::Base
  validates_uri_existence_of :url
end

Highlight Background of Fields With Errors

Using the default rails field_error_proc may lead to some layout headaches–your form looks perfect until, uh-oh, someone entered an invalid email address and Rails adds a fieldWithError-styled div that wraps around the problem field.

While this works in many cases, some pixel-perfect layouts may not be able to tolerate the 2-pixel padding around the text_field caused by the red border. An alternative is to change the background color of the offending field.

Include the following code in environment.rb (or use a “require” like I do):

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  error_style = "background-color: #ffff80"
  if html_tag =~ /<(input|textarea|select)[^>] style=/
    style_attribute = html_tag =~ /style=['"]/
    html_tag.insert(style_attribute   7, "#{error_style} ")
  elsif html_tag =~ /<(input|textarea|select)/
    first_whitespace = html_tag =~ /\s/
    html_tag[first_whitespace] = " style='#{error_style}' "
  end
  html_tag
end

Update: Removed some “cruft left over from refactoring” :)

Update #2: Here is a CSS-friendly version (Thanks to Technoweenie for the suggestion):

ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  error_class = "field_with_error"
  if html_tag =~ /<(input|textarea|select)[^>] class=/i
    class_attribute = html_tag =~ /class=['"]/i
    html_tag.insert(class_attribute   7, "#{error_class} ")
  elsif html_tag =~ /<(input|textarea|select)/i
    first_whitespace = html_tag =~ /\s/
    html_tag[first_whitespace] = %{ class="#{error_class}" }
  end
  html_tag
end

(Past?) Time to Pay Attention to the Earth

In January of this year, James Lovelock, author of the Gaia Theory announced that the earth has caught a fever manifest by irreversible global warming.

More recently, the BBC released an article confirming the alarming rate of increase of CO2 in the atmosphere.

And now there is evidence that not only have our American governing officials been aware of it, but they have actively been censoring communication from those who can help us most. More information on this censorship here.

Awareness is increasing.

The Case for Rails: Talking to Management

Max Baker, a PHP developer trying to influence the powers that be at his company, recently wrote:

I’m currently a php/sql developer for a company and I think rails is one thing that can really get our development to the next level , but management says that rails is just hype and that building ajax rich applications is much easier using php and java script , etc… I’ve shown them applications with rails and such, things like text mate, and how fast and easy things can be done to no avail.

I really wanna switch and join the rails community, but I don’t know what to tell them. What should I do?

With the release of Rails 1.1, rails is finally reaching an outwardly visible stage of maturity. Because of that confident-looking version number, it’s now quite a bit easier to rebutt the first thought to grip management—that Rails is in its infancy, and that there is no stable code base.

So what other concerns are there? I tried to address some of them by relating my own journey from PHP to Ruby in my response to Max’s email:

To Max

It’s a privilege to share with you some of my thoughts on developing web applications in Rails–I was in your shoes not long ago, and I know what it feels like to be the “work horse” when it seems the reins are in someone else’s hands. All I can say is don’t lose hope–while Rails may be hyped right now, it’s not *just* hype. It will prove to be the obvious choice some day, but we’re still riding the early adoption curve right now, so there is a natural resistance to its novelty.

Letter to Management

About 2 years ago, I was hired by a small local web dev company to build and maintain PHP applications. We had a few in-house libraries that aided our development–things like database connection and querying libraries, for example–but no framework that we had standardized on. Some of my responsibilities included maintaining legacy code, training new hires, and leading the development of new applications. Perhaps some of the things I learned there will be helpful to the managers at your company:

1. Ruby is easy to learn

One of the main concerns brought to my attention by management when I worked to bring Ruby on Rails in to our shop was that there are lots of PHP developers out there, and very few Ruby developers. My response was that while that is the case for now, it doesn’t address the more pressing concerns for a development team.

For example, there is always a lead-in time for someone new on the team. How long does it take them to get up to speed with the language, framework, and environment? In my experience, anyone who understands one or two programming languages already will have no trouble picking up on Ruby. In fact, it took about the same time for a PHP developer to begin to be productive using our in-house libraries as it did for a PHP developer to begin to be productive using Ruby and the Rails framework (2 weeks).

In addition, the best practices that are encouraged by the Rails framework actually led to *better* developers in the long run. Those who adopted the agile methodology of Ruby on Rails by testing their code, refactoring, and using tools such as version control were, in my opinion, more valuable to the team.

2. Ruby is a swiss army knife, PHP is a hunting blade

While there’s no doubt that PHP and Ruby are both stable, capable languages, Ruby has some real advantages. It’s namespaces lead to more modularized code. Its closures lead to more code re-use. And its terse syntax makes it possible for even non-programmers to understand a surprising amount of it. In short, it gives developers more choices and more tools when solving problems.

While PHP has some advanced features that come with a late-bound language, it is not as well thought out, nor as self-consistent as Ruby. It require more brain-power to remember the thousands of function names and subtle differences between calls. (Do you pass “strstr” the haystack or the needle first?) In the end, programmers find that there is a “cap” or ceiling that they reach in PHP much sooner than in Ruby. In addition to the brainspace issue, there is the pure limitations of the language. For example, one of my friends–a developer of a Rails-a-like in PHP called Trax–told me that the lack of namespaces in PHP made it necessary to tack on prefixes to variable names in order to prevent clashes between modules. He has since begun to develop using Ruby on Rails (though, from what I understand, he is simultaneously working on Trax).

Fred Flinstone might be happy with a hunting blade, but if you want MacGyver on your team, give him a swiss army knife and see what he can do.

3. You definitely want your developers to standardize on a framework

Having dealt with several projects that use different approaches and techniques to get the same things done, I can recommend with confidence that you want to standardize on a framework. It just makes sense–your developers will be able to re-use more code more often, and there will be a common knowledge-base from which they can share tips and tricks. PHP is not a framework, nor does it offer guidance when making decisions that have been made countless times before. While there are a number of PHP frameworks out there, I have not found one that I can recommend as highly as Rails.

UPDATE: See Ruby on Rails from a Business Perspective for more on this point.

4. The Ruby on Rails framework gives your developers an edge

Because of the grass-roots support and energy surrounding Ruby on Rails, many, many brilliant web developers are contributing code and ideas to each other and to the Rails core on a daily basis. Developers who keep abreast with these new ideas and solutions to common problems have the benefit of “wisdom beyond their years” during the development cycle.

Additionally, there are a number of best practices and standards that are embedded within Rails itself that guide and influence developer decisions along the path to deployment. For example, separation of concerns using the model-view-controller paradigm; separating out the test, development and production databases; using fixtures for unit testing; the easy availability of integration testing (Rails 1.1), and the easy integration of Capistrano for deployment to multiple servers, to name a few.

I believe the productivity claims of up to 10 times *can* be true, but only in some cases. For example, I built “Family Connection” (a web-based family communication tool) in a day. On the other hand, when there are new problems to address or challenges that go beyond the wisdom of Rails, development can be much slower, perhaps equal to my previous PHP development speed. In any case, I’m much happier using Rails.

5. Programmers are more productive when they’re happy

A final note to those who are in a position to decide between one application framework and another: consider your developers feelings. If you see a flash of passion in their eyes when they talk about a framework, pay attention. You may or may not be intimately aware of technology trends, so trust your co-workers instincts. Programs may act mechanically, but humans do not. Go with the passion.

Rails Cheat Sheat for TextMate

Now that the syncPEOPLE on Rails bundle is built in to TextMate by default, it would be nice to see the commands, macros and snippets all in one sheet. It looks like Sebastian Friedrich beat me to it—take a look at his TextMate Rails PDF.

Thanks, Sebastian!

syncPEOPLE on Rails 1.0

Just a little note to say the syncPEOPLE on Rails Bundle for TextMate has reached 1.0 and is ready for download. Visit the syncpeople.com downloads page for links.

There is now a demo video available (low-bandwidth version here).

It’s been several years since I’ve had the desire to invest time in a computer game. In fact, I haven’t really seen an original game in 15 years. But Spore looks to be out of this world.


Take a Look at the Spore Gameplay Demo Video

  • 1 Comment
  • Filed under: Life and Family
  • Finding a Screencasting Tool for Mac OS X

    It’s taken me a suprisingly long time to find a decent screencasting / screen recording tool for Mac OS X. I tried SnapZ and didn’t like the complexity. Nor the price.

    vnc2swf is an interesting and free option, but it doesn’t come with built-in sound recording, and I couldn’t find a shell-based alternative to the linux-only arecord alsa audio recording tool. In addition, the coupling between OSXvnc and the recording tool means you need to change the resolution of your screen using the pref pane to 800×600 if you want to make browser-friendly screencasts. That made things feel a little crunched on my 20″ iMac.

    So what other options are there? The most comprehensive list I could find was at answers.com. In the end, I chose ScreenRecord, due to its simplicity and fair price: I’m willing to shell out $20 for this.