our blog

The Highgroove blog. Sit pit-side with us to learn how we work. Sometimes technical, sometimes business-oriented, but always focused on simple solutions.

Posts tagged with Howto

You are browsing posts about Howto. Check out all posts on our blog.

You've read our blog, had Highgroove do work for you, watched our Tech Talks, attended the Atlanta Ruby User Group which we host, and all around think we're great.

Now, you've decided that what you really want to do is hire one of our developers full time to work for you. Maybe you're a recruiter looking to fill an 'awesome position at a big company in the Atlanta area', or maybe your startup is ready to take the next step and hire an in-house developer.

We get a lot of e-mails and calls from recruiters, and to be honest, most of them are absolutely terrible. Read on for some tips on how to recruit Highgroovers to come work for you instead. Seriously. Please. We're not telling you to not try and recruit our developers, but please stop wasting your time and ours.

→ Read More

Pry Logo

Highgroove really likes Pry. It's a great tool for digging into your code and seeing what's going on with tons of great features. However, there are situations where using a standard binding.pry breakpoint will not block your program and allow you to inspect it. I recently ran into this situation when trying to debug an application that used Foreman to manage it's processes. Luckily, the pry-remote project turned out to be a great solution.

→ Read More

Tools on pegboard 2012-04-03 09.26.50

At Highgroove we really like testing and are constantly looking for ways to improve our testing process, how quickly our tests run, and how exactly we execute our tests. How often during your Test Driven Development (TDD) cycle do your tests fail "mysteriously"? You've written your tests, written your code, and most of them pass but one or two stubbornly fail even though you are fairly certain they should pass given the testing setup you've provided? At Highgroove we bias towards action so we are likely to launch a debugger session or a pry session to get to the bottom of this. Another approach, which won't break your existing TDD workflow, is to use your test-suite in place of a more traditional debugger. After the jump we'll talk about how we've been using this strategy to dig into code quickly and easily.

→ Read More

I find your lack of tests disturbing...

At Highgroove Studios, we're hyperspecialists in Ruby on Rails web application development. Not only do we write amazingly complicated code on time and on budget, but we follow up all our work with tests so we know our code works.

This is not without its problems however, as a test suite can become just as bloated and difficult to update as the code base it tests! This week, I'll talk about some of the ways I've learned to approach writing tests.

→ Read More

by brandon

Combining Many Customer Databases into One

Published November 08, 2011 in Ruby on Rails Howto

Keys

Here at Highgroove we like a good challenge, and we love it when we can meet a challenge with a simple and elegant solution.

Recently we had a customer with a great problem to have - they had signed up lots of new customers and were experiencing some growing pains.

A typical Ruby on Rails app has one database. This app had one database per customer.

Routine tasks like launching servers, deploying code, or migrating databases were taking much longer than normal because they had to be performed per customer instead of just once.

→ Read More

So you've got an awesome web application up and running. You want to keep your users engaged. You could try to handle collecting emails, writing your own newsletters, managing the list, keeping content fresh, tracking who read your messages, and so on (and so on) -- all within your own app; however, there's a better way. We recommend using Mailchimp. It's actually very simple to integrate Mailchimp into your own Ruby on Rails application. Quick. Easy. DRY. Just the way we like it.

→ Read More

by jonathan

A SQL Pattern in Rails

Published June 28, 2011 in Code Keeping it Simple Howto Ruby on Rails

ActiveRecord is wonderful for the easy queries. But there are times, in the name of performance, when one must bust through the ORM facade and dip below into SQL.

Edit: Updated gist to fix SQL injection. Thanks to all the code reviewers, uh I mean commenters, for pointing it out!

Also pointed out in the comments, using lambdas in this pattern makes most sense for Rails 2. In Rails 3, AREL is composable so one can use class methods.

Wed Jun 29 13:55:27 EDT 2011

→ Read More

Using different ‘environments’ in Ruby on Rails development is an established best practice. Rails provides you with 3 default ones: Production, Development, and Test, and at Highgroove we like to add a ‘Staging’ environment as well. Heroku supports multiple environments, and they make life a lot easier when building applications.

In the production environment, some things are cached by default, while in the development environment, things are loaded whenever they are changed which makes working on a project a lot easier because you don’t have to restart the server to see your changes. A staging environment lets you ensure that your staging system and production system stick to their own databases and API services without requiring any server customizations other than setting RAILS_ENV.

This all sounds great, but if you’re not careful early on it can lead to some intersting problems!

→ Read More

by cbq

Less Code is Better

Published March 27, 2011 in Howto Business Keeping it Simple

