首页 > 解决方案 > 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 所以,问题是

这对于关注点和命名空间是可能的,但这会创建混乱的代码

标签: ruby-on-railsrubyrubygemsloadingsubdirectory

解决方案


如何使通知文件夹的文件特定于模型?

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

推荐阅读