README.markdown

Static Model

This is a compilation of some boilerplate code for a non–database-backed model based on ActiveModel. You might want to use this kind of static model for anything that needs to be validated but doesn’t persist to the database—such as a login authenticator or an account password reset initiator. It includes the appropriate ActiveModel modules, has a constructor that initializes attributes from a hash, and has some helper methods useful for implementing custom validations.

Example

A user lookup class like the one below could be used as the parent class for a login authenticator or an account password reset initiator. It needs to find a user via their email, which entails validating the presence of the email attribute and providing access to the user that’s consequently looked up.

class UserLookup < StaticModel
# An accessor to allow specifying the email to look up.
attr_accessor(:email)
# A reader to allow access to the user that's looked up.
attr_reader(:user)
# Require the email attribute.
validates(:email,
:presence => {:message => 'Email is required.'})
# If the email is present, ensure that a user is associated with it.
validate do
no_other_errors? && user_exists?
end
# Find the user.
def user
User.find_by_email(@email)
end
# Add an error if no user is found.
def user_exists?
user ? true : add_email_error_and_return_false
end
protected
# Add an error.
def add_email_error_and_return_false
add_error_and_return_false('Email not found', :email)
end
end