Posts Tagged ‘Ruby on Rails’

We’re working on a current project that utilizes observers to update activity and notification feeds, and we’ve run into a few stumbling blocks while implementing our solution and I wanted to share our experiences after scouring the internet for the proper execution method. It turns out that the Cache Sweeper is just what the doctor ordered.

1) Standard ActiveRecord::Observers wouldn’t work

The problem with the ActiveRecord::Observer class is that it doesn’t know enough. It’s great if you’re doing email notification based on a simple create, update, destroy action, but unless you’re passing a user model in when you perform those actions you won’t have visibility into who’s doing the creating or destroying. Enter the Cache Sweeper observer. It does a great job of observing models and controllers at the same time. Using the Cache Sweeper we were able to identify the current user through the sessions parameter we use. For instance, we were able to put this code in place and see who was doing the action.

1
2
3
4
5
6
7
8
9
10
11
12
13
class ActionSweeper < ActionController::Caching::Sweeper
  observe :comment, :connection, :topic, :post, :membership, :video, :album, :item, :entry
 
  #have to use the after_save hook for created records because the permission isn't saved and can't be interpolated by the activities model 
  def after_save(object)
    Activity.create(:user_id => controller.session[:user], :object => object, :action => 'after_create') if controller.params[:action] == "create"
    Activity.create(:user_id => controller.session[:user], :object => object, :action => 'after_update') if controller.params[:action] == "update"
  end
 
  def after_destroy(object)
    Activity.create(:user_id => controller.session[:user], :object => object, :action => 'after_destroy')
  end
end

You may ask why we’re using the after_save method instead of the after_create and after_update methods. We have a plugin that the activity model references and that plugin is tied to the after_save method for some of the referenced models. If we use the after_save method, the observer fires before the plugin has a chance to save the corresponding models. By using the after_save method in this way, we get around it. I’d like it to be a little cleaner, but it works.

2) We can observe controller actions

Because the Cache Sweeper class also observes controllers, we were able to tie in to specific actions, like the show action. Some might say we could observe the after_find callback. Unfortunately, the after_find callback fires every time a record is found no matter how many records there are. So a Record.find(:all) call would fire the after_find method. Because we need to know when someone views a record, but we don’t want to incur the overhead of 100 after_find callbacks, we use the Cache Sweeper to observe the Show method of a controller which will only fire once. With that knowledge, we can use the code below to watch a controller’s show action:

1
2
3
4
5
class NotificationSweeper < ActionController::Caching::Sweeper
  def after_blogs_show
   Notification.hide(@entry)
  end
end

To observe the controller, simply name your method like so [before|after]_[controller name]_[controller action].

It’s not perfect, of course. You do have to add cache_sweeper :notification_sweeper to each controller you want to observe, which is a real drag. It is however the only way I could find that gives us access to the params array and session information which is necessary if we want to know who’s doing what.

Update

Looking to access an instance variable in the Cache Sweeper. Just use:

1
entry = assigns("entry")

Open-source Software Myths

Friday, April 24th, 2009

I am an advocate of open-source software. Indeed, we deploy (almost exclusively of late) many different open-source software solutions for our clients and our own projects. But I often run into issues when talking about open-source software with clients, and it sounds a little something like this:

Client: Isn’t there an open-source product that performs that function?

Me: There are a couple of products that perform the same operation, yes.

Client: Well, why do I have to pay for something that’s already been done and is open-source?

And so it goes. If you’ve ever developed software using open-source solutions (and my guess is you have), you’ve undoubtedly run into the same tortured logic around the myths of open-source software.

Open-source software is free.
Sure, you can download them for free, install them for free, and deploy them for free, but thats about all you can do…for free. Once you need to work them into a cohesive project, they start to cost you time or money. It’s true that good open-source solutions can lower your costs. For example, the restful_authentication plugin from Rick Olson makes it quick and easy to implement an authentication function in a Ruby on Rails, but restful_authentication alone does not make a complete system. It’s always part of a larger application and using the plugin saves the developers time and the client money, but it must be integrated, and that will always cost time or money.

Open-source software is the complete solution.
This is rarely the case. Even when you deploy a Wordpress site, you still need to create the theme and customize the installation (even slightly) and that’s going to cost money. It will definitely save you a ton of development costs to launch a Wordpress site instead of rolling your own CMS (I know some people debate whether or not Wordpress is a true CMS), but it still costs money. This fact is exaggerated even more greatly when you’re building a custom application in Ruby on Rails or CakePHP. There are literally thousands (maybe hundreds, I’ve never counted) of open-source plugins available for both frameworks, but they solve particular problems and hardly ever make up a complete application.

