Sha256: e684872eb2137fcef6717b5d71d2e942f7139a7822b70b12feabf67e11675730

Contents?: true

Size: 889 Bytes

Versions: 2

Compression:

Stored size: 889 Bytes

Contents

# frozen_string_literal: true
module Arbre
  module HTML

    class Attributes < Hash

      def to_s
        flatten_hash.map do |name, value|
          next if value_empty?(value)
          "#{html_escape(name)}=\"#{html_escape(value)}\""
        end.compact.join ' '
      end

      def any?
        super{ |k,v| !value_empty?(v) }
      end

      protected

      def flatten_hash(hash = self, old_path = [], accumulator = {})
        hash.each do |key, value|
          path = old_path + [key]
          if value.is_a? Hash
            flatten_hash(value, path, accumulator)
          else
            accumulator[path.join('-')] = value
          end
        end
        accumulator
      end

      def value_empty?(value)
        value.respond_to?(:empty?) ? value.empty? : !value
      end

      def html_escape(s)
        ERB::Util.html_escape(s)
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
arbre-1.7.0 lib/arbre/html/attributes.rb
arbre-1.6.0 lib/arbre/html/attributes.rb