Module: ViewComponent::PolymorphicSlots::ClassMethods

Defined in:
lib/view_component/polymorphic_slots.rb

Instance Method Summary collapse

Instance Method Details

#register_polymorphic_slot(slot_name, types, collection:) ⇒ Object



27
28
29
30
31
32
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
64
# File 'lib/view_component/polymorphic_slots.rb', line 27

def register_polymorphic_slot(slot_name, types, collection:)
  unless types.empty?
    getter_name = slot_name

    define_method(getter_name) do
      get_slot(slot_name)
    end
  end

  renderable_hash = types.each_with_object({}) do |(poly_type, poly_callable), memo|
    memo[poly_type] = define_slot(
      "#{slot_name}_#{poly_type}", collection: collection, callable: poly_callable
    )

    setter_name =
      if collection
        "#{ActiveSupport::Inflector.singularize(slot_name)}_#{poly_type}"
      else
        "#{slot_name}_#{poly_type}"
      end

    # Deprecated: Will be removed in 3.0
    define_method(setter_name) do |*args, &block|
      set_polymorphic_slot(slot_name, poly_type, *args, &block)
    end
    ruby2_keywords(setter_name.to_sym) if respond_to?(:ruby2_keywords, true)

    define_method("with_#{setter_name}") do |*args, &block|
      set_polymorphic_slot(slot_name, poly_type, *args, &block)
    end
    ruby2_keywords(:"with_#{setter_name}") if respond_to?(:ruby2_keywords, true)
  end

  self.registered_slots[slot_name] = {
    collection: collection,
    renderable_hash: renderable_hash
  }
end

#renders_many(slot_name, callable = nil) ⇒ Object



20
21
22
23
24
25
# File 'lib/view_component/polymorphic_slots.rb', line 20

def renders_many(slot_name, callable = nil)
  return super unless callable.is_a?(Hash) && callable.key?(:types)

  validate_plural_slot_name(slot_name)
  register_polymorphic_slot(slot_name, callable[:types], collection: true)
end

#renders_one(slot_name, callable = nil) ⇒ Object



13
14
15
16
17
18
# File 'lib/view_component/polymorphic_slots.rb', line 13

def renders_one(slot_name, callable = nil)
  return super unless callable.is_a?(Hash) && callable.key?(:types)

  validate_singular_slot_name(slot_name)
  register_polymorphic_slot(slot_name, callable[:types], collection: false)
end