Category Archives: refactormycode

RefactorMyCodeBook.com

FollowersYou can now follow people on RefactorMyCode.com. Wow it’s like FaceBook + code snippets! Better get your mom an account!

You’ll then have a page with all stuff posted by your new friends and even an Atom feed.

To follow someone, simply go to their profile page and click on “Follow this user”.

Hope you like it!

2 Comments

Filed under refactormycode

Defensio launched

Remember my Defensio plugin ? It is used on RefactorMyCode to keep the site clean of any spam and the users happy.

Defensio(hit refresh if you don’t see the new site) is now public, so you can get an API key in seconds and get to speed with my plugin in milliseconds (or less).

Congrats to the Karabunga guys!

Here’s a screenshot of my stats window:

Defensio Stats

Pretty cool!

And you can also subscribe to a feed, so you get notifications of spam in your feed reader.

11 Comments

Filed under montreal, rails, refactormycode

Upcoming BarCamp and Montreal on Rails

BarCampNext BarCampMontreal is this weekend, November 3rd, I’ll be giving a short presentation on RefactorMyCode.com. I’ll also be giving away a free special and unique gift to celebrate RmC success and announcing a new secret feature, be there!

Montreal on Rails is next week, November 6th, I won’t be giving a presentation on anything, but lots of interesting people will.

There’s also a conference on castle system in Christianity, November 5th, in Madurai, India.

See you there!

Update: I can’t make it to India for the 5th, sorry!

2 Comments

Filed under conference, montreal, refactormycode

Gravatar caching plugin

Gravatar is slow.

You use Gravatar on your site.

Your site is slow.

We hate slow site.

Caching is fast.

Cache Gravatars on your site.

Your site is fast!

Get it!

script/plugin install http://code.macournoyer.com/svn/plugins/gravatar_cache

Or using piston:

piston import http://code.macournoyer.com/svn/plugins/gravatar_cache vendor/plugins/gravatar_cache

Place something like this in your Rakefile:

def gravatar_emails
  User.find(:all).collect(&:email) # Return the emails you wanna cache
end

Now put everything in place for showtime:

rake gravatar:setup

Cache it!

rake gravatar:cache

You might wanna run this in a cron job, here’s mine:

0 */3 * * * cd /var/www/refactormycode/current && /usr/local/bin/rake gravatar:cache RAILS_ENV=production

Caches it every 3 hours.

Now in your view (or helper):

image_tag Gravatar.new('an@email.com').url

Magic!

Page caching friendly

It should be optimized for really high traffic sites as there’s no hole in the caching process (there’s always a cached version and no chance that someone hits a semi-downloaded file). It is page caching friendly as the url to the image won’t change when it’s cached or not (always /images/gravatars/MD5_OR_YOUR_EMAIL.gif).

Warning

You might have guessed that using a different filename for each Gravatar won’t save you any bandwidth. Even if two images are the same, a different symlink will be created for each, causing a new request for each Gravatar (empty or not). I’d suggest not using this plugin if you’re concerned about bandwidth.

Hope this is helpful to anyone else then me. It was extracted from RefactorMyCode.com. Thanks to Daniel (code) and Matthew Hutchinson (code) for inspiration.

Digg it !

Update: I just found out that Gravatar was bought by Automattic, makers of Worpress. Here’s the news from their blog, TechCrunch, Mashable and Techmeme.

3 Comments

Filed under rails, refactormycode

Refactoring of the week

Since last week I pushed a whole lot of new features to RefactorMyCode:

  • Email notification when a new refactoring is posted
  • Edit your refactoring
  • More caching to make page loading über fast
  • Make popular page sort by week first, so old stuff doesn’t stay on top
  • Add an alternative OpenID in case your main one is down (set it in your account page)

One of the most popular code this week was posted by Frank Lamontagne from Ruby Fleebie and TimmyOnTime. He cross posted his last edition of the famous Rubyize this to RmC while using the trackback feature (allowing to send a trackback to your blog on each refactoring being made on the code). The idea of a Rubyize this is that he post a code that is poorly written on purpose and ask his readers to refactor it. Seeing the success of the 2 first editions was a trigger in my idea of building RmC. The results are always amazing in quality and diversity.

Here’s the code he posted:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def remove_insults(input)
   ctr = 0
   input.each do |word|
     word = word.downcase
     if word == "stupid" || word == "moron" || word == "dumbass" || word == "retard"
       i=0
       word.length.times do
          input[ctr][i,1] = "*"
          i+=1
       end
     end
     ctr += 1
   end

   puts input.join(" ").to_s
end

remove_insults "you truly are a moron sir!".split(" ")

Small_logo

Ugly no?

Not anymore, thanks to Jorel, Frank, Scott, Daniel and hungryblank who refactored it to:

1
2
3
4
5
def remove_insults(sentence)
  sentence.gsub(/stupid|moron|dumbass|retard/i) { |insult| '*' * insult.size }
end

puts remove_insults("you truly are a 'Stupid' moron, stupid sir!")

Shorter, faster, better! No this is not a Kanye West song, it’s beautiful code!

Leave a comment

Filed under refactormycode, ruby

Refactoring of the week

RefactorMyCode.com has now been (publicly) live for a week. It was amazing! Who would have though a simple site like this could attract more then 100 000 visits in a week ?

