Archive for the ‘Ruby on Rails’ Category

Merging a :has_many relationship into one instance

Thursday, July 10th, 2008 by Joseph Jakuta

So the problem is that I have an ActiveRecord model that has a :has_many relationship to another model (we’ll call this one object), but when I am in the view context I didn’t want to have to loop through the object each time to determine which data was being displayed. Object has many attributes (approximately 30) and many are often null for a given instance. So I decided to add a method to my model to loop through all of objects and determine which data should be included. Pretty much the rule was that if there was no data for a particular attribute temporarily save it to a copy of the object and then return that. This is what I came up with.

  def object
    tmp = objects.first
    objects.each {|o| tmp.attributes.each {|key, value| tmp[key] = o[key] if value.blank? && key != 'id'}}
    tmp.freeze
  end

However there was a flaw here. Every time I would view the page all of the data in the objects was getting overwritten with one copy of it. After banging my head on the desk it was realized that tmp[key] = o[key] was actually writing the changes to the database permanently rewriting all of the objects (which still seems counter intuitive to me, because it seems like only the first record should have been the one changing). But the solution was pretty simple. The working method is as follows.

  def object
    tmp = Object.new
    objects.each {|o| tmp.attributes.each {|key, value| tmp[key] = o[key] if value.blank? && key != 'id'}}
    tmp.freeze
  end

Reading and replacing text in Word DocX and Excel XlsX documents using Ruby

Wednesday, July 9th, 2008 by Joseph Jakuta

So as you may know. The new Word and Excel formats are similar to open office document formats in that they are just zips of multiple xml documents (well mostly xml documents). So what we wanted to do for our project (the WebDav one mentioned in my last post) is to set up a simple templating system that would do variable replacement in Word/Excel documents. And it turned out to be a piece of cake. I am just going to go through the DocX version of template model, but the only difference between them is the folder structure so there is not too much to change to get this working for both.

(more…)

Microsoft WebDav opens document as Read-Only when using RailsDav

Tuesday, July 1st, 2008 by Joseph Jakuta

I had been working on a project in which we wanted to utilize WebDAV (namely for editing Word & Excel Documents that were saved in our application). In order to do this we decided to use a plugin from liverail.net that can be found here. It was pretty easy to hook up after a little direction from a guy over at Benryan Inc [apologies I cannot find a link for them], but there was a major issue. When opening a document through the ActiveX controller for editing it was opening in Read-Only mode.

After a few starts and stops, many hours of reading through the webdav documentation, and browsing through the http traffic using Fiddler - it was determined that locking was the issue.

(more…)

Rails 2.1 broke my mysql foreign keys!

Tuesday, June 24th, 2008 by John Trupiano

Rails 2.1 introduced in the MySQL Adapter “smart integer columns.” The idea was to use the :limit option to determine whether a smallint, int, or bigint should be used. This is something that the Postgres adapter had already previously implemented. The relevant code in activerecord/lib/active_record/connection_adapters/mysql_adapter.rb is:

  # Maps logical Rails types to MySQL-specific data types.
  def type_to_sql(type, limit = nil, precision = nil, scale = nil)
    return super unless type.to_s == 'integer'
 
    case limit
    when 0..3
      "smallint(#{limit})"
    when 4..8
      "int(#{limit})"
    when 9..20
      "bigint(#{limit})"
    else
      'int(11)'
    end
  end

Mirko Froehlich suggests monkey patching this function. Timothy Jones blogged about it.

To monkey-patch this, just drop a file (fix_mysql_adapter.rb) into your initializers/ directory, as such:

(more…)

Don’t Abuse the Session

Monday, June 23rd, 2008 by John Trupiano

Never, ever, ever, ever, ever store an ActiveRecord model in the session. Just store the id and load it into an instance variable from the database on every request. Why? A couple reasons…

First, you’re susceptible to staleness. Consider this. User A logs in, and you store their user object in the session. Administrator X logs in and deactivates User A’s account. User A can still muck around your site because you’re reading the user data from the session, which has stale data.

Second, the default in Rails these days is to store your session data in cookies (honestly, I don’t know why…..it only clutters up your requests, forcing the session to be passed back and forth on _every_ request, and opening up the possibility that the encryption key could be brute-forced……this is a rant for another day). You just don’t want to be storing whole ActiveRecord objects in the session. They’re big and clunky. The extra database call to reload the object in a before_filter on every request is practically trivial, and you’ll keep the “tubes” less clogged.

This practice is certainly not rails-specific, and should be adopted no matter the server-side technology.

Google AJAX Libraries on Rails

Friday, June 20th, 2008 by Nick Gauthier

If you’re reading this blog you’ve probably already heard about Google’s AJAX Library API on many other news sites like Slashdot.

I’m going to describe my simple process for setting up a RoR app to use Google to pull the APIs in a rails friendly way, throughout layouts, views, and helpers.

(more…)

Ruby on Rails Polymorphic Association Benchmarks

Friday, June 13th, 2008 by Nick Gauthier

Polymorphic relationships in Ruby on Rails are great. If you don’t know what they are, check them out here:

Understanding Polymorphic Associations

John and I were curious about the speed of these relations, since the linking between objects searches on both the ID of the foreign object, and a string which is the model name. So if you have two tables, ChildA and ChildB, your parent has a reference to child which is acutally the combination of child_id (the ID in the ChildA or ChildB table) and child_type (equal to “ChildA” or “ChildB”).

The old-school way of doing this involves creating a lookup table and using integer IDs for type, instead of strings. So you’d have another table mapping “ChildA” to “1″ and “ChildB” to “2″, then when you do your query, you are matching against the number “1″ and not the string “ChildA”.

The down side of doing it that way is that you don’t get to use Rails’ snazzy polymorphism, which makes life a lot easier. So we decided to run some tests to see how much faster it would be, and therefore, if it was worth it.

(more…)

Multithreading in Ruby on Rails

Wednesday, June 11th, 2008 by Nick Gauthier

Don’t you hate it when sites say “Please Wait” when you’d rather just come back later? I am always worried my browser will close and it won’t work. Or maybe I want to shut my computer down but I have to leave my task running. Read on!

(more…)

Deploying Rails Apps with Capistrano without root or sudo Privileges

Friday, June 6th, 2008 by John Trupiano

In an effort to prepare for my presentation on Rails Deployment with Capistrano and Phusion Passenger at the next Bmore on Rails ruby users meetup, I’m writing a series of blog posts to help illustrate some concepts. This represents the second installment of the series. Better setup for environments in rails addressed the set of structural changes that I make to any fresh Rails app. This post will focus on some general principles and useful security considerations to take into account when deploying Rails apps with Capistrano.

The primary point of this post is this: You don’t need to deploy using root. And you don’t need to grant sudo access to the user used for deployment.

Our primary deployment setup is either a single or two-box solution (web server, asset server, database server spread across two). We generally use MySQL for the backend, and Phusion Passenger to serve Rails. We deploy to either Ubuntu Server (Hardy 7.10) or CentOS 5. We also generally disallow root ssh access.

First of all, it’s important to categorize tasks into two types: privileged tasks and unprivileged tasks. The nice part about a rails app is that, for the most part, it’s pretty self-sufficient, and rarely ever needs to venture out of its own tree in the filesystem. This means that we can get away with deploying with an unprivileged account. There are, however, certain ’setup’ tasks that likely need to be executed with root/privileged access. Fortunately, all of our privileged tasks can be performed before we ever deploy the app!

Privileged Tasks
For our baseline deployment, this includes the following:
1) Install any necessary software (Ruby, RubyGems, ImageMagick, MySQL, etc.)

2) Create the Rails app structure. For us, we create the following structure:

/var/vhosts/myapp
  /releases
  /shared
    /content

The default Capistrano setup task performs similar functionality. The only additional folder here is /shared/content. We use this folder to hold all of our uploaded assets (mostly via the File Column plugin). Then, on successive deployments, we set up symbolic links from the public directory up to this shared folder. This allows these assets to live outside of the context of a specific release.

3) Create a log directory at the system level: /var/log/myapp.

4) Create a symlink from the apache config directory (generally /etc/apache2/sites-enabled on Ubuntu, /etc/httpd/conf.d on CentOS) to /var/vhosts/myapp/shared/passenger.conf. Note that at this stage, passenger.conf does not exist. This is ok, as our cold deployment will address this, and each successive deployment will exploit this. This passenger.conf file will actually just be another symlink out to the current release. What this allows us is the ability to alter our apache/passenger configuration for this app on successive deployments. The apache config directories will not be visible to non-privileged users, and thus, we won’t be able to update those symlinks using a nonprivileged account.

