<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users856</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/856" rel="self"/>
  <title>Tien Dung</title>
  <updated>Mon Jan 26 08:19:27 -0800 2009</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor144569</id>
    <published>2009-01-26T08:19:27-08:00</published>
    <title>[JavaScript] On Split text into unordered list.</title>
    <content type="html">

&lt;pre&gt;$(document).ready(function(){
  var resultsMax = 15;

  $.get('test-data.txt', function(textData){
    var lines = textData.split('\n').slice(0, resultsMax);
    
    $.each(lines, function(i, line){
      var terms = line.split('|');
      
      $('#tagcloud').append(
        '&amp;lt;li value=&amp;quot;{index}&amp;quot;&amp;gt;&amp;lt;a href=&amp;quot;{url}&amp;quot; title=&amp;quot;{title}&amp;quot;&amp;gt;{title}&amp;lt;/a&amp;gt;&amp;lt;/li&amp;gt;'.replace(/{(.+?)}/ig, function(raw, key) {
          return { 
            index : resultsMax - i, 
            url   : terms[3], 
            title : terms[0]
          }[ key ] || raw;
      }));      
    });
    
    $('#tagcloud').tagcloud();
  });
});&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/712-split-text-into-unordered-list/refactors/144569" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor144540</id>
    <published>2009-01-26T01:22:46-08:00</published>
    <title>[JavaScript] On Check next option in select tag</title>
    <content type="html">&lt;p&gt;Simo refactoring is great. Just want to remove some code from checkNext function.&lt;/p&gt;

&lt;pre&gt;jQuery.fn.checkNext = function() {
  if (this.is(':selected')) {
    this.attr('selected', false);
    var next = this.is(':last-child') ? this.parent().children(':first') : this.next();
    next.attr('selected', true);
  }
}&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/716-check-next-option-in-select-tag/refactors/144540" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor117521</id>
    <published>2008-12-11T08:35:56-08:00</published>
    <title>[JavaScript] On Writing a loop to create a switch statment</title>
    <content type="html">

&lt;pre&gt;times = [
  null,
  '7:00AM ',
  '8:00AM ',
  '9:00AM ',
  '10:00AM ',
  '11:00AM ',
  '12:00PM ',
  '1:00PM ',
  '2:00PM ',
  '3:00PM ',
  '4:00PM ',
  '5:00PM ',
  '6:00PM ',
  '7:00PM '
]

var start_time = times[timeArray[0]] || 'error';&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/663-writing-a-loop-to-create-a-switch-statment/refactors/117521" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor78064</id>
    <published>2008-11-20T00:01:10-08:00</published>
    <title>[C] On How to find max, min of three numbers?</title>
    <content type="html">&lt;p&gt;Hi Eineki, please explain how it works?&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/606-how-to-find-max-min-of-three-numbers/refactors/78064" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code606</id>
    <published>2008-11-18T12:33:54-08:00</published>
    <updated>2011-11-08T20:49:03-08:00</updated>
    <title>[C] How to find max, min of three numbers?</title>
    <content type="html">&lt;p&gt;I tried to use as less variables and less operators as possible.
&lt;br /&gt;Please help to make the code better.&lt;/p&gt;

&lt;pre&gt;int max = rand(); // or any init value
int min = rand(); // or any init value
int tmp = rand(); // or any init value

if (max &amp;lt; min) {
  if (tmp &amp;lt; min) {
    if (max &amp;lt; tmp) {
      tmp = max;
      max = min;
      min = tmp;
    } 
    else { // max &amp;lt; min &amp;amp;&amp;amp; tmp &amp;lt; min &amp;amp;&amp;amp; tmp &amp;lt;= max
      max = min;
      min = tmp;
    }
  } 
  else { // max &amp;lt; min &amp;amp;&amp;amp; min &amp;lt;= tmp
    min = max;
    max = tmp;
  }
  
}
else { // min &amp;lt;= max
  if (tmp &amp;lt; min)
    min = tmp;

  else // min &amp;lt;= max &amp;amp;&amp;amp; min &amp;lt;= tmp
  if (max &amp;lt; tmp)
    max = tmp;
}&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/606-how-to-find-max-min-of-three-numbers" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor52401</id>
    <published>2008-10-06T22:23:45-07:00</published>
    <title>[JavaScript] On Small Javascript Code</title>
    <content type="html">&lt;p&gt;You can't do ||= in JavaScript&lt;/p&gt;

