0

The Terminal application has been steadily improving with every major release of Mac OS X. Recently added was a new feature called Window Groups which saves the state, tabs, and locations of all windows at a set point in time. I’ve personally found this to be a very helpful feature with just one caveat: It requires frequent upkeep when working with multiple projects.

The Window Group Upkeep Problem

I currently work on nine Ruby on Rails applications that are all tied together via a single sign-on server and signed API requests — think of it like an ecosystem of decoupled apps. When I’m developing within this ecosystem the task of trying to keep track of all the activity going on between these apps is a major pain point.

Before this post I had originally tried to solve this control and monitoring problem by running three Terminal.app Windows, each dedicated to running a tab (per application) for …

  1. $ rails console
  2. $ tail -f -n 100 log/development.log
  3. and a Shell for running rake tasks, tests, and other commands.

This solution started out simply enough but quickly ballooned as more apps were added to the ecosystem.

The pain of this solution was just too much to ignore after the addition of the 9th app resulted in 27 tabs spread across 3 terminal windows. It was clear that the simple solution I has come up with would no longer scale — I reached out for some advice.

Consolidating The Mess Of Windows & Tabs

I knew there had to be a better way to manage these growing number of applications — surely others experienced this problem?! I switched over to the Indy.rb Meetup Group‘s IRC channel and asked the open question of how everyone had been going about their terminal management. Soon thereafter many people were coming to the table with various suggestions, techniques, and solutions to how they’ve address the issue.

The majority of opinions fell on the solution that involved using just a single Terminal.app window with one tab per application; each tab would then be running a tmux session that would group the application’s operations and information together.

Being juuuuust a little bit late to the tmux party (it was released in 2009) I finally decided to “get my tmux on” and dove right in. After spending a couple of hours looking at documentation and messing around with config files I ended up consolidating my original setup of “3 windows + (3 tabs * App)” into “1 window + (1 tmux tab * App)” — finally some sanity!

Note: I’ll discuss my tmux setup and configuration in another post soon!

Scriptable Terminal.app Tabs

With all of the aforementioned advancements to the Max OX Terminal.app I still found controlling it from the command line to be quite a hassle. I had a great new solution for consolidating my development environment but it still required me to do some manual setup. I wanted to find a way to launch all of my applications’ tmux sessions from one Terminal.app window into separate tabs.

I needed a way to script…

  1. Creation of a new tab within the same Terminal window.
  2. Changing the title of each new tab to reflect the application’s name.
  3. Executing arbitrary commands after each tab was created.

After using some serious black-belt level Google-Fu, and sifting through many StackOverflow articles, I managed to hack together a handy little shell function that allowed me to do just that.

Below is a sample launch_dev.sh executable shell script that contains a new_tab() function, and some examples of its usage…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/bin/bash
# File: ~/launch_dev.sh

function new_tab() {
  TAB_NAME=$1
  COMMAND=$2
  osascript \
    -e "tell application \"Terminal\"" \
    -e "tell application \"System Events\" to keystroke \"t\" using {command down}" \
    -e "do script \"printf '\\\e]1;$TAB_NAME\\\a'; $COMMAND\" in front window" \
    -e "end tell" > /dev/null
}

# Let's make a new tab called "My Projects", change to the
# projects directory, and list the contents.
new_tab "My Projects" "cd ~/projects; ls -l"

# Let's also open up our deployment scripts directory
# too -- that would also be handy!
new_tab "Deployment Scripts" "cd ~/scripts/deployment"

What Is The new_tab() Function Doing?

Basically, it’s utilizing a ton of wrapping. Let’s start from the top down…

  1. I’m creating a new_tab(tab_name, command) shell function which primarily uses the osascript command to execute custom AppleScript code.
  2. Apple scripting instructs the Terminal application to open, or become focused.
  3. Apple scripting simulates a key press of “⌘+T” — the shortcut for opening a new tab in Terminal.app
  4. Apple scripting continues by executing a do script command, which in-turn executes the \e]1;$TAB_NAME\ashell command — setting the newly created tab’s title.
    • Side Note: The \e]1; and \a snippets are interesting aspects of the shell that I knew nothing about prior to embarking on this endeavor. I originally found the technique in a StackOverflow article, but no explanation was given on why it worked to set the title. I would encourage you to check out the “Dude, what’s up with your prompt?” blog post by Vince Aggrippino to find out the answer.
  5. The previous \e]1;$TAB_NAME\a command is chained with a semi-colon, and then followed by a $COMMAND variable that gets evaluated and executed in the new tab as well.
  6. Lastly, any output from the original call to osascript is redirected to /dev/null.

Cool huh?

Summary

This ability to open, name, and command new terminal tabs through a simple shell function has vastly changed the way I operate in my current multi-application ecosystem. When I want to setup my development environment I can simply run my ~/.launch_dev.sh shell script and have multiple tabs open, name themselves properly, and attach themselves to tmux sessions.

It’s important to keep in mind that when it comes to the topic of “Development Environments” it really is a case of “to each their own.” With this shell function one can now easily configure and launch their development environment’s tabs all from a simple script. This in turn opens up countless possibilities for anyone looking to gain better control over their Terminal.

This function is not “The Solution” to building and managing development environments. Rather, it’s simply a tool to help create solutions.

If you do end up using this code for anything please come back and comment on your successes — I’d love to hear them :)

Enjoy!

Environment

The environment and tools used at the time of this post are as follows:

  • Max OS X Lion (Version 10.7.5)
  • Terminal.app (Version 2.2.3)

License

This code is released under the New-BSD License.

0

Here’s a quick and easy way to sort a Ruby hash by its keys. The ability to sort recursively and provide a custom sort block are also available features.

The Method

I took the approach of monkey patching a sort_by_key method into the Ruby Hash class itself. The method can be easily modified and placed into a utility class if you’d prefer to take more procedural approach.

1
2
3
4
5
6
7
8
9
10
11
class Hash
  def sort_by_key(recursive=false, &block)
    self.keys.sort(&block).reduce({}) do |seed, key|
      seed[key] = self[key]
      if recursive && seed[key].is_a?(Hash)
        seed[key] = seed[key].sort_by_key(true, &block)
      end
      seed
    end
  end
end

Basic Usage

Below is a very disorganized nested hash and an example of using the recursive sort option to get it back into line using Hash.sort_by_key(true).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
h = {
  "b" => 2, "c" => 3, "a" => 1, "d" => {
    "b" => 2, "c" => 3, "a" => 1, "d" => {
      "b" => 2, "c" => 3, "a" => 1
    }
  }
}
h.sort_by_key(true) # =>
{
  "a" => 1, "b" => 2, "c" => 3, "d" => {
    "a" => 1, "b" => 2, "c" => 3, "d" => {
      "a" => 1, "b" => 2, "c" => 3
    }
  }
}

What About Mixed Type Hash Keys!?

If we continued the example from above by executing h[:a] = “one”, and then calling h.sort_by_key, we would be slapped in the face with an exception of …

ArgumentError: comparison of String with :a failed

Looking at the backtrace it appears the call to self.keys.sort is the culprit.

So What’s The Solution?

There are a couple of solutions depending on your coding style and opinion on ruby convention.

(more…)

31

I’ve been loving the Twitter Bootstrap buttons so I came up with a quick technique that turns them into actual working form input elements.

HTML

Just like a normal Boostrap button group, but with a few added attributes.

1
2
3
4
5
<div class="btn-group" data-toggle-name="is_private" data-toggle="buttons-radio" >
  <button type="button" value="0" class="btn" data-toggle="button">Public</button>
  <button type="button" value="1" class="btn" data-toggle="button">Private</button>
</div>
<input type="hidden" name="is_private" value="0" />

Yes, nested names like bookmark[is_private] work just fine.

Javascript

