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

8

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

7

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

4

A couple weeks ago I was looking for a simple way to make AJAX requests on admin or public WordPress pages from a theme or plug-in. After a bit of searching I could not find the solution I was looking for – so I built my own, AHAX.

AHAX is a drop-in solution that allows theme or plug-in developers to take advantage of a very simple and streamlined way of making AJAX requests.

Live Example

My goal was to make the process of setting up an AJAX request simple as possible. Below is a (very) simple example where I use AHAX to get a random number from the server on user request.

...

Under The Hood

To create the example above I had to do two simple things. First, create the PHP function that handles the AJAX request in my theme’s function.php file and associate it with a specific AHAX action using ahax::bind(…). Second, create an instance of the AHAX JavaScript class and use its post method to make a request to the previously mentioned PHP function.

Back-End

PHP

1
2
3
4
5
6
ahax::bind( 'get_random_number', 'generate_number' );
function generate_number($output) {
  $max = abs( ( int ) $_POST['max'] );
  $output = mt_rand( 0 , ( $max < = 1000 ? $max : 1000 ) );
  return $output;
}

Front-End
JavaScript

1
2
3
4
var ahax = new AHAX();
ahax.post('get_random_number', {max:1000}, function(response) {
  jQuery('#ahax_number').html(response);
});

Breaking It Down

With this plugin I’ve attempted to make the process of creating an AJAX request as simple as possible by centering everything around an action.

The Action

In the code example above get_random_number is the action of the AHAX request. The static method ahax::bind(…) is used to create a WordPress filter that corresponds to the JavaScript ahax.post(…) method’s first argument.

A valid action is only allowed to consist of a-z, A-Z, and underscore ( _ ) characters.

(more…)