Navigation

ADS specializes in using Ruby on Rails to build advanced, scalable, database-backed web sites for organizations of all sizes. Find out more at our website.

Atlantic Dominion Solutions

Have you ever wanted to generate documentation for your rails application quick and easy? I have recently come across a helpful rake task to help do just that. First lets add a comment to the User class to view it later in the documentation.
 

#This the User class that saves the customers login info to the site.
 
class User < ActiveRecord::Base
  # associations
  has_and_belongs_to_many :roles

Then go to console and use the rake task

rake doc:app

It generates all the html and the stats

Generating HTML...
 
Files:   448
Classes: 298
Modules: 154
Methods: 1340
Elapsed: 45.815s

Your documentation is generated in the doc/app folder with the comments that you added to the User class.

Rails application documentation

 

Share this post

I was getting a little fed up touching every single directory that was empty after I created a new Rails app and than pushing it to a git repo and having it not include the empty directories. So, I created a short quick script to help me out. I didn’t test it more than a couple times, but it seems to do the job. Anyway, here it is:

def touch_gitignore(path = '.')
  Dir[File.join(File.expand_path(path), '**')].each do |file|
    if File.directory?(file)
      touch_gitignore(file)
      if Dir[File.join(file, '*')].empty?
        `touch #{File.join(file, '.gitignore')}`
        puts 'touched: ' + file
      end
    end
  end  
end
 
ARGV.first ? touch_gitignore(ARGV.first) : touch_gitignore

Yes, I’m sure it can be improved. As I said, it was quick and dirty, out of frustration even.

As an example how to run it, if I named the file I pasted the code from above into ‘gitignore.rb’ then it would be something like this:

chris$ rails test
chris$ ruby gitignore.rb test

If you found this useful, how about a recommendation on working with rails?

Share this post

While normally an OSX and TextMate user, of late I’ve had need to borrow laptop running Ubuntu 8.04, so obviously TextMate has been out of the question. While the machine is powerful enough to run Eclipse (thus RadRails) or NetBeans, I wanted something simple and quick. As it turns out, Ubuntu 8.04’s Gnome 2.22 comes with gedit, which has a couple of pretty simple plugins that will make use for Rails development a little easier, but it needs a tiny final push to round it off.

First off, pop open the gedit preferences (the Edit menu, then Preferences). For programming basics you’ll want to turn on Display line numbers on the first preferences tab (under View), otherwise when you get Rails errors you won’t be able to find where they were. The next small thing worth doing is the Rails convention of using a tab width of 2 and inserting spaces instead of tabs, which you’ll find on the Editor section - oh, you’ll also want to Enable automatic indentation otherwise you’ll drive yourself crazy. One other small thing I do here is on the Fonts & Colors section I select the Oblivion color scheme, I find the darker background with the colored text to be easier on the eyes.

The fun really begins when you go to the Plugins tab, you’ll want to activate the File Browser Pane, Indent Lines, Snippets and Tag List plugins, but for good measure I also activated Change Case, Insert Date/Time, Modelines, Sort and Spell Checker, though you can skip those if you want.

At this point you’ll be able to browse through the file pane, find your project, then double-click on the main directory to turn the file pane’s focus on just your project, making it behave kinda like TextMate. You’ll also get syntax highlighting on all .rb files, which is all controllers and models.

However, there’s still something missing - no syntax highlighting on rake, ERb or RJS files - lets fix that. The rather simple fix involves tweaking some core Gnome files in the /usr/share/gtksourceview-2.0/language-specs directory to add detection for these extra files. So, in order to do this, pop into terminal and run the following commands:

sudo nano /usr/share/gtksourceview-2.0/language-specs/ruby.lang

Once the editor shows up, after completing the usual sudo login process, go down to the line that says:

<property name="globs">*.rb</property>

and change it to:

<property name="globs">*.rb;*.rake;*.rjs</property>

Next off:

sudo nano /usr/share/gtksourceview-2.0/language-specs/html.lang

Once again, search for the line that says:

<property name="globs">*..html;*.htm</property>

and change it to:

<property name="globs">*.html;*.htm;*.erb;*.rhtml</property>

And that’s all there is to it. Enjoy.

Share this post

Have you ever wanted to create a form with the nice ActiveRecord Validations, but not use a database or ActiveRecord model? Like if you wanted to just have the result of the form emailed. An example might be a contact form or a special inquiry form that requires a name, an email, and perhaps a phone number.

Well, you can, and it”s quite easy too. Especially with the help of a little gem called Validatable.

To install:

sudo gem install validatable

There are at least 2 ways to include this in your Rails project, I’m going to cheat and use the shortcut method of including it in the environment.rb file to save on time and typing (and your patience):

Add to your environment.rb file:

require "validatable"

Next, lets create a new class file called contact.rb. You can put this in lib, models, or some other place, it”s up to you. I put it in my models directory for this example.

The contents of contact.rb will look like the following:

class Contact
  include Validatable
 
  attr_accessor :name, :email, :phone, :message
 
  validates_presence_of :name, :message => "Name is required."
  validates_format_of :email, :with => /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i,
    :message => "Email is not valid."
  validates_format_of :phone, :with => /^[0-9]{3,3}-[0-9]{3,3}-[0-9]{4,4}$/,
    :message => "Phone number is not valid (xxx-xxx-xxxx)."
 
  def phone=(phone)
    @phone = phone.gsub(/[^0-9]/, "").gsub(/^([0-9]{0,3})([0-9]{0,3})([0-9]{0,})$/) do |match|
      tmp = ""
      tmp += $1 if $1.size > 0
      tmp += "-" + $2 if $2.size > 0
      tmp += "-" + $3 if $3.size > 0
      tmp
    end
  end  
 
  def deliver
    if valid?
      Notification.deliver_contact(self)
    else
      false
    end
  end
end

Oh my, doesn”t that look familiar? It looks just like an ActiveRecord model, except, gasp! It doesn”t inherit from ActiveRecord::Base. It”s just a plain Ruby class. Spiffy!

I”m assuming everything else looks familiar to you, yes? Swell, moving on then.

You will also notice I have a Notification mailer in there.

Note: I”m assuming you also know how to set up a mailer and the respective views. If you do not, comment below and I will add those pieces to this post if you desire.

Try it out, open up your console and play around.

>> c = Contact.new
=> #<Contact:0x218e974>
>> c.name = "Chris"
=> "Chris"
>> c.valid?
=> false
>> c.errors.full_messages
=> ["Email Email is not valid.", "Phone Phone number is not valid (xxx-xxx-xxxx)."]
>> c.email = "chris@techcfl.com"
=> "chris@techcfl.com"
>> c.phone = "1234567890"
=> "1234567890"
>> c.valid?
=> true
>> c.name
=> "Chris"
>> c.email
=> "chris@techcfl.com"
>> c.phone
=> "123-456-7890"
>> c.message = "Stillwater? Wtf is that?"
=> "Stillwater? Wtf is that?"

Cool! Now let”s put this into Rails context and see how to use it for handling validations in our controller and view.

In the controller where you want to handle your contact form, you might have something like the following:

def contact
  @contact = Contact.new
  if request.post?
    @contact.name = params[:name]
    @contact.email = params[:email]
    @contact.phone = params[:phone]
    @contact.ticker = params[:ticker]
    if @contact.valid?
      @contact.deliver
      flash[:notice] = "Thank you for you interest."
      redirect_to root_url
    end
  end
end

Here is an example view with custom error handling:

<% form_tag contact_path do %>
  <table>
    <tr>
      <td>
        <label for="name">Name:</label>
      </td>
      <td>
        <%= text_field_tag "name", @contact.name %>
        <%= error_messages_for_attribute(@contact, :name) %>
      </td>
    </tr>
    <tr>
      <td>
        <label for="email">Email:</label>
      </td>
      <td>
        <%= text_field_tag "email", @contact.email %>
        <%= error_messages_for_attribute(@contact, :email) %>
      </td>
    </tr>
    <tr>
      <td>
        <label for="phone">Phone:</label>
      </td>
      <td>
        <%= text_field_tag "phone", @contact.phone %>
        <%= error_messages_for_attribute(@contact, :phone) %>
      </td>
    </tr>
    <tr>
      <td>
        <label for="message">Message:</label>
      </td>
      <td>
        <%= text_area_tag "message", @contact.message %>
        <%= error_messages_for_attribute(@contact, :message) %>
      </td>
    </tr>
    <tr>
      <td colspan="2">
        <%= submit_tag "Submit" %>
      </td>
    </tr>
  </table>
<% end %>

You will notice a custom error_messages_for_attribute helper method I created, here is the code I used for that:

def error_messages_for_attribute(object, attribute)
  if object.errors.on(attribute)
    html = '<small class="errors"><ul>'
    object.errors.on(attribute).each do |message|
      html += "<li>" + message + "</li>"
    end
    html += "</ul></small>"
  end
end

I hope you found this useful.

Share this post

TextMate Tip: HTML Tags

By: Chris Kaukis | Tags:

Have you ever just wanted to select some text and wrap it in a tag instead of jumping to the beginning and end of the lines? Or perhaps you get tired of remembering to close your tags as you go and you wish it was done for you. Both are possible, you just have to know the right keystrokes.

In any HTML editing mode in TextMate (HTML, HTML (Rails), etc) try the following then start typing:

Shift + ctrl + W

You can also select text you want to wrap in the tag.

Click here to view the screencast and see an example

In the screencast, I also used another nice little shortcut.

 + return

This will do a carriage return to the next line starting at the end of the current line, not at the current cursor location.

The Fine Print: It’s my first screencast, it might suck.

Share this post

I did not say this previously, but I am trying to compile a list of posts for picking up TextMate keystrokes. The goal is to NOT use the mouse or at least less often. No matter how simple the tip, the idea is to use that tip or tips for that day to help get in the habit of not using the mouse.

Here are a couple tips for opening and moving around in files.

1. Opening a file

 + t

2. Moving around in Files

Depending on the editor mode (Ruby, Python, HTML, etc), this will work slightly different. For example, this will jump to a method in a Ruby file or a specific HTML DOM Id in HTML mode.

 + shift + T

3. Bonus Tip: Changing the Editor Mode

In case you didn’t notice the key combination shown in the TextMate editor mode drop down:

shift + ctrl + option + SOME_KEY

By SOME_KEY I mean “H” or “R” or “D” or … get the idea?

Basically, if you wanted Ruby mode, you would use the following key strokes:

shift + ctrl + option + R

Then just hit the number for the format you want to use. It seems sort of limited with 0 through 9 though.

Some of my favorites are “D” for Django HTML, “R” for Ruby and Rails, and “P” for Python and Python Django. You can use these when TextMate does not recognize the file correctly or you don’t want to crete/save a file for TextMate to autodetect the format.

I hope you found this useful.

If you have any suggestions for future postings let me know. Today’s was quite simple, but I have talked to quite a few people who didn’t know it existed. So, I decided to post this one today.

Share this post

Here is a TextMate tip when you are editing a stylesheet and need some assistance with colors:

Shift +  + C

It will open up a color picker as shown.TextMate Color Picker  
I hope this is helpful. Please recommend me on Working with Rails:http://www.workingwithrails.com/person/9142-chris-kaukis 

Share this post

Do you loath firing up a whole separate application just to look up some simple data in your database? Or perhaps not in the mood to rip out some simple SQL towards the end of a day from your tired hands and fingers? Try this TextMate tip: 

Shift + Ctrl + Q

Share this post