Open-source software is high quality.
This couldn’t be further from the truth. In fact, I would argue that high-quality open-source software is far more rare than people think. Any Tom, Dick, or Lisa can create an open-source project and release into the wild. It doesn’t have to be tested, and it doesn’t even have to work. To declare something open-source, all some has to do is say it is so (like we did, but PopCrit is well tested). No testing is necessary. While I do agree that the community votes with their feet, they can’t vote on everything so there are a lot of unknowns when using an open-source solution in a project. Choosing one solution over another could be the worst decision in the entire project, and cost you and the client even more time or money.

There are probably even more myths, but I think these are the most pervasive and caustic for custom software developers. I am a true believer in open-source, but not for the reason that they save money or effort. I believe in open-source because, every once and while, the projects can change the direction of entire industries (MySQL), and from time to time, they save me time and energy.

-Chris

We have plans to release several plugins to the open source community. PopCrit is the first of these. PopCrit grew out of our need to create rails conditions dynamically at run-time, usually coupled with a form like the one below.

Dynamic Search

To cope with creating rails conditions, I’m sure you’ve had to do or seen this done before:

1
2
3
4
if @f_name.to_s.length != 0
  crit += " AND first_name like ?"
  crit_values += ["#{@f_name}%"]
end

Multiply that by 10 fields in a robust dynamic query form and your code begins to smell. We hate it too, so we created the PopCrit plugin (previously a simple library in our applications) to manage those nasty dynamic queries users love so much.

With the PopCrit plugin, you can simply use the new process_criteria_params method provided. It will take your forms parameters and convert it into Rails loving conditions. Now you just have to do the following:

@cards = Infocard.find(:all, :conditions=>process_criteria_params(params[:dynamic]))

There’s more to it, so feel free to check out our repository at http://github.com/chazlett/popcrit/tree/master.

Or install it, play around, and feel free to contribute.

script/plugin install git://github.com/chazlett/popcrit.git

-Chris

TextMate vs AptanaStudio

Wednesday, March 18th, 2009

I switched to a Macbook Pro from Dell running Windows XP late last year, which changed the way I both do and view programming. One of the biggest changes for me was which Editor to use for my development needs. I’m a Ruby on Rails and PHP programmer, so that leaves my options open to everything from a simple text editor to a full featured IDE. I’ve just recently gotten in to using TextMate (not available for PC’s) so I thought it useful to do a comparison between TextMate and AptanaStudio. But first, some history which may be applicable…

When I first started to learn programming (other than writing a dice game in Basic via the command line), I learned in Visual Studio using Visual Basic. It’s safe to say that I got very used to a full featured IDE that pretty much did everything I needed it to do. For those of you who don’t know, Visual Studio takes care of almost everything you’ll ever need. It has one of my favorite features, Intellisense, auto-complete to non-users.

When I started doing Ruby on Rails work, I gravitated to an equally robust tool available for Windows, AptanaStudio. It did everything I needed it to (and some things I didn’t). When I moved to my new Mac, I gravitated to AptanaStudio for all the same reasons. But as I continued to get used to the Unix based operating system, AptanaStudio started to slow me down, and I’d read and heard so many great things about TextMate that I gave it a try.

TextMate is a much lighter editor. In fact, it’s like TextEdit on Steroids. I immediately saw the appeal and have fully made the switch for all my development needs (PHP and Ruby). So, without further ado, here’s the bread and butter (based on Ruby on Rails development).

The Bread and Butter

AptanaStudio (with the RadRails Plugin)

Aptana Studio Screenshot

What makes it great?

  • It is a full featured IDE (based on Eclipse).
  • Has some auto-complete.
  • Does a great job of connecting your code. By Command-Clicking any method, you can follow the method to it’s source. Immensely helpful in large projects.
  • When doing MVC development, you can simply switch back and forth between views, models, controllers, and helpers by clicking the M, V, C, or H buttons in the tool bar.
  • It will tail your logs inside the IDE.
  • You can also run script/console in the IDE as well. This is actually really helpful when you’re editing a model and need to immediately test your changes.
  • It has a huge world of plugins to support Subversion and Git.
  • You can also control all of your Rails local development servers from a nice interface.
  • It’s free, which may just be enough for most people.

What really grinds my gears about AptanaStudio?

  • It is way too slow. Sometimes it just hangs there when I open a file.
  • The plugins work, for the most part. To this day, I’m still having trouble configuring it to effectively use Subversion and Git the way I want.
  • While the log tailing window works well, it can also be a memory hog on the Mac version, so I’ve stopped using it at all.
  • If a development server inadvertently drops, you can’t get it back using the IDE. Moreover, you can’t stop it or restart from the Bash or the Command Line. AptanaStudio will just hold on to it forever…or until you restart the IDE.

TextMate

TextMare Screenshot

What makes it great?

  • It’s Speedy Gonzalez. Everything you do takes about a second to complete, which is nice.
  • Single-click open. Click on a file in the left panel, and it opens immediately (no waiting at all).
  • Infinitely configurable. If you know how to work at the Command Line, you’ll feel right at home making TextMate dance to your every whim.
  • A huge community of Bundle editors contributing, and an easy way to edit and roll your own Bundles. Bundles are Plugins.
  • Separation of concerns. In programming, it’s a good idea to make sure classes do one thing and one thing only. As it turns out, it’s a pretty good idea in editors as well. I had already moved away from Aptana for my script/console, script/server, and tail needs, and I like the idea that it’s not really an embedded option in TextMate.
  • It’s sweet. If you like Bash or the Command Line, you’ll love working in TextMate…it feels like home.

What really grinds my gears about TextMate?

  • Steep learning curve. Like I said, it’s not a full-fledged IDE, it’s a text editor. That may not be everyone’s cup of tea.
  • No auto-complete. If you don’t know your classes or API, TextMate won’t help you very much. The beauty of auto-complete is that it helps you learn your classes.
  • Separation of Concerns. It’s not going to do everything for you, and that may chap some user’s hides.
  • It costs $53 US.

In the end, the editor or IDE a developer uses is an incredibly personal decision. It’s important for programmers to configure their IDE or editor so it works best for them. Both Aptana and TextMate give you a seemingly infinite number of configurations to make each your own. If I was still working on Windows machine, the decision would be a no brainer. Both are incredible tools for development, and you really can’t go wrong with either.

I would stick with AptanaStudio. Because I have the option of TextMate, the choice for me is clear, TextMate. If you haven’t tried TextMate, I’d download the trial and close out of AptanaStudio for the full period of the trial. You may not want to go back at the end of the 30 days. Power users will probably make the switch to TextMate without a thought (if they haven’t already).

-Chris

I’m working on a legacy app that combines the use of HAML and erb markup templates for Ruby on Rails.

ROR deals with both templating markups seamlessly when used in the same application, but I noticed an issue when using a textarea element in a form on the page.

The problem:
I have a free text field that loads up an address. Every time the app would load the data from the database and display it in the textarea field, the resulting text would have extra spaces on second or third lines. Even if you deleted the spaces and saved the address, they would reappear next time I edited the field.

No styling, and no gsub action would fix the problem. Ultimately, it was caused because the template that rendered the form was an ERB template. In all other cases, the ERB templates rendered just fine, but when it came to textarea elements, it adds the white space. Normally, this isn’t a problem, but there seems to be a conflict when using HAML and ERB in the same app.

The solution:
It’s simple, convert the ERB template to HAML.

That’s it.

-Chris

fields_for and HAML

Sunday, March 8th, 2009

Found this little quirk in the templating markup language HAML and Ruby on Rails.

Where you can use the fields_for with the same block variable in an erb template file and then continue processing fields for the top level form like so:

1
2
3
4
5
6
7
<% form_for :user, @user do |f| %>
  Process fields for the user
  <% fields_for "address", @screening_address do |f| -%>
     Process fields for the address
  <% end -%>
  Process more fields for the user
<% end -%>

It just won’t work in HAML. You have to explicitly rename the block variable for the fields_for block:

1
2
3
4
5
- form_for :user, @user do |f|
  Process fields for the user
  - fields_for "address", @screening_address do |add| 
      Process fields for the address
  Process more fields for the user

Apparently, the block level variables when executed in a HAML template seem to stick around even when you don’t expect it to.

It tripped me up for a few minutes, so I thought I’d put it up.

-Chris

Event Clipboard