Last active
March 10, 2020 23:55
-
-
Save gilbert/3a521bda811cdba2cf92a88263e7c15f to your computer and use it in GitHub Desktop.
Minimal "states" mixin in Ruby
This file contains hidden or 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
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