tag:refactormycode.com,2007:codespopularallPopular codesWed Nov 19 18:11:23 +0000 2008tag:refactormycode.com,2007:Code6092008-11-19T05:23:59+00:002008-11-19T18:11:23+00:00[Ruby] Caching Methods<p>Is it possible to cache methods in a manor similar to below? (non-RoR). I have a few ideas of how this may work but any suggestions would be great</p>
<pre>
class Something
def something_else
"Expensive operation"
end
cache_method :something_else, :for => 2.hours
end
inst = Something.new
# Empty cache
inst.something_else
# Primed cache
inst.something_else</pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Code6062008-11-18T12:33:54+00:002008-11-20T00:52:58+00:00[C] How to find max, min of three numbers?<p>I tried to use as less variables and less operators as possible.
<br />Please help to make the code better.</p>
<pre>int max = rand(); // or any init value
int min = rand(); // or any init value
int tmp = rand(); // or any init value
if (max < min) {
if (tmp < min) {
if (max < tmp) {
tmp = max;
max = min;
min = tmp;
}
else { // max < min && tmp < min && tmp <= max
max = min;
min = tmp;
}
}
else { // max < min && min <= tmp
min = max;
max = tmp;
}
}
else { // min <= max
if (tmp < min)
min = tmp;
else // min <= max && min <= tmp
if (max < tmp)
max = tmp;
}</pre>Tien Dungdungtn@gmail.comtag:refactormycode.com,2007:Code6132008-11-20T13:42:18+00:002008-11-21T06:12:09+00:00[Ruby] Similar virtual attributes and their getters/setter<p>My Publication class has a few very similar virtual attributes. Is there any way to unite their setter and getter methods?</p>
<pre>class Publication < ActiveRecord::Base
def publisher_name
self.publisher.name
end
def publisher_name=(name)
self.publisher = Publisher.find_or_create_by_name(name.strip) unless name.blank?
end
def organization_name
self.organization.name
end
def organization_name=(name)
self.organization = Organization.find_or_create_by_name(name.strip) unless name.blank?
end
end</pre>foxdemonermin@nomail.comtag:refactormycode.com,2007:Code6142008-11-20T22:09:32+00:002008-11-21T05:23:39+00:00[Ruby] Arrays, loops, strings...<p>Can this be done in one line?</p>
<pre>select = []
joins = []
%w[first second third forth].each{ |semester| joins << ":pdp_#{semester}_semester"; (1..5).each{ |n| select << "pdp_#{semester}_semesters.objetive_#{n} AS #{semester}_objetive_#{n}" }}
[select, joins].each { |x| x.join(', ') }</pre>Ceritiumceritium@gmail.comtag:refactormycode.com,2007:Code6102008-11-19T18:48:58+00:002008-11-21T07:53:19+00:00[Ruby] Shortest regular expression for matching a subdomain.<p>I have written this regular expression which matches any subdomain (consisting of only letters and digits) right below example.com (including the domain, e.g. test.example.com) but not <a href="http://www.example.com" target="_blank">www.example.com</a>. It works, but it is not very elegant.</p>
<pre>/(?<part>(w(?!ww)|w(?=www)|w(?=[a-z0-9]+ww)|ww(?=[a-z0-9]+w)|www[a-z0-9]+|[a-vx-z0-9])[a-z0-9]*)\.example\.com/</pre>troethomt.thomsen@judoo.dktag:refactormycode.com,2007:Code6122008-11-19T22:23:15+00:002008-11-20T16:22:15+00:00[C#] Check type is XML Serializable<p>I need a fast method to check to see if a type is XML Serializable, be that with the [Serializable] attribute or the IXmlSerializable interface. This is what I came up with. Can we make it better?</p>
<pre>/// <summary>
/// Test to see if the type can be XML serialized
/// </summary>
/// <param name="objectToTest"></param>
/// <returns></returns>
private static bool CanBeXmlSerialized(Type objectToTest)
{
Type[] interfaces = objectToTest.GetInterfaces();
bool containsIXmlSerializable = interfaces.Contains(typeof(IXmlSerializable));
return containsIXmlSerializable || objectToTest.IsSerializable;
}</pre>sbehnke.myopenid.comtag:refactormycode.com,2007:Code6072008-11-18T16:22:53+00:002008-11-18T16:22:53+00:00[Perl] Apache log file sorting<p>I have a huge amount of log files on my hard drive and regularly download more. All of the files end up in a single directory. The log file names contain UNIX timestamps. I wrote this script to execute in a given directory and then move the found files to a new path based on the UNIX timestamp. Each new directory is named after a year and the week of the year, e.g. 200801, the first week of 2008. (Actually, the month doesn't have a leading zero yet. I just realized.)</p>
<pre>#!/usr/bin/perl -w
use strict;
use Time::localtime;
use File::Find;
use File::Copy;
my $vmlogpath = $ARGV[0] or die "y'all didn't enter no arguments";
find(\&sortFile, $ARGV[0]);
sub sortFile {
if ( -f ) {
my $filename=$_;
$filename =~ /([0-9]{5,})/;
my $unixtime = $1 or print "Not a log file: $filename\n";
my $dirname=makeDirName($unixtime);
unless(-e "${ARGV[0]}/${dirname}/${filename}") {
my $path=makeDir($ARGV[0], $dirname);
moveFile($filename, $path);
print "$filename is the file name.\n";
print "$unixtime is the extracted unixtime.\n";
print "$dirname is the directory name.\n";
print "$path is the path.\n";
}
}
else { print "Not a plain file: $_\n"; }
}
sub moveFile {
my $tehfile=$_[0];
my $tehdir=$_[1];
move($tehfile, $tehdir) or die "Could not move files!\n$!";
return 1;
}
sub makeDir {
my $currentdir=$_[0];
my $newdir=$_[1];
my $newpath="${currentdir}/${newdir}";
unless (-d $newpath) {
mkdir($newpath,755) or die "mkdir failed for $newpath: $!\n"
}
return $newpath;
}
sub makeDirName {
my $tehunix=$_[0];
my $day_of_year=localtime(int($tehunix))->yday;
my $week_of_year=int($day_of_year / 7) + 1;
my $year=1900+localtime(int($tehunix))->year;
return $year . $week_of_year;
}</pre>hourbackhourback@gmail.comtag:refactormycode.com,2007:Code6082008-11-19T00:45:07+00:002008-11-19T00:48:25+00:00[JavaScript] Tab-Switching in jQuery<p>Is there a better way?</p>
<pre>## showcase.html [HTML]
<div id="showcase">
<ul class="nav">
<li><a href="#example" class="selected">Example</a></li>
<li><a href="#another">Another</a></li>
</ul>
<div class="first item" id="example">
This is the first item. By default it's shown.
</div>
<div class="item" id="another">
This is another item. By default it's hidden.
</div>
</div>
## showcase.css [css]
#showcase .item {
display: none;
}
#showcase .first {
display: block;
}
## showcase.js [javascript]
$(document).ready(function() {
var selected = $("#showcase .first"); // First is selected by default
$("#showcase .nav a").click( function() {
if($(this) != selected) {
$('#showcase .nav a.selected').removeClass('selected');
selected.hide();
selected = $($(this).attr('href'));
selected.show();
$(this).addClass('selected');
return false; // Stops link from jumping to the anchor
}
})
});</pre>Aupajopete@metanation.comtag:refactormycode.com,2007:Code6112008-11-19T21:53:29+00:002008-11-19T21:53:29+00:00[JavaScript] Serena Collage slideshow<p>Creating a slideshow in our crappy CMS, Collage (from Serena), using a simple doctype called 'slide'.
<br />Early version.</p>
<pre>## View [html]
<div id="slideshow" style="background:#FFF">
<h2 class="slideshowTitle">Around the World with Language</h2>
<nexus:component classid="nexus/components/AssetQuery" code="/System/Components/nexusComponents.jar" root="$node.path/slides" levelsdeep="0"
filter="A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate <= current timestamp)) AND ((A.ExpireDate >= current timestamp) OR (A.ExpireDate is null))" max="1" orderonmetadata="pageListPriority" orderbycode="1A">
<div id="slide0" name="slide" style="display:block;">
<h3 class="slideTitle">$node.contribution("title")</h3>
<div class="slideImage" width="30%">$node.contribution("image")</div>
<p class="slideCaption">$node.contribution("caption")</p>
</div>
</nexus:component>
<nexus:component classid="nexus/components/AssetQuery" code="/System/Components/nexusComponents.jar" root="$node.path/slides" levelsdeep="0"
filter="A.AssetType='slide' AND((A.StartDate is null) OR (A.StartDate <= current timestamp)) AND ((A.ExpireDate >= current timestamp) OR (A.ExpireDate is null))" skip="1" orderonmetadata="pageListPriority" orderbycode="1A">
<div id="slide$node.recordnumber" name="slide" style="display:none;">
<h3 class="slideTitle">$node.contribution("title")</h3>
<div class="slideImage" width="30%">$node.contribution("image")</div>
<p class="slideCaption">$node.contribution("caption")</p>
</div>
</nexus:component>
<p id="controls"><a href="javascript:prevslide()">Previous</a> <a href="javascript:nextslide()">Next</a></p>
</div>
## Javascript [javascript]
var slideNum = 0;
var slides = new Array();
slides = document.getElementsByName("slide");
function nextslide() {
if (slideNum < slides.length - 1) {
slides[slideNum + 1].style.display = 'block';
slides[slideNum].style.display = 'none';
slideNum++;
}
else {
slides[0].style.display = 'block';
slides[slides.length - 1].style.display = 'none';
slideNum = 0;
}
}
function prevslide() {
if (slideNum > 0) {
slides[slideNum - 1].style.display = 'block';
slides[slideNum].style.display = 'none';
slideNum--;
}
else {
slides[slides.length - 1].style.display = 'block';
slides[0].style.display = 'none';
slideNum = slides.length - 1;
}
}
</pre>tbesedatbeseda@gmail.comtag:refactormycode.com,2007:Code6032008-11-12T02:16:38+00:002008-11-12T19:17:03+00:00[Ruby] A simple factorial program.<p>I'm quite new to Ruby, and I'm currently reading "Why's (Poignant) Guide to Ruby." It's a great book.
<br />Anyway, I want this to do the same thing, WITHOUT recursion, but is there a way to do it without repeating the raise statement at the beginning and using blocks instead of for?</p>
<pre>def factorial( n )
if !(n.is_a? Integer)
raise ArgumentError, "argument must be a positive integer"
elsif n < 0
raise ArgumentError, "argument must be a positive integer"
end
factorial = 1
for i in 1...n
factorial *= i + 1
end
factorial
end
</pre>lordzoner.myopenid.commorgan.michael@me.comtag:refactormycode.com,2007:Code5982008-11-11T04:09:05+00:002008-11-18T04:53:30+00:00[PHP] remove http from url string<p>Ive made a function simply to remove the http string from a given url string.
<br />Kindly see my code below. and is there other way to make it better or make it short?
<br />Thanks</p>
<pre><?php
/*
E.g:
$s = 'http://google.com';
echo remove_http($s);
output: google.com
*/
function remove_http($url = '')
{
if ($url == 'http://' OR $url == 'https://')
{
return $url;
}
$matches = substr($url, 0, 7);
if ($matches=='http://')
{
$url = substr($url, 7);
}
else
{
$matches = substr($url, 0, 8);
if ($matches=='https://')
$url = substr($url, 8);
}
return $url;
}
</pre>armano.myopenid.combrainwired@gmail.comtag:refactormycode.com,2007:Code6012008-11-11T21:28:53+00:002008-11-12T17:56:53+00:00[Ruby] Condensing nested conditionals<p>The code below works, but feels a bit overly complex, and looks ugly. Any suggestions on how to condense it?</p>
<pre>## app/controllers/properties_controller.rb
class PropertiesController < ApplicationController
before_filter :authorise_action
private
def authorise_action
case action_name
when 'index', 'show', 'map_info_window'
# Allowed by anyone.
when 'new', 'create', 'edit', 'update', 'destroy'
if is_logged_out?
deny_access :notice => Phrases.login_required, :redirect_to => login_url
elsif is_landlord? or is_admin?
# Allowed.
else
deny_access :notice => Phrases.access_denied, :store_location => false
end
else
deny_access :notice => Phrases.not_public_yet, :store_location => false, :redirect_to => :back
end
end
end</pre>Nicknick@deadorange.comtag:refactormycode.com,2007:Code6002008-11-11T17:10:30+00:002008-11-11T23:34:42+00:00[C#] DirectoryInfo.CopyTo<p>Because the .NET Framework does not contain a function which allows you to copy a directory from one location to another, I thought I would write one:</p>
<p><a href="http://gatekiller.co.uk/Post/DirectoryInfo.CopyTo" target="_blank">http://gatekiller.co.uk/Post/DirectoryInfo.CopyTo</a></p>
<p>Please let me know what you think. Any refactorings to make the code more elegant would be much appreciated.</p>
<p>Cheers
<br />Stephen</p>
<pre>public static class DirectoryInfoExtensions
{
public static void CopyTo(this String Source, String Destination, Boolean Overwrite)
{
// Hold directory information
var SourceDirectory = new DirectoryInfo(Source);
var DestinationDirectory = new DirectoryInfo(Destination);
// Throw an error is the source directory does not exist
if (SourceDirectory.Exists == false) {
throw new DirectoryNotFoundException();
}
// Create the destination directory
if (DestinationDirectory.Exists == false) {
DestinationDirectory.Create();
}
// Loop through the files and copy them
var SubFiles = SourceDirectory.GetFiles();
for (int i = 0; i < SubFiles.Length; i++) {
var NewFile = Path.Combine(
DestinationDirectory.FullName,
SubFiles[i].Name
);
SubFiles[i].CopyTo(NewFile, Overwrite);
}
// Loop through the directories and call this function
var SubDirectories = SourceDirectory.GetDirectories();
for (int i = 0; i < SubDirectories.Length; i++) {
var NewDirectory = Path.Combine(
DestinationDirectory.FullName,
SubDirectories[i].Name
);
SubDirectories[i].CopyTo(NewDirectory, Overwrite);
}
}
}
var SourceDirectory = new DirectoryInfo(@"C:\Users\");
SourceDirectory.CopyTo(@"C:\Users_Backup\", true);</pre>GateKillerrefactormycode@gatekiller.co.uktag:refactormycode.com,2007:Code5972008-11-11T01:14:04+00:002008-11-11T05:14:29+00:00[C#] Strip Html Comments<p>Procedural style code to strip HTML comments. No attempt was made to make this code more OO/patterned base so it could be readable/maintainable. ;)</p>
<pre>public static class HtmlHelper {
public static string StripHtmlComments(string html) {
if (html == null) {
throw new ArgumentNullException("html");
}
if (html.IndexOf("<!", StringComparison.Ordinal) < 0) {
return html;
}
var cleanedHtml = new char[html.Length];
bool inHtmlComment = false;
bool inHtmlTag = false;
int cleanCount = 0;
for (int i = 0; i < html.Length; i++) {
char current = html[i];
if (!inHtmlComment && !inHtmlTag) {
if (current == '<') {
if (i + 1 < html.Length) {
char nextChar = html[i + 1];
if (nextChar == '!') {
inHtmlComment = true;
continue;
}
else {
if (IsEnglishLetter(nextChar)) {
inHtmlTag = true;
}
}
}
}
}
else if(inHtmlComment) {
if (current == '>') {
if (inHtmlComment) {
inHtmlComment = false;
continue;
}
}
continue;
}
else if (inHtmlTag) {
if (current == '>') {
inHtmlTag = false;
}
}
cleanedHtml[cleanCount++] = current;
}
return new String(cleanedHtml, 0, cleanCount);
}
private static bool IsEnglishLetter(char nextChar) {
return ('a' <= nextChar && nextChar <= 'z') || ('A' <= nextChar && nextChar <= 'Z');
}
}
//Unit Tests
[TestMethod]
public void NullStringReturnsThrowsArgumentNullException() {
try {
HtmlHelper.StripHtmlComments(null);
Assert.Fail();
}
catch (ArgumentNullException) {
}
}
[TestMethod]
public void EmptyStringReturnsEmpty() {
Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(string.Empty));
}
[TestMethod]
public void StringWithoutCommentReturnsSameString() {
string s = "This has <strong>No Comments</strong>!";
Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void StringWithOnlyCommentReturnsEmptyString() {
string s = "<!-- this go bye bye>";
Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithNonDashDashComment_ReturnsEmptyString() {
string s = "<! this go bye bye>";
Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void StringWithTwoConsecutiveCommentsReturnsEmptyString() {
string s = "<!-- this go bye bye><!-- another comment>";
Assert.AreEqual(string.Empty, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void CommentWithStringBeforeReturnsString() {
string s = "Hello<!-- this go bye bye -->";
Assert.AreEqual("Hello", HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void CommentWithStringAfterReturnsString() {
string s = "<!-- this go bye bye -->World";
Assert.AreEqual("World", HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithAngleBracketsButNotHtml_NotSripped() {
string s = "<$)*(@&$(@*>";
Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithCommentInterleavedWithText_RendersText() {
string s = "Hello <!-- this go bye bye --> World <!--> This is fun";
Assert.AreEqual("Hello World This is fun", HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithHtmlTags_DoesNotStripHtml() {
string s = "<strong>Hello</strong><!this go bye bye>";
Assert.AreEqual("<strong>Hello</strong>", HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithCommentInAttribute_DoesNotStripAttributeValue() {
string s = "<img alt=\"<!-- This should remain -->\" />";
Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithCommentInSingleQuotedAttribute_DoesNotStripAttributeValue() {
string s = "<img alt=\'<!-- This should remain -->\' />";
Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithCommentInNonQuotedAttribute_DoesNotStripAttributeValue() {
string s = "<p title=<!--Thisshouldremain-->Test</p>";
Assert.AreEqual(s, HtmlHelper.StripHtmlComments(s));
}
[TestMethod]
public void Html_WithCommentBetweenNonTagButLooksLikeTag_DoesStripComment() {
string s = @"<ç123 title=""<!bc def>"">";
Assert.AreEqual(@"<ç123 title="""">", HtmlHelper.StripHtmlComments(s));
}
</pre>Haackedhaacked@gmail.comtag:refactormycode.com,2007:Code5992008-11-11T12:30:41+00:002008-11-18T06:19:17+00:00[C++] Stream ADODB recordset into a buffer<p>Can we make the code between "START HERE" and "END HERE" faster? The code is iterating thru the rows and columns of an ADODB Recordset, using Microsoft's generated wrapper classes. I'm streaming it into a buffer as a big flattened string. Can we make the flattening go faster? Notice there is already a trick for turning the BSTRs into ANSI strings (I'm only dealing with ASCII chars). Anything else?</p>
<pre>// For faster converting of dates to strings
char* sLeadingZeroIntegerValues[] = {
"00","01","02","03","04","05","06","07","08","09",
"10","11","12","13","14","15","16","17","18","19",
"20","21","22","23","24","25","26","27","28","29",
"30","31","32","33","34","35","36","37","38","39",
"40","41","42","43","44","45","46","47","48","49",
"50","51","52","53","54","55","56","57","58","59"};
// For faster converting of dates to strings
char date_buf[20] = "XXXX-XX-XX XX:XX:XX";
// Just some non printable ascii chars, for delimiters
const string DataTable::SECTION_DELIMITER = "\1";
const string DataTable::ROW_DELIMITER = "\2";
const string DataTable::COL_DELIMITER = "\3";
const string DataTable::TABLE_DELIMITER = "\4";
const string DataTable::NAME_VALUE_DELIMITER = "\5";
void CDbInterface::LoadRecordsetIntoStreamAsBigString(
_RecordsetPtr& pRs, ostringstream& ostrm)
{
DataTable::TypeList types;
if (!pRs->EndOfFile)
{
int nColumns = pRs->Fields->GetCount();
// Column names
for (long i = 0L; i < nColumns; i++)
{
string name = (const char*) (_bstr_t) pRs->Fields->GetItem(i)->Name;
if (i != 0) ostrm << DataTable::COL_DELIMITER;
ostrm << name.c_str();
}
ostrm << DataTable::SECTION_DELIMITER;
// Column types
for (long i = 0L; i < nColumns; i++)
{
ADODB::DataTypeEnum dbType = pRs->Fields->GetItem(i)->GetType();
if (i != 0) ostrm << DataTable::COL_DELIMITER;
DataTableDataType type;
if (dbType == ADODB::DataTypeEnum::adVarWChar
|| dbType == ADODB::DataTypeEnum::adWChar)
{
type = DataTableDataType::String;
}
else if (dbType == ADODB::DataTypeEnum::adInteger)
{
type = DataTableDataType::Integer;
}
else if (dbType == ADODB::DataTypeEnum::adUnsignedTinyInt)
{
type = DataTableDataType::Bool;
}
else if (dbType == ADODB::DataTypeEnum::adDate)
{
type = DataTableDataType::Date;
}
ostrm << type;
types.push_back(type);
}
ostrm << DataTable::SECTION_DELIMITER;
// Load the rows and columns
int nRow = 0;
ADODB::FieldsPtr pFields = pRs->Fields;
char buf[80];
::SYSTEMTIME sysTime;
_variant_t var;
char* pBstr;
long nBstrLen;
DWORD time1 = ::GetTickCount();
while(!pRs->EndOfFile)
{
if (nRow != 0)
ostrm << DataTable::ROW_DELIMITER;
for (long i = 0L; i < nColumns; i++)
{
// For every column in every row... <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< START HERE
// Can we make this even faster?
if (i != 0)
ostrm << DataTable::COL_DELIMITER;
var = pFields->GetItem(i)->GetValue();
if (V_VT(&var) == VT_BSTR)
{
// Copy every other byte of the bstr into the stream.
// That's doing an ansi conversion w/o allocating unnecessary memory
pBstr = (char*) var.bstrVal;
nBstrLen = *(pBstr-4);
for (int i = 0; i < nBstrLen; i+=2)
{
ostrm << (char) pBstr[i];
}
}
else if (V_VT(&var) == VT_I4
|| V_VT(&var) == VT_UI1
|| V_VT(&var) == VT_I2
|| V_VT(&var) == VT_BOOL)
{
ostrm << itoa(((int)var),buf,10);
}
else if (V_VT(&var) == VT_DATE)
{
::VariantTimeToSystemTime(var,&sysTime);
memcpy(date_buf,itoa(sysTime.wYear,buf,10),4);
memcpy(date_buf+5,sLeadingZeroIntegerValues[sysTime.wMonth],2);
memcpy(date_buf+8,sLeadingZeroIntegerValues[sysTime.wDay],2);
memcpy(date_buf+11,sLeadingZeroIntegerValues[sysTime.wHour],2);
memcpy(date_buf+14,sLeadingZeroIntegerValues[sysTime.wMinute],2);
memcpy(date_buf+17,sLeadingZeroIntegerValues[sysTime.wSecond],2);
ostrm << date_buf;
}
// End of the part we're trying to make faster... <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< END HERE
else if (V_VT(&var) == VT_EMPTY
|| V_VT(&var) == VT_NULL)
{
if (types[i] == DataTableDataType::String)
{
ostrm << "";
}
else if (types[i] == DataTableDataType::Integer)
{
ostrm << DataTableNullInteger;
}
else if (types[i] == DataTableDataType::Bool)
{
ostrm << "0";
}
else if (types[i] == DataTableDataType::Date)
{
ostrm << "";
}
}
}
pRs->MoveNext();
nRow++;
}
}
ostrm << DataTable::FINAL_DELIMITER;
}
</pre>ctrager.blogspot.comctrager@yahoo.comtag:refactormycode.com,2007:Code6022008-11-11T22:53:23+00:002008-11-12T00:33:11+00:00[Haskell] Cat90<p>Rotates text given in stdin 90 degrees. </p>
<pre>main = do s <- getContents
putStr (unlines (reverse (rotate (lines s))))
rotate ls = if (maxLength ls) > 0 then (column ls) : (rotate (dropColumn ls))
else []
maxLength ls = (maximum (map length ls))
column ls = map wholeHead ls
dropColumn ls = map (drop 1) ls
wholeHead cs = if (null cs) then ' '
else (head cs)
</pre>jarkkojarkko.sakkinen@iki.fitag:refactormycode.com,2007:Code6052008-11-15T08:51:14+00:002008-11-15T08:51:14+00:00[Ruby] repeated code in rspec model test<p>how do i clean up this repeated code (Stock.create & Stock.new) in my rspec test</p>
<pre>describe Stock do
it "should be valid when new" do
stock = Stock.new(:symbol => 'GOOG')
stock.should be_valid
end
it "should be invalid when symbol is empty" do
stock = Stock.new(:symbol => '')
stock.should_not be_valid
end
it "should have symbol in all uppercase" do
stock = Stock.create(:symbol => 'GOOG')
stock.symbol.should equal(stock.symbol.upcase)
stock = Stock.create(:symbol => 'goog')
stock.symbol.should equal(stock.symbol.upcase)
end
end</pre>scottmotte.myopenid.comscott@scottmotte.comtag:refactormycode.com,2007:Code5782008-11-05T09:30:03+00:002008-11-13T21:13:57+00:00[Ruby] Re-use code for new and create actions<p>Hello,</p>
<p>I have a 'people' controller to control user accounts. I want to share as much code as possible between the 'new' and 'edit' actions. I've tried to DRY it up as much as I can but in doing that I fear I might have made it more complicated. In the controller code below, the two methods 'new' and 'edit' both display a template 'user_form.html.erb', where title and form action are changed accordingly. The 'new' method submits to 'create', and the 'edit' method submits to 'update'. Errors are redisplayed via saving the user object with errors in the hash.</p>
<p>I would be very grateful for and refactoring suggestions anyone might have!</p>
<p>Many thanks,
<br />Dave</p>
<pre>## Controller [ruby_on_rails]
class PeopleController < ApplicationController
before_filter :clean_attributes, :only => [:create, :update]
# show the form to create a new user
def new
if flash[:user_with_errors]
@user = flash[:user_with_errors]
else
@user = User.new
end
show_user_form('add user', 'create')
end
# show the form to edit an existing user
def edit
if flash[:user_with_errors]
@user = flash[:user_with_errors]
else
@user = get_user(params[:id])
end
if @user
show_user_form('edit user', 'update')
else
flash[:error] = 'user not found'
redirect_to(root_path)
end
end
# this is the target of the 'new' action
def create
if request.post?
user = User.new
save_user(user)
redirect_to(:action => 'new')
end
end
# this is the target of the 'edit' action
def update
if request.post?
if user = get_user(params[:id])
save_user(user)
redirect_to(:action => 'edit', :id => params[:id])
else
flash[:error] = 'user not found'
redirect_to(root_path)
end
end
end
private
# before filter to remove unwanted whitespace
def clean_attributes
begin
[:forename, :surname, :email].each do |attribute|
params[:user][attribute].squish! if params[:user][attribute]
end
rescue
end
end
# show the user form (for new or edit actions)
def show_user_form(title, action)
@form_title = title
@action = action
render :action => 'user_form'
end
# save submitted user details
def save_user(user)
user.attributes = params[:user]
# set administrator only attributes
if current_user_is_admin?
user.login = params[:user][:login]
end
if user.save
flash[:success] = 'user saved successfully'
else
# blank out password for redisplay
user.password = nil
user.password_confirmation = nil
flash[:error] = 'save failed'
flash[:user_with_errors] = user
end
end
# get the user object
def get_user(id)
begin
user = User.find(id)
rescue ActiveRecord::RecordNotFound
logger.error("Attempt to access user id that doesn't exist (id: #{id})")
end
user
end
end</pre>Davepastelvasco@gmail.comtag:refactormycode.com,2007:Code5792008-11-05T12:14:53+00:002008-11-06T11:31:11+00:00[C#] Sorting by dependencies<p>This code sorts a collection by the dependencies of its contents.</p>
<p>It is passed a dictionary mapping a key to a set of keys - the dependencies of that key.</p>
<p>I knocked up this code quickly and realised as I wrote it that it was likely to blow the stack on a large data set due to its recursive nature. I'd try to make it tail recursive, but the C# compiler doesn't take advantage of that yet, so it should probably be iterative. I'd be interested to see any improved solution.</p>
<p></p>
<pre>public static class DependencySorter<T>
{
public static IEnumerable<T> Sort(Dictionary<T, IEnumerable<T>> dependencies)
{
var visited = new Dictionary<T, bool>();
foreach (var key in dependencies.Keys)
{
visited[key] = false;
}
foreach (var key in dependencies.Keys)
{
foreach (var ordered in Search(key, dependencies, visited))
yield return ordered;
}
}
private static IEnumerable<T> Search
(
T key,
IDictionary<T, IEnumerable<T>> dependencies,
IDictionary<T, bool> visited
)
{
if (!visited[key])
{
visited[key] = true;
foreach (T value in dependencies[key])
{
foreach (var ordered in Search(value, dependencies, visited))
{
yield return ordered;
}
}
yield return key;
}
}
}</pre>rikkusrik@rikkus.infotag:refactormycode.com,2007:Code5812008-11-06T22:29:37+00:002008-11-07T03:17:55+00:00[Ruby] Pretty output of permission bits for a file<p>This snippet is designed to match the permission bits output of an ls -l command for a shell replacement written in Ruby.</p>
<pre># [user@host ~]$ ls -l blah
# -rwxr--r-- 1 user users 0 2008-11-06 15:20 foo
def convert(file)
output = [""]
File.stat(file).mode.to_s(8).slice(-3..-1).split('').each do |m|
case m.to_i
when 1 then output << ["-","-","x"]
when 2 then output << ["-","w","-"]
when 3 then output << ["-","w","x"]
when 4 then output << ["r","-","-"]
when 5 then output << ["r","-","x"]
when 6 then output << ["r","w","-"]
when 7 then output << ["r","w","x"]
end
end
output.flatten!
if File.directory?(file) then output[0] = "d"; end
if File.file?(file) then output[0] = "-"; end
if File.symlink?(file) then output[0] = "l"; end
if File.setuid?(file) then output[3] = "s"; end
if File.setgid?(file) then output[6] = "s"; end
if File.sticky?(file)
if output[3] && output[6] == "-"
output[9] = "T"
else
output[9] = "t"
end
end
puts output.flatten.to_s
end
convert('poop')</pre>ScriptFuscriptfu@gmail.comtag:refactormycode.com,2007:Code5772008-11-05T07:13:41+00:002008-11-05T16:12:09+00:00[Ruby] xml rss feed<p>Looking for a better way to define the xml.description node...which needs html embedded as CDATA, but I think it is ugly concating this way with "+".</p>
<p>Generates a description and a link at the bottom.</p>
<p></p>
<pre> for directory in @directories
xml.item do
xml.title "#{directory.name} (PR #{directory.pagerank})"
//cleaner proc here?
xml.description { xml.cdata! simple_format(directory.description) + simple_format(link_to directory.software.name, software_url(directory.software)) }
xml.pubDate directory.created_at.to_s(:rfc822)
xml.link directory_url(directory)
xml.guid directory_url(directory)
end
end
</pre>chovy.myopenid.comspam@chovy.comtag:refactormycode.com,2007:Code5802008-11-06T07:01:36+00:002008-11-07T00:52:45+00:00[Ruby] View refactoring<p>In following code ul getting repeat after showing 3 feed items in the li.</p>
<pre>## List.rhtml [html_rails]
<ul>
<% if @feeds[16..19] %>
<% @feeds[16..19].each do |feed| -%>
<li style="width:170px">
<input name="source[<%=feed.id %>]" type="checkbox" value="<%=feed.id %>" "checked" />
<%=feed.name %>
</li>
<% end -%>
<% end -%>
</ul>
<ul>
<% if @feeds[20..23] %>
<% @feeds[20..23].each do |feed| -%>
<li style="width:170px">
<input name="source[<%=feed.id %>]" type="checkbox" value="<%=feed.id %>" "checked" />
<%=feed.name %>
</li>
<% end -%>
<% end -%>
</ul></pre>DGdeepak.gole8@gmail.comtag:refactormycode.com,2007:Code5822008-11-07T04:41:48+00:002008-11-07T05:48:19+00:00[Ruby] Retrieve class name only<p>Im sure there is a better way to do below:</p>
<pre>
# Suppose I have San::Languages::JavaScript as the 'lang' local var below
# I want a string of 'JavaScript' from this example
p lang.class.to_s.split('::')[2]
# => JavaScript</pre>Tj Holowaychuktj@vision-media.catag:refactormycode.com,2007:Code5652008-10-27T22:00:49+00:002008-10-28T14:52:14+00:00[Ruby] route spec'ing<p>I'm trying to extract a pattern from rails routes rspec'ing into a helper. </p>
<p>The helper works great and makes it nice to read/write routing specs (only for :get right now) such as shown below.
<br />But the "interpreted_route_path" part really sucks. Any better ways?</p>
<pre>## This part is ugly!
>> path
=> "/:foo/bar/:baz"
>> params
=> {:foo=>"FOO", :baz=>"BAZ"}
>> path.split("/").map { |v| (params[v[1,v.length].to_sym] if !v.empty? && v[0] == ':'[0]) || v }.join('/')
=> "/FOO/bar/BAZ"
>>
## in spec/spec_helper.rb
def interpreted_route_path(path, params)
path.split('/').map { |v| (params[v[1,v.length].to_sym] if !v.empty? && v[0] == ':'[0]) || v }.join('/')
end
# To check map.root:
# use as: check_routing_for(:route_name => 'root', :route_path => '/', :controller => 'foo', :action => 'bar')
def check_routing_for(options)
route_name = options.delete(:route_name)
route_path = options.delete(:route_path)
controller, action = options.delete(:controller), options.delete(:action)
class_eval do
describe "map.#{route_name}" do
before do
@route_hash = { :controller => controller, :action => action }.merge(options)
end
it "Routes to #{route_path}" do
route_for(@route_hash).should == interpreted_route_path(route_path, options)
end
it "Recognizes #{@route_hash.inspect}" do
params_from(:get, interpreted_route_path(route_path, options)).should == @route_hash
end
end
end
end
</pre>hellekinhellekin@gmail.comtag:refactormycode.com,2007:Code5752008-10-31T20:52:05+00:002008-11-03T05:46:13+00:00[Ruby] DRY up a controller action<p>My Neighbourhood "map_filter" action finds Property objects that match search criteria submitted by the user. It works, but I reckon it could be a bit shorter. Any suggestions?</p>
<pre># GET /neighbourhoods/map_filter
def map_filter
@map_filter_errors = nil # Stores errors related to a filter request.
@properties = nil # Stores the properties that match the filter constraints.
# Extract the "accessible" attributes from the params.
property_filter_attributes = AccessibleModelAttributes.extract PropertyFilter, params
filtered_properties = PropertyFilter.new(property_filter_attributes).properties
# If properties were returned.
if filtered_properties[:properties]
@properties = filtered_properties[:properties]
@property_data = render_to_string(
:partial => 'properties/map_properties_table',
:locals => {:properties => @properties}
)
@number_of_properties_found_sentence = render_to_string :partial => 'properties/number_of_properties_found'
else
@map_filter_errors = filtered_properties[:errors]
end
end
</pre>Nicknick@deadorange.com