Skip to content

Instantly share code, notes, and snippets.

@okabe-yuya
Last active February 9, 2023 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okabe-yuya/ccd55d39c14d9e855c2a9bacbaba0078 to your computer and use it in GitHub Desktop.
Save okabe-yuya/ccd55d39c14d9e855c2a9bacbaba0078 to your computer and use it in GitHub Desktop.
# 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