Class: MijDiscord::Cache::ChannelCache

Inherits:
Object
  • Object
show all
Defined in:
lib/mij-discord/cache.rb

Constant Summary collapse

MAX_MESSAGES =
200

Instance Method Summary collapse

Constructor Details

#initialize(channel, bot, max_messages: MAX_MESSAGES) ⇒ ChannelCache

Returns a new instance of ChannelCache.



253
254
255
256
257
258
# File 'lib/mij-discord/cache.rb', line 253

def initialize(channel, bot, max_messages: MAX_MESSAGES)
  @channel, @bot = channel, bot
  @max_messages = max_messages

  reset
end

Instance Method Details

#get_message(key, local: false) ⇒ Object



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/mij-discord/cache.rb', line 264

def get_message(key, local: false)
  id = key&.to_id
  return @messages[id] if @messages.has_key?(id)
  return nil if local

  begin
    response = MijDiscord::Core::API::Channel.message(@bot.auth, @channel.id, key)
  rescue RestClient::ResourceNotFound
    return nil
  end

  message = @messages.store(id, MijDiscord::Data::Message.new(JSON.parse(response), @bot))
  @messages.shift while @messages.length > @max_messages

  message
end

#put_message(data, update: false) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/mij-discord/cache.rb', line 281

def put_message(data, update: false)
  id = data['id'].to_i
  if @messages.has_key?(id)
    @messages[id].update_data(data) if update
    return @messages[id]
  end

  message = @messages.store(id, MijDiscord::Data::Message.new(data, @bot))
  @messages.shift while @messages.length > @max_messages

  message
end

#remove_message(key) ⇒ Object



294
295
296
# File 'lib/mij-discord/cache.rb', line 294

def remove_message(key)
  @messages.delete(key&.to_id)
end

#resetObject



260
261
262
# File 'lib/mij-discord/cache.rb', line 260

def reset
  @messages = {}
end