palkan / logidze

Database changes log for Rails
MIT License
1.59k stars 74 forks source link

How to list all versions of a record? #212

Open dchacke opened 2 years ago

dchacke commented 2 years ago

I'm new to this gem. Perusing the Readme, I couldn't find a method to retrieve all versions of a record.

I suppose I could just do:

[1..record.log_size].map { |v| record.at(version: v) }

But if there's a built-in way to do this, that would be even easier.

palkan commented 2 years ago

Nope, there is no API for that.

Do you have an idea how it could look like? And what is your use case?

dchacke commented 2 years ago

Something like post.versions would be fine. It could return an array with the original as the first element and then all subsequent versions in the order they were created.

I host a blog and need to list all revisions to a post with word-based diffs.

palkan commented 2 years ago

It could return an array with the original as the first element and then all subsequent versions in the order they were created

That's an interesting question whether the current version should be included or not 🤔

And I'm thinking of having an enumerator instead of returning an Array right away (since created many records could affect performance). Something like this:

post.versions #=> Enumerator

# you can use take to return all
post.versions.take

# or you take a few or call any Enumerable method
post.versions.take(2)

post.versions.find do
  _1.title == "old title"
end

# we can also add options
post.versions(reverse: true) # from older to newer
post.versions(include_self: true) # return self as the first one (default) or the last one record (if reverse: true)

And we should either use a less common name, say, post.logidze_versions or make this feature disabled by default and allow to configure the name. For example:

class Post < ApplicationRecord
  # add #versions method
  has_logidze versions_accessor: true

  # use a custom name
  has_logidze versions_accessor: :log_versions
end

WDYT? Am I missing something?

dchacke commented 2 years ago

That all sounds good to me. I vote calling it logidze_versions instead of disabling it by default. You can always just do

def arbitrary_versions_attr
  logidze_versions
end

and so no custom syntax is required.