Skip to content

Instantly share code, notes, and snippets.

@latortuga
Created October 11, 2012 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save latortuga/3872890 to your computer and use it in GitHub Desktop.
Save latortuga/3872890 to your computer and use it in GitHub Desktop.
ActiveModel validations without persistence
# Adapted from http://yehudakatz.com/2010/01/10/activemodel-make-any-ruby-object-feel-like-activerecord/
#
# app/models/registration.rb
class Registration
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
# Other ActiveModel modules:
# AttributeMethods: Makes it easy to add attributes that are set like table_name :foo
# Callbacks: ActiveRecord-style lifecycle callbacks.
# Dirty: Support for dirty tracking
attr_accessor(
:company_name,
:email,
:first_name,
:last_name,
:terms_of_service
)
with_options presence: true, length: { in: 2..20 } do |o|
o.validates :company_name, :first_name, :last_name
end
validates :email, presence: true, email: true
validates :terms_of_service, acceptance: true
def register
if valid?
# Do something interesting here
# - send notifications
# - log events, etc.
end
end
def persisted?
false
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment