Posts Tagged ‘ Ruby ’

Hash Autovivification in Ruby

Wednesday, October 6th, 2010

One of the features that I miss most from my Perl days (and to be honest, there isn’t a whole lot I miss from my Perl days) is autovivification. For more information on what it is, read the wikipedia page on it here.
(more…)

Interesting Object Methods in Ruby

Monday, September 27th, 2010

This little Rubyism is something that I use frequently for debugging my objects. I add a method to every object to show only the interesting methods. What do I mean by interesting methods?
(more…)

Getting a Random Record From a MongoDB Collection

Monday, August 9th, 2010

One of my issues with MongoDB is that, as of this writing, there is no way to retrieve a random record. In SQL, you can simply do something similar to “ORDER BY 1” (this varies depending on your flavor) and you can retrieve random records (at a slightly expensive query cost). There is not yet an equivalent in MongoDB because of its sequential access nature. There is a purely Javascript method in the MongoDB cookbook here. If you are really interested, I would also read the Jira ticket thread #533 on this issue.
(more…)

Stopping Curb From Segfaulting

Thursday, July 8th, 2010

While trying to get the curb gem up and running using Ruby 1.8.7p174, I kept getting segmentation faults. I Google’d around and really wasn’t able to come up with much other than lots of people saying not to use ports here. Since I don’t use Mac Ports, I use Homebrew, I figured this wasn’t an issue. I had also recently installed the latest XCode so I incorrectly assumed there was no issue there either. (Note: I am running on a freshly upgraded version of Mac OS X Snow Leopard).
(more…)

Creating Configuration Files With Ruby Templates

Wednesday, June 30th, 2010

I recently had a very repetitive configuration file that needed creating. There were approximately 50 config blocks of 10 lines each with only the host name changing with each block. So I decided to take a shortcut and do it in Ruby using ERB templates. This is so easy and literally save me hours worth of work.
(more…)

Multiple Input Locations From Bash Into Ruby

Thursday, May 13th, 2010

I have been trying to figure out how, while using OptionParser to be able to check for files being input on the command line and if they don’t exist, check other input streams (like Bash). This initially wasn’t very easy since input streams are blocking. So with a little help from friends (thanks roberto), I was able to use his method of non-blocking IO and wrap it in a begin/rescue block. I also took a little advice given in this Stack Overflow question called Best Practices with STDIN in Ruby.
(more…)

Should I Mock Kernel#exit

Monday, April 26th, 2010

I don’t know what the right answer is, so any insight would be appreciated. From Googling around, I came across this thread on StackOverflow which talks about Validating exits and aborts in Rspec. I have a few issues with this, namely that I am using shoulda and I don’t want to validate the exit, I want to stop it from happening inside of the test.
(more…)

ColorTail Gem

Tuesday, April 20th, 2010

One of the best ways to learn something new is to find a project in that realm and do it. I wanted to learn Ruby on Rails, so I wrote a web site. I wanted to learn Python, so I did a project in it for work. Now I want to get better at Ruby, so I wrote a gem. It’s usually not as simple as just picking a project though. It’s much easier to pick and complete a project if you are filling a need. So that’s what I did, I filled a need.
(more…)

Capistrano Hangs on Mac OS X Leopard

Monday, April 5th, 2010

I use Capistrano to deploy my webapps and have been for a while. I also deploy right from my laptop quite frequently. So I was a little taken aback when I could deploy in one place and not in another. It turned out that Capistrano was having issues with deploying to multiple servers. In fact, it turned out that the problem had the appearance of being Capistrano, but in actuality, it was Net-SSH. The whole issue can be tracked via the Lighthouse ticket here. I’m going to show you how to diagnose if you have this problem faster and how to fix it.
(more…)

Custom Google Maps Marker With YM4R_GM

Monday, December 14th, 2009

In one my Rails applications, I allow the user to search for surrounding businesses from their current location. I always showed them a You Are Here marker. The issue I had with this was that the marker was always the icon as the search results. Differentiating these markers is actually extremely easy with ym4r_gm plugin.

First thing is to find a custom icon that you want to use. You can just Google for custom Google maps icons. I chose to use their default icon, just in a different blue. (You can download it here so you are working with what I am working with for this example). The next thing I did was to use the Google custom markers web site to find the proper config options for the icon.
(more…)

Transferring Email From Gmail/Google Apps to Dovecot With Larch

Wednesday, December 9th, 2009

As regular readers of this blog know, I am in the process of trying to back up Google Apps accounts to Dovecot. Well I have finally found my solution. Not only does it work, but its in Ruby.

First thing that you’ll need to do is grab yourself a copy of Larch. I did this simply by typing and it installed everything nicely, but click the link to the repository on Github if it doesn’t work for you.
(more…)

Country-State Select Using Carmen and jQuery

Monday, December 7th, 2009

I’ve been wanting to find a way to use drop down menus for countries and their states when they exist. But keeping a list on my own would have been a huge pain in the ass. So rather reinvent the wheel, I found the Carmen plugin for Rails. All I have to do is keep the plugin updated and my list of countries and their states will be kept updated as well.

How do I do all this with unobtrusive Javascript and Rails you ask? Good question. Let me show you. Don’t forget to install the plugin (or use the gem).

Let’s start out by adding the drop down menu to our view. In my case I have it in a partial for the address part of a form. You’ll have to modify this slightly to pick up the values of the form if the partial handles edits as well. This one is just for a new method as it uses a default country of US and its states. Note the div ID here of addressStates; we will be using this later in the javascript.
(more…)

Adding AJAX Bookmarks to Your Rails Application (Part 2 of 2)

Wednesday, November 25th, 2009

In part 1 of this series, we discussed the base models, controller, database migrations necessary to get this project off the ground. Now we are going to continue with this functionality

Let’s take a look at what needs to go into the models to support this. If you have a model that uses a slug generated via to_param, then your code will look like the top model, If you are using the normal numeric id convention, then it will look like the bottom model. The reason for the specifically named methods get_title and get_description will become apparent when you start displaying bookmarks. The thought process is that you can use a consistent set of calls for displaying the bookmark information and put the code to grab that information in the model where it belongs rather than loading up the helper methods. What should also be noted is that the title and description fields are not always consistent across models. Therefore the method naming conventions returns the proper column with consistent method names.
(more…)

Adding AJAX Bookmarks to Your Rails Application (Part 1 of 2)

Monday, November 23rd, 2009

It you want to add the ability to bookmark pages in your Rails application, its actually a fairly straightforward thing to do. You can even do them in AJAX. There may be better ways to do this, but this way is somewhat abstract and it works for me, so hopefully it can work for you too. It is abstract in the sense that it will work for models with different URL styles and different column names.

The way this works is that you add a bookmark icon (which is initially disabled) to a show <model_name> page. When the user clicks on the bookmark icon, an AJAX query will be made in the background and update the users bookmark lists. I am approaching this from an abstract methodology. Meaning that I have “forced” these methods to work with models executed in various fashions (as I give examples of below). The AJAX call is going to be simply work as a toggle. It will actually call a toggle method in the bookmarks controller and change the current value and replace the image. The user can then view the pages they have bookmarked in their profile.

I have decided to break this into a multi-part blog entry because it ends up being quite long. Not necessarily in how long it takes, just the amount of space it takes to show all the code. I have done my best to only show relevant code and maintain brevity. Note: I will not cover how to allow for unobtrusive AJAX calls. That is beyond the scope of this set of posts.
(more…)

Parsing Ini Files With Ruby

Sunday, October 11th, 2009

There doesn’t seem a lot of documentation or examples about parsing ini files in Ruby. There are definitely shortcut ways to do it and I could always write my own methods, but why reinvent the wheel when there are gems? So start out by simply installing the inifile gem.

1
2
3
4
5
beacon:~ elubow$ sudo gem install inifile
Successfully installed inifile-0.1.0
1 gem installed
Installing ri documentation for inifile-0.1.0...
Installing RDoc documentation for inifile-0.1.0...

The code for the gem is available from github here. Other inifile documentation is available here. The rest of the inifile documentation is a good reference but doesn’t contain any examples.

For some reason (which I don’t understand so please feel free to explain it in the comments if you know), you have to do more than just the standard require statement for this gem. At the top of your Ruby code, add the lines below. Make sure that you replace the directory location with your directory location.

1
2
3
require 'rubygems'
$:.unshift( '/usr/lib64/ruby/gems/1.8/gems/inifile-0.1.0/lib/' )
require 'inifile'

A short example of the ini file that we will be working with:

1
2
3
4
[foo]
bar = "baz"
dir = "2009-10-05/"
id = 75

To get the id parameter of the ini file assuming you know its in the [foo]section, you can use the code below. Notice the parameter section of the new object instantiator. The reason for this is that ini files are pretty abstract can have a few variations on format. Therefore you can specify the comment style and parameter definition style during object instantiation. My ini files use the ‘=’ to assign parameters

1
2
3
  ini = IniFile.new( options[:conf], :parameter => '=' )
  section = ini[foo]
  id = section['id']

Using the above code the id variable now contains the contents of the id parameter from the ini file.

Shortcut Notation in Rails Callbacks

Sunday, August 16th, 2009

As I have spent the last few weeks/months learning Ruby and Rails, I have grown to love it more and more. The ease of use and the high learning curve make is fantastic for people like me who aren’t developers by nature.

I have recently come across a scenario in Rails that there is not yet a shortcut for. If you have a method that you want to execute in a few different callbacks, there is no shortcut for it. ie, I have the following:

1
2
3
  after_create   :methodFoo
  after_save     :methodFoo
  after_destroy  :methodFoo

I would like to be able to write this as:

1
 after_create, after_save, after_destroy => :methodFoo

This would obviously only work if the callbacks were then treated as arrays of functions and each time a callback was found in the model, the method was pushed onto the array.

Adding An Average Column To A Model

Friday, August 14th, 2009

Using Ruby on Rails is all about what people find to be common uses. These items then become part of the core system. An example of this is counter_cache. For more information on this, I suggest checking out the Railscast on it here.

A little more of an edge case is if you want a column that rather than counting totals, its calculates an average. To me this is just common enough to require a HOWTO and not common enough to be in the core rails system. Hence here is my HOWTO.

Context: Let’s use an example similar to Yelp where there is a business and each business gets reviewed. The review count is handled by the counter_cache so that column already exists in our database.

1
| reviews_count | INT(11)      | YES  |     | 0       |                |

The trick here is that every review also has a rating of the business being reviewed. So we are going to use this rating column from the reviews table to calculate the average rating of a business.

First thing we need to do is create the migration:

1
2
3
beacon:test elubow$ script/generate migration add_average_rating_to_business
      exists  db/migrate
      create  db/migrate/20090811135219_add_average_rating_to_business.rb

Edit the migration file to look like this (Note: I know the precision here is 2 when the idea is to not go greater than 5, but MySQL requires precision to be >= scale):

1
2
3
4
5
6
7
8
9
class AddAverageRatingToBusiness < ActiveRecord::Migration
  def self.up
    add_column :businesses, :average_rating, :decimal,  :precision => 4, :scale => 2
  end

  def self.down
    remove_column :businesses, :average_rating
  end
end
1
2
3
4
5
6
beacon:site elubow$ rake db:migrate
(in /Users/elubow/Sites/site)
==  AddAverageRatingToBusiness: migrating =====================================
-- add_column(:businesses, :average_rating, :decimal, {:scale=>4, :precision=>2})
   -> 0.7018s
==  AddAverageRatingToBusiness: migrated (0.7021s) ============================

Now we are going to use the after_save callback hook. We are using after_save because we want the current change to be entered into the database before we make any calculations. In our reviews model, we are going to the following lines:

1
2
3
4
5
6
7
8
9
10
  after_create   :update_business_average_rating
  after_save     :update_business_average_rating
  after_destroy  :update_business_average_rating

  def update_business_average_rating
    average_rating = Review.average(:rating, :conditions => [ 'business_id = ?', business_id ] )
    business = Business.find(:first, business_id)
    business.average_rating = average_rating
    business.save
  end

Let’s walk through this line by line (Note: The business ID and actual ratings will be different based on your data). First, we grab the average rating from every review of that business. What I would like to note is that by default since it is a callback, the review just added is automagically passed into the method. That is how we are able to access the business_id both to find the average of all the reviews of that business, but to also find the business record to update the average_rating attribute.

The method above causes the following SQL to execute:

1
SELECT avg(`reviews`.rating) AS avg_rating FROM `reviews` WHERE (business_id = 1)

The next line finds the record of the business and updates it with the newly calculated average rating. The resulting executed SQL will be this:

1
UPDATE `businesses` SET `average_rating` = 3.0, `updated_at` = '2009-08-13 22:08:55' WHERE `id` = 1

Now that we’re done adding the column and calculating its value, don’t forget to add it to your view. A simple display should do just fine.

1
< %=h @business.average_rating %>