Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Literal::Enum indexes #64

Merged
merged 5 commits into from
Nov 21, 2023
Merged

Literal::Enum indexes #64

merged 5 commits into from
Nov 21, 2023

Conversation

joeldrapper
Copy link
Owner

@joeldrapper joeldrapper commented Nov 20, 2023

In this PR, I’m adding an index macro to Enum, which allows you to generate Hash indexes for O(1) lookups. The index can be generated from any attribute or Proc calculation on a member.

class Language < Literal::Enum(Integer)
  index :name, String, unique: true

  EN(0) do
    def name = "English"
  end

  FR(1) do
    def name = "French"
  end
end

Language.where(name: "English") # => [Language::EN]
Language.find_by(name: "English") # => Language::EN

You can only use find_by for unique indexes.

The indexes are generated using a Proc, which defaults to name.to_proc, however you a pass a block instead.

index :name, String, unique: true do |language|
  language.name.upcase
end

@@ -1,6 +1,10 @@
# frozen_string_literal: true

class Literal::Enum
include Literal::ModuleDefined
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should extend Literal::Types here now that index accepts a type argument.

@joeldrapper joeldrapper changed the title Literal::Enum.index Literal::Enum indexes Nov 21, 2023
@stevegeek
Copy link
Collaborator

Some off the top of my head thoughts:

Could the behaviour be mixed in to subclasses as needed instead? (or maybe there is a new subclass of Enum, eg "IndexedEnum" which includes it?)

If included in base Enum could @index_definitions and @indexes hashes be created lazily, or only if indexes are defined? Though I guess the number of extra hashes created will be small given the number of Enums created in an app will prob be relatively limited

@joeldrapper
Copy link
Owner Author

@stevegeek Good idea. I think it probably makes sense to have this feature in the main Enum class, but the additional hashes could be created lazily.

@joeldrapper joeldrapper marked this pull request as ready for review November 21, 2023 13:43
@joeldrapper joeldrapper merged commit 59bfc15 into main Nov 21, 2023
1 check passed
@joeldrapper joeldrapper deleted the index-enums branch November 21, 2023 13:44
@joeldrapper joeldrapper mentioned this pull request Nov 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants