The Irish Penguin Watching Open Source unfold across Ireland

4Mar/094

Phusion Passenger Configuration File Location – passenger.conf

This was not easy for me to find! My beloved Ruby on Rails apps just sitting there untweaked! Google and even the Passenger website didn't specify where the config file may be found. And eventually it made a startling difference to my apps performance - possibly given that I'm trying to host a few sites at once - so it would be nice if it was easier to learn about how to setup the config file when new to Passenger,

Out of the box on a vanilla passenger install there is no passenger configuration file. However, there are a lots of configuration options and you can either dump these into

a) /etc/apache2/apache2.conf file (messy) or
b) Create a new file called passenger.conf under the /etc/apache2/conf.d directory as files in thei directory automatically get loaded by apache
c) Create a passenger.load file in mods-available and then enable the module

By the way, this setup is on Ubuntu, your mileage may vary depending on your distro. For an example passenger.conf file see this one, just be sure to get the 'LoadModule passenger_module', 'PassengerRoot' and 'PassengerRuby' settings correct. You may already have these specified correctly in your apache2.conf file if you already have passenger working; if so you can reuse these values.

Apparently the recommended PassengerMaxPoolSize is 2 if you're on a 256 MB Virtual Private Server System that's running things like MySQL and keep the PassengerMaxInstancesPerApp smaller than this. If you're running a couple of rails sites then maybe set PassengerMaxInstancesPerApp to 1 if you want to have 1 instance always available for each site. A RailsSpawnMethod of 'smart' can also lead to better performance depending on your setup.

Certainly playing around with this config file helped me greatly improve my sites' responsiveness for little effort and in particular it got the usage of the all important swap space down.

One final tip for today is to install htop (is available through aptitude). This gives a very useful and pretty display of the 'top' commands information and can make monitoring things like memory and swap at a glance much easier. So armed with this knowledge go forth and spawn! Well, till you run out of memory at least!

22Jan/0919

Bug of the Day: nil.include error with create_time_zone_conversion_attribute

This was an 'orrible bug. Tired and midway through writing up a Ruby on Rails tutorial on setting up emailing with AR Mailer and a little postfix configuration I wasn't exactly in the mood for a bizzarely cryptic issue to waste my time. Enter the mysterious create_time_zone_conversion_attribute? method in all it's glory. Basically you will get this error if you set ...

config.cache_classes = false

... wherever it is set in your environment files (in my case config/development.rb) but the error goes away if you change it to ...

config.cache_classes = true

... bloody daft! Here is the bug on lighthouse. Arrgh!!!!

Anyway here is the full stack trace which may help someone googling to pick up this page

NoMethodError in UsersController#create

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.include?

/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:142:in `create_time_zone_conversion_attribute?'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:75:in `define_attribute_methods'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:71:in `each'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:71:in `define_attribute_methods'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/attribute_methods.rb:350:in `respond_to?'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:2587:in `attributes='
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:2583:in `each'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:2583:in `attributes='
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:2283:in `initialize'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:691:in `new'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.2.2/lib/active_record/base.rb:691:in `create'
vendor/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:92:in `perform_delivery_activerecord'
vendor/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `each'
vendor/gems/ar_mailer-1.3.1/lib/action_mailer/ar_mailer.rb:91:in `perform_delivery_activerecord'
/usr/lib/ruby/gems/1.8/gems/actionmailer-2.2.2/lib/action_mailer/base.rb:526:in `__send__'
/usr/lib/ruby/gems/1.8/gems/actionmailer-2.2.2/lib/action_mailer/base.rb:526:in `deliver!'
/usr/lib/ruby/gems/1.8/gems/actionmailer-2.2.2/lib/action_mailer/base.rb:392:in `method_missing'
app/controllers/users_controller.rb:47:in `create'
app/controllers/users_controller.rb:45:in `create'

Happy hackin'

16Jan/090

Hackin on Gruff – A Brief Overview of Gem Development with Ruby

Ah such is the life. Chillin' in Havana (the bar, unfortunately not the city), hackin' away on Gruff of all things. This is the my first attempt at development on a gem and it has to be said is surprisingly satisfying. Getting gems to build is a doddle. Here's a great link that shows how it's done in moments. Also a handy thing to know is how to suck the code out of your OS's gems directory and unpack them to under your app's vendor/gems directory - all courtesy of VendorEverything. You can create the vendor/gems directory manually if it doesn't already exist.

When developing on the gem, I found that the best strategy was to clone down the gem source code from GitHub or Rubyforge to under the vendor/gems directory of my application rather than using the OS package unpacking technique of Vendor Everything (though they do it more for deployment than development - which is a great idea). That way I could easily stay on top of the latest source code using git. Actually, to make things even cleaner I downloaded the Gruff gem source code to a different directory totally unrelated to my sample project and then symlinked to it from under vendor/gems of my app. Clean as an (unused) whistle!

And with Gem, Git and GitHub behind me life was trouble free. Now back to my search for great Cuban cigars...

10Dec/080

Better to be Oriented than an Object

Bit of a mixed bag of thoughts going into this post. Originally it was motivated by a couple of interesting points that I came across a bunch of ideas on programming by Kristian Dupont but then it turned into one of those link hopping sessions where you end up click through a wealth of interesting material.

A Tip or Two for your Troubles

Kristian outlined a good test to determine if adding a comment to your code is justified saying that "they should contain the word 'because'. This way, you know that you are answering a why rather than a what." That's a great test I think. If your comment fails the test then you may well be more in need of a refactor than a comment.

Secondly, when thinking about the classes you plan to use in your code, especially domain models, bear in mind that you're not actually trying to model the real world in a physical sense. For example, if you're writing software for a car dealership and one of your classes is going to be a car remember "You're not implementing a car. You're probably implementing a record of a car which can carry a number of stock items from one city to another, with a certain mileage and speed." The key thing is the context of what you're trying to implement and focus on that - often the real world will map nicely to your domain model but don't force things where doesn't. To shoehorn irrelevant aspects of the physical world into your models doesn't make it "more object oriented" or more correct - quite the reverse. Generally, this in not a problem with the attributes for your models, rather it is a problem with relationships and in particular with inheritance. Should a subclass really be a subclass - just because it is in the real world doesn't necessarily mean that your software be designed on the foundation that it is. This brings on nicely onto the other article, The Rise & Fall of Object Orientation, which ended up being another inspiration for this post.

What is Object Oriented these days anyway?

Danny Kalev argues that traditional OO is something that is less and less likely to be found in areas such as STL library of C++, as techniques such as inheritance give way to more template driven styles of programming. The problem he states "is that a member function is useful only for a single class" and goes on to highlight how this doesn't work well for things such as a library of containers.

"If each container class defines its own size() member function, you will end up writing numerous size() functions that basically do the same thing."

Better to use a standalone function to solve the problem which can be used across the board by any class irrespective of inheritance hierarchies. It isn't just C++ that has looked to functional programming techniques to solve problems that traditional OO couldn't deliver on. Languages such as Ruby have effectively made blocks and closures one of the core and most used features of the language. All iteration is done through blocks and lamba functions can solve tricky problems in an elegant manner.

It seems that traditional OO struggles most with collections but works well enough for single objects. Neal Ford thinks that Object Oriented Development is the wrong way to even frame the question of code reuse. Instead the focus should be on Library Oriented Development. “Ultimately, the class is just too fine grained to really achieve reuse, but libraries can.” On Java he states that while it “is a library oriented language, no good facilities exist within the language to manage libraries" and notes it sorely lacks a fixed directory structure such as in Ruby on Rails, where plugin developers know the layout of the projects they will be interfacing with from the get go.

Whether you prefer to consider your approach to software development an Object or Library Oriented approach it does seem that the modern developer will be drawing on a wide range of programming paradigms that go beyond traditional OO philosophy. In a hotly debated and opinionated field, it appears that the one true killer approach has not yet emerged to truly simplify and streamline development. At least it will continue to provide software developers, designers and architects with plenty to debate during their coffee breaks for years to come!

9Oct/080

Troubleshooting fcgi and the dreaded undefined method `require_gem’ error

It happens to the best of us. We've coded our app go to deploy it and encounter some dispatch.fcgi issue. Today was the turn of
<br />
dispatch.fcgi error: undefined method `require_gem' for main:Object (NoMethodError)<br />

Well way to troubleshoot and arrive at a solution is to actually run ./dispatch.fcgi. I didn't know you could do this! It's well handy! If you are on a remote server to which you don't have ssh access then you can probably still run it as a cron job. Something like cd /path/to/my/app/public && ./dispatch.fcgi should do it. Remember that the dispatch.fcgi file is in the public directory of your application. The combination of running ./dispatch.fcgi and viewing the Rails log file revealed the useful error message above. Then a quick google search revealed that we need to change require_gem to simply gem (see here).

I had to change this in the dispatch.fcgi and then grepped the whole application directory for any instances of require_gem and changed them to gem too.

2Aug/085

Getting Ruby Plasmoids up and running in KDE 4.1 (on Kubuntu)

NOTE: THIS ARTICLE IS NOT YET COMPLETE. IF YOU FOLLOW IT THEN YOU WILL GO A LONG WAY BUT THE PLASMOID IS NOT YET DISPLAYING. SEE THE 'Run your applet' SECTION NEAR THE END OF THIS ARTICLE BEFORE PROCEEDING.

Introduction
KDE 4.1 is an absolutely terrific release of the KDE desktop, licking most of the issues presented in the original 4.0 release. Although it is still an early adopter release, 4.1 will be of interest to techie's who want to get their mitts on a sexy new graphical interface and is reasonably stable for daily usage. Not quite ready for Aunt Tillie yet though! One of the nicest features is the beauty and simplicity of Plasmoids and these super flexible little gadgets can now be written in Ruby - well almost!

This guide assumes that you're using Kubuntu Hardy Heron. But you should be able to adjust the instructions for any distro.

  • The starting point for our tour is to have Ruby installed. Google this if you're unsure as to whether or not it's installed.
  • We need to install cmake via 'sudo aptitude install cmake'. This is a cross-platform build system, similar to make.
  • It's likely that you will need to install the build UNIX build tools via 'aptitude search build-essential'.

Get coding!
And now you're be ready to go. The main tutorial out there on Ruby Plasmoids at time of writing is the Ruby Applet tutorial on KDE Techbase. This is a very good, well written guide on creating a simple Ruby applet in which a web browser is embeded inside the plasmoid. But the guide has a couple of gotcha's, especially for the newbie (myself included!), so we have listed solutions to these problems as we go. In summary, use our article as an supplement to KDE Techbase's.

Ok, to start with a demo everyone wants a nicely packaged directory of files, so let's quickly put together the basic directory structure for our plasmoid - it's pretty simple!

  • Create a directory called 'ruby-web-applet'
  • Save the files plasma-ruby-applet-web.desktop and web_applet.rb into this directory.
  • Create a file called CMakeLists.txt under your ruby-web-applet directory and paste the following code into it
set(SERVICES_INSTALL_DIR /usr/lib/kde4/share/kde4/services/)
set(DATA_INSTALL_DIR /usr/lib/kde4/share/kde4/apps/)

FIND_PACKAGE (Ruby REQUIRED)

include_directories( ${RUBY_INCLUDE_PATH} )
install(FILES plasma-ruby-applet-web.desktop DESTINATION ${SERVICES_INSTALL_DIR})
install(FILES web_applet.rb DESTINATION ${DATA_INSTALL_DIR}/plasma_ruby_web_applet)

Go to KDE Techbase
Once you have the above directory in place, go and read the Ruby Applet tutorial on KDE Techbase article down to just before the 'Install and test the Applet' paragraph. This will teach you what's going on in the code. At that point come back to me as I'll go into a little more detail on the final installation procedure!

You're back!
Great! Ok, so we have the files on disk, you have a good idea of what the code is doing, now let's install it and kick your plasmoid into action!

