Announcing the next release of WordPress Domain Changer – version 2.0!

This release marks the completion of a total rewrite that brings an updated user interface, improved stability, fine-grained control, improved testing, and a few bug fixes.

Redesigned UI & Workflow

Precise Control

The ability to specify database tables has finally arrived!

Safety Net

A Preview & Confirm step has been added in order to help make the domain change process a bit more user-friendly.

Integration Testing

Verifying that WPDC works with every supported version of WordPress would be a slow and tedious process if done by hand. Integration testing to the rescue…

Running RSpec/Capybara suite...

Change Domain of WordPress 2.0.4
  Drop WordPress database
  Create WordPress database
  Unzip WordPress archive
  Start a PHP web server for the OLD domain
  Run through WordPress configuration setup script
  Run through WordPress installation script
  Ensure WordPress site can be reach at OLD domain
  Ensure WordPress site only references the OLD domain
  Install WordPress-Domain-Changer into the root directory of the WordPress site
  Change the URL of the WordPress site using WordPress-Domain-Changer
  Start a different PHP web server for the NEW domain
  Ensure the WordPress site can be reached at the NEW domain
  Ensure the WordPress site only references the NEW domain

Change Domain of WordPress 2.0.5
  Drop WordPress database...

... ( continues up to the latest WordPress release ) ...

Finished in 8 minutes 32 seconds (files took 0.62827 seconds to load)

Continuous Integration

Travis CI has been implemented in order to support the aforementioned testing efforts. Changes pushed to Github will automatically trigger a Travis Build, which verifies that both the unit and integration tests are still passing.

Travis is currently reporting WPDC’s status as – Build Status

Odds & Ends

  • Improvement - All WordPress versions between 2.0.4 and 4.0.0 are officially supported.
  • Improvement - Multi-byte characters support has been added.
  • Bug Fix - Multiple inconsistencies were found in the find & replace logic used for PHP Serialized strings. This logic was rewritten using a more simplistic approach.

See the Change Log for a complete list of changes.

License

WordPress Domain Changer’s code is released under the New-BSD License.

Download

The source code and usage instructions are available at https://github.com/veloper/WordPress-Domain-Changer.

When I decided to port my blog away from WordPress I found myself torn between two great static site generators — Middleman and Jekyll

Feature Envy

One of the features that I’ve grown quite fond in Middleman is their LiveReload Extension. All one needs to do is add activate :livereload to the config.rb file and Middleman will automatically reload the browser when a file change is detected – it’s really slick!

Unfortunately, LiveReload is not available as an out-of-the-box feature for Jekyll. However, the good news is that the same feature can be implemented by using the guard-livereload gem in combination with some simple configuration.

Implementation

Bundler & Gemfile Setup

We start out by ensuring that a Gemfile exists in the Jekyll project’s root directory. Run bundle init to create the Gemfile, open it in an editor, and then add the following gems…

gem 'jekyll'
gem 'guard'
gem 'guard-jekyll-plus'
gem 'guard-livereload'

Install the gems via Bundler and try building your site using the commands below…

$ bundler install
$ jekyll build

It’s very possible that an error will occur after running these commands – don’t worry!

  • The last line of the error should look like this: Missing dependency: xxxxxxxxx.
  • Add the missing dependency to the Gemfile and repeat the last two commands.
  • Continue these steps until your site builds successfully.

Guardfile Configuration

guard 'jekyll-plus', :serve => true do
  watch /.*/
  ignore /^_site/
end

guard 'livereload' do
  watch /.*/
end

Browser Extension

Lastly you’ll need to download and install the Live Reload Extension for your browser – Chrome, Firefox and Safari are supported. This extension automatically refreshes your browser when a change is detected.

Workflow

With :serve => true specified in the jekyll-plus guard options we can now start the Jekyll Web Server + LiveReload by using one simple command…

$ guard

After the guard is executed some output will appear that looks something like this…

Configuration file: _config.yml
22:46:55 - INFO - Guard is using to send notifications.
22:46:55 - INFO - Jekyll building...
    Server address: http://0.0.0.0:4000
  Server running... press ctrl-c to stop.