&lt;pre&gt;function getAnchor(default) {
  default = default || 'news';
  return document.location.toString().split( '#' )[1] || default;
};
&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/518-small-javascript-code/refactors/52401" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor52393</id>
    <published>2008-10-06T22:19:01-07:00</published>
    <title>[JavaScript] On Toggle "Check all / Uncheck all" with jQuery</title>
    <content type="html">&lt;p&gt;Use true/false instead of using &amp;quot;on&amp;quot;/&amp;quot;off&amp;quot; for .mode
&lt;br /&gt;For .text() I think you can set it according to mode value&lt;/p&gt;

&lt;pre&gt;    Q(&amp;quot;#toggler&amp;quot;).click(function() {
        var mode = this.mode;
        this.mode = !mode;

        Q(&amp;quot;form#the_form input.id&amp;quot;).each(function(){
            this.checked = mode;
        }); 

        Q(this).text(mode ? 'check all' : 'uncheck all');
        return false;
    });&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/520-toggle-check-all-uncheck-all-with-jquery/refactors/52393" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor50575</id>
    <published>2008-10-06T04:21:44-07:00</published>
    <title>[JavaScript] On Small Javascript Code</title>
    <content type="html">

&lt;pre&gt;// Don't know why you need hash &amp;gt; 0 and page.length &amp;gt; 1
// In case you don't need those conditions
var page = document.location.toString().split(&amp;quot;#&amp;quot;)[1];
LoadURL(page || 'news')

// In case you need them
var parts = document.location.toString().split(&amp;quot;#&amp;quot;);
LoadURL((parts[0].length &amp;gt; 0 &amp;amp;&amp;amp; parts[1].length &amp;gt; 1) ? parts[1] : 'news')&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/518-small-javascript-code/refactors/50575" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor28396</id>
    <published>2008-09-22T01:53:58-07:00</published>
    <title>[Ruby] On Cleaner Ruby</title>
    <content type="html">&lt;p&gt;@Adam: cool refactoring :D&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/498-cleaner-ruby/refactors/28396" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor28394</id>
    <published>2008-09-22T01:27:00-07:00</published>
    <title>[Ruby] On Conditional Assignment</title>
    <content type="html">&lt;p&gt;temp variable based version using inject function.&lt;/p&gt;

&lt;pre&gt;def square(number)
  return number**2
end

biggest_square = [1,4,3,5].inject(0){ |max, base| (temp = square(base)) &amp;gt; max ? temp : max }&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/500-conditional-assignment/refactors/28394" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor28381</id>
    <published>2008-09-22T00:01:09-07:00</published>
    <title>[Ruby] On Conditional Assignment</title>
    <content type="html">&lt;p&gt;Hi Daniel, can you ask Marc-Andre for comment on rating also. For me the reason or thinking behind a refactoring or a rating is more important than the code or the rating itself.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/500-conditional-assignment/refactors/28381" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor28375</id>
    <published>2008-09-21T22:31:37-07:00</published>
    <title>[Ruby] On Conditional Assignment</title>
    <content type="html">&lt;p&gt;Thanks Daniel. I found the last one is more readable and self-commenting. Nice refactoring.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/500-conditional-assignment/refactors/28375" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor28323</id>
    <published>2008-09-21T16:19:05-07:00</published>
    <title>[Ruby] On Conditional Assignment</title>
    <content type="html">&lt;p&gt;Don't know who vote 1 star for my &amp;quot;one line assignment using temp variable refactoring&amp;quot;. Please tell me why you think it's bad. As I said the original code is perfect for me. That refactoring is in case your concern is lines of code.&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/500-conditional-assignment/refactors/28323" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor28318</id>
    <published>2008-09-21T15:58:01-07:00</published>
    <title>[Ruby] On Conditional Assignment</title>
    <content type="html">&lt;p&gt;Refactor Amos King .max function version&lt;/p&gt;

&lt;pre&gt;def square(number)
  return number**2
end

biggest_square = [1,4,3,5].map{|base| square(base)}.max
&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/500-conditional-assignment/refactors/28318" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor28317</id>
    <published>2008-09-21T15:43:59-07:00</published>
    <title>[Ruby] On Conditional Assignment</title>
    <content type="html">&lt;p&gt;I prefer using temp variable for PERFORMANCE. For me, the # Alternative code is already clean and clear. &lt;/p&gt;

&lt;p&gt;If your concern is lines of code. Here is one line assignment using temp variable refactoring.&lt;/p&gt;

&lt;pre&gt;def square(number)
  return number**2
end

biggest_square = 0

[1,4,3,5].each do |base|
  (temp = square(base)) &amp;gt; biggest_square &amp;amp;&amp;amp; biggest_square = temp
end&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/500-conditional-assignment/refactors/28317" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor27778</id>
    <published>2008-09-21T00:13:30-07:00</published>
    <title>[Ruby] On require_dependency</title>
    <content type="html">&lt;p&gt;Thanks for your help guys :)&lt;/p&gt;

&lt;p&gt;I use require_dependency because it is used to reload source files on each request when in development mode.
&lt;br /&gt;&lt;a href="http://wiki.rubyonrails.org/rails/pages/RequireDependency" target="_blank"&gt;http://wiki.rubyonrails.org/rails/pages/RequireDependency&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Learn it from Rick's Beast forum
&lt;br /&gt;&lt;a href="http://github.com/courtenay/altered_beast/tree/master/config/initializers/concerns.rb" target="_blank"&gt;http://github.com/courtenay/altered_beast/tree/master/config/initializers/concerns.rb&lt;/a&gt;&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/496-require_dependency/refactors/27778" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor27750</id>
    <published>2008-09-20T23:57:43-07:00</published>
    <title>[Ruby] On Cleaner Ruby</title>
    <content type="html">&lt;p&gt;Man, you made your code over complicated and ugly.&lt;/p&gt;

&lt;p&gt;* Why you use class as a namespace?
&lt;br /&gt;* Why you create a function called xp_to_level and don't use it in your program?
&lt;br /&gt;* Why you don't reuse computation result from previous step?
&lt;br /&gt;* Why you name a function that no one can understand what does it mean without any comment? (what does xp stand for).&lt;/p&gt;

&lt;p&gt;Here is an equivalent program that is faster, clearer and shorter.&lt;/p&gt;

&lt;pre&gt;def equate(level)
  (level + 300 * (2 ** (level / 7.0))).floor
end

x = 0
(1...100).each do |level|
  puts(&amp;quot;level #{level}: #{(x/4).floor}&amp;quot;)
  x = x + equate(level)
end
&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/498-cleaner-ruby/refactors/27750" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor27707</id>
    <published>2008-09-20T23:34:59-07:00</published>
    <title>[Ruby] On Cleaner Ruby</title>
    <content type="html">

&lt;pre&gt;# Duplicated post, please help to delete&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/498-cleaner-ruby/refactors/27707" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Code496</id>
    <published>2008-09-18T01:08:56-07:00</published>
    <updated>2008-09-23T04:05:05-07:00</updated>
    <title>[Ruby] require_dependency</title>
    <content type="html">&lt;p&gt;Rails require_dependency usage&lt;/p&gt;

&lt;pre&gt;class Listing &amp;lt; ActiveRecord::Base
  require_dependency &amp;quot;listing/property_related&amp;quot;
  require_dependency &amp;quot;listing/price_related&amp;quot;
  require_dependency &amp;quot;listing/contact_related&amp;quot;
  require_dependency &amp;quot;listing/address_related&amp;quot;
  require_dependency &amp;quot;full_text_search/listing_config&amp;quot;
  ....
end
&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/496-require_dependency" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor17376</id>
    <published>2008-09-16T06:44:54-07:00</published>
    <title>[JavaScript] On Color elements by state of matter at temperature</title>
    <content type="html">&lt;p&gt;or using eval(..)&lt;/p&gt;

&lt;pre&gt;function state_classes(updateall) {
    var value = display.value * 1, tempcolor;
    var element, state, 
        validations = {
          &amp;quot;Unknown&amp;quot; : &amp;quot;!boil[i] &amp;amp;&amp;amp; !melt[i]&amp;quot;, 
          &amp;quot;Gas&amp;quot;     : &amp;quot;value &amp;gt; boil[i]&amp;quot;,
          &amp;quot;Liquid&amp;quot;  : &amp;quot;value &amp;gt; melt[i]&amp;quot;, 
          &amp;quot;Solid&amp;quot;   : &amp;quot;true&amp;quot;
        };

    for (var i = 1; i &amp;lt;= 118; i++) {
        tempcolor = updateall;
        element = element_ids[i];
        
        for ( state in validations ) 
         if ( validations.hasOwnProperty(state) &amp;amp;&amp;amp; 
              element.state !== state &amp;amp;&amp;amp;
              eval(validations[state]) )
         {
           tempcolor = true;
           element.state = state;
           break;
         }

        if (tempcolor) {
          if (wholetable.inverted)    
            element.style.backgroundColor = statecolors[1][element.state];
          else                        
            element.style.color = statecolors[0][element.state];
        }
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/492-color-elements-by-state-of-matter-at-temperature/refactors/17376" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor17352</id>
    <published>2008-09-16T00:52:57-07:00</published>
    <title>[JavaScript] On Color elements by state of matter at temperature</title>
    <content type="html">

&lt;pre&gt;function state_classes(updateall) {
    var value = display.value * 1, tempcolor;
    var element, state, states = [&amp;quot;Unknown&amp;quot;, &amp;quot;Gas&amp;quot;, &amp;quot;Liquid&amp;quot;, &amp;quot;Solid&amp;quot;];
    for (var i = 1; i &amp;lt;= 118; i++) {
        tempcolor = updateall;
        element = element_ids[i];
        
        for (var j = 0; j &amp;lt; state.length; j++) {
           state = states[j];
           if (element.state !== state) {
             if ( (state === &amp;quot;Unknown&amp;quot; &amp;amp;&amp;amp; !boil[i] &amp;amp;&amp;amp; !melt[i]) ||
                  (state === &amp;quot;Gas&amp;quot;     &amp;amp;&amp;amp; value &amp;gt; boil[i]) ||
                  (state === &amp;quot;Liquid&amp;quot;  &amp;amp;&amp;amp; value &amp;gt; melt[i]) ||
                  (state === &amp;quot;Solid&amp;quot;)
             {
                tempcolor = true;
                element.state = state;
                break;
             }
           }
        }        

        if (tempcolor) {
          if (wholetable.inverted)    
            element.style.backgroundColor = statecolors[1][element.state];
          else                        
            element.style.color = statecolors[0][element.state];
        }
    }
}&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/492-color-elements-by-state-of-matter-at-temperature/refactors/17352" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor15269</id>
    <published>2008-08-19T00:41:31-07:00</published>
    <title>[JavaScript] On Setting focus after alert</title>
    <content type="html">&lt;p&gt;Hi Daniel, &lt;/p&gt;

&lt;p&gt;I create a saveAndSet function to remove repetitions. Don't have time to test. Hope it work :)&lt;/p&gt;

&lt;pre&gt;function saveAndSet(obj, newValues) {
  var oldValues = {};
  for (var p in newValues) 
    if (newValues.hasOwnProperty(p)) {
      oldValues[p] = obj[p];
      obj[p] = newValues[p];
    } 
  return oldValues;
}

function msgFocus(msg, obj) {
    var oldValues = saveAndSet(obj, {onkeyup: null, onkeypress: null, onblur: null, onfocus: null });
        
    alert(msg);
        
    setTimeout(function() {
        obj.focus();
        saveAndSet(obj, oldValues);
    }, 50);
}&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/442-setting-focus-after-alert/refactors/15269" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor14563</id>
    <published>2008-08-06T14:07:58-07:00</published>
    <title>[Ruby] On showing records in Ascending or Descening order on click</title>
    <content type="html">&lt;p&gt;Hi DG,&lt;/p&gt;

&lt;p&gt;1) We should not put model data (User model) in session because:
&lt;br /&gt; - Session is used to hold only the TEMPORARY data between a specific user and our web app.
&lt;br /&gt; - Session data should be kept as small as possible. For most of the case the user_id is enough.
&lt;br /&gt; - Model data is PERSISTENT data and should be consistent with all views (from different users). 
&lt;br /&gt; - If we keep model data in session, each user will have a different copy of model data. It invalid the consistency.&lt;/p&gt;

&lt;p&gt;2) We should not put model-related code in controller. We can move them to model.rb file to keep controller slim :)
&lt;br /&gt;Another benefit of putting logic code in model is that you can test code more easier. 
&lt;br /&gt;You can &amp;quot;script/console&amp;quot; and try model's functions or write spec tests for them.&lt;/p&gt;

&lt;p&gt;3) Don't afraid database queries will slow down the app. Finding &amp;amp; sorting are the jobs of database system.&lt;/p&gt;

&lt;p&gt;Base on 3 points above I refactor your code as below. 
&lt;br /&gt;I use param variable params[:order_by] to guide the controller to sort @users by age_ascending, age_descending and salary_ascending.
&lt;br /&gt;Urls will look like:
&lt;br /&gt;/users?
&lt;br /&gt;=&amp;gt; show all users ordered by age DESC&lt;/p&gt;

&lt;p&gt;/users?order_by=age
&lt;br /&gt;=&amp;gt; show all user ordered by age ASC&lt;/p&gt;

&lt;p&gt;/users?order_by=salary
&lt;br /&gt;=&amp;gt; show all user ordered by salary ASC&lt;/p&gt;

&lt;pre&gt;class UsersController &amp;lt; ApplicationController
  def index
    @users = find_all_and_order_by(params[:order_by])
  end
end


# user.rb
class User &amp;lt; ActiveRecord::Base
  named_scope :order_by_age_descending,   :order =&amp;gt; &amp;quot;age DESC&amp;quot;
  named_scope :order_by_age_ascending,    :order =&amp;gt; &amp;quot;age ASC&amp;quot;
  named_scope :order_by_salary_ascending, :order =&amp;gt; &amp;quot;salary ASC&amp;quot;

  def self.find_all_and_order_by( field_name )
    case field_name
    when &amp;quot;age&amp;quot;
      User.order_by_age_ascending.all
    when &amp;quot;salary&amp;quot;
      User.order_by_salary_ascending.all
    default
      User.order_by_age_descending.all
    end
  end
end

# Now we can &amp;quot;script/console&amp;quot; and try User.find_all_and_order_by(&amp;quot;age&amp;quot;)&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/421-showing-records-in-ascending-or-descening-order-on-click/refactors/14563" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor14545</id>
    <published>2008-08-06T07:22:20-07:00</published>
    <title>[JavaScript] On Handling Keyboard Shortcuts in JavaScript</title>
    <content type="html">&lt;p&gt;My final attempt :)&lt;/p&gt;

