Recent Posts

Sending email: Controllers versus Models

November 16, 2009

While reviewing some code recently, I came across controller code that resembled the following.


if {lang=”ruby”}customer.save CustomerMailer.deliver_welcome_message(customer){lang=”ruby”}
flash[:message] = “Your account has been successfully created. We’ve sent you a welcome letter with…”{lang=”ruby”}
redirect_to dashboard_path{lang=”ruby”}
else{lang=”ruby”}
{lang=”ruby”}
end{lang=”ruby”}\

Fairly typical Rails code. Nothing alarming here, but I wanted to evaluate the call to the mailer in this scenario. When it comes to sending emails from your application, you can choose to do it from the controller as in the example above or in your models. Our team prefers to do this from our model via a callback as we are considering this to be part of our business logic.

Each time a customer is created, we want to send them an email. This can be moved into the model and resembled something like the following..


after_create :send_welcome_message #, other callbacks..

def send_welcome_message
CustomerMailer.deliver_welcome_message(self)
end\

There are a few benefits to doing it this way.

  1. We can test that this is being triggered within our model specs instead of our controller specs. (we prefer to spend more of our time working within models than controllers)
  2. We remove the dependency that all requests must be processed through our controllers.
    • Example: We may one day create rake tasks that data and want these emails to still be sent out. (We’ve had to do this a few times)

I definitely don’t think doing this via controllers is a bad idea, I just lean towards keeping controllers as dumbed down as possible. This allows us to have less controller code that is focused on passing data to/from models and letting our models do the heavy lifting.

UPDATE: DHH was kind enough to post a more detailed response on his blog.

Using BETWEEN for SQL comparisons

November 14, 2009

Recently, Carlos, suggested that I should start sharing some basic SQL tips that help with performance and/or general usage. I recently came across some code that I didn’t like to read and/or write. For example, let’s take the following…

```
SELECT * FROM brochures WHERE published_at <= now() AND archived_at >= now()
```

Essentially, this is pulling back some data WHERE the the brochures are considered published. (We have a project that allows people to manage their brochure launch dates ahead of time.) In fact, in this project, we have no less than 6-8 dates in the database that we’re comparing data on and it’s easy to get lost in the logic when trying to understand it.

Now, there isn’t anything inheriently wrong with how this condition is constuctued. As a matter of personal taste, I find it annoying to mentally parse. Also, I find having to write now() more than once in a WHERE clause to feel like I’m repeating myself.

Read it outloud…

“WHERE the brochures published at date is less than and/or equal to right now AND the archived date is greater than and/or equal to now.”

Who talks like that?

Luckily, there is a better and in my opinion, a more readable way to express this is with the BETWEEN construct in SQL. (postgresql docs, mysql docs)

```
SELECT * FROM brochures WHERE now() BETWEEN published_at AND archived_at
```

Let’s read this outloud…

“WHERE the current date is between the published at and archived at dates.”

This sounds more natural to me.

Additionally, you can also do the inverse with NOT.

```
SELECT ... WHERE now() NOT BETWEEN brochures.published_at AND brochures.archive_at
```

Remember kids, “code is for humans first and computers second.” — Martin Fowler

Planet Argon Podcast, Episode 3: How We Manage Bugs

November 11, 2009

Earlier this week, we published Episode 3 of the Planet Argon Podcast. In this latest episode we responded to one of the ideas someone in the audience asked on this brainstormr, which was, “How do you manage bugs?”

We had a round table discussion about how we classify and prioritize bugs with our clients, ticketing systems, and other tools that we use to streamline this process.

You can listen to this on iTunes or online.

Tracking Google Analytics events in development environment with GoogleAnalyticsProxy

November 01, 2009

