Module: RedisAppJoin

Defined in:
lib/redis_app_join.rb,
lib/redis_app_join/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Instance Method Summary collapse

Instance Method Details

#cache_records(records:) ⇒ Object

will loop through records creating keys using combination of class and ID. can combine different record types (Users and Articles) in the same method call record’s attributes will be hash fields

Parameters:

  • records (Array)

    ActiveModels to cache

See Also:



11
12
13
14
15
16
17
# File 'lib/redis_app_join.rb', line 11

def cache_records(records:)
  records.each do |record|
    key = [record.class.name, record.id.to_s].join(':')
    data = record.attributes.except(:_id, :id)
    REDIS_APP_JOIN.mapped_hmset(key, data)
  end
end

#delete_records(records:) ⇒ Object

used to delete cached records after the process is done can combine different record types (Users and Articles) in the same method call

Parameters:

  • records (Array)

    ActiveModels to delete



23
24
25
26
27
28
# File 'lib/redis_app_join.rb', line 23

def delete_records(records:)
  records.each do |record|
    key = [record.class.name, record.id.to_s].join(':')
    REDIS_APP_JOIN.del(key)
  end
end

#fetch_records(record_class:, record_ids:) ⇒ Array

fetch recors from cache, cannot combine different record types (Users and Articles) in the same method call

Parameters:

  • record_class (String)
    • name of class, used in lookup

  • record_ids (Array)

    array of IDs to lookup

Returns:

  • (Array)

    array of objects and include the original record ID as one of the attributes for each object.



36
37
38
39
40
41
42
43
44
45
# File 'lib/redis_app_join.rb', line 36

def fetch_records(record_class:, record_ids:)
  output = []
  record_ids.each do |record_id|
    key = [record_class, record_id.to_s].join(':')
    data = REDIS_APP_JOIN.hgetall(key)
    # => add the key as ID attribute
    output << OpenStruct.new(data.merge(id: record_id.to_s))
  end
  return output
end

#fetch_records_field(record_class:, record_ids:, field:) ⇒ Array

retrieves specific field for an array or records (all user_ids for articles) only returns the field if it’s present cannot combine different record types in the same method call

Parameters:

  • record_class (String)
    • name of class, used in lookup

  • record_ids (Array)

    array of IDs to lookup

  • field (String)

    name of field/attribute to retrieve

Returns:

  • (Array)

    array of unique strings



55
56
57
58
59
60
61
62
63
# File 'lib/redis_app_join.rb', line 55

def fetch_records_field(record_class:, record_ids:, field:)
  output = []
  record_ids.each do |record_id|
    key = [record_class, record_id.to_s].join(':')
    data = REDIS_APP_JOIN.hget(key, field)
    output << data
  end
  return output.uniq
end