Sha256: e560f9eeddfbed4003f05b20396d942e8ab43549a631c3f41b3a7fb3a66515f8

Contents?: true

Size: 1.36 KB

Versions: 8

Compression:

Stored size: 1.36 KB

Contents

# frozen_string_literal: true

module WCC::Contentful::RichText
  module Node
    extend ActiveSupport::Concern

    def keys
      members.map(&:to_s)
    end

    included do
      include Enumerable

      alias_method :node_type, :nodeType

      # Make the nodes read-only
      undef_method :[]=
      members.each do |member|
        undef_method("#{member}=")
      end

      # Override each so it has a Hash-like interface rather than Struct-like.
      # The goal being to mimic a JSON-parsed hash representation of the raw
      def each
        members.map do |key|
          tuple = [key.to_s, self.[](key)]
          yield tuple if block_given?
          tuple
        end
      end
    end

    class_methods do
      # Default value for node_type covers most cases
      def node_type
        name.demodulize.underscore.dasherize
      end

      def tokenize(raw, context = nil)
        raise ArgumentError, "Expected '#{node_type}', got '#{raw['nodeType']}'" unless raw['nodeType'] == node_type

        values =
          members.map do |symbol|
            val = raw[symbol.to_s]

            case symbol
            when :content
              WCC::Contentful::RichText.tokenize(val, context)
              # when :data
              # TODO: resolve links...
            else
              val
            end
          end

        new(*values)
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
wcc-contentful-1.4.0 lib/wcc/contentful/rich_text/node.rb
wcc-contentful-1.4.0.rc3 lib/wcc/contentful/rich_text/node.rb
wcc-contentful-1.4.0.rc2 lib/wcc/contentful/rich_text/node.rb
wcc-contentful-1.3.2 lib/wcc/contentful/rich_text/node.rb
wcc-contentful-1.4.0.rc1 lib/wcc/contentful/rich_text/node.rb
wcc-contentful-1.3.1 lib/wcc/contentful/rich_text/node.rb
wcc-contentful-1.3.0 lib/wcc/contentful/rich_text/node.rb
wcc-contentful-1.2.1 lib/wcc/contentful/rich_text/node.rb