It’s a good thing we don’t charge by the lines of code we write in an application.

Do Less Achieve More

On a recent project, we’ve been keeping track of the lines of code, and it’s continually going down. You may be thinking — how is the project progressing? With less code, is the application doing less or providing less functionality?

Quite the opposite, actually.

→ Read More

Highgroovers. Flexible, self-starting, curious, good, nerdy, professional. These are a few of the words we used to describe ourselves in our annual 2010 Recap meeting (attendance optional -- we're ROWE baby!). We are always re-examining our best practices (a best practice - how meta!) to insure that we're delivering maximum value to our customers.

"Delivering maximum value." That sounds lame!

→ Read More

by jonathan

Debugging Ruby Tools

Published November 09, 2010 in Howto Atlanta Ruby on Rails

New albums drop on Tuesdays, why not drop some nifty knowledge as well?

Today, I had the pleasure of attending an Engine Yard webinar, Debugging
Ruby Systems. In this webinar, the always sharp Aman Gupta (twitter, github), reviewed his
favorite tools for debugging ruby and rails applications.

The webinar recording isn’t yet up and even though the slides will eventually be posted,
I figured it would be worthwhile to post my notes so here they are. For my
next post, I’ll cover which tools helped me diagnose and resolve an
outstanding issue in one of our current applications. Stay tuned!

All credit for good goes to Aman. Any errors are mine. Most of these tools are linux specific. Enjoy!

→ Read More

by cbq

The 4 Things We Look For in a Code Review

Published March 20, 2010 in Howto Business

Most developers think that every “other” developer’s code is “no good.” In fact, it is exactly this “Not Invented Here” syndrome that makes it dangerous for other developers to evaluate an existing project’s quality without a checklist or template as a guide.

Here are a few of the things in Highgroove’s Code Review tool-belt, that we look for:

  • Tests – This is a given – Ruby on Rails ships with a great test framework. Your app needs tests. The default suite will do! Many developer teams will even upgrade the testing suite, adding RSpec and Cucumber, Selenium for in-browser testing, rcov for code coverage, and FactoryGirl for fixtures and test data. Without tests, you’re bound to regress (“Jim fixed a bug, but looks like he added a few more…”). Bottom line: Tests = Quality.
  • Idiomatic Ruby and Rails – Did the developers use standard plugins, or did they re-invent pagination? Did they use a search plugin or did they write their own fancy-pancy algorithm for search? Are they using helpers, or just copy-pasting code all over the place? This can tell a lot about a code-base and how easy to maintain it is and will be long-term.
  • Code Look and Feel – We are actually looking for indentation, comments, and commented-out code here. This may seem strange, but projects that have lots of sloppy indentation means a developer didn’t have much respect for the code long-term. If they’ve got a lot of code commented out, it appears they “got something working” and then didn’t bother cleaning up. It’s the equivalent of a mechanic who fixes a car, but leaves bolts lying around, loose, dings up other pieces, and doesn’t clean up. Yikes!
  • Bootstrapping Documentation – How easy is it to get a new Developer up and running? This may seem strange to check for, but just looking to see how well the current Developers expect other Developers to be able to get up to speed is a sure sign of a quality application. It takes a high level of maturity to realize, as a Developer, that you will not always be the only one working on a project!

Even when we come across a project that may not contain many of these quality indicators, it’s not the end of the world. Once we’ve identified the broken windows, we can get to work fixing them.

Photo Credits:

by cbq

Apache Page Caching and Multiview

Published August 04, 2009 in Howto

I just wanted to post a quick note to anyone searching for problems with Rails Page Caching with Apache.

We just helped a client through a tricky issue that manifested itself through some strangely generated cached files.

The Problem

A visit to the resource:


http://example.com/articles

Would correctly generate the page:


/path/to/app/public/articles.html

Subsequent visits would load the cached page.

→ Read More

For a client’s application, we needed to programmatically (without user-intervention) update the Status (Wall) of a Page for a Company. After researching the API and several guides, you would think it was just not possible..

In fact, there’s even a forum post on the Facebook developers forum on How to update facebook page status from 3rd party application
where a Facebook employee explains that it is impossible (as of 2007, at least).

The good news is, it is not impossible (as of right now). Here’s how to update the Status of a Facebook Page Programmatically, through the API.

What you’ll need:

  • Ruby and RubyGems
  • A Facebook Account
  • A Facebook Page
  • A Facebook Developer Account/Access (we’ll go through setting this up)
  • A Ruby or Rails app with access to the facebooker library (either as a gem or using the Rails plugin).

Update: As pointed out in the comments, publishing through Facebook using the method described below does place content on the fan page, however, it is not displayed in any user’s feeds or streams, which makes it not quite so useful. We have since opted to go with the uber-cool ping.FM service and we even wrote a little ping.fm ruby wrapper library for their API.

→ Read More

Passenger, AKA mod_rails

There are a number of posts (one, two) out there on getting Phusion's Passenger up and running on OSX (Leopard). I decided to give it a go, and was pleased to discover several things:

  1. Despite reports to the contrary, Passenger installed just fine with Leopard's built-in Apache (I'm running Apache 2.2.8).
  2. Setup is very easy, as advertised.
  3. My default doc root(~/Sites) is works exactly as it did before. I do some HTML and PHP work there, so it was key that it continue to work properly.

Since the install process itself is quite easy, I wanted to offer a few tips for utilizing Passenger in a typical dev environment -- i.e., what you need after you get your first Passenger-powered Rails app up and running.

Your Brain on Passenger

As you know, script/server starts your Rails app on a specific port. If you bounce around between a number of applications at any one time, you're probably used to either starting them on different ports, or control-c'ing your current mongrel, cd'ing to another app's directory, and script/server'ing again. This familiar pattern changes when you're running passenger. All your apps are available at any one time, as long as you have your vhosts configured.

If you're like me, you usually hit your currently running Rails app on http://localhost:3000. That also changes when you're running Passenger. Instead, you'll hit a unique URL for each app, which you've configured in /etc/hosts to just go to 127.0.0.1

Setting up a new app

I set up a lot of Rails apps in my dev environment. With Passenger, in exchange for the on-demand convenience of accessing any of your apps any time, there are a few additional setup steps to take whenever you introduce a new app into your dev environment.

  1. create your rails project as usual
  2. add a new vhost. I configure mine in /private/etc/apache2/extra/http-vhosts.conf
  3. add the host in /etc/hosts
  4. restart apache: sudo apachectl restart

Here's a vhosts example with two apps I'm running locally. You can set up as many apps as you want this way:

  <VirtualHost *:80>
    DocumentRoot "/Users/andre/projects/rails/hotspotr/public"
    ServerName dev.hotspotr.com
    ErrorLog "/Users/andre/projects/rails/hotspotr/log/error.log"
  </VirtualHost>

  <VirtualHost *:80>
    DocumentRoot "/Users/andre/projects/rails/shapewiki/public"
    ServerName dev.shapewiki.com
    ErrorLog "/Users/andre/projects/rails/shapewiki/log/error.log"
  </VirtualHost>

Two things to note here:

  1. The ErrorLog line is optional. If you don't include it, the error output for this app will go to /private/var/log/apache2/error.log. Not that that's bad, but you're probably not used to looking for Rails logs there.
  2. I decided to go with the convention of dev.[PRODUCTION_URL].com. You can use anything here, as long as it matches up with an entry in /etc/hosts (see below)

And here's an example /etc/hosts addition to match the two virtual hosts above:

  127.0.0.1       dev.hotspotr.com
  127.0.0.1       dev.shapewiki.com

That's it! Go to (for example) http://dev.hotspotr.com, and you're hitting you local development app. There is nothing to start and stop. The first request for any app you hit will take a moment. Subsequent requests will feel quite snappy.

Let's Set up some Aliases to Make it all Flow

Here are the aliases I added to my .bashrc file to give me quick access to everything I needed for a new, Passenger-centric workflow in my development environment:

# Use this in any RAILS_ROOT dir. That restart.txt file tells mod_rails to restart this app.
# You'll want to do this when (for example) you install a new plugin.
alias restart_rails='touch tmp/restart.txt'

# By default, your app's error log now goes here. Unless you configure your apps otherwise, 
# it's helpful to have an alias to take you to your error log quickly.
alias apache_logs='cd /private/var/log/apache2/'

# You'll be adding to your vhosts configuration everytime you introduce a new Rails app. 
# Might as well make it a shortcut
alias vhosts='sudo vi /private/etc/apache2/extra/httpd-vhosts.conf'

# Dito with hosts
alias hosts='sudo vi /etc/hosts'

# You'll need to restart apache whenever you make a change to vhosts. 
# You can also click System Preference->Sharing->Web Sharing, but this is quicker.
alias apache_restart='sudo apachectl restart'

A while back, we wrote an article on Running Background Jobs in Ruby on Rails.

