Sha256: d8829260ba8835f9a05e0a7a6a0f57a974e309b42af0ffb62b957851a2f4f20a

Contents?: true

Size: 1.45 KB

Versions: 4

Compression:

Stored size: 1.45 KB

Contents

module Yaks
  class Mapper
    class Form
      class Field
        include Attributes.new(
                  :name,
                  label: nil,
                  options: [].freeze
                ).add(HTML5Forms::FIELD_OPTIONS)

        Builder = Builder.new(self) do
          def_set :name
          def_set :label
          def_add :option, create: Option, append_to: :options
        end

        def self.create(*args)
          attrs = args.last.instance_of?(Hash) ? args.pop : {}
          if name = args.shift
            attrs = attrs.merge(name: name)
          end
          new(attrs)
        end

        # Convert to a Resource::Form::Field, expanding any dynamic
        # values
        def to_resource(mapper)
          Resource::Form::Field.new(
            resource_attributes.each_with_object({}) do |attr, attrs|
              attrs[attr] = mapper.expand_value(public_send(attr))
            end.merge(options: resource_options(mapper))
          )
        end

        def resource_options(mapper)
          # make sure all empty options arrays are the same instance,
          # makes for prettier #pp
          options.empty? ? options : options.map {|opt| opt.to_resource_field_option(mapper) }
        end

        # All attributes that can be converted 1-to-1 to
        # Resource::Form::Field
        def resource_attributes
          self.class.attributes.names - [:options]
        end
      end #Field
    end # Form
  end # Mapper
end # Yaks

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
yaks-0.8.3 lib/yaks/mapper/form/field.rb
yaks-0.8.2 lib/yaks/mapper/form/field.rb
yaks-0.8.1 lib/yaks/mapper/form/field.rb
yaks-0.8.0 lib/yaks/mapper/form/field.rb