Archive for June, 2009

How to trim a string and fill remaining space in Ruby

Sunday, June 14th, 2009

So I needed a way to take a string, and depending on its size, shorten it and fill the remaining space with some arbitrary sequence of characters. Ljust would work, except for the fact that it will fill a string up to a given length, but I only needed to do this when over a certain size. Here is an example:

str = "Somereallylongstring"
if str.length > 10
  puts str[0..7] + '...'
else
  puts str
end
# => "Somerea..."

This is the basic idea of what I wanted to do. I decide to make it cleaner and override the String class like so:

class String
  def lfill(len = self.length, fill = '.')
    tmp = self[0..(len|> - 3)] + '...' if self.length - 3 > len
    return tmp || self
  end
end
 
str = "Somereallylongstring"
puts str.lfill(10)
 
#=> "Somerea..."

acts_as_similar - A basic similarity activerecord plugin

Thursday, June 4th, 2009

I had a need to find items that were similar to an item. I looked at acts_as_recommendable, and while this was very nice plugin, it was too slow when working with large data sets. I also decided that the results I needed didn’t need to be scientifically accurate, just a rough match. So I created this plugin to allow for a very elementary way to find items that are similar to the object you are working with. This works best when used with a has_many :through relationship.

Basically all it is doing is looking for other objects of the same class, that have some related value.

Git it here: http://github.com/freezzo/acts_as_similar/tree/master

Example 1
=========
Look for similar playlists, using the videos as what defines similarity.
This will look for all playlists that have a similar video as the playlist you are looking against.

class Playlist
  has_many :playlists_videos
  has_many :videos, :through => :playlists_videos
 
  acts_as_similar :videos
end

Example 2
=========
Look for similar playlists, using the title of the playlist as the similarity item.
This will look for all playlists that have a similar title as the playlist you are looking against.

class Playlist
  has_many :playlists_videos
  has_many :videos, :through => :playlists_videos
 
  acts_as_similar :field => :title
end

Example 3
=========
Look for similar playlists, using the video_id of the playlists_videos as the similarity item.
This will look for all playlists that have a similar video_id as the playlist you are looking against.

class Playlist
  has_many :playlists_videos
  has_many :videos, :through => :playlists_videos
 
  acts_as_similar :playlists_videos, :field => :video_id
end

Execute
=========

@playlist = Playlist.first
@playlist.similar

Note: This is a work in progress.