Sha256: 32de453a72a98ae98dac47273b391831034dd5a854dcaa7cf7a53923c57c3854

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

module Garterbelt
  class ClosedTag < Renderer
    attr_accessor :type, :attributes, :css_class
    
    def initialize(opts)
      super
      self.type = opts[:type] || raise(ArgumentError, ":type required in initialization options")
      self.attributes = opts[:attributes] || {}
      
      css_class = attributes.delete(:class)
      self.css_class = if css_class
        css_class.is_a?(Array) ? css_class : [css_class]
      else
        []
      end
    end
    
    # Convenience method chaining ---------------------------
    
    def id(identifier)
      raise ArgumentError, "Id must be a String or Symbol" unless [String, Symbol].include?(identifier.class)
      self.attributes[:id] = identifier
      self
    end
    
    def c(*args)
      self.css_class += args
      self
    end
    
    # Rendering -----------------------------------------------
    
    def rendered_attributes
      str = ""
      str << " class=\"#{css_class.join(' ')}\"" unless css_class.empty?
      keys = attributes.keys.sort{|a, b| a.to_s <=> b.to_s}
      keys.each do |key|
        value = attributes[key]
        if value
          value = value.to_s.gsub('"', '\'')
          str << " #{key}=\"#{value}\""
        end
      end
      str
    end
    
    def template
      "#{indent}<#{type}#{rendered_attributes}>\n"
    end
    
    def render
      str = template
      self.output << str
      str
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
garterbelt-0.0.7 lib/renderers/closed_tag.rb
garterbelt-0.0.6 lib/renderers/closed_tag.rb
garterbelt-0.0.5 lib/renderers/closed_tag.rb