Skip to content

Instantly share code, notes, and snippets.

@darkhelmet
Created March 4, 2019 17:36
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 darkhelmet/4e275278ac9e293d44d4811665913b3c to your computer and use it in GitHub Desktop.
Save darkhelmet/4e275278ac9e293d44d4811665913b3c to your computer and use it in GitHub Desktop.
class ApplicationRestriction
include Virtus.model(strict: true)
def to_module(&block)
restriction = self
mod = Module.new do
define_singleton_method(:inspect) do
"#{restriction.class.name}(#{restriction.attributes})"
end
end
mod.class_eval(&block) if block_given?
mod
end
end
class ReadyAtTimeRestriction < ApplicationRestriction
attribute :ready_at, TimeWithZone
def to_module
restriction = self
super do
define_method(:ready?) do
if restriction.ready_at.past?
super()
else
false
end
end
end
end
end
class Thing < ApplicationRecord
after_initialize do
if restrictions.any?
# Look through restrictions, create appropriate classes which craete modules and prepend
# Normally the ready_at time would be in the restrictions json,
# you wouldn't actually do 10.seconds.from_now here, but it's just an example.
restriction = ReadyAtTimeRestriction.new(ready_at: 10.seconds.from_now)
mod = restriction.to_module
singleton_class.prepend(mod)
end
end
def ready?
true
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment