(Non-active Record) Models and inheritance

I have a non-persisted model for a web form. Model is taking care of
business logic without mapping directly to a DB.

I have included validation for the form model by creating the following
Module :

module Validation::ModelValidation
[:save, :save!, :update_attribute].each{ |attr| define_method(attr){}

def method_missing(symbol, params)
if(symbol.to_s =~ /(.

def self.append_features(base)
base.send(:include, ActiveRecord::Validations)


and including in my model with:

class MyValidatedModel
include Validation::ModelValidation


In ‘MyValidatedModel’ I also have needed to add the method

def self.human_attribute_name(attr)
return @@atty_names[attr] || (attr.nil??attr:attr.humanize)

for the framework to return friendly names to ‘error_messages_for’, and
have my field names and corresponding names in a class hash as per :

@@atty_names = {
‘username’ => ‘User Name’,
‘email’ => ‘E-Mail Address’,
‘firstname’ =>‘First Name’,
‘lastname’ => ‘Last Name’,
‘dob’ => ‘Date of Birth’,

I wanted self.human_attribute_name(attr) to be in the module also, but
it wouldn’t work there, so I am looking at model inheritance for models
to achieve this.

I have other forms that I also want to use validation with.

I am thinking of creating a ValidatableModel class, with the
human_attribute_name(attr) method and associated hash in it and
including the module, and then inherit from this in all the
Non-active-record models I want to be validatable.

I am just wondering if there is a better way to solve this, and what are
the conventions for model inheritance for non-persisted models in rails.

So far I have only found discussions relating to ActiveRecord persisted
models online.

Still looking…

Small point on error,


def self.human_attribute_name(attr)
return @@atty_names[attr] || (attr.nil??attr:attr.humanize)


def self.human_attribute_name(attr)
return @@atty_names[attr] || attr.humanize

if you are duplicating this as the ternary operation was unneccessary

On 23 Jan 2008, at 13:15, Dara Ca wrote:

to achieve this.
The classic way of doing this is to have a ClassMethods module
containing the class methods you want to add.
You can then to base.extend(ClassMethods) from self.included (or since
from append_features since you’re use that)


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs