Skip to content

Instantly share code, notes, and snippets.

@hugobast
Created November 28, 2014 15:21
Show Gist options
  • Save hugobast/a7e52c49ac51e707cd64 to your computer and use it in GitHub Desktop.
Save hugobast/a7e52c49ac51e707cd64 to your computer and use it in GitHub Desktop.
Reform ActiveAdmin Extensions
module Form
module Destroyable
extend ActiveSupport::Concern
included do
# This is deprecated, what's the replacement?
property :_destroy, virtual: true
end
def new_record?
model.new_record?
end
def marked_for_destruction?
true_values.include? _destroy
end
def destroy
model.destroy
end
def save_model
destroy and return if marked_for_destruction?
super
end
end
end
module Form
module Reflections
extend ActiveSupport::Concern
def initialize(model = nil)
model ? super : super(model_class.new)
end
def model_class
self.class.model_class
end
module ClassMethods
def reflect_on_association(association)
# The idea here is to trick `reflect_on_association`
# to get a form object. The fundamental reason why is
# that using AA::FormBuilder#has_many hits this method
# and exposes the underlying model.
reflection = Reflection.new(model_name, association)
reflection.association_form
end
def klass
self
end
def model_class
model_name.name.constantize
end
end
class Reflection
attr_reader :klass, :association
def initialize(model, association)
@klass = constantize(model.name)
@association = association
end
def association_form
return unless association_model
constantize(association_form_name)
end
def association_model
return unless klass
reflection = klass.reflect_on_association(association)
return unless reflection
reflection.klass
end
def association_form_name
"#{association_model}Form"
end
def constantize(name)
# This is usually bad practice but the whole
# point of `reflect_on_association` is to return nil
# when nothing is found, this ensures just that.
name.constantize rescue nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment