Archive for October, 2009

A Through Z

Posted 30 Oct 2009 — by admin
Category Ruby on Rails

How to print the alphabet in Rails very easily.

("A".."Z").each {|letter| link_to letter, "/#{letter"}
"A".upto("Z") {|letter| link_to letter, "/#letter"}

Fun with Apache2 – httpd not running, trying to start (98)Address already in use: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down

Posted 16 Oct 2009 — by admin
Category apache

Have you ever gotten this error message when trying to (re)start Apache

httpd not running, trying to start
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down

If you are running with an SSL certificate on your box, Apache cannot start up without the correct passphrase. I’ve run into this problem a couple times. Once when I rebuilt my virtual server from Mosso and the reboot process (obviously) required Apache to be started up when the machine came back up. Not being there when the start up phase required the correct passphrase Apache was up but not handling requests. The other time my server crashed when it ran out of memory. It was a 256 meg O’RAM box running a Rails app. Go figure!

Fortunately, there is an easy solution. Kill Apache and start it up again. If you’re in the console you’ll be prompted for the passphrase. Enter it correctly and everything will be fine. Here’s how I did it.

ps aux | grep apache
root      3948  0.0  0.2   4028   668 ?        S    17:48   0:00 /bin/sh -e /etc/rc2.d/S91apache2 start
root      3959  0.0  0.2   4028   616 ?        S    17:48   0:00 /bin/sh /usr/sbin/apache2ctl start
root      3964  0.0  2.4 133564  6472 ?        S    17:48   0:00 /usr/sbin/apache2 -k start
root      4069  0.0  0.2   6268   660 pts/0    R+   17:49   0:00 grep apache

I took at a look at the running processes and grep for apache. The one I wanted was the 2nd to last.
Look for the process id and kill it with the -9 option. The process id will be in the second column to the left

kill -9 3964

After it’s dead you can restart Apache like so

apache2ctl start

You’ll get the prompt for the passphrase. Enter it and everything should be fine.

Rails Paperclip Plugin Options for Attaching Files

Posted 15 Oct 2009 — by admin
Category Ruby on Rails

I usually change some of the default settings when I use the Paperclip plugin. For most of my projects I don’t like having separate directories for each image that is uploaded. I prefer, in this instance, to put avatars of different sizes together under one directory and differentiated based on the style size of the image. To do this just set the path and url options like so…

  has_attached_file :avatar,
    :styles => {:thumb => "75x75", :medium => "150x150", :large => "500x500"},
    :default_url => "/images/default_avatar.png",
    :url => "/system/avatars/:id/:style_:basename.:extension",
    :path => ":rails_root/public/system/avatars/:id/:style_:basename.:extension"

Also, when you set up the database your model will need to have the following columns for Paperclip to work properly

      t.column :avatar_file_name, :string
      t.column :avatar_content_type, :string
      t.column :avatar_file_size, :integer

Don’t forget that to handle file uploads in Rails you need to set the form with

form_for current_user, :html =>{:multipart => true} do |f|