Open the CMakeLists.txt file listed above in a text editor. Change the path listed for KDE4 services and data directories to the ones on your system. These are the lines to change.

set(SERVICES_INSTALL_DIR /usr/lib/kde4/share/kde4/services/)
set(DATA_INSTALL_DIR /usr/lib/kde4/share/kde4/apps/)

Do this by replacing '/usr/lib/kde4/share/kde4/services/' with the output of the command 'kde4-config --install services' and replace '/usr/lib/kde4/share/kde4/apps/' with the output of the command 'kde4-config --install data' command. If you are using Kubuntu then they should be the same as mine but otherwise you may need to change them.

Then make sure you are inside your ruby-web-applet directory and type

cmake .

to generate nice makefiles for you which the make command can then use. Don't forget the trailing dot! Now type 'make' and 'sudo make install'. This will install your plasmoid code into the KDE4 services directory (you can see where this is by running 'kde4-config --install services') and your plasmoid data into the KDE4 data directory (you can see where this is by running 'kde4-config --install data'). Effectively, the installation just involves the two files - plasma-ruby-applet-web.desktop web_applet.rb. If it's worked then you'll get output like

Install the project...
-- Install configuration: ""
-- Installing: /usr/lib/kde4/share/kde4/services/plasma-ruby-applet-web.desktop
-- Installing: /usr/lib/kde4/share/kde4/apps/plasma_ruby_web_applet/web_applet.rb

The applet is now installed!

Run your applet (THIS DOES NOT WORK YET)
There are two ways to do this. In a developer kind of way you can run 'kbuildsycoca4' from the command line followed by 'plasmoidviewer plasma-ruby-web-applet'. Unfortunately this currently brings up the error

findServiceByDesktopPath:  not found
findServiceByDesktopPath:  not found

IF YOU HAVE A SOLUTION TO THIS THEN PLEASE COMMENT BELOW!!!

As a user, the cmake/make/make install procedure should have done all the necessary to install your plasmoid and you can activate it by going to the right of the task bar and clicking the Add Widgets icon. You should see your plasmoid listed but unfortunately this is not yet working - presumably for the same reason as the above. Oh well, I'm sure a solution will soon be posted. Until then, happy hackin!

Final notes

Note that the KDE techbase article provides a version of this file but it didn't work for me because

  • I knew nothing about cmake or cmake files and I didn't even cop that right clicking on the CMakeLists.txt file link in their article and saving it to disk would also save a load of HTML into the file
  • The line 'FIND_PACKAGE (RUBY REQUIRED)' should really be 'FIND_PACKAGE (Ruby REQUIRED)' as it's case sensitive and will otherwise give you the error

    CMake Error at CMakeLists.txt:6 (FIND_PACKAGE):
    find_package could not find module FindRUBY.cmake or a configuration file for package RUBY.

    Adjust CMAKE_MODULE_PATH to find FindRUBY.cmake or set RUBY_DIR to the directory containing a CMake configuration file for RUBY. The file will have one of the following names:

    RUBYConfig.cmake
    ruby-config.cmake

  • The destination targets specified in the file didn't work for me. Perhaps some environment variables need to be set somewhere
  • I didn't even know how to use cmake! Or that you needed to follow it up with 'make'. Anyway we'll come cover this soon!

I didn't need to set any CMAKE_MODULE_PATH but if you are having troubles with this then it's at /usr/share/cmake-2.6/Modules/ on Kubuntu Hardy Heron. You may be able to set it in your script if your having difficulties as follows 'set(CMAKE_MODULE_PATH /usr/share/cmake-2.6/Modules/)'. Again I haven't tried this my self!

25Jun/085

A Little Help on Importing Gmail Contacts using Ruby on Rails

We came across a fabulous article on getting your RoR app to pull contacts from your Gmail account at Atlantic Domain Solutions: Import Gmail Contacts using Ruby on Rails. Kudos to Atlantic Domain Solutions! This is a really great article. The only slight issue is that it omitted a couple of details which may confuse the newbie - in particular, where does all the code in points 1, 2 and 3 go and how do the code snippets relate to each other.

