Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
class Render
def self.[](engine:)
Class.new(self) do
define_singleton_method(:engine) do
engine
end
define_singleton_method(:with_engine) do
engine
end
def self.inherited(subclass)
puts "subclass: #{subclass}"
puts "engine: #{subclass.engine}"
end
end
end
def render
self.class.engine.render(self.to_h)
end
end
class Render::JSON
def self.render(h)
require 'json'
JSON.generate(h)
end
end
class Memo < Render[engine: Render::JSON]
attr_accessor :title
attr_accessor :body
def to_h
{ title: title, body: body }
end
end
memo = Memo.new
memo.title = 'my title'
memo.body = 'my body'
puts memo.render
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment