actionpack 1.12.5 → 1.13.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of actionpack might be problematic. Click here for more details.

Files changed (179) hide show
  1. data/CHANGELOG +517 -15
  2. data/MIT-LICENSE +1 -1
  3. data/README +18 -20
  4. data/Rakefile +7 -4
  5. data/examples/address_book_controller.rb +3 -3
  6. data/examples/blog_controller.cgi +3 -3
  7. data/examples/debate_controller.cgi +5 -5
  8. data/lib/action_controller.rb +2 -2
  9. data/lib/action_controller/assertions.rb +73 -311
  10. data/lib/action_controller/{deprecated_assertions.rb → assertions/deprecated_assertions.rb} +32 -8
  11. data/lib/action_controller/assertions/dom_assertions.rb +25 -0
  12. data/lib/action_controller/assertions/model_assertions.rb +12 -0
  13. data/lib/action_controller/assertions/response_assertions.rb +140 -0
  14. data/lib/action_controller/assertions/routing_assertions.rb +82 -0
  15. data/lib/action_controller/assertions/selector_assertions.rb +571 -0
  16. data/lib/action_controller/assertions/tag_assertions.rb +117 -0
  17. data/lib/action_controller/base.rb +334 -163
  18. data/lib/action_controller/benchmarking.rb +3 -6
  19. data/lib/action_controller/caching.rb +83 -22
  20. data/lib/action_controller/cgi_ext/cgi_ext.rb +0 -7
  21. data/lib/action_controller/cgi_ext/cgi_methods.rb +167 -173
  22. data/lib/action_controller/cgi_ext/raw_post_data_fix.rb +43 -22
  23. data/lib/action_controller/cgi_process.rb +50 -27
  24. data/lib/action_controller/components.rb +21 -25
  25. data/lib/action_controller/cookies.rb +10 -9
  26. data/lib/action_controller/{dependencies.rb → deprecated_dependencies.rb} +9 -27
  27. data/lib/action_controller/filters.rb +448 -225
  28. data/lib/action_controller/flash.rb +24 -20
  29. data/lib/action_controller/helpers.rb +2 -5
  30. data/lib/action_controller/integration.rb +40 -16
  31. data/lib/action_controller/layout.rb +11 -8
  32. data/lib/action_controller/macros/auto_complete.rb +3 -2
  33. data/lib/action_controller/macros/in_place_editing.rb +3 -2
  34. data/lib/action_controller/mime_responds.rb +41 -29
  35. data/lib/action_controller/mime_type.rb +68 -10
  36. data/lib/action_controller/pagination.rb +4 -3
  37. data/lib/action_controller/request.rb +22 -14
  38. data/lib/action_controller/rescue.rb +25 -22
  39. data/lib/action_controller/resources.rb +302 -0
  40. data/lib/action_controller/response.rb +20 -2
  41. data/lib/action_controller/response.rb.rej +17 -0
  42. data/lib/action_controller/routing.rb +1165 -567
  43. data/lib/action_controller/scaffolding.rb +30 -31
  44. data/lib/action_controller/session/active_record_store.rb +2 -0
  45. data/lib/action_controller/session/drb_store.rb +4 -0
  46. data/lib/action_controller/session/mem_cache_store.rb +4 -0
  47. data/lib/action_controller/session_management.rb +6 -9
  48. data/lib/action_controller/status_codes.rb +89 -0
  49. data/lib/action_controller/streaming.rb +6 -15
  50. data/lib/action_controller/templates/rescues/_request_and_response.rhtml +5 -5
  51. data/lib/action_controller/templates/rescues/diagnostics.rhtml +2 -2
  52. data/lib/action_controller/templates/rescues/routing_error.rhtml +4 -4
  53. data/lib/action_controller/templates/rescues/template_error.rhtml +1 -1
  54. data/lib/action_controller/templates/scaffolds/list.rhtml +1 -1
  55. data/lib/action_controller/test_process.rb +52 -30
  56. data/lib/action_controller/url_rewriter.rb +63 -29
  57. data/lib/action_controller/vendor/html-scanner/html/document.rb +1 -0
  58. data/lib/action_controller/vendor/html-scanner/html/node.rb +3 -4
  59. data/lib/action_controller/vendor/html-scanner/html/selector.rb +822 -0
  60. data/lib/action_controller/verification.rb +22 -11
  61. data/lib/action_pack.rb +1 -1
  62. data/lib/action_pack/version.rb +2 -2
  63. data/lib/action_view.rb +1 -1
  64. data/lib/action_view/base.rb +46 -43
  65. data/lib/action_view/compiled_templates.rb +1 -1
  66. data/lib/action_view/helpers/active_record_helper.rb +54 -17
  67. data/lib/action_view/helpers/asset_tag_helper.rb +97 -46
  68. data/lib/action_view/helpers/capture_helper.rb +1 -1
  69. data/lib/action_view/helpers/date_helper.rb +258 -136
  70. data/lib/action_view/helpers/debug_helper.rb +1 -1
  71. data/lib/action_view/helpers/deprecated_helper.rb +34 -0
  72. data/lib/action_view/helpers/form_helper.rb +75 -35
  73. data/lib/action_view/helpers/form_options_helper.rb +7 -5
  74. data/lib/action_view/helpers/form_tag_helper.rb +44 -6
  75. data/lib/action_view/helpers/java_script_macros_helper.rb +59 -46
  76. data/lib/action_view/helpers/javascript_helper.rb +71 -10
  77. data/lib/action_view/helpers/javascripts/controls.js +41 -23
  78. data/lib/action_view/helpers/javascripts/dragdrop.js +105 -76
  79. data/lib/action_view/helpers/javascripts/effects.js +293 -163
  80. data/lib/action_view/helpers/javascripts/prototype.js +897 -389
  81. data/lib/action_view/helpers/javascripts/prototype.js.rej +561 -0
  82. data/lib/action_view/helpers/number_helper.rb +111 -65
  83. data/lib/action_view/helpers/prototype_helper.rb +84 -109
  84. data/lib/action_view/helpers/scriptaculous_helper.rb +5 -0
  85. data/lib/action_view/helpers/tag_helper.rb +69 -16
  86. data/lib/action_view/helpers/text_helper.rb +149 -112
  87. data/lib/action_view/helpers/url_helper.rb +200 -107
  88. data/lib/action_view/template_error.rb +66 -42
  89. data/test/abstract_unit.rb +4 -2
  90. data/test/active_record_unit.rb +84 -56
  91. data/test/activerecord/active_record_assertions_test.rb +26 -18
  92. data/test/activerecord/active_record_store_test.rb +4 -36
  93. data/test/activerecord/pagination_test.rb +1 -6
  94. data/test/controller/action_pack_assertions_test.rb +230 -113
  95. data/test/controller/addresses_render_test.rb +2 -6
  96. data/test/controller/assert_select_test.rb +576 -0
  97. data/test/controller/base_test.rb +73 -3
  98. data/test/controller/caching_test.rb +228 -0
  99. data/test/controller/capture_test.rb +12 -10
  100. data/test/controller/cgi_test.rb +89 -12
  101. data/test/controller/components_test.rb +24 -2
  102. data/test/controller/content_type_test.rb +139 -0
  103. data/test/controller/controller_fixtures/app/controllers/admin/user_controller.rb +0 -0
  104. data/test/controller/controller_fixtures/app/controllers/user_controller.rb +0 -0
  105. data/test/controller/controller_fixtures/vendor/plugins/bad_plugin/lib/plugin_controller.rb +0 -0
  106. data/test/controller/cookie_test.rb +33 -25
  107. data/test/controller/deprecated_instance_variables_test.rb +48 -0
  108. data/test/controller/deprecation/deprecated_base_methods_test.rb +60 -0
  109. data/test/controller/fake_controllers.rb +0 -1
  110. data/test/controller/filters_test.rb +301 -16
  111. data/test/controller/flash_test.rb +19 -2
  112. data/test/controller/helper_test.rb +2 -2
  113. data/test/controller/integration_test.rb +154 -0
  114. data/test/controller/layout_test.rb +115 -1
  115. data/test/controller/mime_responds_test.rb +94 -0
  116. data/test/controller/mime_type_test.rb +9 -0
  117. data/test/controller/new_render_test.rb +161 -11
  118. data/test/controller/raw_post_test.rb +52 -15
  119. data/test/controller/redirect_test.rb +27 -14
  120. data/test/controller/render_test.rb +76 -29
  121. data/test/controller/request_test.rb +55 -4
  122. data/test/controller/resources_test.rb +274 -0
  123. data/test/controller/routing_test.rb +1533 -824
  124. data/test/controller/selector_test.rb +628 -0
  125. data/test/controller/send_file_test.rb +9 -1
  126. data/test/controller/session_management_test.rb +51 -0
  127. data/test/controller/test_test.rb +113 -29
  128. data/test/controller/url_rewriter_test.rb +86 -17
  129. data/test/controller/verification_test.rb +19 -17
  130. data/test/controller/webservice_test.rb +0 -7
  131. data/test/fixtures/content_type/render_default_content_types_for_respond_to.rhtml +1 -0
  132. data/test/fixtures/content_type/render_default_for_rhtml.rhtml +1 -0
  133. data/test/fixtures/content_type/render_default_for_rjs.rjs +1 -0
  134. data/test/fixtures/content_type/render_default_for_rxml.rxml +1 -0
  135. data/test/fixtures/deprecated_instance_variables/_cookies_ivar.rhtml +1 -0
  136. data/test/fixtures/deprecated_instance_variables/_cookies_method.rhtml +1 -0
  137. data/test/fixtures/deprecated_instance_variables/_flash_ivar.rhtml +1 -0
  138. data/test/fixtures/deprecated_instance_variables/_flash_method.rhtml +1 -0
  139. data/test/fixtures/deprecated_instance_variables/_headers_ivar.rhtml +1 -0
  140. data/test/fixtures/deprecated_instance_variables/_headers_method.rhtml +1 -0
  141. data/test/fixtures/deprecated_instance_variables/_params_ivar.rhtml +1 -0
  142. data/test/fixtures/deprecated_instance_variables/_params_method.rhtml +1 -0
  143. data/test/fixtures/deprecated_instance_variables/_request_ivar.rhtml +1 -0
  144. data/test/fixtures/deprecated_instance_variables/_request_method.rhtml +1 -0
  145. data/test/fixtures/deprecated_instance_variables/_response_ivar.rhtml +1 -0
  146. data/test/fixtures/deprecated_instance_variables/_response_method.rhtml +1 -0
  147. data/test/fixtures/deprecated_instance_variables/_session_ivar.rhtml +1 -0
  148. data/test/fixtures/deprecated_instance_variables/_session_method.rhtml +1 -0
  149. data/test/fixtures/multipart/binary_file +0 -0
  150. data/test/fixtures/public/javascripts/application.js +1 -0
  151. data/test/fixtures/test/_hello.rxml +1 -0
  152. data/test/fixtures/test/hello_world_container.rxml +3 -0
  153. data/test/fixtures/topic.rb +2 -2
  154. data/test/template/active_record_helper_test.rb +83 -12
  155. data/test/template/asset_tag_helper_test.rb +75 -95
  156. data/test/template/compiled_templates_test.rb +1 -0
  157. data/test/template/date_helper_test.rb +873 -181
  158. data/test/template/deprecated_helper_test.rb +36 -0
  159. data/test/template/deprecated_instance_variables_test.rb +43 -0
  160. data/test/template/form_helper_test.rb +77 -1
  161. data/test/template/form_options_helper_test.rb +4 -0
  162. data/test/template/form_tag_helper_test.rb +66 -2
  163. data/test/template/java_script_macros_helper_test.rb +4 -1
  164. data/test/template/javascript_helper_test.rb +29 -0
  165. data/test/template/number_helper_test.rb +63 -27
  166. data/test/template/prototype_helper_test.rb +77 -34
  167. data/test/template/tag_helper_test.rb +34 -6
  168. data/test/template/text_helper_test.rb +69 -34
  169. data/test/template/url_helper_test.rb +168 -16
  170. data/test/testing_sandbox.rb +7 -22
  171. metadata +66 -20
  172. data/filler.txt +0 -50
  173. data/lib/action_controller/code_generation.rb +0 -235
  174. data/lib/action_controller/vendor/xml_simple.rb +0 -1019
  175. data/test/controller/caching_filestore.rb +0 -74
  176. data/test/fixtures/application_root/app/controllers/a_class_that_contains_a_controller/poorly_placed_controller.rb +0 -7
  177. data/test/fixtures/application_root/app/controllers/module_that_holds_controllers/nested_controller.rb +0 -3
  178. data/test/fixtures/application_root/app/models/a_class_that_contains_a_controller.rb +0 -7
  179. data/test/fixtures/dont_load.rb +0 -3