As mentioned in a recent article[^1^](#fn1){#fnref1 .footnote-ref role=”doc-noteref”}, I’ve been diving deep into Google Analytics lately while working on a few client projects. We’re aiming to use much more of the features of Google Analytics and have been hitting some roadblocks with the development versus production application environments. Once you begin to dive into event tracking and AJAX-driven goal conversions, relying on just the sample code that Google Analytics provides you is going to result in you looking at a handful of JavaScript errors.

::: thumbnail pageTracker is not
defined :::

another example from the firebug javascript console…

::: thumbnail firebug pageTracker is not
defined :::

We see JavaScript errors like this because we don’t load the google analytics code in our development environments. As you can see, we are only loading this in our production environment.


<% if RAILS_ENV 'production' -%> <!--// Google Analytics //--> <script type="text/javascript"> var gaJsHost = (("https:" document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

<% end -%>\

To track an event with Google Analytics, you’d need to trigger something like:


pageTracker._trackEvent(‘Button’, ‘Click’, ‘Get in touch’);{lang=”ruby”}\

As you can see from our code earlier, in development, the pageTracker variable isn’t defined and that’s why we’re getting those JS errors. We also don’t want to add conditionals everywhere in our application to check if we’re in development or production environment.. as that’d just make our views uglier than they need to be. So, I decided that I’d create a proxy class in JavaScript that would allow us to trigger _trackEvent() and _trackPageview() and handle it appropriately.

This class works with the following logic:

  • if google analytics is loaded, pass the parameters to the real pageTracker
  • if google analytics is NOT loaded, output the information to console.log() for debugging purposes

For example, on a gallery on our web site… we track when people navigate next and/or previous through the photos. In our development environment, I can watch the JavaScript console output the following:

::: thumbnail Firebug -
GAP :::

And in our production environment, we can see that this was sent to Google Analytics.

::: thumbnail Firebug -
trackEvent() :::

We’re able to do this by initializing the GoogleAnalyticsProxy class and calling these functions through it. For example:


_gap = new GoogleAnalyticsProxy();{lang=”ruby”}
_gap._trackEvent(‘Video’, ‘Play’, ‘Homepage video’);{lang=”ruby”}
_gap._trackEvent(‘Video’, ‘Pause’, ‘Homepage video’);{lang=”ruby”}
_gap._trackEvent(‘Button’, ‘Click’, ‘Call to action X’);{lang=”ruby”}\

You’ll see that we’re just calling _gap versus pageTracker. We then replace all the instances of pageTracker (except where it is defined in the google analytics code block they provide you). You’ll find this located near the bottom of our application.html.erb file.


<% if RAILS_ENV 'production' -%> <!--// Google Analytics //--> <script type="text/javascript"> var gaJsHost = (("https:" document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));

<% end -%>

We now have _gap available throughout our project and can call _trackEvent() and _trackPageview() with it. Note: You can use any JS variable name that you want, _gap is just what I went with.

Get GoogleAnalyticsProxy

I’ve gone ahead and tossed this small JavaScript class (known as GoogleAnalyticsProxy) on Github for your enjoyment. I have some more articles in the works that will show you some tips for how to make the most of Google Analytics. If you have any questions and/or ideas for related article topics, don’t hesitate to let me know.


  1. ::: {#fn1} Tracking AJAX-driven events in Ruby on Rails for Google Analytics conversion goals↩︎{.footnote-back role=”doc-backlink”} :::

Planet Argon Podcast, Episode 2: The Letter Scotch

October 30, 2009

Earlier this week our new podcast was approved and is now available in the Apple iTunes Store. We’re also soliciting topic ideas for future episodes on brainstormr.

We posted Episode 2, The Letter Scotch, yesterday for your enjoyment. In this episode, we covered a handful of web browser tools that we use (and detest) to debug HTML, CSS, and JavaScript. This included Web Inspector, Firebug, DebugBar, and a handful of other tools. We all have slightly different preferences, depending on the tasks that we’re working on and the team had an open dialogue about the pros/cons of each of these tools.

You can learn more about and listen to our podcast at http://planetargon.com/podcast.

Thanks in advance for listening!

Tracking AJAX-driven events in Ruby on Rails for Google Analytics conversion goals

October 21, 2009

Tracking your KPI’s is extremely important in your online venture. At a minimum, you should be using something like Google Analytics to track conversions in your application. Setting up goals is actually quite simple, especially if you’re just tracking that specific pages are loaded. However, if some of your conversion points occur through AJAX, you might not be capturing those activities in Google Analytics.

Lucky for you, it’s actually quite simple to update this. I thought I’d show you a fairly simple example to help you along.

On our web site, we have a mini contact form at the bottom of many of our pages. When submitted, if JavaScript is enabled, it’ll perform an Ajax request to submit the form. If you fill out the main Get in Touch form that gets processed and we redirect people to a thank you page. The URL for that is unique and we’re able to track those in Google Analytics quite easily.

However, with the Ajax-form, the URL in the browser isn’t going to change so Google Analytics isn’t going to track that conversion. So, we needed to track that properly.

To do this, we just need to call a JavaScript function that the Google Analytics code provides you.


pageTracker._trackPageview(“/contact_requests/thanks”);{lang=”ruby”}\

Let’s look at some simple code from our controller action. If the request is from JavaScript, we currently replace the form area with the content in a partial. (note: if you’re curious about the _x, read Designers, Developers and the x_ factor)


respond_to do |format|{lang=”ruby”}
format.html { redirect_to :action => :thanks }{lang=”ruby”}
format.js do{lang=”ruby”}
render :update do |page|{lang=”ruby”}
page.replace :x_mini_contact_form_module, :partial => ‘mini_contact_form_thanks’{lang=”ruby”}
end{lang=”ruby”}
end{lang=”ruby”}
end{lang=”ruby”}\

As you can see, the redirect will within the format.html block will lead people to our conversion point. However, the format.js block will keep the user on the current page and it’ll not trigger Google Analytics to track the conversion. To make this happen, we’ll just sprinkle in the following line of code.


page.call ‘pageTracker._trackPageview(“/contact_requests/thanks”);’{lang=”ruby”}\

However, if you need to do something like this in several locations in your application, you might want to just extend the JavaScriptGenerator page. GeneratorMethods. (you could toss this in lib/, create a plugin, etc…)


module ActionView{lang=”ruby”}
module Helpers{lang=”ruby”}
module PrototypeHelper{lang=”ruby”}
class JavaScriptGenerator #:nodoc:{lang=”ruby”}
module GeneratorMethods{lang=”ruby”}
# Calls the Google Analytics pageTracker._trackPageview function with {lang=”ruby”}[path{lang=”ruby”}]{.underline}.{lang=”ruby”}
#{lang=”ruby”}
# Examples:{lang=”ruby”}
#{lang=”ruby”}
#{lang=”ruby”}
# # Triggers: pageTracker._trackPageview(‘/contact_requests/thanks’);{lang=”ruby”}
# page.track_page_view ‘/contact_requests/thanks’{lang=”ruby”}
#{lang=”ruby”}
def track_page_view(path){lang=”ruby”}
record “pageTracker._trackPageview(‘#{path}’);”{lang=”ruby”}
end{lang=”ruby”}
end{lang=”ruby”}
end{lang=”ruby”}
end{lang=”ruby”}
end{lang=”ruby”}
end{lang=”ruby”}\

This will allow us to do the following:


page.track_page_view “/contact_requests/thanks”

# or using a route/path
page.track_page_view thanks_contact_requests_path\

So, our updated code now looks like:


render :update do |page|{lang=”ruby”}
page.replace :x_mini_contact_form_module, :partial => ‘mini_contact_form_thanks’{lang=”ruby”}
page.track_page_view thanks_contact_requests_path{lang=”ruby”}
end{lang=”ruby”}\

With this in place, we can sprinkle similar code for our various conversion points that are Ajax-driven and Google Analytics will pick it up.

Happy tracking!

RailsOnPg released

October 21, 2009

Hello fellow PostgreSQL and Ruby on Rails geeks,

Alexander Tretyakov (twitter) recently released a plugin for Ruby on Rails, which extends migrations and provides you with the ability to create.

While you can already do something like this with execute in your migrations:


execute(“CREATE VIEW my_tasty_snacks AS SELECT * FROM snacks WHERE food = ‘Tasty’;”){lang=”ruby”}\

With RailsOnPage, you’re provided a DSL so that you can do the following:


create_view :my_tasy_snacks do |view|{lang=”ruby”}
view.select ‘*’{lang=”ruby”}
view.from ‘snacks’{lang=”ruby”}
view.conditions ‘food’ => ‘Tasty’{lang=”ruby”}
end{lang=”ruby”}\

[note: I haven’t tested the above, just a hypothetical example]{.small}

Anyhow, if you’re in the habit of using views, functions, or triggers with your PostgreSQL database and are using Ruby on Rails, you might give RailsOnPg a whirl.

Email twice. Four months later

October 21, 2009

It’s been just over four months since I posted about my experiment, Email. Twice daily. No more, no less. where I shared my plans to restrict myself to checking email only twice a day at designated times. In the post, I had hinted at sharing my lessons months later. So, it’s time to throw my dirty laundry in the street and expose myself.

First off.. the brutal truth. It’s really fucking hard to maintain this. Habits are nearly as hard to make as they are to break. I suspect that I honor my rule 2-3 days each week and it’s completely inconsistent the remainder. Usually, I find myself looking at email at 8:30am and have to slap myself and yell, “what are you doing?!!?”

Guilt sinks in and I hit ⌘-q. Problem solved… for a little while.

So, what has lead to this. Well, one of the biggest hurdles has been that one of our largest clients is now focused more in the United Kingdom. Luckily, I’m an early-morning person, but this means that my 10am PDT rule wouldn’t have me checking for their precious emails until 6pm GMT their time. Not exactly acceptable. So, I’ve been more flexible in the mornings and responding to emails as early as 5-6am PDT. However, I realize that I’m cheating myself of previous focus time and need to recalibrate my email windows.

Given these new constraints, I’m now trying 8:30am and 2:30pm as my primary email times.

I’m curious how this has been working out for you…

The 8-Hour Rails Code Audit

October 20, 2009

While our team is typically focused on larger client and internal projects, we do get an opportunity to assist businesses on a much smaller scale. Whether this be through retainer-based consulting or through code audits, we have seen a lot of Ruby on Rails code over what has nearly been… five years!? We’ve been able to compile a fairly extensive checklist that we use in our code audit process that we’ve decided to streamline it into a smaller product.

Historically, this service has ranged anywhere from $2000-6000, depending the size and scope of the projects, but we want to help smaller startups[^1^](#fn1){#fnref1 .footnote-ref role=”doc-noteref”} and projects outline a roadmap for how they can begin to refactor and optimize their existing code base so that they can be more efficient at the start of 2010. So, we’ve scaled things down into an extremely affordable flat-rate package where we work off of a pre-defined number of hours.[^2^](#fn2){#fnref2 .footnote-ref role=”doc-noteref”}

Through the end of 2009, we’re now offering the 8-Hour Rails Code Audit package for just $1000 USD (details).

We’re currently limiting this service to just two projects per week, so reserve your spot now.


  1. ::: {#fn1} Larger projects are welcome to benefit from this service and custom quotes are available upon request.↩︎{.footnote-back role=”doc-backlink”} :::

  2. ::: {#fn2} As always, we’re happy to discuss longer engagements.↩︎{.footnote-back role=”doc-backlink”} :::

Flash Message Conductor now a Gem

October 13, 2009

We’ve been doing some early (or late… if you’re a half-full kind of person) spring cleaning on some of our projects. One of the small projects, flash_message_conductor, which we released last year as a plugin is now a gem. We’ve been moving away from using plugins in favor of gems as we like locking in specific released versions and being able to specify them in our environment.rb file is quite convenient.

To install, just run the following:

```
  sudo gem install flash-message-conductor --source=http://gemcutter.org
  Successfully installed flash-message-conductor-1.0.0
  1 gem installed
  Installing ri documentation for flash-message-conductor-1.0.0...
  Installing RDoc documentation for flash-message-conductor-1.0.0...
```

You’ll then just need to include the following in your config/environment.rb file.


Rails::Initializer.run do |config|{lang=”ruby”}
# …{lang=”ruby”}
config.gem ‘flash-message-conductor’, :lib => ‘flash_message_conductor’, :source => “http://gemcutter.org”{lang=”ruby”}
end{lang=”ruby”}\

You can take a peak at the README for usage examples.

We’ll be packaging up a handful of our various plugins that we reuse on projects and moving them to gems. Stay tuned… :-)