lib/mystique.rb in mystique-0.1.2 vs lib/mystique.rb in mystique-0.3.0
- old
+ new
@@ -4,20 +4,24 @@
module Mystique
class Presenter
def initialize(object, context)
@__object__ = object
- @__context__ = context
+ @__context__ = context || self.class.context
end
- def self.present(object)
- new(object, context)
+ def self.present(object, context=nil)
+ self.new(object, context).tap do |presenter|
+ yield presenter if block_given?
+ end
end
- def h
- @__context__ || self.class.context
+ def context
+ @__context__
end
+ alias :ctx :context
+ alias :h :context
def target
@__object__
end
@@ -32,22 +36,28 @@
elsif __class_formats__.any? { |klass, _| value.is_a?(klass)}
__class_formats__.select { |klass, _| value.is_a?(klass)}.first.last
else
value
end
- Callable(result).call(value)
+ Callable(result).call(value, context)
end
def self.context(ctx=Undefined)
@__context__ = ctx unless ctx == Undefined
@__context__
end
- def self.format(key, value)
- __formats__[key] = value
+ def self.format(matcher, value=nil, &block)
+ __formats__[matcher] = block_given? ? block : value
end
+ def self.format_multiple(*matchers, &block)
+ matchers.each do |matcher|
+ format(matcher, &block)
+ end
+ end
+
def __formats__
self.class.__formats__
end
def self.__formats__
@@ -75,18 +85,17 @@
class Undefined; end
module_function
- def present(object, with: nil)
- from_module &&= "#{from_module.to_s.camelcase}::"
+ def present(object, with: nil, context: nil, &block)
presenter_class = case with
when nil
"#{object.class}Presenter".constantize
when Symbol, String
- "#{presenter}Presenter".constantize
+ "#{with}Presenter".constantize
else
- presenter
+ with
end
- presenter_class.present(object)
+ presenter_class.present(object, context, &block)
end
end