@@ -14,7 +14,7 @@
14
14
  <% end %>
15
15
  <td><%= link_to "Show", :action => "show#{@scaffold_suffix}", :id => entry %></td>
16
16
  <td><%= link_to "Edit", :action => "edit#{@scaffold_suffix}", :id => entry %></td>
17
- <td><%= link_to "Destroy", {:action => "destroy#{@scaffold_suffix}", :id => entry}, { :confirm => "Are you sure?", :post => true} %></td>
17
+ <td><%= link_to "Destroy", {:action => "destroy#{@scaffold_suffix}", :id => entry}, { :confirm => "Are you sure?", :method => :post } %></td>
18
18
  </tr>
19
19
  <% end %>
20
20
  </table>
@@ -1,5 +1,4 @@
1
1
  require File.dirname(__FILE__) + '/assertions'
2
- require File.dirname(__FILE__) + '/deprecated_assertions'
3
2
 
4
3
  module ActionController #:nodoc:
5
4
  class Base
@@ -18,8 +17,7 @@ module ActionController #:nodoc:
18
17
  end
19
18
  end
20
19
 
21
- alias_method :process_without_test, :process
22
- alias_method :process, :process_with_test
20
+ alias_method_chain :process, :test
23
21
  end
24
22
 
25
23
  class TestRequest < AbstractRequest #:nodoc:
@@ -39,8 +37,8 @@ module ActionController #:nodoc:
39
37
  end
40
38
 
41
39
  def reset_session
42
- @session = {}
43
- end
40
+ @session = TestSession.new
41
+ end
44
42
 
45
43
  def raw_post
46
44
  if raw_post = env['RAW_POST_DATA']
@@ -79,6 +77,10 @@ module ActionController #:nodoc:
79
77
  @path = uri.split("?").first
80
78
  end
81
79
 
80
+ def accept=(mime_types)
81
+ @env["HTTP_ACCEPT"] = Array(mime_types).collect { |mime_types| mime_types.to_s }.join(",")
82
+ end
83
+
82
84
  def remote_addr=(addr)
