Sha256: fc7b390adcf62477807d8cc0c1c1145229e9cca5ba4b7df5a4b813972fbdc3df

Contents?: true

Size: 1.58 KB

Versions: 19

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

require "active_support/concern"

module Decidim
  # A set of convenient methods to generate dynamic jsonb objects in a way is
  # compatible with AttirubteObject and ActiveModel thus making it easy to
  # integrate into Rails forms and similar workflows.
  module JsonbAttributes
    extend ActiveSupport::Concern

    class_methods do
      # Public: Mirrors the `attribute` interface to define attributes in
      # custom jsonb objects.
      #
      # name - Attribute's name
      # fields - The attribute's child fields
      #
      # Example:
      #   jsonb_attribute(:settings, [[:custom_setting, String], [:another_setting, Boolean])
      #   # This will generate `custom_setting`, `custom_setting=` and
      #   # `another_setting`, `another_setting=` and will keep them
      #   # syncronized with a hash in `settings`:
      #   # settings = { "custom_setting" => "demo", "another_setting" => "demo"}
      #
      # Returns nothing.
      def jsonb_attribute(name, fields, *options)
        attribute(name, { String => Object }, default: {})

        fields.each do |f, type|
          attribute f, type, *options
          define_method f do
            field = public_send(name) || {}
            field[f.to_s] || field[f.to_sym]
          end

          define_method "#{f}=" do |value|
            field = public_send(name) || {}
            value_type = self.class.attribute_types[f.to_s]
            value = value_type.cast(value) if value_type
            public_send("#{name}=", field.merge(f => super(value)))
          end
        end
      end
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
decidim-core-0.28.4 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.9 lib/decidim/jsonb_attributes.rb
decidim-core-0.28.3 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.8 lib/decidim/jsonb_attributes.rb
decidim-core-0.28.2 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.7 lib/decidim/jsonb_attributes.rb
decidim-core-0.28.1 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.6 lib/decidim/jsonb_attributes.rb
decidim-core-0.28.0 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.5 lib/decidim/jsonb_attributes.rb
decidim-core-0.28.0.rc5 lib/decidim/jsonb_attributes.rb
decidim-core-0.28.0.rc4 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.4 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.3 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.2 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.1 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.0 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.0.rc2 lib/decidim/jsonb_attributes.rb
decidim-core-0.27.0.rc1 lib/decidim/jsonb_attributes.rb