Skip to content

Instantly share code, notes, and snippets.

@gilbert
Last active March 10, 2020 23:55
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 gilbert/3a521bda811cdba2cf92a88263e7c15f to your computer and use it in GitHub Desktop.
Save gilbert/3a521bda811cdba2cf92a88263e7c15f to your computer and use it in GitHub Desktop.
Minimal "states" mixin in Ruby
module HasStates
def state_field(column, state_names)
state_names.each do |name|
define_method("#{name}?") do
self.send(column) == name
end
end
end
end
class MyModel
extend HasStates
state_field :status, [:start, :end]
# IRL this can be an ActiveRecord attribute, no need to def
def status
:start
end
end
m = MyModel.new
puts m.start? #=> true
puts m.end? #=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment