ruby-on-rails - Ruby on Rails:在 app 目录中添加子文件夹,其中包含特定于模型的文件
问题描述
我正在编写一个gem,它将处理模型的所有类型的通知(短信、移动和浏览器通知)
在 app 目录下的 rails 项目中创建了新文件夹“notifiers”,其中包含如下文件
app/notifiers/user_notifier.rb
class UserNotifier < ApplicationNotifier
def send_reminder
{
type: 'sms',
content: 'hi everyone',
recipients: [12134343,2342322,3434343]
}
end
end
这个 user_notifier 文件应该针对 User 模型。表示此方法 send_reminder 应该可用于 User 的实例/对象
User.last.send_reminder
所以,问题是
- 如何使通知程序文件夹的文件特定于模型(user.rb 模型文件在通知程序文件夹中有 user_notifier.rb 文件)
- 此文件 user_notifier.rb 方法如何可用于用户模型
这对于关注点和命名空间是可能的,但这会创建混乱的代码
解决方案
如何使通知文件夹的文件特定于模型?
app 文件夹下的所有代码都是在没有任何配置的情况下加载的。您只需要尊重类的命名约定。在这种情况下UserNotifier
是正确的名称app/notifiers/user_notifier.rb
。
这个文件 user_notifier.rb 方法如何对用户模型可用?
# app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
# your code
def send_notification(notification_name, recipients)
notifier = "#{self.class.name}Notifier".constantize.new()
send(notification_name, recipients)
end
end
# app/models/user.rb
class User < ApplicationRecord
# your code
# a method where you want to send a notification
def foo
send_notification(:reminder, [id])
end
end
# app/notifiers/user_notifier.rb
class UserNotifier < ApplicationNotifier
def reminder(recipients)
{
type: 'sms',
content: 'hi everyone',
recipients: recipients
}
end
end
推荐阅读
- python - 使用 sha512_crypt 解密密码 - python3
- symmetricds - 初始加载在 sym_x 表模式中创建我的表
- android - Notification is coming sometimes and sometimes not coming when the app is in foreground using firebase notifications in Flutter for android
- mysql - Names of months as names of columns in MySQL
- android - RX How to subscribe only to specific events on a Subject
- python - 通过 Wikipedia 构建语料库:ModuleNotFoundError: No module named 'gensim'
- c++ - 使用 QXmlStreamReader 解析 XSD
- c++ - 将 lambda 用于回调函数作为 C 函数参数
- javascript - 这个倒计时的执行顺序是什么?
- heroku - Heroku 无法生成分发要求 -lotly 2.7.0