Otherwise, your upload won’t work :(

link_to_function Rails Ajax Reference

Posted 14 Oct 2009 — by admin
Category Ruby on Rails

Link_to_function syntax for Haml template. Notice the “|” pipe which will allow for new lines in your code.

= link_to_function( "Add Line Item") |
  {|page| page.insert_html :bottom, :invoice_line_items, |
  :partial => "line_item", :locals=>{:line_item=>LineItem.new}} |

SHA1 or MD5 Hashing in Python

Posted 10 Oct 2009 — by admin
Category Python
import hashlib
print hashlib.sha1("My wonderful string").hexdigest()
print hashlib.md5("My other wonderful string").hexdigest()

Dynamic Attributes in Python Model Class

Posted 10 Oct 2009 — by admin
Category Python
class Bar():
    def __init__(self, **args):
        for key in args:
            self.__dict__[key] = args[key]

b = Bar(fullname="Monty Python", email="me@monthpython.org")
b.fullname #=> Monty Python
b.email #=>me@montypython.org

Python Zlib Compress DeCompress

Posted 09 Oct 2009 — by admin
Category Python
import zlib
regular_string = 'this is my string'
compressed_string = zlib.compress(regular_string)
decompressed_string = zlib.decompress(compressed_string)

print compressed_string
print decompressed_string

Pickle Python Objects

Posted 09 Oct 2009 — by admin
Category Python
import pickle
entity = {
	"user_id": "1",
	"title": "Natural Dog Training",
	"link": "http://naturaldogtraining.com",
}
pickled_entity = pickle.dumps(entity)
unpickled_entity = pickle.loads(pickled_entity)

Build Your Own Calendar in Rails without any Plugins in less than 10 lines of Ruby Code

Posted 07 Oct 2009 — by admin
Category Ruby on Rails

There are a number of terrific calendar plugins for Rails. But it’s almost as easy, if not easier, to implement your own calendar.

The steps are pretty simple. First get the @beginning_of_month and @end_of_month and iterate over the days in between. In the loop we check if the day matches the @beginning_of_month and if it does we get the offset ( 0 – 6 ) because if the month doesn’t start on a Sunday all our days won’t match up correctly. We print out the offset number as table cells <td class=’offset’></td>. We then need to consider that weeks ‘restart’ and restart our row if we’re at the beginning of the week… this is accomplished with </tr><tr>. Then we just output the date contained in table cells <td>#{d.day}</td>. The code is below and it’s pretty simple.

In this example I use haml, but you could just as easily use ERB (at the bottom). If you’re not familiar with haml, check it out at http://haml-lang.com/ Haml automatically handles wrapping your html so you don’t have to! The end result is that it cuts your html in half and makes it look pretty, which in turns makes it a lot more manageable long term.

#app/views/calendars/show.html.haml

%table#calendar
  %tr
    %th
      Sunday
    %th
      Monday
    %th
      Tuesday
    %th
      Wednesday
    %th
      Thursday
    %th
      Friday
    %th
      Saturday
  %tr
    - @beginning_of_month = Date.civil(2009,12,1)
    - @end_of_month       = Date.civil(2009, 12, -1)

    - (@beginning_of_month..@end_of_month).each do |d|
      - if d == @beginning_of_month
        - (d.wday).times do # offset beginning of calendar
         < td class='offset'> </td>
      -if d.wday == 0 #restart the week
        </tr><tr>

      == <td class='#{d}'> #{d.day} </td>

Here it is in ERB

<table id='calendar'>
 <tr>
   <th>Sunday</th><th>Monday</th>
   <th>Tuesday</th><th>Wednesday</th>
   <th>Thursday</th><th>Friday</th>
   <th>Saturday</th>
  </tr>
  <tr>
  <% @beginning_of_month = Date.civil(2009, 12, 1) %>
  <% @end_of_month = Date.civil(2009, 12, -1) %>

  <% (@beginning_of_month..@end_of_month).each do |d| %>
    <% if d == @beginning_of_month %>
      <% d.wday.times do %> <td class='offset'></td> <% end %>
    <% end %>

    <% if d.wday == 0 %> </tr><tr> <% end %>
    <td> <%= d.day %> </td>
  <% end %>
  </tr>
</table>

Override to_param method in model to get pseudo permalinks without any work

Posted 03 Oct 2009 — by admin
Category Ruby on Rails

There are a number of permalink plugins for Rails, http://www.seoonrails.com/even-better-looking-urls-with-permalink_fu, is a good one that I’ve used before. However, this involves informing the model class (has_permalink :title), adding a route, using the route in your views and controllers and of course running some migrations. If you’re willing to get 99% of the functionality for 0% of the work, just override the to_param method in your model.

This assumes you have an attribute for your model that you’d like to use for your permalink, but that’s it.

#app/models/post.rb

class Post < ActiveRecord::Base
  def to_param
    "#{id}-#{title.gsub(/[^a-z0-9]+/i, '-').downcase}"
  end
end

That's it. You don't have to change your controllers, routes or views. Your URL will look something like

/posts/45-pseudo-permalinks-with-rails

Active record will strip all alpha characters from the params[:id] variable leaving you with just the integer value of your model.

So long as you don't mind that integer in the url, it's an easy solution that you can bake in at any point w/out having to touch the rest of your application code.