Class: Yaks::Mapper::Form::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/yaks/mapper/form/field.rb,
lib/yaks/mapper/form/field/option.rb

Defined Under Namespace

Classes: Option

Constant Summary collapse

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

  def condition(blk1 = nil, &blk2)
    @config = @config.with(if: blk1 || blk2)
  end

  HTML5Forms::FIELD_OPTIONS.each do |option, _|
    def_set option
  end
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create(*args) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/yaks/mapper/form/field.rb', line 25

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

Instance Method Details

#resource_attributesObject

All attributes that can be converted 1-to-1 to Resource::Form::Field



55
56
57
# File 'lib/yaks/mapper/form/field.rb', line 55

def resource_attributes
  self.class.attributes.names - [:options, :if]
end

#resource_options(mapper) ⇒ Object



43
44
45
46
47
48
49
50
51
# File 'lib/yaks/mapper/form/field.rb', line 43

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

#to_resource_fields(mapper) ⇒ Object

Convert to a Resource::Form::Field, expanding any dynamic values



35
36
37
38
39
40
41
# File 'lib/yaks/mapper/form/field.rb', line 35

def to_resource_fields(mapper)
  return [] unless self.if.nil? || mapper.expand_value(self.if)
  [ 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