So here's a set of clarifications to the original article (a 'meta-guide' if you will), as we didn't want to just rip off these nice folks source code. Thus read these clarifications in conjunction with the original Atlantic Domain Solutions guide.

We'll assume that you know how to create a new rails app from scratch and create a controller. While you're following this you can use localhost as your server (eg. the default localhost:3000).

Create yourself a controller called ImportedContacts

class ImportedContactsController < ApplicationController

    def authenticate
        # Put the code from point 1 in the Atlantic Domain Solutions article here.

        # Note:
        # Set the next_param to the follow on controller action. For example,
        # next_param = url_for(:action => 'authorise')
    end

    def authorise
        # Put the code from point 2 in the article here.

        # Note:
        # I changed some of the code as shown below...
        # if resp.code == "200"
        #     token = ''
        #     data.split.each do |str|
        #         if not (str =~ /Token=/).nil?
        #             token = str.gsub(/Token=/, '')
        #         end
        #     end
        #     redirect_to(:action => 'import', :token => token)
        # else
        #     redirect_to ('/')
        # end
    end

    def import
        # Put the code point 3 from the article here.

        # Some notes:
        # Put the line 'authsub_token = params[:token]' at around line 4 of this method
        # (just after the two requires). It was accidentally omitted in the original article.
        # I also changed the local variable 'contacts' to '@contacts' so that it is available to views
    end
end

To see the contacts after importing, I created a folder called 'imported_contacts' under app/views and placed the file import.rhtml in it, containing the following code.

<table>
  <%= @contacts.map { |c| "<tr><td>Name: #{c['name']}</td><td>Email: #{c['email']}</td></tr>" } %>
</table>

Ok! You should be ready to rock! Ensure that you are not logged into gmail and visit http://localhost:3000/imported_contacts/authenticate

You should be brought to a Google account login page. Login and you will be brought to the Google page for allowing third party access to the Google API. Click 'Grant' and you should be brought to your app's import.rhtml page which should hopefully be displaying all your lovely contacts! Hurrah!

Blogged with the Flock Browser
19May/080

Quick Example of Serialisation via to_json in Ruby On Rails

Ruby On Rails provides a few neat ways to serialise/deserialise objects to JSON. Out of the box you get the following approaches

SERIALISING

* json_string = a_house.to_json

DESERIALISING

* an_object = ActiveSupport::JSON.decode(json_string) # gives you an object of type Object
* a_house.from_json(json_string) # gives you an object of type House, note that a_house
                                             # is an instance of House

These are pretty straightforward and do exactly what they say on the tin. Of the deserialising methods, note that using ActiveSupport directly gives you an object of type Object so you may prefer the stronger typing of the second technique which gives you an actual House object.

Note: There's been some great improvements to JSON support built right into Rails since Rails 2 has come around. For more info on this see here.

When things just aren't enough...
There are times when you will want to override the default serialisation that Rails provides - such as if you want to do some object 'flattening' like including an attribute from an association on serialising. Now before proceeding check out the latest Rails 2 JSON support mentioned at the end of the previous section as this might make your life a lot easier. Otherwise, let's press on with an example of DIY JSON handling.

Given a House object which has an associated Owner object, you might want to include the Owner's name attribute when serialising a House.

House Class
- has address and value attributes
- has an associated Owner object

Owner Class
- has a name attribute

We'll need to override the default to_json method on the House model.

class House::Base
  def to_json
    result = Hash.new

    self.class.content_columns.each do |column|
      if self.attributes.include?(column.name)
        result[column.name.to_sym] = self.send(column.name)
      end
    end

    if self.attributes.include?(column.name)
      result[:owner_name] = owner.name
    end

    result.to_json
  end
end

The above was partially taken from the howtogeneratejson page on the Rails wiki, which is has little bit more detail. Now all you need to do is call the a_house.to_json method and you get lots of lovely JSON which represents your model! One final note is that you may not want to override the default to_json method. If not, just call your method something else like to_custom_json. Also, there's

14Jan/080

Simple ‘Through Associations’ in Ruby on Rails

This little article shows one way to model many-to-many relationships using a join table.

Obviously, The Penguin isn't the first so here is an alternative good practical example which might give your good self an different perspective. Also this documentation has some more detailed information but doesn't have a simple self contained example like below (and neglects to mention belongs_to in its primary example - at time of writing this).

Here goes. The following statements define our basic requirements.

* An order has many items
* An item has many orders
* We shall model this through a join table called order_items

orders     order_items    items
-----      ----------     ----
id         order_id        id
           item_id

Before we continue, please note that a massive massive thing to remember is that Order needs to have a has_many to the join table model AS WELL as a has_many (through the join table model) to Item. Also the join table model has a belongs_to for each model.

class Order < ActiveRecord::Base
has_many :o rder_lines #Don't forget this line!
has_many :items, :through => :o rder_lines
end

class Item < ActiveRecord::Base
has_many :o rder_lines #Don't forget this line!
has_many :o rders, :through => :o rder_lines
end

class OrderLine < ActiveRecord::Base
belongs_to :o rder
belongs_to :item
end

Ok so that's it folks! The Penguin has to admit that the above code hasn't been run in a RoR interpreter so if has typo's or smelly code please comment below.

One last thing is that if you're going to try and present a RoR solution in an enterprise situation it is quite likely that the powers that be will want to see foreign key relationships in your database tables (note, this applies to all db relationships; not just man-to-many). These will give referential integrity to your associations. One very very handy and straightforward way to do this is using Red Hill's foreign_key_migrations plugin. This really is great (it does pretty much all the hard work for you!) so it's worth a serious look.

One gotcha with using foreign keys in Rails, is that the order in which test fixtures load becomes important. See Per Olesen's post for tips on countering this. Other than that happy hacking and may the Rails Rise to Meet You!

9Dec/075

Uninitialized Constant GemRunner Error When Using Ruby Gem

Here's the problem...

me@host:~$ sudo gem update
/usr/bin/gem:23: uninitialized constant Gem::GemRunner (NameError)

... which had us on the ropes more than on the rails for a while. Unusually googl'ing on this error provided no solutions.

What led to the situation was that we used the source install of rubygems on Ubuntu Gutsy (7.10) instead of using the rubygems in Ubuntu's repository but then changed our mind and apt-getted the Ubuntu repository version. Surprise! Surprise! These 2 versions were conflicting a bit; leading to the above error. The workaround is pretty simple, just go to your /usr/local/lib section and delete the site_ruby directory (as this is the remnant of the rubygems source install and thus cause of the problem). This removes all the gems (that were downloaded by the original rubygems which we no longer want) off our system. Perhaps you want to simply move this directory first in case something goes wrong and you need to revert (eg. sudo mv /usr/local/lib/site_ruby /usr_local/lib/site_ruby_old).

Note: In case your not aware, /usr/local/* is the set of directories under which programs that you compile yourself get installed to by default. Generally the directories will start out pretty empty on a freshly installed Linux distro and then as you (if ever!) compile and install programs from source (eg. using ./configure && make && make install) then they end up under this directory. Also not that programs installed using apt-get (or via rpms on non-Debian systems) don't get put here - they usually end up under the /usr/ directory itself (this varies a bit from distro to distro but what we've just outlined holds true for Ubuntu anyway).

Now, once your finished you should find that gem works. Do a 'gem list' and see if the above error is gone. If this doesn't work you may need to 'sudo apt-get install rubygems'. Next up, we need to rebuild that gem directory that we deleted (site_ruby) with the apt-gotten rubygems (if apt-gotten is a real word!). To do this run

'sudo gem update'
'sudo gem update --system'

You will notice that the result of these commands means that /usr/local/lib/site_ruby is back and populated. This is where ruby likes to put it's gem extensions. Finally reinstall rails with

'sudo gem install rails'

Hope this solution works for you! We're still getting to grips with this rails stuff so if you find any glaring errors in this post please comment below to let us know.