Skip to content

Provide Enum class method to easily generate options for Rails select fields #324

@charlesluzar

Description

@charlesluzar

Current state, in order to build a Rails select field you have to do something like this:

@f.select :federal_filing_status,
  W4::FederalFilingStatus.members.map { |status| [ status.name.split("::").last, status.value ] },
...

It'd be preferable to be able to do this...

@f.select :federal_filing_status,
  W4::FederalFilingStatus.options_for_select,
...

In order to do this, changing the behavior of to_s on a member is key. Changing to_sym is a "while you're in there." name returns the fully qualified class name as a string, and this keeps with patterns used in classes and modules. We don't want to change that, but we need a method that will return the class name as a string. to_s is perfect for that.

Color::Red.to_sym -> :Red
Color::Red.to_s -> "Red"
Color::Red.name -> "Color::Red"

We can then provide a prop human_name as a sort of override for Rails select field options...

class Status < Literal::Enum(Integer)
  prop :human_name, String

  MarriedFilingJointly = new(1, human_name: "Married filing jointly")
end

This would allow for the following on Enums:

def self.options_for_select
  map { |member| [member.human_name || member.to_s, member.value] }
end

Without a human_name, the default option is "MarriedFilingJointly."

Steps:

  • Change behavior of to_s on a member, eg: Art::Colors::Red.to_s => "Red"
  • Change behavior of to_sym on a member, eg: Art::Colors::Red.to_sym => :Red

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