Skip to content

Instantly share code, notes, and snippets.

@elskwid
Last active February 8, 2016 09:16
Show Gist options
  • Save elskwid/6472192 to your computer and use it in GitHub Desktop.
Save elskwid/6472192 to your computer and use it in GitHub Desktop.
Form Model object like this: http://www.paperplanes.de/2012/12/6/form-objects-with-activemodel.html but with Virtus.
# Example:
#
# class EditForm < FormModel
# model :a
#
# attribute :title, String
#
# validates :title, presence: true
# end
#
# a = A.first
#
# f = EditForm.new(a)
# f.valid?
# # => false
#
# f.title = "A Title"
# f.valid?
# => true
#
# f = EditForm.new(a, title: "Some Title")
# f.valid?
# # => true
#
class FormModel
include Virtus
Boolean = Virtus::Attribute::Boolean # fixes Virtus boolean mapping
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
def self.model(model = nil)
return @model unless model
@model = model
end
def self.model_name
ActiveModel::Name.new(model.to_s.classify.constantize)
end
def initialize(model, attributes = {})
super(attributes)
@model = model
end
def model
@model
end
def to_key
model.to_key
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment