diff options
Diffstat (limited to 'vendor/plugins')
124 files changed, 0 insertions, 8794 deletions
diff --git a/vendor/plugins/active_record_base_without_table/CHANGELOG b/vendor/plugins/active_record_base_without_table/CHANGELOG deleted file mode 100644 index c74809532..000000000 --- a/vendor/plugins/active_record_base_without_table/CHANGELOG +++ /dev/null @@ -1,3 +0,0 @@ -[27 April 2007]
-
-* Correctly cache class instance variables containing column information [Reported by Nils Jonsson]
diff --git a/vendor/plugins/active_record_base_without_table/MIT-LICENSE b/vendor/plugins/active_record_base_without_table/MIT-LICENSE deleted file mode 100644 index 602bda208..000000000 --- a/vendor/plugins/active_record_base_without_table/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2006 Jonathan Viney - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/active_record_base_without_table/README b/vendor/plugins/active_record_base_without_table/README deleted file mode 100644 index 8200d7ad6..000000000 --- a/vendor/plugins/active_record_base_without_table/README +++ /dev/null @@ -1,29 +0,0 @@ -= ActiveRecordBaseWithoutTable - -If you find this plugin useful, please consider a donation to show your support! - - http://www.paypal.com/cgi-bin/webscr?cmd=_send-money - - Email address: jonathan.viney@gmail.com - -== Instructions - -* For edge Rails r7315 or above use http://svn.viney.net.nz/things/branches/active_record_base_without_table - -Get the power of ActiveRecord models, including validation, without having a table in the database. - - class Contact < ActiveRecord::BaseWithoutTable - column :name, :string - column :email_address, :string - column :message, :text - - validates_presence_of :name, :email_address, :string - end - -This model can be used just like a regular model based on a table, except it will never be saved to the database. - -There is a good blog post available on the plugin: - - http://www.kangarooit.com/developer_blog/2007/02/email-form-validation-in-ruby-on-rails.php - -Any bugs, questions, comments please feel free to email me: jonathan.viney@gmail.com diff --git a/vendor/plugins/active_record_base_without_table/Rakefile b/vendor/plugins/active_record_base_without_table/Rakefile deleted file mode 100644 index ac9244515..000000000 --- a/vendor/plugins/active_record_base_without_table/Rakefile +++ /dev/null @@ -1,22 +0,0 @@ -require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the active_record_base_without_table plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the active_record_base_without_table plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'ActiveRecordBaseWithoutTable' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/vendor/plugins/active_record_base_without_table/lib/active_record/base_without_table.rb b/vendor/plugins/active_record_base_without_table/lib/active_record/base_without_table.rb deleted file mode 100644 index 12cb05e02..000000000 --- a/vendor/plugins/active_record_base_without_table/lib/active_record/base_without_table.rb +++ /dev/null @@ -1,26 +0,0 @@ -module ActiveRecord
- class BaseWithoutTable < Base
- self.abstract_class = true
-
- def create_or_update
- errors.empty?
- end
-
- class << self
- def columns()
- @columns ||= []
- end
-
- def column(name, sql_type = nil, default = nil, null = true)
- columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
- reset_column_information
- end
-
- # Do not reset @columns
- def reset_column_information
- generated_methods.each { |name| undef_method(name) }
- @column_names = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = nil
- end
- end
- end
-end
diff --git a/vendor/plugins/active_record_base_without_table/test/abstract_unit.rb b/vendor/plugins/active_record_base_without_table/test/abstract_unit.rb deleted file mode 100644 index f72a8785b..000000000 --- a/vendor/plugins/active_record_base_without_table/test/abstract_unit.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'test/unit'
-
-begin
- require File.dirname(__FILE__) + '/../../../../config/boot'
- require 'active_record'
-rescue LoadError
- require 'rubygems'
- require_gem 'activerecord'
-end
-
-require File.dirname(__FILE__) + '/../lib/active_record/base_without_table'
-
-config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
-ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + '/debug.log')
-ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'mysql'])
diff --git a/vendor/plugins/active_record_base_without_table/test/active_record_base_without_table_test.rb b/vendor/plugins/active_record_base_without_table/test/active_record_base_without_table_test.rb deleted file mode 100644 index 8d4bd4115..000000000 --- a/vendor/plugins/active_record_base_without_table/test/active_record_base_without_table_test.rb +++ /dev/null @@ -1,41 +0,0 @@ -require File.dirname(__FILE__) + '/abstract_unit' - -class Person < ActiveRecord::BaseWithoutTable - column :name, :string - column :lucky_number, :integer, 4 - - validates_presence_of :name -end - -class ActiveRecordBaseWithoutTableTest < Test::Unit::TestCase - def test_default_value - assert_equal 4, Person.new.lucky_number - end - - def test_validation - p = Person.new - - assert !p.save - assert p.errors[:name] - - assert p.update_attributes(:name => 'Name') - end - - def test_typecast - assert_equal 1, Person.new(:lucky_number => "1").lucky_number - end - - def test_cached_column_variables_reset_when_column_defined - cached_variables = %w(column_names columns_hash content_columns dynamic_methods_hash read_methods) - - Person.column_names - Person.columns_hash - Person.content_columns - Person.column_methods_hash - Person.read_methods - - cached_variables.each { |v| assert_not_nil Person.instance_variable_get("@#{v}") } - Person.column :new_column, :string - cached_variables.each { |v| assert_nil Person.instance_variable_get("@#{v}") } - end -end diff --git a/vendor/plugins/active_record_base_without_table/test/database.yml b/vendor/plugins/active_record_base_without_table/test/database.yml deleted file mode 100644 index b952dac55..000000000 --- a/vendor/plugins/active_record_base_without_table/test/database.yml +++ /dev/null @@ -1,6 +0,0 @@ -mysql:
- :adapter: mysql
- :host: localhost
- :username: rails
- :password:
- :database: rails_plugin_test
diff --git a/vendor/plugins/acts_as_versioned/CHANGELOG b/vendor/plugins/acts_as_versioned/CHANGELOG deleted file mode 100644 index 01882d767..000000000 --- a/vendor/plugins/acts_as_versioned/CHANGELOG +++ /dev/null @@ -1,82 +0,0 @@ -*GIT* (version numbers are overrated) - -* (16 Jun 2008) Backwards Compatibility is overrated (big updates for rails 2.1) - - * Use ActiveRecord 2.1's dirty attribute checking instead [Asa Calow] - * Remove last traces of #non_versioned_fields - * Remove AR::Base.find_version and AR::Base.find_versions, rely on AR association proxies and named_scope - * Remove #versions_count, rely on AR association counter caching. - * Remove #versioned_attributes, basically the same as AR::Base.versioned_columns - -* (5 Oct 2006) Allow customization of #versions association options [Dan Peterson] - -*0.5.1* - -* (8 Aug 2006) Versioned models now belong to the unversioned model. @article_version.article.class => Article [Aslak Hellesoy] - -*0.5* # do versions even matter for plugins? - -* (21 Apr 2006) Added without_locking and without_revision methods. - - Foo.without_revision do - @foo.update_attributes ... - end - -*0.4* - -* (28 March 2006) Rename non_versioned_fields to non_versioned_columns (old one is kept for compatibility). -* (28 March 2006) Made explicit documentation note that string column names are required for non_versioned_columns. - -*0.3.1* - -* (7 Jan 2006) explicitly set :foreign_key option for the versioned model's belongs_to assocation for STI [Caged] -* (7 Jan 2006) added tests to prove has_many :through joins work - -*0.3* - -* (2 Jan 2006) added ability to share a mixin with versioned class -* (2 Jan 2006) changed the dynamic version model to MyModel::Version - -*0.2.4* - -* (27 Nov 2005) added note about possible destructive behavior of if_changed? [Michael Schuerig] - -*0.2.3* - -* (12 Nov 2005) fixed bug with old behavior of #blank? [Michael Schuerig] -* (12 Nov 2005) updated tests to use ActiveRecord Schema - -*0.2.2* - -* (3 Nov 2005) added documentation note to #acts_as_versioned [Martin Jul] - -*0.2.1* - -* (6 Oct 2005) renamed dirty? to changed? to keep it uniform. it was aliased to keep it backwards compatible. - -*0.2* - -* (6 Oct 2005) added find_versions and find_version class methods. - -* (6 Oct 2005) removed transaction from create_versioned_table(). - this way you can specify your own transaction around a group of operations. - -* (30 Sep 2005) fixed bug where find_versions() would order by 'version' twice. (found by Joe Clark) - -* (26 Sep 2005) added :sequence_name option to acts_as_versioned to set the sequence name on the versioned model - -*0.1.3* (18 Sep 2005) - -* First RubyForge release - -*0.1.2* - -* check if module is already included when acts_as_versioned is called - -*0.1.1* - -* Adding tests and rdocs - -*0.1* - -* Initial transfer from Rails ticket: http://dev.rubyonrails.com/ticket/1974
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/MIT-LICENSE b/vendor/plugins/acts_as_versioned/MIT-LICENSE deleted file mode 100644 index 5851fdae1..000000000 --- a/vendor/plugins/acts_as_versioned/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2005 Rick Olson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/README b/vendor/plugins/acts_as_versioned/README deleted file mode 100644 index 8961f0522..000000000 --- a/vendor/plugins/acts_as_versioned/README +++ /dev/null @@ -1,28 +0,0 @@ -= acts_as_versioned - -This library adds simple versioning to an ActiveRecord module. ActiveRecord is required. - -== Resources - -Install - -* gem install acts_as_versioned - -Rubyforge project - -* http://rubyforge.org/projects/ar-versioned - -RDocs - -* http://ar-versioned.rubyforge.org - -Subversion - -* http://techno-weenie.net/svn/projects/acts_as_versioned - -Collaboa - -* http://collaboa.techno-weenie.net/repository/browse/acts_as_versioned - -Special thanks to Dreamer on ##rubyonrails for help in early testing. His ServerSideWiki (http://serversidewiki.com) -was the first project to use acts_as_versioned <em>in the wild</em>.
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/RUNNING_UNIT_TESTS b/vendor/plugins/acts_as_versioned/RUNNING_UNIT_TESTS deleted file mode 100644 index a6e55b841..000000000 --- a/vendor/plugins/acts_as_versioned/RUNNING_UNIT_TESTS +++ /dev/null @@ -1,41 +0,0 @@ -== Creating the test database - -The default name for the test databases is "activerecord_versioned". If you -want to use another database name then be sure to update the connection -adapter setups you want to test with in test/connections/<your database>/connection.rb. -When you have the database online, you can import the fixture tables with -the test/fixtures/db_definitions/*.sql files. - -Make sure that you create database objects with the same user that you specified in i -connection.rb otherwise (on Postgres, at least) tests for default values will fail. - -== Running with Rake - -The easiest way to run the unit tests is through Rake. The default task runs -the entire test suite for all the adapters. You can also run the suite on just -one adapter by using the tasks test_mysql_ruby, test_ruby_mysql, test_sqlite, -or test_postresql. For more information, checkout the full array of rake tasks with "rake -T" - -Rake can be found at http://rake.rubyforge.org - -== Running by hand - -Unit tests are located in test directory. If you only want to run a single test suite, -or don't want to bother with Rake, you can do so with something like: - - cd test; ruby -I "connections/native_mysql" base_test.rb - -That'll run the base suite using the MySQL-Ruby adapter. Change the adapter -and test suite name as needed. - -== Faster tests - -If you are using a database that supports transactions, you can set the -"AR_TX_FIXTURES" environment variable to "yes" to use transactional fixtures. -This gives a very large speed boost. With rake: - - rake AR_TX_FIXTURES=yes - -Or, by hand: - - AR_TX_FIXTURES=yes ruby -I connections/native_sqlite3 base_test.rb diff --git a/vendor/plugins/acts_as_versioned/Rakefile b/vendor/plugins/acts_as_versioned/Rakefile deleted file mode 100644 index 3ae69e961..000000000 --- a/vendor/plugins/acts_as_versioned/Rakefile +++ /dev/null @@ -1,182 +0,0 @@ -require 'rubygems' - -Gem::manage_gems - -require 'rake/rdoctask' -require 'rake/packagetask' -require 'rake/gempackagetask' -require 'rake/testtask' -require 'rake/contrib/rubyforgepublisher' - -PKG_NAME = 'acts_as_versioned' -PKG_VERSION = '0.3.1' -PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}" -PROD_HOST = "technoweenie@bidwell.textdrive.com" -RUBY_FORGE_PROJECT = 'ar-versioned' -RUBY_FORGE_USER = 'technoweenie' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the calculations plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the calculations plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = "#{PKG_NAME} -- Simple versioning with active record models" - rdoc.options << '--line-numbers --inline-source' - rdoc.rdoc_files.include('README', 'CHANGELOG', 'RUNNING_UNIT_TESTS') - rdoc.rdoc_files.include('lib/**/*.rb') -end - -spec = Gem::Specification.new do |s| - s.name = PKG_NAME - s.version = PKG_VERSION - s.platform = Gem::Platform::RUBY - s.summary = "Simple versioning with active record models" - s.files = FileList["{lib,test}/**/*"].to_a + %w(README MIT-LICENSE CHANGELOG RUNNING_UNIT_TESTS) - s.files.delete "acts_as_versioned_plugin.sqlite.db" - s.files.delete "acts_as_versioned_plugin.sqlite3.db" - s.files.delete "test/debug.log" - s.require_path = 'lib' - s.autorequire = 'acts_as_versioned' - s.has_rdoc = true - s.test_files = Dir['test/**/*_test.rb'] - s.add_dependency 'activerecord', '>= 1.10.1' - s.add_dependency 'activesupport', '>= 1.1.1' - s.author = "Rick Olson" - s.email = "technoweenie@gmail.com" - s.homepage = "http://techno-weenie.net" -end - -Rake::GemPackageTask.new(spec) do |pkg| - pkg.need_tar = true -end - -desc "Publish the API documentation" -task :pdoc => [:rdoc] do - Rake::RubyForgePublisher.new(RUBY_FORGE_PROJECT, RUBY_FORGE_USER).upload -end - -desc 'Publish the gem and API docs' -task :publish => [:pdoc, :rubyforge_upload] - -desc "Publish the release files to RubyForge." -task :rubyforge_upload => :package do - files = %w(gem tgz).map { |ext| "pkg/#{PKG_FILE_NAME}.#{ext}" } - - if RUBY_FORGE_PROJECT then - require 'net/http' - require 'open-uri' - - project_uri = "http://rubyforge.org/projects/#{RUBY_FORGE_PROJECT}/" - project_data = open(project_uri) { |data| data.read } - group_id = project_data[/[?&]group_id=(\d+)/, 1] - raise "Couldn't get group id" unless group_id - - # This echos password to shell which is a bit sucky - if ENV["RUBY_FORGE_PASSWORD"] - password = ENV["RUBY_FORGE_PASSWORD"] - else - print "#{RUBY_FORGE_USER}@rubyforge.org's password: " - password = STDIN.gets.chomp - end - - login_response = Net::HTTP.start("rubyforge.org", 80) do |http| - data = [ - "login=1", - "form_loginname=#{RUBY_FORGE_USER}", - "form_pw=#{password}" - ].join("&") - http.post("/account/login.php", data) - end - - cookie = login_response["set-cookie"] - raise "Login failed" unless cookie - headers = { "Cookie" => cookie } - - release_uri = "http://rubyforge.org/frs/admin/?group_id=#{group_id}" - release_data = open(release_uri, headers) { |data| data.read } - package_id = release_data[/[?&]package_id=(\d+)/, 1] - raise "Couldn't get package id" unless package_id - - first_file = true - release_id = "" - - files.each do |filename| - basename = File.basename(filename) - file_ext = File.extname(filename) - file_data = File.open(filename, "rb") { |file| file.read } - - puts "Releasing #{basename}..." - - release_response = Net::HTTP.start("rubyforge.org", 80) do |http| - release_date = Time.now.strftime("%Y-%m-%d %H:%M") - type_map = { - ".zip" => "3000", - ".tgz" => "3110", - ".gz" => "3110", - ".gem" => "1400" - }; type_map.default = "9999" - type = type_map[file_ext] - boundary = "rubyqMY6QN9bp6e4kS21H4y0zxcvoor" - - query_hash = if first_file then - { - "group_id" => group_id, - "package_id" => package_id, - "release_name" => PKG_FILE_NAME, - "release_date" => release_date, - "type_id" => type, - "processor_id" => "8000", # Any - "release_notes" => "", - "release_changes" => "", - "preformatted" => "1", - "submit" => "1" - } - else - { - "group_id" => group_id, - "release_id" => release_id, - "package_id" => package_id, - "step2" => "1", - "type_id" => type, - "processor_id" => "8000", # Any - "submit" => "Add This File" - } - end - - query = "?" + query_hash.map do |(name, value)| - [name, URI.encode(value)].join("=") - end.join("&") - - data = [ - "--" + boundary, - "Content-Disposition: form-data; name=\"userfile\"; filename=\"#{basename}\"", - "Content-Type: application/octet-stream", - "Content-Transfer-Encoding: binary", - "", file_data, "" - ].join("\x0D\x0A") - - release_headers = headers.merge( - "Content-Type" => "multipart/form-data; boundary=#{boundary}" - ) - - target = first_file ? "/frs/admin/qrs.php" : "/frs/admin/editrelease.php" - http.post(target + query, data, release_headers) - end - - if first_file then - release_id = release_response.body[/release_id=(\d+)/, 1] - raise("Couldn't get release id") unless release_id - end - - first_file = false - end - end -end
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/init.rb b/vendor/plugins/acts_as_versioned/init.rb deleted file mode 100644 index 5937bbc7c..000000000 --- a/vendor/plugins/acts_as_versioned/init.rb +++ /dev/null @@ -1 +0,0 @@ -require 'acts_as_versioned'
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/lib/acts_as_versioned.rb b/vendor/plugins/acts_as_versioned/lib/acts_as_versioned.rb deleted file mode 100644 index 5299e0dc7..000000000 --- a/vendor/plugins/acts_as_versioned/lib/acts_as_versioned.rb +++ /dev/null @@ -1,490 +0,0 @@ -# Copyright (c) 2005 Rick Olson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -module ActiveRecord #:nodoc: - module Acts #:nodoc: - # Specify this act if you want to save a copy of the row in a versioned table. This assumes there is a - # versioned table ready and that your model has a version field. This works with optimistic locking if the lock_version - # column is present as well. - # - # The class for the versioned model is derived the first time it is seen. Therefore, if you change your database schema you have to restart - # your container for the changes to be reflected. In development mode this usually means restarting WEBrick. - # - # class Page < ActiveRecord::Base - # # assumes pages_versions table - # acts_as_versioned - # end - # - # Example: - # - # page = Page.create(:title => 'hello world!') - # page.version # => 1 - # - # page.title = 'hello world' - # page.save - # page.version # => 2 - # page.versions.size # => 2 - # - # page.revert_to(1) # using version number - # page.title # => 'hello world!' - # - # page.revert_to(page.versions.last) # using versioned instance - # page.title # => 'hello world' - # - # page.versions.earliest # efficient query to find the first version - # page.versions.latest # efficient query to find the most recently created version - # - # - # Simple Queries to page between versions - # - # page.versions.before(version) - # page.versions.after(version) - # - # Access the previous/next versions from the versioned model itself - # - # version = page.versions.latest - # version.previous # go back one version - # version.next # go forward one version - # - # See ActiveRecord::Acts::Versioned::ClassMethods#acts_as_versioned for configuration options - module Versioned - CALLBACKS = [:set_new_version, :save_version, :save_version?] - def self.included(base) # :nodoc: - base.extend ClassMethods - end - - module ClassMethods - # == Configuration options - # - # * <tt>class_name</tt> - versioned model class name (default: PageVersion in the above example) - # * <tt>table_name</tt> - versioned model table name (default: page_versions in the above example) - # * <tt>foreign_key</tt> - foreign key used to relate the versioned model to the original model (default: page_id in the above example) - # * <tt>inheritance_column</tt> - name of the column to save the model's inheritance_column value for STI. (default: versioned_type) - # * <tt>version_column</tt> - name of the column in the model that keeps the version number (default: version) - # * <tt>sequence_name</tt> - name of the custom sequence to be used by the versioned model. - # * <tt>limit</tt> - number of revisions to keep, defaults to unlimited - # * <tt>if</tt> - symbol of method to check before saving a new version. If this method returns false, a new version is not saved. - # For finer control, pass either a Proc or modify Model#version_condition_met? - # - # acts_as_versioned :if => Proc.new { |auction| !auction.expired? } - # - # or... - # - # class Auction - # def version_condition_met? # totally bypasses the <tt>:if</tt> option - # !expired? - # end - # end - # - # * <tt>if_changed</tt> - Simple way of specifying attributes that are required to be changed before saving a model. This takes - # either a symbol or array of symbols. WARNING - This will attempt to overwrite any attribute setters you may have. - # Use this instead if you want to write your own attribute setters (and ignore if_changed): - # - # def name=(new_name) - # write_changed_attribute :name, new_name - # end - # - # * <tt>extend</tt> - Lets you specify a module to be mixed in both the original and versioned models. You can also just pass a block - # to create an anonymous mixin: - # - # class Auction - # acts_as_versioned do - # def started? - # !started_at.nil? - # end - # end - # end - # - # or... - # - # module AuctionExtension - # def started? - # !started_at.nil? - # end - # end - # class Auction - # acts_as_versioned :extend => AuctionExtension - # end - # - # Example code: - # - # @auction = Auction.find(1) - # @auction.started? - # @auction.versions.first.started? - # - # == Database Schema - # - # The model that you're versioning needs to have a 'version' attribute. The model is versioned - # into a table called #{model}_versions where the model name is singlular. The _versions table should - # contain all the fields you want versioned, the same version column, and a #{model}_id foreign key field. - # - # A lock_version field is also accepted if your model uses Optimistic Locking. If your table uses Single Table inheritance, - # then that field is reflected in the versioned model as 'versioned_type' by default. - # - # Acts_as_versioned comes prepared with the ActiveRecord::Acts::Versioned::ActMethods::ClassMethods#create_versioned_table - # method, perfect for a migration. It will also create the version column if the main model does not already have it. - # - # class AddVersions < ActiveRecord::Migration - # def self.up - # # create_versioned_table takes the same options hash - # # that create_table does - # Post.create_versioned_table - # end - # - # def self.down - # Post.drop_versioned_table - # end - # end - # - # == Changing What Fields Are Versioned - # - # By default, acts_as_versioned will version all but these fields: - # - # [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column] - # - # You can add or change those by modifying #non_versioned_columns. Note that this takes strings and not symbols. - # - # class Post < ActiveRecord::Base - # acts_as_versioned - # self.non_versioned_columns << 'comments_count' - # end - # - def acts_as_versioned(options = {}, &extension) - # don't allow multiple calls - return if self.included_modules.include?(ActiveRecord::Acts::Versioned::ActMethods) - - send :include, ActiveRecord::Acts::Versioned::ActMethods - - cattr_accessor :versioned_class_name, :versioned_foreign_key, :versioned_table_name, :versioned_inheritance_column, - :version_column, :max_version_limit, :track_altered_attributes, :version_condition, :version_sequence_name, :non_versioned_columns, - :version_association_options, :version_if_changed - - self.versioned_class_name = options[:class_name] || "Version" - self.versioned_foreign_key = options[:foreign_key] || self.to_s.foreign_key - self.versioned_table_name = options[:table_name] || "#{table_name_prefix}#{base_class.name.demodulize.underscore}_versions#{table_name_suffix}" - self.versioned_inheritance_column = options[:inheritance_column] || "versioned_#{inheritance_column}" - self.version_column = options[:version_column] || 'version' - self.version_sequence_name = options[:sequence_name] - self.max_version_limit = options[:limit].to_i - self.version_condition = options[:if] || true - self.non_versioned_columns = [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column, 'created_at', 'created_on'] - self.version_association_options = { - :class_name => "#{self.to_s}::#{versioned_class_name}", - :foreign_key => versioned_foreign_key, - :dependent => :delete_all - }.merge(options[:association_options] || {}) - - if block_given? - extension_module_name = "#{versioned_class_name}Extension" - silence_warnings do - self.const_set(extension_module_name, Module.new(&extension)) - end - - options[:extend] = self.const_get(extension_module_name) - end - - class_eval do - has_many :versions, version_association_options do - # finds earliest version of this record - def earliest - @earliest ||= find(:first, :order => 'version') - end - - # find latest version of this record - def latest - @latest ||= find(:first, :order => 'version desc') - end - end - before_save :set_new_version - after_save :save_version - after_save :clear_old_versions - - unless options[:if_changed].nil? - self.track_altered_attributes = true - options[:if_changed] = [options[:if_changed]] unless options[:if_changed].is_a?(Array) - self.version_if_changed = options[:if_changed] - end - - include options[:extend] if options[:extend].is_a?(Module) - end - - # create the dynamic versioned model - const_set(versioned_class_name, Class.new(ActiveRecord::Base)).class_eval do - def self.reloadable? ; false ; end - # find first version before the given version - def self.before(version) - find :first, :order => 'version desc', - :conditions => ["#{original_class.versioned_foreign_key} = ? and version < ?", version.send(original_class.versioned_foreign_key), version.version] - end - - # find first version after the given version. - def self.after(version) - find :first, :order => 'version', - :conditions => ["#{original_class.versioned_foreign_key} = ? and version > ?", version.send(original_class.versioned_foreign_key), version.version] - end - - def previous - self.class.before(self) - end - - def next - self.class.after(self) - end - - def versions_count - page.version - end - end - - versioned_class.cattr_accessor :original_class - versioned_class.original_class = self - versioned_class.set_table_name versioned_table_name - versioned_class.belongs_to self.to_s.demodulize.underscore.to_sym, - :class_name => "::#{self.to_s}", - :foreign_key => versioned_foreign_key - versioned_class.send :include, options[:extend] if options[:extend].is_a?(Module) - versioned_class.set_sequence_name version_sequence_name if version_sequence_name - end - end - - module ActMethods - def self.included(base) # :nodoc: - base.extend ClassMethods - end - - # Saves a version of the model in the versioned table. This is called in the after_save callback by default - def save_version - if @saving_version - @saving_version = nil - rev = self.class.versioned_class.new - clone_versioned_model(self, rev) - rev.version = send(self.class.version_column) - rev.send("#{self.class.versioned_foreign_key}=", id) - rev.save - end - end - - # Clears old revisions if a limit is set with the :limit option in <tt>acts_as_versioned</tt>. - # Override this method to set your own criteria for clearing old versions. - def clear_old_versions - return if self.class.max_version_limit == 0 - excess_baggage = send(self.class.version_column).to_i - self.class.max_version_limit - if excess_baggage > 0 - self.class.versioned_class.delete_all ["version <= ? and #{self.class.versioned_foreign_key} = ?", excess_baggage, id] - end - end - - # Reverts a model to a given version. Takes either a version number or an instance of the versioned model - def revert_to(version) - if version.is_a?(self.class.versioned_class) - return false unless version.send(self.class.versioned_foreign_key) == id and !version.new_record? - else - return false unless version = versions.find_by_version(version) - end - self.clone_versioned_model(version, self) - send("#{self.class.version_column}=", version.version) - true - end - - # Reverts a model to a given version and saves the model. - # Takes either a version number or an instance of the versioned model - def revert_to!(version) - revert_to(version) ? save_without_revision : false - end - - # Temporarily turns off Optimistic Locking while saving. Used when reverting so that a new version is not created. - def save_without_revision - save_without_revision! - true - rescue - false - end - - def save_without_revision! - without_locking do - without_revision do - save! - end - end - end - - def altered? - track_altered_attributes ? (version_if_changed.map(&:to_s) - changed).length < version_if_changed.length : changed? - end - - # Clones a model. Used when saving a new version or reverting a model's version. - def clone_versioned_model(orig_model, new_model) - self.class.versioned_columns.each do |col| - new_model.send("#{col.name}=", orig_model.send(col.name)) if orig_model.has_attribute?(col.name) - end - - if orig_model.is_a?(self.class.versioned_class) - new_model[new_model.class.inheritance_column] = orig_model[self.class.versioned_inheritance_column] - elsif new_model.is_a?(self.class.versioned_class) - new_model[self.class.versioned_inheritance_column] = orig_model[orig_model.class.inheritance_column] - end - end - - # Checks whether a new version shall be saved or not. Calls <tt>version_condition_met?</tt> and <tt>changed?</tt>. - def save_version? - version_condition_met? && altered? - end - - # Checks condition set in the :if option to check whether a revision should be created or not. Override this for - # custom version condition checking. - def version_condition_met? - case - when version_condition.is_a?(Symbol) - send(version_condition) - when version_condition.respond_to?(:call) && (version_condition.arity == 1 || version_condition.arity == -1) - version_condition.call(self) - else - version_condition - end - end - - # Executes the block with the versioning callbacks disabled. - # - # @foo.without_revision do - # @foo.save - # end - # - def without_revision(&block) - self.class.without_revision(&block) - end - - # Turns off optimistic locking for the duration of the block - # - # @foo.without_locking do - # @foo.save - # end - # - def without_locking(&block) - self.class.without_locking(&block) - end - - def empty_callback() end #:nodoc: - - protected - # sets the new version before saving, unless you're using optimistic locking. In that case, let it take care of the version. - def set_new_version - @saving_version = new_record? || save_version? - self.send("#{self.class.version_column}=", next_version) if new_record? || (!locking_enabled? && save_version?) - end - - # Gets the next available version for the current record, or 1 for a new record - def next_version - (new_record? ? 0 : versions.calculate(:max, :version).to_i) + 1 - end - - module ClassMethods - # Returns an array of columns that are versioned. See non_versioned_columns - def versioned_columns - @versioned_columns ||= columns.select { |c| !non_versioned_columns.include?(c.name) } - end - - # Returns an instance of the dynamic versioned model - def versioned_class - const_get versioned_class_name - end - - # Rake migration task to create the versioned table using options passed to acts_as_versioned - def create_versioned_table(create_table_options = {}) - # create version column in main table if it does not exist - if !self.content_columns.find { |c| %w(version lock_version).include? c.name } - self.connection.add_column table_name, :version, :integer - end - - self.connection.create_table(versioned_table_name, create_table_options) do |t| - t.column versioned_foreign_key, :integer - t.column :version, :integer - end - - updated_col = nil - self.versioned_columns.each do |col| - updated_col = col if !updated_col && %(updated_at updated_on).include?(col.name) - self.connection.add_column versioned_table_name, col.name, col.type, - :limit => col.limit, - :default => col.default, - :scale => col.scale, - :precision => col.precision - end - - if type_col = self.columns_hash[inheritance_column] - self.connection.add_column versioned_table_name, versioned_inheritance_column, type_col.type, - :limit => type_col.limit, - :default => type_col.default, - :scale => type_col.scale, - :precision => type_col.precision - end - - if updated_col.nil? - self.connection.add_column versioned_table_name, :updated_at, :timestamp - end - end - - # Rake migration task to drop the versioned table - def drop_versioned_table - self.connection.drop_table versioned_table_name - end - - # Executes the block with the versioning callbacks disabled. - # - # Foo.without_revision do - # @foo.save - # end - # - def without_revision(&block) - class_eval do - CALLBACKS.each do |attr_name| - alias_method "orig_#{attr_name}".to_sym, attr_name - alias_method attr_name, :empty_callback - end - end - block.call - ensure - class_eval do - CALLBACKS.each do |attr_name| - alias_method attr_name, "orig_#{attr_name}".to_sym - end - end - end - - # Turns off optimistic locking for the duration of the block - # - # Foo.without_locking do - # @foo.save - # end - # - def without_locking(&block) - current = ActiveRecord::Base.lock_optimistically - ActiveRecord::Base.lock_optimistically = false if current - result = block.call - ActiveRecord::Base.lock_optimistically = true if current - result - end - end - end - end - end -end - -ActiveRecord::Base.send :include, ActiveRecord::Acts::Versioned
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/abstract_unit.rb b/vendor/plugins/acts_as_versioned/test/abstract_unit.rb deleted file mode 100644 index 269667ad0..000000000 --- a/vendor/plugins/acts_as_versioned/test/abstract_unit.rb +++ /dev/null @@ -1,48 +0,0 @@ -$:.unshift(File.dirname(__FILE__) + '/../../../rails/activesupport/lib') -$:.unshift(File.dirname(__FILE__) + '/../../../rails/activerecord/lib') -$:.unshift(File.dirname(__FILE__) + '/../lib') -require 'test/unit' -begin - require 'active_support' - require 'active_record' - require 'active_record/fixtures' -rescue LoadError - require 'rubygems' - retry -end - -begin - require 'ruby-debug' - Debugger.start -rescue LoadError -end - -require 'acts_as_versioned' - -config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) -ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") -ActiveRecord::Base.configurations = {'test' => config[ENV['DB'] || 'sqlite3']} -ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test']) - -load(File.dirname(__FILE__) + "/schema.rb") - -# set up custom sequence on widget_versions for DBs that support sequences -if ENV['DB'] == 'postgresql' - ActiveRecord::Base.connection.execute "DROP SEQUENCE widgets_seq;" rescue nil - ActiveRecord::Base.connection.remove_column :widget_versions, :id - ActiveRecord::Base.connection.execute "CREATE SEQUENCE widgets_seq START 101;" - ActiveRecord::Base.connection.execute "ALTER TABLE widget_versions ADD COLUMN id INTEGER PRIMARY KEY DEFAULT nextval('widgets_seq');" -end - -Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures/" -$:.unshift(Test::Unit::TestCase.fixture_path) - -class Test::Unit::TestCase #:nodoc: - # Turn off transactional fixtures if you're working with MyISAM tables in MySQL - self.use_transactional_fixtures = true - - # Instantiated fixtures are slow, but give you @david where you otherwise would need people(:david) - self.use_instantiated_fixtures = false - - # Add more helper methods to be used by all tests here... -end
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/database.yml b/vendor/plugins/acts_as_versioned/test/database.yml deleted file mode 100644 index 506e6bd37..000000000 --- a/vendor/plugins/acts_as_versioned/test/database.yml +++ /dev/null @@ -1,18 +0,0 @@ -sqlite: - :adapter: sqlite - :dbfile: acts_as_versioned_plugin.sqlite.db -sqlite3: - :adapter: sqlite3 - :dbfile: acts_as_versioned_plugin.sqlite3.db -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: acts_as_versioned_plugin_test - :min_messages: ERROR -mysql: - :adapter: mysql - :host: localhost - :username: rails - :password: - :database: acts_as_versioned_plugin_test
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/authors.yml b/vendor/plugins/acts_as_versioned/test/fixtures/authors.yml deleted file mode 100644 index bd7a5aed6..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/authors.yml +++ /dev/null @@ -1,6 +0,0 @@ -caged: - id: 1 - name: caged -mly: - id: 2 - name: mly
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/landmark.rb b/vendor/plugins/acts_as_versioned/test/fixtures/landmark.rb deleted file mode 100644 index cb9b93057..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/landmark.rb +++ /dev/null @@ -1,3 +0,0 @@ -class Landmark < ActiveRecord::Base - acts_as_versioned :if_changed => [ :name, :longitude, :latitude ] -end diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/landmark_versions.yml b/vendor/plugins/acts_as_versioned/test/fixtures/landmark_versions.yml deleted file mode 100644 index 2dbd54ed2..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/landmark_versions.yml +++ /dev/null @@ -1,7 +0,0 @@ -washington: - id: 1 - landmark_id: 1 - version: 1 - name: Washington, D.C. - latitude: 38.895 - longitude: -77.036667 diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/landmarks.yml b/vendor/plugins/acts_as_versioned/test/fixtures/landmarks.yml deleted file mode 100644 index cf0639006..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/landmarks.yml +++ /dev/null @@ -1,7 +0,0 @@ -washington: - id: 1 - name: Washington, D.C. - latitude: 38.895 - longitude: -77.036667 - doesnt_trigger_version: This is not important - version: 1 diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/locked_pages.yml b/vendor/plugins/acts_as_versioned/test/fixtures/locked_pages.yml deleted file mode 100644 index 318e776cb..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/locked_pages.yml +++ /dev/null @@ -1,10 +0,0 @@ -welcome: - id: 1 - title: Welcome to the weblog - lock_version: 24 - type: LockedPage -thinking: - id: 2 - title: So I was thinking - lock_version: 24 - type: SpecialLockedPage diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/locked_pages_revisions.yml b/vendor/plugins/acts_as_versioned/test/fixtures/locked_pages_revisions.yml deleted file mode 100644 index 5c978e629..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/locked_pages_revisions.yml +++ /dev/null @@ -1,27 +0,0 @@ -welcome_1: - id: 1 - page_id: 1 - title: Welcome to the weblg - version: 23 - version_type: LockedPage - -welcome_2: - id: 2 - page_id: 1 - title: Welcome to the weblog - version: 24 - version_type: LockedPage - -thinking_1: - id: 3 - page_id: 2 - title: So I was thinking!!! - version: 23 - version_type: SpecialLockedPage - -thinking_2: - id: 4 - page_id: 2 - title: So I was thinking - version: 24 - version_type: SpecialLockedPage diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/migrations/1_add_versioned_tables.rb b/vendor/plugins/acts_as_versioned/test/fixtures/migrations/1_add_versioned_tables.rb deleted file mode 100644 index 5007b16ad..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/migrations/1_add_versioned_tables.rb +++ /dev/null @@ -1,15 +0,0 @@ -class AddVersionedTables < ActiveRecord::Migration - def self.up - create_table("things") do |t| - t.column :title, :text - t.column :price, :decimal, :precision => 7, :scale => 2 - t.column :type, :string - end - Thing.create_versioned_table - end - - def self.down - Thing.drop_versioned_table - drop_table "things" rescue nil - end -end
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/page.rb b/vendor/plugins/acts_as_versioned/test/fixtures/page.rb deleted file mode 100644 index f133e351a..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/page.rb +++ /dev/null @@ -1,43 +0,0 @@ -class Page < ActiveRecord::Base - belongs_to :author - has_many :authors, :through => :versions, :order => 'name' - belongs_to :revisor, :class_name => 'Author' - has_many :revisors, :class_name => 'Author', :through => :versions, :order => 'name' - acts_as_versioned :if => :feeling_good? do - def self.included(base) - base.cattr_accessor :feeling_good - base.feeling_good = true - base.belongs_to :author - base.belongs_to :revisor, :class_name => 'Author' - end - - def feeling_good? - @@feeling_good == true - end - end -end - -module LockedPageExtension - def hello_world - 'hello_world' - end -end - -class LockedPage < ActiveRecord::Base - acts_as_versioned \ - :inheritance_column => :version_type, - :foreign_key => :page_id, - :table_name => :locked_pages_revisions, - :class_name => 'LockedPageRevision', - :version_column => :lock_version, - :limit => 2, - :if_changed => :title, - :extend => LockedPageExtension -end - -class SpecialLockedPage < LockedPage -end - -class Author < ActiveRecord::Base - has_many :pages -end
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/page_versions.yml b/vendor/plugins/acts_as_versioned/test/fixtures/page_versions.yml deleted file mode 100644 index ef565fa4f..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/page_versions.yml +++ /dev/null @@ -1,16 +0,0 @@ -welcome_2: - id: 1 - page_id: 1 - title: Welcome to the weblog - body: Such a lovely day - version: 24 - author_id: 1 - revisor_id: 1 -welcome_1: - id: 2 - page_id: 1 - title: Welcome to the weblg - body: Such a lovely day - version: 23 - author_id: 2 - revisor_id: 2 diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/pages.yml b/vendor/plugins/acts_as_versioned/test/fixtures/pages.yml deleted file mode 100644 index 9f4ab546a..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/pages.yml +++ /dev/null @@ -1,8 +0,0 @@ -welcome: - id: 1 - title: Welcome to the weblog - body: Such a lovely day - version: 24 - author_id: 1 - revisor_id: 1 - created_on: "2008-01-01 00:00:00"
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/fixtures/widget.rb b/vendor/plugins/acts_as_versioned/test/fixtures/widget.rb deleted file mode 100644 index 086ac2b40..000000000 --- a/vendor/plugins/acts_as_versioned/test/fixtures/widget.rb +++ /dev/null @@ -1,6 +0,0 @@ -class Widget < ActiveRecord::Base - acts_as_versioned :sequence_name => 'widgets_seq', :association_options => { - :dependent => :nullify, :order => 'version desc' - } - non_versioned_columns << 'foo' -end
\ No newline at end of file diff --git a/vendor/plugins/acts_as_versioned/test/migration_test.rb b/vendor/plugins/acts_as_versioned/test/migration_test.rb deleted file mode 100644 index 47a7537ce..000000000 --- a/vendor/plugins/acts_as_versioned/test/migration_test.rb +++ /dev/null @@ -1,46 +0,0 @@ -require File.join(File.dirname(__FILE__), 'abstract_unit') - -if ActiveRecord::Base.connection.supports_migrations? - class Thing < ActiveRecord::Base - attr_accessor :version - acts_as_versioned - end - - class MigrationTest < Test::Unit::TestCase - self.use_transactional_fixtures = false - def teardown
- if ActiveRecord::Base.connection.respond_to?(:initialize_schema_information)
- ActiveRecord::Base.connection.initialize_schema_information
- ActiveRecord::Base.connection.update "UPDATE schema_info SET version = 0"
- else
- ActiveRecord::Base.connection.initialize_schema_migrations_table
- ActiveRecord::Base.connection.assume_migrated_upto_version(0)
- end
- - Thing.connection.drop_table "things" rescue nil - Thing.connection.drop_table "thing_versions" rescue nil - Thing.reset_column_information - end - - def test_versioned_migration - assert_raises(ActiveRecord::StatementInvalid) { Thing.create :title => 'blah blah' } - # take 'er up - ActiveRecord::Migrator.up(File.dirname(__FILE__) + '/fixtures/migrations/') - t = Thing.create :title => 'blah blah', :price => 123.45, :type => 'Thing' - assert_equal 1, t.versions.size - - # check that the price column has remembered its value correctly - assert_equal t.price, t.versions.first.price - assert_equal t.title, t.versions.first.title - assert_equal t[:type], t.versions.first[:type] - - # make sure that the precision of the price column has been preserved - assert_equal 7, Thing::Version.columns.find{|c| c.name == "price"}.precision - assert_equal 2, Thing::Version.columns.find{|c| c.name == "price"}.scale - - # now lets take 'er back down - ActiveRecord::Migrator.down(File.dirname(__FILE__) + '/fixtures/migrations/') - assert_raises(ActiveRecord::StatementInvalid) { Thing.create :title => 'blah blah' } - end - end -end diff --git a/vendor/plugins/acts_as_versioned/test/schema.rb b/vendor/plugins/acts_as_versioned/test/schema.rb deleted file mode 100644 index 4e7e96319..000000000 --- a/vendor/plugins/acts_as_versioned/test/schema.rb +++ /dev/null @@ -1,80 +0,0 @@ -ActiveRecord::Schema.define(:version => 0) do - create_table :pages, :force => true do |t| - t.column :version, :integer - t.column :title, :string, :limit => 255 - t.column :body, :text - t.column :created_on, :datetime - t.column :updated_on, :datetime - t.column :author_id, :integer - t.column :revisor_id, :integer - end - - create_table :page_versions, :force => true do |t| - t.column :page_id, :integer - t.column :version, :integer - t.column :title, :string, :limit => 255 - t.column :body, :text - t.column :created_on, :datetime - t.column :updated_on, :datetime - t.column :author_id, :integer - t.column :revisor_id, :integer - end - - add_index :page_versions, [:page_id, :version], :unique => true - - create_table :authors, :force => true do |t| - t.column :page_id, :integer - t.column :name, :string - end - - create_table :locked_pages, :force => true do |t| - t.column :lock_version, :integer - t.column :title, :string, :limit => 255 - t.column :type, :string, :limit => 255 - end - - create_table :locked_pages_revisions, :force => true do |t| - t.column :page_id, :integer - t.column :version, :integer - t.column :title, :string, :limit => 255 - t.column :version_type, :string, :limit => 255 - t.column :updated_at, :datetime - end - - add_index :locked_pages_revisions, [:page_id, :version], :unique => true - - create_table :widgets, :force => true do |t| - t.column :name, :string, :limit => 50 - t.column :foo, :string - t.column :version, :integer - t.column :updated_at, :datetime - end - - create_table :widget_versions, :force => true do |t| - t.column :widget_id, :integer - t.column :name, :string, :limit => 50 - t.column :version, :integer - t.column :updated_at, :datetime - end - - add_index :widget_versions, [:widget_id, :version], :unique => true - - create_table :landmarks, :force => true do |t| - t.column :name, :string - t.column :latitude, :float - t.column :longitude, :float - t.column :doesnt_trigger_version,:string - t.column :version, :integer - end - - create_table :landmark_versions, :force => true do |t| - t.column :landmark_id, :integer - t.column :name, :string - t.column :latitude, :float - t.column :longitude, :float - t.column :doesnt_trigger_version,:string - t.column :version, :integer - end - - add_index :landmark_versions, [:landmark_id, :version], :unique => true -end diff --git a/vendor/plugins/acts_as_versioned/test/versioned_test.rb b/vendor/plugins/acts_as_versioned/test/versioned_test.rb deleted file mode 100644 index 6ab9e739c..000000000 --- a/vendor/plugins/acts_as_versioned/test/versioned_test.rb +++ /dev/null @@ -1,352 +0,0 @@ -require File.join(File.dirname(__FILE__), 'abstract_unit') -require File.join(File.dirname(__FILE__), 'fixtures/page') -require File.join(File.dirname(__FILE__), 'fixtures/widget') - -class VersionedTest < Test::Unit::TestCase - fixtures :pages, :page_versions, :locked_pages, :locked_pages_revisions, :authors, :landmarks, :landmark_versions - set_fixture_class :page_versions => Page::Version - - def test_saves_versioned_copy - p = Page.create! :title => 'first title', :body => 'first body' - assert !p.new_record? - assert_equal 1, p.versions.size - assert_equal 1, p.version - assert_instance_of Page.versioned_class, p.versions.first - end - - def test_version_has_unique_created_at - p = pages(:welcome) - p.title = 'update me' - p.save! - assert_not_equal p.created_on, p.versions.latest.created_on - end - - def test_saves_without_revision - p = pages(:welcome) - old_versions = p.versions.count - - p.save_without_revision - - p.without_revision do - p.update_attributes :title => 'changed' - end - - assert_equal old_versions, p.versions.count - end - - def test_rollback_with_version_number - p = pages(:welcome) - assert_equal 24, p.version - assert_equal 'Welcome to the weblog', p.title - - assert p.revert_to!(23), "Couldn't revert to 23" - assert_equal 23, p.version - assert_equal 'Welcome to the weblg', p.title - end - - def test_versioned_class_name - assert_equal 'Version', Page.versioned_class_name - assert_equal 'LockedPageRevision', LockedPage.versioned_class_name - end - - def test_versioned_class - assert_equal Page::Version, Page.versioned_class - assert_equal LockedPage::LockedPageRevision, LockedPage.versioned_class - end - - def test_special_methods - assert_nothing_raised { pages(:welcome).feeling_good? } - assert_nothing_raised { pages(:welcome).versions.first.feeling_good? } - assert_nothing_raised { locked_pages(:welcome).hello_world } - assert_nothing_raised { locked_pages(:welcome).versions.first.hello_world } - end - - def test_rollback_with_version_class - p = pages(:welcome) - assert_equal 24, p.version - assert_equal 'Welcome to the weblog', p.title - - assert p.revert_to!(p.versions.find_by_version(23)), "Couldn't revert to 23" - assert_equal 23, p.version - assert_equal 'Welcome to the weblg', p.title - end - - def test_rollback_fails_with_invalid_revision - p = locked_pages(:welcome) - assert !p.revert_to!(locked_pages(:thinking)) - end - - def test_saves_versioned_copy_with_options - p = LockedPage.create! :title => 'first title' - assert !p.new_record? - assert_equal 1, p.versions.size - assert_instance_of LockedPage.versioned_class, p.versions.first - end - - def test_rollback_with_version_number_with_options - p = locked_pages(:welcome) - assert_equal 'Welcome to the weblog', p.title - assert_equal 'LockedPage', p.versions.first.version_type - - assert p.revert_to!(p.versions.first.version), "Couldn't revert to 23" - assert_equal 'Welcome to the weblg', p.title - assert_equal 'LockedPage', p.versions.first.version_type - end - - def test_rollback_with_version_class_with_options - p = locked_pages(:welcome) - assert_equal 'Welcome to the weblog', p.title - assert_equal 'LockedPage', p.versions.first.version_type - - assert p.revert_to!(p.versions.first), "Couldn't revert to 1" - assert_equal 'Welcome to the weblg', p.title - assert_equal 'LockedPage', p.versions.first.version_type - end - - def test_saves_versioned_copy_with_sti - p = SpecialLockedPage.create! :title => 'first title' - assert !p.new_record? - assert_equal 1, p.versions.size - assert_instance_of LockedPage.versioned_class, p.versions.first - assert_equal 'SpecialLockedPage', p.versions.first.version_type - end - - def test_rollback_with_version_number_with_sti - p = locked_pages(:thinking) - assert_equal 'So I was thinking', p.title - - assert p.revert_to!(p.versions.first.version), "Couldn't revert to 1" - assert_equal 'So I was thinking!!!', p.title - assert_equal 'SpecialLockedPage', p.versions.first.version_type - end - - def test_lock_version_works_with_versioning - p = locked_pages(:thinking) - p2 = LockedPage.find(p.id) - - p.title = 'fresh title' - p.save - assert_equal 2, p.versions.size # limit! - - assert_raises(ActiveRecord::StaleObjectError) do - p2.title = 'stale title' - p2.save - end - end - - def test_version_if_condition - p = Page.create! :title => "title" - assert_equal 1, p.version - - Page.feeling_good = false - p.save - assert_equal 1, p.version - Page.feeling_good = true - end - - def test_version_if_condition2 - # set new if condition - Page.class_eval do - def new_feeling_good() title[0..0] == 'a'; end - alias_method :old_feeling_good, :feeling_good? - alias_method :feeling_good?, :new_feeling_good - end - - p = Page.create! :title => "title" - assert_equal 1, p.version # version does not increment - assert_equal 1, p.versions.count - - p.update_attributes(:title => 'new title') - assert_equal 1, p.version # version does not increment - assert_equal 1, p.versions.count - - p.update_attributes(:title => 'a title') - assert_equal 2, p.version - assert_equal 2, p.versions.count - - # reset original if condition - Page.class_eval { alias_method :feeling_good?, :old_feeling_good } - end - - def test_version_if_condition_with_block - # set new if condition - old_condition = Page.version_condition - Page.version_condition = Proc.new { |page| page.title[0..0] == 'b' } - - p = Page.create! :title => "title" - assert_equal 1, p.version # version does not increment - assert_equal 1, p.versions.count - - p.update_attributes(:title => 'a title') - assert_equal 1, p.version # version does not increment - assert_equal 1, p.versions.count - - p.update_attributes(:title => 'b title') - assert_equal 2, p.version - assert_equal 2, p.versions.count - - # reset original if condition - Page.version_condition = old_condition - end - - def test_version_no_limit - p = Page.create! :title => "title", :body => 'first body' - p.save - p.save - 5.times do |i| - p.title = "title#{i}" - p.save - assert_equal "title#{i}", p.title - assert_equal (i+2), p.version - end - end - - def test_version_max_limit - p = LockedPage.create! :title => "title" - p.update_attributes(:title => "title1") - p.update_attributes(:title => "title2") - 5.times do |i| - p.title = "title#{i}" - p.save - assert_equal "title#{i}", p.title - assert_equal (i+4), p.lock_version - assert p.versions(true).size <= 2, "locked version can only store 2 versions" - end - end - - def test_track_altered_attributes_default_value - assert !Page.track_altered_attributes - assert LockedPage.track_altered_attributes - assert SpecialLockedPage.track_altered_attributes - end - - def test_track_altered_attributes - p = LockedPage.create! :title => "title" - assert_equal 1, p.lock_version - assert_equal 1, p.versions(true).size - - p.title = 'title' - assert !p.save_version? - p.save - assert_equal 2, p.lock_version # still increments version because of optimistic locking - assert_equal 1, p.versions(true).size - - p.title = 'updated title' - assert p.save_version? - p.save - assert_equal 3, p.lock_version - assert_equal 1, p.versions(true).size # version 1 deleted - - p.title = 'updated title!' - assert p.save_version? - p.save - assert_equal 4, p.lock_version - assert_equal 2, p.versions(true).size # version 1 deleted - end - - def test_find_versions - assert_equal 1, locked_pages(:welcome).versions.find(:all, :conditions => ['title LIKE ?', '%weblog%']).size - end - - def test_find_version - assert_equal page_versions(:welcome_1), pages(:welcome).versions.find_by_version(23) - end - - def test_with_sequence - assert_equal 'widgets_seq', Widget.versioned_class.sequence_name - 3.times { Widget.create! :name => 'new widget' } - assert_equal 3, Widget.count - assert_equal 3, Widget.versioned_class.count - end - - def test_has_many_through - assert_equal [authors(:caged), authors(:mly)], pages(:welcome).authors - end - - def test_has_many_through_with_custom_association - assert_equal [authors(:caged), authors(:mly)], pages(:welcome).revisors - end - - def test_referential_integrity - pages(:welcome).destroy - assert_equal 0, Page.count - assert_equal 0, Page::Version.count - end - - def test_association_options - association = Page.reflect_on_association(:versions) - options = association.options - assert_equal :delete_all, options[:dependent] - - association = Widget.reflect_on_association(:versions) - options = association.options - assert_equal :nullify, options[:dependent] - assert_equal 'version desc', options[:order] - assert_equal 'widget_id', options[:foreign_key] - - widget = Widget.create! :name => 'new widget' - assert_equal 1, Widget.count - assert_equal 1, Widget.versioned_class.count - widget.destroy - assert_equal 0, Widget.count - assert_equal 1, Widget.versioned_class.count - end - - def test_versioned_records_should_belong_to_parent - page = pages(:welcome) - page_version = page.versions.last - assert_equal page, page_version.page - end - - def test_unaltered_attributes - landmarks(:washington).attributes = landmarks(:washington).attributes.except("id") - assert !landmarks(:washington).changed? - end - - def test_unchanged_string_attributes - landmarks(:washington).attributes = landmarks(:washington).attributes.except("id").inject({}) { |params, (key, value)| params.update(key => value.to_s) } - assert !landmarks(:washington).changed? - end - - def test_should_find_earliest_version - assert_equal page_versions(:welcome_1), pages(:welcome).versions.earliest - end - - def test_should_find_latest_version - assert_equal page_versions(:welcome_2), pages(:welcome).versions.latest - end - - def test_should_find_previous_version - assert_equal page_versions(:welcome_1), page_versions(:welcome_2).previous - assert_equal page_versions(:welcome_1), pages(:welcome).versions.before(page_versions(:welcome_2)) - end - - def test_should_find_next_version - assert_equal page_versions(:welcome_2), page_versions(:welcome_1).next - assert_equal page_versions(:welcome_2), pages(:welcome).versions.after(page_versions(:welcome_1)) - end - - def test_should_find_version_count - assert_equal 2, pages(:welcome).versions.size - end - - def test_if_changed_creates_version_if_a_listed_column_is_changed - landmarks(:washington).name = "Washington" - assert landmarks(:washington).changed? - assert landmarks(:washington).altered? - end - - def test_if_changed_creates_version_if_all_listed_columns_are_changed - landmarks(:washington).name = "Washington" - landmarks(:washington).latitude = 1.0 - landmarks(:washington).longitude = 1.0 - assert landmarks(:washington).changed? - assert landmarks(:washington).altered? - end - - def test_if_changed_does_not_create_new_version_if_unlisted_column_is_changed - landmarks(:washington).doesnt_trigger_version = "This should not trigger version" - assert landmarks(:washington).changed? - assert !landmarks(:washington).altered? - end -end
\ No newline at end of file diff --git a/vendor/plugins/acts_as_xapian/.cvsignore b/vendor/plugins/acts_as_xapian/.cvsignore deleted file mode 100644 index 6379fb207..000000000 --- a/vendor/plugins/acts_as_xapian/.cvsignore +++ /dev/null @@ -1,2 +0,0 @@ -xapiandbs -.git diff --git a/vendor/plugins/acts_as_xapian/.gitignore b/vendor/plugins/acts_as_xapian/.gitignore deleted file mode 100644 index 60e95666f..000000000 --- a/vendor/plugins/acts_as_xapian/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -/xapiandbs -CVS -*.swp diff --git a/vendor/plugins/acts_as_xapian/LICENSE.txt b/vendor/plugins/acts_as_xapian/LICENSE.txt deleted file mode 100644 index 72d93c4be..000000000 --- a/vendor/plugins/acts_as_xapian/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -acts_as_xapian is released under the MIT License. - -Copyright (c) 2008 UK Citizens Online Democracy. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of the acts_as_xapian software and associated documentation files (the -"Software"), to deal in the Software without restriction, including without -limitation the rights to use, copy, modify, merge, publish, distribute, -sublicense, and/or sell copies of the Software, and to permit persons to whom -the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/vendor/plugins/acts_as_xapian/README.txt b/vendor/plugins/acts_as_xapian/README.txt deleted file mode 100644 index 62cef2f24..000000000 --- a/vendor/plugins/acts_as_xapian/README.txt +++ /dev/null @@ -1,276 +0,0 @@ -The official page for acts_as_xapian is now the Google Groups page. - -http://groups.google.com/group/acts_as_xapian - -frabcus's github repository is no longer the official repository, -find the official one from the Google Groups page. - ------------------------------------------------------------------------- - -Do patch this file if there is documentation missing / wrong. It's called -README.txt and is in git, using Textile formatting. The wiki page is just -copied from the README.txt file. - -Contents -======== - -* a. Introduction to acts_as_xapian -* b. Installation -* c. Comparison to acts_as_solr (as on 24 April 2008) -* d. Documentation - indexing -* e. Documentation - querying -* f. Configuration -* g. Performance -* h. Support - - -a. Introduction to acts_as_xapian -================================= - -"Xapian":http://www.xapian.org is a full text search engine library which has -Ruby bindings. acts_as_xapian adds support for it to Rails. It is an -alternative to acts_as_solr, acts_as_ferret, Ultrasphinx, acts_as_indexed, -acts_as_searchable or acts_as_tsearch. - -acts_as_xapian is deployed in production on these websites. -* "WhatDoTheyKnow":http://www.whatdotheyknow.com -* "MindBites":http://www.mindbites.com - -The section "c. Comparison to acts_as_solr" below will give you an idea of -acts_as_xapian's features. - -acts_as_xapian was started by Francis Irving in May 2008 for search and email -alerts in WhatDoTheyKnow, and so was supported by "mySociety":http://www.mysociety.org -and initially paid for by the "JRSST Charitable Trust":http://www.jrrt.org.uk/jrsstct.htm - - -b. Installation -=============== - -Retrieve the plugin directly from the git version control system by running -this command within your Rails app. - - git clone git://github.com/frabcus/acts_as_xapian.git vendor/plugins/acts_as_xapian - -Xapian 1.0.5 and associated Ruby bindings are also required. - -Debian or Ubuntu - install the packages libxapian15 and libxapian-ruby1.8. - -Mac OSX - follow the instructions for installing from source on -the "Installing Xapian":http://xapian.org/docs/install.html page - you need the -Xapian library and bindings (you don't need Omega). - -There is no Ruby Gem for Xapian, it would be great if you could make one! - - -c. Comparison to acts_as_solr (as on 24 April 2008) -============================= - -* Offline indexing only mode - which is a minus if you want changes -immediately reflected in the search index, and a plus if you were going to -have to implement your own offline indexing anyway. - -* Collapsing - the equivalent of SQL's "group by". You can specify a field -to collapse on, and only the most relevant result from each value of that -field is returned. Along with a count of how many there are in total. -acts_as_solr doesn't have this. - -* No highlighting - Xapian can't return you text highlighted with a search -query. You can try and make do with TextHelper::highlight (combined with -words_to_highlight below). I found the highlighting in acts_as_solr didn't -really understand the query anyway. - -* Date range searching - this exists in acts_as_solr, but I found it -wasn't documented well enough, and was hard to get working. - -* Spelling correction - "did you mean?" built in and just works. - -* Similar documents - acts_as_xapian has a simple command to find other models -that are like a specified model. - -* Multiple models - acts_as_xapian searches multiple types of model if you -like, returning them mixed up together by relevancy. This is like -multi_solr_search, only it is the default mode of operation and is properly -supported. - -* No daemons - However, if you have more than one web server, you'll need to -work out how to use "Xapian's remote backend":http://xapian.org/docs/remote.html. - -* One layer - full-powered Xapian is called directly from the Ruby, without -Solr getting in the way whenever you want to use a new feature from Lucene. - -* No Java - an advantage if you're more used to working in the rest of the -open source world. acts_as_xapian, it's pure Ruby and C++. - -* Xapian's awesome email list - the kids over at -"xapian-discuss":http://lists.xapian.org/mailman/listinfo/xapian-discuss -are super helpful. Useful if you need to extend and improve acts_as_xapian. The -Ruby bindings are mature and well maintained as part of Xapian. - - -d. Documentation - indexing -=========================== - -Xapian is an *offline indexing* search library - only one process can have the -Xapian database open for writing at once, and others that try meanwhile are -unceremoniously kicked out. For this reason, acts_as_xapian does not support -immediate writing to the database when your models change. - -Instead, there is a ActsAsXapianJob model which stores which models need -updating or deleting in the search index. A rake task 'xapian:update_index' -then performs the updates since last change. You can run it on a cron job, or -similar. - -Here's how to add indexing to your Rails app: - -1. Put acts_as_xapian in your models that need search indexing. e.g. - - acts_as_xapian :texts => [ :name, :short_name ], - :values => [ [ :created_at, 0, "created_at", :date ] ], - :terms => [ [ :variety, 'V', "variety" ] ] - -Options must include: - -* :texts, an array of fields for indexing with full text search. -e.g. :texts => [ :title, :body ] - -* :values, things which have a range of values for sorting, or for collapsing. -Specify an array quadruple of [ field, identifier, prefix, type ] where -** identifier is an arbitary numeric identifier for use in the Xapian database -** prefix is the part to use in search queries that goes before the : -** type can be any of :string, :number or :date - -e.g. :values => [ [ :created_at, 0, "created_at", :date ], -[ :size, 1, "size", :string ] ] - -* :terms, things which come with a prefix (before a :) in search queries. -Specify an array triple of [ field, char, prefix ] where -** char is an arbitary single upper case char used in the Xapian database, just -pick any single uppercase character, but use a different one for each prefix. -** prefix is the part to use in search queries that goes before the : -For example, if you were making Google and indexing to be able to later do a -query like "site:www.whatdotheyknow.com", then the prefix would be "site". - -e.g. :terms => [ [ :variety, 'V', "variety" ] ] - -A 'field' is a symbol referring to either an attribute or a function which -returns the text, date or number to index. Both 'identifier' and 'char' must be -the same for the same prefix in different models. - -Options may include: -* :eager_load, added as an :include clause when looking up search results in -database -* :if, either an attribute or a function which if returns false means the -object isn't indexed - -2. Generate a database migration to create the ActsAsXapianJob model: - - script/generate acts_as_xapian - rake db:migrate - -3. Call 'rake xapian:rebuild_index models="ModelName1 ModelName2"' to build the index -the first time (you must specify all your indexed models). It's put in a -development/test/production dir in acts_as_xapian/xapiandbs. See f. Configuration -below if you want to change this. - -4. Then from a cron job or a daemon, or by hand regularly!, call 'rake xapian:update_index' - - -e. Documentation - querying -=========================== - -Testing indexing ----------------- - -If you just want to test indexing is working, you'll find this rake task -useful (it has more options, see tasks/xapian.rake) - - rake xapian:query models="PublicBody User" query="moo" - -Performing a query ------------------- - -To perform a query from code call ActsAsXapian::Search.new. This takes in turn: -* model_classes - list of models to search, e.g. [PublicBody, InfoRequestEvent] -* query_string - Google like syntax, see below - -And then a hash of options: -* :offset - Offset of first result (default 0) -* :limit - Number of results per page -* :sort_by_prefix - Optionally, prefix of value to sort by, otherwise sort by relevance -* :sort_by_ascending - Default true (documents with higher values better/earlier), set to false for descending sort -* :collapse_by_prefix - Optionally, prefix of value to collapse by (i.e. only return most relevant result from group) - -Google like query syntax is as described in - "Xapian::QueryParser Syntax":http://www.xapian.org/docs/queryparser.html -Queries can include prefix:value parts, according to what you indexed in the -acts_as_xapian part above. You can also say things like model:InfoRequestEvent -to constrain by model in more complex ways than the :model parameter, or -modelid:InfoRequestEvent-100 to only find one specific object. - -Returns an ActsAsXapian::Search object. Useful methods are: -* description - a techy one, to check how the query has been parsed -* matches_estimated - a guesstimate at the total number of hits -* spelling_correction - the corrected query string if there is a correction, otherwise nil -* words_to_highlight - list of words for you to highlight, perhaps with TextHelper::highlight -* results - an array of hashes each containing: -** :model - your Rails model, this is what you most want! -** :weight - relevancy measure -** :percent - the weight as a %, 0 meaning the item did not match the query at all -** :collapse_count - number of results with the same prefix, if you specified collapse_by_prefix - -Finding similar models ----------------------- - -To find models that are similar to a given set of models call ActsAsXapian::Similar.new. This takes: -* model_classes - list of model classes to return models from within -* models - list of models that you want to find related ones to - -Returns an ActsAsXapian::Similar object. Has all methods from ActsAsXapian::Search above, except -for words_to_highlight. In addition has: -* important_terms - the terms extracted from the input models, that were used to search for output -You need the results methods to get the similar models. - - -f. Configuration -================ - -If you want to customise the configuration of acts_as_xapian, it will look for -a file called 'xapian.yml' under RAILS_ROOT/config. As is familiar from the -format of the database.yml file, separate :development, :test and :production -sections are expected. - -The following options are available: -* base_db_path - specifies the directory, relative to RAILS_ROOT, in which -acts_as_xapian stores its search index databases. Default is the directory -xapiandbs within the acts_as_xapian directory. - - -g. Performance -============== - -On development sites, acts_as_xapian automatically logs the time taken to do -searches. The time displayed is for the Xapian parts of the query; the Rails -database model lookups will be logged separately by ActiveRecord. Example: - - Xapian query (0.00029s) Search: hello - -To enable this, and other performance logging, on a production site, -temporarily add this to the end of your config/environment.rb - - ActiveRecord::Base.logger = Logger.new(STDOUT) - - -h. Support -========== - -Please ask any questions on the -"acts_as_xapian Google Group":http://groups.google.com/group/acts_as_xapian - -The official home page and repository for acts_as_xapian are the -"acts_as_xapian github page":http://github.com/frabcus/acts_as_xapian/wikis - -For more details about anything, see source code in lib/acts_as_xapian.rb - -Merging source instructions "Using git for collaboration" here: -http://www.kernel.org/pub/software/scm/git/docs/gittutorial.html diff --git a/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/USAGE b/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/USAGE deleted file mode 100644 index 2d027c46f..000000000 --- a/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/USAGE +++ /dev/null @@ -1 +0,0 @@ -./script/generate acts_as_xapian diff --git a/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/acts_as_xapian_generator.rb b/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/acts_as_xapian_generator.rb deleted file mode 100644 index a1cd1801d..000000000 --- a/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/acts_as_xapian_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -class ActsAsXapianGenerator < Rails::Generator::Base - def manifest - record do |m| - m.migration_template 'migration.rb', 'db/migrate', - :migration_file_name => "create_acts_as_xapian" - end - end - - protected - def banner - "Usage: #{$0} acts_as_xapian" - end -end diff --git a/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/templates/migration.rb b/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/templates/migration.rb deleted file mode 100644 index 84a9dd766..000000000 --- a/vendor/plugins/acts_as_xapian/generators/acts_as_xapian/templates/migration.rb +++ /dev/null @@ -1,14 +0,0 @@ -class CreateActsAsXapian < ActiveRecord::Migration - def self.up - create_table :acts_as_xapian_jobs do |t| - t.column :model, :string, :null => false - t.column :model_id, :integer, :null => false - t.column :action, :string, :null => false - end - add_index :acts_as_xapian_jobs, [:model, :model_id], :unique => true - end - def self.down - drop_table :acts_as_xapian_jobs - end -end - diff --git a/vendor/plugins/acts_as_xapian/init.rb b/vendor/plugins/acts_as_xapian/init.rb deleted file mode 100644 index 36b43ac0b..000000000 --- a/vendor/plugins/acts_as_xapian/init.rb +++ /dev/null @@ -1,7 +0,0 @@ -# acts_as_xapian/init.rb: -# -# Copyright (c) 2008 UK Citizens Online Democracy. All rights reserved. -# Email: francis@mysociety.org; WWW: http://www.mysociety.org/ - -require 'acts_as_xapian' - diff --git a/vendor/plugins/acts_as_xapian/lib/acts_as_xapian.rb b/vendor/plugins/acts_as_xapian/lib/acts_as_xapian.rb deleted file mode 100644 index 374fcd65b..000000000 --- a/vendor/plugins/acts_as_xapian/lib/acts_as_xapian.rb +++ /dev/null @@ -1,969 +0,0 @@ -# acts_as_xapian/lib/acts_as_xapian.rb: -# Xapian full text search in Ruby on Rails. -# -# Copyright (c) 2008 UK Citizens Online Democracy. All rights reserved. -# Email: francis@mysociety.org; WWW: http://www.mysociety.org/ -# -# Documentation -# ============= -# -# See ../README.txt foocumentation. Please update that file if you edit -# code. - -# Make it so if Xapian isn't installed, the Rails app doesn't fail completely, -# just when somebody does a search. -begin - require 'xapian' - $acts_as_xapian_bindings_available = true -rescue LoadError - STDERR.puts "acts_as_xapian: No Ruby bindings for Xapian installed" - $acts_as_xapian_bindings_available = false -end - -module ActsAsXapian - ###################################################################### - # Module level variables - # XXX must be some kind of cattr_accessor that can do this better - def ActsAsXapian.bindings_available - $acts_as_xapian_bindings_available - end - class NoXapianRubyBindingsError < StandardError - end - - @@db = nil - @@db_path = nil - @@writable_db = nil - @@init_values = [] - - # There used to be a problem with this module being loaded more than once. - # Keep a check here, so we can tell if the problem recurs. - if $acts_as_xapian_class_var_init - raise "The acts_as_xapian module has already been loaded" - else - $acts_as_xapian_class_var_init = true - end - - def ActsAsXapian.db - @@db - end - def ActsAsXapian.db_path=(db_path) - @@db_path = db_path - end - def ActsAsXapian.db_path - @@db_path - end - def ActsAsXapian.writable_db - @@writable_db - end - def ActsAsXapian.stemmer - @@stemmer - end - def ActsAsXapian.term_generator - @@term_generator - end - def ActsAsXapian.enquire - @@enquire - end - def ActsAsXapian.query_parser - @@query_parser - end - def ActsAsXapian.values_by_prefix - @@values_by_prefix - end - def ActsAsXapian.config - @@config - end - - ###################################################################### - # Initialisation - def ActsAsXapian.init(classname = nil, options = nil) - if not classname.nil? - # store class and options for use later, when we open the db in readable_init - @@init_values.push([classname,options]) - end - end - - # Reads the config file (if any) and sets up the path to the database we'll be using - def ActsAsXapian.prepare_environment - return unless @@db_path.nil? - - # barf if we can't figure out the environment - environment = (ENV['RAILS_ENV'] or RAILS_ENV) - raise "Set RAILS_ENV, so acts_as_xapian can find the right Xapian database" if not environment - - # check for a config file - config_file = RAILS_ROOT + "/config/xapian.yml" - @@config = File.exists?(config_file) ? YAML.load_file(config_file)[environment] : {} - - # figure out where the DBs should go - if config['base_db_path'] - db_parent_path = RAILS_ROOT + "/" + config['base_db_path'] - else - db_parent_path = File.join(File.dirname(__FILE__), '../xapiandbs/') - end - - # make the directory for the xapian databases to go in - Dir.mkdir(db_parent_path) unless File.exists?(db_parent_path) - - @@db_path = File.join(db_parent_path, environment) - - # make some things that don't depend on the db - # XXX this gets made once for each acts_as_xapian. Oh well. - @@stemmer = Xapian::Stem.new('english') - end - - # Opens / reopens the db for reading - # XXX we perhaps don't need to rebuild database and enquire and queryparser - - # but db.reopen wasn't enough by itself, so just do everything it's easier. - def ActsAsXapian.readable_init - raise NoXapianRubyBindingsError.new("Xapian Ruby bindings not installed") unless ActsAsXapian.bindings_available - raise "acts_as_xapian hasn't been called in any models" if @@init_values.empty? - - prepare_environment - - # We need to reopen the database each time, so Xapian gets changes to it. - # Calling reopen() does not always pick up changes for reasons that I can - # only speculate about at the moment. (It is easy to reproduce this by - # changing the code below to use reopen() rather than open() followed by - # close(), and running rake spec.) - if !@@db.nil? - @@db.close - end - - # basic Xapian objects - begin - @@db = Xapian::Database.new(@@db_path) - @@enquire = Xapian::Enquire.new(@@db) - rescue IOError => e - raise "Failed to open Xapian database #{@@db_path}: #{e.message}" - end - - init_query_parser - end - - # Make a new query parser - def ActsAsXapian.init_query_parser - # for queries - @@query_parser = Xapian::QueryParser.new - @@query_parser.stemmer = @@stemmer - @@query_parser.stemming_strategy = Xapian::QueryParser::STEM_SOME - @@query_parser.database = @@db - @@query_parser.default_op = Xapian::Query::OP_AND - begin - @@query_parser.set_max_wildcard_expansion(1000) - rescue NoMethodError - # The set_max_wildcard_expansion method was introduced in Xapian 1.2.7, - # so may legitimately not be available. - # - # Large installations of Alaveteli should consider - # upgrading, because uncontrolled wildcard expansion - # can crash the whole server: see http://trac.xapian.org/ticket/350 - end - - @@stopper = Xapian::SimpleStopper.new - @@stopper.add("and") - @@stopper.add("of") - @@stopper.add("&") - @@query_parser.stopper = @@stopper - - @@terms_by_capital = {} - @@values_by_number = {} - @@values_by_prefix = {} - @@value_ranges_store = [] - - for init_value_pair in @@init_values - classname = init_value_pair[0] - options = init_value_pair[1] - - # go through the various field types, and tell query parser about them, - # and error check them - i.e. check for consistency between models - @@query_parser.add_boolean_prefix("model", "M") - @@query_parser.add_boolean_prefix("modelid", "I") - if options[:terms] - for term in options[:terms] - raise "Use a single capital letter for term code" if not term[1].match(/^[A-Z]$/) - raise "M and I are reserved for use as the model/id term" if term[1] == "M" or term[1] == "I" - raise "model and modelid are reserved for use as the model/id prefixes" if term[2] == "model" or term[2] == "modelid" - raise "Z is reserved for stemming terms" if term[1] == "Z" - raise "Already have code '" + term[1] + "' in another model but with different prefix '" + @@terms_by_capital[term[1]] + "'" if @@terms_by_capital.include?(term[1]) && @@terms_by_capital[term[1]] != term[2] - @@terms_by_capital[term[1]] = term[2] - # XXX use boolean here so doesn't stem our URL names in WhatDoTheyKnow - # If making acts_as_xapian generic, would really need to make the :terms have - # another option that lets people choose non-boolean for terms that need it - # (i.e. searching explicitly within a free text field) - @@query_parser.add_boolean_prefix(term[2], term[1]) - end - end - if options[:values] - for value in options[:values] - raise "Value index '"+value[1].to_s+"' must be an integer, is " + value[1].class.to_s if value[1].class != 1.class - raise "Already have value index '" + value[1].to_s + "' in another model but with different prefix '" + @@values_by_number[value[1]].to_s + "'" if @@values_by_number.include?(value[1]) && @@values_by_number[value[1]] != value[2] - - # date types are special, mark them so the first model they're seen for - if !@@values_by_number.include?(value[1]) - if value[3] == :date - value_range = Xapian::DateValueRangeProcessor.new(value[1]) - elsif value[3] == :string - value_range = Xapian::StringValueRangeProcessor.new(value[1]) - elsif value[3] == :number - value_range = Xapian::NumberValueRangeProcessor.new(value[1]) - else - raise "Unknown value type '" + value[3].to_s + "'" - end - - @@query_parser.add_valuerangeprocessor(value_range) - - # stop it being garbage collected, as - # add_valuerangeprocessor ref is outside Ruby's GC - @@value_ranges_store.push(value_range) - end - - @@values_by_number[value[1]] = value[2] - @@values_by_prefix[value[2]] = value[1] - end - end - end - end - - def ActsAsXapian.writable_init(suffix = "") - raise NoXapianRubyBindingsError.new("Xapian Ruby bindings not installed") unless ActsAsXapian.bindings_available - raise "acts_as_xapian hasn't been called in any models" if @@init_values.empty? - - # if DB is not nil, then we're already initialised, so don't do it - # again XXX reopen it each time, xapian_spec.rb needs this so database - # gets written twice correctly. - # return unless @@writable_db.nil? - - prepare_environment - - full_path = @@db_path + suffix - - # for indexing - @@writable_db = Xapian::WritableDatabase.new(full_path, Xapian::DB_CREATE_OR_OPEN) - @@enquire = Xapian::Enquire.new(@@writable_db) - @@term_generator = Xapian::TermGenerator.new() - @@term_generator.set_flags(Xapian::TermGenerator::FLAG_SPELLING, 0) - @@term_generator.database = @@writable_db - @@term_generator.stemmer = @@stemmer - end - - ###################################################################### - # Search with a query or for similar models - - # Base class for Search and Similar below - class QueryBase - attr_accessor :offset - attr_accessor :limit - attr_accessor :query - attr_accessor :matches - attr_accessor :query_models - attr_accessor :runtime - attr_accessor :cached_results - - def initialize_db - self.runtime = 0.0 - - ActsAsXapian.readable_init - if ActsAsXapian.db.nil? - raise "ActsAsXapian not initialized" - end - end - - MSET_MAX_TRIES = 5 - MSET_MAX_DELAY = 5 - # Set self.query before calling this - def initialize_query(options) - #raise options.to_yaml - - self.runtime += Benchmark::realtime { - offset = options[:offset] || 0; offset = offset.to_i - limit = options[:limit] - raise "please specifiy maximum number of results to return with parameter :limit" if not limit - limit = limit.to_i - sort_by_prefix = options[:sort_by_prefix] || nil - sort_by_ascending = options[:sort_by_ascending].nil? ? true : options[:sort_by_ascending] - collapse_by_prefix = options[:collapse_by_prefix] || nil - - ActsAsXapian.enquire.query = self.query - - if sort_by_prefix.nil? - ActsAsXapian.enquire.sort_by_relevance! - else - value = ActsAsXapian.values_by_prefix[sort_by_prefix] - raise "couldn't find prefix '" + sort_by_prefix.to_s + "'" if value.nil? - ActsAsXapian.enquire.sort_by_value_then_relevance!(value, sort_by_ascending) - end - if collapse_by_prefix.nil? - ActsAsXapian.enquire.collapse_key = Xapian.BAD_VALUENO - else - value = ActsAsXapian.values_by_prefix[collapse_by_prefix] - raise "couldn't find prefix '" + collapse_by_prefix + "'" if value.nil? - ActsAsXapian.enquire.collapse_key = value - end - - tries = 0 - delay = 1 - begin - self.matches = ActsAsXapian.enquire.mset(offset, limit, 100) - rescue IOError => e - if e.message =~ /DatabaseModifiedError: / - # This should be a transient error, so back off and try again, up to a point - if tries > MSET_MAX_TRIES - raise "Received DatabaseModifiedError from Xapian even after retrying #{MSET_MAX_TRIES} times" - else - sleep delay - end - tries += 1 - delay *= 2 - delay = MSET_MAX_DELAY if delay > MSET_MAX_DELAY - - ActsAsXapian.db.reopen() - retry - else - raise - end - end - self.cached_results = nil - } - end - - # Return a description of the query - def description - self.query.description - end - - # Does the query have non-prefixed search terms in it? - def has_normal_search_terms? - ret = false - #x = '' - for t in self.query.terms - term = t.term - #x = x + term.to_yaml + term.size.to_s + term[0..0] + "*" - if term.size >= 2 && term[0..0] == 'Z' - # normal terms begin Z (for stemmed), then have no capital letter prefix - if term[1..1] == term[1..1].downcase - ret = true - end - end - end - return ret - end - - # Estimate total number of results - def matches_estimated - self.matches.matches_estimated - end - - # Return query string with spelling correction - def spelling_correction - correction = ActsAsXapian.query_parser.get_corrected_query_string - if correction.empty? - return nil - end - return correction - end - - # Return array of models found - def results - # If they've already pulled out the results, just return them. - if !self.cached_results.nil? - return self.cached_results - end - - docs = [] - self.runtime += Benchmark::realtime { - # Pull out all the results - iter = self.matches._begin - while not iter.equals(self.matches._end) - docs.push({:data => iter.document.data, - :percent => iter.percent, - :weight => iter.weight, - :collapse_count => iter.collapse_count}) - iter.next - end - } - - # Log time taken, excluding database lookups below which will be displayed separately by ActiveRecord - if ActiveRecord::Base.logger - ActiveRecord::Base.logger.add(Logger::DEBUG, " Xapian query (#{'%.5fs' % self.runtime}) #{self.log_description}") - end - - # Look up without too many SQL queries - lhash = {} - lhash.default = [] - for doc in docs - k = doc[:data].split('-') - lhash[k[0]] = lhash[k[0]] + [k[1]] - end - # for each class, look up all ids - chash = {} - for cls, ids in lhash - conditions = [ "#{cls.constantize.table_name}.#{cls.constantize.primary_key} in (?)", ids ] - found = cls.constantize.find(:all, :conditions => conditions, :include => cls.constantize.xapian_options[:eager_load]) - for f in found - chash[[cls, f.id]] = f - end - end - # now get them in right order again - results = [] - docs.each do |doc| - k = doc[:data].split('-') - model_instance = chash[[k[0], k[1].to_i]] - if model_instance - results << { :model => model_instance, - :percent => doc[:percent], - :weight => doc[:weight], - :collapse_count => doc[:collapse_count] } - end - end - self.cached_results = results - return results - end - end - - # Search for a query string, returns an array of hashes in result order. - # Each hash contains the actual Rails object in :model, and other detail - # about relevancy etc. in other keys. - class Search < QueryBase - attr_accessor :query_string - - # Note that model_classes is not only sometimes useful here - it's - # essential to make sure the classes have been loaded, and thus - # acts_as_xapian called on them, so we know the fields for the query - # parser. - - # model_classes - model classes to search within, e.g. [PublicBody, - # User]. Can take a single model class, or you can express the model - # class names in strings if you like. - # query_string - user inputed query string, with syntax much like Google Search - def initialize(model_classes, query_string, options = {}, user_query = nil) - # Check parameters, convert to actual array of model classes - new_model_classes = [] - model_classes = [model_classes] if model_classes.class != Array - for model_class in model_classes - raise "pass in the model class itself, or a string containing its name" if model_class.class != Class && model_class.class != String - model_class = model_class.constantize if model_class.class == String - new_model_classes.push(model_class) - end - model_classes = new_model_classes - - # Set things up - self.initialize_db - - # Case of a string, searching for a Google-like syntax query - self.query_string = query_string - - # Construct query which only finds things from specified models - model_query = Xapian::Query.new(Xapian::Query::OP_OR, model_classes.map{|mc| "M" + mc.to_s}) - if user_query.nil? - user_query = ActsAsXapian.query_parser.parse_query( - self.query_string, - Xapian::QueryParser::FLAG_BOOLEAN | Xapian::QueryParser::FLAG_PHRASE | - Xapian::QueryParser::FLAG_LOVEHATE | - Xapian::QueryParser::FLAG_SPELLING_CORRECTION) - end - self.query = Xapian::Query.new(Xapian::Query::OP_AND, model_query, user_query) - - # Call base class constructor - self.initialize_query(options) - end - - # Return just normal words in the query i.e. Not operators, ones in - # date ranges or similar. Use this for cheap highlighting with - # TextHelper::highlight, and excerpt. - def words_to_highlight - query_nopunc = self.query_string.gsub(/[^a-z0-9:\.\/_]/i, " ") - query_nopunc = query_nopunc.gsub(/\s+/, " ") - words = query_nopunc.split(" ") - # Remove anything with a :, . or / in it - words = words.find_all {|o| !o.match(/(:|\.|\/)/) } - words = words.find_all {|o| !o.match(/^(AND|NOT|OR|XOR)$/) } - return words - end - - # Text for lines in log file - def log_description - "Search: " + self.query_string - end - - end - - # Search for models which contain theimportant terms taken from a specified - # list of models. i.e. Use to find documents similar to one (or more) - # documents, or use to refine searches. - class Similar < QueryBase - attr_accessor :query_models - attr_accessor :important_terms - - # model_classes - model classes to search within, e.g. [PublicBody, User] - # query_models - list of models you want to find things similar to - def initialize(model_classes, query_models, options = {}) - self.initialize_db - - self.runtime += Benchmark::realtime { - # Case of an array, searching for models similar to those models in the array - self.query_models = query_models - - # Find the documents by their unique term - input_models_query = Xapian::Query.new(Xapian::Query::OP_OR, query_models.map{|m| "I" + m.xapian_document_term}) - ActsAsXapian.enquire.query = input_models_query - matches = ActsAsXapian.enquire.mset(0, 100, 100) # XXX so this whole method will only work with 100 docs - - # Get set of relevant terms for those documents - selection = Xapian::RSet.new() - iter = matches._begin - while not iter.equals(matches._end) - selection.add_document(iter) - iter.next - end - - # Bit weird that the function to make esets is part of the enquire - # object. This explains what exactly it does, which is to exclude - # terms in the existing query. - # http://thread.gmane.org/gmane.comp.search.xapian.general/3673/focus=3681 - eset = ActsAsXapian.enquire.eset(40, selection) - - # Do main search for them - self.important_terms = [] - iter = eset._begin - while not iter.equals(eset._end) - self.important_terms.push(iter.term) - iter.next - end - similar_query = Xapian::Query.new(Xapian::Query::OP_OR, self.important_terms) - # Exclude original - combined_query = Xapian::Query.new(Xapian::Query::OP_AND_NOT, similar_query, input_models_query) - - # Restrain to model classes - model_query = Xapian::Query.new(Xapian::Query::OP_OR, model_classes.map{|mc| "M" + mc.to_s}) - self.query = Xapian::Query.new(Xapian::Query::OP_AND, model_query, combined_query) - } - - # Call base class constructor - self.initialize_query(options) - end - - # Text for lines in log file - def log_description - "Similar: " + self.query_models.to_s - end - end - - ###################################################################### - # Index - - # Offline indexing job queue model, create with migration made - # using "script/generate acts_as_xapian" as described in ../README.txt - class ActsAsXapianJob < ActiveRecord::Base - end - - # Update index with any changes needed, call this offline. Usually call it - # from a script that exits - otherwise Xapian's writable database won't - # flush your changes. Specifying flush will reduce performance, but make - # sure that each index update is definitely saved to disk before - # logging in the database that it has been. - def ActsAsXapian.update_index(flush = false, verbose = false) - # STDOUT.puts("start of ActsAsXapian.update_index") if verbose - - # Before calling writable_init we have to make sure every model class has been initialized. - # i.e. has had its class code loaded, so acts_as_xapian has been called inside it, and - # we have the info from acts_as_xapian. - model_classes = ActsAsXapianJob.find_by_sql("select model from acts_as_xapian_jobs group by model").map {|a| a.model.constantize} - # If there are no models in the queue, then nothing to do - return if model_classes.size == 0 - - ActsAsXapian.writable_init - # Abort if full rebuild is going on - new_path = ActsAsXapian.db_path + ".new" - if File.exist?(new_path) - raise "aborting incremental index update while full index rebuild happens; found existing " + new_path - end - - ids_to_refresh = ActsAsXapianJob.find(:all).map() { |i| i.id } - for id in ids_to_refresh - job = nil - begin - ActiveRecord::Base.transaction do - begin - job = ActsAsXapianJob.find(id, :lock =>true) - rescue ActiveRecord::RecordNotFound => e - # This could happen if while we are working the model - # was updated a second time by another process. In that case - # ActsAsXapianJob.delete_all in xapian_mark_needs_index below - # might have removed the first job record while we are working on it. - #STDERR.puts("job with #{id} vanished under foot") if verbose - next - end - STDOUT.puts("ActsAsXapian.update_index #{job.action} #{job.model} #{job.model_id.to_s} #{Time.now.to_s}") if verbose - - begin - if job.action == 'update' - # XXX Index functions may reference other models, so we could eager load here too? - model = job.model.constantize.find(job.model_id) # :include => cls.constantize.xapian_options[:include] - model.xapian_index - elsif job.action == 'destroy' - # Make dummy model with right id, just for destruction - model = job.model.constantize.new - model.id = job.model_id - model.xapian_destroy - else - raise "unknown ActsAsXapianJob action '" + job.action + "'" - end - rescue ActiveRecord::RecordNotFound => e - # this can happen if the record was hand deleted in the database - job.action = 'destroy' - retry - end - if flush - ActsAsXapian.writable_db.flush - end - job.destroy - end - rescue => detail - # print any error, and carry on so other things are indexed - STDERR.puts(detail.backtrace.join("\n") + "\nFAILED ActsAsXapian.update_index job #{id} #{$!} " + (job.nil? ? "" : "model " + job.model + " id " + job.model_id.to_s)) - end - end - # We close the database when we're finished to remove the lock file. Since writable_init - # reopens it and recreates the environment every time we don't need to do further cleanup - ActsAsXapian.writable_db.flush - ActsAsXapian.writable_db.close - end - - def ActsAsXapian._is_xapian_db(path) - is_db = File.exist?(File.join(path, "iamflint")) || File.exist?(File.join(path, "iamchert")) - return is_db - end - - # You must specify *all* the models here, this totally rebuilds the Xapian - # database. You'll want any readers to reopen the database after this. - # - # Incremental update_index calls above are suspended while this rebuild - # happens (i.e. while the .new database is there) - any index update jobs - # are left in the database, and will run after the rebuild has finished. - - def ActsAsXapian.rebuild_index(model_classes, verbose = false, terms = true, values = true, texts = true, safe_rebuild = true) - #raise "when rebuilding all, please call as first and only thing done in process / task" if not ActsAsXapian.writable_db.nil? - prepare_environment - - update_existing = !(terms == true && values == true && texts == true) - # Delete any existing .new database, and open a new one which is a copy of the current one - new_path = ActsAsXapian.db_path + ".new" - old_path = ActsAsXapian.db_path - if File.exist?(new_path) - raise "found existing " + new_path + " which is not Xapian flint database, please delete for me" if not ActsAsXapian._is_xapian_db(new_path) - FileUtils.rm_r(new_path) - end - if update_existing - FileUtils.cp_r(old_path, new_path) - end - ActsAsXapian.writable_init - ActsAsXapian.writable_db.close # just to make an empty one to read - # Index everything - if safe_rebuild - _rebuild_index_safely(model_classes, verbose, terms, values, texts) - else - @@db_path = ActsAsXapian.db_path + ".new" - ActsAsXapian.writable_init - # Save time by running the indexing in one go and in-process - for model_class in model_classes - STDOUT.puts("ActsAsXapian.rebuild_index: Rebuilding #{model_class.to_s}") if verbose - model_class.find(:all).each do |model| - STDOUT.puts("ActsAsXapian.rebuild_index #{model_class} #{model.id}") if verbose - model.xapian_index(terms, values, texts) - end - end - ActsAsXapian.writable_db.flush - ActsAsXapian.writable_db.close - end - - # Rename into place - temp_path = old_path + ".tmp" - if File.exist?(temp_path) - @@db_path = old_path - raise "temporary database found " + temp_path + " which is not Xapian flint database, please delete for me" if not ActsAsXapian._is_xapian_db(temp_path) - FileUtils.rm_r(temp_path) - end - if File.exist?(old_path) - FileUtils.mv old_path, temp_path - end - FileUtils.mv new_path, old_path - - # Delete old database - if File.exist?(temp_path) - if not ActsAsXapian._is_xapian_db(temp_path) - @@db_path = old_path - raise "old database now at " + temp_path + " is not Xapian flint database, please delete for me" - end - FileUtils.rm_r(temp_path) - end - - # You'll want to restart your FastCGI or Mongrel processes after this, - # so they get the new db - @@db_path = old_path - end - - def ActsAsXapian._rebuild_index_safely(model_classes, verbose, terms, values, texts) - batch_size = 1000 - for model_class in model_classes - model_class_count = model_class.count - 0.step(model_class_count, batch_size) do |i| - # We fork here, so each batch is run in a different process. This is - # because otherwise we get a memory "leak" and you can't rebuild very - # large databases (however long you have!) - pid = Process.fork # XXX this will only work on Unix, tough - if pid - Process.waitpid(pid) - if not $?.success? - raise "batch fork child failed, exiting also" - end - # database connection doesn't survive a fork, rebuild it - ActiveRecord::Base.connection.reconnect! - else - - # fully reopen the database each time (with a new object) - # (so doc ids and so on aren't preserved across the fork) - @@db_path = ActsAsXapian.db_path + ".new" - ActsAsXapian.writable_init - STDOUT.puts("ActsAsXapian.rebuild_index: New batch. #{model_class.to_s} from #{i} to #{i + batch_size} of #{model_class_count} pid #{Process.pid.to_s}") if verbose - model_class.find(:all, :limit => batch_size, :offset => i, :order => :id).each do |model| - STDOUT.puts("ActsAsXapian.rebuild_index #{model_class} #{model.id}") if verbose - model.xapian_index(terms, values, texts) - end - ActsAsXapian.writable_db.flush - ActsAsXapian.writable_db.close - # database connection won't survive a fork, so shut it down - ActiveRecord::Base.connection.disconnect! - # brutal exit, so other shutdown code not run (for speed and safety) - Kernel.exit! 0 - end - - end - end - end - - ###################################################################### - # Instance methods that get injected into your model. - - module InstanceMethods - # Used internally - def xapian_document_term - self.class.to_s + "-" + self.id.to_s - end - - def xapian_value(field, type = nil, index_translations = false) - if index_translations && self.respond_to?("translations") - if type == :date or type == :boolean - value = single_xapian_value(field, type = type) - else - values = [] - for locale in self.translations.map{|x| x.locale} - self.class.with_locale(locale) do - values << single_xapian_value(field, type=type) - end - end - if values[0].kind_of?(Array) - values = values.flatten - value = values.reject{|x| x.nil?} - else - values = values.reject{|x| x.nil?} - value = values.join(" ") - end - end - else - value = single_xapian_value(field, type = type) - end - return value - end - - # Extract value of a field from the model - def single_xapian_value(field, type = nil) - value = self.send(field.to_sym) || self[field] - if type == :date - if value.kind_of?(Time) - value.utc.strftime("%Y%m%d") - elsif value.kind_of?(Date) - value.to_time.utc.strftime("%Y%m%d") - else - raise "Only Time or Date types supported by acts_as_xapian for :date fields, got " + value.class.to_s - end - elsif type == :boolean - value ? true : false - else - # Arrays are for terms which require multiple of them, e.g. tags - if value.kind_of?(Array) - value.map {|v| v.to_s} - else - value.to_s - end - end - end - - # Store record in the Xapian database - def xapian_index(terms = true, values = true, texts = true) - # if we have a conditional function for indexing, call it and destroy object if failed - if self.class.xapian_options.include?(:if) - if_value = xapian_value(self.class.xapian_options[:if], :boolean) - if not if_value - self.xapian_destroy - return - end - end - - existing_query = Xapian::Query.new("I" + self.xapian_document_term) - ActsAsXapian.enquire.query = existing_query - match = ActsAsXapian.enquire.mset(0,1,1).matches[0] - - if !match.nil? - doc = match.document - else - doc = Xapian::Document.new - doc.data = self.xapian_document_term - doc.add_term("M" + self.class.to_s) - doc.add_term("I" + doc.data) - end - # work out what to index - # 1. Which terms to index? We allow the user to specify particular ones - terms_to_index = [] - drop_all_terms = false - if terms and self.xapian_options[:terms] - terms_to_index = self.xapian_options[:terms].dup - if terms.is_a?(String) - terms_to_index.reject!{|term| !terms.include?(term[1])} - if terms_to_index.length == self.xapian_options[:terms].length - drop_all_terms = true - end - else - drop_all_terms = true - end - end - # 2. Texts to index? Currently, it's all or nothing - texts_to_index = [] - if texts and self.xapian_options[:texts] - texts_to_index = self.xapian_options[:texts] - end - # 3. Values to index? Currently, it's all or nothing - values_to_index = [] - if values and self.xapian_options[:values] - values_to_index = self.xapian_options[:values] - end - - # clear any existing data that we might want to replace - if drop_all_terms && texts - # as an optimisation, if we're reindexing all of both, we remove everything - doc.clear_terms - doc.add_term("M" + self.class.to_s) - doc.add_term("I" + doc.data) - else - term_prefixes_to_index = terms_to_index.map {|x| x[1]} - for existing_term in doc.terms - first_letter = existing_term.term[0...1] - if !"MI".include?(first_letter) # it's not one of the reserved value - if first_letter.match("^[A-Z]+") # it's a "value" (rather than indexed text) - if term_prefixes_to_index.include?(first_letter) # it's a value that we've been asked to index - doc.remove_term(existing_term.term) - end - elsif texts - doc.remove_term(existing_term.term) # it's text and we've been asked to reindex it - end - end - end - end - - for term in terms_to_index - value = xapian_value(term[0]) - if value.kind_of?(Array) - for v in value - doc.add_term(term[1] + v) - end - else - doc.add_term(term[1] + value) - end - end - - if values - doc.clear_values - for value in values_to_index - doc.add_value(value[1], xapian_value(value[0], value[3])) - end - end - if texts - ActsAsXapian.term_generator.document = doc - for text in texts_to_index - ActsAsXapian.term_generator.increase_termpos # stop phrases spanning different text fields - # XXX the "1" here is a weight that could be varied for a boost function - ActsAsXapian.term_generator.index_text(xapian_value(text, nil, true), 1) - end - end - - ActsAsXapian.writable_db.replace_document("I" + doc.data, doc) - end - - # Delete record from the Xapian database - def xapian_destroy - ActsAsXapian.writable_db.delete_document("I" + self.xapian_document_term) - end - - # Used to mark changes needed by batch indexer - def xapian_mark_needs_index - model = self.class.base_class.to_s - model_id = self.id - ActiveRecord::Base.transaction do - found = ActsAsXapianJob.delete_all([ "model = ? and model_id = ?", model, model_id]) - job = ActsAsXapianJob.new - job.model = model - job.model_id = model_id - job.action = 'update' - job.save! - end - end - - # Allow reindexing to be skipped if a flag is set - def xapian_mark_needs_index_if_reindex - return true if (self.respond_to?(:no_xapian_reindex) && self.no_xapian_reindex == true) - xapian_mark_needs_index - end - - def xapian_mark_needs_destroy - model = self.class.base_class.to_s - model_id = self.id - ActiveRecord::Base.transaction do - found = ActsAsXapianJob.delete_all([ "model = ? and model_id = ?", model, model_id]) - job = ActsAsXapianJob.new - job.model = model - job.model_id = model_id - job.action = 'destroy' - job.save! - end - end - end - - ###################################################################### - # Main entry point, add acts_as_xapian to your model. - - module ActsMethods - # See top of this file for docs - def acts_as_xapian(options) - # Give error only on queries if bindings not available - if not ActsAsXapian.bindings_available - return - end - - include InstanceMethods - - cattr_accessor :xapian_options - self.xapian_options = options - - ActsAsXapian.init(self.class.to_s, options) - - after_save :xapian_mark_needs_index_if_reindex - after_destroy :xapian_mark_needs_destroy - end - end - -end - -# Reopen ActiveRecord and include the acts_as_xapian method -ActiveRecord::Base.extend ActsAsXapian::ActsMethods - - diff --git a/vendor/plugins/acts_as_xapian/lib/tasks/xapian.rake b/vendor/plugins/acts_as_xapian/lib/tasks/xapian.rake deleted file mode 100644 index c1986ce1e..000000000 --- a/vendor/plugins/acts_as_xapian/lib/tasks/xapian.rake +++ /dev/null @@ -1,66 +0,0 @@ -require 'rubygems' -require 'rake' -require 'rake/testtask' -require 'active_record' - -namespace :xapian do - # Parameters - specify "flush=true" to save changes to the Xapian database - # after each model that is updated. This is safer, but slower. Specify - # "verbose=true" to print model name as it is run. - desc 'Updates Xapian search index with changes to models since last call' - task :update_index => :environment do - ActsAsXapian.update_index(ENV['flush'] ? true : false, ENV['verbose'] ? true : false) - end - - # Parameters - specify 'models="PublicBody User"' to say which models - # you index with Xapian. - - # This totally rebuilds the database, so you will want to restart - # any web server afterwards to make sure it gets the changes, - # rather than still pointing to the old deleted database. Specify - # "verbose=true" to print model name as it is run. By default, - # all of the terms, values and texts are reindexed. You can - # suppress any of these by specifying, for example, "texts=false". - # You can specify that only certain terms should be updated by - # specifying their prefix(es) as a string, e.g. "terms=IV" will - # index the two terms I and V (and "terms=false" will index none, - # and "terms=true", the default, will index all) - - - desc 'Completely rebuilds Xapian search index (must specify all models)' - task :rebuild_index => :environment do - def coerce_arg(arg, default) - if arg == "false" - return false - elsif arg == "true" - return true - elsif arg.nil? - return default - else - return arg - end - end - raise "specify ALL your models with models=\"ModelName1 ModelName2\" as parameter" if ENV['models'].nil? - ActsAsXapian.rebuild_index(ENV['models'].split(" ").map{|m| m.constantize}, - coerce_arg(ENV['verbose'], false), - coerce_arg(ENV['terms'], true), - coerce_arg(ENV['values'], true), - coerce_arg(ENV['texts'], true)) - end - - # Parameters - are models, query, offset, limit, sort_by_prefix, - # collapse_by_prefix - desc 'Run a query, return YAML of results' - task :query => :environment do - raise "specify models=\"ModelName1 ModelName2\" as parameter" if ENV['models'].nil? - raise "specify query=\"your terms\" as parameter" if ENV['query'].nil? - s = ActsAsXapian::Search.new(ENV['models'].split(" ").map{|m| m.constantize}, - ENV['query'], - :offset => (ENV['offset'] || 0), :limit => (ENV['limit'] || 10), - :sort_by_prefix => (ENV['sort_by_prefix'] || nil), - :collapse_by_prefix => (ENV['collapse_by_prefix'] || nil) - ) - STDOUT.puts(s.results.to_yaml) - end -end - diff --git a/vendor/plugins/exception_notification/README b/vendor/plugins/exception_notification/README deleted file mode 100644 index d5e343630..000000000 --- a/vendor/plugins/exception_notification/README +++ /dev/null @@ -1,144 +0,0 @@ -= Exception Notifier Plugin for Rails - -The Exception Notifier plugin provides a mailer object and a default set of -templates for sending email notifications when errors occur in a Rails -application. The plugin is configurable, allowing programmers to specify: - -* the sender address of the email -* the recipient addresses -* the text used to prefix the subject line - -The email includes information about the current request, session, and -environment, and also gives a backtrace of the exception. - -== Usage - -First, include the ExceptionNotifiable mixin in whichever controller you want -to generate error emails (typically ApplicationController): - - class ApplicationController < ActionController::Base - include ExceptionNotification::Notifiable - ... - end - -Then, specify the email recipients in your environment: - - ExceptionNotification::Notifier.exception_recipients = %w(joe@schmoe.com bill@schmoe.com) - -And that's it! The defaults take care of the rest. - -== Configuration - -You can tweak other values to your liking, as well. In your environment file, -just set any or all of the following values: - - # defaults to exception.notifier@default.com - ExceptionNotification::Notifier.sender_address = - %("Application Error" <app.error@myapp.com>) - - # defaults to "[ERROR] " - ExceptionNotification::Notifier.email_prefix = "[APP] " - -Even if you have mixed into ApplicationController you can skip notification in -some controllers by - - class MyController < ApplicationController - skip_exception_notifications - end - -== Deprecated local_request? overriding - -Email notifications will only occur when the IP address is determined not to -be local. You can specify certain addresses to always be local so that you'll -get a detailed error instead of the generic error page. You do this in your -controller (or even per-controller): - - consider_local "64.72.18.143", "14.17.21.25" - -You can specify subnet masks as well, so that all matching addresses are -considered local: - - consider_local "64.72.18.143/24" - -The address "127.0.0.1" is always considered local. If you want to completely -reset the list of all addresses (for instance, if you wanted "127.0.0.1" to -NOT be considered local), you can simply do, somewhere in your controller: - - local_addresses.clear - -NOTE: The above functionality has has been pulled out to consider_local.rb, -as interfering with rails local determination is orthogonal to notification, -unnecessarily clutters backtraces, and even occasionally errs on odd ip or -requests bugs. To return original functionality add an initializer with: - - ActionController::Base.send :include, ConsiderLocal - -or just include it per controller that wants it - - class MyController < ApplicationController - include ExceptionNotification::ConsiderLocal - end - -== Customization - -By default, the notification email includes four parts: request, session, -environment, and backtrace (in that order). You can customize how each of those -sections are rendered by placing a partial named for that part in your -app/views/exception_notifier directory (e.g., _session.rhtml). Each partial has -access to the following variables: - -* @controller: the controller that caused the error -* @request: the current request object -* @exception: the exception that was raised -* @host: the name of the host that made the request -* @backtrace: a sanitized version of the exception's backtrace -* @rails_root: a sanitized version of RAILS_ROOT -* @data: a hash of optional data values that were passed to the notifier -* @sections: the array of sections to include in the email - -You can reorder the sections, or exclude sections completely, by altering the -ExceptionNotification::Notifier.sections variable. You can even add new sections that -describe application-specific data--just add the section's name to the list -(whereever you'd like), and define the corresponding partial. Then, if your -new section requires information that isn't available by default, make sure -it is made available to the email using the exception_data macro: - - class ApplicationController < ActionController::Base - ... - protected - exception_data :additional_data - - def additional_data - { :document => @document, - :person => @person } - end - ... - end - -In the above case, @document and @person would be made available to the email -renderer, allowing your new section(s) to access and display them. See the -existing sections defined by the plugin for examples of how to write your own. - -== 404s errors - -Notification is skipped if you return a 404 status, which happens by default -for an ActiveRecord::RecordNotFound or ActionController::UnknownAction error. - -== Manually notifying of error in a rescue block - -If your controller action manually handles an error, the notifier will never be -run. To manually notify of an error call notify_about_exception from within the -rescue block - - def index - #risky operation here - rescue StandardError => error - #custom error handling here - notify_about_exception(error) - end - -== Support and tickets - -https://rails.lighthouseapp.com/projects/8995-rails-plugins - -Copyright (c) 2005 Jamis Buck, released under the MIT license
\ No newline at end of file diff --git a/vendor/plugins/exception_notification/exception_notification.gemspec b/vendor/plugins/exception_notification/exception_notification.gemspec deleted file mode 100644 index b3ff82322..000000000 --- a/vendor/plugins/exception_notification/exception_notification.gemspec +++ /dev/null @@ -1,11 +0,0 @@ -Gem::Specification.new do |s| - s.name = 'exception_notification' - s.version = '2.3.3.0' - s.authors = ["Jamis Buck", "Josh Peek", "Tim Connor"] - s.date = %q{2010-03-13} - s.summary = "Exception notification by email for Rails apps - 2.3-stable compatible version" - s.email = "timocratic@gmail.com" - - s.files = ['README'] + Dir['lib/**/*'] + Dir['views/**/*'] - s.require_path = 'lib' -end diff --git a/vendor/plugins/exception_notification/init.rb b/vendor/plugins/exception_notification/init.rb deleted file mode 100644 index ef215f809..000000000 --- a/vendor/plugins/exception_notification/init.rb +++ /dev/null @@ -1 +0,0 @@ -require "exception_notification" diff --git a/vendor/plugins/exception_notification/lib/exception_notification.rb b/vendor/plugins/exception_notification/lib/exception_notification.rb deleted file mode 100644 index bf5975201..000000000 --- a/vendor/plugins/exception_notification/lib/exception_notification.rb +++ /dev/null @@ -1,7 +0,0 @@ -require "action_mailer" -module ExceptionNotification - autoload :Notifiable, 'exception_notification/notifiable' - autoload :Notifier, 'exception_notification/notifier' - #autoload :NotifierHelper, 'exception_notification/notifier_helper' - autoload :ConsiderLocal, 'exception_notification/consider_local' -end
\ No newline at end of file diff --git a/vendor/plugins/exception_notification/lib/exception_notification/consider_local.rb b/vendor/plugins/exception_notification/lib/exception_notification/consider_local.rb deleted file mode 100644 index 6b9e236f7..000000000 --- a/vendor/plugins/exception_notification/lib/exception_notification/consider_local.rb +++ /dev/null @@ -1,31 +0,0 @@ -#This didn't belong on ExceptionNotifier and made backtraces worse. To keep original functionality in place -#'ActionController::Base.send :include, ExceptionNotification::ConsiderLocal' or just include in your controller -module ExceptionNotification::ConsiderLocal - def self.included(target) - require 'ipaddr' - target.extend(ClassMethods) - end - - module ClassMethods - def consider_local(*args) - local_addresses.concat(args.flatten.map { |a| IPAddr.new(a) }) - end - - def local_addresses - addresses = read_inheritable_attribute(:local_addresses) - unless addresses - addresses = [IPAddr.new("127.0.0.1")] - write_inheritable_attribute(:local_addresses, addresses) - end - addresses - end - end - -private - - def local_request? - remote = IPAddr.new(request.remote_ip) - !self.class.local_addresses.detect { |addr| addr.include?(remote) }.nil? - end - -end diff --git a/vendor/plugins/exception_notification/lib/exception_notification/notifiable.rb b/vendor/plugins/exception_notification/lib/exception_notification/notifiable.rb deleted file mode 100644 index 19895e8db..000000000 --- a/vendor/plugins/exception_notification/lib/exception_notification/notifiable.rb +++ /dev/null @@ -1,66 +0,0 @@ -# Copyright (c) 2005 Jamis Buck -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -module ExceptionNotification::Notifiable - def self.included(target) - target.extend(ClassMethods) - target.skip_exception_notifications false - end - - module ClassMethods - def exception_data(deliverer=self) - if deliverer == self - read_inheritable_attribute(:exception_data) - else - write_inheritable_attribute(:exception_data, deliverer) - end - end - - def skip_exception_notifications(boolean=true) - write_inheritable_attribute(:skip_exception_notifications, boolean) - end - - def skip_exception_notifications? - read_inheritable_attribute(:skip_exception_notifications) - end - end - -private - - def rescue_action_in_public(exception) - super - notify_about_exception(exception) if deliver_exception_notification? - end - - def deliver_exception_notification? - !self.class.skip_exception_notifications? && ![404, "404 Not Found"].include?(response.status.to_s) - end - - def notify_about_exception(exception) - deliverer = self.class.exception_data - data = case deliverer - when nil then {} - when Symbol then send(deliverer) - when Proc then deliverer.call(self) - end - - ExceptionNotification::Notifier.deliver_exception_notification(exception, self, request, data) - end -end diff --git a/vendor/plugins/exception_notification/lib/exception_notification/notifier.rb b/vendor/plugins/exception_notification/lib/exception_notification/notifier.rb deleted file mode 100644 index 2cab3f963..000000000 --- a/vendor/plugins/exception_notification/lib/exception_notification/notifier.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'pathname' - -# Copyright (c) 2005 Jamis Buck -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -class ExceptionNotification::Notifier < ActionMailer::Base - self.mailer_name = 'exception_notifier' - self.view_paths << "#{File.dirname(__FILE__)}/../../views" - - # next line is a hack to fix - # undefined method `find_template' for #<Array:0x000001009cd230> - # after Rails 2.3.8 -> 2.3.11 upgrade - self.view_paths = ActionView::PathSet.new(self.view_paths) unless self.view_paths.respond_to?(:find_template) - - @@sender_address = %("Exception Notifier" <exception.notifier@default.com>) - cattr_accessor :sender_address - - @@exception_recipients = [] - cattr_accessor :exception_recipients - - @@email_prefix = "[ERROR] " - cattr_accessor :email_prefix - - @@sections = %w(request session environment backtrace) - cattr_accessor :sections - - def self.reloadable?() false end - - def exception_notification(exception, controller, request, data={}) - source = self.class.exception_source(controller) - content_type "text/plain" - - subject "#{email_prefix}#{source} (#{exception.class}) #{exception.message.inspect}" - - recipients exception_recipients - from sender_address - - body data.merge({ :controller => controller, :request => request, - :exception => exception, :exception_source => source, :host => (request.env["HTTP_X_FORWARDED_HOST"] || request.env["HTTP_HOST"]), - :backtrace => sanitize_backtrace(exception.backtrace), - :rails_root => rails_root, :data => data, - :sections => sections }) - end - - def self.exception_source(controller) - if controller.respond_to?(:controller_name) - "in #{controller.controller_name}##{controller.action_name}" - else - "outside of a controller" - end - end - -private - - def sanitize_backtrace(trace) - re = Regexp.new(/^#{Regexp.escape(rails_root)}/) - trace.map { |line| Pathname.new(line.gsub(re, "[RAILS_ROOT]")).cleanpath.to_s } - end - - def rails_root - @rails_root ||= Pathname.new(RAILS_ROOT).cleanpath.to_s - end -end diff --git a/vendor/plugins/exception_notification/lib/exception_notification/notifier_helper.rb b/vendor/plugins/exception_notification/lib/exception_notification/notifier_helper.rb deleted file mode 100644 index 942e1c527..000000000 --- a/vendor/plugins/exception_notification/lib/exception_notification/notifier_helper.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'pp' - -# Copyright (c) 2005 Jamis Buck -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -module ExceptionNotification::NotifierHelper - PARAM_FILTER_REPLACEMENT = "[FILTERED]" - - def render_section(section) - RAILS_DEFAULT_LOGGER.info("rendering section #{section.inspect}") - summary = render("exception_notifier/#{section}").strip - unless summary.blank? - title = render("exception_notifier/title", :locals => { :title => section }).strip - "#{title}\n\n#{summary.gsub(/^/, " ")}\n\n" - end - end - - def inspect_model_object(model, locals={}) - render('exception_notifier/inspect_model', - :locals => { :inspect_model => model, - :show_instance_variables => true, - :show_attributes => true }.merge(locals)) - end - - def inspect_value(value) - len = 512 - result = object_to_yaml(value).gsub(/\n/, "\n ").strip - result = result[0,len] + "... (#{result.length-len} bytes more)" if result.length > len+20 - result - end - - def object_to_yaml(object) - object.to_yaml.sub(/^---\s*/m, "") - end - - def exclude_raw_post_parameters? - @controller && @controller.respond_to?(:filter_parameters) - end - - def filter_sensitive_post_data_parameters(parameters) - exclude_raw_post_parameters? ? @controller.__send__(:filter_parameters, parameters) : parameters - end - - def filter_sensitive_post_data_from_env(env_key, env_value) - return env_value unless exclude_raw_post_parameters? - return PARAM_FILTER_REPLACEMENT if (env_key =~ /RAW_POST_DATA/i) - return @controller.__send__(:filter_parameters, {env_key => env_value}).values[0] - end - -end diff --git a/vendor/plugins/exception_notification/test/exception_notifier_helper_test.rb b/vendor/plugins/exception_notification/test/exception_notifier_helper_test.rb deleted file mode 100644 index e077f405b..000000000 --- a/vendor/plugins/exception_notification/test/exception_notifier_helper_test.rb +++ /dev/null @@ -1,62 +0,0 @@ -require 'test_helper' -require 'exception_notification/notifier_helper' - -class ExceptionNotifierHelperTest < Test::Unit::TestCase - - class ExceptionNotifierHelperIncludeTarget - include ExceptionNotification::NotifierHelper - end - - def setup - @helper = ExceptionNotifierHelperIncludeTarget.new - end - - # No controller - - def test_should_not_exclude_raw_post_parameters_if_no_controller - assert !@helper.exclude_raw_post_parameters? - end - - # Controller, no filtering - - class ControllerWithoutFilterParameters; end - - def test_should_not_filter_env_values_for_raw_post_data_keys_if_controller_can_not_filter_parameters - stub_controller(ControllerWithoutFilterParameters.new) - assert @helper.filter_sensitive_post_data_from_env("RAW_POST_DATA", "secret").include?("secret") - end - def test_should_not_exclude_raw_post_parameters_if_controller_can_not_filter_parameters - stub_controller(ControllerWithoutFilterParameters.new) - assert !@helper.exclude_raw_post_parameters? - end - def test_should_return_params_if_controller_can_not_filter_parameters - stub_controller(ControllerWithoutFilterParameters.new) - assert_equal :params, @helper.filter_sensitive_post_data_parameters(:params) - end - - # Controller with filtering - - class ControllerWithFilterParameters - def filter_parameters(params) - { "PARAM" => ExceptionNotification::NotifierHelper::PARAM_FILTER_REPLACEMENT } - end - end - - def test_should_filter_env_values_for_raw_post_data_keys_if_controller_can_filter_parameters - stub_controller(ControllerWithFilterParameters.new) - assert !@helper.filter_sensitive_post_data_from_env("RAW_POST_DATA", "secret").include?("secret") - end - def test_should_exclude_raw_post_parameters_if_controller_can_filter_parameters - stub_controller(ControllerWithFilterParameters.new) - assert @helper.exclude_raw_post_parameters? - end - def test_should_delegate_param_filtering_to_controller_if_controller_can_filter_parameters - stub_controller(ControllerWithFilterParameters.new) - assert_equal({"PARAM" => "[FILTERED]" }, @helper.filter_sensitive_post_data_parameters({"PARAM" => 'secret'})) - end - - private - def stub_controller(controller) - @helper.instance_variable_set(:@controller, controller) - end -end
\ No newline at end of file diff --git a/vendor/plugins/exception_notification/test/test_helper.rb b/vendor/plugins/exception_notification/test/test_helper.rb deleted file mode 100644 index 5831a1784..000000000 --- a/vendor/plugins/exception_notification/test/test_helper.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'test/unit' -require 'rubygems' -require 'active_support' - -RAILS_ROOT = '.' unless defined?(RAILS_ROOT) - -$:.unshift File.join(File.dirname(__FILE__), '../lib') -require 'exception_notification'
\ No newline at end of file diff --git a/vendor/plugins/exception_notification/views/exception_notifier/_backtrace.rhtml b/vendor/plugins/exception_notification/views/exception_notifier/_backtrace.rhtml deleted file mode 100644 index 7d13ba007..000000000 --- a/vendor/plugins/exception_notification/views/exception_notifier/_backtrace.rhtml +++ /dev/null @@ -1 +0,0 @@ -<%= @backtrace.join "\n" %> diff --git a/vendor/plugins/exception_notification/views/exception_notifier/_environment.rhtml b/vendor/plugins/exception_notification/views/exception_notifier/_environment.rhtml deleted file mode 100644 index 42dd803f1..000000000 --- a/vendor/plugins/exception_notification/views/exception_notifier/_environment.rhtml +++ /dev/null @@ -1,7 +0,0 @@ -<% max = @request.env.keys.max { |a,b| a.length <=> b.length } -%> -<% @request.env.keys.sort.each do |key| -%> -* <%= "%-*s: %s" % [max.length, key, filter_sensitive_post_data_from_env(key, @request.env[key].to_s.strip)] %> -<% end -%> - -* Process: <%= $$ %> -* Server : <%= `hostname -s`.chomp %> diff --git a/vendor/plugins/exception_notification/views/exception_notifier/_inspect_model.rhtml b/vendor/plugins/exception_notification/views/exception_notifier/_inspect_model.rhtml deleted file mode 100644 index e817847e4..000000000 --- a/vendor/plugins/exception_notification/views/exception_notifier/_inspect_model.rhtml +++ /dev/null @@ -1,16 +0,0 @@ -<% if show_attributes -%> -[attributes] -<% attrs = inspect_model.attributes -%> -<% max = attrs.keys.max { |a,b| a.length <=> b.length } -%> -<% attrs.keys.sort.each do |attr| -%> -* <%= "%*-s: %s" % [max.length, attr, object_to_yaml(attrs[attr]).gsub(/\n/, "\n ").strip] %> -<% end -%> -<% end -%> - -<% if show_instance_variables -%> -[instance variables] -<% inspect_model.instance_variables.sort.each do |variable| -%> -<%- next if variable == "@attributes" -%> -* <%= variable %>: <%= inspect_value(inspect_model.instance_variable_get(variable)) %> -<% end -%> -<% end -%> diff --git a/vendor/plugins/exception_notification/views/exception_notifier/_request.rhtml b/vendor/plugins/exception_notification/views/exception_notifier/_request.rhtml deleted file mode 100644 index 25423093f..000000000 --- a/vendor/plugins/exception_notification/views/exception_notifier/_request.rhtml +++ /dev/null @@ -1,4 +0,0 @@ -* URL : <%= @request.protocol %><%= @host %><%= @request.request_uri %> -* IP address: <%= @request.env["HTTP_X_FORWARDED_FOR"] || @request.env["REMOTE_ADDR"] %> -* Parameters: <%= filter_sensitive_post_data_parameters(@request.parameters).inspect %> -* Rails root: <%= @rails_root %> diff --git a/vendor/plugins/exception_notification/views/exception_notifier/_session.rhtml b/vendor/plugins/exception_notification/views/exception_notifier/_session.rhtml deleted file mode 100644 index 308684885..000000000 --- a/vendor/plugins/exception_notification/views/exception_notifier/_session.rhtml +++ /dev/null @@ -1,2 +0,0 @@ -* session id: <%= @request.session_options[:id] %> -* data: <%= @request.session.inspect %>
\ No newline at end of file diff --git a/vendor/plugins/exception_notification/views/exception_notifier/_title.rhtml b/vendor/plugins/exception_notification/views/exception_notifier/_title.rhtml deleted file mode 100644 index 1ed5a3f2b..000000000 --- a/vendor/plugins/exception_notification/views/exception_notifier/_title.rhtml +++ /dev/null @@ -1,3 +0,0 @@ -------------------------------- -<%= title.to_s.humanize %>: -------------------------------- diff --git a/vendor/plugins/exception_notification/views/exception_notifier/exception_notification.rhtml b/vendor/plugins/exception_notification/views/exception_notifier/exception_notification.rhtml deleted file mode 100644 index 715c105bf..000000000 --- a/vendor/plugins/exception_notification/views/exception_notifier/exception_notification.rhtml +++ /dev/null @@ -1,6 +0,0 @@ -A <%= @exception.class %> occurred <%= @exception_source %>: - - <%= @exception.message %> - <%= @backtrace.first %> - -<%= @sections.map { |section| render_section(section) }.join %> diff --git a/vendor/plugins/globalize2/LICENSE b/vendor/plugins/globalize2/LICENSE deleted file mode 100644 index 94a6b8160..000000000 --- a/vendor/plugins/globalize2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License - -Copyright (c) 2008, 2009 Joshua Harvey - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE.
\ No newline at end of file diff --git a/vendor/plugins/globalize2/README.textile b/vendor/plugins/globalize2/README.textile deleted file mode 100644 index e47e9bf37..000000000 --- a/vendor/plugins/globalize2/README.textile +++ /dev/null @@ -1,86 +0,0 @@ -h1. Globalize2 - -Globalize2 is the successor of Globalize for Rails. - -It is compatible with and builds on the new "I18n api in Ruby on Rails":http://guides.rubyonrails.org/i18n.html. and adds model translations to ActiveRecord. - -Globalize2 is much more lightweight and compatible than its predecessor was. Model translations in Globalize2 use default ActiveRecord features and do not limit any ActiveRecord functionality any more. - -h2. Requirements - -ActiveRecord -I18n - -(or Rails > 2.2) - -h2. Installation - -To install Globalize2 with its default setup just use: - -<pre><code> -script/plugin install git://github.com/joshmh/globalize2.git -</code></pre> - -h2. Model translations - -Model translations allow you to translate your models' attribute values. E.g. - -<pre><code> -class Post < ActiveRecord::Base - translates :title, :text -end -</code></pre> - -Allows you to values for the attributes :title and :text per locale: - -<pre><code> -I18n.locale = :en -post.title # => Globalize2 rocks! - -I18n.locale = :he -post.title # => גלובאלייז2 שולט! -</code></pre> - -In order to make this work, you'll need to add the appropriate translation tables. Globalize2 comes with a handy helper method to help you do this. It's called @create_translation_table!@. Here's an example: - -<pre><code> -class CreatePosts < ActiveRecord::Migration - def self.up - create_table :posts do |t| - t.timestamps - end - Post.create_translation_table! :title => :string, :text => :text - end - def self.down - drop_table :posts - Post.drop_translation_table! - end -end -</code></pre> - -Note that the ActiveRecord model @Post@ must already exist and have a @translates@ directive listing the translated fields. - -h2. Migration from Globalize - -See this script by Tomasz Stachewicz: http://gist.github.com/120867 - -h2. Changes since Globalize2 v0.1.0 - -* The association globalize_translations has been renamed to translations. - -h2. Alternative Solutions - -* "Veger's fork":http://github.com/veger/globalize2 - uses default AR schema for the default locale, delegates to the translations table for other locales only -* "TranslatableColumns":http://github.com/iain/translatable_columns - have multiple languages of the same attribute in a model (Iain Hecker) -* "localized_record":http://github.com/glennpow/localized_record - allows records to have localized attributes without any modifications to the database (Glenn Powell) -* "model_translations":http://github.com/janne/model_translations - Minimal implementation of Globalize2 style model translations (Jan Andersson) - -h2. Related solutions - -* "globalize2_versioning":http://github.com/joshmh/globalize2_versioning - acts_as_versioned style versioning for Globalize2 (Joshua Harvey) -* "i18n_multi_locales_validations":http://github.com/ZenCocoon/i18n_multi_locales_validations - multi-locales attributes validations to validates attributes from Globalize2 translations models (Sébastien Grosjean) -* "Globalize2 Demo App":http://github.com/svenfuchs/globalize2-demo - demo application for Globalize2 (Sven Fuchs)</li> -* "migrate_from_globalize1":http://gist.github.com/120867 - migrate model translations from Globalize1 to Globalize2 (Tomasz Stachewicz)</li> -* "easy_globalize2_accessors":http://github.com/astropanic/easy_globalize2_accessors - easily access (read and write) globalize2-translated fields (astropanic, Tomasz Stachewicz)</li> -* "globalize2-easy-translate":http://github.com/bsamman/globalize2-easy-translate - adds methods to easily access or set translated attributes to your model (bsamman)</li> -* "batch_translations":http://github.com/alvarezrilla/batch_translations - allow saving multiple Globalize2 translations in the same request (Jose Alvarez Rilla)</li> diff --git a/vendor/plugins/globalize2/Rakefile b/vendor/plugins/globalize2/Rakefile deleted file mode 100644 index bc35dada4..000000000 --- a/vendor/plugins/globalize2/Rakefile +++ /dev/null @@ -1,39 +0,0 @@ -require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the globalize2 plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the globalize2 plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'Globalize2' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end - -begin - require 'jeweler' - Jeweler::Tasks.new do |s| - s.name = "globalize2" - s.summary = "Rails I18n: de-facto standard library for ActiveRecord data translation" - s.description = "Rails I18n: de-facto standard library for ActiveRecord data translation" - s.email = "joshmh@gmail.com" - s.homepage = "http://github.com/joshmh/globalize2" - # s.rubyforge_project = '' - s.authors = ["Sven Fuchs, Joshua Harvey, Clemens Kofler, John-Paul Bader"] - # s.add_development_dependency '' - end - Jeweler::GemcutterTasks.new -rescue LoadError - puts "Jeweler not available. Install it with: sudo gem install technicalpickles-jeweler -s http://gems.github.com" -end diff --git a/vendor/plugins/globalize2/VERSION b/vendor/plugins/globalize2/VERSION deleted file mode 100644 index 0c62199f1..000000000 --- a/vendor/plugins/globalize2/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.2.1 diff --git a/vendor/plugins/globalize2/generators/db_backend.rb b/vendor/plugins/globalize2/generators/db_backend.rb deleted file mode 100644 index e69de29bb..000000000 --- a/vendor/plugins/globalize2/generators/db_backend.rb +++ /dev/null diff --git a/vendor/plugins/globalize2/generators/templates/db_backend_migration.rb b/vendor/plugins/globalize2/generators/templates/db_backend_migration.rb deleted file mode 100644 index 0f0261113..000000000 --- a/vendor/plugins/globalize2/generators/templates/db_backend_migration.rb +++ /dev/null @@ -1,25 +0,0 @@ -class ActsAsTaggableMigration < ActiveRecord::Migration - def self.up - create_table :globalize_translations do |t| - t.string :locale, :null => false - t.string :key, :null => false - t.string :translation - t.timestamps - end - -# TODO: FINISH DOING MIGRATION -- stopped in the middle - - create_table :globalize_translations_map do |t| - t.string :key, :null => false - t.integer :translation_id, :null => false - end - - add_index :taggings, :tag_id - add_index :taggings, [:taggable_id, :taggable_type] - end - - def self.down - drop_table :globalize_translations - drop_table :tags - end -end diff --git a/vendor/plugins/globalize2/globalize2.gemspec b/vendor/plugins/globalize2/globalize2.gemspec deleted file mode 100644 index 89021115e..000000000 --- a/vendor/plugins/globalize2/globalize2.gemspec +++ /dev/null @@ -1,81 +0,0 @@ -# Generated by jeweler -# DO NOT EDIT THIS FILE DIRECTLY -# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command -# -*- encoding: utf-8 -*- - -Gem::Specification.new do |s| - s.name = %q{globalize2} - s.version = "0.2.0" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.authors = ["Sven Fuchs, Joshua Harvey, Clemens Kofler, John-Paul Bader"] - s.date = %q{2010-04-22} - s.description = %q{Rails I18n: de-facto standard library for ActiveRecord data translation} - s.email = %q{joshmh@gmail.com} - s.extra_rdoc_files = [ - "LICENSE", - "README.textile" - ] - s.files = [ - ".gitignore", - "LICENSE", - "README.textile", - "Rakefile", - "VERSION", - "generators/db_backend.rb", - "generators/templates/db_backend_migration.rb", - "globalize2.gemspec", - "init.rb", - "lib/globalize.rb", - "lib/globalize/active_record.rb", - "lib/globalize/active_record/adapter.rb", - "lib/globalize/active_record/attributes.rb", - "lib/globalize/active_record/migration.rb", - "lib/i18n/missing_translations_log_handler.rb", - "lib/i18n/missing_translations_raise_handler.rb", - "test/active_record/fallbacks_test.rb", - "test/active_record/migration_test.rb", - "test/active_record/sti_translated_test.rb", - "test/active_record/translates_test.rb", - "test/active_record/translation_class_test.rb", - "test/active_record/validation_tests.rb", - "test/active_record_test.rb", - "test/all.rb", - "test/data/models.rb", - "test/data/no_globalize_schema.rb", - "test/data/schema.rb", - "test/i18n/missing_translations_test.rb", - "test/test_helper.rb" - ] - s.homepage = %q{http://github.com/joshmh/globalize2} - s.rdoc_options = ["--charset=UTF-8"] - s.require_paths = ["lib"] - s.rubygems_version = %q{1.3.6} - s.summary = %q{Rails I18n: de-facto standard library for ActiveRecord data translation} - s.test_files = [ - "test/active_record/fallbacks_test.rb", - "test/active_record/migration_test.rb", - "test/active_record/sti_translated_test.rb", - "test/active_record/translates_test.rb", - "test/active_record/translation_class_test.rb", - "test/active_record/validation_tests.rb", - "test/active_record_test.rb", - "test/all.rb", - "test/data/models.rb", - "test/data/no_globalize_schema.rb", - "test/data/schema.rb", - "test/i18n/missing_translations_test.rb", - "test/test_helper.rb" - ] - - if s.respond_to? :specification_version then - current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION - s.specification_version = 3 - - if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then - else - end - else - end -end - diff --git a/vendor/plugins/globalize2/init.rb b/vendor/plugins/globalize2/init.rb deleted file mode 100644 index a4089251b..000000000 --- a/vendor/plugins/globalize2/init.rb +++ /dev/null @@ -1 +0,0 @@ -require 'globalize' diff --git a/vendor/plugins/globalize2/lib/globalize.rb b/vendor/plugins/globalize2/lib/globalize.rb deleted file mode 100644 index 67c1878ec..000000000 --- a/vendor/plugins/globalize2/lib/globalize.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Globalize - autoload :ActiveRecord, 'globalize/active_record' - - class << self - def fallbacks? - I18n.respond_to?(:fallbacks) - end - - def fallbacks(locale) - fallbacks? ? I18n.fallbacks[locale] : [locale.to_sym] - end - end -end - -ActiveRecord::Base.send(:include, Globalize::ActiveRecord) diff --git a/vendor/plugins/globalize2/lib/globalize/active_record.rb b/vendor/plugins/globalize2/lib/globalize/active_record.rb deleted file mode 100644 index 3095bfe28..000000000 --- a/vendor/plugins/globalize2/lib/globalize/active_record.rb +++ /dev/null @@ -1,238 +0,0 @@ -module Globalize - class MigrationError < StandardError; end - class MigrationMissingTranslatedField < MigrationError; end - class BadMigrationFieldType < MigrationError; end - - module ActiveRecord - autoload :Adapter, 'globalize/active_record/adapter' - autoload :Attributes, 'globalize/active_record/attributes' - autoload :Migration, 'globalize/active_record/migration' - - def self.included(base) - base.extend ActMacro - end - - class << self - def build_translation_class(target, options) - options[:table_name] ||= "#{target.table_name.singularize}_translations" - - klass = target.const_defined?(:Translation) ? - target.const_get(:Translation) : - target.const_set(:Translation, Class.new(::ActiveRecord::Base)) - - klass.class_eval do - set_table_name(options[:table_name]) - belongs_to target.name.underscore.gsub('/', '_') - def locale; read_attribute(:locale).to_sym; end - def locale=(locale); write_attribute(:locale, locale.to_s); end - end - - klass - end - end - - module ActMacro - def locale - (defined?(@@locale) && @@locale) - end - - def locale=(locale) - @@locale = locale - end - - def translates(*attr_names) - return if translates? - options = attr_names.extract_options! - - class_inheritable_accessor :translation_class, :translated_attribute_names - class_inheritable_writer :required_attributes - self.translation_class = ActiveRecord.build_translation_class(self, options) - self.translated_attribute_names = attr_names.map(&:to_sym) - - include InstanceMethods - extend ClassMethods, Migration - - after_save :save_translations! - ActiveSupport::Deprecation.silence do - # Silence the warning that :class_name is deprecated and will be - # removed in Rails 3, since it clutters up e.g. test output, and - # there is nothing obvious that we can replace it with in Rails 2. - - has_many :translations, :class_name => translation_class.name, - :foreign_key => class_name.foreign_key, - :dependent => :delete_all, - :extend => HasManyExtensions - end - - named_scope :with_translations, lambda { |locale| - conditions = required_attributes.map do |attribute| - "#{quoted_translation_table_name}.#{attribute} IS NOT NULL" - end - conditions << "#{quoted_translation_table_name}.locale = ?" - { :include => :translations, :conditions => [conditions.join(' AND '), locale] } - } - - attr_names.each { |attr_name| translated_attr_accessor(attr_name) } - end - - def translates? - included_modules.include?(InstanceMethods) - end - end - - module HasManyExtensions - def by_locale(locale) - first(:conditions => { :locale => locale.to_s }) - end - - def by_locales(locales) - all(:conditions => { :locale => locales.map(&:to_s) }) - end - end - - module ClassMethods - delegate :set_translation_table_name, :to => :translation_class - - def with_locale(locale) - begin - previous_locale, self.locale = self.locale, locale - result = yield - ensure - self.locale = previous_locale - end - result - end - - def translation_table_name - translation_class.table_name - end - - def quoted_translation_table_name - translation_class.quoted_table_name - end - - def required_attributes - @required_attributes ||= reflect_on_all_validations.select do |validation| - validation.macro == :validates_presence_of && translated_attribute_names.include?(validation.name) - end.map(&:name) - end - - def respond_to?(method, *args, &block) - method.to_s =~ /^find_by_(\w+)$/ && translated_attribute_names.include?($1.to_sym) || super - end - - def method_missing(method, *args) - if method.to_s =~ /^find_by_(\w+)$/ && translated_attribute_names.include?($1.to_sym) - find_first_by_translated_attr_and_locales($1, args.first) - elsif method.to_s =~ /^find_all_by_(\w+)$/ && translated_attribute_names.include?($1.to_sym) - find_all_by_translated_attr_and_locales($1, args.first) - else - super - end - end - - protected - - def find_first_by_translated_attr_and_locales(name, value) - query = "#{translated_attr_name(name)} = ? AND #{translated_attr_name('locale')} IN (?)" - locales = Globalize.fallbacks(locale || I18n.locale).map(&:to_s) - find( - :first, - :joins => :translations, - :conditions => [query, value, locales], - :readonly => false - ) - end - - def find_all_by_translated_attr_and_locales(name, value) - query = "#{translated_attr_name(name)} = ? AND #{translated_attr_name('locale')} IN (?)" - locales = Globalize.fallbacks(locale || I18n.locale).map(&:to_s) - find( - :all, - :joins => :translations, - :conditions => [query, value, locales], - :readonly => false - ) - end - - def translated_attr_accessor(name) - define_method "#{name}=", lambda { |value| - globalize.write(self.class.locale || I18n.locale, name, value) - self[name] = value - } - define_method name, lambda { |*args| - globalize.fetch(args.first || self.class.locale || I18n.locale, name) - } - alias_method "#{name}_before_type_cast", name - end - - def translated_attr_name(name) - "#{translation_class.table_name}.#{name}" - end - end - - module InstanceMethods - def globalize - @globalize ||= Adapter.new self - end - - def attributes - self.attribute_names.inject({}) do |attrs, name| - attrs[name] = read_attribute(name) || - (globalize.fetch(I18n.locale, name) rescue nil) - attrs - end - end - - def attributes=(attributes, *args) - if attributes.respond_to?(:delete) && locale = attributes.delete(:locale) - self.class.with_locale(locale) { super } - else - super - end - end - - def attribute_names - translated_attribute_names.map(&:to_s) + super - end - - def available_locales - translations.scoped(:select => 'DISTINCT locale').map(&:locale) - end - - def translated_locales - translations.map(&:locale) - end - - def translated_attributes - translated_attribute_names.inject({}) do |attributes, name| - attributes.merge(name => send(name)) - end - end - - def set_translations(options) - options.keys.each do |locale| - translation = translations.find_by_locale(locale.to_s) || - translations.build(:locale => locale.to_s) - translation.update_attributes!(options[locale]) - end - end - - def reload(options = nil) - translated_attribute_names.each { |name| @attributes.delete(name.to_s) } - globalize.reset - super(options) - end - - protected - - def save_translations! - globalize.save_translations! - end - end - end -end - -def globalize_write(name, value) - globalize.write(self.class.locale || I18n.locale, name, value) -end diff --git a/vendor/plugins/globalize2/lib/globalize/active_record/adapter.rb b/vendor/plugins/globalize2/lib/globalize/active_record/adapter.rb deleted file mode 100644 index 12f89ec01..000000000 --- a/vendor/plugins/globalize2/lib/globalize/active_record/adapter.rb +++ /dev/null @@ -1,80 +0,0 @@ -module Globalize - module ActiveRecord - class Adapter - # The cache caches attributes that already were looked up for read access. - # The stash keeps track of new or changed values that need to be saved. - attr_reader :record, :cache, :stash - - def initialize(record) - @record = record - @cache = Attributes.new - @stash = Attributes.new - end - - def fetch(locale, attr_name) - cache.contains?(locale, attr_name) ? - cache.read(locale, attr_name) : - cache.write(locale, attr_name, fetch_attribute(locale, attr_name)) - end - - def write(locale, attr_name, value) - stash.write(locale, attr_name, value) - cache.write(locale, attr_name, value) - end - - def save_translations! - stash.each do |locale, attrs| - translation = record.translations.find_or_initialize_by_locale(locale.to_s) - attrs.each { |attr_name, value| translation[attr_name] = value } - translation.save! - end - stash.clear - end - - def reset - cache.clear - # stash.clear - end - - protected - - def fetch_translation(locale) - locale = locale.to_sym - record.translations.loaded? ? record.translations.detect { |t| t.locale == locale } : - record.translations.by_locale(locale) - end - - def fetch_translations(locale) - # only query if not already included with :include => translations - record.translations.loaded? ? record.translations : - record.translations.by_locales(Globalize.fallbacks(locale)) - end - - def fetch_attribute(locale, attr_name) - translations = fetch_translations(locale) - value, requested_locale = nil, locale - - Globalize.fallbacks(locale).each do |fallback| - translation = translations.detect { |t| t.locale == fallback } - value = translation && translation.send(attr_name) - locale = fallback && break if value - end - - set_metadata(value, :locale => locale, :requested_locale => requested_locale) - value - end - - def set_metadata(object, metadata) - if object.respond_to?(:translation_metadata) - object.translation_metadata.merge!(meta_data) - end - end - - def translation_metadata_accessor(object) - return if obj.respond_to?(:translation_metadata) - class << object; attr_accessor :translation_metadata end - object.translation_metadata ||= {} - end - end - end -end diff --git a/vendor/plugins/globalize2/lib/globalize/active_record/attributes.rb b/vendor/plugins/globalize2/lib/globalize/active_record/attributes.rb deleted file mode 100644 index 7bd923ce2..000000000 --- a/vendor/plugins/globalize2/lib/globalize/active_record/attributes.rb +++ /dev/null @@ -1,25 +0,0 @@ -# Helper class for storing values per locale. Used by Globalize::Adapter -# to stash and cache attribute values. -module Globalize - module ActiveRecord - class Attributes < Hash - def [](locale) - locale = locale.to_sym - self[locale] = {} unless has_key?(locale) - self.fetch(locale) - end - - def contains?(locale, attr_name) - self[locale].has_key?(attr_name) - end - - def read(locale, attr_name) - self[locale][attr_name] - end - - def write(locale, attr_name, value) - self[locale][attr_name] = value - end - end - end -end diff --git a/vendor/plugins/globalize2/lib/globalize/active_record/migration.rb b/vendor/plugins/globalize2/lib/globalize/active_record/migration.rb deleted file mode 100644 index fa63aed8c..000000000 --- a/vendor/plugins/globalize2/lib/globalize/active_record/migration.rb +++ /dev/null @@ -1,44 +0,0 @@ -module Globalize - module ActiveRecord - module Migration - def create_translation_table!(fields) - translated_attribute_names.each do |f| - raise MigrationMissingTranslatedField, "Missing translated field #{f}" unless fields[f] - end - - fields.each do |name, type| - if translated_attribute_names.include?(name) && ![:string, :text].include?(type) - raise BadMigrationFieldType, "Bad field type for #{name}, should be :string or :text" - end - end - - self.connection.create_table(translation_table_name) do |t| - t.references table_name.sub(/^#{table_name_prefix}/, "").singularize - t.string :locale - fields.each do |name, type| - t.column name, type - end - t.timestamps - end - - self.connection.add_index( - translation_table_name, - "#{table_name.sub(/^#{table_name_prefix}/, "").singularize}_id", - :name => translation_index_name - ) - end - - def translation_index_name - require 'digest/sha1' - # FIXME what's the max size of an index name? - index_name = "index_#{translation_table_name}_on_#{self.table_name.singularize}_id" - index_name.size < 50 ? index_name : "index_#{Digest::SHA1.hexdigest(index_name)}" - end - - def drop_translation_table! - self.connection.remove_index(translation_table_name, :name => translation_index_name) rescue nil - self.connection.drop_table(translation_table_name) - end - end - end -end diff --git a/vendor/plugins/globalize2/lib/i18n/missing_translations_log_handler.rb b/vendor/plugins/globalize2/lib/i18n/missing_translations_log_handler.rb deleted file mode 100644 index 24c10890a..000000000 --- a/vendor/plugins/globalize2/lib/i18n/missing_translations_log_handler.rb +++ /dev/null @@ -1,41 +0,0 @@ -# A simple exception handler that behaves like the default exception handler -# but additionally logs missing translations to a given log. -# -# Useful for identifying missing translations during testing. -# -# E.g. -# -# require 'globalize/i18n/missing_translations_log_handler' -# I18n.missing_translations_logger = RAILS_DEFAULT_LOGGER -# I18n.exception_handler = :missing_translations_log_handler -# -# To set up a different log file: -# -# logger = Logger.new("#{RAILS_ROOT}/log/missing_translations.log") -# I18n.missing_translations_logger = logger - -module I18n - @@missing_translations_logger = nil - - class << self - def missing_translations_logger - @@missing_translations_logger ||= begin - require 'logger' unless defined?(Logger) - Logger.new(STDOUT) - end - end - - def missing_translations_logger=(logger) - @@missing_translations_logger = logger - end - - def missing_translations_log_handler(exception, locale, key, options) - if MissingTranslationData === exception - missing_translations_logger.warn(exception.message) - return exception.message - else - raise exception - end - end - end -end diff --git a/vendor/plugins/globalize2/lib/i18n/missing_translations_raise_handler.rb b/vendor/plugins/globalize2/lib/i18n/missing_translations_raise_handler.rb deleted file mode 100644 index 18237b151..000000000 --- a/vendor/plugins/globalize2/lib/i18n/missing_translations_raise_handler.rb +++ /dev/null @@ -1,25 +0,0 @@ -# A simple exception handler that behaves like the default exception handler -# but also raises on missing translations. -# -# Useful for identifying missing translations during testing. -# -# E.g. -# -# require 'globalize/i18n/missing_translations_raise_handler' -# I18n.exception_handler = :missing_translations_raise_handler -module I18n - class << self - def missing_translations_raise_handler(exception, locale, key, options) - raise exception - end - end -end - -I18n.exception_handler = :missing_translations_raise_handler - -ActionView::Helpers::TranslationHelper.module_eval do - def translate(key, options = {}) - I18n.translate(key, options) - end - alias :t :translate -end diff --git a/vendor/plugins/globalize2/test/active_record/fallbacks_test.rb b/vendor/plugins/globalize2/test/active_record/fallbacks_test.rb deleted file mode 100644 index 449ec8b2b..000000000 --- a/vendor/plugins/globalize2/test/active_record/fallbacks_test.rb +++ /dev/null @@ -1,102 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../test_helper') -require File.expand_path(File.dirname(__FILE__) + '/../data/models') - -if I18n.respond_to?(:fallbacks) - class TranslatedTest < ActiveSupport::TestCase - def setup - I18n.locale = :'en-US' - I18n.fallbacks.clear - reset_db! - ActiveRecord::Base.locale = nil - end - - def teardown - I18n.fallbacks.clear - end - - test "keeping one field in new locale when other field is changed" do - I18n.fallbacks.map 'de-DE' => [ 'en-US' ] - post = Post.create :subject => 'foo' - I18n.locale = 'de-DE' - post.content = 'bar' - assert_equal 'foo', post.subject - end - - test "modifying non-required field in a new locale" do - I18n.fallbacks.map 'de-DE' => [ 'en-US' ] - post = Post.create :subject => 'foo' - I18n.locale = 'de-DE' - post.content = 'bar' - assert post.save - end - - test "resolves a simple fallback" do - I18n.locale = 'de-DE' - post = Post.create :subject => 'foo' - I18n.locale = 'de' - post.subject = 'baz' - post.content = 'bar' - post.save - I18n.locale = 'de-DE' - assert_equal 'foo', post.subject - assert_equal 'bar', post.content - end - - test "resolves a simple fallback without reloading" do - I18n.locale = 'de-DE' - post = Post.new :subject => 'foo' - I18n.locale = 'de' - post.subject = 'baz' - post.content = 'bar' - I18n.locale = 'de-DE' - assert_equal 'foo', post.subject - assert_equal 'bar', post.content - end - - test "resolves a complex fallback without reloading" do - I18n.fallbacks.map 'de' => %w(en he) - I18n.locale = 'de' - post = Post.new - I18n.locale = 'en' - post.subject = 'foo' - I18n.locale = 'he' - post.subject = 'baz' - post.content = 'bar' - I18n.locale = 'de' - assert_equal 'foo', post.subject - assert_equal 'bar', post.content - end - - test 'fallbacks with lots of locale switching' do - I18n.fallbacks.map :'de-DE' => [ :'en-US' ] - post = Post.create :subject => 'foo' - - I18n.locale = :'de-DE' - assert_equal 'foo', post.subject - - I18n.locale = :'en-US' - post.update_attribute :subject, 'bar' - - I18n.locale = :'de-DE' - assert_equal 'bar', post.subject - end - - test 'fallbacks with lots of locale switching' do - I18n.fallbacks.map :'de-DE' => [ :'en-US' ] - child = Child.create :content => 'foo' - - I18n.locale = :'de-DE' - assert_equal 'foo', child.content - - I18n.locale = :'en-US' - child.update_attribute :content, 'bar' - - I18n.locale = :'de-DE' - assert_equal 'bar', child.content - end - end -end - -# TODO should validate_presence_of take fallbacks into account? maybe we need -# an extra validation call, or more options for validate_presence_of. - diff --git a/vendor/plugins/globalize2/test/active_record/migration_test.rb b/vendor/plugins/globalize2/test/active_record/migration_test.rb deleted file mode 100644 index 359d811f0..000000000 --- a/vendor/plugins/globalize2/test/active_record/migration_test.rb +++ /dev/null @@ -1,118 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../test_helper') -require File.expand_path(File.dirname(__FILE__) + '/../data/models') - -class MigrationTest < ActiveSupport::TestCase - def setup - reset_db! - Post.drop_translation_table! - end - - test 'globalize table added' do - assert !Post.connection.table_exists?(:post_translations) - assert !Post.connection.index_exists?(:post_translations, :post_id) - - Post.create_translation_table!(:subject => :string, :content => :text) - assert Post.connection.table_exists?(:post_translations) - assert Post.connection.index_exists?(:post_translations, :post_id) - - columns = Post.connection.columns(:post_translations) - assert locale = columns.detect { |c| c.name == 'locale' } - assert_equal :string, locale.type - assert subject = columns.detect { |c| c.name == 'subject' } - assert_equal :string, subject.type - assert content = columns.detect { |c| c.name == 'content' } - assert_equal :text, content.type - assert post_id = columns.detect { |c| c.name == 'post_id' } - assert_equal :integer, post_id.type - assert created_at = columns.detect { |c| c.name == 'created_at' } - assert_equal :datetime, created_at.type - assert updated_at = columns.detect { |c| c.name == 'updated_at' } - assert_equal :datetime, updated_at.type - end - - test 'globalize table dropped' do - assert !Post.connection.table_exists?( :post_translations ) - assert !Post.connection.index_exists?( :post_translations, :post_id ) - Post.create_translation_table! :subject => :string, :content => :text - assert Post.connection.table_exists?( :post_translations ) - assert Post.connection.index_exists?( :post_translations, :post_id ) - Post.drop_translation_table! - assert !Post.connection.table_exists?( :post_translations ) - assert !Post.connection.index_exists?( :post_translations, :post_id ) - end - - test 'exception on missing field inputs' do - assert_raise Globalize::MigrationMissingTranslatedField do - Post.create_translation_table! :content => :text - end - end - - test 'exception on bad input type' do - assert_raise Globalize::BadMigrationFieldType do - Post.create_translation_table! :subject => :string, :content => :integer - end - end - - test "exception on bad input type isn't raised for untranslated fields" do - assert_nothing_raised do - Post.create_translation_table! :subject => :string, :content => :string, :views_count => :integer - end - end - - test 'create_translation_table! should not be called on non-translated models' do - assert_raise NoMethodError do - Blog.create_translation_table! :name => :string - end - end - - test 'drop_translation_table! should not be called on non-translated models' do - assert_raise NoMethodError do - Blog.drop_translation_table! - end - end - - test "translation_index_name returns a readable index name when it's not longer than 50 characters" do - assert_equal 'index_post_translations_on_post_id', Post.send(:translation_index_name) - end - - test "translation_index_name returns a hashed index name when it's longer than 50 characters" do - class UltraLongModelNameWithoutProper < ActiveRecord::Base - translates :foo - end - name = UltraLongModelNameWithoutProper.send(:translation_index_name) - assert_match /^index_[a-z0-9]{40}$/, name - end - - test 'globalize table added when table has long name' do - UltraLongModelNameWithoutProper.create_translation_table!( - :subject => :string, :content => :text - ) - - assert UltraLongModelNameWithoutProper.connection.table_exists?( - :ultra_long_model_name_without_proper_translations - ) - assert UltraLongModelNameWithoutProper.connection.index_exists?( - :ultra_long_model_name_without_proper_translations, - :name => UltraLongModelNameWithoutProper.send( - :translation_index_name - ) - ) - end - - test 'globalize table dropped when table has long name' do - UltraLongModelNameWithoutProper.drop_translation_table! - UltraLongModelNameWithoutProper.create_translation_table!( - :subject => :string, :content => :text - ) - UltraLongModelNameWithoutProper.drop_translation_table! - - assert !UltraLongModelNameWithoutProper.connection.table_exists?( - :ultra_long_model_name_without_proper_translations - ) - assert !UltraLongModelNameWithoutProper.connection.index_exists?( - :ultra_long_model_name_without_proper_translations, - :ultra_long_model_name_without_proper_id - ) - end - -end diff --git a/vendor/plugins/globalize2/test/active_record/sti_translated_test.rb b/vendor/plugins/globalize2/test/active_record/sti_translated_test.rb deleted file mode 100644 index f529b8d6e..000000000 --- a/vendor/plugins/globalize2/test/active_record/sti_translated_test.rb +++ /dev/null @@ -1,49 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../test_helper') -require File.expand_path(File.dirname(__FILE__) + '/../data/models') - -class StiTranslatedTest < ActiveSupport::TestCase - def setup - I18n.locale = :'en-US' - reset_db! - end - - test "works with simple dynamic finders" do - foo = Child.create :content => 'foo' - Child.create :content => 'bar' - child = Child.find_by_content('foo') - assert_equal foo, child - end - - test 'change attribute on globalized model' do - child = Child.create :content => 'foo' - assert_equal [], child.changed - child.content = 'bar' - assert_equal [ 'content' ], child.changed - child.content = 'baz' - assert_member 'content', child.changed - end - - test 'change attribute on globalized model after locale switching' do - child = Child.create :content => 'foo' - assert_equal [], child.changed - child.content = 'bar' - I18n.locale = :de - assert_equal [ 'content' ], child.changed - end - - test "saves all locales, even after locale switching" do - child = Child.new :content => 'foo' - I18n.locale = 'de-DE' - child.content = 'bar' - I18n.locale = 'he-IL' - child.content = 'baz' - child.save - I18n.locale = 'en-US' - child = Child.first - assert_equal 'foo', child.content - I18n.locale = 'de-DE' - assert_equal 'bar', child.content - I18n.locale = 'he-IL' - assert_equal 'baz', child.content - end -end diff --git a/vendor/plugins/globalize2/test/active_record/translates_test.rb b/vendor/plugins/globalize2/test/active_record/translates_test.rb deleted file mode 100644 index 1831063fb..000000000 --- a/vendor/plugins/globalize2/test/active_record/translates_test.rb +++ /dev/null @@ -1,96 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../test_helper') -require File.expand_path(File.dirname(__FILE__) + '/../data/models') - -class TranslatesTest < ActiveSupport::TestCase - def setup - I18n.locale = nil - ActiveRecord::Base.locale = nil - reset_db! - end - - test 'defines a :locale accessors on ActiveRecord::Base' do - ActiveRecord::Base.locale = :de - assert_equal :de, ActiveRecord::Base.locale - end - - test 'the :locale reader on ActiveRecord::Base does not default to I18n.locale (anymore)' do - I18n.locale = :en - assert_nil ActiveRecord::Base.locale - end - - test 'ActiveRecord::Base.with_locale temporarily sets the given locale and yields the block' do - I18n.locale = :en - post = Post.with_locale(:de) do - Post.create!(:subject => 'Titel', :content => 'Inhalt') - end - assert_nil Post.locale - assert_equal :en, I18n.locale - - I18n.locale = :de - assert_equal 'Titel', post.subject - end - - test 'translation_class returns the Translation class' do - assert_equal Post::Translation, Post.translation_class - end - - test 'defines a has_many association on the model class' do - assert_has_many Post, :translations - end - - test 'defines a scope for retrieving locales that have complete translations' do - post = Post.create!(:subject => 'subject', :content => 'content') - assert_equal [:en], post.translated_locales - end - - test 'sets the given attributes to translated_attribute_names' do - assert_equal [:subject, :content], Post.translated_attribute_names - end - - test 'defines accessors for the translated attributes' do - post = Post.new - assert post.respond_to?(:subject) - assert post.respond_to?(:subject=) - end - - test 'attribute reader without arguments will use the current locale on ActiveRecord::Base or I18n' do - post = Post.with_locale(:de) do - Post.create!(:subject => 'Titel', :content => 'Inhalt') - end - I18n.locale = :de - assert_equal 'Titel', post.subject - - I18n.locale = :en - ActiveRecord::Base.locale = :de - assert_equal 'Titel', post.subject - end - - test 'attribute reader when passed a locale will use the given locale' do - post = Post.with_locale(:de) do - Post.create!(:subject => 'Titel', :content => 'Inhalt') - end - assert_equal 'Titel', post.subject(:de) - end - - test 'attribute reader will use the current locale on ActiveRecord::Base or I18n' do - post = Post.with_locale(:en) do - Post.create!(:subject => 'title', :content => 'content') - end - I18n.locale = :de - post.subject = 'Titel' - assert_equal 'Titel', post.subject - - ActiveRecord::Base.locale = :en - post.subject = 'title' - assert_equal 'title', post.subject - end - - test "find_by_xx records have writable attributes" do - Post.create :subject => "change me" - p = Post.find_by_subject("change me") - p.subject = "changed" - assert_nothing_raised(ActiveRecord::ReadOnlyRecord) do - p.save - end - end -end diff --git a/vendor/plugins/globalize2/test/active_record/translation_class_test.rb b/vendor/plugins/globalize2/test/active_record/translation_class_test.rb deleted file mode 100644 index 1628416d7..000000000 --- a/vendor/plugins/globalize2/test/active_record/translation_class_test.rb +++ /dev/null @@ -1,30 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../test_helper') -require File.expand_path(File.dirname(__FILE__) + '/../data/models') - -class TranlationClassTest < ActiveSupport::TestCase - def setup - reset_db! - end - - test 'defines a Translation class nested in the model class' do - assert Post.const_defined?(:Translation) - end - - test 'defines a belongs_to association' do - assert_belongs_to Post::Translation, :post - end - - test 'defines a reader for :locale that always returns a symbol' do - post = Post::Translation.new - post.write_attribute('locale', 'de') - assert_equal :de, post.locale - end - - test 'defines a write for :locale that always writes a string' do - post = Post::Translation.new - post.locale = :de - assert_equal 'de', post.read_attribute('locale') - end -end - - diff --git a/vendor/plugins/globalize2/test/active_record/validation_tests.rb b/vendor/plugins/globalize2/test/active_record/validation_tests.rb deleted file mode 100644 index 0148fa384..000000000 --- a/vendor/plugins/globalize2/test/active_record/validation_tests.rb +++ /dev/null @@ -1,75 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../test_helper') -require File.expand_path(File.dirname(__FILE__) + '/../data/models') - -class ValidationTest < ActiveSupport::TestCase - def setup - reset_db! - end - - def teardown - Validatee.instance_variable_set(:@validate_callbacks, CallbackChain.new) - end - - test "validates_presence_of" do - Validatee.class_eval { validates_presence_of :string } - assert !Validatee.new.valid? - assert Validatee.new(:string => 'foo').valid? - end - - test "validates_confirmation_of" do - Validatee.class_eval { validates_confirmation_of :string } - assert !Validatee.new(:string => 'foo', :string_confirmation => 'bar').valid? - assert Validatee.new(:string => 'foo', :string_confirmation => 'foo').valid? - end - - test "validates_acceptance_of" do - Validatee.class_eval { validates_acceptance_of :string, :accept => '1' } - assert !Validatee.new(:string => '0').valid? - assert Validatee.new(:string => '1').valid? - end - - test "validates_length_of (:is)" do - Validatee.class_eval { validates_length_of :string, :is => 1 } - assert !Validatee.new(:string => 'aa').valid? - assert Validatee.new(:string => 'a').valid? - end - - test "validates_format_of" do - Validatee.class_eval { validates_format_of :string, :with => /^\d+$/ } - assert !Validatee.new(:string => 'a').valid? - assert Validatee.new(:string => '1').valid? - end - - test "validates_inclusion_of" do - Validatee.class_eval { validates_inclusion_of :string, :in => %(a) } - assert !Validatee.new(:string => 'b').valid? - assert Validatee.new(:string => 'a').valid? - end - - test "validates_exclusion_of" do - Validatee.class_eval { validates_exclusion_of :string, :in => %(b) } - assert !Validatee.new(:string => 'b').valid? - assert Validatee.new(:string => 'a').valid? - end - - test "validates_numericality_of" do - Validatee.class_eval { validates_numericality_of :string } - assert !Validatee.new(:string => 'a').valid? - assert Validatee.new(:string => '1').valid? - end - - # This doesn't pass and Rails' validates_uniqueness_of implementation doesn't - # seem to be extensible easily. One can work around that by either defining - # a custom validation on the Validatee model itself, or by using validates_uniqueness_of - # on Validatee::Translation. - # - # test "validates_uniqueness_of" do - # Validatee.class_eval { validates_uniqueness_of :string } - # Validatee.create!(:string => 'a') - # assert !Validatee.new(:string => 'a').valid? - # assert Validatee.new(:string => 'b').valid? - # end - - # test "validates_associated" do - # end -end
\ No newline at end of file diff --git a/vendor/plugins/globalize2/test/active_record_test.rb b/vendor/plugins/globalize2/test/active_record_test.rb deleted file mode 100644 index 38e247e17..000000000 --- a/vendor/plugins/globalize2/test/active_record_test.rb +++ /dev/null @@ -1,467 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/test_helper') -require File.expand_path(File.dirname(__FILE__) + '/data/models') - -# Higher level tests. - -class ActiveRecordTest < ActiveSupport::TestCase - def setup - I18n.locale = :en - reset_db! - ActiveRecord::Base.locale = nil - end - - def assert_translated(locale, record, names, expected) - I18n.locale = locale - assert_equal Array(expected), Array(names).map { |name| record.send(name) } - end - - test "a translated record has translations" do - assert_equal [], Post.new.translations - end - - test "saves a translated version of the record for each locale" do - post = Post.create(:subject => 'title') - I18n.locale = :de - post.update_attributes(:subject => 'Titel') - - assert_equal 2, post.translations.size - assert_equal %w(de en), post.translations.map(&:locale).map(&:to_s).sort - assert_equal %w(Titel title), post.translations.map(&:subject).sort - end - - test "a translated record has German translations" do - I18n.locale = :de - post = Post.create(:subject => 'foo') - assert_equal 1, post.translations.size - assert_equal [:de], post.translations.map { |t| t.locale } - end - - test "modifiying translated fields while switching locales" do - post = Post.create(:subject => 'title', :content => 'content') - assert_equal %w(title content), [post.subject, post.content] - - I18n.locale = :de - post.subject, post.content = 'Titel', 'Inhalt' - - assert_translated(:de, post, [:subject, :content], %w(Titel Inhalt)) - assert_translated(:en, post, [:subject, :content], %w(title content)) - assert_translated(:de, post, [:subject, :content], %w(Titel Inhalt)) - - post.save - post.reload - - assert_translated(:en, post, [:subject, :content], %w(title content)) - assert_translated(:de, post, [:subject, :content], %w(Titel Inhalt)) - end - - test "attribute writers do return their argument" do - value = Post.new.subject = 'foo' - assert_equal 'foo', value - end - - test "update_attribute succeeds with valid values" do - post = Post.create(:subject => 'foo', :content => 'bar') - post.update_attribute(:subject, 'baz') - assert_equal 'baz', Post.first.subject - end - - test "update_attributes fails with invalid values" do - post = Post.create(:subject => 'foo', :content => 'bar') - assert !post.update_attributes(:subject => '') - assert_not_nil post.reload.attributes['subject'] - assert_equal 'foo', post.subject - end - - test "passing the locale to create uses the given locale" do - post = Post.create(:subject => 'Titel', :content => 'Inhalt', :locale => :de) - assert_equal :en, I18n.locale - assert_nil ActiveRecord::Base.locale - - I18n.locale = :de - assert_equal 'Titel', post.subject - end - - test "passing the locale to attributes= uses the given locale" do - post = Post.create(:subject => 'title', :content => 'content') - post.update_attributes(:subject => 'Titel', :content => 'Inhalt', :locale => :de) - post.reload - - assert_equal :en, I18n.locale - assert_nil ActiveRecord::Base.locale - - assert_equal 'title', post.subject - I18n.locale = :de - assert_equal 'Titel', post.subject - end - - test 'reload works' do - post = Post.create(:subject => 'foo', :content => 'bar') - post.subject = 'baz' - post.reload - assert_equal 'foo', post.subject - end - - test "returns nil if no translations are found (unsaved record)" do - post = Post.new(:subject => 'foo') - assert_equal 'foo', post.subject - assert_nil post.content - end - - test "returns nil if no translations are found (saved record)" do - post = Post.create(:subject => 'foo') - post.reload - assert_equal 'foo', post.subject - assert_nil post.content - end - - test "finds a German post" do - post = Post.create(:subject => 'foo (en)', :content => 'bar') - I18n.locale = :de - post = Post.first - post.subject = 'baz (de)' - post.save - assert_equal 'baz (de)', Post.first.subject - I18n.locale = :en - assert_equal 'foo (en)', Post.first.subject - end - - test "saves an English post and loads correctly" do - post = Post.create(:subject => 'foo', :content => 'bar') - assert post.save - post = Post.first - assert_equal 'foo', post.subject - assert_equal 'bar', post.content - end - - test "returns the value for the correct locale, after locale switching" do - post = Post.create(:subject => 'foo') - I18n.locale = :de - post.subject = 'bar' - post.save - I18n.locale = :en - post = Post.first - assert_equal 'foo', post.subject - I18n.locale = :de - assert_equal 'bar', post.subject - end - - test "returns the value for the correct locale, after locale switching, without saving" do - post = Post.create :subject => 'foo' - I18n.locale = :de - post.subject = 'bar' - I18n.locale = :en - assert_equal 'foo', post.subject - I18n.locale = :de - assert_equal 'bar', post.subject - end - - test "saves all locales, even after locale switching" do - post = Post.new :subject => 'foo' - I18n.locale = :de - post.subject = 'bar' - I18n.locale = :he - post.subject = 'baz' - post.save - I18n.locale = :en - post = Post.first - assert_equal 'foo', post.subject - I18n.locale = :de - assert_equal 'bar', post.subject - I18n.locale = :he - assert_equal 'baz', post.subject - end - - test "works with associations" do - blog = Blog.create - post1 = blog.posts.create(:subject => 'foo') - - I18n.locale = :de - post2 = blog.posts.create(:subject => 'bar') - assert_equal 2, blog.posts.size - - I18n.locale = :en - assert_equal 'foo', blog.posts.first.subject - assert_nil blog.posts.last.subject - - I18n.locale = :de - assert_equal 'bar', blog.posts.last.subject - end - - test "works with simple dynamic finders" do - foo = Post.create(:subject => 'foo') - Post.create(:subject => 'bar') - post = Post.find_by_subject('foo') - assert_equal foo, post - end - - test 'change attribute on globalized model' do - post = Post.create(:subject => 'foo', :content => 'bar') - assert_equal [], post.changed - post.subject = 'baz' - assert_equal ['subject'], post.changed - post.content = 'quux' - assert_member 'subject', post.changed - assert_member 'content', post.changed - end - - test 'change attribute on globalized model after locale switching' do - post = Post.create(:subject => 'foo', :content => 'bar') - assert_equal [], post.changed - post.subject = 'baz' - I18n.locale = :de - assert_equal ['subject'], post.changed - end - - test 'complex writing and stashing' do - post = Post.create(:subject => 'foo', :content => 'bar') - post.subject = nil - assert_nil post.subject - assert !post.valid? - post.subject = 'stashed_foo' - assert_equal 'stashed_foo', post.subject - end - - test 'translated class locale setting' do - assert ActiveRecord::Base.respond_to?(:locale) - assert_equal :en, I18n.locale - assert_nil ActiveRecord::Base.locale - - I18n.locale = :de - assert_equal :de, I18n.locale - assert_nil ActiveRecord::Base.locale - - ActiveRecord::Base.locale = :es - assert_equal :de, I18n.locale - assert_equal :es, ActiveRecord::Base.locale - - I18n.locale = :fr - assert_equal :fr, I18n.locale - assert_equal :es, ActiveRecord::Base.locale - end - - test "untranslated class responds to locale" do - assert Blog.respond_to?(:locale) - end - - test "to ensure locales in different classes are the same" do - ActiveRecord::Base.locale = :de - assert_equal :de, ActiveRecord::Base.locale - assert_equal :de, Parent.locale - - Parent.locale = :es - assert_equal :es, ActiveRecord::Base.locale - assert_equal :es, Parent.locale - end - - test "attribute saving goes by content locale and not global locale" do - ActiveRecord::Base.locale = :de - assert_equal :en, I18n.locale - Post.create :subject => 'foo' - assert_equal :de, Post.first.translations.first.locale - end - - test "attribute loading goes by content locale and not global locale" do - post = Post.create(:subject => 'foo') - assert_nil ActiveRecord::Base.locale - - ActiveRecord::Base.locale = :de - assert_equal :en, I18n.locale - post.update_attribute(:subject, 'foo [de]') - assert_equal 'foo [de]', Post.first.subject - - ActiveRecord::Base.locale = :en - assert_equal 'foo', Post.first.subject - end - - test "access content locale before setting" do - Globalize::ActiveRecord::ActMacro.class_eval "remove_class_variable(:@@locale)" - assert_nothing_raised { ActiveRecord::Base.locale } - end - - test "available_locales" do - Post.locale = :de - post = Post.create(:subject => 'foo') - Post.locale = :es - post.update_attribute(:subject, 'bar') - Post.locale = :fr - post.update_attribute(:subject, 'baz') - assert_equal [:de, :es, :fr], post.available_locales - assert_equal [:de, :es, :fr], Post.first.available_locales - end - - test "saving record correctly after post-save reload" do - reloader = Reloader.create(:content => 'foo') - assert_equal 'foo', reloader.content - end - - test "including translations" do - I18n.locale = :de - Post.create(:subject => "Foo1", :content => "Bar1") - Post.create(:subject => "Foo2", :content => "Bar2") - - class << Post - def translations_included - self.all(:include => :translations) - end - end - - default = Post.all.map { |x| [x.subject, x.content] } - with_include = Post.translations_included.map { |x| [x.subject, x.content] } - assert_equal default, with_include - end - - test "setting multiple translations at once with options hash" do - Post.locale = :de - post = Post.create(:subject => "foo1", :content => "foo1") - Post.locale = :en - post.update_attributes(:subject => "bar1", :content => "bar1") - - options = { :de => {:subject => "foo2", :content => "foo2"}, - :en => {:subject => "bar2", :content => "bar2"} } - post.set_translations options - post.reload - - assert ["bar2", "bar2"], [post.subject, post.content] - Post.locale = :de - assert ["foo2", "foo2"], [post.subject, post.content] - end - - test "setting only one translation with set_translations" do - Post.locale = :de - post = Post.create(:subject => "foo1", :content => "foo1") - Post.locale = :en - post.update_attributes(:subject => "bar1", :content => "bar1") - - options = { :en => { :subject => "bar2", :content => "bar2" } } - post.set_translations options - post.reload - - assert ["bar2", "bar2"], [post.subject, post.content] - Post.locale = :de - assert ["foo1", "foo1"], [post.subject, post.content] - end - - test "setting only selected attributes with set_translations" do - Post.locale = :de - post = Post.create(:subject => "foo1", :content => "foo1") - Post.locale = :en - post.update_attributes(:subject => "bar1", :content => "bar1") - - options = { :de => { :content => "foo2" }, :en => { :subject => "bar2" } } - post.set_translations options - post.reload - - assert ["bar2", "bar1"], [post.subject, post.content] - Post.locale = :de - assert ["foo1", "foo2"], [post.subject, post.content] - end - - test "setting invalid attributes raises ArgumentError" do - Post.locale = :de - post = Post.create(:subject => "foo1", :content => "foo1") - Post.locale = :en - post.update_attributes(:subject => "bar1", :content => "bar1") - - options = { :de => {:fake => "foo2"} } - exception = assert_raise(ActiveRecord::UnknownAttributeError) do - post.set_translations options - end - assert_equal "unknown attribute: fake", exception.message - end - - test "reload accepting find options" do - p = Post.create(:subject => "Foo", :content => "Bar") - assert p.reload(:readonly => true, :lock => true) - assert_raise(ArgumentError) { p.reload(:foo => :bar) } - end - - test "dependent destroy of translation" do - p = Post.create(:subject => "Foo", :content => "Bar") - assert_equal 1, PostTranslation.count - p.destroy - assert_equal 0, PostTranslation.count - end - - test "translating subclass of untranslated comment model" do - translated_comment = TranslatedComment.create(:post => @post) - assert_nothing_raised { translated_comment.translations } - end - - test "modifiying translated comments works as expected" do - I18n.locale = :en - translated_comment = TranslatedComment.create(:post => @post, :content => 'foo') - assert_equal 'foo', translated_comment.content - - I18n.locale = :de - translated_comment.content = 'bar' - assert translated_comment.save - assert_equal 'bar', translated_comment.content - - I18n.locale = :en - assert_equal 'foo', translated_comment.content - - assert_equal 2, translated_comment.translations.size - end - - test "can create a proxy class for a namespaced model" do - assert_nothing_raised do - module Foo - module Bar - class Baz < ActiveRecord::Base - translates :bumm - end - end - end - end - end - - test "attribute translated before type cast" do - Post.locale = :en - post = Post.create(:subject => 'foo', :content => 'bar') - Post.locale = :de - post.update_attribute(:subject, "German foo") - assert_equal 'German foo', post.subject_before_type_cast - Post.locale = :en - assert_equal 'foo', post.subject_before_type_cast - end - - test "don't override existing translation class" do - assert PostTranslation.new.respond_to?(:existing_method) - end - - test "has_many and named scopes work with globalize" do - blog = Blog.create - assert_nothing_raised { blog.posts.foobar } - end - - test "required_attribuets don't include non-translated attributes" do - validations = [ - stub(:name => :name, :macro => :validates_presence_of), - stub(:name => :email, :macro => :validates_presence_of) - ] - User.expects(:reflect_on_all_validations => validations) - assert_equal [:name], User.required_attributes - end - - test "attribute_names returns translated and regular attribute names" do - Post.create :subject => "foo", :content => "bar" - assert_equal Post.last.attribute_names.sort, %w[blog_id content id subject] - end - - test "attributes returns translated and regular attributes" do - Post.create :subject => "foo", :content => "bar" - assert_equal Post.last.attributes.keys.sort, %w[blog_id content id subject] - end - - test "to_xml includes translated fields" do - Post.create :subject => "foo", :content => "bar" - assert Post.last.to_xml =~ /subject/ - assert Post.last.to_xml =~ /content/ - end -end - -# TODO error checking for fields that exist in main table, don't exist in -# proxy table, aren't strings or text -# -# TODO allow finding by translated attributes in conditions? -# TODO generate advanced dynamic finders? diff --git a/vendor/plugins/globalize2/test/all.rb b/vendor/plugins/globalize2/test/all.rb deleted file mode 100644 index ff467a176..000000000 --- a/vendor/plugins/globalize2/test/all.rb +++ /dev/null @@ -1,2 +0,0 @@ -files = Dir[File.dirname(__FILE__) + '/**/*_test.rb'] -files.each { |file| require file }
\ No newline at end of file diff --git a/vendor/plugins/globalize2/test/data/models.rb b/vendor/plugins/globalize2/test/data/models.rb deleted file mode 100644 index 5408d6e23..000000000 --- a/vendor/plugins/globalize2/test/data/models.rb +++ /dev/null @@ -1,56 +0,0 @@ -#require 'ruby2ruby' -#require 'parse_tree' -#require 'parse_tree_extensions' -#require 'pp' - -class PostTranslation < ActiveRecord::Base - def existing_method ; end -end - -class Post < ActiveRecord::Base - translates :subject, :content - validates_presence_of :subject - named_scope :foobar, :conditions => { :title => "foobar" } -end - -class Blog < ActiveRecord::Base - has_many :posts, :order => 'id ASC' -end - -class Parent < ActiveRecord::Base - translates :content -end - -class Child < Parent -end - -class Comment < ActiveRecord::Base - validates_presence_of :content - belongs_to :post -end - -class TranslatedComment < Comment - translates :content -end - -class UltraLongModelNameWithoutProper < ActiveRecord::Base - translates :subject, :content - validates_presence_of :subject -end - -class Reloader < Parent - after_create :do_reload - - def do_reload - reload - end -end - -class Validatee < ActiveRecord::Base - translates :string -end - -class User < ActiveRecord::Base - translates :name - validates_presence_of :name, :email -end diff --git a/vendor/plugins/globalize2/test/data/no_globalize_schema.rb b/vendor/plugins/globalize2/test/data/no_globalize_schema.rb deleted file mode 100644 index 379455ddb..000000000 --- a/vendor/plugins/globalize2/test/data/no_globalize_schema.rb +++ /dev/null @@ -1,11 +0,0 @@ -# This schema creates tables without columns for the translated fields -ActiveRecord::Schema.define do - create_table :blogs, :force => true do |t| - t.string :name - end - - create_table :posts, :force => true do |t| - t.references :blog - end -end - diff --git a/vendor/plugins/globalize2/test/data/schema.rb b/vendor/plugins/globalize2/test/data/schema.rb deleted file mode 100644 index 910dd0855..000000000 --- a/vendor/plugins/globalize2/test/data/schema.rb +++ /dev/null @@ -1,55 +0,0 @@ -ActiveRecord::Schema.define do - create_table :blogs, :force => true do |t| - t.string :description - end - - create_table :posts, :force => true do |t| - t.references :blog - end - - create_table :post_translations, :force => true do |t| - t.string :locale - t.references :post - t.string :subject - t.text :content - end - - create_table :parents, :force => true do |t| - end - - create_table :parent_translations, :force => true do |t| - t.string :locale - t.references :parent - t.text :content - t.string :type - end - - create_table :comments, :force => true do |t| - t.references :post - end - - create_table :comment_translations, :force => true do |t| - t.string :locale - t.references :comment - t.string :subject - t.text :content - end - - create_table :validatees, :force => true do |t| - end - - create_table :validatee_translations, :force => true do |t| - t.string :locale - t.references :validatee - t.string :string - end - - create_table :users, :force => true do |t| - t.string :email - end - - create_table :users_translations, :force => true do |t| - t.references :user - t.string :name - end -end diff --git a/vendor/plugins/globalize2/test/i18n/missing_translations_test.rb b/vendor/plugins/globalize2/test/i18n/missing_translations_test.rb deleted file mode 100644 index 5d0ecd6fc..000000000 --- a/vendor/plugins/globalize2/test/i18n/missing_translations_test.rb +++ /dev/null @@ -1,36 +0,0 @@ -require File.dirname(__FILE__) + '/../test_helper' -require 'i18n/missing_translations_log_handler' - -class MissingTranslationsTest < ActiveSupport::TestCase - test "defines I18n.missing_translations_logger accessor" do - assert I18n.respond_to?(:missing_translations_logger) - end - - test "defines I18n.missing_translations_logger= writer" do - assert I18n.respond_to?(:missing_translations_logger=) - end -end - -class TestLogger < String - def warn(msg) self.concat msg; end -end - -class LogMissingTranslationsTest < ActiveSupport::TestCase - def setup - @locale, @key, @options = :en, :foo, {} - @exception = I18n::MissingTranslationData.new(@locale, @key, @options) - - @logger = TestLogger.new - I18n.missing_translations_logger = @logger - end - - test "still returns the exception message for MissingTranslationData exceptions" do - result = I18n.send(:missing_translations_log_handler, @exception, @locale, @key, @options) - assert_equal 'translation missing: en, foo', result - end - - test "logs the missing translation to I18n.missing_translations_logger" do - I18n.send(:missing_translations_log_handler, @exception, @locale, @key, @options) - assert_equal 'translation missing: en, foo', @logger - end -end diff --git a/vendor/plugins/globalize2/test/test_helper.rb b/vendor/plugins/globalize2/test/test_helper.rb deleted file mode 100644 index 99a5d3950..000000000 --- a/vendor/plugins/globalize2/test/test_helper.rb +++ /dev/null @@ -1,76 +0,0 @@ -$LOAD_PATH << File.expand_path( File.dirname(__FILE__) + '/../lib' ) - -require 'rubygems' -require 'test/unit' -require 'active_record' -require 'active_support' -require 'active_support/test_case' -require 'mocha' -require 'globalize' -# require 'validation_reflection' - -config = { :adapter => 'sqlite3', :database => ':memory:' } -ActiveRecord::Base.establish_connection(config) - -class ActiveSupport::TestCase - def reset_db!(schema_path = nil) - schema_path ||= File.expand_path(File.dirname(__FILE__) + '/data/schema.rb') - ActiveRecord::Migration.verbose = false - ActiveRecord::Base.silence { load(schema_path) } - end - - def assert_member(item, array) - assert_block "Item #{item} is not in array #{array}" do - array.member?(item) - end - end - - def assert_belongs_to(model, associated) - assert model.reflect_on_all_associations(:belongs_to).detect { |association| - association.name.to_s == associated.to_s - } - end - - def assert_has_many(model, associated) - assert model.reflect_on_all_associations(:has_many).detect { |association| - association.name.to_s == associated.to_s - } - end -end - -module ActiveRecord - module ConnectionAdapters - class AbstractAdapter - def index_exists?(table_name, column_name) - indexes(table_name).any? { |index| index.name == index_name(table_name, column_name) } - end - end - end -end - -# module ActiveRecord -# class BaseWithoutTable < Base -# self.abstract_class = true -# -# def create_or_update -# errors.empty? -# end -# -# class << self -# def columns() -# @columns ||= [] -# end -# -# def column(name, sql_type = nil, default = nil, null = true) -# columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null) -# reset_column_information -# end -# -# # Do not reset @columns -# def reset_column_information -# read_methods.each { |name| undef_method(name) } -# @column_names = @columns_hash = @content_columns = @dynamic_methods_hash = @read_methods = nil -# end -# end -# end -# end
\ No newline at end of file diff --git a/vendor/plugins/has_tag_string/README.txt b/vendor/plugins/has_tag_string/README.txt deleted file mode 100644 index 0d3a38229..000000000 --- a/vendor/plugins/has_tag_string/README.txt +++ /dev/null @@ -1 +0,0 @@ -Plugin used only in WhatDoTheyKnow right now. diff --git a/vendor/plugins/has_tag_string/init.rb b/vendor/plugins/has_tag_string/init.rb deleted file mode 100644 index 4a07073a7..000000000 --- a/vendor/plugins/has_tag_string/init.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'has_tag_string' - diff --git a/vendor/plugins/has_tag_string/lib/has_tag_string.rb b/vendor/plugins/has_tag_string/lib/has_tag_string.rb deleted file mode 100644 index b982bc3a0..000000000 --- a/vendor/plugins/has_tag_string/lib/has_tag_string.rb +++ /dev/null @@ -1,165 +0,0 @@ -# lib/has_tag_string.rb: -# Lets a model have tags, represented as space separate strings in a public -# interface, but stored in the database as keys. Each tag can have a value -# followed by a colon - e.g. url:http://www.flourish.org -# -# Copyright (c) 2010 UK Citizens Online Democracy. All rights reserved. -# Email: francis@mysociety.org; WWW: http://www.mysociety.org/ - -module HasTagString - # Represents one tag of one model. - # The migration to make this is currently only in WDTK code. - class HasTagStringTag < ActiveRecord::Base - # XXX strip_attributes! - - validates_presence_of :name - - # Return instance of the model that this tag tags - def tagged_model - return self.model.constantize.find(self.model_id) - end - - # For display purposes, returns the name and value as a:b, or - # if there is no value just the name a - def name_and_value - ret = self.name - if !self.value.nil? - ret += ":" + self.value - end - return ret - end - - # Parses a text version of one single tag, such as "a:b" and returns - # the name and value, with nil for value if there isn't one. - def HasTagStringTag.split_tag_into_name_value(tag) - sections = tag.split(/:/) - name = sections[0] - if sections[1] - value = sections[1,sections.size].join(":") - else - value = nil - end - return name, value - end - end - - # Methods which are added to the model instances being tagged - module InstanceMethods - # Given an input string of tags, sets all tags to that string. - # XXX This immediately saves the new tags. - def tag_string=(tag_string) - if tag_string.nil? - tag_string = "" - end - - tag_string = tag_string.strip - # split tags apart - tags = tag_string.split(/\s+/).uniq - - ActiveRecord::Base.transaction do - for tag in self.tags - tag.destroy - end - self.tags = [] - for tag in tags - # see if is a machine tags (i.e. a tag which has a value) - name, value = HasTagStringTag.split_tag_into_name_value(tag) - - tag = HasTagStringTag.new( - :model => self.class.base_class.to_s, - :model_id => self.id, - :name => name, :value => value - ) - self.tags << tag - end - end - end - - # Returns the tags the model has, as a space separated string - def tag_string - return self.tags.map { |t| t.name_and_value }.join(' ') - end - - # Returns the tags the model has, as an array of pairs of key/value - # (this can't be a dictionary as you can have multiple instances of a - # key with different values) - def tag_array - return self.tags.map { |t| [t.name, t.value] } - end - - # Returns a list of all the strings someone might want to search for. - # So that is the key by itself, or the key and value. - # e.g. if a request was tagged openlylocal_id:12345, they might - # want to search for "openlylocal_id" or for "openlylocal_id:12345" to find it. - def tag_array_for_search - ret = {} - for tag in self.tags - ret[tag.name] = 1 - ret[tag.name_and_value] = 1 - end - - return ret.keys.sort - end - - # Test to see if class is tagged with the given tag - def has_tag?(tag_as_string) - for tag in self.tags - if tag.name == tag_as_string - return true - end - end - return false - end - - class TagNotFound < StandardError - end - - # If the tag is a machine tag, returns array of its values - def get_tag_values(tag_as_string) - found = false - results = [] - for tag in self.tags - if tag.name == tag_as_string - found = true - if !tag.value.nil? - results << tag.value - end - end - end - if !found - raise TagNotFound - end - return results - end - - # Adds a new tag to the model, if it isn't already there - def add_tag_if_not_already_present(tag_as_string) - self.tag_string = self.tag_string + " " + tag_as_string - end - end - - # Methods which are added to the model class being tagged - module ClassMethods - # Find all public bodies with a particular tag - def find_by_tag(tag_as_string) - return HasTagStringTag.find(:all, :conditions => - ['name = ? and model = ?', tag_as_string, self.to_s ] - ).map { |t| t.tagged_model }.sort { |a,b| a.name <=> b.name }.uniq - end - end - - ###################################################################### - # Main entry point, add has_tag_string to your model. - module HasMethods - def has_tag_string() - has_many :tags, :conditions => "model = '" + self.to_s + "'", :foreign_key => "model_id", :class_name => 'HasTagString::HasTagStringTag' - - include InstanceMethods - self.class.send :include, ClassMethods - end - end - -end - -ActiveRecord::Base.extend HasTagString::HasMethods - diff --git a/vendor/plugins/rails_xss/MIT-LICENSE b/vendor/plugins/rails_xss/MIT-LICENSE deleted file mode 100644 index ed44a7bde..000000000 --- a/vendor/plugins/rails_xss/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 Koziarski Software Ltd. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/rails_xss/README.markdown b/vendor/plugins/rails_xss/README.markdown deleted file mode 100644 index 1222ef38d..000000000 --- a/vendor/plugins/rails_xss/README.markdown +++ /dev/null @@ -1,91 +0,0 @@ -RailsXss -======== - -This plugin replaces the default ERB template handlers with erubis, and switches the behaviour to escape by default rather than requiring you to escape. This is consistent with the behaviour in Rails 3.0. - -Strings now have a notion of "html safe", which is false by default. Whenever rails copies a string into the response body it checks whether or not the string is safe, safe strings are copied verbatim into the response body, but unsafe strings are escaped first. - -All the XSS-proof helpers like link_to and form_tag now return safe strings, and will continue to work unmodified. If you have your own helpers which return strings you *know* are safe, you will need to explicitly tell rails that they're safe. For an example, take the following helper. - - - def some_helper - (1..5).map do |i| - "<li>#{i}</li>" - end.join("\n") - end - -With this plugin installed, the html will be escaped. So you will need to do one of the following: - -1) Use the raw helper in your template. raw will ensure that your string is copied verbatim into the response body. - - <%= raw some_helper %> - -2) Mark the string as safe in the helper itself: - - def some_helper - (1..5).map do |i| - "<li>#{i}</li>" - end.join("\n").html_safe - end - -3) Use the `safe_helper` meta programming method (WARNING: This is not supported by Rails 3, so if you're planning to -eventually upgrade your app this alternative is not recommended): - - module ApplicationHelper - def some_helper - #... - end - safe_helper :some_helper # not supported by Rails 3 - end - -Example -------- - -BEFORE: - - <%= params[:own_me] %> => XSS attack - <%=h params[:own_me] %> => No XSS - <%= @blog_post.content %> => Displays the HTML - -AFTER: - - <%= params[:own_me] %> => No XSS - <%=h params[:own_me] %> => No XSS (same result) - <%= @blog_post.content %> => *escapes* the HTML - <%= raw @blog_post.content %> => Displays the HTML - - -Gotchas ---- - -#### textilize and simple_format do *not* return safe strings - -Both these methods support arbitrary HTML and are *not* safe to embed directly in your document. You'll need to do something like: - - <%= sanitize(textilize(@blog_post.content_textile)) %> - -#### Safe strings aren't magic. - -Once a string has been marked as safe, the only operations which will maintain that HTML safety are String#<<, String#concat and String#+. All other operations are safety ignorant so it's still probably possible to break your app if you're doing something like - - value = something_safe - value.gsub!(/a/, params[:own_me]) - -Don't do that. - -#### String interpolation won't be safe, even when it 'should' be - - value = "#{something_safe}#{something_else_safe}" - value.html_safe? # => false - -This is intended functionality and can't be fixed. - -Getting Started -=============== - -1. Install rails 2.3.8 or higher, or freeze rails from 2-3-stable. -2. Install erubis (gem install erubis) -3. Install this plugin (ruby script/plugin install git://github.com/rails/rails_xss.git) -4. Report anything that breaks. - -Copyright (c) 2009 Koziarski Software Ltd, released under the MIT license. For full details see MIT-LICENSE included in this distribution. diff --git a/vendor/plugins/rails_xss/Rakefile b/vendor/plugins/rails_xss/Rakefile deleted file mode 100644 index 929ecbb81..000000000 --- a/vendor/plugins/rails_xss/Rakefile +++ /dev/null @@ -1,23 +0,0 @@ -require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the rails_xss plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.libs << 'test' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the rails_xss plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'RailsXss' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/vendor/plugins/rails_xss/init.rb b/vendor/plugins/rails_xss/init.rb deleted file mode 100644 index 533eb1f36..000000000 --- a/vendor/plugins/rails_xss/init.rb +++ /dev/null @@ -1,9 +0,0 @@ -unless $gems_rake_task - if Rails::VERSION::MAJOR >= 3 - $stderr.puts "You don't need to install rails_xss as a plugin for Rails 3 and after." - elsif Rails::VERSION::MAJOR <= 2 && Rails::VERSION::MINOR <= 3 && Rails::VERSION::TINY <= 7 - $stderr.puts "rails_xss requires Rails 2.3.8 or later. Please upgrade to enable automatic HTML safety." - else - require 'rails_xss' - end -end diff --git a/vendor/plugins/rails_xss/lib/rails_xss.rb b/vendor/plugins/rails_xss/lib/rails_xss.rb deleted file mode 100644 index 46d1b9a4a..000000000 --- a/vendor/plugins/rails_xss/lib/rails_xss.rb +++ /dev/null @@ -1,3 +0,0 @@ -require 'rails_xss/erubis' -require 'rails_xss/action_view' -require 'rails_xss/string_ext' diff --git a/vendor/plugins/rails_xss/lib/rails_xss/action_view.rb b/vendor/plugins/rails_xss/lib/rails_xss/action_view.rb deleted file mode 100644 index c3f5e47df..000000000 --- a/vendor/plugins/rails_xss/lib/rails_xss/action_view.rb +++ /dev/null @@ -1,111 +0,0 @@ -module ActionView - class Base - def self.xss_safe? - true - end - - module WithSafeOutputBuffer - # Rails version of with_output_buffer uses '' as the default buf - def with_output_buffer(buf = ActiveSupport::SafeBuffer.new) #:nodoc: - super buf - end - end - - include WithSafeOutputBuffer - end - - module Helpers - module CaptureHelper - def content_for(name, content = nil, &block) - ivar = "@content_for_#{name}" - content = capture(&block) if block_given? - instance_variable_set(ivar, "#{instance_variable_get(ivar)}#{ERB::Util.h(content)}".html_safe) - nil - end - end - - module TextHelper - def concat(string, unused_binding = nil) - if unused_binding - ActiveSupport::Deprecation.warn("The binding argument of #concat is no longer needed. Please remove it from your views and helpers.", caller) - end - - output_buffer.concat(string) - end - - def simple_format(text, html_options={}) - start_tag = tag('p', html_options, true) - text = ERB::Util.h(text).to_str.dup - text.gsub!(/\r\n?/, "\n") # \r\n and \r -> \n - text.gsub!(/\n\n+/, "</p>\n\n#{start_tag}") # 2+ newline -> paragraph - text.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />') # 1 newline -> br - text.insert 0, start_tag - text.html_safe.safe_concat("</p>") - end - end - - module TagHelper - private - def content_tag_string_with_escaping(name, content, options, escape = true) - content_tag_string_without_escaping(name, escape ? ERB::Util.h(content) : content, options, escape) - end - alias_method_chain :content_tag_string, :escaping - end - - module UrlHelper - def link_to(*args, &block) - if block_given? - options = args.first || {} - html_options = args.second - concat(link_to(capture(&block), options, html_options)) - else - name = args.first - options = args.second || {} - html_options = args.third - - url = url_for(options) - - if html_options - html_options = html_options.stringify_keys - href = html_options['href'] - convert_options_to_javascript!(html_options, url) - tag_options = tag_options(html_options) - else - tag_options = nil - end - - href_attr = "href=\"#{url}\"" unless href - "<a #{href_attr}#{tag_options}>#{ERB::Util.h(name || url)}</a>".html_safe - end - end - end - - module JavaScriptHelper - def escape_javascript(javascript) - if javascript - javascript.gsub(/(\\|<\/|\r\n|[\n\r"'])/) {|match| JS_ESCAPE_MAP[match] } - else - '' - end - end - end - end -end - -module RailsXss - module SafeHelpers - def safe_helper(*names) - names.each do |helper_method_name| - aliased_target, punctuation = helper_method_name.to_s.sub(/([?!=])$/, ''), $1 - module_eval <<-END - def #{aliased_target}_with_xss_safety#{punctuation}(*args, &block) - raw(#{aliased_target}_without_xss_safety#{punctuation}(*args, &block)) - end - END - alias_method_chain helper_method_name, :xss_safety - end - end - end -end - -Module.class_eval { include RailsXss::SafeHelpers } diff --git a/vendor/plugins/rails_xss/lib/rails_xss/erubis.rb b/vendor/plugins/rails_xss/lib/rails_xss/erubis.rb deleted file mode 100644 index b8a239483..000000000 --- a/vendor/plugins/rails_xss/lib/rails_xss/erubis.rb +++ /dev/null @@ -1,41 +0,0 @@ -# stop erubis from printing it's version number all the time -old_stdout = $stdout -File.open("/dev/null", "w") do |f| - $stdout = f - require 'erubis/helpers/rails_helper' - $stdout = old_stdout -end - -module RailsXss - class Erubis < ::Erubis::Eruby - def add_preamble(src) - src << "@output_buffer = ActiveSupport::SafeBuffer.new;" - end - - def add_text(src, text) - return if text.empty? - src << "@output_buffer.safe_concat('" << escape_text(text) << "');" - end - - BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/ - - def add_expr_literal(src, code) - if code =~ BLOCK_EXPR - src << "@output_buffer.safe_concat((" << $1 << ").to_s);" - else - src << '@output_buffer << ((' << code << ').to_s);' - end - end - - def add_expr_escaped(src, code) - src << '@output_buffer << ' << escaped_expr(code) << ';' - end - - def add_postamble(src) - src << '@output_buffer.to_s' - end - end -end - -Erubis::Helpers::RailsHelper.engine_class = RailsXss::Erubis -Erubis::Helpers::RailsHelper.show_src = false diff --git a/vendor/plugins/rails_xss/lib/rails_xss/string_ext.rb b/vendor/plugins/rails_xss/lib/rails_xss/string_ext.rb deleted file mode 100644 index ee32e47c8..000000000 --- a/vendor/plugins/rails_xss/lib/rails_xss/string_ext.rb +++ /dev/null @@ -1,65 +0,0 @@ -require 'active_support/deprecation' - -ActiveSupport::SafeBuffer.class_eval do - def concat(value) - if value.html_safe? - super(value) - else - super(ERB::Util.h(value)) - end - end - alias << concat - UNSAFE_STRING_METHODS = ["capitalize", "chomp", "chop", "delete", "downcase", "gsub", "lstrip", "next", "reverse", "rstrip", "slice", "squeeze", "strip", "sub", "succ", "swapcase", "tr", "tr_s", "upcase"].freeze - - for unsafe_method in UNSAFE_STRING_METHODS - class_eval <<-EOT, __FILE__, __LINE__ + 1 - def #{unsafe_method}(*args) - super.to_str - end - - def #{unsafe_method}!(*args) - raise TypeError, "Cannot modify SafeBuffer in place" - end - EOT - end -end - -class String - def html_safe? - defined?(@_rails_html_safe) - end - - def html_safe! - ActiveSupport::Deprecation.warn("Use html_safe with your strings instead of html_safe! See http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/ for the full story.", caller) - @_rails_html_safe = true - self - end - - def add_with_safety(other) - result = add_without_safety(other) - if html_safe? && also_html_safe?(other) - result.html_safe! - else - result - end - end - alias_method :add_without_safety, :+ - alias_method :+, :add_with_safety - - def concat_with_safety(other_or_fixnum) - result = concat_without_safety(other_or_fixnum) - unless html_safe? && also_html_safe?(other_or_fixnum) - remove_instance_variable(:@_rails_html_safe) if defined?(@_rails_html_safe) - end - result - end - - alias_method_chain :concat, :safety - undef_method :<< - alias_method :<<, :concat_with_safety - - private - def also_html_safe?(other) - other.respond_to?(:html_safe?) && other.html_safe? - end -end diff --git a/vendor/plugins/rails_xss/lib/tasks/rails_xss_tasks.rake b/vendor/plugins/rails_xss/lib/tasks/rails_xss_tasks.rake deleted file mode 100644 index b8659f089..000000000 --- a/vendor/plugins/rails_xss/lib/tasks/rails_xss_tasks.rake +++ /dev/null @@ -1,4 +0,0 @@ -# desc "Explaining what the task does" -# task :rails_xss do -# # Task goes here -# end diff --git a/vendor/plugins/rails_xss/test/active_record_helper_test.rb b/vendor/plugins/rails_xss/test/active_record_helper_test.rb deleted file mode 100644 index 728ec0ac6..000000000 --- a/vendor/plugins/rails_xss/test/active_record_helper_test.rb +++ /dev/null @@ -1,74 +0,0 @@ -require 'test_helper' - -class ActiveRecordHelperTest < ActionView::TestCase - silence_warnings do - Post = Struct.new("Post", :title, :author_name, :body, :secret, :written_on) - Post.class_eval do - alias_method :title_before_type_cast, :title unless respond_to?(:title_before_type_cast) - alias_method :body_before_type_cast, :body unless respond_to?(:body_before_type_cast) - alias_method :author_name_before_type_cast, :author_name unless respond_to?(:author_name_before_type_cast) - end - end - - def setup_post - @post = Post.new - def @post.errors - Class.new { - def on(field) - case field.to_s - when "author_name" - "can't be empty" - when "body" - true - else - false - end - end - def empty?() false end - def count() 1 end - def full_messages() [ "Author name can't be empty" ] end - }.new - end - - def @post.new_record?() true end - def @post.to_param() nil end - - def @post.column_for_attribute(attr_name) - Post.content_columns.select { |column| column.name == attr_name }.first - end - - silence_warnings do - def Post.content_columns() [ Column.new(:string, "title", "Title"), Column.new(:text, "body", "Body") ] end - end - - @post.title = "Hello World" - @post.author_name = "" - @post.body = "Back to the hill and over it again!" - @post.secret = 1 - @post.written_on = Date.new(2004, 6, 15) - end - - def setup - setup_post - - @response = ActionController::TestResponse.new - - @controller = Object.new - def @controller.url_for(options) - options = options.symbolize_keys - - [options[:action], options[:id].to_param].compact.join('/') - end - end - - def test_text_field_with_errors_is_safe - assert text_field("post", "author_name").html_safe? - end - - def test_text_field_with_errors - assert_dom_equal( - %(<div class="fieldWithErrors"><input id="post_author_name" name="post[author_name]" size="30" type="text" value="" /></div>), - text_field("post", "author_name") - ) - end -end diff --git a/vendor/plugins/rails_xss/test/asset_tag_helper_test.rb b/vendor/plugins/rails_xss/test/asset_tag_helper_test.rb deleted file mode 100644 index f58feda3d..000000000 --- a/vendor/plugins/rails_xss/test/asset_tag_helper_test.rb +++ /dev/null @@ -1,49 +0,0 @@ -require 'test_helper' - -class AssetTagHelperTest < ActionView::TestCase - def setup - @controller = Class.new do - attr_accessor :request - def url_for(*args) "http://www.example.com" end - end.new - end - - def test_auto_discovery_link_tag - assert_dom_equal(%(<link href="http://www.example.com" rel="Not so alternate" title="ATOM" type="application/atom+xml" />), - auto_discovery_link_tag(:atom, {}, {:rel => "Not so alternate"})) - end - - def test_javascript_include_tag_with_blank_asset_id - ENV["RAILS_ASSET_ID"] = "" - assert_dom_equal(%(<script src="/javascripts/test.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), - javascript_include_tag("test", :defaults)) - end - - def test_javascript_include_tag_with_given_asset_id - ENV["RAILS_ASSET_ID"] = "1" - assert_dom_equal(%(<script src="/javascripts/prototype.js?1" type="text/javascript"></script>\n<script src="/javascripts/effects.js?1" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js?1" type="text/javascript"></script>\n<script src="/javascripts/controls.js?1" type="text/javascript"></script>\n<script src="/javascripts/application.js?1" type="text/javascript"></script>), - javascript_include_tag(:defaults)) - ENV["RAILS_ASSET_ID"] = "" - end - - def test_javascript_include_tag_is_html_safe - assert javascript_include_tag(:defaults).html_safe? - assert javascript_include_tag("prototype").html_safe? - end - - def test_stylesheet_link_tag - assert_dom_equal(%(<link href="http://www.example.com/styles/style.css" media="screen" rel="stylesheet" type="text/css" />), - stylesheet_link_tag("http://www.example.com/styles/style")) - end - - def test_stylesheet_link_tag_is_html_safe - assert stylesheet_link_tag('dir/file').html_safe? - assert stylesheet_link_tag('dir/other/file', 'dir/file2').html_safe? - assert stylesheet_tag('dir/file', {}).html_safe? - end - - def test_image_tag - assert_dom_equal(%(<img alt="Mouse" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" src="/images/mouse.png" />), - image_tag("mouse.png", :mouseover => image_path("mouse_over.png"))) - end -end diff --git a/vendor/plugins/rails_xss/test/caching_test.rb b/vendor/plugins/rails_xss/test/caching_test.rb deleted file mode 100644 index 3ea41e8b5..000000000 --- a/vendor/plugins/rails_xss/test/caching_test.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'test_helper' - -CACHE_DIR = 'test_cache' -# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed -FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR) -ActionController::Base.page_cache_directory = FILE_STORE_PATH -ActionController::Base.cache_store = :file_store, FILE_STORE_PATH - -class FragmentCachingTestController < ActionController::Base - def some_action; end; -end - -class FragmentCachingTest < ActionController::TestCase - def setup - ActionController::Base.perform_caching = true - @store = ActiveSupport::Cache::MemoryStore.new - ActionController::Base.cache_store = @store - @controller = FragmentCachingTestController.new - @params = {:controller => 'posts', :action => 'index'} - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller.params = @params - @controller.request = @request - @controller.response = @response - @controller.send(:initialize_current_url) - @controller.send(:initialize_template_class, @response) - @controller.send(:assign_shortcuts, @request, @response) - end - - def test_fragment_for - @store.write('views/expensive', 'fragment content') - fragment_computed = false - - buffer = 'generated till now -> '.html_safe - @controller.fragment_for(buffer, 'expensive') { fragment_computed = true } - - assert !fragment_computed - assert_equal 'generated till now -> fragment content', buffer - end - - def test_html_safety - assert_nil @store.read('views/name') - content = 'value'.html_safe - assert_equal content, @controller.write_fragment('name', content) - - cached = @store.read('views/name') - assert_equal content, cached - assert_equal String, cached.class - - html_safe = @controller.read_fragment('name') - assert_equal content, html_safe - assert html_safe.html_safe? - end -end diff --git a/vendor/plugins/rails_xss/test/content_for_test.rb b/vendor/plugins/rails_xss/test/content_for_test.rb deleted file mode 100644 index 45ba6762c..000000000 --- a/vendor/plugins/rails_xss/test/content_for_test.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'test_helper' - -class ContentForTest < ActionView::TestCase - - def test_content_for_should_yield_html_safe_string - content_for(:testing, "Some <p>html</p>") - content = instance_variable_get(:"@content_for_testing") - assert content.html_safe? - end - - def test_content_for_should_escape_content - content_for(:testing, "Some <p>html</p>") - content = instance_variable_get(:"@content_for_testing") - expected = %{Some <p>html</p>} - assert_dom_equal expected, content - end - - def test_content_for_should_not_escape_html_safe_content - content_for(:testing, "Some <p>html</p>".html_safe) - content = instance_variable_get(:"@content_for_testing") - expected = %{Some <p>html</p>} - assert_dom_equal expected, content - end - - def test_content_for_should_escape_content_from_block - content_for(:testing){ "Some <p>html</p>" } - content = instance_variable_get(:"@content_for_testing") - expected = %{Some <p>html</p>} - assert_dom_equal expected, content - end - - def test_content_for_should_not_escape_html_safe_content_from_block - content_for(:testing){ "Some <p>html</p>".html_safe } - content = instance_variable_get(:"@content_for_testing") - expected = %{Some <p>html</p>} - assert_dom_equal expected, content - end - -end diff --git a/vendor/plugins/rails_xss/test/date_helper_test.rb b/vendor/plugins/rails_xss/test/date_helper_test.rb deleted file mode 100644 index daf010274..000000000 --- a/vendor/plugins/rails_xss/test/date_helper_test.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'test_helper' - -class DateHelperTest < ActionView::TestCase - silence_warnings do - Post = Struct.new("Post", :id, :written_on, :updated_at) - end - - def test_select_html_safety - assert select_day(16).html_safe? - assert select_month(8).html_safe? - assert select_year(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? - assert select_minute(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? - assert select_second(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? - - assert select_minute(8, :use_hidden => true).html_safe? - assert select_month(8, :prompt => 'Choose month').html_safe? - - assert select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector').html_safe? - assert select_date(Time.mktime(2003, 8, 16), :date_separator => " / ", :start_year => 2003, :end_year => 2005, :prefix => "date[first]").html_safe? - end - - def test_object_select_html_safety - @post = Post.new - @post.written_on = Date.new(2004, 6, 15) - - assert date_select("post", "written_on", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true).html_safe? - assert time_select("post", "written_on", :ignore_date => true).html_safe? - end -end diff --git a/vendor/plugins/rails_xss/test/deprecated_output_safety_test.rb b/vendor/plugins/rails_xss/test/deprecated_output_safety_test.rb deleted file mode 100644 index e16f7ce0d..000000000 --- a/vendor/plugins/rails_xss/test/deprecated_output_safety_test.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'test_helper' - -class DeprecatedOutputSafetyTest < ActiveSupport::TestCase - def setup - @string = "hello" - end - - test "A string can be marked safe using html_safe!" do - assert_deprecated do - @string.html_safe! - assert @string.html_safe? - end - end - - test "Marking a string safe returns the string using html_safe!" do - assert_deprecated do - assert_equal @string, @string.html_safe! - end - end - - test "Adding a safe string to another safe string returns a safe string using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @string.html_safe! - @combination = @other_string + @string - - assert_equal "otherhello", @combination - assert @combination.html_safe? - end - end - - test "Adding an unsafe string to a safe string returns an unsafe string using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @combination = @other_string + "<foo>" - @other_combination = @string + "<foo>" - - assert_equal "other<foo>", @combination - assert_equal "hello<foo>", @other_combination - - assert !@combination.html_safe? - assert !@other_combination.html_safe? - end - end - - test "Concatting safe onto unsafe yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other" - @string.html_safe! - - @other_string.concat(@string) - assert !@other_string.html_safe? - end - end - - test "Concatting unsafe onto safe yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - string = @other_string.concat("<foo>") - assert_equal "other<foo>", string - assert !string.html_safe? - end - end - - test "Concatting safe onto safe yields safe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @string.html_safe! - - @other_string.concat(@string) - assert @other_string.html_safe? - end - end - - test "Concatting safe onto unsafe with << yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other" - @string.html_safe! - - @other_string << @string - assert !@other_string.html_safe? - end - end - - test "Concatting unsafe onto safe with << yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - string = @other_string << "<foo>" - assert_equal "other<foo>", string - assert !string.html_safe? - end - end - - test "Concatting safe onto safe with << yields safe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @string.html_safe! - - @other_string << @string - assert @other_string.html_safe? - end - end - - test "Concatting a fixnum to safe always yields safe using html_safe!" do - assert_deprecated do - @string.html_safe! - @string.concat(13) - assert_equal "hello".concat(13), @string - assert @string.html_safe? - end - end -end diff --git a/vendor/plugins/rails_xss/test/erb_util_test.rb b/vendor/plugins/rails_xss/test/erb_util_test.rb deleted file mode 100644 index 9a04d38e6..000000000 --- a/vendor/plugins/rails_xss/test/erb_util_test.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'test_helper' - -class ErbUtilTest < Test::Unit::TestCase - include ERB::Util - - ERB::Util::HTML_ESCAPE.each do |given, expected| - define_method "test_html_escape_#{expected.gsub(/\W/, '')}" do - assert_equal expected, html_escape(given) - end - - unless given == '"' - define_method "test_json_escape_#{expected.gsub(/\W/, '')}" do - assert_equal ERB::Util::JSON_ESCAPE[given], json_escape(given) - end - end - end - - def test_html_escape_is_html_safe - escaped = h("<p>") - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - def test_html_escape_passes_html_escpe_unmodified - escaped = h("<p>".html_safe) - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - def test_rest_in_ascii - (0..127).to_a.map {|int| int.chr }.each do |chr| - next if %w(& " < >).include?(chr) - assert_equal chr, html_escape(chr) - end - end -end diff --git a/vendor/plugins/rails_xss/test/form_helper_test.rb b/vendor/plugins/rails_xss/test/form_helper_test.rb deleted file mode 100644 index e5580d26c..000000000 --- a/vendor/plugins/rails_xss/test/form_helper_test.rb +++ /dev/null @@ -1,1447 +0,0 @@ -require 'test_helper' - -silence_warnings do - Post = Struct.new(:title, :author_name, :body, :secret, :written_on, :cost) - Post.class_eval do - alias_method :title_before_type_cast, :title unless respond_to?(:title_before_type_cast) - alias_method :body_before_type_cast, :body unless respond_to?(:body_before_type_cast) - alias_method :author_name_before_type_cast, :author_name unless respond_to?(:author_name_before_type_cast) - alias_method :secret?, :secret - - def new_record=(boolean) - @new_record = boolean - end - - def new_record? - @new_record - end - - attr_accessor :author - def author_attributes=(attributes); end - - attr_accessor :comments - def comments_attributes=(attributes); end - - attr_accessor :tags - def tags_attributes=(attributes); end - end - - class Comment - attr_reader :id - attr_reader :post_id - def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end - def save; @id = 1; @post_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def name - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - - attr_accessor :relevances - def relevances_attributes=(attributes); end - - end - - class Tag - attr_reader :id - attr_reader :post_id - def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end - def save; @id = 1; @post_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def value - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - - attr_accessor :relevances - def relevances_attributes=(attributes); end - - end - - class CommentRelevance - attr_reader :id - attr_reader :comment_id - def initialize(id = nil, comment_id = nil); @id, @comment_id = id, comment_id end - def save; @id = 1; @comment_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def value - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - end - - class TagRelevance - attr_reader :id - attr_reader :tag_id - def initialize(id = nil, tag_id = nil); @id, @tag_id = id, tag_id end - def save; @id = 1; @tag_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def value - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - end - - class Author < Comment - attr_accessor :post - def post_attributes=(attributes); end - end -end - -class FormHelperTest < ActionView::TestCase - tests ActionView::Helpers::FormHelper - - def setup - super - - # Create "label" locale for testing I18n label helpers - I18n.backend.store_translations 'label', { - :helpers => { - :label => { - :post => { - :body => "Write entire text here" - } - } - } - } - - @post = Post.new - @comment = Comment.new - def @post.errors() - Class.new{ - def on(field); "can't be empty" if field == "author_name"; end - def empty?() false end - def count() 1 end - def full_messages() [ "Author name can't be empty" ] end - }.new - end - def @post.id; 123; end - def @post.id_before_type_cast; 123; end - def @post.to_param; '123'; end - - @post.title = "Hello World" - @post.author_name = "" - @post.body = "Back to the hill and over it again!" - @post.secret = 1 - @post.written_on = Date.new(2004, 6, 15) - - def Post.human_attribute_name(attribute) - attribute.to_s == "cost" ? "Total cost" : attribute.to_s.humanize - end - - @controller = Class.new do - attr_reader :url_for_options - def url_for(options) - @url_for_options = options - "http://www.example.com" - end - end - @controller = @controller.new - end - - def test_label - assert_dom_equal('<label for="post_title">Title</label>', label("post", "title")) - assert_dom_equal('<label for="post_title">The title goes here</label>', label("post", "title", "The title goes here")) - assert_dom_equal( - '<label class="title_label" for="post_title">Title</label>', - label("post", "title", nil, :class => 'title_label') - ) - assert_dom_equal('<label for="post_secret">Secret?</label>', label("post", "secret?")) - end - - def test_label_with_symbols - assert_dom_equal('<label for="post_title">Title</label>', label(:post, :title)) - assert_dom_equal('<label for="post_secret">Secret?</label>', label(:post, :secret?)) - end - - def test_label_with_locales_strings - old_locale, I18n.locale = I18n.locale, :label - assert_dom_equal('<label for="post_body">Write entire text here</label>', label("post", "body")) - ensure - I18n.locale = old_locale - end - - def test_label_with_human_attribute_name - old_locale, I18n.locale = I18n.locale, :label - assert_dom_equal('<label for="post_cost">Total cost</label>', label(:post, :cost)) - ensure - I18n.locale = old_locale - end - - def test_label_with_locales_symbols - old_locale, I18n.locale = I18n.locale, :label - assert_dom_equal('<label for="post_body">Write entire text here</label>', label(:post, :body)) - ensure - I18n.locale = old_locale - end - - def test_label_with_for_attribute_as_symbol - assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for")) - end - - def test_label_with_for_attribute_as_string - assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, "for" => "my_for")) - end - - def test_label_with_id_attribute_as_symbol - assert_dom_equal('<label for="post_title" id="my_id">Title</label>', label(:post, :title, nil, :id => "my_id")) - end - - def test_label_with_id_attribute_as_string - assert_dom_equal('<label for="post_title" id="my_id">Title</label>', label(:post, :title, nil, "id" => "my_id")) - end - - def test_label_with_for_and_id_attributes_as_symbol - assert_dom_equal('<label for="my_for" id="my_id">Title</label>', label(:post, :title, nil, :for => "my_for", :id => "my_id")) - end - - def test_label_with_for_and_id_attributes_as_string - assert_dom_equal('<label for="my_for" id="my_id">Title</label>', label(:post, :title, nil, "for" => "my_for", "id" => "my_id")) - end - - def test_label_for_radio_buttons_with_value - assert_dom_equal('<label for="post_title_great_title">The title goes here</label>', label("post", "title", "The title goes here", :value => "great_title")) - assert_dom_equal('<label for="post_title_great_title">The title goes here</label>', label("post", "title", "The title goes here", :value => "great title")) - end - - def test_text_field - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title") - ) - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="password" value="Hello World" />', password_field("post", "title") - ) - assert_dom_equal( - '<input id="person_name" name="person[name]" size="30" type="password" />', password_field("person", "name") - ) - end - - def test_text_field_with_escapes - @post.title = "<b>Hello World</b>" - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="<b>Hello World</b>" />', text_field("post", "title") - ) - end - - def test_text_field_with_html_entities - @post.title = "The HTML Entity for & is &" - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="The HTML Entity for & is &amp;" />', - text_field("post", "title") - ) - end - - def test_text_field_with_options - expected = '<input id="post_title" name="post[title]" size="35" type="text" value="Hello World" />' - assert_dom_equal expected, text_field("post", "title", "size" => 35) - assert_dom_equal expected, text_field("post", "title", :size => 35) - end - - def test_text_field_assuming_size - expected = '<input id="post_title" maxlength="35" name="post[title]" size="35" type="text" value="Hello World" />' - assert_dom_equal expected, text_field("post", "title", "maxlength" => 35) - assert_dom_equal expected, text_field("post", "title", :maxlength => 35) - end - - def test_text_field_removing_size - expected = '<input id="post_title" maxlength="35" name="post[title]" type="text" value="Hello World" />' - assert_dom_equal expected, text_field("post", "title", "maxlength" => 35, "size" => nil) - assert_dom_equal expected, text_field("post", "title", :maxlength => 35, :size => nil) - end - - def test_text_field_doesnt_change_param_values - object_name = 'post[]' - expected = '<input id="post_123_title" name="post[123][title]" size="30" type="text" value="Hello World" />' - assert_equal expected, text_field(object_name, "title") - assert_equal object_name, "post[]" - end - - def test_hidden_field - assert_dom_equal '<input id="post_title" name="post[title]" type="hidden" value="Hello World" />', - hidden_field("post", "title") - assert_dom_equal '<input id="post_secret" name="post[secret]" type="hidden" value="1" />', - hidden_field("post", "secret?") - end - - def test_hidden_field_with_escapes - @post.title = "<b>Hello World</b>" - assert_dom_equal '<input id="post_title" name="post[title]" type="hidden" value="<b>Hello World</b>" />', - hidden_field("post", "title") - end - - def test_hidden_field_with_options - assert_dom_equal '<input id="post_title" name="post[title]" type="hidden" value="Something Else" />', - hidden_field("post", "title", :value => "Something Else") - end - - def test_check_box - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - @post.secret = 0 - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret" ,{"checked"=>"checked"}) - ) - @post.secret = true - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret?") - ) - - @post.secret = ['0'] - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - @post.secret = ['1'] - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - end - - def test_check_box_with_explicit_checked_and_unchecked_values - @post.secret = "on" - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="off" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" />', - check_box("post", "secret", {}, "on", "off") - ) - end - - def test_checkbox_disabled_still_submits_checked_value - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret", { :disabled => :true }) - ) - end - - def test_radio_button - assert_dom_equal('<input checked="checked" id="post_title_hello_world" name="post[title]" type="radio" value="Hello World" />', - radio_button("post", "title", "Hello World") - ) - assert_dom_equal('<input id="post_title_goodbye_world" name="post[title]" type="radio" value="Goodbye World" />', - radio_button("post", "title", "Goodbye World") - ) - assert_dom_equal('<input id="item_subobject_title_inside_world" name="item[subobject][title]" type="radio" value="inside world"/>', - radio_button("item[subobject]", "title", "inside world") - ) - end - - def test_radio_button_is_checked_with_integers - assert_dom_equal('<input checked="checked" id="post_secret_1" name="post[secret]" type="radio" value="1" />', - radio_button("post", "secret", "1") - ) - end - - def test_radio_button_respects_passed_in_id - assert_dom_equal('<input checked="checked" id="foo" name="post[secret]" type="radio" value="1" />', - radio_button("post", "secret", "1", :id=>"foo") - ) - end - - def test_radio_button_with_booleans - assert_dom_equal('<input id="post_secret_true" name="post[secret]" type="radio" value="true" />', - radio_button("post", "secret", true) - ) - - assert_dom_equal('<input id="post_secret_false" name="post[secret]" type="radio" value="false" />', - radio_button("post", "secret", false) - ) - end - - def test_text_area - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to the hill and over it again!</textarea>', - text_area("post", "body") - ) - end - - def test_text_area_with_escapes - @post.body = "Back to <i>the</i> hill and over it again!" - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to <i>the</i> hill and over it again!</textarea>', - text_area("post", "body") - ) - end - - def test_text_area_with_alternate_value - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Testing alternate values.</textarea>', - text_area("post", "body", :value => 'Testing alternate values.') - ) - end - - def test_text_area_with_html_entities - @post.body = "The HTML Entity for & is &" - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">The HTML Entity for & is &amp;</textarea>', - text_area("post", "body") - ) - end - - def test_text_area_with_size_option - assert_dom_equal( - '<textarea cols="183" id="post_body" name="post[body]" rows="820">Back to the hill and over it again!</textarea>', - text_area("post", "body", :size => "183x820") - ) - end - - def test_explicit_name - assert_dom_equal( - '<input id="post_title" name="dont guess" size="30" type="text" value="Hello World" />', text_field("post", "title", "name" => "dont guess") - ) - assert_dom_equal( - '<textarea cols="40" id="post_body" name="really!" rows="20">Back to the hill and over it again!</textarea>', - text_area("post", "body", "name" => "really!") - ) - assert_dom_equal( - '<input name="i mean it" type="hidden" value="0" /><input checked="checked" id="post_secret" name="i mean it" type="checkbox" value="1" />', - check_box("post", "secret", "name" => "i mean it") - ) - assert_dom_equal text_field("post", "title", "name" => "dont guess"), - text_field("post", "title", :name => "dont guess") - assert_dom_equal text_area("post", "body", "name" => "really!"), - text_area("post", "body", :name => "really!") - assert_dom_equal check_box("post", "secret", "name" => "i mean it"), - check_box("post", "secret", :name => "i mean it") - end - - def test_explicit_id - assert_dom_equal( - '<input id="dont guess" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title", "id" => "dont guess") - ) - assert_dom_equal( - '<textarea cols="40" id="really!" name="post[body]" rows="20">Back to the hill and over it again!</textarea>', - text_area("post", "body", "id" => "really!") - ) - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="i mean it" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret", "id" => "i mean it") - ) - assert_dom_equal text_field("post", "title", "id" => "dont guess"), - text_field("post", "title", :id => "dont guess") - assert_dom_equal text_area("post", "body", "id" => "really!"), - text_area("post", "body", :id => "really!") - assert_dom_equal check_box("post", "secret", "id" => "i mean it"), - check_box("post", "secret", :id => "i mean it") - end - - def test_auto_index - pid = @post.id - assert_dom_equal( - "<label for=\"post_#{pid}_title\">Title</label>", - label("post[]", "title") - ) - assert_dom_equal( - "<input id=\"post_#{pid}_title\" name=\"post[#{pid}][title]\" size=\"30\" type=\"text\" value=\"Hello World\" />", text_field("post[]","title") - ) - assert_dom_equal( - "<textarea cols=\"40\" id=\"post_#{pid}_body\" name=\"post[#{pid}][body]\" rows=\"20\">Back to the hill and over it again!</textarea>", - text_area("post[]", "body") - ) - assert_dom_equal( - "<input name=\"post[#{pid}][secret]\" type=\"hidden\" value=\"0\" /><input checked=\"checked\" id=\"post_#{pid}_secret\" name=\"post[#{pid}][secret]\" type=\"checkbox\" value=\"1\" />", - check_box("post[]", "secret") - ) - assert_dom_equal( -"<input checked=\"checked\" id=\"post_#{pid}_title_hello_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Hello World\" />", - radio_button("post[]", "title", "Hello World") - ) - assert_dom_equal("<input id=\"post_#{pid}_title_goodbye_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Goodbye World\" />", - radio_button("post[]", "title", "Goodbye World") - ) - end - - def test_form_for - form_for(:post, @post, :html => { :id => 'create-post' }) do |f| - concat f.label(:title) - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - concat f.submit('Create post') - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<label for='post_title'>Title</label>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='commit' id='post_submit' type='submit' value='Create post' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_method - form_for(:post, @post, :html => { :id => 'create-post', :method => :put }) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<div style='margin:0;padding:0;display:inline'><input name='_method' type='hidden' value='put' /></div>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_without_object - form_for(:post, :html => { :id => 'create-post' }) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_index - form_for("post[]", @post) do |f| - concat f.label(:title) - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<label for=\"post_123_title\">Title</label>" + - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' type='hidden' value='0' />" + - "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_nil_index_option_override - form_for("post[]", @post, :index => nil) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + - "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[][secret]' type='hidden' value='0' />" + - "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for - form_for(:post, @post) do |f| - f.fields_for(:comment, @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[comment][title]' size='30' type='text' id='post_comment_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_nested_collections - form_for('post[]', @post) do |f| - concat f.text_field(:title) - f.fields_for('comment[]', @comment) do |c| - concat c.text_field(:name) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<input name='post[123][comment][][name]' size='30' type='text' id='post_123_comment__name' value='new comment' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_and_parent_fields - form_for('post', @post, :index => 1) do |c| - concat c.text_field(:title) - c.fields_for('comment', @comment, :index => 1) do |r| - concat r.text_field(:name) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][title]' size='30' type='text' id='post_1_title' value='Hello World' />" + - "<input name='post[1][comment][1][name]' size='30' type='text' id='post_1_comment_1_name' value='new comment' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_index_and_nested_fields_for - form_for(:post, @post, :index => 1) do |f| - f.fields_for(:comment, @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][comment][title]' size='30' type='text' id='post_1_comment_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_on_both - form_for(:post, @post, :index => 1) do |f| - f.fields_for(:comment, @post, :index => 5) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][comment][5][title]' size='30' type='text' id='post_1_comment_5_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_auto_index - form_for("post[]", @post) do |f| - f.fields_for(:comment, @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][comment][title]' size='30' type='text' id='post_123_comment_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_radio_button - form_for(:post, @post) do |f| - f.fields_for(:comment, @post, :index => 5) do |c| - concat c.radio_button(:title, "hello") - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[comment][5][title]' type='radio' id='post_comment_5_title_hello' value='hello' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_auto_index_on_both - form_for("post[]", @post) do |f| - f.fields_for("comment[]", @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][comment][123][title]' size='30' type='text' id='post_123_comment_123_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_and_auto_index - form_for("post[]", @post) do |f| - f.fields_for(:comment, @post, :index => 5) do |c| - concat c.text_field(:title) - end - end - - form_for(:post, @post, :index => 1) do |f| - f.fields_for("comment[]", @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][comment][5][title]' size='30' type='text' id='post_123_comment_5_title' value='Hello World' />" + - "</form>" + - "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][comment][123][title]' size='30' type='text' id='post_1_comment_123_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_a_new_record_on_a_nested_attributes_one_to_one_association - @post.author = Author.new - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:author) do |af| - concat af.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="new author" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_explicitly_passed_object_on_a_nested_attributes_one_to_one_association - form_for(:post, @post) do |f| - f.fields_for(:author, Author.new(123)) do |af| - assert_not_nil af.object - assert_equal 123, af.object.id - end - end - end - - def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association - @post.author = Author.new(321) - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:author) do |af| - concat af.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement - @post.author = Author.new(321) - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:author) do |af| - concat af.hidden_field(:id) - concat af.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association - @post.comments = Array.new(2) { |id| Comment.new(id + 1) } - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + - '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement - @post.comments = Array.new(2) { |id| Comment.new(id + 1) } - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.hidden_field(:id) - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_new_records_on_a_nested_attributes_collection_association - @post.comments = [Comment.new, Comment.new] - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_and_new_records_on_a_nested_attributes_collection_association - @post.comments = [Comment.new(321), Comment.new] - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_an_empty_supplied_attributes_collection - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:comments, []) do |cf| - concat cf.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_supplied_nested_attributes_collection - @post.comments = Array.new(2) { |id| Comment.new(id + 1) } - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:comments, @post.comments) do |cf| - concat cf.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + - '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_on_a_nested_attributes_collection_association_yields_only_builder - @post.comments = [Comment.new(321), Comment.new] - yielded_comments = [] - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:comments) do |cf| - concat cf.text_field(:name) - yielded_comments << cf.object - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + - '</form>' - - assert_dom_equal expected, output_buffer - assert_equal yielded_comments, @post.comments - end - - def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association - @post.comments = [] - - form_for(:post, @post) do |f| - f.fields_for(:comments, Comment.new(321), :child_index => 'abc') do |cf| - concat cf.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_uses_unique_indices_for_different_collection_associations - @post.comments = [Comment.new(321)] - @post.tags = [Tag.new(123), Tag.new(456)] - @post.comments[0].relevances = [] - @post.tags[0].relevances = [] - @post.tags[1].relevances = [] - form_for(:post, @post) do |f| - f.fields_for(:comments, @post.comments[0]) do |cf| - concat cf.text_field(:name) - cf.fields_for(:relevances, CommentRelevance.new(314)) do |crf| - concat crf.text_field(:value) - end - end - f.fields_for(:tags, @post.tags[0]) do |tf| - concat tf.text_field(:value) - tf.fields_for(:relevances, TagRelevance.new(3141)) do |trf| - concat trf.text_field(:value) - end - end - f.fields_for('tags', @post.tags[1]) do |tf| - concat tf.text_field(:value) - tf.fields_for(:relevances, TagRelevance.new(31415)) do |trf| - concat trf.text_field(:value) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" size="30" type="text" value="commentrelevance #314" />' + - '<input id="post_comments_attributes_0_relevances_attributes_0_id" name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_tags_attributes_0_value" name="post[tags_attributes][0][value]" size="30" type="text" value="tag #123" />' + - '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" size="30" type="text" value="tagrelevance #3141" />' + - '<input id="post_tags_attributes_0_relevances_attributes_0_id" name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" />' + - '<input id="post_tags_attributes_0_id" name="post[tags_attributes][0][id]" type="hidden" value="123" />' + - '<input id="post_tags_attributes_1_value" name="post[tags_attributes][1][value]" size="30" type="text" value="tag #456" />' + - '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" size="30" type="text" value="tagrelevance #31415" />' + - '<input id="post_tags_attributes_1_relevances_attributes_0_id" name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" />' + - '<input id="post_tags_attributes_1_id" name="post[tags_attributes][1][id]" type="hidden" value="456" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_fields_for - fields_for(:post, @post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_index - fields_for("post[]", @post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' type='hidden' value='0' />" + - "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_nil_index_option_override - fields_for("post[]", @post, :index => nil) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + - "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[][secret]' type='hidden' value='0' />" + - "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_index_option_override - fields_for("post[]", @post, :index => "abc") do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[abc][title]' size='30' type='text' id='post_abc_title' value='Hello World' />" + - "<textarea name='post[abc][body]' id='post_abc_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[abc][secret]' type='hidden' value='0' />" + - "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_without_object - fields_for(:post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_only_object - fields_for(@post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_object_with_bracketed_name - fields_for("author[post]", @post) do |f| - concat f.label(:title) - concat f.text_field(:title) - end - - assert_dom_equal "<label for=\"author_post_title\">Title</label>" + - "<input name='author[post][title]' size='30' type='text' id='author_post_title' value='Hello World' />", - output_buffer - end - - def test_fields_for_object_with_bracketed_name_and_index - fields_for("author[post]", @post, :index => 1) do |f| - concat f.label(:title) - concat f.text_field(:title) - end - - assert_dom_equal "<label for=\"author_post_1_title\">Title</label>" + - "<input name='author[post][1][title]' size='30' type='text' id='author_post_1_title' value='Hello World' />", - output_buffer - end - - def test_form_builder_does_not_have_form_for_method - assert ! ActionView::Helpers::FormBuilder.instance_methods.include?('form_for') - end - - def test_form_for_and_fields_for - form_for(:post, @post, :html => { :id => 'create-post' }) do |post_form| - concat post_form.text_field(:title) - concat post_form.text_area(:body) - - fields_for(:parent_post, @post) do |parent_fields| - concat parent_fields.check_box(:secret) - end - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='parent_post[secret]' type='hidden' value='0' />" + - "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_and_fields_for_with_object - form_for(:post, @post, :html => { :id => 'create-post' }) do |post_form| - concat post_form.text_field(:title) - concat post_form.text_area(:body) - - post_form.fields_for(@comment) do |comment_fields| - concat comment_fields.text_field(:name) - end - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' size='30' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - class LabelledFormBuilder < ActionView::Helpers::FormBuilder - (field_helpers - %w(hidden_field)).each do |selector| - src, line = <<-END_SRC, __LINE__ + 1 - def #{selector}(field, *args, &proc) - ("<label for='\#{field}'>\#{field.to_s.humanize}:</label> " + super + "<br/>").html_safe - end - END_SRC - class_eval src, __FILE__, line - end - end - - def test_form_for_with_labelled_builder - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_default_form_builder - old_default_form_builder, ActionView::Base.default_form_builder = - ActionView::Base.default_form_builder, LabelledFormBuilder - - form_for(:post, @post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + - "</form>" - - assert_dom_equal expected, output_buffer - ensure - ActionView::Base.default_form_builder = old_default_form_builder - end - - def test_default_form_builder_with_active_record_helpers - form_for(:post, @post) do |f| - concat f.error_message_on('author_name') - concat f.error_messages - end - - expected = %(<form action='http://www.example.com' method='post'>) + - %(<div class='formError'>can't be empty</div>) + - %(<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited this post from being saved</h2><p>There were problems with the following fields:</p><ul><li>Author name can't be empty</li></ul></div>) + - %(</form>) - - assert_dom_equal expected, output_buffer - - end - - def test_default_form_builder_no_instance_variable - post = @post - @post = nil - - form_for(:post, post) do |f| - concat f.error_message_on('author_name') - concat f.error_messages - end - - expected = %(<form action='http://www.example.com' method='post'>) + - %(<div class='formError'>can't be empty</div>) + - %(<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited this post from being saved</h2><p>There were problems with the following fields:</p><ul><li>Author name can't be empty</li></ul></div>) + - %(</form>) - - assert_dom_equal expected, output_buffer - - end - - def test_default_form_builder_without_object - - form_for(:post) do |f| - concat f.error_message_on('author_name') - concat f.error_messages - end - - expected = %(<form action='http://www.example.com' method='post'>) + - %(<div class='formError'>can't be empty</div>) + - %(<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited this post from being saved</h2><p>There were problems with the following fields:</p><ul><li>Author name can't be empty</li></ul></div>) + - %(</form>) - - assert_dom_equal expected, output_buffer - - end - - # Perhaps this test should be moved to prototype helper tests. - def test_remote_form_for_with_labelled_builder - self.extend ActionView::Helpers::PrototypeHelper - - remote_form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - %(<form action="http://www.example.com" onsubmit="new Ajax.Request('http://www.example.com', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" method="post">) + - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_labelled_builder - fields_for(:post, @post, :builder => LabelledFormBuilder) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_labelled_builder_with_nested_fields_for_without_options_hash - klass = nil - - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - f.fields_for(:comments, Comment.new) do |nested_fields| - klass = nested_fields.class - '' - end - end - - assert_equal LabelledFormBuilder, klass - end - - def test_form_for_with_labelled_builder_with_nested_fields_for_with_options_hash - klass = nil - - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - f.fields_for(:comments, Comment.new, :index => 'foo') do |nested_fields| - klass = nested_fields.class - '' - end - end - - assert_equal LabelledFormBuilder, klass - end - - class LabelledFormBuilderSubclass < LabelledFormBuilder; end - - def test_form_for_with_labelled_builder_with_nested_fields_for_with_custom_builder - klass = nil - - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - f.fields_for(:comments, Comment.new, :builder => LabelledFormBuilderSubclass) do |nested_fields| - klass = nested_fields.class - '' - end - end - - assert_equal LabelledFormBuilderSubclass, klass - end - - def test_form_for_with_html_options_adds_options_to_form_tag - form_for(:post, @post, :html => {:id => 'some_form', :class => 'some_class'}) do |f| end - expected = "<form action=\"http://www.example.com\" class=\"some_class\" id=\"some_form\" method=\"post\"></form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_string_url_option - form_for(:post, @post, :url => 'http://www.otherdomain.com') do |f| end - - assert_equal '<form action="http://www.otherdomain.com" method="post"></form>', output_buffer - end - - def test_form_for_with_hash_url_option - form_for(:post, @post, :url => {:controller => 'controller', :action => 'action'}) do |f| end - - assert_equal 'controller', @controller.url_for_options[:controller] - assert_equal 'action', @controller.url_for_options[:action] - end - - def test_form_for_with_record_url_option - form_for(:post, @post, :url => @post) do |f| end - - expected = "<form action=\"/posts/123\" method=\"post\"></form>" - assert_equal expected, output_buffer - end - - def test_form_for_with_existing_object - form_for(@post) do |f| end - - expected = "<form action=\"/posts/123\" class=\"edit_post\" id=\"edit_post_123\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"_method\" type=\"hidden\" value=\"put\" /></div></form>" - assert_equal expected, output_buffer - end - - def test_form_for_with_new_object - post = Post.new - post.new_record = true - def post.id() nil end - - form_for(post) do |f| end - - expected = "<form action=\"/posts\" class=\"new_post\" id=\"new_post\" method=\"post\"></form>" - assert_equal expected, output_buffer - end - - def test_form_for_with_existing_object_in_list - @post.new_record = false - @comment.save - - form_for([@post, @comment]) {} - - expected = %(<form action="#{comment_path(@post, @comment)}" class="edit_comment" id="edit_comment_1" method="post"><div style="margin:0;padding:0;display:inline"><input name="_method" type="hidden" value="put" /></div></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_new_object_in_list - @post.new_record = false - - form_for([@post, @comment]) {} - - expected = %(<form action="#{comments_path(@post)}" class="new_comment" id="new_comment" method="post"></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_existing_object_and_namespace_in_list - @post.new_record = false - @comment.save - - form_for([:admin, @post, @comment]) {} - - expected = %(<form action="#{admin_comment_path(@post, @comment)}" class="edit_comment" id="edit_comment_1" method="post"><div style="margin:0;padding:0;display:inline"><input name="_method" type="hidden" value="put" /></div></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_new_object_and_namespace_in_list - @post.new_record = false - - form_for([:admin, @post, @comment]) {} - - expected = %(<form action="#{admin_comments_path(@post)}" class="new_comment" id="new_comment" method="post"></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_existing_object_and_custom_url - form_for(@post, :url => "/super_posts") do |f| end - - expected = "<form action=\"/super_posts\" class=\"edit_post\" id=\"edit_post_123\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"_method\" type=\"hidden\" value=\"put\" /></div></form>" - assert_equal expected, output_buffer - end - - def test_remote_form_for_with_html_options_adds_options_to_form_tag - self.extend ActionView::Helpers::PrototypeHelper - - remote_form_for(:post, @post, :html => {:id => 'some_form', :class => 'some_class'}) do |f| end - expected = "<form action=\"http://www.example.com\" class=\"some_class\" id=\"some_form\" method=\"post\" onsubmit=\"new Ajax.Request('http://www.example.com', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\"></form>" - - assert_dom_equal expected, output_buffer - end - - protected - def comments_path(post) - "/posts/#{post.id}/comments" - end - alias_method :post_comments_path, :comments_path - - def comment_path(post, comment) - "/posts/#{post.id}/comments/#{comment.id}" - end - alias_method :post_comment_path, :comment_path - - def admin_comments_path(post) - "/admin/posts/#{post.id}/comments" - end - alias_method :admin_post_comments_path, :admin_comments_path - - def admin_comment_path(post, comment) - "/admin/posts/#{post.id}/comments/#{comment.id}" - end - alias_method :admin_post_comment_path, :admin_comment_path - - def posts_path - "/posts" - end - - def post_path(post) - "/posts/#{post.id}" - end - - def protect_against_forgery? - false - end -end diff --git a/vendor/plugins/rails_xss/test/form_tag_helper_test.rb b/vendor/plugins/rails_xss/test/form_tag_helper_test.rb deleted file mode 100644 index 41eeceeb3..000000000 --- a/vendor/plugins/rails_xss/test/form_tag_helper_test.rb +++ /dev/null @@ -1,354 +0,0 @@ -require 'test_helper' - -class FormTagHelperTest < ActionView::TestCase - def setup - @controller = Class.new do - def url_for(options) - "http://www.example.com" - end - end - @controller = @controller.new - end - - VALID_HTML_ID = /^[A-Za-z][-_:.A-Za-z0-9]*$/ # see http://www.w3.org/TR/html4/types.html#type-name - - def test_check_box_tag - actual = check_box_tag "admin" - expected = %(<input id="admin" name="admin" type="checkbox" value="1" />) - assert_dom_equal expected, actual - end - - def test_check_box_tag_id_sanitized - label_elem = root_elem(check_box_tag("project[2][admin]")) - assert_match VALID_HTML_ID, label_elem['id'] - end - - def test_form_tag - actual = form_tag - expected = %(<form action="http://www.example.com" method="post">) - assert_dom_equal expected, actual - end - - def test_form_tag_multipart - actual = form_tag({}, { 'multipart' => true }) - expected = %(<form action="http://www.example.com" enctype="multipart/form-data" method="post">) - assert_dom_equal expected, actual - end - - def test_form_tag_with_method_put - actual = form_tag({}, { :method => :put }) - expected = %(<form action="http://www.example.com" method="post"><div style='margin:0;padding:0;display:inline'><input type="hidden" name="_method" value="put" /></div>) - assert_dom_equal expected, actual - end - - def test_form_tag_with_method_delete - actual = form_tag({}, { :method => :delete }) - expected = %(<form action="http://www.example.com" method="post"><div style='margin:0;padding:0;display:inline'><input type="hidden" name="_method" value="delete" /></div>) - assert_dom_equal expected, actual - end - - def test_form_tag_with_block_in_erb - __in_erb_template = '' - form_tag("http://example.com") { concat "Hello world!" } - - expected = %(<form action="http://example.com" method="post">Hello world!</form>) - assert_dom_equal expected, output_buffer - end - - def test_form_tag_with_block_and_method_in_erb - __in_erb_template = '' - form_tag("http://example.com", :method => :put) { concat "Hello world!" } - - expected = %(<form action="http://example.com" method="post"><div style='margin:0;padding:0;display:inline'><input type="hidden" name="_method" value="put" /></div>Hello world!</form>) - assert_dom_equal expected, output_buffer - end - - def test_hidden_field_tag - actual = hidden_field_tag "id", 3 - expected = %(<input id="id" name="id" type="hidden" value="3" />) - assert_dom_equal expected, actual - end - - def test_hidden_field_tag_id_sanitized - input_elem = root_elem(hidden_field_tag("item[][title]")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_file_field_tag - assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz") - end - - def test_file_field_tag_with_options - assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", file_field_tag("picsplz", :class => "pix") - end - - def test_password_field_tag - actual = password_field_tag - expected = %(<input id="password" name="password" type="password" />) - assert_dom_equal expected, actual - end - - def test_radio_button_tag - actual = radio_button_tag "people", "david" - expected = %(<input id="people_david" name="people" type="radio" value="david" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("num_people", 5) - expected = %(<input id="num_people_5" name="num_people" type="radio" value="5" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("gender", "m") + radio_button_tag("gender", "f") - expected = %(<input id="gender_m" name="gender" type="radio" value="m" /><input id="gender_f" name="gender" type="radio" value="f" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("opinion", "-1") + radio_button_tag("opinion", "1") - expected = %(<input id="opinion_-1" name="opinion" type="radio" value="-1" /><input id="opinion_1" name="opinion" type="radio" value="1" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("person[gender]", "m") - expected = %(<input id="person_gender_m" name="person[gender]" type="radio" value="m" />) - assert_dom_equal expected, actual - end - - def test_select_tag - actual = select_tag "people", "<option>david</option>".html_safe - expected = %(<select id="people" name="people"><option>david</option></select>) - assert_dom_equal expected, actual - end - - def test_select_tag_with_multiple - actual = select_tag "colors", "<option>Red</option><option>Blue</option><option>Green</option>".html_safe, :multiple => :true - expected = %(<select id="colors" multiple="multiple" name="colors"><option>Red</option><option>Blue</option><option>Green</option></select>) - assert_dom_equal expected, actual - end - - def test_select_tag_disabled - actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :disabled => :true - expected = %(<select id="places" disabled="disabled" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>) - assert_dom_equal expected, actual - end - - def test_select_tag_id_sanitized - input_elem = root_elem(select_tag("project[1]people", "<option>david</option>")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_select_tag_with_array_options - assert_deprecated /array/ do - select_tag "people", ["<option>david</option>"] - end - end - - def test_text_area_tag_size_string - actual = text_area_tag "body", "hello world", "size" => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_size_symbol - actual = text_area_tag "body", "hello world", :size => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_should_disregard_size_if_its_given_as_an_integer - actual = text_area_tag "body", "hello world", :size => 20 - expected = %(<textarea id="body" name="body">hello world</textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_id_sanitized - input_elem = root_elem(text_area_tag("item[][description]")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_text_area_tag_escape_content - actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40"><b>hello world</b></textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_unescaped_content - actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40", :escape => false - expected = %(<textarea cols="20" id="body" name="body" rows="40"><b>hello world</b></textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_unescaped_nil_content - actual = text_area_tag "body", nil, :escape => false - expected = %(<textarea id="body" name="body"></textarea>) - assert_dom_equal expected, actual - end - - def test_text_field_tag - actual = text_field_tag "title", "Hello!" - expected = %(<input id="title" name="title" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_class_string - actual = text_field_tag "title", "Hello!", "class" => "admin" - expected = %(<input class="admin" id="title" name="title" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_size_symbol - actual = text_field_tag "title", "Hello!", :size => 75 - expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_size_string - actual = text_field_tag "title", "Hello!", "size" => "75" - expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_maxlength_symbol - actual = text_field_tag "title", "Hello!", :maxlength => 75 - expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_maxlength_string - actual = text_field_tag "title", "Hello!", "maxlength" => "75" - expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_disabled - actual = text_field_tag "title", "Hello!", :disabled => :true - expected = %(<input id="title" name="title" disabled="disabled" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_with_multiple_options - actual = text_field_tag "title", "Hello!", :size => 70, :maxlength => 80 - expected = %(<input id="title" name="title" size="70" maxlength="80" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_id_sanitized - input_elem = root_elem(text_field_tag("item[][title]")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_label_tag_without_text - actual = label_tag "title" - expected = %(<label for="title">Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_with_symbol - actual = label_tag :title - expected = %(<label for="title">Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_with_text - actual = label_tag "title", "My Title" - expected = %(<label for="title">My Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_class_string - actual = label_tag "title", "My Title", "class" => "small_label" - expected = %(<label for="title" class="small_label">My Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_id_sanitized - label_elem = root_elem(label_tag("item[title]")) - assert_match VALID_HTML_ID, label_elem['for'] - end - - def test_boolean_options - assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes") - assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil) - assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false) - assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => true) - assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>".html_safe, :multiple => true) - assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => nil) - end - - def test_stringify_symbol_keys - actual = text_field_tag "title", "Hello!", :id => "admin" - expected = %(<input id="admin" name="title" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_submit_tag - assert_dom_equal( - %(<input name='commit' onclick="if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); }this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Saving...';alert('hello!');result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" type="submit" value="Save" />), - submit_tag("Save", :disable_with => "Saving...", :onclick => "alert('hello!')") - ) - end - - def test_submit_tag_with_no_onclick_options - assert_dom_equal( - %(<input name='commit' onclick="if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); }this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Saving...';result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" type="submit" value="Save" />), - submit_tag("Save", :disable_with => "Saving...") - ) - end - - def test_submit_tag_with_confirmation - assert_dom_equal( - %(<input name='commit' type='submit' value='Save' onclick="if (!confirm('Are you sure?')) return false; return true;"/>), - submit_tag("Save", :confirm => "Are you sure?") - ) - end - - def test_submit_tag_with_confirmation_and_with_disable_with - assert_dom_equal( - %(<input name="commit" onclick="if (!confirm('Are you sure?')) return false; if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); }this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Saving...';result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" type="submit" value="Save" />), - submit_tag("Save", :disable_with => "Saving...", :confirm => "Are you sure?") - ) - end - - def test_image_submit_tag_with_confirmation - assert_dom_equal( - %(<input type="image" src="/images/save.gif" onclick="return confirm('Are you sure?');"/>), - image_submit_tag("save.gif", :confirm => "Are you sure?") - ) - end - - def test_pass - assert_equal 1, 1 - end - - def test_field_set_tag_in_erb - __in_erb_template = '' - field_set_tag("Your details") { concat "Hello world!" } - - expected = %(<fieldset><legend>Your details</legend>Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - - self.output_buffer = ''.html_safe - field_set_tag { concat "Hello world!" } - - expected = %(<fieldset>Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - - self.output_buffer = ''.html_safe - field_set_tag('') { concat "Hello world!" } - - expected = %(<fieldset>Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - - self.output_buffer = ''.html_safe - field_set_tag('', :class => 'format') { concat "Hello world!" } - - expected = %(<fieldset class="format">Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - end - - def protect_against_forgery? - false - end - - private - - def root_elem(rendered_content) - HTML::Document.new(rendered_content).root.children[0] - end -end diff --git a/vendor/plugins/rails_xss/test/javascript_helper_test.rb b/vendor/plugins/rails_xss/test/javascript_helper_test.rb deleted file mode 100644 index 691d97a15..000000000 --- a/vendor/plugins/rails_xss/test/javascript_helper_test.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'test_helper' - -class JavascriptHelperTest < ActionView::TestCase - def test_escape_javascript_with_safebuffer - given = %('quoted' "double-quoted" new-line:\n </closed>) - expect = %(\\'quoted\\' \\"double-quoted\\" new-line:\\n <\\/closed>) - assert_equal expect, escape_javascript(given) - assert_equal expect, escape_javascript(ActiveSupport::SafeBuffer.new(given)) - end -end diff --git a/vendor/plugins/rails_xss/test/output_escaping_test.rb b/vendor/plugins/rails_xss/test/output_escaping_test.rb deleted file mode 100644 index 8b6f8b83c..000000000 --- a/vendor/plugins/rails_xss/test/output_escaping_test.rb +++ /dev/null @@ -1,19 +0,0 @@ -require 'test_helper' - -class OutputEscapingTest < ActiveSupport::TestCase - - test "escape_html shouldn't die when passed nil" do - assert ERB::Util.h(nil).blank? - end - - test "escapeHTML should escape strings" do - assert_equal "<>"", ERB::Util.h("<>\"") - end - - test "escapeHTML shouldn't touch explicitly safe strings" do - # TODO this seems easier to compose and reason about, but - # this should be verified - assert_equal "<", ERB::Util.h("<".html_safe) - end - -end diff --git a/vendor/plugins/rails_xss/test/output_safety_test.rb b/vendor/plugins/rails_xss/test/output_safety_test.rb deleted file mode 100644 index 2e376477d..000000000 --- a/vendor/plugins/rails_xss/test/output_safety_test.rb +++ /dev/null @@ -1,115 +0,0 @@ -require 'test_helper' - -class OutputSafetyTest < ActiveSupport::TestCase - def setup - @string = "hello" - @object = Class.new(Object) do - def to_s - "other" - end - end.new - end - - test "A string is unsafe by default" do - assert !@string.html_safe? - end - - test "A string can be marked safe" do - string = @string.html_safe - assert string.html_safe? - end - - test "Marking a string safe returns the string" do - assert_equal @string, @string.html_safe - end - - test "A fixnum is safe by default" do - assert 5.html_safe? - end - - test "An object is unsafe by default" do - assert !@object.html_safe? - end - - test "Adding an object to a safe string returns a safe string" do - string = @string.html_safe - string << @object - - assert_equal "helloother", string - assert string.html_safe? - end - - test "Adding a safe string to another safe string returns a safe string" do - @other_string = "other".html_safe - string = @string.html_safe - @combination = @other_string + string - - assert_equal "otherhello", @combination - assert @combination.html_safe? - end - - test "Adding an unsafe string to a safe string escapes it and returns a safe string" do - @other_string = "other".html_safe - @combination = @other_string + "<foo>" - @other_combination = @string + "<foo>" - - assert_equal "other<foo>", @combination - assert_equal "hello<foo>", @other_combination - - assert @combination.html_safe? - assert !@other_combination.html_safe? - end - - test "Concatting safe onto unsafe yields unsafe" do - @other_string = "other" - - string = @string.html_safe - @other_string.concat(string) - assert !@other_string.html_safe? - end - - test "Concatting unsafe onto safe yields escaped safe" do - @other_string = "other".html_safe - string = @other_string.concat("<foo>") - assert_equal "other<foo>", string - assert string.html_safe? - end - - test "Concatting safe onto safe yields safe" do - @other_string = "other".html_safe - string = @string.html_safe - - @other_string.concat(string) - assert @other_string.html_safe? - end - - test "Concatting safe onto unsafe with << yields unsafe" do - @other_string = "other" - string = @string.html_safe - - @other_string << string - assert !@other_string.html_safe? - end - - test "Concatting unsafe onto safe with << yields escaped safe" do - @other_string = "other".html_safe - string = @other_string << "<foo>" - assert_equal "other<foo>", string - assert string.html_safe? - end - - test "Concatting safe onto safe with << yields safe" do - @other_string = "other".html_safe - string = @string.html_safe - - @other_string << string - assert @other_string.html_safe? - end - - test "Concatting a fixnum to safe always yields safe" do - string = @string.html_safe - string = string.concat(13) - assert_equal "hello".concat(13), string - assert string.html_safe? - end -end diff --git a/vendor/plugins/rails_xss/test/rails_xss_test.rb b/vendor/plugins/rails_xss/test/rails_xss_test.rb deleted file mode 100644 index b6268bafd..000000000 --- a/vendor/plugins/rails_xss/test/rails_xss_test.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'test_helper' - -class RailsXssTest < ActiveSupport::TestCase - test "ERB::Util.h should mark its return value as safe and escape it" do - escaped = ERB::Util.h("<p>") - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - test "ERB::Util.h should leave previously safe strings alone " do - # TODO this seems easier to compose and reason about, but - # this should be verified - escaped = ERB::Util.h("<p>".html_safe) - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - test "ERB::Util.h should not implode when passed a non-string" do - assert_nothing_raised do - assert_equal "1", ERB::Util.h(1) - end - end -end diff --git a/vendor/plugins/rails_xss/test/raw_output_helper_test.rb b/vendor/plugins/rails_xss/test/raw_output_helper_test.rb deleted file mode 100644 index 2a67f976e..000000000 --- a/vendor/plugins/rails_xss/test/raw_output_helper_test.rb +++ /dev/null @@ -1,18 +0,0 @@ -require 'test_helper' - -class RawOutputHelperTest < ActionView::TestCase - - def setup - @string = "hello" - end - - test "raw returns the safe string" do - result = raw(@string) - assert_equal @string, result - assert result.html_safe? - end - - test "raw handles nil values correctly" do - assert_equal "", raw(nil) - end -end diff --git a/vendor/plugins/rails_xss/test/safe_buffer_test.rb b/vendor/plugins/rails_xss/test/safe_buffer_test.rb deleted file mode 100644 index a0a2eccee..000000000 --- a/vendor/plugins/rails_xss/test/safe_buffer_test.rb +++ /dev/null @@ -1,51 +0,0 @@ -require 'test_helper' - -class SafeBufferTest < ActiveSupport::TestCase - def setup - @buffer = ActiveSupport::SafeBuffer.new - end - - test "Should look like a string" do - assert @buffer.is_a?(String) - assert_equal "", @buffer - end - - test "Should escape a raw string which is passed to them" do - @buffer << "<script>" - assert_equal "<script>", @buffer - end - - test "Should NOT escape a safe value passed to it" do - @buffer << "<script>".html_safe - assert_equal "<script>", @buffer - end - - test "Should not mess with an innocuous string" do - @buffer << "Hello" - assert_equal "Hello", @buffer - end - - test "Should not mess with a previously escape test" do - @buffer << ERB::Util.html_escape("<script>") - assert_equal "<script>", @buffer - end - - test "Should be considered safe" do - assert @buffer.html_safe? - end - - test "Should return a safe buffer when calling to_s" do - new_buffer = @buffer.to_s - assert_equal ActiveSupport::SafeBuffer, new_buffer.class - end - - test "Should not return a safe buffer when using sub" do - assert !@buffer.sub('', "asdf").html_safe? - end - - test "Should raise argument error when using sub!" do - assert_raise TypeError do - @buffer.sub!('', "asdf") - end - end -end diff --git a/vendor/plugins/rails_xss/test/tag_helper_test.rb b/vendor/plugins/rails_xss/test/tag_helper_test.rb deleted file mode 100644 index 2a4280943..000000000 --- a/vendor/plugins/rails_xss/test/tag_helper_test.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'test_helper' - -class TagHelperTest < ActionView::TestCase - - def test_content_tag - assert_equal "<a href=\"create\">Create</a>", content_tag("a", "Create", "href" => "create") - assert content_tag("a", "Create", "href" => "create").html_safe? - assert_equal content_tag("a", "Create", "href" => "create"), - content_tag("a", "Create", :href => "create") - assert_equal "<p><script>evil_js</script></p>", - content_tag(:p, '<script>evil_js</script>') - assert_equal "<p><script>evil_js</script></p>", - content_tag(:p, '<script>evil_js</script>', nil, false) - end - - def test_tag_honors_html_safe_for_param_values - ['1&2', '1 < 2', '“test“'].each do |escaped| - assert_equal %(<a href="#{escaped}" />), tag('a', :href => escaped.html_safe) - end - end -end diff --git a/vendor/plugins/rails_xss/test/test_helper.rb b/vendor/plugins/rails_xss/test/test_helper.rb deleted file mode 100644 index d9594e446..000000000 --- a/vendor/plugins/rails_xss/test/test_helper.rb +++ /dev/null @@ -1,6 +0,0 @@ -abort 'RAILS_ROOT=/path/to/rails/2.3/app rake test' unless ENV['RAILS_ROOT'] -require File.expand_path('config/environment', ENV['RAILS_ROOT']) -require File.expand_path('../../init', __FILE__) -require 'active_support/test_case' -require 'action_view/test_case' -require 'test/unit' diff --git a/vendor/plugins/rails_xss/test/text_helper_test.rb b/vendor/plugins/rails_xss/test/text_helper_test.rb deleted file mode 100644 index b74ae547c..000000000 --- a/vendor/plugins/rails_xss/test/text_helper_test.rb +++ /dev/null @@ -1,30 +0,0 @@ -require 'test_helper' - -class TextHelperTest < ActionView::TestCase - - def setup - @controller = Class.new do - attr_accessor :request - def url_for(*args) "http://www.example.com" end - end.new - end - - def test_simple_format_with_escaping_html_options - assert_dom_equal(%(<p class="intro">It's nice to have options.</p>), - simple_format("It's nice to have options.", :class=>"intro")) - end - - def test_simple_format_should_not_escape_safe_content - assert_dom_equal(%(<p>This is <script>safe_js</script>.</p>), - simple_format('This is <script>safe_js</script>.'.html_safe)) - end - - def test_simple_format_escapes_unsafe_content - assert_dom_equal(%(<p>This is <script>evil_js</script>.</p>), - simple_format('This is <script>evil_js</script>.')) - end - - def test_truncate_should_not_be_html_safe - assert !truncate("Hello World!", :length => 12).html_safe? - end -end diff --git a/vendor/plugins/rails_xss/test/url_for_test.rb b/vendor/plugins/rails_xss/test/url_for_test.rb deleted file mode 100644 index b13451bfb..000000000 --- a/vendor/plugins/rails_xss/test/url_for_test.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'test_helper' - -class UrlHelperTest < ActionView::TestCase - - def abcd(hash = {}) - hash_for(:a => :b, :c => :d).merge(hash) - end - - def hash_for(opts = {}) - {:controller => "foo", :action => "bar"}.merge(opts) - end - - def test_url_for_does_not_escape_urls_if_explicitly_stated - assert_equal "/foo/bar?a=b&c=d", url_for(abcd(:escape => false)) - end - - def test_link_tag_with_img - link = link_to("<img src='/favicon.jpg' />".html_safe, "/") - expected = %{<a href="/"><img src='/favicon.jpg' /></a>} - assert_dom_equal expected, link - end - - def test_link_to_should_not_escape_content_for_html_safe - link = link_to("Some <p>html</p>".html_safe, "/") - expected = %{<a href="/">Some <p>html</p></a>} - assert_dom_equal link, expected - end - - def test_link_to_escapes_content_for_non_safe - link = link_to("Some <p>html</p>", "/") - expected = %{<a href="/">Some <p>html</p></a>} - assert_dom_equal link, expected - end - - def test_url_for_escaping_is_safety_aware - assert url_for(abcd(:escape => true)).html_safe?, "escaped urls should be html_safe?" - assert !url_for(abcd(:escape => false)).html_safe?, "non-escaped urls should not be html_safe?" - end -end diff --git a/vendor/plugins/strip_attributes/.gitignore b/vendor/plugins/strip_attributes/.gitignore deleted file mode 100644 index 1a240903a..000000000 --- a/vendor/plugins/strip_attributes/.gitignore +++ /dev/null @@ -1 +0,0 @@ -rdoc
\ No newline at end of file diff --git a/vendor/plugins/strip_attributes/README.rdoc b/vendor/plugins/strip_attributes/README.rdoc deleted file mode 100644 index bd55c0c1c..000000000 --- a/vendor/plugins/strip_attributes/README.rdoc +++ /dev/null @@ -1,77 +0,0 @@ -== StripAttributes - -StripAttributes is a Rails plugin that automatically strips all ActiveRecord -model attributes of leading and trailing whitespace before validation. If the -attribute is blank, it strips the value to +nil+. - -It works by adding a before_validation hook to the record. By default, all -attributes are stripped of whitespace, but <tt>:only</tt> and <tt>:except</tt> -options can be used to limit which attributes are stripped. Both options accept -a single attribute (<tt>:only => :field</tt>) or arrays of attributes (<tt>:except => -[:field1, :field2, :field3]</tt>). - -=== Examples - - class DrunkPokerPlayer < ActiveRecord::Base - strip_attributes! - end - - class SoberPokerPlayer < ActiveRecord::Base - strip_attributes! :except => :boxers - end - - class ConservativePokerPlayer < ActiveRecord::Base - strip_attributes! :only => [:shoe, :sock, :glove] - end - -=== Installation - -Option 1. Use the standard Rails plugin install (assuming Rails 2.1). - - ./script/plugin install git://github.com/rmm5t/strip_attributes.git - -Option 2. Use git submodules - - git submodule add git://github.com/rmm5t/strip_attributes.git vendor/plugins/strip_attributes - -Option 3. Use braid[http://github.com/evilchelu/braid/tree/master] (assuming -you're using git) - - braid add --rails_plugin git://github.com/rmm5t/strip_attributes.git - git merge braid/track - -=== Other - -If you want to use this outside of Rails, extend StripAttributes in your -ActiveRecord model after putting strip_attributes in your <tt>$LOAD_PATH</tt>: - - require 'strip_attributes' - class SomeModel < ActiveRecord::Base - extend StripAttributes - strip_attributes! - end - -=== Support - -The StripAttributes homepage is http://stripattributes.rubyforge.org. You can -find the StripAttributes RubyForge progject page at: -http://rubyforge.org/projects/stripattributes - -StripAttributes source is hosted on GitHub[http://github.com/]: -http://github.com/rmm5t/strip_attributes - -Feel free to submit suggestions or feature requests. If you send a patch, -remember to update the corresponding unit tests. In fact, I prefer new features -to be submitted in the form of new unit tests. - -=== Credits - -The idea was triggered by the information at -http://wiki.rubyonrails.org/rails/pages/HowToStripWhitespaceFromModelFields -but was modified from the original to include more idiomatic ruby and rails -support. - -=== License - -Copyright (c) 2007-2008 Ryan McGeary released under the MIT license -http://en.wikipedia.org/wiki/MIT_License
\ No newline at end of file diff --git a/vendor/plugins/strip_attributes/Rakefile b/vendor/plugins/strip_attributes/Rakefile deleted file mode 100644 index 05b0c14ad..000000000 --- a/vendor/plugins/strip_attributes/Rakefile +++ /dev/null @@ -1,30 +0,0 @@ -require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the stripattributes plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the stripattributes plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'Stripattributes' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README.rdoc') - rdoc.rdoc_files.include('lib/**/*.rb') -end - -desc 'Publishes rdoc to rubyforge server' -task :publish_rdoc => :rdoc do - cmd = "scp -r rdoc/* rmm5t@rubyforge.org:/var/www/gforge-projects/stripattributes" - puts "\nPublishing rdoc: #{cmd}\n\n" - system(cmd) -end - diff --git a/vendor/plugins/strip_attributes/init.rb b/vendor/plugins/strip_attributes/init.rb deleted file mode 100644 index 2c71b29bc..000000000 --- a/vendor/plugins/strip_attributes/init.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'strip_attributes' -ActiveRecord::Base.extend(StripAttributes) diff --git a/vendor/plugins/strip_attributes/lib/strip_attributes.rb b/vendor/plugins/strip_attributes/lib/strip_attributes.rb deleted file mode 100644 index 70f414654..000000000 --- a/vendor/plugins/strip_attributes/lib/strip_attributes.rb +++ /dev/null @@ -1,32 +0,0 @@ -module StripAttributes - # Strips whitespace from model fields and leaves nil values as nil. - # XXX this differs from official StripAttributes, as it doesn't make blank cells null. - def strip_attributes!(options = nil) - before_validation do |record| - attributes = StripAttributes.narrow(record.attributes, options) - attributes.each do |attr, value| - if value.respond_to?(:strip) - record[attr] = (value.nil?) ? nil : value.strip - end - end - end - end - - # Necessary because Rails has removed the narrowing of attributes using :only - # and :except on Base#attributes - def self.narrow(attributes, options) - if options.nil? - attributes - else - if except = options[:except] - except = Array(except).collect { |attribute| attribute.to_s } - attributes.except(*except) - elsif only = options[:only] - only = Array(only).collect { |attribute| attribute.to_s } - attributes.slice(*only) - else - raise ArgumentError, "Options does not specify :except or :only (#{options.keys.inspect})" - end - end - end -end diff --git a/vendor/plugins/strip_attributes/test/strip_attributes_test.rb b/vendor/plugins/strip_attributes/test/strip_attributes_test.rb deleted file mode 100644 index 95754fca7..000000000 --- a/vendor/plugins/strip_attributes/test/strip_attributes_test.rb +++ /dev/null @@ -1,90 +0,0 @@ -require "#{File.dirname(__FILE__)}/test_helper" - -module MockAttributes - def self.included(base) - base.column :foo, :string - base.column :bar, :string - base.column :biz, :string - base.column :baz, :string - end -end - -class StripAllMockRecord < ActiveRecord::Base - include MockAttributes - strip_attributes! -end - -class StripOnlyOneMockRecord < ActiveRecord::Base - include MockAttributes - strip_attributes! :only => :foo -end - -class StripOnlyThreeMockRecord < ActiveRecord::Base - include MockAttributes - strip_attributes! :only => [:foo, :bar, :biz] -end - -class StripExceptOneMockRecord < ActiveRecord::Base - include MockAttributes - strip_attributes! :except => :foo -end - -class StripExceptThreeMockRecord < ActiveRecord::Base - include MockAttributes - strip_attributes! :except => [:foo, :bar, :biz] -end - -class StripAttributesTest < Test::Unit::TestCase - def setup - @init_params = { :foo => "\tfoo", :bar => "bar \t ", :biz => "\tbiz ", :baz => "" } - end - - def test_should_exist - assert Object.const_defined?(:StripAttributes) - end - - def test_should_strip_all_fields - record = StripAllMockRecord.new(@init_params) - record.valid? - assert_equal "foo", record.foo - assert_equal "bar", record.bar - assert_equal "biz", record.biz - assert_nil record.baz - end - - def test_should_strip_only_one_field - record = StripOnlyOneMockRecord.new(@init_params) - record.valid? - assert_equal "foo", record.foo - assert_equal "bar \t ", record.bar - assert_equal "\tbiz ", record.biz - assert_equal "", record.baz - end - - def test_should_strip_only_three_fields - record = StripOnlyThreeMockRecord.new(@init_params) - record.valid? - assert_equal "foo", record.foo - assert_equal "bar", record.bar - assert_equal "biz", record.biz - assert_equal "", record.baz - end - - def test_should_strip_all_except_one_field - record = StripExceptOneMockRecord.new(@init_params) - record.valid? - assert_equal "\tfoo", record.foo - assert_equal "bar", record.bar - assert_equal "biz", record.biz - assert_nil record.baz - end - - def test_should_strip_all_except_three_fields - record = StripExceptThreeMockRecord.new(@init_params) - record.valid? - assert_equal "\tfoo", record.foo - assert_equal "bar \t ", record.bar - assert_equal "\tbiz ", record.biz - assert_nil record.baz - end -end diff --git a/vendor/plugins/strip_attributes/test/test_helper.rb b/vendor/plugins/strip_attributes/test/test_helper.rb deleted file mode 100644 index 7d06c40db..000000000 --- a/vendor/plugins/strip_attributes/test/test_helper.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'test/unit' -require 'rubygems' -require 'active_record' - -PLUGIN_ROOT = File.expand_path(File.join(File.dirname(__FILE__), "..")) - -$LOAD_PATH.unshift "#{PLUGIN_ROOT}/lib" -require "#{PLUGIN_ROOT}/init" - -class ActiveRecord::Base - alias_method :save, :valid? - def self.columns() - @columns ||= [] - end - - def self.column(name, sql_type = nil, default = nil, null = true) - @columns ||= [] - @columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type, null) - end -end |