5) Create (if it doesn’t already exist) a deploy user, and assign it to the same group that apache runs (www-data on Ubuntu, apache on CentOS).

$> adduser --group www-data deploy

6) chown the app root (/var/vhosts/myapp) and log directory (/var/log/myapp), and give both user/group write permissions (775, 774, or 770). Apache’s user will be able to write to these directories by virtue of them being owned by the group.

$> chown 775 deploy:www-data -R /var/vhosts/myapp /var/log/myapp

7) Create your database, and grant all privileges to a non-root user.

mysql> CREATE DATABASE myapp;
mysql> GRANT ALL PRIVILEGES ON myapp.* TO 'myappuser'@localhost IDENTIFIED BY 'asecretpassword';

8) Install Passenger and the GemInstaller gem (as long as we keep our geminstaller.yml file up to date, we can ensure that our server will use those exact gem versions).

In order to execute these tasks, you’re going to need root access. Note, however, that it is ill-advised to ever include your root password in your deploy script (lest someone accidentally commits it to the repo). One way to handle this is to implement some/all of this functionality in cap deploy:setup. You can then temporarily run this with the root user, but no password (this only works if root can ssh in), which will force you to enter your password. I like this approach, because at this point, we’ll never need the root password again. Put it in a lockbox and leave it alone! Your other option (if root can’t login), is just to login with the unprivileged account, su -, then perform these steps manually. Similarly, you can temporarily grant your deploy user unrestricted sudo access temporarily (but don’t forget to undo this!) in the sudoers file. Either way, these are one time steps, and it’s really not much of a hassle if you know what you’re doing.

Unprivileged Tasks
Everything else you’ll ever have to do (unless you’re adding a new feature that requires installing other software, etc.) with Capistrano can now be completed with the unprivileged deploy user that we created in step 5 above.

At this stage, the only difference between a cold deployment and a successive deployment is the fact that your app was never running in the first place. In essence, it’s the difference between a hard restart of apache and a soft restart. All other steps are the same:

1) create a new release (with the updated code)

2) update the current and filecolumn symlinks (these were the symlinks I mentioned above that point out to the shared/content directory)

3) ensure that all of our necessary gems are installed (reading geminstaller.yml and executing geminstaller if necessary) — more on this in the next post

4) run any pending migrations

5) update /var/vhosts/myapp/shared/passenger.conf to point to the config snippet in the latest release

6) restart apache (hard if cold deploy or if the apache config is updated, soft otherwise)

We overwrite more or less all of the default Capistrano recipes. Actual code will be released probably just after the presentation (Tuesday, Jun 10, 2008, 7:00 PM at Medical Decision Logic, 1216 E. Baltimore Street, Baltimore, MD 21202), as I’m still tweaking things here and there.

The important take home note is this: yeah, it’s nice to be able to just pull out your Capistrano recipes and build an app on a brand new server from scratch with a few command line calls. However, it is borderline impossible to securely pull this off. The line between server setup and application deployment becomes blurred when you try to put this together. The server setup process, by nature, requires root/privileged access. Incremental deployment, however, does not require this level of privilege. Capistrano was not designed to build a server from scratch. Rather, a better approach is to develop a server image that you will use for all of your client app servers.

My next post will elaborate (with more code samples, particularly recipe snippets and some capistrano/rails extensions I’ve been working on) on much of what was covered here. Additionally, I’ll go into further detail regarding other ways to make maintaining your production apps easier with Capistrano.

map.resources and custom nested routes

Thursday, June 5th, 2008 by Scott Davis

I encountered an error in rails trying to create a nested route in rails 2.x

map.import_time_cards 'users/:user_id/time_cards/import',
:controller => 'time_cards',
:action => 'import'

Wasn’t setting up a route for users because this route was being setup automatically and overwritten by:

map.resources :users,
:has_many => [:notes, :addresses, :expenses, :time_cards] ,
:collection => [:login, :logout, :disable, :enable]

So after digging around on the rails api I discovered that map.resources takes a block so my solution to this problem was :

map.resources(:users,
:has_many => [:notes, :addresses, :expenses] ,
:collection => [:login, :logout, :disable, :enable]) do |user|
user.resources :time_cards, :collection => [:import]
end

By using a block this tells rails to include route to ‘users/1/time_cards/import’ instead of appending import as the id for the show route.