I have a Model Bot
and I would like to ensure that there is only one Bot
object in my database. I also need to make sure it is persisted and not tampered with.
My original thought was to do this in a migration, one that would follow the :bots
table migration. It would include a line that is something like:
Bot.all.size == 0 ? Bot.create! : nil
Maybe this would prevent the AR object from being messed with in future migrations?
BONUS: Would be awesome to be able to have instant and global access to this class object. I was thinking using a singleton
module in my Bot
class that way I can always reference Bot.instance
and have access to that specific object.
USE CASE:
I have 4 types of users in my DB and this bot will be the facilitator to delivery role-specific messages to them through our in-app messaging feature.
The Class Bot
will have a has_many
association with BotMessage/bot_messages
. On the bot_messages
table will be an enum field for user_role
.
Messages will be created by company admins and stored in these tables because we want them to be viewable at any time by looking at the "conversation" thread between the User and the Bot.
When it comes to only having 1 bot, it's just that. I have no need for an additional Bot
object. Additionally, since there is only one object it would be nice to be able to have a way of explicitly targeting that object without having to run a query to find it.
For example, unlike User
where there could be 1000 records and in order to find the specific one you would do something like @user = User.find_by_email('foo@bar.com')
, doing something like that for the bot would be unnecessary since there is only one record to find. That is what lead me to believe having a singleton
object may be worthwhile here, so whenever I need to pull up a message for a specific role, I could run Bot.instance.bot_messages.where(user_role: 1)
or something similar