The Ruby on Rails framework has a number of tools for running your code outside of the web-request, including the venerable script/runner for one-off tasks, but using them can be a little heavy on your server. If you want to run a task on the minute, or on demand, script/runner will load your entire Rails environment, which can be from 20-50 MB, depending on how many libraries and how much code you’re pulling in.

There are also a few other good guides, recipes, and libraries that we’ve mentioned before, including:

We’ve found that it’s not terribly hard to build your own job server that runs continuously in the background and can handle all kinds of jobs, including those that should run on a specified interval. Here’s how we did it.

→ Read More

by james

Auto-Login for Any URL in Rails

Published February 06, 2008 in Howto Ruby on Rails

One of our current projects at Highgroove sends a lot of email to its users. It essentially walks them through a process and emails them at each step. All of those messages include URL's to visit the relevant page in the application for that step. Since we've emailed them the URL's we don't want them to have to login every time they click one.

To get around that I modified the application to accept URL's like the following:

http://domain.com/login/TOKEN/ANY/SITE/URL

These URL's log the user in using their security TOKEN and then redirect them to /ANY/SITE/URL. This setup allows me to easily forward a user to any URL on the site which is great when writing all of these emails.

The code is easy enough too. I imagine many of us have a sessions controller that looks something like:

class SessionController < ApplicationController
  def create
    if user = User.authenticate(params[:email], params[:pass])
      # log user in...
    else
      # login error message...
    end
  end

  # ...
end

First, I just added some support for the token based login with redirect to that:

class SessionController < ApplicationController
  def create
    if params[:token] and (user = User.find_by_token(params[:token]))
      # log user in...
      if params[:path].is_a? Array
        redirect_to "/#{params[:path].join('/')}"
      else
        redirect_to home_path  # or whatever default page you want
      end
    elsif user = User.authenticate(params[:email], params[:pass])
      # log user in...
    else
      # login error message...
    end
  end

  # ...
end

The magic redirect_to() call in that new code uses a not-often-seen feature of Rails's routing. You can specify that Rails collect any number of trailing URL bits into an Array much like Ruby can do for method parameters. Here's the route definition I am using to get users to the code above:

# a custom login route with forwarding
map.connect "login/:token/*path", :controller => "session",
                                  :action     => "create"

The *path is the magic slurping parameter syntax, again just like arguments to a Ruby method. Rails will collect each piece of the remaining URL into an Array called path, so just remember that you need to rejoin the elements to make them a real URL again.

Sometimes our Ruby on Rails apps work perfectly with test data, but when they go to production, errors creep in. Debugging errors on a production server is a pain and a bit dangerous.

Here’s what we do to quickly and safely debug issues on our production servers:

1. Add the following capistrano task to create an SQL dump of your data. If it’s a large database, it may be worthwhile to compress the SQL dump as well.

desc "Exports the production db to the home directory of user"
task :db_dump, :roles => [:app, :db] do
  run("mysqldump -u #{database_username} --password=#{database_password} #{application}_production > production.sql")
end

2. Create the following rake tasks to grab database dump and import the data locally.

namespace :db do
  desc 'Grab a dump of the production database on the server and places it in db/production.sql.'
  task :get_production do 
    `cap db_dump`
    `scp DEPLOY_USER@SERVER_NAME.slingshothosting.com:production.sql #{RAILS_ROOT}/db/production.sql`
  end
  
  desc 'Imports the database dump of file db/production.sql into development.'
  task :import do 
    `mysql -u root app_name_development < db/production.sql`
  end
  
  desc 'Grabs a dump of the production database from the server and imports the data into the local development database.'
  task :get_import => [ :get_production, :import ]
end

3. Install the Firefox plugin Server Switcher to make it easy to switch between the production and local server in your web browser.

4. Disable mail in your development box – it’s not a good feeling when you realize you’ve emailed several thousand users while testing out a newsletter script.

config.action_mailer.delivery_method = :test

by james

Mini File Uploads

Published October 03, 2006 in Howto Ruby on Rails

I just finshed fixing file uploads in a HighGroove application to work with any size file. I uploaded a 14 byte file to make sure I had things right. This has a few gotchas in Rails, so I thought I would share the recipe for success.

→ Read More

by james

Look What's Coming...

Published August 28, 2006 in What We Wrote Howto

Just wanted to make sure HighGroove customers and fans are the first to know, my new book is official:

James’s Book on TextMate

If you’re living under a rock, TextMate is the wildly popular text editor for Mac OS X shown off in most Rails screencasts.
It even won the covetted Apple Design Award for Best Developer Tool just a few weeks back.

