luckyframework / luckyframework/avram
Using avram_enum with options_for_select
- Dominant language
- Crystal
- Stars
- 183
- Forks
- 67
- PR merge metrics
- No merged PRs in 30d
Description
I'm trying to figure out the correct way of handling `avram_enum`.
Let's say we need to be able to specify the language and would like to offer a select field to the user.
```crystal
class Doc < BaseModel
avram_enum Lang do
Fr
En
end
table do
column lang : Doc::Lang
column title : String
column slug : String
column content : String
end
end
```
```crystal
class Docs::FormFields < BaseComponent
needs operation : SaveDoc
def render
m Shared::Field, operation.lang do |input_html|
input_html.select_input do
options_for_select operation.lang, lang_options
# option value: "0" do
# text "Français"
# end
# option value: "1" do
# text "English"
# end
end
end
m Shared::Field, operation.title
m Shared::Field, operation.slug
m Shared::Field, operation.content, &.textarea
end
private def lang_options
[
{"Français", Doc::Lang.new(:Fr).value},
{"English", Doc::Lang.new(:En).value},
]
end
end
```
```
web | Compiling...
web | Showing last frame. Use --error-trace for full trace.
web |
web | In src/components/docs/form_fields.cr:7:9
web |
web | 7 | options_for_select operation.lang, lang_options
web | ^-----------------
web | Error: no overload matches 'Docs::FormFields#options_for_select' with types Avram::PermittedAttribute(Doc::Lang | Nil), Array(Tuple(String, Int32))
web |
web | Overloads are:
web | - Lucky::SelectHelpers#options_for_select(field : Avram::PermittedAttribute(T), select_options : Array(Tuple(String, T)), **html_options)
```
So basically, we can't iterate with `.each` and we can't use the value since `Int32` does not match `T`. Also, we cannot get the key, like `Fr` or `En`, which would be useful for internationalization.
What can we do to improve this?
Contributor guide
Research direction
Start with the Lucky::SelectHelpers#options_for_select overload shown in the error and trace how Avram avram_enum values are represented. Define the desired handling for enum keys, integer values, iteration, and internationalized labels before changing the API; done should include behavior that supports the select example and coverage for the resulting options.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- crystal
- Domain
- database
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100