Sha256: eab26c6b59229d90e0000e0d84f81993452eb82721e846d51075df86baa36cce

Contents?: true

Size: 2 KB

Versions: 3

Compression:

Stored size: 2 KB

Contents

module Arbre
  module Html

    # HTML attributes hash. Behaves like a hash with some minor differences:
    #
    # - Indifferent access: everything is stored as strings, but also values.
    # - Setting an attribute to +true+ sets it to the name of the attribute, as per the HTML
    #   standard.
    # - Setting an attribute to +false+ or +nil+ will remove it.
    class Attributes

      def initialize(attributes = {})
        @attributes = {}
        update attributes
      end

      def self.[](*args)
        Attributes.new(Hash[*args])
      end

      def [](attribute)
        if attribute.to_s == 'class'
          @attributes['class'] ||= ClassList.new
        else
          @attributes[attribute.to_s]
        end
      end
      def []=(attribute, value)
        if attribute.to_s == 'class'
          if value.present?
            @attributes['class'] = ClassList.new(value)
          else
            remove 'class'
          end
        elsif value == true
          @attributes[attribute.to_s] = attribute.to_s
        elsif value
          @attributes[attribute.to_s] = value.to_s
        else
          remove attribute
        end
      end

      def remove(attribute)
        @attributes.delete attribute.to_s
      end

      def update(attributes)
        attributes.each { |k, v| self[k] = v }
      end

      def ==(other)
        to_hash == other.to_hash
      end

      def eql?(other)
        other.is_a?(Attributes) && self == other
      end

      def has_key?(key)
        @attributes.has_key?(key.to_s)
      end

      include Enumerable
      delegate :each, :empty?, :length, :size, :count, :to => :@attributes

      def pairs
        map do |name, value|
          next if name == 'class' && value.blank?
          "#{html_escape(name)}=\"#{html_escape(value)}\""
        end
      end

      def to_hash
        @attributes
      end

      def to_s
        pairs.join(' ').html_safe
      end

      protected

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

    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
arbre2-2.2.1 lib/arbre/html/attributes.rb
arbre2-2.2.0 lib/arbre/html/attributes.rb
arbre2-2.1.0 lib/arbre/html/attributes.rb