Sha256: 9a1fa940586dde3fa0d737f2fec37e40da541de59934bc59430fe6cc9926dd64

Contents?: true

Size: 1.94 KB

Versions: 6

Compression:

Stored size: 1.94 KB

Contents

module Headmin
  module Fieldable
    extend ActiveSupport::Concern

    included do
      has_many :fields, as: :fieldable, dependent: :destroy
      accepts_nested_attributes_for :fields, allow_destroy: true

      def fields_hash
        fields.order(position: :asc).map do |field|
          parse_hash_tree(field.hash_tree)
        end.reduce({}, :merge)
      end

      def fields_hash=(hash)
        parse_fields_hash(hash)
      end

      private

      def parse_fields_hash(hash)
        hash.map do |key, value|
          case value
          when Hash
            fields.build(
              name: key,
              field_type: 'group',
              fields: parse_fields_hash(value)
            )
          when Array
            fields.build(
              name: key,
              field_type: 'list',
              fields: value.map do |item|
                fields.new(name: 'item', field_type: 'group', fields: parse_fields_hash(item))
              end
            )
          when String
            fields.build(
              name: key,
              field_type: 'text',
              value: value
            )
          else
            fields.build(
              name: key,
              field_type: 'file',
              file: value
            )
          end
        end
      end

      def parse_hash_tree(hash_tree)
        Hash[hash_tree.map do |field, children|
          case field.field_type.to_sym
          when :group
            children = children.any? ? children : field.hash_tree
            [field.name, parse_hash_tree(children)]
          when :list
            children = children.any? ? children : field.hash_tree
            [field.name, children.map { |child, grand_children| parse_hash_tree(grand_children) }]
          when :image
            [field.name, field.file]
          when :file
            [field.name, field.file]
          else
            [field.name, field.value]
          end
        end]
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
headmin-0.2.9 app/models/concerns/headmin/fieldable.rb
headmin-0.3.2 app/models/concerns/headmin/fieldable.rb
headmin-0.3.1 app/models/concerns/headmin/fieldable.rb
headmin-0.2.8 app/models/concerns/headmin/fieldable.rb
headmin-0.2.7 app/models/concerns/headmin/fieldable.rb
headmin-0.2.6 app/models/concerns/headmin/fieldable.rb