1require "rss/utils"
2
3module RSS
4
5  module XMLStyleSheetMixin
6    attr_accessor :xml_stylesheets
7    def initialize(*args)
8      super
9      @xml_stylesheets = []
10    end
11
12    private
13    def xml_stylesheet_pi
14      xsss = @xml_stylesheets.collect do |xss|
15        pi = xss.to_s
16        pi = nil if /\A\s*\z/ =~ pi
17        pi
18      end.compact
19      xsss.push("") unless xsss.empty?
20      xsss.join("\n")
21    end
22  end
23
24  class XMLStyleSheet
25
26    include Utils
27
28    ATTRIBUTES = %w(href type title media charset alternate)
29
30    GUESS_TABLE = {
31      "xsl" => "text/xsl",
32      "css" => "text/css",
33    }
34
35    attr_accessor(*ATTRIBUTES)
36    attr_accessor(:do_validate)
37    def initialize(*attrs)
38      if attrs.size == 1 and
39          (attrs.first.is_a?(Hash) or attrs.first.is_a?(Array))
40        attrs = attrs.first
41      end
42      @do_validate = true
43      ATTRIBUTES.each do |attr|
44        __send__("#{attr}=", nil)
45      end
46      vars = ATTRIBUTES.dup
47      vars.unshift(:do_validate)
48      attrs.each do |name, value|
49        if vars.include?(name.to_s)
50          __send__("#{name}=", value)
51        end
52      end
53    end
54
55    def to_s
56      rv = ""
57      if @href
58        rv << %Q[<?xml-stylesheet]
59        ATTRIBUTES.each do |name|
60          if __send__(name)
61            rv << %Q[ #{name}="#{h __send__(name)}"]
62          end
63        end
64        rv << %Q[?>]
65      end
66      rv
67    end
68
69    remove_method(:href=)
70    def href=(value)
71      @href = value
72      if @href and @type.nil?
73        @type = guess_type(@href)
74      end
75      @href
76    end
77
78    remove_method(:alternate=)
79    def alternate=(value)
80      if value.nil? or /\A(?:yes|no)\z/ =~ value
81        @alternate = value
82      else
83        if @do_validate
84          args = ["?xml-stylesheet?", %Q[alternate="#{value}"]]
85          raise NotAvailableValueError.new(*args)
86        end
87      end
88      @alternate
89    end
90
91    def setup_maker(maker)
92      xss = maker.xml_stylesheets.new_xml_stylesheet
93      ATTRIBUTES.each do |attr|
94        xss.__send__("#{attr}=", __send__(attr))
95      end
96    end
97
98    private
99    def guess_type(filename)
100      /\.([^.]+)$/ =~ filename
101      GUESS_TABLE[$1]
102    end
103
104  end
105end
106