Created
January 20, 2021 22:49
-
-
Save cjavdev/b9244e89d26d0dd91a583b61cc275f1b to your computer and use it in GitHub Desktop.
code for an video about define_method: https://youtu.be/I0itVuoprAY
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
class ModelBase | |
def self.enum(**kwargs) | |
kwargs.each do |key, values| | |
define_method("#{key}=") do |v| | |
if values.include?(v) | |
instance_variable_set("@#{key}", v) | |
else | |
raise "Not a valid status: #{v}" | |
end | |
end | |
define_method(key) do | |
instance_variable_get("@#{key}") | |
end | |
values.each do |v| | |
define_method("#{v}!") do | |
self.send("#{key}=", v) | |
end | |
define_method("#{v}?") do | |
self.send(key) == v | |
end | |
end | |
end | |
end | |
end | |
class Event < ModelBase | |
enum status: [:pending, :success, :failed] | |
end | |
event = Event.new | |
event.pending! | |
puts event.success? | |
puts event.pending? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment