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

36 lines
1.0 KiB
Ruby
Raw Normal View History

class DiscourseChat::PluginModel < PluginStoreRow
PLUGIN_NAME = 'discourse-chat-integration'
KEY_PREFIX = 'unimplemented'
after_initialize :init_plugin_model
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)
.where("key like?", "#{self::KEY_PREFIX}%")
end
2017-08-01 15:53:39 -04:00
before_save :set_key
2017-08-01 15:53:39 -04:00
private
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