DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
Add Helper Methods To An ActiveRecord Model
Adds a common set of class methods to a group of models. This is obviously a silly example. View a real example of mine: http://dev.comiclog.com/file/trunk/lib/raw_sql_helper.rb.
The helper:
require 'digest/sha1'
module ShaHelper
def self.append_features(base) # :nodoc:
super
base.extend ClassMethods
end
module ClassMethods
def sha1(data)
Digest::SHA1.hexdigest data
end
end
end
The model:
class Post < ActiveRecord::Base include ShaHelper end
Usage:
<%= Post.sha1 'test' %>
Unit Test:
require File.dirname(__FILE__) + '/../test_helper'
class ShaHelperTest < Test::Unit::TestCase
include ShaHelper::ClassMethods
def test_sha1
assert_equals 'a94a8fe5ccb19ba61c4c0873d391e987982fbbd3', sha1('test')
end
end





