How do i write a cleaner date picker input for SimpleForm

后端 未结 5 1747
萌比男神i
萌比男神i 2020-12-04 07:23

I love the simple_form gem for rails but i dont like this line of code:

<%= f.input :deadline, :as => :string, :input_html => { :class          


        
5条回答
  •  感情败类
    2020-12-04 08:28

    An other option could also be to overwrite the default DateTimeInput helper, here's an example to be placed in app/inputs/date_time_input.rb

    class DateTimeInput < SimpleForm::Inputs::DateTimeInput
      def input
        add_autocomplete!
        @builder.text_field(attribute_name, input_html_options.merge(datetime_options(object.send(attribute_name))))
      end
    
      def label_target
        attribute_name
      end
    
      private
    
        def datetime_options(value = nil)
          return {} if value.nil?
    
          current_locale = I18n.locale
          I18n.locale = :en
    
          result = []
          result.push(I18n.localize(value, { :format => "%a %d %b %Y" })) if input_type =~ /date/
          if input_type =~ /time/
            hours_format = options[:"24hours"] ? "%H:%M" : "%I:%M %p"
            result.push(I18n.localize(value, { :format => hours_format }))
          end
    
          I18n.locale = current_locale
    
          { :value => result.join(', ').html_safe }
        end
    
        def has_required?
          options[:required]
        end
    
        def add_autocomplete!
          input_html_options[:autocomplete] ||= 'off'
        end
    end
    

    Please notice than while using this method makes it a drop feature for your forms, it might also break with future versions of simple_form.

    Notice about localized dates: As far as I know Ruby interprets dates following only a few formats, you might want to be careful before localizing them and make sure Ruby can handle them. An attempt to better localization support on the Ruby Date parsing as been started at https://github.com/ZenCocoon/I18n-date-parser, yet, this is not working.

提交回复
热议问题