Skip to content

Instantly share code, notes, and snippets.

@mrbongiolo
Created October 8, 2015 20:58
Show Gist options
  • Save mrbongiolo/bbabbda0bbd8f57769a0 to your computer and use it in GitHub Desktop.
Save mrbongiolo/bbabbda0bbd8f57769a0 to your computer and use it in GitHub Desktop.
A Decorator module for Trailblazer, basically it's just a copy of the Representer module, but it only adds the rendering methods.
# Including this will change the way the Operation renders the contract
#
# TODO: so far, we only support JSON, but it's two lines to change to support any kind of format.
module Trailblazer::Operation::Decorator
def self.included(base)
base.inheritable_attr :_decorator_class
base.extend ClassMethods
end
module ClassMethods
def decorator(constant=nil, &block)
return decorator_class unless constant or block_given?
self.decorator_class= Class.new(constant) if constant
decorator_class.class_eval(&block) if block_given?
end
def decorator_class
self._decorator_class ||= infer_decorator_class
end
def decorator_class=(constant)
self._decorator_class = constant
end
def infer_decorator_class
Disposable::Twin::Schema.from(contract_class,
include: [Representable::JSON],
superclass: Representable::Decorator,
representer_from: lambda { |inline| inline.representer_class },
)
end
end
private
module Rendering
def to_json(*)
self.class.decorator_class.new(decorated).to_json
end
def decorated
contract
end
end
include Rendering
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment