module ActiveNotifier module Configurable def self.included(base) base.extend ClassMethods end module ClassMethods def config @config ||= Configuration.new end def configure yield config end end class Configuration # 常量名, 简化调用, 符号,默认 :Notifier (如果被占用请更换) def const_name @const_name || :Notifier end def const_name=(const_name) const_name = const_name.to_sym const_name = "Notifier" if const_name.empty? if Kernel.const_defined?(const_name) raise ActiveNotifier::ConfigureError, "const_name 已经存在,请在 initializers 中定义其他值" end Kernel.const_set(const_name, ActiveNotifier) @const_name = const_name end # 消息适配器, 字符串, 默认 :dingtalk def adapter @adapter || :dingtalk end def adapter=(adapter) adapter = adapter.to_sym unless valid_adapters.include?(adapter) raise ActiveNotifier::ConfigureError, "adapter 当前只支持:#{valid_adapters.join(', ')}" end @adapter = adapter end # 消息渠道的 webhook 设置 def channel_webhooks @channel_webhooks || {} end def channel_webhooks=(channel_webhooks) channel_webhooks = channel_webhooks.to_h.symbolize_keys unless channel_webhooks.key?(:default) && channel_webhooks[:default].present? raise ActiveNotifier::ConfigureError, "channel_webhooks 请至少设置 default 键" end @channel_webhooks = channel_webhooks end # 消息模版主目录, 字符串, 默认 views/notifier/application), 不需要加模版后缀 def template_home @template_home || "#{__dir__}/templates" end def template_home=(template_home) template_home = template_home.to_s raise ActiveNotifier::ConfigureError, "模板主目录不能为空" if template_home.empty? @template_home = template_home end # 消息模版, 字符串, 默认 default($template_home/default), 不需要加模版后缀 def template @template || "default" end def template=(template) template = template.to_s raise ActiveNotifier::ConfigureError, "模板名不能为空" if template.empty? @template = template end # 消息优先类型, 字符串, 默认 :markdown, 对应模板后缀名,如果未指定该参数且存在多个模板,则优先选择此类型 def priority_type @priority_type || :markdown end def priority_type=(priority_type) @priority_type = priority_type.to_sym end private def valid_adapters @valid_adapters ||= begin found_adapters = Dir["*_adapter.rb", base: "#{__dir__}/adapters"] found_adapters.map { |adapter| adapter.sub("_adapter.rb", "").to_sym } - [:abstract] end end end end end