On document load we apply the button logic and state based on the hidden input’s value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
jQuery(function($) {
  $('div.btn-group[data-toggle-name=*]').each(function(){
    var group   = $(this);
    var form    = group.parents('form').eq(0);
    var name    = group.attr('data-toggle-name');
    var hidden  = $('input[name="' + name + '"]', form);
    $('button', group).each(function(){
      var button = $(this);
      button.live('click', function(){
          hidden.val($(this).val());
      });
      if(button.val() == hidden.val()) {
        button.addClass('active');
      }
    });
  });
});

The Result

Twitter Bootstrap Radio Button Form Inputs Result

Notes & Considerations

  • This solution requires javascript in order to work properly so use judgement when implementing it.
  • You may also need to do some styling to get the buttons to look right in some contexts, but thankfully that’s been a relatively painless experience.
  • The type=”button” is required to prevent the form getting submitted when the toggle buttons are clicked.

Summary

Please contact me if you find any issues. I’ve tested this technique over the weekend and I’ve been very happy with it.

26

I had just finished the standard installation of ActiveAdmin when I noticed that authentication was implemented using the fantastic Devise gem. I had already been planning on using Devise for authentication within my application so I initially thought integration would be a snap. However, as development progressed it became clear that all of the pieces were not quite fitting together.

Realization

After exploring the idea of using one login for ActiveAdmin and the application I ran into a rather large road block. By default ActiveAdmin uses an AdminUser Devise model to manage user authentication. Why is that such a big problem you ask? Well, I really wanted to avoid having…

  • the application users login via the ActiveAdmin interface
  • a model named “AdminUser” representing an application user
  • two models that contained much of the same code and functionality
  • to maintain two separate user management systems (Admin vs Application)

In most cases ActiveAdmin would be used by… well, administrators. However, that was not my situation. I had a slew of qualified people that needed access to both ActiveAdmin and the Application; having two sets of credentials was just not the optimal solution.

The Optimal Solution

What I really wanted was for both the ActiveAdmin and Application users to be…

  • able to sign in/out via a single set of Devise controller/actions routes
  • managed by single, Devise configured, User model
  • distinguished by a boolean flag, such as superadmin?
  • restricted from accessing ActiveAdmin based on the above flag.

After chewing on the problem for a while, reading through ActiveAdmin documentation, and talking to a couple of colleagues I managed to come up with a way of implementing a solution that provided exactly what I was looking for.

(more…)

0

I was recently reviewing some code when a simple question came up…

What’s the fastest way to output a segmented string?

1
2
3
4
5
echo '<div>';
echo '<span>';
echo 'This is a random number: ' . mt_rand(1,100);
echo '</span>';
echo '</div>';

– OR –

1
2
3
4
5
6
7
$html = '';
$html .= '<div>';
$html .= '<span>';
$html .= 'This is a random number: ' . mt_rand(1,100);
$html .= '</span>';
$html .= '</div>';
echo $html;

My initial guess was that calling echo as little as possible during a request would end up performing better as there would be no need to interact with an output buffer or perform other logic tied to STDOUT.

I ended up asking a few friends and colleges what they thought about the question and most responded with “hu?” After telling them that I was in fact serious the majority of their opinions fell on echo being the winner. Still, others thought of ways to get a segmented string out faster, like pushing them onto an array and executing echo implode(”, $array);

This difference of opinion got me thinking about what was truly the most efficient way to output a collection of strings? Curiosity got the best of me and I quickly setup some profiling tests using my Bench Class to find out the answer.

Profiling Setup

I used the following code in order to get enough data points for a solid performance comparison.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$samples = 40;
$sets = array(10,20,50,100,500,1000,1500,2000,2500,3000);
$results = array();
foreach($sets as $iterations) {
  $results[$iterations] = array();
  for($i=0; $i<$samples; $i++) {
    Bench::start();
    for($j=0;$j<$iterations;$j++) {
      // ... Output Test ...
    }
    $results[$iterations][] = Bench::stop();
    Bench::reset();
  }
}

Tests

I tested the performance on four different methods of outputting data…

(more…)