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

[Feature] Enum support #87

Closed
Epigene opened this issue Nov 9, 2017 · 3 comments
Closed

[Feature] Enum support #87

Epigene opened this issue Nov 9, 2017 · 3 comments

Comments

@Epigene
Copy link

Epigene commented Nov 9, 2017

Hi!

I am interested in developing a sort of enum support for jsonb fields.

The use case:
A JSONB field key should be allowed to have one of a predefined set of (string) values.

Pseudocode of DSL:

class Product
  jsonb_accessor :data,
    status: [:string, enum: [:available, :en_route, :unavailable], default: :available]   
end

p = Product.new
p.status #=> "available"
p.status = "en_route" #=> "en_route"
p.status #=> "en_route"
p.data
#=> {
  "status" => "en_route"
}

p.status = "discontinued" #=> RuntimeError, status "discontinued" not supported, try [:available, :en_route, :unavailable].

Does this sound like something that would get added to this gem were I to make a PR?

@abhiyan52
Copy link

Hey what is the status of this feature?

@preetsethi
Copy link

preetsethi commented Oct 31, 2019

I tried this:

jsonb_accessor :index_config,
    index_scope: [:string, default: "off"],
    multi_field_op: [:string, default: "or"]

  enum index_scope: {
    off: "off",
    source: "source",
    global: "global"
  }, _prefix: :index

  enum multi_field_op: {
    combined_uniqueness: "and",
    field_uniqueness: "or"
  }

Declare fields with jsonb_accessor then define Rails enum (using Hash) on field.
Works flawlessly!!!

Original proposal:

p.status = "discontinued" #=> RuntimeError, status "discontinued" not supported, try [:available, :en_route, :unavailable].

Rails enum:

Model.last.update({index_scope: "bad option"})
ArgumentError: 'bad option' is not a valid index_scope

@haffla
Copy link
Contributor

haffla commented May 6, 2021

As @preetsethi has demonstrated this works perfectly fine. Thanks

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

No branches or pull requests

4 participants