discourse-chat-integration/app/models/plugin_model.rb

39 lines
1.1 KiB
Ruby
Raw Normal View History

class DiscourseChat::PluginModel < PluginStoreRow
PLUGIN_NAME = 'discourse-chat-integration'
KEY_PREFIX = 'unimplemented'
after_initialize :init_plugin_model
2017-09-24 23:06:27 -04:00
default_scope { self.default_scope }
def init_plugin_model
self.type_name ||= 'JSON'
2017-08-01 15:53:39 -04:00
self.plugin_name ||= PLUGIN_NAME
end
2017-08-01 15:53:39 -04:00
# Restrict the scope to JSON PluginStoreRows which are for this plugin, and this model
2017-08-01 15:53:39 -04:00
def self.default_scope
where(type_name: 'JSON')
2017-08-01 15:53:39 -04:00
.where(plugin_name: self::PLUGIN_NAME)
2017-09-24 23:06:27 -04:00
.where("key LIKE ?", "#{self::KEY_PREFIX}%")
end
2017-08-01 15:53:39 -04:00
before_save :set_key
2017-09-24 23:06:27 -04:00
2017-08-01 15:53:39 -04:00
private
2017-09-24 23:06:27 -04:00
def set_key
self.key ||= self.class.alloc_key
end
def self.alloc_key
raise "KEY_PREFIX must be defined" if self::KEY_PREFIX == 'unimplemented'
DistributedMutex.synchronize("#{self::PLUGIN_NAME}_#{self::KEY_PREFIX}_id") do
max_id = PluginStore.get(self::PLUGIN_NAME, "#{self::KEY_PREFIX}_id")
max_id = 1 unless max_id
PluginStore.set(self::PLUGIN_NAME, "#{self::KEY_PREFIX}_id", max_id + 1)
"#{self::KEY_PREFIX}#{max_id}"
end
end
end