matta-googlecharts 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/gchart.rb ADDED
@@ -0,0 +1,364 @@
1
+ $:.unshift File.dirname(__FILE__)
2
+ require 'gchart/version'
3
+ require "open-uri"
4
+ require "uri"
5
+
6
+ class Gchart
7
+
8
+ include GchartInfo
9
+
10
+ @@url = "http://chart.apis.google.com/chart?"
11
+ @@types = ['line', 'line_xy', 'scatter', 'bar', 'venn', 'pie', 'pie_3d', 'jstize']
12
+ @@simple_chars = ('A'..'Z').to_a + ('a'..'z').to_a + ('0'..'9').to_a
13
+ @@chars = @@simple_chars + ['-', '.']
14
+ @@ext_pairs = @@chars.map { |char_1| @@chars.map { |char_2| char_1 + char_2 } }.flatten
15
+ @@file_name = 'chart.png'
16
+
17
+ attr_accessor :title, :type, :width, :height, :horizontal, :grouped, :legend, :data, :encoding, :max_value, :bar_colors,
18
+ :title_color, :title_size, :custom, :axis_with_labels, :axis_labels
19
+
20
+ class << self
21
+ # Support for Gchart.line(:title => 'my title', :size => '400x600')
22
+ def method_missing(m, options={})
23
+ # Extract the format and optional filename, then clean the hash
24
+ format = options[:format] || 'url'
25
+ @@file_name = options[:filename] unless options[:filename].nil?
26
+ options.delete(:format)
27
+ options.delete(:filename)
28
+ # create the chart and return it in the format asked for
29
+ if @@types.include?(m.to_s)
30
+ chart = new(options.merge!({:type => m}))
31
+ chart.send(format)
32
+ elsif m.to_s == 'version'
33
+ Gchart::VERSION::STRING
34
+ else
35
+ "#{m} is not a supported chart format, please use one of the following: #{supported_types}."
36
+ end
37
+ end
38
+
39
+ end
40
+
41
+ def initialize(options={})
42
+ @type = :line
43
+ @data = []
44
+ @width = 300
45
+ @height = 200
46
+ @horizontal = false
47
+ @grouped = false
48
+ @encoding = 'simple'
49
+ @max_value = 'auto'
50
+
51
+ # set the options value if definable
52
+ options.each do |attribute, value|
53
+ send("#{attribute.to_s}=", value) if self.respond_to?("#{attribute}=")
54
+ end
55
+ end
56
+
57
+ def self.supported_types
58
+ @@types.join(' ')
59
+ end
60
+
61
+ # Defines the Graph size using the following format:
62
+ # width X height
63
+ def size=(size='300x200')
64
+ @width, @height = size.split("x").map { |dimension| dimension.to_i }
65
+ end
66
+
67
+ def size
68
+ "#{@width}x#{@height}"
69
+ end
70
+
71
+ # Sets the orientation of a bar graph
72
+ def orientation=(orientation='h')
73
+ if orientation == 'h' || orientation == 'horizontal'
74
+ self.horizontal = true
75
+ elsif orientation == 'v' || orientation == 'vertical'
76
+ self.horizontal = false
77
+ end
78
+ end
79
+
80
+ # Sets the bar graph presentation (stacked or grouped)
81
+ def stacked=(option=true)
82
+ @grouped = option ? false : true
83
+ end
84
+
85
+ def bg=(options)
86
+ if options.is_a?(String)
87
+ @bg_color = options
88
+ elsif options.is_a?(Hash)
89
+ @bg_color = options[:color]
90
+ @bg_type = options[:type]
91
+ @bg_angle = options[:angle]
92
+ end
93
+ end
94
+
95
+ def graph_bg=(options)
96
+ if options.is_a?(String)
97
+ @chart_color = options
98
+ elsif options.is_a?(Hash)
99
+ @chart_color = options[:color]
100
+ @chart_type = options[:type]
101
+ @chart_angle = options[:angle]
102
+ end
103
+ end
104
+
105
+ def self.jstize(string)
106
+ string.gsub(' ', '+').gsub(/\[|\{|\}|\||\\|\^|\[|\]|\`|\]/) {|c| "%#{c[0].to_s(16).upcase}"}
107
+ end
108
+ # load all the custom aliases
109
+ require 'gchart/aliases'
110
+
111
+ protected
112
+
113
+ # Returns the chart's generated PNG as a blob. (borrowed from John's gchart.rubyforge.org)
114
+ def fetch
115
+ open(query_builder) { |io| io.read }
116
+ end
117
+
118
+ # Writes the chart's generated PNG to a file. (borrowed from John's gchart.rubyforge.org)
119
+ def write(io_or_file=@@file_name)
120
+ return io_or_file.write(fetch) if io_or_file.respond_to?(:write)
121
+ open(io_or_file, "w+") { |io| io.write(fetch) }
122
+ end
123
+
124
+ # Format
125
+
126
+ def img_tag
127
+ "<img src='#{query_builder}'/>"
128
+ end
129
+
130
+ def url
131
+ query_builder
132
+ end
133
+
134
+ def file
135
+ write
136
+ end
137
+
138
+ #
139
+ def jstize(string)
140
+ Gchart.jstize(string)
141
+ end
142
+
143
+ private
144
+
145
+ # The title size cannot be set without specifying a color.
146
+ # A dark key will be used for the title color if no color is specified
147
+ def set_title
148
+ title_params = "chtt=#{title}"
149
+ unless (title_color.nil? && title_size.nil? )
150
+ title_params << "&chts=" + (color, size = (@title_color || '454545'), @title_size).compact.join(',')
151
+ end
152
+ title_params
153
+ end
154
+
155
+ def set_size
156
+ "chs=#{size}"
157
+ end
158
+
159
+ def set_data
160
+ data = send("#{@encoding}_encoding", @data)
161
+ "chd=#{data}"
162
+ end
163
+
164
+ def set_colors
165
+ bg_type = fill_type(@bg_type) || 's' if @bg_color
166
+ chart_type = fill_type(@chart_type) || 's' if @chart_color
167
+
168
+ "chf=" + {'bg' => fill_for(bg_type, @bg_color, @bg_angle), 'c' => fill_for(chart_type, @chart_color, @chart_angle)}.map{|k,v| "#{k},#{v}" unless v.nil?}.compact.join('|')
169
+ end
170
+
171
+ # set bar, line colors
172
+ def set_bar_colors
173
+ @bar_colors = @bar_colors.join(',') if @bar_colors.is_a?(Array)
174
+ "chco=#{@bar_colors}"
175
+ end
176
+
177
+ def fill_for(type=nil, color='', angle=nil)
178
+ unless type.nil?
179
+ case type
180
+ when 'lg'
181
+ angle ||= 0
182
+ color = "#{color},0,ffffff,1" if color.split(',').size == 1
183
+ "#{type},#{angle},#{color}"
184
+ when 'ls'
185
+ angle ||= 90
186
+ color = "#{color},0.2,ffffff,0.2" if color.split(',').size == 1
187
+ "#{type},#{angle},#{color}"
188
+ else
189
+ "#{type},#{color}"
190
+ end
191
+ end
192
+ end
193
+
194
+ # A chart can have one or many legends.
195
+ # Gchart.line(:legend => 'label')
196
+ # or
197
+ # Gchart.line(:legend => ['first label', 'last label'])
198
+ def set_legend
199
+ return set_labels if @type == :pie || @type == :pie_3d
200
+
201
+ if @legend.is_a?(Array)
202
+ "chdl=#{@legend.map{|label| "#{label}"}.join('|')}"
203
+ else
204
+ "chdl=#{@legend}"
205
+ end
206
+
207
+ end
208
+
209
+ def set_labels
210
+ if @legend.is_a?(Array)
211
+ "chl=#{@legend.map{|label| "#{label}"}.join('|')}"
212
+ else
213
+ "chl=#{@legend}"
214
+ end
215
+ end
216
+
217
+ def set_axis_with_labels
218
+ @axis_with_labels = @axis_with_labels.join(',') if @axis_with_labels.is_a?(Array)
219
+ "chxt=#{@axis_with_labels}"
220
+ end
221
+
222
+ def set_axis_labels
223
+ labels_arr = []
224
+ axis_labels.each_with_index do |labels,index|
225
+ if labels.is_a?(Array)
226
+ labels_arr << "#{index}:|#{labels.join('|')}"
227
+ else
228
+ labels_arr << "#{index}:|#{labels}"
229
+ end
230
+ end
231
+ "chxl=#{labels_arr.join('|')}"
232
+ end
233
+
234
+ def set_type
235
+ case @type
236
+ when :line
237
+ "cht=lc"
238
+ when :line_xy
239
+ "cht=lxy"
240
+ when :bar
241
+ "cht=b" + (horizontal? ? "h" : "v") + (grouped? ? "g" : "s")
242
+ when :pie_3d
243
+ "cht=p3"
244
+ when :pie
245
+ "cht=p"
246
+ when :venn
247
+ "cht=v"
248
+ when :scatter
249
+ "cht=s"
250
+ end
251
+ end
252
+
253
+ def fill_type(type)
254
+ case type
255
+ when 'solid'
256
+ 's'
257
+ when 'gradient'
258
+ 'lg'
259
+ when 'stripes'
260
+ 'ls'
261
+ end
262
+ end
263
+
264
+ # Wraps a single dataset inside another array to support more datasets
265
+ def prepare_dataset(ds)
266
+ ds = [ds] unless ds.first.is_a?(Array)
267
+ ds
268
+ end
269
+
270
+ def convert_to_simple_value(number)
271
+ if number.nil?
272
+ "_"
273
+ else
274
+ value = @@simple_chars[number.to_i]
275
+ value.nil? ? "_" : value
276
+ end
277
+ end
278
+
279
+ # http://code.google.com/apis/chart/#simple
280
+ # Simple encoding has a resolution of 62 different values.
281
+ # Allowing five pixels per data point, this is sufficient for line and bar charts up
282
+ # to about 300 pixels. Simple encoding is suitable for all other types of chart regardless of size.
283
+ def simple_encoding(dataset=[])
284
+ dataset = prepare_dataset(dataset)
285
+ @max_value = dataset.map{|ds| ds.max}.max if @max_value == 'auto'
286
+
287
+ if @max_value == false || @max_value == 'false' || @max_value == :false
288
+ "s:" + dataset.map { |ds| ds.map { |number| convert_to_simple_value(number) }.join }.join(',')
289
+ else
290
+ "s:" + dataset.map { |ds| ds.map { |number| convert_to_simple_value( (@@simple_chars.size - 1) * number / @max_value) }.join }.join(',')
291
+ end
292
+
293
+ end
294
+
295
+ # http://code.google.com/apis/chart/#text
296
+ # Text encoding has a resolution of 1,000 different values,
297
+ # using floating point numbers between 0.0 and 100.0. Allowing five pixels per data point,
298
+ # integers (1.0, 2.0, and so on) are sufficient for line and bar charts up to about 500 pixels.
299
+ # Include a single decimal place (35.7 for example) if you require higher resolution.
300
+ # Text encoding is suitable for all other types of chart regardless of size.
301
+ def text_encoding(dataset=[])
302
+ dataset = prepare_dataset(dataset)
303
+ "t:" + dataset.map{ |ds| ds.join(',') }.join('|')
304
+ end
305
+
306
+ def convert_to_extended_value(number)
307
+ if number.nil?
308
+ '__'
309
+ else
310
+ value = @@ext_pairs[number.to_i]
311
+ value.nil? ? "__" : value
312
+ end
313
+ end
314
+
315
+ # http://code.google.com/apis/chart/#extended
316
+ # Extended encoding has a resolution of 4,096 different values
317
+ # and is best used for large charts where a large data range is required.
318
+ def extended_encoding(dataset=[])
319
+
320
+ dataset = prepare_dataset(dataset)
321
+ @max_value = dataset.map{|ds| ds.max}.max if @max_value == 'auto'
322
+
323
+ if @max_value == false || @max_value == 'false' || @max_value == :false
324
+ "e:" + dataset.map { |ds| ds.map { |number| convert_to_extended_value(number)}.join }.join(',')
325
+ else
326
+ "e:" + dataset.map { |ds| ds.map { |number| convert_to_extended_value( (@@ext_pairs.size - 1) * number / @max_value) }.join }.join(',')
327
+ end
328
+
329
+ end
330
+
331
+
332
+ def query_builder
333
+ query_params = instance_variables.map do |var|
334
+ case var
335
+ # Set the graph size
336
+ when '@width'
337
+ set_size unless @width.nil? || @height.nil?
338
+ when '@type'
339
+ set_type
340
+ when '@title'
341
+ set_title unless @title.nil?
342
+ when '@legend'
343
+ set_legend unless @legend.nil?
344
+ when '@bg_color'
345
+ set_colors
346
+ when '@chart_color'
347
+ set_colors if @bg_color.nil?
348
+ when '@data'
349
+ set_data unless @data == []
350
+ when '@bar_colors'
351
+ set_bar_colors
352
+ when '@axis_with_labels'
353
+ set_axis_with_labels
354
+ when '@axis_labels'
355
+ set_axis_labels
356
+ when '@custom'
357
+ @custom
358
+ end
359
+ end.compact
360
+
361
+ jstize(@@url + query_params.join('&'))
362
+ end
363
+
364
+ end
data/script/destroy ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+ APP_ROOT = File.join(File.dirname(__FILE__), '..')
3
+
4
+ begin
5
+ require 'rubigen'
6
+ rescue LoadError
7
+ require 'rubygems'
8
+ require 'rubigen'
9
+ end
10
+ require 'rubigen/scripts/destroy'
11
+
12
+ ARGV.shift if ['--help', '-h'].include?(ARGV[0])
13
+ RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit]
14
+ RubiGen::Scripts::Destroy.new.run(ARGV)
data/script/generate ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+ APP_ROOT = File.join(File.dirname(__FILE__), '..')
3
+
4
+ begin
5
+ require 'rubigen'
6
+ rescue LoadError
7
+ require 'rubygems'
8
+ require 'rubigen'
9
+ end
10
+ require 'rubigen/scripts/generate'
11
+
12
+ ARGV.shift if ['--help', '-h'].include?(ARGV[0])
13
+ RubiGen::Base.use_component_sources! [:rubygems, :newgem, :newgem_theme, :test_unit]
14
+ RubiGen::Scripts::Generate.new.run(ARGV)
data/script/txt2html ADDED
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'rubygems'
4
+ begin
5
+ require 'newgem'
6
+ rescue LoadError
7
+ puts "\n\nGenerating the website requires the newgem RubyGem"
8
+ puts "Install: gem install newgem\n\n"
9
+ exit(1)
10
+ end
11
+ require 'redcloth'
12
+ require 'syntax/convertors/html'
13
+ require 'erb'
14
+ require File.dirname(__FILE__) + '/../lib/gchart'
15
+
16
+ version = Gchart.version
17
+ download = 'http://rubyforge.org/projects/googlecharts'
18
+
19
+ class Fixnum
20
+ def ordinal
21
+ # teens
22
+ return 'th' if (10..19).include?(self % 100)
23
+ # others
24
+ case self % 10
25
+ when 1: return 'st'
26
+ when 2: return 'nd'
27
+ when 3: return 'rd'
28
+ else return 'th'
29
+ end
30
+ end
31
+ end
32
+
33
+ class Time
34
+ def pretty
35
+ return "#{mday}#{mday.ordinal} #{strftime('%B')} #{year}"
36
+ end
37
+ end
38
+
39
+ def convert_syntax(syntax, source)
40
+ return Syntax::Convertors::HTML.for_syntax(syntax).convert(source).gsub(%r!^<pre>|</pre>$!,'')
41
+ end
42
+
43
+ if ARGV.length >= 1
44
+ src, template = ARGV
45
+ template ||= File.join(File.dirname(__FILE__), '/../website/template.rhtml')
46
+
47
+ else
48
+ puts("Usage: #{File.split($0).last} source.txt [template.rhtml] > output.html")
49
+ exit!
50
+ end
51
+
52
+ template = ERB.new(File.open(template).read)
53
+
54
+ title = nil
55
+ body = nil
56
+ File.open(src) do |fsrc|
57
+ title_text = fsrc.readline
58
+ body_text = fsrc.read
59
+ syntax_items = []
60
+ body_text.gsub!(%r!<(pre|code)[^>]*?syntax=['"]([^'"]+)[^>]*>(.*?)</\1>!m){
61
+ ident = syntax_items.length
62
+ element, syntax, source = $1, $2, $3
63
+ syntax_items << "<#{element} class='syntax'>#{convert_syntax(syntax, source)}</#{element}>"
64
+ "syntax-temp-#{ident}"
65
+ }
66
+ title = RedCloth.new(title_text).to_html.gsub(%r!<.*?>!,'').strip
67
+ body = RedCloth.new(body_text).to_html
68
+ body.gsub!(%r!(?:<pre><code>)?syntax-temp-(\d+)(?:</code></pre>)?!){ syntax_items[$1.to_i] }
69
+ end
70
+ stat = File.stat(src)
71
+ created = stat.ctime
72
+ modified = stat.mtime
73
+
74
+ $stdout << template.result(binding)