22:46:56 - INFO - Jekyll build complete ./ → _site
22:46:56 - INFO - Jekyll watching and serving at 0.0.0.0:4000/
22:46:56 - INFO - LiveReload is waiting for a browser to connect.
22:46:56 - INFO - Guard is now watching at '/Users/daniel/projects/my-blog'
[1] guard(main)>

Now, switch to the browser, make sure the LiveReload extension is turned on, and navigate to a blog post. If everything is configured correctly the line below will appear in the terminal…

22:46:58 - INFO - Browser connected.

Open up the blog post in an editor, modify it and save the changes. When you switch back to the browser you should find that the page has automatically reloaded.

Environment

This post was written for, and tested under, the following technologies…

  • Jekyll (1.4.3)
  • Guard (1.8.3)
  • Guard-Jekyll-Plus (1.4.10)
  • Guard-LiveReload (1.4.0)
  • Bundler (1.3.5)
  • Ruby (1.9.3)

Summary

Since implementing Guard-LiveReload in Jekyll I’ve found the process of writing and editing blog posts to be a much more enjoyable experience.

If you’ve found the post useful, or run into any unexpected issues, please feel free to contact me or leave a comment below.

The Terminal application has been steadily improving with every major release of Mac OS X. A new feature called Window Groups was recently added which saves the state, tabs, and locations of all terminal 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…

  • Creation of a new tab within the same Terminal window.
  • Changing the title of each new tab to reflect the application’s name.
  • 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…

#!/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…

  • I’m creating a new_tab(tab_name, command) shell function which primarily uses the osascript command to execute custom AppleScript code.
  • Apple scripting instructs the Terminal application to open, or become focused.
  • Apple scripting simulates a key press of ⌘+T – the shortcut for opening a new tab in Terminal.app
  • 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.
  • 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.
  • 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.

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.

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).

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.

Option 1: Don’t do that!

Many coders in the Ruby community will argue that it’s not the job of Ruby to undo a user’s mistakes. While “Don’t do that!” that can sound like a copout, it’s also really good advice – keep things simple.

Generally, it’s not a good idea to mix the types of Hash keys. If you find that you’re getting this exception it’s probably an indication that “You’re doing it the wrong way.”

Option 2: Passing a custom sort block, and casting key values…

Coming from PHP I’ve grown accustomed to certain… luxuries, in that if you ask PHP to ksort() an array it will do its very best to get you something reasonable back. By passing a custom sort block to Hash.sort_by_keys we can mimic PHP’s robustness.

Let’s change how Hash.sort_by_keys is called by passing it a custom sort block that casts each key to a string before the comparison.

h.sort_by_key(true) {|x, y| x.to_s <=> y.to_s} # =>
{
  :a => "one", "a" => 1, "b" => 2, "c" => 3, "d" => {
    "a" => 1, "b" => 2, "c" => 3, "d" => {
      "a" => 1, "b" => 2, "c" => 3
    }
  }
}

It’s a very simplistic technique that should be capable of accommodating almost all of the off-the-beaten-path situations out there in the wild.

Summary

I ended up needing a variant of this solution to address a situation where http parameter ordering had to be alphabetical in order to create and validate signed requests to OAuth based APIs. So far things are working well and my code is a lot cleaner.

In my search for an existing sorting solution I also stumble upon this StackOverflow.com Question that shed some light on other hash key sorting techniques.

License

This code is released under the New-BSD License.

If you’ve found an issue, improvement, or bug with this technique please Contact Me, or comment below.

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 Bootstrap Button Group, but with a few added attributes.

<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" />

Note: 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.

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.on('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.
  • The type="button" is required to prevent the form getting submitted when the toggle buttons are clicked.
  • You may also need to do some styling to get the buttons to look right in some contexts. Thankfully I’ve found this to be a relatively painless experience.

Summary

Please comment or contact me if you find any issues. I’ve tested this technique and so far I’ve been very happy with it.