Skip to content

Instantly share code, notes, and snippets.

@cjavdev
Created January 20, 2021 22:49
Show Gist options
  • Save cjavdev/b9244e89d26d0dd91a583b61cc275f1b to your computer and use it in GitHub Desktop.
Save cjavdev/b9244e89d26d0dd91a583b61cc275f1b to your computer and use it in GitHub Desktop.
code for an video about define_method: https://youtu.be/I0itVuoprAY
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