Sha256: 1c74c0d5a3addcb44d7e11778758a599b0986ae5cfef94a11b7987901bd51dcc

Contents?: true

Size: 1.09 KB

Versions: 11

Compression:

Stored size: 1.09 KB

Contents

module Compony
  module ModelFields
    class Anchormodel < Base
      # Takes an array of objects implementing the methods `label` and `key` and returns an array suitable for simple_form select fields.
      def self.collect(flat_array, label_method: :label, key_method: :key)
        return flat_array.map { |entry| [entry.send(label_method), entry.send(key_method)] }
      end

      def value_for(data, controller: nil, **_)
        return transform_and_join(data.send(@name), controller:) { |el| el&.label }
      end

      def simpleform_input_hidden(form, _component, name: nil, **input_opts)
        if form.object
          selected_cst = form.object.send(@name)
          am_attr = form.object.class.anchormodel_attributes[@name]
          am_serializer = (am_attr.multiple? ? ::Anchormodel::ActiveModelTypeValueMulti : ::Anchormodel::ActiveModelTypeValueSingle).new(am_attr)
          input_opts[:input_html] ||= {}
          input_opts[:input_html][:value] = am_serializer.serialize(selected_cst)
        end
        return form.input name || @name, as: :hidden, **input_opts
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
compony-0.5.3 lib/compony/model_fields/anchormodel.rb
compony-0.5.2 lib/compony/model_fields/anchormodel.rb
compony-0.5.1 lib/compony/model_fields/anchormodel.rb
compony-0.5.0 lib/compony/model_fields/anchormodel.rb
compony-0.4.1 lib/compony/model_fields/anchormodel.rb
compony-0.4.0 lib/compony/model_fields/anchormodel.rb
compony-0.3.3 lib/compony/model_fields/anchormodel.rb
compony-0.3.2 lib/compony/model_fields/anchormodel.rb
compony-0.3.1 lib/compony/model_fields/anchormodel.rb
compony-0.3.0 lib/compony/model_fields/anchormodel.rb
compony-0.2.3 lib/compony/model_fields/anchormodel.rb