Created
July 19, 2016 17:58
-
-
Save ahmadshah/9c0c4f91b10ed4e792e304072b65a3f9 to your computer and use it in GitHub Desktop.
Metable Concern for Rails ActiveRecord
This file contains hidden or 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
| 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