83
85
  @env['REMOTE_ADDR'] = addr
84
86
  end
@@ -103,7 +105,7 @@ module ActionController #:nodoc:
103
105
  if value.is_a? Fixnum
104
106
  value = value.to_s
105
107
  elsif value.is_a? Array
106
- value = ActionController::Routing::PathComponent::Result.new(value)
108
+ value = ActionController::Routing::PathSegment::Result.new(value)
107
109
  end
108
110
 
109
111
  if extra_keys.include?(key.to_sym)
@@ -112,6 +114,7 @@ module ActionController #:nodoc:
112
114
  path_parameters[key.to_s] = value
113
115
  end
114
116
  end
117
+ @parameters = nil # reset TestRequest#parameters to use the new path_parameters
115
118
  end
116
119
 
117
120
  def recycle!
@@ -176,7 +179,7 @@ module ActionController #:nodoc:
176
179
 
177
180
  # returns the redirection location or nil
178
181
  def redirect_url
179
- redirect? ? headers['location'] : nil
182
+ headers['Location']
180
183
  end
181
184
 
182
185
  # does the redirect location match this regexp pattern?
@@ -272,27 +275,40 @@ module ActionController #:nodoc:
272
275
  end
273
276
 
274
277
  class TestSession #:nodoc:
275
- def initialize(attributes = {})
278
+ attr_accessor :session_id
279
+
280
+ def initialize(attributes = nil)
281
+ @session_id = ''
276
282
  @attributes = attributes
283
+ @saved_attributes = nil
284
+ end
285
+
286
+ def data
287
+ @attributes ||= @saved_attributes || {}
277
288
  end
278
289
 
279
290
  def [](key)
280
- @attributes[key]
291
+ data[key]
281
292
  end
282
293
 
283
294
  def []=(key, value)
284
- @attributes[key] = value
295
+ data[key] = value
285
296
  end
286
297
 
287
- def session_id
288
- ""
298
+ def update
299
+ @saved_attributes = @attributes
289
300
  end
290
301
 
291
- def update() end
292
- def close() end
293
- def delete() @attributes = {} end
302
+ def delete
303
+ @attributes = nil
304
+ end
305
+
306
+ def close
307
+ update
308
+ delete
309
+ end
294
310
  end
295
-
311
+
296
312
  # Essentially generates a modified Tempfile object similar to the object
297
313
  # you'd get from the standard library CGI module in a multipart
298
314
  # request. This means you can use an ActionController::TestUploadedFile
@@ -301,6 +317,7 @@ module ActionController #:nodoc:
301
317
  #
302
318
  # Usage example, within a functional test:
303
319
  # post :change_avatar, :avatar => ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + '/files/spongebob.png', 'image/png')
320
+ require 'tempfile'
304
321
  class TestUploadedFile
305
322
  # The filename, *not* including the path, of the "uploaded" file
306
323
  attr_reader :original_filename
@@ -309,7 +326,7 @@ module ActionController #:nodoc:
309
326
  attr_reader :content_type
310
327
 
311
328
  def initialize(path, content_type = 'text/plain')
312
- raise "file does not exist" unless File.exist?(path)
329
+ raise "#{path} file does not exist" unless File.exist?(path)
313
330
  @content_type = content_type
314
331
  @original_filename = path.sub(/^.*#{File::SEPARATOR}([^#{File::SEPARATOR}]+)$/) { $1 }
315
332
  @tempfile = Tempfile.new(@original_filename)
@@ -333,7 +350,7 @@ module ActionController #:nodoc:
333
350
  %w( get post put delete head ).each do |method|
334
351
  base.class_eval <<-EOV, __FILE__, __LINE__
335
352
  def #{method}(action, parameters = nil, session = nil, flash = nil)
336
- @request.env['REQUEST_METHOD'] = "#{method.upcase}" if @request
353
+ @request.env['REQUEST_METHOD'] = "#{method.upcase}" if defined?(@request)
337
354
  process(action, parameters, session, flash)
338
355
  end
339
356
  EOV
@@ -344,8 +361,10 @@ module ActionController #:nodoc:
344
361
  def process(action, parameters = nil, session = nil, flash = nil)
345
362
  # Sanity check for required instance variables so we can give an
346
363
  # understandable error message.
347
- %w(controller request response).each do |iv_name|
348
- raise "@#{iv_name} is nil: make sure you set it in your test's setup method." if instance_variable_get("@#{iv_name}").nil?
364
+ %w(@controller @request @response).each do |iv_name|
365
+ if !instance_variables.include?(iv_name) || instance_variable_get(iv_name).nil?
366
+ raise "#{iv_name} is nil: make sure you set it in your test's setup method."
367
+ end
349
368
  end
350
369
 
351
370
  @request.recycle!
@@ -374,8 +393,9 @@ module ActionController #:nodoc:
374
393
  alias xhr :xml_http_request
375
394
 
376
395
  def follow_redirect
377
- if @response.redirected_to[:controller]
378
- raise "Can't follow redirects outside of current controller (#{@response.redirected_to[:controller]})"
396
+ redirected_controller = @response.redirected_to[:controller]
397
+ if redirected_controller && redirected_controller != @controller.controller_name
398
+ raise "Can't follow redirects outside of current controller (from #{@controller.controller_name} to #{redirected_controller})"
379
399
  end
380
400
 
381
401
  get(@response.redirected_to.delete(:action), @response.redirected_to.stringify_keys)
@@ -428,7 +448,7 @@ module ActionController #:nodoc:
428
448
  end
429
449
 
430
450
  def method_missing(selector, *args)
431
- return @controller.send(selector, *args) if ActionController::Routing::NamedRoutes::Helpers.include?(selector)
451
+ return @controller.send(selector, *args) if ActionController::Routing::Routes.named_routes.helpers.include?(selector)
432
452
  return super
433
453
  end
434
454
 
@@ -448,13 +468,15 @@ module ActionController #:nodoc:
448
468
  # The new instance is yielded to the passed block. Typically the block
449
469
  # will create some routes using map.draw { map.connect ... }:
450
470
  #
451
- # with_routing do |set|
452
- # set.draw { set.connect ':controller/:id/:action' }
453
- # assert_equal(
454
- # ['/content/10/show', {}],
455
- # set.generate(:controller => 'content', :id => 10, :action => 'show')
456
- # )
457
- # end
471
+ # with_routing do |set|
472
+ # set.draw do |map|
473
+ # map.connect ':controller/:action/:id'
474
+ # assert_equal(
475
+ # ['/content/10/show', {}],
476
+ # map.generate(:controller => 'content', :id => 10, :action => 'show')
477
+ # end
478
+ # end
479
+ # end
458
480
  #
459
481
  def with_routing
460
482
  real_routes = ActionController::Routing::Routes
@@ -1,13 +1,71 @@
1
1
  module ActionController
2
+
3
+ # Write URLs from arbitrary places in your codebase, such as your mailers.
4
+ #
5
+ # Example:
6
+ #
7
+ # class MyMailer
8
+ # include ActionController::UrlWriter
9
+ # default_url_options[:host] = 'www.basecamphq.com'
10
+ #
11
+ # def signup_url(token)
12
+ # url_for(:controller => 'signup', action => 'index', :token => token)
13
+ # end
14
+ # end
15
+ #
16
+ # In addition to providing +url_for+, named routes are also accessible after
17
+ # including UrlWriter.
18
+ #
19
+ module UrlWriter
20
+
21
+ # The default options for urls written by this writer. Typically a :host pair
22
+ # is provided.
23
+ mattr_accessor :default_url_options
24
+ self.default_url_options = {}
25
+
26
+ def self.included(base) #:nodoc:
27
+ ActionController::Routing::Routes.named_routes.install base
28
+ base.mattr_accessor :default_url_options
29
+ base.default_url_options ||= default_url_options
30
+ end
31
+
32
+ # Generate a url with the provided options. The following special options may
33
+ # effect the constructed url:
34
+ #
35
+ # * :host Specifies the host the link should be targetted at. This option
36
+ # must be provided either explicitly, or via default_url_options.
37
+ # * :protocol The protocol to connect to. Defaults to 'http'
38
+ # * :port Optionally specify the port to connect to.
39
+ #
40
+ def url_for(options)
41
+ options = self.class.default_url_options.merge(options)
42
+
43
+ url = ''
44
+ unless options.delete :only_path
45
+ url << (options.delete(:protocol) || 'http')
46
+ url << '://'
47
+
48
+ raise "Missing host to link to! Please provide :host parameter or set default_url_options[:host]" unless options[:host]
49
+ url << options.delete(:host)
50
+ url << ":#{options.delete(:port)}" if options.key?(:port)
51
+ else
52
+ # Delete the unused options to prevent their appearance in the query string
53
+ [:protocol, :host, :port].each { |k| options.delete k }
54
+ end
55
+ url << Routing::Routes.generate(options, {})
56
+ return url
57
+ end
58
+
59
+ end
60
+
2
61
  # Rewrites URLs for Base.redirect_to and Base.url_for in the controller.
3
-
4
62
  class UrlRewriter #:nodoc:
5
63
  RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :trailing_slash, :skip_relative_url_root]
6
64
  def initialize(request, parameters)
7
65
  @request, @parameters = request, parameters
8
66
  end
9
67
 
10
- def rewrite(options = {})
68
+ def rewrite(options = {})
11
69
  rewrite_url(rewrite_path(options), options)
12
70
  end
13
71
 
@@ -41,34 +99,10 @@ module ActionController
41
99
  options.update(overwrite)
42
100
  end
43
101
  RESERVED_OPTIONS.each {|k| options.delete k}
44
- path, extra_keys = Routing::Routes.generate(options.dup, @request) # Warning: Routes will mutate and violate the options hash
45
-
46
- path << build_query_string(options, extra_keys) unless extra_keys.empty?
47
-
48
- path
49
- end
50
102
 
51
- # Returns a query string with escaped keys and values from the passed hash. If the passed hash contains an "id" it'll
52
- # be added as a path element instead of a regular parameter pair.
53
- def build_query_string(hash, only_keys = nil)
54
- elements = []
55
- query_string = ""
56
-
57
- only_keys ||= hash.keys
58
-
59
- only_keys.each do |key|
60
- value = hash[key]
61
- key = CGI.escape key.to_s
62
- if value.class == Array
63
- key << '[]'
64
- else
65
- value = [ value ]
66
- end
67
- value.each { |val| elements << "#{key}=#{Routing.extract_parameter_value(val)}" }
68
- end
69
-
70
- query_string << ("?" + elements.join("&")) unless elements.empty?
71
- query_string
103
+ # Generates the query string, too
104
+ Routing::Routes.generate(options, @request.symbolized_path_parameters)
72
105
  end
73
106
  end
107
+
74
108
  end
@@ -1,5 +1,6 @@
1
1
  require File.dirname(__FILE__) + '/tokenizer'
2
2
  require File.dirname(__FILE__) + '/node'
3
+ require File.dirname(__FILE__) + '/selector'
3
4
 
4
5
  module HTML #:nodoc:
5
6
 
@@ -156,7 +156,7 @@ module HTML #:nodoc:
156
156
  end
157
157
 
158
158
  closing = ( scanner.scan(/\//) ? :close : nil )
159
- return Text.new(parent, line, pos, content) unless name = scanner.scan(/[\w:]+/)
159
+ return Text.new(parent, line, pos, content) unless name = scanner.scan(/[\w:-]+/)
160
160
  name.downcase!
161
161
 
162
162
  unless closing
@@ -239,7 +239,7 @@ module HTML #:nodoc:
239
239
  def match(conditions)
240
240
  case conditions
241
241
  when String
242
- @content.index(conditions)
242
+ @content == conditions
243
243
  when Regexp
244
244
  @content =~ conditions
245
245
  when Hash
@@ -316,7 +316,7 @@ module HTML #:nodoc:
316
316
  s = "<#{@name}"
317
317
  @attributes.each do |k,v|
318
318
  s << " #{k}"
319
- s << "='#{v.gsub(/'/,"\\\\'")}'" if String === v
319
+ s << "=\"#{v}\"" if String === v
320
320
  end
321
321
  s << " /" if @closing == :self
322
322
  s << ">"
@@ -455,7 +455,6 @@ module HTML #:nodoc:
455
455
  # count children
456
456
  if opts = conditions[:children]
457
457
  matches = children.select do |c|
458
- c.match(/./) or
459
458
  (c.kind_of?(HTML::Tag) and (c.closing == :self or ! c.childless?))
460
459
  end
461
460
 
@@ -0,0 +1,822 @@
1
+ #--
2
+ # Copyright (c) 2006 Assaf Arkin (http://labnotes.org)
3
+ # Under MIT and/or CC By license.
4
+ #++
5
+
6
+ module HTML
7
+
8
+ # Selects HTML elements using CSS 2 selectors.
9
+ #
10
+ # The +Selector+ class uses CSS selector expressions to match and select
11
+ # HTML elements.
12
+ #
13
+ # For example:
14
+ # selector = HTML::Selector.new "form.login[action=/login]"
15
+ # creates a new selector that matches any +form+ element with the class
16
+ # +login+ and an attribute +action+ with the value <tt>/login</tt>.
17
+ #
18
+ # === Matching Elements
19
+ #
20
+ # Use the #match method to determine if an element matches the selector.
21
+ #
22
+ # For simple selectors, the method returns an array with that element,
23
+ # or +nil+ if the element does not match. For complex selectors (see below)
24
+ # the method returns an array with all matched elements, of +nil+ if no
25
+ # match found.
26
+ #
27
+ # For example:
28
+ # if selector.match(element)
29
+ # puts "Element is a login form"
30
+ # end
31
+ #
32
+ # === Selecting Elements
33
+ #
34
+ # Use the #select method to select all matching elements starting with
35
+ # one element and going through all children in depth-first order.
36
+ #
37
+ # This method returns an array of all matching elements, an empty array
38
+ # if no match is found
39
+ #
40
+ # For example:
41
+ # selector = HTML::Selector.new "input[type=text]"
42
+ # matches = selector.select(element)
43
+ # matches.each do |match|
44
+ # puts "Found text field with name #{match.attributes['name']}"
45
+ # end
46
+ #
47
+ # === Expressions
48
+ #
49
+ # Selectors can match elements using any of the following criteria:
50
+ # * <tt>name</tt> -- Match an element based on its name (tag name).
51
+ # For example, <tt>p</tt> to match a paragraph. You can use <tt>*</tt>
52
+ # to match any element.
53
+ # * <tt>#</tt><tt>id</tt> -- Match an element based on its identifier (the
54
+ # <tt>id</tt> attribute). For example, <tt>#</tt><tt>page</tt>.
55
+ # * <tt>.class</tt> -- Match an element based on its class name, all
56
+ # class names if more than one specified.
57
+ # * <tt>[attr]</tt> -- Match an element that has the specified attribute.
58
+ # * <tt>[attr=value]</tt> -- Match an element that has the specified
59
+ # attribute and value. (More operators are supported see below)
60
+ # * <tt>:pseudo-class</tt> -- Match an element based on a pseudo class,
61
+ # such as <tt>:nth-child</tt> and <tt>:empty</tt>.
62
+ # * <tt>:not(expr)</tt> -- Match an element that does not match the
63
+ # negation expression.
64
+ #
65
+ # When using a combination of the above, the element name comes first
66
+ # followed by identifier, class names, attributes, pseudo classes and
67
+ # negation in any order. Do not seprate these parts with spaces!
68
+ # Space separation is used for descendant selectors.
69
+ #
70
+ # For example:
71
+ # selector = HTML::Selector.new "form.login[action=/login]"
72
+ # The matched element must be of type +form+ and have the class +login+.
73
+ # It may have other classes, but the class +login+ is required to match.
74
+ # It must also have an attribute called +action+ with the value
75
+ # <tt>/login</tt>.
76
+ #
77
+ # This selector will match the following element:
78
+ # <form class="login form" method="post" action="/login">
79
+ # but will not match the element:
80
+ # <form method="post" action="/logout">
81
+ #
82
+ # === Attribute Values
83
+ #
84
+ # Several operators are supported for matching attributes:
85
+ # * <tt>name</tt> -- The element must have an attribute with that name.
86
+ # * <tt>name=value</tt> -- The element must have an attribute with that
87
+ # name and value.
88
+ # * <tt>name^=value</tt> -- The attribute value must start with the
89
+ # specified value.
90
+ # * <tt>name$=value</tt> -- The attribute value must end with the
91
+ # specified value.
92
+ # * <tt>name*=value</tt> -- The attribute value must contain the
93
+ # specified value.
94
+ # * <tt>name~=word</tt> -- The attribute value must contain the specified
95
+ # word (space separated).
96
+ # * <tt>name|=word</tt> -- The attribute value must start with specified
97
+ # word.
98
+ #
99
+ # For example, the following two selectors match the same element:
100
+ # #my_id
101
+ # [id=my_id]
102
+ # and so do the following two selectors:
103
+ # .my_class
104
+ # [class~=my_class]
105
+ #
106
+ # === Alternatives, siblings, children
107
+ #
108
+ # Complex selectors use a combination of expressions to match elements:
109
+ # * <tt>expr1 expr2</tt> -- Match any element against the second expression
110
+ # if it has some parent element that matches the first expression.
111
+ # * <tt>expr1 > expr2</tt> -- Match any element against the second expression
112
+ # if it is the child of an element that matches the first expression.
113
+ # * <tt>expr1 + expr2</tt> -- Match any element against the second expression
114
+ # if it immediately follows an element that matches the first expression.
115
+ # * <tt>expr1 ~ expr2</tt> -- Match any element against the second expression
116
+ # that comes after an element that matches the first expression.
117
+ # * <tt>expr1, expr2</tt> -- Match any element against the first expression,
118
+ # or against the second expression.
119
+ #
120
+ # Since children and sibling selectors may match more than one element given
121
+ # the first element, the #match method may return more than one match.
122
+ #
123
+ # === Pseudo classes
124
+ #
125
+ # Pseudo classes were introduced in CSS 3. They are most often used to select
126
+ # elements in a given position:
127
+ # * <tt>:root</tt> -- Match the element only if it is the root element
128
+ # (no parent element).
129
+ # * <tt>:empty</tt> -- Match the element only if it has no child elements,
130
+ # and no text content.
131
+ # * <tt>:only-child</tt> -- Match the element if it is the only child (element)
132
+ # of its parent element.
133
+ # * <tt>:only-of-type</tt> -- Match the element if it is the only child (element)
134
+ # of its parent element and its type.
135
+ # * <tt>:first-child</tt> -- Match the element if it is the first child (element)
136
+ # of its parent element.
137
+ # * <tt>:first-of-type</tt> -- Match the element if it is the first child (element)
138
+ # of its parent element of its type.
139
+ # * <tt>:last-child</tt> -- Match the element if it is the last child (element)
140
+ # of its parent element.
141
+ # * <tt>:last-of-type</tt> -- Match the element if it is the last child (element)
142
+ # of its parent element of its type.
143
+ # * <tt>:nth-child(b)</tt> -- Match the element if it is the b-th child (element)
144
+ # of its parent element. The value <tt>b</tt> specifies its index, starting with 1.
145
+ # * <tt>:nth-child(an+b)</tt> -- Match the element if it is the b-th child (element)
146
+ # in each group of <tt>a</tt> child elements of its parent element.
147
+ # * <tt>:nth-child(-an+b)</tt> -- Match the element if it is the first child (element)
148
+ # in each group of <tt>a</tt> child elements, up to the first <tt>b</tt> child
149
+ # elements of its parent element.
150
+ # * <tt>:nth-child(odd)</tt> -- Match element in the odd position (i.e. first, third).
151
+ # Same as <tt>:nth-child(2n+1)</tt>.
152
+ # * <tt>:nth-child(even)</tt> -- Match element in the even position (i.e. second,
153
+ # fourth). Same as <tt>:nth-child(2n+2)</tt>.
154
+ # * <tt>:nth-of-type(..)</tt> -- As above, but only counts elements of its type.
155
+ # * <tt>:nth-last-child(..)</tt> -- As above, but counts from the last child.
156
+ # * <tt>:nth-last-of-type(..)</tt> -- As above, but counts from the last child and
157
+ # only elements of its type.
158
+ # * <tt>:not(selector)</tt> -- Match the element only if the element does not
159
+ # match the simple selector.
160
+ #
161
+ # As you can see, <tt>:nth-child<tt> pseudo class and its varient can get quite
162
+ # tricky and the CSS specification doesn't do a much better job explaining it.
163
+ # But after reading the examples and trying a few combinations, it's easy to
164
+ # figure out.
165
+ #
166
+ # For example:
167
+ # table tr:nth-child(odd)
168
+ # Selects every second row in the table starting with the first one.
169
+ #
170
+ # div p:nth-child(4)
171
+ # Selects the fourth paragraph in the +div+, but not if the +div+ contains
172
+ # other elements, since those are also counted.
173
+ #
174
+ # div p:nth-of-type(4)
175
+ # Selects the fourth paragraph in the +div+, counting only paragraphs, and
176
+ # ignoring all other elements.
177
+ #
178
+ # div p:nth-of-type(-n+4)
179
+ # Selects the first four paragraphs, ignoring all others.
180
+ #
181
+ # And you can always select an element that matches one set of rules but
182
+ # not another using <tt>:not</tt>. For example:
183
+ # p:not(.post)
184
+ # Matches all paragraphs that do not have the class <tt>.post</tt>.
185
+ #
186
+ # === Substitution Values
187
+ #
188
+ # You can use substitution with identifiers, class names and element values.
189
+ # A substitution takes the form of a question mark (<tt>?</tt>) and uses the
190
+ # next value in the argument list following the CSS expression.
191
+ #
192
+ # The substitution value may be a string or a regular expression. All other
193
+ # values are converted to strings.
194
+ #
195
+ # For example:
196
+ # selector = HTML::Selector.new "#?", /^\d+$/
197
+ # matches any element whose identifier consists of one or more digits.
198
+ #
199
+ # See http://www.w3.org/TR/css3-selectors/
200
+ class Selector
201
+
202
+
203
+ # An invalid selector.
204
+ class InvalidSelectorError < StandardError ; end
205
+
206
+
207
+ class << self
208
+
209
+ # :call-seq:
210
+ # Selector.for_class(cls) => selector
211
+ #
212
+ # Creates a new selector for the given class name.
213
+ def for_class(cls)
214
+ self.new([".?", cls])
215
+ end
216
+
217
+
218
+ # :call-seq:
219
+ # Selector.for_id(id) => selector
220
+ #
221
+ # Creates a new selector for the given id.
222
+ def for_id(id)
223
+ self.new(["#?", id])
224
+ end
225
+
226
+ end
227
+
228
+
229
+ # :call-seq:
230
+ # Selector.new(string, [values ...]) => selector
231
+ #
232
+ # Creates a new selector from a CSS 2 selector expression.
233
+ #
234
+ # The first argument is the selector expression. All other arguments
235
+ # are used for value substitution.
236
+ #
237
+ # Throws InvalidSelectorError is the selector expression is invalid.
238
+ def initialize(selector, *values)
239
+ raise ArgumentError, "CSS expression cannot be empty" if selector.empty?
240
+ @source = ""
241
+ values = values[0] if values.size == 1 && values[0].is_a?(Array)
242
+ # We need a copy to determine if we failed to parse, and also
243
+ # preserve the original pass by-ref statement.
244
+ statement = selector.strip.dup
245
+ # Create a simple selector, along with negation.
246
+ simple_selector(statement, values).each { |name, value| instance_variable_set("@#{name}", value) }
247
+
248
+ # Alternative selector.
249
+ if statement.sub!(/^\s*,\s*/, "")
250
+ second = Selector.new(statement, values)
251
+ (@alternates ||= []) << second
252
+ # If there are alternate selectors, we group them in the top selector.
253
+ if alternates = second.instance_variable_get(:@alternates)
254
+ second.instance_variable_set(:@alternates, nil)
255
+ @alternates.concat alternates
256
+ end
257
+ @source << " , " << second.to_s
258
+ # Sibling selector: create a dependency into second selector that will
259
+ # match element immediately following this one.
260
+ elsif statement.sub!(/^\s*\+\s*/, "")
261
+ second = next_selector(statement, values)
262
+ @depends = lambda do |element, first|
263
+ if element = next_element(element)
264
+ second.match(element, first)
265
+ end
266
+ end
267
+ @source << " + " << second.to_s
268
+ # Adjacent selector: create a dependency into second selector that will
269
+ # match all elements following this one.
270
+ elsif statement.sub!(/^\s*~\s*/, "")
271
+ second = next_selector(statement, values)
272
+ @depends = lambda do |element, first|
273
+ matches = []
274
+ while element = next_element(element)
275
+ if subset = second.match(element, first)
276
+ if first && !subset.empty?
277
+ matches << subset.first
278
+ break
279
+ else
280
+ matches.concat subset
281
+ end
282
+ end
283
+ end
284
+ matches.empty? ? nil : matches
285
+ end
286
+ @source << " ~ " << second.to_s
287
+ # Child selector: create a dependency into second selector that will
288
+ # match a child element of this one.
289
+ elsif statement.sub!(/^\s*>\s*/, "")
290
+ second = next_selector(statement, values)
291
+ @depends = lambda do |element, first|
292
+ matches = []
293
+ element.children.each do |child|
294
+ if child.tag? && subset = second.match(child, first)
295
+ if first && !subset.empty?
296
+ matches << subset.first
297
+ break
298
+ else
299
+ matches.concat subset
300
+ end
301
+ end
302
+ end
303
+ matches.empty? ? nil : matches
304
+ end
305
+ @source << " > " << second.to_s
306
+ # Descendant selector: create a dependency into second selector that
307
+ # will match all descendant elements of this one. Note,
308
+ elsif statement =~ /^\s+\S+/ && statement != selector
309
+ second = next_selector(statement, values)
310
+ @depends = lambda do |element, first|
311
+ matches = []
312
+ stack = element.children.reverse
313
+ while node = stack.pop
314
+ next unless node.tag?
315
+ if subset = second.match(node, first)
316
+ if first && !subset.empty?
317
+ matches << subset.first
318
+ break
319
+ else
320
+ matches.concat subset
321
+ end
322
+ elsif children = node.children
323
+ stack.concat children.reverse
324
+ end
325
+ end
326
+ matches.empty? ? nil : matches
327
+ end
328
+ @source << " " << second.to_s
329
+ else
330
+ # The last selector is where we check that we parsed
331
+ # all the parts.
332
+ unless statement.empty? || statement.strip.empty?
333
+ raise ArgumentError, "Invalid selector: #{statement}"
334
+ end
335
+ end
336
+ end
337
+
338
+
339
+ # :call-seq:
340
+ # match(element, first?) => array or nil
341
+ #
342
+ # Matches an element against the selector.
343
+ #
344
+ # For a simple selector this method returns an array with the
345
+ # element if the element matches, nil otherwise.
346
+ #
347
+ # For a complex selector (sibling and descendant) this method
348
+ # returns an array with all matching elements, nil if no match is
349
+ # found.
350
+ #
351
+ # Use +first_only=true+ if you are only interested in the first element.
352
+ #
353
+ # For example:
354
+ # if selector.match(element)
355
+ # puts "Element is a login form"
356
+ # end
357
+ def match(element, first_only = false)
358
+ # Match element if no element name or element name same as element name
359
+ if matched = (!@tag_name || @tag_name == element.name)
360
+ # No match if one of the attribute matches failed
361
+ for attr in @attributes
362
+ if element.attributes[attr[0]] !~ attr[1]
363
+ matched = false
364
+ break
365
+ end
366
+ end
367
+ end
368
+
369
+ # Pseudo class matches (nth-child, empty, etc).
370
+ if matched
371
+ for pseudo in @pseudo
372
+ unless pseudo.call(element)
373
+ matched = false
374
+ break
375
+ end
376
+ end
377
+ end
378
+
379
+ # Negation. Same rules as above, but we fail if a match is made.
380
+ if matched && @negation
381
+ for negation in @negation
382
+ if negation[:tag_name] == element.name
383
+ matched = false
384
+ else
385
+ for attr in negation[:attributes]
386
+ if element.attributes[attr[0]] =~ attr[1]
387
+ matched = false
388
+ break
389
+ end
390
+ end
391
+ end
392
+ if matched
393
+ for pseudo in negation[:pseudo]
394
+ if pseudo.call(element)
395
+ matched = false
396
+ break
397
+ end
398
+ end
399
+ end
400
+ break unless matched
401
+ end
402
+ end
403
+
404
+ # If element matched but depends on another element (child,
405
+ # sibling, etc), apply the dependent matches instead.
406
+ if matched && @depends
407
+ matches = @depends.call(element, first_only)
408
+ else
409
+ matches = matched ? [element] : nil
410
+ end
411
+
412
+ # If this selector is part of the group, try all the alternative
413
+ # selectors (unless first_only).
414
+ if @alternates && (!first_only || !matches)
415
+ @alternates.each do |alternate|
416
+ break if matches && first_only
417
+ if subset = alternate.match(element, first_only)
418
+ if matches
419
+ matches.concat subset
420
+ else
421
+ matches = subset
422
+ end
423
+ end
424
+ end
425
+ end
426
+
427
+ matches
428
+ end
429
+
430
+
431
+ # :call-seq:
432
+ # select(root) => array
433
+ #
434
+ # Selects and returns an array with all matching elements, beginning
435
+ # with one node and traversing through all children depth-first.
436
+ # Returns an empty array if no match is found.
437
+ #
438
+ # The root node may be any element in the document, or the document
439
+ # itself.
440
+ #
441
+ # For example:
442
+ # selector = HTML::Selector.new "input[type=text]"
443
+ # matches = selector.select(element)
444
+ # matches.each do |match|
445
+ # puts "Found text field with name #{match.attributes['name']}"
446
+ # end
447
+ def select(root)
448
+ matches = []
449
+ stack = [root]
450
+ while node = stack.pop
451
+ if node.tag? && subset = match(node, false)
452
+ subset.each do |match|
453
+ matches << match unless matches.any? { |item| item.equal?(match) }
454
+ end
455
+ elsif children = node.children
456
+ stack.concat children.reverse
457
+ end
458
+ end
459
+ matches
460
+ end
461
+
462
+
463
+ # Similar to #select but returns the first matching element. Returns +nil+
464
+ # if no element matches the selector.
465
+ def select_first(root)
466
+ stack = [root]
467
+ while node = stack.pop
468
+ if node.tag? && subset = match(node, true)
469
+ return subset.first if !subset.empty?
470
+ elsif children = node.children
471
+ stack.concat children.reverse
472
+ end
473
+ end
474
+ nil
475
+ end
476
+
477
+
478
+ def to_s #:nodoc:
479
+ @source
480
+ end
481
+
482
+
483
+ # Return the next element after this one. Skips sibling text nodes.
484
+ #
485
+ # With the +name+ argument, returns the next element with that name,
486
+ # skipping other sibling elements.
487
+ def next_element(element, name = nil)
488
+ if siblings = element.parent.children
489
+ found = false
490
+ siblings.each do |node|
491
+ if node.equal?(element)
492
+ found = true
493
+ elsif found && node.tag?
494
+ return node if (name.nil? || node.name == name)
495
+ end
496
+ end
497
+ end
498
+ nil
499
+ end
500
+
501
+
502
+ protected
503
+
504
+
505
+ # Creates a simple selector given the statement and array of
506
+ # substitution values.
507
+ #
508
+ # Returns a hash with the values +tag_name+, +attributes+,
509
+ # +pseudo+ (classes) and +negation+.
510
+ #
511
+ # Called the first time with +can_negate+ true to allow
512
+ # negation. Called a second time with false since negation
513
+ # cannot be negated.
514
+ def simple_selector(statement, values, can_negate = true)
515
+ tag_name = nil
516
+ attributes = []
517
+ pseudo = []
518
+ negation = []
519
+
520
+ # Element name. (Note that in negation, this can come at
521
+ # any order, but for simplicity we allow if only first).
522
+ statement.sub!(/^(\*|[[:alpha:]][\w\-]*)/) do |match|
523
+ match.strip!
524
+ tag_name = match.downcase unless match == "*"
525
+ @source << match
526
+ "" # Remove
527
+ end
528
+
529
+ # Get identifier, class, attribute name, pseudo or negation.
530
+ while true
531
+ # Element identifier.
532
+ next if statement.sub!(/^#(\?|[\w\-]+)/) do |match|
533
+ id = $1
534
+ if id == "?"
535
+ id = values.shift
536
+ end
537
+ @source << "##{id}"
538
+ id = Regexp.new("^#{Regexp.escape(id.to_s)}$") unless id.is_a?(Regexp)
539
+ attributes << ["id", id]
540
+ "" # Remove
541
+ end
542
+
543
+ # Class name.
544
+ next if statement.sub!(/^\.([\w\-]+)/) do |match|
545
+ class_name = $1
546
+ @source << ".#{class_name}"
547
+ class_name = Regexp.new("(^|\s)#{Regexp.escape(class_name)}($|\s)") unless class_name.is_a?(Regexp)
548
+ attributes << ["class", class_name]
549
+ "" # Remove
550
+ end
551
+
552
+ # Attribute value.
553
+ next if statement.sub!(/^\[\s*([[:alpha:]][\w\-]*)\s*((?:[~|^$*])?=)?\s*('[^']*'|"[^*]"|[^\]]*)\s*\]/) do |match|
554
+ name, equality, value = $1, $2, $3
555
+ if value == "?"
556
+ value = values.shift
557
+ else
558
+ # Handle single and double quotes.
559
+ value.strip!
560
+ if (value[0] == ?" || value[0] == ?') && value[0] == value[-1]
561
+ value = value[1..-2]
562
+ end
563
+ end
564
+ @source << "[#{name}#{equality}'#{value}']"
565
+ attributes << [name.downcase.strip, attribute_match(equality, value)]
566
+ "" # Remove
567
+ end
568
+
569
+ # Root element only.
570
+ next if statement.sub!(/^:root/) do |match|
571
+ pseudo << lambda do |element|
572
+ element.parent.nil? || !element.parent.tag?
573
+ end
574
+ @source << ":root"
575
+ "" # Remove
576
+ end
577
+
578
+ # Nth-child including last and of-type.
579
+ next if statement.sub!(/^:nth-(last-)?(child|of-type)\((odd|even|(\d+|\?)|(-?\d*|\?)?n([+\-]\d+|\?)?)\)/) do |match|
580
+ reverse = $1 == "last-"
581
+ of_type = $2 == "of-type"
582
+ @source << ":nth-#{$1}#{$2}("
583
+ case $3
584
+ when "odd"
585
+ pseudo << nth_child(2, 1, of_type, reverse)
586
+ @source << "odd)"
587
+ when "even"
588
+ pseudo << nth_child(2, 2, of_type, reverse)
589
+ @source << "even)"
590
+ when /^(\d+|\?)$/ # b only
591
+ b = ($1 == "?" ? values.shift : $1).to_i
592
+ pseudo << nth_child(0, b, of_type, reverse)
593
+ @source << "#{b})"
594
+ when /^(-?\d*|\?)?n([+\-]\d+|\?)?$/
595
+ a = ($1 == "?" ? values.shift :
596
+ $1 == "" ? 1 : $1 == "-" ? -1 : $1).to_i
597
+ b = ($2 == "?" ? values.shift : $2).to_i
598
+ pseudo << nth_child(a, b, of_type, reverse)
599
+ @source << (b >= 0 ? "#{a}n+#{b})" : "#{a}n#{b})")
600
+ else
601
+ raise ArgumentError, "Invalid nth-child #{match}"
602
+ end
603
+ "" # Remove
604
+ end
605
+ # First/last child (of type).
606
+ next if statement.sub!(/^:(first|last)-(child|of-type)/) do |match|
607
+ reverse = $1 == "last"
608
+ of_type = $2 == "of-type"
609
+ pseudo << nth_child(0, 1, of_type, reverse)
610
+ @source << ":#{$1}-#{$2}"
611
+ "" # Remove
612
+ end
613
+ # Only child (of type).
614
+ next if statement.sub!(/^:only-(child|of-type)/) do |match|
615
+ of_type = $1 == "of-type"
616
+ pseudo << only_child(of_type)
617
+ @source << ":only-#{$1}"
618
+ "" # Remove
619
+ end
620
+
621
+ # Empty: no child elements or meaningful content (whitespaces
622
+ # are ignored).
623
+ next if statement.sub!(/^:empty/) do |match|
624
+ pseudo << lambda do |element|
625
+ empty = true
626
+ for child in element.children
627
+ if child.tag? || !child.content.strip.empty?
628
+ empty = false
629
+ break
630
+ end
631
+ end
632
+ empty
633
+ end
634
+ @source << ":empty"
635
+ "" # Remove
636
+ end
637
+ # Content: match the text content of the element, stripping
638
+ # leading and trailing spaces.
639
+ next if statement.sub!(/^:content\(\s*(\?|'[^']*'|"[^"]*"|[^)]*)\s*\)/) do |match|
640
+ content = $1
641
+ if content == "?"
642
+ content = values.shift
643
+ elsif (content[0] == ?" || content[0] == ?') && content[0] == content[-1]
644
+ content = content[1..-2]
645
+ end
646
+ @source << ":content('#{content}')"
647
+ content = Regexp.new("^#{Regexp.escape(content.to_s)}$") unless content.is_a?(Regexp)
648
+ pseudo << lambda do |element|
649
+ text = ""
650
+ for child in element.children
651
+ unless child.tag?
652
+ text << child.content
653
+ end
654
+ end
655
+ text.strip =~ content
656
+ end
657
+ "" # Remove
658
+ end
659
+
660
+ # Negation. Create another simple selector to handle it.
661
+ if statement.sub!(/^:not\(\s*/, "")
662
+ raise ArgumentError, "Double negatives are not missing feature" unless can_negate
663
+ @source << ":not("
664
+ negation << simple_selector(statement, values, false)
665
+ raise ArgumentError, "Negation not closed" unless statement.sub!(/^\s*\)/, "")
666
+ @source << ")"
667
+ next
668
+ end
669
+
670
+ # No match: moving on.
671
+ break
672
+ end
673
+
674
+ # Return hash. The keys are mapped to instance variables.
675
+ {:tag_name=>tag_name, :attributes=>attributes, :pseudo=>pseudo, :negation=>negation}
676
+ end
677
+
678
+
679
+ # Create a regular expression to match an attribute value based
680
+ # on the equality operator (=, ^=, |=, etc).
681
+ def attribute_match(equality, value)
682
+ regexp = value.is_a?(Regexp) ? value : Regexp.escape(value.to_s)
683
+ case equality
684
+ when "=" then
685
+ # Match the attribute value in full
686
+ Regexp.new("^#{regexp}$")
687
+ when "~=" then
688
+ # Match a space-separated word within the attribute value
689
+ Regexp.new("(^|\s)#{regexp}($|\s)")
690
+ when "^="
691
+ # Match the beginning of the attribute value
692
+ Regexp.new("^#{regexp}")
693
+ when "$="
694
+ # Match the end of the attribute value
695
+ Regexp.new("#{regexp}$")
696
+ when "*="
697
+ # Match substring of the attribute value
698
+ regexp.is_a?(Regexp) ? regexp : Regexp.new(regexp)
699
+ when "|=" then
700
+ # Match the first space-separated item of the attribute value
701
+ Regexp.new("^#{regexp}($|\s)")
702
+ else
703
+ raise InvalidSelectorError, "Invalid operation/value" unless value.empty?
704
+ # Match all attributes values (existence check)
705
+ //
706
+ end
707
+ end
708
+
709
+
710
+ # Returns a lambda that can match an element against the nth-child
711
+ # pseudo class, given the following arguments:
712
+ # * +a+ -- Value of a part.
713
+ # * +b+ -- Value of b part.
714
+ # * +of_type+ -- True to test only elements of this type (of-type).
715
+ # * +reverse+ -- True to count in reverse order (last-).
716
+ def nth_child(a, b, of_type, reverse)
717
+ # a = 0 means select at index b, if b = 0 nothing selected
718
+ return lambda { |element| false } if a == 0 && b == 0
719
+ # a < 0 and b < 0 will never match against an index
720
+ return lambda { |element| false } if a < 0 && b < 0
721
+ b = a + b + 1 if b < 0 # b < 0 just picks last element from each group
722
+ b -= 1 unless b == 0 # b == 0 is same as b == 1, otherwise zero based
723
+ lambda do |element|
724
+ # Element must be inside parent element.
725
+ return false unless element.parent && element.parent.tag?
726
+ index = 0
727
+ # Get siblings, reverse if counting from last.
728
+ siblings = element.parent.children
729
+ siblings = siblings.reverse if reverse
730
+ # Match element name if of-type, otherwise ignore name.
731
+ name = of_type ? element.name : nil
732
+ found = false
733
+ for child in siblings
734
+ # Skip text nodes/comments.
735
+ if child.tag? && (name == nil || child.name == name)
736
+ if a == 0
737
+ # Shortcut when a == 0 no need to go past count
738
+ if index == b
739
+ found = child.equal?(element)
740
+ break
741
+ end
742
+ elsif a < 0
743
+ # Only look for first b elements
744
+ break if index > b
745
+ if child.equal?(element)
746
+ found = (index % a) == 0
747
+ break
748
+ end
749
+ else
750
+ # Otherwise, break if child found and count == an+b
751
+ if child.equal?(element)
752
+ found = (index % a) == b
753
+ break
754
+ end
755
+ end
756
+ index += 1
757
+ end
758
+ end
759
+ found
760
+ end
761
+ end
762
+
763
+
764
+ # Creates a only child lambda. Pass +of-type+ to only look at
765
+ # elements of its type.
766
+ def only_child(of_type)
767
+ lambda do |element|
768
+ # Element must be inside parent element.
769
+ return false unless element.parent && element.parent.tag?
770
+ name = of_type ? element.name : nil
771
+ other = false
772
+ for child in element.parent.children
773
+ # Skip text nodes/comments.
774
+ if child.tag? && (name == nil || child.name == name)
775
+ unless child.equal?(element)
776
+ other = true
777
+ break
778
+ end
779
+ end
780
+ end
781
+ !other
782
+ end
783
+ end
784
+
785
+
786
+ # Called to create a dependent selector (sibling, descendant, etc).
787
+ # Passes the remainder of the statement that will be reduced to zero
788
+ # eventually, and array of substitution values.
789
+ #
790
+ # This method is called from four places, so it helps to put it here
791
+ # for resue. The only logic deals with the need to detect comma
792
+ # separators (alternate) and apply them to the selector group of the
793
+ # top selector.
794
+ def next_selector(statement, values)
795
+ second = Selector.new(statement, values)
796
+ # If there are alternate selectors, we group them in the top selector.
797
+ if alternates = second.instance_variable_get(:@alternates)
798
+ second.instance_variable_set(:@alternates, nil)
799
+ (@alternates ||= []).concat alternates
800
+ end
801
+ second
802
+ end
803
+
804
+ end
805
+
806
+
807
+ # See HTML::Selector.new
808
+ def self.selector(statement, *values)
809
+ Selector.new(statement, *values)
810
+ end
811
+
812
+
813
+ class Tag
814
+
815
+ def select(selector, *values)
816
+ selector = HTML::Selector.new(selector, values)
817
+ selector.select(self)
818
+ end
819
+
820
+ end
821
+
822
+ end