Method: MiniCache::Store#set

Defined in:
lib/mini_cache/store.rb

#set(key, value = nil, expires_in: nil) ⇒ Object

Public: Sets a value for a given key either as an argument or block.

key - A String or Symbol representing the key. value - Any object that represents the value (optional).

The value can be a MiniCache::Data.
Not used if a block is given.

block - A block of code that returns the value to set (optional).

Can be set a MiniCache::Data in the block.

expires_in - Time, in seconds, to expire the cache (optional).

If not set, the cache never expires.

Examples

cache.set("name", "Derrick")
=> "Derrick"

cache.set("name", "Derrick", expires_in: 60)
=> "Derrick"

cache.set("name") { "Joe" }
=> "Joe"

cache.set("name") { MiniCache::Data.new("Joe", 60) }
=> "Joe"

Returns the value given.



60
61
62
63
64
65
66
67
68
69
# File 'lib/mini_cache/store.rb', line 60

def set(key, value = nil, expires_in: nil)
  check_key!(key)
  data = block_given? ? yield : value
  @data[key.to_s] = if data.is_a?(MiniCache::Data)
                      data
                    else
                      MiniCache::Data.new(data, expires_in: expires_in)
                    end
  get(key)
end