Jul 5 2006

Acts As Blog Plugin

The Ruby on Rails plugin acts_as_blog does not make your ActiveRecord model into a blog… The acts_as_blog plugin helps your model by converting simple text to HTML formatted text. You can use acts_as_blog in blogs, as the name alludes to, or in a wiki-like system. Acts As Blog currently supports text-to-HTML formats Textfile via the RedCloth gem, Markdown via the BlueCloth gem, and SmartyPants via the RubyPants gem. You need to install any one, or all, of these gems before you use this plugin.

gem install RedCloth
gem install BlueCloth
gem install RubyPants

To install the plugin just run this script:

script/plugin install http://svn.recentrambles.com/plugins/acts_as_blog

In your model you need to call the acts_as_blog method just like any other ActiveRecord plugin. For this plugin you will also need to do some additional processing before the model is persisted into the database.

class Post < ActiveRecord::Base
  acts_as_blog

  before_save :txt_to_html

  def txt_to_html
    self.post = Post.convert_to_html(self.raw_post, 'textile')
  end
end

You can switch ‘markdown’ or ‘smartypants’ as the text-to-HTML format in the convert_to_html method by replacing ‘textile’. Also notice that in the txt_to_html method a field raw_post is converted to HTML and copied to the field post. If you use code similar to this you will need a raw_post and a post column in your database posts table. The data in the post column of the posts database will have the HTML formatted text while the raw_post column will keep the original unformatted data. Using the acts_as_blog plugin in this fashion you will stash the model data and the presentation data in the database.

You can also use BlueCloth, RedCloth, and/or RubyPants without using this plugin. Personally, I would store the raw text in database and only convert it to HTML in the view without using the plugin.

<%= BlueCloth.new("### HELLO\nTECHKNOW\n").to_html %>

I recommend you use a helper function that will do the conversion so that you can switch between the different text-to-HTML formats more easily.

Technorati Tags: , , , , , , , , ,


Jul 5 2006

Acts As Rateable Plugin

Continuing with my work with Ruby on Rails plugins here is my version of the acts_as_rateable plugin. Use this plugin to make your model instances be rated by users. The ratings are numeric and could be from 0 to any number you would like. Typically you can rate articles, posts, reviews, etc from 0 to 5 but this plugin does not dictate the range. To install this plugin run the following command:

script/plugin install http://juixe.com/svn/acts_as_rateable

The installation process will add several ruby files in the vendor/plugins directory. Create a new rails migration and cut and past the following self.up and self.down methods:

def self.up
  create_table :ratings, :force => true do |t|
    t.column :rating, :integer, :default => 0
    t.column :created_at, :datetime, :null => false
    t.column :rateable_type, :string, :limit => 15,
      :default => "", :null => false
    t.column :rateable_id, :integer, :default => 0, :null => false
    t.column :user_id, :integer, :default => 0, :null => false
  end

  add_index :ratings, ["user_id"], :name => "fk_ratings_user"
end

def self.down
  drop_table :ratings
end

Once you have the acts_as_rateable plugin installed you can make your ActiveRecord models act as rateable by calling the acts_as_rateable method.

class Post < ActiveRecord::Base
  acts_as_rateable
end

In your controller you can rate a post with just a few lines of code:

post = Post.find(params[:id])
rating = Rating.new(:rating => 2, :submitted => Time.new)
@post.ratings << rating

Similarly you can do this:

post = Post.find(params[:id])
post.add_rating Rating.new(:rating => 2)

And of course you can iterate through the ratings of a post by using the ratings property such as the following bit of code:

post.ratings.each { |r|
  logger << "rating value: #{r.rating} for object: #{r.rateable}\n"
}

You can also use the ratings property to get the number of ratings this post has been given.

count = post.ratings.size

And if you want to display the average rating you can use the rating function.

average_rating = post.rating

Stay tuned for more on Ruby on Rails plugins…


Jul 5 2006

Acts As Taggable Plugin

The first Ruby on Rails plugin that I used was acts_as_taggable. With the acts_as_taggable plugin you can tag instances of your models in the same fashion you tag your pictures on Flickr or your bookmarks on Del.icio.us. Just to create some confusion there are two version of the the acts_as_taggable functionality. One is available as a gem while the other is a plugin. I’ll be covering the plugin here.

The taggable how-to wiki page on the rubyonrails.org has great information on how to get started with the acts_as_taggable plugin. In particular the wiki will walk you through the installation process and the creation of the tables necessary to store the tags. Once you get the plugin installed all you have to do is make your model act as taggable:

class Post < ActiveRecord::Base
  acts_as_taggable
end

In your controller you can tag a post with these siple lines of ruby code:

post = Post.find(params[:id])
post.tag_with('tag1 tag2 tag3')

To retrieve the tags for a post, as a single string, use the tag_list method. To get the tags as a list use the tags property. You can also find all posts marked with a given tag, for example:

posts = Post.find_tagged_with('tag1')

This plugin is easy to use and easy to learn from. I’ve written several ActiveRecord plugins that use this plugin as a template and now my most of my models act as taggable, commentable, versionable, rateable, etc.

Technorati Tags: , , , , , ,


Jun 24 2006

Acts As Voteable Rails Plugin

Right on the heels of my release of acts_as_commentable, I am now making available a acts_as_voteable Ruby on Rails plugin. The Acts As Voteable plugin allows for model to be voted on by users.

To install this plugin run the following command:

script/plugin install http://juixe.com/svn/acts_as_voteable

