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