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



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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/view_component/polymorphic_slots.rb', line 38

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

    define_method("#{getter_name}?") do
      get_slot(slot_name).present?
    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

    define_method(setter_name) do |*args, &block|
      if _warn_on_deprecated_slot_setter
        ViewComponent::Deprecation.deprecation_warning(
          "Using polymorphic slot setters like `#{setter_name}`",
          :"`with_#{setter_name}`"
        )
      end

      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

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

#renders_many(slot_name, callable = nil) ⇒ Object



31
32
33
34
35
36
# File 'lib/view_component/polymorphic_slots.rb', line 31

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



24
25
26
27
28
29
# File 'lib/view_component/polymorphic_slots.rb', line 24

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