tag:refactormycode.com,2007:refactoringsrecentall Recent refactorings Thu Nov 27 17:18:05 +0000 2008 tag:refactormycode.com,2007:Refactor88951 2008-11-27T17:18:05+00:00 [Ruby] On Displaying numbers to words. <p>Done ...cheers</p> <pre>require 'rubygems' require 'linguistics' class Fixnum def to_words word_translation_range = 1..1_000_000 if word_translation_range.include?(self) Linguistics::EN.numwords(self) else to_s end end end ra = 1..1_000_000 ra.each {|v| puts v.to_words}</pre> ytse.myopenid.com jaredtse@hotmail.com tag:refactormycode.com,2007:Refactor88941 2008-11-27T17:13:57+00:00 [Ruby] On Displaying numbers to words. <p>You want to print numbers from 1 to 1,000,000? Just do something like this:</p> <pre>1.upto(1_000_000) { |number| puts Linguistics::EN.numwords(number) }</pre> Adam skidooer+p@gmail.com tag:refactormycode.com,2007:Refactor88937 2008-11-27T17:10:29+00:00 [Ruby] On Displaying numbers to words. <p>Yes this is prety much what I want to do. But shouldnt the method go inside the Range class ? And also would you mind demonstrate on how to do the iteration from 1 - 1000000</p> <p>Thanx</p> <pre>require 'rubygems' require 'linguistics' class Fixnum def to_words word_translation_range = 1..1_000_000 if word_translation_range.include?(self) Linguistics::EN.numwords(self) else to_s end end end</pre> ytse.myopenid.com jaredtse@hotmail.com tag:refactormycode.com,2007:Refactor88811 2008-11-27T15:42:13+00:00 [Ruby] On Displaying numbers to words. <pre># http://www.deveiate.org/projects/Linguistics/ require 'linguistics' class Fixnum def to_words word_translation_range = 1..1_000_000 if word_translation_range.include?(self) Linguistics::EN.numwords(self) else to_s end end end</pre> Adam skidooer+p@gmail.com tag:refactormycode.com,2007:Refactor88479 2008-11-27T10:54:44+00:00 [Ruby] On Ruby simple loop <pre>name = 'nicholas' (1..10).each { |i| puts i,name } output 1 nicholas 2 nicholas 3 nicholas 4 nicholas 5 nicholas 6 nicholas 7 nicholas 8 nicholas 9 nicholas 10 nicholas </pre> Nicholas nicholas.domnic.i@gmailc.om tag:refactormycode.com,2007:Refactor88165 2008-11-27T02:15:57+00:00 [C#] On Filterting a List<> with a Regular Expression <p>Some advices : The way you are using the regular expression is equivalent to using the regular way to do a string comparaison. Also, I would suggest also to filter documents in your document layer by adding the name and author to your GetDocuments(username) method, I would be more efficient as your method can retrieve 500 documents from the database to finally display one or two results for exemple.</p> <pre>List&lt;Document&gt; aDocuments = documentLayer.GetDocuments(username); string docName = (string)Session[&quot;DocumentName&quot;]; string docAuthor = (string)Session[&quot;DocumentAuthor&quot;]; bool docNameEmpty = string.IsNullOrEmpty(docName); bool docAuthorEmpty = string.IsNullOrEmpty(docAuthor); if (docNameEmpty &amp;&amp; docAuthorEmpty) gridDocuments.DataSource = aDocuments; else { List&lt;Document&gt; aDocumentsFilter = new List&lt;Document&gt;(); aDocuments.ForEach(oDoc =&gt; { if ((!docNameEmpty &amp;&amp; !docAuthorEmpty &amp;&amp; docName == oDoc.Name &amp;&amp; docAuthor == oDoc.Author) || (docNameEmpty &amp;&amp; docAuthor == oDoc.Author) || (docAuthorEmpty &amp;&amp; docName == oDoc.Name)) aDocumentsFilter.Add(oDoc); }); gridDocuments.DataSource = aDocumentsFilter; } gridDocuments.DataBind();</pre> Moonshield monsterinthepit@hotmail.com tag:refactormycode.com,2007:Refactor88062 2008-11-26T23:24:45+00:00 [Java] On Factoring Integers <p>The two functions, nextFactor and has nextFactor shared the common pattern I refactored into the findNextFactor() private method. <br />You have obfuscated the while conditions a bit but I'm sure you can see that the loop laying after the two sligthy different syntax are the same.</p> <p>Once you get this, the two method get straight simple. <br />I added a runtime exception to cover the case of a call of nextFactor method without a previous check of hasNextFactor</p> <p>I hope you can get through my english to the explanation :)</p> <pre>## Quick Fix [Java] // line 44 while condition have to change to or you don't apply the last division (but return the last factor everytime) =&gt; number don't become 1 =&gt; hasnextfactor misbehave. while (factor &lt;= number) ## Refactoring [Java] public class factorGenerator { private int number; private int factor; /** * Creates a FactorGenerator object used to determine the factor of an input value. * @param aNum is the input value **/ public factorGenerator(int aNum) { number = aNum; factor = 2; } /** * Find the next factor of a value. * @return factor the next factor **/ private int findNextFactor() { while((factor &lt; number) &amp;&amp; ((number%factor)!=0)) factor++; return factor; } /** * Apply the next factor of a value. * @return factor the next factor **/ public int nextFactor() throws RuntimeException { int result = findNextFactor(); if (result &lt;= number) { number/= result; return result; } else throw new RuntimeException(); } /** Determine whether or not there are more factors. @return true there are more factors */ public boolean hasMoreFactors() { return (findNextFactor()&lt;=number); } }</pre> Eineki magisano@cs.unibo.it tag:refactormycode.com,2007:Refactor87989 2008-11-26T21:23:04+00:00 [C#] On Filterting a List<> with a Regular Expression <p>Might as well make this easier on yourself with LINQ. <br />Is there a reason you are using a regex? I threw the below together in LINQPad and it works...</p> <pre>//I just need some values to work with. var names = new[] { &quot;Tom&quot;, &quot;Dick&quot;, &quot;Harry&quot;, &quot;Hurry&quot;,&quot;Mary&quot;, &quot;Jay&quot; }.AsQueryable(); IEnumerable&lt;Document&gt; documents = from n in names select new Document { author = n, name = n.Replace (&quot;a&quot;, &quot;&quot;).Replace (&quot;e&quot;, &quot;&quot;).Replace (&quot;i&quot;, &quot;&quot;).Replace (&quot;o&quot;, &quot;&quot;).Replace (&quot;u&quot;, &quot;&quot;) }; documents.Dump(); System.Random r = new Random(); string documentName = r.Next(2) == 1 ? &quot;Hrry&quot;: &quot;&quot;; string documentAuthor = r.Next(2) == 1 ? &quot;Harry&quot;:&quot;&quot;; &quot;Name&quot;.Dump(documentName); &quot;Author&quot;.Dump(documentAuthor); //commented out this if else just for demo purposes. On the other hand //if ((string.IsNullOrEmpty(documentName)) &amp;&amp; (string.IsNullOrEmpty(documentAuthor))) // { //documents.DataSource = documents; //documents.DataBind(); // } // else //{ //this should be easier to read and more efficient: less accessing of properties, fewer lines, //fewer function calls, takes advantage of fewer comparisons due to &amp;&amp; IEnumerable filteredDocuments = from d in documents where d.name == (string.IsNullOrEmpty(documentName) ? d.name : documentName) &amp;&amp; d.author == (string.IsNullOrEmpty(documentAuthor) ? d.author : documentAuthor) select d; filteredDocuments.Dump(); //} } class Document { public string author; public string name; </pre> MattK openid@morelightmorelight.com tag:refactormycode.com,2007:Refactor87924 2008-11-26T19:45:27+00:00 [Ruby] On Doing a 'blank?' in named_scope <p>maybe work.</p> <pre>named_scope :with_description, :conditions =&gt; &quot;description IS NOT NULL and description NOT REGEXP '[[:blank:]]'</pre> kivanio kivanio@gmail.com tag:refactormycode.com,2007:Refactor84987 2008-11-25T08:18:52+00:00 [Java] On Efficiently load a text file into a sorted String Array <p>One disadvantage with your approach is that since Sets do not allow duplicate elements, duplicate lines will be lost.</p> <p>Alternatively, you could just add them to some kind of List (ArrayList or LinkedList will do) and then sort it.</p> <pre>public static String[] loadFile(final String f) { String thisLine; final List&lt;String&gt; s = new ArrayList&lt;String&gt;(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(f)); while ((thisLine = br.readLine()) != null) s.add(thisLine.trim()); } catch (IOException ioe) { System.err.println(&quot;Error reading file &quot; + f); throw new RuntimeException(ioe); } finally { if(br!=null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } } Collections.sort(s); return s.toArray(new String[s.size()]); }</pre> foo tag:refactormycode.com,2007:Refactor84535 2008-11-24T23:32:27+00:00 [C#] On Sanitize HTML <p>Here is an actual parser (written in PHP) that only accepts white listed input, <a href="http://refactormycode.com/codes/557-html-filter" target="_blank">http://refactormycode.com/codes/557-html-filter</a></p> <pre></pre> grom grom@zeminvaders.net tag:refactormycode.com,2007:Refactor83863 2008-11-24T10:54:17+00:00 [Ruby] On Cheap ruby block templating <p>Nice Adam. I'm ended up using the equivalent in Merb.</p> <pre>def row(&amp;block) tag :div, capture(&amp;block), :class =&gt; 'row' end</pre> Alistair alistairholt@gmail.com tag:refactormycode.com,2007:Refactor83430 2008-11-24T04:38:34+00:00 [Ruby] On Cheap ruby block templating <pre>def field_row(&amp;block) content_tag(:div, :class =&gt; :field_row, &amp;block) end</pre> Adam skidooer+p@gmail.com tag:refactormycode.com,2007:Refactor82560 2008-11-23T15:11:36+00:00 [PHP] On Eval encoded file decoder <p>can anyone help with a procedure of decrypting this:</p> <p></p> <pre>&lt;?php eval(strtr(strrev(' encoded text here ')); ?&gt;</pre> mrlame mrlame@mail.ru tag:refactormycode.com,2007:Refactor81169 2008-11-22T17:38:28+00:00 [Ruby] On Cheap ruby block templating <p>I believe it is the same now in Rails 2.2. I am unsure how it was different before 2.2.</p> <pre></pre> Jeff Berg jeff@ministrycentered.com tag:refactormycode.com,2007:Refactor81164 2008-11-22T17:34:22+00:00 [Ruby] On Cheap ruby block templating <p>That's cool thanks. I was previously using yield. What are the advantages/disadvantages of using yield over capture(&amp;block)?</p> <pre></pre> Alistair alistairholt@gmail.com tag:refactormycode.com,2007:Refactor81160 2008-11-22T17:29:16+00:00 [Ruby] On Cheap ruby block templating <p>That is the best way unless you are on Rails 2.2 (Which just got released). Check out this blog post: <a href="http://www.pathf.com/blogs/2008/10/rails-22-for-me-and-for-you/" target="_blank">http://www.pathf.com/blogs/2008/10/rails-22-for-me-and-for-you/</a></p> <pre> def label_block(caption) concat(&quot;&lt;label&gt;&quot;) concat(&quot;&lt;span&gt;#{caption}&lt;/span&gt;&quot;) yield concat(&quot;&lt;/label&gt;&quot;) end</pre> Jeff Berg jeff@ministrycentered.com tag:refactormycode.com,2007:Refactor81050 2008-11-22T15:48:37+00:00 [Ruby] On Bindings on caller <p>Cool thanks! not overly practical I suppose but still cool</p> <pre></pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Refactor80775 2008-11-22T11:12:26+00:00 [Ruby] On Bindings on caller <pre>def capitalize_args(bind) eval(&quot;local_variables&quot;, bind).each do |var| var = eval(var, bind) var.capitalize! if var.is_a?(String) var.map! { |arg| arg.is_a?(String) ? arg.capitalize : arg } if var.is_a?(Array) end end def test(a, b) capitalize_args(binding) puts a puts b end def test2(*args) capitalize_args(binding) puts args end test &quot;hello&quot;, &quot;world&quot; # =&gt; Hello # =&gt; World test2 &quot;hello&quot;, 1, &quot;world&quot; # =&gt; Hello # =&gt; 1 # =&gt; World</pre> Simo Niemelä simo.niemela@gmail.com tag:refactormycode.com,2007:Refactor79520 2008-11-21T15:33:06+00:00 [Perl] On Apache log file sorting <p>Modified the capitalization of subroutines.</p> <pre>#!/usr/bin/perl -w use strict; use Moose; use Time::localtime; use File::Find; use File::Copy; my $vmlogpath = $ARGV[0] or die &quot;y'all didn't enter no arguments&quot;; find(\&amp;sort_file, $ARGV[0]); sub sort_file { if ( -f ) { my $filename=$_; $filename =~ /([0-9]{5,})/; my $unixtime = $1 or print &quot;Not a log file: $filename\n&quot;; my $dirname=make_dir_name($unixtime); unless(-e &quot;${ARGV[0]}/${dirname}/${filename}&quot;) { my $path=make_dir($ARGV[0], $dirname); move_file($filename, $path); print &quot;$filename is the file name.\n&quot;; print &quot;$unixtime is the extracted unixtime.\n&quot;; print &quot;$dirname is the directory name.\n&quot;; print &quot;$path is the path.\n&quot;; } } else { print &quot;Not a plain file: $_\n&quot;; } } sub move_file { my $tehfile=$_[0]; my $tehdir=$_[1]; move($tehfile, $tehdir) or die &quot;Could not move files!\n$!&quot;; return 1; } sub make_dir { my $currentdir=$_[0]; my $newdir=$_[1]; my $newpath=&quot;${currentdir}/${newdir}&quot;; unless (-d $newpath) { mkdir($newpath,755) or die &quot;mkdir failed for $newpath: $!\n&quot; } return $newpath; } sub make_dir_name { my $tehunix=$_[0]; my $day_of_year=localtime(int($tehunix))-&gt;yday; my $week_of_year=int($day_of_year / 7) + 1; my $year=1900+localtime(int($tehunix))-&gt;year; return $year . $week_of_year; }</pre> hourback hourback@gmail.com tag:refactormycode.com,2007:Refactor79324 2008-11-21T12:17:13+00:00 [Ruby] On Shortest regular expression for matching a subdomain. <p>This ought to do it.</p> <pre>/^(?!www\.)(?:\w+\.)*example\.com$/</pre> Daniel Schierbeck daniel.schierbeck@gmail.com tag:refactormycode.com,2007:Refactor79246 2008-11-21T07:53:13+00:00 [Ruby] On Shortest regular expression for matching a subdomain. <p>I would maybe consider extending URI similarly to below. 'example' is technically a subdomain of the TLD 'com' so I would maybe allow that to have a param like below, just as well 'www' is still a valid subdomain of course so maybe that logic could belong in a different method</p> <pre>require 'uri' module URI class HTTP def domains host.split '.' end def tld domains.last end def subdomain(level = 1) domains[-(level + 1)] unless domains.length &lt; level + 1 end end end p URI.parse(&quot;http://something.example.com&quot;).domains p URI.parse(&quot;http://something.example.com&quot;).tld p URI.parse(&quot;http://something.example.com&quot;).subdomain p URI.parse(&quot;http://something.example.com&quot;).subdomain 2 p URI.parse(&quot;http://example.com&quot;).subdomain p URI.parse(&quot;http://example.com&quot;).subdomain 2 Outputs : [&quot;something&quot;, &quot;example&quot;, &quot;com&quot;] &quot;com&quot; &quot;example&quot; &quot;something&quot; &quot;example&quot; nil </pre> Tj Holowaychuk tj@vision-media.ca tag:refactormycode.com,2007:Refactor79245 2008-11-21T07:32:40+00:00 [C++] On Counting Sort <p>I did not understand why the code is categorized as C++ code. It is in C except the I/O functions. </p> <pre></pre> pardus1 tag:refactormycode.com,2007:Refactor79240 2008-11-21T06:12:08+00:00 [Ruby] On Similar virtual attributes and their getters/setter <pre>module NameAssociation def self.extended(object) object.instance_eval(&lt;&lt;-EOS, '(__NAME_ASSOCIATION__)', 1) def #{object.proxy_owner.to_s.downcase}_name=(name) find_or_create_by_name(name) end EOS end end class Publication &lt; ActiveRecord::Base has_one :publication, :extend =&gt; NameAssociation has_one :organization, :extend =&gt; NameAssociation delegate :name, :name=, :to =&gt; :publication, :prefix =&gt; true delegate :name, :name=, :to =&gt; :organization, :prefix =&gt; true end</pre> Adam skidooer+p@gmail.com tag:refactormycode.com,2007:Refactor79238 2008-11-21T05:55:58+00:00 [Ruby] On Similar virtual attributes and their getters/setter <p>removed string based class_eval in favor of define_method.. shorter code :)</p> <pre>module ChildAccessor def attr_child_accessor(obj,attr_name) child_name = obj.name.downcase method_name = &quot;#{child_name}_#{attr_name.to_s}&quot; class_eval do define_method method_name do self.send(child_name).send(attr_name) end define_method &quot;#{method_name}=&quot; do |name| self.send(&quot;#{child_name}=&quot;, obj.send(&quot;find_or_create_by_#{attr_name}&quot;, name.strip)) unless name.blank? end end end end ActiveRecord::Base.extend ChildAccessor class Publication &lt; ActiveRecord::Base attr_child_accessor Publisher, :name attr_child_accessor Orginization, :name end </pre> Josh N joshnuss@gmail.com