The installation process will add several ruby files in the vendor/plugins directory. Create a new rails migration and cut and past the following self.up and self.down methods:

def self.up
  create_table :votes, :force => true do |t|
    t.column :vote, :boolean, :default => false
    t.column :created_at, :datetime, :null => false
    t.column :voteable_type, :string, :limit => 15,
      :default => "", :null => false
    t.column :voteable_id, :integer, :default => 0, :null => false
    t.column :user_id, :integer, :default => 0, :null => false
  end

  add_index :votes, ["user_id"], :name => "fk_votes_user"
end

def self.down
  drop_table :votes
end

Once you have installed the plugin you can start using it in your ActiveRecord models simply by calling the acts_as_voteable method.

class Post < ActiveRecord::Base
  acts_as_voteable
end

To cast a vote for a post you can do the following:

vote = Vote.new(:vote => true)
post = Post.find(params[:id])
post.votes << vote

ActiveRecord models that act as voteable can be queried for the positive votes, negative votes, and a total vote count by using the votes_for, votes_against, and votes_count methods respectively. Here is an example:

positiveVoteCount = post.votes_for
negativeVoteCount = post.votes_against
totalVoteCount = post.votes_count

And because the Acts As Voteable plugin will add the has_many votes relationship to your model you can always get all the votes by using the votes property:

allVotes = post.votes

Technorati Tags: , , , , , ,


Jun 22 2006

Rails Recipes

I just received Rails Recipes by Chad Fowler (I original ordered this book through Amazon back in February). This book is jam packed with 70 recipes covering user interface, database, controller, testing, and big-picture, and email recipes. The recipes that I am most interested in are Converting to Migration-Based Schemas, Make Dumb Data Smart with composed_of(), Cleaning Up Controllers with Postback Actions, Write Code That Writes Code, Automating Development with Your Own Generators, Getting Notified of Unhandled Exceptions, Syndicate Your Site with RSS, and Making Your Own Rails Plugins (I wrote my own recipe on rails plugins).

Rails Recipes picks up where Agile Web Developement with Rails leaves off. I got started with Rails just by reading the first few chapters of Agile Web Development with Rails. Now that I am getting into some more advanced features of the framework I will depend on Rails Recipes. Another book that has been helpful in my rails development has been Ruby in a Nutshell by Ruby’s author Yukihiro Matsumoto. These three books form the holy trinity of Ruby on Rails.

Technorati Tags: , , , , , , ,


Jun 18 2006

Rails Plugin Tutorial

There are other Rails Plugin tutorials out there but I found holes in the details they provided so I felt I need to write this Ruby on Rails plugin tutorial. This tutorial is written with the experience of developing the acts_as_commentable plugin.

To get started you will need to create your plugin directory under the vendor/plugins for your Rails application. You will need a init.rb file and a lib directory. Here are

To get started run the generate plugin script to create the necessary directory structure in your Rails application.

script/generate plugin acts_as_commentable

This command should have created the following files and directories:

create  vendor/plugins/acts_as_commentable/lib
create  vendor/plugins/acts_as_commentable/tasks
create  vendor/plugins/acts_as_commentable/test
create  vendor/plugins/acts_as_commentable/README
create  vendor/plugins/acts_as_commentable/Rakefile
create  vendor/plugins/acts_as_commentable/init.rb
create  vendor/plugins/acts_as_commentable/install.rb
create  vendor/plugins/acts_as_commentable/lib/acts_as_commentable.rb
create  vendor/plugins/acts_as_commentable/tasks/acts_as_commentable_tasks.rake
create  vendor/plugins/acts_as_commentable/test/acts_as_commentable_test.rb

In this tutorial we are just going to edit init.rb and acts_as_commentable.rb. We are also going to add a comment.rb file for our ActiveRecord model.

For the Rails environment to find you plugin correctly you need to edit the init.rb. For the acts_as_commentable plugin I had to add the following lines:

require 'acts_as_commentable'
ActiveRecord::Base.send(:include, Juixe::Acts::Commentable)

These two lines of code will enhance the ActiveRecord class to include the methods defined in the Juixe::Acts:Commentable module. The Juixe::Acts::Commentable module contains most of the implementation for this plugin.

Now let me define the basic structure of the acts_as_commentable plugin.

module Juixe
  module Acts #:nodoc:
    module Commentable #:nodoc:

      def self.included(base)
        base.extend ClassMethods
      end

      module ClassMethods
        def acts_as_commentable
          include Juixe::Acts::Commentable::InstanceMethods
          extend Juixe::Acts::Commentable::SingletonMethods
        end
      end

      module SingletonMethods
        # Add class methods here
      end

      module InstanceMethods
        # Add instance methods here
      end
    end
  end
end

Even though I still haven’t defined any methods there is a lot going on in this stub. The include and extend functions add functionality to a class or module from the named module. I have have written extensively about mixin modules with classes with include and extend in Ruby Mixin Tutorial.

Just to flush out the stub for this plugin let add and edit the Comment ActiveRecord class in comment.rb file.

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

At this point any model can act as commentable by just adding one line in you ActiveRecord class. Lets say you are writing a blog application you maybe define a Post mode as such:

class Post < ActiveRecord::Base
  acts_as_commentable
end

At this point you have a working plugin. You can add static and instance methods in the SingletonMethods and InstanceMethods, respectively, that will be available to any model that acts as commentable. Of course you can also add methods to the Comment class. For a complete listing of the code for the Acts As Commentable plugin see the project's site.

One final note, when editing a plugin I found it necessary to restart the server.

Technorati Tags: , , , , ,