I’ve been heavily involved with TextMate development for some time now and am excited about the opportunity to show you how to really get the most out of it. The book will cover beginning to advanced editing techniques, built-in automations and how to create your own, even how to teach TextMate new languages. I promise, there’s something for everyone in here.

Some time ago I read a “10 Best Things You Can Do as a Programmer” list and one of the points on that list was: Learn one text editor very well and use it for everything you can. I believe that’s great advice and TextMate was my pick. I’m now ready to pass that knowledge on to all of you!

You’ll be seeing even more news about this book very soon now. (Weeks, not months!) Stay tuned…

Salesforce, the large Customer Relationship Management tool, and Ruby on Rails, the elegant web development framework, seem like an awkward pair. About as awkward as dipping a Wendy’s french fry in a frosty.

Salesforce is large, often times confusing, and is a tool built for handling lots of different jobs. Rails is lean, elegant, and designed specifically for making web development easier. While Salesforce and Rails are dramatically different, they actually work very well together (much like a Wendy’s french fry dipped in a frosty – trust me).

This unlikely pairing is sparked by ActiveSalesforce, a Ruby on Rails connection adapter to Salesforce-managed data. This Ruby Gem makes working with Salesforce data about as easy as the Rails-MySQL combination.

Highgroove Studios is working on a Salesforce-Rails application, and one of the things we have to do is synchronize a local MySQL database with Salesforce. This is needed because the connection to Salesforce is slower than when working with a local database, and several parts of the application are time-sensitive.

Here’s a look at how we designed the application to synchronize data between the local database and Salesforce.

→ Read More

by derek

Metaprogramming and Ruby on Rails

Published June 27, 2006 in Howto Ruby on Rails

Metaprogramming is your secret identical twin that likes doing all of the things you don’t. Need to take out the trash? Just tell your twin. Need to program in Java? Send your twin an email.

Metaprogramming, defined as writing code that writes code by Why The Lucky Stiff, makes scaffolding, associations, validations, and the many magical parts of Rails possible. Implementing metaprogramming techniques can drastically eliminate duplicate code, making your applications far easier to maintain and build. It also lets your code do the work – not you.

CampusSync.com, a client project of ours, is a collaboration site for college students. It has several administration areas that are almost identical, but not a good fit for Rail’s standard scaffolding. The solution to eliminating duplicate code: roll our own metaprogramming solution.

→ Read More

UPDATE: rails_cron is no longer available, and daemon_generator has moved. BackgrounDRB has gone through a major rewrite, and I’ve got a chapter on Background Processing in The Rails Way by Obie Fernandez. Thanks to Chris Johnson and Douglas F Shearer for the updated information.

Without a way to run long-running tasks, Heartbeat, our 2006 Rails Day Entry, wouldn’t have had a pulse.

Like Heartbeat, most web applications need to run regulary scheduled or long-running tasks at some point in their life-cycle. These tasks are often not inititated by a web request. How can you check the validity of a URL every 15 minutes? How do we get an eCommerce store to calculate the most popular items every 5 hours? How can we re-index our site for searching every day?

If you’ve ever had to do this, chances are you’ve used cron (the *nix tool used to schedule remote tasks) coupled with script/runner. However, wouldn’t it be great if you could maintain your tasks and background “jobs” inside the ruby language, or even better, as part of your Rails application?

Let’s explore two ways to do this: the excellent BackgrounDRb plugin by Ezra Zygmuntowicz, which was used to power Heartbeat, and the fabulous rails_cron by Kyle Maxwell.

→ Read More

by derek

Faster Auto-Completion with Rails

Published June 15, 2006 in Howto Ruby on Rails

Auto-Complete is a great tool when it provides possible results BEFORE you finish typing. Unfortunately, using Rails’s included AJAX helpers to query the database as you type often results in a large delay before matches are returned.

However, there is a lightning-quick option: pre-fetch the results in a Javascript array.

In a client project, users can add labels to events on their calendar. To prevent users from creating variations of the same label name (i.e. – “favorite” vs. “favorites”), we needed to provide faster auto-complete functionality than that available through Rails’s provided AJAX helpers.

We created a simple helper method for this case (special thanks to Chad Fowler and his Rails Recipes book for the inspiration).

Take a look at the local_auto_complete_field helper method. TXT

To call the function from your views:


<%= local_auto_complete_field(‘name’,@labels) %>

In the above example, we are adding JavaScript-powered auto-complete functionality to the 'name' text field. The JavaScript array is generated by calling #name on each element in the @labels array. To override this behavior:

<%= local_auto_complete_field('name',@labels, 
                              :method => 'description') %>

Here’s to faster auto-completion!

Related Tags: