Skip to content

Instantly share code, notes, and snippets.

@MITSUBOSHI
Created March 9, 2021 05:03
Show Gist options
  • Save MITSUBOSHI/f306f3efee2b8936ef5828850e969919 to your computer and use it in GitHub Desktop.
Save MITSUBOSHI/f306f3efee2b8936ef5828850e969919 to your computer and use it in GitHub Desktop.
# 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