Created
March 9, 2021 05:03
-
-
Save MITSUBOSHI/f306f3efee2b8936ef5828850e969919 to your computer and use it in GitHub Desktop.
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
# ref: https://speakerdeck.com/shioyama/the-ruby-module-builder-pattern?slide=65 | |
class Predicable < Module | |
def initialize(*attribute_names) | |
@names = attribute_names | |
end | |
def included(klass) | |
@names.each do |name| | |
define_method "#{name}?" do | |
!!self.instance_variable_get(:"@#{name}") | |
end | |
end | |
end | |
end | |
class Article | |
include Predicable.new(:draft, :archived) | |
def initialize(**state_attributes) | |
state_attributes.each do |key, val| | |
self.instance_variable_set(:"@#{key}", val) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment