Last active
February 8, 2016 09:16
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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