diff --git a/backup.rails2.3/Gemfile.rails2.3 b/backup.rails2.3/Gemfile.rails2.3 deleted file mode 100644 index dc3af876..00000000 --- a/backup.rails2.3/Gemfile.rails2.3 +++ /dev/null @@ -1,65 +0,0 @@ -source :gemcutter -source "http://gems.github.com/" - -gem "rake", "~>0.8.7" -gem "rails", "~>2.3.12" -gem "highline", "~>1.5.0" -gem "RedCloth", "4.2.8" -gem "sanitize", "~>1.2.1" -gem "rack", "1.1.0" -gem "will_paginate", "~> 2.3.15" -gem "has_many_polymorphs", "~> 2.13" -gem "acts_as_list", "~>0.1.4" -gem "aasm", "~>2.2.0" -gem "rubyjedi-actionwebservice", :require => "actionwebservice" -gem "rubycas-client", "~>2.2.1" -gem "ruby-openid", :require => "openid" - -# you may comment out the database driver you will not be using. -# This will prevent a native build of the driver. Building native drivers is not always possible on all hosters -gem "sqlite3" -gem "mysql" - -gem 'bcrypt-ruby', '~> 2.1.4' -gem 'htmlentities', '~> 4.3.0' -gem "mail" - -if RUBY_VERSION.to_f >= 1.9 - gem "soap4r-ruby1.9" -else - gem "soap4r", "~>1.5.8" -end - -group :development do - if RUBY_VERSION.to_f >= 1.9 - gem "ruby-debug19" - gem "mongrel", "1.2.0.pre2" - else - gem "ruby-debug" - gem "mongrel" - end - gem "yard" -end - -group :test do - gem "test-unit", "1.2.3" - gem "flexmock" - gem "ZenTest", ">=4.0.0" - gem "hpricot" - gem "hoe" - gem "rspec-rails", "~>1.3.3" - gem "thoughtbot-factory_girl" - gem 'memory_test_fix', '~>0.1.3' - gem "capybara", ">=0.3.5" - gem "selenium-webdriver" # Note that > 2.14 has problems: https://code.google.com/p/selenium/issues/detail?id=3075 - gem "database_cleaner", ">=0.5.0" - gem "cucumber-rails", "~>0.3.2" - gem "aruba", "0.2.2", :path => "vendor/gems/aruba-0.2.2" - - # uncomment to use the webkit option. This depends on Qt to be installed - #gem "capybara-webkit" - - # uncomment to be able to make screenshots from scenarios - #gem "capybara-screenshot" - #gem "launchy" -end diff --git a/backup.rails2.3/Gemfile.rails3 b/backup.rails2.3/Gemfile.rails3 deleted file mode 100644 index c07b2b6a..00000000 --- a/backup.rails2.3/Gemfile.rails3 +++ /dev/null @@ -1,39 +0,0 @@ -source 'https://rubygems.org' - -gem 'rails', '3.2.3' - -# Bundle edge Rails instead: -# gem 'rails', :git => 'git://github.com/rails/rails.git' - -gem 'sqlite3' -gem 'mysql' - - -# Gems used only for assets and not required -# in production environments by default. -group :assets do - gem 'sass-rails', '~> 3.2.3' - gem 'coffee-rails', '~> 3.2.1' - - # See https://github.com/sstephenson/execjs#readme for more supported runtimes - # gem 'therubyracer', :platform => :ruby - - gem 'uglifier', '>= 1.0.3' -end - -gem 'jquery-rails' - -# To use ActiveModel has_secure_password -# gem 'bcrypt-ruby', '~> 3.0.0' - -# To use Jbuilder templates for JSON -# gem 'jbuilder' - -# Use unicorn as the app server -# gem 'unicorn' - -# Deploy with Capistrano -# gem 'capistrano' - -# To use debugger -# gem 'ruby-debug19', :require => 'ruby-debug' diff --git a/backup.rails2.3/app/apis/todo_api.rb b/backup.rails2.3/app/apis/todo_api.rb deleted file mode 100644 index 5f980a64..00000000 --- a/backup.rails2.3/app/apis/todo_api.rb +++ /dev/null @@ -1,22 +0,0 @@ -class TodoApi < ActionWebService::API::Base - api_method :new_todo, - :expects => [{:username => :string}, {:token => :string}, {:context_id => :int}, {:description => :string}, {:notes => :string}], - :returns => [:int] - - api_method :new_todo_for_project, - :expects => [{:username => :string}, {:token => :string}, {:context_id => :int}, {:project_id => :int}, {:description => :string}, {:notes => :string}], - :returns => [:int] - - api_method :new_rich_todo, - :expects => [{:username => :string}, {:token => :string}, {:default_context_id => :int}, {:description => :string}, {:notes => :string}], - :returns => [:int] - - api_method :list_contexts, - :expects => [{:username => :string}, {:token => :string}], - :returns => [[Context]] - - api_method :list_projects, - :expects => [{:username => :string}, {:token => :string}], - :returns => [[Project]] - -end diff --git a/backup.rails2.3/application_helper.rb.rails2 b/backup.rails2.3/application_helper.rb.rails2 deleted file mode 100644 index 39c591e4..00000000 --- a/backup.rails2.3/application_helper.rb.rails2 +++ /dev/null @@ -1,301 +0,0 @@ -# The methods added to this helper will be available to all templates in the -# application. -module ApplicationHelper - - # Replicates the link_to method but also checks request.request_uri to find - # current page. If that matches the url, the link is marked id = "current" - # - def navigation_link(name, options = {}, html_options = nil, *parameters_for_method_reference) - if html_options - html_options = html_options.stringify_keys - convert_options_to_javascript!(html_options) - tag_options = tag_options(html_options) - else - tag_options = nil - end - url = options.is_a?(String) ? options : self.url_for(options, *parameters_for_method_reference) - id_tag = (request.request_uri == url) ? " id=\"current\"" : "" - - "#{name || url}" - end - - def days_from_today(date) - date.in_time_zone.to_date - current_user.time.to_date - end - - # Check due date in comparison to today's date Flag up date appropriately with - # a 'traffic light' colour code - # - def due_date(due) - return "" if due.nil? - - days = days_from_today(due) - - colors = ['amber','amber','orange','orange','orange','orange','orange','orange'] - color = :red if days < 0 - color = :green if days > 7 - color = colors[days] if color.nil? - - return content_tag(:a, {:title => format_date(due)}) { - content_tag(:span, {:class => color}) { - case days - when 0 - t('todos.next_actions_due_date.due_today') - when 1 - t('todos.next_actions_due_date.due_tomorrow') - when 2..7 - if prefs.due_style == Preference.due_styles[:due_on] - # TODO: internationalize strftime here - t('models.preference.due_on', :date => due.strftime("%A")) - else - t('models.preference.due_in', :days => days) - end - else - # overdue or due very soon! sound the alarm! - if days == -1 - t('todos.next_actions_due_date.overdue_by', :days => days * -1) - elsif days < -1 - t('todos.next_actions_due_date.overdue_by_plural', :days => days * -1) - else - # more than a week away - relax - t('models.preference.due_in', :days => days) - end - end - } - } - end - - # Check due date in comparison to today's date Flag up date appropriately with - # a 'traffic light' colour code Modified method for mobile screen - # - def due_date_mobile(due) - if due == nil - return "" - end - - days = days_from_today(due) - - case days - when 0 - ""+ format_date(due) + "" - when 1 - "" + format_date(due) + "" - # due 2-7 days away - when 2..7 - "" + format_date(due) + "" - else - # overdue or due very soon! sound the alarm! - if days < 0 - "" + format_date(due) +"" - else - # more than a week away - relax - "" + format_date(due) + "" - end - end - end - - # Returns a count of next actions in the given context or project. The result - # is count and a string descriptor, correctly pluralised if there are no - # actions or multiple actions - # - def count_undone_todos_phrase(todos_parent, string="actions") - @controller.count_undone_todos_phrase(todos_parent, string) - end - - def count_undone_todos_phrase_text(todos_parent, string="actions") - count_undone_todos_phrase(todos_parent, string).gsub(" "," ") - end - - def count_undone_todos_and_notes_phrase(project, string="actions") - s = count_undone_todos_phrase(project, string) - s += ", #{pluralize(project.note_count, 'note')}" unless project.note_count == 0 - s - end - - def link_to_context(context, descriptor = sanitize(context.name)) - link_to( descriptor, context, :title => "View context: #{context.name}" ) - end - - def link_to_project(project, descriptor = sanitize(project.name)) - link_to( descriptor, project, :title => "View project: #{project.name}" ) - end - - def link_to_edit_note (note, descriptor = sanitize(note.id.to_s)) - link_to(descriptor, - url_for({:controller => 'notes', :action => 'edit', :id => note.id}), - {:id => "link_edit_#{dom_id(note)}", :class => "note_edit_settings"}) - end - - def link_to_project_mobile(project, accesskey, descriptor = sanitize(project.name)) - link_to( descriptor, project_path(project, :format => 'm'), {:title => "View project: #{project.name}", :accesskey => accesskey} ) - end - - def item_link_to_context(item) - descriptor = "[C]" - descriptor = "[#{item.context.name}]" if prefs.verbose_action_descriptors - link_to_context( item.context, descriptor ) - end - - def item_link_to_project(item) - descriptor = "[P]" - descriptor = "[#{item.project.name}]" if prefs.verbose_action_descriptors - link_to_project( item.project, descriptor ) - end - - def render_flash - render :partial => 'shared/flash', :object => flash - end - - def recurrence_time_span(rt) - case rt.ends_on - when "no_end_date" - return rt.start_from.nil? ? "" : I18n.t("todos.recurrence.pattern.from") + " " + format_date(rt.start_from) - when "ends_on_number_of_times" - return I18n.t("todos.recurrence.pattern.times", :number => rt.number_of_occurences) - when "ends_on_end_date" - starts = rt.start_from.nil? ? "" : I18n.t("todos.recurrence.pattern.from") + " " + format_date(rt.start_from) - ends = rt.end_date.nil? ? "" : " " + I18n.t("todos.recurrence.pattern.until") + " " + format_date(rt.end_date) - return starts+ends - else - raise Exception.new, "unknown recurrence time span selection (#{rt.ends_on})" - end - end - - def recurrence_pattern_as_text(recurring_todo) - rt = recurring_todo.recurring_target_as_text - rp = recurring_todo.recurrence_pattern - # only add space if recurrence_pattern has content - rp = " " + rp if !rp.nil? - rts = recurrence_time_span(recurring_todo) - # only add space if recurrence_time_span has content - rts = " " + rts if !(rts == "") - return rt+rp+rts - end - - def date_format_for_date_picker() - standard_format = current_user.prefs.date_format - translations = [ - ['%m', 'mm'], - ['%b', 'M'], - ['%B', 'MM'], - ['%d', 'dd'], - ['%a', 'D'], - ['%A', 'DD'], - ['%y', 'y'], - ['%Y', 'yy'] - ] - translations.inject(standard_format) do |str, translation| - str.gsub(*translation) - end - end - - AUTO_LINK_MESSAGE_RE = %r{message://<[^>]+>} unless const_defined?(:AUTO_LINK_MESSAGE_RE) - - # Converts message:// links to href. This URL scheme is used on Mac OS X - # to link to a mail message in Mail.app. - def auto_link_message(text) - text.gsub(AUTO_LINK_MESSAGE_RE) do - href = $& - left, right = $`, $' - # detect already linked URLs and URLs in the middle of a tag - if left =~ /<[^>]+$/ && right =~ /^[^>]*>/ - # do not change string; URL is alreay linked - href - else - content = content_tag(:a, h(href), :href => h(href)) - end - end - end - - def format_note(note) - note = auto_link_message(note) - note = markdown(note) - note = auto_link(note, :link => :urls) - - # add onenote and message protocols - Sanitize::Config::RELAXED[:protocols]['a']['href'] << 'onenote' - Sanitize::Config::RELAXED[:protocols]['a']['href'] << 'message' - - note = Sanitize.clean(note, Sanitize::Config::RELAXED) - return note - end - - def sidebar_html_for_titled_list (list, title) - return content_tag(:h3, title+" (#{list.length})") + - content_tag(:ul, sidebar_html_for_list(list)) - end - - def sidebar_html_for_list(list) - if list.empty? - return content_tag(:li, t('sidebar.list_empty')) - else - return list.inject("") do |html, item| - link = (item.class == "Project") ? link_to_project( item ) : link_to_context(item) - html << content_tag(:li, link + " (" + count_undone_todos_phrase(item,"actions")+")") - end - end - end - - def generate_i18n_strings - js = "i18n_locale='#{I18n.locale}';\n" - js << "i18n = new Array();\n" - %w{ - shared.toggle_multi shared.toggle_multi_title - shared.hide_form shared.hide_action_form_title - shared.toggle_single shared.toggle_single_title - projects.hide_form projects.hide_form_title - projects.show_form projects.show_form_title - contexts.hide_form contexts.hide_form_title - contexts.show_form contexts.show_form_title - contexts.new_context_pre contexts.new_context_post - common.cancel common.ok - common.ajaxError todos.unresolved_dependency - }.each do |s| - js << "i18n['#{s}'] = '#{ t(s).gsub(/'/, "\\\\'") }';\n" - end - return js - end - - def javascript_tag_for_i18n_datepicker - locale = I18n.locale - # do not include en as locale since this the available by default - if locale and locale != :en - javascript_include_tag("i18n/jquery.ui.datepicker-#{locale}.js") - end - end - - def determine_done_path - case @controller.controller_name - when "contexts" - done_todos_context_path(@context) - when "projects" - done_todos_project_path(@project) - when "todos" - if source_view_is(:tag) - done_tag_path(@tag_name) - else - done_todos_path - end - else - done_todos_path - end - end - - def determine_all_done_path - case @controller.controller_name - when "contexts" - all_done_todos_context_path(@context) - when "projects" - all_done_todos_project_path(@project) - when "todos" - if source_view_is(:tag) - all_done_tag_path(@tag_name) - else - all_done_todos_path - end - else - all_done_todos_path - end - end - -end diff --git a/backup.rails2.3/backend_controller.rb b/backup.rails2.3/backend_controller.rb deleted file mode 100644 index 0f84c649..00000000 --- a/backup.rails2.3/backend_controller.rb +++ /dev/null @@ -1,73 +0,0 @@ -class CannotAccessContext < RuntimeError; end - -class BackendController < ApplicationController - acts_as_web_service - wsdl_service_name 'Backend' - web_service_api TodoApi - web_service_scaffold :invoke - skip_before_filter :login_required - - - def new_todo(username, token, context_id, description, notes) - check_token(username, token) - check_context_belongs_to_user(context_id) - item = create_todo(description, context_id, nil, notes) - item.id - end - - def new_todo_for_project(username, token, context_id, project_id, description, notes) - check_token(username, token) - check_context_belongs_to_user(context_id) - item = create_todo(description, context_id, project_id, notes) - item.id - end - - def new_rich_todo(username, token, default_context_id, description, notes) - check_token(username,token) - item = Todo.from_rich_message(@user, default_context_id, description, notes) - item.save - raise item.errors.full_messages.to_s if item.new_record? - item.id - end - - def list_contexts(username, token) - check_token(username, token) - - @user.contexts - end - - def list_projects(username, token) - check_token(username, token) - - @user.projects - end - - private - - # Check whether the token in the URL matches the token in the User's table - def check_token(username, token) - @user = User.find_by_login( username ) - unless (token == @user.token) - raise(InvalidToken, "Sorry, you don't have permission to perform this action.") - end - end - - def check_context_belongs_to_user(context_id) - unless @user.contexts.exists? context_id - raise(CannotAccessContext, "Cannot access a context that does not belong to this user.") - end - end - - def create_todo(description, context_id, project_id = nil, notes="") - item = @user.todos.build - item.description = description - item.notes = notes - item.context_id = context_id - item.project_id = project_id unless project_id.nil? - item.save - raise item.errors.full_messages.to_s if item.new_record? - item - end -end - -class InvalidToken < RuntimeError; end diff --git a/backup.rails2.3/database.yml.rails2 b/backup.rails2.3/database.yml.rails2 deleted file mode 100644 index da7aebc8..00000000 --- a/backup.rails2.3/database.yml.rails2 +++ /dev/null @@ -1,37 +0,0 @@ -# MySQL. Versions 4.1 and 5.0 are recommended. -# -# -# Be sure to use new-style password hashing: -# http://dev.mysql.com/doc/refman/5.0/en/old-client.html -development: - adapter: mysql - database: tracks_trunk - encoding: utf8 - host: localhost - username: tracks - password: 32tracks55 - -mdevelopment: - adapter: sqlite3 - database: db/tracks-21-test.sqlite3.db - -test: &TEST -# adapter: sqlite3 -# database: ":memory:" -# verbosity: quiet - adapter: mysql - database: tracks_test - host: localhost - username: tracks - password: 32tracks55 - -production: - adapter: mysql - database: tracks_trunk - encoding: utf8 - host: localhost - username: tracks - password: 32tracks55 - -cucumber: - <<: *TEST diff --git a/backup.rails2.3/development.rb.rails2 b/backup.rails2.3/development.rb.rails2 deleted file mode 100644 index 05c880d7..00000000 --- a/backup.rails2.3/development.rb.rails2 +++ /dev/null @@ -1,19 +0,0 @@ -# In the development environment your application's code is reloaded on -# every request. This slows down response time but is perfect for development -# since you don't have to restart the webserver when you make code changes. -config.cache_classes = false - -# Log error messages when you accidentally call methods on nil. -config.whiny_nils = true - -# Show full error reports and disable caching -config.action_controller.consider_all_requests_local = true -config.action_controller.perform_caching = false - -# Don't care if the mailer can't send -config.action_mailer.raise_delivery_errors = false - -# Unique cookies -config.action_controller.session = { :key => 'TracksDev' } - -NOTIFY_BAR="
 
" diff --git a/backup.rails2.3/env.rb b/backup.rails2.3/env.rb deleted file mode 100644 index b763fced..00000000 --- a/backup.rails2.3/env.rb +++ /dev/null @@ -1,70 +0,0 @@ -# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. -# It is recommended to regenerate this file in the future when you upgrade to a -# newer version of cucumber-rails. Consider adding your own code to a new file -# instead of editing this one. Cucumber will automatically load all features/**/*.rb -# files. - -ENV["RAILS_ENV"] ||= "cucumber" -require File.expand_path(File.dirname(__FILE__) + '/../../config/environment') - -require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support -# require 'cucumber/rails/rspec' -require 'cucumber/rails/world' -require 'cucumber/rails/active_record' -require 'cucumber/web/tableish' -require 'aruba/cucumber' - -require 'capybara/rails' -require 'capybara/cucumber' -require 'capybara/session' -# BUG in this version of cucumber/capybara: require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript - -Capybara.default_wait_time = 5 -Capybara.javascript_driver = ENV["JS_DRIVER"] ? ENV["JS_DRIVER"].to_sym : :selenium - -if Capybara.javascript_driver == :webkit - require 'capybara/webkit' -end - -# Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In -# order to ease the transition to Capybara we set the default here. If you'd -# prefer to use XPath just remove this line and adjust any selectors in your -# steps to use the XPath syntax. -Capybara.default_selector = :css - -Capybara.prefer_visible_elements = true - -# If you set this to false, any error raised from within your app will bubble -# up to your step definition and out to cucumber unless you catch it somewhere -# on the way. You can make Rails rescue errors and render error pages on a -# per-scenario basis by tagging a scenario or feature with the @allow-rescue tag. -# -# If you set this to true, Rails will rescue all errors and render error -# pages, more or less in the same way your application would behave in the -# default production environment. It's not recommended to do this for all -# of your scenarios, as this makes it hard to discover errors in your application. -ActionController::Base.allow_rescue = false - -# If you set this to true, each scenario will run in a database transaction. -# You can still turn off transactions on a per-scenario basis, simply tagging -# a feature or scenario with the @no-txn tag. If you are using Capybara, -# tagging with @culerity or @javascript will also turn transactions off. -# -# If you set this to false, transactions will be off for all scenarios, -# regardless of whether you use @no-txn or not. -# -# Beware that turning transactions off will leave data in your database -# after each scenario, which can lead to hard-to-debug failures in -# subsequent scenarios. If you do this, we recommend you create a Before -# block that will explicitly put your database in a known state. -Cucumber::Rails::World.use_transactional_fixtures = true - -# How to clean your database when transactions are turned off. See -# http://github.com/bmabey/database_cleaner for more info. -if defined?(ActiveRecord::Base) - begin - require 'database_cleaner' - DatabaseCleaner.strategy = :truncation - rescue LoadError => ignore_if_database_cleaner_not_present - end -end diff --git a/backup.rails2.3/environment.rb.rails2 b/backup.rails2.3/environment.rb.rails2 deleted file mode 100644 index 390f585b..00000000 --- a/backup.rails2.3/environment.rb.rails2 +++ /dev/null @@ -1,119 +0,0 @@ -# Be sure to restart your webserver when you modify this file. -# Uncomment below to force Rails into production mode - -# (Use only when you can't set environment variables through your web/app server) -# ENV['RAILS_ENV'] = 'production' - -# Bootstrap the Rails environment, frameworks, and default configuration -require File.join(File.dirname(__FILE__), 'boot') - -require 'yaml' -SITE_CONFIG = YAML.load_file(File.join(File.dirname(__FILE__), 'site.yml')) - -class Rails::Configuration - attr_accessor :action_web_service -end - -Encoding.default_external = Encoding::UTF_8 if RUBY_VERSION > "1.9" - -Rails::Initializer.run do |config| - # Skip frameworks you're not going to use - # config.frameworks -= [ :action_web_service, :action_mailer ] - config.autoload_paths += %W( #{RAILS_ROOT}/app/apis ) - - config.action_controller.use_accept_header = true - - # Use the database for sessions instead of the file system - # (create the session table with 'rake create_sessions_table') - config.action_controller.session_store = :active_record_store - - config.action_controller.session = { - :key => '_tracks_session_id', - :secret => SITE_CONFIG['salt'] * (30.0 / SITE_CONFIG['salt'].length).ceil #must be at least 30 characters - } - - config.action_controller.relative_url_root = SITE_CONFIG['subdir'] if SITE_CONFIG['subdir'] - - # Enable page/fragment caching by setting a file-based store - # (remember to create the caching directory and make it readable to the application) - # config.action_controller.fragment_cache_store = :file_store, "#{RAILS_ROOT}/cache" - - # Activate observers that should always be running - # config.active_record.observers = :cacher, :garbage_collector - - # Make Active Record use UTC-base instead of local time - config.active_record.default_timezone = :utc - - # You''ll probably want to change this to the time zone of the computer where Tracks is running - # run rake time:zones:local have Rails suggest time zone names on your system - config.time_zone = SITE_CONFIG['time_zone'] - - # Use Active Record's schema dumper instead of SQL when creating the test database - # (enables use of different database adapters for development and test environments) - config.active_record.schema_format = :ruby - - # allow other protocols in urls for sanitzer. Add to your liking, for example - # config.action_view.sanitized_allowed_protocols = 'onenote', 'blah', 'proto' - # to enable "link":onenote://... or "link":blah://... hyperlinks - config.action_view.sanitized_allowed_protocols = 'onenote', 'message' - - # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] - # config.i18n.default_locale = :de - -end - -# Add new inflection rules using the following format -# (all these examples are active by default): -# Inflector.inflections do |inflect| -# inflect.plural /^(ox)$/i, '\1en' -# inflect.singular /^(ox)en/i, '\1' -# inflect.irregular 'person', 'people' -# inflect.uncountable %w( fish sheep ) -# end - -# Include your application configuration below - - -require 'name_part_finder' -require 'tracks/todo_list' -require 'tracks/config' -require 'tagging_extensions' # Needed for tagging-specific extensions -require 'digest/sha1' #Needed to support 'rake db:fixtures:load' on some ruby installs: http://dev.rousette.org.uk/ticket/557 - -if ( SITE_CONFIG['authentication_schemes'].include? 'ldap') - require 'net/ldap' #requires ruby-net-ldap gem be installed - require 'simple_ldap_authenticator' - ldap = SITE_CONFIG['ldap'] - SimpleLdapAuthenticator.ldap_library = ldap['library'] - SimpleLdapAuthenticator.servers = ldap['servers'] - SimpleLdapAuthenticator.use_ssl = ldap['ssl'] - SimpleLdapAuthenticator.login_format = ldap['login_format'] -end - -if ( SITE_CONFIG['authentication_schemes'].include? 'open_id') - #requires ruby-openid gem to be installed - OpenID::Util.logger = RAILS_DEFAULT_LOGGER -end - -if ( SITE_CONFIG['authentication_schemes'].include? 'cas') - #requires rubycas-client gem to be installed - if defined? CASClient - require 'casclient/frameworks/rails/filter' - CASClient::Frameworks::Rails::Filter.configure( - :cas_base_url => SITE_CONFIG['cas_server'] , - :cas_server_logout => SITE_CONFIG['cas_server_logout'] - ) - end -end - -# changed in development.rb to show under_construction bar -NOTIFY_BAR = "" unless defined?(NOTIFY_BAR) - -tracks_version='2.2devel' -# comment out next two lines if you do not want (or can not) the date of the -# last git commit in the footer -info=`git log --pretty=format:"%ai" -1` -tracks_version=tracks_version + ' ('+info+')' - -TRACKS_VERSION=tracks_version diff --git a/backup.rails2.3/hoverIntent.js b/backup.rails2.3/hoverIntent.js deleted file mode 100644 index dd8a9da2..00000000 --- a/backup.rails2.3/hoverIntent.js +++ /dev/null @@ -1,84 +0,0 @@ -(function($){ - /* hoverIntent by Brian Cherne */ - $.fn.hoverIntent = function(f,g) { - // default configuration options - var cfg = { - sensitivity: 7, - interval: 100, - timeout: 400 - }; - // override configuration options with user supplied object - cfg = $.extend(cfg, g ? { over: f, out: g } : f ); - - // instantiate variables - // cX, cY = current X and Y position of mouse, updated by mousemove event - // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval - var cX, cY, pX, pY; - - // A private function for getting mouse position - var track = function(ev) { - cX = ev.pageX; - cY = ev.pageY; - }; - - // A private function for comparing current and previous mouse position - var compare = function(ev,ob) { - ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); - // compare mouse positions to see if they've crossed the threshold - if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) { - $(ob).unbind("mousemove",track); - // set hoverIntent state to true (so mouseOut can be called) - ob.hoverIntent_s = 1; - return cfg.over.apply(ob,[ev]); - } else { - // set previous coordinates for next time - pX = cX; pY = cY; - // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs) - ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval ); - } - }; - - // A private function for delaying the mouseOut function - var delay = function(ev,ob) { - ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); - ob.hoverIntent_s = 0; - return cfg.out.apply(ob,[ev]); - }; - - // A private function for handling mouse 'hovering' - var handleHover = function(e) { - // next three lines copied from jQuery.hover, ignore children onMouseOver/onMouseOut - var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; - while ( p && p != this ) { try { p = p.parentNode; } catch(e) { p = this; } } - if ( p == this ) { return false; } - - // copy objects to be passed into t (required for event object to be passed in IE) - var ev = jQuery.extend({},e); - var ob = this; - - // cancel hoverIntent timer if it exists - if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); } - - // else e.type == "onmouseover" - if (e.type == "mouseover") { - // set "previous" X and Y position based on initial entry point - pX = ev.pageX; pY = ev.pageY; - // update "current" X and Y position based on mousemove - $(ob).bind("mousemove",track); - // start polling interval (self-calling timeout) to compare mouse coordinates over time - if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );} - - // else e.type == "onmouseout" - } else { - // unbind expensive mousemove event - $(ob).unbind("mousemove",track); - // if hoverIntent state is true, then call the mouseOut function after the specified delay - if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );} - } - }; - - // bind the function to the two event listeners - return this.mouseover(handleHover).mouseout(handleHover); - }; - -})(jQuery); diff --git a/backup.rails2.3/lib/assets/.gitkeep b/backup.rails2.3/lib/assets/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/backup.rails2.3/lib/authenticated_test_helper.rb b/backup.rails2.3/lib/authenticated_test_helper.rb deleted file mode 100644 index 7a52e62b..00000000 --- a/backup.rails2.3/lib/authenticated_test_helper.rb +++ /dev/null @@ -1,113 +0,0 @@ -module AuthenticatedTestHelper - # Sets the current user in the session from the user fixtures. - def login_as(user) - @request.session['user_id'] = user ? users(user).id : nil - end - - def content_type(type) - @request.env['Content-Type'] = type - end - - def accept(accept) - @request.env["HTTP_ACCEPT"] = accept - end - - def authorize_as(user) - if user - @request.env["HTTP_AUTHORIZATION"] = "Basic #{Base64.encode64("#{users(user).login}:test")}" - accept 'application/xml' - content_type 'application/xml' - else - @request.env["HTTP_AUTHORIZATION"] = nil - accept nil - content_type nil - end - end - - # http://project.ioni.st/post/217#post-217 - # - # def test_new_publication - # assert_difference(Publication, :count) do - # post :create, :publication => {...} - # # ... - # end - # end - # - def assert_difference(object, method = nil, difference = 1) - initial_value = object.send(method) - yield - assert_equal initial_value + difference, object.send(method), "#{object}##{method}" - end - - def assert_no_difference(object, method, &block) - assert_difference object, method, 0, &block - end - - # Assert the block redirects to the login - # - # assert_requires_login(:bob) { |c| c.get :edit, :id => 1 } - # - def assert_requires_login(login = nil) - yield HttpLoginProxy.new(self, login) - end - - def assert_http_authentication_required(login = nil) - yield XmlLoginProxy.new(self, login) - end - - def reset!(*instance_vars) - instance_vars = [:controller, :request, :response] unless instance_vars.any? - instance_vars.collect! { |v| "@#{v}".to_sym } - instance_vars.each do |var| - instance_variable_set(var, instance_variable_get(var).class.new) - end - end -end - -class BaseLoginProxy - attr_reader :controller - attr_reader :options - def initialize(controller, login) - @controller = controller - @login = login - end - - private - def authenticated - raise NotImplementedError - end - - def check - raise NotImplementedError - end - - def method_missing(method, *args) - @controller.reset! - authenticate - @controller.send(method, *args) - check - end -end - -class HttpLoginProxy < BaseLoginProxy - protected - def authenticate - @controller.login_as @login if @login - end - - def check - @controller.assert_redirected_to :controller => 'account', :action => 'login' - end -end - -class XmlLoginProxy < BaseLoginProxy - protected - def authenticate - @controller.accept 'application/xml' - @controller.authorize_as @login if @login - end - - def check - @controller.assert_response 401 - end -end \ No newline at end of file diff --git a/backup.rails2.3/lib/login_system.rb b/backup.rails2.3/lib/login_system.rb deleted file mode 100644 index bc25de08..00000000 --- a/backup.rails2.3/lib/login_system.rb +++ /dev/null @@ -1,222 +0,0 @@ -require_dependency "user" - -module LoginSystem - - def current_user - get_current_user - end - - def prefs - current_user.prefs unless current_user.nil? - end - - # Logout the {#current_user} and redirect to login page - # - # @param [String] message notification to display - def logout_user message=t('login.logged_out') - @user.forget_me if logged_in? - cookies.delete :auth_token - session['user_id'] = nil - if ( SITE_CONFIG['authentication_schemes'].include? 'cas') && session[:cas_user] - CASClient::Frameworks::Rails::Filter.logout(self) - else - reset_session - notify :notice, message - redirect_to_login - end - end - - protected - - # overwrite this if you want to restrict access to only a few actions - # or if you want to check if the user has the correct rights - # example: - # - # # only allow nonbobs - # def authorize?(user) - # user.login != "bob" - # end - def authorize?(user) - true - end - - # overwrite this method if you only want to protect certain actions of the controller - # example: - # - # # don't protect the login and the about method - # def protect?(action) - # if ['action', 'about'].include?(action) - # return false - # else - # return true - # end - # end - def protect?(action) - true - end - - # When called with before_filter :login_from_cookie will check for an :auth_token - # cookie and log the user back in if appropriate - def login_from_cookie - return unless cookies[:auth_token] && !logged_in? - token = cookies[:auth_token] - user = User.where(:remember_token => token) - if user && user.remember_token? - session['user_id'] = user.id - set_current_user(user) - current_user.remember_me - cookies[:auth_token] = { :value => current_user.remember_token , :expires => current_user.remember_token_expires_at, :secure => SITE_CONFIG['secure_cookies'] } - flash[:notice] = t('login.successful') - end - end - - def login_or_feed_token_required - if ['rss', 'atom', 'txt', 'ics'].include?(params[:format]) - if user = User.find_by_token(params[:token]) - set_current_user(user) - return true - end - end - login_required - end - - # login_required filter. add - # - # before_filter :login_required - # - # if the controller should be under any rights management. - # for finer access control you can overwrite - # - # def authorize?(user) - # - def login_required - - if not protect?(action_name) - return true - end - - login_from_cookie - - if session['user_id'] and authorize?(get_current_user) - return true - end - - http_user, http_pass = get_basic_auth_data - if user = User.authenticate(http_user, http_pass) - session['user_id'] = user.id - set_current_user(user) - return true - end - - # store current location so that we can - # come back after the user logged in - store_location unless params[:format] == 'js' - - # call overwriteable reaction to unauthorized access - access_denied - return false - end - - def login_optional - - login_from_cookie - - if session['user_id'] and authorize?(get_current_user) - return true - end - - http_user, http_pass = get_basic_auth_data - if user = User.authenticate(http_user, http_pass) - session['user_id'] = user.id - set_current_user(user) - return true - end - - return true - end - - def logged_in? - current_user != nil - end - - def get_current_user - if @user.nil? && session['user_id'] - @user = User.find(session['user_id']) - end - @user - end - - def set_current_user(user) - @user = user - end - - # overwrite if you want to have special behavior in case the user is not authorized - # to access the current operation. - # the default action is to redirect to the login screen - # example use : - # a popup window might just close itself for instance - def access_denied - respond_to do |format| - format.html { redirect_to login_path } - format.m { redirect_to formatted_login_path(:format => 'm') } - format.js { render :partial => 'login/redirect_to_login' } - format.xml { basic_auth_denied } - format.rss { basic_auth_denied } - format.atom { basic_auth_denied } - format.text { basic_auth_denied } - end - end - - # store current uri in the session. - # we can return to this location by calling return_location - def store_location - session['return-to'] = request.request_uri - end - - # move to the last store_location call or to the passed default one - def redirect_back_or_default(default) - if session['return-to'].nil? - redirect_to default - else - redirect_to session['return-to'] - session['return-to'] = nil - end - end - - # HTTP Basic auth code adapted from Coda Hale's simple_http_auth plugin. Thanks, Coda! - def get_basic_auth_data - - auth_locations = ['REDIRECT_REDIRECT_X_HTTP_AUTHORIZATION', - 'REDIRECT_X_HTTP_AUTHORIZATION', - 'X-HTTP_AUTHORIZATION', 'HTTP_AUTHORIZATION'] - - authdata = nil - for location in auth_locations - if request.env.has_key?(location) - authdata = request.env[location].to_s.split - end - end - if authdata and authdata[0] == 'Basic' - user, pass = Base64.decode64(authdata[1]).split(':')[0..1] - else - user, pass = ['', ''] - end - return user, pass - end - - def basic_auth_denied - response.headers["WWW-Authenticate"] = "Basic realm=\"'Tracks Login Required'\"" - render :text => t('login.unsuccessful'), :status => 401 - end - -private - - # Redirect the user to the login page. - def redirect_to_login - respond_to do |format| - format.html { redirect_to login_path } - format.m { redirect_to login_path(:format => 'm') } - end - end - -end \ No newline at end of file diff --git a/backup.rails2.3/lib/name_part_finder.rb b/backup.rails2.3/lib/name_part_finder.rb deleted file mode 100644 index 79d66338..00000000 --- a/backup.rails2.3/lib/name_part_finder.rb +++ /dev/null @@ -1,5 +0,0 @@ -module NamePartFinder - def find_by_namepart(namepart) - find_by_name(namepart) || find(:first, :conditions => ["name LIKE ?", namepart + '%']) - end -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tagging_extensions.rb b/backup.rails2.3/lib/tagging_extensions.rb deleted file mode 100644 index 2808f42a..00000000 --- a/backup.rails2.3/lib/tagging_extensions.rb +++ /dev/null @@ -1,200 +0,0 @@ -class ActiveRecord::Base #:nodoc: - - # These extensions make models taggable. This file is automatically generated and required by your app if you run the tagging generator included with has_many_polymorphs. - module TaggingExtensions - - # Add tags to self. Accepts a string of tagnames, an array of tagnames, an array of ids, or an array of Tags. - # - # We need to avoid name conflicts with the built-in ActiveRecord association methods, thus the underscores. - def _add_tags incoming - taggable?(true) - tag_cast_to_string(incoming).each do |tag_name| - # added following check to prevent empty tags from being saved (which will fail) - unless tag_name.blank? - begin - tag = Tag.find_or_create_by_name(tag_name) - raise Tag::Error, "tag could not be saved: #{tag_name}" if tag.new_record? - tags << tag - rescue ActiveRecord::StatementInvalid => e - raise unless e.to_s =~ /duplicate/i - end - end - end - end - - # Removes tags from self. Accepts a string of tagnames, an array of tagnames, an array of ids, or an array of Tags. - def _remove_tags outgoing - taggable?(true) - outgoing = tag_cast_to_string(outgoing) - tags.delete(*(tags.select do |tag| - outgoing.include? tag.name - end)) - end - - # Returns the tags on self as a string. - def tag_list - # Redefined later to avoid an RDoc parse error. - end - - # Replace the existing tags on self. Accepts a string of tagnames, an array of tagnames, an array of ids, or an array of Tags. - def tag_with list - #:stopdoc: - taggable?(true) - list = tag_cast_to_string(list) - - # Transactions may not be ideal for you here; be aware. - Tag.transaction do - current = tags.map(&:name) - _add_tags(list - current) - _remove_tags(current - list) - end - - self - #:startdoc: - end - - # Returns the tags on self as a string. - def tag_list #:nodoc: - #:stopdoc: - taggable?(true) - tags.reload - tags.to_s - #:startdoc: - end - - def tag_list=(value) - tag_with(value) - end - - private - - def tag_cast_to_string obj #:nodoc: - case obj - when Array - obj.map! do |item| - case item - # removed next line as it prevents using numbers as tags - # when /^\d+$/, Fixnum then Tag.find(item).name # This will be slow if you use ids a lot. - when Tag then item.name - when String then item - else - raise "Invalid type" - end - end - when String - obj = obj.split(Tag::DELIMITER).map do |tag_name| - tag_name.strip.squeeze(" ") - end - else - raise "Invalid object of class #{obj.class} as tagging method parameter" - end.flatten.compact.map(&:downcase).uniq - end - - # Check if a model is in the :taggables target list. The alternative to this check is to explicitly include a TaggingMethods module (which you would create) in each target model. - def taggable?(should_raise = false) #:nodoc: - unless flag = respond_to?(:tags) - raise "#{self.class} is not a taggable model" if should_raise - end - flag - end - - end - - module TaggingFinders - # Find all the objects tagged with the supplied list of tags - # - # Usage : Model.tagged_with("ruby") - # Model.tagged_with("hello", "world") - # Model.tagged_with("hello", "world", :limit => 10) - # - # XXX This query strategy is not performant, and needs to be rewritten as an inverted join or a series of unions - # - def tagged_with(*tag_list) - options = tag_list.last.is_a?(Hash) ? tag_list.pop : {} - tag_list = parse_tags(tag_list) - - scope = scope(:find) - options[:select] ||= "#{table_name}.*" - options[:from] ||= "#{table_name}, tags, taggings" - - sql = "SELECT #{(scope && scope[:select]) || options[:select]} " - sql << "FROM #{(scope && scope[:from]) || options[:from]} " - - add_joins!(sql, options[:joins], scope) - - sql << "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " - sql << "AND taggings.taggable_type = '#{ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s}' " - sql << "AND taggings.tag_id = tags.id " - - tag_list_condition = tag_list.map {|name| "'#{name}'"}.join(", ") - - sql << "AND (tags.name IN (#{sanitize_sql(tag_list_condition)})) " - sql << "AND #{sanitize_sql(options[:conditions])} " if options[:conditions] - - columns = column_names.map do |column| - "#{table_name}.#{column}" - end.join(", ") - - sql << "GROUP BY #{columns} " - sql << "HAVING COUNT(taggings.tag_id) = #{tag_list.size}" - - add_order!(sql, options[:order], scope) - add_limit!(sql, options, scope) - add_lock!(sql, options, scope) - - find_by_sql(sql) - end - - def self.tagged_with_any(*tag_list) - options = tag_list.last.is_a?(Hash) ? tag_list.pop : {} - tag_list = parse_tags(tag_list) - - scope = scope(:find) - options[:select] ||= "#{table_name}.*" - options[:from] ||= "#{table_name}, meta_tags, taggings" - - sql = "SELECT #{(scope && scope[:select]) || options[:select]} " - sql << "FROM #{(scope && scope[:from]) || options[:from]} " - - add_joins!(sql, options, scope) - - sql << "WHERE #{table_name}.#{primary_key} = taggings.taggable_id " - sql << "AND taggings.taggable_type = '#{ActiveRecord::Base.send(:class_name_of_active_record_descendant, self).to_s}' " - sql << "AND taggings.meta_tag_id = meta_tags.id " - - sql << "AND (" - or_options = [] - tag_list.each do |name| - or_options << "meta_tags.name = '#{name}'" - end - or_options_joined = or_options.join(" OR ") - sql << "#{or_options_joined}) " - - - sql << "AND #{sanitize_sql(options[:conditions])} " if options[:conditions] - - columns = column_names.map do |column| - "#{table_name}.#{column}" - end.join(", ") - - sql << "GROUP BY #{columns} " - - add_order!(sql, options[:order], scope) - add_limit!(sql, options, scope) - add_lock!(sql, options, scope) - - find_by_sql(sql) - end - - def parse_tags(tags) - return [] if tags.blank? - tags = Array(tags).first - tags = tags.respond_to?(:flatten) ? tags.flatten : tags.split(Tag::DELIMITER) - tags.map { |tag| tag.strip.squeeze(" ") }.flatten.compact.map(&:downcase).uniq - end - - end - - include TaggingExtensions - extend TaggingFinders -end diff --git a/backup.rails2.3/lib/tasks/.gitkeep b/backup.rails2.3/lib/tasks/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/backup.rails2.3/lib/tasks/cucumber-tracks.rake b/backup.rails2.3/lib/tasks/cucumber-tracks.rake deleted file mode 100644 index ae5bdfad..00000000 --- a/backup.rails2.3/lib/tasks/cucumber-tracks.rake +++ /dev/null @@ -1,38 +0,0 @@ -# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. -# It is recommended to regenerate this file in the future when you upgrade to a -# newer version of cucumber-rails. Consider adding your own code to a new file -# instead of editing this one. Cucumber will automatically load all features/**/*.rb -# files. - -vendored_cucumber_bin = Dir["#{Rails.root}/vendor/{gems,plugins}/cucumber*/bin/cucumber"].first -$LOAD_PATH.unshift(File.dirname(vendored_cucumber_bin) + '/../lib') unless vendored_cucumber_bin.nil? - -begin - require 'cucumber/rake/task' - - namespace :cucumber do - Cucumber::Rake::Task.new({:selenium => :env_to_selenium}, 'Run features that require selenium') do |t| - t.binary = vendored_cucumber_bin - t.fork = true # You may get faster startup if you set this to false - t.profile = 'selenium' - end - - Cucumber::Rake::Task.new({:selenium_wip => :env_to_selenium}, 'Run unfinished features that require selenium') do |t| - t.binary = vendored_cucumber_bin - t.fork = true # You may get faster startup if you set this to false - t.profile = 'selenium_wip' - end - - task :env_to_selenium => 'db:test:prepare' do - ENV['RAILS_ENV'] = 'selenium' - end - - desc 'Run all features' - task :all => [:ok, :wip, :selenium, :selenium_wip] - end -rescue LoadError - desc 'cucumber rake task not available (cucumber not installed)' - task :cucumber do - abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin' - end -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tasks/cucumber.rake b/backup.rails2.3/lib/tasks/cucumber.rake deleted file mode 100644 index 7db1a557..00000000 --- a/backup.rails2.3/lib/tasks/cucumber.rake +++ /dev/null @@ -1,53 +0,0 @@ -# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. -# It is recommended to regenerate this file in the future when you upgrade to a -# newer version of cucumber-rails. Consider adding your own code to a new file -# instead of editing this one. Cucumber will automatically load all features/**/*.rb -# files. - - -unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks - -vendored_cucumber_bin = Dir["#{Rails.root}/vendor/{gems,plugins}/cucumber*/bin/cucumber"].first -$LOAD_PATH.unshift(File.dirname(vendored_cucumber_bin) + '/../lib') unless vendored_cucumber_bin.nil? - -begin - require 'cucumber/rake/task' - - namespace :cucumber do - Cucumber::Rake::Task.new({:ok => 'db:test:prepare'}, 'Run features that should pass') do |t| - t.binary = vendored_cucumber_bin # If nil, the gem's binary is used. - t.fork = true # You may get faster startup if you set this to false - t.profile = 'default' - end - - Cucumber::Rake::Task.new({:wip => 'db:test:prepare'}, 'Run features that are being worked on') do |t| - t.binary = vendored_cucumber_bin - t.fork = true # You may get faster startup if you set this to false - t.profile = 'wip' - end - - Cucumber::Rake::Task.new({:rerun => 'db:test:prepare'}, 'Record failing features and run only them if any exist') do |t| - t.binary = vendored_cucumber_bin - t.fork = true # You may get faster startup if you set this to false - t.profile = 'rerun' - end - - desc 'Run all features' - task :all => [:ok, :wip] - end - desc 'Alias for cucumber:ok' - task :cucumber => 'cucumber:ok' - - task :default => :cucumber - - task :features => :cucumber do - STDERR.puts "*** The 'features' task is deprecated. See rake -T cucumber ***" - end -rescue LoadError - desc 'cucumber rake task not available (cucumber not installed)' - task :cucumber do - abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin' - end -end - -end diff --git a/backup.rails2.3/lib/tasks/database.rake b/backup.rails2.3/lib/tasks/database.rake deleted file mode 100644 index eb02a45f..00000000 --- a/backup.rails2.3/lib/tasks/database.rake +++ /dev/null @@ -1,27 +0,0 @@ -require 'rake' - -namespace :db do - desc "Dump the current SQLite3 or MySQL database to a sql file" - task :dump_sql do - load 'config/environment.rb' - abcs = ActiveRecord::Base.configurations - case abcs[RAILS_ENV]["adapter"] - when 'mysql' - ActiveRecord::Base.establish_connection(abcs[RAILS_ENV]) - File.open("db/#{RAILS_ENV}_data.sql", "w+") do |f| - if abcs[RAILS_ENV]["password"].blank? - f << `mysqldump -h #{abcs[RAILS_ENV]["host"]} -u #{abcs[RAILS_ENV]["username"]} #{abcs[RAILS_ENV]["database"]}` - else - f << `mysqldump -h #{abcs[RAILS_ENV]["host"]} -u #{abcs[RAILS_ENV]["username"]} -p#{abcs[RAILS_ENV]["password"]} #{abcs[RAILS_ENV]["database"]}` - end - end - when 'sqlite3' - ActiveRecord::Base.establish_connection(abcs[RAILS_ENV]) - File.open("db/#{RAILS_ENV}_data.sql", "w+") do |f| - f << `sqlite3 #{abcs[RAILS_ENV]["database"]} .dump` - end - else - raise "Task not supported by '#{abcs[RAILS_ENV]['adapter']}'" - end - end -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tasks/extract_fixtures.rake b/backup.rails2.3/lib/tasks/extract_fixtures.rake deleted file mode 100644 index f69683a3..00000000 --- a/backup.rails2.3/lib/tasks/extract_fixtures.rake +++ /dev/null @@ -1,17 +0,0 @@ -desc ' Create YAML test fixtures from data in an existing database. -Defaults to development database. Set RAILS_ENV to override (taken from Rails Recipes book).' -task :extract_fixtures => :environment do - sql = "SELECT * FROM %s" - skip_tables = ["schema_info", "sessions", "users"] - ActiveRecord::Base.establish_connection - (ActiveRecord::Base.connection.tables - skip_tables).each do |table_name| - i = "000" - File.open("#{RAILS_ROOT}/db/exported_fixtures/#{table_name}.yml", 'w' ) do |file| - data = ActiveRecord::Base.connection.select_all(sql % table_name) - file.write data.inject({}) { |hash, record| - hash["#{table_name}_#{i.succ!}"] = record - hash - }.to_yaml - end - end -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tasks/gems.rake b/backup.rails2.3/lib/tasks/gems.rake deleted file mode 100644 index 464b787f..00000000 --- a/backup.rails2.3/lib/tasks/gems.rake +++ /dev/null @@ -1,34 +0,0 @@ -desc "Copy third-party gems into ./lib" -task :freeze_other_gems do - # TODO Get this list from parsing environment.rb - libraries = %w(redcloth) - require 'rubygems' - require 'find' - - libraries.each do |library| - library_gem = Gem.cache.search(library).sort_by { |g| g.version }.last - puts "Freezing #{library} for #{library_gem.version}..." - - # TODO Add dependencies to list of libraries to freeze - #library_gem.dependencies.each { |g| libraries << g } - - folder_for_library = "#{library_gem.name}-#{library_gem.version}" - system "cd vendor; gem unpack -v '#{library_gem.version}' #{library_gem.name};" - - # Copy files recursively to ./lib - folder_for_library_with_lib = "vendor/#{folder_for_library}/lib/" - Find.find(folder_for_library_with_lib) do |original_file| - destination_file = "./lib/" + original_file.gsub(folder_for_library_with_lib, '') - - if File.directory?(original_file) - if !File.exist?(destination_file) - Dir.mkdir destination_file - end - else - File.copy original_file, destination_file - end - end - - system "rm -r vendor/#{folder_for_library}" - end -end diff --git a/backup.rails2.3/lib/tasks/load_exported_fixtures.rake b/backup.rails2.3/lib/tasks/load_exported_fixtures.rake deleted file mode 100644 index 10757471..00000000 --- a/backup.rails2.3/lib/tasks/load_exported_fixtures.rake +++ /dev/null @@ -1,8 +0,0 @@ -desc "Load exported fixtures (in db/exported_fixtures) into the current environment's database" -task :load_exported_fixtures => :environment do - require 'active_record/fixtures' - ActiveRecord::Base.establish_connection(RAILS_ENV.to_sym) - Dir.glob(File.join(RAILS_ROOT, 'db', 'exported_fixtures', '*.{yml,csv}')).each do |fixture_file| - Fixtures.create_fixtures('db/exported_fixtures', File.basename(fixture_file, '.*')) - end -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tasks/query_trace_toggle.rake b/backup.rails2.3/lib/tasks/query_trace_toggle.rake deleted file mode 100644 index a6321541..00000000 --- a/backup.rails2.3/lib/tasks/query_trace_toggle.rake +++ /dev/null @@ -1,50 +0,0 @@ -namespace :query_trace do - desc "Enables the query_trace plugin. Must restart server to take effect." - task :on => :environment do - unless File.exist?("#{RAILS_ROOT}/vendor/query_trace.tar.gz") - Dir.chdir("#{RAILS_ROOT}/vendor") do - url = "https://terralien.devguard.com/svn/projects/plugins/query_trace" - puts "Loading query_trace from #{url}..." - system "svn co #{url} query_trace" - system "tar zcf query_trace.tar.gz --exclude=.svn query_trace" - FileUtils.rm_rf("query_trace") - end - end - Dir.chdir("#{RAILS_ROOT}/vendor/plugins") do - system "tar zxf ../query_trace.tar.gz query_trace" - end - puts "QueryTrace plugin enabled. Must restart server to take effect." - end - - desc "Disables the query_trace plugin. Must restart server to take effect." - task :off => :environment do - FileUtils.rm_rf("#{RAILS_ROOT}/vendor/plugins/query_trace") - puts "QueryTrace plugin disabled. Must restart server to take effect." - end -end - -namespace :query_analyzer do - desc "Enables the query_analyzer plugin. Must restart server to take effect." - task :on => :environment do - unless File.exist?("#{RAILS_ROOT}/vendor/query_analyzer.tar.gz") - Dir.chdir("#{RAILS_ROOT}/vendor") do - url = "http://svn.nfectio.us/plugins/query_analyzer" - puts "Loading query_analyzer from #{url}..." - system "svn co #{url} query_analyzer" - system "tar zcf query_analyzer.tar.gz --exclude=.svn query_analyzer" - FileUtils.rm_rf("query_analyzer") - end - end - Dir.chdir("#{RAILS_ROOT}/vendor/plugins") do - system "tar zxf ../query_analyzer.tar.gz query_analyzer" - end - puts "QueryAnalyzer plugin enabled. Must restart server to take effect." - end - - desc "Disables the query_analyzer plugin. Must restart server to take effect." - task :off => :environment do - FileUtils.rm_rf("#{RAILS_ROOT}/vendor/plugins/query_analyzer") - puts "QueryAnalyzer plugin disabled. Must restart server to take effect." - end -end - diff --git a/backup.rails2.3/lib/tasks/reset_password.rake b/backup.rails2.3/lib/tasks/reset_password.rake deleted file mode 100644 index 6cc61a60..00000000 --- a/backup.rails2.3/lib/tasks/reset_password.rake +++ /dev/null @@ -1,23 +0,0 @@ -namespace :tracks do - desc 'Replace the password of USER with a new one.' - task :password => :environment do - require "highline/import" - - user = User.find_by_login(ENV['USER']) - if user.nil? - puts "Sorry, we couldn't find user '#{ENV['USER']}'. To specify a different user, pass USER=username to this task." - exit 0 - end - - puts "Changing Tracks password for #{ENV['USER']}." - password = ask("New password: ") { |q| q.echo = false } - password_confirmation = ask('Retype new password: ') { |q| q.echo = false } - - begin - user.change_password(password, password_confirmation) - rescue ActiveRecord::RecordInvalid - puts "Sorry, we couldn't change #{ENV['USER']}'s password: " - user.errors.each_full { |msg| puts "- #{msg}\n" } - end - end -end diff --git a/backup.rails2.3/lib/tasks/rspec.rake b/backup.rails2.3/lib/tasks/rspec.rake deleted file mode 100644 index dba3ffcc..00000000 --- a/backup.rails2.3/lib/tasks/rspec.rake +++ /dev/null @@ -1,144 +0,0 @@ -gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9 -rspec_gem_dir = nil -Dir["#{RAILS_ROOT}/vendor/gems/*"].each do |subdir| - rspec_gem_dir = subdir if subdir.gsub("#{RAILS_ROOT}/vendor/gems/","") =~ /^(\w+-)?rspec-(\d+)/ && File.exist?("#{subdir}/lib/spec/rake/spectask.rb") -end -rspec_plugin_dir = File.expand_path(File.dirname(__FILE__) + '/../../vendor/plugins/rspec') - -if rspec_gem_dir && (test ?d, rspec_plugin_dir) - raise "\n#{'*'*50}\nYou have rspec installed in both vendor/gems and vendor/plugins\nPlease pick one and dispose of the other.\n#{'*'*50}\n\n" -end - -if rspec_gem_dir - $LOAD_PATH.unshift("#{rspec_gem_dir}/lib") -elsif File.exist?(rspec_plugin_dir) - $LOAD_PATH.unshift("#{rspec_plugin_dir}/lib") -end - -# Don't load rspec if running "rake gems:*" -unless ARGV.any? {|a| a =~ /^gems/} - -begin - require 'spec/rake/spectask' -rescue MissingSourceFile - module Spec - module Rake - class SpecTask - def initialize(name) - task name do - # if rspec-rails is a configured gem, this will output helpful material and exit ... - require File.expand_path(File.join(File.dirname(__FILE__),"..","..","config","environment")) - - # ... otherwise, do this: - raise <<-MSG - -#{"*" * 80} -* You are trying to run an rspec rake task defined in -* #{__FILE__}, -* but rspec can not be found in vendor/gems, vendor/plugins or system gems. -#{"*" * 80} -MSG - end - end - end - end - end -end - -Rake.application.instance_variable_get('@tasks').delete('default') - -spec_prereq = File.exist?(File.join(RAILS_ROOT, 'config', 'database.yml')) ? "db:test:prepare" : :noop -task :noop do -end - -task :default => :spec -task :stats => "spec:statsetup" - -desc "Run all specs in spec directory (excluding plugin specs)" -Spec::Rake::SpecTask.new(:spec => spec_prereq) do |t| - t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] - t.spec_files = FileList['spec/**/*_spec.rb'] -end - -namespace :spec do - desc "Run all specs in spec directory with RCov (excluding plugin specs)" - Spec::Rake::SpecTask.new(:rcov) do |t| - t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] - t.spec_files = FileList['spec/**/*_spec.rb'] - t.rcov = true - t.rcov_opts = lambda do - IO.readlines("#{RAILS_ROOT}/spec/rcov.opts").map {|l| l.chomp.split " "}.flatten - end - end - - desc "Print Specdoc for all specs (excluding plugin specs)" - Spec::Rake::SpecTask.new(:doc) do |t| - t.spec_opts = ["--format", "specdoc", "--dry-run"] - t.spec_files = FileList['spec/**/*_spec.rb'] - end - - desc "Print Specdoc for all plugin examples" - Spec::Rake::SpecTask.new(:plugin_doc) do |t| - t.spec_opts = ["--format", "specdoc", "--dry-run"] - t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*') - end - - [:models, :controllers, :views, :helpers, :lib, :integration].each do |sub| - desc "Run the code examples in spec/#{sub}" - Spec::Rake::SpecTask.new(sub => spec_prereq) do |t| - t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] - t.spec_files = FileList["spec/#{sub}/**/*_spec.rb"] - end - end - - desc "Run the code examples in vendor/plugins (except RSpec's own)" - Spec::Rake::SpecTask.new(:plugins => spec_prereq) do |t| - t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] - t.spec_files = FileList['vendor/plugins/**/spec/**/*_spec.rb'].exclude('vendor/plugins/rspec/*').exclude("vendor/plugins/rspec-rails/*") - end - - namespace :plugins do - desc "Runs the examples for rspec_on_rails" - Spec::Rake::SpecTask.new(:rspec_on_rails) do |t| - t.spec_opts = ['--options', "\"#{RAILS_ROOT}/spec/spec.opts\""] - t.spec_files = FileList['vendor/plugins/rspec-rails/spec/**/*_spec.rb'] - end - end - - # Setup specs for stats - task :statsetup do - require 'code_statistics' - ::STATS_DIRECTORIES << %w(Model\ specs spec/models) if File.exist?('spec/models') - ::STATS_DIRECTORIES << %w(View\ specs spec/views) if File.exist?('spec/views') - ::STATS_DIRECTORIES << %w(Controller\ specs spec/controllers) if File.exist?('spec/controllers') - ::STATS_DIRECTORIES << %w(Helper\ specs spec/helpers) if File.exist?('spec/helpers') - ::STATS_DIRECTORIES << %w(Library\ specs spec/lib) if File.exist?('spec/lib') - ::STATS_DIRECTORIES << %w(Routing\ specs spec/routing) if File.exist?('spec/routing') - ::STATS_DIRECTORIES << %w(Integration\ specs spec/integration) if File.exist?('spec/integration') - ::CodeStatistics::TEST_TYPES << "Model specs" if File.exist?('spec/models') - ::CodeStatistics::TEST_TYPES << "View specs" if File.exist?('spec/views') - ::CodeStatistics::TEST_TYPES << "Controller specs" if File.exist?('spec/controllers') - ::CodeStatistics::TEST_TYPES << "Helper specs" if File.exist?('spec/helpers') - ::CodeStatistics::TEST_TYPES << "Library specs" if File.exist?('spec/lib') - ::CodeStatistics::TEST_TYPES << "Routing specs" if File.exist?('spec/routing') - ::CodeStatistics::TEST_TYPES << "Integration specs" if File.exist?('spec/integration') - end - - namespace :db do - namespace :fixtures do - desc "Load fixtures (from spec/fixtures) into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z." - task :load => :environment do - ActiveRecord::Base.establish_connection(Rails.env) - base_dir = File.join(Rails.root, 'spec', 'fixtures') - fixtures_dir = ENV['FIXTURES_DIR'] ? File.join(base_dir, ENV['FIXTURES_DIR']) : base_dir - - require 'active_record/fixtures' - (ENV['FIXTURES'] ? ENV['FIXTURES'].split(/,/).map {|f| File.join(fixtures_dir, f) } : Dir.glob(File.join(fixtures_dir, '*.{yml,csv}'))).each do |fixture_file| - Fixtures.create_fixtures(File.dirname(fixture_file), File.basename(fixture_file, '.*')) - end - end - end - end -end - -end diff --git a/backup.rails2.3/lib/tasks/setup_tracks.rake b/backup.rails2.3/lib/tasks/setup_tracks.rake deleted file mode 100644 index 0881dfb3..00000000 --- a/backup.rails2.3/lib/tasks/setup_tracks.rake +++ /dev/null @@ -1,15 +0,0 @@ -desc "Initialises the installation, copy the *.tmpl files and directories to versions named without the .tmpl extension. It won't overwrite the files and directories if you've already copied them. You need to manually copy database.yml.tmpl -> database.yml and fill in the details before you run this task." -task :setup_tracks => :environment do - # Check the root directory for template files - FileList["*.tmpl"].each do |template_file| - f = File.basename(template_file) # with suffix - f_only = File.basename(template_file,".tmpl") # without suffix - if File.exists?(f_only) - puts f_only + " already exists" - else - cp_r(f, f_only) - puts f_only + " created" - end - end - -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tasks/upgrade_sqlite_db.rake b/backup.rails2.3/lib/tasks/upgrade_sqlite_db.rake deleted file mode 100644 index 8e96fb18..00000000 --- a/backup.rails2.3/lib/tasks/upgrade_sqlite_db.rake +++ /dev/null @@ -1,40 +0,0 @@ -desc "Updates sqlite/sqlite3 databases created under Tracks 1.03 to the format required for Tracks 1.04. After this is done, you should be able to keep up to date with changes in the schema by running rake db:migrate." -task :upgrade_sqlite_db => :environment do - # Change the three lines below appropriately for your setup - old_db = "tracks_103.db" - new_db = "tracks_104.db" - cmd = "sqlite3" - replace_string = "update todos set done='f' where done=0;\nupdate todos set done='t' where done=1;\nupdate contexts set hide='f' where hide=0;\nupdate contexts set hide='t' where hide=1;\nupdate projects set done='f' where done=0;\nupdate projects set done='t' where done=1;\nCREATE TABLE 'schema_info' (\n 'version' INTEGER default NULL\n);\nINSERT INTO \"schema_info\" VALUES(1);\nCOMMIT;" - - # cd to the db directory - cd("db") do - # Dump the old db into the temp file and replace the tinyints with booleans - `#{cmd} #{old_db} .dump | sed "s/tinyint(4) NOT NULL default '0'/boolean default 'f'/" > temp.sql` - # Create a second sqldump file for writing - sqldump = File.open("temp2.sql", "w+") - File.open("temp.sql") do |file| - file.each_line do |line| - # If COMMIT is on the line, insert the replace string - # else just write the line back in - # This effectively replaces COMMIT with the replace string - if /COMMIT/ =~ line - sqldump.write replace_string - else - sqldump.write line - end - end - sqldump.close - end - - # Read the second dump back in to a new db - system "#{cmd} #{new_db} < temp2.sql" - puts "Created the a new database called #{new_db}." - # Clean up the temp files - rm("temp.sql") - rm("temp2.sql") - puts "Temporary files cleaned up." - end - - # rake db:migrate - puts "Now check the database and run 'rake db:migrate' in the root of your Tracks installation." -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tracks/config.rb b/backup.rails2.3/lib/tracks/config.rb deleted file mode 100644 index 0ca04f97..00000000 --- a/backup.rails2.3/lib/tracks/config.rb +++ /dev/null @@ -1,27 +0,0 @@ -module Tracks - class Config - def self.salt - SITE_CONFIG['salt'] - end - - def self.auth_schemes - SITE_CONFIG['authentication_schemes'] || [] - end - - def self.openid_enabled? - auth_schemes.include?('open_id') - end - - def self.cas_enabled? - auth_schemes.include?('cas') - end - - def self.prefered_auth? - if SITE_CONFIG['prefered_auth'] - SITE_CONFIG['prefered_auth'] - else - auth_schemes.first - end - end - end -end \ No newline at end of file diff --git a/backup.rails2.3/lib/tracks/source_view.rb b/backup.rails2.3/lib/tracks/source_view.rb deleted file mode 100644 index 8cb17ca8..00000000 --- a/backup.rails2.3/lib/tracks/source_view.rb +++ /dev/null @@ -1,68 +0,0 @@ -# Inspiration from Bruce Williams [http://codefluency.com/articles/2006/07/01/rails-views-getting-in-context/] -module Tracks - - module SourceViewSwitching - - class Responder - - def initialize(source_view) - @source_view = source_view.underscore.gsub(/\s+/,'_').to_sym rescue nil - end - - def nil? - yield if @source_view.nil? && block_given? - end - - def context - yield if :context == @source_view && block_given? - end - - def method_missing(check_source_view,*args) - yield if check_source_view == @source_view && block_given? - end - - end - - module Controller - - def self.included(base) - base.send(:helper, Tracks::SourceViewSwitching::Helper) - base.send(:helper_method, :source_view) - end - - def source_view_is( s ) - s == (params[:_source_view] || @source_view).to_sym - end - - def source_view_is_one_of( *s ) - s.include?(params[:_source_view].to_sym) - end - - def source_view - responder = Tracks::SourceViewSwitching::Responder.new(params[:_source_view] || @source_view) - block_given? ? yield(responder) : responder - end - - end - - module Helper - - def source_view_tag(name) - hidden_field_tag :_source_view, name.underscore.gsub(/\s+/,'_') - end - - def source_view_is( s ) - s == (params[:_source_view] || @source_view).to_sym - end - - def source_view_is_one_of( *s ) - s.include?(params[:_source_view].to_sym) - end - - end - - end - -end - -ActionController::Base.send(:include, Tracks::SourceViewSwitching::Controller) diff --git a/backup.rails2.3/lib/tracks/todo_list.rb b/backup.rails2.3/lib/tracks/todo_list.rb deleted file mode 100644 index b1a32229..00000000 --- a/backup.rails2.3/lib/tracks/todo_list.rb +++ /dev/null @@ -1,59 +0,0 @@ -module Tracks - module TodoList - # TODO: this module should be deprecated. This could mostly (all?) be replaced by named scopes) - - def not_done_todos(opts={}) - @not_done_todos ||= self.find_not_done_todos(opts) - end - - def done_todos - @done_todos ||= self.find_done_todos - end - - def deferred_todos - @deferred_todos ||= self.find_deferred_todos - end - - def find_not_done_todos(opts={}) - with_not_done_scope(opts) do - self.todos.find(:all, :order => "todos.due IS NULL, todos.due ASC, todos.created_at ASC") - end - end - - def find_deferred_todos(opts={}) - self.todos.find_in_state(:all, :deferred, :order => "todos.due IS NULL, todos.due ASC, todos.created_at ASC") - end - - def find_done_todos - self.todos.completed.all(:order => "todos.completed_at DESC", :limit => self.user.prefs.show_number_completed) - end - - def not_done_todo_count(opts={}) - with_not_done_scope(opts) do - self.todos.count - end - end - - def with_not_done_scope(opts={}) - conditions = ["todos.state = ?", 'active'] - if opts.has_key?(:include_project_hidden_todos) && (opts[:include_project_hidden_todos] == true) - conditions = ["(todos.state = ? OR todos.state = ?)", 'active', 'project_hidden'] - end - if opts.has_key?(:tag) - conditions = ["todos.state = ? AND taggings.tag_id = ?", 'active', opts[:tag]] - end - self.todos.send :with_scope, :find => {:conditions => conditions, :include => [:taggings]} do - yield - end - end - - def done_todo_count - self.todos.count_in_state(:completed) - end - - def deferred_todo_count - self.todos.count_in_state(:deferred) - end - - end -end diff --git a/backup.rails2.3/mongrel_workaround.rb b/backup.rails2.3/mongrel_workaround.rb deleted file mode 100644 index 60b207b9..00000000 --- a/backup.rails2.3/mongrel_workaround.rb +++ /dev/null @@ -1,107 +0,0 @@ -# adapted from https://gist.github.com/471663 and https://rails.lighthouseapp.com/projects/8994/tickets/4690-mongrel-doesnt-work-with-rails-238 - -def check_mongrel_around_115 -begin - # Gem.available? is deprecated from rubygems 1.8.2 - Gem::Specification::find_by_name "mongrel", "~>1.1.5" - rescue - if RUBY_VERSION[2] == "9" - false - else - Gem.available?('mongrel', '~>1.1.5') - end - end -end - -mongrel115 = check_mongrel_around_115 - -if Rails.version == '2.3.14' && mongrel115 && self.class.const_defined?(:Mongrel) - - # Pulled right from latest rack. Old looked like this in 1.1.0 version. - # - # def [](k) - # super(@names[k] ||= @names[k.downcase]) - # end - # - module Rack - module Utils - class HeaderHash < Hash - def [](k) - super(@names[k]) if @names[k] - super(@names[k.downcase]) - end - end - end - end - - # Code pulled from the ticket above. - # - class Mongrel::CGIWrapper - def header_with_rails_fix(options = 'text/html') - @head['cookie'] = options.delete('cookie').flatten.map { |v| v.sub(/^\n/,'') } if options.class != String and options['cookie'] - header_without_rails_fix(options) - end - alias_method_chain :header, :rails_fix - end - - # Pulled right from 2.3.10 ActionPack. Simple diff was - # - # if headers.include?('Set-Cookie') - # headers['cookie'] = headers.delete('Set-Cookie').split("\n") - # end - # - # to - # - # if headers['Set-Cookie'] - # headers['cookie'] = headers.delete('Set-Cookie').split("\n") - # end - # - module ActionController - class CGIHandler - def self.dispatch_cgi(app, cgi, out = $stdout) - env = cgi.__send__(:env_table) - env.delete "HTTP_CONTENT_LENGTH" - - cgi.stdinput.extend ProperStream - - env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/" - - env.update({ - "rack.version" => [0,1], - "rack.input" => cgi.stdinput, - "rack.errors" => $stderr, - "rack.multithread" => false, - "rack.multiprocess" => true, - "rack.run_once" => false, - "rack.url_scheme" => ["yes", "on", "1"].include?(env["HTTPS"]) ? "https" : "http" - }) - - env["QUERY_STRING"] ||= "" - env["HTTP_VERSION"] ||= env["SERVER_PROTOCOL"] - env["REQUEST_PATH"] ||= "/" - env.delete "PATH_INFO" if env["PATH_INFO"] == "" - - status, headers, body = app.call(env) - begin - out.binmode if out.respond_to?(:binmode) - out.sync = false if out.respond_to?(:sync=) - - headers['Status'] = status.to_s - - if headers['Set-Cookie'] - headers['cookie'] = headers.delete('Set-Cookie').split("\n") - end - - out.write(cgi.header(headers)) - - body.each { |part| - out.write part - out.flush if out.respond_to?(:flush) - } - ensure - body.close if body.respond_to?(:close) - end - end - end - end -end diff --git a/backup.rails2.3/new_rails_defaults.rb b/backup.rails2.3/new_rails_defaults.rb deleted file mode 100644 index c94db0a6..00000000 --- a/backup.rails2.3/new_rails_defaults.rb +++ /dev/null @@ -1,21 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# These settings change the behavior of Rails 2 apps and will be defaults -# for Rails 3. You can remove this initializer when Rails 3 is released. - -if defined?(ActiveRecord) - # Include Active Record class name as root for JSON serialized output. - ActiveRecord::Base.include_root_in_json = true - - # Store the full class name (including module namespace) in STI type column. - ActiveRecord::Base.store_full_sti_class = true -end - -ActionController::Routing.generate_best_match = false - -# Use ISO 8601 format for JSON serialized times and dates. -ActiveSupport.use_standard_json_time_format = true - -# Don't escape HTML entities in JSON, leave that for the #json_escape helper. -# if you're including raw json in an HTML page. -ActiveSupport.escape_html_entities_in_json = false \ No newline at end of file diff --git a/backup.rails2.3/plugins/extra_validations/init.rb b/backup.rails2.3/plugins/extra_validations/init.rb deleted file mode 100644 index 17709ad4..00000000 --- a/backup.rails2.3/plugins/extra_validations/init.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'extra_validations' -ActiveRecord::Base.extend ExtraValidations \ No newline at end of file diff --git a/backup.rails2.3/plugins/extra_validations/lib/extra_validations.rb b/backup.rails2.3/plugins/extra_validations/lib/extra_validations.rb deleted file mode 100644 index be50b659..00000000 --- a/backup.rails2.3/plugins/extra_validations/lib/extra_validations.rb +++ /dev/null @@ -1,29 +0,0 @@ -module ExtraValidations - - # Validates the value of the specified attribute by checking for a forbidden string - # - # class Person < ActiveRecord::Base - # validates_does_not_contain :first_name, :string => ',' - # end - # - # A string must be provided or else an exception will be raised. - # - # Configuration options: - # * message - A custom error message (default is: "is invalid") - # * string - The string to verify is not included (note: must be supplied!) - # * on Specifies when this validation is active (default is :save, other options :create, :update) - # * if - Specifies a method, proc or string to call to determine if the validation should - # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The - # method, proc or string should return or evaluate to a true or false value. - def validates_does_not_contain(*attr_names) - configuration = { :message => I18n.translate('activerecord.errors.messages')[:invalid], :on => :save, :string => nil } - configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash) - - raise(ArgumentError, "A string must be supplied as the :string option of the configuration hash") unless configuration[:string].is_a?(String) - - validates_each(attr_names, configuration) do |record, attr_name, value| - record.errors.add(attr_name, configuration[:message]) if value.to_s =~ Regexp.new(Regexp.escape(configuration[:string])) - end - end - -end diff --git a/backup.rails2.3/plugins/open_id_authentication/CHANGELOG b/backup.rails2.3/plugins/open_id_authentication/CHANGELOG deleted file mode 100644 index 7349bd3c..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/CHANGELOG +++ /dev/null @@ -1,35 +0,0 @@ -* Fake HTTP method from OpenID server since they only support a GET. Eliminates the need to set an extra route to match the server's reply. [Josh Peek] - -* OpenID 2.0 recommends that forms should use the field name "openid_identifier" rather than "openid_url" [Josh Peek] - -* Return open_id_response.display_identifier to the application instead of .endpoints.claimed_id. [nbibler] - -* Add Timeout protection [Rick] - -* An invalid identity url passed through authenticate_with_open_id will no longer raise an InvalidOpenId exception. Instead it will return Result[:missing] to the completion block. - -* Allow a return_to option to be used instead of the requested url [Josh Peek] - -* Updated plugin to use Ruby OpenID 2.x.x [Josh Peek] - -* Tied plugin to ruby-openid 1.1.4 gem until we can make it compatible with 2.x [DHH] - -* Use URI instead of regexps to normalize the URL and gain free, better matching #8136 [dkubb] - -* Allow -'s in #normalize_url [Rick] - -* remove instance of mattr_accessor, it was breaking tests since they don't load ActiveSupport. Fix Timeout test [Rick] - -* Throw a InvalidOpenId exception instead of just a RuntimeError when the URL can't be normalized [DHH] - -* Just use the path for the return URL, so extra query parameters don't interfere [DHH] - -* Added a new default database-backed store after experiencing trouble with the filestore on NFS. The file store is still available as an option [DHH] - -* Added normalize_url and applied it to all operations going through the plugin [DHH] - -* Removed open_id? as the idea of using the same input box for both OpenID and username has died -- use using_open_id? instead (which checks for the presence of params[:openid_url] by default) [DHH] - -* Added OpenIdAuthentication::Result to make it easier to deal with default situations where you don't care to do something particular for each error state [DHH] - -* Stop relying on root_url being defined, we can just grab the current url instead [DHH] \ No newline at end of file diff --git a/backup.rails2.3/plugins/open_id_authentication/README b/backup.rails2.3/plugins/open_id_authentication/README deleted file mode 100644 index 807cdc75..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/README +++ /dev/null @@ -1,231 +0,0 @@ -OpenIdAuthentication -==================== - -Provides a thin wrapper around the excellent ruby-openid gem from JanRan. Be sure to install that first: - - gem install ruby-openid - -To understand what OpenID is about and how it works, it helps to read the documentation for lib/openid/consumer.rb -from that gem. - -The specification used is http://openid.net/specs/openid-authentication-2_0.html. - - -Prerequisites -============= - -OpenID authentication uses the session, so be sure that you haven't turned that off. It also relies on a number of -database tables to store the authentication keys. So you'll have to run the migration to create these before you get started: - - rake open_id_authentication:db:create - -Or, use the included generators to install or upgrade: - - ./script/generate open_id_authentication_tables MigrationName - ./script/generate upgrade_open_id_authentication_tables MigrationName - -Alternatively, you can use the file-based store, which just relies on on tmp/openids being present in RAILS_ROOT. But be aware that this store only works if you have a single application server. And it's not safe to use across NFS. It's recommended that you use the database store if at all possible. To use the file-based store, you'll also have to add this line to your config/environment.rb: - - OpenIdAuthentication.store = :file - -This particular plugin also relies on the fact that the authentication action allows for both POST and GET operations. -If you're using RESTful authentication, you'll need to explicitly allow for this in your routes.rb. - -The plugin also expects to find a root_url method that points to the home page of your site. You can accomplish this by using a root route in config/routes.rb: - - map.root :controller => 'articles' - -This plugin relies on Rails Edge revision 6317 or newer. - - -Example -======= - -This example is just to meant to demonstrate how you could use OpenID authentication. You might well want to add -salted hash logins instead of plain text passwords and other requirements on top of this. Treat it as a starting point, -not a destination. - -Note that the User model referenced in the simple example below has an 'identity_url' attribute. You will want to add the same or similar field to whatever -model you are using for authentication. - -Also of note is the following code block used in the example below: - - authenticate_with_open_id do |result, identity_url| - ... - end - -In the above code block, 'identity_url' will need to match user.identity_url exactly. 'identity_url' will be a string in the form of 'http://example.com' - -If you are storing just 'example.com' with your user, the lookup will fail. - -There is a handy method in this plugin called 'normalize_url' that will help with validating OpenID URLs. - - OpenIdAuthentication.normalize_url(user.identity_url) - -The above will return a standardized version of the OpenID URL - the above called with 'example.com' will return 'http://example.com/' -It will also raise an InvalidOpenId exception if the URL is determined to not be valid. -Use the above code in your User model and validate OpenID URLs before saving them. - -config/routes.rb - - map.root :controller => 'articles' - map.resource :session - - -app/views/sessions/new.erb - - <% form_tag(session_url) do %> -

- - <%= text_field_tag "name" %> -

- -

- - <%= password_field_tag %> -

- -

- ...or use: -

- -

- - <%= text_field_tag "openid_identifier" %> -

- -

- <%= submit_tag 'Sign in', :disable_with => "Signing in…" %> -

- <% end %> - -app/controllers/sessions_controller.rb - class SessionsController < ApplicationController - def create - if using_open_id? - open_id_authentication - else - password_authentication(params[:name], params[:password]) - end - end - - - protected - def password_authentication(name, password) - if @current_user = @account.users.authenticate(params[:name], params[:password]) - successful_login - else - failed_login "Sorry, that username/password doesn't work" - end - end - - def open_id_authentication - authenticate_with_open_id do |result, identity_url| - if result.successful? - if @current_user = @account.users.find_by_identity_url(identity_url) - successful_login - else - failed_login "Sorry, no user by that identity URL exists (#{identity_url})" - end - else - failed_login result.message - end - end - end - - - private - def successful_login - session[:user_id] = @current_user.id - redirect_to(root_url) - end - - def failed_login(message) - flash[:error] = message - redirect_to(new_session_url) - end - end - - - -If you're fine with the result messages above and don't need individual logic on a per-failure basis, -you can collapse the case into a mere boolean: - - def open_id_authentication - authenticate_with_open_id do |result, identity_url| - if result.successful? && @current_user = @account.users.find_by_identity_url(identity_url) - successful_login - else - failed_login(result.message || "Sorry, no user by that identity URL exists (#{identity_url})") - end - end - end - - -Simple Registration OpenID Extension -==================================== - -Some OpenID Providers support this lightweight profile exchange protocol. See more: http://www.openidenabled.com/openid/simple-registration-extension - -You can support it in your app by changing #open_id_authentication - - def open_id_authentication(identity_url) - # Pass optional :required and :optional keys to specify what sreg fields you want. - # Be sure to yield registration, a third argument in the #authenticate_with_open_id block. - authenticate_with_open_id(identity_url, - :required => [ :nickname, :email ], - :optional => :fullname) do |result, identity_url, registration| - case result.status - when :missing - failed_login "Sorry, the OpenID server couldn't be found" - when :invalid - failed_login "Sorry, but this does not appear to be a valid OpenID" - when :canceled - failed_login "OpenID verification was canceled" - when :failed - failed_login "Sorry, the OpenID verification failed" - when :successful - if @current_user = @account.users.find_by_identity_url(identity_url) - assign_registration_attributes!(registration) - - if current_user.save - successful_login - else - failed_login "Your OpenID profile registration failed: " + - @current_user.errors.full_messages.to_sentence - end - else - failed_login "Sorry, no user by that identity URL exists" - end - end - end - end - - # registration is a hash containing the valid sreg keys given above - # use this to map them to fields of your user model - def assign_registration_attributes!(registration) - model_to_registration_mapping.each do |model_attribute, registration_attribute| - unless registration[registration_attribute].blank? - @current_user.send("#{model_attribute}=", registration[registration_attribute]) - end - end - end - - def model_to_registration_mapping - { :login => 'nickname', :email => 'email', :display_name => 'fullname' } - end - -Attribute Exchange OpenID Extension -=================================== - -Some OpenID providers also support the OpenID AX (attribute exchange) protocol for exchanging identity information between endpoints. See more: http://openid.net/specs/openid-attribute-exchange-1_0.html - -Accessing AX data is very similar to the Simple Registration process, described above -- just add the URI identifier for the AX field to your :optional or :required parameters. For example: - - authenticate_with_open_id(identity_url, - :required => [ :email, 'http://schema.openid.net/birthDate' ]) do |result, identity_url, registration| - -This would provide the sreg data for :email, and the AX data for 'http://schema.openid.net/birthDate' - - - -Copyright (c) 2007 David Heinemeier Hansson, released under the MIT license \ No newline at end of file diff --git a/backup.rails2.3/plugins/open_id_authentication/Rakefile b/backup.rails2.3/plugins/open_id_authentication/Rakefile deleted file mode 100644 index 31074b85..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/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 open_id_authentication plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the open_id_authentication plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'OpenIdAuthentication' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/backup.rails2.3/plugins/open_id_authentication/generators/open_id_authentication_tables/open_id_authentication_tables_generator.rb b/backup.rails2.3/plugins/open_id_authentication/generators/open_id_authentication_tables/open_id_authentication_tables_generator.rb deleted file mode 100644 index 6f78afc7..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/generators/open_id_authentication_tables/open_id_authentication_tables_generator.rb +++ /dev/null @@ -1,11 +0,0 @@ -class OpenIdAuthenticationTablesGenerator < Rails::Generator::NamedBase - def initialize(runtime_args, runtime_options = {}) - super - end - - def manifest - record do |m| - m.migration_template 'migration.rb', 'db/migrate' - end - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/generators/open_id_authentication_tables/templates/migration.rb b/backup.rails2.3/plugins/open_id_authentication/generators/open_id_authentication_tables/templates/migration.rb deleted file mode 100644 index ef2a0cfb..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/generators/open_id_authentication_tables/templates/migration.rb +++ /dev/null @@ -1,20 +0,0 @@ -class <%= class_name %> < ActiveRecord::Migration - def self.up - create_table :open_id_authentication_associations, :force => true do |t| - t.integer :issued, :lifetime - t.string :handle, :assoc_type - t.binary :server_url, :secret - end - - create_table :open_id_authentication_nonces, :force => true do |t| - t.integer :timestamp, :null => false - t.string :server_url, :null => true - t.string :salt, :null => false - end - end - - def self.down - drop_table :open_id_authentication_associations - drop_table :open_id_authentication_nonces - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/generators/upgrade_open_id_authentication_tables/templates/migration.rb b/backup.rails2.3/plugins/open_id_authentication/generators/upgrade_open_id_authentication_tables/templates/migration.rb deleted file mode 100644 index d13bbab2..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/generators/upgrade_open_id_authentication_tables/templates/migration.rb +++ /dev/null @@ -1,26 +0,0 @@ -class <%= class_name %> < ActiveRecord::Migration - def self.up - drop_table :open_id_authentication_settings - drop_table :open_id_authentication_nonces - - create_table :open_id_authentication_nonces, :force => true do |t| - t.integer :timestamp, :null => false - t.string :server_url, :null => true - t.string :salt, :null => false - end - end - - def self.down - drop_table :open_id_authentication_nonces - - create_table :open_id_authentication_nonces, :force => true do |t| - t.integer :created - t.string :nonce - end - - create_table :open_id_authentication_settings, :force => true do |t| - t.string :setting - t.binary :value - end - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/generators/upgrade_open_id_authentication_tables/upgrade_open_id_authentication_tables_generator.rb b/backup.rails2.3/plugins/open_id_authentication/generators/upgrade_open_id_authentication_tables/upgrade_open_id_authentication_tables_generator.rb deleted file mode 100644 index 02fddd7f..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/generators/upgrade_open_id_authentication_tables/upgrade_open_id_authentication_tables_generator.rb +++ /dev/null @@ -1,11 +0,0 @@ -class UpgradeOpenIdAuthenticationTablesGenerator < Rails::Generator::NamedBase - def initialize(runtime_args, runtime_options = {}) - super - end - - def manifest - record do |m| - m.migration_template 'migration.rb', 'db/migrate' - end - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/init.rb b/backup.rails2.3/plugins/open_id_authentication/init.rb deleted file mode 100644 index 808c7bdb..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/init.rb +++ /dev/null @@ -1,18 +0,0 @@ -if config.respond_to?(:gems) - config.gem 'ruby-openid', :lib => 'openid', :version => '>=2.0.4' -else - begin - require 'openid' - rescue LoadError - begin - gem 'ruby-openid', '>=2.0.4' - rescue Gem::LoadError - puts "Install the ruby-openid gem to enable OpenID support" - end - end -end - -config.to_prepare do - OpenID::Util.logger = Rails.logger - ActionController::Base.send :include, OpenIdAuthentication -end diff --git a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication.rb b/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication.rb deleted file mode 100644 index b485c5fe..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication.rb +++ /dev/null @@ -1,240 +0,0 @@ -require 'uri' -require 'openid/extensions/sreg' -require 'openid/extensions/ax' -require 'openid/store/filesystem' - -require File.dirname(__FILE__) + '/open_id_authentication/association' -require File.dirname(__FILE__) + '/open_id_authentication/nonce' -require File.dirname(__FILE__) + '/open_id_authentication/db_store' -require File.dirname(__FILE__) + '/open_id_authentication/request' -require File.dirname(__FILE__) + '/open_id_authentication/timeout_fixes' if OpenID::VERSION == "2.0.4" - -module OpenIdAuthentication - OPEN_ID_AUTHENTICATION_DIR = RAILS_ROOT + "/tmp/openids" - - def self.store - @@store - end - - def self.store=(*store_option) - store, *parameters = *([ store_option ].flatten) - - @@store = case store - when :db - OpenIdAuthentication::DbStore.new - when :file - OpenID::Store::Filesystem.new(OPEN_ID_AUTHENTICATION_DIR) - else - store - end - end - - self.store = :db - - class InvalidOpenId < StandardError - end - - class Result - ERROR_MESSAGES = { - :missing => "Sorry, the OpenID server couldn't be found", - :invalid => "Sorry, but this does not appear to be a valid OpenID", - :canceled => "OpenID verification was canceled", - :failed => "OpenID verification failed", - :setup_needed => "OpenID verification needs setup" - } - - def self.[](code) - new(code) - end - - def initialize(code) - @code = code - end - - def status - @code - end - - ERROR_MESSAGES.keys.each { |state| define_method("#{state}?") { @code == state } } - - def successful? - @code == :successful - end - - def unsuccessful? - ERROR_MESSAGES.keys.include?(@code) - end - - def message - ERROR_MESSAGES[@code] - end - end - - # normalizes an OpenID according to http://openid.net/specs/openid-authentication-2_0.html#normalization - def self.normalize_identifier(identifier) - # clean up whitespace - identifier = identifier.to_s.strip - - # if an XRI has a prefix, strip it. - identifier.gsub!(/xri:\/\//i, '') - - # dodge XRIs -- TODO: validate, don't just skip. - unless ['=', '@', '+', '$', '!', '('].include?(identifier.at(0)) - # does it begin with http? if not, add it. - identifier = "http://#{identifier}" unless identifier =~ /^http/i - - # strip any fragments - identifier.gsub!(/\#(.*)$/, '') - - begin - uri = URI.parse(identifier) - uri.scheme = uri.scheme.downcase # URI should do this - identifier = uri.normalize.to_s - rescue URI::InvalidURIError - raise InvalidOpenId.new("#{identifier} is not an OpenID identifier") - end - end - - return identifier - end - - # deprecated for OpenID 2.0, where not all OpenIDs are URLs - def self.normalize_url(url) - ActiveSupport::Deprecation.warn "normalize_url has been deprecated, use normalize_identifier instead" - self.normalize_identifier(url) - end - - protected - def normalize_url(url) - OpenIdAuthentication.normalize_url(url) - end - - def normalize_identifier(url) - OpenIdAuthentication.normalize_identifier(url) - end - - # The parameter name of "openid_identifier" is used rather than the Rails convention "open_id_identifier" - # because that's what the specification dictates in order to get browser auto-complete working across sites - def using_open_id?(identity_url = nil) #:doc: - identity_url ||= params[:openid_identifier] || params[:openid_url] - !identity_url.blank? || params[:open_id_complete] - end - - def authenticate_with_open_id(identity_url = nil, options = {}, &block) #:doc: - identity_url ||= params[:openid_identifier] || params[:openid_url] - - if params[:open_id_complete].nil? - begin_open_id_authentication(identity_url, options, &block) - else - complete_open_id_authentication(&block) - end - end - - private - def begin_open_id_authentication(identity_url, options = {}) - identity_url = normalize_identifier(identity_url) - return_to = options.delete(:return_to) - method = options.delete(:method) - - options[:required] ||= [] # reduces validation later - options[:optional] ||= [] - - open_id_request = open_id_consumer.begin(identity_url) - add_simple_registration_fields(open_id_request, options) - add_ax_fields(open_id_request, options) - redirect_to(open_id_redirect_url(open_id_request, return_to, method)) - rescue OpenIdAuthentication::InvalidOpenId => e - yield Result[:invalid], identity_url, nil - rescue OpenID::OpenIDError, Timeout::Error => e - logger.error("[OPENID] #{e}") - yield Result[:missing], identity_url, nil - end - - def complete_open_id_authentication - params_with_path = params.reject { |key, value| request.path_parameters[key] } - params_with_path.delete(:format) - open_id_response = timeout_protection_from_identity_server { open_id_consumer.complete(params_with_path, requested_url) } - identity_url = normalize_identifier(open_id_response.display_identifier) if open_id_response.display_identifier - - case open_id_response.status - when OpenID::Consumer::SUCCESS - profile_data = {} - - # merge the SReg data and the AX data into a single hash of profile data - [ OpenID::SReg::Response, OpenID::AX::FetchResponse ].each do |data_response| - if data_response.from_success_response( open_id_response ) - profile_data.merge! data_response.from_success_response( open_id_response ).data - end - end - - yield Result[:successful], identity_url, profile_data - when OpenID::Consumer::CANCEL - yield Result[:canceled], identity_url, nil - when OpenID::Consumer::FAILURE - yield Result[:failed], identity_url, nil - when OpenID::Consumer::SETUP_NEEDED - yield Result[:setup_needed], open_id_response.setup_url, nil - end - end - - def open_id_consumer - OpenID::Consumer.new(session, OpenIdAuthentication.store) - end - - def add_simple_registration_fields(open_id_request, fields) - sreg_request = OpenID::SReg::Request.new - - # filter out AX identifiers (URIs) - required_fields = fields[:required].collect { |f| f.to_s unless f =~ /^https?:\/\// }.compact - optional_fields = fields[:optional].collect { |f| f.to_s unless f =~ /^https?:\/\// }.compact - - sreg_request.request_fields(required_fields, true) unless required_fields.blank? - sreg_request.request_fields(optional_fields, false) unless optional_fields.blank? - sreg_request.policy_url = fields[:policy_url] if fields[:policy_url] - open_id_request.add_extension(sreg_request) - end - - def add_ax_fields( open_id_request, fields ) - ax_request = OpenID::AX::FetchRequest.new - - # look through the :required and :optional fields for URIs (AX identifiers) - fields[:required].each do |f| - next unless f =~ /^https?:\/\// - ax_request.add( OpenID::AX::AttrInfo.new( f, nil, true ) ) - end - - fields[:optional].each do |f| - next unless f =~ /^https?:\/\// - ax_request.add( OpenID::AX::AttrInfo.new( f, nil, false ) ) - end - - open_id_request.add_extension( ax_request ) - end - - def open_id_redirect_url(open_id_request, return_to = nil, method = nil) - open_id_request.return_to_args['_method'] = (method || request.method).to_s - open_id_request.return_to_args['open_id_complete'] = '1' - open_id_request.redirect_url(root_url, return_to || requested_url) - end - - def requested_url - relative_url_root = self.class.respond_to?(:relative_url_root) ? - self.class.relative_url_root.to_s : - request.relative_url_root - "#{request.protocol}#{request.host_with_port}#{ActionController::Base.relative_url_root}#{request.path}" - end - - def timeout_protection_from_identity_server - yield - rescue Timeout::Error - Class.new do - def status - OpenID::FAILURE - end - - def msg - "Identity server timed out" - end - end.new - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/association.rb b/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/association.rb deleted file mode 100644 index 9654eaeb..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/association.rb +++ /dev/null @@ -1,9 +0,0 @@ -module OpenIdAuthentication - class Association < ActiveRecord::Base - set_table_name :open_id_authentication_associations - - def from_record - OpenID::Association.new(handle, secret, issued, lifetime, assoc_type) - end - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/db_store.rb b/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/db_store.rb deleted file mode 100644 index 780fb6ad..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/db_store.rb +++ /dev/null @@ -1,55 +0,0 @@ -require 'openid/store/interface' - -module OpenIdAuthentication - class DbStore < OpenID::Store::Interface - def self.cleanup_nonces - now = Time.now.to_i - Nonce.delete_all(["timestamp > ? OR timestamp < ?", now + OpenID::Nonce.skew, now - OpenID::Nonce.skew]) - end - - def self.cleanup_associations - now = Time.now.to_i - Association.delete_all(['issued + lifetime > ?',now]) - end - - def store_association(server_url, assoc) - remove_association(server_url, assoc.handle) - Association.create(:server_url => server_url, - :handle => assoc.handle, - :secret => assoc.secret, - :issued => assoc.issued, - :lifetime => assoc.lifetime, - :assoc_type => assoc.assoc_type) - end - - def get_association(server_url, handle = nil) - assocs = if handle.blank? - Association.find_all_by_server_url(server_url) - else - Association.find_all_by_server_url_and_handle(server_url, handle) - end - - assocs.reverse.each do |assoc| - a = assoc.from_record - if a.expires_in == 0 - assoc.destroy - else - return a - end - end if assocs.any? - - return nil - end - - def remove_association(server_url, handle) - Association.delete_all(['server_url = ? AND handle = ?', server_url, handle]) > 0 - end - - def use_nonce(server_url, timestamp, salt) - return false if Nonce.find_by_server_url_and_timestamp_and_salt(server_url, timestamp, salt) - return false if (timestamp - Time.now.to_i).abs > OpenID::Nonce.skew - Nonce.create(:server_url => server_url, :timestamp => timestamp, :salt => salt) - return true - end - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/nonce.rb b/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/nonce.rb deleted file mode 100644 index c52f6c50..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/nonce.rb +++ /dev/null @@ -1,5 +0,0 @@ -module OpenIdAuthentication - class Nonce < ActiveRecord::Base - set_table_name :open_id_authentication_nonces - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/request.rb b/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/request.rb deleted file mode 100644 index e0cc8e3f..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/request.rb +++ /dev/null @@ -1,23 +0,0 @@ -module OpenIdAuthentication - module Request - def self.included(base) - base.alias_method_chain :request_method, :openid - end - - def request_method_with_openid - if !parameters[:_method].blank? && parameters[:open_id_complete] == '1' - parameters[:_method].to_sym - else - request_method_without_openid - end - end - end -end - -# In Rails 2.3, the request object has been renamed -# from AbstractRequest to Request -if defined? ActionController::Request - ActionController::Request.send :include, OpenIdAuthentication::Request -else - ActionController::AbstractRequest.send :include, OpenIdAuthentication::Request -end diff --git a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/timeout_fixes.rb b/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/timeout_fixes.rb deleted file mode 100644 index cc711c9a..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/lib/open_id_authentication/timeout_fixes.rb +++ /dev/null @@ -1,20 +0,0 @@ -# http://trac.openidenabled.com/trac/ticket/156 -module OpenID - @@timeout_threshold = 20 - - def self.timeout_threshold - @@timeout_threshold - end - - def self.timeout_threshold=(value) - @@timeout_threshold = value - end - - class StandardFetcher - def make_http(uri) - http = @proxy.new(uri.host, uri.port) - http.read_timeout = http.open_timeout = OpenID.timeout_threshold - http - end - end -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/open_id_authentication/tasks/open_id_authentication_tasks.rake b/backup.rails2.3/plugins/open_id_authentication/tasks/open_id_authentication_tasks.rake deleted file mode 100644 index c71434a5..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/tasks/open_id_authentication_tasks.rake +++ /dev/null @@ -1,30 +0,0 @@ -namespace :open_id_authentication do - namespace :db do - desc "Creates authentication tables for use with OpenIdAuthentication" - task :create => :environment do - generate_migration(["open_id_authentication_tables", "add_open_id_authentication_tables"]) - end - - desc "Upgrade authentication tables from ruby-openid 1.x.x to 2.x.x" - task :upgrade => :environment do - generate_migration(["upgrade_open_id_authentication_tables", "upgrade_open_id_authentication_tables"]) - end - - def generate_migration(args) - require 'rails_generator' - require 'rails_generator/scripts/generate' - - if ActiveRecord::Base.connection.supports_migrations? - Rails::Generator::Scripts::Generate.new.run(args) - else - raise "Task unavailable to this database (no migration support)" - end - end - - desc "Clear the authentication tables" - task :clear => :environment do - OpenIdAuthentication::DbStore.cleanup_nonces - OpenIdAuthentication::DbStore.cleanup_associations - end - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/test/normalize_test.rb b/backup.rails2.3/plugins/open_id_authentication/test/normalize_test.rb deleted file mode 100644 index 635d3abc..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/test/normalize_test.rb +++ /dev/null @@ -1,32 +0,0 @@ -require File.dirname(__FILE__) + '/test_helper' - -class NormalizeTest < Test::Unit::TestCase - include OpenIdAuthentication - - NORMALIZATIONS = { - "openid.aol.com/nextangler" => "http://openid.aol.com/nextangler", - "http://openid.aol.com/nextangler" => "http://openid.aol.com/nextangler", - "https://openid.aol.com/nextangler" => "https://openid.aol.com/nextangler", - "HTTP://OPENID.AOL.COM/NEXTANGLER" => "http://openid.aol.com/NEXTANGLER", - "HTTPS://OPENID.AOL.COM/NEXTANGLER" => "https://openid.aol.com/NEXTANGLER", - "loudthinking.com" => "http://loudthinking.com/", - "http://loudthinking.com" => "http://loudthinking.com/", - "http://loudthinking.com:80" => "http://loudthinking.com/", - "https://loudthinking.com:443" => "https://loudthinking.com/", - "http://loudthinking.com:8080" => "http://loudthinking.com:8080/", - "techno-weenie.net" => "http://techno-weenie.net/", - "http://techno-weenie.net" => "http://techno-weenie.net/", - "http://techno-weenie.net " => "http://techno-weenie.net/", - "=name" => "=name" - } - - def test_normalizations - NORMALIZATIONS.each do |from, to| - assert_equal to, normalize_identifier(from) - end - end - - def test_broken_open_id - assert_raises(InvalidOpenId) { normalize_identifier(nil) } - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/test/open_id_authentication_test.rb b/backup.rails2.3/plugins/open_id_authentication/test/open_id_authentication_test.rb deleted file mode 100644 index ddcc17b9..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/test/open_id_authentication_test.rb +++ /dev/null @@ -1,46 +0,0 @@ -require File.dirname(__FILE__) + '/test_helper' - -class OpenIdAuthenticationTest < Test::Unit::TestCase - def setup - @controller = Class.new do - include OpenIdAuthentication - def params() {} end - end.new - end - - def test_authentication_should_fail_when_the_identity_server_is_missing - open_id_consumer = mock() - open_id_consumer.expects(:begin).raises(OpenID::OpenIDError) - @controller.expects(:open_id_consumer).returns(open_id_consumer) - @controller.expects(:logger).returns(mock(:error => true)) - - @controller.send(:authenticate_with_open_id, "http://someone.example.com") do |result, identity_url| - assert result.missing? - assert_equal "Sorry, the OpenID server couldn't be found", result.message - end - end - - def test_authentication_should_be_invalid_when_the_identity_url_is_invalid - @controller.send(:authenticate_with_open_id, "!") do |result, identity_url| - assert result.invalid?, "Result expected to be invalid but was not" - assert_equal "Sorry, but this does not appear to be a valid OpenID", result.message - end - end - - def test_authentication_should_fail_when_the_identity_server_times_out - open_id_consumer = mock() - open_id_consumer.expects(:begin).raises(Timeout::Error, "Identity Server took too long.") - @controller.expects(:open_id_consumer).returns(open_id_consumer) - @controller.expects(:logger).returns(mock(:error => true)) - - @controller.send(:authenticate_with_open_id, "http://someone.example.com") do |result, identity_url| - assert result.missing? - assert_equal "Sorry, the OpenID server couldn't be found", result.message - end - end - - def test_authentication_should_begin_when_the_identity_server_is_present - @controller.expects(:begin_open_id_authentication) - @controller.send(:authenticate_with_open_id, "http://someone.example.com") - end -end diff --git a/backup.rails2.3/plugins/open_id_authentication/test/status_test.rb b/backup.rails2.3/plugins/open_id_authentication/test/status_test.rb deleted file mode 100644 index b1d5e093..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/test/status_test.rb +++ /dev/null @@ -1,14 +0,0 @@ -require File.dirname(__FILE__) + '/test_helper' - -class StatusTest < Test::Unit::TestCase - include OpenIdAuthentication - - def test_state_conditional - assert Result[:missing].missing? - assert Result[:missing].unsuccessful? - assert !Result[:missing].successful? - - assert Result[:successful].successful? - assert !Result[:successful].unsuccessful? - end -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/open_id_authentication/test/test_helper.rb b/backup.rails2.3/plugins/open_id_authentication/test/test_helper.rb deleted file mode 100644 index 43216e1e..00000000 --- a/backup.rails2.3/plugins/open_id_authentication/test/test_helper.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'test/unit' -require 'rubygems' - -gem 'activesupport' -require 'active_support' - -gem 'actionpack' -require 'action_controller' - -gem 'mocha' -require 'mocha' - -gem 'ruby-openid' -require 'openid' - -RAILS_ROOT = File.dirname(__FILE__) unless defined? RAILS_ROOT -require File.dirname(__FILE__) + "/../lib/open_id_authentication" diff --git a/backup.rails2.3/plugins/resource_feeder/README b/backup.rails2.3/plugins/resource_feeder/README deleted file mode 100644 index 5502be25..00000000 --- a/backup.rails2.3/plugins/resource_feeder/README +++ /dev/null @@ -1,7 +0,0 @@ -ResourceFeeder -============== - -Simple feeds for resources - -NOTE: This plugin depends on the latest version of simply_helpful, available here: -http://dev.rubyonrails.org/svn/rails/plugins/simply_helpful/ diff --git a/backup.rails2.3/plugins/resource_feeder/Rakefile b/backup.rails2.3/plugins/resource_feeder/Rakefile deleted file mode 100644 index 51fce7b3..00000000 --- a/backup.rails2.3/plugins/resource_feeder/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 resource_feed plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the resource_feed plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'ResourceFeed' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/backup.rails2.3/plugins/resource_feeder/init.rb b/backup.rails2.3/plugins/resource_feeder/init.rb deleted file mode 100644 index 7b55d76f..00000000 --- a/backup.rails2.3/plugins/resource_feeder/init.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'resource_feeder' -ActionController::Base.send(:include, ResourceFeeder::Rss, ResourceFeeder::Atom) \ No newline at end of file diff --git a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder.rb b/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder.rb deleted file mode 100644 index b5003419..00000000 --- a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'resource_feeder/rss' -require 'resource_feeder/atom' diff --git a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/atom.rb b/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/atom.rb deleted file mode 100644 index 40af87df..00000000 --- a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/atom.rb +++ /dev/null @@ -1,67 +0,0 @@ -require 'resource_feeder/common' - -module ResourceFeeder - module Atom - include ResourceFeeder::Common - include ActionController::Routing - extend self - - def render_atom_feed_for(resources, options = {}) - render :text => atom_feed_for(resources, options), :content_type => Mime::ATOM - end - - def atom_feed_for(resources, options = {}) - xml = Builder::XmlMarkup.new(:indent => 2) - - options[:feed] ||= {} - options[:item] ||= {} - options[:url_writer] ||= self - - if options[:class] || resources.first - klass = options[:class] || resources.first.class - new_record = klass.new - else - options[:feed] = { :title => "Empty", :link => "http://example.com" } - end - - options[:feed][:title] ||= klass.name.pluralize - options[:feed][:id] ||= "tag:#{request.host_with_port}:#{klass.name.pluralize}" - options[:feed][:link] ||= polymorphic_url(new_record, :controller => options[:url_writer].controller_name) - - options[:item][:title] ||= [ :title, :subject, :headline, :name ] - options[:item][:description] ||= [ :description, :body, :content ] - options[:item][:pub_date] ||= [ :updated_at, :updated_on, :created_at, :created_on ] - options[:item][:author] ||= [ :author, :creator ] - - resource_link = lambda { |r| polymorphic_url(r, :controller => options[:url_writer].controller_name) } - - xml.instruct! - xml.feed "xml:lang" => "en-US", "xmlns" => 'http://www.w3.org/2005/Atom' do - xml.title(options[:feed][:title]) - xml.id(options[:feed][:id]) - xml.link(:rel => 'alternate', :type => 'text/html', :href => options[:feed][:link]) - xml.link(:rel => 'self', :type => 'application/atom+xml', :href => options[:feed][:self]) if options[:feed][:self] - xml.subtitle(options[:feed][:description]) if options[:feed][:description] - - for resource in resources - published_at = call_or_read(options[:item][:pub_date], resource) - - xml.entry do - xml.title(call_or_read(options[:item][:title], resource)) - xml.content(call_or_read(options[:item][:description], resource), :type => 'html') - xml.id("tag:#{request.host_with_port},#{published_at.xmlschema}:#{call_or_read(options[:item][:guid] || options[:item][:link] || resource_link, resource)}") - xml.published(published_at.xmlschema) - xml.updated((resource.respond_to?(:updated_at) ? call_or_read(options[:item][:pub_date] || :updated_at, resource) : published_at).xmlschema) - xml.link(:rel => 'alternate', :type => 'text/html', :href => call_or_read(options[:item][:link] || options[:item][:guid] || resource_link, resource)) - - if author = call_or_read(options[:item][:author], resource) - xml.author do - xml.name() - end - end - end - end - end - end - end -end diff --git a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/common.rb b/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/common.rb deleted file mode 100644 index 383b965e..00000000 --- a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/common.rb +++ /dev/null @@ -1,24 +0,0 @@ -module ResourceFeeder - module Common - private - def call_or_read(procedure_or_attributes, resource) - case procedure_or_attributes - when nil - raise ArgumentError, "WTF is nil here? #{resource.inspect}" - when Array - attributes = procedure_or_attributes - if attr = attributes.select { |a| resource.respond_to?(a) }.first - resource.send attr - end - when Symbol - attribute = procedure_or_attributes - resource.send(attribute) - when Proc - procedure = procedure_or_attributes - procedure.call(resource) - else - raise ArgumentError, "WTF is #{procedure_or_attributes.inspect} here? #{resource.inspect}" - end - end - end -end diff --git a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/rss.rb b/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/rss.rb deleted file mode 100644 index d3fa56d7..00000000 --- a/backup.rails2.3/plugins/resource_feeder/lib/resource_feeder/rss.rb +++ /dev/null @@ -1,68 +0,0 @@ -require 'resource_feeder/common' - -module ResourceFeeder - module Rss - include ResourceFeeder::Common - include ActionController::Routing - extend self - - def render_rss_feed_for(resources, options = {}) - render :text => rss_feed_for(resources, options), :content_type => Mime::RSS - end - - def rss_feed_for(resources, options = {}) - xml = Builder::XmlMarkup.new(:indent => 2) - - options[:feed] ||= {} - options[:item] ||= {} - options[:url_writer] ||= self - - if options[:class] || resources.first - klass = options[:class] || resources.first.class - new_record = klass.new - else - options[:feed] = { :title => "Empty", :link => "http://example.com" } - end - use_content_encoded = options[:item].has_key?(:content_encoded) - - options[:feed][:title] ||= klass.name.pluralize - options[:feed][:link] ||= polymorphic_url(new_record, :controller => options[:url_writer].controller_name) - options[:feed][:language] ||= "en-us" - options[:feed][:ttl] ||= "40" - - options[:item][:title] ||= [ :title, :subject, :headline, :name ] - options[:item][:description] ||= [ :description, :body, :content ] - options[:item][:pub_date] ||= [ :updated_at, :updated_on, :created_at, :created_on ] - - resource_link = lambda { |r| polymorphic_url(r, :controller => options[:url_writer].controller_name) } - - rss_root_attributes = { :version => 2.0 } - rss_root_attributes.merge!("xmlns:content" => "http://purl.org/rss/1.0/modules/content/") if use_content_encoded - - xml.instruct! - - xml.rss(rss_root_attributes) do - xml.channel do - xml.title(options[:feed][:title]) - xml.link(options[:feed][:link]) - xml.description(options[:feed][:description]) if options[:feed][:description] - xml.language(options[:feed][:language]) - xml.ttl(options[:feed][:ttl]) - - for resource in resources - xml.item do - xml.title(call_or_read(options[:item][:title], resource)) - xml.description(call_or_read(options[:item][:description], resource)) - if use_content_encoded then - xml.content(:encoded) { xml.cdata!(call_or_read(options[:item][:content_encoded], resource)) } - end - xml.pubDate(call_or_read(options[:item][:pub_date], resource).to_s(:rfc822)) - xml.guid(call_or_read(options[:item][:guid] || options[:item][:link] || resource_link, resource)) - xml.link(call_or_read(options[:item][:link] || options[:item][:guid] || resource_link, resource)) - end - end - end - end - end - end -end diff --git a/backup.rails2.3/plugins/resource_feeder/test/atom_feed_test.rb b/backup.rails2.3/plugins/resource_feeder/test/atom_feed_test.rb deleted file mode 100644 index 3112da47..00000000 --- a/backup.rails2.3/plugins/resource_feeder/test/atom_feed_test.rb +++ /dev/null @@ -1,85 +0,0 @@ -require File.dirname(__FILE__) + '/test_helper' -class AtomFeedTest < Test::Unit::TestCase - attr_reader :request - - def setup - @request = OpenStruct.new - @request.host_with_port = 'example.com' - @records = Array.new(5).fill(Post.new) - @records.each &:save - end - - def test_default_atom_feed - atom_feed_for @records - - assert_select 'feed' do - assert_select '>title', 'Posts' - assert_select '>id', "tag:#{request.host_with_port}:Posts" - assert_select '>link' do - assert_select "[rel='alternate']" - assert_select "[type='text/html']" - assert_select "[href='http://example.com/posts']" - end - assert_select 'entry', 5 do - assert_select 'title', :text => 'feed title (title)' - assert_select "content[type='html']", '<p>feed description (description)</p>' - assert_select 'id', "tag:#{request.host_with_port},#{@records.first.created_at.xmlschema}:#{'http://example.com/posts/1'}" - assert_select 'published', @records.first.created_at.xmlschema - assert_select 'updated', @records.first.created_at.xmlschema - assert_select 'link' do - assert_select "[rel='alternate']" - assert_select "[type='text/html']" - assert_select "[href='http://example.com/posts/1']" - end - end - end - end - - def test_should_allow_custom_feed_options - atom_feed_for @records, :feed => { :title => 'Custom Posts', :link => '/posts', :description => 'stuff', :self => '/posts.atom' } - - assert_select 'feed>title', 'Custom Posts' - assert_select "feed>link[href='/posts']" - assert_select 'feed>subtitle', 'stuff' - assert_select 'feed>link' do - assert_select "[rel='self']" - assert_select "[type='application/atom+xml']" - assert_select "[href='/posts.atom']" - end - end - - def test_should_allow_custom_item_attributes - atom_feed_for @records, :item => { :title => :name, :description => :body, :pub_date => :create_date, :link => :id } - - assert_select 'entry', 5 do - assert_select 'title', :text => 'feed title (name)' - assert_select "content[type='html']", '<p>feed description (body)</p>' - assert_select 'published', (@records.first.created_at - 5.minutes).xmlschema - assert_select 'updated', (@records.first.created_at - 5.minutes).xmlschema - assert_select 'id', "tag:#{request.host_with_port},#{(@records.first.created_at - 5.minutes).xmlschema}:1" - assert_select 'link' do - assert_select "[rel='alternate']" - assert_select "[type='text/html']" - assert_select "[href='1']" - end - end - end - - def test_should_allow_custom_item_attribute_blocks - atom_feed_for @records, :item => { :title => lambda { |r| r.name }, :description => lambda { |r| r.body }, :pub_date => lambda { |r| r.create_date }, - :link => lambda { |r| "/#{r.created_at.to_i}" }, :guid => lambda { |r| r.created_at.to_i } } - - assert_select 'entry', 5 do - assert_select 'title', :text => 'feed title (name)' - assert_select "content[type='html']", '<p>feed description (body)</p>' - assert_select 'published', (@records.first.created_at - 5.minutes).xmlschema - assert_select 'updated', (@records.first.created_at - 5.minutes).xmlschema - assert_select 'id', /:\d+$/ - assert_select 'link' do - assert_select "[rel='alternate']" - assert_select "[type='text/html']" - assert_select "[href=?]", /^\/\d+$/ - end - end - end -end diff --git a/backup.rails2.3/plugins/resource_feeder/test/rss_feed_test.rb b/backup.rails2.3/plugins/resource_feeder/test/rss_feed_test.rb deleted file mode 100644 index 90525baf..00000000 --- a/backup.rails2.3/plugins/resource_feeder/test/rss_feed_test.rb +++ /dev/null @@ -1,86 +0,0 @@ -require File.dirname(__FILE__) + '/test_helper' -class RssFeedTest < Test::Unit::TestCase - def setup - @records = Array.new(5).fill(Post.new) - @records.each &:save - end - - def test_default_rss_feed - rss_feed_for @records - - assert_select 'rss[version="2.0"]' do - assert_select 'channel' do - assert_select '>title', 'Posts' - assert_select '>link', 'http://example.com/posts' - assert_select 'language', 'en-us' - assert_select 'ttl', '40' - end - assert_select 'item', 5 do - assert_select 'title', :text => 'feed title (title)' - assert_select 'description', '<p>feed description (description)</p>' - %w(guid link).each do |node| - assert_select node, 'http://example.com/posts/1' - end - assert_select 'pubDate', @records.first.created_at.to_s(:rfc822) - end - end - end - - def test_should_allow_custom_feed_options - rss_feed_for @records, :feed => { :title => 'Custom Posts', :link => '/posts', :description => 'stuff', :language => 'en-gb', :ttl => '80' } - - assert_select 'channel>title', 'Custom Posts' - assert_select 'channel>link', '/posts' - assert_select 'channel>description', 'stuff' - assert_select 'channel>language', 'en-gb' - assert_select 'channel>ttl', '80' - end - - def test_should_allow_custom_item_attributes - rss_feed_for @records, :item => { :title => :name, :description => :body, :pub_date => :create_date, :link => :id } - - assert_select 'item', 5 do - assert_select 'title', :text => 'feed title (name)' - assert_select 'description', '<p>feed description (body)</p>' - assert_select 'pubDate', (@records.first.created_at - 5.minutes).to_s(:rfc822) - assert_select 'link', '1' - assert_select 'guid', '1' - end - end - - def test_should_allow_custom_item_attribute_blocks - rss_feed_for @records, :item => { :title => lambda { |r| r.name }, :description => lambda { |r| r.body }, :pub_date => lambda { |r| r.create_date }, - :link => lambda { |r| "/#{r.created_at.to_i}" }, :guid => lambda { |r| r.created_at.to_i } } - - assert_select 'item', 5 do - assert_select 'title', :text => 'feed title (name)' - assert_select 'description', '<p>feed description (body)</p>' - assert_select 'pubDate', (@records.first.created_at - 5.minutes).to_s(:rfc822) - end - end - - # note that assert_select isnt easily able to get elements that have xml namespaces (as it thinks they are - # invalid html psuedo children), so we do some manual testing with the response body - def test_should_allow_content_encoded_for_items - rss_feed_for @records, :item => { :content_encoded => :full_html_body } - - html_content = "Here is some full content, with out any excerpts" - assert_equal 5, @response.body.scan("").size - assert_select 'item', 5 do - assert_select 'description + *', " { :content_encoded => :full_html_body } - assert_equal %[\n], - @response.body.grep(/\n], - @response.body.grep(/feed description (#{attr_name})

" - end - end - - def full_html_body - "Here is some full content, with out any excerpts" - end - - def create_date - @created_at - 5.minutes - end -end - -class Test::Unit::TestCase - include ResourceFeeder::Rss, ResourceFeeder::Atom - - def render_feed(xml) - @response = OpenStruct.new - @response.headers = {'Content-Type' => 'text/xml'} - @response.body = xml - end - - def rss_feed_for_with_ostruct(resources, options = {}) - render_feed rss_feed_for_without_ostruct(resources, options) - end - - def atom_feed_for_with_ostruct(resources, options = {}) - render_feed atom_feed_for_without_ostruct(resources, options) - end - - alias_method_chain :rss_feed_for, :ostruct - alias_method_chain :atom_feed_for, :ostruct - - def html_document - @html_document ||= HTML::Document.new(@response.body, false, true) - end - - def posts_url - "http://example.com/posts" - end - - def post_url(post) - "http://example.com/posts/#{post.id}" - end -end diff --git a/backup.rails2.3/plugins/simple_ldap_authenticator/README b/backup.rails2.3/plugins/simple_ldap_authenticator/README deleted file mode 100644 index dc8ca509..00000000 --- a/backup.rails2.3/plugins/simple_ldap_authenticator/README +++ /dev/null @@ -1,5 +0,0 @@ -SimpleLdapAuthenticator -======================= - -Allows for simple authentication to an LDAP server with a minimum of -configuration. See the RDoc for details. diff --git a/backup.rails2.3/plugins/simple_ldap_authenticator/Rakefile b/backup.rails2.3/plugins/simple_ldap_authenticator/Rakefile deleted file mode 100644 index f7c3459e..00000000 --- a/backup.rails2.3/plugins/simple_ldap_authenticator/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 simple_ldap_authenticator plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the simple_ldap_authenticator plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'SimpleLdapAuthenticator' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/backup.rails2.3/plugins/simple_ldap_authenticator/init.rb b/backup.rails2.3/plugins/simple_ldap_authenticator/init.rb deleted file mode 100644 index 85917669..00000000 --- a/backup.rails2.3/plugins/simple_ldap_authenticator/init.rb +++ /dev/null @@ -1,2 +0,0 @@ -# Include hook code here -#require 'simple_ldap_authenticator' diff --git a/backup.rails2.3/plugins/simple_ldap_authenticator/install.rb b/backup.rails2.3/plugins/simple_ldap_authenticator/install.rb deleted file mode 100644 index f7732d37..00000000 --- a/backup.rails2.3/plugins/simple_ldap_authenticator/install.rb +++ /dev/null @@ -1 +0,0 @@ -# Install hook code here diff --git a/backup.rails2.3/plugins/simple_ldap_authenticator/lib/simple_ldap_authenticator.rb b/backup.rails2.3/plugins/simple_ldap_authenticator/lib/simple_ldap_authenticator.rb deleted file mode 100644 index 2992d892..00000000 --- a/backup.rails2.3/plugins/simple_ldap_authenticator/lib/simple_ldap_authenticator.rb +++ /dev/null @@ -1,127 +0,0 @@ -# SimpleLdapAuthenticator -# -# This plugin supports both Ruby/LDAP and Net::LDAP, defaulting to Ruby/LDAP -# if it is available. If both are installed and you want to force the use of -# Net::LDAP, set SimpleLdapAuthenticator.ldap_library = 'net/ldap'. - -# Allows for easily authenticating users via LDAP (or LDAPS). If authenticating -# via LDAP to a server running on localhost, you should only have to configure -# the login_format. -# -# Can be configured using the following accessors (with examples): -# * login_format = '%s@domain.com' # Active Directory, OR -# * login_format = 'cn=%s,cn=users,o=organization,c=us' # Other LDAP servers -# * servers = ['dc1.domain.com', 'dc2.domain.com'] # names/addresses of LDAP servers to use -# * use_ssl = true # for logging in via LDAPS -# * port = 3289 # instead of 389 for LDAP or 636 for LDAPS -# * logger = RAILS_DEFAULT_LOGGER # for logging authentication successes/failures -# -# The class is used as a global variable, you are not supposed to create an -# instance of it. For example: -# -# require 'simple_ldap_authenticator' -# SimpleLdapAuthenticator.servers = %w'dc1.domain.com dc2.domain.com' -# SimpleLdapAuthenticator.use_ssl = true -# SimpleLdapAuthenticator.login_format = '%s@domain.com' -# SimpleLdapAuthenticator.logger = RAILS_DEFAULT_LOGGER -# class LoginController < ApplicationController -# def login -# return redirect_to(:action=>'try_again') unless SimpleLdapAuthenticator.valid?(params[:username], params[:password]) -# session[:username] = params[:username] -# end -# end -class SimpleLdapAuthenticator - class << self - @servers = ['127.0.0.1'] - @use_ssl = false - @login_format = '%s' - attr_accessor :servers, :use_ssl, :port, :login_format, :logger, :connection, :ldap_library - - # Load the required LDAP library, either 'ldap' or 'net/ldap' - def load_ldap_library - return if @ldap_library_loaded - if ldap_library - if ldap_library == 'net/ldap' - require 'net/ldap' - else - require 'ldap' - require 'ldap/control' - end - else - begin - require 'ldap' - require 'ldap/control' - ldap_library = 'ldap' - rescue LoadError - require 'net/ldap' - ldap_library = 'net/ldap' - end - end - @ldap_library_loaded = true - end - - # The next LDAP server to which to connect - def server - servers[0] - end - - # The connection to the LDAP server. A single connection is made and the - # connection is only changed if a server returns an error other than - # invalid password. - def connection - return @connection if @connection - load_ldap_library - @connection = if ldap_library == 'net/ldap' - Net::LDAP.new(:host=>server, :port=>(port), :encryption=>(:simple_tls if use_ssl)) - else - (use_ssl ? LDAP::SSLConn : LDAP::Conn).new(server, port) - end - end - - # The port to use. Defaults to 389 for LDAP and 636 for LDAPS. - def port - @port ||= use_ssl ? 636 : 389 - end - - # Disconnect from current LDAP server and use a different LDAP server on the - # next authentication attempt - def switch_server - self.connection = nil - servers << servers.shift - end - - # Check the validity of a login/password combination - def valid?(login, password) - if ldap_library == 'net/ldap' - connection.authenticate(login_format % login.to_s, password.to_s) - begin - if connection.bind - logger.info("Authenticated #{login.to_s} by #{server}") if logger - true - else - logger.info("Error attempting to authenticate #{login.to_s} by #{server}: #{connection.get_operation_result.code} #{connection.get_operation_result.message}") if logger - switch_server unless connection.get_operation_result.code == 49 - false - end - rescue Net::LDAP::LdapError => error - logger.info("Error attempting to authenticate #{login.to_s} by #{server}: #{error.message}") if logger - switch_server - false - end - else - connection.unbind if connection.bound? - begin - connection.bind(login_format % login.to_s, password.to_s) - connection.unbind - logger.info("Authenticated #{login.to_s} by #{server}") if logger - true - rescue LDAP::ResultError => error - connection.unbind if connection.bound? - logger.info("Error attempting to authenticate #{login.to_s} by #{server}: #{error.message}") if logger - switch_server unless error.message == 'Invalid credentials' - false - end - end - end - end -end diff --git a/backup.rails2.3/plugins/simple_ldap_authenticator/tasks/simple_ldap_authenticator_tasks.rake b/backup.rails2.3/plugins/simple_ldap_authenticator/tasks/simple_ldap_authenticator_tasks.rake deleted file mode 100644 index 1916c233..00000000 --- a/backup.rails2.3/plugins/simple_ldap_authenticator/tasks/simple_ldap_authenticator_tasks.rake +++ /dev/null @@ -1,4 +0,0 @@ -# desc "Explaining what the task does" -# task :simple_ldap_authenticator do -# # Task goes here -# end \ No newline at end of file diff --git a/backup.rails2.3/plugins/simple_ldap_authenticator/test/simple_ldap_authenticator_test.rb b/backup.rails2.3/plugins/simple_ldap_authenticator/test/simple_ldap_authenticator_test.rb deleted file mode 100644 index dfd92dae..00000000 --- a/backup.rails2.3/plugins/simple_ldap_authenticator/test/simple_ldap_authenticator_test.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'test/unit' - -class SimpleLdapAuthenticatorTest < Test::Unit::TestCase - # Replace this with your real tests. - def test_this_plugin - flunk - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/.gitignore b/backup.rails2.3/plugins/skinny_spec/.gitignore deleted file mode 100644 index 28f7b7da..00000000 --- a/backup.rails2.3/plugins/skinny_spec/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -.DS_Store -doc \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/README.rdoc b/backup.rails2.3/plugins/skinny_spec/README.rdoc deleted file mode 100644 index 118b58e1..00000000 --- a/backup.rails2.3/plugins/skinny_spec/README.rdoc +++ /dev/null @@ -1,270 +0,0 @@ -= Skinny Spec - -Skinny Spec is a collection of spec helper methods designed to help trim the fat and DRY up -some of the bloat that sometimes results from properly specing your classes and templates. - -== Requirements and Recommendations - -Obviously you'll need to be using RSpec[http://github.com/dchelimsky/rspec/tree/master] and -Rspec-Rails[http://github.com/dchelimsky/rspec-rails/tree/master] as your testing framework. - -Skinny Spec was originally designed [and best enjoyed] if you're using -Haml[http://github.com/nex3/haml/tree/master] and -make_resourceful[http://github.com/rsl/make_resourceful/tree/master] but will default to -ERb and a facsimile of Rails' default scaffolding [for the views and controllers, respectively] -if Haml and/or make_resourceful are not available. I recommend using them though. :) - -In addition, Skinny Spec uses Ruby2Ruby to make nicer expectation messages and you'll want to -have that installed as well. It's not a dependency or anything but it is highly -recommended. - -== Setup - -Once you've installed the plugin in your app's vendor/plugins folder, you're ready to rock! -Skinny Spec includes itself into the proper RSpec classes so there's no configuration on your -part. Sweet! - -== Usage - -The simplest way to use Skinny Specs is to generate a resource scaffold: - - script/generate skinny_scaffold User - -This command takes the usual complement of attribute definitions like -script/generate scaffold. Then have a look at the generated files (particularly the -specs) to see what's new and different with Skinny Spec. - -=== Controller Specs - -Let's look at the controller specs. - - describe UsersController do - describe "GET :index" do - before(:each) do - @users = stub_index(User) - end - - it_should_find_and_assign :users - it_should_render :template, "index" - end - - # ... - - describe "POST :create" do - describe "when successful" do - before(:each) do - @user = stub_create(User) - end - - it_should_initialize_and_save :user - it_should_redirect_to { user_url(@user) } - end - - # ... - -First thing you should see is an example group for GET :index. That stub_index method there -does a lot of work behind the curtain. I'll leave it up to you to check the documentation for it -(and its brothers and sister methods like stub_new) but I will point out that the -methods named stub_controller_method should only be used for stubbing and -mocking the main object of the method. To create mocks for other ancillary objects, please -use stub_find_all, stub_find_one, and stub_initialize. The reason -for this is because the former methods actually save us a step by defining an implicit -controller method request. If you add a new method to your resource routing, you'll want to -use the helper method define_request in those example groups to define an explicit -request, like so: - - describe "PUT :demote" do - define_request { put :demote } - - # ... - end - -You can also define a method called shared_request to "share" a -define_request across nested describe blocks, like so: - - describe "POST :create" do - def shared_request - post :create - end - - describe "when successful" do - # ... - end - - describe "when unsuccessful" do - # ... - end - end - -Note: When you're adding longer, more complicated controller specs you can still leverage -implicit and explicit requests by calling do_request in your spec as in the following -example: - - # Note this controller is UsersController and _not_ CategoriesController - # and that loading the categories isn't part of the default actions - # and cannot use the stub_controller_method helpers - # [which create implicit requests based on the controller method in the name] - # but uses stub_find_all instead - describe "GET :new" do - before(:each) do - @user = stub_new(User) - @categories = stub_find_all(Category) - end - - # ... - - it "should preload categories" do - Category.should_receive(:find).with(:all) - do_request - end - - it "should assign @categories" do - do_request - assigns[:categories].should == @categories - end - end - -Finally we get to the meat of the spec and of Skinny Specs itself: the actual expectations. -The first thing you'll notice is the use of example group (read: "describe" block) level methods -instead of the usual example (read: "it") blocks. Using this helper at the example group level -saves us three lines over using an example block. (If this isn't significant to you, this is -probably the wrong plugin for you as well. Sorry.) Note that none of these methods use the -instance variables defined in the "before" block because they are all nil at the example block -level. Let's look at a sample method to see how it works: - - it_should_find_and_assign :users - -This actually wraps two different expectations: one that User.should_receive(:find).with(:all) -and another that the instance variable @users is assigned with the return value from that finder call. -If you need to add more detailed arguments to the find, you can easily break this into two different -expectations like: - - it_should_find :users, :limit => 2 - it_should_assign :users - -See the documentation for the it_should_find for more information. You might have guessed that -it_should_initialize_assign and it_should_render_template work in a similar -fashion and you'd be right. Again, see the documentation for these individual methods for more -information. Lots of information in those docs. - -A useful helper method that doesn't appear in any of the scaffolding is with_default_restful_actions -which takes a block and evaluates it for each of the RESTful controller actions. Very useful for -spec'ing that these methods redirect to the login page when the user isn't logged in, for example. This -method is designed to be used inside an example like so: - - describe "when not logged in" do - it "should redirect all requests to the login page" do - with_default_restful_actions do - response.should redirect_to(login_url) - end - end - end - -Before we're through with the controller specs, let me point out one more important detail. In -order to use it_should_redirect_to we have to send the routing inside a block argument -there so it can be evaluated in the example context instead of the example group, where it -completely blows up. This methodology is used anywhere routing is referred to in a "skinny", -example group level spec. - -=== View Specs - -Now let's move to the view specs! - - describe "/users/form.html.haml" do - before(:each) do - @user = mock_and_assign(User, :stub => { - :name => "foo", - :birthday => 1.week.ago, - :adult => false - }) - end - - it_should_have_form_for :user - - it_should_allow_editing :user, :name - it_should_allow_editing :user, :birthday - it_should_allow_editing :user, :adult - - it_should_link_to_show :user - it_should_link_to { users_path } - end - -Like the special stub_index methods in the controller -specs, the view specs have a shorthand mock and stub helpers: mock_and_assign and -mock_and_assign_collection. These are well documented so please check them out. - -There are also some really nice helper methods that I'd like point out. First is -it_should_have_form_for. This is a really good convenience wrapper that basically wraps -the much longer: - - it "should use form_for to generate the proper form action and options" do - template.should_receive(:form_for).with(@user) - do_render - end - -Next up is the it_should_allow_editing helper. I love this method the most because it -really helps DRY up that view spec while at the same time being amazingly unbrittle. Instead of -creating an expectation for a specific form element, this method creates a generalized expectation -that there's a form element with the name attribute set in such away that it will -generate the proper params to use in the controller to edit or create the instance. -Check out the docs and the source for more information on this. Also check out -it_should_have_form_element_for which is roughly equivalent for those times when you use -form_tag instead. - -Finally let's look at those it_should_link_to_controller_method helpers. -These methods (and there's one each for the controller methods -new, edit, show, and delete) point to instance variables -which you should be created in the "before" blocks with mock_and_assign. The other is -it_should_allow_editing which is likewise covered extensively in the documentation and -I will just point out here that, like it_should_link_to_edit and such, it takes a -symbol for the name of the instance variable it refers to and additionally takes -a symbol for the name of the attribute to be edited. - -Also note that, when constructing a long form example, instead of defining an instance variable -for the name of the template and calling render @that_template you can simply call -do_render which takes the name of the template from the outermost example group where -it is customarily stated. - -=== Model Specs - -Skinny Spec adds a matcher for the various ActiveRecord associations. On the example group level -you call them like: - - it_should_belong_to :manager - it_should_have_many :clients - -Within an example you can call them on either the class or the instance setup in the -"before" block. These are equivalent: - - @user.should belong_to(:group) - User.should belong_to(:group) - -I've also added some very basic validation helpers like it_should_validate_presence_of, -it_should_validate_uniqueness_of, it_should_not_mass_assign. Please consult -the documentation for more information. - -== Miscellaneous Notes - -In the scaffolding, I have used my own idiomatic Rails usage: - -* All controller actions which use HTML forms [new, edit, etc] use a shared - form and leverage form_for to its fullest by letting it create the appropriate - action and options. -* Some instances where you might expect link_to are button_to. This is to provide a common - interface element which can be styled the same instead of a mishmash of links and buttons and - inputs everywhere. To take full advantage of this, I usually override many of Rails' default - helpers with custom ones that all use actual HTML BUTTON elements which are much - easier to style than "button" typed INPUT. I've provided a text file in the - "additional" folder of this plugin which you can use in your ApplicationHelper. (I also - provide an optional override helper for the label method which uses - #titleize instead of humanize for stylistic reasons). -* Probably more that I can't think of. - -== Credits and Thanks - -Sections of this code were taken from or inspired by Rick Olsen's -rspec_on_rails_on_crack[http://github.com/technoweenie/rspec_on_rails_on_crack/tree/master]. -Also thanks and props to Hampton Catlin and Nathan Weizenbaum for the lovely and imminently useable -Haml and make_resourceful. Also also praises and glory to David Chelimsky and the Rspec crew. - -Also thanks to Don Petersen, Nicolas Mérouze, Mikkel Malmberg, and Brandan Lennox for their suggestions and fixes. \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/Rakefile b/backup.rails2.3/plugins/skinny_spec/Rakefile deleted file mode 100644 index b0adbc43..00000000 --- a/backup.rails2.3/plugins/skinny_spec/Rakefile +++ /dev/null @@ -1,11 +0,0 @@ -require 'rake' -require 'rake/rdoctask' - -desc 'Generate documentation for the Skinny Spec plugin' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'doc' - rdoc.title = 'Skinny Spec' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README.rdoc') - rdoc.rdoc_files.include('lib/**/*.rb') -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/additional/helper_overrides.txt b/backup.rails2.3/plugins/skinny_spec/additional/helper_overrides.txt deleted file mode 100644 index 7717e079..00000000 --- a/backup.rails2.3/plugins/skinny_spec/additional/helper_overrides.txt +++ /dev/null @@ -1,58 +0,0 @@ -# Please insert these into your ApplicationHelper - -# Replacement for Rails' default submit_tag helper -# using HTML button element rather than HTML input element -def submit_tag(text, options = {}) - content_tag :button, text, options.merge(:type => :submit) -end - -# Replacement for Rails' default button_to helper -# using HTML button element rather than HTML input element -def button_to(name, options = {}, html_options = {}) - html_options = html_options.stringify_keys - convert_boolean_attributes!(html_options, %w( disabled )) - - method_tag = '' - if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s) - method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s) - end - - form_method = method.to_s == 'get' ? 'get' : 'post' - - request_token_tag = '' - if form_method == 'post' && protect_against_forgery? - request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) - end - - if confirm = html_options.delete("confirm") - html_options["onclick"] = "return #{confirm_javascript_function(confirm)};" - end - - url = options.is_a?(String) ? options : self.url_for(options) - name ||= url - - html_options.merge!("type" => "submit", "value" => name) - - "
" + - method_tag + content_tag("button", name, html_options) + request_token_tag + "
" -end - -# Replacement for Rails' default button_to_function helper -# using HTML button element rather than HTML input element -def button_to_function(name, *args, &block) - html_options = args.extract_options! - function = args[0] || '' - - html_options.symbolize_keys! - function = update_page(&block) if block_given? - content_tag(:button, name, html_options.merge({ - :onclick => (html_options[:onclick] ? "#{html_options[:onclick]}; " : "") + "#{function};" - })) -end - -# Replacement for Rails' default label helper -# using String#titleize rather than String#humanize -def label(object_name, method, text = nil, options = {}) - text ||= method.to_s[].titleize - super -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/skinny_scaffold_generator.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/skinny_scaffold_generator.rb deleted file mode 100644 index 3cde3564..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/skinny_scaffold_generator.rb +++ /dev/null @@ -1,102 +0,0 @@ -class SkinnyScaffoldGenerator < Rails::Generator::NamedBase - attr_reader :controller_class_path, :controller_file_path, :controller_class_nesting, - :controller_class_nesting_depth, :controller_class_name, :controller_underscore_name, - :controller_plural_name, :template_language - alias_method :controller_file_name, :controller_underscore_name - alias_method :controller_singular_name, :controller_file_name - alias_method :controller_table_name, :controller_plural_name - - default_options :skip_migration => false - - def initialize(runtime_args, runtime_options = {}) - super - - base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@name.pluralize) - @controller_class_name_without_nesting, @controller_underscore_name, @controller_plural_name = inflect_names(base_name) - - if @controller_class_nesting.empty? - @controller_class_name = @controller_class_name_without_nesting - else - @controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}" - end - end - - def manifest - record do |m| - # Check for class naming collisions - m.class_collisions controller_class_path, "#{controller_class_name}Controller", "#{controller_class_name}Helper" - m.class_collisions class_path, "#{class_name}" - - # # Controller, helper, and views directories - m.directory File.join('app', 'views', controller_class_path, controller_file_name) - m.directory File.join('spec', 'views', controller_class_path, controller_file_name) - m.directory File.join('app', 'helpers', controller_class_path) - m.directory File.join('spec', 'helpers', controller_class_path) - m.directory File.join('app', 'controllers', controller_class_path) - m.directory File.join('spec', 'controllers', controller_class_path) - m.directory File.join('app', 'models', class_path) - m.directory File.join('spec', 'models', class_path) - - # Views - @template_language = defined?(Haml) ? "haml" : "erb" - %w{index show form}.each do |action| - m.template "#{action}.html.#{template_language}", - File.join('app/views', controller_class_path, controller_file_name, "#{action}.html.#{template_language}") - m.template "#{action}.html_spec.rb", - File.join('spec/views', controller_class_path, controller_file_name, "#{action}.html.#{template_language}_spec.rb") - end - m.template "index_partial.html.#{template_language}", - File.join('app/views', controller_class_path, controller_file_name, "_#{file_name}.html.#{template_language}") - m.template 'index_partial.html_spec.rb', - File.join('spec/views', controller_class_path, controller_file_name, "_#{file_name}.html.#{template_language}_spec.rb") - - # Helper - m.template 'helper.rb', - File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb") - m.template 'helper_spec.rb', - File.join('spec/helpers', controller_class_path, "#{controller_file_name}_helper_spec.rb") - - # Controller - m.template 'controller.rb', - File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb") - m.template 'controller_spec.rb', - File.join('spec/controllers', controller_class_path, "#{controller_file_name}_controller_spec.rb") - - # Model - m.template 'model.rb', - File.join('app/models', class_path, "#{file_name}.rb") - m.template 'model_spec.rb', - File.join('spec/models', class_path, "#{file_name}_spec.rb") - - # Routing - m.route_resources controller_file_name - - unless options[:skip_migration] - m.migration_template( - 'migration.rb', 'db/migrate', - :assigns => { - :migration_name => "Create#{class_name.pluralize.gsub(/::/, '')}", - :attributes => attributes - }, - :migration_file_name => "create_#{file_path.gsub(/\//, '_').pluralize}" - ) - end - end - end - -protected - def banner - "Usage: #{$0} skinny_scaffold ModelName [field:type, field:type]" - end - - def add_options!(opt) - opt.separator '' - opt.separator 'Options:' - opt.on("--skip-migration", - "Don't generate a migration file for this model") { |v| options[:skip_migration] = v } - end - - def model_name - class_name.demodulize - end -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/controller.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/controller.rb deleted file mode 100644 index ea9b617d..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/controller.rb +++ /dev/null @@ -1,105 +0,0 @@ -class <%= controller_class_name %>Controller < ApplicationController - <%- if defined?(Resourceful::Maker) -%> - make_resourceful do - actions :all - - # Let's get the most use from form_for and share a single form here! - response_for :new, :edit do - render :template => "<%= plural_name %>/form" - end - - response_for :create_fails, :update_fails do - flash[:error] = "There was a problem!" - render :template => "<%= plural_name %>/form" - end - end - <%- else -%> - # GET /<%= table_name %> - # GET /<%= table_name %>.xml - def index - @<%= table_name %> = <%= class_name %>.find(:all) - - respond_to do |format| - format.html # index.html.erb - format.xml { render :xml => @<%= table_name %> } - end - end - - # GET /<%= table_name %>/1 - # GET /<%= table_name %>/1.xml - def show - @<%= file_name %> = <%= class_name %>.find(params[:id]) - - respond_to do |format| - format.html # show.html.erb - format.xml { render :xml => @<%= file_name %> } - end - end - - # GET /<%= table_name %>/new - # GET /<%= table_name %>/new.xml - def new - @<%= file_name %> = <%= class_name %>.new - - respond_to do |format| - format.html { render :template => "<%= plural_name %>/form" } - format.xml { render :xml => @<%= file_name %> } - end - end - - # GET /<%= table_name %>/1/edit - def edit - @<%= file_name %> = <%= class_name %>.find(params[:id]) - render :template => "<%= plural_name %>/form" - end - - # POST /<%= table_name %> - # POST /<%= table_name %>.xml - def create - @<%= file_name %> = <%= class_name %>.new(params[:<%= file_name %>]) - - respond_to do |format| - if @<%= file_name %>.save - flash[:notice] = '<%= class_name %> was successfully created.' - format.html { redirect_to(@<%= file_name %>) } - format.xml { render :xml => @<%= file_name %>, :status => :created, :location => @<%= file_name %> } - else - flash.now[:error] = '<%= class_name %> could not be created.' - format.html { render :template => "<%= plural_name %>/form" } - format.xml { render :xml => @<%= file_name %>.errors, :status => :unprocessable_entity } - end - end - end - - # PUT /<%= table_name %>/1 - # PUT /<%= table_name %>/1.xml - def update - @<%= file_name %> = <%= class_name %>.find(params[:id]) - - respond_to do |format| - if @<%= file_name %>.update_attributes(params[:<%= file_name %>]) - flash[:notice] = '<%= class_name %> was successfully updated.' - format.html { redirect_to(@<%= file_name %>) } - format.xml { head :ok } - else - flash.now[:error] = '<%= class_name %> could not be created.' - format.html { render :template => "<%= plural_name %>/form" } - format.xml { render :xml => @<%= file_name %>.errors, :status => :unprocessable_entity } - end - end - end - - # DELETE /<%= table_name %>/1 - # DELETE /<%= table_name %>/1.xml - def destroy - @<%= file_name %> = <%= class_name %>.find(params[:id]) - @<%= file_name %>.destroy - - respond_to do |format| - flash[:notice] = '<%= class_name %> was successfully deleted.' - format.html { redirect_to(<%= table_name %>_url) } - format.xml { head :ok } - end - end - <%- end -%> -end diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/controller_spec.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/controller_spec.rb deleted file mode 100644 index ff1b6b29..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/controller_spec.rb +++ /dev/null @@ -1,93 +0,0 @@ -require File.dirname(__FILE__) + '/../spec_helper' - -describe <%= controller_class_name %>Controller do - describe "GET :index" do - before(:each) do - @<%= plural_name %> = stub_index(<%= class_name %>) - end - - it_should_find_and_assign :<%= plural_name %> - it_should_render_template "index" - end - - describe "GET :new" do - before(:each) do - @<%= singular_name %> = stub_new(<%= class_name %>) - end - - it_should_initialize_and_assign :<%= singular_name %> - it_should_render_template "form" - end - - describe "POST :create" do - describe "when successful" do - before(:each) do - @<%= singular_name %> = stub_create(<%= class_name %>) - end - - it_should_initialize_and_save :<%= singular_name %> - it_should_set_flash :notice - it_should_redirect_to { <%= singular_name %>_url(@<%= singular_name %>) } - end - - describe "when unsuccessful" do - before(:each) do - @<%= singular_name %> = stub_create(<%= class_name %>, :return => :false) - end - - it_should_initialize_and_assign :<%= singular_name %> - it_should_set_flash :error - it_should_render_template "form" - end - end - - describe "GET :show" do - before(:each) do - @<%= singular_name %> = stub_show(<%= class_name %>) - end - - it_should_find_and_assign :<%= singular_name %> - it_should_render_template "show" - end - - describe "GET :edit" do - before(:each) do - @<%= singular_name %> = stub_edit(<%= class_name %>) - end - - it_should_find_and_assign :<%= singular_name %> - it_should_render_template "form" - end - - describe "PUT :update" do - describe "when successful" do - before(:each) do - @<%= singular_name %> = stub_update(<%= class_name %>) - end - - it_should_find_and_update :<%= singular_name %> - it_should_set_flash :notice - it_should_redirect_to { <%= singular_name %>_url(@<%= singular_name %>) } - end - - describe "when unsuccessful" do - before(:each) do - @<%= singular_name %> = stub_update(<%= class_name %>, :return => :false) - end - - it_should_find_and_assign :<%= singular_name %> - it_should_set_flash :error - it_should_render_template "form" - end - end - - describe "DELETE :destroy" do - before(:each) do - @<%= singular_name %> = stub_destroy(<%= class_name %>) - end - - it_should_find_and_destroy :<%= singular_name %> - it_should_set_flash :notice - it_should_redirect_to { <%= plural_name %>_url } - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html.erb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html.erb deleted file mode 100644 index ac30dc1b..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html.erb +++ /dev/null @@ -1,25 +0,0 @@ -

<%= singular_name %>.new_record? ? "New" : "Edit" %> <%= model_name %>

-<%% form_for(@<%= singular_name %>) do |f| %> -
- <%%= f.error_messages %> -
- <%- if attributes.blank? -%> -

Add your form elements here, please!

- <%- else -%> - <%- attributes.each do |attribute| -%> -

- <%%= f.label :<%= attribute.name %> %>
- <%%= f.<%= attribute.field_type %> :<%= attribute.name %> %> -

- <%- end -%> - <%- end -%> -
- <%%= submit_tag "Save" %> - -
-<%% end -%> \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html.haml b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html.haml deleted file mode 100644 index d97eabb9..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html.haml +++ /dev/null @@ -1,18 +0,0 @@ -%h1== #{@<%= singular_name %>.new_record? ? "New" : "Edit"} #{<%= model_name %>} -- form_for @<%= singular_name %> do |f| - #form_errors= f.error_messages -<% if attributes.blank? -%> - %p Add your form elements here, please! -<% else -%> - <%- attributes.each do |attribute| -%> - %p - = f.label :<%= attribute.name %> - = f.<%= attribute.field_type %> :<%= attribute.name %> - <%- end -%> -<% end -%> - #commands - = submit_tag "Save" -#navigation_commands - - unless @<%= singular_name %>.new_record? - = button_to "Show", <%= singular_name %>_path(@<%= singular_name %>), :method => "get", :title => "Show <%= singular_name %>. Unsaved changes will be lost." - = button_to "Back to List", <%= plural_name %>_path, :class => "cancel", :method => "get", :title => "Return to <%= singular_name %> list without saving changes" \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html_spec.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html_spec.rb deleted file mode 100644 index bc6f6f24..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/form.html_spec.rb +++ /dev/null @@ -1,40 +0,0 @@ -require File.dirname(__FILE__) + '<%= '/..' * controller_class_nesting_depth %>/../../spec_helper' - -describe "<%= File.join(controller_class_path, controller_singular_name) %>/form.html.<%= template_language %>" do - before(:each) do - @<%= singular_name %> = mock_and_assign(<%= model_name %>, :stub => { -<% if attributes.blank? -%> - # Add your stub attributes and return values here like: - # :name => "Foo", :address => "815 Oceanic Drive" -<% else -%> - <%- attributes.each_with_index do |attribute, index| -%> - <%- case attribute.type when :string, :text -%> - :<%= attribute.name %> => "foo"<%= index < attributes.size - 1 ? "," : "" %> - <%- when :integer, :float, :decimal -%> - :<%= attribute.name %> => 815<%= index < attributes.size - 1 ? "," : "" %> - <%- when :boolean -%> - :<%= attribute.name %> => false<%= index < attributes.size - 1 ? "," : "" %> - <%- when :date, :datetime, :time, :timestamp -%> - :<%= attribute.name %> => 1.week.ago<%= index < attributes.size - 1 ? "," : "" %> - <%- else -%> - :<%= attribute.name %> => nil<%= index < attributes.size - 1 ? "," : "" %> # Could not determine valid attribute - <%- end -%> - <%- end -%> -<% end -%> - }) - end - - it_should_have_form_for :<%= singular_name %> -<% if attributes.blank? -%> - # Add specs for editing attributes here, please! Like this: - # - # it_should_allow_editing :<%= singular_name %>, :foo -<% else -%> - <%- attributes.each do |attribute| -%> - it_should_allow_editing :<%= singular_name %>, :<%= attribute.name %> - <%- end -%> -<% end -%> - - it_should_link_to_show :<%= singular_name %> - it_should_link_to { <%= plural_name %>_path } -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/helper.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/helper.rb deleted file mode 100644 index 9bd821b1..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module <%= controller_class_name %>Helper -end diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/helper_spec.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/helper_spec.rb deleted file mode 100644 index 6a34ca2a..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/helper_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require File.dirname(__FILE__) + '<%= '/..' * controller_class_nesting_depth %>/../spec_helper' - -describe <%= controller_class_name %>Helper do - # Add your specs here or remove this file completely, please! -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html.erb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html.erb deleted file mode 100644 index 318f94e3..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html.erb +++ /dev/null @@ -1,31 +0,0 @@ -

<%= model_name %> List

- - <%%- if @<%= plural_name %>.empty? -%> - - - - - - <%%- else -%> - - - <%- if attributes.blank? -%> - - <%- else -%> - <%- attributes.each do |attribute| -%> - - <%- end -%> - <%- end -%> - - - - - - - <%%= render :partial => @<%= plural_name %> %> - - <%%- end -%> -
There are no <%= plural_name.humanize.downcase %>
<%= attribute.name.titleize %>
-
- <%%= button_to "New <%= singular_name.titleize %>", new_<%= singular_name %>_path, :method => "get" %> -
\ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html.haml b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html.haml deleted file mode 100644 index b0c78b28..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html.haml +++ /dev/null @@ -1,23 +0,0 @@ -%h1 <%= model_name %> List -%table - - if @<%= plural_name %>.empty? - %tbody - %tr.empty - %td== There are no <%= plural_name.humanize.downcase %> - - else - %thead - %tr -<% if attributes.blank? -%> - %th= # Generic display column -<% else -%> - <%- attributes.each do |attribute| -%> - %th <%= attribute.name.titleize %> - <%- end -%> -<% end -%> - %th.show= # 'Show' link column - %th.edit= # 'Edit' link column - %th.delete= # 'Delete' link column - %tbody - = render :partial => @<%= plural_name %> -#commands - = button_to "New <%= singular_name.titleize %>", new_<%= singular_name %>_path, :method => "get" \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html_spec.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html_spec.rb deleted file mode 100644 index cfe213f5..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index.html_spec.rb +++ /dev/null @@ -1,15 +0,0 @@ -require File.dirname(__FILE__) + '<%= '/..' * controller_class_nesting_depth %>/../../spec_helper' - -describe "<%= File.join(controller_class_path, controller_singular_name) %>/index.html.<%= template_language %>" do - before(:each) do - @<%= plural_name %> = mock_and_assign_collection(<%= model_name %>) - template.stub! :render - end - - it "should render :partial => @<%= plural_name %>" do - template.should_receive(:render).with(:partial => @<%= plural_name %>) - do_render - end - - it_should_link_to_new :<%= singular_name %> -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html.erb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html.erb deleted file mode 100644 index ecdca836..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html.erb +++ /dev/null @@ -1,12 +0,0 @@ -"> -<% if attributes.blank? -%> - <%= model_name %> #<%%= <%= singular_name %>.id %> -<% else -%> - <%- attributes.each do |attribute| -%> - <%%=h <%= singular_name %>.<%= attribute.name %> %> - <%- end %> -<% end -%> - <%%= button_to "Show", <%= singular_name %>, :method => "get" %> - <%%= button_to "Edit", edit_<%= singular_name %>_path(<%= singular_name %>), :method => "get" %> - <%%= button_to "Delete", <%= singular_name %>, :method => "delete" %> - \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html.haml b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html.haml deleted file mode 100644 index 08b3b383..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html.haml +++ /dev/null @@ -1,11 +0,0 @@ -%tr{:class => cycle("odd", "even")} -<% if attributes.blank? -%> - %td== <%= model_name %> #{<%= singular_name %>.id} -<% else -%> - <%- attributes.each do |attribute| -%> - %td=h <%= singular_name %>.<%= attribute.name %> - <%- end -%> -<% end -%> - %td.show= button_to "Show", <%= singular_name %>_path(<%= singular_name %>), :method => "get" - %td.edit= button_to "Edit", edit_<%= singular_name %>_path(<%= singular_name %>), :method => "get" - %td.delete= button_to "Delete", <%= singular_name %>, :method => "delete" \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html_spec.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html_spec.rb deleted file mode 100644 index 2a10afb1..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/index_partial.html_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require File.dirname(__FILE__) + '<%= '/..' * controller_class_nesting_depth %>/../../spec_helper' - -describe "<%= File.join(controller_class_path, controller_singular_name) %>/_<%= singular_name %>.html.<%= template_language %>" do - before(:each) do - @<%= singular_name %> = mock_and_assign(<%= model_name %>, :stub => { -<% if attributes.blank? -%> - # Add your stub attributes and return values here like: - # :name => "Foo", :created_at => 1.week.ago, :updated_at => nil -<% else -%> - <%- attributes.each_with_index do |attribute, index| -%> - <%- case attribute.type when :string, :text -%> - :<%= attribute.name %> => "foo"<%= index < attributes.size - 1 ? "," : "" %> - <%- when :integer, :float, :decimal -%> - :<%= attribute.name %> => 815<%= index < attributes.size - 1 ? "," : "" %> - <%- when :boolean -%> - :<%= attribute.name %> => false<%= index < attributes.size - 1 ? "," : "" %> - <%- when :date, :datetime, :time, :timestamp -%> - :<%= attribute.name %> => 1.week.ago<%= index < attributes.size - 1 ? "," : "" %> - <%- else -%> - :<%= attribute.name %> => nil<%= index < attributes.size - 1 ? "," : "" %> - <%- end -%> - <%- end -%> -<% end -%> - }) - template.stub!(:<%= singular_name %>).and_return(@<%= singular_name %>) - end - - it_should_link_to_show :<%= singular_name %> - it_should_link_to_edit :<%= singular_name %> - it_should_link_to_delete :<%= singular_name %> -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/migration.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/migration.rb deleted file mode 100644 index 2e4c29c8..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/migration.rb +++ /dev/null @@ -1,14 +0,0 @@ -class <%= migration_name %> < ActiveRecord::Migration - def self.up - create_table :<%= table_name %>, :force => true do |t| -<% attributes.each do |attribute| -%> - t.column :<%= attribute.name %>, :<%= attribute.type %> -<% end -%> - t.timestamps - end - end - - def self.down - drop_table :<%= table_name %> - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/model.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/model.rb deleted file mode 100644 index 202f8b30..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/model.rb +++ /dev/null @@ -1,2 +0,0 @@ -class <%= class_name %> < ActiveRecord::Base -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/model_spec.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/model_spec.rb deleted file mode 100644 index ed6a1945..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/model_spec.rb +++ /dev/null @@ -1,25 +0,0 @@ -require File.dirname(__FILE__) + '<%= '/..' * class_nesting_depth %>/../spec_helper' - -describe <%= class_name %> do - def valid_attributes(args = {}) - { - # Add valid attributes for building your model instances here! - }.merge(args) - end - - before(:each) do - @<%= singular_name %> = <%= class_name %>.new - end - - after(:each) do - @<%= singular_name %>.destroy - end - - # Add your model specs here, please! - # And don't forget about the association matchers built-in to skinny_spec like: - # - # it_should_have_many :foos - # it_should_validate_presence_of :bar - # - # Check out the docs for more information. -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html.erb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html.erb deleted file mode 100644 index 5db36d56..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html.erb +++ /dev/null @@ -1,15 +0,0 @@ -

Show <%= model_name %>

-<% if attributes.blank? -%> -

Add your customized markup here, please!

-<% else -%> - <%- attributes.each do |attribute| -%> -

- - <%%=h @<%= singular_name %>.<%= attribute.name %> %> -

- <%- end -%> -<% end -%> -
- <%%= button_to "Edit", edit_<%= singular_name %>_path(@<%= singular_name %>), :method => "get" %> - <%%= button_to "Back to List", <%= plural_name %>_path, :method => "get" %> -
diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html.haml b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html.haml deleted file mode 100644 index d8afe80a..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html.haml +++ /dev/null @@ -1,13 +0,0 @@ -%h1== Show #{<%= model_name %>} -<% if attributes.blank? -%> -%p Add your customized markup here, please! -<% else -%> - <%- attributes.each do |attribute| -%> -%p - %label <%= attribute.name.titleize %>: - =h @<%= singular_name %>.<%= attribute.name %> - <%- end -%> -<% end -%> -#commands - = button_to "Edit", edit_<%= singular_name %>_path(@<%= singular_name %>), :method => "get" - = button_to "Back to List", <%= plural_name %>_path, :method => "get" \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html_spec.rb b/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html_spec.rb deleted file mode 100644 index aefbbe17..00000000 --- a/backup.rails2.3/plugins/skinny_spec/generators/skinny_scaffold/templates/show.html_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require File.dirname(__FILE__) + '<%= '/..' * controller_class_nesting_depth %>/../../spec_helper' - -describe "<%= File.join(controller_class_path, controller_singular_name) %>/show.html.<%= template_language %>" do - before(:each) do -<% if attributes.blank? -%> - @<%= singular_name %> = mock_and_assign(<%= model_name %>) -<% else -%> - @<%= singular_name %> = mock_and_assign(<%= model_name %>, :stub => { - <%- attributes.each_with_index do |attribute, index| -%> - <%- case attribute.type when :string, :text -%> - :<%= attribute.name %> => "foo"<%= index < attributes.size - 1 ? "," : "" %> - <%- when :integer, :float, :decimal -%> - :<%= attribute.name %> => 815<%= index < attributes.size - 1 ? "," : "" %> - <%- when :boolean -%> - :<%= attribute.name %> => false<%= index < attributes.size - 1 ? "," : "" %> - <%- when :date, :datetime, :time, :timestamp -%> - :<%= attribute.name %> => 1.week.ago<%= index < attributes.size - 1 ? "," : "" %> - <%- else -%> - :<%= attribute.name %> => nil<%= index < attributes.size - 1 ? "," : "" %> - <%- end -%> - <%- end -%> - }) -<% end -%> - end - - # Add your specs here, please! But remember not to make them brittle - # by specing specing specific HTML elements and classes. - - it_should_link_to_edit :<%= singular_name %> - it_should_link_to { <%= plural_name %>_path } -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/common_spec_helpers.rb b/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/common_spec_helpers.rb deleted file mode 100644 index 0a7acff3..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/common_spec_helpers.rb +++ /dev/null @@ -1,83 +0,0 @@ -module LuckySneaks - # These methods are mostly just called internally by various other spec helper - # methods but you're welcome to use them as needed in your own specs. - module CommonSpecHelpers - # Stubs out Time.now and returns value to use when comparing it. Example: - # - # time_now = stub_time_now - # @foo.some_method_that_resets_updated_at - # @foo.updated_at.should == time_now - def stub_time_now - returning Time.now do |now| - Time.stub!(:now).and_return(now) - end - end - - # Returns class for the specified name. Example: - # - # class_for("foo") # => Foo - def class_for(name) - name.to_s.constantize - rescue NameError - name.to_s.pluralize.classify.constantize - # Let any other error rise! - end - - # Returns instance variable for the specified name. Example: - # - # instance_for("foo") # => @foo - def instance_for(name) - instance_variable_get("@#{name.to_s.underscore}") - end - - # Wraps a matcher that checks if the receiver contains an A element (link) - # whose href attribute is set to the specified path. - def have_link_to(path) - have_tag("a[href='#{path}']") - end - - # Returns dummy value for specified attribute based on the datatype expected for that - # attribute. - def dummy_value_for(instance, attribute) - if datatype = instance.column_for_attribute(attribute) - actual = instance.send(attribute) - case datatype.type - when :string, :text - actual == "foo" ? "bar" : "food" - when :integer, :float, :decimal - actual == 108 ? 815 : 108 - when :boolean - actual ? false : true - when :date, :datetime, :time, :timestamp - actual == 1.week.ago ? 2.years.ago : 1.week.ago - end - end - end - - # Returns class description text - def class_description_text - if self.class.respond_to?(:description_text) - # Old school - self.class.description_text - else - # New school - self.class.description - end - end - - # Returns description text - def self_description_text - if respond_to?(:description_text) - # Old school - description_text - else - # New school - description - end - end - - def described_type - self.class.described_type - end - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_request_helpers.rb b/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_request_helpers.rb deleted file mode 100644 index 4aeffaf4..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_request_helpers.rb +++ /dev/null @@ -1,67 +0,0 @@ -module LuckySneaks - module ControllerRequestHelpers # :nodoc: - def self.included(base) - base.extend ExampleGroupMethods - end - - private - def define_implicit_request(method) - @controller_method = method - @implicit_request = case method - when :index, :new, :show, :edit - proc { get method, params } - when :create - proc { post :create, params } - when :update - proc { put :update, params } - when :destroy - proc { put :destroy, params } - end - end - - def eval_request - instance_eval &self.class.instance_variable_get("@the_request") - rescue ArgumentError # missing block - try_shared_request_definition - end - alias do_request eval_request - - def try_shared_request_definition - if defined?(shared_request) == "method" - shared_request - elsif @implicit_request - try_implicit_request - else - error_message = "Could not determine request definition for 'describe' context. " - error_message << "Please use define_request or define a shared_request." - raise ArgumentError, error_message - end - end - - def try_implicit_request - @implicit_request.call - end - - def get_response(&block) - eval_request - block.call(response) if block_given? - response - end - - module ExampleGroupMethods - # Defines a request at the example group ("describe") level to be evaluated in the examples. Example: - # - # define_request { get :index, params } - # - # Note: The following methods all define implicit requests: stub_index, stub_new, - # stub_create, stub_show, stub_edit, stub_update, and - # stub_destroy. Using them in your before blocks will allow you to forego - # defining explicit requests using define_request. See - # LuckySneaks::ControllerStubHelpers for information on these methods. - def define_request(&block) - raise ArgumentError, "Must provide a block to define a request!" unless block_given? - @the_request = block - end - end - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_spec_helpers.rb b/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_spec_helpers.rb deleted file mode 100644 index 20bca87e..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_spec_helpers.rb +++ /dev/null @@ -1,571 +0,0 @@ -$:.unshift File.join(File.dirname(__FILE__), "..") -require "skinny_spec" - -module LuckySneaks - module ControllerSpecHelpers # :nodoc: - include LuckySneaks::CommonSpecHelpers - include LuckySneaks::ControllerRequestHelpers - include LuckySneaks::ControllerStubHelpers - - def self.included(base) - base.extend ExampleGroupMethods - base.extend ControllerRequestHelpers::ExampleGroupMethods - end - - # Evaluates the specified block for each of the RESTful controller methods. - # This is useful to spec that all controller methods redirect when no user is - # logged in. - def with_default_restful_actions(params = {}, &block) - { - :get => :index, - :get => :new, - :post => :create - }.each do |method_id, message| - self.send method_id, message, params - block.call - end - { - :get => :edit, - :put => :update, - :delete => :destroy - }.each do |method_id, message| - if params[:before] - params.delete(:before).call - end - # Presuming any id will do - self.send method_id, message, params.merge(:id => 1) - block.call - end - end - - private - def create_ar_class_expectation(name, method, argument = nil, options = {}) - args = [] - unless options.delete(:only_method) - args << argument unless argument.nil? - args << hash_including(options) unless options.empty? - end - method = options.delete(:find_method) if options[:find_method] - if args.empty? - class_for(name).should_receive(method).and_return(instance_for(name)) - else - class_for(name).should_receive(method).with(*args).and_return(instance_for(name)) - end - end - - def create_positive_ar_instance_expectation(name, method, *args) - instance = instance_for(name) - if args.empty? - instance.should_receive(method).and_return(true) - else - instance.should_receive(method).with(*args).and_return(true) - end - end - - # These methods are designed to be used at the example group [read: "describe"] level - # to simplify and DRY up common expectations. - module ExampleGroupMethods - # Creates an expectation that the controller method calls ActiveRecord::Base.find. - # Examples: - # - # it_should_find :foos # => Foo.should_receive(:find).with(:all) - # it_should_find :foos, :all # An explicit version of the above - # it_should_find :foos, :conditions => {:foo => "bar"} # => Foo.should_receive(:find).with(:all, :conditions => {"foo" => "bar"} - # it_should_find :foos, "joe", :method => :find_all_by_name # Foo.should_receive(:find_all_by_name).with("joe") - # it_should_find :foo # => Foo.should_recieve(:find).with(@foo.id.to_s) - # it_should_find :foo, :params => "id" # => Foo.should_receive(:find).with(params[:id].to_s) - # it_should_find :foo, 2 # => Foo.should_receive(:find).with("2") - # it_should_find :foo, "joe", :method => :find_by_name # => Foo.should_recieve(:find_by_name).with("joe") - # - # Note: All params (key and value) will be strings if they come from a form element and are handled - # internally with this expectation. - def it_should_find(name, *args) - name_string = name.to_s - name_message = if name_string == name_string.singularize - "a #{name}" - else - name - end - it "should find #{name_message}" do - options = args.extract_options! - # Blech! - argument = if param = params[options.delete(:params)] - param.to_s - else - if args.first - args.first - elsif (instance = instance_variable_get("@#{name}")).is_a?(ActiveRecord::Base) - instance.id.to_s - else - :all - end - end - find_method = options.delete(:method) || :find - create_ar_class_expectation name, find_method, argument, options - eval_request - end - end - - # Negative version of it_should_find. This creates an expectation that - # the class never receives find at all. - def it_should_not_find(name) - name_string = name.to_s - name_message = if name_string == name_string.singularize - "a #{name}" - else - name - end - it "should not find #{name_message}" do - if name_string == name_string.singularize - class_for(name).should_not_receive(:find) - else - class_for(name).should_not_receive(:find).with(:all) - end - eval_request - end - end - - # Creates an expectation that the controller method calls ActiveRecord::Base.new. - # Takes optional params for the initialization arguments. Example - # - # it_should_initialize :foo # => Foo.should_receive(:new) - # it_should_initialize :foo, :params => :bar # => Foo.should_receive(:new).with(params[:bar]) - # it_should_initialize :foo, :bar => "baz" # => Foo.should_receive(:new).with(:bar => "baz") - def it_should_initialize(name, options = {}) - it "should initialize a #{name}" do - create_ar_class_expectation name, :new, params[options.delete(:params)], options - eval_request - end - end - - # Negative version of it_should_initialize. This creates an expectation - # that the class never recieves new at all. - def it_should_not_initialize(name) - it "should initialize a #{name}" do - class_for(name).should_not_receive(:new) - eval_request - end - end - - # Creates an expectation that the controller method calls ActiveRecord::Base#save on the - # named instance. Example: - # - # it_should_save :foo # => @foo.should_receive(:save).and_return(true) - # - # Note: This helper should not be used to spec a failed save call. Use it_should_assign - # instead, to verify that the instance is captured in an instance variable for the inevitable re-rendering - # of the form template. - def it_should_save(name) - it "should save the #{name}" do - create_positive_ar_instance_expectation name, :save - eval_request - end - end - - # Negative version of it_should_update. This creates an expectation - # that the instance never receives save at all. - def it_should_not_save(name) - it "should not save the #{name}" do - instance_for(name).should_not_receive(:save) - eval_request - end - end - - # Creates an expectation that the controller method calls ActiveRecord::Base#update_attributes - # on the named instance. Takes optional argument for params to specify in the - # expectation. Examples: - # - # it_should_update :foo # => @foo.should_receive(:update_attributes).and_return(true) - # it_should_update :foo, :params => :bar # => @foo.should_receive(:update_attributes).with(params[:bar]).and_return(true) - # - # Note: This helper should not be used to spec a failed update_attributes call. Use - # it_should_assign instead, to verify that the instance is captured in an instance variable - # for the inevitable re-rendering of the form template. - def it_should_update(name, options = {}) - it "should update the #{name}" do - create_positive_ar_instance_expectation name, :update_attributes, params[name] - eval_request - end - end - - # Negative version of it_should_update. This creates an expectation - # that the instance never receives update_attributes at all. - def it_should_not_update(name) - it "should not update the #{name}" do - instance_for(name).should_not_receive(:update_attributes) - eval_request - end - end - - # Creates an expectation that the controller method calls ActiveRecord::Base#destroy on the named - # instance. Example: - # - # it_should_destroy :foo # => @foo.should_receive(:destroy).and_return(true) - # - # Note: This helper should not be used to spec a failed destroy call. Use - # it_should_assign instead, if you need to verify that the instance is captured in an instance - # variable if it is re-rendered somehow. This is probably a really edge use case. - def it_should_destroy(name, options = {}) - it "should delete the #{name}" do - create_positive_ar_instance_expectation name, :destroy - eval_request - end - end - - # Negative version of it_should_destroy. This creates an expectation - # that the instance never receives destroy at all. - def it_should_not_destroy(name) - it "should not destroy the #{name}" do - instance_for(name).should_not_receive(:destroy) - eval_request - end - end - - # Creates expectation[s] that the controller method should assign the specified - # instance variables along with any specified values. Examples: - # - # it_should_assign :foo # => assigns[:foo].should == @foo - # it_should_assign :foo => "bar" # => assigns[:foo].should == "bar" - # it_should_assign :foo => :nil # => assigns[:foo].should be_nil - # it_should_assign :foo => :not_nil # => assigns[:foo].should_not be_nil - # it_should_assign :foo => :undefined # => controller.send(:instance_variables).should_not include("@foo") - # - # Very special thanks to Rick Olsen for the basis of this code. The only reason I even - # redefine it at all is purely an aesthetic choice for specs like "it should foo" - # over ones like "it foos". - def it_should_assign(*names) - names.each do |name| - if name.is_a?(Symbol) - it_should_assign name => name - elsif name.is_a?(Hash) - name.each do |key, value| - it_should_assign_instance_variable key, value - end - end - end - end - - # Essentially shorthand for it_should_assign name => :nil. This method can take multiple - # instance variable names, creating this shorthand for each name. See the docs for - # it_should_assign for more information. - def it_should_not_assign(*names) - names.each do |name| - # Assuming name is a symbol - it_should_assign name => :nil - end - end - - # Wraps the separate expectations it_should_find and it_should_assign - # for simple cases. If you need more control over the parameters of the find, this - # isn't the right helper method and you should write out the two expectations separately. - def it_should_find_and_assign(*names) - names.each do |name| - it_should_find name, :only_method => true - it_should_assign name - end - end - - # Negative version of it_should_find_and_assign. This creates an - # expectation that the class never receives find at all and that - # no matching instance variable is ever created. - def it_should_not_find_and_assign(*names) - names.each do |name| - it_should_not_find name - it_should_assign name => :nil - end - end - - # Wraps the separate expectations it_should_initialize and it_should_assign - # for simple cases. If you need more control over the parameters of the initialization, this - # isn't the right helper method and you should write out the two expectations separately. - # - # Note: This method is used for controller methods like new, where the instance - # is initialized without being saved (this includes failed create requests). - # If you want to spec that the controller method successfully saves the instance, - # please use it_should_initialize_and_save. - def it_should_initialize_and_assign(*names) - names.each do |name| - it_should_initialize name, :only_method => true - it_should_assign name - end - end - - # Negative version of it_should_initialize_and_assign. This creates an - # expectation that the class never receives new at all and that - # no matching instance variable is ever created. - def it_should_not_initialize_and_assign(*names) - names.each do |name| - it_should_not_initialize name - it_should_assign name => :nil - end - end - - # Wraps the separate expectations it_should_initialize and it_should_save - # for simple cases. If you need more control over the parameters of the initialization, this - # isn't the right helper method and you should write out the two expectations separately. - # - # Note: This method is used for controller methods like create, where the instance - # is initialized and successfully saved. If you want to spec that the instance is created - # but not saved, just use it_should_initialize_and_assign. - def it_should_initialize_and_save(*names) - names.each do |name| - it_should_initialize name, :only_method => true - it_should_save name - end - end - - # Wraps the separate expectations it_should_find and it_should_update - # for simple cases. If you need more control over the parameters of the find, this - # isn't the right helper method and you should write out the two expectations separately. - # - # Note: This method is used for controller methods like update, where the - # instance is loaded from the database and successfully saved. If you want to spec that the - # instance is found but not saved, just use it_should_find_and_assign. - def it_should_find_and_update(*names) - names.each do |name| - it_should_find name, :only_method => true - it_should_update name - end - end - - # Wraps the separate expectations it_should_find and it_should_destroy - # for simple cases. If you need more control over the parameters of the find, this - # isn't the right helper method and you should write out the two expectations separately. - def it_should_find_and_destroy(*names) - names.each do |name| - it_should_find name, :only_method => true - it_should_destroy name - end - end - - # Creates an expectation that the specified collection (flash, session, - # params, cookies) contains the specified key and value. To specify that - # the collection should be set to nil, specify the value as :nil instead. - def it_should_set(collection, key, value = nil, &block) - it "should set #{collection}[:#{key}]#{' with ' + value.inspect if value}" do - # Allow flash.now[:foo] to remain in the flash - flash.stub!(:sweep) if collection == :flash - eval_request - if value - if value == :nil - self.send(collection)[key].should be_nil - else - self.send(collection)[key].should == value - end - elsif block_given? - self.send(collection)[key].should == instance_eval(&block) - else - self.send(collection)[key].should_not be_nil - end - end - end - - # Wraps it_should_set :flash. To specify that the collection should be set - # to nil, specify the value as :nil instead. - def it_should_set_flash(name, value = nil, &block) - it_should_set :flash, name, value, &block - end - - # Wraps it_should_set :flash, :nil. - def it_should_not_set_flash(name) - it_should_set :flash, name, :nil - end - - # Wraps it_should_set :session. To specify that the collection should be set - # to nil, specify the value as :nil instead. - def it_should_set_session(name, value = nil, &block) - it_should_set :session, name, value, &block - end - - # Wraps it_should_set :session, :nil. - def it_should_not_set_session(name) - it_should_set :session, name, :nil - end - - # Wraps it_should_set :params. To specify that the collection should be set - # to nil, specify the value as :nil instead. - def it_should_set_params(name, value = nil, &block) - it_should_set :params, name, value, &block - end - - # Wraps it_should_set :params, :nil. - def it_should_not_set_params(name) - it_should_set :params, name, :nil - end - - # Wraps it_should_set :cookies. To specify that the collection should be set - # to nil, specify the value as :nil instead. - def it_should_set_cookies(name, value = nil, &block) - it_should_set :cookies, name, value, &block - end - - # Wraps it_should_set :cookies, :nil. - def it_should_not_set_cookies(name) - it_should_set :cookies, name, :nil - end - - # Wraps the various it_should_render_foo methods: - # it_should_render_template, it_should_render_partial, - # it_should_render_xml, it_should_render_json, - # it_should_render_formatted, and it_should_render_nothing. - def it_should_render(render_method, *args) - send "it_should_render_#{render_method}", *args - end - - # Creates an expectation that the controller method renders the specified template. - # Accepts the following options which create additional expectations. - # - # :content_type:: Creates an expectation that the Content-Type header for the response - # matches the one specified - # :status:: Creates an expectation that the HTTP status for the response - # matches the one specified - def it_should_render_template(name, options = {}) - create_status_expectation options[:status] if options[:status] - it "should render '#{name}' template" do - eval_request - response.should render_template(name) - end - create_content_type_expectation(options[:content_type]) if options[:content_type] - end - - # Creates an expectation that the controller method renders the specified partial. - # Accepts the following options which create additional expectations. - # - # :content_type:: Creates an expectation that the Content-Type header for the response - # matches the one specified - # :status:: Creates an expectation that the HTTP status for the response - # matches the one specified - def it_should_render_partial(name, options = {}) - create_status_expectation options[:status] if options[:status] - it "should render '#{name}' partial" do - controller.expect_render(:partial => name) - eval_request - end - create_content_type_expectation(options[:content_type]) if options[:content_type] - end - - # Creates an expectation that the controller method renders the specified record via to_xml. - # Accepts the following options which create additional expectations. - # - # :content_type:: Creates an expectation that the Content-Type header for the response - # matches the one specified - # :status:: Creates an expectation that the HTTP status for the response - # matches the one specified - def it_should_render_xml(record = nil, options = {}, &block) - it_should_render_formatted :xml, record, options, &block - end - - # Creates an expectation that the controller method renders the specified record via to_json. - # Accepts the following options which create additional expectations. - # - # :content_type:: Creates an expectation that the Content-Type header for the response - # matches the one specified - # :status:: Creates an expectation that the HTTP status for the response - # matches the one specified - def it_should_render_json(record = nil, options = {}, &block) - it_should_render_formatted :json, record, options, &block - end - - # Called internally by it_should_render_xml and it_should_render_json - # but should not really be called much externally unless you have defined your own - # formats with a matching to_foo method on the record. - # - # Which is probably never. - def it_should_render_formatted(format, record = nil, options = {}, &block) - create_status_expectation options[:status] if options[:status] - it "should render #{format.inspect}" do - if record.is_a?(Hash) - options = record - record = nil - end - if record.nil? && !block_given? - raise ArgumentError, "it_should_render must be called with either a record or a block and neither was given." - else - if record - pieces = record.to_s.split(".") - record = instance_variable_get("@#{pieces.shift}") - record = record.send(pieces.shift) until pieces.empty? - end - block ||= proc { record.send("to_#{format}") } - get_response do |response| - response.should have_text(block.call) - end - end - end - create_content_type_expectation(options[:content_type]) if options[:content_type] - end - - # Creates an expectation that the controller method returns a blank page. You'd already - # know when and why to use this so I'm not typing it out. - def it_should_render_nothing(options = {}) - create_status_expectation options[:status] if options[:status] - it "should render :nothing" do - get_response do |response| - response.body.strip.should be_blank - end - end - end - - # Creates an expectation that the controller method redirects to the specified destination. Example: - # - # it_should_redirect_to { foos_url } - # - # Note: This method takes a block to evaluate the route in the example - # context rather than the example group context. - def it_should_redirect_to(hint = nil, &route) - if hint.nil? && route.respond_to?(:to_ruby) - hint = route.to_ruby.gsub(/(^proc \{)|(\}$)/, '').strip - end - it "should redirect to #{(hint || route)}" do - eval_request - response.should redirect_to(instance_eval(&route)) - end - end - - # Negative version of it_should_redirect_to. - def it_should_not_redirect_to(hint = nil, &route) - if hint.nil? && route.respond_to?(:to_ruby) - hint = route.to_ruby.gsub(/(^proc \{)|(\}$)/, '').strip - end - it "should not redirect to #{(hint || route)}" do - eval_request - response.should_not redirect_to(instance_eval(&route)) - end - end - - # Creates an expectation that the controller method redirects back to the previous page - def it_should_redirect_to_referer - it "should redirect to the referring page" do - request.env["HTTP_REFERER"] = "http://test.host/referer" - eval_request - response.should redirect_to("http://test.host/referer") - end - end - alias it_should_redirect_to_referrer it_should_redirect_to_referer - - private - def it_should_assign_instance_variable(name, value) - expectation_proc = case value - when :nil - proc { assigns[name].should be_nil } - when :not_nil - proc { assigns[name].should_not be_nil } - when :undefined - proc { controller.send(:instance_variables).should_not include("@{name}") } - when Symbol - if (instance_variable = instance_variable_get("@#{name}")).nil? - proc { assigns[name].should_not be_nil } - else - proc { assigns[name].should == instance_variable } - end - else - proc { assigns[name].should == value } - end - it "should #{value == :nil ? 'not ' : ''}assign @#{name}" do - eval_request - instance_eval &expectation_proc - end - end - end - end -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_stub_helpers.rb b/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_stub_helpers.rb deleted file mode 100644 index 6d78ce54..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/controller_stub_helpers.rb +++ /dev/null @@ -1,238 +0,0 @@ -module LuckySneaks # :nodoc: - # These methods are designed to be used in your example before blocks to accomplish - # a whole lot of functionality with just a tiny bit of effort. The methods which correspond - # to the controller methods perform the most duties as they create the mock_model instances, - # stub out all the necessary methods, and also create implicit requests to DRY up your spec - # file even more. You are encouraged to use these methods to setup the basic calls for your - # resources and only resort to the other methods when mocking and stubbing secondary objects - # and calls. - module ControllerStubHelpers - # Stubs out find :all and returns a collection of mock_model - # instances of that class. Accepts the following options: - # - # :find_method:: Method to use as finder call. Default is :find. - # Note: When specifying the method, the call is stubbed - # to accept any arguments. Caveat programmer. - # :format:: Format of the request. Used to only add to_xml and - # to_json when actually needed. - # :size:: Number of instances to return in the result. Default is 3. - # :stub:: Additional methods to stub on the instances - # - # Any additional options will be passed as arguments to the class find. - # You will want to make sure to pass those arguments to the it_should_find spec as well. - def stub_find_all(klass, options = {}) - returning(Array.new(options[:size] || 3){mock_model(klass)}) do |collection| - stub_out klass, options.delete(:stub) - if format = options.delete(:format) - stub_formatted collection, format - params[:format] = format - end - if find_method = options[:find_method] - # Not stubbing specific arguments here - # If you need more specificity, write a custom example - klass.stub!(find_method).and_return(collection) - else - klass.stub!(:find).with(:all).and_return(collection) - klass.stub!(:find).with(:all, hash_including(options)).and_return(collection) - end - end - end - - # Alias for stub_find_all but additionally defines an implicit request get :index. - def stub_index(klass, options = {}) - define_implicit_request :index - stub_find_all klass, options - end - - # Stubs out new method and returns a mock_model instance marked as a new record. - # Accepts the following options: - # - # :format:: Format of the request. Used to only add to_xml and - # to_json when actually needed. - # :stub:: Additional methods to stub on the instances - # - # It also accepts some options used to stub out save with a specified true - # or false but you should be using stub_create in that case. - def stub_initialize(klass, options = {}) - returning mock_model(klass) do |member| - stub_out member, options.delete(:stub) - if format = options[:format] - stub_formatted member, format - params[:format] = format - end - klass.stub!(:new).and_return(member) - if options[:params] - klass.stub!(:new).with(hash_including(options[:params])).and_return(member) - end - if options[:stub_save] - stub_ar_method member, :save, options[:return] - else - member.stub!(:new_record?).and_return(true) - member.stub!(:id).and_return(nil) - end - end - end - - # Alias for stub_initialize which additionally defines an implicit request get :new. - def stub_new(klass, options = {}) - define_implicit_request :new - stub_initialize klass, options - end - - # Alias for stub_initialize which additionally defines an implicit request post :create. - # - # Note: If stub_create is provided an optional :params hash, - # those params will be added to the example's params object. - def stub_create(klass, options = {}) - define_implicit_request :create - class_name = klass.name.underscore - options[:params] ||= params[class_name] - stub_initialize klass, options.merge(:stub_save => true) - end - - # Stubs out find and returns a single mock_model - # instances of that class. Accepts the following options: - # - # :find_method:: Method to use as finder call. Default is :find. - # :format:: Format of the request. Used to only add to_xml and - # to_json when actually needed. - # :stub:: Additional methods to stub on the instances - # :current_object:: If set to true, find will set params[:id] - # using the id of the mock_model instance - # and use that value as an argument when stubbing find - # - # Any additional options will be passed as arguments to find.You will want - # to make sure to pass those arguments to the it_should_find spec as well. - # - # Note: The option :stub_ar is used internally by stub_update - # and stub_destroy. If you need to stub update_attributes or - # destroy you should be using the aforementioned methods instead. - def stub_find_one(klass, options = {}) - returning mock_model(klass) do |member| - stub_out member, options.delete(:stub) - if format = options.delete(:format) - stub_formatted member, format - params[:format] = format - end - if options.delete(:current_object) - params[:id] = member.id - if ar_stub = options.delete(:stub_ar) - stub_ar_method member, ar_stub, options.delete(:return), options.delete(:update_params) - end - end - if find_method = options.delete(:find_method) - klass.stub!(find_method).and_return(member) - else - # Stubbing string and non-string just to be safe - klass.stub!(:find).with(member.id).and_return(member) - klass.stub!(:find).with(member.id.to_s).and_return(member) - unless options.empty? - klass.stub!(:find).with(member.id, hash_including(options)).and_return(member) - klass.stub!(:find).with(member.id.to_s, hash_including(options)).and_return(member) - end - end - end - end - - # Note: Use of this method with :child options (to mock - # association) is deprecated. Please use stub_association. - # - # Same as stub_find_one but setups the instance as the parent - # of the specified association. Example: - # - # stub_parent(Document, :child => :comments) - # - # This stubs Document.find, @document.comments (which - # will return Comment class), as well as params[:document_id]. - # This method is meant to be used in the controller for the specified child - # (CommentsController in this instance) in situations like: - # - # def index - # @document = Document.find(params[:document_id]) - # @comments = @document.comments.find(:all) - # end - def stub_parent(klass, options = {}) - returning stub_find_one(klass, options) do |member| - params[klass.name.foreign_key] = member.id - if offspring = options.delete(:child) - puts "stub_parent with :child option has been marked for deprecation" - puts "please use stub_association to create the mock instead" - member.stub!(offspring).and_return(class_for(offspring)) - end - end - end - - # Alias for stub_find_one which additionally defines an implicit request get :show. - def stub_show(klass, options = {}) - define_implicit_request :show - stub_find_one klass, options.merge(:current_object => true) - end - - # Alias for stub_find_one which additionally defines an implicit request get :edit. - def stub_edit(klass, options = {}) - define_implicit_request :edit - stub_find_one klass, options.merge(:current_object => true) - end - - # Alias for stub_find_one which additionally defines an implicit request put :update - # and stubs out the update_attribute method on the instance as well. - # - # Note: If stub_update is provided an optional :params hash, - # those params will be added to the example's params object. - def stub_update(klass, options = {}) - define_implicit_request :update - stub_find_one klass, options.merge(:current_object => true, :stub_ar => :update_attributes) - end - - # Alias for stub_find_one which additionally defines an implicit request delete :destroy - # and stubs out the destroy method on the instance as well. - def stub_destroy(klass, options = {}) - define_implicit_request :destroy - stub_find_one klass, options.merge(:current_object => true, :stub_ar => :destroy) - end - - # Stubs to_xml or to_json respectively based on format argument. - def stub_formatted(object, format) - return unless format - object.stub!("to_#{format}").and_return("#{object.class} formatted as #{format}") - end - - # Creates a mock object representing an association proxy, stubs the appropriate - # method on the parent object and returns that association proxy. - # Accepts the following option: - # - # :stub:: Additional methods to stub on the mock proxy object - def stub_association(object, association, options = {}) - # I know options isn't implemented anywhere - object_name = instance_variables.select{|name| instance_variable_get(name) == object} - returning mock("Association proxy for #{object_name}.#{association}") do |proxy| - stub_out proxy, options[:stub] if options[:stub] - object.stub!(association).and_return(proxy) - end - end - - private - # Stubs out multiple methods. You shouldn't be calling this yourself and if you do - # you should be able to understand the code yourself, right? - def stub_out(object, stubs = {}) - return if stubs.nil? - stubs.each do |method, value| - if value - object.stub!(method).and_return(value) - else - object.stub!(method) - end - end - end - - # Stubs out ActiveRecord::Base methods like #save, #update_attributes, etc - # that may be called on a found or instantiated mock_model instance. - def stub_ar_method(object, method, return_value, params = {}) - if params.blank? - object.stub!(method).and_return(return_value ? false : true) - else - object.stub!(method).with(hash_including(params)).and_return(return_value ? false : true) - end - end - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/model_spec_helpers.rb b/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/model_spec_helpers.rb deleted file mode 100644 index 4119acc6..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/model_spec_helpers.rb +++ /dev/null @@ -1,496 +0,0 @@ -$:.unshift File.join(File.dirname(__FILE__), "..") -require "skinny_spec" - -module LuckySneaks - # These methods are designed to be used in your example [read: "it"] blocks - # to make your model specs a little more DRY. You might also be interested - # in checking out the example block [read: "describe"] level versions in of these - # methods which can DRY things up even more: - # LuckySneaks::ModelSpecHelpers::ExampleGroupLevelMethods. - # - # Also check out the methods in LuckySneaks::ModelSpecHelpers::AssociationMatcher - # for some helpful matcher helper methods to use with these methods if you want to spec - # options on your association setups. - module ModelSpecHelpers - include LuckySneaks::CommonSpecHelpers - - def self.included(base) # :nodoc: - base.extend ExampleGroupLevelMethods - end - - # These methods cannot be used alone but are used in compliment with the association - # matchers in LuckySneaks::ModelSpecHelpers like have_many. Example: - # - # describe User do - # it "should have many memberships" do - # User.should have_many(:memberships) - # end - # - # it "should have many sites through memberships" do - # User.should have_many(:sites).through(:memberships) - # end - # - # it "should belong to a manager" do - # User.should belong_to(:manager).with_counter_cache - # end - # end - # - # Note: To spec these sorts of options using the example block helpers like - # it_should_have_many, just add them as options directly. This will use - # with_options rather than any specific matcher helpers but will have the same - # effects. Example: - # - # describe User do - # it_should_have_many :sites, :through => :memberships - # end - class AssociationMatcher - def initialize(associated, macro) # :nodoc: - @associated = associated - @macro = macro - @options = {} - end - - def matches?(main_model) # :nodoc: - unless main_model.respond_to?(:reflect_on_association) - if main_model.class.respond_to?(:reflect_on_association) - main_model = main_model.class - else - @not_model = main_model - return false - end - end - if @association = main_model.reflect_on_association(@associated) - @options.all?{|k, v| @association.options[k] == v || - [@association.options[k]] == v} # Stupid to_a being obsoleted! - end - end - - def failure_message # :nodoc: - if @not_model - " expected: #{@not_model} to be a subclass of ActiveRecord::Base class, but was not" - elsif @association - " expected: #{association_with(@options)}\n got: #{association_with(@association.options)}" - else - " expected: #{association_with(@options)}, but the association does not exist" - end - end - - def negative_failure_message # :nodoc: - if @association - " expected: #{association_with(@options)}\n got: #{association_with(@association.options)}" - else - " expected: #{association_with(@options)} to not occur but it does" - end - end - - # The following public methods are chainable extensions on the main matcher - # Examples: - # - # Foo.should have_many(:bars).through(:foobars).with_dependent(:destroy) - # Bar.should belong_to(:baz).with_class_name("Unbaz") - def through(through_model) - @options[:through] = through_model - self - end - - def and_includes(included_models) - @options[:include] = included_models - self - end - - def and_extends(*modules) - @options[:extends] = modules - self - end - - def with_counter_cache(counter_cache = true) - if counter_cache - @options[:counter_cache] = counter_cache - end - self - end - - def uniq(*irrelevant_args) - @options[:uniq] = true - self - end - alias and_is_unique uniq - alias with_unique uniq - - def polymorphic(*irrelevant_args) - @options[:polymorphic] = true - self - end - alias and_is_polymorphic polymorphic - alias with_polymorphic polymorphic - - def as(interface) - @options[:as] = interface - end - - # Use this to just specify the options as a hash. - # Note: It will completely override any previously set options - def with_options(options = {}) - options.each{|k, v| @options[k] = v} - self - end - - private - # Takes care of methods like with_dependent(:destroy) - def method_missing(method_id, *args, &block) - method_name = method_id.to_s - if method_name =~ /^with_(.*)/ - @options[$1.to_sym] = args - self - else - super method_id, *args, &block - end - end - - def association_with(options) - option_string = (options.nil? || options.empty?) ? "" : options.inspect - unless option_string.blank? - option_string.sub! /^\{(.*)\}$/, ', \1' - option_string.gsub! /\=\>/, ' => ' - end - "#{@macro} :#{@associated}#{option_string}" - end - end - - # Creates matcher that checks if the receiver has a belongs_to association - # with the specified model. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def belong_to(model) - AssociationMatcher.new model, :belongs_to - end - - # Creates matcher that checks if the receiver has a have_one association - # with the specified model. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def have_one(model) - AssociationMatcher.new model, :has_one - end - - # Creates matcher that checks if the receiver has a have_many association - # with the specified model. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def have_many(models) - AssociationMatcher.new models, :has_many - end - - # Creates matcher that checks if the receiver has a have_and_belong_to_many association - # with the specified model. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def have_and_belong_to_many(models) - AssociationMatcher.new models, :has_and_belongs_to_many - end - - private - def class_or_instance - @model_spec_class_or_instance ||= class_for(described_type) || instance - end - - def instance - @model_spec_instance ||= instance_for(described_type) - end - - # These methods are designed to be used at the example group [read: "describe"] level - # to simplify and DRY up common expectations. Some of these methods are wrappers for - # matchers which can also be used on the example level [read: within an "it" block]. See - # LuckySneaks::ModelSpecHelpers for more information. - # - # Note: The validation matchers are only meant to be used for simple validation checking - # not as a one-size-fits-all solution. - module ExampleGroupLevelMethods - # Creates an expectation that the current model being spec'd has a belong_to - # association with the specified model. Accepts optional arguments which are appended to - # the belong_to spec like this: - # - # it_should_belong_to :document, :counter_cache => true - # - # which is the same as writing out: - # - # it "should belong to document" do - # Comment.should belong_to(:document).with_options(:counter_cache => true) - # end - # - # If you want a more detailed spec description text, feel free to write this out in the long - # form and use belong_to and its related matcher helpers. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def it_should_belong_to(model, options = {}) - it "should belong to a #{model}" do - if options.empty? - class_or_instance.should belong_to(model) - else - class_or_instance.should belong_to(model).with_options(options) - end - end - end - - # Creates an expectation that the current model being spec'd has a have_one - # association with the specified model. Accepts optional arguments which are appended to - # the have_one spec like this: - # - # it_should_have_one :last_comment, :class_name => "Comment", :order => "created_at DESC" - # - # which is the same as writing out: - # - # it "should have one document" do - # Document.should have_one(:last_comment).with_options(:class_name => "Comment", :order => "created_at DESC") - # end - # - # If you want a more detailed spec description text, feel free to write this out in the long - # form and use have_one and its related matcher helpers. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def it_should_have_one(model, options = {}) - it "should have one #{model}" do - if options.empty? - class_or_instance.should have_one(model) - else - class_or_instance.should have_one(model).with_options(options) - end - end - end - - # Creates an expectation that the current model being spec'd has a have_many - # association with the specified model. Accepts optional arguments which are appended to - # the have_many spec like this: - # - # it_should_have_many :memberships, :through => :sites - # - # which is the same as writing out: - # - # it "should have many memberships" do - # User.should have_many(:memberships).with_options(:through => :sites) - # end - # - # If you want a more detailed spec description text, feel free to write this out in the long - # form and use have_many and its related matcher helpers. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def it_should_have_many(models, options = {}) - it "should have many #{models}" do - if options.empty? - class_or_instance.should have_many(models) - else - class_or_instance.should have_many(models).with_options(options) - end - end - end - - # Creates an expectation that the current model being spec'd has a have_and_belong_to_many - # association with the specified model. Accepts optional arguments which are appended to - # the have_and_belong_to_many spec like this: - # - # it_should_have_and_belong_to_many :documents, :include => :attachments - # - # which is the same as writing out: - # - # it "should belong to document" do - # User.should have_and_belong_to_many(:documents).with_options(:include => :attachments) - # end - # - # If you want a more detailed spec description text, feel free to write this out in the long - # form and use have_and_belong_to_many and its related matcher helpers. - # - # Note: The argument should be a symbol as in the model's association definition - # and not the model's class name. - def it_should_have_and_belong_to_many(models, options = {}) - it "should have and belong to many #{models}" do - if options.empty? - class_or_instance.should have_and_belong_to_many(models) - else - class_or_instance.should have_and_belong_to_many(models).with_options(options) - end - end - end - - # Creates an expectation that new instances of the model being spec'd - # should initialise the specified attributes with a default value. - # - # it_should_default_attributes :status => 'new' - # - def it_should_default_attributes(hash_attribute_values) - hash_attribute_values.each_pair do |a,v| - it "should default #{a} attribute to #{v}" do - class_or_instance.new.send(a).should == v - end - end - end - - # Creates an expectation that the current model being spec'd validates_presence_of - # the specified attribute. Takes an optional custom message to match the one in the model's - # validation. - def it_should_validate_presence_of(attribute, message = default_error_message(:blank)) - it "should not be valid if #{attribute} is blank" do - instance.send "#{attribute}=", nil - instance.errors_on(attribute).should include(message) - end - end - - # Negative version of it_should_validate_presence_of. See that method for more - # details. You'd probably only be using this in a nested example block to compare that - # one scenario validates presence and another does not (because of conditions in - # :if/:unless). - def it_should_not_validate_presence_of(attribute, message = default_error_message(:blank)) - it "should be valid if #{attribute} is blank" do - instance.send "#{attribute}=", nil - instance.errors_on(attribute).should_not include(message) - end - end - - # Creates an expectation that the current model being spec'd validates_inclusion_of - # the specified attribute. Takes an optional custom message to match the one in the model's - # validation. - def it_should_validate_inclusion_of(attribute, options = {}, message = default_error_message(:inclusion)) - it "should validate #{attribute} is in #{options[:in].to_s}" do - # We specifically do not try to go below the range on String and character ranges because that problem set is unpredictable. - lower = options[:in].first.respond_to?(:-) ? options[:in].first - 0.0001 : nil - higher = options[:in].last.succ - - instance.send "#{attribute}=", lower - instance.errors_on(attribute).should include(message) - - instance.send "#{attribute}=", higher - instance.errors_on(attribute).should include(message) - - instance.send "#{attribute}=", (lower+higher)/2 - instance.errors_on(attribute).should_not include(message) - end - end - - # Creates an expectation that the current model being spec'd validates_numericality_of - # the specified attribute. Takes an optional custom message to match the one in the model's - # validation. - def it_should_validate_numericality_of(attribute, message = default_error_message(:not_a_number)) - it "should validate #{attribute} is a numeric" do - instance.send "#{attribute}=", "NaN" - instance.errors_on(attribute).should include(message) - end - end - - # Negative version of it_should_validate_numericality_of. See that method for more - # details. You'd probably only be using this in a nested example block to compare that - # one scenario validates presence and another does not (because of conditions in - # :if/:unless). - def it_should_not_validate_numericality_of(attribute, message = default_error_message(:not_a_number)) - it "should not validate #{attribute} is a numeric" do - instance.send "#{attribute}=", "NaN" - instance.errors_on(attribute).should_not include(message) - end - end - - # Creates an expectation that the current model being spec'd validates_confirmation_of - # the specified attribute. Takes an optional custom message to match the one in the model's - # validation. - def it_should_validate_confirmation_of(attribute, message = default_error_message(:confirmation)) - it "should validate confirmation of #{attribute}" do - dummy_value = dummy_value_for(instance, attribute) || "try a string" - instance.send "#{attribute}=", dummy_value - instance.send "#{attribute}_confirmation=", dummy_value.succ - instance.errors_on(attribute).should include(message) - end - end - - # Creates an expectation that the current model being spec'd validates_uniqueness_of - # the specified attribute. Takes an optional custom message to match the one in the model's - # validation. - # - # Note: This method will fail completely if valid_attributes - # does not provide all the attributes needed to create a valid record. - def it_should_validate_uniqueness_of(attribute, message = default_error_message(:taken)) - it "should validate uniqueness of #{attribute}" do - previous_instance = instance.class.create!(valid_attributes) - instance.attributes = valid_attributes - instance.errors_on(attribute).should include(message) - previous_instance.destroy - end - end - - # Negative version of it_should_validate_uniqueness_of. See that method for more - # details. You'd probably only be using this in a nested example block to compare that - # one scenario validates presence and another does not (because of conditions in - # :if/:unless). - def it_should_not_validate_uniqueness_of(attribute, message = default_error_message(:taken)) - it "should not validate uniqueness of #{attribute}" do - previous_instance = instance.class.create!(valid_attributes) - instance.attributes = valid_attributes - instance.errors_on(attribute).should_not include(message) - previous_instance.destroy - end - end - - # Creates an expectation that the current model being spec'd accepts the specified values as - # valid for the specified attribute. This is most likely used with validates_format_of - # but there's nothing saying it couldn't be another validation. - def it_should_accept_as_valid(attribute, *values) - values.flatten.each do |value| - value_inspect = case value - when String : "'#{value}'" - when NilClass : "nil" - else value - end - it "should accept #{value_inspect} as a valid #{attribute}" do - instance.send "#{attribute}=", value - instance.errors_on(attribute).should == [] - end - end - end - - # Creates an expectation that the current model being spec'd does not accept the specified - # values as valid for the specified attribute. This is most likely used with - # validates_format_of but there's nothing saying it couldn't be another validation. - # Takes an optional argument :message => "some custom error messsage" for - # spec'ing the actual error message. - def it_should_not_accept_as_valid(attribute, *values) - options = values.extract_options! - values.flatten.each do |value| - value_inspect = case value - when String : "'#{value}'" - when NilClass : "nil" - else value - end - it "should not accept #{value_inspect} as a valid #{attribute}" do - instance.send "#{attribute}=", value - if options[:message] - instance.errors_on(attribute).should include(options[:message]) - else - instance.should have_at_least(1).errors_on(attribute) - end - end - end - end - - # Creates an expectation that the current model being spec'd doesn't allow mass-assignment - # of the specified attribute. - def it_should_not_mass_assign(attribute) - it "should not allow mass-assignment of #{attribute}" do - lambda { - instance.send :attributes=, {attribute => dummy_value_for(instance, attribute)} - }.should_not change(instance, attribute) - end - end - - def default_error_message(attribute) - if defined?(I18n) - I18n.translate attribute, :scope => "activerecord.errors.messages" - else - ActiveRecord::Errors.default_error_messages[attribute] - end - end - end - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/view_spec_helpers.rb b/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/view_spec_helpers.rb deleted file mode 100644 index fb8775a1..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/view_spec_helpers.rb +++ /dev/null @@ -1,577 +0,0 @@ -$:.unshift File.join(File.dirname(__FILE__), "..") -require "skinny_spec" - -module LuckySneaks - # These methods are designed to be used in your example [read: "it"] blocks - # to make your view specs less brittle and more DRY. You might also be interested - # in checking out the example block [read: "describe"] level versions in of these - # methods which can DRY things up even more: - # LuckySneaks::ViewSpecHelpers::ExampleGroupLevelMethods. - module ViewSpecHelpers - include LuckySneaks::CommonSpecHelpers - include LuckySneaks::ViewStubHelpers - include ActionController::PolymorphicRoutes - - def self.included(base) # :nodoc: - base.extend ExampleGroupLevelMethods - end - - # Wraps a matcher that checks if the receiver contains a FORM element with - # its action attribute set to the specified path. - def submit_to(path) - have_tag("form[action=#{path}]") - end - - # Wraps a matcher that checks if the receiver contains any of several form elements - # that would return sufficient named parameters to allow editing of the specified - # attribute on the specified instance. Example: - # - # response.should allow_editing(@foo, "bar") - # - # can be satisfied by any of the following HTML elements: - # - # - # - # - # - # - def allow_editing(instance, attribute) - instance_name = instance.class.name.underscore.downcase - column = instance.column_for_attribute(attribute) - if column && [Date, Time].include?(column.klass) - have_tag( - "input[name='#{instance_name}[#{attribute}]'], - select[name=?]", /#{instance_name}\[#{attribute}\(.*\)\]/ - ) - else - have_tag( - "input[type='text'][name='#{instance_name}[#{attribute}]'], - input[type='password'][name='#{instance_name}[#{attribute}]'], - select[name='#{instance_name}[#{attribute}]'], - textarea[name='#{instance_name}[#{attribute}]'], - input[type='checkbox'][name='#{instance_name}[#{attribute}]'], - input[type='checkbox'][name='#{instance_name}[#{attribute.to_s.tableize.singularize}_ids][]'], - input[type='radio'][name='#{instance_name}[#{attribute}]']" - ) - end - end - - # Wraps a matcher that checks if the receiver contains a FORM element - # whose enctype attribute is set to "multipart/form-data" - # and contains an INPUT element whose name attribute correlates - # with the provided instance and attribute. - def allow_uploading(instance, attribute) - instance_name = instance.class.name.underscore.downcase - have_tag("form[enctype='multipart/form-data'] input[type='file'][name='#{instance_name}[#{attribute}]']") - end - - # Wraps a matcher that checks if the receiver contains an A element (link) - # whose href attribute is set to the specified path or a FORM - # element whose action attribute is set to the specified path. - def have_link_or_button_to(path) - have_tag( - "a[href='#{path}'], - form[action='#{path}'] input, - form[action='#{path}'] button" - ) - end - alias have_link_to have_link_or_button_to - alias have_button_to have_link_or_button_to - - # Wraps have_link_or_button_to new_polymorphic_path for the specified class which - # corresponds with the new method of the controller. - # - # Note: This method may takes a string or symbol representing the model's name - # to send to have_link_or_button_to_show or the model's name itself. - def have_link_or_button_to_new(name) - have_link_or_button_to new_polymorphic_path(name.is_a?(ActiveRecord::Base) ? name : class_for(name)) - end - - # Wraps have_link_or_button_to polymorphic_path(instance) which - # corresponds with the show method of the controller. - def have_link_or_button_to_show(instance) - path = polymorphic_path(instance) - have_tag( - "a[href='#{path}'], - form[action='#{path}'][method='get'] input, - form[action='#{path}'][method='get'] button, - form[action='#{path}'] input[name='_method'][value='get'] + input, - form[action='#{path}'] input[name='_method'][value='get'] + button" - ) - end - alias have_link_to_show have_link_or_button_to_show - alias have_button_to_show have_link_or_button_to_show - - # Wraps have_link_or_button_to edit_polymorphic_path(instance) which - # corresponds with the edit method of the controller. - def have_link_or_button_to_edit(instance) - have_link_or_button_to edit_polymorphic_path(instance) - end - alias have_link_to_edit have_link_or_button_to_edit - alias have_button_to_edit have_link_or_button_to_edit - - # Wraps a matcher that checks if the receiver contains the HTML created by Rails' - # button_to helper: to wit, a FORM element whose action - # attribute is pointed at the polymorphic_path of the instance - # and contains an INPUT named "_method" with a value of "delete". - def have_button_to_delete(instance) - path = polymorphic_path(instance) - have_tag( - "form[action='#{path}'] input[name='_method'][value='delete'] + input, - form[action='#{path}'] input[name='_method'][value='delete'] + button, - a[href=\"#{path}\"][onclick*=\"f.method = 'POST'\"][onclick*=\"m.setAttribute('name', '_method'); m.setAttribute('value', 'delete')\"]" - ) - end - - # Creates a mock_model instance and adds it to the assigns collection - # using either the name passed as the first argument or the underscore version - # of its class name. Accepts optional arguments to stub out additional methods - # (and their return values) on the mock_model instance. Example: - # - # mock_and_assign(Foo, :stub => {:bar => "bar"}) - # - # is the same as running assigns[:foo] = mock_model(Foo, :bar => "bar"). - # - # mock_and_assign(Foo, "special_foo", :stub => {:bar => "baz"}) - # - # is the same as running assigns[:special_foo] = mock_model(Foo, :bar => "baz"). - # - # Note: Adding to the assigns collection returns the object added, so this can - # be chained a la @foo = mock_and_assign(Foo). - def mock_and_assign(klass, *args) - options = args.extract_options! - mocked = if options[:stub] - self.respond_to?(:stub_model) ? stub_model(klass, options[:stub]) : mock_model(klass, options[:stub]) - else - self.respond_to?(:stub_model) ? stub_model(klass) : mock_model(klass) - end - yield mocked if block_given? - self.assigns[args.first || "#{klass}".underscore] = mocked - end - - # Creates an array of mock_model instances in the manner of - # mock_and_assign. Accepts option[:size] which sets the size - # of the array (default is 3). - def mock_and_assign_collection(klass, *args) - options = args.extract_options! - return_me = Array.new(options[:size] || 3) do - mocked = if options[:stub] - self.respond_to?(:stub_model) ? stub_model(klass, options[:stub]) : mock_model(klass, options[:stub]) - else - self.respond_to?(:stub_model) ? stub_model(klass) : mock_model(klass) - end - yield mocked if block_given? - mocked - end - self.assigns[args.first || "#{klass}".tableize] = return_me - end - - private - def do_render - if @the_template - render @the_template - elsif File.exists?(File.join(RAILS_ROOT, "app/views", class_description_text)) - render class_description_text - else - error_message = "Cannot determine template for render. " - error_message << "Please define @the_template in the before block " - error_message << "or name your describe block so that it indicates the correct template." - raise NameError, error_message - end - end - - # These methods are designed to be used at the example group [read: "describe"] level - # to simplify and DRY up common expectations. Most of these methods are wrappers for - # matchers which can also be used on the example level [read: within an "it" block]. See - # LuckySneaks::ViewSpecHelpers for more information. - module ExampleGroupLevelMethods - include LuckySneaks::CommonSpecHelpers - - # Creates an expectation which calls submit_to on the response - # from rendering the template. See that method for more details. - # - # Note: This method takes a Proc to evaluate the route not simply a named route - # helper, which would be undefined in the scope of the example block. - def it_should_submit_to(hint = nil, &route) - if hint.nil? && route.respond_to?(:to_ruby) - hint = route.to_ruby.gsub(/(^proc \{)|(\}$)/, '').strip - end - it "should submit to #{(hint || route)}" do - do_render - response.should submit_to(instance_eval(&route)) - end - end - - # Negative version of it_should_submit_to. See that method for more - # details. - def it_should_not_submit_to(hint = nil, &route) - if hint.nil? && route.respond_to?(:to_ruby) - hint = route.to_ruby.gsub(/(^proc \{)|(\}$)/, '').strip - end - it "should not submit to #{(hint || route)}" do - do_render - response.should_not submit_to(instance_eval(&route)) - end - end - - # Creates an expectation that the template uses Rails' form_for to generate - # the proper form action and method to create or update the specified object. - # - # Note: This method takes a string or symbol representing the instance - # variable's name to create the expectation for form_for - # not an instance variable, which would be nil in the scope of the example block. - # If you use namespacing for your form_for, you'll have to manually write out - # a similar spec. - def it_should_have_form_for(name, options = {}) - it "should have a form_for(@#{name})" do - if options.empty? - template.should_receive(:form_for).with(instance_for(name)) - else - template.should_receive(:form_for).with(instance_for(name), hash_including(options)) - end - do_render - end - end - - # Negative version of it_should_have_form_for. See that method for more - # details. - def it_should_not_have_form_for(name, options = {}) - it "should not have a form_for(@#{name})" do - if options.empty? - template.should_not_receive(:form_for).with(instance_for(name)) - else - template.should_not_receive(:form_for).with(instance_for(name), hash_including(options)) - end - do_render - end - end - - # Creates an expectation which calls allow_editing on the rendered - # template for each attribute specified. See the docs for allow_editing - # for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name to send to allow_editing - # not an instance variable, which would be nil in the scope of the example block. - def it_should_allow_editing(instance_name, *attributes) - attributes.flatten! - attributes.each do |attribute| - it "should allow editing of @#{instance_name}##{attribute}" do - do_render - response.should allow_editing(instance_for(instance_name), attribute) - end - end - end - - # Negative version of it_should_allow_editing. See that method for more - # details. - def it_should_not_allow_editing(instance_name, *attributes) - attributes.flatten! - attributes.each do |attribute| - it "should not allow editing of @#{instance_name}##{attribute}" do - do_render - response.should_not allow_editing(instance_for(instance_name), attribute) - end - end - end - - # Creates an expectation which calls allow_uploading on the rendered - # template for each attribute specified. See the docs for allow_uploading - # for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name to send to allow_uploading - # not an instance variable, which would be nil in the scope of the example block. - def it_should_allow_uploading(instance_name, *attributes) - attributes.flatten! - attributes.each do |attribute| - it "should allow editing of @#{instance_name}##{attribute}" do - do_render - response.should allow_uploading(instance_for(instance_name), attribute) - end - end - end - - # Negative version of it_should_allow_uploading. See that method for more - # details. - def it_should_not_allow_uploading(instance_name, *attributes) - attributes.flatten! - attributes.each do |attribute| - it "should not allow editing of @#{instance_name}##{attribute}" do - do_render - response.should_not allow_uploading(instance_for(instance_name), attribute) - end - end - end - - # Creates an expectation that the rendered template contains a FORM element - # (INPUT, TEXTAREA, or SELECT) with the specified name. - def it_should_have_form_element_for(name) - it "should have a form element named '#{name}'" do - do_render - response.should have_tag( - "form input[name='#{name}'], - form textarea[name='#{name}'], - form select[name='#{name}']" - ) - end - end - - # Negative version of it_should_have_form_element_for. See that method - # for more details. - def it_should_not_have_form_element_for(name) - it "should not have a form element named '#{name}'" do - do_render - response.should_not have_tag( - "form input[name='#{name}'], - form textarea[name='#{name}'], - form select[name='#{name}']" - ) - end - end - - # Creates an expectation which calls have_link_or_button_to on the response - # from rendering the template. See that method for more details. - # - # Note: This method takes a block to evaluate the route in the example context - # instead of the example group context. - def it_should_link_to(hint = nil, &route) - if hint.nil? && route.respond_to?(:to_ruby) - hint = route.to_ruby.gsub(/(^proc \{)|(\}$)/, '').strip - end - it "should have a link/button to #{(hint || route)}" do - do_render - response.should have_link_or_button_to(instance_eval(&route)) - end - end - alias it_should_have_link_to it_should_link_to - alias it_should_have_button_to it_should_link_to - alias it_should_have_button_or_link_to it_should_link_to - - # Negative version of it_should_link_to. See that method - # for more details. - def it_should_not_link_to(hint = nil, &route) - if hint.nil? && route.respond_to?(:to_ruby) - hint = route.to_ruby.gsub(/(^proc \{)|(\}$)/, '').strip - end - it "should have a link/button to #{(hint || route)}" do - do_render - response.should_not have_link_or_button_to(instance_eval(&route)) - end - end - alias it_should_not_have_link_to it_should_not_link_to - alias it_should_not_have_button_to it_should_not_link_to - alias it_should_not_have_button_or_link_to it_should_not_link_to - - # Creates an expectation which calls have_link_or_button_to_new on the response - # from rendering the template. See that method for more details. - # - # Note: This method may takes a string or symbol representing the model's name - # to send to have_link_or_button_to_show or the model's name itself. - def it_should_link_to_new(name) - it "should have a link/button to create a new #{name}" do - do_render - response.should have_link_or_button_to_new(name) - end - end - alias it_should_have_link_to_new it_should_link_to_new - alias it_should_have_button_to_new it_should_link_to_new - alias it_should_have_button_or_link_to_new it_should_link_to_new - - # Negative version of it_should_link_to_show. See that method - # for more details. - def it_should_not_link_to_new(name) - it "should have a link/button to create a new #{name}" do - do_render - response.should_not have_link_or_button_to_new(name) - end - end - alias it_should_not_have_link_to_new it_should_not_link_to_new - alias it_should_not_have_button_to_new it_should_not_link_to_new - alias it_should_not_have_button_or_link_to_new it_should_not_link_to_new - - # Creates an expectation which calls have_link_or_button_to_show on the response - # from rendering the template. See that method for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name to send to have_link_or_button_to_show - # not an instance variable, which would be nil in the scope of the example block. - def it_should_link_to_show(name) - it "should have a link/button to show @#{name}" do - do_render - response.should have_link_or_button_to_show(instance_for(name)) - end - end - alias it_should_have_link_to_show it_should_link_to_show - alias it_should_have_button_to_show it_should_link_to_show - alias it_should_have_button_or_link_to_show it_should_link_to_show - - # Negative version of it_should_link_to_show. See that method - # for more details. - def it_should_not_link_to_show(name) - it "should have a link/button to show @#{name}" do - do_render - response.should_not have_link_or_button_to_show(instance_for(name)) - end - end - alias it_should_not_have_link_to_show it_should_not_link_to_show - alias it_should_not_have_button_to_show it_should_not_link_to_show - alias it_should_not_have_button_or_link_to_show it_should_not_link_to_show - - # Creates an expectation which calls have_link_or_button_to_show - # for each member of the instance variable matching the specified name - # on the response from rendering the template. See that method for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name and not an instance variable, which would be nil - # in the scope of the example block. - def it_should_link_to_show_each(name) - it "should have a link/button to show each member of @#{name}" do - do_render - instance_for(name).each do |member| - response.should have_link_or_button_to_show(member) - end - end - end - alias it_should_have_link_to_show_each it_should_link_to_show_each - alias it_should_have_button_to_show_each it_should_link_to_show_each - alias it_should_have_button_or_link_to_show_each it_should_link_to_show_each - - # Creates an expectation which calls have_link_or_button_to_edit on the response - # from rendering the template. See that method for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name to send to have_link_or_button_to_edit - # not an instance variable, which would be nil in the scope of the example block. - def it_should_link_to_edit(name) - it "should have a link/button to edit @#{name}" do - do_render - response.should have_link_or_button_to_edit(instance_for(name)) - end - end - alias it_should_have_link_to_edit it_should_link_to_edit - alias it_should_have_button_to_edit it_should_link_to_edit - alias it_should_have_button_or_link_to_edit it_should_link_to_edit - - # Negative version of it_should_link_to_edit. See that method - # for more details. - def it_should_not_link_to_edit(name) - it "should have a link/button to edit @#{name}" do - do_render - response.should_not have_link_or_button_to_edit(instance_for(name)) - end - end - alias it_should_not_have_link_to_edit it_should_not_link_to_edit - alias it_should_not_have_button_to_edit it_should_not_link_to_edit - alias it_should_not_have_button_or_link_to_edit it_should_not_link_to_edit - - - # Creates an expectation which calls have_link_or_button_to_edit - # for each member of the instance variable matching the specified name - # on the response from rendering the template. See that method for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name and not an instance variable, which would be nil - # in the scope of the example block. - def it_should_link_to_edit_each(name) - it "should have a link/button to edit each member of @#{name}" do - do_render - instance_for(name).each do |member| - response.should have_link_or_button_to_edit(member) - end - end - end - alias it_should_have_link_to_edit_each it_should_link_to_edit_each - alias it_should_have_button_to_edit_each it_should_link_to_edit_each - alias it_should_have_button_or_link_to_edit_each it_should_link_to_edit_each - - # Creates an expectation which calls have_link_or_button_to_delete on the response - # from rendering the template. See that method for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name to send to have_link_or_button_to_delete - # not an instance variable, which would be nil in the scope of the example block. - def it_should_link_to_delete(name) - it "should have a link/button to delete @#{name}" do - do_render - response.should have_button_to_delete(instance_for(name)) - end - end - alias it_should_have_link_to_delete it_should_link_to_delete - alias it_should_have_button_to_delete it_should_link_to_delete - alias it_should_have_button_or_link_to_delete it_should_link_to_delete - - # Negative version of it_should_link_to_delete. See that method - # for more details. - def it_should_not_link_to_delete(name) - it "should not have a link/button to delete @#{name}" do - do_render - response.should_not have_button_to_delete(instance_for(name)) - end - end - alias it_should_not_have_link_to_delete it_should_not_link_to_delete - alias it_should_not_have_button_to_delete it_should_not_link_to_delete - alias it_should_not_have_button_or_link_to_delete it_should_not_link_to_delete - - # Creates an expectation which calls have_link_or_button_to_delete - # for each member of the instance variable matching the specified name - # on the response from rendering the template. See that method for more details. - # - # Note: This method takes a string or symbol representing the instance - # variable's name and not an instance variable, which would be nil - # in the scope of the example block. - def it_should_link_to_delete_each(name) - it "should have a link/button to delete each member of @#{name}" do - do_render - instance_for(name).each do |member| - response.should have_button_to_delete(member) - end - end - end - alias it_should_have_link_to_delete_each it_should_link_to_delete_each - alias it_should_have_button_to_delete_each it_should_link_to_delete_each - alias it_should_have_button_or_link_to_delete_each it_should_link_to_delete_each - - # Creates an expectation that the template should call render :partial - # with the specified template. - def it_should_render_partial(name) - it "should render :partial => '#{name}'" do - template.should_receive(:render).with(hash_including(:partial => name)) - do_render - end - end - - # Negative version of it_should_render_partial. See that method - # for more details. - def it_should_not_render_partial(name) - it "should not render :partial => '#{name}'" do - template.should_not_receive(:render).with(hash_including(:partial => name)) - do_render - end - end - - # Sets @the_template (for use in do_render) using the current - # example group description. Example: - # - # describe "users/index.haml.erb" do - # use_describe_for_template! - # # ... - # end - # - # This is equivalent to setting @the_template = "users/index.haml.erb" - # in a before block. - def use_describe_for_template! - template = self_description_text - if File.exists?(File.join(RAILS_ROOT, "app/views", template)) - before(:each) do - @the_template = template - end - else - error_message = "You called use_describe_for_template! " - error_message << "but 'app/views/#{template}' does not exist. " - raise NameError, error_message - end - end - end - end -end diff --git a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/view_stub_helpers.rb b/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/view_stub_helpers.rb deleted file mode 100644 index 2dde384e..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/lucky_sneaks/view_stub_helpers.rb +++ /dev/null @@ -1,15 +0,0 @@ -$:.unshift File.join(File.dirname(__FILE__), "..") -require "skinny_spec" - -module LuckySneaks - # These methods are designed to be used in your example before blocks to accomplish - # a whole lot of functionality with just a tiny bit of effort. - module ViewStubHelpers - # Shorthand for the following stub: - # - # template.stub!(:render).with(hash_including(:partial => anything)) - def stub_partial_rendering! - template.stub!(:render).with(hash_including(:partial => anything)) - end - end -end \ No newline at end of file diff --git a/backup.rails2.3/plugins/skinny_spec/lib/skinny_spec.rb b/backup.rails2.3/plugins/skinny_spec/lib/skinny_spec.rb deleted file mode 100644 index 3c366ce1..00000000 --- a/backup.rails2.3/plugins/skinny_spec/lib/skinny_spec.rb +++ /dev/null @@ -1,26 +0,0 @@ -# Let's make sure everyone else is loaded -require File.expand_path(RAILS_ROOT + "/config/environment") -require 'spec' -require 'spec/rails' -begin - require 'ruby2ruby' -rescue LoadError - puts "-----" - puts "Attention: skinny_spec requires ruby2ruby for nicer route descriptions" - puts "It is highly recommended that you install it: sudo gem install ruby2ruby" - puts "-----" -end - -# Let's load our family now -require "lucky_sneaks/common_spec_helpers" -require "lucky_sneaks/controller_request_helpers" -require "lucky_sneaks/controller_spec_helpers" -require "lucky_sneaks/controller_stub_helpers" -require "lucky_sneaks/model_spec_helpers" -require "lucky_sneaks/view_spec_helpers" - -# Let's all come together -Spec::Rails::Example::ViewExampleGroup.send :include, LuckySneaks::ViewSpecHelpers -Spec::Rails::Example::HelperExampleGroup.send :include, LuckySneaks::CommonSpecHelpers -Spec::Rails::Example::ControllerExampleGroup.send :include, LuckySneaks::ControllerSpecHelpers -Spec::Rails::Example::ModelExampleGroup.send :include, LuckySneaks::ModelSpecHelpers \ No newline at end of file diff --git a/backup.rails2.3/plugins/swf_fu/CHANGELOG.rdoc b/backup.rails2.3/plugins/swf_fu/CHANGELOG.rdoc deleted file mode 100644 index 7b99496e..00000000 --- a/backup.rails2.3/plugins/swf_fu/CHANGELOG.rdoc +++ /dev/null @@ -1,46 +0,0 @@ -= swf_fu --- History - -== Version 1.4.0 - May 8, 2010 - -* Any option can be a block, in which case it is called (with the source swf passed as argument) - -== Version 1.3.1 - February 5, 2010 - -* Improved compatibility with Rails 3.0: swf_tag now outputs html_safe content. - -* Got rid of deprecation warning in Rails 2.2+ when using swf_tag in block form. - -== Version 1.3.0 - June 20, 2009 - -* Updated to swf_object v2.2. Change should not be noticeable to users, except compatibility improvements and better auto install. Added the option +switch_off_auto_hide_show+. - -== Version 1.2.0 - January 14, 2009 - -* flashvars[:id] will now default to the DOM id of the object. I didn't want to have any extra defaults than the very basic ones, but there is no easy way to get this from Flash (see http://www.actionscript.org/forums/showthread.php3?t=136044 ) and no easy way to specify that using +swf_default_options+. -* If flashvars is a string (e.g. "myVar=myValue") it will be parsed into a hash so that the behaviour for default values apply to strings or hashes. swf_default_options[:flashvars] can also be a string and will also be parsed before being merged. -* Small bug fix: the options passed as hashes (:flashvars, :parameters and :html_options) were changed if swf_default_options[:flashvars, ...] existed. They are now left unchanged. - -== Version 1.1.0 - January 3, 2009 - -* Improved the way to specify alternate content - -== Version 1.0.3 - January 3, 2009 - -* Improved javascript initialization - - :initialize => [1, 2, 3] # produces in javascript: obj.initialize(1,2,3) instead of ([1,2,3]) - # no :initialize produces in javascript: obj.initialize() instead of (null) - :initialize => nil # stil produces obj.initialize(null) - -== Version 1.0.2 - January 3, 2009 - -* Bug fix for flashvars in dynamic method - -== Version 1.0.1 - January 2, 2009 - -* File reorganization -* Bug fix for default options - -== Version 1.0 - X-mas, 2008 - -=== Initial release. diff --git a/backup.rails2.3/plugins/swf_fu/FLASH_OBJECT.rdoc b/backup.rails2.3/plugins/swf_fu/FLASH_OBJECT.rdoc deleted file mode 100644 index 87a0e72f..00000000 --- a/backup.rails2.3/plugins/swf_fu/FLASH_OBJECT.rdoc +++ /dev/null @@ -1,31 +0,0 @@ -== Compatibility with FlashObject - -This document is intended for users of FlashObject, a (much older) swf embedding plugin that inspired swf_fu. - -You can choose to: - -1) keep both. They won't interfere and +flashobject_tag+ will continue to use the older SWFObject 1.5 library. - -2) remove FlashObject: - - script/plugin remove flashobject_helper - -You can also manually remove javascripts/flashobject.js - -+swf_fu+ will take over the +flashobject_tag+ and will use the new SWFObject 2.2 library. -This should not have impacts as long as: -* your swf path is absolute (e.g. "/path/to/my_flash.swf"). If it is relative, move your swf file from 'public/' to the new 'public/swfs/' asset folder -* you include the default javascripts (otherwise you need to include 'swfobject' explicitely and stop including 'flashobject') -* you don't use the javascript object before the page is loaded. SWFObject 2.2 makes the changes to the web page later -* you don't rely on the +verify_file_exists+ option (it doesn't do anything anymore) - -In either case 1 or 2, you change existing calls to +flashobject_tag+ for +swf_tag+ at your leisure. -The interface is similar and the main differences are some options name changes: - :flash_id => :id - :variables => :flashvars - :background_color => options[:parameters][:bgcolor] - -Moreover, the following defaults are gone: - :flashvars[:lzproxied] - :parameters[:scale] - :parameters[:bgcolor] diff --git a/backup.rails2.3/plugins/swf_fu/LICENSE b/backup.rails2.3/plugins/swf_fu/LICENSE deleted file mode 100644 index efd683ff..00000000 --- a/backup.rails2.3/plugins/swf_fu/LICENSE +++ /dev/null @@ -1,29 +0,0 @@ -# swf_fu plugin for rails -# Copyright (c) 2010, Marc-André Lafortune. -# All rights reserved. -# Inspired by FlashObject by Davide D'Agostino aka DAddYE (http://www.lipsiasoft.com) -# Uses SWFObject.js 2.1 (http://code.google.com/p/swfobject) -# -# Licensed under the terms of the (modified) BSD License below: -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# * Neither the name of the nor the -# names of its contributors may be used to endorse or promote products -# derived from this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY -# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -# DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY -# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/backup.rails2.3/plugins/swf_fu/README.rdoc b/backup.rails2.3/plugins/swf_fu/README.rdoc deleted file mode 100644 index 1791f1ff..00000000 --- a/backup.rails2.3/plugins/swf_fu/README.rdoc +++ /dev/null @@ -1,92 +0,0 @@ -= +swf_fu+ - -With the +swf_fu+ plugin, rails treats your swf files like any other asset (images, javascripts, etc...). - -+swf_fu+ (pronounced "swif-fu", bonus joke for french speakers) uses SWFObject 2.2 to embed swf objects in HTML and supports all its options. -SWFObject 2 is such a nice library that Adobe now uses it as the official way to embed swf! -SWFObject's project can be found at http://code.google.com/p/swfobject - -+swf_fu+ has been tested with rails v2.0 up to v3.0b and has decent test coverage so rake test:plugins should reveal any incompatibility. Comments and pull requests welcome: http://github.com/marcandre/swf_fu - -== Install - -Assuming you have git[http://git-scm.com/] installed (check with git version), it is easy to install from your applications directory: - - rails plugin install git://github.com/marcandre/swf_fu.git # rails 3 - - script/plugin install git://github.com/marcandre/swf_fu.git # rails 2 (starting at 2.0.2) - -For older versions of +rails+ or without +git+, you can always download -+swf_fu+ from github[http://github.com/marcandre/swf_fu/archives/master] and then install it manually: - - rails plugin install ~/Download/swf_fu # rails 3 - - script/plugin install ~/Downloads/swf_fu # rails 2.x - -== Usage - -=== Embedding in HTML - -To embed a swf file, use +swf_tag+: - <%= swf_tag "i_like_flashing" %> - -Exactly like images and javascripts, +swf_tag+ will use +swf_path+ -to determine the path of the swf file; it will assume it is in /public/swfs/ -unless specified otherwise and it will add the ".swf" extension automatically. - -You can specify alternate content either with the options :alt => "Get Flash!" or you can use +swf_tag+ as a block: - - <% swf_tag "i_like_flashing" do %> - Get Flash - <% end %> - -=== Options - -* :id - the DOM +id+ of the flash +object+ element that is used to contain the Flash object; defaults to the name of the swf in +source+ -* :width, :height - the width & height of the Flash object. Defaults to "100%". These could also specified using :size -* :size - the size of the Flash object, in the form "400x300". -* :mode - Either :dynamic (default) or :static. Refer to SWFObject's doc[http://code.google.com/p/swfobject/wiki/documentation#Should_I_use_the_static_or_dynamic_publishing_method?] -* :flashvars - a Hash of variables that are passed to the swf. Can also be a string like "foo=bar&hello=world". Defaults to {:id => the DOM id} -* :parameters - a Hash of configuration parameters for the swf. See Adobe's doc[http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701#optional] -* :html_options - a Hash of extra html options for the object tag. -* :alt - HTML text that is displayed when the Flash player is not available. Defaults to a "Get Flash" image pointing to Adobe Flash's installation page. This can also be specified as a block (see embedding section). In Rails 3, this text is _assumed_ to be HTML, so there is no need to call +html_safe+ on it. -* :flash_version - the version of the Flash player that is required (e.g. "7" (default) or "8.1.0") -* :auto_install - a swf file that will upgrade flash player if needed (defaults to "expressInstall" which was installed by +swf_fu+) -* :javascript_class - specify a javascript class (e.g. "MyFlash") for your flash object. If it exists, the initialize method will be called. -* :initialize - arguments to pass to the initialization method of your javascript class. -* :div_id - the DOM +id+ of the containing div itself. Defaults to "#{option[:id]}_div" -* :switch_off_auto_hide_show - switch off SWFObject's default hide/show behavior. SWFObject temporarily hides your SWF or alternative content until the library has decided which content to display. Defaults to nil. - -You can override these default options with a global setting: - - ActionView::Base.swf_default_options = {:mode => :static} # All swf_tag will use the static mode by default - -Any of these options can be a +Proc+, in which case it will be called each time swf_tag is called. - -For example, the following will generate unique IDs: - - my_swf_counter = 0 - ActionView::Base.swf_default_options[:id] = Proc.new{"swf_unique_id_#{my_swf_counter+=1}"} - -=== Javascript - -+swf_fu+ will add 'swfobject' to the list of default javascript files. If you don't include -the default javascripts, a simple javascript_include "swfobject" is needed. - -=== swf_path - -+swf_tag+ implements and relies on +swf_path+ which behaves in a similar fashion to +image_path+, +javascript_path+, etc...: - - swf_path("example") => "/swfs/example.swf" - swf_path("example.swf") => "/swfs/example.swf" - swf_path("fonts/optima") => "/swfs/fonts/optima.swf" - swf_path("/fonts/optima") => "/fonts/optima.swf" - swf_path("http://www.example.com/game.swf") => "http://www.example.com/game.swf" - -It takes into account the global setting +asset_host+, like any other asset: - - ActionController::Base.asset_host = "http://assets.example.com" - image_path("logo.jpg") => "http://assets.example.com/images/logo.jpg" - swf_path("fonts/optima") => "http://assets.example.com/swfs/fonts/optima.swf"" - -Copyright (c) 2010 Marc-André Lafortune, released under the BSD license diff --git a/backup.rails2.3/plugins/swf_fu/Rakefile b/backup.rails2.3/plugins/swf_fu/Rakefile deleted file mode 100644 index 9898dadb..00000000 --- a/backup.rails2.3/plugins/swf_fu/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 swf_fu plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the swf_fu plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'Swf Fu' - rdoc.options << '--line-numbers' << '--inline-source' << '-m README.rdoc' - rdoc.rdoc_files.include('*.rdoc') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/backup.rails2.3/plugins/swf_fu/assets/javascripts/swfobject.js b/backup.rails2.3/plugins/swf_fu/assets/javascripts/swfobject.js deleted file mode 100644 index 8eafe9dd..00000000 --- a/backup.rails2.3/plugins/swf_fu/assets/javascripts/swfobject.js +++ /dev/null @@ -1,4 +0,0 @@ -/* SWFObject v2.2 - is released under the MIT License -*/ -var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y0){for(var af=0;af0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad'}}aa.outerHTML='"+af+"";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab ["swfobject"] -rescue NoMethodError # I think this might fail in Rails 2.1.x - ActionView::Helpers::AssetTagHelper.register_javascript_include_default 'swfobject' -end diff --git a/backup.rails2.3/plugins/swf_fu/install.rb b/backup.rails2.3/plugins/swf_fu/install.rb deleted file mode 100644 index fda481b0..00000000 --- a/backup.rails2.3/plugins/swf_fu/install.rb +++ /dev/null @@ -1,24 +0,0 @@ -require "fileutils" - -# Some paths -src = File.dirname(__FILE__)+"/assets" -dest = File.dirname(__FILE__)+"/../../../public" - -filename = "#{dest}/javascripts/swfobject.js" -unless File.exist?(filename) - FileUtils.cp "#{src}/javascripts/swfobject.js", filename - puts "Copying 'swfobject.js'" -end - -unless File.exist?("#{dest}/swfs/") - FileUtils.mkdir "#{dest}/swfs/" - puts "Creating new 'swfs' directory for swf assets" -end - -filename = "#{dest}/swfs/expressInstall.swf" -unless File.exist?(filename) - FileUtils.cp "#{src}/swfs/expressInstall.swf", filename - puts "Copying 'expressInstall.swf', the default flash auto-installer." -end - -puts "Installation done." diff --git a/backup.rails2.3/plugins/swf_fu/lib/action_view/helpers/asset_tag_helper/swf_asset.rb b/backup.rails2.3/plugins/swf_fu/lib/action_view/helpers/asset_tag_helper/swf_asset.rb deleted file mode 100644 index 2fe6e5bd..00000000 --- a/backup.rails2.3/plugins/swf_fu/lib/action_view/helpers/asset_tag_helper/swf_asset.rb +++ /dev/null @@ -1,61 +0,0 @@ -module ActionView #:nodoc: - - # ActionView::Base.swf_default_options is a hash that - # will be used to specify defaults in priority to the standard - # defaults. - class Base - @@swf_default_options = {} - cattr_accessor :swf_default_options - end - - module Helpers # :nodoc: - module AssetTagHelper - - # Computes the path to an swf asset in the public 'swfs' directory. - # Full paths from the document root will be passed through. - # Used internally by +swf_tag+ to build the swf path. - # - # ==== Examples - # swf_path("example") # => /swfs/example.swf - # swf_path("example.swf") # => /swfs/example.swf - # swf_path("fonts/optima") # => /swfs/fonts/optima.swf - # swf_path("/fonts/optima") # => /fonts/optima.swf - # swf_path("http://www.example.com/game.swf") # => http://www.example.com/game.swf - # - # It takes into account the global setting +asset_host+, like any other asset: - # - # ActionController::Base.asset_host = "http://assets.example.com" - # image_path("logo.jpg") # => http://assets.example.com/images/logo.jpg - # swf_path("fonts/optima") # => http://assets.example.com/swfs/fonts/optima.swf - # - def swf_path(source) - if defined? SwfTag - SwfTag.new(self, @controller, source).public_path - else - compute_public_path(source, SwfAsset::DIRECTORY, SwfAsset::EXTENSION) - end - end - alias_method :path_to_swf, :swf_path # aliased to avoid conflicts with a swf_path named route - - private - module SwfAsset # :nodoc: - DIRECTORY = 'swfs'.freeze - EXTENSION = 'swf'.freeze - - def directory - DIRECTORY - end - - def extension - EXTENSION - end - end - - # AssetTag is available since 2.1.1 (http://github.com/rails/rails/commit/900fd6eca9dd97d2341e89bcb27d7a82d62965bf ) - class SwfTag < AssetTag # :nodoc: - include SwfAsset - end if defined? AssetTag - end - end -end - diff --git a/backup.rails2.3/plugins/swf_fu/lib/action_view/helpers/swf_fu_helper.rb b/backup.rails2.3/plugins/swf_fu/lib/action_view/helpers/swf_fu_helper.rb deleted file mode 100644 index 3c05807c..00000000 --- a/backup.rails2.3/plugins/swf_fu/lib/action_view/helpers/swf_fu_helper.rb +++ /dev/null @@ -1,197 +0,0 @@ -module ActionView #:nodoc: - module Helpers # :nodoc: - module SwfFuHelper - # Returns a set of tags that display a Flash object within an - # HTML page. - # - # Options: - # * :id - the DOM +id+ of the flash +object+ element that is used to contain the Flash object; defaults to the name of the swf in +source+ - # * :width, :height - the width & height of the Flash object. Defaults to "100%". These could also specified using :size - # * :size - the size of the Flash object, in the form "400x300". - # * :mode - Either :dynamic (default) or :static. Refer to SWFObject's doc[http://code.google.com/p/swfobject/wiki/documentation#Should_I_use_the_static_or_dynamic_publishing_method?] - # * :flashvars - a Hash of variables that are passed to the swf. Can also be a string like "foo=bar&hello=world" - # * :parameters - a Hash of configuration parameters for the swf. See Adobe's doc[http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_12701#optional] - # * :alt - HTML text that is displayed when the Flash player is not available. Defaults to a "Get Flash" image pointing to Adobe Flash's installation page. - # * :flash_version - the version of the Flash player that is required (e.g. "7" (default) or "8.1.0") - # * :auto_install - a swf file that will upgrade flash player if needed (defaults to "expressInstall" which was installed by swf_fu) - # * :javascript_class - specify a javascript class (e.g. "MyFlash") for your flash object. The initialize method will be called when the flash object is ready. - # * :initialize - arguments to pass to the initialization method of your javascript class. - # * :div_id - the DOM +id+ of the containing div itself. Defaults to "#{option[:id]}"_div - # - def swf_tag(source, options={}, &block) - Generator.new(source, options, self).generate(&block) - end - - # For compatibility with the older FlashObject. - # It modifies the given options before calling +swf_tag+. - # See FLASH_OBJECT.rdoc - def flashobject_tag_for_compatibility(source, options={}) - options = options.reverse_merge( - :auto_install => nil, - :parameters => {:scale => "noscale"}, - :variables => {:lzproxied => false}, - :flash_id => "flashcontent_#{rand(1_100)}", - :background_color => "#ffffff" - ) - { :variables => :flashvars, :flash_id => :id }.each{|from, to| options[to] ||= options.delete(from) } - options[:parameters][:bgcolor] ||= options.delete(:background_color) - swf_tag(source, options) - end - - alias_method :flashobject_tag, :flashobject_tag_for_compatibility unless defined? flashobject_tag - - private - DEFAULTS = { - :width => "100%", - :height => "100%", - :flash_version => 7, - :mode => :dynamic, - :auto_install => "expressInstall", - :alt => <<-"EOS".squeeze(" ").strip.freeze - - Get Adobe Flash player - - EOS - }.freeze - - class Generator # :nodoc: - VALID_MODES = [:static, :dynamic] - def initialize(source, options, view) - @view = view - @source = view.swf_path(source) - options = ActionView::Base.swf_default_options.merge(options) - options.each do |key, value| - options[key] = value.call(source) if value.respond_to?(:call) - end - [:html_options, :parameters, :flashvars].each do |k| - options[k] = convert_to_hash(options[k]).reverse_merge convert_to_hash(ActionView::Base.swf_default_options[k]) - end - options.reverse_merge!(DEFAULTS) - options[:id] ||= source.gsub(/^.*\//, '').gsub(/\.swf$/,'') - options[:id] = force_to_valid_id(options[:id]) - options[:div_id] ||= options[:id]+"_div" - options[:div_id] = force_to_valid_id(options[:div_id]) - options[:width], options[:height] = options[:size].scan(/^(\d*%?)x(\d*%?)$/).first if options[:size] - options[:auto_install] &&= @view.swf_path(options[:auto_install]) - options[:flashvars][:id] ||= options[:id] - @mode = options.delete(:mode) - @options = options - unless VALID_MODES.include? @mode - raise ArgumentError, "options[:mode] should be either #{VALID_MODES.join(' or ')}" - end - end - - def force_to_valid_id(id) - id = id.gsub /[^A-Za-z0-9\-_]/, "_" # HTML id can only contain these characters - id = "swf_" + id unless id =~ /^[A-Z]/i # HTML id must start with alpha - id - end - - def generate(&block) - if block_given? - @options[:alt] = @view.capture(&block) - if Rails::VERSION::STRING >= "3.0" - send(@mode) - elsif Rails::VERSION::STRING < "2.2" - @view.concat(send(@mode), block.binding) - else - @view.concat(send(@mode)) - end - else - send(@mode) - end - end - - private - CONCAT = ActiveSupport.const_defined?(:SafeBuffer) ? :safe_concat : :concat - def convert_to_hash(s) - case s - when Hash - s - when nil - {} - when String - s.split("&").inject({}) do |h, kvp| - key, value = kvp.split("=") - h[key.to_sym] = CGI::unescape(value) - h - end - else - raise ArgumentError, "#{s} should be a Hash, a String or nil" - end - end - - def convert_to_string(h) - h.map do |key_value| - key_value.map{|val| CGI::escape(val.to_s)}.join("=") - end.join("&") - end - - def static - param_list = @options[:parameters].map{|k,v| %() }.join("\n") - param_list += %(\n) unless @options[:flashvars].empty? - html_options = @options[:html_options].map{|k,v| %(#{k}="#{v}")}.join(" ") - r = @view.javascript_tag( - %(swfobject.registerObject("#{@options[:id]}_container", "#{@options[:flash_version]}", #{@options[:auto_install].to_json});) - ) - r.send CONCAT, <<-"EOS".strip -
- - #{param_list} - - - #{param_list} - - #{@options[:alt]} - - - -
- EOS - r << @view.javascript_tag(extend_js) if @options[:javascript_class] - r.send CONCAT, library_check - r - end - - def dynamic - @options[:html_options] = @options[:html_options].merge(:id => @options[:id]) - @options[:parameters] = @options[:parameters].dup # don't modify the original parameters - args = (([@source] + @options.values_at(:div_id,:width,:height,:flash_version)).map(&:to_s) + - @options.values_at(:auto_install,:flashvars,:parameters,:html_options) - ).map(&:to_json).join(",") - preambule = @options[:switch_off_auto_hide_show] ? "swfobject.switchOffAutoHideShow();" : "" - r = @view.javascript_tag(preambule + "swfobject.embedSWF(#{args})") - r.send CONCAT, <<-"EOS".strip -
- #{@options[:alt]} -
- EOS - r << @view.javascript_tag("swfobject.addDomLoadEvent(function(){#{extend_js}})") if @options[:javascript_class] - r.send CONCAT, library_check - r - end - - def extend_js - arglist = case - when @options[:initialize].instance_of?(Array) - @options[:initialize].map(&:to_json).join(",") - when @options.has_key?(:initialize) - @options[:initialize].to_json - else - "" - end - "Object.extend($('#{@options[:id]}'), #{@options[:javascript_class]}.prototype).initialize(#{arglist})" - end - - def library_check - return "" unless 'development' == ENV['RAILS_ENV'] - @view.javascript_tag(<<-"EOS") - if (typeof swfobject == 'undefined') { - document.getElementById('#{@options[:div_id]}').innerHTML = 'Warning: SWFObject.js was not loaded properly. Make sure you <%= javascript_include_tag :defaults %> or <%= javascript_include_tag :swfobject %>'; - } - EOS - end - end #class Generator - end - end -end diff --git a/backup.rails2.3/plugins/swf_fu/test/results.rb b/backup.rails2.3/plugins/swf_fu/test/results.rb deleted file mode 100644 index a7306b0d..00000000 --- a/backup.rails2.3/plugins/swf_fu/test/results.rb +++ /dev/null @@ -1,42 +0,0 @@ -DYNAMIC_RESULT = <<'EOS' -
- -Get Adobe Flash player - -
-EOS - -STATIC_RESULT = <<'EOS' -
- - - - - - - - - -Get Adobe Flash player - - - - -
-EOS \ No newline at end of file diff --git a/backup.rails2.3/plugins/swf_fu/test/swf_fu_test.rb b/backup.rails2.3/plugins/swf_fu/test/swf_fu_test.rb deleted file mode 100644 index 64a2a8bf..00000000 --- a/backup.rails2.3/plugins/swf_fu/test/swf_fu_test.rb +++ /dev/null @@ -1,159 +0,0 @@ -require File.expand_path(File.dirname(__FILE__)+'/test_helper') -require File.expand_path(File.dirname(__FILE__)+'/results') - -class SwfFuTest < ActionView::TestCase - def assert_same_stripped(expect, test) - expect, test = [expect, test].map{|s| s.split("\n").map(&:strip)} - same = expect & test - delta_expect, delta_test = [expect, test].map{|a| a-same} - STDOUT << "\n\n---- Actual result: ----\n" << test.join("\n") << "\n---------\n" unless delta_expect == delta_test - assert_equal delta_expect, delta_test - end - - context "swf_path" do - context "with no special asset host" do - should "deduce the extension" do - assert_equal swf_path("example.swf"), swf_path("example") - assert_starts_with "/swfs/example.swf", swf_path("example.swf") - end - - should "accept relative paths" do - assert_starts_with "/swfs/whatever/example.swf", swf_path("whatever/example.swf") - end - - should "leave full paths alone" do - ["/full/path.swf", "http://www.example.com/whatever.swf"].each do |p| - assert_starts_with p, swf_path(p) - end - end - end - - context "with custom asset host" do - HOST = "http://assets.example.com" - setup do - ActionController::Base.asset_host = HOST - end - - teardown do - ActionController::Base.asset_host = nil - end - - should "take it into account" do - assert_equal "#{HOST}/swfs/whatever.swf", swf_path("whatever") - end - end - end - - context "swf_tag" do - COMPLEX_OPTIONS = { :width => "456", :height => 123, - :flashvars => {:myVar => "value 1 > 2"}.freeze, - :javascript_class => "SomeClass", - :initialize => {:be => "good"}.freeze, - :parameters => {:play => true}.freeze - }.freeze - - should "understand size" do - assert_equal swf_tag("hello", :size => "123x456"), - swf_tag("hello", :width => 123, :height => "456") - end - - should "only accept valid modes" do - assert_raise(ArgumentError) { swf_tag("xyz", :mode => :xyz) } - end - - context "with custom defaults" do - setup do - test = {:flashvars=> {:xyz => "abc", :hello => "world"}.freeze, :mode => :static, :size => "400x300"}.freeze - @expect = swf_tag("test", test) - @expect_with_hello = swf_tag("test", :flashvars => {:xyz => "abc", :hello => "my friend"}, :mode => :static, :size => "400x300") - ActionView::Base.swf_default_options = test - end - - should "respect them" do - assert_equal @expect, swf_tag("test") - end - - should "merge suboptions" do - assert_equal @expect_with_hello, swf_tag("test", :flashvars => {:hello => "my friend"}.freeze) - end - - teardown { ActionView::Base.swf_default_options = {} } - end - - context "with proc options" do - should "call them" do - expect = swf_tag("test", :id => "generated_id_for_test") - assert_equal expect, swf_tag("test", :id => Proc.new{|arg| "generated_id_for_#{arg}"}) - end - - should "call global default's everytime" do - expect1 = swf_tag("test", :id => "call_number_1") - expect2 = swf_tag("test", :id => "call_number_2") - cnt = 0 - ActionView::Base.swf_default_options = { :id => Proc.new{ "call_number_#{cnt+=1}" }} - assert_equal expect1, swf_tag("test") - assert_equal expect2, swf_tag("test") - end - end - - context "with static mode" do - setup { ActionView::Base.swf_default_options = {:mode => :static} } - - should "deal with string flashvars" do - assert_equal swf_tag("hello", :flashvars => "xyz=abc", :mode => :static), - swf_tag("hello", :flashvars => {:xyz => "abc"}, :mode => :static) - end - - should "produce the expected code" do - assert_same_stripped STATIC_RESULT, swf_tag("mySwf", COMPLEX_OPTIONS.merge(:html_options => {:class => "lots"}.freeze).freeze) - end - - teardown { ActionView::Base.swf_default_options = {} } - end - - context "with dynamic mode" do - should "produce the expected code" do - assert_same_stripped DYNAMIC_RESULT, swf_tag("mySwf", COMPLEX_OPTIONS) - end - - end - - should "enforce HTML id validity" do - div_result = '
' - assert_match /#{div_result}/, swf_tag("123-456_ok$!+X") - obj_result = '"id":"swf_123-456_ok___X"' - assert_match /#{obj_result}/, swf_tag("123-456_ok$!+X") - end - - should "treat initialize arrays as list of parameters" do - assert_match 'initialize("hello","world")', swf_tag("mySwf", :initialize => ["hello", "world"], :javascript_class => "SomeClass") - end - - if ActiveSupport.const_defined?(:SafeBuffer) - should "be html safe" do - assert swf_tag("test").html_safe? - end - end - end - - context "flashobject_tag" do - should "be the same as swf_tag with different defaults" do - assert_same_stripped swf_tag("mySwf", - :auto_install => nil, - :parameters => {:scale => "noscale", :bgcolor => "#ffffff"}, - :flashvars => {:lzproxied => false}, - :id => "myFlash" - ), flashobject_tag("mySwf", :flash_id => "myFlash") - end - - should "be the same with custom settings" do - assert_same_stripped swf_tag("mySwf", - :auto_install => nil, - :parameters => {:scale => "noborder", :bgcolor => "#ffffff"}, - :flashvars => {:answer_is => 42}, - :id => "myFlash" - ), flashobject_tag("mySwf", :flash_id => "myFlash", :parameters => {:scale => "noborder"}, :variables => {:answer_is => 42}) - end - end -end - diff --git a/backup.rails2.3/plugins/swf_fu/test/test_helper.rb b/backup.rails2.3/plugins/swf_fu/test/test_helper.rb deleted file mode 100644 index 58d113f8..00000000 --- a/backup.rails2.3/plugins/swf_fu/test/test_helper.rb +++ /dev/null @@ -1,20 +0,0 @@ -require 'test/unit' -require 'rubygems' -gem 'activesupport', '~> 2.3' -require 'active_support' -gem 'activerecord', '~> 2.3' -require 'active_record' -gem 'actionpack', '~> 2.3' -require 'active_support' -require 'action_view' -require 'action_controller' - -#require File.dirname(__FILE__)+'/../../../../config/environment.rb' -require 'action_view/test_case' -require "action_controller/test_process" -require 'shoulda' -require File.dirname(__FILE__) + '/../init' - -def assert_starts_with(start, what) - assert what.starts_with?(start), "#{what} does not start with #{start}" -end diff --git a/backup.rails2.3/plugins/swf_fu/uninstall.rb b/backup.rails2.3/plugins/swf_fu/uninstall.rb deleted file mode 100644 index bc3c1b57..00000000 --- a/backup.rails2.3/plugins/swf_fu/uninstall.rb +++ /dev/null @@ -1,6 +0,0 @@ -require "fileutils" - -dest = File.dirname(__FILE__) + "/../../../public" -FileUtils.rm "#{dest}/javascripts/swfobject.js" rescue puts "Warning: swfobject.js could not be deleted" -FileUtils.rm "#{dest}/swfs/expressInstall.swf" rescue puts "Warning: expressInstall.swf could not be deleted" -Dir.rmdir "#{dest}/swfs/" rescue "don't worry if directory is not empty" \ No newline at end of file diff --git a/backup.rails2.3/plugins/translate/MIT-LICENSE b/backup.rails2.3/plugins/translate/MIT-LICENSE deleted file mode 100644 index 9376605b..00000000 --- a/backup.rails2.3/plugins/translate/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 [name of plugin creator] - -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/backup.rails2.3/plugins/translate/README b/backup.rails2.3/plugins/translate/README deleted file mode 100644 index e2732dc9..00000000 --- a/backup.rails2.3/plugins/translate/README +++ /dev/null @@ -1,63 +0,0 @@ -Translate -========= - -This plugin provides a web interface for translating Rails I18n texts (requires Rails 2.2 or higher) from one locale to another. The plugin has been tested only with the simple I18n backend that ships with Rails. I18n texts are read from and written to YAML files under config/locales. - -To translate to a new locale you need to add a YAML file for that locale that contains the locale as the top key and at least one translation. - -Please note that there are certain I18n keys that map to Array objects rather than strings and those are currently not dealt with by the translation UI. This means that Rails built in keys such as date.day_names need to be translated manually directly in the YAML file. - -To get the translation UI to write the YAML files in UTF8 you need to install the ya2yaml gem. - -The translation UI finds all I18n keys by extracting them from I18n lookups in your application source code. In addition it adds all :en and default locale keys from the I18n backend. - -- Updated: Each string in the UI now has an "Auto Translate" link which will send the original text to Google Translate and will input the returned translation into the form field for further clean up and review prior to saving. - - -Rake Tasks -========= - -In addition to the web UI this plugin adds the following rake tasks: - -translate:untranslated -translate:missing -translate:remove_obsolete_keys -translate:merge_keys -translate:google -translate:changed - -The missing task shows you any I18n keys in your code that do not have translations in the YAML file for your default locale, i.e. config/locales/sv.yml. - -The merge_keys task is supposed to be used in conjunction with Sven Fuch's Rails I18n TextMate bundle (http://github.com/svenfuchs/rails-i18n/tree/master). Texts and keys extracted with the TextMate bundle end up in the temporary file log/translations.yml. When you run the merge_keys rake task the keys are moved over to the corresponding I18n locale file, i.e. config/locales/sv.yml. The merge_keys task also checks for overwrites of existing keys by warning you that one of your extracted keys already exists with a different translation. - -The google task is used for auto translating from one locale to another using Google Translate. - -The changed rake task can show you between one YAML file to another which keys have had their texts changed. - -Installation -========= -Obtain the source with: - -./script/plugin install git://github.com/newsdesk/translate.git - -To mount the plugin, add the following to your config/routes.rb file: - -Translate::Routes.translation_ui(map) if RAILS_ENV != "production" - -Now visit /translate in your web browser to start translating. - -Dependencies -========= - -- Rails 2.2 or higher -- The ya2yaml gem if you want your YAML files written in UTF8 encoding. - -Authors -========= - -- Peter Marklund (programming) -- Joakim Westerlund (web design) - -Many thanks to http://newsdesk.se for sponsoring the development of this plugin. - -Copyright (c) 2009 Peter Marklund, released under the MIT license diff --git a/backup.rails2.3/plugins/translate/Rakefile b/backup.rails2.3/plugins/translate/Rakefile deleted file mode 100644 index 7e1954b7..00000000 --- a/backup.rails2.3/plugins/translate/Rakefile +++ /dev/null @@ -1,11 +0,0 @@ -require 'rake' -require 'spec/rake/spectask' - -desc 'Default: run specs.' -task :default => :spec - -desc 'Run the specs' -Spec::Rake::SpecTask.new(:spec) do |t| - t.spec_opts = ['--colour --format progress --loadby mtime --reverse'] - t.spec_files = FileList['spec/**/*_spec.rb'] -end diff --git a/backup.rails2.3/plugins/translate/init.rb b/backup.rails2.3/plugins/translate/init.rb deleted file mode 100644 index 18707f83..00000000 --- a/backup.rails2.3/plugins/translate/init.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'translate' - -# TODO: Use new method available_locales once Rails is upgraded, see: -# http://github.com/svenfuchs/i18n/commit/411f8fe7c8f3f89e9b6b921fa62ed66cb92f3af4 -def I18n.valid_locales - I18n.backend.send(:init_translations) unless I18n.backend.initialized? - backend.send(:translations).keys.reject { |locale| locale == :root } -end diff --git a/backup.rails2.3/plugins/translate/lib/translate.rb b/backup.rails2.3/plugins/translate/lib/translate.rb deleted file mode 100644 index 39629bf4..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate.rb +++ /dev/null @@ -1,8 +0,0 @@ -module Translate -end - -require File.join(File.dirname(__FILE__), "translate_controller") -require File.join(File.dirname(__FILE__), "translate_helper") -Dir[File.join(File.dirname(__FILE__), "translate", "*.rb")].each do |file| - require file -end diff --git a/backup.rails2.3/plugins/translate/lib/translate/file.rb b/backup.rails2.3/plugins/translate/lib/translate/file.rb deleted file mode 100644 index c8ae93b0..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate/file.rb +++ /dev/null @@ -1,35 +0,0 @@ -require 'fileutils' - -class Translate::File - attr_accessor :path - - def initialize(path) - self.path = path - end - - def write(keys) - FileUtils.mkdir_p File.dirname(path) - File.open(path, "w") do |file| - file.puts keys_to_yaml(Translate::File.deep_stringify_keys(keys)) - end - end - - def read - File.exists?(path) ? YAML::load(IO.read(path)) : {} - end - - # Stringifying keys for prettier YAML - def self.deep_stringify_keys(hash) - hash.inject({}) { |result, (key, value)| - value = deep_stringify_keys(value) if value.is_a? Hash - result[(key.to_s rescue key) || key] = value - result - } - end - - private - def keys_to_yaml(keys) - # Using ya2yaml, if available, for UTF8 support - keys.respond_to?(:ya2yaml) ? keys.ya2yaml(:escape_as_utf8 => true) : keys.to_yaml - end -end diff --git a/backup.rails2.3/plugins/translate/lib/translate/keys.rb b/backup.rails2.3/plugins/translate/lib/translate/keys.rb deleted file mode 100644 index 3bee3c41..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate/keys.rb +++ /dev/null @@ -1,152 +0,0 @@ -require 'pathname' - -class Translate::Keys - # Allows keys extracted from lookups in files to be cached - def self.files - @@files ||= Translate::Keys.new.files - end - - # Allows flushing of the files cache - def self.files=(files) - @@files = files - end - - def files - @files ||= extract_files - end - alias_method :to_hash, :files - - def keys - files.keys - end - alias_method :to_a, :keys - - def i18n_keys(locale) - I18n.backend.send(:init_translations) unless I18n.backend.initialized? - Translate::Keys.to_shallow_hash(I18n.backend.send(:translations)[locale.to_sym]).keys.sort - end - - def untranslated_keys - Translate::Keys.translated_locales.inject({}) do |missing, locale| - missing[locale] = i18n_keys(I18n.default_locale).map do |key| - I18n.backend.send(:lookup, locale, key).nil? ? key : nil - end.compact - missing - end - end - - def missing_keys - locale = I18n.default_locale; yaml_keys = {} - yaml_keys = Translate::Storage.file_paths(locale).inject({}) do |keys, path| - keys = keys.deep_merge(Translate::File.new(path).read[locale.to_s]) - end - files.reject { |key, file| self.class.contains_key?(yaml_keys, key) } - end - - def self.translated_locales - I18n.available_locales.reject { |locale| [:root, I18n.default_locale.to_sym].include?(locale) } - end - - # Checks if a nested hash contains the keys in dot separated I18n key. - # - # Example: - # - # hash = { - # :foo => { - # :bar => { - # :baz => 1 - # } - # } - # } - # - # contains_key?("foo", key) # => true - # contains_key?("foo.bar", key) # => true - # contains_key?("foo.bar.baz", key) # => true - # contains_key?("foo.bar.baz.bla", key) # => false - # - def self.contains_key?(hash, key) - keys = key.to_s.split(".") - return false if keys.empty? - !keys.inject(HashWithIndifferentAccess.new(hash)) do |memo, key| - memo.is_a?(Hash) ? memo.try(:[], key) : nil - end.nil? - end - - # Convert something like: - # - # { - # :pressrelease => { - # :label => { - # :one => "Pressmeddelande" - # } - # } - # } - # - # to: - # - # {'pressrelease.label.one' => "Pressmeddelande"} - # - def self.to_shallow_hash(hash) - hash.inject({}) do |shallow_hash, (key, value)| - if value.is_a?(Hash) - to_shallow_hash(value).each do |sub_key, sub_value| - shallow_hash[[key, sub_key].join(".")] = sub_value - end - else - shallow_hash[key.to_s] = value - end - shallow_hash - end - end - - # Convert something like: - # - # {'pressrelease.label.one' => "Pressmeddelande"} - # - # to: - # - # { - # :pressrelease => { - # :label => { - # :one => "Pressmeddelande" - # } - # } - # } - def self.to_deep_hash(hash) - hash.inject({}) do |deep_hash, (key, value)| - keys = key.to_s.split('.').reverse - leaf_key = keys.shift - key_hash = keys.inject({leaf_key.to_sym => value}) { |hash, key| {key.to_sym => hash} } - deep_merge!(deep_hash, key_hash) - deep_hash - end - end - - # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809 - def self.deep_merge!(hash1, hash2) - merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } - hash1.merge!(hash2, &merger) - end - - private - - def extract_files - files_to_scan.inject(HashWithIndifferentAccess.new) do |files, file| - IO.read(file).scan(i18n_lookup_pattern).flatten.map(&:to_sym).each do |key| - files[key] ||= [] - path = Pathname.new(File.expand_path(file)).relative_path_from(Pathname.new(Rails.root)).to_s - files[key] << path if !files[key].include?(path) - end - files - end - end - - def i18n_lookup_pattern - /\b(?:I18n\.t|I18n\.translate|t)(?:\s|\():?'([a-z0-9_]+.[a-z0-9_.]+)'\)?/ - end - - def files_to_scan - Dir.glob(File.join(Translate::Storage.root_dir, "{app,config,lib}", "**","*.{rb,erb,rhtml}")) + - Dir.glob(File.join(Translate::Storage.root_dir, "public", "javascripts", "**","*.js")) - end -end diff --git a/backup.rails2.3/plugins/translate/lib/translate/log.rb b/backup.rails2.3/plugins/translate/lib/translate/log.rb deleted file mode 100644 index 9b5b3148..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate/log.rb +++ /dev/null @@ -1,35 +0,0 @@ -class Translate::Log - attr_accessor :from_locale, :to_locale, :keys - - def initialize(from_locale, to_locale, keys) - self.from_locale = from_locale - self.to_locale = to_locale - self.keys = keys - end - - def write_to_file - current_texts = File.exists?(file_path) ? file.read : {} - current_texts.merge!(from_texts) - file.write(current_texts) - end - - def read - file.read - end - - private - def file - @file ||= Translate::File.new(file_path) - end - - def from_texts - Translate::File.deep_stringify_keys(Translate::Keys.to_deep_hash(keys.inject({}) do |hash, key| - hash[key] = I18n.backend.send(:lookup, from_locale, key) - hash - end)) - end - - def file_path - File.join(Rails.root, "config", "locales", "log", "from_#{from_locale}_to_#{to_locale}.yml") - end -end diff --git a/backup.rails2.3/plugins/translate/lib/translate/routes.rb b/backup.rails2.3/plugins/translate/lib/translate/routes.rb deleted file mode 100644 index 8d02c869..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate/routes.rb +++ /dev/null @@ -1,11 +0,0 @@ -module Translate - class Routes - def self.translation_ui(map) - map.with_options(:controller => 'translate') do |t| - t.translate_list 'translate' - t.translate 'translate/translate', :action => 'translate' - t.translate_reload 'translate/reload', :action => 'reload' - end - end - end -end diff --git a/backup.rails2.3/plugins/translate/lib/translate/storage.rb b/backup.rails2.3/plugins/translate/lib/translate/storage.rb deleted file mode 100644 index 2b9a3858..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate/storage.rb +++ /dev/null @@ -1,28 +0,0 @@ -class Translate::Storage - attr_accessor :locale - - def initialize(locale) - self.locale = locale.to_sym - end - - def write_to_file - Translate::File.new(file_path).write(keys) - end - - def self.file_paths(locale) - Dir.glob(File.join(root_dir, "config", "locales", "**","#{locale}.yml")) - end - - def self.root_dir - Rails.root - end - - private - def keys - {locale => I18n.backend.send(:translations)[locale]} - end - - def file_path - File.join(Translate::Storage.root_dir, "config", "locales", "#{locale}.yml") - end -end diff --git a/backup.rails2.3/plugins/translate/lib/translate_controller.rb b/backup.rails2.3/plugins/translate/lib/translate_controller.rb deleted file mode 100644 index d06e171e..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate_controller.rb +++ /dev/null @@ -1,165 +0,0 @@ -class TranslateController < ActionController::Base - # It seems users with active_record_store may get a "no :secret given" error if we don't disable csrf protection, - skip_before_filter :verify_authenticity_token - - prepend_view_path(File.join(File.dirname(__FILE__), "..", "views")) - layout 'translate' - - before_filter :init_translations - before_filter :set_locale - - def index - initialize_keys - filter_by_key_pattern - filter_by_text_pattern - filter_by_translated_or_changed - sort_keys - paginate_keys - @total_entries = @keys.size - end - - def translate - I18n.backend.store_translations(@to_locale, Translate::Keys.to_deep_hash(params[:key])) - Translate::Storage.new(@to_locale).write_to_file - Translate::Log.new(@from_locale, @to_locale, params[:key].keys).write_to_file - force_init_translations # Force reload from YAML file - flash[:notice] = "Translations stored" - redirect_to params.slice(:filter, :sort_by, :key_type, :key_pattern, :text_type, :text_pattern).merge({:action => :index}) - end - - def reload - Translate::Keys.files = nil - redirect_to :action => 'index' - end - - private - def initialize_keys - @files = Translate::Keys.files - @keys = (@files.keys.map(&:to_s) + Translate::Keys.new.i18n_keys(@from_locale)).uniq - @keys.reject! do |key| - from_text = lookup(@from_locale, key) - # When translating from one language to another, make sure there is a text to translate from. - # Always exclude non string translation objects as we don't support editing them in the UI. - (@from_locale != @to_locale && !from_text.present?) || (from_text.present? && !from_text.is_a?(String)) - end - end - - def lookup(locale, key) - I18n.backend.send(:lookup, locale, key) - end - helper_method :lookup - - def filter_by_translated_or_changed - params[:filter] ||= 'all' - return if params[:filter] == 'all' - @keys.reject! do |key| - case params[:filter] - when 'untranslated' - lookup(@to_locale, key).present? - when 'translated' - lookup(@to_locale, key).blank? - when 'changed' - old_from_text(key).blank? || lookup(@from_locale, key) == old_from_text(key) - else - raise "Unknown filter '#{params[:filter]}'" - end - end - end - - def filter_by_key_pattern - return if params[:key_pattern].blank? - @keys.reject! do |key| - case params[:key_type] - when "starts_with" - !key.starts_with?(params[:key_pattern]) - when "contains" - key.index(params[:key_pattern]).nil? - else - raise "Unknown key_type '#{params[:key_type]}'" - end - end - end - - def filter_by_text_pattern - return if params[:text_pattern].blank? - @keys.reject! do |key| - case params[:text_type] - when 'contains' - !lookup(@from_locale, key).present? || !lookup(@from_locale, key).to_s.downcase.index(params[:text_pattern].downcase) - when 'equals' - !lookup(@from_locale, key).present? || lookup(@from_locale, key).to_s.downcase != params[:text_pattern].downcase - else - raise "Unknown text_type '#{params[:text_type]}'" - end - end - end - - def sort_keys - params[:sort_by] ||= "key" - case params[:sort_by] - when "key" - @keys.sort! - when "text" - @keys.sort! do |key1, key2| - if lookup(@from_locale, key1).present? && lookup(@from_locale, key2).present? - lookup(@from_locale, key1).to_s.downcase <=> lookup(@from_locale, key2).to_s.downcase - elsif lookup(@from_locale, key1).present? - -1 - else - 1 - end - end - else - raise "Unknown sort_by '#{params[:sort_by]}'" - end - end - - def paginate_keys - params[:page] ||= 1 - @paginated_keys = @keys[offset, per_page] - end - - def offset - (params[:page].to_i - 1) * per_page - end - - def per_page - 50 - end - helper_method :per_page - - def init_translations - I18n.backend.send(:init_translations) unless I18n.backend.initialized? - end - - def force_init_translations - I18n.backend.send(:init_translations) - end - - def default_locale - I18n.default_locale - end - - def set_locale - session[:from_locale] ||= default_locale - session[:to_locale] ||= :en - session[:from_locale] = params[:from_locale] if params[:from_locale].present? - session[:to_locale] = params[:to_locale] if params[:to_locale].present? - @from_locale = session[:from_locale].to_sym - @to_locale = session[:to_locale].to_sym - end - - def old_from_text(key) - return @old_from_text[key] if @old_from_text && @old_from_text[key] - @old_from_text = {} - text = key.split(".").inject(log_hash) do |hash, k| - hash ? hash[k] : nil - end - @old_from_text[key] = text - end - helper_method :old_from_text - - def log_hash - @log_hash ||= Translate::Log.new(@from_locale, @to_locale, {}).read - end -end diff --git a/backup.rails2.3/plugins/translate/lib/translate_helper.rb b/backup.rails2.3/plugins/translate/lib/translate_helper.rb deleted file mode 100644 index cb4c400f..00000000 --- a/backup.rails2.3/plugins/translate/lib/translate_helper.rb +++ /dev/null @@ -1,45 +0,0 @@ -module TranslateHelper - def simple_filter(labels, param_name = 'filter', selected_value = nil) - selected_value ||= params[param_name] - filter = [] - labels.each do |item| - if item.is_a?(Array) - type, label = item - else - type = label = item - end - if type.to_s == selected_value.to_s - filter << "#{label}" - else - link_params = params.merge({param_name.to_s => type}) - link_params.merge!({"page" => nil}) if param_name.to_s != "page" - filter << link_to(label, link_params) - end - end - filter.join(" | ") - end - - def n_lines(text, line_size) - n_lines = 1 - if text.present? - n_lines = text.split("\n").size - if n_lines == 1 && text.length > line_size - n_lines = text.length / line_size + 1 - end - end - n_lines - end - - def translate_javascript_includes - sources = [] - if File.exists?(File.join(Rails.root, "public", "javascripts", "prototype.js")) - sources << "/javascripts/prototype.js" - else - sources << "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js" - end - sources << "http://www.google.com/jsapi" - sources.map do |src| - %Q{} - end.join("\n") - end -end diff --git a/backup.rails2.3/plugins/translate/spec/controllers/translate_controller_spec.rb b/backup.rails2.3/plugins/translate/spec/controllers/translate_controller_spec.rb deleted file mode 100644 index e384811b..00000000 --- a/backup.rails2.3/plugins/translate/spec/controllers/translate_controller_spec.rb +++ /dev/null @@ -1,129 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') - -describe TranslateController do - describe "index" do - before(:each) do - controller.stub!(:per_page).and_return(1) - I18n.backend.stub!(:translations).and_return(i18n_translations) - I18n.backend.instance_eval { @initialized = true } - keys = mock(:keys) - keys.stub!(:i18n_keys).and_return(['vendor.foobar']) - Translate::Keys.should_receive(:new).and_return(keys) - Translate::Keys.should_receive(:files).and_return(files) - I18n.stub!(:valid_locales).and_return([:en, :sv]) - I18n.stub!(:default_locale).and_return(:sv) - end - - it "shows sorted paginated keys from the translate from locale and extracted keys by default" do - get_page :index - assigns(:from_locale).should == :sv - assigns(:to_locale).should == :en - assigns(:files).should == files - assigns(:keys).sort.should == ['articles.new.page_title', 'home.page_title', 'vendor.foobar'] - assigns(:paginated_keys).should == ['articles.new.page_title'] - end - - it "can be paginated with the page param" do - get_page :index, :page => 2 - assigns(:files).should == files - assigns(:paginated_keys).should == ['home.page_title'] - end - - it "accepts a key_pattern param with key_type=starts_with" do - get_page :index, :key_pattern => 'articles', :key_type => 'starts_with' - assigns(:files).should == files - assigns(:paginated_keys).should == ['articles.new.page_title'] - assigns(:total_entries).should == 1 - end - - it "accepts a key_pattern param with key_type=contains" do - get_page :index, :key_pattern => 'page_', :key_type => 'contains' - assigns(:files).should == files - assigns(:total_entries).should == 2 - assigns(:paginated_keys).should == ['articles.new.page_title'] - end - - it "accepts a filter=untranslated param" do - get_page :index, :filter => 'untranslated' - assigns(:total_entries).should == 2 - assigns(:paginated_keys).should == ['articles.new.page_title'] - end - - it "accepts a filter=translated param" do - get_page :index, :filter => 'translated' - assigns(:total_entries).should == 1 - assigns(:paginated_keys).should == ['vendor.foobar'] - end - - it "accepts a filter=changed param" do - log = mock(:log) - old_translations = {:home => {:page_title => "Skapar ny artikel"}} - log.should_receive(:read).and_return(Translate::File.deep_stringify_keys(old_translations)) - Translate::Log.should_receive(:new).with(:sv, :en, {}).and_return(log) - get_page :index, :filter => 'changed' - assigns(:total_entries).should == 1 - assigns(:keys).should == ["home.page_title"] - end - - def i18n_translations - HashWithIndifferentAccess.new({ - :en => { - :vendor => { - :foobar => "Foo Baar" - } - }, - :sv => { - :articles => { - :new => { - :page_title => "Skapa ny artikel" - } - }, - :home => { - :page_title => "Välkommen till I18n" - }, - :vendor => { - :foobar => "Fobar" - } - } - }) - end - - def files - HashWithIndifferentAccess.new({ - :'home.page_title' => ["app/views/home/index.rhtml"], - :'general.back' => ["app/views/articles/new.rhtml", "app/views/categories/new.rhtml"], - :'articles.new.page_title' => ["app/views/articles/new.rhtml"] - }) - end - end - - describe "translate" do - it "should store translations to I18n backend and then write them to a YAML file" do - session[:from_locale] = :sv - session[:to_locale] = :en - translations = { - :articles => { - :new => { - :title => "New Article" - } - }, - :category => "Category" - } - key_param = {'articles.new.title' => "New Article", "category" => "Category"} - I18n.backend.should_receive(:store_translations).with(:en, translations) - storage = mock(:storage) - storage.should_receive(:write_to_file) - Translate::Storage.should_receive(:new).with(:en).and_return(storage) - log = mock(:log) - log.should_receive(:write_to_file) - Translate::Log.should_receive(:new).with(:sv, :en, key_param.keys).and_return(log) - post :translate, "key" => key_param - response.should be_redirect - end - end - - def get_page(*args) - get(*args) - response.should be_success - end -end diff --git a/backup.rails2.3/plugins/translate/spec/file_spec.rb b/backup.rails2.3/plugins/translate/spec/file_spec.rb deleted file mode 100644 index 5f94f5a9..00000000 --- a/backup.rails2.3/plugins/translate/spec/file_spec.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'fileutils' -require File.dirname(__FILE__) + '/spec_helper' - -describe Translate::File do - describe "write" do - before(:each) do - @file = Translate::File.new(file_path) - end - - after(:each) do - FileUtils.rm(file_path) - end - - it "writes all I18n messages for a locale to YAML file" do - @file.write(translations) - @file.read.should == Translate::File.deep_stringify_keys(translations) - end - - def translations - { - :en => { - :article => { - :title => "One Article" - }, - :category => "Category" - } - } - end - end - - describe "deep_stringify_keys" do - it "should convert all keys in a hash to strings" do - Translate::File.deep_stringify_keys({ - :en => { - :article => { - :title => "One Article" - }, - :category => "Category" - } - }).should == { - "en" => { - "article" => { - "title" => "One Article" - }, - "category" => "Category" - } - } - end - end - - def file_path - File.join(File.dirname(__FILE__), "files", "en.yml") - end -end diff --git a/backup.rails2.3/plugins/translate/spec/files/translate/app/models/article.rb b/backup.rails2.3/plugins/translate/spec/files/translate/app/models/article.rb deleted file mode 100644 index d151e316..00000000 --- a/backup.rails2.3/plugins/translate/spec/files/translate/app/models/article.rb +++ /dev/null @@ -1,12 +0,0 @@ -class Article < ActiveRecord::Base - def validate - # t('li') - errors.add_to_base([t(:'article.key1') + "#{t('article.key2')}"]) - I18n.t 'article.key3' - I18n.t 'article.key3' - I18n.t :'article.key4' - I18n.translate :'article.key5' - 'bla bla t' + "blubba bla" + ' foobar' - 'bla bla t ' + "blubba bla" + ' foobar' - end -end diff --git a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.erb b/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.erb deleted file mode 100644 index 2146f874..00000000 --- a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.erb +++ /dev/null @@ -1 +0,0 @@ -<%= t(:'category_erb.key1') %> diff --git a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.html b/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.html deleted file mode 100644 index 0947d174..00000000 --- a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.html +++ /dev/null @@ -1 +0,0 @@ -t(:'category_html.key1') diff --git a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.html.erb b/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.html.erb deleted file mode 100644 index a226ccff..00000000 --- a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= t(:'category_html_erb.key1') %> diff --git a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.rhtml b/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.rhtml deleted file mode 100644 index 235e5173..00000000 --- a/backup.rails2.3/plugins/translate/spec/files/translate/app/views/category.rhtml +++ /dev/null @@ -1,5 +0,0 @@ - - -<%= t(:'category_rhtml.key1') %> diff --git a/backup.rails2.3/plugins/translate/spec/files/translate/public/javascripts/application.js b/backup.rails2.3/plugins/translate/spec/files/translate/public/javascripts/application.js deleted file mode 100644 index a673ca02..00000000 --- a/backup.rails2.3/plugins/translate/spec/files/translate/public/javascripts/application.js +++ /dev/null @@ -1 +0,0 @@ -I18n.t('js.alert') \ No newline at end of file diff --git a/backup.rails2.3/plugins/translate/spec/keys_spec.rb b/backup.rails2.3/plugins/translate/spec/keys_spec.rb deleted file mode 100644 index 3b0bd629..00000000 --- a/backup.rails2.3/plugins/translate/spec/keys_spec.rb +++ /dev/null @@ -1,179 +0,0 @@ -require File.dirname(__FILE__) + '/spec_helper' -require 'fileutils' - -describe Translate::Keys do - before(:each) do - I18n.stub!(:default_locale).and_return(:en) - @keys = Translate::Keys.new - Translate::Storage.stub!(:root_dir).and_return(i18n_files_dir) - end - - describe "to_a" do - it "extracts keys from I18n lookups in .rb, .html.erb, and .rhtml files" do - @keys.to_a.map(&:to_s).sort.should == ['article.key1', 'article.key2', 'article.key3', 'article.key4', 'article.key5', - 'category_erb.key1', 'category_html_erb.key1', 'category_rhtml.key1', 'js.alert'] - end - end - - describe "to_hash" do - it "return a hash with I18n keys and file lists" do - @keys.to_hash[:'article.key3'].should == ["vendor/plugins/translate/spec/files/translate/app/models/article.rb"] - end - end - - describe "i18n_keys" do - before(:each) do - I18n.backend.send(:init_translations) unless I18n.backend.initialized? - end - - it "should return all keys in the I18n backend translations hash" do - I18n.backend.should_receive(:translations).and_return(translations) - @keys.i18n_keys(:en).should == ['articles.new.page_title', 'categories.flash.created', 'empty', 'home.about'] - end - - describe "untranslated_keys" do - before(:each) do - I18n.backend.stub!(:translations).and_return(translations) - end - - it "should return a hash with keys with missing translations in each locale" do - @keys.untranslated_keys.should == { - :sv => ['articles.new.page_title', 'categories.flash.created', 'empty'] - } - end - end - - describe "missing_keys" do - before(:each) do - @file_path = File.join(i18n_files_dir, "config", "locales", "en.yml") - Translate::File.new(@file_path).write({ - :en => { - :home => { - :page_title => false, - :intro => { - :one => "intro one", - :other => "intro other" - } - } - } - }) - end - - after(:each) do - FileUtils.rm(@file_path) - end - - it "should return a hash with keys that are not in the locale file" do - @keys.stub!(:files).and_return({ - :'home.page_title' => "app/views/home/index.rhtml", - :'home.intro' => 'app/views/home/index.rhtml', - :'home.signup' => "app/views/home/_signup.rhtml", - :'about.index.page_title' => "app/views/about/index.rhtml" - }) - @keys.missing_keys.should == { - :'home.signup' => "app/views/home/_signup.rhtml", - :'about.index.page_title' => "app/views/about/index.rhtml" - } - end - end - - describe "contains_key?" do - it "works" do - hash = { - :foo => { - :bar => { - :baz => false - } - } - } - Translate::Keys.contains_key?(hash, "").should be_false - Translate::Keys.contains_key?(hash, "foo").should be_true - Translate::Keys.contains_key?(hash, "foo.bar").should be_true - Translate::Keys.contains_key?(hash, "foo.bar.baz").should be_true - Translate::Keys.contains_key?(hash, :"foo.bar.baz").should be_true - Translate::Keys.contains_key?(hash, "foo.bar.baz.bla").should be_false - end - end - - describe "translated_locales" do - before(:each) do - I18n.stub!(:default_locale).and_return(:en) - I18n.stub!(:available_locales).and_return([:sv, :no, :en, :root]) - end - - it "returns all avaiable except :root and the default" do - Translate::Keys.translated_locales.should == [:sv, :no] - end - end - - describe "to_deep_hash" do - it "convert shallow hash with dot separated keys to deep hash" do - Translate::Keys.to_deep_hash(shallow_hash).should == deep_hash - end - end - - describe "to_shallow_hash" do - it "converts a deep hash to a shallow one" do - Translate::Keys.to_shallow_hash(deep_hash).should == shallow_hash - end - end - - ########################################################################## - # - # Helper Methods - # - ########################################################################## - - def translations - { - :en => { - :home => { - :about => "This site is about making money" - }, - :articles => { - :new => { - :page_title => "New Article" - } - }, - :categories => { - :flash => { - :created => "Category created" - } - }, - :empty => nil - }, - :sv => { - :home => { - :about => false - } - } - } - end - end - - def shallow_hash - { - 'pressrelease.label.one' => "Pressmeddelande", - 'pressrelease.label.other' => "Pressmeddelanden", - 'article' => "Artikel", - 'category' => '' - } - end - - def deep_hash - { - :pressrelease => { - :label => { - :one => "Pressmeddelande", - :other => "Pressmeddelanden" - } - }, - :article => "Artikel", - :category => '' - } - end - - def i18n_files_dir - File.join(ENV['PWD'], "spec", "files", "translate") - end -end diff --git a/backup.rails2.3/plugins/translate/spec/log_spec.rb b/backup.rails2.3/plugins/translate/spec/log_spec.rb deleted file mode 100644 index 7dc9f542..00000000 --- a/backup.rails2.3/plugins/translate/spec/log_spec.rb +++ /dev/null @@ -1,47 +0,0 @@ -require 'fileutils' -require File.dirname(__FILE__) + '/spec_helper' - -describe Translate::Log do - describe "write_to_file" do - before(:each) do - I18n.locale = :sv - I18n.backend.store_translations(:sv, from_texts) - keys = Translate::Keys.new - @log = Translate::Log.new(:sv, :en, Translate::Keys.to_shallow_hash(from_texts).keys) - @log.stub!(:file_path).and_return(file_path) - FileUtils.rm_f file_path - end - - after(:each) do - FileUtils.rm_f file_path - end - - it "writes new log file with from texts" do - File.exists?(file_path).should be_false - @log.write_to_file - File.exists?(file_path).should be_true - Translate::File.new(file_path).read.should == Translate::File.deep_stringify_keys(from_texts) - end - - it "merges from texts with current texts in log file and re-writes the log file" do - @log.write_to_file - I18n.backend.store_translations(:sv, {:category => "Kategori ny"}) - @log.keys = ['category'] - @log.write_to_file - Translate::File.new(file_path).read['category'].should == "Kategori ny" - end - - def file_path - File.join(File.dirname(__FILE__), "files", "from_sv_to_en.yml") - end - - def from_texts - { - :article => { - :title => "En artikel" - }, - :category => "Kategori" - } - end - end -end diff --git a/backup.rails2.3/plugins/translate/spec/spec_helper.rb b/backup.rails2.3/plugins/translate/spec/spec_helper.rb deleted file mode 100644 index 5a919082..00000000 --- a/backup.rails2.3/plugins/translate/spec/spec_helper.rb +++ /dev/null @@ -1,11 +0,0 @@ -begin - # Using PWD here instead of File.dirname(__FILE__) to be able to symlink to plugin - # from within a Rails app. - require File.expand_path(ENV['PWD'] + '/../../../spec/spec_helper') -rescue LoadError => e - puts "You need to install rspec in your base app\n#{e.message}: #{e.backtrace.join("\n")}" - exit -end - -plugin_spec_dir = File.dirname(__FILE__) -ActiveRecord::Base.logger = Logger.new(plugin_spec_dir + "/debug.log") diff --git a/backup.rails2.3/plugins/translate/spec/storage_spec.rb b/backup.rails2.3/plugins/translate/spec/storage_spec.rb deleted file mode 100644 index e6110c3d..00000000 --- a/backup.rails2.3/plugins/translate/spec/storage_spec.rb +++ /dev/null @@ -1,33 +0,0 @@ -require File.dirname(__FILE__) + '/spec_helper' - -describe Translate::Storage do - describe "write_to_file" do - before(:each) do - @storage = Translate::Storage.new(:en) - end - - it "writes all I18n messages for a locale to YAML file" do - I18n.backend.should_receive(:translations).and_return(translations) - @storage.stub!(:file_path).and_return(file_path) - file = mock(:file) - file.should_receive(:write).with(translations) - Translate::File.should_receive(:new).with(file_path).and_return(file) - @storage.write_to_file - end - - def file_path - File.join(File.dirname(__FILE__), "files", "en.yml") - end - - def translations - { - :en => { - :article => { - :title => "One Article" - }, - :category => "Category" - } - } - end - end -end diff --git a/backup.rails2.3/plugins/translate/tasks/translate.rake b/backup.rails2.3/plugins/translate/tasks/translate.rake deleted file mode 100644 index a70b934c..00000000 --- a/backup.rails2.3/plugins/translate/tasks/translate.rake +++ /dev/null @@ -1,178 +0,0 @@ -require 'yaml' - -class Hash - def deep_merge(other) - # deep_merge by Stefan Rusterholz, see http://www.ruby-forum.com/topic/142809 - merger = proc { |key, v1, v2| (Hash === v1 && Hash === v2) ? v1.merge(v2, &merger) : v2 } - merge(other, &merger) - end - - def set(keys, value) - key = keys.shift - if keys.empty? - self[key] = value - else - self[key] ||= {} - self[key].set keys, value - end - end - - if ENV['SORT'] - # copy of ruby's to_yaml method, prepending sort. - # before each so we get an ordered yaml file - def to_yaml( opts = {} ) - YAML::quick_emit( self, opts ) do |out| - out.map( taguri, to_yaml_style ) do |map| - sort.each do |k, v| #<- Adding sort. - map.add( k, v ) - end - end - end - end - end -end - -namespace :translate do - desc "Show untranslated keys for locale LOCALE" - task :untranslated => :environment do - from_locale = I18n.default_locale - untranslated = Translate::Keys.new.untranslated_keys - - messages = [] - untranslated.each do |locale, keys| - keys.each do |key| - from_text = I18n.backend.send(:lookup, from_locale, key) - messages << "#{locale}.#{key} (#{from_locale}.#{key}='#{from_text}')" - end - end - - if messages.present? - messages.each { |m| puts m } - else - puts "No untranslated keys" - end - end - - desc "Show I18n keys that are missing in the config/locales/default_locale.yml YAML file" - task :missing => :environment do - missing = Translate::Keys.new.missing_keys.inject([]) do |keys, (key, filename)| - keys << "#{key} in \t #{filename} is missing" - end - puts missing.present? ? missing.join("\n") : "No missing translations in the default locale file" - end - - desc "Remove all translation texts that are no longer present in the locale they were translated from" - task :remove_obsolete_keys => :environment do - I18n.backend.send(:init_translations) - master_locale = ENV['LOCALE'] || I18n.default_locale - Translate::Keys.translated_locales.each do |locale| - texts = {} - Translate::Keys.new.i18n_keys(locale).each do |key| - if I18n.backend.send(:lookup, master_locale, key).to_s.present? - texts[key] = I18n.backend.send(:lookup, locale, key) - end - end - I18n.backend.send(:translations)[locale] = nil # Clear out all current translations - I18n.backend.store_translations(locale, Translate::Keys.to_deep_hash(texts)) - Translate::Storage.new(locale).write_to_file - end - end - - desc "Merge I18n keys from log/translations.yml into config/locales/*.yml (for use with the Rails I18n TextMate bundle)" - task :merge_keys => :environment do - I18n.backend.send(:init_translations) - new_translations = YAML::load(IO.read(File.join(Rails.root, "log", "translations.yml"))) - raise("Can only merge in translations in single locale") if new_translations.keys.size > 1 - locale = new_translations.keys.first - - overwrites = false - Translate::Keys.to_shallow_hash(new_translations[locale]).keys.each do |key| - new_text = key.split(".").inject(new_translations[locale]) { |hash, sub_key| hash[sub_key] } - existing_text = I18n.backend.send(:lookup, locale.to_sym, key) - if existing_text && new_text != existing_text - puts "ERROR: key #{key} already exists with text '#{existing_text.inspect}' and would be overwritten by new text '#{new_text}'. " + - "Set environment variable OVERWRITE=1 if you really want to do this." - overwrites = true - end - end - - if !overwrites || ENV['OVERWRITE'] - I18n.backend.store_translations(locale, new_translations[locale]) - Translate::Storage.new(locale).write_to_file - end - end - - desc "Apply Google translate to auto translate all texts in locale ENV['FROM'] to locale ENV['TO']" - task :google => :environment do - raise "Please specify FROM and TO locales as environment variables" if ENV['FROM'].blank? || ENV['TO'].blank? - - # Depends on httparty gem - # http://www.robbyonrails.com/articles/2009/03/16/httparty-goes-foreign - class GoogleApi - include HTTParty - base_uri 'ajax.googleapis.com' - def self.translate(string, to, from) - tries = 0 - begin - get("/ajax/services/language/translate", - :query => {:langpair => "#{from}|#{to}", :q => string, :v => 1.0}, - :format => :json) - rescue - tries += 1 - puts("SLEEPING - retrying in 5...") - sleep(5) - retry if tries < 10 - end - end - end - - I18n.backend.send(:init_translations) - - start_at = Time.now - translations = {} - Translate::Keys.new.i18n_keys(ENV['FROM']).each do |key| - from_text = I18n.backend.send(:lookup, ENV['FROM'], key).to_s - to_text = I18n.backend.send(:lookup, ENV['TO'], key) - if !from_text.blank? && to_text.blank? - print "#{key}: '#{from_text[0, 40]}' => " - if !translations[from_text] - response = GoogleApi.translate(from_text, ENV['TO'], ENV['FROM']) - translations[from_text] = response["responseData"] && response["responseData"]["translatedText"] - end - if !(translation = translations[from_text]).blank? - translation.gsub!(/\(\(([a-z_.]+)\)\)/i, '{{\1}}') - # Google translate sometimes replaces {{foobar}} with (()) foobar. We skip these - if translation !~ /\(\(\)\)/ - puts "'#{translation[0, 40]}'" - I18n.backend.store_translations(ENV['TO'].to_sym, Translate::Keys.to_deep_hash({key => translation})) - else - puts "SKIPPING since interpolations were messed up: '#{translation[0,40]}'" - end - else - puts "NO TRANSLATION - #{response.inspect}" - end - end - end - - puts "\nTime elapsed: #{(((Time.now - start_at) / 60) * 10).to_i / 10.to_f} minutes" - Translate::Storage.new(ENV['TO'].to_sym).write_to_file - end - - desc "List keys that have changed I18n texts between YAML file ENV['FROM_FILE'] and YAML file ENV['TO_FILE']. Set ENV['VERBOSE'] to see changes" - task :changed => :environment do - from_hash = Translate::Keys.to_shallow_hash(Translate::File.new(ENV['FROM_FILE']).read) - to_hash = Translate::Keys.to_shallow_hash(Translate::File.new(ENV['TO_FILE']).read) - from_hash.each do |key, from_value| - if (to_value = to_hash[key]) && to_value != from_value - key_without_locale = key[/^[^.]+\.(.+)$/, 1] - if ENV['VERBOSE'] - puts "KEY: #{key_without_locale}" - puts "FROM VALUE: '#{from_value}'" - puts "TO VALUE: '#{to_value}'" - else - puts key_without_locale - end - end - end - end -end diff --git a/backup.rails2.3/plugins/translate/views/layouts/translate.rhtml b/backup.rails2.3/plugins/translate/views/layouts/translate.rhtml deleted file mode 100644 index 58dbc5c3..00000000 --- a/backup.rails2.3/plugins/translate/views/layouts/translate.rhtml +++ /dev/null @@ -1,359 +0,0 @@ - - - - - - <%= h(@page_title) %> - - <%= translate_javascript_includes %> - - - - - - - -
- <% if @page_title -%>

<%=h @page_title %>

<% end -%> - <% [:notice, :error].each do |message| %> - <%if flash[message] %> -
- <%= h(flash[message]) if flash[message] %> -
- <% end %> - <% end %> - <%= yield %> -
- - diff --git a/backup.rails2.3/plugins/translate/views/translate/_pagination.rhtml b/backup.rails2.3/plugins/translate/views/translate/_pagination.rhtml deleted file mode 100644 index 64f4d690..00000000 --- a/backup.rails2.3/plugins/translate/views/translate/_pagination.rhtml +++ /dev/null @@ -1,24 +0,0 @@ -<% - # Expects locals: - # - # total_entries - # per_page - - n_pages = total_entries/per_page + (total_entries % per_page > 0 ? 1 : 0) - current_page = (params[:page] || 1).to_i -%> - -<% if n_pages > 1 %> -

Pages:

-
-
    - <% (1..n_pages).each do |page_number| %> - <% if current_page == page_number %> -
  • <%= link_to(page_number, params.merge(:page => page_number), :title => "Page #{page_number}" ) %>
  • - <% else %> -
  • <%= link_to(page_number, params.merge(:page => page_number), :title => "Page #{page_number}") %>
  • - <% end %> - <% end %> -
-
-<% end %> \ No newline at end of file diff --git a/backup.rails2.3/plugins/translate/views/translate/index.rhtml b/backup.rails2.3/plugins/translate/views/translate/index.rhtml deleted file mode 100644 index a057659d..00000000 --- a/backup.rails2.3/plugins/translate/views/translate/index.rhtml +++ /dev/null @@ -1,114 +0,0 @@ -<% - @page_title = "Translate" - show_filters = ["all", "untranslated", "translated"] - show_filters << "changed" if @from_locale != @to_locale -%> - -
- Search filter -
-

- <%= simple_filter(show_filters) %> -

-

- <%= simple_filter(["key", "text"], 'sort_by') %> -

-
- <% form_tag(params, :method => :get) do %> -
-

- <%= hidden_field_tag(:filter, params[:filter]) %> - <%= hidden_field_tag(:sort_by, params[:sort_by]) %> - - <%= select_tag(:from_locale, options_for_select(I18n.valid_locales, @from_locale.to_sym)) %> to - <%= select_tag(:to_locale, options_for_select(I18n.valid_locales, @to_locale.to_sym)) %> - <%= submit_tag "Display" %> -

-
-
-

- - <%= select_tag(:key_type, options_for_select([["contains", 'contains'], ["starts with", 'starts_with']], params[:key_type])) %> - <%= text_field_tag(:key_pattern, params[:key_pattern], :size => 50, :id => "key_pattern_value", :class => "text-default") %> -

-

- - <%= select_tag(:text_type, options_for_select(['contains', 'equals'], params[:text_type])) %> - <%= text_field_tag(:text_pattern, params[:text_pattern], :size => 50, :id => "text_pattern_value", :class => "text-default") %> -

-

- <%= submit_tag "Search" %> - <%= link_to "clear", params.merge({:text_pattern => nil, :key_pattern => nil}) %> -

-
- <% end %> -

- Found <%= @total_entries %> messages -

-

- <%= link_to "Reload messages", translate_reload_path %> -

-
- - -
- <%= render :partial => 'pagination', :locals => {:total_entries => @total_entries, :per_page => per_page} %> -
- -<% if @total_entries > 0 %> -<% form_tag(translate_path) do %> -
- <%= hidden_field_tag(:filter, params[:filter], :id => "hid_filter") %> - <%= hidden_field_tag(:sort_by, params[:sort_by], :id => "hid_sort_by") %> - <%= hidden_field_tag(:key_type, params[:key_type], :id => "hid_key_type") %> - <%= hidden_field_tag(:key_pattern, params[:key_pattern], :id => "hid_key_pattern") %> - <%= hidden_field_tag(:text_type, params[:text_type], :id => "hid_text_type") %> - <%= hidden_field_tag(:text_pattern, params[:text_pattern], :id => "hid_text_pattern") %> -
-
-

Translations from <%= @from_locale %> to <%= @to_locale %>

-

- <%= submit_tag "Save Translations" %> -

- <% @paginated_keys.each do |key| - from_text = lookup(@from_locale, key) - to_text = lookup(@to_locale, key) - line_size = 100 - n_lines = n_lines(from_text, line_size) - field_name = "key[#{key}]" - %> -
- <% if from_text.present? %> -

- <%= simple_format(h(from_text)) %> -

- <% end %> -

- <% if n_lines > 1 %> - <%= text_area_tag(field_name, to_text, :size => "#{line_size}x#{n_lines}", :id => key) %> - <% else %> - <%= text_field_tag(field_name, to_text, :size => line_size, :id => key) %> - <% end %> -

-

- - <%= link_to_function 'Auto Translate', "getGoogleTranslation('#{key}', \"#{escape_javascript(from_text)}\", '#{@from_locale}', '#{@to_locale}')", :style => 'padding: 0; margin: 0;' %> -
- Key:<%=h key %>
- <% if @files[key] %> - File:<%= @files[key].join("
") %> - <% end %> -
-

-
-<% end %> -

- <%= submit_tag "Save Translations" %> -

-
-<% end %> -<% end %> - -
- <%= render :partial => 'pagination', :locals => {:total_entries => @total_entries, :per_page => per_page} %> -
\ No newline at end of file diff --git a/backup.rails2.3/production.rb.rails2 b/backup.rails2.3/production.rb.rails2 deleted file mode 100644 index 56470f47..00000000 --- a/backup.rails2.3/production.rb.rails2 +++ /dev/null @@ -1,17 +0,0 @@ -# The production environment is meant for finished, "live" apps. -# Code is not reloaded between requests -config.cache_classes = true - -# Use a different logger for distributed setups -# config.logger = SyslogLogger.new - - -# Full error reports are disabled and caching is turned on -config.action_controller.consider_all_requests_local = false -config.action_controller.perform_caching = true - -# Enable serving of images, stylesheets, and javascripts from an asset server -# config.action_controller.asset_host = "http://assets.example.com" - -# Disable delivery errors if you bad email addresses should just be ignored -# config.action_mailer.raise_delivery_errors = false \ No newline at end of file diff --git a/backup.rails2.3/routes.rb.rails2 b/backup.rails2.3/routes.rb.rails2 deleted file mode 100644 index ec0ed738..00000000 --- a/backup.rails2.3/routes.rb.rails2 +++ /dev/null @@ -1,113 +0,0 @@ -ActionController::Routing::Routes.draw do |map| - map.resources :users, - :member => {:change_password => :get, :update_password => :post, - :change_auth_type => :get, :update_auth_type => :post, :complete => :get, - :refresh_token => :post } - - map.with_options :controller => :users do |users| - users.signup 'signup', :action => "new" - end - - map.resources :contexts, :collection => {:order => :post, :done => :get}, :member => {:done_todos => :get, :all_done_todos => :get} do |contexts| - contexts.resources :todos, :name_prefix => "context_" - end - - map.resources :projects, - :collection => {:order => :post, :alphabetize => :post, :actionize => :post, :done => :get}, - :member => {:done_todos => :get, :all_done_todos => :get, :set_reviewed => :get} do |projects| - projects.resources :todos, :name_prefix => "project_" - end - - map.with_options :controller => :projects do |projects| - projects.review 'review', :action => :review - end - - map.resources :notes - - map.resources :todos, - :member => {:toggle_check => :put, :toggle_star => :put, :defer => :put}, - :collection => {:check_deferred => :post, :filter_to_context => :post, :filter_to_project => :post, :done => :get, :all_done => :get - } - - map.with_options :controller => :todos do |todos| - todos.home '', :action => "index" - todos.tickler 'tickler.:format', :action => "list_deferred" - todos.mobile_tickler 'tickler.m', :action => "list_deferred", :format => 'm' - - # This route works for tags with dots like /todos/tag/version1.5 - # please note that this pattern consumes everything after /todos/tag - # so /todos/tag/version1.5.xml will result in :name => 'version1.5.xml' - # UPDATE: added support for mobile view. All tags ending on .m will be - # routed to mobile view of tags. - todos.mobile_tag 'todos/tag/:name.m', :action => "tag", :format => 'm' - todos.text_tag 'todos/tag/:name.txt', :action => "tag", :format => 'txt' - todos.tag 'todos/tag/:name', :action => "tag", :name => /.*/ - todos.done_tag 'todos/done/tag/:name', :action => "done_tag" - todos.all_done_tag 'todos/all_done/tag/:name', :action => "all_done_tag" - - todos.tags 'tags.autocomplete', :action => "tags", :format => 'autocomplete' - todos.auto_complete_for_predecessor 'auto_complete_for_predecessor', :action => 'auto_complete_for_predecessor' - - todos.calendar 'calendar.ics', :action => "calendar", :format => 'ics' - todos.calendar 'calendar.xml', :action => "calendar", :format => 'xml' - todos.calendar 'calendar', :action => "calendar" - - todos.hidden 'hidden.xml', :action => "list_hidden", :format => 'xml' - - todos.mobile 'mobile', :action => "index", :format => 'm' - todos.mobile_abbrev 'm', :action => "index", :format => 'm' - todos.mobile_abbrev_new 'm/new', :action => "new", :format => 'm' - - todos.mobile_todo_show_notes 'todos/notes/:id.m', :action => "show_notes", :format => 'm' - todos.todo_show_notes 'todos/notes/:id', :action => "show_notes" - todos.done_todos 'todos/done', :action => :done - todos.all_done_todos 'todos/all_done', :action => :all_done - end - map.root :controller => 'todos' # Make OpenID happy because it needs #root_url defined - - map.resources :recurring_todos, :collection => {:done => :get}, - :member => {:toggle_check => :put, :toggle_star => :put} - map.with_options :controller => :recurring_todos do |rt| - rt.recurring_todos 'recurring_todos', :action => 'index' - end - - map.with_options :controller => :login do |login| - login.login 'login', :action => 'login' - login.login_cas 'login_cas', :action => 'login_cas' - login.formatted_login 'login.:format', :action => 'login' - login.logout 'logout', :action => 'logout' - login.formatted_logout 'logout.:format', :action => 'logout' - end - - map.with_options :controller => :feedlist do |fl| - fl.mobile_feeds 'feeds.m', :action => 'index', :format => 'm' - fl.feeds 'feeds', :action => 'index' - end - - map.with_options :controller => :integrations do |i| - i.integrations 'integrations', :action => 'index' - i.rest_api_docs 'integrations/rest_api', :action => "rest_api" - i.search_plugin 'integrations/search_plugin.xml', :action => 'search_plugin', :format => 'xml' - i.google_gadget 'integrations/google_gadget.xml', :action => 'google_gadget', :format => 'xml' - i.cloudmailin 'integrations/cloudmailin', :action => 'cloudmailin' - end - - map.with_options :controller => :preferences do |p| - p.preferences 'preferences', :action => 'index' - p.preferences_date_format 'preferences/render_date_format', :action => 'render_date_format' - end - - map.with_options :controller => :stats do |stats| - stats.stats 'stats', :action => 'index' - stats.done_overview 'done', :action => 'done' - end - - map.search 'search', :controller => 'search', :action => 'index' - map.data 'data', :controller => 'data', :action => 'index' - - Translate::Routes.translation_ui(map) if Rails.env != "production" - - # Install the default route as the lowest priority. - map.connect ':controller/:action/:id' - -end diff --git a/backup.rails2.3/slider.js b/backup.rails2.3/slider.js deleted file mode 100644 index c0f1fc01..00000000 --- a/backup.rails2.3/slider.js +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright (c) 2005 Marty Haught, Thomas Fuchs -// -// See http://script.aculo.us for more info -// -// 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. - -if(!Control) var Control = {}; -Control.Slider = Class.create(); - -// options: -// axis: 'vertical', or 'horizontal' (default) -// -// callbacks: -// onChange(value) -// onSlide(value) -Control.Slider.prototype = { - initialize: function(handle, track, options) { - var slider = this; - - if(handle instanceof Array) { - this.handles = handle.collect( function(e) { return $(e) }); - } else { - this.handles = [$(handle)]; - } - - this.track = $(track); - this.options = options || {}; - - this.axis = this.options.axis || 'horizontal'; - this.increment = this.options.increment || 1; - this.step = parseInt(this.options.step || '1'); - this.range = this.options.range || $R(0,1); - - this.value = 0; // assure backwards compat - this.values = this.handles.map( function() { return 0 }); - this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false; - this.options.startSpan = $(this.options.startSpan || null); - this.options.endSpan = $(this.options.endSpan || null); - - this.restricted = this.options.restricted || false; - - this.maximum = this.options.maximum || this.range.end; - this.minimum = this.options.minimum || this.range.start; - - // Will be used to align the handle onto the track, if necessary - this.alignX = parseInt(this.options.alignX || '0'); - this.alignY = parseInt(this.options.alignY || '0'); - - this.trackLength = this.maximumOffset() - this.minimumOffset(); - this.handleLength = this.isVertical() ? this.handles[0].offsetHeight : this.handles[0].offsetWidth; - - this.active = false; - this.dragging = false; - this.disabled = false; - - if(this.options.disabled) this.setDisabled(); - - // Allowed values array - this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false; - if(this.allowedValues) { - this.minimum = this.allowedValues.min(); - this.maximum = this.allowedValues.max(); - } - - this.eventMouseDown = this.startDrag.bindAsEventListener(this); - this.eventMouseUp = this.endDrag.bindAsEventListener(this); - this.eventMouseMove = this.update.bindAsEventListener(this); - - // Initialize handles in reverse (make sure first handle is active) - this.handles.each( function(h,i) { - i = slider.handles.length-1-i; - slider.setValue(parseFloat( - (slider.options.sliderValue instanceof Array ? - slider.options.sliderValue[i] : slider.options.sliderValue) || - slider.range.start), i); - Element.makePositioned(h); // fix IE - Event.observe(h, "mousedown", slider.eventMouseDown); - }); - - Event.observe(this.track, "mousedown", this.eventMouseDown); - Event.observe(document, "mouseup", this.eventMouseUp); - Event.observe(document, "mousemove", this.eventMouseMove); - - this.initialized = true; - }, - dispose: function() { - var slider = this; - Event.stopObserving(this.track, "mousedown", this.eventMouseDown); - Event.stopObserving(document, "mouseup", this.eventMouseUp); - Event.stopObserving(document, "mousemove", this.eventMouseMove); - this.handles.each( function(h) { - Event.stopObserving(h, "mousedown", slider.eventMouseDown); - }); - }, - setDisabled: function(){ - this.disabled = true; - }, - setEnabled: function(){ - this.disabled = false; - }, - getNearestValue: function(value){ - if(this.allowedValues){ - if(value >= this.allowedValues.max()) return(this.allowedValues.max()); - if(value <= this.allowedValues.min()) return(this.allowedValues.min()); - - var offset = Math.abs(this.allowedValues[0] - value); - var newValue = this.allowedValues[0]; - this.allowedValues.each( function(v) { - var currentOffset = Math.abs(v - value); - if(currentOffset <= offset){ - newValue = v; - offset = currentOffset; - } - }); - return newValue; - } - if(value > this.range.end) return this.range.end; - if(value < this.range.start) return this.range.start; - return value; - }, - setValue: function(sliderValue, handleIdx){ - if(!this.active) { - this.activeHandle = this.handles[handleIdx]; - this.activeHandleIdx = handleIdx; - this.updateStyles(); - } - handleIdx = handleIdx || this.activeHandleIdx || 0; - if(this.initialized && this.restricted) { - if((handleIdx>0) && (sliderValuethis.values[handleIdx+1])) - sliderValue = this.values[handleIdx+1]; - } - sliderValue = this.getNearestValue(sliderValue); - this.values[handleIdx] = sliderValue; - this.value = this.values[0]; // assure backwards compat - - this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = - this.translateToPx(sliderValue); - - this.drawSpans(); - if(!this.dragging || !this.event) this.updateFinished(); - }, - setValueBy: function(delta, handleIdx) { - this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, - handleIdx || this.activeHandleIdx || 0); - }, - translateToPx: function(value) { - return Math.round( - ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * - (value - this.range.start)) + "px"; - }, - translateToValue: function(offset) { - return ((offset/(this.trackLength-this.handleLength) * - (this.range.end-this.range.start)) + this.range.start); - }, - getRange: function(range) { - var v = this.values.sortBy(Prototype.K); - range = range || 0; - return $R(v[range],v[range+1]); - }, - minimumOffset: function(){ - return(this.isVertical() ? this.alignY : this.alignX); - }, - maximumOffset: function(){ - return(this.isVertical() ? - this.track.offsetHeight - this.alignY : this.track.offsetWidth - this.alignX); - }, - isVertical: function(){ - return (this.axis == 'vertical'); - }, - drawSpans: function() { - var slider = this; - if(this.spans) - $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) }); - if(this.options.startSpan) - this.setSpan(this.options.startSpan, - $R(0, this.values.length>1 ? this.getRange(0).min() : this.value )); - if(this.options.endSpan) - this.setSpan(this.options.endSpan, - $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum)); - }, - setSpan: function(span, range) { - if(this.isVertical()) { - span.style.top = this.translateToPx(range.start); - span.style.height = this.translateToPx(range.end - range.start + this.range.start); - } else { - span.style.left = this.translateToPx(range.start); - span.style.width = this.translateToPx(range.end - range.start + this.range.start); - } - }, - updateStyles: function() { - this.handles.each( function(h){ Element.removeClassName(h, 'selected') }); - Element.addClassName(this.activeHandle, 'selected'); - }, - startDrag: function(event) { - if(Event.isLeftClick(event)) { - if(!this.disabled){ - this.active = true; - - var handle = Event.element(event); - var pointer = [Event.pointerX(event), Event.pointerY(event)]; - if(handle==this.track) { - var offsets = Position.cumulativeOffset(this.track); - this.event = event; - this.setValue(this.translateToValue( - (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2) - )); - var offsets = Position.cumulativeOffset(this.activeHandle); - this.offsetX = (pointer[0] - offsets[0]); - this.offsetY = (pointer[1] - offsets[1]); - } else { - // find the handle (prevents issues with Safari) - while((this.handles.indexOf(handle) == -1) && handle.parentNode) - handle = handle.parentNode; - - this.activeHandle = handle; - this.activeHandleIdx = this.handles.indexOf(this.activeHandle); - this.updateStyles(); - - var offsets = Position.cumulativeOffset(this.activeHandle); - this.offsetX = (pointer[0] - offsets[0]); - this.offsetY = (pointer[1] - offsets[1]); - } - } - Event.stop(event); - } - }, - update: function(event) { - if(this.active) { - if(!this.dragging) this.dragging = true; - this.draw(event); - // fix AppleWebKit rendering - if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); - Event.stop(event); - } - }, - draw: function(event) { - var pointer = [Event.pointerX(event), Event.pointerY(event)]; - var offsets = Position.cumulativeOffset(this.track); - pointer[0] -= this.offsetX + offsets[0]; - pointer[1] -= this.offsetY + offsets[1]; - this.event = event; - this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] )); - if(this.initialized && this.options.onSlide) - this.options.onSlide(this.values.length>1 ? this.values : this.value, this); - }, - endDrag: function(event) { - if(this.active && this.dragging) { - this.finishDrag(event, true); - Event.stop(event); - } - this.active = false; - this.dragging = false; - }, - finishDrag: function(event, success) { - this.active = false; - this.dragging = false; - this.updateFinished(); - }, - updateFinished: function() { - if(this.initialized && this.options.onChange) - this.options.onChange(this.values.length>1 ? this.values : this.value, this); - this.event = null; - } -} \ No newline at end of file diff --git a/backup.rails2.3/spec/controllers/projects_controller_spec.rb b/backup.rails2.3/spec/controllers/projects_controller_spec.rb deleted file mode 100644 index 3ee3b81b..00000000 --- a/backup.rails2.3/spec/controllers/projects_controller_spec.rb +++ /dev/null @@ -1,21 +0,0 @@ -require File.dirname(__FILE__) + '/../spec_helper' - -describe ProjectsController do - it "should save default tags" do - project = Project.new - - projects = mock(:project_list, :build => project, - :active => mock(:meh, :count => 0), :size => 0) - - user = mock_model(User, :projects => projects, :prefs => mock(:locale => :en), - :contexts => mock(:context_list, :find => [])) - controller.stub!(:current_user).and_return(user) - controller.stub!(:login_required).and_return(true) - controller.stub!(:set_time_zone).and_return(true) - controller.stub!(:mobile?).and_return(true) - - get 'create', :project => {:name => "fooproject", :default_tags => "a,b"} - - project.default_tags.should == 'a,b' - end -end diff --git a/backup.rails2.3/spec/controllers/todos_controller_spec.rb b/backup.rails2.3/spec/controllers/todos_controller_spec.rb deleted file mode 100644 index 0bd0870c..00000000 --- a/backup.rails2.3/spec/controllers/todos_controller_spec.rb +++ /dev/null @@ -1,4 +0,0 @@ -require File.dirname(__FILE__) + '/../spec_helper' - -describe TodosController do -end diff --git a/backup.rails2.3/spec/factories/factories.rb b/backup.rails2.3/spec/factories/factories.rb deleted file mode 100644 index 8a2c550f..00000000 --- a/backup.rails2.3/spec/factories/factories.rb +++ /dev/null @@ -1,26 +0,0 @@ -begin - Factory.define :user do |u| - u.sequence(:login) { |n| "testuser#{n}" } - u.password "secret" - u.password_confirmation { |user| user.password } - u.is_admin false - end - - Factory.define :context do |c| - c.sequence(:name) { |n| "testcontext#{n}" } - c.hide false - c.created_at Time.now.utc - end - - Factory.define :project do |p| - p.sequence(:name) { |n| "testproject#{n}" } - end - - Factory.define :todo do |t| - t.sequence(:description) { |n| "testtodo#{n}" } - t.association :context - end - -rescue FactoryGirl::DuplicateDefinitionError - # No problem, apparently this file was included already. -end diff --git a/backup.rails2.3/spec/fixtures/contexts.yml b/backup.rails2.3/spec/fixtures/contexts.yml deleted file mode 100644 index a0513ccc..00000000 --- a/backup.rails2.3/spec/fixtures/contexts.yml +++ /dev/null @@ -1,22 +0,0 @@ -# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html - -agenda: - id: 2 - name: agenda - position: 2 - hide: false - user: admin_user - -call: - id: 3 - name: call - position: 3 - hide: true - user: admin_user - -email: - id: 4 - name: email - position: 4 - hide: false - user: admin_user diff --git a/backup.rails2.3/spec/fixtures/preferences.yml b/backup.rails2.3/spec/fixtures/preferences.yml deleted file mode 100644 index 66d41ee8..00000000 --- a/backup.rails2.3/spec/fixtures/preferences.yml +++ /dev/null @@ -1,34 +0,0 @@ -# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html -admin_user_prefs: - user: admin_user - staleness_starts: 7 - date_format: "%d/%m/%Y" - title_date_format: "%A, %d %B %Y" - show_number_completed: 5 - show_completed_projects_in_sidebar: true - show_hidden_contexts_in_sidebar: true - show_hidden_projects_in_sidebar: true - admin_email: butshesagirl@rousette.org.uk - week_starts: 1 - due_style: 0 - refresh: 0 - time_zone: "London" - verbose_action_descriptors: true - show_project_on_todo_done: false - -other_user_prefs: - user: jane - staleness_starts: 7 - date_format: "%d/%m/%Y" - title_date_format: "%A, %d %B %Y" - show_number_completed: 5 - show_completed_projects_in_sidebar: true - show_hidden_contexts_in_sidebar: true - show_hidden_projects_in_sidebar: true - admin_email: butshesagirl@rousette.org.uk - week_starts: 1 - due_style: 0 - refresh: 0 - time_zone: "London" - verbose_action_descriptors: false - show_project_on_todo_done: true diff --git a/backup.rails2.3/spec/fixtures/todos.yml b/backup.rails2.3/spec/fixtures/todos.yml deleted file mode 100644 index b8af3088..00000000 --- a/backup.rails2.3/spec/fixtures/todos.yml +++ /dev/null @@ -1,68 +0,0 @@ -# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html -<% - -def today - Time.zone.now.beginning_of_day.to_s(:db) -end - -def next_week - 1.week.from_now.beginning_of_day.to_s(:db) -end - -def last_week - 1.week.ago.beginning_of_day.to_s(:db) -end - -def two_weeks_ago - 2.weeks.ago.beginning_of_day.to_s(:db) -end - -def two_weeks_hence - 2.weeks.from_now.beginning_of_day.to_s(:db) -end - -%> - -billgates: - id: 2 - context_id: 2 - project_id: 2 - description: Call Bill Gates to find out how much he makes per day - notes: ~ - state: active - due: <%= two_weeks_hence %> - completed_at: ~ - user: admin_user - -dinoexterm: - id: 3 - context_id: 2 - project_id: 3 - description: Call dinosaur exterminator - notes: Ask him if I need to hire a skip for the corpses. - state: active - due: <%= two_weeks_hence %> - completed_at: ~ - user: admin_user - -buymilk: - id: 4 - context_id: 2 - project_id: ~ - description: Buy milk - notes: ~ - state: completed - due: ~ - completed_at: <%= today %> - user: admin_user - -callmom: - id: 5 - context_id: 3 # call - project_id: ~ - description: Call mom - notes: Remember her birthday - state: active - due: ~ - completed_at: ~ - user: admin_user diff --git a/backup.rails2.3/spec/fixtures/users.yml b/backup.rails2.3/spec/fixtures/users.yml deleted file mode 100644 index cdd9a914..00000000 --- a/backup.rails2.3/spec/fixtures/users.yml +++ /dev/null @@ -1,27 +0,0 @@ -# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html -admin_user: - login: admin - crypted_password: <%= BCrypt::Password.create("abracadabra") %> - token: <%= Digest::SHA1.hexdigest("adminSat Feb 25 17:14:00 GMT 20060.236961325863376") %> - is_admin: true - first_name: Admin - last_name: Schmadmin - auth_type: database - -other_user: - login: jane - crypted_password: <%= BCrypt::Password.create("sesame") %> - token: <%= Digest::SHA1.hexdigest("janeSun Feb 19 14:42:45 GMT 20060.408173979260027") %> - is_admin: false - first_name: Jane - last_name: Doe - auth_type: database - -ldap_user: - login: john - crypted_password: test - token: <%= Digest::SHA1.hexdigest("johnSun Feb 19 14:42:45 GMT 20060.408173979260027") %> - is_admin: false - first_name: John - last_name: Deere - auth_type: ldap diff --git a/backup.rails2.3/spec/models/context_spec.rb b/backup.rails2.3/spec/models/context_spec.rb deleted file mode 100644 index 562f285f..00000000 --- a/backup.rails2.3/spec/models/context_spec.rb +++ /dev/null @@ -1,100 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') - -describe Context do - def valid_attributes - {:name => 'Errands'} - end - - before(:each) do - @context = Context.new - end - - it 'has many users' do - Context.should have_many(:todos). - with_order('todos.due IS NULL, todos.due ASC, todos.created_at ASC'). - with_dependent(:delete_all). - with_include(:project) - end - - it_should_belong_to :user - - it_should_validate_presence_of :name, 'context must have a name' - it_should_validate_length_of :name, :maximum => 255, - :message_too_long => 'context name must be less than 256 characters' - it_should_validate_uniqueness_of :name, 'already exists' # TODO: scope user_id - it_should_not_accept_as_valid :name, ',', - :message => "cannot contain the comma (',') character" - - it 'is hidden when hide is true' do - Context.new(:hide => false).should_not be_hidden - Context.new(:hide => true).should be_hidden - end - - it 'returns name as title' do - Context.new(:name => 'foo').title.should == 'foo' - end - - it 'returns an instance NullContext for null_object' do - Context.null_object.should be_an_instance_of(NullContext) - end - - it "returns feed options with description containing user's name" do - user = mock_model(User, :display_name => 'simon') - feed_options_for_user = Context.feed_options(user) - feed_options_for_user[:title].should == 'Tracks Contexts' - feed_options_for_user[:description].should == 'Lists all the contexts for simon' - end - - describe 'when finding by namepart' do - fixtures :todos, :contexts - - it 'finds with exact match' do - Context.find_by_namepart('agenda').should == contexts(:agenda) - end - - it 'finds with partial match' do - Context.find_by_namepart('age').should == contexts(:agenda) - end - - it 'deletes todos within context when context deleted' do - contexts(:agenda).should have(3).todos - call_todos = contexts(:agenda).todos - contexts(:agenda).destroy - Todo.find(:all).should_not include(call_todos) - end - end - - describe 'when counting todos' do - fixtures :todos, :contexts, :users, :preferences - - it 'returns correct number of completed todos' do - contexts(:call).done_todos.should_not have(:any).items - contexts(:call).todos.first.complete! - Context.find(contexts(:call).id).done_todos.should have(1).items - end - - it 'returns correct number of not done todos' do - contexts(:agenda).todos.not_completed.should have(2).items - contexts(:agenda).todos.last.complete! - contexts(:agenda).todos.not_completed.should have(1).items - end - end -end - -describe NullContext do - before(:each) do - @context = NullContext.new - end - - it 'is nil' do - @context.should be_nil - end - - it 'has no id' do - @context.id.should be_nil - end - - it 'has a blank name' do - @context.name.should be_blank - end -end diff --git a/backup.rails2.3/spec/models/message_gateway_spec.rb b/backup.rails2.3/spec/models/message_gateway_spec.rb deleted file mode 100644 index 188093ee..00000000 --- a/backup.rails2.3/spec/models/message_gateway_spec.rb +++ /dev/null @@ -1,29 +0,0 @@ -require File.dirname(__FILE__) + '/../spec_helper' - -describe MessageGateway do - before :each do - todo = mock_model(Todo, :description= => nil, :raw_notes= => nil, :context_id= => nil, :save! => nil) - - @user = mock_model(User, - :prefs => mock_model(Preference, :sms_context => mock_model(Context)), - :todos => mock('Todo collection', :find => nil, :build => todo), - :contexts => mock('Context collection', :exists? => true, :find => nil)) - - User.stub!(:find).and_return(@user) - end - - def load_message(filename) - MessageGateway.receive(File.read(File.join(RAILS_ROOT, 'test', 'fixtures', filename))) - end - - - it "should dispatch on From: or To: according to site.yml" do - SITE_CONFIG['email_dispatch'] = 'from' - User.should_receive(:find).with(:first, :include => [:preference], :conditions => ["preferences.sms_email = ?", '5555555555@tmomail.net']) - load_message('sample_email.txt') - - SITE_CONFIG['email_dispatch'] = 'to' - User.should_receive(:find).with(:first, :include => [:preference], :conditions => ["preferences.sms_email = ?", 'gtd@tracks.com']) - load_message('sample_email.txt') - end -end diff --git a/backup.rails2.3/spec/models/todo_spec.rb b/backup.rails2.3/spec/models/todo_spec.rb deleted file mode 100644 index b31ab7a2..00000000 --- a/backup.rails2.3/spec/models/todo_spec.rb +++ /dev/null @@ -1,182 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') - -describe Todo do - def valid_attributes(attributes={}) - { - :description => "don't forget the milk", - :context => mock_model(Context, :name => 'errands', :destroyed? => false) - }.merge(attributes) - end - - def create_todo(attributes={}) - todo = Todo.new(valid_attributes(attributes)) - todo.stub!(:user).and_return(mock_model(User, :date => Time.zone.now)) - todo.save! - todo - end - - before(:each) do - @todo = Todo.new - end - - it_should_belong_to :context - it_should_belong_to :project - it_should_belong_to :user - - it_should_validate_presence_of :description - it_should_validate_presence_of :context - it_should_validate_length_of :description, :maximum => 100 - it_should_validate_length_of :notes, :maximum => 60_000 - - it 'validates presence of show_from when deferred' - - it 'ensures that show_from is a date in the future' do - todo = Todo.new(valid_attributes) - todo.stub!(:user).and_return(mock_model(User, :date => Time.zone.now)) - todo.show_from = 3.days.ago - todo.should have(1).error_on(:show_from) - end - - it 'allows show_from to be blank' do - todo = Todo.new(valid_attributes(:show_from => '')) - todo.should_not have(:any).error_on(:show_from) - end - - describe 'states' do - it 'is active on initializing' do - create_todo.should be_active - end - - it 'is deferred when show from is in the future' do - todo = create_todo - todo.show_from = 1.week.from_now - todo.should be_deferred - end - - describe 'active' do - %w(project_hidden completed deferred).each do |from_state| - it "is activable from `#{from_state}'" do - todo = create_todo - todo.state = from_state - todo.send("#{from_state}?").should be_true - todo.activate! - todo.should be_active - end - end - - it 'clears show_from when entering active state' do - todo = create_todo - todo.show_from = 3.days.from_now - todo.should be_deferred - todo.activate! - todo.should be_active - todo.show_from.should be_nil - end - - it 'clears completed_at when entering active state' do - todo = create_todo - todo.complete! - todo.should be_completed - todo.activate! - todo.should be_active - todo.completed_at.should be_nil - end - end - - describe 'completed' do - %w(active project_hidden deferred).each do |from_state| - it "is completable from `#{from_state}'" do - todo = create_todo - todo.state = from_state - todo.send("#{from_state}?").should be_true - todo.complete! - todo.should be_completed - end - end - - it 'sets complated_at' do - todo = create_todo - todo.complete! - todo.completed_at.should_not be_nil - end - end - - describe 'project_hidden' do - %w(active deferred).each do |from_state| - it "is hiddable from `#{from_state}'" do - todo = create_todo - todo.state = from_state - todo.send("#{from_state}?").should be_true - todo.hide! - todo.should be_project_hidden - end - end - - it 'unhides to active when not show_from' do - todo = create_todo(:show_from => '') - todo.hide! - todo.should be_project_hidden - todo.unhide! - todo.should be_active - end - end - end - - describe 'when toggling completion' do - it 'toggles to active when completed' do - todo = create_todo - todo.complete! - todo.should be_completed - todo.toggle_completion! - todo.should be_active - end - - it 'toggles to completed when not completed' do - todo = create_todo - todo.should_not be_completed - todo.toggle_completion! - todo.should be_completed - end - end - - describe 'when retrieving project' do - it 'returns project if set' do - project = mock_model(Project) - todo = Todo.new(:project => project) - todo.project.should == project - end - - it 'returns a NullProject if not set' do - Todo.new.project.should be_an_instance_of(NullProject) - end - end - - describe('when setting show_from') { it 'is speced' } - - it 'is starred if tag is "starred"' do - todo = create_todo - todo.should_not be_starred - todo._add_tags('starred') - todo.reload - todo.should be_starred - end - - describe 'when toggling star flag' do - it 'toggles to not starred when starred' do - todo = create_todo - todo._add_tags('starred') - todo.should be_starred - todo.toggle_star! - todo.reload - todo.should_not be_starred - end - - it 'toggles to starred when not starred' do - todo = create_todo - todo.should_not be_starred - todo.toggle_star! - todo.reload - todo.should be_starred - end - end -end diff --git a/backup.rails2.3/spec/models/user_spec.rb b/backup.rails2.3/spec/models/user_spec.rb deleted file mode 100644 index 035960ad..00000000 --- a/backup.rails2.3/spec/models/user_spec.rb +++ /dev/null @@ -1,168 +0,0 @@ -require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') - -describe User do - def valid_attributes(attributes={}) - { - :login => 'simon', - :password => 'foobarspam', - :password_confirmation => 'foobarspam' - }.merge(attributes) - end - - before(:each) do - @user = User.new - end - - describe 'associations' do - it 'has many contexts' do - User.should have_many(:contexts). - with_order('position ASC'). - with_dependent(:delete_all) - end - - it 'has many projects' do - User.should have_many(:projects). - with_order('projects.position ASC'). - with_dependent(:delete_all) - end - - it 'has many todos' do - User.should have_many(:todos). - with_order('todos.completed_at DESC, todos.created_at DESC'). - with_dependent(:delete_all) - end - - it 'has many deferred todos' do - User.should have_many(:deferred_todos). - with_order('show_from ASC, todos.created_at DESC'). - with_conditions('state = ?', 'deferred'). - with_class_name('Todo') - end - - it 'has many notes' do - User.should have_many(:notes). - with_order('created_at DESC'). - with_dependent(:delete_all) - end - - it 'has one preference' do - User.should have_one(:preference) - end - end - - it_should_validate_presence_of :login - it_should_validate_presence_of :password - it_should_validate_presence_of :password_confirmation - - it_should_validate_length_of :password, :within => 5..40 - it_should_validate_length_of :login, :within => 3..80 - - it_should_validate_uniqueness_of :login - it_should_validate_confirmation_of :password - - it 'validates presence of password only when password is required' - it 'validates presence of password_confirmation only when password is required' - it 'validates confirmation of password only when password is required' - it 'validates presence of open_id_url only when using openid' - - it 'accepts only allow auth_type authorized by the admin' do - Tracks::Config.should_receive(:auth_schemes).exactly(3).times.and_return(%w(database open_id)) - User.new(valid_attributes(:auth_type => 'database')).should_not have(:any).error_on(:auth_type) - User.new(valid_attributes(:auth_type => 'open_id')).should_not have(:any).error_on(:auth_type) - User.new(valid_attributes(:auth_type => 'ldap')).should have(1).error_on(:auth_type) - end - - it 'returns login for #to_param' do - @user.login = 'john' - @user.to_param.should == 'john' - end - - it 'has a custom finder to find admin' do - User.should_receive(:find).with(:first, :conditions => ['is_admin = ?', true]) - User.find_admin - end - - it 'has a custom finder to find by openid url' - it 'knows if there is any user through #no_users_yet? (TODO: better description)' - - describe 'when choosing what do display as a name' do - it 'displays login when no first name and last name' do - User.new(valid_attributes).display_name.should == 'simon' - end - - it 'displays last name when no first name' do - User.new(valid_attributes(:last_name => 'foo')).display_name.should == 'foo' - end - - it 'displays first name when no last name' do - User.new(valid_attributes(:first_name => 'bar')).display_name.should == 'bar' - end - - it 'displays first name and last name when both specified' do - User.new(valid_attributes(:first_name => 'foo', :last_name => 'bar')).display_name.should == 'foo bar' - end - end - - describe 'authentication' do - before(:each) do - @user = User.create!(valid_attributes) - end - - it 'authenticates user' do - User.authenticate('simon', 'foobarspam').id.should be @user.id - end - - it 'resets password' do - @user.update_attributes( - :password => 'new password', - :password_confirmation => 'new password' - ) - User.authenticate('simon', 'foobarspam').should be_nil - User.authenticate('simon', 'new password').id.should be @user.id - end - - it 'does not rehash password after update of login' do - @user.update_attribute(:login, 'foobar') - User.authenticate('foobar', 'foobarspam').id.should be @user.id - end - - it 'sets remember token' do - @user.remember_me - @user.remember_token.should_not be_nil - @user.remember_token_expires_at.should_not be_nil - end - - it 'unsets remember token' do - @user.remember_me - @user.remember_token.should_not be_nil - @user.forget_me - @user.remember_token.should be_nil - end - - it 'remembers me default two weeks' do - before = 2.weeks.from_now.utc - @user.remember_me - after = 2.weeks.from_now.utc - @user.remember_token.should_not be_nil - @user.remember_token_expires_at.should_not be_nil - @user.remember_token_expires_at.should be_between(before, after) - end - end - - it "should not activate todos that are showing when UTC is tomorrow" do - context = Context.create(:name => 'a context') - user = User.create(:login => 'user7', :password => 'foobar', :password_confirmation => 'foobar') - user.save! - user.create_preference - user.preference.update_attribute('time_zone', 'Pacific Time (US & Canada)') -# Time.zone = 'Pacific Time (US & Canada)' - Time.stub!(:now).and_return(Time.new.end_of_day - 20.minutes) - todo = user.todos.build(:description => 'test task', :context => context) - todo.show_from = user.date + 1.days - todo.save! - - user.deferred_todos.find_and_activate_ready - user = User.find(user.id) - user.deferred_todos.should include(todo) - end -end diff --git a/backup.rails2.3/spec/rcov.opts b/backup.rails2.3/spec/rcov.opts deleted file mode 100644 index 274ed51a..00000000 --- a/backup.rails2.3/spec/rcov.opts +++ /dev/null @@ -1,2 +0,0 @@ ---exclude "spec/*,gems/*" ---rails \ No newline at end of file diff --git a/backup.rails2.3/spec/spec.opts b/backup.rails2.3/spec/spec.opts deleted file mode 100644 index 391705bf..00000000 --- a/backup.rails2.3/spec/spec.opts +++ /dev/null @@ -1,4 +0,0 @@ ---colour ---format progress ---loadby mtime ---reverse diff --git a/backup.rails2.3/spec/spec_helper.rb b/backup.rails2.3/spec/spec_helper.rb deleted file mode 100644 index e83f9daa..00000000 --- a/backup.rails2.3/spec/spec_helper.rb +++ /dev/null @@ -1,52 +0,0 @@ -# This file is copied to ~/spec when you run 'ruby script/generate rspec' -# from the project root directory. -ENV["RAILS_ENV"] ||= 'test' -require File.expand_path(File.join(File.dirname(__FILE__),'..','config','environment')) -require 'spec/autorun' -require 'spec/rails' -require 'skinny_spec' - -# Requires supporting files with custom matchers and macros, etc, -# in ./support/ and its subdirectories. -Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f} - -Spec::Runner.configure do |config| - # If you're not using ActiveRecord you should remove these - # lines, delete config/database.yml and disable :active_record - # in your config/boot.rb - config.use_transactional_fixtures = true - config.use_instantiated_fixtures = false - config.fixture_path = RAILS_ROOT + '/spec/fixtures/' - - # == Fixtures - # - # You can declare fixtures for each example_group like this: - # describe "...." do - # fixtures :table_a, :table_b - # - # Alternatively, if you prefer to declare them only once, you can - # do so right here. Just uncomment the next line and replace the fixture - # names with your fixtures. - # - # config.global_fixtures = :table_a, :table_b - # - # If you declare global fixtures, be aware that they will be declared - # for all of your examples, even those that don't use them. - # - # You can also declare which fixtures to use (for example fixtures for test/fixtures): - # - # config.fixture_path = RAILS_ROOT + '/spec/fixtures/' - # - # == Mock Framework - # - # RSpec uses it's own mocking framework by default. If you prefer to - # use mocha, flexmock or RR, uncomment the appropriate line: - # - # config.mock_with :mocha - # config.mock_with :flexmock - # config.mock_with :rr - # - # == Notes - # - # For more information take a look at Spec::Runner::Configuration and Spec::Runner -end diff --git a/backup.rails2.3/spec/support/should_validate_length_of.rb b/backup.rails2.3/spec/support/should_validate_length_of.rb deleted file mode 100644 index ae7b5a1a..00000000 --- a/backup.rails2.3/spec/support/should_validate_length_of.rb +++ /dev/null @@ -1,25 +0,0 @@ -module LuckySneaks - module ModelSpecHelpers - module ExampleGroupLevelMethods - def it_should_validate_length_of(attribute, options={}) - maximum = options[:maximum] || (options[:within] || []).last || false - minimum = options[:minimum] || (options[:within] || []).first || false - raise ArgumentError unless maximum || minimum - - it "should not be valid if #{attribute} length is more than #{maximum}" do - instance.send "#{attribute}=", 'x'*(maximum+1) - instance.errors_on(attribute).should include( - options[:message_too_long] || I18n.t('activerecord.errors.messages.too_long', :count => maximum) - ) - end if maximum - - it "should not be valid if #{attribute} length is less than #{minimum}" do - instance.send "#{attribute}=", 'x'*(minimum-1) - instance.errors_on(attribute).should include( - options[:message_to_short] || I18n.t('activerecord.errors.messages.too_short', :count => minimum) - ) - end if minimum - end - end - end -end diff --git a/backup.rails2.3/spec/views/login/login_mobile.html.erb_spec.rb b/backup.rails2.3/spec/views/login/login_mobile.html.erb_spec.rb deleted file mode 100644 index b3bce82d..00000000 --- a/backup.rails2.3/spec/views/login/login_mobile.html.erb_spec.rb +++ /dev/null @@ -1,9 +0,0 @@ -require File.dirname(__FILE__) + '/../../spec_helper' - -describe "/login/login_mobile.html.erb" do - it "should render without an error" do - @controller.template.stub!(:set_default_external!) - render :action => 'login/login_mobile.html.erb', :layout => 'mobile.m.erb' - response.should_not have_tag("div#Application-Trace") - end -end diff --git a/backup.rails2.3/spec/views/notes/_notes.rhtml_spec.rb b/backup.rails2.3/spec/views/notes/_notes.rhtml_spec.rb deleted file mode 100644 index 477e66b5..00000000 --- a/backup.rails2.3/spec/views/notes/_notes.rhtml_spec.rb +++ /dev/null @@ -1,39 +0,0 @@ -require File.dirname(__FILE__) + '/../../spec_helper' - -describe "/notes/_notes.rhtml" do - before :each do - @project = mock_model(Project, :name => "a project") - @note = mock_model(Note, :body => "this is a note", :project => @project, :project_id => @project.id, - :created_at => Time.now, :updated_at? => false) - @controller.template.stub!(:format_date) - # @controller.template.stub!(:render) - # @controller.template.stub!(:form_remote_tag) - end - - it "should render" do - pending "figure out how to mock or work with with UJS" - render :partial => "/notes/notes", :object => @note - response.should have_tag("div.note_footer") - end - - it "should auto-link URLs" do - pending "figure out how to mock or work with with UJS" - @note.stub!(:body).and_return("http://www.google.com/") - render :partial => "/notes/notes", :object => @note - response.should have_tag("a[href=\"http://www.google.com/\"]") - end - - it "should auto-link embedded URLs" do - pending "figure out how to mock or work with with UJS" - @note.stub!(:body).and_return("this is cool: http://www.google.com/") - render :partial => "/notes/notes", :object => @note - response.should have_tag("a[href=\"http://www.google.com/\"]") - end - - it "should parse Textile links correctly" do - pending "figure out how to mock or work with with UJS" - @note.stub!(:body).and_return("\"link\":http://www.google.com/") - render :partial => "/notes/notes", :locals => {:notes => @note} - response.should have_tag("a[href=\"http://www.google.com/\"]") - end -end diff --git a/backup.rails2.3/test_helper.rb.rails2 b/backup.rails2.3/test_helper.rb.rails2 deleted file mode 100644 index 40d8a464..00000000 --- a/backup.rails2.3/test_helper.rb.rails2 +++ /dev/null @@ -1,152 +0,0 @@ -ENV["RAILS_ENV"] = "test" -require 'thread' -require File.expand_path(File.dirname(__FILE__) + "/../config/environment") -require File.expand_path(File.dirname(__FILE__) + "/../app/controllers/application_controller") -require 'test_help' -require 'flexmock/test_unit' #and the flexmock gem, too! -require 'action_web_service/test_invoke' - -module Tracks - class Config - def self.salt - "change-me" - end - def self.auth_schemes - return ["database","open_id"] - end - end -end - -class Test::Unit::TestCase - include AuthenticatedTestHelper - - def xml_document - @xml_document ||= HTML::Document.new(@response.body, false, true) - end - - def assert_xml_select(*args, &block) - @html_document = xml_document - assert_select(*args, &block) - end - - def assert_error_on(model_instance, attribute, expected_error) - actual_error = model_instance.errors.on attribute.to_sym - assert_equal expected_error, actual_error - end - - alias_method :assert_errors_on, :assert_error_on - - def assert_value_changed(object, method = nil) - initial_value = object.send(method) - yield - assert_not_equal initial_value, object.send(method), "#{object}##{method}" - end - -end - -class ActiveSupport::TestCase - - # Generates a random string of ascii characters (a-z, "1 0") - # of a given length for testing assignment to fields - # for validation purposes - # - def generate_random_string(length) - string = "" - characters = %w(a b c d e f g h i j k l m n o p q r s t u v w z y z 1\ 0) - length.times do - pick = characters[rand(26)] - string << pick - end - return string - end - - def next_week - 1.week.from_now.utc - end - - # Courtesy of http://habtm.com/articles/2006/02/20/assert-yourself-man-redirecting-with-rjs - def assert_js_redirected_to(options={}, message=nil) - clean_backtrace do - assert_response(:success, message) - assert_equal 'text/javascript', @response.content_type, 'Response should be Javascript content-type'; - js_regexp = %r{(\w+://)?.*?(/|$|\\\?)(.*)} - url_regexp = %r{^window\.location\.href [=] ['"]#{js_regexp}['"][;]$} - redirected_to = @response.body.match(url_regexp) - assert_not_nil(redirected_to, message) - redirected_to = redirected_to[3] - msg = build_message(message, "expected a JS redirect to , found one to ", options, redirected_to) - - if options.is_a?(String) - assert_equal(options.gsub(/^\//, ''), redirected_to, message) - elsif options.is_a?(Regexp) - assert(options =~ redirected_to, "#{message} #{options} #{redirected_to}") - else - msg = build_message(message, "response is not a redirection to all of the options supplied (redirection is )", redirected_to) - assert_equal(@controller.url_for(options).match(js_regexp)[3], redirected_to, msg) - end - end - end - - def set_user_to_current_time_zone(user) - jan_offset = Time.now.beginning_of_year.utc_offset - jul_offset = Time.now.beginning_of_year.change(:month => 7).utc_offset - offset = jan_offset < jul_offset ? jan_offset : jul_offset - offset = if offset.to_s.match(/(\+|-)?(\d+):(\d+)/) - sign = $1 == '-' ? -1 : 1 - hours, minutes = $2.to_f, $3.to_f - ((hours * 3600) + (minutes.to_f * 60)) * sign - elsif offset.to_f.abs <= 13 - offset.to_f * 3600 - else - offset.to_f - end - zone = ActiveSupport::TimeZone.all.find{|t| t.utc_offset == offset} - user.prefs.update_attribute(:time_zone, zone.name) - end -end - -class ActionController::IntegrationTest - Tag #avoid errors in integration tests - - def assert_test_environment_ok - assert_equal "test", ENV['RAILS_ENV'] - assert_equal "change-me", Tracks::Config.salt - end - - def authenticated_post_xml(url, username, password, parameters, headers = {}) - post url, - parameters, - {'AUTHORIZATION' => "Basic " + Base64.encode64("#{username}:#{password}"), - 'ACCEPT' => 'application/xml', - 'CONTENT_TYPE' => 'application/xml' - }.merge(headers) - end - - def authenticated_get_xml(url, username, password, parameters, headers = {}) - get url, - parameters, - {'AUTHORIZATION' => "Basic " + Base64.encode64("#{username}:#{password}"), - 'ACCEPT' => 'application/xml', - 'CONTENT_TYPE' => 'application/xml' - }.merge(headers) - end - - def assert_response_and_body(type, body, message = nil) - assert_equal body, @response.body, message - assert_response type, message - end - - def assert_response_and_body_matches(type, body_regex, message = nil) - assert_response type, message - assert_match body_regex, @response.body, message - end - - def assert_401_unauthorized - assert_response_and_body 401, "401 Unauthorized: You are not authorized to interact with Tracks." - end - - def assert_401_unauthorized_admin - assert_response_and_body 401, "401 Unauthorized: Only admin users are allowed access to this function." - end - -end diff --git a/backup.rails2.3/test_views/views/context_helper_test.rb b/backup.rails2.3/test_views/views/context_helper_test.rb deleted file mode 100644 index 8aa0bd4b..00000000 --- a/backup.rails2.3/test_views/views/context_helper_test.rb +++ /dev/null @@ -1,7 +0,0 @@ - def test_summary - undone_todo_count = '5 actions' - assert_equal "

#{undone_todo_count}. Context is Active.

", @agenda.summary(undone_todo_count) - @agenda.hide = true - @agenda.save! - assert_equal "

#{undone_todo_count}. Context is Hidden.

", @agenda.summary(undone_todo_count) - end diff --git a/backup.rails2.3/test_views/views/todos_helper_test.rb b/backup.rails2.3/test_views/views/todos_helper_test.rb deleted file mode 100644 index 441ec2b5..00000000 --- a/backup.rails2.3/test_views/views/todos_helper_test.rb +++ /dev/null @@ -1,98 +0,0 @@ -require File.dirname(__FILE__) + '/../test_helper' - -class TodosHelperTest < ActiveSupport::HelperTestCase - fixtures :users - - def setup - super - end - - include ActionView::Helpers::DateHelper - include ApplicationHelper - include TodosHelper - - def current_user - if @user.nil? - @user = users(:admin_user) - class << @user - def prefs - Preference.new - end - end - end - @user - end - - def format_date(date) - if date - date_format = "%d/%m/%Y" - date.strftime("#{date_format}") - else - '' - end - end - - def test_show_date_in_past - date = 3.days.ago - html = show_date(date) - formatted_date = format_date(date) - assert_equal %Q{Scheduled to show 3 days ago }, html - end - - def test_show_date_today - date = Time.zone.now - html = show_date(date) - formatted_date = format_date(date) - assert_equal %Q{Show Today }, html - end - - def test_show_date_tomorrow - date = 1.day.from_now - html = show_date(date) - formatted_date = format_date(date) - assert_equal %Q{Show Tomorrow }, html - end - - def test_show_date_future - date = 10.days.from_now - html = show_date(date) - formatted_date = format_date(date) - assert_equal %Q{Show in 10 days }, html - end - - def test_remote_star_icon_unstarred - @todo = flexmock(:id => 1, :to_param => 1, :description => 'Get gas', :starred? => false) - # added dot (.) to regexp because somehouw the extra dot is added in the tests while its not in the rendered html - assert_remote_star_icon_helper_matches %r{Blank} - assert_behavior_registered - end - - def test_remote_star_icon_starred - @todo = flexmock(:id => 1, :to_param => 1, :description => 'Get gas', :starred? => true) - # added dot (.) to regexp because somehouw the extra dot is added in the tests while its not in the rendered html - assert_remote_star_icon_helper_matches %r{Blank} - assert_behavior_registered - end - - def assert_remote_star_icon_helper_matches(regex) - @controller.send :initialise_js_behaviours #simulate before filter - output = remote_star_icon - # puts output - assert output =~ regex - @controller.send :store_js_behaviours #simulate after filter - end - - def assert_behavior_registered - behaviors = @controller.session[:js_behaviours] - assert behaviors[:options][:reapply_after_ajax] - assert_equal 1, behaviors[:rules].length - rule = behaviors[:rules][0] - assert_equal ".item-container a.star_item:click", rule[0] - assert_equal "new Ajax.Request(this.href, {asynchronous:true, evalScripts:true, method:'put', parameters:{ _source_view : '' }})\n; return false;", - rule[1] - end - - def protect_against_forgery? - false - end -end