Skip to content

Instantly share code, notes, and snippets.

@ahmadshah
Created July 19, 2016 17:58
Show Gist options
  • Select an option

  • Save ahmadshah/9c0c4f91b10ed4e792e304072b65a3f9 to your computer and use it in GitHub Desktop.

Select an option

Save ahmadshah/9c0c4f91b10ed4e792e304072b65a3f9 to your computer and use it in GitHub Desktop.
Metable Concern for Rails ActiveRecord
module Metable
extend ActiveSupport::Concern
included do
serialize :meta, JSON
end
def is_metable?
has_attribute?(:meta)
end
def has_meta?(key)
meta = dump_meta()
meta.has_key?(key)
end
def get_meta(key, default=nil)
meta = dump_meta()
if has_meta?(key)
meta[key]
else
default
end
end
def put_meta!(key, value)
meta = dump_meta()
meta[key] = value
write_attribute(:meta, meta)
self.save!
end
def forget_meta!(key)
meta = dump_meta()
if has_meta?(key)
meta.delete(key)
write_attribute(:meta, meta)
self.save!
end
end
def dump_meta()
read_attribute(:meta)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment