Sha256: fdf9db8657baab5202e1c20e3940b4646bb02d4ab92d24aeb75770a384b8287f

Contents?: true

Size: 1.63 KB

Versions: 3

Compression:

Stored size: 1.63 KB

Contents

module Trestle
  class Form
    module Fields
      class Select < Field
        attr_reader :choices, :html_options

        def initialize(builder, template, name, choices=nil, options={}, html_options={}, &block)
          super(builder, template, name, options, &block)

          @choices = Choices.new(choices || builder.object.send(name))
          @html_options = default_html_options.merge(html_options)
        end

        def field
          builder.raw_select(name, choices, options, html_options, &block)
        end

        def default_html_options
          Trestle::Options.new(class: ["form-control"], data: { enable_select2: true })
        end

        # Allows an array of model instances (or a scope) to be
        # passed to the select field as the list of choices.
        class Choices
          include Enumerable
          alias empty? none?

          def initialize(choices)
            @choices = Array(choices)
          end

          def each
            @choices.each do |option|
              yield option_text_and_value(option)
            end
          end

        protected
          def option_text_and_value(option)
            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]
            elsif option.respond_to?(:id)
              [Trestle::Display.new(option).to_s, option.id]
            else
              [option, option]
            end
          end
        end
      end
    end
  end
end

Trestle::Form::Builder.register(:select, Trestle::Form::Fields::Select)

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
trestle-0.8.6 lib/trestle/form/fields/select.rb
trestle-0.8.5 lib/trestle/form/fields/select.rb
trestle-0.8.4 lib/trestle/form/fields/select.rb