&lt;pre&gt;/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 *
 * Refactored by Nguyen Tien Dung ( http://free-and-happy.blogspot.com )
 */
window.shortcut = (function () {

  var defaultOptions = {
    type      : 'keydown',
    propagate : false,
    disable   : 'input textarea',
    target    : document,
    keycode   : false
  };

  // Work around for Shift key bug created by using lowercase
  // as a result the shift+num combinationnation was broken
  var shiftNums = {
    '`':'~',    '1':'!',    '2':'@',    '3':'#',  
    '4':'$',    '5':'%',    '6':'^',    '7':'&amp;amp;',    '8':'*',  
    '9':'(',    '0':')',    '-':'_',    '=':'+',    ';':':',  
    &amp;quot;'&amp;quot;:'&amp;quot;',    ',':'&amp;lt;',    '.':'&amp;gt;',    '/':'?',   '\\':'|'
  };
	
  // Special Keys and their codes
  var specialKeys = {
    'escape'  :27,	'space'	:32,
    'return'  :13,	'enter'	:13,
    'pause'   :19,	'break'	:19,
    'insert'  :45,	'home'	:36, 
    'delete'  :46,      'end'   :35,

    'backspace'  :8,    'esc'         :27,    'tab'    :9,
    'scrolllock' :145,  'scroll_lock' :145,   'scroll' :145,
    'capslock'   :20,   'caps_lock'   :20,    'caps'   :20, 
    'numlock'    :144,  'num_lock'    :144,   'num'    :144,
    'pageup'     :33,   'page_up'     :33,    'pu'     :33,
    'pagedown'   :34,   'page_down'   :34,    'pd'     :34,

    'left':37,   'up':38,   'right':39,   'down':40,
    'f1':112,    'f2':113,   'f3' :114,    'f4' :115, 
    'f5':116,    'f6':117,   'f7' :118,    'f8' :119, 
    'f9':120,   'f10':121,   'f11':122,   'f12' :123
  };

  var modifierMapping = {
    ctrl   :'ctrl',     control :'ctrl',
    shift  :'shift',    alt     :'alt',
    option :'alt',      meta    :'meta'
  };
  
  var bindings = {};

  function triggeredInDisableTags(event, disableTags) {
    if (typeof disableTags !== 'string') return false; 

    var element = event.target || event.srcElement;
    if (element.nodeType === 3)
      element = element.parentNode;

    return (disableTags.toLowerCase().indexOf(element.tagName.toLowerCase()) &amp;gt;= 0) ? true : false;
  }
	
	
  function matching(combination, options, e) {
    var i, key, modifier;
    var want = {};
    var keys = combination.split('+');

    //Find Which key is pressed
    var code = e.keyCode || e.which;
    var char = { 188: ',', 190: '.' }[code] || String.fromCharCode(code).toLowerCase();

    var count = 0;
    for (i=0; i &amp;lt; keys.length; i++) {
      key = keys[i];
      modifier = modifierMapping[key];

      if (modifier) {
        want[modifier] = true;
        count++;
      } 
      else 
      if ( (key.length &amp;gt; 1 &amp;amp;&amp;amp; specialKeys[key] === code) ||
           (options.keycode === code) || (char === key) || 
           (e.shiftKey &amp;amp;&amp;amp; shiftNums[char] === key) ) 
        count++; 
    } // End for (..)
		
    return (
      keys.length  === count &amp;amp;&amp;amp;
      !!want.shift === !!e.shiftKey &amp;amp;&amp;amp;
      !!want.ctrl  === !!e.ctrlKey &amp;amp;&amp;amp;
      !!want.alt   === !!e.altKey &amp;amp;&amp;amp;
      !!want.meta  === !!e.metaKey
    );
  }

  // Return the function to be called at keypress
  function makeKeypressedFun( combination, callback, options ) {
    return function( e ) {
      e = e || window.event;

      if ( triggeredInDisableTags(e, options.disable) || 
           !matching(combination, options, e) ) return;

      callback(e);
      if( !options.propagate ) {
        e.stopPropagation &amp;amp;&amp;amp; e.stopPropagation();
        e.preventDefault &amp;amp;&amp;amp; e.preventDefault();
        e.cancelBubble = true;
        e.returnValue = false;
      }
    };
  }

	
return /*shotcut*/ {
  add: function(combination, callback, options) {
    options = options || {};

    for (var name in defaultOptions)
      if (!options.hasOwnProperty(name))
        options[name] = defaultOptions[name];
		
    var ele = options.target;

    if(typeof ele === 'string')
      ele = document.getElementById(ele);

    var func = makeKeypressedFun( combination, callback, options );
		
    bindings[combination.toLowerCase()] = {
      'callback' : func,
      'target'	 : ele,
      'event'    : options.type
    };

    //Attach the function with the event
    if (ele.addEventListener)
        ele.addEventListener(options.type, func, false); 
    else 
    if (ele.attachEvent)
        ele.attachEvent('on' + options.type, func); 
    else
      ele['on' + options.type] = func; 
  },

  //Remove the shortcut - just specify the shortcut and I will remove the binding
  remove: function(combination) {
    combination = combination.toLowerCase();
    var binding = bindings[combination];

    delete bindings[combination];

    if( !binding ) return;
		
    var type = binding.event;
    var ele = binding.target;
    var callback = binding.callback;

    if (ele.detachEvent)
        ele.detachEvent('on'+type, callback);
    else 
    if (ele.removeEventListener)
        ele.removeEventListener(type, callback, false);
    else
      ele['on'+type] = false;
  }	
};
})();
&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/402-handling-keyboard-shortcuts-in-javascript/refactors/14545" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor14162</id>
    <published>2008-07-31T02:05:35-07:00</published>
    <title>[Ruby] On two for loops cleanup?</title>
    <content type="html">&lt;p&gt;Shortest version :)&lt;/p&gt;

&lt;pre&gt;times -= events.map(&amp;amp;:datetime)&lt;/pre&gt;</content>
    <author>
      <name>Tien Dung</name>
      <email>dungtn@gmail.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/408-two-for-loops-cleanup/refactors/14162" rel="alternate"/>
  </entry>
</feed>

