Skip to content

Instantly share code, notes, and snippets.

@soulcutter
Last active August 29, 2015 14:08
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 soulcutter/893fb70fc3ab66517906 to your computer and use it in GitHub Desktop.
Save soulcutter/893fb70fc3ab66517906 to your computer and use it in GitHub Desktop.
Basic rails delegating form object factory
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