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.



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

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



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

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



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

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

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



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
64
65
# File 'lib/expo.rb', line 35

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



22
23
24
25
26
# File 'lib/expo.rb', line 22

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



76
77
78
79
80
# File 'lib/expo.rb', line 76

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

#resetObject



28
29
30
31
32
33
# File 'lib/expo.rb', line 28

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

#sub_expo(key, object, sub_expo_passed) ⇒ Object



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

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