Created
June 25, 2013 17:31
-
-
Save russ/5860492 to your computer and use it in GitHub Desktop.
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
module Unform | |
extend ActiveSupport::Concern | |
class FormObject | |
include Virtus | |
include ActiveModel::Validations | |
end | |
included do | |
@models = {} | |
class_eval do | |
def self.models | |
@models | |
end | |
end | |
end | |
def initialize(params = {}) | |
self.class.models.each do |name, model| | |
instance_variable_set(:"@#{name}", model.new) | |
instance_eval("def #{name}() @#{name}; end") | |
instance_eval("def #{name}=(val) @#{name} = val; end") | |
end | |
params.each do |model, values| | |
self.send(model).attributes = values | |
end | |
end | |
def attributes | |
params = {} | |
self.class.models.each do |key, model| | |
params[key] = self.send(key).attributes | |
end | |
params | |
end | |
def attributes=(params) | |
params.each do |key, values| | |
self.send(key).attributes = values | |
end | |
end | |
def valid? | |
self.class.models.any? do |name, model| | |
if self.send(name).valid? | |
true | |
else | |
false | |
end | |
end | |
end | |
module ClassMethods | |
def on(model, &block) | |
@models[model] ||= FormObject.class_eval(&block) | |
end | |
end | |
end |
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
class UserForm | |
include Unform | |
on :user do | |
validates :email, presence: true | |
validates :password, presence: true | |
attribute :email, String | |
attribute :password, String | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment