Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@gkop
Last active August 29, 2015 14:26
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 gkop/1cd874ecc298ac685a81 to your computer and use it in GitHub Desktop.
Save gkop/1cd874ecc298ac685a81 to your computer and use it in GitHub Desktop.
# inspired by http://faxon.org/2015/02/03/edit-rails-activerecord-json-attributes-in-html-forms
# NOTE requires `custom_fields` column!
#
# class Foo
# include HasCustomFieldsBackedByJSON
# custom_fields_keys :bar, :baz
# end
module HasCustomFieldsBackedByJSON
extend ActiveSupport::Concern
def custom_fields_attributes=(attrs)
write_attribute(
:custom_fields,
read_attribute(:custom_fields).merge(attrs)
)
end
def custom_fields
CustomFieldset.new(
read_attribute(:custom_fields), self.class.custom_fields_keys
)
end
class_methods do
def custom_fields_keys(*keys)
# kind of weird this is both a reader and writer, hmm
if keys.any?
instance_variable_set("@custom_fields_keys", keys)
delegate *keys, to: :custom_fields, allow_nil: true
else
instance_variable_get("@custom_fields_keys") || []
end
end
end
class CustomFieldset
attr_reader :fields_keys
def initialize(hash, fields_keys)
@fields_keys = fields_keys
fields_keys.each do |key|
singleton_class.class_eval do; attr_reader key; end
instance_variable_set("@#{key}", hash[key.to_s])
end
end
def persisted?() false; end
def new_record?() false; end
def marked_for_destruction?() false; end
def _destroy() false; end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment