Last active
August 29, 2015 14:08
-
-
Save soulcutter/893fb70fc3ab66517906 to your computer and use it in GitHub Desktop.
Basic rails delegating form object factory
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 PartialReportForm | |
include DelegatingFormObject.new(Report) | |
delegate :name, :name=, | |
to: :report | |
validates :name, | |
presence: true | |
end | |
module DelegatingFormObject | |
def self.new(model_class) | |
Module.new do | |
extend ActiveSupport::Concern | |
included do | |
include ActiveModel::Model | |
@_model_name = ActiveModel::Name.new(self, nil, model_class.name) | |
attr_accessor @_model_name.singular | |
delegate :persisted?, to: @_model_name.singular | |
def initialize(obj, params = {}) | |
instance_variable_set("@#{self.class.model_name.singular}".to_sym, obj) | |
super params.fetch(self.class.model_name.singular.to_sym, {}) | |
end | |
end | |
def save | |
return false unless valid? | |
public_send(self.class.model_name.singular).save(validate: false) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment