Skip to content

Instantly share code, notes, and snippets.

@bkudria
Created January 19, 2018 04:27
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 bkudria/82e3721d4ec2b62a2a3d95050e964d84 to your computer and use it in GitHub Desktop.
Save bkudria/82e3721d4ec2b62a2a3d95050e964d84 to your computer and use it in GitHub Desktop.
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