module BootstrapFormExtensions::Timespan

Constants

UNITS_IN_SECONDS

Public Instance Methods

timespan(method, units: @@units, quantity_options: {}) click to toggle source
# File lib/bootstrap_form_extensions/timespan.rb, line 14
def timespan method, units: @@units, quantity_options: {}, unit_options: {}
  quantity, selected, units = quantity_and_units_for_timespan method, units
  hidden = hidden_field method, class: 'timespan-seconds'
  field  = text_field_for_timespan method, quantity, quantity_options
  select = select_for_timespan method, selected, units, unit_options
  content_tag :span, hidden + field + ' '.html_safe + select, data: { timespan: true }
end

Private Instance Methods

quantity_and_units_for_timespan(method, units) click to toggle source
# File lib/bootstrap_form_extensions/timespan.rb, line 24
def quantity_and_units_for_timespan method, units
  units = units.map { |unit| [ unit, UNITS_IN_SECONDS[unit] ] }

  time_in_seconds = object.send method
  return [ '', units.first.last, units ] if time_in_seconds.blank?

  selected = UNITS_IN_SECONDS.values.reverse.find(proc { 1 }) { |seconds| time_in_seconds % seconds == 0 }
  quantity = time_in_seconds / selected
  [ quantity, selected, units ]
end
select_for_timespan(method, selected, units, unit_options) click to toggle source
# File lib/bootstrap_form_extensions/timespan.rb, line 48
def select_for_timespan method, selected, units, unit_options
  select_field_name = method.to_s.sub(/(_in_seconds)?$/, '_unit').to_sym
  unit_options[:class] = merge_css_classes 'form-control', 'timespan-unit', unit_options[:class]
  select = @template.select_tag select_field_name, @template.options_for_select(units, selected), unit_options
  content_tag :div, select, class: 'form-group'
end
text_field_for_timespan(method, quantity, quantity_options) click to toggle source
# File lib/bootstrap_form_extensions/timespan.rb, line 35
def text_field_for_timespan method, quantity, quantity_options
  text_field_name = method.to_s.sub(/(_in_seconds)?$/, '_quantity').to_sym

  quantity_options[:size] ||= 5
  quantity_options[:class] = merge_css_classes 'form-control', 'timespan-quantity', quantity_options[:class]
  quantity_options[:class] = merge_css_classes 'is-invalid', quantity_options[:class] if inline_error?(method)

  field = @template.text_field_tag text_field_name, quantity, quantity_options
  field << generate_error(method)

  content_tag :div, field, class: 'form-group'
end