But what surprises me the most is how much the community is alive and healty. I haven’t had any spam really yet, well maybe 3-4. And 3 other posts from people saying “you suck”. But most of the time when people get upset in there, they apologies right after and people are really thankful when they get help, amazing! How different from forums and websites where people tell you to search or RTMF before thinking about helping you ? But RefactorMyCode is not for support anyway, it’s for challenging the mind ratter then fixing problems. Hackers like solving small well defined problems, I think that’s why the site is so successful.

To celebrate RmC first week anniversary I’d like to highlight one of the refactoring from this week.

Chris Lamothe submitted this one: Beautify JS Date to how recently the event occured.

This adds a .when() method to Date() object allowing you do things such as “Posted ” + someDate.when() + ” ago.” and get output such as “Posted 10 minutes ago.” I’ve refactored it twice but would like to see it even smaller.

1
2
3
4
5
6
7
8
9
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
/***
* Beautify date to how recent the event occurred compared to now.
* Some examples:  1 second, 4 hours, 10 days, 1 year.
*	Example:
*   var oneFiftyMin = new Date(new Date().getTime() - 60000 * 150);
*   alert(oneFiftyMin.when()); // will display "2 hours"
*
*  Handy for things like "Item posted " + someDate.when() + " ago."
*/
Date.prototype.when = function() {

	var diff = new Date().getTime() - this.getTime();
	var when; // our return value

	//TODO:  what if the time is in the future? 
	//if (diff < 0) throw new Error ("Date is in future, check timezone?";

	//one or more of these will be non-zero, but we only care about the biggest one (in scale of time)
  var secondsOld = Math.floor(diff / 1000);
  var minutesOld = Math.floor(diff / 60000);
  var hoursOld   = Math.floor(diff / 3600000);
  var daysOld    = Math.floor(diff / 86400000);
	var monthsOld  = Math.floor(diff / 2592000000);
	var yearsOld   = Math.floor(diff / (2592000000 * 12));  //your content is old!

	//determine which value is non-zero and assign appropriate text
  if (yearsOld > 0) {
		when = yearsOld + " year";
  }
  else if (monthsOld > 0) {
		when = monthsOld + " month";
  }
  else if (daysOld > 0) {
		when = daysOld + " day";
  }
  else if (hoursOld > 0) {
		when = hoursOld + " hour";
  }
  else if (minutesOld > 0) {
		when = minutesOld + " minute";
  }
  else {
		when = Math.round(diff /1000) + " second";
	}

	//add plural if necessary
	return (0 == when.indexOf("1 ")) ? when : when + "s";
} 

Small_logo

With the help of typefreak, Andre Steenveld and Tomasz Kołodziejski they finally end up with this code, that does exactly the same thing in less then one-third the line count.

1
2
3
4
5
6
7
8
9
10
11
12
Date.prototype.when = function(){
        var diff = (new Date() - this)/1e3,
        u = [ "second", "minute", "hour", "day", "weeks", "month", "year" ],
        s = [ 1, 60, 60, 24, 7, 4.333, 12, 1e9], // again fast hack - 1e9
        i=0;

        for(;;i++){
                if((diff/=s[i])<1){
                        return ~~(diff*=s[i])+' '+u[i-1]+(diff>1?'s':0);
                }
        }
}

Small_logo

What can you say ? WOW !

Thanks to all people who’ve taken the time to write me an email to report a bug, suggestion or simply to say thanks, it means a lot to me!

7 Comments

Filed under js, refactormycode

Ouch! You broke my site

When James asked me if he could send RefactorMyCode to Digg, I said: sure. After all I spent lot of time on caching parts of the site so it would be fast. Ben and Fred also helped me spread the word with their networking ninja skills. By the time I went home that day it gained 30-40 diggs, but disappeared on the other link sites (reddit and ycomb hacker news). The server had no problem handle the load.

I kept checking my stats until I fell asleep.

7 AM: Checking my site… Huh! Not responding…

Ouch

It’s on programming front page of Digg, Reddit and Delicious! 20 000 visits! My heart is pumping!

What can I do ?

I tried multiple things on my poor little 200 MB of RAM Dreamhost account. Whenever a new dispatcher process is started it’s killed right away due to the incredible number of simultaneous visits. I read some comments on Digg, damn those people are mean, :(. I make some coffee and realize the only solution it to put an index.html file at the root and turn Rails dispatching off. Doesn’t seem to work, I can’t even serve a static page! 15 minutes later it works! The home page shows the last snapshot of the live site I could take. And visits keep going through the roof, 30 000.

It was better then nothing and I think it was less frustrating for people to see at least the facing page.

On my way home I was pretty desperate that the only solution was to move everything to a new provider. That means it will be down until I can get an account and resetup the whole app (installation of Ruby gems for syntax highlithing require some black magic and lots of luck). That’s too long!

So there I was, yesterday night, trying to find a better solution with my site busting the 50 000 visits mark.

I was caching almost everything on the front page, but with fragment caching, the request had to go through ActionPack. What prevented me from using full page caching was the login and account link and the “Your submissions sidebar”. Each are specific to a user, so it’s impossible to cache those. But still, security is checked on the server. So I though: I can show everything and show/hide relevant links with javascript. This way everyone would have the same HTML and it could be cached. That’s what I did. You can check the HTML source of the page and see the trick. I’ll go into more details in a future post.

After all this, the site is now back online. Everything seems to be working well now. Even though the traffic is going down a little bit, I still got 5800 visits today (at 1PM).

Thanks to all the people who talked, commented or blogged about or digged/voted for RefactorMyCode! You made it happend (made it popular that is, not crashing it, that was only me)!

3 Comments

Filed under Misc, refactormycode