April 26, 2009

super cheap VPS hosting

I just read this post on hacker news and there are a couple links on some suspiciously low hosting services.

Check out:
http://www.lowendbox.com/

I think this is the recommended one:
http://www.prgmr.com/xen/

If anyone tries it, let me know how it goes please.

code highlighting with javascript

I didn't think I'd write two posts in one day, but after trying for an hour to get this to work, I thought I better put this up.

If you want to write code in your blog post and have it nicely colored there are javascript libraries that will do this for you. I've chosen Alex Gorbatchev's Syntax Highlighter.

Here is how to get it to work.

In the <head> element of your HTML, you need to add this:
<link href="http://alexgorbatchev.com/pub/sh/1.5.1/styles/SyntaxHighlighter.css" rel="stylesheet" type="text/css">


For Blogger ppl, this means going to Layout, then Edit HTML, then inserting the above right before the tag.

Then before the </body> tag, insert:
<script language="javascript" src="http://alexgorbatchev.com/pub/sh/1.5.1/scripts/shCore.js">
<script language="'javascript'" src="'http://alexgorbatchev.com/pub/sh/1.5.1/scripts/shBrushRuby.js'/">
<script language="'javascript'">
dp.SyntaxHighlighter.BloggerMode();
dp.SyntaxHighlighter.HighlightAll('code');
</script>

This works for Ruby code but can be adjusted to add other languages. The different language scripts can be found here.

Also, there are different CSS styles that you can hook up and they are found here.

I basically followed this blog and used Alex's hosting.

Clearing the file upload field

I recently needed to add file upload functionality to a rails app and discovered that HTML doesn't let you clear the file upload field after you have selected a file (in the case where you suddenly changed your mind and decided not to upload anything).

So after searching for a while I found an answer and it isn't pretty. You have to pretty much replace the file upload field with a new one using javascript.

Here is a basic example using jQuery:

In the view:
<%= f.file_field :attachment %>
<%= link_to_function 'clear', clear_js(id, name) %>
where id and name should be the same as your file field. Right now, I'm trying to figure out a way of pulling this info out cleanly from the form builder but not having much progress.

In a helper:
# creates an equivalent file field and replaces the current one
def clear_js(id, name)
%Q[
var newButton = document.createElement("input");
$(newButton).attr("type","file");
$(newButton).attr("id", "#{id}");
$(newButton).attr("name", "#{name}");
$(newButton).attr("size", "30");
$("##{id}").replaceWith(newButton);
]
end
FYI, I read that you can't just alter the value of the field with something like $('input').value = ' ', and for a good reason - then someone could theoretically write a script to set the value to any file on your computer.