Sha256: 67dfe2b814fe7982d42cb120beb7808a8a8abefe5644a75f2141ddb156b76dc6

Contents?: true

Size: 1.86 KB

Versions: 2

Compression:

Stored size: 1.86 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
        parse_hash_tree(fields.hash_tree)
      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

2 entries across 2 versions & 1 rubygems

Version Path
headmin-0.2.5 app/models/concerns/headmin/fieldable.rb
headmin-0.2.4 app/models/concerns/headmin/fieldable.rb