Skip to content

Default proc if empty #66

@tleish

Description

@tleish

Is there a way to set a default value for a list using a proc? I'm thinking something like:

class User < ApplicationRecord
  kredis_list :role_ids, default: ->(user) { user.roles.pluck(:id) }
end

Then if there's a nil value (either because it was never created or expired at some point), it recreates itself with the latest data.

I can accomplish the same thing with:

class User < ApplicationRecord
  kredis_list :role_ids_cache, default: ->(user) { user.roles.pluck(:id) }

  def role_ids
    self.role_ids_cache.append(self.roles.pluck(:id)) unless self.role_ids_cache.elements.empty?
    self.role_ids_cache
  end
end

... but I prefer dealing with one method/variable vs two.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions