Class: Blacklight::System::DropdownComponent

Inherits:
Component
  • Object
show all
Defined in:
app/components/blacklight/system/dropdown_component.rb

Constant Summary

Constants inherited from Component

Component::EXCLUDE_VARIABLES

Instance Method Summary collapse

Methods inherited from Component

compiler, config, #inspect

Constructor Details

#initialize(param:, choices:, search_state:, id: nil, classes: [], default: nil, selected: nil, interpolation: :field) ⇒ DropdownComponent

rubocop:disable Metrics/ParameterLists



13
14
15
16
17
18
19
20
21
# File 'app/components/blacklight/system/dropdown_component.rb', line 13

def initialize(param:, choices:, search_state:, id: nil, classes: [], default: nil, selected: nil, interpolation: :field)
  @param = param
  @choices = choices
  @search_state = search_state
  @id = id
  @classes = classes.push('btn-group', "#{param.to_s.parameterize}-dropdown")
  @selected = selected || default || option_text_and_value(@choices.first)&.first
  @interpolation = interpolation
end

Instance Method Details

#before_renderObject



28
29
30
31
32
33
34
35
36
37
# File 'app/components/blacklight/system/dropdown_component.rb', line 28

def before_render
  with_button(label: button_label) unless button

  return if options.any?

  with_options(@choices.map do |option|
    text, value = option_text_and_value(option)
    { text: text, url: helpers.url_for(@search_state.params_for_search(@param => value)), selected: @selected == value }
  end)
end

#button_labelObject

rubocop:enable Metrics/ParameterLists



24
25
26
# File 'app/components/blacklight/system/dropdown_component.rb', line 24

def button_label
  t(:button_label_html, default: :label_html, scope: "blacklight.search.#{@param}", @interpolation => label_for_value(@selected))
end

#label_for_value(value) ⇒ Object

rubocop:enable Style/CaseEquality



56
57
58
59
60
# File 'app/components/blacklight/system/dropdown_component.rb', line 56

def label_for_value(value)
  choice = @choices.find { |option| option_text_and_value(option).last == value }

  choice && option_text_and_value(choice).first
end

#option_text_and_value(option) ⇒ Object

rubocop:disable Style/CaseEquality This method is from Rails to mirror how it handles native dropdowns



45
46
47
48
49
50
51
52
53
# File 'app/components/blacklight/system/dropdown_component.rb', line 45

def option_text_and_value(option)
  # Options are [text, value] pairs or strings used for both.
  if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last)
    option = option.reject { |e| Hash === e } if Array === option
    [option.first, option.last]
  else
    [option, option]
  end
end

#render?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'app/components/blacklight/system/dropdown_component.rb', line 39

def render?
  @choices.many?
end