Last active
February 9, 2023 13:42
-
-
Save okabe-yuya/ccd55d39c14d9e855c2a9bacbaba0078 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ref: https://www.paweldabrowski.com/articles/rails-enum-under-the-hood | |
module Channel | |
def enum_channels(mappings) | |
mappings.each_pair do |name, values| | |
singleton_class.define_method("#{name}_hash") { values } | |
values.each_pair do |key, value| | |
define_method("#{key}?") { self.status == value } | |
end | |
end | |
end | |
end | |
class Applicant | |
extend Channel | |
enum_channels status: { invite: 0, active: 1 } | |
attr_reader :status | |
def initialize(status) | |
@status = status | |
end | |
end | |
app = Applicant.new(0) | |
puts app.active? # false | |
puts app.invite? # true | |
app = Applicant.new(1) | |
puts app.active? # true | |
puts app.invite? # false | |
puts Applicant.status_hash |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment