Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Add Helper Methods To An ActiveRecord Model

DZone's Guide to

Add Helper Methods To An ActiveRecord Model

·
Free Resource
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
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}