Sha256: 78bb216f076127a0b3c0aaf0b55f9f6782c6dee5dd4c4a23268396c5b8d4ebe9

Contents?: true

Size: 1.13 KB

Versions: 6

Compression:

Stored size: 1.13 KB

Contents

module Yaks
  class Resource
    class Form
      class Field
        include Yaks::Mapper::Form::Field.attributes.add(:error => nil)

        def value
          if type.equal? :select
            selected = options.find(&:selected)
            selected.value if selected
          else
            @value
          end
        end

        def with_value(value)
          if type.equal? :select
            with(options: select_options_for_value(value))
          else
            with(value: value)
          end
        end

        private

        def select_options_for_value(value)
          unset = ->(option) { option.selected && !value().eql?(value) }
          set   = ->(option) { !option.selected && option.value.eql?(value) }

          options.each_with_object([]) do |option, new_opts|
            new_opts << case option
                        when unset
                          option.update selected: false
                        when set
                          option.update selected: true
                        else
                          option
                        end
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
yaks-0.9.0 lib/yaks/resource/form/field.rb
yaks-0.8.3 lib/yaks/resource/form/field.rb
yaks-0.8.2 lib/yaks/resource/form/field.rb
yaks-0.8.1 lib/yaks/resource/form/field.rb
yaks-0.8.0 lib/yaks/resource/form/field.rb
yaks-0.8.0.beta2 lib/yaks/resource/form/field.rb