Class: Slotify::Partial

Inherits:
Object
  • Object
show all
Includes:
SymbolInflectionHelper
Defined in:
lib/slotify/partial.rb

Constant Summary collapse

RESERVED_SLOT_NAMES =
[
  :content, :slot, :value, :content_for,
  :capture, :yield, :partial
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from SymbolInflectionHelper

#plural?, #singular?, #singularize

Constructor Details

#initialize(view_context, slots = []) ⇒ Partial

Returns a new instance of Partial.



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

def initialize(view_context, slots = [])
  @view_context = view_context
  @outer_partial = view_context.partial
  @values = ValueStore.new(@view_context)
  @defined_slots = nil

  define_slots!(slots)
end

Instance Attribute Details

#outer_partialObject (readonly)

Returns the value of attribute outer_partial.



10
11
12
# File 'lib/slotify/partial.rb', line 10

def outer_partial
  @outer_partial
end

Instance Method Details

#capture(*args, &block) ⇒ Object



34
35
36
# File 'lib/slotify/partial.rb', line 34

def capture(*args, &block)
  @captured_buffer = @view_context.capture(*args, self, &block)
end

#contentObject



42
43
44
# File 'lib/slotify/partial.rb', line 42

def content
  self.yield
end

#content_for(slot_name) ⇒ Object

Raises:



21
22
23
24
25
26
# File 'lib/slotify/partial.rb', line 21

def content_for(slot_name)
  raise UnknownSlotError, "unknown slot :#{slot_name}" unless slot?(slot_name)

  slot_values = values.for(slot_name)
  singular?(slot_name) ? slot_values.first : ValueCollection.new(slot_values)
end

#content_for?(slot_name) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



28
29
30
31
32
# File 'lib/slotify/partial.rb', line 28

def content_for?(slot_name)
  raise UnknownSlotError, "unknown slot :#{slot_name}" unless slot?(slot_name)

  values.for(slot_name).any?
end

#set_slot_default(slot_name, default_value) ⇒ Object

Raises:



46
47
48
49
50
51
52
# File 'lib/slotify/partial.rb', line 46

def set_slot_default(slot_name, default_value)
  raise UnknownSlotError, "unknown slot :#{slot_name}" unless slot?(slot_name)

  if values.for(slot_name).none? && !default_value.nil?
    values.add(slot_name, Array.wrap(default_value))
  end
end

#slot_localsObject



54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/slotify/partial.rb', line 54

def slot_locals
  pairs = @defined_slots.map do |slot_name|
    slot_values = values.for(slot_name)
    slot_values = singular?(slot_name) ? slot_values&.first : slot_values
    [slot_name, slot_values]
  end

  pairs.filter do |key, value|
    # keep empty strings as local value but filter out empty arrays
    # and objects so they don't override any default values set via strict slots.
    value.is_a?(String) || value&.present?
  end.to_h
end

#yield(*args) ⇒ Object



38
39
40
# File 'lib/slotify/partial.rb', line 38

def yield(*args)
  args.empty? ? @captured_buffer : content_for(args.first)
end