Class: AwesomeXmlDsl::Tag

Inherits:
Object
  • Object
show all
Defined in:
lib/awesome_xml_dsl/tag.rb

Instance Method Summary collapse

Constructor Details

#initialize(name, generator, depth, options = {}) ⇒ Tag

Returns a new instance of Tag.



5
6
7
8
9
10
11
12
13
# File 'lib/awesome_xml_dsl/tag.rb', line 5

def initialize(name, generator, depth, options = {})
  @name = name
  @generator = generator
  @depth = depth
  @options = options

  @attributes = []
  @tags = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object



61
62
63
64
65
# File 'lib/awesome_xml_dsl/tag.rb', line 61

def method_missing(m, *args, &block)
  return @options[:locals][m] if @options[:locals]&.key?(m)

  @generator.send(m, *args, &block)
end

Instance Method Details

#a(name, options_or_value = {}) ⇒ Object

Block evaluation



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/awesome_xml_dsl/tag.rb', line 16

def a(name, options_or_value = {})
  # It is options
  if options_or_value.is_a? Hash
    AttributeOptionsParser.parse(options_or_value).each do |value|
      attribute = Attribute.new(name, value)
      @attributes.push attribute
    end

    return
  end

  # It is a value
  attribute = Attribute.new(name, options_or_value)
  @attributes.push attribute
end

#attributes_as_xml(spaces) ⇒ Object



54
55
56
57
58
59
# File 'lib/awesome_xml_dsl/tag.rb', line 54

def attributes_as_xml(spaces)
  return '' unless @attributes.any?
  return " #{@attributes.first.to_xml}" if @attributes.length == 1

  ([''] + @attributes.map(&:to_xml).compact.map { |attribute| "#{spaces}#{attribute}" }).join("\n")
end

#partial(name, options = {}) ⇒ Object



40
41
42
# File 'lib/awesome_xml_dsl/tag.rb', line 40

def partial(name, options = {})
  @generator.partial(name, options, self, @options)
end

#tag(name, options = {}, &block) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/awesome_xml_dsl/tag.rb', line 32

def tag(name, options = {}, &block)
  OptionsParser.parse(options, @options).each do |parsed_options|
    xml_tag = Tag.new(name, @generator, @depth + 1, parsed_options)
    @tags.push xml_tag
    xml_tag.instance_eval(&block) if block_given?
  end
end

#to_xmlObject

XML Generation



45
46
47
48
49
50
51
52
# File 'lib/awesome_xml_dsl/tag.rb', line 45

def to_xml
  spaces = ' ' * @depth * 2
  start = "#{spaces}<#{@name}#{attributes_as_xml(spaces + '  ')}"

  return start + ' />' if @tags.length.zero?

  [start + '>', @tags.map(&:to_xml).join("\n"), "#{spaces}</#{@name}>"].join "\n"
end