Skip to content

Instantly share code, notes, and snippets.

@rlogwood
Created May 6, 2021 23:40
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 rlogwood/c1871a593ffaba34305ddd9a6af5fe6b to your computer and use it in GitHub Desktop.
Save rlogwood/c1871a593ffaba34305ddd9a6af5fe6b to your computer and use it in GitHub Desktop.
Rails ActiveModel::Model Example, an alternative to ActiveRecord when you don't need the DB
# NOTE: this a partial copy of some working code from a working Rails app
# *However* it hasn't been tested on it's own, shown here as an example of
# using ActiveModel::Model as an alternative to ActiveRecord when you don't
# need the DB
class ContactRequest
include ActiveModel::Model
def self.define_sanitized_attr(attr)
define_method(attr) do
instance_variable_get("@#{attr}")
end
define_method("#{attr}=") do |val|
val = ActionView::Base.full_sanitizer.sanitize(val)
instance_variable_set("@#{attr}", val)
end
end
ATTRS = %i[name email email_confirmation phone message country_code].freeze
ATTRS.each do |attr|
define_sanitized_attr attr
end
def self.contact_request_from_params(params)
contact_request = ContactRequest.new
Rails.logger.info("contact_request has following instance variables #{contact_request.instance_variables}")
ATTRS.each do |attr_name|
prop_name = "@#{attr_name}".to_sym
Rails.logger.info("setting attribute #{attr_name} to prop #{prop_name} = value #{params[attr_name]}")
contact_request.instance_variable_set(prop_name, params[attr_name]) if params.key?(attr_name)
end
contact_request
end
validates :name, :email, :email_confirmation, :message, :country_code, presence: { message: "%{attribute} must be given please" }
validates :email, confirmation: { case_sensitive: false }
validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
validates :name, length: { minimum: 2, too_short: "Name must be at least %{count} characters" }
validates :message, length: { maximum: 2000, too_long: "%{count} characters is the maximum allowed."}
def persisted?
true
end
def id
nil
end
def to_hash
hash = {}
ATTRS.each do |attr_name|
prop_name = "@#{attr_name}".to_sym
if value = instance_variable_get(prop_name)
hash[attr_name.to_s] = value
end
end
hash
end
def to_param
if persisted?
to_hash
else
nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment