module StringEnums
String Enums¶ ↑
StringEnum is a concern that makes it easy to work with enums. Include the module, then invoke the class method string_enum with the attribute name followed by the list of valid values. This will add checks, writers, and constants for each value.
Example¶ ↑
A class declares string_enum status: ['pending', 'in progress', 'completed']
, which adds the following… … checks:
-
pending?
-
in_progress?
-
completed?
… and writers:
-
mark_pending
-
mark_in_progress
-
mark_completed
… and constants:
-
STATUS_PENDING
-
STATUS_IN_PROGRESS
-
STATUS_COMPLETED
Note that the string values with spaces are snake cased to provide method and constant names.
Private Instance Methods
string_enum_check_value?(status_attribute_name, value)
click to toggle source
# File lib/string_enums.rb, line 54 def string_enum_check_value?(status_attribute_name, value) status = send(status_attribute_name) status.present? && status == value end
string_enum_write_value(status_attribute_name, value)
click to toggle source
# File lib/string_enums.rb, line 59 def string_enum_write_value(status_attribute_name, value) send("#{status_attribute_name}=", value) end