You can define Kredis attributes directly within your Rails models using Kredis methods. This allows you to associate Redis keys with specific model instances.
Key features:
- Custom Keys: Use a
lambda or a method name to generate keys dynamically (e.g., key: ->(p) { "person:#{p.id}:names" }). - Default Values: Set a
default value. Note that Kredis will perform additional Redis calls (WATCH, EXISTS, UNWATCH) to ensure the default is written if the key does not exist. - Callbacks: Use
after_change to trigger logic when the Kredis attribute is mutated.
Example:
class Person < ApplicationRecord
kredis_list :names, after_change: ->(p) { puts "Names changed!" }
kredis_enum :morning, values: %w[ bright blue black ], default: "bright"
kredis_counter :steps, expires_in: 1.hour
private
def generate_names_key
"person:#{id}:names"
end
kredis_list :names_with_custom_key, key: :generate_names_key
end
class Person < ApplicationRecord
kredis_list :names
kredis_list :names_with_custom_key_via_lambda, key: ->(p) { "person:#{p.id}:names_customized" }
kredis_list :names_with_custom_key_via_method, key: :generate_names_key
kredis_unique_list :skills, limit: 2
kredis_enum :morning, values: %w[ bright blue black ], default: "bright"
kredis_counter :steps, expires_in: 1.hour
private
def generate_names_key
"key-generated-from-private-method"
end
end