Class: Expo

Inherits:
Object
  • Object
show all
Defined in:
lib/expo.rb

Defined Under Namespace

Classes: Proxy

Constant Summary collapse

CALL_ORDER =
[:aside, :expose, :sub_expo, :collection]
TRIVIAL_PRESENTER =
Class.new do
  def present(object)
    object
  end
end.new

Instance Method Summary collapse

Constructor Details

#initialize(presenter = nil, &block) ⇒ Expo

Returns a new instance of Expo.



10
11
12
13
14
15
16
17
18
# File 'lib/expo.rb', line 10

def initialize(presenter=nil, &block)
  @presenter = presenter
  @block = block
  @message_map = {}
  @subs = {}
  @collections = {}
  @inner_calls = []
  @id = self.object_id
end

Instance Method Details

#aside(*messages) ⇒ Object



65
66
67
68
69
70
71
72
# File 'lib/expo.rb', line 65

def aside(*messages)
  array, hash = parse_arguments(messages)
  @context.merge!(hasherize(array) {|msg| @preso.send(msg) })
  hash.each do |k,v|
    @context[v] = @preso.send(k)
  end
  nil
end

#collection(key, collection, item_expo) ⇒ Object



89
90
91
92
93
94
95
96
# File 'lib/expo.rb', line 89

def collection(key, collection, item_expo)
  @inner_calls << {
    method: :collection_inner,
    args: [key, collection, item_expo],
    block: nil
  }
  nil
end

#expo(object, context = {}) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/expo.rb', line 33

def expo(object, context={})

  @object = object
  @context = context
  if object.nil?
    return nil
  end
  @preso = Proxy.new(
    object,
    (@presenter || TRIVIAL_PRESENTER).present(object)
  )
  if !@block
    return {}
  end
  block_return = self.instance_exec @object, context, &@block
  @inner_calls.each do |call|
    self.send(call[:method], *call[:args], &call[:block])
  end
  exposition = {}
  @message_map.each do |k,v|
    exposition[v] = @preso.send(k)
  end
  exposition.merge!(@subs)
  exposition.merge!(@collections)
  self.reset
  if block_return
    exposition.merge(block_return)
  else
    exposition
  end
end

#expo_collection(objects, context = {}) ⇒ Object



20
21
22
23
24
# File 'lib/expo.rb', line 20

def expo_collection(objects, context={})
  objects.map.with_index do |object, index|
    Expo.new(@presenter, &@block).expo(object, context.merge({index: index}))
  end
end

#expose(*messages) ⇒ Object



74
75
76
77
78
# File 'lib/expo.rb', line 74

def expose(*messages)
  array, hash = parse_arguments(messages)
  @message_map.merge!(hasherize(array).merge(hash))
  nil
end

#resetObject



26
27
28
29
30
31
# File 'lib/expo.rb', line 26

def reset
  @message_map = {}
  @subs = {}
  @collections = {}
  @inner_calls = []
end

#sub_expo(key, object, sub_expo_passed) ⇒ Object



80
81
82
83
84
85
86
87
# File 'lib/expo.rb', line 80

def sub_expo(key, object, sub_expo_passed)
  @inner_calls << {
    method: :sub_expo_inner,
    args: [key, object, sub_expo_passed],
    block: nil
  }
  nil
end