From 4d6da89fb12377ad7253f55d1982a399a9564672 Mon Sep 17 00:00:00 2001 From: Novikov Andrey Date: Wed, 14 Mar 2012 11:03:36 +1000 Subject: [PATCH] Upgrade to Ruby on Rails 3.0 --- Gemfile | 7 +- Gemfile.lock | 132 +- Rakefile | 7 +- app/controllers/application_controller.rb | 11 +- .../dept_head/disciplines_controller.rb | 2 +- .../dept_head/specialities_controller.rb | 4 +- .../dept_head/teaching_places_controller.rb | 2 +- .../editor/groups/charge_cards_controller.rb | 4 +- .../reference/charge_cards_controller.rb | 4 +- .../reference/departments_controller.rb | 10 +- .../reference/disciplines_controller.rb | 8 +- .../reference/teaching_places_controller.rb | 11 +- .../supervisor/departments_controller.rb | 2 +- .../supervisor/faculties_controller.rb | 2 +- .../supervisor/specialities_controller.rb | 2 +- .../supervisor/teaching_plans_controller.rb | 2 +- app/models/charge_card.rb | 12 +- app/models/classroom.rb | 2 +- app/models/group.rb | 15 +- app/models/lecturer.rb | 2 +- app/models/pair.rb | 6 +- .../{ => devise}/confirmations/new.html.erb | 4 +- .../confirmation_instructions.html.erb | 0 .../reset_password_instructions.html.erb | 0 .../unlock_instructions.html.erb | 0 .../{ => devise}/passwords/edit.html.erb | 4 +- app/views/{ => devise}/passwords/new.html.erb | 4 +- .../{ => devise}/registrations/edit.html.erb | 2 +- .../{ => devise}/registrations/new.html.erb | 2 +- app/views/{ => devise}/sessions/new.html.erb | 4 +- app/views/{ => devise}/unlocks/new.html.erb | 4 +- .../classrooms/pairs/_pair_edit.html.haml | 2 +- app/views/editor/classrooms/pairs/edit.js.erb | 1 - .../editor/groups/pairs/_pair_edit.html.haml | 2 +- app/views/editor/groups/pairs/edit.js.erb | 1 - config.ru | 4 + config/application.rb | 51 + config/boot.rb | 127 +- config/environment.rb | 40 +- config/environments/development.rb | 32 +- config/environments/production.rb | 59 +- config/environments/test.rb | 48 +- config/initializers/active_scaffold.rb | 9 + config/initializers/devise.rb | 4 +- config/initializers/new_rails_defaults.rb | 21 - config/initializers/secret_token.rb | 7 + config/initializers/session_store.rb | 11 +- config/routes.rb | 220 +- db/schema.rb | 13 +- lib/tasks/.gitkeep | 0 .../active_scaffold/default/close_touch.png | Bin 0 -> 391 bytes .../images/active_scaffold/default/config.png | Bin 0 -> 714 bytes .../images/active_scaffold/default/gears.png | Bin 0 -> 1741 bytes .../default/active_scaffold.js | 759 ++- .../active_scaffold/default/dhtml_history.js | 157 +- public/javascripts/controls.js | 8 +- public/javascripts/dragdrop.js | 13 +- public/javascripts/editors/classrooms.js | 2 +- public/javascripts/editors/groups.js | 2 +- public/javascripts/effects.js | 21 +- public/javascripts/prototype.js | 5081 +++++++++++------ public/javascripts/rails.js | 202 + .../record_select/record_select.js | 29 +- public/stylesheets/.gitkeep | 0 .../active_scaffold/default/stylesheet.css | 298 +- .../record_select/record_select.css | 4 + script/about | 4 - script/console | 3 - script/dbconsole | 3 - script/destroy | 3 - script/generate | 3 - script/performance/benchmarker | 3 - script/performance/profiler | 3 - script/plugin | 3 - script/rails | 6 + script/runner | 3 - script/server | 3 - test/performance/browsing_test.rb | 4 +- test/test_helper.rb | 29 +- vendor/plugins/.gitkeep | 0 vendor/plugins/active_scaffold/.autotest | 27 - vendor/plugins/active_scaffold/CHANGELOG | 152 - vendor/plugins/active_scaffold/MIT-LICENSE | 20 - vendor/plugins/active_scaffold/README | 41 - vendor/plugins/active_scaffold/Rakefile | 24 - vendor/plugins/active_scaffold/environment.rb | 17 - .../frontends/default/images/add.gif | Bin 986 -> 0 bytes .../frontends/default/images/arrow_down.gif | Bin 853 -> 0 bytes .../frontends/default/images/arrow_up.gif | Bin 851 -> 0 bytes .../frontends/default/images/close.gif | Bin 960 -> 0 bytes .../frontends/default/images/cross.png | Bin 655 -> 0 bytes .../default/images/indicator-small.gif | Bin 592 -> 0 bytes .../frontends/default/images/indicator.gif | Bin 725 -> 0 bytes .../frontends/default/images/magnifier.png | Bin 615 -> 0 bytes .../default/javascripts/active_scaffold.js | 532 -- .../default/javascripts/dhtml_history.js | 867 --- .../default/javascripts/form_enhancements.js | 117 - .../default/javascripts/rico_corner.js | 370 -- .../default/stylesheets/stylesheet-ie.css | 35 - .../default/stylesheets/stylesheet.css | 845 --- .../default/views/_add_existing_form.html.erb | 36 - .../default/views/_create_form.html.erb | 52 - .../views/_create_form_on_list.html.erb | 38 - .../default/views/_field_search.html.erb | 40 - .../frontends/default/views/_form.html.erb | 18 - .../default/views/_form_association.html.erb | 15 - .../views/_form_association_footer.html.erb | 40 - .../default/views/_form_attribute.html.erb | 15 - .../views/_form_hidden_attribute.html.erb | 2 - .../default/views/_form_messages.html.erb | 5 - .../views/_horizontal_subform.html.erb | 19 - .../views/_horizontal_subform_header.html.erb | 10 - .../views/_horizontal_subform_record.html.erb | 31 - .../frontends/default/views/_list.html.erb | 23 - .../default/views/_list_actions.html.erb | 26 - .../default/views/_list_calculations.html.erb | 15 - .../views/_list_column_headings.html.erb | 32 - .../default/views/_list_header.html.erb | 14 - .../views/_list_inline_adapter.html.erb | 10 - .../default/views/_list_messages.html.erb | 20 - .../default/views/_list_pagination.html.erb | 11 - .../views/_list_pagination_links.html.erb | 28 - .../default/views/_list_record.html.erb | 11 - .../views/_list_record_columns.html.erb | 9 - .../default/views/_messages.html.erb | 10 - .../frontends/default/views/_nested.html.erb | 35 - .../default/views/_render_fields.js.rjs | 11 - .../frontends/default/views/_search.html.erb | 27 - .../frontends/default/views/_show.html.erb | 8 - .../default/views/_show_columns.html.erb | 12 - .../default/views/_update_actions.html.erb | 9 - .../default/views/_update_form.html.erb | 56 - .../default/views/_vertical_subform.html.erb | 12 - .../views/_vertical_subform_record.html.erb | 33 - .../default/views/add_existing.js.rjs | 17 - .../default/views/add_existing_form.html.erb | 5 - .../frontends/default/views/create.html.erb | 5 - .../frontends/default/views/delete.html.erb | 13 - .../frontends/default/views/destroy.js.rjs | 10 - .../default/views/edit_associated.js.rjs | 20 - .../default/views/field_search.html.erb | 5 - .../default/views/form_messages.js.rjs | 1 - .../frontends/default/views/list.html.erb | 48 - .../frontends/default/views/list.js.rjs | 1 - .../frontends/default/views/mark.js.rjs | 6 - .../frontends/default/views/on_create.js.rjs | 29 - .../frontends/default/views/on_update.js.rjs | 18 - .../default/views/render_field.js.rjs | 1 - .../frontends/default/views/search.html.erb | 5 - .../frontends/default/views/show.html.erb | 5 - .../frontends/default/views/update.html.erb | 8 - .../default/views/update_column.js.rjs | 13 - .../frontends/default/views/update_row.js.rjs | 2 - vendor/plugins/active_scaffold/init.rb | 18 - vendor/plugins/active_scaffold/install.rb | 39 - .../plugins/active_scaffold/install_assets.rb | 36 - .../lib/active_record_permissions.rb | 134 - .../active_scaffold/lib/active_scaffold.rb | 217 - .../active_scaffold/actions/common_search.rb | 18 - .../lib/active_scaffold/actions/core.rb | 152 - .../lib/active_scaffold/actions/create.rb | 152 - .../lib/active_scaffold/actions/delete.rb | 73 - .../active_scaffold/actions/field_search.rb | 60 - .../lib/active_scaffold/actions/list.rb | 82 - .../lib/active_scaffold/actions/mark.rb | 72 - .../lib/active_scaffold/actions/nested.rb | 217 - .../lib/active_scaffold/actions/search.rb | 54 - .../lib/active_scaffold/actions/show.rb | 54 - .../lib/active_scaffold/actions/subform.rb | 17 - .../lib/active_scaffold/actions/update.rb | 129 - .../lib/active_scaffold/attribute_params.rb | 191 - .../lib/active_scaffold/config/base.rb | 62 - .../lib/active_scaffold/config/core.rb | 229 - .../lib/active_scaffold/config/create.rb | 36 - .../lib/active_scaffold/config/delete.rb | 24 - .../active_scaffold/config/field_search.rb | 55 - .../lib/active_scaffold/config/form.rb | 42 - .../lib/active_scaffold/config/list.rb | 171 - .../lib/active_scaffold/config/nested.rb | 32 - .../lib/active_scaffold/config/search.rb | 72 - .../lib/active_scaffold/config/show.rb | 32 - .../lib/active_scaffold/config/subform.rb | 35 - .../lib/active_scaffold/config/update.rb | 36 - .../lib/active_scaffold/configurable.rb | 29 - .../lib/active_scaffold/constraints.rb | 173 - .../data_structures/action_columns.rb | 101 - .../data_structures/action_link.rb | 146 - .../data_structures/action_links.rb | 47 - .../data_structures/actions.rb | 45 - .../active_scaffold/data_structures/column.rb | 336 -- .../data_structures/columns.rb | 75 - .../data_structures/error_message.rb | 24 - .../active_scaffold/data_structures/set.rb | 57 - .../data_structures/sorting.rb | 159 - .../lib/active_scaffold/finder.rb | 303 - .../helpers/association_helpers.rb | 40 - .../helpers/controller_helpers.rb | 40 - .../helpers/country_helpers.rb | 352 -- .../helpers/form_column_helpers.rb | 338 -- .../lib/active_scaffold/helpers/id_helpers.rb | 125 - .../helpers/list_column_helpers.rb | 371 -- .../helpers/pagination_helpers.rb | 63 - .../helpers/search_column_helpers.rb | 211 - .../helpers/show_column_helpers.rb | 53 - .../active_scaffold/helpers/view_helpers.rb | 230 - .../lib/active_scaffold/locale/de.yml | 69 - .../lib/active_scaffold/locale/en.yml | 72 - .../lib/active_scaffold/locale/es.yml | 74 - .../lib/active_scaffold/locale/fr.yml | 68 - .../lib/active_scaffold/locale/hu.yml | 68 - .../lib/active_scaffold/locale/ja.yml | 69 - .../lib/active_scaffold/locale/ru.yml | 72 - .../lib/active_scaffold/marked_model.rb | 38 - .../active_scaffold/lib/bridges/bridge.rb | 52 - .../bridges/calendar_date_select/bridge.rb | 11 - .../calendar_date_select/lib/as_cds_bridge.rb | 87 - .../lib/bridges/dependent_protect/bridge.rb | 10 - .../lib/dependent_protect_bridge.rb | 11 - .../lib/bridges/file_column/bridge.rb | 12 - .../file_column/lib/as_file_column_bridge.rb | 46 - .../file_column/lib/file_column_helpers.rb | 51 - .../lib/bridges/file_column/lib/form_ui.rb | 32 - .../lib/bridges/file_column/lib/list_ui.rb | 26 - .../test/functional/file_column_keep_test.rb | 43 - .../bridges/file_column/test/mock_model.rb | 9 - .../bridges/file_column/test/test_helper.rb | 15 - .../lib/bridges/paperclip/bridge.rb | 13 - .../lib/bridges/paperclip/lib/form_ui.rb | 20 - .../lib/bridges/paperclip/lib/list_ui.rb | 16 - .../bridges/paperclip/lib/paperclip_bridge.rb | 32 - .../paperclip/lib/paperclip_bridge_helpers.rb | 18 - .../lib/bridges/record_select/bridge.rb | 5 - .../record_select/lib/record_select_bridge.rb | 79 - .../lib/bridges/semantic_attributes/bridge.rb | 5 - .../lib/semantic_attributes_bridge.rb | 20 - .../lib/bridges/tiny_mce/bridge.rb | 5 - .../bridges/tiny_mce/lib/tiny_mce_bridge.rb | 57 - .../bridges/unobtrusive_date_picker/bridge.rb | 9 - .../unobtrusive_date_picker/lib/form_ui.rb | 14 - .../lib/unobtrusive_date_picker_bridge.rb | 15 - .../lib/view_helpers.rb | 16 - .../bridges/validation_reflection/bridge.rb | 9 - .../lib/validation_reflection_bridge.rb | 19 - .../active_scaffold/lib/dhtml_confirm.rb | 54 - .../extensions/action_controller_rendering.rb | 20 - .../lib/extensions/action_view_rendering.rb | 99 - .../active_scaffold/lib/extensions/array.rb | 7 - .../component_response_with_namespacing.rb | 17 - .../lib/extensions/generic_view_paths.rb | 33 - .../lib/extensions/localize.rb | 10 - .../lib/extensions/nil_id_in_url_params.rb | 7 - .../lib/extensions/paginator_extensions.rb | 26 - .../lib/extensions/resources.rb | 27 - .../lib/extensions/reverse_associations.rb | 62 - .../lib/extensions/to_label.rb | 8 - .../lib/extensions/unsaved_associated.rb | 61 - .../lib/extensions/unsaved_record.rb | 20 - .../lib/extensions/usa_state.rb | 46 - .../plugins/active_scaffold/lib/paginator.rb | 136 - .../active_scaffold/lib/responds_to_parent.rb | 68 - .../plugins/active_scaffold/public/blank.html | 33 - .../active_scaffold/shoulda_macros/macros.rb | 136 - .../active_scaffold_dependent_protect_test.rb | 34 - .../test/bridges/bridge_test.rb | 90 - .../active_scaffold/test/bridges/company.rb | 81 - .../test/bridges/paperclip_test.rb | 68 - .../test/bridges/tiny_mce_test.rb | 27 - .../bridges/unobtrusive_date_picker_test.rb | 49 - .../bridges/validation_reflection_test.rb | 57 - .../active_scaffold/test/config/base_test.rb | 15 - .../active_scaffold/test/config/core_test.rb | 58 - .../test/config/create_test.rb | 58 - .../test/config/delete_test.rb | 33 - .../test/config/field_search_test.rb | 47 - .../active_scaffold/test/config/list_test.rb | 129 - .../test/config/nested_test.rb | 44 - .../test/config/search_test.rb | 60 - .../active_scaffold/test/config/show_test.rb | 43 - .../test/config/subform_test.rb | 17 - .../test/config/update_test.rb | 40 - .../active_scaffold/test/const_mocker.rb | 36 - .../data_structures/action_columns_test.rb | 113 - .../test/data_structures/action_link_test.rb | 78 - .../test/data_structures/action_links_test.rb | 78 - .../test/data_structures/actions_test.rb | 25 - .../association_column_test.rb | 42 - .../test/data_structures/column_test.rb | 185 - .../test/data_structures/columns_test.rb | 69 - .../data_structures/error_message_test.rb | 28 - .../test/data_structures/set_test.rb | 86 - .../test/data_structures/sorting_test.rb | 126 - .../data_structures/standard_column_test.rb | 24 - .../data_structures/virtual_column_test.rb | 23 - .../test/extensions/active_record_test.rb | 45 - .../test/extensions/array_test.rb | 12 - .../test/helpers/form_column_helpers_test.rb | 31 - .../test/helpers/list_column_helpers_test.rb | 42 - .../test/helpers/pagination_helpers_test.rb | 59 - .../misc/active_record_permissions_test.rb | 154 - .../test/misc/attribute_params_test.rb | 146 - .../test/misc/configurable_test.rb | 96 - .../test/misc/constraints_test.rb | 193 - .../active_scaffold/test/misc/finder_test.rb | 92 - .../active_scaffold/test/misc/lang_test.rb | 11 - .../active_scaffold/test/mock_app/.gitignore | 2 - .../app/controllers/application_controller.rb | 10 - .../app/helpers/application_helper.rb | 3 - .../test/mock_app/config/boot.rb | 110 - .../test/mock_app/config/database.yml | 16 - .../test/mock_app/config/environment.rb | 43 - .../config/environments/development.rb | 17 - .../config/environments/production.rb | 28 - .../test/mock_app/config/environments/test.rb | 28 - .../initializers/backtrace_silencers.rb | 7 - .../config/initializers/inflections.rb | 10 - .../config/initializers/mime_types.rb | 5 - .../config/initializers/new_rails_defaults.rb | 19 - .../config/initializers/session_store.rb | 15 - .../test/mock_app/config/locales/en.yml | 5 - .../test/mock_app/config/routes.rb | 43 - .../test/mock_app/db/test.sqlite3 | 1 - .../test/mock_app/public/blank.html | 33 - .../public/images/active_scaffold/DO_NOT_EDIT | 2 - .../images/active_scaffold/default/add.gif | Bin 986 -> 0 bytes .../active_scaffold/default/arrow_down.gif | Bin 853 -> 0 bytes .../active_scaffold/default/arrow_up.gif | Bin 851 -> 0 bytes .../images/active_scaffold/default/close.gif | Bin 960 -> 0 bytes .../images/active_scaffold/default/cross.png | Bin 655 -> 0 bytes .../default/indicator-small.gif | Bin 592 -> 0 bytes .../active_scaffold/default/indicator.gif | Bin 725 -> 0 bytes .../active_scaffold/default/magnifier.png | Bin 615 -> 0 bytes .../javascripts/active_scaffold/DO_NOT_EDIT | 2 - .../default/active_scaffold.js | 532 -- .../active_scaffold/default/dhtml_history.js | 867 --- .../default/form_enhancements.js | 117 - .../active_scaffold/default/rico_corner.js | 370 -- .../stylesheets/active_scaffold/DO_NOT_EDIT | 2 - .../active_scaffold/default/stylesheet-ie.css | 35 - .../active_scaffold/default/stylesheet.css | 849 --- .../active_scaffold/test/model_stub.rb | 55 - .../plugins/active_scaffold/test/run_all.rb | 8 - .../active_scaffold/test/test_helper.rb | 39 - vendor/plugins/active_scaffold/uninstall.rb | 13 - vendor/plugins/rails_xss/MIT-LICENSE | 20 - vendor/plugins/rails_xss/README.markdown | 90 - vendor/plugins/rails_xss/Rakefile | 23 - vendor/plugins/rails_xss/init.rb | 7 - vendor/plugins/rails_xss/lib/rails_xss.rb | 3 - .../rails_xss/lib/rails_xss/action_view.rb | 87 - .../plugins/rails_xss/lib/rails_xss/erubis.rb | 33 - .../rails_xss/lib/rails_xss/string_ext.rb | 52 - .../rails_xss/lib/tasks/rails_xss_tasks.rake | 4 - .../test/active_record_helper_test.rb | 74 - .../rails_xss/test/asset_tag_helper_test.rb | 49 - vendor/plugins/rails_xss/test/caching_test.rb | 43 - .../rails_xss/test/date_helper_test.rb | 29 - .../test/deprecated_output_safety_test.rb | 112 - .../plugins/rails_xss/test/erb_util_test.rb | 36 - .../rails_xss/test/form_helper_test.rb | 1447 ----- .../rails_xss/test/form_tag_helper_test.rb | 354 -- .../rails_xss/test/output_safety_test.rb | 115 - .../plugins/rails_xss/test/rails_xss_test.rb | 23 - vendor/plugins/rails_xss/test/test_helper.rb | 5 - .../rails_xss/test/text_helper_test.rb | 17 - vendor/plugins/recordselect/CHANGELOG | 25 - vendor/plugins/recordselect/MIT-LICENSE | 20 - vendor/plugins/recordselect/README | 11 - vendor/plugins/recordselect/Rakefile | 23 - .../app/helpers/record_select_helper.rb | 187 - .../app/views/record_select/_browse.html.erb | 8 - .../app/views/record_select/_list.html.erb | 31 - .../app/views/record_select/_search.html.erb | 14 - .../app/views/record_select/browse.js.rjs | 4 - .../recordselect/assets/images/cross.gif | Bin 545 -> 0 bytes .../recordselect/assets/images/next.gif | Bin 302 -> 0 bytes .../recordselect/assets/images/previous.gif | Bin 303 -> 0 bytes .../assets/javascripts/record_select.js | 352 -- .../assets/stylesheets/record_select.css | 129 - vendor/plugins/recordselect/init.rb | 16 - vendor/plugins/recordselect/install.rb | 1 - .../lib/extensions/active_record.rb | 9 - .../plugins/recordselect/lib/localization.rb | 8 - .../plugins/recordselect/lib/record_select.rb | 36 - .../recordselect/lib/record_select/actions.rb | 68 - .../lib/record_select/conditions.rb | 91 - .../recordselect/lib/record_select/config.rb | 91 - .../lib/record_select/form_builder.rb | 25 - .../recordselect/test/recordselect_test.rb | 8 - vendor/plugins/recordselect/uninstall.rb | 4 - vendor/plugins/render_component/README | 37 - vendor/plugins/render_component/Rakefile | 22 - vendor/plugins/render_component/init.rb | 2 - .../render_component/lib/components.rb | 141 - .../render_component/test/abstract_unit.rb | 8 - .../render_component/test/components_test.rb | 136 - vendor/plugins/russian/CHANGELOG | 98 - vendor/plugins/russian/LICENSE | 20 - vendor/plugins/russian/README.textile | 297 - vendor/plugins/russian/Rakefile | 55 - vendor/plugins/russian/TODO | 10 - vendor/plugins/russian/init.rb | 3 - vendor/plugins/russian/lib/russian.rb | 119 - .../action_view_ext/helpers/date_helper.rb | 112 - .../active_record_ext/custom_error_message.rb | 163 - .../active_support_ext/parameterize.rb | 31 - .../russian/lib/russian/backend/advanced.rb | 132 - .../russian/lib/russian/locale/actionview.yml | 162 - .../lib/russian/locale/activerecord.yml | 95 - .../lib/russian/locale/activesupport.yml | 16 - .../russian/lib/russian/locale/datetime.yml | 46 - .../russian/lib/russian/locale/pluralize.rb | 25 - .../russian/lib/russian/transliteration.rb | 72 - .../russian/lib/vendor/i18n/.gitignore | 3 - .../russian/lib/vendor/i18n/MIT-LICENSE | 20 - .../russian/lib/vendor/i18n/README.textile | 20 - .../plugins/russian/lib/vendor/i18n/Rakefile | 5 - .../russian/lib/vendor/i18n/i18n.gemspec | 27 - .../russian/lib/vendor/i18n/lib/i18n.rb | 199 - .../vendor/i18n/lib/i18n/backend/simple.rb | 214 - .../lib/vendor/i18n/lib/i18n/exceptions.rb | 53 - .../russian/lib/vendor/i18n/test/all.rb | 5 - .../vendor/i18n/test/i18n_exceptions_test.rb | 100 - .../russian/lib/vendor/i18n/test/i18n_test.rb | 125 - .../russian/lib/vendor/i18n/test/locale/en.rb | 1 - .../lib/vendor/i18n/test/locale/en.yml | 3 - .../vendor/i18n/test/simple_backend_test.rb | 568 -- .../lib/vendor/i18n_label/README.textile | 38 - .../russian/lib/vendor/i18n_label/Rakefile | 11 - .../russian/lib/vendor/i18n_label/init.rb | 1 - .../russian/lib/vendor/i18n_label/install.rb | 1 - .../lib/vendor/i18n_label/lib/i18n_label.rb | 23 - .../vendor/i18n_label/spec/i18n_label_spec.rb | 20 - .../lib/vendor/i18n_label/spec/spec_helper.rb | 10 - .../i18n_label/tasks/i18n_label_tasks.rake | 4 - .../lib/vendor/i18n_label/uninstall.rb | 1 - vendor/plugins/russian/russian.gemspec | 29 - vendor/plugins/russian/spec/fixtures/en.yml | 4 - vendor/plugins/russian/spec/fixtures/ru.yml | 4 - .../russian/spec/i18n/locale/datetime_spec.rb | 93 - .../spec/i18n/locale/pluralization_spec.rb | 28 - vendor/plugins/russian/spec/locale_spec.rb | 129 - vendor/plugins/russian/spec/russian_spec.rb | 136 - vendor/plugins/russian/spec/spec_helper.rb | 7 - .../russian/spec/transliteration_spec.rb | 51 - 444 files changed, 5093 insertions(+), 28033 deletions(-) rename app/views/{ => devise}/confirmations/new.html.erb (60%) rename app/views/{ => devise}/devise_mailer/confirmation_instructions.html.erb (100%) rename app/views/{ => devise}/devise_mailer/reset_password_instructions.html.erb (100%) rename app/views/{ => devise}/devise_mailer/unlock_instructions.html.erb (100%) rename app/views/{ => devise}/passwords/edit.html.erb (67%) rename app/views/{ => devise}/passwords/new.html.erb (60%) rename app/views/{ => devise}/registrations/edit.html.erb (86%) rename app/views/{ => devise}/registrations/new.html.erb (81%) rename app/views/{ => devise}/sessions/new.html.erb (85%) rename app/views/{ => devise}/unlocks/new.html.erb (60%) create mode 100644 config.ru create mode 100644 config/application.rb create mode 100644 config/initializers/active_scaffold.rb delete mode 100644 config/initializers/new_rails_defaults.rb create mode 100644 config/initializers/secret_token.rb create mode 100644 lib/tasks/.gitkeep create mode 100644 public/images/active_scaffold/default/close_touch.png create mode 100755 public/images/active_scaffold/default/config.png create mode 100644 public/images/active_scaffold/default/gears.png mode change 100755 => 100644 public/javascripts/active_scaffold/default/dhtml_history.js create mode 100644 public/javascripts/rails.js create mode 100644 public/stylesheets/.gitkeep delete mode 100755 script/about delete mode 100755 script/console delete mode 100755 script/dbconsole delete mode 100755 script/destroy delete mode 100755 script/generate delete mode 100755 script/performance/benchmarker delete mode 100755 script/performance/profiler delete mode 100755 script/plugin create mode 100755 script/rails delete mode 100755 script/runner delete mode 100755 script/server create mode 100644 vendor/plugins/.gitkeep delete mode 100644 vendor/plugins/active_scaffold/.autotest delete mode 100644 vendor/plugins/active_scaffold/CHANGELOG delete mode 100644 vendor/plugins/active_scaffold/MIT-LICENSE delete mode 100644 vendor/plugins/active_scaffold/README delete mode 100644 vendor/plugins/active_scaffold/Rakefile delete mode 100644 vendor/plugins/active_scaffold/environment.rb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/add.gif delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/arrow_down.gif delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/arrow_up.gif delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/close.gif delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/cross.png delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/indicator-small.gif delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/indicator.gif delete mode 100644 vendor/plugins/active_scaffold/frontends/default/images/magnifier.png delete mode 100644 vendor/plugins/active_scaffold/frontends/default/javascripts/active_scaffold.js delete mode 100755 vendor/plugins/active_scaffold/frontends/default/javascripts/dhtml_history.js delete mode 100644 vendor/plugins/active_scaffold/frontends/default/javascripts/form_enhancements.js delete mode 100644 vendor/plugins/active_scaffold/frontends/default/javascripts/rico_corner.js delete mode 100644 vendor/plugins/active_scaffold/frontends/default/stylesheets/stylesheet-ie.css delete mode 100644 vendor/plugins/active_scaffold/frontends/default/stylesheets/stylesheet.css delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_add_existing_form.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_create_form.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_create_form_on_list.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_field_search.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_form.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_form_association.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_form_association_footer.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_form_attribute.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_form_hidden_attribute.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_form_messages.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_header.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_record.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_actions.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_calculations.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_column_headings.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_header.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_inline_adapter.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_messages.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_pagination.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_pagination_links.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_record.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_list_record_columns.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_messages.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_nested.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_render_fields.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_search.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_show.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_show_columns.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_update_actions.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_update_form.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform_record.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/add_existing.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/add_existing_form.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/create.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/delete.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/destroy.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/edit_associated.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/field_search.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/form_messages.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/list.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/list.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/mark.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/on_create.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/on_update.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/render_field.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/search.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/show.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/update.html.erb delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/update_column.js.rjs delete mode 100644 vendor/plugins/active_scaffold/frontends/default/views/update_row.js.rjs delete mode 100755 vendor/plugins/active_scaffold/init.rb delete mode 100644 vendor/plugins/active_scaffold/install.rb delete mode 100755 vendor/plugins/active_scaffold/install_assets.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_record_permissions.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/common_search.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/core.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/create.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/delete.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/field_search.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/list.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/mark.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/nested.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/search.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/show.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/subform.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/actions/update.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/attribute_params.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/base.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/core.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/create.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/delete.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/field_search.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/form.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/list.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/nested.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/search.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/show.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/subform.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/config/update.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/configurable.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/constraints.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_columns.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_link.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_links.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/actions.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/column.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/columns.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/error_message.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/set.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/sorting.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/finder.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/association_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/controller_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/country_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/form_column_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/id_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/list_column_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/pagination_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/search_column_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/show_column_helpers.rb delete mode 100755 vendor/plugins/active_scaffold/lib/active_scaffold/helpers/view_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/locale/de.yml delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/locale/en.yml delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/locale/es.yml delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/locale/fr.yml delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/locale/hu.yml delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/locale/ja.yml delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/locale/ru.yml delete mode 100644 vendor/plugins/active_scaffold/lib/active_scaffold/marked_model.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/lib/as_cds_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/dependent_protect/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/dependent_protect/lib/dependent_protect_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/lib/as_file_column_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/lib/file_column_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/lib/form_ui.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/lib/list_ui.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/test/functional/file_column_keep_test.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/test/mock_model.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/file_column/test/test_helper.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/paperclip/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/form_ui.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/list_ui.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/record_select/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/record_select/lib/record_select_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/lib/semantic_attributes_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/tiny_mce/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/tiny_mce/lib/tiny_mce_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/form_ui.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/unobtrusive_date_picker_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/view_helpers.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/validation_reflection/bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/bridges/validation_reflection/lib/validation_reflection_bridge.rb delete mode 100644 vendor/plugins/active_scaffold/lib/dhtml_confirm.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/action_controller_rendering.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/action_view_rendering.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/array.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/component_response_with_namespacing.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/generic_view_paths.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/localize.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/nil_id_in_url_params.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/paginator_extensions.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/resources.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/to_label.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/unsaved_associated.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/unsaved_record.rb delete mode 100644 vendor/plugins/active_scaffold/lib/extensions/usa_state.rb delete mode 100644 vendor/plugins/active_scaffold/lib/paginator.rb delete mode 100644 vendor/plugins/active_scaffold/lib/responds_to_parent.rb delete mode 100644 vendor/plugins/active_scaffold/public/blank.html delete mode 100644 vendor/plugins/active_scaffold/shoulda_macros/macros.rb delete mode 100644 vendor/plugins/active_scaffold/test/bridges/active_scaffold_dependent_protect_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/bridges/bridge_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/bridges/company.rb delete mode 100644 vendor/plugins/active_scaffold/test/bridges/paperclip_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/bridges/tiny_mce_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/bridges/unobtrusive_date_picker_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/bridges/validation_reflection_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/base_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/core_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/create_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/delete_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/field_search_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/list_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/nested_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/search_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/show_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/subform_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/config/update_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/const_mocker.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/action_columns_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/action_link_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/action_links_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/actions_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/association_column_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/column_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/columns_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/error_message_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/set_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/sorting_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/standard_column_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/data_structures/virtual_column_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/extensions/active_record_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/extensions/array_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/helpers/form_column_helpers_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/helpers/list_column_helpers_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/helpers/pagination_helpers_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/misc/active_record_permissions_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/misc/attribute_params_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/misc/configurable_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/misc/constraints_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/misc/finder_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/misc/lang_test.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/.gitignore delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/app/controllers/application_controller.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/app/helpers/application_helper.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/boot.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/database.yml delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/environment.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/environments/development.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/environments/production.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/environments/test.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/initializers/backtrace_silencers.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/initializers/inflections.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/initializers/mime_types.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/initializers/new_rails_defaults.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/initializers/session_store.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/locales/en.yml delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/config/routes.rb delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/db/test.sqlite3 delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/blank.html delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/DO_NOT_EDIT delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/add.gif delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/arrow_down.gif delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/arrow_up.gif delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/close.gif delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/cross.png delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/indicator-small.gif delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/indicator.gif delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/magnifier.png delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/DO_NOT_EDIT delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/active_scaffold.js delete mode 100755 vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/dhtml_history.js delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/form_enhancements.js delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/rico_corner.js delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/DO_NOT_EDIT delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet-ie.css delete mode 100644 vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet.css delete mode 100644 vendor/plugins/active_scaffold/test/model_stub.rb delete mode 100644 vendor/plugins/active_scaffold/test/run_all.rb delete mode 100644 vendor/plugins/active_scaffold/test/test_helper.rb delete mode 100644 vendor/plugins/active_scaffold/uninstall.rb delete mode 100644 vendor/plugins/rails_xss/MIT-LICENSE delete mode 100644 vendor/plugins/rails_xss/README.markdown delete mode 100644 vendor/plugins/rails_xss/Rakefile delete mode 100644 vendor/plugins/rails_xss/init.rb delete mode 100644 vendor/plugins/rails_xss/lib/rails_xss.rb delete mode 100644 vendor/plugins/rails_xss/lib/rails_xss/action_view.rb delete mode 100644 vendor/plugins/rails_xss/lib/rails_xss/erubis.rb delete mode 100644 vendor/plugins/rails_xss/lib/rails_xss/string_ext.rb delete mode 100644 vendor/plugins/rails_xss/lib/tasks/rails_xss_tasks.rake delete mode 100644 vendor/plugins/rails_xss/test/active_record_helper_test.rb delete mode 100644 vendor/plugins/rails_xss/test/asset_tag_helper_test.rb delete mode 100644 vendor/plugins/rails_xss/test/caching_test.rb delete mode 100644 vendor/plugins/rails_xss/test/date_helper_test.rb delete mode 100644 vendor/plugins/rails_xss/test/deprecated_output_safety_test.rb delete mode 100644 vendor/plugins/rails_xss/test/erb_util_test.rb delete mode 100644 vendor/plugins/rails_xss/test/form_helper_test.rb delete mode 100644 vendor/plugins/rails_xss/test/form_tag_helper_test.rb delete mode 100644 vendor/plugins/rails_xss/test/output_safety_test.rb delete mode 100644 vendor/plugins/rails_xss/test/rails_xss_test.rb delete mode 100644 vendor/plugins/rails_xss/test/test_helper.rb delete mode 100644 vendor/plugins/rails_xss/test/text_helper_test.rb delete mode 100644 vendor/plugins/recordselect/CHANGELOG delete mode 100644 vendor/plugins/recordselect/MIT-LICENSE delete mode 100644 vendor/plugins/recordselect/README delete mode 100644 vendor/plugins/recordselect/Rakefile delete mode 100644 vendor/plugins/recordselect/app/helpers/record_select_helper.rb delete mode 100644 vendor/plugins/recordselect/app/views/record_select/_browse.html.erb delete mode 100644 vendor/plugins/recordselect/app/views/record_select/_list.html.erb delete mode 100644 vendor/plugins/recordselect/app/views/record_select/_search.html.erb delete mode 100644 vendor/plugins/recordselect/app/views/record_select/browse.js.rjs delete mode 100644 vendor/plugins/recordselect/assets/images/cross.gif delete mode 100644 vendor/plugins/recordselect/assets/images/next.gif delete mode 100644 vendor/plugins/recordselect/assets/images/previous.gif delete mode 100644 vendor/plugins/recordselect/assets/javascripts/record_select.js delete mode 100644 vendor/plugins/recordselect/assets/stylesheets/record_select.css delete mode 100644 vendor/plugins/recordselect/init.rb delete mode 100644 vendor/plugins/recordselect/install.rb delete mode 100644 vendor/plugins/recordselect/lib/extensions/active_record.rb delete mode 100644 vendor/plugins/recordselect/lib/localization.rb delete mode 100644 vendor/plugins/recordselect/lib/record_select.rb delete mode 100644 vendor/plugins/recordselect/lib/record_select/actions.rb delete mode 100644 vendor/plugins/recordselect/lib/record_select/conditions.rb delete mode 100644 vendor/plugins/recordselect/lib/record_select/config.rb delete mode 100644 vendor/plugins/recordselect/lib/record_select/form_builder.rb delete mode 100644 vendor/plugins/recordselect/test/recordselect_test.rb delete mode 100644 vendor/plugins/recordselect/uninstall.rb delete mode 100644 vendor/plugins/render_component/README delete mode 100644 vendor/plugins/render_component/Rakefile delete mode 100644 vendor/plugins/render_component/init.rb delete mode 100644 vendor/plugins/render_component/lib/components.rb delete mode 100644 vendor/plugins/render_component/test/abstract_unit.rb delete mode 100644 vendor/plugins/render_component/test/components_test.rb delete mode 100644 vendor/plugins/russian/CHANGELOG delete mode 100644 vendor/plugins/russian/LICENSE delete mode 100644 vendor/plugins/russian/README.textile delete mode 100644 vendor/plugins/russian/Rakefile delete mode 100644 vendor/plugins/russian/TODO delete mode 100644 vendor/plugins/russian/init.rb delete mode 100644 vendor/plugins/russian/lib/russian.rb delete mode 100644 vendor/plugins/russian/lib/russian/action_view_ext/helpers/date_helper.rb delete mode 100644 vendor/plugins/russian/lib/russian/active_record_ext/custom_error_message.rb delete mode 100644 vendor/plugins/russian/lib/russian/active_support_ext/parameterize.rb delete mode 100644 vendor/plugins/russian/lib/russian/backend/advanced.rb delete mode 100644 vendor/plugins/russian/lib/russian/locale/actionview.yml delete mode 100644 vendor/plugins/russian/lib/russian/locale/activerecord.yml delete mode 100644 vendor/plugins/russian/lib/russian/locale/activesupport.yml delete mode 100644 vendor/plugins/russian/lib/russian/locale/datetime.yml delete mode 100644 vendor/plugins/russian/lib/russian/locale/pluralize.rb delete mode 100644 vendor/plugins/russian/lib/russian/transliteration.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/.gitignore delete mode 100755 vendor/plugins/russian/lib/vendor/i18n/MIT-LICENSE delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/README.textile delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/Rakefile delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/i18n.gemspec delete mode 100755 vendor/plugins/russian/lib/vendor/i18n/lib/i18n.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/lib/i18n/backend/simple.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/lib/i18n/exceptions.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/test/all.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/test/i18n_exceptions_test.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/test/i18n_test.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/test/locale/en.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/test/locale/en.yml delete mode 100644 vendor/plugins/russian/lib/vendor/i18n/test/simple_backend_test.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/README.textile delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/Rakefile delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/init.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/install.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/lib/i18n_label.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/spec/i18n_label_spec.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/spec/spec_helper.rb delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/tasks/i18n_label_tasks.rake delete mode 100644 vendor/plugins/russian/lib/vendor/i18n_label/uninstall.rb delete mode 100644 vendor/plugins/russian/russian.gemspec delete mode 100644 vendor/plugins/russian/spec/fixtures/en.yml delete mode 100644 vendor/plugins/russian/spec/fixtures/ru.yml delete mode 100644 vendor/plugins/russian/spec/i18n/locale/datetime_spec.rb delete mode 100644 vendor/plugins/russian/spec/i18n/locale/pluralization_spec.rb delete mode 100644 vendor/plugins/russian/spec/locale_spec.rb delete mode 100644 vendor/plugins/russian/spec/russian_spec.rb delete mode 100644 vendor/plugins/russian/spec/spec_helper.rb delete mode 100644 vendor/plugins/russian/spec/transliteration_spec.rb diff --git a/Gemfile b/Gemfile index 6be25c6..0d1eec6 100644 --- a/Gemfile +++ b/Gemfile @@ -1,8 +1,11 @@ source "http://rubygems.org" -gem "rails", "~> 2.3.8" +gem "rails", "~> 3.0.0" -gem "devise", "~> 1.0.8" +gem "active_scaffold", "~> 3.0.0" +gem "recordselect", "~> 3.0.4" +gem "russian" +gem "devise", "~> 1.1.0" gem "erubis" gem "haml", "~> 3.0.21" gem "pdfkit" diff --git a/Gemfile.lock b/Gemfile.lock index 91fc179..4999631 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -5,37 +5,65 @@ GEM Platform (>= 0.4.0) open4 Platform (0.4.0) - actionmailer (2.3.14) - actionpack (= 2.3.14) - actionpack (2.3.14) - activesupport (= 2.3.14) - rack (~> 1.1.0) - activerecord (2.3.14) - activesupport (= 2.3.14) - activeresource (2.3.14) - activesupport (= 2.3.14) - activesupport (2.3.14) - backup (3.0.20) + abstract (1.0.0) + actionmailer (3.0.12) + actionpack (= 3.0.12) + mail (~> 2.2.19) + actionpack (3.0.12) + activemodel (= 3.0.12) + activesupport (= 3.0.12) + builder (~> 2.1.2) + erubis (~> 2.6.6) + i18n (~> 0.5.0) + rack (~> 1.2.5) + rack-mount (~> 0.6.14) + rack-test (~> 0.5.7) + tzinfo (~> 0.3.23) + active_scaffold (3.0.26) + rails (~> 3.0.0) + render_component_vho + verification + activemodel (3.0.12) + activesupport (= 3.0.12) + builder (~> 2.1.2) + i18n (~> 0.5.0) + activerecord (3.0.12) + activemodel (= 3.0.12) + activesupport (= 3.0.12) + arel (~> 2.0.10) + tzinfo (~> 0.3.23) + activeresource (3.0.12) + activemodel (= 3.0.12) + activesupport (= 3.0.12) + activesupport (3.0.12) + arel (2.0.10) + backup (3.0.23) POpen4 (~> 0.1.4) thor (~> 0.14.6) - capistrano (2.9.0) + bcrypt-ruby (2.1.4) + builder (2.1.2) + capistrano (2.11.2) highline net-scp (>= 1.0.0) net-sftp (>= 2.0.0) net-ssh (>= 2.0.14) net-ssh-gateway (>= 1.1.0) - chronic (0.6.6) + chronic (0.6.7) columnize (0.3.6) - devise (1.0.11) - warden (~> 0.10.3) - erubis (2.7.0) + devise (1.1.9) + bcrypt-ruby (~> 2.1.2) + warden (~> 1.0.2) + erubis (2.6.6) + abstract (>= 1.0.0) haml (3.0.25) - highline (1.6.9) - i18n (0.6.0) + highline (1.6.11) + i18n (0.5.0) + json (1.6.5) kgio (2.7.2) linecache (0.46) rbx-require-relative (> 0.0.4) - mail (2.3.0) + mail (2.2.19) + activesupport (>= 2.3.6) i18n (>= 0.4.0) mime-types (~> 1.16) treetop (~> 1.4.8) @@ -47,39 +75,62 @@ GEM net-ssh (2.1.4) net-ssh-gateway (1.1.0) net-ssh (>= 1.99.1) - nokogiri (1.5.0) + nokogiri (1.5.2) open4 (1.3.0) pdfkit (0.5.2) - pg (0.12.2) + pg (0.13.2) polyglot (0.3.3) - rack (1.1.3) - rails (2.3.14) - actionmailer (= 2.3.14) - actionpack (= 2.3.14) - activerecord (= 2.3.14) - activeresource (= 2.3.14) - activesupport (= 2.3.14) - rake (>= 0.8.3) + rack (1.2.5) + rack-mount (0.6.14) + rack (>= 1.0.0) + rack-test (0.5.7) + rack (>= 1.0) + rails (3.0.12) + actionmailer (= 3.0.12) + actionpack (= 3.0.12) + activerecord (= 3.0.12) + activeresource (= 3.0.12) + activesupport (= 3.0.12) + bundler (~> 1.0) + railties (= 3.0.12) + railties (3.0.12) + actionpack (= 3.0.12) + activesupport (= 3.0.12) + rake (>= 0.8.7) + rdoc (~> 3.4) + thor (~> 0.14.4) raindrops (0.8.0) rake (0.9.2.2) - rbx-require-relative (0.0.5) + rbx-require-relative (0.0.9) + rdoc (3.12) + json (~> 1.4) + recordselect (3.0.4) + rails (~> 3.0.0) + render_component_vho (3.0.3) + railties (~> 3.0.0) ruby-debug (0.10.4) columnize (>= 0.1) ruby-debug-base (~> 0.10.4.0) ruby-debug-base (0.10.4) linecache (>= 0.3) + russian (0.6.0) + i18n (>= 0.5.0) thor (0.14.6) treetop (1.4.10) polyglot polyglot (>= 0.3.1) - unicode (0.4.0) - unicorn (4.1.1) - kgio (~> 2.4) + tzinfo (0.3.32) + unicode (0.4.2) + unicorn (4.2.0) + kgio (~> 2.6) rack - raindrops (~> 0.6) - warden (0.10.7) - rack (>= 1.0.0) - whenever (0.7.2) + raindrops (~> 0.7) + verification (1.0.1) + actionpack (~> 3.0.0) + activesupport (~> 3.0.0) + warden (1.0.6) + rack (>= 1.0) + whenever (0.7.3) activesupport (>= 2.3.4) chronic (~> 0.6.3) @@ -87,9 +138,10 @@ PLATFORMS ruby DEPENDENCIES + active_scaffold (~> 3.0.0) backup capistrano - devise (~> 1.0.8) + devise (~> 1.1.0) erubis haml (~> 3.0.21) mail @@ -98,8 +150,10 @@ DEPENDENCIES nokogiri pdfkit pg - rails (~> 2.3.8) + rails (~> 3.0.0) + recordselect (~> 3.0.4) ruby-debug + russian unicode unicorn whenever diff --git a/Rakefile b/Rakefile index 3bb0e85..19296e4 100644 --- a/Rakefile +++ b/Rakefile @@ -1,10 +1,7 @@ # Add your own tasks in files placed in lib/tasks ending in .rake, # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. -require(File.join(File.dirname(__FILE__), 'config', 'boot')) - +require File.expand_path('../config/application', __FILE__) require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' -require 'tasks/rails' +Taurus::Application.load_tasks diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 2cb9ef6..bb0685f 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -3,14 +3,5 @@ class ApplicationController < ActionController::Base protect_from_forgery # See ActionController::RequestForgeryProtection for details - - # Scrub sensitive parameters from your log - filter_parameter_logging :password - ActiveScaffold.set_defaults do |config| - config.actions.exclude :show, :delete - config.search.live = true - config.ignore_columns = [:created_at, :updated_at, :lock_version] - config.list.per_page = 30 - config.subform.layout = :vertical - end + clear_helpers end diff --git a/app/controllers/dept_head/disciplines_controller.rb b/app/controllers/dept_head/disciplines_controller.rb index 5988c37..85f7b07 100644 --- a/app/controllers/dept_head/disciplines_controller.rb +++ b/app/controllers/dept_head/disciplines_controller.rb @@ -6,7 +6,7 @@ class DeptHead::DisciplinesController < DeptHead::BaseController config.create.columns = [:name, :short_name] config.update.columns = [:name, :short_name] config.list.sorting = { :name => :asc } - config.nested.add_link 'Карты распределения нагрузки', [:charge_cards] + config.nested.add_link :charge_cards end protected diff --git a/app/controllers/dept_head/specialities_controller.rb b/app/controllers/dept_head/specialities_controller.rb index 8510621..f993e72 100644 --- a/app/controllers/dept_head/specialities_controller.rb +++ b/app/controllers/dept_head/specialities_controller.rb @@ -4,7 +4,7 @@ class DeptHead::SpecialitiesController < DeptHead::BaseController active_scaffold do |config| config.actions << :delete config.columns = [:code, :name] - config.nested.add_link('Группы', [:groups]) + config.nested.add_link(:groups) config.action_links.add :teaching_plan, :label => "Учебный план", :type => :member, :page => true config.action_links.add :teaching_plan_import, :label => "Импорт учебного плана", :type => :collection, :page => true config.action_links.add :add_charge_cards, :label => "Автосоздание карт нагрузки", :type => :member, :page => true @@ -20,7 +20,7 @@ def teaching_plan end def teaching_plan_import - if params[:plan] and params[:plan].class == Tempfile + if params[:plan] and params[:plan].class == ActionDispatch::Http::UploadedFile @specialities = current_dept_head.department.specialities @speciality, @results, @errors = parse_and_fill_teaching_plan(params[:plan].read, @specialities) render "supervisor/teaching_plans/fill" diff --git a/app/controllers/dept_head/teaching_places_controller.rb b/app/controllers/dept_head/teaching_places_controller.rb index 73f6bb5..166d907 100644 --- a/app/controllers/dept_head/teaching_places_controller.rb +++ b/app/controllers/dept_head/teaching_places_controller.rb @@ -9,7 +9,7 @@ class DeptHead::TeachingPlacesController < DeptHead::BaseController config.columns[:lecturer].sort_by :sql => 'lecturers.name' config.search.columns = :lecturer config.columns[:lecturer].search_sql = 'lecturers.name' - config.nested.add_link('Карты распределения нагрузки', [:charge_cards]) + config.nested.add_link :charge_cards end protected diff --git a/app/controllers/editor/groups/charge_cards_controller.rb b/app/controllers/editor/groups/charge_cards_controller.rb index 95cb5c5..728d009 100644 --- a/app/controllers/editor/groups/charge_cards_controller.rb +++ b/app/controllers/editor/groups/charge_cards_controller.rb @@ -1,9 +1,7 @@ class Editor::Groups::ChargeCardsController < Editor::BaseController def index charge_card_search = params[:charge_card].to_s.split - charge_card = ChargeCard.all :joins => :jets, - :select => "charge_cards.id,charge_cards.editor_name", - :conditions => {:jets => {:group_id => params[:group_id]}} + charge_card = ChargeCard.joins(:jets).where(:jets => {:group_id => params[:group_id]}).select("charge_cards.id,charge_cards.editor_name").all charge_card_search.each do |s| charge_card = charge_card.select { |c| c.editor_name_include? s } end diff --git a/app/controllers/editor/reference/charge_cards_controller.rb b/app/controllers/editor/reference/charge_cards_controller.rb index b75f337..3fd7517 100644 --- a/app/controllers/editor/reference/charge_cards_controller.rb +++ b/app/controllers/editor/reference/charge_cards_controller.rb @@ -1,6 +1,6 @@ class Editor::Reference::ChargeCardsController < Editor::BaseController - active_scaffold do |config| - config.actions = [:list] + active_scaffold :charge_cards do |config| + config.actions = [:list, :search, :nested] config.list.columns = [:teaching_place, :assistant_teaching_place, :lesson_type, :discipline, :hours_quantity, :hours_per_week, :weeks_quantity, :groups] config.columns[:teaching_place].clear_link config.columns[:assistant_teaching_place].clear_link diff --git a/app/controllers/editor/reference/departments_controller.rb b/app/controllers/editor/reference/departments_controller.rb index 81cb309..86fbcc5 100644 --- a/app/controllers/editor/reference/departments_controller.rb +++ b/app/controllers/editor/reference/departments_controller.rb @@ -1,9 +1,9 @@ class Editor::Reference::DepartmentsController < Editor::BaseController - active_scaffold do |config| - config.actions = [:list, :nested] - config.columns = [:name, :short_name] + active_scaffold :departments do |config| + config.actions = [:list, :search, :nested] + config.list.columns = [:name, :short_name] config.list.sorting = { :name => :asc } - config.nested.add_link('Дисциплины', [:disciplines]) - config.nested.add_link('Преподаватели', [:teaching_places]) + config.nested.add_link :disciplines + config.nested.add_link :teaching_places end end diff --git a/app/controllers/editor/reference/disciplines_controller.rb b/app/controllers/editor/reference/disciplines_controller.rb index b252adb..a0b2813 100644 --- a/app/controllers/editor/reference/disciplines_controller.rb +++ b/app/controllers/editor/reference/disciplines_controller.rb @@ -1,9 +1,9 @@ class Editor::Reference::DisciplinesController < Editor::BaseController record_select :search_on => :name, :order_by => :name - active_scaffold do |config| - config.actions = [:list, :nested] - config.columns = [:short_name, :name] + active_scaffold :disciplines do |config| + config.actions = [:list, :search, :nested] + config.list.columns = [:short_name, :name] config.list.sorting = { :name => :asc } - config.nested.add_link 'Карты распределения нагрузки', [:charge_cards] + config.nested.add_link :charge_cards end end diff --git a/app/controllers/editor/reference/teaching_places_controller.rb b/app/controllers/editor/reference/teaching_places_controller.rb index 014937f..a431cf2 100644 --- a/app/controllers/editor/reference/teaching_places_controller.rb +++ b/app/controllers/editor/reference/teaching_places_controller.rb @@ -1,10 +1,11 @@ class Editor::Reference::TeachingPlacesController < Editor::BaseController - active_scaffold do |config| - config.actions = [:list, :nested] - config.columns = [:position, :lecturer, :whish] + active_scaffold :teaching_places do |config| + config.actions = [:list, :search, :nested] + config.list.columns = [:position, :lecturer, :whish] config.columns[:lecturer].clear_link config.columns[:lecturer].sort_by :sql => 'lecturers.name' - config.list.sorting = { :lecturer => :asc } - config.nested.add_link('Карты распределения нагрузки', [:charge_cards]) + config.columns[:lecturer].search_sql = 'lecturers.name' + config.search.columns << :lecturer + config.nested.add_link :charge_cards end end diff --git a/app/controllers/supervisor/departments_controller.rb b/app/controllers/supervisor/departments_controller.rb index b563679..9950632 100644 --- a/app/controllers/supervisor/departments_controller.rb +++ b/app/controllers/supervisor/departments_controller.rb @@ -2,6 +2,6 @@ class Supervisor::DepartmentsController < Supervisor::BaseController active_scaffold do |config| config.actions << :delete config.columns = [:name, :short_name, :gosinsp_code] - config.nested.add_link('Специальности', [:specialities]) + config.nested.add_link :specialities end end diff --git a/app/controllers/supervisor/faculties_controller.rb b/app/controllers/supervisor/faculties_controller.rb index 2772d90..e86da5c 100644 --- a/app/controllers/supervisor/faculties_controller.rb +++ b/app/controllers/supervisor/faculties_controller.rb @@ -2,6 +2,6 @@ class Supervisor::FacultiesController < Supervisor::BaseController active_scaffold do |config| config.actions << :delete config.columns = [:full_name, :name] - config.nested.add_link('Кафедры', [:departments]) + config.nested.add_link :departments end end diff --git a/app/controllers/supervisor/specialities_controller.rb b/app/controllers/supervisor/specialities_controller.rb index 5139e89..5c73263 100644 --- a/app/controllers/supervisor/specialities_controller.rb +++ b/app/controllers/supervisor/specialities_controller.rb @@ -2,7 +2,7 @@ class Supervisor::SpecialitiesController < Supervisor::BaseController active_scaffold do |config| config.actions << :delete config.columns = [:code, :name, :department] - config.nested.add_link('Группы', [:groups]) + config.nested.add_link :groups config.columns[:department].form_ui = :select config.action_links.add :teaching_plan, :label => "Учебный план", :type => :member, :page => true end diff --git a/app/controllers/supervisor/teaching_plans_controller.rb b/app/controllers/supervisor/teaching_plans_controller.rb index 017b18b..1ffbebc 100644 --- a/app/controllers/supervisor/teaching_plans_controller.rb +++ b/app/controllers/supervisor/teaching_plans_controller.rb @@ -6,7 +6,7 @@ def new end def fill - if params[:plan] and params[:plan].class == Tempfile + if params[:plan] and params[:plan].class == ActionDispatch::Http::UploadedFile @speciality, @results, @errors = parse_and_fill_teaching_plan(params[:plan].read) end end diff --git a/app/models/charge_card.rb b/app/models/charge_card.rb index 607fa2a..3cab681 100644 --- a/app/models/charge_card.rb +++ b/app/models/charge_card.rb @@ -14,12 +14,9 @@ class ChargeCard < ActiveRecord::Base validates_presence_of :discipline, :lesson_type, :weeks_quantity, :hours_per_week validates_numericality_of :weeks_quantity, :hours_per_week - named_scope :with_recommended_first_for, lambda { |department| + scope :with_recommended_first_for, lambda { |department| if department.class == Department - { - :joins => :teaching_place, - :order => "teaching_places.department_id = #{department.id} DESC NULLS LAST, charge_cards.editor_name ASC" - } + joins(:teaching_place).order("teaching_places.department_id = #{department.id} DESC NULLS LAST, charge_cards.editor_name ASC") end } @@ -64,12 +61,11 @@ def editor_name_with_recommendation def self.for_autocreation(discipline_id, lesson_type_id, groups) groups = [groups].flatten # In case of single group make it look like an array - pretendents = all(:joins => :jets, :conditions => { + pretendents = joins(:jets).where( :discipline_id => discipline_id, :lesson_type_id => lesson_type_id, :jets => {:group_id => groups} - } - ) + ).all pretendents = pretendents.find_all {|cc| cc.groups == groups } if pretendents.empty? return new(:discipline_id => discipline_id, :lesson_type_id => lesson_type_id) diff --git a/app/models/classroom.rb b/app/models/classroom.rb index 8b2feb3..2859bbe 100644 --- a/app/models/classroom.rb +++ b/app/models/classroom.rb @@ -5,7 +5,7 @@ class Classroom < ActiveRecord::Base validates_presence_of :building - default_scope :joins => :building, :order => "classrooms.name ASC, buildings.name ASC" + default_scope joins(:building).order("classrooms.name ASC, buildings.name ASC") def self.all_with_recommended_first_for (department) if department.class == Department diff --git a/app/models/group.rb b/app/models/group.rb index fd03dbf..783050d 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -9,9 +9,9 @@ class Group < ActiveRecord::Base validates_format_of :forming_year, :with => /^(20)\d{2}$/, :message => '- необходимо вводить год целиком. Допустимы годы от 2000 до 2099' - named_scope :for_timetable, :include => [{:subgroups => [{:pair => [{:classroom => :building}, { :charge_card => [:discipline, {:teaching_place => [:lecturer, :department]}]}]}]}] - named_scope :by_name, lambda { |name| { :conditions => ['groups.name LIKE ?', escape_name(name)] } } - named_scope :for_groups_editor, :include => {:jets => {:subgroups => {:pair => [{:classroom => :building}, { :charge_card => [:discipline, {:teaching_place => [:lecturer, :department]}]}]}}} + scope :for_timetable, includes(:subgroups => [{:pair => [{:classroom => :building}, { :charge_card => [:discipline, {:teaching_place => [:lecturer, :department]}]}]}]) + scope :by_name, lambda { |name| where('groups.name LIKE ?', escape_name(name)) } + scope :for_groups_editor, includes(:jets => {:subgroups => {:pair => [{:classroom => :building}, { :charge_card => [:discipline, {:teaching_place => [:lecturer, :department]}]}]}}) def course this_year = Time.now.year.to_i @@ -34,19 +34,18 @@ def get_pairs end def pairs_with_subgroups - self.subgroups.all(:include => :pair).map{|s| [s.pair, s.number]} + self.subgroups.includes(:pair).map{|s| [s.pair, s.number]} end def pairs_with_subgroups_for_timeslot(day, time) - subgroups = self.subgroups.all :joins => :pair, :include => :pair, - :conditions => {:pairs => { + subgroups = self.subgroups.joins(:pair).includes(:pair).where(:pairs => { :day_of_the_week => day, :pair_number => time - }} + }) return subgroups.map{|s| [s.pair, s.number]} end def department - Department.first :joins => {:specialities => :groups}, :conditions => {:groups => {:id => self.id}} + Department.joins(:specialities => :groups).where(:groups => {:id => self.id}).first end def descriptive_name diff --git a/app/models/lecturer.rb b/app/models/lecturer.rb index a5b0090..21a15d4 100644 --- a/app/models/lecturer.rb +++ b/app/models/lecturer.rb @@ -5,7 +5,7 @@ class Lecturer < ActiveRecord::Base validates_uniqueness_of :name - named_scope :by_name, lambda { |name| { :conditions => ['LOWER(lecturers.name) LIKE LOWER(?)', escape_name(name)] } } + scope :by_name, lambda { |name| where('LOWER(lecturers.name) LIKE LOWER(?)', escape_name(name)) } private diff --git a/app/models/pair.rb b/app/models/pair.rb index cfedde7..f6f7fb1 100644 --- a/app/models/pair.rb +++ b/app/models/pair.rb @@ -5,6 +5,8 @@ class Pair < ActiveRecord::Base accepts_nested_attributes_for :subgroups + validate :create_validation, :on => :create + validate :update_validation, :on => :update validate :expiration_date_validness, :activation_date_validness validate :week_number_existance @@ -108,7 +110,7 @@ def guess_expire_date private - def validate_on_create + def create_validation conditions = { :classroom_id => classroom_id, :day_of_the_week => day_of_the_week, :pair_number => pair_number, @@ -121,7 +123,7 @@ def validate_on_create end end - def validate_on_update + def update_validation week_conditions = week == 0 ? [0, 1, 2] : [0, week] conditions = ['pairs.id <> ? AND pairs.day_of_the_week = ? AND pairs.pair_number = ? AND pairs.week IN (?) AND NOT ((pairs.active_at > ? AND expired_at > ?) OR (active_at < ? AND expired_at < ?))', id, day_of_the_week, pair_number, week_conditions, expired_at, expired_at, active_at, active_at] diff --git a/app/views/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb similarity index 60% rename from app/views/confirmations/new.html.erb rename to app/views/devise/confirmations/new.html.erb index 80670d8..15555da 100644 --- a/app/views/confirmations/new.html.erb +++ b/app/views/devise/confirmations/new.html.erb @@ -1,6 +1,6 @@

Resend confirmation instructions

-<% form_for resource_name, resource, :url => confirmation_path(resource_name) do |f| %> +<%= form_for resource_name, resource, :url => confirmation_path(resource_name) do |f| %> <%= f.error_messages %>

<%= f.label :email %>

@@ -9,4 +9,4 @@

<%= f.submit "Resend confirmation instructions" %>

<% end %> -<%= render :partial => "shared/devise_links" %> \ No newline at end of file +<%= render :partial => "shared/devise_links" %> diff --git a/app/views/devise_mailer/confirmation_instructions.html.erb b/app/views/devise/devise_mailer/confirmation_instructions.html.erb similarity index 100% rename from app/views/devise_mailer/confirmation_instructions.html.erb rename to app/views/devise/devise_mailer/confirmation_instructions.html.erb diff --git a/app/views/devise_mailer/reset_password_instructions.html.erb b/app/views/devise/devise_mailer/reset_password_instructions.html.erb similarity index 100% rename from app/views/devise_mailer/reset_password_instructions.html.erb rename to app/views/devise/devise_mailer/reset_password_instructions.html.erb diff --git a/app/views/devise_mailer/unlock_instructions.html.erb b/app/views/devise/devise_mailer/unlock_instructions.html.erb similarity index 100% rename from app/views/devise_mailer/unlock_instructions.html.erb rename to app/views/devise/devise_mailer/unlock_instructions.html.erb diff --git a/app/views/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb similarity index 67% rename from app/views/passwords/edit.html.erb rename to app/views/devise/passwords/edit.html.erb index 968701f..c4f6c52 100644 --- a/app/views/passwords/edit.html.erb +++ b/app/views/devise/passwords/edit.html.erb @@ -1,6 +1,6 @@

Change your password

-<% form_for resource_name, resource, :url => password_path(resource_name), :html => { :method => :put } do |f| %> +<%= form_for resource_name, resource, :url => password_path(resource_name), :html => { :method => :put } do |f| %> <%= f.error_messages %> <%= f.hidden_field :reset_password_token %> @@ -13,4 +13,4 @@

<%= f.submit "Change my password" %>

<% end %> -<%= render :partial => "shared/devise_links" %> \ No newline at end of file +<%= render :partial => "shared/devise_links" %> diff --git a/app/views/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb similarity index 60% rename from app/views/passwords/new.html.erb rename to app/views/devise/passwords/new.html.erb index 055e7ce..a9404a8 100644 --- a/app/views/passwords/new.html.erb +++ b/app/views/devise/passwords/new.html.erb @@ -1,6 +1,6 @@

Forgot your password?

-<% form_for resource_name, resource, :url => password_path(resource_name) do |f| %> +<%= form_for resource_name, resource, :url => password_path(resource_name) do |f| %> <%= f.error_messages %>

<%= f.label :email %>

@@ -9,4 +9,4 @@

<%= f.submit "Send me reset password instructions" %>

<% end %> -<%= render :partial => "shared/devise_links" %> \ No newline at end of file +<%= render :partial => "shared/devise_links" %> diff --git a/app/views/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb similarity index 86% rename from app/views/registrations/edit.html.erb rename to app/views/devise/registrations/edit.html.erb index 1fd0b45..03ee7c5 100644 --- a/app/views/registrations/edit.html.erb +++ b/app/views/devise/registrations/edit.html.erb @@ -1,6 +1,6 @@

Edit <%= resource_name.to_s.humanize %>

-<% form_for resource_name, resource, :url => registration_path(resource_name), :html => { :method => :put } do |f| -%> +<%= form_for resource_name, resource, :url => registration_path(resource_name), :html => { :method => :put } do |f| -%> <%= f.error_messages %>

<%= f.label :email %>

diff --git a/app/views/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb similarity index 81% rename from app/views/registrations/new.html.erb rename to app/views/devise/registrations/new.html.erb index 423edd3..ad75d61 100644 --- a/app/views/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -1,6 +1,6 @@

Sign up

-<% form_for resource_name, resource, :url => registration_path(resource_name) do |f| -%> +<%= form_for resource_name, resource, :url => registration_path(resource_name) do |f| -%> <%= f.error_messages %>

<%= f.label :email %>

<%= f.text_field :email %>

diff --git a/app/views/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb similarity index 85% rename from app/views/sessions/new.html.erb rename to app/views/devise/sessions/new.html.erb index 431968f..006d158 100644 --- a/app/views/sessions/new.html.erb +++ b/app/views/devise/sessions/new.html.erb @@ -1,7 +1,7 @@

Вход в систему

- <% form_for resource_name, resource, :url => session_path(resource_name) do |f| -%> + <%= form_for resource_name, resource, :url => session_path(resource_name) do |f| -%>

<%= f.label :login, "Имя пользователя" %>
<%= f.text_field :login %> @@ -20,4 +20,4 @@ <% end -%> <%= render :partial => "shared/devise_links" %> -

\ No newline at end of file + diff --git a/app/views/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb similarity index 60% rename from app/views/unlocks/new.html.erb rename to app/views/devise/unlocks/new.html.erb index 60314e7..ed6e618 100644 --- a/app/views/unlocks/new.html.erb +++ b/app/views/devise/unlocks/new.html.erb @@ -1,6 +1,6 @@

Resend unlock instructions

-<% form_for resource_name, resource, :url => unlock_path(resource_name) do |f| %> +<%= form_for resource_name, resource, :url => unlock_path(resource_name) do |f| %> <%= f.error_messages %>

<%= f.label :email %>

@@ -9,4 +9,4 @@

<%= f.submit "Resend unlock instructions" %>

<% end %> -<%= render :partial => "shared/devise_links" %> \ No newline at end of file +<%= render :partial => "shared/devise_links" %> diff --git a/app/views/editor/classrooms/pairs/_pair_edit.html.haml b/app/views/editor/classrooms/pairs/_pair_edit.html.haml index 972c4fc..cd162b3 100644 --- a/app/views/editor/classrooms/pairs/_pair_edit.html.haml +++ b/app/views/editor/classrooms/pairs/_pair_edit.html.haml @@ -1,5 +1,5 @@ .update_form{:id => "pair_edit_#{@pair.id.to_s}"} - - remote_form_for([:editor, :classrooms, @pair]) do |f| + - form_for([:editor, :classrooms, @pair], :remote => true) do |f| %p{:id => "week_block"} %br = f.radio_button :week, 0 diff --git a/app/views/editor/classrooms/pairs/edit.js.erb b/app/views/editor/classrooms/pairs/edit.js.erb index a59fb72..61431fa 100644 --- a/app/views/editor/classrooms/pairs/edit.js.erb +++ b/app/views/editor/classrooms/pairs/edit.js.erb @@ -34,7 +34,6 @@ jQuery(document).ready(function($){ $('.edit_pair').submit(function() { dlg.dialog("close"); - return false; }); $('.charge_card').autocomplete({ diff --git a/app/views/editor/groups/pairs/_pair_edit.html.haml b/app/views/editor/groups/pairs/_pair_edit.html.haml index d96ffe5..c7e5db8 100644 --- a/app/views/editor/groups/pairs/_pair_edit.html.haml +++ b/app/views/editor/groups/pairs/_pair_edit.html.haml @@ -1,5 +1,5 @@ .update_form{:id => "pair_edit_#{@pair.id.to_s}"} - - remote_form_for([:editor, :groups, @pair]) do |f| + - form_for([:editor, :groups, @pair], :remote => true) do |f| = hidden_field_tag(:group_id, params[:group_id]) if params[:group_id] = hidden_field_tag(:subgroup, params[:subgroup]) if params[:subgroup] = f.hidden_field :day_of_the_week diff --git a/app/views/editor/groups/pairs/edit.js.erb b/app/views/editor/groups/pairs/edit.js.erb index 20832a8..2eeba32 100644 --- a/app/views/editor/groups/pairs/edit.js.erb +++ b/app/views/editor/groups/pairs/edit.js.erb @@ -40,7 +40,6 @@ jQuery(document).ready(function($){ $('.edit_pair').submit(function() { dlg.dialog("close"); - return false; }); $('.classroom').autocomplete({ diff --git a/config.ru b/config.ru new file mode 100644 index 0000000..bb72908 --- /dev/null +++ b/config.ru @@ -0,0 +1,4 @@ +# This file is used by Rack-based servers to start the application. + +require ::File.expand_path('../config/environment', __FILE__) +run Taurus::Application diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 0000000..48f3bd8 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,51 @@ +require File.expand_path('../boot', __FILE__) + +require 'rails/all' + +# If you have a Gemfile, require the gems listed there, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(:default, Rails.env) if defined?(Bundler) + +module Taurus + class Application < Rails::Application + + config.autoload_paths += [config.root.join('lib')] + + # Configure the default encoding used in templates for Ruby 1.9. + config.encoding = "utf-8" + + # Settings in config/environments/* take precedence over those specified here. + # Application configuration should go into files in config/initializers + # -- all .rb files in that directory are automatically loaded. + + # Add additional load paths for your own custom dirs + # config.load_paths += %W( #{RAILS_ROOT}/extras ) + + # Only load the plugins named here, in the order given (default is alphabetical). + # :all can be used as a placeholder for all plugins not explicitly named + # config.plugins = [ :exception_notification, :ssl_requirement, :all ] + + # Skip frameworks you're not going to use. To use Rails without a database, + # you must remove the Active Record framework. + # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] + + # Activate observers that should always be running + # config.active_record.observers = :cacher, :garbage_collector, :forum_observer + + # Don't show passwords in logs + config.filter_parameters += [:password] + + # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. + # Run "rake -D time" for a list of tasks for finding time zone names. + config.time_zone = 'Yakutsk' + + # 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}')] + config.i18n.default_locale = :ru + + require 'pdfkit' + config.middleware.use PDFKit::Middleware, :print_media_type => true, :page_size => "A4", :orientation => :landscape, :margin_top => "10mm", :margin_bottom => "10mm", :margin_left => "10mm", :margin_right => "10mm" + + end +end + diff --git a/config/boot.rb b/config/boot.rb index f08c849..4489e58 100644 --- a/config/boot.rb +++ b/config/boot.rb @@ -1,125 +1,6 @@ -# Don't change this file! -# Configure your app in config/environment.rb and config/environments/*.rb +require 'rubygems' -RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) +# Set up gems listed in the Gemfile. +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) -module Rails - class << self - def boot! - unless booted? - preinitialize - pick_boot.run - end - end - - def booted? - defined? Rails::Initializer - end - - def pick_boot - (vendor_rails? ? VendorBoot : GemBoot).new - end - - def vendor_rails? - File.exist?("#{RAILS_ROOT}/vendor/rails") - end - - def preinitialize - load(preinitializer_path) if File.exist?(preinitializer_path) - end - - def preinitializer_path - "#{RAILS_ROOT}/config/preinitializer.rb" - end - end - - class Boot - def run - load_initializer - Rails::Initializer.run(:set_load_path) - end - end - - class VendorBoot < Boot - def load_initializer - require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" - Rails::Initializer.run(:install_gem_spec_stubs) - Rails::GemDependency.add_frozen_gem_path - end - end - - class GemBoot < Boot - def load_initializer - self.class.load_rubygems - load_rails_gem - require 'initializer' - end - - def load_rails_gem - if version = self.class.gem_version - gem 'rails', version - else - gem 'rails' - end - rescue Gem::LoadError => load_error - $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.) - exit 1 - end - - class << self - def rubygems_version - Gem::RubyGemsVersion rescue nil - end - - def gem_version - if defined? RAILS_GEM_VERSION - RAILS_GEM_VERSION - elsif ENV.include?('RAILS_GEM_VERSION') - ENV['RAILS_GEM_VERSION'] - else - parse_gem_version(read_environment_rb) - end - end - - def load_rubygems - min_version = '1.3.2' - require 'rubygems' - unless rubygems_version >= min_version - $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) - exit 1 - end - - rescue LoadError - $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org) - exit 1 - end - - def parse_gem_version(text) - $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/ - end - - private - def read_environment_rb - File.read("#{RAILS_ROOT}/config/environment.rb") - end - end - end -end - -# For bundler support -class Rails::Boot - def run - load_initializer - - Rails::Initializer.class_eval do - def load_gems - @bundler_loaded ||= Bundler.require :default, Rails.env - end - end - - Rails::Initializer.run(:set_load_path) - end -end - -# All that for this: -Rails.boot! +require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE']) diff --git a/config/environment.rb b/config/environment.rb index ae287f3..68c7100 100644 --- a/config/environment.rb +++ b/config/environment.rb @@ -1,37 +1,5 @@ -# Be sure to restart your server when you modify this file +# Load the rails application +require File.expand_path('../application', __FILE__) -# Specifies gem version of Rails to use when vendor/rails is not present -RAILS_GEM_VERSION = '2.3.14' unless defined? RAILS_GEM_VERSION - -# Bootstrap the Rails environment, frameworks, and default configuration -require File.join(File.dirname(__FILE__), 'boot') - -Rails::Initializer.run do |config| - # Settings in config/environments/* take precedence over those specified here. - # Application configuration should go into files in config/initializers - # -- all .rb files in that directory are automatically loaded. - - # Add additional load paths for your own custom dirs - # config.load_paths += %W( #{RAILS_ROOT}/extras ) - - # Only load the plugins named here, in the order given (default is alphabetical). - # :all can be used as a placeholder for all plugins not explicitly named - # config.plugins = [ :exception_notification, :ssl_requirement, :all ] - - # Skip frameworks you're not going to use. To use Rails without a database, - # you must remove the Active Record framework. - # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] - - # Activate observers that should always be running - # config.active_record.observers = :cacher, :garbage_collector, :forum_observer - - # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. - # Run "rake -D time" for a list of tasks for finding time zone names. - config.time_zone = 'Yakutsk' - - # 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}')] - # config.i18n.default_locale = :de - require 'pdfkit' - config.middleware.use PDFKit::Middleware, :print_media_type => true, :page_size => "A4", :orientation => :landscape, :margin_top => "10mm", :margin_bottom => "10mm", :margin_left => "10mm", :margin_right => "10mm" -end +# Initialize the rails application +Taurus::Application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb index 85c9a60..c6c6bbd 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -1,17 +1,23 @@ -# Settings specified here will take precedence over those in config/environment.rb +Taurus::Application.configure do + # Settings specified here will take precedence over those in config/environment.rb -# 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 + # 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 + # 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_view.debug_rjs = true -config.action_controller.perform_caching = false + # Show full error reports and disable caching + config.consider_all_requests_local = true + config.action_view.debug_rjs = true + config.action_controller.perform_caching = false -# Don't care if the mailer can't send -config.action_mailer.raise_delivery_errors = false \ No newline at end of file + # Don't care if the mailer can't send + config.action_mailer.raise_delivery_errors = false + + # Report deprecation warnings + config.active_support.deprecation = :log + +end diff --git a/config/environments/production.rb b/config/environments/production.rb index 27119d2..b5fb330 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -1,28 +1,47 @@ -# Settings specified here will take precedence over those in config/environment.rb +Taurus::Application.configure do + # Settings specified here will take precedence over those in config/environment.rb -# The production environment is meant for finished, "live" apps. -# Code is not reloaded between requests -config.cache_classes = true + # The production environment is meant for finished, "live" apps. + # Code is not reloaded between requests + config.cache_classes = true -# Full error reports are disabled and caching is turned on -config.action_controller.consider_all_requests_local = false -config.action_controller.perform_caching = true -config.action_view.cache_template_loading = true + # Full error reports are disabled and caching is turned on + config.consider_all_requests_local = false + config.action_controller.perform_caching = true -# See everything in the log (default is :info) -# config.log_level = :debug + # Specifies the header that your server uses for sending files + config.action_dispatch.x_sendfile_header = "X-Sendfile" -# Use a different logger for distributed setups -# config.logger = SyslogLogger.new + # For nginx: + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' -# Use a different cache store in production -# config.cache_store = :mem_cache_store + # If you have no front-end server that supports something like X-Sendfile, + # just comment this out and Rails will serve the files -# Enable serving of images, stylesheets, and javascripts from an asset server -# config.action_controller.asset_host = "http://assets.example.com" + # See everything in the log (default is :info) + # config.log_level = :debug -# Disable delivery errors, bad email addresses will be ignored -# config.action_mailer.raise_delivery_errors = false + # Use a different logger for distributed setups + # config.logger = SyslogLogger.new -# Enable threaded mode -# config.threadsafe! \ No newline at end of file + # Use a different cache store in production + # config.cache_store = :mem_cache_store + + # Disable Rails's static asset server + # In production, Apache or nginx will already do this + config.serve_static_assets = false + + # Enable serving of images, stylesheets, and javascripts from an asset server + # config.action_controller.asset_host = "http://assets.example.com" + + # Disable delivery errors, bad email addresses will be ignored + # config.action_mailer.raise_delivery_errors = false + + # Enable threaded mode + # config.threadsafe! + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation can not be found) + config.i18n.fallbacks = true + +end diff --git a/config/environments/test.rb b/config/environments/test.rb index d6f80a4..679a540 100644 --- a/config/environments/test.rb +++ b/config/environments/test.rb @@ -1,28 +1,32 @@ -# Settings specified here will take precedence over those in config/environment.rb +Taurus::Application.configure do + # Settings specified here will take precedence over those in config/environment.rb -# The test environment is used exclusively to run your application's -# test suite. You never need to work with it otherwise. Remember that -# your test database is "scratch space" for the test suite and is wiped -# and recreated between test runs. Don't rely on the data there! -config.cache_classes = true + # The test environment is used exclusively to run your application's + # test suite. You never need to work with it otherwise. Remember that + # your test database is "scratch space" for the test suite and is wiped + # and recreated between test runs. Don't rely on the data there! + config.cache_classes = true -# Log error messages when you accidentally call methods on nil. -config.whiny_nils = true + # 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 -config.action_view.cache_template_loading = true + # Show full error reports and disable caching + config.consider_all_requests_local = true + config.action_controller.perform_caching = false -# Disable request forgery protection in test environment -config.action_controller.allow_forgery_protection = false + # Raise exceptions instead of rendering exception templates + config.action_dispatch.show_exceptions = false -# Tell Action Mailer not to deliver emails to the real world. -# The :test delivery method accumulates sent emails in the -# ActionMailer::Base.deliveries array. -config.action_mailer.delivery_method = :test + # Disable request forgery protection in test environment + config.action_controller.allow_forgery_protection = false -# Use SQL instead of Active Record's schema dumper when creating the test database. -# This is necessary if your schema can't be completely dumped by the schema dumper, -# like if you have constraints or database-specific column types -# config.active_record.schema_format = :sql \ No newline at end of file + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Use SQL instead of Active Record's schema dumper when creating the test database. + # This is necessary if your schema can't be completely dumped by the schema dumper, + # like if you have constraints or database-specific column types + # config.active_record.schema_format = :sql +end diff --git a/config/initializers/active_scaffold.rb b/config/initializers/active_scaffold.rb new file mode 100644 index 0000000..b9218d1 --- /dev/null +++ b/config/initializers/active_scaffold.rb @@ -0,0 +1,9 @@ +ActiveScaffold.js_framework = :prototype # :prototype is the default, :jquery as a variant + +ActiveScaffold.set_defaults do |config| + config.actions.exclude :show, :delete + config.search.live = true + config.ignore_columns.add [:created_at, :updated_at, :lock_version] + config.list.per_page = 30 + config.subform.layout = :vertical +end diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 96a5a13..60afaf1 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -1,3 +1,5 @@ +require 'devise/orm/active_record' + # Use this hook to configure devise mailer, warden hooks and so forth. The first # four configuration values can also be set straight in your models. Devise.setup do |config| @@ -20,7 +22,7 @@ # authentication tools as :clearance_sha1, :authlogic_sha512 (then you should set # stretches above to 20 for default behavior) and :restful_authentication_sha1 # (then you should set stretches to 10, and copy REST_AUTH_SITE_KEY to pepper) - # config.encryptor = :sha1 + config.encryptor = :sha1 # Configure which keys are used when authenticating an user. By default is # just :email. You can configure it to use [:username, :subdomain], so for diff --git a/config/initializers/new_rails_defaults.rb b/config/initializers/new_rails_defaults.rb deleted file mode 100644 index c94db0a..0000000 --- a/config/initializers/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/config/initializers/secret_token.rb b/config/initializers/secret_token.rb new file mode 100644 index 0000000..878aff1 --- /dev/null +++ b/config/initializers/secret_token.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +Taurus::Application.config.secret_token = 'fdbfccb520b43634b7c800a5553aa96cbebad050c542dbfd1bcee48ab77610d4274c64662f16e28fafcc19759982fc6a705ed4bb55f069d4b9742948e2bb9b68' diff --git a/config/initializers/session_store.rb b/config/initializers/session_store.rb index fbe3865..e219cef 100644 --- a/config/initializers/session_store.rb +++ b/config/initializers/session_store.rb @@ -1,15 +1,8 @@ # Be sure to restart your server when you modify this file. -# Your secret key for verifying cookie session data integrity. -# If you change this key, all old sessions will become invalid! -# Make sure the secret is at least 30 characters and all random, -# no regular words or you'll be exposed to dictionary attacks. -ActionController::Base.session = { - :key => '_taurus_session', - :secret => '3a04bef7899d2955f459a8d5519cc86adb1ad13041eee5d8668789380a116481602d2bfa457d9458ad12537fe6b5c030452dd61fe816d452eb3d0aaffdf6df78' -} +Rails.application.config.session_store :active_record_store, :key => '_taurus_session' # Use the database for sessions instead of the cookie-based default, # which shouldn't be used to store highly confidential information # (create the session table with "rake db:sessions:create") -ActionController::Base.session_store = :active_record_store +# Rails.application.config.session_store :active_record_store diff --git a/config/routes.rb b/config/routes.rb index 83e47f4..e0174df 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,103 +1,155 @@ -ActionController::Routing::Routes.draw do |map| - map.namespace :admin do |a| - a.resources :dept_heads, :active_scaffold => true - a.resources :editors, :active_scaffold => true - a.resources :supervisors, :active_scaffold => true - a.resources :admins, :active_scaffold => true - a.root :controller => 'dept_heads' +Taurus::Application.routes.draw do + +##### Отображение расписания ##### + + root :to => redirect('/timetable/groups') + + namespace :timetable do + resources :groups + resources :lecturers + root :to => redirect('/timetable/groups') end - map.namespace :editor do |e| - # Pair editor based on classrooms - e.namespace :classrooms do |c| - c.resources :classrooms - c.resources :pairs - c.resources :charge_cards - c.resources :classrooms_sheets - c.root :controller => 'classrooms' +##### Редакторский раздел ##### + + namespace :editor do + root :to => redirect('/editor/groups') + + # Редактор по аудиториям + namespace :classrooms do + resources :classrooms + resources :pairs + resources :charge_cards + resources :classrooms_sheets + root :to => 'classrooms#index' end - # Pair editor based on groups - e.namespace :groups do |g| - g.resources :groups - g.resources :pairs - g.resources :classrooms - g.resources :charge_cards - g.root :controller => 'groups' + + # Редактор по группам + namespace :groups do + resources :groups + resources :pairs + resources :classrooms + resources :charge_cards + root :to => 'groups#index' end - # Miscellaneous reference materials for editor needs - e.namespace :reference do |r| - r.resources :groups - r.resource :groups_list do |list| - list.resources :groups + + # Справочные материалы + namespace :reference do + resources :groups + resource :groups_list do + resources :groups end - r.resources :departments, :active_scaffold => true - r.resources :disciplines, :active_scaffold => true - r.resources :teaching_places, :active_scaffold => true - r.resources :charge_cards, :active_scaffold => true - r.connect 'teaching_plans', :controller => "teaching_plans", :action => "index" - r.connect 'teaching_plans/:group_id', :controller => "teaching_plans", :action => "show" - r.root :controller => 'classrooms_sheets' + resources :departments do as_routes end + resources :disciplines do as_routes end + resources :teaching_places do as_routes end + resources :charge_cards do as_routes end + get 'teaching_plans' => 'teaching_plans#index' + get 'teaching_plans/:group_id' => 'teaching_plans#show' + root :to => redirect('/editor/reference/classroom_sheets') end - e.root :controller => 'classrooms/classrooms_sheets' end - map.namespace :dept_head do |d| - d.resources :teaching_places, :active_scaffold => true, :collection => {:browse => :get}, :member => {:select => :post} - d.resources :disciplines, :active_scaffold => true, :collection => {:browse => :get}, :member => {:select => :post} - d.resources :groups, :active_scaffold => true, :collection => {:browse => :get}, :member => {:select => :post, :teaching_plan => :get} - d.resources :lecturers, :active_scaffold => true, :collection => {:browse => :get}, :member => {:select => :post} - d.resources :specialities, :active_scaffold => true, - :member => {:teaching_plan => :get, :create_charge_cards => :post, :add_charge_cards => :get}, - :collection => {:teaching_plan_import => [:get, :post]} - d.root :controller => 'teaching_places' - end - - map.namespace :supervisor do |s| - s.resources :faculties, :active_scaffold => true - s.resources :specialities, :active_scaffold => true, :member => {:teaching_plan => :get} - s.resources :groups, :active_scaffold => true, :member => {:teaching_plan => :get} - s.resources :classrooms, :active_scaffold => true - s.resources :lecturers, :active_scaffold => true - s.connect 'teaching_plans', :controller => "teaching_plans", :action => "new", :method => :get - s.connect 'teaching_plans/fill', :controller => "teaching_plans", :action => "fill", :method => :post - s.root :controller => 'lecturers' - end +##### Раздел заведующего кафедрой ##### - map.namespace :timetable do |t| - t.resources :groups - t.resources :lecturers - t.root :controller => 'groups' + namespace :dept_head do + resources :teaching_places do + as_routes + collection do get :browse end + member do post :select end + end + resources :disciplines do + as_routes + collection do get :browse end + member do post :select end + end + resources :groups do + as_routes + collection do get :browse end + member do + post :select + get :teaching_plan + end + end + resources :lecturers do + as_routes + collection do get :browse end + member do post :select end + end + resources :charge_cards do + as_routes + end + resources :specialities do + as_routes + collection do + get :teaching_plan_import + post :teaching_plan_import + end + member do + get :add_charge_cards + get :teaching_plan + post :create_charge_cards + end + end + root :to => redirect('/dept_head/teaching_places') end - map.resources :classrooms +##### Раздел супервайзера ##### -# map.admin_root '/admin/departments', :controller => 'admin/dept_heads' -# map.editor_root '/editor/classrooms', :controller => 'editor/classrooms' -# map.supervisor_root '/supervisor/lecturers', :controller => 'supervisor/lecturers' -# map.dept_head_root '/dept_head/lecturers', :controller => 'dept_head/teaching_places' + namespace :supervisor do + resources :faculties do as_routes end + resources :specialities do + as_routes + member do get :teaching_plan end + end + resources :groups do + as_routes + member do get :teaching_plan end + end + resources :classrooms do as_routes end + resources :lecturers do as_routes end + resources :departments do as_routes end + get 'teaching_plans' => 'teaching_plans#new' + post 'teaching_plans/fill' => 'teaching_plans#fill' + root :to => redirect('/supervisor/lecturers') + end - map.devise_for :admin, :path_names => { :sign_in => 'login', :sign_out => 'logout'} - map.new_admin_session '/admin/login', :controller => 'sessions', :action => 'new', :conditions => { :method => :get } - map.admin_session '/admin/login', :controller => 'sessions', :action => 'create', :conditions => { :method => :post } - map.destroy_admin_session '/admin/logout', :controller => 'sessions', :action => 'destroy', :conditions => { :method => :get } +##### Администраторский раздел ##### - map.devise_for :editor, :path_names => { :sign_in => 'login', :sign_out => 'logout'} - map.new_editor_session '/editor/login', :controller => 'sessions', :action => 'new', :conditions => { :method => :get } - map.editor_session '/editor/login', :controller => 'sessions', :action => 'create', :conditions => { :method => :post } - map.destroy_editor_session '/editor/logout', :controller => 'sessions', :action => 'destroy', :conditions => { :method => :get } + namespace :admin do + resources :dept_heads do as_routes end + resources :editors do as_routes end + resources :supervisors do as_routes end + resources :admins do as_routes end + root :to => redirect('/admin/dept_heads') + end - map.devise_for :supervisor, :path_names => { :sign_in => 'login', :sign_out => 'logout'} - map.new_supervisor_session '/supervisor/login', :controller => 'sessions', :action => 'new', :conditions => { :method => :get } - map.supervisor_session '/supervisor/login', :controller => 'sessions', :action => 'create', :conditions => { :method => :post } - map.destroy_supervisor_session '/supervisor/logout', :controller => 'sessions', :action => 'destroy', :conditions => { :method => :get } +##### Аутентификация ##### - map.devise_for :dept_head, :path_names => { :sign_in => 'login', :sign_out => 'logout'} - map.new_dept_head_session '/dept_head/login', :controller => 'sessions', :action => 'new', :conditions => { :method => :get } - map.dept_head_session '/dept_head/login', :controller => 'sessions', :action => 'create', :conditions => { :method => :post } - map.destroy_dept_head_session '/dept_head/logout', :controller => 'sessions', :action => 'destroy', :conditions => { :method => :get } + devise_for :admin, :skip => [:sessions] + devise_scope :admin do + get 'admin/login' => 'devise/sessions#new', :as => :new_admin_session + post 'admin/login' => 'devise/sessions#create', :as => :admin_session + delete 'admin/logout' => 'devise/sessions#destroy', :as => :destroy_admin_session + end + devise_for :editor, :skip => [:sessions] + devise_scope :editor do + get 'editor/login' => 'devise/sessions#new', :as => :new_editor_session + post 'editor/login' => 'devise/sessions#create', :as => :editor_session + delete 'editor/logout' => 'devise/sessions#destroy', :as => :destroy_editor_session + end + devise_for :dept_head, :skip => [:sessions] + devise_scope :dept_head do + get 'dept_head/login' => 'devise/sessions#new', :as => :new_dept_head_session + post 'dept_head/login' => 'devise/sessions#create', :as => :dept_head_session + delete 'dept_head/logout' => 'devise/sessions#destroy', :as => :destroy_dept_head_session + end + devise_for :supervisor, :skip => [:sessions] + devise_scope :supervisor do + get 'supervisor/login' => 'devise/sessions#new', :as => :new_supervisor_session + post 'supervisor/login' => 'devise/sessions#create', :as => :supervisor_session + delete 'supervisor/logout' => 'devise/sessions#destroy', :as => :destroy_supervisor_session + end - map.root :controller => "timetable/groups" + match '/:controller(/:action(/:id))' - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' end diff --git a/db/schema.rb b/db/schema.rb index 945f45d..0735b2b 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,10 +1,11 @@ -# This file is auto-generated from the current state of the database. Instead of editing this file, -# please use the migrations feature of Active Record to incrementally modify your database, and -# then regenerate this schema definition. +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. # -# Note that this schema.rb definition is the authoritative source for your database schema. If you need -# to create the application database on another system, you should be using db:schema:load, not running -# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations +# Note that this schema.rb definition is the authoritative source for your +# database schema. If you need to create the application database on another +# system, you should be using db:schema:load, not running all the migrations +# from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended to check this file into your version control system. diff --git a/lib/tasks/.gitkeep b/lib/tasks/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/public/images/active_scaffold/default/close_touch.png b/public/images/active_scaffold/default/close_touch.png new file mode 100644 index 0000000000000000000000000000000000000000..73b2ad63d36011f98686d95cace7631313ec745d GIT binary patch literal 391 zcmV;20eJq2P)P000{Z0{{R3zW>x(00001b5ch_0Itp) z=>Px#qEJj!MHX`p7jq67cM2PM2OfO_AAbNAa1;_}D-&od6lf|KYc3gVE*fty9&s-s zb2ce?J1crTB7p-bg$p{5A2EPJJ%~+6moHYIKWwXVZmx8FwQGdAbC=AOpvjY`&6~X0 zv$W!`w&Sq5=Ci-*x5M4L#_+w#^1sja#LxG{)#uOH>C@5p#?tx5)B4EO`^nk<%-a9W z=JDh7`SbYu_xt_(|NsBC_sr%1000SaNLh0L01FcU01FcV0GgZ_0001fNklljelzT0-*r(R^U;(?$&f}m%489RMo2>QXa%4 zB674tRhCf6O@zGXSX^Z%9=64qL<KTsd(L2%Nfb28ake(Nc)gcnjiHl06Vi5zr`8 z(3F?(m8sa))$`m0WS?l=+qJX%?3~|q&b{3f0P254(UJXrb9jGiI#k0{pbFjlDki*T zsNK65bM9bxejAF{MGVvdfg*Ucf>99P^0^-hR9&S2%@qIt{DU3aL~IrBX@O zh{xkltJMZF!Qku$_KzEIr<%^br7DT7!cwWkIkl(KYIP_Ui*UJIkjv$u`d_XSfR}Cb z{UM9R0=L_ZLZJY?UJqxoLZsE{kj-XUkQPFr5LDmuPuODtfppV3xYCS`Mgz%Y5)8w@ z@Angkj%{{2orpvt5Q#*37I1~SZ(2p|=nR#EQ|#1EP^{GPb@v#bw+~@78VP`#hFgbg zG?`3@Mxz`6VzKxVB{AfpV(m)(_QW!7K24!#B!TNn23O@VNMzIK?d?U6)DE-R43$cS wYY%A%1cIMD9`7A_#BRT>L?Qv7&&S{SUnp5P#YQSqod5s;07*qoM6N<$f_olE%m4rY literal 0 HcmV?d00001 diff --git a/public/images/active_scaffold/default/gears.png b/public/images/active_scaffold/default/gears.png new file mode 100644 index 0000000000000000000000000000000000000000..9857c1c52467bd5a5d6f9b63f2f6638c6a7b969d GIT binary patch literal 1741 zcmV;;1~U1HP)4Tx0C)j~RL^S@K@|QrZmG~B2wH0nvUrdpNm;9CMbtL^5n^i$+aIn^?(HA4aZWV5ov6ELTdbo0FI&wK{O>*+w4vx20?>!`FrQsdJlnHR>OPy zcd~b_n$otK2Za4V;76L-DzNVtaSB-y0*E}{p()372;bw_^6ZZ}PI-92wGS&j#91PI zKs7DSe@(bk%_Y-7gGe}(^>I=@oY#w#*Bu9GZf3^F5WP>3rn}7Ut74&?PWBFvy`A)a zPP5)V!Xd&78LdA?xQ(9mjMYElVd13a#D+Z_7&Y|xU=_C-srWU*6kiZcC!$nw*)9$7 zn6CX+@=AhmkT}X@VSsa5NKe;HZuq)~1$`#h6R+ZTR#D-3j}vF!)ZOnz+5)dI4jl{{ z44Mr{P!L4~VVJN`K!!XTF*LGrKO?IK8z<8w`3e3jI8lUGNUta*C8 zn(P`s>{pjD=7Kek#B;Fw@hxAK%$F&Q6vg9J^Xf~4by_hu-=A!MJ3Znq&n~srbFGPs zH&&aMXZ>nO`|hf|ljc?VPhR!${AbO?W8x_>CU%PFA&Hm8F7cAsOREdwU~R_;ot1_u z(ruCYB-LPGn!NQdT|ZlRy+(fw^-+`=%+gee_kY4FWHg<*4sZI8+sFJD270UUORdLHO0nA4V) z%{fwsET5CQ>B?eK%uw4yQc~9?*JVo2}ze(;aRcp*ceL#HUJSllrgm5wQKR zQu+C;QrUh^8rFfA`ftFz{YAidi-`aL010qNS#tmY4c7nw4c7reD4Tcy00V_dL_t(I z5nWPkXj^3zKJUFZZN9&5+T3)e+D<#HV6_>o5{0gRwmByLa6@G3kLvWtP|(3dikQOw zOeupoT&pY7>Vy%gb4#_;r81g+jCS2Rx3P3FrXNX~v`LzK^KqNp`+DD4rFh`*zVCC+ zbKZw@4q%L7)6tfD1q(+a$Cejk$NrBiZ*&14paBE=mrRo+pU>A6k0(cmM@Blydo7X4 zEkqad0MO_g^Bs&tq9a$oxVdd>K}HE8#U;gIe0-MMy=QMnhr6TcMsOziK)POCR;}Ql zW4-eT?o(-2hMV zLx&FwkiNE&cGndtms|gUr zf($wcV1!p_j7AAr=`*r8pZl&f?b`i(<4%=Eqmwv?lM$9S-eBhbxNlloUbSd+I=RMT zg2yaR;Mw9Yb2g(nQEipX{}jOZ)ZP~_e*5+Ql0jo<*3)?ig;QcO9j_*FT5(Iy@xFWC zpZDY6CjI!(nLS^@XVAQF$l*FX?J|+M4-5_-y?r-`2L>-=&+#+&6b`F6Lly|{*x_n7 z7>tLis;l%IYsanI+ge@plYDNed|MxFpyjltYv$K&A2VS}6^_~xt zMS`^yf1=jz;3%q;&*wL^cEdLO(zB0#*!lPi?=h$fYHYQdL}C^5d>+xXlviuCTw*15 zLZP--3d~Fgj>r_Y#g`)G?(R>#2vJ5{M8FzZ4f%lQvw&r#_f$FC-*@t5?xBYnN=B;y zuL2n(S!GNT&z}9Jtz%c`R8CmWV30C(4u_NA(O7H|0d3alP3GT6{q0>{uU{v)Vu&mf z_INxMCDCY9T3GyRZen8Mt*2UAT8qV^NSxdWMq(s~FgH2Mw3QBTT15#`j5L;Dfk2>_ joNl-KeR6Jz{iphG{%hOHrFy$+00000NkvXXu0mjfTyS46 literal 0 HcmV?d00001 diff --git a/public/javascripts/active_scaffold/default/active_scaffold.js b/public/javascripts/active_scaffold/default/active_scaffold.js index af64bd0..4872e16 100644 --- a/public/javascripts/active_scaffold/default/active_scaffold.js +++ b/public/javascripts/active_scaffold/default/active_scaffold.js @@ -11,6 +11,280 @@ if (Prototype.Version.substring(0, 3) < '1.6') if (!Element.Methods.highlight) Element.addMethods({highlight: Prototype.emptyFunction}); +document.observe("dom:loaded", function() { + document.on('ajax:create', 'form.as_form', function(event) { + var source = event.findElement(); + var as_form = event.findElement('form'); + if (source.nodeName.toUpperCase() == 'INPUT' && source.readAttribute('type') == 'button') { + // Hack: Prototype or rails.js somehow screw up event handling if someone clicks + // a button of type button such as Create Another + // as a result form is disabled but never reenabled.. + } else { + if (as_form && as_form.readAttribute('data-loading') == 'true') { + ActiveScaffold.disable_form(as_form); + } + } + return true; + }); + document.on('ajax:complete', 'form.as_form', function(event) { + var as_form = event.findElement('form'); + if (as_form && as_form.readAttribute('data-loading') == 'true') { + ActiveScaffold.enable_form(as_form); + event.stop(); + return false; + } + }); + document.on('ajax:failure', 'form.as_form', function(event) { + var as_div = event.findElement('div.active-scaffold'); + if (as_div) { + ActiveScaffold.report_500_response(as_div) + event.stop(); + return false; + } + }); + document.on('submit', 'form.as_form.as_remote_upload', function(event) { + var as_form = event.findElement('form'); + if (as_form && as_form.readAttribute('data-loading') == 'true') { + setTimeout("ActiveScaffold.disable_form('" + as_form.readAttribute('id') + "')", 10); + } + return true; + }); + document.on('ajax:before', 'a.as_action', function(event) { + var action_link = ActiveScaffold.ActionLink.get(event.findElement()); + if (action_link) { + if (action_link.is_disabled()) { + event.stop(); + } else { + if (action_link.loading_indicator) action_link.loading_indicator.style.visibility = 'visible'; + action_link.disable(); + } + } + return true; + }); + document.on('ajax:success', 'a.as_action', function(event) { + var action_link = ActiveScaffold.ActionLink.get(event.findElement()); + if (action_link && event.memo && event.memo.request) { + if (action_link.position) { + action_link.insert(event.memo.request.transport.responseText); + if (action_link.hide_target) action_link.target.hide(); + } else { + //event.memo.request.evalResponse(); // (clyfe) prototype evals the response by itself checking headers, this would eval twice + action_link.enable(); + } + event.stop(); + } + return true; + }); + document.on('ajax:complete', 'a.as_action', function(event) { + var action_link = ActiveScaffold.ActionLink.get(event.findElement()); + if (action_link && action_link.loading_indicator) { + action_link.loading_indicator.style.visibility = 'hidden'; + } + return true; + }); + document.on('ajax:failure', 'a.as_action', function(event) { + var action_link = ActiveScaffold.ActionLink.get(event.findElement()); + if (action_link) { + ActiveScaffold.report_500_response(action_link.scaffold_id()); + action_link.enable(); + } + return true; + }); + document.on('ajax:before', 'a.as_cancel', function(event) { + var as_cancel = event.findElement(); + var action_link = ActiveScaffold.find_action_link(as_cancel); + + if (action_link) { + var refresh_data = as_cancel.readAttribute('data-refresh'); + if (refresh_data === 'true' && action_link.refresh_url) { + event.memo.url = action_link.refresh_url; + } else if (refresh_data === 'false' || as_cancel.readAttribute('href').blank()) { + action_link.close(); + event.stop(); + } + } + return true; + }); + document.on('ajax:success', 'a.as_cancel', function(event) { + var action_link = ActiveScaffold.find_action_link(event.findElement()); + if (action_link) { + if (action_link.position) { + action_link.close(event.memo.request.responseText); + } else { + event.memo.request.evalResponse(); + } + } + return true; + }); + document.on('ajax:failure', 'a.as_cancel', function(event) { + var action_link = ActiveScaffold.find_action_link(event.findElement()); + if (action_link) { + ActiveScaffold.report_500_response(action_link.scaffold_id()); + } + return true; + }); + document.on('ajax:before', 'a.as_sort', function(event) { + var as_sort = event.findElement(); + var history_controller_id = as_sort.readAttribute('data-page-history'); + if (history_controller_id) addActiveScaffoldPageToHistory(as_sort.readAttribute('href'), history_controller_id); + as_sort.up('th').addClassName('loading'); + return true; + }); + document.on('ajax:failure', 'a.as_sort', function(event) { + var as_scaffold = event.findElement('.active-scaffold'); + ActiveScaffold.report_500_response(as_scaffold); + return true; + }); + document.on('mouseover', 'span.in_place_editor_field', function(event) { + event.findElement().addClassName('hover'); + }); + document.on('mouseout', 'span.in_place_editor_field', function(event) { + event.findElement().removeClassName('hover'); + }); + document.on('click', 'span.in_place_editor_field', function(event) { + var span = event.findElement('span.in_place_editor_field'); + + if (typeof(span.inplace_edit) === 'undefined') { + var options = {htmlResponse: false, + onEnterHover: null, + onLeaveHover: null, + onComplete: null, + params: '', + ajaxOptions: {method: 'post'}}, + csrf_param = $$('meta[name=csrf-param]')[0], + csrf_token = $$('meta[name=csrf-token]')[0], + my_parent = span.up(), + column_heading = null; + + if(!(my_parent.nodeName.toLowerCase() === 'td' || my_parent.nodeName.toLowerCase() === 'th')){ + my_parent = span.up('td'); + } + + if (my_parent.nodeName.toLowerCase() === 'td') { + var heading_selector = '.' + span.up().readAttribute('class').split(' ')[0] + '_heading'; + column_heading = span.up('.active-scaffold').down(heading_selector); + } else if (my_parent.nodeName.toLowerCase() === 'th') { + column_heading = my_parent; + } + + var render_url = column_heading.readAttribute('data-ie_render_url'), + mode = column_heading.readAttribute('data-ie_mode'), + record_id = span.readAttribute('data-ie_id'); + + ActiveScaffold.read_inplace_edit_heading_attributes(column_heading, options); + + if (span.readAttribute('data-ie_url')) { + options.url = span.readAttribute('data-ie_url'); + } else { + options.url = column_heading.readAttribute('data-ie_url'); + } + if (record_id) options.url = options.url.sub('__id__', record_id); + + if (csrf_param) options['params'] = csrf_param.readAttribute('content') + '=' + csrf_token.readAttribute('content'); + + if (span.up('div.active-scaffold').readAttribute('data-eid')) { + if (options['params'].length > 0) { + options['params'] += "&"; + } + options['params'] += ("eid=" + span.up('div.active-scaffold').readAttribute('data-eid')); + } + + if (mode === 'clone') { + options.nodeIdSuffix = record_id; + options.inplacePatternSelector = '#' + column_heading.readAttribute('id') + ' .as_inplace_pattern'; + options['onFormCustomization'] = new Function('element', 'form', 'element.clonePatternField();'); + } + + if (render_url) { + var plural = false; + if (column_heading.readAttribute('data-ie_plural')) plural = true; + options['onFormCustomization'] = new Function('element', 'form', 'element.setFieldFromAjax(' + "'" + render_url.sub('__id__', record_id) + "', {plural: " + plural + '});'); + } + + if (mode === 'inline_checkbox') { + ActiveScaffold.process_checkbox_inplace_edit(span.down('input[type="checkbox"]'), options); + } else { + ActiveScaffold.create_inplace_editor(span, options); + } + } + return true; + }); + document.on('ajax:before', 'a.as_paginate', function(event) { + var as_paginate = event.findElement(); + var loading_indicator = as_paginate.up().down('img.loading-indicator'); + var history_controller_id = as_paginate.readAttribute('data-page-history'); + + if (history_controller_id) addActiveScaffoldPageToHistory(as_paginate.readAttribute('href'), history_controller_id); + if (loading_indicator) loading_indicator.style.visibility = 'visible'; + return true; + }); + document.on('ajax:failure', 'a.as_paginate', function(event) { + var as_scaffold = event.findElement('.active-scaffold'); + ActiveScaffold.report_500_response(as_scaffold); + return true; + }); + document.on('ajax:complete', 'a.as_paginate', function(event) { + var as_paginate = event.findElement(); + var loading_indicator = as_paginate.up().down('img.loading-indicator'); + + if(loading_indicator) loading_indicator.style.visibility = 'hidden'; + return true; + }); + document.on('ajax:before', 'a.as_add_existing, a.as_replace_existing', function(event) { + var button = event.findElement(); + var url = button.readAttribute('href').sub('--ID--', button.previous().getValue()); + event.memo.url = url; + return true; + }); + document.on('change', 'input.update_form, select.update_form', function(event) { + var element = event.findElement(); + ActiveScaffold.update_column(element, element.readAttribute('data-update_url'), element.hasAttribute('data-update_send_form'), element.readAttribute('id'), element.getValue()); + return true; + }); + document.on('change', 'select.as_search_range_option', function(event) { + var element = event.findElement(); + Element[element.value == 'BETWEEN' ? 'show' : 'hide'](element.readAttribute('id').sub('_opt', '_between')); + return true; + }); + document.on('change', 'select.as_search_date_time_option', function(event) { + var element = event.findElement(); + Element[!(element.value == 'PAST' || element.value == 'FUTURE' || element.value == 'RANGE') ? 'show' : 'hide'](element.readAttribute('id').sub('_opt', '_numeric')); + Element[(element.value == 'PAST' || element.value == 'FUTURE') ? 'show' : 'hide'](element.readAttribute('id').sub('_opt', '_trend')); + Element[element.value == 'RANGE' ? 'show' : 'hide'](element.readAttribute('id').sub('_opt', '_range')); + return true; + }); + document.on('change', 'select.as_update_date_operator', function(event) { + var element = event.findElement(); + Element[element.value == 'REPLACE' ? 'show' : 'hide'](element.next()); + Element[element.value == 'REPLACE' ? 'show' : 'hide'](element.next().next()); + Element[element.value == 'REPLACE' ? 'hide' : 'show'](element.next('span')); + return true; + }); + document.on("click", "a[data-popup]", function(event, element) { + if (event.stopped) return; + window.open($(element).href); + event.stop(); + }); + document.on("click", ".hover_click", function(event, element) { + var ul_element = element.down('ul'); + if (ul_element.getStyle('display') === 'none') { + ul_element.style.display = 'block'; + } else { + ul_element.style.display = 'none'; + } + + return true; + }); + document.on("click", ".hover_click a.as_action", function(event, element) { + var element = element.up('.hover_click').down('ul'); + if (element) { + element.style.display = 'none'; + } + return true; + }); +}); + + /* * Simple utility methods */ @@ -44,9 +318,10 @@ var ActiveScaffold = { } } }, - hide_empty_message: function(tbody, empty_message_id) { + hide_empty_message: function(tbody) { if (this.records_for(tbody).length != 0) { - $(empty_message_id).hide(); + var empty_message_nodes = $(tbody).up().select('tbody.messages p.empty-message') + empty_message_nodes.invoke('hide'); } }, reload_if_empty: function(tbody, url) { @@ -58,38 +333,297 @@ var ActiveScaffold = { }); } }, - removeSortClasses: function(scaffold_id) { - $$('#' + scaffold_id + ' td.sorted').each(function(element) { + removeSortClasses: function(scaffold) { + scaffold = $(scaffold) + scaffold.select('td.sorted').each(function(element) { element.removeClassName("sorted"); }); - $$('#' + scaffold_id + ' th.sorted').each(function(element) { + scaffold.select('th.sorted').each(function(element) { element.removeClassName("sorted"); element.removeClassName("asc"); element.removeClassName("desc"); }); }, - decrement_record_count: function(scaffold_id) { + decrement_record_count: function(scaffold) { // decrement the last record count, firsts record count are in nested lists - count = $$('#' + scaffold_id + ' span.active-scaffold-records').last(); + scaffold = $(scaffold) + count = scaffold.select('span.active-scaffold-records').last(); if (count) count.update(parseInt(count.innerHTML, 10) - 1); }, - increment_record_count: function(scaffold_id) { + increment_record_count: function(scaffold) { // increment the last record count, firsts record count are in nested lists - count = $$('#' + scaffold_id + ' span.active-scaffold-records').last(); + scaffold = $(scaffold) + count = scaffold.select('span.active-scaffold-records').last(); if (count) count.update(parseInt(count.innerHTML, 10) + 1); }, update_row: function(row, html) { row = $(row); - Element.replace(row, html); - var new_row = $(row.id); + var new_row = this.replace(row, html) if (row.hasClassName('even-record')) new_row.addClassName('even-record'); new_row.highlight(); }, + + replace: function(element, html) { + element = $(element) + Element.replace(element, html); + element = $(element.readAttribute('id')); + return element; + }, + + replace_html: function(element, html) { + element = $(element); + element.update(html); + return element; + }, + + remove: function(element) { + $(element).remove(); + }, + + hide: function(element) { + $(element).hide(); + }, + + show: function(element) { + $(element).show(); + }, + + reset_form: function(element) { + $(element).reset(); + }, + + disable_form: function(as_form) { + as_form = $(as_form) + var loading_indicator = $(as_form.readAttribute('id').sub('-form', '-loading-indicator')); + if (loading_indicator) loading_indicator.style.visibility = 'visible'; + as_form.disable(); + }, + + enable_form: function(as_form) { + as_form = $(as_form) + var loading_indicator = $(as_form.readAttribute('id').sub('-form', '-loading-indicator')); + if (loading_indicator) loading_indicator.style.visibility = 'hidden'; + as_form.enable(); + }, + + focus_first_element_of_form: function(form_element) { + Form.focusFirstElement(form_element); + }, + + create_record_row: function(active_scaffold_id, html, options) { + tbody = $(active_scaffold_id).down('tbody.records'); + + var new_row = null; + + if (options.insert_at == 'top') { + tbody.insert({top: html}); + new_row = tbody.firstDescendant(); + } else if (options.insert_at == 'bottom') { + var last_row = tbody.childElements().reverse().detect(function(node) { return node.hasClassName('record') || node.hasClassName('inline-adapter')}); + if (last_row) { + last_row.insert({after: html}); + } else { + tbody.insert({bottom: html}); + } + new_row = Selector.findChildElements(tbody, ['tr.record']).last(); + } + + this.stripe(tbody); + this.hide_empty_message(tbody); + this.increment_record_count(tbody.up('div.active-scaffold')); + new_row.highlight(); + }, + + delete_record_row: function(row, page_reload_url) { + row = $(row); + var tbody = row.up('tbody.records'); + + var current_action_node = row.down('td.actions a.disabled'); + + if (current_action_node) { + var action_link = ActiveScaffold.ActionLink.get(current_action_node); + if (action_link) { + action_link.close_previous_adapter(); + } + } + row.remove(); + tbody = $(tbody); + this.stripe(tbody); + this.decrement_record_count(tbody.up('div.active-scaffold')); + this.reload_if_empty(tbody, page_reload_url); + }, + + delete_subform_record: function(record) { + var errors = $(record).previous(); + if (errors.hasClassName('association-record-errors')) { + this.replace_html(errors, ''); + } + this.remove(record); + }, - server_error_response: '', report_500_response: function(active_scaffold_id) { - messages_container = $(active_scaffold_id).down('td.messages-container'); - new Insertion.Top(messages_container, this.server_error_response); + server_error = $(active_scaffold_id).down('td.messages-container p.server-error'); + if (server_error.visible()) { + server_error.highlight(); + } else { + server_error.show(); + } + }, + + find_action_link: function(element) { + return ActiveScaffold.ActionLink.get($(element).up('.as_adapter')); + }, + + scroll_to: function(element) { + $(element).scrollTo(); + }, + + process_checkbox_inplace_edit: function(checkbox, options) { + var checked = checkbox.readAttribute('checked'); + // checked attribute is nt updated + if (checked !== 'checked') options['params'] += '&value=1'; + new Ajax.Request(options.url, { + method: 'post', + parameters: options['params'], + onCreate: function(response) { + checkbox.disable(); + }, + onComplete: function(response) { + checkbox.enable(); + } + }); + }, + + read_inplace_edit_heading_attributes: function(column_heading, options) { + if (column_heading.readAttribute('data-ie_cancel_text')) options.cancelText = column_heading.readAttribute('data-ie_cancel_text'); + if (column_heading.readAttribute('data-ie_loading_text')) options.loadingText = column_heading.readAttribute('data-ie_loading_text'); + if (column_heading.readAttribute('data-ie_saving_text')) options.savingText = column_heading.readAttribute('data-ie_saving_text'); + if (column_heading.readAttribute('data-ie_save_text')) options.okText = column_heading.readAttribute('data-ie_save_text'); + if (column_heading.readAttribute('data-ie_rows')) options.rows = column_heading.readAttribute('data-ie_rows'); + if (column_heading.readAttribute('data-ie_cols')) options.cols = column_heading.readAttribute('data-ie_cols'); + if (column_heading.readAttribute('data-ie_size')) options.size = column_heading.readAttribute('data-ie_size'); + }, + + create_inplace_editor: function(span, options) { + if (options['params'].length > 0) { + options['callback'] = new Function('form', 'return Form.serialize(form) + ' + "'&" + options['params'] + "';"); + } + span.removeClassName('hover'); + span.inplace_edit = new ActiveScaffold.InPlaceEditor(span.readAttribute('id'), options.url, options) + span.inplace_edit.enterEditMode(); + }, + + create_visibility_toggle: function(element, options) { + var toggable = $(element); + var toggler = toggable.previous(); + var initial_label = (options.default_visible === true) ? options.hide_label : options.show_label; + + toggler.insert(' (' + initial_label + ')'); + toggler.firstDescendant().observe('click', function(event) { + var element = event.element(); + toggable.toggle(); + element.innerHTML = (toggable.style.display == 'none') ? options.show_label : options.hide_label; + return false; + }); + }, + + create_associated_record_form: function(element, content, options) { + var element = $(element); + if (options.singular == false) { + if (!(options.id && $(options.id))) { + element.insert(content); + } + } else { + var current = $$('#' + element.readAttribute('id') + ' .association-record'); + if (current[0]) { + this.replace(current[0], content); + } else { + element.insert({top: content}); + } + } + }, + + render_form_field: function(source, content, options) { + var source = $(source); + var element = source.up('.association-record'); + if (typeof(element) === 'undefined') { + element = source.up('ol.form'); + } + element = element.down('.' + options.field_class); + + if (element) { + if (options.is_subform == false) { + this.replace(element.up('dl'), content); + } else { + this.replace_html(element, content); + } + } + }, + + record_select_onselect: function(edit_associated_url, active_scaffold_id, id){ + new Ajax.Request( + edit_associated_url.sub('--ID--', id), { + asynchronous: true, + evalScripts: true, + onFailure: function(){ + ActiveScaffold.report_500_response(active_scaffold_id.to_json) + } + } + ); + }, + + // element is tbody id + mark_records: function(element, options) { + var element = $(element); + var mark_checkboxes = $$('#' + element.readAttribute('id') + ' > tr.record td.marked-column input[type="checkbox"]'); + mark_checkboxes.each(function(item) { + if(options.checked === true) { + item.writeAttribute({ checked: 'checked' }); + } else { + item.removeAttribute('checked'); + } + item.writeAttribute('value', ('' + !options.checked)); + }); + if(options.include_mark_all === true) { + var mark_all_checkbox = element.previous('thead').down('th.marked-column_heading span input[type="checkbox"]'); + if(options.checked === true) { + mark_all_checkbox.writeAttribute({ checked: 'checked' }); + } else { + mark_all_checkbox.removeAttribute('checked'); + } + mark_all_checkbox.writeAttribute('value', ('' + !options.checked)); + } + }, + + update_column: function(element, url, send_form, source_id, val) { + var as_form = element.up('form.as_form'); + var params = null; + + if (send_form) { + params = as_form.serialize(true); + } else { + params = {value: val}; + } + params.source_id = source_id; + + new Ajax.Request(url, { + method: 'get', + parameters: params, + onLoading: function(response) { + element.next('img.loading-indicator').style.visibility = 'visible'; + as_form.disable(); + }, + onComplete: function(response) { + element.next('img.loading-indicator').style.visibility = 'hidden'; + as_form.enable(); + }, + onFailure: function(request) { + var as_div = event.findElement('div.active-scaffold'); + if (as_div) { + ActiveScaffold.report_500_response(as_div) + } + } + }); } } @@ -193,79 +727,45 @@ ActiveScaffold.Actions.Abstract = Class.create({ * A DataStructures::ActionLink, represented in JavaScript. * Concerned with AJAX-enabling a link and adapting the result for insertion into the table. */ -ActiveScaffold.ActionLink = new Object(); +ActiveScaffold.ActionLink = { + get: function(element) { + var element = $(element); + if (typeof(element.retrieve('action_link')) === 'undefined' && !element.hasClassName('as_adapter')) { + var parent = element.up('.actions'); + if (typeof(parent) === 'undefined') { + // maybe an column action_link + parent = element.up(); + } + if (parent && parent.nodeName.toUpperCase() == 'TD') { + // record action + parent = parent.up('tr.record') + new ActiveScaffold.Actions.Record(parent.select('a.as_action'), parent, parent.down('td.actions .loading-indicator')); + } else if (parent && parent.nodeName.toUpperCase() == 'DIV') { + //table action + new ActiveScaffold.Actions.Table(parent.select('a.as_action'), parent.up('div.active-scaffold').down('tbody.before-header'), parent.down('.loading-indicator')); + } + element = $(element); + } + return element.retrieve('action_link'); + } +}; + ActiveScaffold.ActionLink.Abstract = Class.create({ initialize: function(a, target, loading_indicator) { this.tag = $(a); this.url = this.tag.href; - this.method = 'get'; - if(this.url.match('_method=delete')){ - this.method = 'delete'; - } else if(this.url.match('_method=post')){ - this.method = 'post'; - } else if(this.url.match('_method=put')){ - this.method = 'put'; - } + this.method = this.tag.readAttribute('data-method') || 'get'; this.target = target; this.loading_indicator = loading_indicator; this.hide_target = false; - this.position = this.tag.getAttribute('position'); - this.page_link = this.tag.getAttribute('page_link'); - - this.onclick = this.tag.onclick; - this.tag.onclick = null; - this.tag.observe('click', function(event) { - this.open(); - Event.stop(event); - }.bind(this)); - - this.tag.action_link = this; + this.position = this.tag.readAttribute('data-position'); + + this.tag.store('action_link', this); }, - open: function() { - if (this.is_disabled()) return; - - if (this.tag.hasAttribute( "dhtml_confirm")) { - if (this.onclick) this.onclick(); - return; - } else { - if (this.onclick && !this.onclick()) return;//e.g. confirmation messages - this.open_action(); - } - }, - - open_action: function() { - if (this.position) this.disable(); - - if (this.page_link) { - window.location = this.url; - } else { - if (this.loading_indicator) this.loading_indicator.style.visibility = 'visible'; - new Ajax.Request(this.url, { - asynchronous: true, - evalScripts: true, - method: this.method, - onSuccess: function(request) { - if (this.position) { - this.insert(request.responseText); - if (this.hide_target) this.target.hide(); - } else { - request.evalResponse(); - } - }.bind(this), - - onFailure: function(request) { - ActiveScaffold.report_500_response(this.scaffold_id()); - if (this.position) this.enable() - }.bind(this), - - onComplete: function(request) { - if (this.loading_indicator) this.loading_indicator.style.visibility = 'hidden'; - }.bind(this) - }); - } + open: function(event) { }, - + insert: function(content) { throw 'unimplemented' }, @@ -276,20 +776,6 @@ ActiveScaffold.ActionLink.Abstract = Class.create({ if (this.hide_target) this.target.show(); }, - close_handler: function(event) { - this.close(); - if (event) Event.stop(event); - }, - - register_cancel_hooks: function() { - // anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure - var self = this; - this.adapter.select('.cancel').each(function(elem) { - elem.observe('click', this.close_handler.bind(this)); - elem.link = self; - }.bind(this)) - }, - reload: function() { this.close(); this.open(); @@ -315,7 +801,22 @@ ActiveScaffold.ActionLink.Abstract = Class.create({ }, scaffold_id: function() { - return this.tag.up('div.active-scaffold').id; + return this.tag.up('div.active-scaffold').readAttribute('id'); + }, + + scaffold: function() { + return this.tag.up('div.active-scaffold'); + }, + + update_flash_messages: function(messages) { + message_node = $(this.scaffold_id().sub('-active-scaffold', '-messages')); + if (message_node) message_node.update(messages); + }, + + set_adapter: function(element) { + this.adapter = element; + this.adapter.addClassName('as_adapter'); + this.adapter.store('action_link', this); } }); @@ -325,12 +826,12 @@ ActiveScaffold.ActionLink.Abstract = Class.create({ ActiveScaffold.Actions.Record = Class.create(ActiveScaffold.Actions.Abstract, { instantiate_link: function(link) { var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator); - l.refresh_url = this.options.refresh_url; - if (link.hasClassName('delete')) { - l.url = l.url.replace(/\/delete(\?.*)?$/, '$1'); - l.url = l.url.replace(/\/delete\/(.*)/, '/destroy/$1'); + if (this.target.hasAttribute('data-refresh') && !this.target.readAttribute('data-refresh').blank()) l.refresh_url = this.target.readAttribute('data-refresh'); + + if (l.position) { + l.url = l.url.append_params({adapter: '_list_inline_adapter'}); + l.tag.href = l.url; } - if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'}); l.set = this; return l; } @@ -355,42 +856,24 @@ ActiveScaffold.ActionLink.Record = Class.create(ActiveScaffold.ActionLink.Abstra } if (this.position == 'after') { - new Insertion.After(this.target, content); - this.adapter = this.target.next(); + this.target.insert({after:content}); + this.set_adapter(this.target.next()); } else if (this.position == 'before') { - new Insertion.Before(this.target, content); - this.adapter = this.target.previous(); + this.target.insert({before:content}); + this.set_adapter(this.target.previous()); } else { return false; } - - this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this)); - this.register_cancel_hooks(); - this.adapter.down('td').down().highlight(); }, - close: function($super, updatedRow) { - if (updatedRow) { - ActiveScaffold.update_row(this.target, updatedRow); - $super(); - } else { - new Ajax.Request(this.refresh_url, { - asynchronous: true, - evalScripts: true, - method: this.method, - onSuccess: function(request) { - ActiveScaffold.update_row(this.target, request.responseText); - $super(); - }.bind(this), - - onFailure: function(request) { - ActiveScaffold.report_500_response(this.scaffold_id()); - } - }); + close: function($super, refreshed_content) { + if (refreshed_content) { + ActiveScaffold.update_row(this.target, refreshed_content); } + $super(); }, enable: function() { @@ -405,6 +888,16 @@ ActiveScaffold.ActionLink.Record = Class.create(ActiveScaffold.ActionLink.Abstra if (item.url != this.url) return; item.tag.addClassName('disabled'); }.bind(this)); + }, + + set_opened: function() { + if (this.position == 'after') { + this.set_adapter(this.target.next()); + } + else if (this.position == 'before') { + this.set_adapter(this.target.previous()); + } + this.disable(); } }); @@ -414,7 +907,10 @@ ActiveScaffold.ActionLink.Record = Class.create(ActiveScaffold.ActionLink.Abstra ActiveScaffold.Actions.Table = Class.create(ActiveScaffold.Actions.Abstract, { instantiate_link: function(link) { var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator); - if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'}); + if (l.position) { + l.url = l.url.append_params({adapter: '_list_inline_adapter'}); + l.tag.href = l.url; + } return l; } }); @@ -422,22 +918,25 @@ ActiveScaffold.Actions.Table = Class.create(ActiveScaffold.Actions.Abstract, { ActiveScaffold.ActionLink.Table = Class.create(ActiveScaffold.ActionLink.Abstract, { insert: function(content) { if (this.position == 'top') { - new Insertion.Top(this.target, content); - this.adapter = this.target.immediateDescendants().first(); + this.target.insert({top:content}); + this.set_adapter(this.target.immediateDescendants().first()); } else { throw 'Unknown position "' + this.position + '"' } - - this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this)); - this.register_cancel_hooks(); - this.adapter.down('td').down().highlight(); } }); if (Ajax.InPlaceEditor) { ActiveScaffold.InPlaceEditor = Class.create(Ajax.InPlaceEditor, { + initialize: function($super, element, url, options) { + $super(element, url, options); + if (this._originalBackground == 'transparent') { + this._originalBackground = null; + } + }, + setFieldFromAjax: function(url, options) { var ipe = this; $(ipe._controls.editor).remove(); diff --git a/public/javascripts/active_scaffold/default/dhtml_history.js b/public/javascripts/active_scaffold/default/dhtml_history.js old mode 100755 new mode 100644 index 3bf6275..da08ba2 --- a/public/javascripts/active_scaffold/default/dhtml_history.js +++ b/public/javascripts/active_scaffold/default/dhtml_history.js @@ -53,18 +53,6 @@ window.dhtmlHistory = { var that = this; - /*Set up the historyStorage object; pass in options bundle*/ - window.historyStorage.setup(options); - - /*Set up our base title if one is passed in*/ - if (options && options.baseTitle) { - if (options.baseTitle.indexOf("@@@") < 0 && historyStorage.debugMode) { - throw new Error("Programmer error: options.baseTitle must contain the replacement parameter" - + " '@@@' to be useful."); - } - this.baseTitle = options.baseTitle; - } - /*set user-agent flags*/ var UA = navigator.userAgent.toLowerCase(); var platform = navigator.platform.toLowerCase(); @@ -80,77 +68,92 @@ window.dhtmlHistory = { this.isSupported = true; } else if (vendor.indexOf("Apple Computer, Inc.") > -1) { this.isSafari = true; - this.isSupported = (platform.indexOf("mac") > -1); + //this.isSupported = (platform.indexOf("mac") > -1); + this.isSupported = false; } else if (UA.indexOf("gecko") != -1) { this.isGecko = true; this.isSupported = true; } - /*Create Safari/Opera-specific code*/ - if (this.isSafari) { - this.createSafari(); - } else if (this.isOpera) { - this.createOpera(); - } - - /*Get our initial location*/ - var initialHash = this.getCurrentLocation(); - - /*Save it as our current location*/ - this.currentLocation = initialHash; - - /*Now that we have a hash, create IE-specific code*/ - if (this.isIE) { - /*Optionally override the URL of IE's blank HTML file*/ - if (options && options.blankURL) { - var u = options.blankURL; - /*assign the value, adding the trailing ? if it's not passed in*/ - this.blankURL = (u.indexOf("?") != u.length - 1 - ? u + "?" - : u - ); - } - this.createIE(initialHash); - } - - /*Add an unload listener for the page; this is needed for FF 1.5+ because this browser caches all dynamic updates to the - page, which can break some of our logic related to testing whether this is the first instance a page has loaded or whether - it is being pulled from the cache*/ - - var unloadHandler = function() { - that.firstLoad = null; - }; - - this.addEventListener(window,'unload',unloadHandler); - - /*Determine if this is our first page load; for IE, we do this in this.iframeLoaded(), which is fired on pageload. We do it - there because we have no historyStorage at this point, which only exists after the page is finished loading in IE*/ - if (this.isIE) { - /*The iframe will get loaded on page load, and we want to ignore this fact*/ - this.ignoreLocationChange = true; - } else { - if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { - /*This is our first page load, so ignore the location change and add our special history entry*/ - this.ignoreLocationChange = true; - this.firstLoad = true; - historyStorage.put(this.PAGELOADEDSTRING, true); - } else { - /*This isn't our first page load, so indicate that we want to pay attention to this location change*/ - this.ignoreLocationChange = false; - this.firstLoad = false; - /*For browsers other than IE, fire a history change event; on IE, the event will be thrown automatically when its - hidden iframe reloads on page load. Unfortunately, we don't have any listeners yet; indicate that we want to fire - an event when a listener is added.*/ - this.fireOnNewListener = true; - } + if (this.isSupported) { + /*Set up the historyStorage object; pass in options bundle*/ + window.historyStorage.setup(options); + + /*Set up our base title if one is passed in*/ + if (options && options.baseTitle) { + if (options.baseTitle.indexOf("@@@") < 0 && historyStorage.debugMode) { + throw new Error("Programmer error: options.baseTitle must contain the replacement parameter" + + " '@@@' to be useful."); + } + this.baseTitle = options.baseTitle; + } + + /*Create Safari/Opera-specific code*/ + if (this.isSafari && this.isSupported) { + this.createSafari(); + } else if (this.isOpera) { + this.createOpera(); + } + + /*Get our initial location*/ + var initialHash = this.getCurrentLocation(); + + /*Save it as our current location*/ + this.currentLocation = initialHash; + + /*Now that we have a hash, create IE-specific code*/ + if (this.isIE) { + /*Optionally override the URL of IE's blank HTML file*/ + if (options && options.blankURL) { + var u = options.blankURL; + /*assign the value, adding the trailing ? if it's not passed in*/ + this.blankURL = (u.indexOf("?") != u.length - 1 + ? u + "?" + : u + ); + } + this.createIE(initialHash); + } + + /*Add an unload listener for the page; this is needed for FF 1.5+ because this browser caches all dynamic updates to the + page, which can break some of our logic related to testing whether this is the first instance a page has loaded or whether + it is being pulled from the cache*/ + + var unloadHandler = function() { + that.firstLoad = null; + }; + + this.addEventListener(window,'unload',unloadHandler); + + /*Determine if this is our first page load; for IE, we do this in this.iframeLoaded(), which is fired on pageload. We do it + there because we have no historyStorage at this point, which only exists after the page is finished loading in IE*/ + if (this.isIE) { + /*The iframe will get loaded on page load, and we want to ignore this fact*/ + this.ignoreLocationChange = true; + } else if (this.isSupported) { + if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { + /*This is our first page load, so ignore the location change and add our special history entry*/ + this.ignoreLocationChange = true; + this.firstLoad = true; + historyStorage.put(this.PAGELOADEDSTRING, true); + } else { + /*This isn't our first page load, so indicate that we want to pay attention to this location change*/ + this.ignoreLocationChange = false; + this.firstLoad = false; + /*For browsers other than IE, fire a history change event; on IE, the event will be thrown automatically when its + hidden iframe reloads on page load. Unfortunately, we don't have any listeners yet; indicate that we want to fire + an event when a listener is added.*/ + this.fireOnNewListener = true; + } + } + + /*Other browsers can use a location handler that checks at regular intervals as their primary mechanism; we use it for IE as + well to handle an important edge case; see checkLocation() for details*/ + var locationHandler = function() { + that.checkLocation(); + }; + setInterval(locationHandler, 100); } - - /*Other browsers can use a location handler that checks at regular intervals as their primary mechanism; we use it for IE as - well to handle an important edge case; see checkLocation() for details*/ - var locationHandler = function() { - that.checkLocation(); - }; - setInterval(locationHandler, 100); }, /*Public: Initialize our DHTML history. You must call this after the page is finished loading. Optionally, you can pass your listener in diff --git a/public/javascripts/controls.js b/public/javascripts/controls.js index ca29aef..7392fb6 100644 --- a/public/javascripts/controls.js +++ b/public/javascripts/controls.js @@ -1,6 +1,8 @@ -// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) -// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan) -// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com) +// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 + +// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan) +// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com) // Contributors: // Richard Livsey // Rahul Bhargava diff --git a/public/javascripts/dragdrop.js b/public/javascripts/dragdrop.js index 07229f9..15c6dbc 100644 --- a/public/javascripts/dragdrop.js +++ b/public/javascripts/dragdrop.js @@ -1,5 +1,6 @@ -// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) -// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) +// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 + +// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ @@ -311,7 +312,7 @@ var Draggable = Class.create({ tag_name=='TEXTAREA')) return; var pointer = [Event.pointerX(event), Event.pointerY(event)]; - var pos = Position.cumulativeOffset(this.element); + var pos = this.element.cumulativeOffset(); this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); Draggables.activate(this); @@ -454,7 +455,7 @@ var Draggable = Class.create({ }, draw: function(point) { - var pos = Position.cumulativeOffset(this.element); + var pos = this.element.cumulativeOffset(); if(this.options.ghosting) { var r = Position.realOffset(this.element); pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; @@ -730,7 +731,7 @@ var Sortable = { } // keep reference - this.sortables[element.id] = options; + this.sortables[element.identify()] = options; // for onupdate Draggables.addObserver(new SortableObserver(element, options.onUpdate)); @@ -825,7 +826,7 @@ var Sortable = { hide().addClassName('dropmarker').setStyle({position:'absolute'}); document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); } - var offsets = Position.cumulativeOffset(dropon); + var offsets = dropon.cumulativeOffset(); Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); if(position=='after') diff --git a/public/javascripts/editors/classrooms.js b/public/javascripts/editors/classrooms.js index 53d21cb..838be04 100644 --- a/public/javascripts/editors/classrooms.js +++ b/public/javascripts/editors/classrooms.js @@ -14,7 +14,7 @@ jQuery(document).ready(function($) { }, function(data) { var classrooms = new Array(0); - data.each(function(i) { + $.each(data, function(index, i) { classrooms.push({ label: i.classroom.name + ' (' + i.classroom.building.name + ')', value: i.classroom.id }); }); response(classrooms); diff --git a/public/javascripts/editors/groups.js b/public/javascripts/editors/groups.js index 826c8a7..830cc93 100644 --- a/public/javascripts/editors/groups.js +++ b/public/javascripts/editors/groups.js @@ -14,7 +14,7 @@ jQuery(document).ready(function($) { }, function(data) { var groups = new Array(0); - data.each(function(i) { + $.each(data, function(index, i) { groups.push({ label: i.group.descriptive_name, value: i.group.id }); }); response(groups); diff --git a/public/javascripts/effects.js b/public/javascripts/effects.js index 5a639d2..c81e6c7 100644 --- a/public/javascripts/effects.js +++ b/public/javascripts/effects.js @@ -1,4 +1,6 @@ -// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// script.aculo.us effects.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 + +// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) // Contributors: // Justin Palmer (http://encytemedia.com/) // Mark Pilgrim (http://diveintomark.org/) @@ -145,14 +147,13 @@ var Effect = { 'blind': ['BlindDown','BlindUp'], 'appear': ['Appear','Fade'] }, - toggle: function(element, effect) { + toggle: function(element, effect, options) { element = $(element); - effect = (effect || 'appear').toLowerCase(); - var options = Object.extend({ + effect = (effect || 'appear').toLowerCase(); + + return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({ queue: { position:'end', scope:(element.id || 'global'), limit: 1 } - }, arguments[2] || { }); - Effect[element.visible() ? - Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); + }, options || {})); } }; @@ -228,12 +229,6 @@ Effect.Queue = Effect.Queues.get('global'); Effect.Base = Class.create({ position: null, start: function(options) { - function codeForEvent(options,eventName){ - return ( - (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') + - (options[eventName] ? 'this.options.'+eventName+'(this);' : '') - ); - } if (options && options.transition === false) options.transition = Effect.Transitions.linear; this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { }); this.currentFrame = 0; diff --git a/public/javascripts/prototype.js b/public/javascripts/prototype.js index dfe8ab4..06249a6 100644 --- a/public/javascripts/prototype.js +++ b/public/javascripts/prototype.js @@ -1,5 +1,5 @@ -/* Prototype JavaScript framework, version 1.6.0.3 - * (c) 2005-2008 Sam Stephenson +/* Prototype JavaScript framework, version 1.7_rc2 + * (c) 2005-2010 Sam Stephenson * * Prototype is freely distributable under the terms of an MIT-style license. * For details, see the Prototype web site: http://www.prototypejs.org/ @@ -7,32 +7,53 @@ *--------------------------------------------------------------------------*/ var Prototype = { - Version: '1.6.0.3', - Browser: { - IE: !!(window.attachEvent && - navigator.userAgent.indexOf('Opera') === -1), - Opera: navigator.userAgent.indexOf('Opera') > -1, - WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1, - Gecko: navigator.userAgent.indexOf('Gecko') > -1 && - navigator.userAgent.indexOf('KHTML') === -1, - MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/) - }, + Version: '1.7_rc2', + + Browser: (function(){ + var ua = navigator.userAgent; + var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]'; + return { + IE: !!window.attachEvent && !isOpera, + Opera: isOpera, + WebKit: ua.indexOf('AppleWebKit/') > -1, + Gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') === -1, + MobileSafari: /Apple.*Mobile/.test(ua) + } + })(), BrowserFeatures: { XPath: !!document.evaluate, + SelectorsAPI: !!document.querySelector, - ElementExtensions: !!window.HTMLElement, - SpecificElementExtensions: - document.createElement('div')['__proto__'] && - document.createElement('div')['__proto__'] !== - document.createElement('form')['__proto__'] + + ElementExtensions: (function() { + var constructor = window.Element || window.HTMLElement; + return !!(constructor && constructor.prototype); + })(), + SpecificElementExtensions: (function() { + if (typeof window.HTMLDivElement !== 'undefined') + return true; + + var div = document.createElement('div'), + form = document.createElement('form'), + isSupported = false; + + if (div['__proto__'] && (div['__proto__'] !== form['__proto__'])) { + isSupported = true; + } + + div = form = null; + + return isSupported; + })() }, ScriptFragment: ']*>([\\S\\s]*?)<\/script>', JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/, emptyFunction: function() { }, + K: function(x) { return x } }; @@ -40,9 +61,38 @@ if (Prototype.Browser.MobileSafari) Prototype.BrowserFeatures.SpecificElementExtensions = false; +var Abstract = { }; + + +var Try = { + these: function() { + var returnValue; + + for (var i = 0, length = arguments.length; i < length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) { } + } + + return returnValue; + } +}; + /* Based on Alex Arnell's inheritance implementation. */ -var Class = { - create: function() { + +var Class = (function() { + + var IS_DONTENUM_BUGGY = (function(){ + for (var p in { toString: 1 }) { + if (p === 'toString') return false; + } + return true; + })(); + + function subclass() {}; + function create() { var parent = null, properties = $A(arguments); if (Object.isFunction(properties[0])) parent = properties.shift(); @@ -56,39 +106,39 @@ var Class = { klass.subclasses = []; if (parent) { - var subclass = function() { }; subclass.prototype = parent.prototype; klass.prototype = new subclass; parent.subclasses.push(klass); } - for (var i = 0; i < properties.length; i++) + for (var i = 0, length = properties.length; i < length; i++) klass.addMethods(properties[i]); if (!klass.prototype.initialize) klass.prototype.initialize = Prototype.emptyFunction; klass.prototype.constructor = klass; - return klass; } -}; -Class.Methods = { - addMethods: function(source) { - var ancestor = this.superclass && this.superclass.prototype; - var properties = Object.keys(source); + function addMethods(source) { + var ancestor = this.superclass && this.superclass.prototype, + properties = Object.keys(source); - if (!Object.keys({ toString: true }).length) - properties.push("toString", "valueOf"); + if (IS_DONTENUM_BUGGY) { + if (source.toString != Object.prototype.toString) + properties.push("toString"); + if (source.valueOf != Object.prototype.valueOf) + properties.push("valueOf"); + } for (var i = 0, length = properties.length; i < length; i++) { var property = properties[i], value = source[property]; if (ancestor && Object.isFunction(value) && - value.argumentNames().first() == "$super") { + value.argumentNames()[0] == "$super") { var method = value; value = (function(m) { - return function() { return ancestor[m].apply(this, arguments) }; + return function() { return ancestor[m].apply(this, arguments); }; })(property).wrap(method); value.valueOf = method.valueOf.bind(method); @@ -99,198 +149,331 @@ Class.Methods = { return this; } -}; -var Abstract = { }; + return { + create: create, + Methods: { + addMethods: addMethods + } + }; +})(); +(function() { -Object.extend = function(destination, source) { - for (var property in source) - destination[property] = source[property]; - return destination; -}; + var _toString = Object.prototype.toString, + NULL_TYPE = 'Null', + UNDEFINED_TYPE = 'Undefined', + BOOLEAN_TYPE = 'Boolean', + NUMBER_TYPE = 'Number', + STRING_TYPE = 'String', + OBJECT_TYPE = 'Object', + BOOLEAN_CLASS = '[object Boolean]', + NUMBER_CLASS = '[object Number]', + STRING_CLASS = '[object String]', + ARRAY_CLASS = '[object Array]', + NATIVE_JSON_STRINGIFY_SUPPORT = window.JSON && + typeof JSON.stringify === 'function' && + JSON.stringify(0) === '0' && + typeof JSON.stringify(Prototype.K) === 'undefined'; + + function Type(o) { + switch(o) { + case null: return NULL_TYPE; + case (void 0): return UNDEFINED_TYPE; + } + var type = typeof o; + switch(type) { + case 'boolean': return BOOLEAN_TYPE; + case 'number': return NUMBER_TYPE; + case 'string': return STRING_TYPE; + } + return OBJECT_TYPE; + } -Object.extend(Object, { - inspect: function(object) { + function extend(destination, source) { + for (var property in source) + destination[property] = source[property]; + return destination; + } + + function inspect(object) { try { - if (Object.isUndefined(object)) return 'undefined'; + if (isUndefined(object)) return 'undefined'; if (object === null) return 'null'; return object.inspect ? object.inspect() : String(object); } catch (e) { if (e instanceof RangeError) return '...'; throw e; } - }, + } - toJSON: function(object) { - var type = typeof object; - switch (type) { - case 'undefined': - case 'function': - case 'unknown': return; - case 'boolean': return object.toString(); + function toJSON(value) { + return Str('', { '': value }, []); + } + + function Str(key, holder, stack) { + var value = holder[key], + type = typeof value; + + if (Type(value) === OBJECT_TYPE && typeof value.toJSON === 'function') { + value = value.toJSON(key); } - if (object === null) return 'null'; - if (object.toJSON) return object.toJSON(); - if (Object.isElement(object)) return; + var _class = _toString.call(value); - var results = []; - for (var property in object) { - var value = Object.toJSON(object[property]); - if (!Object.isUndefined(value)) - results.push(property.toJSON() + ': ' + value); + switch (_class) { + case NUMBER_CLASS: + case BOOLEAN_CLASS: + case STRING_CLASS: + value = value.valueOf(); } - return '{' + results.join(', ') + '}'; - }, + switch (value) { + case null: return 'null'; + case true: return 'true'; + case false: return 'false'; + } + + type = typeof value; + switch (type) { + case 'string': + return value.inspect(true); + case 'number': + return isFinite(value) ? String(value) : 'null'; + case 'object': + + for (var i = 0, length = stack.length; i < length; i++) { + if (stack[i] === value) { throw new TypeError(); } + } + stack.push(value); + + var partial = []; + if (_class === ARRAY_CLASS) { + for (var i = 0, length = value.length; i < length; i++) { + var str = Str(i, value, stack); + partial.push(typeof str === 'undefined' ? 'null' : str); + } + partial = '[' + partial.join(',') + ']'; + } else { + var keys = Object.keys(value); + for (var i = 0, length = keys.length; i < length; i++) { + var key = keys[i], str = Str(key, value, stack); + if (typeof str !== "undefined") { + partial.push(key.inspect(true)+ ':' + str); + } + } + partial = '{' + partial.join(',') + '}'; + } + stack.pop(); + return partial; + } + } + + function stringify(object) { + return JSON.stringify(object); + } - toQueryString: function(object) { + function toQueryString(object) { return $H(object).toQueryString(); - }, + } - toHTML: function(object) { + function toHTML(object) { return object && object.toHTML ? object.toHTML() : String.interpret(object); - }, + } - keys: function(object) { - var keys = []; - for (var property in object) - keys.push(property); - return keys; - }, + function keys(object) { + if (Type(object) !== OBJECT_TYPE) { throw new TypeError(); } + var results = []; + for (var property in object) { + if (object.hasOwnProperty(property)) { + results.push(property); + } + } + return results; + } - values: function(object) { - var values = []; + function values(object) { + var results = []; for (var property in object) - values.push(object[property]); - return values; - }, + results.push(object[property]); + return results; + } - clone: function(object) { - return Object.extend({ }, object); - }, + function clone(object) { + return extend({ }, object); + } - isElement: function(object) { + function isElement(object) { return !!(object && object.nodeType == 1); - }, + } - isArray: function(object) { - return object != null && typeof object == "object" && - 'splice' in object && 'join' in object; - }, + function isArray(object) { + return _toString.call(object) === ARRAY_CLASS; + } + + var hasNativeIsArray = (typeof Array.isArray == 'function') + && Array.isArray([]) && !Array.isArray({}); + + if (hasNativeIsArray) { + isArray = Array.isArray; + } - isHash: function(object) { + function isHash(object) { return object instanceof Hash; - }, + } - isFunction: function(object) { - return typeof object == "function"; - }, + function isFunction(object) { + return typeof object === "function"; + } - isString: function(object) { - return typeof object == "string"; - }, + function isString(object) { + return _toString.call(object) === STRING_CLASS; + } - isNumber: function(object) { - return typeof object == "number"; - }, + function isNumber(object) { + return _toString.call(object) === NUMBER_CLASS; + } - isUndefined: function(object) { - return typeof object == "undefined"; + function isUndefined(object) { + return typeof object === "undefined"; + } + + extend(Object, { + extend: extend, + inspect: inspect, + toJSON: NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON, + toQueryString: toQueryString, + toHTML: toHTML, + keys: Object.keys || keys, + values: values, + clone: clone, + isElement: isElement, + isArray: isArray, + isHash: isHash, + isFunction: isFunction, + isString: isString, + isNumber: isNumber, + isUndefined: isUndefined + }); +})(); +Object.extend(Function.prototype, (function() { + var slice = Array.prototype.slice; + + function update(array, args) { + var arrayLength = array.length, length = args.length; + while (length--) array[arrayLength + length] = args[length]; + return array; } -}); -Object.extend(Function.prototype, { - argumentNames: function() { - var names = this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1] + function merge(array, args) { + array = slice.call(array, 0); + return update(array, args); + } + + function argumentNames() { + var names = this.toString().match(/^[\s\(]*function[^(]*\(([^)]*)\)/)[1] + .replace(/\/\/.*?[\r\n]|\/\*(?:.|[\r\n])*?\*\//g, '') .replace(/\s+/g, '').split(','); return names.length == 1 && !names[0] ? [] : names; - }, + } - bind: function() { + function bind(context) { if (arguments.length < 2 && Object.isUndefined(arguments[0])) return this; - var __method = this, args = $A(arguments), object = args.shift(); + var __method = this, args = slice.call(arguments, 1); return function() { - return __method.apply(object, args.concat($A(arguments))); + var a = merge(args, arguments); + return __method.apply(context, a); } - }, + } - bindAsEventListener: function() { - var __method = this, args = $A(arguments), object = args.shift(); + function bindAsEventListener(context) { + var __method = this, args = slice.call(arguments, 1); return function(event) { - return __method.apply(object, [event || window.event].concat(args)); + var a = update([event || window.event], args); + return __method.apply(context, a); } - }, + } - curry: function() { + function curry() { if (!arguments.length) return this; - var __method = this, args = $A(arguments); + var __method = this, args = slice.call(arguments, 0); return function() { - return __method.apply(this, args.concat($A(arguments))); + var a = merge(args, arguments); + return __method.apply(this, a); } - }, + } - delay: function() { - var __method = this, args = $A(arguments), timeout = args.shift() * 1000; + function delay(timeout) { + var __method = this, args = slice.call(arguments, 1); + timeout = timeout * 1000; return window.setTimeout(function() { return __method.apply(__method, args); }, timeout); - }, + } - defer: function() { - var args = [0.01].concat($A(arguments)); + function defer() { + var args = update([0.01], arguments); return this.delay.apply(this, args); - }, + } - wrap: function(wrapper) { + function wrap(wrapper) { var __method = this; return function() { - return wrapper.apply(this, [__method.bind(this)].concat($A(arguments))); + var a = update([__method.bind(this)], arguments); + return wrapper.apply(this, a); } - }, + } - methodize: function() { + function methodize() { if (this._methodized) return this._methodized; var __method = this; return this._methodized = function() { - return __method.apply(null, [this].concat($A(arguments))); + var a = update([this], arguments); + return __method.apply(null, a); }; } -}); -Date.prototype.toJSON = function() { - return '"' + this.getUTCFullYear() + '-' + - (this.getUTCMonth() + 1).toPaddedString(2) + '-' + - this.getUTCDate().toPaddedString(2) + 'T' + - this.getUTCHours().toPaddedString(2) + ':' + - this.getUTCMinutes().toPaddedString(2) + ':' + - this.getUTCSeconds().toPaddedString(2) + 'Z"'; -}; + return { + argumentNames: argumentNames, + bind: bind, + bindAsEventListener: bindAsEventListener, + curry: curry, + delay: delay, + defer: defer, + wrap: wrap, + methodize: methodize + } +})()); -var Try = { - these: function() { - var returnValue; - for (var i = 0, length = arguments.length; i < length; i++) { - var lambda = arguments[i]; - try { - returnValue = lambda(); - break; - } catch (e) { } - } - return returnValue; +(function(proto) { + + + function toISOString() { + return this.getUTCFullYear() + '-' + + (this.getUTCMonth() + 1).toPaddedString(2) + '-' + + this.getUTCDate().toPaddedString(2) + 'T' + + this.getUTCHours().toPaddedString(2) + ':' + + this.getUTCMinutes().toPaddedString(2) + ':' + + this.getUTCSeconds().toPaddedString(2) + 'Z'; } -}; + + + function toJSON() { + return this.toISOString(); + } + + if (!proto.toISOString) proto.toISOString = toISOString; + if (!proto.toJSON) proto.toJSON = toJSON; + +})(Date.prototype); + RegExp.prototype.match = RegExp.prototype.test; RegExp.escape = function(str) { return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; - -/*--------------------------------------------------------------------------*/ - var PeriodicalExecuter = Class.create({ initialize: function(callback, frequency) { this.callback = callback; @@ -319,8 +502,10 @@ var PeriodicalExecuter = Class.create({ try { this.currentlyExecuting = true; this.execute(); - } finally { this.currentlyExecuting = false; + } catch(e) { + this.currentlyExecuting = false; + throw e; } } } @@ -339,10 +524,28 @@ Object.extend(String, { } }); -Object.extend(String.prototype, { - gsub: function(pattern, replacement) { +Object.extend(String.prototype, (function() { + var NATIVE_JSON_PARSE_SUPPORT = window.JSON && + typeof JSON.parse === 'function' && + JSON.parse('{"test": true}').test; + + function prepareReplacement(replacement) { + if (Object.isFunction(replacement)) return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; + } + + function gsub(pattern, replacement) { var result = '', source = this, match; - replacement = arguments.callee.prepareReplacement(replacement); + replacement = prepareReplacement(replacement); + + if (Object.isString(pattern)) + pattern = RegExp.escape(pattern); + + if (!(pattern.length || pattern.source)) { + replacement = replacement(''); + return replacement + source.split('').join(replacement) + replacement; + } while (source.length > 0) { if (match = source.match(pattern)) { @@ -354,76 +557,72 @@ Object.extend(String.prototype, { } } return result; - }, + } - sub: function(pattern, replacement, count) { - replacement = this.gsub.prepareReplacement(replacement); + function sub(pattern, replacement, count) { + replacement = prepareReplacement(replacement); count = Object.isUndefined(count) ? 1 : count; return this.gsub(pattern, function(match) { if (--count < 0) return match[0]; return replacement(match); }); - }, + } - scan: function(pattern, iterator) { + function scan(pattern, iterator) { this.gsub(pattern, iterator); return String(this); - }, + } - truncate: function(length, truncation) { + function truncate(length, truncation) { length = length || 30; truncation = Object.isUndefined(truncation) ? '...' : truncation; return this.length > length ? this.slice(0, length - truncation.length) + truncation : String(this); - }, + } - strip: function() { + function strip() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); - }, + } - stripTags: function() { - return this.replace(/<\/?[^>]+>/gi, ''); - }, + function stripTags() { + return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, ''); + } - stripScripts: function() { + function stripScripts() { return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); - }, + } - extractScripts: function() { - var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); - var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + function extractScripts() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'), + matchOne = new RegExp(Prototype.ScriptFragment, 'im'); return (this.match(matchAll) || []).map(function(scriptTag) { return (scriptTag.match(matchOne) || ['', ''])[1]; }); - }, + } - evalScripts: function() { + function evalScripts() { return this.extractScripts().map(function(script) { return eval(script) }); - }, + } - escapeHTML: function() { - var self = arguments.callee; - self.text.data = this; - return self.div.innerHTML; - }, + function escapeHTML() { + return this.replace(/&/g,'&').replace(//g,'>'); + } - unescapeHTML: function() { - var div = new Element('div'); - div.innerHTML = this.stripTags(); - return div.childNodes[0] ? (div.childNodes.length > 1 ? - $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) : - div.childNodes[0].nodeValue) : ''; - }, + function unescapeHTML() { + return this.stripTags().replace(/</g,'<').replace(/>/g,'>').replace(/&/g,'&'); + } - toQueryParams: function(separator) { + + function toQueryParams(separator) { var match = this.strip().match(/([^?#]*)(#.*)?$/); if (!match) return { }; return match[1].split(separator || '&').inject({ }, function(hash, pair) { if ((pair = pair.split('='))[0]) { - var key = decodeURIComponent(pair.shift()); - var value = pair.length > 1 ? pair.join('=') : pair[0]; + var key = decodeURIComponent(pair.shift()), + value = pair.length > 1 ? pair.join('=') : pair[0]; + if (value != undefined) value = decodeURIComponent(value); if (key in hash) { @@ -434,128 +633,144 @@ Object.extend(String.prototype, { } return hash; }); - }, + } - toArray: function() { + function toArray() { return this.split(''); - }, + } - succ: function() { + function succ() { return this.slice(0, this.length - 1) + String.fromCharCode(this.charCodeAt(this.length - 1) + 1); - }, + } - times: function(count) { + function times(count) { return count < 1 ? '' : new Array(count + 1).join(this); - }, - - camelize: function() { - var parts = this.split('-'), len = parts.length; - if (len == 1) return parts[0]; - - var camelized = this.charAt(0) == '-' - ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) - : parts[0]; - - for (var i = 1; i < len; i++) - camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1); + } - return camelized; - }, + function camelize() { + return this.replace(/-+(.)?/g, function(match, chr) { + return chr ? chr.toUpperCase() : ''; + }); + } - capitalize: function() { + function capitalize() { return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase(); - }, + } - underscore: function() { - return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase(); - }, + function underscore() { + return this.replace(/::/g, '/') + .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') + .replace(/([a-z\d])([A-Z])/g, '$1_$2') + .replace(/-/g, '_') + .toLowerCase(); + } - dasherize: function() { - return this.gsub(/_/,'-'); - }, + function dasherize() { + return this.replace(/_/g, '-'); + } - inspect: function(useDoubleQuotes) { - var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) { - var character = String.specialChar[match[0]]; - return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16); + function inspect(useDoubleQuotes) { + var escapedString = this.replace(/[\x00-\x1f\\]/g, function(character) { + if (character in String.specialChar) { + return String.specialChar[character]; + } + return '\\u00' + character.charCodeAt().toPaddedString(2, 16); }); if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"'; return "'" + escapedString.replace(/'/g, '\\\'') + "'"; - }, - - toJSON: function() { - return this.inspect(true); - }, + } - unfilterJSON: function(filter) { - return this.sub(filter || Prototype.JSONFilter, '#{1}'); - }, + function unfilterJSON(filter) { + return this.replace(filter || Prototype.JSONFilter, '$1'); + } - isJSON: function() { + function isJSON() { var str = this; if (str.blank()) return false; - str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''); - return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str); - }, + str = str.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@'); + str = str.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']'); + str = str.replace(/(?:^|:|,)(?:\s*\[)+/g, ''); + return (/^[\],:{}\s]*$/).test(str); + } - evalJSON: function(sanitize) { - var json = this.unfilterJSON(); + function evalJSON(sanitize) { + var json = this.unfilterJSON(), + cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; + if (cx.test(json)) { + json = json.replace(cx, function (a) { + return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }); + } try { if (!sanitize || json.isJSON()) return eval('(' + json + ')'); } catch (e) { } throw new SyntaxError('Badly formed JSON string: ' + this.inspect()); - }, + } + + function parseJSON() { + var json = this.unfilterJSON(); + return JSON.parse(json); + } - include: function(pattern) { + function include(pattern) { return this.indexOf(pattern) > -1; - }, + } - startsWith: function(pattern) { - return this.indexOf(pattern) === 0; - }, + function startsWith(pattern) { + return this.lastIndexOf(pattern, 0) === 0; + } - endsWith: function(pattern) { + function endsWith(pattern) { var d = this.length - pattern.length; - return d >= 0 && this.lastIndexOf(pattern) === d; - }, + return d >= 0 && this.indexOf(pattern, d) === d; + } - empty: function() { + function empty() { return this == ''; - }, + } - blank: function() { + function blank() { return /^\s*$/.test(this); - }, - - interpolate: function(object, pattern) { - return new Template(this, pattern).evaluate(object); } -}); -if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, { - escapeHTML: function() { - return this.replace(/&/g,'&').replace(//g,'>'); - }, - unescapeHTML: function() { - return this.stripTags().replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); + function interpolate(object, pattern) { + return new Template(this, pattern).evaluate(object); } -}); - -String.prototype.gsub.prepareReplacement = function(replacement) { - if (Object.isFunction(replacement)) return replacement; - var template = new Template(replacement); - return function(match) { return template.evaluate(match) }; -}; - -String.prototype.parseQuery = String.prototype.toQueryParams; -Object.extend(String.prototype.escapeHTML, { - div: document.createElement('div'), - text: document.createTextNode('') -}); - -String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text); + return { + gsub: gsub, + sub: sub, + scan: scan, + truncate: truncate, + strip: String.prototype.trim || strip, + stripTags: stripTags, + stripScripts: stripScripts, + extractScripts: extractScripts, + evalScripts: evalScripts, + escapeHTML: escapeHTML, + unescapeHTML: unescapeHTML, + toQueryParams: toQueryParams, + parseQuery: toQueryParams, + toArray: toArray, + succ: succ, + times: times, + camelize: camelize, + capitalize: capitalize, + underscore: underscore, + dasherize: dasherize, + inspect: inspect, + unfilterJSON: unfilterJSON, + isJSON: isJSON, + evalJSON: NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON, + include: include, + startsWith: startsWith, + endsWith: endsWith, + empty: empty, + blank: blank, + interpolate: interpolate + }; +})()); var Template = Class.create({ initialize: function(template, pattern) { @@ -564,22 +779,23 @@ var Template = Class.create({ }, evaluate: function(object) { - if (Object.isFunction(object.toTemplateReplacements)) + if (object && Object.isFunction(object.toTemplateReplacements)) object = object.toTemplateReplacements(); return this.template.gsub(this.pattern, function(match) { - if (object == null) return ''; + if (object == null) return (match[1] + ''); var before = match[1] || ''; if (before == '\\') return match[2]; - var ctx = object, expr = match[3]; - var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; + var ctx = object, expr = match[3], + pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/; + match = pattern.exec(expr); if (match == null) return before; while (match != null) { - var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1]; + var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1]; ctx = ctx[comp]; if (null == ctx || '' == match[3]) break; expr = expr.substring('[' == match[3] ? match[1].length : match[0].length); @@ -594,8 +810,8 @@ Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; var $break = { }; -var Enumerable = { - each: function(iterator, context) { +var Enumerable = (function() { + function each(iterator, context) { var index = 0; try { this._each(function(value) { @@ -605,17 +821,17 @@ var Enumerable = { if (e != $break) throw e; } return this; - }, + } - eachSlice: function(number, iterator, context) { + function eachSlice(number, iterator, context) { var index = -number, slices = [], array = this.toArray(); if (number < 1) return array; while ((index += number) < array.length) slices.push(array.slice(index, index+number)); return slices.collect(iterator, context); - }, + } - all: function(iterator, context) { + function all(iterator, context) { iterator = iterator || Prototype.K; var result = true; this.each(function(value, index) { @@ -623,9 +839,9 @@ var Enumerable = { if (!result) throw $break; }); return result; - }, + } - any: function(iterator, context) { + function any(iterator, context) { iterator = iterator || Prototype.K; var result = false; this.each(function(value, index) { @@ -633,18 +849,18 @@ var Enumerable = { throw $break; }); return result; - }, + } - collect: function(iterator, context) { + function collect(iterator, context) { iterator = iterator || Prototype.K; var results = []; this.each(function(value, index) { results.push(iterator.call(context, value, index)); }); return results; - }, + } - detect: function(iterator, context) { + function detect(iterator, context) { var result; this.each(function(value, index) { if (iterator.call(context, value, index)) { @@ -653,32 +869,32 @@ var Enumerable = { } }); return result; - }, + } - findAll: function(iterator, context) { + function findAll(iterator, context) { var results = []; this.each(function(value, index) { if (iterator.call(context, value, index)) results.push(value); }); return results; - }, + } - grep: function(filter, iterator, context) { + function grep(filter, iterator, context) { iterator = iterator || Prototype.K; var results = []; if (Object.isString(filter)) - filter = new RegExp(filter); + filter = new RegExp(RegExp.escape(filter)); this.each(function(value, index) { if (filter.match(value)) results.push(iterator.call(context, value, index)); }); return results; - }, + } - include: function(object) { + function include(object) { if (Object.isFunction(this.indexOf)) if (this.indexOf(object) != -1) return true; @@ -690,31 +906,31 @@ var Enumerable = { } }); return found; - }, + } - inGroupsOf: function(number, fillWith) { + function inGroupsOf(number, fillWith) { fillWith = Object.isUndefined(fillWith) ? null : fillWith; return this.eachSlice(number, function(slice) { while(slice.length < number) slice.push(fillWith); return slice; }); - }, + } - inject: function(memo, iterator, context) { + function inject(memo, iterator, context) { this.each(function(value, index) { memo = iterator.call(context, memo, value, index); }); return memo; - }, + } - invoke: function(method) { + function invoke(method) { var args = $A(arguments).slice(1); return this.map(function(value) { return value[method].apply(value, args); }); - }, + } - max: function(iterator, context) { + function max(iterator, context) { iterator = iterator || Prototype.K; var result; this.each(function(value, index) { @@ -723,9 +939,9 @@ var Enumerable = { result = value; }); return result; - }, + } - min: function(iterator, context) { + function min(iterator, context) { iterator = iterator || Prototype.K; var result; this.each(function(value, index) { @@ -734,9 +950,9 @@ var Enumerable = { result = value; }); return result; - }, + } - partition: function(iterator, context) { + function partition(iterator, context) { iterator = iterator || Prototype.K; var trues = [], falses = []; this.each(function(value, index) { @@ -744,26 +960,26 @@ var Enumerable = { trues : falses).push(value); }); return [trues, falses]; - }, + } - pluck: function(property) { + function pluck(property) { var results = []; this.each(function(value) { results.push(value[property]); }); return results; - }, + } - reject: function(iterator, context) { + function reject(iterator, context) { var results = []; this.each(function(value, index) { if (!iterator.call(context, value, index)) results.push(value); }); return results; - }, + } - sortBy: function(iterator, context) { + function sortBy(iterator, context) { return this.map(function(value, index) { return { value: value, @@ -773,13 +989,13 @@ var Enumerable = { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }).pluck('value'); - }, + } - toArray: function() { + function toArray() { return this.map(); - }, + } - zip: function() { + function zip() { var iterator = Prototype.K, args = $A(arguments); if (Object.isFunction(args.last())) iterator = args.pop(); @@ -788,336 +1004,409 @@ var Enumerable = { return this.map(function(value, index) { return iterator(collections.pluck(index)); }); - }, + } - size: function() { + function size() { return this.toArray().length; - }, + } - inspect: function() { + function inspect() { return '#'; } -}; -Object.extend(Enumerable, { - map: Enumerable.collect, - find: Enumerable.detect, - select: Enumerable.findAll, - filter: Enumerable.findAll, - member: Enumerable.include, - entries: Enumerable.toArray, - every: Enumerable.all, - some: Enumerable.any -}); + + + + + + + + + return { + each: each, + eachSlice: eachSlice, + all: all, + every: all, + any: any, + some: any, + collect: collect, + map: collect, + detect: detect, + findAll: findAll, + select: findAll, + filter: findAll, + grep: grep, + include: include, + member: include, + inGroupsOf: inGroupsOf, + inject: inject, + invoke: invoke, + max: max, + min: min, + partition: partition, + pluck: pluck, + reject: reject, + sortBy: sortBy, + toArray: toArray, + entries: toArray, + zip: zip, + size: size, + inspect: inspect, + find: detect + }; +})(); + function $A(iterable) { if (!iterable) return []; - if (iterable.toArray) return iterable.toArray(); + if ('toArray' in Object(iterable)) return iterable.toArray(); var length = iterable.length || 0, results = new Array(length); while (length--) results[length] = iterable[length]; return results; } -if (Prototype.Browser.WebKit) { - $A = function(iterable) { - if (!iterable) return []; - // In Safari, only use the `toArray` method if it's not a NodeList. - // A NodeList is a function, has an function `item` property, and a numeric - // `length` property. Adapted from Google Doctype. - if (!(typeof iterable === 'function' && typeof iterable.length === - 'number' && typeof iterable.item === 'function') && iterable.toArray) - return iterable.toArray(); - var length = iterable.length || 0, results = new Array(length); - while (length--) results[length] = iterable[length]; - return results; - }; + +function $w(string) { + if (!Object.isString(string)) return []; + string = string.strip(); + return string ? string.split(/\s+/) : []; } Array.from = $A; -Object.extend(Array.prototype, Enumerable); -if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse; +(function() { + var arrayProto = Array.prototype, + slice = arrayProto.slice, + _each = arrayProto.forEach; // use native browser JS 1.6 implementation if available -Object.extend(Array.prototype, { - _each: function(iterator) { + function each(iterator) { for (var i = 0, length = this.length; i < length; i++) iterator(this[i]); - }, + } + if (!_each) _each = each; - clear: function() { + function clear() { this.length = 0; return this; - }, + } - first: function() { + function first() { return this[0]; - }, + } - last: function() { + function last() { return this[this.length - 1]; - }, + } - compact: function() { + function compact() { return this.select(function(value) { return value != null; }); - }, + } - flatten: function() { + function flatten() { return this.inject([], function(array, value) { - return array.concat(Object.isArray(value) ? - value.flatten() : [value]); + if (Object.isArray(value)) + return array.concat(value.flatten()); + array.push(value); + return array; }); - }, + } - without: function() { - var values = $A(arguments); + function without() { + var values = slice.call(arguments, 0); return this.select(function(value) { return !values.include(value); }); - }, - - reverse: function(inline) { - return (inline !== false ? this : this.toArray())._reverse(); - }, + } - reduce: function() { - return this.length > 1 ? this : this[0]; - }, + function reverse(inline) { + return (inline === false ? this.toArray() : this)._reverse(); + } - uniq: function(sorted) { + function uniq(sorted) { return this.inject([], function(array, value, index) { if (0 == index || (sorted ? array.last() != value : !array.include(value))) array.push(value); return array; }); - }, + } - intersect: function(array) { + function intersect(array) { return this.uniq().findAll(function(item) { return array.detect(function(value) { return item === value }); }); - }, + } - clone: function() { - return [].concat(this); - }, - size: function() { + function clone() { + return slice.call(this, 0); + } + + function size() { return this.length; - }, + } - inspect: function() { + function inspect() { return '[' + this.map(Object.inspect).join(', ') + ']'; - }, - - toJSON: function() { - var results = []; - this.each(function(object) { - var value = Object.toJSON(object); - if (!Object.isUndefined(value)) results.push(value); - }); - return '[' + results.join(', ') + ']'; } -}); - -// use native browser JS 1.6 implementation if available -if (Object.isFunction(Array.prototype.forEach)) - Array.prototype._each = Array.prototype.forEach; - -if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) { - i || (i = 0); - var length = this.length; - if (i < 0) i = length + i; - for (; i < length; i++) - if (this[i] === item) return i; - return -1; -}; - -if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) { - i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1; - var n = this.slice(0, i).reverse().indexOf(item); - return (n < 0) ? n : i - n - 1; -}; -Array.prototype.toArray = Array.prototype.clone; + function indexOf(item, i) { + i || (i = 0); + var length = this.length; + if (i < 0) i = length + i; + for (; i < length; i++) + if (this[i] === item) return i; + return -1; + } -function $w(string) { - if (!Object.isString(string)) return []; - string = string.strip(); - return string ? string.split(/\s+/) : []; -} + function lastIndexOf(item, i) { + i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1; + var n = this.slice(0, i).reverse().indexOf(item); + return (n < 0) ? n : i - n - 1; + } -if (Prototype.Browser.Opera){ - Array.prototype.concat = function() { - var array = []; - for (var i = 0, length = this.length; i < length; i++) array.push(this[i]); + function concat() { + var array = slice.call(this, 0), item; for (var i = 0, length = arguments.length; i < length; i++) { - if (Object.isArray(arguments[i])) { - for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++) - array.push(arguments[i][j]); + item = arguments[i]; + if (Object.isArray(item) && !('callee' in item)) { + for (var j = 0, arrayLength = item.length; j < arrayLength; j++) + array.push(item[j]); } else { - array.push(arguments[i]); + array.push(item); } } return array; - }; -} -Object.extend(Number.prototype, { - toColorPart: function() { - return this.toPaddedString(2, 16); - }, - - succ: function() { - return this + 1; - }, + } - times: function(iterator, context) { - $R(0, this, true).each(iterator, context); - return this; - }, + Object.extend(arrayProto, Enumerable); + + if (!arrayProto._reverse) + arrayProto._reverse = arrayProto.reverse; + + Object.extend(arrayProto, { + _each: _each, + clear: clear, + first: first, + last: last, + compact: compact, + flatten: flatten, + without: without, + reverse: reverse, + uniq: uniq, + intersect: intersect, + clone: clone, + toArray: clone, + size: size, + inspect: inspect + }); - toPaddedString: function(length, radix) { - var string = this.toString(radix || 10); - return '0'.times(length - string.length) + string; - }, + var CONCAT_ARGUMENTS_BUGGY = (function() { + return [].concat(arguments)[0][0] !== 1; + })(1,2) - toJSON: function() { - return isFinite(this) ? this.toString() : 'null'; - } -}); + if (CONCAT_ARGUMENTS_BUGGY) arrayProto.concat = concat; -$w('abs round ceil floor').each(function(method){ - Number.prototype[method] = Math[method].methodize(); -}); + if (!arrayProto.indexOf) arrayProto.indexOf = indexOf; + if (!arrayProto.lastIndexOf) arrayProto.lastIndexOf = lastIndexOf; +})(); function $H(object) { return new Hash(object); }; var Hash = Class.create(Enumerable, (function() { + function initialize(object) { + this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); + } - function toQueryPair(key, value) { - if (Object.isUndefined(value)) return key; - return key + '=' + encodeURIComponent(String.interpret(value)); + + function _each(iterator) { + for (var key in this._object) { + var value = this._object[key], pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } } - return { - initialize: function(object) { - this._object = Object.isHash(object) ? object.toObject() : Object.clone(object); - }, + function set(key, value) { + return this._object[key] = value; + } - _each: function(iterator) { - for (var key in this._object) { - var value = this._object[key], pair = [key, value]; - pair.key = key; - pair.value = value; - iterator(pair); - } - }, + function get(key) { + if (this._object[key] !== Object.prototype[key]) + return this._object[key]; + } - set: function(key, value) { - return this._object[key] = value; - }, + function unset(key) { + var value = this._object[key]; + delete this._object[key]; + return value; + } - get: function(key) { - // simulating poorly supported hasOwnProperty - if (this._object[key] !== Object.prototype[key]) - return this._object[key]; - }, + function toObject() { + return Object.clone(this._object); + } - unset: function(key) { - var value = this._object[key]; - delete this._object[key]; - return value; - }, - toObject: function() { - return Object.clone(this._object); - }, - keys: function() { - return this.pluck('key'); - }, + function keys() { + return this.pluck('key'); + } - values: function() { - return this.pluck('value'); - }, + function values() { + return this.pluck('value'); + } - index: function(value) { - var match = this.detect(function(pair) { - return pair.value === value; - }); - return match && match.key; - }, + function index(value) { + var match = this.detect(function(pair) { + return pair.value === value; + }); + return match && match.key; + } - merge: function(object) { - return this.clone().update(object); - }, + function merge(object) { + return this.clone().update(object); + } - update: function(object) { - return new Hash(object).inject(this, function(result, pair) { - result.set(pair.key, pair.value); - return result; - }); - }, + function update(object) { + return new Hash(object).inject(this, function(result, pair) { + result.set(pair.key, pair.value); + return result; + }); + } - toQueryString: function() { - return this.inject([], function(results, pair) { - var key = encodeURIComponent(pair.key), values = pair.value; + function toQueryPair(key, value) { + if (Object.isUndefined(value)) return key; + return key + '=' + encodeURIComponent(String.interpret(value)); + } - if (values && typeof values == 'object') { - if (Object.isArray(values)) - return results.concat(values.map(toQueryPair.curry(key))); - } else results.push(toQueryPair(key, values)); - return results; - }).join('&'); - }, + function toQueryString() { + return this.inject([], function(results, pair) { + var key = encodeURIComponent(pair.key), values = pair.value; - inspect: function() { - return '#'; - }, + if (values && typeof values == 'object') { + if (Object.isArray(values)) + return results.concat(values.map(toQueryPair.curry(key))); + } else results.push(toQueryPair(key, values)); + return results; + }).join('&'); + } - toJSON: function() { - return Object.toJSON(this.toObject()); - }, + function inspect() { + return '#'; + } - clone: function() { - return new Hash(this); - } + function clone() { + return new Hash(this); } + + return { + initialize: initialize, + _each: _each, + set: set, + get: get, + unset: unset, + toObject: toObject, + toTemplateReplacements: toObject, + keys: keys, + values: values, + index: index, + merge: merge, + update: update, + toQueryString: toQueryString, + inspect: inspect, + toJSON: toObject, + clone: clone + }; })()); -Hash.prototype.toTemplateReplacements = Hash.prototype.toObject; Hash.from = $H; -var ObjectRange = Class.create(Enumerable, { - initialize: function(start, end, exclusive) { +Object.extend(Number.prototype, (function() { + function toColorPart() { + return this.toPaddedString(2, 16); + } + + function succ() { + return this + 1; + } + + function times(iterator, context) { + $R(0, this, true).each(iterator, context); + return this; + } + + function toPaddedString(length, radix) { + var string = this.toString(radix || 10); + return '0'.times(length - string.length) + string; + } + + function abs() { + return Math.abs(this); + } + + function round() { + return Math.round(this); + } + + function ceil() { + return Math.ceil(this); + } + + function floor() { + return Math.floor(this); + } + + return { + toColorPart: toColorPart, + succ: succ, + times: times, + toPaddedString: toPaddedString, + abs: abs, + round: round, + ceil: ceil, + floor: floor + }; +})()); + +function $R(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +} + +var ObjectRange = Class.create(Enumerable, (function() { + function initialize(start, end, exclusive) { this.start = start; this.end = end; this.exclusive = exclusive; - }, + } - _each: function(iterator) { + function _each(iterator) { var value = this.start; while (this.include(value)) { iterator(value); value = value.succ(); } - }, + } - include: function(value) { + function include(value) { if (value < this.start) return false; if (this.exclusive) return value < this.end; return value <= this.end; } -}); -var $R = function(start, end, exclusive) { - return new ObjectRange(start, end, exclusive); -}; + return { + initialize: initialize, + _each: _each, + include: include + }; +})()); + + var Ajax = { getTransport: function() { @@ -1164,7 +1453,6 @@ Ajax.Responders.register({ onCreate: function() { Ajax.activeRequestCount++ }, onComplete: function() { Ajax.activeRequestCount-- } }); - Ajax.Base = Class.create({ initialize: function(options) { this.options = { @@ -1186,7 +1474,6 @@ Ajax.Base = Class.create({ this.options.parameters = this.options.parameters.toObject(); } }); - Ajax.Request = Class.create(Ajax.Base, { _complete: false, @@ -1202,7 +1489,6 @@ Ajax.Request = Class.create(Ajax.Base, { var params = Object.clone(this.options.parameters); if (!['get', 'post'].include(this.method)) { - // simulate other verbs over post params['_method'] = this.method; this.method = 'post'; } @@ -1210,7 +1496,6 @@ Ajax.Request = Class.create(Ajax.Base, { this.parameters = params; if (params = Object.toQueryString(params)) { - // when GET, append parameters to URL if (this.method == 'get') this.url += (this.url.include('?') ? '&' : '?') + params; else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) @@ -1269,7 +1554,6 @@ Ajax.Request = Class.create(Ajax.Base, { headers['Connection'] = 'close'; } - // user-defined headers if (typeof this.options.requestHeaders == 'object') { var extras = this.options.requestHeaders; @@ -1323,7 +1607,6 @@ Ajax.Request = Class.create(Ajax.Base, { } if (state == 'Complete') { - // avoid memory leak in MSIE: clean up this.transport.onreadystatechange = Prototype.emptyFunction; } }, @@ -1340,7 +1623,7 @@ Ajax.Request = Class.create(Ajax.Base, { getHeader: function(name) { try { return this.transport.getResponseHeader(name) || null; - } catch (e) { return null } + } catch (e) { return null; } }, evalResponse: function() { @@ -1360,20 +1643,27 @@ Ajax.Request = Class.create(Ajax.Base, { Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + + + + + + + Ajax.Response = Class.create({ initialize: function(request){ this.request = request; var transport = this.transport = request.transport, readyState = this.readyState = transport.readyState; - if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { + if ((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) { this.status = this.getStatus(); this.statusText = this.getStatusText(); this.responseText = String.interpret(transport.responseText); this.headerJSON = this._getHeaderJSON(); } - if(readyState == 4) { + if (readyState == 4) { var xml = transport.responseXML; this.responseXML = Object.isUndefined(xml) ? null : xml; this.responseJSON = this._getResponseJSON(); @@ -1381,6 +1671,7 @@ Ajax.Response = Class.create({ }, status: 0, + statusText: '', getStatus: Ajax.Request.prototype.getStatus, @@ -1510,6 +1801,8 @@ Ajax.PeriodicalUpdater = Class.create(Ajax.Base, { this.updater = new Ajax.Updater(this.container, this.url, this.options); } }); + + function $(element) { if (arguments.length > 1) { for (var i = 0, elements = [], length = arguments.length; i < length; i++) @@ -1534,10 +1827,9 @@ if (Prototype.BrowserFeatures.XPath) { /*--------------------------------------------------------------------------*/ -if (!window.Node) var Node = { }; +if (!Node) var Node = { }; if (!Node.ELEMENT_NODE) { - // DOM level 2 ECMAScript Language Binding Object.extend(Node, { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, @@ -1554,13 +1846,27 @@ if (!Node.ELEMENT_NODE) { }); } -(function() { - var element = this.Element; - this.Element = function(tagName, attributes) { + + +(function(global) { + + var HAS_EXTENDED_CREATE_ELEMENT_SYNTAX = (function(){ + try { + var el = document.createElement(''); + return el.tagName.toLowerCase() === 'input' && el.name === 'x'; + } + catch(err) { + return false; + } + })(); + + var element = global.Element; + + global.Element = function(tagName, attributes) { attributes = attributes || { }; tagName = tagName.toLowerCase(); var cache = Element.cache; - if (Prototype.Browser.IE && attributes.name) { + if (HAS_EXTENDED_CREATE_ELEMENT_SYNTAX && attributes.name) { tagName = '<' + tagName + ' name="' + attributes.name + '">'; delete attributes.name; return Element.writeAttribute(document.createElement(tagName), attributes); @@ -1568,12 +1874,24 @@ if (!Node.ELEMENT_NODE) { if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName)); return Element.writeAttribute(cache[tagName].cloneNode(false), attributes); }; - Object.extend(this.Element, element || { }); - if (element) this.Element.prototype = element.prototype; -}).call(window); + Object.extend(global.Element, element || { }); + if (element) global.Element.prototype = element.prototype; + +})(this); + +Element.idCounter = 1; Element.cache = { }; +function purgeElement(element) { + var uid = element._prototypeUID; + if (uid) { + Element.stopObserving(element); + element._prototypeUID = void 0; + delete Element.Storage[uid]; + } +} + Element.Methods = { visible: function(element) { return $(element).style.display != 'none'; @@ -1603,22 +1921,100 @@ Element.Methods = { return element; }, - update: function(element, content) { - element = $(element); - if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) return element.update().insert(content); - content = Object.toHTML(content); - element.innerHTML = content.stripScripts(); - content.evalScripts.bind(content).defer(); - return element; - }, + update: (function(){ - replace: function(element, content) { - element = $(element); - if (content && content.toElement) content = content.toElement(); - else if (!Object.isElement(content)) { - content = Object.toHTML(content); - var range = element.ownerDocument.createRange(); + var SELECT_ELEMENT_INNERHTML_BUGGY = (function(){ + var el = document.createElement("select"), + isBuggy = true; + el.innerHTML = ""; + if (el.options && el.options[0]) { + isBuggy = el.options[0].nodeName.toUpperCase() !== "OPTION"; + } + el = null; + return isBuggy; + })(); + + var TABLE_ELEMENT_INNERHTML_BUGGY = (function(){ + try { + var el = document.createElement("table"); + if (el && el.tBodies) { + el.innerHTML = "test"; + var isBuggy = typeof el.tBodies[0] == "undefined"; + el = null; + return isBuggy; + } + } catch (e) { + return true; + } + })(); + + var SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING = (function () { + var s = document.createElement("script"), + isBuggy = false; + try { + s.appendChild(document.createTextNode("")); + isBuggy = !s.firstChild || + s.firstChild && s.firstChild.nodeType !== 3; + } catch (e) { + isBuggy = true; + } + s = null; + return isBuggy; + })(); + + function update(element, content) { + element = $(element); + + var descendants = element.getElementsByTagName('*'), + i = descendants.length; + while (i--) purgeElement(descendants[i]); + + if (content && content.toElement) + content = content.toElement(); + + if (Object.isElement(content)) + return element.update().insert(content); + + content = Object.toHTML(content); + + var tagName = element.tagName.toUpperCase(); + + if (tagName === 'SCRIPT' && SCRIPT_ELEMENT_REJECTS_TEXTNODE_APPENDING) { + element.text = content; + return element; + } + + if (SELECT_ELEMENT_INNERHTML_BUGGY || TABLE_ELEMENT_INNERHTML_BUGGY) { + if (tagName in Element._insertionTranslations.tags) { + while (element.firstChild) { + element.removeChild(element.firstChild); + } + Element._getContentFromAnonymousElement(tagName, content.stripScripts()) + .each(function(node) { + element.appendChild(node) + }); + } + else { + element.innerHTML = content.stripScripts(); + } + } + else { + element.innerHTML = content.stripScripts(); + } + + content.evalScripts.bind(content).defer(); + return element; + } + + return update; + })(), + + replace: function(element, content) { + element = $(element); + if (content && content.toElement) content = content.toElement(); + else if (!Object.isElement(content)) { + content = Object.toHTML(content); + var range = element.ownerDocument.createRange(); range.selectNode(element); content.evalScripts.bind(content).defer(); content = range.createContextualFragment(content.stripScripts()); @@ -1679,28 +2075,35 @@ Element.Methods = { element = $(element); var result = '<' + element.tagName.toLowerCase(); $H({'id': 'id', 'className': 'class'}).each(function(pair) { - var property = pair.first(), attribute = pair.last(); - var value = (element[property] || '').toString(); + var property = pair.first(), + attribute = pair.last(), + value = (element[property] || '').toString(); if (value) result += ' ' + attribute + '=' + value.inspect(true); }); return result + '>'; }, - recursivelyCollect: function(element, property) { + recursivelyCollect: function(element, property, maximumLength) { element = $(element); + maximumLength = maximumLength || -1; var elements = []; - while (element = element[property]) + + while (element = element[property]) { if (element.nodeType == 1) elements.push(Element.extend(element)); + if (elements.length == maximumLength) + break; + } + return elements; }, ancestors: function(element) { - return $(element).recursivelyCollect('parentNode'); + return Element.recursivelyCollect(element, 'parentNode'); }, descendants: function(element) { - return $(element).select("*"); + return Element.select(element, "*"); }, firstDescendant: function(element) { @@ -1710,78 +2113,96 @@ Element.Methods = { }, immediateDescendants: function(element) { - if (!(element = $(element).firstChild)) return []; - while (element && element.nodeType != 1) element = element.nextSibling; - if (element) return [element].concat($(element).nextSiblings()); - return []; + var results = [], child = $(element).firstChild; + while (child) { + if (child.nodeType === 1) { + results.push(Element.extend(child)); + } + child = child.nextSibling; + } + return results; }, - previousSiblings: function(element) { - return $(element).recursivelyCollect('previousSibling'); + previousSiblings: function(element, maximumLength) { + return Element.recursivelyCollect(element, 'previousSibling'); }, nextSiblings: function(element) { - return $(element).recursivelyCollect('nextSibling'); + return Element.recursivelyCollect(element, 'nextSibling'); }, siblings: function(element) { element = $(element); - return element.previousSiblings().reverse().concat(element.nextSiblings()); + return Element.previousSiblings(element).reverse() + .concat(Element.nextSiblings(element)); }, match: function(element, selector) { + element = $(element); if (Object.isString(selector)) - selector = new Selector(selector); - return selector.match($(element)); + return Prototype.Selector.match(element, selector); + return selector.match(element); }, up: function(element, expression, index) { element = $(element); if (arguments.length == 1) return $(element.parentNode); - var ancestors = element.ancestors(); + var ancestors = Element.ancestors(element); return Object.isNumber(expression) ? ancestors[expression] : - Selector.findElement(ancestors, expression, index); + Prototype.Selector.find(ancestors, expression, index); }, down: function(element, expression, index) { element = $(element); - if (arguments.length == 1) return element.firstDescendant(); - return Object.isNumber(expression) ? element.descendants()[expression] : + if (arguments.length == 1) return Element.firstDescendant(element); + return Object.isNumber(expression) ? Element.descendants(element)[expression] : Element.select(element, expression)[index || 0]; }, previous: function(element, expression, index) { element = $(element); - if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element)); - var previousSiblings = element.previousSiblings(); - return Object.isNumber(expression) ? previousSiblings[expression] : - Selector.findElement(previousSiblings, expression, index); + if (Object.isNumber(expression)) index = expression, expression = false; + if (!Object.isNumber(index)) index = 0; + + if (expression) { + return Prototype.Selector.find(element.previousSiblings(), expression, index); + } else { + return element.recursivelyCollect("previousSibling", index + 1)[index]; + } }, next: function(element, expression, index) { element = $(element); - if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element)); - var nextSiblings = element.nextSiblings(); - return Object.isNumber(expression) ? nextSiblings[expression] : - Selector.findElement(nextSiblings, expression, index); + if (Object.isNumber(expression)) index = expression, expression = false; + if (!Object.isNumber(index)) index = 0; + + if (expression) { + return Prototype.Selector.find(element.nextSiblings(), expression, index); + } else { + var maximumLength = Object.isNumber(index) ? index + 1 : 1; + return element.recursivelyCollect("nextSibling", index + 1)[index]; + } }, - select: function() { - var args = $A(arguments), element = $(args.shift()); - return Selector.findChildElements(element, args); + + select: function(element) { + element = $(element); + var expressions = Array.prototype.slice.call(arguments, 1).join(', '); + return Prototype.Selector.select(expressions, element); }, - adjacent: function() { - var args = $A(arguments), element = $(args.shift()); - return Selector.findChildElements(element.parentNode, args).without(element); + adjacent: function(element) { + element = $(element); + var expressions = Array.prototype.slice.call(arguments, 1).join(', '); + return Prototype.Selector.select(expressions, element.parentNode).without(element); }, identify: function(element) { element = $(element); - var id = element.readAttribute('id'), self = arguments.callee; + var id = Element.readAttribute(element, 'id'); if (id) return id; - do { id = 'anonymous_element_' + self.counter++ } while ($(id)); - element.writeAttribute('id', id); + do { id = 'anonymous_element_' + Element.idCounter++ } while ($(id)); + Element.writeAttribute(element, 'id', id); return id; }, @@ -1820,11 +2241,11 @@ Element.Methods = { }, getHeight: function(element) { - return $(element).getDimensions().height; + return Element.getDimensions(element).height; }, getWidth: function(element) { - return $(element).getDimensions().width; + return Element.getDimensions(element).width; }, classNames: function(element) { @@ -1840,7 +2261,7 @@ Element.Methods = { addClassName: function(element, className) { if (!(element = $(element))) return; - if (!element.hasClassName(className)) + if (!Element.hasClassName(element, className)) element.className += (element.className ? ' ' : '') + className; return element; }, @@ -1854,11 +2275,10 @@ Element.Methods = { toggleClassName: function(element, className) { if (!(element = $(element))) return; - return element[element.hasClassName(className) ? - 'removeClassName' : 'addClassName'](className); + return Element[Element.hasClassName(element, className) ? + 'removeClassName' : 'addClassName'](element, className); }, - // removes whitespace-only text node children cleanWhitespace: function(element) { element = $(element); var node = element.firstChild; @@ -1892,7 +2312,7 @@ Element.Methods = { scrollTo: function(element) { element = $(element); - var pos = element.cumulativeOffset(); + var pos = Element.cumulativeOffset(element); window.scrollTo(pos[0], pos[1]); return element; }, @@ -1938,37 +2358,12 @@ Element.Methods = { return element; }, - getDimensions: function(element) { - element = $(element); - var display = element.getStyle('display'); - if (display != 'none' && display != null) // Safari bug - return {width: element.offsetWidth, height: element.offsetHeight}; - - // All *Width and *Height properties give 0 on elements with display none, - // so enable the element temporarily - var els = element.style; - var originalVisibility = els.visibility; - var originalPosition = els.position; - var originalDisplay = els.display; - els.visibility = 'hidden'; - els.position = 'absolute'; - els.display = 'block'; - var originalWidth = element.clientWidth; - var originalHeight = element.clientHeight; - els.display = originalDisplay; - els.position = originalPosition; - els.visibility = originalVisibility; - return {width: originalWidth, height: originalHeight}; - }, - makePositioned: function(element) { element = $(element); var pos = Element.getStyle(element, 'position'); if (pos == 'static' || !pos) { element._madePositioned = true; element.style.position = 'relative'; - // Opera returns the offset relative to the positioning context, when an - // element is position relative but top and left have not been defined if (Prototype.Browser.Opera) { element.style.top = 0; element.style.left = 0; @@ -2009,11 +2404,13 @@ Element.Methods = { cumulativeOffset: function(element) { var valueT = 0, valueL = 0; - do { - valueT += element.offsetTop || 0; - valueL += element.offsetLeft || 0; - element = element.offsetParent; - } while (element); + if (element.parentNode) { + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + } return Element._returnOffset(valueL, valueT); }, @@ -2034,14 +2431,13 @@ Element.Methods = { absolutize: function(element) { element = $(element); - if (element.getStyle('position') == 'absolute') return element; - // Position.prepare(); // To be done manually by Scripty when it needs it. + if (Element.getStyle(element, 'position') == 'absolute') return element; - var offsets = element.positionedOffset(); - var top = offsets[1]; - var left = offsets[0]; - var width = element.clientWidth; - var height = element.clientHeight; + var offsets = Element.positionedOffset(element), + top = offsets[1], + left = offsets[0], + width = element.clientWidth, + height = element.clientHeight; element._originalLeft = left - parseFloat(element.style.left || 0); element._originalTop = top - parseFloat(element.style.top || 0); @@ -2058,12 +2454,11 @@ Element.Methods = { relativize: function(element) { element = $(element); - if (element.getStyle('position') == 'relative') return element; - // Position.prepare(); // To be done manually by Scripty when it needs it. + if (Element.getStyle(element, 'position') == 'relative') return element; element.style.position = 'relative'; - var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); - var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0), + left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); element.style.top = top + 'px'; element.style.left = left + 'px'; @@ -2094,14 +2489,14 @@ Element.Methods = { }, viewportOffset: function(forElement) { - var valueT = 0, valueL = 0; + var valueT = 0, + valueL = 0, + element = forElement; - var element = forElement; do { valueT += element.offsetTop || 0; valueL += element.offsetLeft || 0; - // Safari fix if (element.offsetParent == document.body && Element.getStyle(element, 'position') == 'absolute') break; @@ -2128,28 +2523,21 @@ Element.Methods = { offsetLeft: 0 }, arguments[2] || { }); - // find page position of source source = $(source); - var p = source.viewportOffset(); + var p = Element.viewportOffset(source), delta = [0, 0], parent = null; - // find coordinate system to use element = $(element); - var delta = [0, 0]; - var parent = null; - // delta [0,0] will do fine with position: fixed elements, - // position:absolute needs offsetParent deltas + if (Element.getStyle(element, 'position') == 'absolute') { - parent = element.getOffsetParent(); - delta = parent.viewportOffset(); + parent = Element.getOffsetParent(element); + delta = Element.viewportOffset(parent); } - // correct by body offsets (fixes Safari) if (parent == document.body) { delta[0] -= document.body.offsetLeft; delta[1] -= document.body.offsetTop; } - // set position if (options.setLeft) element.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; if (options.setTop) element.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; if (options.setWidth) element.style.width = source.offsetWidth + 'px'; @@ -2158,10 +2546,9 @@ Element.Methods = { } }; -Element.Methods.identify.counter = 1; - Object.extend(Element.Methods, { getElementsBySelector: Element.Methods.select, + childElements: Element.Methods.immediateDescendants }); @@ -2182,11 +2569,8 @@ if (Prototype.Browser.Opera) { case 'left': case 'top': case 'right': case 'bottom': if (proceed(element, 'position') === 'static') return null; case 'height': case 'width': - // returns '0px' for hidden elements; we want it to return null if (!Element.visible(element)) return null; - // returns the border-box dimensions rather than the content-box - // dimensions, so we subtract padding and borders from the value var dim = parseInt(proceed(element, style), 10); if (dim !== element['offset' + style.capitalize()]) @@ -2219,14 +2603,10 @@ if (Prototype.Browser.Opera) { } else if (Prototype.Browser.IE) { - // IE doesn't report offsets correctly for static elements, so we change them - // to "relative" to get the values, then change them back. Element.Methods.getOffsetParent = Element.Methods.getOffsetParent.wrap( function(proceed, element) { element = $(element); - // IE throws an error if element is not in document - try { element.offsetParent } - catch(e) { return $(document.body) } + if (!element.parentNode) return $(document.body); var position = element.getStyle('position'); if (position !== 'static') return proceed(element); element.setStyle({ position: 'relative' }); @@ -2240,12 +2620,9 @@ else if (Prototype.Browser.IE) { Element.Methods[method] = Element.Methods[method].wrap( function(proceed, element) { element = $(element); - try { element.offsetParent } - catch(e) { return Element._returnOffset(0,0) } + if (!element.parentNode) return Element._returnOffset(0, 0); var position = element.getStyle('position'); if (position !== 'static') return proceed(element); - // Trigger hasLayout on the offset parent so that IE6 reports - // accurate offsetTop and offsetLeft values for position: fixed. var offsetParent = element.getOffsetParent(); if (offsetParent && offsetParent.getStyle('position') === 'fixed') offsetParent.setStyle({ zoom: 1 }); @@ -2257,14 +2634,6 @@ else if (Prototype.Browser.IE) { ); }); - Element.Methods.cumulativeOffset = Element.Methods.cumulativeOffset.wrap( - function(proceed, element) { - try { element.offsetParent } - catch(e) { return Element._returnOffset(0,0) } - return proceed(element); - } - ); - Element.Methods.getStyle = function(element, style) { element = $(element); style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize(); @@ -2306,36 +2675,90 @@ else if (Prototype.Browser.IE) { return element; }; - Element._attributeTranslations = { - read: { - names: { - 'class': 'className', - 'for': 'htmlFor' - }, - values: { - _getAttr: function(element, attribute) { - return element.getAttribute(attribute, 2); - }, - _getAttrNode: function(element, attribute) { - var node = element.getAttributeNode(attribute); - return node ? node.value : ""; - }, - _getEv: function(element, attribute) { - attribute = element.getAttribute(attribute); - return attribute ? attribute.toString().slice(23, -2) : null; - }, - _flag: function(element, attribute) { - return $(element).hasAttribute(attribute) ? attribute : null; - }, - style: function(element) { - return element.style.cssText.toLowerCase(); + Element._attributeTranslations = (function(){ + + var classProp = 'className', + forProp = 'for', + el = document.createElement('div'); + + el.setAttribute(classProp, 'x'); + + if (el.className !== 'x') { + el.setAttribute('class', 'x'); + if (el.className === 'x') { + classProp = 'class'; + } + } + el = null; + + el = document.createElement('label'); + el.setAttribute(forProp, 'x'); + if (el.htmlFor !== 'x') { + el.setAttribute('htmlFor', 'x'); + if (el.htmlFor === 'x') { + forProp = 'htmlFor'; + } + } + el = null; + + return { + read: { + names: { + 'class': classProp, + 'className': classProp, + 'for': forProp, + 'htmlFor': forProp }, - title: function(element) { - return element.title; + values: { + _getAttr: function(element, attribute) { + return element.getAttribute(attribute); + }, + _getAttr2: function(element, attribute) { + return element.getAttribute(attribute, 2); + }, + _getAttrNode: function(element, attribute) { + var node = element.getAttributeNode(attribute); + return node ? node.value : ""; + }, + _getEv: (function(){ + + var el = document.createElement('div'), f; + el.onclick = Prototype.emptyFunction; + var value = el.getAttribute('onclick'); + + if (String(value).indexOf('{') > -1) { + f = function(element, attribute) { + attribute = element.getAttribute(attribute); + if (!attribute) return null; + attribute = attribute.toString(); + attribute = attribute.split('{')[1]; + attribute = attribute.split('}')[0]; + return attribute.strip(); + }; + } + else if (value === '') { + f = function(element, attribute) { + attribute = element.getAttribute(attribute); + if (!attribute) return null; + return attribute.strip(); + }; + } + el = null; + return f; + })(), + _flag: function(element, attribute) { + return $(element).hasAttribute(attribute) ? attribute : null; + }, + style: function(element) { + return element.style.cssText.toLowerCase(); + }, + title: function(element) { + return element.title; + } } } } - }; + })(); Element._attributeTranslations.write = { names: Object.extend({ @@ -2363,8 +2786,8 @@ else if (Prototype.Browser.IE) { (function(v) { Object.extend(v, { - href: v._getAttr, - src: v._getAttr, + href: v._getAttr2, + src: v._getAttr2, type: v._getAttr, action: v._getAttrNode, disabled: v._flag, @@ -2391,6 +2814,26 @@ else if (Prototype.Browser.IE) { onchange: v._getEv }); })(Element._attributeTranslations.read.values); + + if (Prototype.BrowserFeatures.ElementExtensions) { + (function() { + function _descendants(element) { + var nodes = element.getElementsByTagName('*'), results = []; + for (var i = 0, node; node = nodes[i]; i++) + if (node.tagName !== "!") // Filter out comment nodes. + results.push(node); + return results; + } + + Element.Methods.down = function(element, expression, index) { + element = $(element); + if (arguments.length == 1) return element.firstDescendant(); + return Object.isNumber(expression) ? _descendants(element)[expression] : + Element.select(element, expression)[index || 0]; + } + })(); + } + } else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) { @@ -2409,7 +2852,7 @@ else if (Prototype.Browser.WebKit) { (value < 0.00001) ? 0 : value; if (value == 1) - if(element.tagName.toUpperCase() == 'IMG' && element.width) { + if (element.tagName.toUpperCase() == 'IMG' && element.width) { element.width++; element.width--; } else try { var n = document.createTextNode(' '); @@ -2420,9 +2863,6 @@ else if (Prototype.Browser.WebKit) { return element; }; - // Safari returns margins on body which is incorrect if the child is absolutely - // positioned. For performance reasons, redefine Element#cumulativeOffset for - // KHTML/WebKit only. Element.Methods.cumulativeOffset = function(element) { var valueT = 0, valueL = 0; do { @@ -2438,30 +2878,7 @@ else if (Prototype.Browser.WebKit) { }; } -if (Prototype.Browser.IE || Prototype.Browser.Opera) { - // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements - Element.Methods.update = function(element, content) { - element = $(element); - - if (content && content.toElement) content = content.toElement(); - if (Object.isElement(content)) return element.update().insert(content); - - content = Object.toHTML(content); - var tagName = element.tagName.toUpperCase(); - - if (tagName in Element._insertionTranslations.tags) { - $A(element.childNodes).each(function(node) { element.removeChild(node) }); - Element._getContentFromAnonymousElement(tagName, content.stripScripts()) - .each(function(node) { element.appendChild(node) }); - } - else element.innerHTML = content.stripScripts(); - - content.evalScripts.bind(content).defer(); - return element; - }; -} - -if ('outerHTML' in document.createElement('div')) { +if ('outerHTML' in document.documentElement) { Element.Methods.replace = function(element, content) { element = $(element); @@ -2475,8 +2892,8 @@ if ('outerHTML' in document.createElement('div')) { var parent = element.parentNode, tagName = parent.tagName.toUpperCase(); if (Element._insertionTranslations.tags[tagName]) { - var nextSibling = element.next(); - var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); + var nextSibling = element.next(), + fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts()); parent.removeChild(element); if (nextSibling) fragments.each(function(node) { parent.insertBefore(node, nextSibling) }); @@ -2498,11 +2915,17 @@ Element._returnOffset = function(l, t) { }; Element._getContentFromAnonymousElement = function(tagName, html) { - var div = new Element('div'), t = Element._insertionTranslations.tags[tagName]; + var div = new Element('div'), + t = Element._insertionTranslations.tags[tagName]; if (t) { div.innerHTML = t[0] + html + t[1]; - t[2].times(function() { div = div.firstChild }); - } else div.innerHTML = html; + for (var i = t[2]; i--; ) { + div = div.firstChild; + } + } + else { + div.innerHTML = html; + } return $A(div.childNodes); }; @@ -2529,12 +2952,13 @@ Element._insertionTranslations = { }; (function() { - Object.extend(this.tags, { - THEAD: this.tags.TBODY, - TFOOT: this.tags.TBODY, - TH: this.tags.TD + var tags = Element._insertionTranslations.tags; + Object.extend(tags, { + THEAD: tags.TBODY, + TFOOT: tags.TBODY, + TH: tags.TD }); -}).call(Element._insertionTranslations); +})(); Element.Methods.Simulated = { hasAttribute: function(element, attribute) { @@ -2548,41 +2972,81 @@ Element.Methods.ByTag = { }; Object.extend(Element, Element.Methods); -if (!Prototype.BrowserFeatures.ElementExtensions && - document.createElement('div')['__proto__']) { - window.HTMLElement = { }; - window.HTMLElement.prototype = document.createElement('div')['__proto__']; - Prototype.BrowserFeatures.ElementExtensions = true; -} +(function(div) { + + if (!Prototype.BrowserFeatures.ElementExtensions && div['__proto__']) { + window.HTMLElement = { }; + window.HTMLElement.prototype = div['__proto__']; + Prototype.BrowserFeatures.ElementExtensions = true; + } + + div = null; + +})(document.createElement('div')); Element.extend = (function() { - if (Prototype.BrowserFeatures.SpecificElementExtensions) + + function checkDeficiency(tagName) { + if (typeof window.Element != 'undefined') { + var proto = window.Element.prototype; + if (proto) { + var id = '_' + (Math.random()+'').slice(2), + el = document.createElement(tagName); + proto[id] = 'x'; + var isBuggy = (el[id] !== 'x'); + delete proto[id]; + el = null; + return isBuggy; + } + } + return false; + } + + function extendElementWith(element, methods) { + for (var property in methods) { + var value = methods[property]; + if (Object.isFunction(value) && !(property in element)) + element[property] = value.methodize(); + } + } + + var HTMLOBJECTELEMENT_PROTOTYPE_BUGGY = checkDeficiency('object'); + + if (Prototype.BrowserFeatures.SpecificElementExtensions) { + if (HTMLOBJECTELEMENT_PROTOTYPE_BUGGY) { + return function(element) { + if (element && typeof element._extendedByPrototype == 'undefined') { + var t = element.tagName; + if (t && (/^(?:object|applet|embed)$/i.test(t))) { + extendElementWith(element, Element.Methods); + extendElementWith(element, Element.Methods.Simulated); + extendElementWith(element, Element.Methods.ByTag[t.toUpperCase()]); + } + } + return element; + } + } return Prototype.K; + } var Methods = { }, ByTag = Element.Methods.ByTag; var extend = Object.extend(function(element) { - if (!element || element._extendedByPrototype || + if (!element || typeof element._extendedByPrototype != 'undefined' || element.nodeType != 1 || element == window) return element; var methods = Object.clone(Methods), - tagName = element.tagName.toUpperCase(), property, value; + tagName = element.tagName.toUpperCase(); - // extend methods for specific tags if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]); - for (property in methods) { - value = methods[property]; - if (Object.isFunction(value) && !(property in element)) - element[property] = value.methodize(); - } + extendElementWith(element, methods); element._extendedByPrototype = Prototype.emptyFunction; return element; }, { refresh: function() { - // extend methods for all tags (Safari doesn't need this) if (!Prototype.BrowserFeatures.ElementExtensions) { Object.extend(Methods, Element.Methods); Object.extend(Methods, Element.Methods.Simulated); @@ -2594,10 +3058,14 @@ Element.extend = (function() { return extend; })(); -Element.hasAttribute = function(element, attribute) { - if (element.hasAttribute) return element.hasAttribute(attribute); - return Element.Methods.Simulated.hasAttribute(element, attribute); -}; +if (document.documentElement.hasAttribute) { + Element.hasAttribute = function(element, attribute) { + return element.hasAttribute(attribute); + }; +} +else { + Element.hasAttribute = Element.Methods.Simulated.hasAttribute; +} Element.addMethods = function(methods) { var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag; @@ -2661,14 +3129,19 @@ Element.addMethods = function(methods) { klass = 'HTML' + tagName.capitalize() + 'Element'; if (window[klass]) return window[klass]; - window[klass] = { }; - window[klass].prototype = document.createElement(tagName)['__proto__']; - return window[klass]; + var element = document.createElement(tagName), + proto = element['__proto__'] || element.constructor.prototype; + + element = null; + return proto; } + var elementPrototype = window.HTMLElement ? HTMLElement.prototype : + Element.prototype; + if (F.ElementExtensions) { - copy(Element.Methods, HTMLElement.prototype); - copy(Element.Methods.Simulated, HTMLElement.prototype, true); + copy(Element.Methods, elementPrototype); + copy(Element.Methods.Simulated, elementPrototype, true); } if (F.SpecificElementExtensions) { @@ -2686,766 +3159,1803 @@ Element.addMethods = function(methods) { Element.cache = { }; }; -document.viewport = { - getDimensions: function() { - var dimensions = { }, B = Prototype.Browser; - $w('width height').each(function(d) { - var D = d.capitalize(); - if (B.WebKit && !document.evaluate) { - // Safari <3.0 needs self.innerWidth/Height - dimensions[d] = self['inner' + D]; - } else if (B.Opera && parseFloat(window.opera.version()) < 9.5) { - // Opera <9.5 needs document.body.clientWidth/Height - dimensions[d] = document.body['client' + D] - } else { - dimensions[d] = document.documentElement['client' + D]; - } - }); - return dimensions; - }, - getWidth: function() { - return this.getDimensions().width; - }, +document.viewport = { - getHeight: function() { - return this.getDimensions().height; + getDimensions: function() { + return { width: this.getWidth(), height: this.getHeight() }; }, getScrollOffsets: function() { return Element._returnOffset( window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft, - window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); + window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop); } }; -/* Portions of the Selector class are derived from Jack Slocum's DomQuery, - * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style - * license. Please see http://www.yui-ext.com/ for more information. */ - -var Selector = Class.create({ - initialize: function(expression) { - this.expression = expression.strip(); - - if (this.shouldUseSelectorsAPI()) { - this.mode = 'selectorsAPI'; - } else if (this.shouldUseXPath()) { - this.mode = 'xpath'; - this.compileXPathMatcher(); - } else { - this.mode = "normal"; - this.compileMatcher(); - } - - }, - shouldUseXPath: function() { - if (!Prototype.BrowserFeatures.XPath) return false; +(function(viewport) { + var B = Prototype.Browser, doc = document, element, property = {}; - var e = this.expression; + function getRootElement() { + if (B.WebKit && !doc.evaluate) + return document; - // Safari 3 chokes on :*-of-type and :empty - if (Prototype.Browser.WebKit && - (e.include("-of-type") || e.include(":empty"))) - return false; + if (B.Opera && window.parseFloat(window.opera.version()) < 9.5) + return document.body; - // XPath can't do namespaced attributes, nor can it read - // the "checked" property from DOM nodes - if ((/(\[[\w-]*?:|:checked)/).test(e)) - return false; + return document.documentElement; + } - return true; - }, + function define(D) { + if (!element) element = getRootElement(); - shouldUseSelectorsAPI: function() { - if (!Prototype.BrowserFeatures.SelectorsAPI) return false; + property[D] = 'client' + D; - if (!Selector._div) Selector._div = new Element('div'); + viewport['get' + D] = function() { return element[property[D]] }; + return viewport['get' + D](); + } - // Make sure the browser treats the selector as valid. Test on an - // isolated element to minimize cost of this check. - try { - Selector._div.querySelector(this.expression); - } catch(e) { - return false; - } + viewport.getWidth = define.curry('Width'); - return true; - }, + viewport.getHeight = define.curry('Height'); +})(document.viewport); - compileMatcher: function() { - var e = this.expression, ps = Selector.patterns, h = Selector.handlers, - c = Selector.criteria, le, p, m; - if (Selector._cache[e]) { - this.matcher = Selector._cache[e]; - return; - } +Element.Storage = { + UID: 1 +}; - this.matcher = ["this.matcher = function(root) {", - "var r = root, h = Selector.handlers, c = false, n;"]; +Element.addMethods({ + getStorage: function(element) { + if (!(element = $(element))) return; - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - p = ps[i]; - if (m = e.match(p)) { - this.matcher.push(Object.isFunction(c[i]) ? c[i](m) : - new Template(c[i]).evaluate(m)); - e = e.replace(m[0], ''); - break; - } - } + var uid; + if (element === window) { + uid = 0; + } else { + if (typeof element._prototypeUID === "undefined") + element._prototypeUID = Element.Storage.UID++; + uid = element._prototypeUID; } - this.matcher.push("return h.unique(n);\n}"); - eval(this.matcher.join('\n')); - Selector._cache[this.expression] = this.matcher; - }, + if (!Element.Storage[uid]) + Element.Storage[uid] = $H(); - compileXPathMatcher: function() { - var e = this.expression, ps = Selector.patterns, - x = Selector.xpath, le, m; + return Element.Storage[uid]; + }, - if (Selector._cache[e]) { - this.xpath = Selector._cache[e]; return; - } + store: function(element, key, value) { + if (!(element = $(element))) return; - this.matcher = ['.//*']; - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - if (m = e.match(ps[i])) { - this.matcher.push(Object.isFunction(x[i]) ? x[i](m) : - new Template(x[i]).evaluate(m)); - e = e.replace(m[0], ''); - break; - } - } + if (arguments.length === 2) { + Element.getStorage(element).update(key); + } else { + Element.getStorage(element).set(key, value); } - this.xpath = this.matcher.join(''); - Selector._cache[this.expression] = this.xpath; + return element; }, - findElements: function(root) { - root = root || document; - var e = this.expression, results; + retrieve: function(element, key, defaultValue) { + if (!(element = $(element))) return; + var hash = Element.getStorage(element), value = hash.get(key); - switch (this.mode) { - case 'selectorsAPI': - // querySelectorAll queries document-wide, then filters to descendants - // of the context element. That's not what we want. - // Add an explicit context to the selector if necessary. - if (root !== document) { - var oldId = root.id, id = $(root).identify(); - e = "#" + id + " " + e; - } + if (Object.isUndefined(value)) { + hash.set(key, defaultValue); + value = defaultValue; + } - results = $A(root.querySelectorAll(e)).map(Element.extend); - root.id = oldId; + return value; + }, - return results; - case 'xpath': - return document._getElementsByXPath(this.xpath, root); - default: - return this.matcher(root); - } - }, - - match: function(element) { - this.tokens = []; - - var e = this.expression, ps = Selector.patterns, as = Selector.assertions; - var le, p, m; - - while (e && le !== e && (/\S/).test(e)) { - le = e; - for (var i in ps) { - p = ps[i]; - if (m = e.match(p)) { - // use the Selector.assertions methods unless the selector - // is too complex. - if (as[i]) { - this.tokens.push([i, Object.clone(m)]); - e = e.replace(m[0], ''); - } else { - // reluctantly do a document-wide search - // and look for a match in the array - return this.findElements(document).include(element); - } - } + clone: function(element, deep) { + if (!(element = $(element))) return; + var clone = element.cloneNode(deep); + clone._prototypeUID = void 0; + if (deep) { + var descendants = Element.select(clone, '*'), + i = descendants.length; + while (i--) { + descendants[i]._prototypeUID = void 0; } } + return Element.extend(clone); + }, - var match = true, name, matches; - for (var i = 0, token; token = this.tokens[i]; i++) { - name = token[0], matches = token[1]; - if (!Selector.assertions[name](element, matches)) { - match = false; break; - } - } + purge: function(element) { + if (!(element = $(element))) return; + purgeElement(element); - return match; - }, + var descendants = element.getElementsByTagName('*'), + i = descendants.length; - toString: function() { - return this.expression; - }, + while (i--) purgeElement(descendants[i]); - inspect: function() { - return "#"; + return null; } }); -Object.extend(Selector, { - _cache: { }, - - xpath: { - descendant: "//*", - child: "/*", - adjacent: "/following-sibling::*[1]", - laterSibling: '/following-sibling::*', - tagName: function(m) { - if (m[1] == '*') return ''; - return "[local-name()='" + m[1].toLowerCase() + - "' or local-name()='" + m[1].toUpperCase() + "']"; - }, - className: "[contains(concat(' ', @class, ' '), ' #{1} ')]", - id: "[@id='#{1}']", - attrPresence: function(m) { - m[1] = m[1].toLowerCase(); - return new Template("[@#{1}]").evaluate(m); - }, - attr: function(m) { - m[1] = m[1].toLowerCase(); - m[3] = m[5] || m[6]; - return new Template(Selector.xpath.operators[m[2]]).evaluate(m); - }, - pseudo: function(m) { - var h = Selector.xpath.pseudos[m[1]]; - if (!h) return ''; - if (Object.isFunction(h)) return h(m); - return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m); - }, - operators: { - '=': "[@#{1}='#{3}']", - '!=': "[@#{1}!='#{3}']", - '^=': "[starts-with(@#{1}, '#{3}')]", - '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']", - '*=': "[contains(@#{1}, '#{3}')]", - '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]", - '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]" - }, - pseudos: { - 'first-child': '[not(preceding-sibling::*)]', - 'last-child': '[not(following-sibling::*)]', - 'only-child': '[not(preceding-sibling::* or following-sibling::*)]', - 'empty': "[count(*) = 0 and (count(text()) = 0)]", - 'checked': "[@checked]", - 'disabled': "[(@disabled) and (@type!='hidden')]", - 'enabled': "[not(@disabled) and (@type!='hidden')]", - 'not': function(m) { - var e = m[6], p = Selector.patterns, - x = Selector.xpath, le, v; - - var exclusion = []; - while (e && le != e && (/\S/).test(e)) { - le = e; - for (var i in p) { - if (m = e.match(p[i])) { - v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m); - exclusion.push("(" + v.substring(1, v.length - 1) + ")"); - e = e.replace(m[0], ''); - break; - } - } - } - return "[not(" + exclusion.join(" and ") + ")]"; - }, - 'nth-child': function(m) { - return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m); - }, - 'nth-last-child': function(m) { - return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m); - }, - 'nth-of-type': function(m) { - return Selector.xpath.pseudos.nth("position() ", m); - }, - 'nth-last-of-type': function(m) { - return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m); - }, - 'first-of-type': function(m) { - m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m); - }, - 'last-of-type': function(m) { - m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m); - }, - 'only-of-type': function(m) { - var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m); - }, - nth: function(fragment, m) { - var mm, formula = m[6], predicate; - if (formula == 'even') formula = '2n+0'; - if (formula == 'odd') formula = '2n+1'; - if (mm = formula.match(/^(\d+)$/)) // digit only - return '[' + fragment + "= " + mm[1] + ']'; - if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b - if (mm[1] == "-") mm[1] = -1; - var a = mm[1] ? Number(mm[1]) : 1; - var b = mm[2] ? Number(mm[2]) : 0; - predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " + - "((#{fragment} - #{b}) div #{a} >= 0)]"; - return new Template(predicate).evaluate({ - fragment: fragment, a: a, b: b }); - } - } - } - }, +(function() { - criteria: { - tagName: 'n = h.tagName(n, r, "#{1}", c); c = false;', - className: 'n = h.className(n, r, "#{1}", c); c = false;', - id: 'n = h.id(n, r, "#{1}", c); c = false;', - attrPresence: 'n = h.attrPresence(n, r, "#{1}", c); c = false;', - attr: function(m) { - m[3] = (m[5] || m[6]); - return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(m); - }, - pseudo: function(m) { - if (m[6]) m[6] = m[6].replace(/"/g, '\\"'); - return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m); - }, - descendant: 'c = "descendant";', - child: 'c = "child";', - adjacent: 'c = "adjacent";', - laterSibling: 'c = "laterSibling";' - }, - - patterns: { - // combinators must be listed first - // (and descendant needs to be last combinator) - laterSibling: /^\s*~\s*/, - child: /^\s*>\s*/, - adjacent: /^\s*\+\s*/, - descendant: /^\s/, - - // selectors follow - tagName: /^\s*(\*|[\w\-]+)(\b|$)?/, - id: /^#([\w\-\*]+)(\b|$)/, - className: /^\.([\w\-\*]+)(\b|$)/, - pseudo: -/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/, - attrPresence: /^\[((?:[\w]+:)?[\w]+)\]/, - attr: /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/ - }, - - // for Selector.match and Element#match - assertions: { - tagName: function(element, matches) { - return matches[1].toUpperCase() == element.tagName.toUpperCase(); - }, + function toDecimal(pctString) { + var match = pctString.match(/^(\d+)%?$/i); + if (!match) return null; + return (Number(match[1]) / 100); + } - className: function(element, matches) { - return Element.hasClassName(element, matches[1]); - }, + function getPixelValue(value, property) { + if (Object.isElement(value)) { + element = value; + value = element.getStyle(property); + } + if (value === null) { + return null; + } - id: function(element, matches) { - return element.id === matches[1]; - }, + if ((/^(?:-)?\d+(\.\d+)?(px)?$/i).test(value)) { + return window.parseFloat(value); + } - attrPresence: function(element, matches) { - return Element.hasAttribute(element, matches[1]); - }, + if (/\d/.test(value) && element.runtimeStyle) { + var style = element.style.left, rStyle = element.runtimeStyle.left; + element.runtimeStyle.left = element.currentStyle.left; + element.style.left = value || 0; + value = element.style.pixelLeft; + element.style.left = style; + element.runtimeStyle.left = rStyle; - attr: function(element, matches) { - var nodeValue = Element.readAttribute(element, matches[1]); - return nodeValue && Selector.operators[matches[2]](nodeValue, matches[5] || matches[6]); + return value; } - }, - handlers: { - // UTILITY FUNCTIONS - // joins two collections - concat: function(a, b) { - for (var i = 0, node; node = b[i]; i++) - a.push(node); - return a; - }, + if (value.include('%')) { + var decimal = toDecimal(value); + var whole; + if (property.include('left') || property.include('right') || + property.include('width')) { + whole = $(element.parentNode).measure('width'); + } else if (property.include('top') || property.include('bottom') || + property.include('height')) { + whole = $(element.parentNode).measure('height'); + } - // marks an array of nodes for counting - mark: function(nodes) { - var _true = Prototype.emptyFunction; - for (var i = 0, node; node = nodes[i]; i++) - node._countedByPrototype = _true; - return nodes; - }, + return whole * decimal; + } - unmark: function(nodes) { - for (var i = 0, node; node = nodes[i]; i++) - node._countedByPrototype = undefined; - return nodes; - }, + return 0; + } - // mark each child node with its position (for nth calls) - // "ofType" flag indicates whether we're indexing for nth-of-type - // rather than nth-child - index: function(parentNode, reverse, ofType) { - parentNode._countedByPrototype = Prototype.emptyFunction; - if (reverse) { - for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) { - var node = nodes[i]; - if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; - } - } else { - for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++) - if (node.nodeType == 1 && (!ofType || node._countedByPrototype)) node.nodeIndex = j++; + function toCSSPixels(number) { + if (Object.isString(number) && number.endsWith('px')) { + return number; + } + return number + 'px'; + } + + function isDisplayed(element) { + var originalElement = element; + while (element && element.parentNode) { + var display = element.getStyle('display'); + if (display === 'none') { + return false; + } + element = $(element.parentNode); + } + return true; + } + + var hasLayout = Prototype.K; + if ('currentStyle' in document.documentElement) { + hasLayout = function(element) { + if (!element.currentStyle.hasLayout) { + element.style.zoom = 1; + } + return element; + }; + } + + function cssNameFor(key) { + if (key.include('border')) key = key + '-width'; + return key.camelize(); + } + + Element.Layout = Class.create(Hash, { + initialize: function($super, element, preCompute) { + $super(); + this.element = $(element); + + Element.Layout.PROPERTIES.each( function(property) { + this._set(property, null); + }, this); + + if (preCompute) { + this._preComputing = true; + this._begin(); + Element.Layout.PROPERTIES.each( this._compute, this ); + this._end(); + this._preComputing = false; } }, - // filters out duplicates and extends all nodes - unique: function(nodes) { - if (nodes.length == 0) return nodes; - var results = [], n; - for (var i = 0, l = nodes.length; i < l; i++) - if (!(n = nodes[i])._countedByPrototype) { - n._countedByPrototype = Prototype.emptyFunction; - results.push(Element.extend(n)); - } - return Selector.handlers.unmark(results); + _set: function(property, value) { + return Hash.prototype.set.call(this, property, value); }, - // COMBINATOR FUNCTIONS - descendant: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - h.concat(results, node.getElementsByTagName('*')); - return results; + set: function(property, value) { + throw "Properties of Element.Layout are read-only."; }, - child: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) { - for (var j = 0, child; child = node.childNodes[j]; j++) - if (child.nodeType == 1 && child.tagName != '!') results.push(child); - } - return results; + get: function($super, property) { + var value = $super(property); + return value === null ? this._compute(property) : value; }, - adjacent: function(nodes) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - var next = this.nextElementSibling(node); - if (next) results.push(next); + _begin: function() { + if (this._prepared) return; + + var element = this.element; + if (isDisplayed(element)) { + this._prepared = true; + return; } - return results; + + var originalStyles = { + position: element.style.position || '', + width: element.style.width || '', + visibility: element.style.visibility || '', + display: element.style.display || '' + }; + + element.store('prototype_original_styles', originalStyles); + + var position = element.getStyle('position'), + width = element.getStyle('width'); + + element.setStyle({ + position: 'absolute', + visibility: 'hidden', + display: 'block' + }); + + var positionedWidth = element.getStyle('width'); + + var newWidth; + if (width && (positionedWidth === width)) { + newWidth = getPixelValue(width); + } else if (width && (position === 'absolute' || position === 'fixed')) { + newWidth = getPixelValue(width); + } else { + var parent = element.parentNode, pLayout = $(parent).getLayout(); + + newWidth = pLayout.get('width') - + this.get('margin-left') - + this.get('border-left') - + this.get('padding-left') - + this.get('padding-right') - + this.get('border-right') - + this.get('margin-right'); + } + + element.setStyle({ width: newWidth + 'px' }); + + this._prepared = true; }, - laterSibling: function(nodes) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - h.concat(results, Element.nextSiblings(node)); - return results; + _end: function() { + var element = this.element; + var originalStyles = element.retrieve('prototype_original_styles'); + element.store('prototype_original_styles', null); + element.setStyle(originalStyles); + this._prepared = false; }, - nextElementSibling: function(node) { - while (node = node.nextSibling) - if (node.nodeType == 1) return node; - return null; + _compute: function(property) { + var COMPUTATIONS = Element.Layout.COMPUTATIONS; + if (!(property in COMPUTATIONS)) { + throw "Property not found."; + } + return this._set(property, COMPUTATIONS[property].call(this, this.element)); }, - previousElementSibling: function(node) { - while (node = node.previousSibling) - if (node.nodeType == 1) return node; - return null; + toObject: function() { + var args = $A(arguments); + var keys = (args.length === 0) ? Element.Layout.PROPERTIES : + args.join(' ').split(' '); + var obj = {}; + keys.each( function(key) { + if (!Element.Layout.PROPERTIES.include(key)) return; + var value = this.get(key); + if (value != null) obj[key] = value; + }, this); + return obj; }, - // TOKEN FUNCTIONS - tagName: function(nodes, root, tagName, combinator) { - var uTagName = tagName.toUpperCase(); - var results = [], h = Selector.handlers; - if (nodes) { - if (combinator) { - // fastlane for ordinary descendant combinators - if (combinator == "descendant") { - for (var i = 0, node; node = nodes[i]; i++) - h.concat(results, node.getElementsByTagName(tagName)); - return results; - } else nodes = this[combinator](nodes); - if (tagName == "*") return nodes; - } - for (var i = 0, node; node = nodes[i]; i++) - if (node.tagName.toUpperCase() === uTagName) results.push(node); - return results; - } else return root.getElementsByTagName(tagName); + toHash: function() { + var obj = this.toObject.apply(this, arguments); + return new Hash(obj); }, - id: function(nodes, root, id, combinator) { - var targetNode = $(id), h = Selector.handlers; - if (!targetNode) return []; - if (!nodes && root == document) return [targetNode]; - if (nodes) { - if (combinator) { - if (combinator == 'child') { - for (var i = 0, node; node = nodes[i]; i++) - if (targetNode.parentNode == node) return [targetNode]; - } else if (combinator == 'descendant') { - for (var i = 0, node; node = nodes[i]; i++) - if (Element.descendantOf(targetNode, node)) return [targetNode]; - } else if (combinator == 'adjacent') { - for (var i = 0, node; node = nodes[i]; i++) - if (Selector.handlers.previousElementSibling(targetNode) == node) - return [targetNode]; - } else nodes = h[combinator](nodes); - } - for (var i = 0, node; node = nodes[i]; i++) - if (node == targetNode) return [targetNode]; - return []; + toCSS: function() { + var args = $A(arguments); + var keys = (args.length === 0) ? Element.Layout.PROPERTIES : + args.join(' ').split(' '); + var css = {}; + + keys.each( function(key) { + if (!Element.Layout.PROPERTIES.include(key)) return; + if (Element.Layout.COMPOSITE_PROPERTIES.include(key)) return; + + var value = this.get(key); + if (value != null) css[cssNameFor(key)] = value + 'px'; + }, this); + return css; + }, + + inspect: function() { + return "#"; + } + }); + + Object.extend(Element.Layout, { + PROPERTIES: $w('height width top left right bottom border-left border-right border-top border-bottom padding-left padding-right padding-top padding-bottom margin-top margin-bottom margin-left margin-right padding-box-width padding-box-height border-box-width border-box-height margin-box-width margin-box-height'), + + COMPOSITE_PROPERTIES: $w('padding-box-width padding-box-height margin-box-width margin-box-height border-box-width border-box-height'), + + COMPUTATIONS: { + 'height': function(element) { + if (!this._preComputing) this._begin(); + + var bHeight = this.get('border-box-height'); + if (bHeight <= 0) return 0; + + var bTop = this.get('border-top'), + bBottom = this.get('border-bottom'); + + var pTop = this.get('padding-top'), + pBottom = this.get('padding-bottom'); + + if (!this._preComputing) this._end(); + + return bHeight - bTop - bBottom - pTop - pBottom; + }, + + 'width': function(element) { + if (!this._preComputing) this._begin(); + + var bWidth = this.get('border-box-width'); + if (bWidth <= 0) return 0; + + var bLeft = this.get('border-left'), + bRight = this.get('border-right'); + + var pLeft = this.get('padding-left'), + pRight = this.get('padding-right'); + + if (!this._preComputing) this._end(); + + return bWidth - bLeft - bRight - pLeft - pRight; + }, + + 'padding-box-height': function(element) { + var height = this.get('height'), + pTop = this.get('padding-top'), + pBottom = this.get('padding-bottom'); + + return height + pTop + pBottom; + }, + + 'padding-box-width': function(element) { + var width = this.get('width'), + pLeft = this.get('padding-left'), + pRight = this.get('padding-right'); + + return width + pLeft + pRight; + }, + + 'border-box-height': function(element) { + return element.offsetHeight; + }, + + 'border-box-width': function(element) { + return element.offsetWidth; + }, + + 'margin-box-height': function(element) { + var bHeight = this.get('border-box-height'), + mTop = this.get('margin-top'), + mBottom = this.get('margin-bottom'); + + if (bHeight <= 0) return 0; + + return bHeight + mTop + mBottom; + }, + + 'margin-box-width': function(element) { + var bWidth = this.get('border-box-width'), + mLeft = this.get('margin-left'), + mRight = this.get('margin-right'); + + if (bWidth <= 0) return 0; + + return bWidth + mLeft + mRight; + }, + + 'top': function(element) { + var offset = element.positionedOffset(); + return offset.top; + }, + + 'bottom': function(element) { + var offset = element.positionedOffset(), + parent = element.getOffsetParent(), + pHeight = parent.measure('height'); + + var mHeight = this.get('border-box-height'); + + return pHeight - mHeight - offset.top; + }, + + 'left': function(element) { + var offset = element.positionedOffset(); + return offset.left; + }, + + 'right': function(element) { + var offset = element.positionedOffset(), + parent = element.getOffsetParent(), + pWidth = parent.measure('width'); + + var mWidth = this.get('border-box-width'); + + return pWidth - mWidth - offset.left; + }, + + 'padding-top': function(element) { + return getPixelValue(element, 'paddingTop'); + }, + + 'padding-bottom': function(element) { + return getPixelValue(element, 'paddingBottom'); + }, + + 'padding-left': function(element) { + return getPixelValue(element, 'paddingLeft'); + }, + + 'padding-right': function(element) { + return getPixelValue(element, 'paddingRight'); + }, + + 'border-top': function(element) { + return Object.isNumber(element.clientTop) ? element.clientTop : + getPixelValue(element, 'borderTopWidth'); + }, + + 'border-bottom': function(element) { + return Object.isNumber(element.clientBottom) ? element.clientBottom : + getPixelValue(element, 'borderBottomWidth'); + }, + + 'border-left': function(element) { + return Object.isNumber(element.clientLeft) ? element.clientLeft : + getPixelValue(element, 'borderLeftWidth'); + }, + + 'border-right': function(element) { + return Object.isNumber(element.clientRight) ? element.clientRight : + getPixelValue(element, 'borderRightWidth'); + }, + + 'margin-top': function(element) { + return getPixelValue(element, 'marginTop'); + }, + + 'margin-bottom': function(element) { + return getPixelValue(element, 'marginBottom'); + }, + + 'margin-left': function(element) { + return getPixelValue(element, 'marginLeft'); + }, + + 'margin-right': function(element) { + return getPixelValue(element, 'marginRight'); + } + } + }); + + if ('getBoundingClientRect' in document.documentElement) { + Object.extend(Element.Layout.COMPUTATIONS, { + 'right': function(element) { + var parent = hasLayout(element.getOffsetParent()); + var rect = element.getBoundingClientRect(), + pRect = parent.getBoundingClientRect(); + + return (pRect.right - rect.right).round(); + }, + + 'bottom': function(element) { + var parent = hasLayout(element.getOffsetParent()); + var rect = element.getBoundingClientRect(), + pRect = parent.getBoundingClientRect(); + + return (pRect.bottom - rect.bottom).round(); } - return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : []; + }); + } + + Element.Offset = Class.create({ + initialize: function(left, top) { + this.left = left.round(); + this.top = top.round(); + + this[0] = this.left; + this[1] = this.top; }, - className: function(nodes, root, className, combinator) { - if (nodes && combinator) nodes = this[combinator](nodes); - return Selector.handlers.byClassName(nodes, root, className); + relativeTo: function(offset) { + return new Element.Offset( + this.left - offset.left, + this.top - offset.top + ); }, - byClassName: function(nodes, root, className) { - if (!nodes) nodes = Selector.handlers.descendant([root]); - var needle = ' ' + className + ' '; - for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) { - nodeClassName = node.className; - if (nodeClassName.length == 0) continue; - if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle)) - results.push(node); - } - return results; + inspect: function() { + return "#".interpolate(this); }, - attrPresence: function(nodes, root, attr, combinator) { - if (!nodes) nodes = root.getElementsByTagName("*"); - if (nodes && combinator) nodes = this[combinator](nodes); - var results = []; - for (var i = 0, node; node = nodes[i]; i++) - if (Element.hasAttribute(node, attr)) results.push(node); - return results; + toString: function() { + return "[#{left}, #{top}]".interpolate(this); }, - attr: function(nodes, root, attr, value, operator, combinator) { - if (!nodes) nodes = root.getElementsByTagName("*"); - if (nodes && combinator) nodes = this[combinator](nodes); - var handler = Selector.operators[operator], results = []; - for (var i = 0, node; node = nodes[i]; i++) { - var nodeValue = Element.readAttribute(node, attr); - if (nodeValue === null) continue; - if (handler(nodeValue, value)) results.push(node); + toArray: function() { + return [this.left, this.top]; + } + }); + + function getLayout(element, preCompute) { + return new Element.Layout(element, preCompute); + } + + function measure(element, property) { + return $(element).getLayout().get(property); + } + + function getDimensions(element) { + var layout = $(element).getLayout(); + return { + width: layout.get('width'), + height: layout.get('height') + }; + } + + function getOffsetParent(element) { + if (isDetached(element)) return $(document.body); + + var isInline = (Element.getStyle(element, 'display') === 'inline'); + if (!isInline && element.offsetParent) return $(element.offsetParent); + if (element === document.body) return $(element); + + while ((element = element.parentNode) && element !== document.body) { + if (Element.getStyle(element, 'position') !== 'static') { + return (element.nodeName === 'HTML') ? $(document.body) : $(element); } - return results; - }, + } + + return $(document.body); + } + + + function cumulativeOffset(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return new Element.Offset(valueL, valueT); + } + + function positionedOffset(element) { + var layout = element.getLayout(); + + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + if (isBody(element)) break; + var p = Element.getStyle(element, 'position'); + if (p !== 'static') break; + } + } while (element); + + valueL -= layout.get('margin-top'); + valueT -= layout.get('margin-left'); + + return new Element.Offset(valueL, valueT); + } + + function cumulativeScrollOffset(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return new Element.Offset(valueL, valueT); + } + + function viewportOffset(forElement) { + var valueT = 0, valueL = 0, docBody = document.body; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == docBody && + Element.getStyle(element, 'position') == 'absolute') break; + } while (element = element.offsetParent); + + element = forElement; + do { + if (element != docBody) { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } + } while (element = element.parentNode); + return new Element.Offset(valueL, valueT); + } + + function absolutize(element) { + element = $(element); + + if (Element.getStyle(element, 'position') === 'absolute') { + return element; + } + + var offsetParent = getOffsetParent(element); + var eOffset = element.viewportOffset(), + pOffset = offsetParent.viewportOffset(); + + var offset = eOffset.relativeTo(pOffset); + var layout = element.getLayout(); + + element.store('prototype_absolutize_original_styles', { + left: element.getStyle('left'), + top: element.getStyle('top'), + width: element.getStyle('width'), + height: element.getStyle('height') + }); + + element.setStyle({ + position: 'absolute', + top: offset.top + 'px', + left: offset.left + 'px', + width: layout.get('width') + 'px', + height: layout.get('height') + 'px' + }); + + return element; + } + + function relativize(element) { + element = $(element); + if (Element.getStyle(element, 'position') === 'relative') { + return element; + } + + var originalStyles = + element.retrieve('prototype_absolutize_original_styles'); + + if (originalStyles) element.setStyle(originalStyles); + return element; + } + + Element.addMethods({ + getLayout: getLayout, + measure: measure, + getDimensions: getDimensions, + getOffsetParent: getOffsetParent, + cumulativeOffset: cumulativeOffset, + positionedOffset: positionedOffset, + cumulativeScrollOffset: cumulativeScrollOffset, + viewportOffset: viewportOffset, + absolutize: absolutize, + relativize: relativize + }); + + function isBody(element) { + return element.nodeName.toUpperCase() === 'BODY'; + } + + function isDetached(element) { + return element !== document.body && + !Element.descendantOf(element, document.body); + } + + if ('getBoundingClientRect' in document.documentElement) { + Element.addMethods({ + viewportOffset: function(element) { + element = $(element); + if (isDetached(element)) return new Element.Offset(0, 0); + + var rect = element.getBoundingClientRect(), + docEl = document.documentElement; + return new Element.Offset(rect.left - docEl.clientLeft, + rect.top - docEl.clientTop); + }, + + positionedOffset: function(element) { + element = $(element); + var parent = element.getOffsetParent(); + if (isDetached(element)) return new Element.Offset(0, 0); + + if (element.offsetParent && + element.offsetParent.nodeName.toUpperCase() === 'HTML') { + return positionedOffset(element); + } + + var eOffset = element.viewportOffset(), + pOffset = isBody(parent) ? viewportOffset(parent) : + parent.viewportOffset(); + var retOffset = eOffset.relativeTo(pOffset); + + var layout = element.getLayout(); + var top = retOffset.top - layout.get('margin-top'); + var left = retOffset.left - layout.get('margin-left'); + + return new Element.Offset(left, top); + } + }); + } +})(); +window.$$ = function() { + var expression = $A(arguments).join(', '); + return Prototype.Selector.select(expression, document); +}; + +Prototype.Selector = (function() { + + function select() { + throw new Error('Method "Prototype.Selector.select" must be defined.'); + } + + function match() { + throw new Error('Method "Prototype.Selector.match" must be defined.'); + } + + function find(elements, expression, index) { + index = index || 0; + var match = Prototype.Selector.match, length = elements.length, matchIndex = 0, i; + + for (i = 0; i < length; i++) { + if (match(elements[i], expression) && index == matchIndex++) { + return Element.extend(elements[i]); + } + } + } + + function extendElements(elements) { + for (var i = 0, length = elements.length; i < length; i++) { + Element.extend(elements[i]); + } + return elements; + } + + + var K = Prototype.K; + + return { + select: select, + match: match, + find: find, + extendElements: (Element.extend === K) ? K : extendElements, + extendElement: Element.extend + }; +})(); +Prototype._original_property = window.Sizzle; +/*! + * Sizzle CSS Selector Engine - v1.0 + * Copyright 2009, The Dojo Foundation + * Released under the MIT, BSD, and GPL Licenses. + * More information: http://sizzlejs.com/ + */ +(function(){ + +var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, + done = 0, + toString = Object.prototype.toString, + hasDuplicate = false, + baseHasDuplicate = true; + +[0, 0].sort(function(){ + baseHasDuplicate = false; + return 0; +}); + +var Sizzle = function(selector, context, results, seed) { + results = results || []; + var origContext = context = context || document; + + if ( context.nodeType !== 1 && context.nodeType !== 9 ) { + return []; + } + + if ( !selector || typeof selector !== "string" ) { + return results; + } + + var parts = [], m, set, checkSet, check, mode, extra, prune = true, contextXML = isXML(context), + soFar = selector; + + while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) { + soFar = m[3]; + + parts.push( m[1] ); + + if ( m[2] ) { + extra = m[3]; + break; + } + } + + if ( parts.length > 1 && origPOS.exec( selector ) ) { + if ( parts.length === 2 && Expr.relative[ parts[0] ] ) { + set = posProcess( parts[0] + parts[1], context ); + } else { + set = Expr.relative[ parts[0] ] ? + [ context ] : + Sizzle( parts.shift(), context ); + + while ( parts.length ) { + selector = parts.shift(); + + if ( Expr.relative[ selector ] ) + selector += parts.shift(); + + set = posProcess( selector, set ); + } + } + } else { + if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML && + Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) { + var ret = Sizzle.find( parts.shift(), context, contextXML ); + context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0]; + } + + if ( context ) { + var ret = seed ? + { expr: parts.pop(), set: makeArray(seed) } : + Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML ); + set = ret.expr ? Sizzle.filter( ret.expr, ret.set ) : ret.set; + + if ( parts.length > 0 ) { + checkSet = makeArray(set); + } else { + prune = false; + } + + while ( parts.length ) { + var cur = parts.pop(), pop = cur; + + if ( !Expr.relative[ cur ] ) { + cur = ""; + } else { + pop = parts.pop(); + } + + if ( pop == null ) { + pop = context; + } + + Expr.relative[ cur ]( checkSet, pop, contextXML ); + } + } else { + checkSet = parts = []; + } + } + + if ( !checkSet ) { + checkSet = set; + } + + if ( !checkSet ) { + throw "Syntax error, unrecognized expression: " + (cur || selector); + } + + if ( toString.call(checkSet) === "[object Array]" ) { + if ( !prune ) { + results.push.apply( results, checkSet ); + } else if ( context && context.nodeType === 1 ) { + for ( var i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) { + results.push( set[i] ); + } + } + } else { + for ( var i = 0; checkSet[i] != null; i++ ) { + if ( checkSet[i] && checkSet[i].nodeType === 1 ) { + results.push( set[i] ); + } + } + } + } else { + makeArray( checkSet, results ); + } + + if ( extra ) { + Sizzle( extra, origContext, results, seed ); + Sizzle.uniqueSort( results ); + } + + return results; +}; + +Sizzle.uniqueSort = function(results){ + if ( sortOrder ) { + hasDuplicate = baseHasDuplicate; + results.sort(sortOrder); + + if ( hasDuplicate ) { + for ( var i = 1; i < results.length; i++ ) { + if ( results[i] === results[i-1] ) { + results.splice(i--, 1); + } + } + } + } + + return results; +}; + +Sizzle.matches = function(expr, set){ + return Sizzle(expr, null, null, set); +}; + +Sizzle.find = function(expr, context, isXML){ + var set, match; + + if ( !expr ) { + return []; + } + + for ( var i = 0, l = Expr.order.length; i < l; i++ ) { + var type = Expr.order[i], match; + + if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { + var left = match[1]; + match.splice(1,1); + + if ( left.substr( left.length - 1 ) !== "\\" ) { + match[1] = (match[1] || "").replace(/\\/g, ""); + set = Expr.find[ type ]( match, context, isXML ); + if ( set != null ) { + expr = expr.replace( Expr.match[ type ], "" ); + break; + } + } + } + } + + if ( !set ) { + set = context.getElementsByTagName("*"); + } + + return {set: set, expr: expr}; +}; + +Sizzle.filter = function(expr, set, inplace, not){ + var old = expr, result = [], curLoop = set, match, anyFound, + isXMLFilter = set && set[0] && isXML(set[0]); + + while ( expr && set.length ) { + for ( var type in Expr.filter ) { + if ( (match = Expr.match[ type ].exec( expr )) != null ) { + var filter = Expr.filter[ type ], found, item; + anyFound = false; + + if ( curLoop == result ) { + result = []; + } + + if ( Expr.preFilter[ type ] ) { + match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter ); + + if ( !match ) { + anyFound = found = true; + } else if ( match === true ) { + continue; + } + } + + if ( match ) { + for ( var i = 0; (item = curLoop[i]) != null; i++ ) { + if ( item ) { + found = filter( item, match, i, curLoop ); + var pass = not ^ !!found; + + if ( inplace && found != null ) { + if ( pass ) { + anyFound = true; + } else { + curLoop[i] = false; + } + } else if ( pass ) { + result.push( item ); + anyFound = true; + } + } + } + } + + if ( found !== undefined ) { + if ( !inplace ) { + curLoop = result; + } + + expr = expr.replace( Expr.match[ type ], "" ); + + if ( !anyFound ) { + return []; + } + + break; + } + } + } + + if ( expr == old ) { + if ( anyFound == null ) { + throw "Syntax error, unrecognized expression: " + expr; + } else { + break; + } + } + + old = expr; + } + + return curLoop; +}; + +var Expr = Sizzle.selectors = { + order: [ "ID", "NAME", "TAG" ], + match: { + ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/, + NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/, + ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/, + TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/, + CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/, + POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/, + PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/ + }, + leftMatch: {}, + attrMap: { + "class": "className", + "for": "htmlFor" + }, + attrHandle: { + href: function(elem){ + return elem.getAttribute("href"); + } + }, + relative: { + "+": function(checkSet, part, isXML){ + var isPartStr = typeof part === "string", + isTag = isPartStr && !/\W/.test(part), + isPartStrNotTag = isPartStr && !isTag; + + if ( isTag && !isXML ) { + part = part.toUpperCase(); + } + + for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) { + if ( (elem = checkSet[i]) ) { + while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {} + + checkSet[i] = isPartStrNotTag || elem && elem.nodeName === part ? + elem || false : + elem === part; + } + } + + if ( isPartStrNotTag ) { + Sizzle.filter( part, checkSet, true ); + } + }, + ">": function(checkSet, part, isXML){ + var isPartStr = typeof part === "string"; + + if ( isPartStr && !/\W/.test(part) ) { + part = isXML ? part : part.toUpperCase(); + + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + var parent = elem.parentNode; + checkSet[i] = parent.nodeName === part ? parent : false; + } + } + } else { + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + checkSet[i] = isPartStr ? + elem.parentNode : + elem.parentNode === part; + } + } + + if ( isPartStr ) { + Sizzle.filter( part, checkSet, true ); + } + } + }, + "": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck; + + if ( !/\W/.test(part) ) { + var nodeCheck = part = isXML ? part : part.toUpperCase(); + checkFn = dirNodeCheck; + } + + checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML); + }, + "~": function(checkSet, part, isXML){ + var doneName = done++, checkFn = dirCheck; + + if ( typeof part === "string" && !/\W/.test(part) ) { + var nodeCheck = part = isXML ? part : part.toUpperCase(); + checkFn = dirNodeCheck; + } + + checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML); + } + }, + find: { + ID: function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? [m] : []; + } + }, + NAME: function(match, context, isXML){ + if ( typeof context.getElementsByName !== "undefined" ) { + var ret = [], results = context.getElementsByName(match[1]); + + for ( var i = 0, l = results.length; i < l; i++ ) { + if ( results[i].getAttribute("name") === match[1] ) { + ret.push( results[i] ); + } + } + + return ret.length === 0 ? null : ret; + } + }, + TAG: function(match, context){ + return context.getElementsByTagName(match[1]); + } + }, + preFilter: { + CLASS: function(match, curLoop, inplace, result, not, isXML){ + match = " " + match[1].replace(/\\/g, "") + " "; + + if ( isXML ) { + return match; + } + + for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) { + if ( elem ) { + if ( not ^ (elem.className && (" " + elem.className + " ").indexOf(match) >= 0) ) { + if ( !inplace ) + result.push( elem ); + } else if ( inplace ) { + curLoop[i] = false; + } + } + } + + return false; + }, + ID: function(match){ + return match[1].replace(/\\/g, ""); + }, + TAG: function(match, curLoop){ + for ( var i = 0; curLoop[i] === false; i++ ){} + return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase(); + }, + CHILD: function(match){ + if ( match[1] == "nth" ) { + var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec( + match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" || + !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]); + + match[2] = (test[1] + (test[2] || 1)) - 0; + match[3] = test[3] - 0; + } + + match[0] = done++; + + return match; + }, + ATTR: function(match, curLoop, inplace, result, not, isXML){ + var name = match[1].replace(/\\/g, ""); + + if ( !isXML && Expr.attrMap[name] ) { + match[1] = Expr.attrMap[name]; + } + + if ( match[2] === "~=" ) { + match[4] = " " + match[4] + " "; + } + + return match; + }, + PSEUDO: function(match, curLoop, inplace, result, not){ + if ( match[1] === "not" ) { + if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) { + match[3] = Sizzle(match[3], null, null, curLoop); + } else { + var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not); + if ( !inplace ) { + result.push.apply( result, ret ); + } + return false; + } + } else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) { + return true; + } + + return match; + }, + POS: function(match){ + match.unshift( true ); + return match; + } + }, + filters: { + enabled: function(elem){ + return elem.disabled === false && elem.type !== "hidden"; + }, + disabled: function(elem){ + return elem.disabled === true; + }, + checked: function(elem){ + return elem.checked === true; + }, + selected: function(elem){ + elem.parentNode.selectedIndex; + return elem.selected === true; + }, + parent: function(elem){ + return !!elem.firstChild; + }, + empty: function(elem){ + return !elem.firstChild; + }, + has: function(elem, i, match){ + return !!Sizzle( match[3], elem ).length; + }, + header: function(elem){ + return /h\d/i.test( elem.nodeName ); + }, + text: function(elem){ + return "text" === elem.type; + }, + radio: function(elem){ + return "radio" === elem.type; + }, + checkbox: function(elem){ + return "checkbox" === elem.type; + }, + file: function(elem){ + return "file" === elem.type; + }, + password: function(elem){ + return "password" === elem.type; + }, + submit: function(elem){ + return "submit" === elem.type; + }, + image: function(elem){ + return "image" === elem.type; + }, + reset: function(elem){ + return "reset" === elem.type; + }, + button: function(elem){ + return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON"; + }, + input: function(elem){ + return /input|select|textarea|button/i.test(elem.nodeName); + } + }, + setFilters: { + first: function(elem, i){ + return i === 0; + }, + last: function(elem, i, match, array){ + return i === array.length - 1; + }, + even: function(elem, i){ + return i % 2 === 0; + }, + odd: function(elem, i){ + return i % 2 === 1; + }, + lt: function(elem, i, match){ + return i < match[3] - 0; + }, + gt: function(elem, i, match){ + return i > match[3] - 0; + }, + nth: function(elem, i, match){ + return match[3] - 0 == i; + }, + eq: function(elem, i, match){ + return match[3] - 0 == i; + } + }, + filter: { + PSEUDO: function(elem, match, i, array){ + var name = match[1], filter = Expr.filters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } else if ( name === "contains" ) { + return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0; + } else if ( name === "not" ) { + var not = match[3]; + + for ( var i = 0, l = not.length; i < l; i++ ) { + if ( not[i] === elem ) { + return false; + } + } + + return true; + } + }, + CHILD: function(elem, match){ + var type = match[1], node = elem; + switch (type) { + case 'only': + case 'first': + while ( (node = node.previousSibling) ) { + if ( node.nodeType === 1 ) return false; + } + if ( type == 'first') return true; + node = elem; + case 'last': + while ( (node = node.nextSibling) ) { + if ( node.nodeType === 1 ) return false; + } + return true; + case 'nth': + var first = match[2], last = match[3]; + + if ( first == 1 && last == 0 ) { + return true; + } + + var doneName = match[0], + parent = elem.parentNode; + + if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { + var count = 0; + for ( node = parent.firstChild; node; node = node.nextSibling ) { + if ( node.nodeType === 1 ) { + node.nodeIndex = ++count; + } + } + parent.sizcache = doneName; + } + + var diff = elem.nodeIndex - last; + if ( first == 0 ) { + return diff == 0; + } else { + return ( diff % first == 0 && diff / first >= 0 ); + } + } + }, + ID: function(elem, match){ + return elem.nodeType === 1 && elem.getAttribute("id") === match; + }, + TAG: function(elem, match){ + return (match === "*" && elem.nodeType === 1) || elem.nodeName === match; + }, + CLASS: function(elem, match){ + return (" " + (elem.className || elem.getAttribute("class")) + " ") + .indexOf( match ) > -1; + }, + ATTR: function(elem, match){ + var name = match[1], + result = Expr.attrHandle[ name ] ? + Expr.attrHandle[ name ]( elem ) : + elem[ name ] != null ? + elem[ name ] : + elem.getAttribute( name ), + value = result + "", + type = match[2], + check = match[4]; + + return result == null ? + type === "!=" : + type === "=" ? + value === check : + type === "*=" ? + value.indexOf(check) >= 0 : + type === "~=" ? + (" " + value + " ").indexOf(check) >= 0 : + !check ? + value && result !== false : + type === "!=" ? + value != check : + type === "^=" ? + value.indexOf(check) === 0 : + type === "$=" ? + value.substr(value.length - check.length) === check : + type === "|=" ? + value === check || value.substr(0, check.length + 1) === check + "-" : + false; + }, + POS: function(elem, match, i, array){ + var name = match[2], filter = Expr.setFilters[ name ]; + + if ( filter ) { + return filter( elem, i, match, array ); + } + } + } +}; + +var origPOS = Expr.match.POS; + +for ( var type in Expr.match ) { + Expr.match[ type ] = new RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source ); + Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source ); +} + +var makeArray = function(array, results) { + array = Array.prototype.slice.call( array, 0 ); + + if ( results ) { + results.push.apply( results, array ); + return results; + } + + return array; +}; + +try { + Array.prototype.slice.call( document.documentElement.childNodes, 0 ); + +} catch(e){ + makeArray = function(array, results) { + var ret = results || []; + + if ( toString.call(array) === "[object Array]" ) { + Array.prototype.push.apply( ret, array ); + } else { + if ( typeof array.length === "number" ) { + for ( var i = 0, l = array.length; i < l; i++ ) { + ret.push( array[i] ); + } + } else { + for ( var i = 0; array[i]; i++ ) { + ret.push( array[i] ); + } + } + } + + return ret; + }; +} + +var sortOrder; + +if ( document.documentElement.compareDocumentPosition ) { + sortOrder = function( a, b ) { + if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) { + if ( a == b ) { + hasDuplicate = true; + } + return 0; + } + + var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( "sourceIndex" in document.documentElement ) { + sortOrder = function( a, b ) { + if ( !a.sourceIndex || !b.sourceIndex ) { + if ( a == b ) { + hasDuplicate = true; + } + return 0; + } + + var ret = a.sourceIndex - b.sourceIndex; + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} else if ( document.createRange ) { + sortOrder = function( a, b ) { + if ( !a.ownerDocument || !b.ownerDocument ) { + if ( a == b ) { + hasDuplicate = true; + } + return 0; + } + + var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange(); + aRange.setStart(a, 0); + aRange.setEnd(a, 0); + bRange.setStart(b, 0); + bRange.setEnd(b, 0); + var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange); + if ( ret === 0 ) { + hasDuplicate = true; + } + return ret; + }; +} + +(function(){ + var form = document.createElement("div"), + id = "script" + (new Date).getTime(); + form.innerHTML = ""; + + var root = document.documentElement; + root.insertBefore( form, root.firstChild ); + + if ( !!document.getElementById( id ) ) { + Expr.find.ID = function(match, context, isXML){ + if ( typeof context.getElementById !== "undefined" && !isXML ) { + var m = context.getElementById(match[1]); + return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : []; + } + }; + + Expr.filter.ID = function(elem, match){ + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + return elem.nodeType === 1 && node && node.nodeValue === match; + }; + } + + root.removeChild( form ); + root = form = null; // release memory in IE +})(); + +(function(){ + + var div = document.createElement("div"); + div.appendChild( document.createComment("") ); + + if ( div.getElementsByTagName("*").length > 0 ) { + Expr.find.TAG = function(match, context){ + var results = context.getElementsByTagName(match[1]); + + if ( match[1] === "*" ) { + var tmp = []; + + for ( var i = 0; results[i]; i++ ) { + if ( results[i].nodeType === 1 ) { + tmp.push( results[i] ); + } + } + + results = tmp; + } + + return results; + }; + } + + div.innerHTML = ""; + if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" && + div.firstChild.getAttribute("href") !== "#" ) { + Expr.attrHandle.href = function(elem){ + return elem.getAttribute("href", 2); + }; + } + + div = null; // release memory in IE +})(); + +if ( document.querySelectorAll ) (function(){ + var oldSizzle = Sizzle, div = document.createElement("div"); + div.innerHTML = "

"; + + if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) { + return; + } + + Sizzle = function(query, context, extra, seed){ + context = context || document; + + if ( !seed && context.nodeType === 9 && !isXML(context) ) { + try { + return makeArray( context.querySelectorAll(query), extra ); + } catch(e){} + } + + return oldSizzle(query, context, extra, seed); + }; + + for ( var prop in oldSizzle ) { + Sizzle[ prop ] = oldSizzle[ prop ]; + } + + div = null; // release memory in IE +})(); + +if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) (function(){ + var div = document.createElement("div"); + div.innerHTML = "
"; + + if ( div.getElementsByClassName("e").length === 0 ) + return; + + div.lastChild.className = "e"; + + if ( div.getElementsByClassName("e").length === 1 ) + return; + + Expr.order.splice(1, 0, "CLASS"); + Expr.find.CLASS = function(match, context, isXML) { + if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) { + return context.getElementsByClassName(match[1]); + } + }; + + div = null; // release memory in IE +})(); + +function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + var sibDir = dir == "previousSibling" && !isXML; + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + if ( sibDir && elem.nodeType === 1 ){ + elem.sizcache = doneName; + elem.sizset = i; + } + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 && !isXML ){ + elem.sizcache = doneName; + elem.sizset = i; + } + + if ( elem.nodeName === cur ) { + match = elem; + break; + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} - pseudo: function(nodes, name, value, root, combinator) { - if (nodes && combinator) nodes = this[combinator](nodes); - if (!nodes) nodes = root.getElementsByTagName("*"); - return Selector.pseudos[name](nodes, value, root); - } - }, +function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) { + var sibDir = dir == "previousSibling" && !isXML; + for ( var i = 0, l = checkSet.length; i < l; i++ ) { + var elem = checkSet[i]; + if ( elem ) { + if ( sibDir && elem.nodeType === 1 ) { + elem.sizcache = doneName; + elem.sizset = i; + } + elem = elem[dir]; + var match = false; + + while ( elem ) { + if ( elem.sizcache === doneName ) { + match = checkSet[elem.sizset]; + break; + } + + if ( elem.nodeType === 1 ) { + if ( !isXML ) { + elem.sizcache = doneName; + elem.sizset = i; + } + if ( typeof cur !== "string" ) { + if ( elem === cur ) { + match = true; + break; + } + + } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) { + match = elem; + break; + } + } + + elem = elem[dir]; + } + + checkSet[i] = match; + } + } +} - pseudos: { - 'first-child': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - if (Selector.handlers.previousElementSibling(node)) continue; - results.push(node); - } - return results; - }, - 'last-child': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - if (Selector.handlers.nextElementSibling(node)) continue; - results.push(node); - } - return results; - }, - 'only-child': function(nodes, value, root) { - var h = Selector.handlers; - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!h.previousElementSibling(node) && !h.nextElementSibling(node)) - results.push(node); - return results; - }, - 'nth-child': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root); - }, - 'nth-last-child': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, true); - }, - 'nth-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, false, true); - }, - 'nth-last-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, formula, root, true, true); - }, - 'first-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, "1", root, false, true); - }, - 'last-of-type': function(nodes, formula, root) { - return Selector.pseudos.nth(nodes, "1", root, true, true); - }, - 'only-of-type': function(nodes, formula, root) { - var p = Selector.pseudos; - return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root); - }, +var contains = document.compareDocumentPosition ? function(a, b){ + return a.compareDocumentPosition(b) & 16; +} : function(a, b){ + return a !== b && (a.contains ? a.contains(b) : true); +}; - // handles the an+b logic - getIndices: function(a, b, total) { - if (a == 0) return b > 0 ? [b] : []; - return $R(1, total).inject([], function(memo, i) { - if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i); - return memo; - }); - }, +var isXML = function(elem){ + return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" || + !!elem.ownerDocument && elem.ownerDocument.documentElement.nodeName !== "HTML"; +}; - // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type - nth: function(nodes, formula, root, reverse, ofType) { - if (nodes.length == 0) return []; - if (formula == 'even') formula = '2n+0'; - if (formula == 'odd') formula = '2n+1'; - var h = Selector.handlers, results = [], indexed = [], m; - h.mark(nodes); - for (var i = 0, node; node = nodes[i]; i++) { - if (!node.parentNode._countedByPrototype) { - h.index(node.parentNode, reverse, ofType); - indexed.push(node.parentNode); - } - } - if (formula.match(/^\d+$/)) { // just a number - formula = Number(formula); - for (var i = 0, node; node = nodes[i]; i++) - if (node.nodeIndex == formula) results.push(node); - } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b - if (m[1] == "-") m[1] = -1; - var a = m[1] ? Number(m[1]) : 1; - var b = m[2] ? Number(m[2]) : 0; - var indices = Selector.pseudos.getIndices(a, b, nodes.length); - for (var i = 0, node, l = indices.length; node = nodes[i]; i++) { - for (var j = 0; j < l; j++) - if (node.nodeIndex == indices[j]) results.push(node); - } - } - h.unmark(nodes); - h.unmark(indexed); - return results; - }, +var posProcess = function(selector, context){ + var tmpSet = [], later = "", match, + root = context.nodeType ? [context] : context; - 'empty': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) { - // IE treats comments as element nodes - if (node.tagName == '!' || node.firstChild) continue; - results.push(node); - } - return results; - }, + while ( (match = Expr.match.PSEUDO.exec( selector )) ) { + later += match[0]; + selector = selector.replace( Expr.match.PSEUDO, "" ); + } - 'not': function(nodes, selector, root) { - var h = Selector.handlers, selectorType, m; - var exclusions = new Selector(selector).findElements(root); - h.mark(exclusions); - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!node._countedByPrototype) results.push(node); - h.unmark(exclusions); - return results; - }, + selector = Expr.relative[selector] ? selector + "*" : selector; - 'enabled': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (!node.disabled && (!node.type || node.type !== 'hidden')) - results.push(node); - return results; - }, + for ( var i = 0, l = root.length; i < l; i++ ) { + Sizzle( selector, root[i], tmpSet ); + } - 'disabled': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (node.disabled) results.push(node); - return results; - }, + return Sizzle.filter( later, tmpSet ); +}; - 'checked': function(nodes, value, root) { - for (var i = 0, results = [], node; node = nodes[i]; i++) - if (node.checked) results.push(node); - return results; - } - }, - operators: { - '=': function(nv, v) { return nv == v; }, - '!=': function(nv, v) { return nv != v; }, - '^=': function(nv, v) { return nv == v || nv && nv.startsWith(v); }, - '$=': function(nv, v) { return nv == v || nv && nv.endsWith(v); }, - '*=': function(nv, v) { return nv == v || nv && nv.include(v); }, - '$=': function(nv, v) { return nv.endsWith(v); }, - '*=': function(nv, v) { return nv.include(v); }, - '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); }, - '|=': function(nv, v) { return ('-' + (nv || "").toUpperCase() + - '-').include('-' + (v || "").toUpperCase() + '-'); } - }, +window.Sizzle = Sizzle; - split: function(expression) { - var expressions = []; - expression.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) { - expressions.push(m[1].strip()); - }); - return expressions; - }, +})(); - matchElements: function(elements, expression) { - var matches = $$(expression), h = Selector.handlers; - h.mark(matches); - for (var i = 0, results = [], element; element = elements[i]; i++) - if (element._countedByPrototype) results.push(element); - h.unmark(matches); - return results; - }, +;(function(engine) { + var extendElements = Prototype.Selector.extendElements; - findElement: function(elements, expression, index) { - if (Object.isNumber(expression)) { - index = expression; expression = false; - } - return Selector.matchElements(elements, expression || '*')[index || 0]; - }, + function select(selector, scope) { + return extendElements(engine(selector, scope || document)); + } - findChildElements: function(element, expressions) { - expressions = Selector.split(expressions.join(',')); - var results = [], h = Selector.handlers; - for (var i = 0, l = expressions.length, selector; i < l; i++) { - selector = new Selector(expressions[i].strip()); - h.concat(results, selector.findElements(element)); - } - return (l > 1) ? h.unique(results) : results; + function match(element, selector) { + return engine.matches(selector, [element]).length == 1; } -}); -if (Prototype.Browser.IE) { - Object.extend(Selector.handlers, { - // IE returns comment nodes on getElementsByTagName("*"). - // Filter them out. - concat: function(a, b) { - for (var i = 0, node; node = b[i]; i++) - if (node.tagName !== "!") a.push(node); - return a; - }, + Prototype.Selector.engine = engine; + Prototype.Selector.select = select; + Prototype.Selector.match = match; +})(Sizzle); - // IE improperly serializes _countedByPrototype in (inner|outer)HTML. - unmark: function(nodes) { - for (var i = 0, node; node = nodes[i]; i++) - node.removeAttribute('_countedByPrototype'); - return nodes; - } - }); -} +window.Sizzle = Prototype._original_property; +delete Prototype._original_property; -function $$() { - return Selector.findChildElements(document, $A(arguments)); -} var Form = { reset: function(form) { - $(form).reset(); + form = $(form); + form.reset(); return form; }, @@ -3460,7 +4970,6 @@ var Form = { if (value != null && element.type != 'file' && (element.type != 'submit' || (!submitted && submit !== false && (!submit || key == submit) && (submitted = true)))) { if (key in result) { - // a key is already present; construct an array of values if (!Object.isArray(result[key])) result[key] = [result[key]]; result[key].push(value); } @@ -3480,13 +4989,18 @@ Form.Methods = { }, getElements: function(form) { - return $A($(form).getElementsByTagName('*')).inject([], - function(elements, child) { - if (Form.Element.Serializers[child.tagName.toLowerCase()]) - elements.push(Element.extend(child)); - return elements; - } - ); + var elements = $(form).getElementsByTagName('*'), + element, + arr = [ ], + serializers = Form.Element.Serializers; + for (var i = 0; element = elements[i]; i++) { + arr.push(element); + } + return arr.inject([], function(elements, child) { + if (serializers[child.tagName.toLowerCase()]) + elements.push(Element.extend(child)); + return elements; + }) }, getInputs: function(form, typeName, name) { @@ -3526,7 +5040,7 @@ Form.Methods = { }).sortBy(function(element) { return element.tabIndex }).first(); return firstByIndex ? firstByIndex : elements.find(function(element) { - return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); + return /^(?:input|select|textarea)$/i.test(element.tagName); }); }, @@ -3557,6 +5071,7 @@ Form.Methods = { /*--------------------------------------------------------------------------*/ + Form.Element = { focus: function(element) { $(element).focus(); @@ -3570,6 +5085,7 @@ Form.Element = { }; Form.Element.Methods = { + serialize: function(element) { element = $(element); if (!element.disabled && element.name) { @@ -3610,7 +5126,7 @@ Form.Element.Methods = { try { element.focus(); if (element.select && (element.tagName.toLowerCase() != 'input' || - !['button', 'reset', 'submit'].include(element.type))) + !(/^(?:button|reset|submit)$/i.test(element.type)))) element.select(); } catch (e) { } return element; @@ -3632,6 +5148,7 @@ Form.Element.Methods = { /*--------------------------------------------------------------------------*/ var Field = Form.Element; + var $F = Form.Element.Methods.getValue; /*--------------------------------------------------------------------------*/ @@ -3694,13 +5211,13 @@ Form.Element.Serializers = { }, optionValue: function(opt) { - // extend element because hasAttribute may not be native return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text; } }; /*--------------------------------------------------------------------------*/ + Abstract.TimedObserver = Class.create(PeriodicalExecuter, { initialize: function($super, element, frequency, callback) { $super(callback, frequency); @@ -3782,354 +5299,475 @@ Form.EventObserver = Class.create(Abstract.EventObserver, { return Form.serialize(this.element); } }); -if (!window.Event) var Event = { }; - -Object.extend(Event, { - KEY_BACKSPACE: 8, - KEY_TAB: 9, - KEY_RETURN: 13, - KEY_ESC: 27, - KEY_LEFT: 37, - KEY_UP: 38, - KEY_RIGHT: 39, - KEY_DOWN: 40, - KEY_DELETE: 46, - KEY_HOME: 36, - KEY_END: 35, - KEY_PAGEUP: 33, - KEY_PAGEDOWN: 34, - KEY_INSERT: 45, - - cache: { }, - - relatedTarget: function(event) { - var element; - switch(event.type) { - case 'mouseover': element = event.fromElement; break; - case 'mouseout': element = event.toElement; break; - default: return null; - } - return Element.extend(element); - } -}); +(function() { + + var Event = { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + KEY_HOME: 36, + KEY_END: 35, + KEY_PAGEUP: 33, + KEY_PAGEDOWN: 34, + KEY_INSERT: 45, + + cache: {} + }; -Event.Methods = (function() { - var isButton; + var docEl = document.documentElement; + var MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED = 'onmouseenter' in docEl + && 'onmouseleave' in docEl; + var _isButton; if (Prototype.Browser.IE) { var buttonMap = { 0: 1, 1: 4, 2: 2 }; - isButton = function(event, code) { - return event.button == buttonMap[code]; + _isButton = function(event, code) { + return event.button === buttonMap[code]; }; - } else if (Prototype.Browser.WebKit) { - isButton = function(event, code) { + _isButton = function(event, code) { switch (code) { case 0: return event.which == 1 && !event.metaKey; case 1: return event.which == 1 && event.metaKey; default: return false; } }; - } else { - isButton = function(event, code) { + _isButton = function(event, code) { return event.which ? (event.which === code + 1) : (event.button === code); }; } - return { - isLeftClick: function(event) { return isButton(event, 0) }, - isMiddleClick: function(event) { return isButton(event, 1) }, - isRightClick: function(event) { return isButton(event, 2) }, - - element: function(event) { - event = Event.extend(event); - - var node = event.target, - type = event.type, - currentTarget = event.currentTarget; - - if (currentTarget && currentTarget.tagName) { - // Firefox screws up the "click" event when moving between radio buttons - // via arrow keys. It also screws up the "load" and "error" events on images, - // reporting the document as the target instead of the original image. - if (type === 'load' || type === 'error' || - (type === 'click' && currentTarget.tagName.toLowerCase() === 'input' - && currentTarget.type === 'radio')) - node = currentTarget; - } - if (node.nodeType == Node.TEXT_NODE) node = node.parentNode; - return Element.extend(node); - }, + function isLeftClick(event) { return _isButton(event, 0) } - findElement: function(event, expression) { - var element = Event.element(event); - if (!expression) return element; - var elements = [element].concat(element.ancestors()); - return Selector.findElement(elements, expression, 0); - }, + function isMiddleClick(event) { return _isButton(event, 1) } - pointer: function(event) { - var docElement = document.documentElement, - body = document.body || { scrollLeft: 0, scrollTop: 0 }; - return { - x: event.pageX || (event.clientX + - (docElement.scrollLeft || body.scrollLeft) - - (docElement.clientLeft || 0)), - y: event.pageY || (event.clientY + - (docElement.scrollTop || body.scrollTop) - - (docElement.clientTop || 0)) - }; - }, + function isRightClick(event) { return _isButton(event, 2) } + + function element(event) { + event = Event.extend(event); + + var node = event.target, type = event.type, + currentTarget = event.currentTarget; + + if (currentTarget && currentTarget.tagName) { + if (type === 'load' || type === 'error' || + (type === 'click' && currentTarget.tagName.toLowerCase() === 'input' + && currentTarget.type === 'radio')) + node = currentTarget; + } + + if (node.nodeType == Node.TEXT_NODE) + node = node.parentNode; - pointerX: function(event) { return Event.pointer(event).x }, - pointerY: function(event) { return Event.pointer(event).y }, + return Element.extend(node); + } - stop: function(event) { - Event.extend(event); - event.preventDefault(); - event.stopPropagation(); - event.stopped = true; + function findElement(event, expression) { + var element = Event.element(event); + if (!expression) return element; + while (element) { + if (Object.isElement(element) && Prototype.Selector.match(element, expression)) { + return Element.extend(element); + } + element = element.parentNode; } + } + + function pointer(event) { + return { x: pointerX(event), y: pointerY(event) }; + } + + function pointerX(event) { + var docElement = document.documentElement, + body = document.body || { scrollLeft: 0 }; + + return event.pageX || (event.clientX + + (docElement.scrollLeft || body.scrollLeft) - + (docElement.clientLeft || 0)); + } + + function pointerY(event) { + var docElement = document.documentElement, + body = document.body || { scrollTop: 0 }; + + return event.pageY || (event.clientY + + (docElement.scrollTop || body.scrollTop) - + (docElement.clientTop || 0)); + } + + + function stop(event) { + Event.extend(event); + event.preventDefault(); + event.stopPropagation(); + + event.stopped = true; + } + + Event.Methods = { + isLeftClick: isLeftClick, + isMiddleClick: isMiddleClick, + isRightClick: isRightClick, + + element: element, + findElement: findElement, + + pointer: pointer, + pointerX: pointerX, + pointerY: pointerY, + + stop: stop }; -})(); -Event.extend = (function() { + var methods = Object.keys(Event.Methods).inject({ }, function(m, name) { m[name] = Event.Methods[name].methodize(); return m; }); if (Prototype.Browser.IE) { + function _relatedTarget(event) { + var element; + switch (event.type) { + case 'mouseover': element = event.fromElement; break; + case 'mouseout': element = event.toElement; break; + default: return null; + } + return Element.extend(element); + } + Object.extend(methods, { stopPropagation: function() { this.cancelBubble = true }, preventDefault: function() { this.returnValue = false }, - inspect: function() { return "[object Event]" } + inspect: function() { return '[object Event]' } }); - return function(event) { + Event.extend = function(event, element) { if (!event) return false; if (event._extendedByPrototype) return event; event._extendedByPrototype = Prototype.emptyFunction; var pointer = Event.pointer(event); + Object.extend(event, { - target: event.srcElement, - relatedTarget: Event.relatedTarget(event), + target: event.srcElement || element, + relatedTarget: _relatedTarget(event), pageX: pointer.x, pageY: pointer.y }); + return Object.extend(event, methods); }; - } else { - Event.prototype = Event.prototype || document.createEvent("HTMLEvents")['__proto__']; + Event.prototype = window.Event.prototype || document.createEvent('HTMLEvents').__proto__; Object.extend(Event.prototype, methods); - return Prototype.K; + Event.extend = Prototype.K; } -})(); - -Object.extend(Event, (function() { - var cache = Event.cache; - function getEventID(element) { - if (element._prototypeEventID) return element._prototypeEventID[0]; - arguments.callee.id = arguments.callee.id || 1; - return element._prototypeEventID = [++arguments.callee.id]; - } + function _createResponder(element, eventName, handler) { + var registry = Element.retrieve(element, 'prototype_event_registry'); - function getDOMEventName(eventName) { - if (eventName && eventName.include(':')) return "dataavailable"; - return eventName; - } + if (Object.isUndefined(registry)) { + CACHE.push(element); + registry = Element.retrieve(element, 'prototype_event_registry', $H()); + } - function getCacheForID(id) { - return cache[id] = cache[id] || { }; - } + var respondersForEvent = registry.get(eventName); + if (Object.isUndefined(respondersForEvent)) { + respondersForEvent = []; + registry.set(eventName, respondersForEvent); + } - function getWrappersForEventName(id, eventName) { - var c = getCacheForID(id); - return c[eventName] = c[eventName] || []; - } + if (respondersForEvent.pluck('handler').include(handler)) return false; - function createWrapper(element, eventName, handler) { - var id = getEventID(element); - var c = getWrappersForEventName(id, eventName); - if (c.pluck("handler").include(handler)) return false; + var responder; + if (eventName.include(":")) { + responder = function(event) { + if (Object.isUndefined(event.eventName)) + return false; - var wrapper = function(event) { - if (!Event || !Event.extend || - (event.eventName && event.eventName != eventName)) + if (event.eventName !== eventName) return false; - Event.extend(event); - handler.call(element, event); - }; + Event.extend(event, element); + handler.call(element, event); + }; + } else { + if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED && + (eventName === "mouseenter" || eventName === "mouseleave")) { + if (eventName === "mouseenter" || eventName === "mouseleave") { + responder = function(event) { + Event.extend(event, element); + + var parent = event.relatedTarget; + while (parent && parent !== element) { + try { parent = parent.parentNode; } + catch(e) { parent = element; } + } - wrapper.handler = handler; - c.push(wrapper); - return wrapper; - } + if (parent === element) return; - function findWrapper(id, eventName, handler) { - var c = getWrappersForEventName(id, eventName); - return c.find(function(wrapper) { return wrapper.handler == handler }); - } + handler.call(element, event); + }; + } + } else { + responder = function(event) { + Event.extend(event, element); + handler.call(element, event); + }; + } + } - function destroyWrapper(id, eventName, handler) { - var c = getCacheForID(id); - if (!c[eventName]) return false; - c[eventName] = c[eventName].without(findWrapper(id, eventName, handler)); + responder.handler = handler; + respondersForEvent.push(responder); + return responder; } - function destroyCache() { - for (var id in cache) - for (var eventName in cache[id]) - cache[id][eventName] = null; + function _destroyCache() { + for (var i = 0, length = CACHE.length; i < length; i++) { + Event.stopObserving(CACHE[i]); + CACHE[i] = null; + } } + var CACHE = []; - // Internet Explorer needs to remove event handlers on page unload - // in order to avoid memory leaks. - if (window.attachEvent) { - window.attachEvent("onunload", destroyCache); - } + if (Prototype.Browser.IE) + window.attachEvent('onunload', _destroyCache); - // Safari has a dummy event handler on page unload so that it won't - // use its bfcache. Safari <= 3.1 has an issue with restoring the "document" - // object when page is returned to via the back button using its bfcache. - if (Prototype.Browser.WebKit) { + if (Prototype.Browser.WebKit) window.addEventListener('unload', Prototype.emptyFunction, false); + + + var _getDOMEventName = Prototype.K, + translations = { mouseenter: "mouseover", mouseleave: "mouseout" }; + + if (!MOUSEENTER_MOUSELEAVE_EVENTS_SUPPORTED) { + _getDOMEventName = function(eventName) { + return (translations[eventName] || eventName); + }; } - return { - observe: function(element, eventName, handler) { - element = $(element); - var name = getDOMEventName(eventName); + function observe(element, eventName, handler) { + element = $(element); - var wrapper = createWrapper(element, eventName, handler); - if (!wrapper) return element; + var responder = _createResponder(element, eventName, handler); - if (element.addEventListener) { - element.addEventListener(name, wrapper, false); - } else { - element.attachEvent("on" + name, wrapper); + if (!responder) return element; + + if (eventName.include(':')) { + if (element.addEventListener) + element.addEventListener("dataavailable", responder, false); + else { + element.attachEvent("ondataavailable", responder); + element.attachEvent("onfilterchange", responder); } + } else { + var actualEventName = _getDOMEventName(eventName); + + if (element.addEventListener) + element.addEventListener(actualEventName, responder, false); + else + element.attachEvent("on" + actualEventName, responder); + } + + return element; + } + + function stopObserving(element, eventName, handler) { + element = $(element); + var registry = Element.retrieve(element, 'prototype_event_registry'); + if (!registry) return element; + + if (!eventName) { + registry.each( function(pair) { + var eventName = pair.key; + stopObserving(element, eventName); + }); return element; - }, + } - stopObserving: function(element, eventName, handler) { - element = $(element); - var id = getEventID(element), name = getDOMEventName(eventName); + var responders = registry.get(eventName); + if (!responders) return element; - if (!handler && eventName) { - getWrappersForEventName(id, eventName).each(function(wrapper) { - element.stopObserving(eventName, wrapper.handler); - }); - return element; + if (!handler) { + responders.each(function(r) { + stopObserving(element, eventName, r.handler); + }); + return element; + } - } else if (!eventName) { - Object.keys(getCacheForID(id)).each(function(eventName) { - element.stopObserving(eventName); - }); - return element; + var responder = responders.find( function(r) { return r.handler === handler; }); + if (!responder) return element; + + if (eventName.include(':')) { + if (element.removeEventListener) + element.removeEventListener("dataavailable", responder, false); + else { + element.detachEvent("ondataavailable", responder); + element.detachEvent("onfilterchange", responder); } + } else { + var actualEventName = _getDOMEventName(eventName); + if (element.removeEventListener) + element.removeEventListener(actualEventName, responder, false); + else + element.detachEvent('on' + actualEventName, responder); + } - var wrapper = findWrapper(id, eventName, handler); - if (!wrapper) return element; + registry.set(eventName, responders.without(responder)); - if (element.removeEventListener) { - element.removeEventListener(name, wrapper, false); - } else { - element.detachEvent("on" + name, wrapper); - } + return element; + } - destroyWrapper(id, eventName, handler); + function fire(element, eventName, memo, bubble) { + element = $(element); - return element; - }, + if (Object.isUndefined(bubble)) + bubble = true; - fire: function(element, eventName, memo) { - element = $(element); - if (element == document && document.createEvent && !element.dispatchEvent) - element = document.documentElement; + if (element == document && document.createEvent && !element.dispatchEvent) + element = document.documentElement; - var event; - if (document.createEvent) { - event = document.createEvent("HTMLEvents"); - event.initEvent("dataavailable", true, true); - } else { - event = document.createEventObject(); - event.eventType = "ondataavailable"; - } + var event; + if (document.createEvent) { + event = document.createEvent('HTMLEvents'); + event.initEvent('dataavailable', true, true); + } else { + event = document.createEventObject(); + event.eventType = bubble ? 'ondataavailable' : 'onfilterchange'; + } - event.eventName = eventName; - event.memo = memo || { }; + event.eventName = eventName; + event.memo = memo || { }; - if (document.createEvent) { - element.dispatchEvent(event); - } else { - element.fireEvent(event.eventType, event); - } + if (document.createEvent) + element.dispatchEvent(event); + else + element.fireEvent(event.eventType, event); + + return Event.extend(event); + } + + Event.Handler = Class.create({ + initialize: function(element, eventName, selector, callback) { + this.element = $(element); + this.eventName = eventName; + this.selector = selector; + this.callback = callback; + this.handler = this.handleEvent.bind(this); + }, + + start: function() { + Event.observe(this.element, this.eventName, this.handler); + return this; + }, + + stop: function() { + Event.stopObserving(this.element, this.eventName, this.handler); + return this; + }, - return Event.extend(event); + handleEvent: function(event) { + var element = event.findElement(this.selector); + if (element) this.callback.call(this.element, event, element); } - }; -})()); + }); -Object.extend(Event, Event.Methods); + function on(element, eventName, selector, callback) { + element = $(element); + if (Object.isFunction(selector) && Object.isUndefined(callback)) { + callback = selector, selector = null; + } -Element.addMethods({ - fire: Event.fire, - observe: Event.observe, - stopObserving: Event.stopObserving -}); + return new Event.Handler(element, eventName, selector, callback).start(); + } -Object.extend(document, { - fire: Element.Methods.fire.methodize(), - observe: Element.Methods.observe.methodize(), - stopObserving: Element.Methods.stopObserving.methodize(), - loaded: false -}); + Object.extend(Event, Event.Methods); + + Object.extend(Event, { + fire: fire, + observe: observe, + stopObserving: stopObserving, + on: on + }); + + Element.addMethods({ + fire: fire, + + observe: observe, + + stopObserving: stopObserving, + + on: on + }); + + Object.extend(document, { + fire: fire.methodize(), + + observe: observe.methodize(), + + stopObserving: stopObserving.methodize(), + + on: on.methodize(), + + loaded: false + }); + + if (window.Event) Object.extend(window.Event, Event); + else window.Event = Event; +})(); (function() { /* Support for the DOMContentLoaded event is based on work by Dan Webb, - Matthias Miller, Dean Edwards and John Resig. */ + Matthias Miller, Dean Edwards, John Resig, and Diego Perini. */ var timer; function fireContentLoadedEvent() { if (document.loaded) return; - if (timer) window.clearInterval(timer); - document.fire("dom:loaded"); + if (timer) window.clearTimeout(timer); document.loaded = true; + document.fire('dom:loaded'); } - if (document.addEventListener) { - if (Prototype.Browser.WebKit) { - timer = window.setInterval(function() { - if (/loaded|complete/.test(document.readyState)) - fireContentLoadedEvent(); - }, 0); - - Event.observe(window, "load", fireContentLoadedEvent); + function checkReadyState() { + if (document.readyState === 'complete') { + document.stopObserving('readystatechange', checkReadyState); + fireContentLoadedEvent(); + } + } - } else { - document.addEventListener("DOMContentLoaded", - fireContentLoadedEvent, false); + function pollDoScroll() { + try { document.documentElement.doScroll('left'); } + catch(e) { + timer = pollDoScroll.defer(); + return; } + fireContentLoadedEvent(); + } + if (document.addEventListener) { + document.addEventListener('DOMContentLoaded', fireContentLoadedEvent, false); } else { - document.write(" diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_create_form.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_create_form.html.erb deleted file mode 100644 index 0c89d98..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_create_form.html.erb +++ /dev/null @@ -1,52 +0,0 @@ -<% url_options = params_for(:action => :create) -%> -<% xhr ||= request.xhr? -%> -<%= -if xhr - if active_scaffold_config.create.multipart? # file_uploads - form_remote_upload_tag url_options.merge({:iframe => true}), - :onsubmit => onsubmit, - :id => element_form_id(:action => :create), - :loading => "$('#{loading_indicator_id(:action => :create, :id => params[:id])}').style.visibility = 'visible';", - :class => 'create' - else - form_remote_tag :url => url_options, - :after => "$('#{loading_indicator_id(:action => :create, :id => params[:id])}').style.visibility = 'visible'; Form.disable('#{element_form_id(:action => :create)}');", - :complete => "$('#{loading_indicator_id(:action => :create, :id => params[:id])}').style.visibility = 'hidden'; Form.enable('#{element_form_id(:action => :create)}');", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :html => { - :href => url_for(url_options), - :onsubmit => onsubmit, - :id => element_form_id(:action => :create), - :class => 'create' - } - end -else - form_tag url_options, - :onsubmit => onsubmit, - :id => element_form_id(:action => :create), - :multipart => active_scaffold_config.create.multipart?, - :class => 'create' -end -%> - -

<%= active_scaffold_config.create.label(active_scaffold_config.sti_create_links ? @record.class.human_name(:count => 1) : nil) -%>

- -
-<% if request.xhr? -%> - <%= error_messages_for :record, :object_name => @record.class.human_name.downcase %> -<% else -%> - <%= render :partial => 'form_messages' %> -<% end -%> -
- - <%= render :partial => 'form', :locals => { :columns => active_scaffold_config.create.columns } %> - - - - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_create_form_on_list.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_create_form_on_list.html.erb deleted file mode 100644 index 2d15a9d..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_create_form_on_list.html.erb +++ /dev/null @@ -1,38 +0,0 @@ -<% url_options = params_for(:action => :create) -%> -<%= -if active_scaffold_config.create.multipart? # file_uploads - form_remote_upload_tag url_options.merge({:iframe => true}), - :onsubmit => onsubmit, - :id => element_form_id(:action => :create), - :class => 'create' -else - form_remote_tag :url => url_options, - :after => "$('#{loading_indicator_id(:action => :create, :id => params[:id])}').style.visibility = 'visible'; Form.disable('#{element_form_id(:action => :create)}');", - :complete => "$('#{loading_indicator_id(:action => :create, :id => params[:id])}').style.visibility = 'hidden'; Form.enable('#{element_form_id(:action => :create)}');", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :html => { - :href => url_for(url_options), - :onsubmit => onsubmit, - :id => element_form_id(:action => :create), - :class => 'create' - } -end -%> - -

<%= active_scaffold_config.create.label -%>

- - <% if request.xhr? -%> -
<%= error_messages_for :record, :object_name => @record.class.human_name.downcase %>
- <% else -%> - <%= render :partial => 'form_messages' %> - <% end -%> - - <%= render :partial => 'form', :locals => { :columns => active_scaffold_config.create.columns } %> - - - - \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_field_search.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_field_search.html.erb deleted file mode 100644 index ed8c588..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_field_search.html.erb +++ /dev/null @@ -1,40 +0,0 @@ -<% href_params = params_for(:action => :index, :escape => false, :search => nil) -%> -<% href = url_for(href_params) -%> -<%= form_remote_tag :url => href, - :method => :get, - :before => "addActiveScaffoldPageToHistory('#{href}', '#{params[:controller]}')", - :after => "$('#{loading_indicator_id(:action => :search, :id => params[:id])}').style.visibility = 'visible'; Form.disable('#{search_form_id}');", - :complete => "$('#{loading_indicator_id(:action => :search, :id => params[:id])}').style.visibility = 'hidden'; Form.enable('#{search_form_id}');", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :html => { :action => href, :id => search_form_id, :class => 'search', :method => :get } %> - -
    - <% active_scaffold_config.field_search.columns.each do |column| -%> - <% next unless column.search_sql -%> - <% name = "search[#{column.name}]" %> -
  1. -
    -
    - -
    -
    - <%= active_scaffold_search_for(column) %> -
    -
    -
  2. - <% end -%> -
- - - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_form.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_form.html.erb deleted file mode 100644 index 238adef..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_form.html.erb +++ /dev/null @@ -1,18 +0,0 @@ -
    > - <% columns.each :for => @record do |column| -%> - <% if is_subsection? column -%> -
  1. -
    <%= column.label %> (<%= link_to_visibility_toggle(:default_visible => !column.collapsed) -%>)
    - <%= render :partial => 'form', :locals => { :columns => column } %> -
  2. - <% elsif is_subform? column and !override_form_field?(column) -%> -
  3. - <%= render :partial => form_partial_for_column(column), :locals => { :column => column } -%> -
  4. - <% else -%> -
  5. - <%= render :partial => form_partial_for_column(column), :locals => { :column => column } -%> -
  6. - <% end -%> - <% end -%> -
diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_form_association.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_form_association.html.erb deleted file mode 100644 index e34b923..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_form_association.html.erb +++ /dev/null @@ -1,15 +0,0 @@ -<% -parent_record = @record -associated = column.singular_association? ? [parent_record.send(column.name)].compact : parent_record.send(column.name).to_a -associated = associated.sort_by {|r| r.new_record? ? 99999999999 : r.id} unless column.association.options.has_key?(:order) - -if column.show_blank_record? associated - associated << column.association.klass.new - locked = associated.last -end --%> -
<%= column.label -%> (<%= link_to_visibility_toggle(:default_visible => !column.collapsed) -%>)
-
> -<%= render :partial => subform_partial_for_column(column), :locals => {:column => column, :parent_record => parent_record, :associated => associated, :locked => locked} %> -
-<% @record = parent_record -%> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_form_association_footer.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_form_association_footer.html.erb deleted file mode 100644 index 5cd90bf..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_form_association_footer.html.erb +++ /dev/null @@ -1,40 +0,0 @@ -<% -begin - remote_controller = active_scaffold_controller_for(column.association.klass) -rescue ActiveScaffold::ControllerNotFound - remote_controller = nil -end - -show_add_existing = column_show_add_existing(column) -show_add_new = column_show_add_new(column, associated, @record) - -return unless show_add_new or show_add_existing - -edit_associated_url = url_for(:action => 'edit_associated', :id => parent_record.id, :association => column.name, :associated_id => '--ID--', :escape => false, :eid => params[:eid], :parent_controller => params[:parent_controller], :parent_id => params[:parent_id]) if show_add_existing -add_new_url = url_for(:action => 'edit_associated', :id => parent_record.id, :association => column.name, :escape => false, :eid => params[:eid], :parent_controller => params[:parent_controller], :parent_id => params[:parent_id]) if show_add_new - --%> - - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_form_attribute.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_form_attribute.html.erb deleted file mode 100644 index 01d68b4..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_form_attribute.html.erb +++ /dev/null @@ -1,15 +0,0 @@ -<% scope ||= nil %> -
-
- -
-
- <%= active_scaffold_input_for column, scope %> - <% if column.options.is_a?(Hash) && column.options[:update_column] -%> - <%= loading_indicator_tag(:action => :render_field, :id => params[:id]) %> - <% end -%> - <% if column.description.present? -%> - <%= column.description %> - <% end -%> -
-
\ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_form_hidden_attribute.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_form_hidden_attribute.html.erb deleted file mode 100644 index e7afb29..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_form_hidden_attribute.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -<% scope ||= nil %> -<%= hidden_field :record, column.name, active_scaffold_input_options(column, scope) %> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_form_messages.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_form_messages.html.erb deleted file mode 100644 index ba7217a..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_form_messages.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -<%= render :partial => 'messages' %> - -<% unless @record.nil? %> - <%= error_messages_for :record, :object_name => @record.class.human_name.downcase %> -<% end %> \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform.html.erb deleted file mode 100644 index 3e39257..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform.html.erb +++ /dev/null @@ -1,19 +0,0 @@ - - <% @record = column.association.klass.new -%> - <%= render :partial => 'horizontal_subform_header', :locals => {:parent_record => parent_record} %> - - - <% associated.each_index do |index| %> - <% @record = associated[index] -%> - <% if @record.errors.count -%> - - - - <% end %> - <%= render :partial => 'horizontal_subform_record', :locals => {:scope => column_scope(column), :parent_record => parent_record, :column => column, :locked => @record == locked} %> - <% end -%> - -
"> - <%= error_messages_for :record, :object_name => @record.class.human_name.downcase %> -
-<%= render :partial => 'form_association_footer', :locals => {:parent_record => parent_record, :column => column, :associated => associated} -%> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_header.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_header.html.erb deleted file mode 100644 index 240d0d3..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_header.html.erb +++ /dev/null @@ -1,10 +0,0 @@ - - - <% - active_scaffold_config_for(@record.class).subform.columns.each :for => @record, :flatten => true do |column| - next unless in_subform?(column, parent_record) and column_renders_as(column) != :hidden - -%> - > - <% end -%> - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_record.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_record.html.erb deleted file mode 100644 index 1388f92..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_horizontal_subform_record.html.erb +++ /dev/null @@ -1,31 +0,0 @@ -<% record_column = column -%> -<% readonly = (@record.readonly? or not @record.authorized_for?(:crud_type => :update)) -%> -<% crud_type = @record.new_record? ? :create : (readonly ? :read : nil) -%> -<% show_actions = false -%> -<% config = active_scaffold_config_for(@record.class) -%> - -<% config.subform.columns.each :for => @record.class, :crud_type => crud_type, :flatten => true do |column| %> -<% - next unless in_subform?(column, parent_record) - show_actions = true - column = column.clone - column.form_ui ||= :select if column.association --%> - - <% unless readonly and not @record.new_record? -%> - <%= render :partial => form_partial_for_column(column), :locals => { :column => column, :scope => scope } -%> - <% else -%> -

<%= get_column_value(@record, column) -%>

- <% end -%> - -<% end -%> -<% if show_actions -%> - - <%= link_to_function as_(:remove), '$(this).up(".association-record").remove()', { :class => "destroy" } if record_column.plural_association? and (@record.authorized_for?(:crud_type => :delete) or not [:destroy, :delete_all].include?(record_column.association.options[:dependent])) %> - <% unless @record.new_record? %> - <% options = active_scaffold_input_options(config.columns[@record.class.primary_key], scope) -%> - - <% end -%> - -<% end -%> - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list.html.erb deleted file mode 100644 index b7fca59..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list.html.erb +++ /dev/null @@ -1,23 +0,0 @@ - - - - <%= render :partial => 'list_column_headings' %> - - - - - - - - - <% if !@records.empty? -%> - <%= render :partial => 'list_record', :collection => @page.items, :locals => { :hidden => false } %> - <% end -%> - <% if active_scaffold_config.list.columns.any? {|c| c.calculation?} -%> - <%= render :partial => 'list_calculations' %> - <% end -%> - -
- <%= render :partial => 'list_messages' %> -
-<%= render :partial => 'list_pagination' %> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_actions.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_actions.html.erb deleted file mode 100644 index 7077169..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_actions.html.erb +++ /dev/null @@ -1,26 +0,0 @@ - - - - <% active_scaffold_config.action_links.each :member do |link| -%> - <% next if skip_action_link(link) -%> - - <% end -%> - -
- <%= loading_indicator_tag(:action => :record, :id => record.id) %> - - <%= record.authorized_for?(:crud_type => link.crud_type, :action => link.action) ? render_action_link(link, url_options, record) : "#{link.label}".html_safe -%> -
- -<% target_id = element_row_id(:action => :list, :id => record.id) -%> - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_calculations.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_calculations.html.erb deleted file mode 100644 index 67097e6..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_calculations.html.erb +++ /dev/null @@ -1,15 +0,0 @@ -<% display_class = ( @records.kind_of?(Array) ? @records.first : @records ) -%> - - <% active_scaffold_config.list.columns.each do |column| -%> - - <% if column.calculation? -%> - <%= render_column_calculation(column) %> - <% else -%> -   - <% end -%> - - <% end -%> - <% unless active_scaffold_config.action_links.empty? -%> -   - <% end -%> - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_column_headings.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_column_headings.html.erb deleted file mode 100644 index 162e5ba..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_column_headings.html.erb +++ /dev/null @@ -1,32 +0,0 @@ -<% -sorting = active_scaffold_config.list.user.sorting -sorting_stages = ['reset', 'ASC', 'DESC'] -default_sorting = active_scaffold_config.list.sorting -default_sorting_stages = ['ASC', 'DESC'] --%> - <%= content_tag :th, mark_record(marked_records.length >= @page.pager.count), :class => 'mark_record_column' if active_scaffold_config.list.mark_records %> -<% active_scaffold_config.list.columns.each do |column| -%> - <% - stages = default_sorting.sorts_on?(column) ? default_sorting_stages : sorting_stages - column_sort_direction = stages.after(sorting.direction_of(column)) || 'ASC' - sort_params = params_for(:page => 1, :sort => column.name, :sort_direction => column_sort_direction) - column_header_id = active_scaffold_column_header_id(column) - -%> - " title="<%= h column.description %>"> - <% if column.sortable? -%> - <% href = url_for(sort_params) -%> - <%= link_to_remote column.label, - { :url => sort_params, - :before => "addActiveScaffoldPageToHistory('#{href}', '#{controller_id}')", - :loading => "Element.addClassName('#{column_header_id}','loading');", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :method => :get }, - { :href => href } %> - <% else -%> -

<%= column.label %>

- <% end -%> - <%= inplace_edit_control(column) -%> - -<% end -%> - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_header.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_header.html.erb deleted file mode 100644 index 6027fba..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_header.html.erb +++ /dev/null @@ -1,14 +0,0 @@ -<% if active_scaffold_config.action_links.any? { |link| link.type == :collection } -%> -
- <% new_params = params_for(:action => :index) %> - <% active_scaffold_config.action_links.each :collection do |link| -%> - <% next if skip_action_link(link) -%> - <% next if link.action == 'new' && params[:nested].nil? && active_scaffold_config.list.always_show_create %> - <% next if link.action == 'show_search' && active_scaffold_config.list.always_show_search %> - <%= render_action_link(link, new_params) -%> - <% end -%> - - <%= loading_indicator_tag(:action => :index) %> -
-<% end %> -

<%= active_scaffold_config.list.user.label %>

diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_inline_adapter.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_inline_adapter.html.erb deleted file mode 100644 index d302cfa..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_inline_adapter.html.erb +++ /dev/null @@ -1,10 +0,0 @@ -<%= update_page_tag { |page| page.replace_html active_scaffold_messages_id, :partial => 'messages' } %> -<%# nested_id, allows us to remove a nested scaffold programmatically %> - - -
<%= "#{params[:associations] ? params[:associations] : params[:controller]}-view" %> view"> - <%= as_(:close) %> - <%= payload -%> -
- - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_messages.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_messages.html.erb deleted file mode 100644 index f62acaa..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_messages.html.erb +++ /dev/null @@ -1,20 +0,0 @@ -
- <%= render :partial => 'messages' %> -
-

> - <%= as_(active_scaffold_config.list.filtered_message) %> - <% if active_scaffold_config.list.show_search_reset -%> - <% href = url_for(params_for(:action => :index, :escape => false, :search => '')) -%> - <%= link_to_remote as_(:click_to_reset), - { :url => href, - :method => :get, - :before => "addActiveScaffoldPageToHistory('#{href}', '#{params[:controller]}')", - :after => "$('#{loading_indicator_id(:action => :index)}').style.visibility = 'visible';", - :complete => "$('#{loading_indicator_id(:action => :index)}').style.visibility = 'hidden';", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')" - }, :href => href %> - <% end -%> -

-

> - <%= as_(active_scaffold_config.list.no_entries_message) %> -

diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_pagination.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_pagination.html.erb deleted file mode 100644 index 863d2e1..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_pagination.html.erb +++ /dev/null @@ -1,11 +0,0 @@ -<% if active_scaffold_config.list.pagination -%> - -<% end -%> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_pagination_links.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_pagination_links.html.erb deleted file mode 100644 index df08d1c..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_pagination_links.html.erb +++ /dev/null @@ -1,28 +0,0 @@ -<% unless current_page.nil? -%> - <% pagination_params = params_for -%> - <% indicator_params = pagination_params.merge(:action => 'pagination') -%> - <% previous_url = url_for(pagination_params.merge(:page => current_page.number - 1)) -%> - <% next_url = url_for(pagination_params.merge(:page => current_page.number + 1)) -%> - <% current_url = url_for(pagination_params.merge(:page => current_page.number)) -%> - - <%= loading_indicator_tag :action => :pagination %> - <%= link_to_remote(as_(:previous), - { :url => pagination_params.merge(:page => current_page.number - 1), - :after => "$('#{loading_indicator_id(:action => :pagination)}').style.visibility = 'visible';", - :before => "addActiveScaffoldPageToHistory('#{previous_url}', '#{controller_id}');", - :complete => "$('#{loading_indicator_id(:action => :pagination)}').style.visibility = 'hidden';", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :method => :get }, - { :href => previous_url, - :class => "previous"}) if current_page.prev? %> - <%= pagination_ajax_links current_page, pagination_params, active_scaffold_config.list.page_links_window %> - <%= link_to_remote(as_(:next), - { :url => pagination_params.merge(:page => current_page.number + 1), - :after => "$('#{loading_indicator_id(:action => :pagination)}').style.visibility = 'visible';", - :before => "addActiveScaffoldPageToHistory('#{next_url}', '#{controller_id}');", - :complete => "$('#{loading_indicator_id(:action => :pagination)}').style.visibility = 'hidden';", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :method => :get }, - { :href => next_url, - :class => "next"}) if current_page.next? %> -<% end -%> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_record.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_record.html.erb deleted file mode 100644 index b3c0e43..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_record.html.erb +++ /dev/null @@ -1,11 +0,0 @@ -<% -record = list_record if list_record # compat with render :partial :collection -tr_class = cycle("", "even-record") -tr_class += " #{list_row_class(record)}" if respond_to? :list_row_class -url_options = params_for(:action => :list, :id => record.id) --%> - - - <%= render :partial => 'list_record_columns', :locals => {:record => record} %> - <%= render :partial => 'list_actions', :locals => {:record => record, :url_options => url_options} if active_scaffold_config.action_links.any? {|link| link.type == :member } %> - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_list_record_columns.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_list_record_columns.html.erb deleted file mode 100644 index cbbba28..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_list_record_columns.html.erb +++ /dev/null @@ -1,9 +0,0 @@ - <%= content_tag :td, mark_record(marked_records.include?(record.id.to_s), :id => record.id), :class => 'mark_record_column' if active_scaffold_config.list.mark_records %> -<% active_scaffold_config.list.columns.each do |column| %> - <% authorized = record.authorized_for?(:crud_type => :read, :column => column.name) -%> - <% column_value = authorized ? get_column_value(record, column) : active_scaffold_config.list.empty_field_text -%> - - - <%= authorized ? render_list_column(column_value, column, record) : column_value %> - -<% end -%> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_messages.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_messages.html.erb deleted file mode 100644 index f21e14c..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_messages.html.erb +++ /dev/null @@ -1,10 +0,0 @@ -<% for name in [:info, :warning, :error] %> - <% if flash[name] %> -

" > - <%= h flash[name] %> - <% if request.xhr? %> - - <% end %> -

- <% end %> -<% end %> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_nested.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_nested.html.erb deleted file mode 100644 index 51b30f8..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_nested.html.erb +++ /dev/null @@ -1,35 +0,0 @@ -<% - # TODO: shouldn't this logic happen in the controller action instead of the template? - # Actually, maybe we should make render :active_scaffold work in the controller, and not even have a _nested.rhtml? - - # This assumes that the association is included as a column in the active_scaffold_config.columns collection - associated_columns = [] - associated_columns = params[:associations].split(" ") unless params[:associations].nil? - unless associated_columns.empty? - parent_id = params[:id] - associated_columns.each do | column_name | - # find the column and the association - column = active_scaffold_config.columns[column_name] - association = column.association - - # determine what constraints we need - @constraints = { association.reverse => parent_id } - - # generate the customized label - @label = as_(:nested_for_model, :nested_model => active_scaffold_config_for(association.klass).list.label, :parent_model => format_value(@record.to_label)) - - begin - controller = active_scaffold_controller_for(association.klass) - rescue ActiveScaffold::ControllerNotFound => error - concat "#{error.class} - #{error.message}" - else - concat render(:active_scaffold => controller.controller_path, - :constraints => @constraints, - :conditions => association.options[:conditions], - :label => h(@label), - :params => {:nested => true, :parent_column => column_name, :parent_model => association.active_record.name, :format => 'html'} - ) - end - end - end -%> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_render_fields.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/_render_fields.js.rjs deleted file mode 100644 index 884a6ae..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_render_fields.js.rjs +++ /dev/null @@ -1,11 +0,0 @@ -render_fields.each do |column_name| - column = active_scaffold_config.columns[column_name.to_sym] - if column_renders_as(column) == :subform - field_id = sub_form_id(:association => column.name) - page[field_id].replace_html :partial => form_partial_for_column(column), :locals => { :column => column, :scope => params[:scope] } - else - field_id = active_scaffold_input_options(column, params[:scope])[:id] - page[field_id].up('dl').replace :partial => form_partial_for_column(column), :locals => { :column => column, :scope => params[:scope] } - end - page << render(:partial => 'render_fields.js', :object => Array(column.update_column)) if column.update_column -end diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_search.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_search.html.erb deleted file mode 100644 index f62af86..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_search.html.erb +++ /dev/null @@ -1,27 +0,0 @@ -<% live_search = active_scaffold_config.search.live? -%> -<% href = url_for(params_for(:action => :index, :escape => false).delete_if{|k,v| k == 'search'}) -%> -<%= form_remote_tag :url => href, - :method => :get, - :before => "addActiveScaffoldPageToHistory('#{href}', '#{params[:controller]}')", - :after => "$('#{loading_indicator_id(:action => :search, :id => params[:id])}').style.visibility = 'visible';#{"Form.disable('#{search_form_id}');" unless live_search }", - :complete => "$('#{loading_indicator_id(:action => :search, :id => params[:id])}').style.visibility = 'hidden';#{"Form.enable('#{search_form_id}');" unless live_search }", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :html => { :action => href, :id => search_form_id, :class => 'search', :method => :get } %> - <%= text_field_tag :search, search_params, :class => 'text-input', :id => search_input_id, :size => 50, :autocompleted => :off %> - <%= submit_tag as_(:search), :class => "submit" unless live_search %> - <%= link_to_remote as_(:reset), {:url => href, :with => "'search='", :method => :get, - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')"}, :class => 'cancel' %> - <%= loading_indicator_tag(:action => :search) %> - - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_show.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_show.html.erb deleted file mode 100644 index 52c944d..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_show.html.erb +++ /dev/null @@ -1,8 +0,0 @@ -

<%= active_scaffold_config.show.label(@record.to_label.nil? ? nil : clean_column_value(@record.to_label)) %>

- -<%= render :partial => 'show_columns', :locals => {:columns => active_scaffold_config.show.columns} -%> - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_show_columns.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_show_columns.html.erb deleted file mode 100644 index 830ea23..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_show_columns.html.erb +++ /dev/null @@ -1,12 +0,0 @@ -
-<% columns.each :for => @record do |column| %> -
<%= column.label -%>
- > -<% if column.is_a? ActiveScaffold::DataStructures::ActionColumns -%> -  <%= render :partial => 'show_columns', :locals => {:columns => column} %> -<% else -%> - <%= show_column_value(@record, column) %> -<% end -%> - -<% end -%> -
diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_update_actions.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_update_actions.html.erb deleted file mode 100644 index ecb85fa..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_update_actions.html.erb +++ /dev/null @@ -1,9 +0,0 @@ -
-
- <% active_scaffold_config.action_links.each :member do |link| -%> - <% next unless link.action == 'nested' -%> - <% next if skip_action_link(link) -%> - <%= record.authorized_for?(:crud_type => link.crud_type, :action => link.action) ? render_action_link(link, url_options, record) : "#{link.label}" -%> - <% end -%> -
-
diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_update_form.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_update_form.html.erb deleted file mode 100644 index ba248a1..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_update_form.html.erb +++ /dev/null @@ -1,56 +0,0 @@ -<% url_options = params_for(:action => :update) -%> -<% xhr ||= request.xhr? -%> -<%= -if xhr - if active_scaffold_config.update.multipart? # file_uploads - form_remote_upload_tag url_options.merge({:iframe => true}), - :onsubmit => onsubmit, - :id => element_form_id(:action => :update), - :loading => "$('#{loading_indicator_id(:action => :update, :id => params[:id])}').style.visibility = 'visible';", - :class => 'update', - :method => :put - else - form_remote_tag :url => url_options, - :after => "$('#{loading_indicator_id(:action => :update, :id => params[:id])}').style.visibility = 'visible'; Form.disable('#{element_form_id(:action => :update)}');", - :complete => "$('#{loading_indicator_id(:action => :update, :id => params[:id])}').style.visibility = 'hidden'; Form.enable('#{element_form_id(:action => :update)}');", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :html => { - :href => url_for(url_options), - :onsubmit => onsubmit, - :id => element_form_id(:action => :update), - :class => 'update', - :method => :put - } - end -else - form_tag url_options, - :onsubmit => onsubmit, - :id => element_form_id(:action => :update), - :multipart => active_scaffold_config.update.multipart?, - :class => 'update', - :method => :put -end -%> - -

<%= @record.to_label.nil? ? active_scaffold_config.update.label : as_(:update_model, :model => clean_column_value(@record.to_label)) %>

- -
-<% if request.xhr? -%> - <%= error_messages_for :record, :object_name => @record.class.human_name.downcase %> -<% else -%> - <%= render :partial => 'form_messages' %> -<% end -%> -
- - <%= render :partial => 'form', :locals => { :columns => active_scaffold_config.update.columns } %> - - - - - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform.html.erb deleted file mode 100644 index eb374c1..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform.html.erb +++ /dev/null @@ -1,12 +0,0 @@ -
- <% associated.each_index do |index| %> - <% @record = associated[index] -%> - <% if @record.errors.count -%> -
"> - <%= error_messages_for :record, :object_name => @record.class.human_name.downcase %> -
- <% end %> - <%= render :partial => 'vertical_subform_record', :locals => {:scope => column_scope(column), :parent_record => parent_record, :column => column, :locked => @record == locked} %> - <% end -%> -
-<%= render :partial => 'form_association_footer', :locals => {:parent_record => parent_record, :column => column, :associated => associated} -%> diff --git a/vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform_record.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform_record.html.erb deleted file mode 100644 index 594a4b5..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/_vertical_subform_record.html.erb +++ /dev/null @@ -1,33 +0,0 @@ -<% - record_column = column - readonly = (@record.readonly? or not @record.authorized_for?(:crud_type => :update)) - crud_type = @record.new_record? ? :create : (readonly ? :read : nil) - show_actions = false - config = active_scaffold_config_for(@record.class) --%> -
    -<% config.subform.columns.each :for => @record, :crud_type => crud_type, :flatten => true do |column| %> -<% - next unless in_subform?(column, parent_record) - show_actions = true - column = column.clone - column.form_ui ||= :select if column.association --%> -
  1. - <% unless readonly -%> - <%= render :partial => form_partial_for_column(column), :locals => { :column => column, :scope => scope } -%> - <% else -%> -

    <%= get_column_value(@record, column) -%>

    - <% end -%> -
  2. -<% end -%> -<% if show_actions -%> -
  3. - <%= link_to_function as_(:remove), '$(this).up(".association-record").remove()', { :class => "destroy" } if record_column.plural_association? and (@record.authorized_for?(:crud_type => :delete) or not [:destroy, :delete_all].include?(record_column.association.options[:dependent])) %> - <% unless @record.new_record? %> - <% options = active_scaffold_input_options(config.columns[@record.class.primary_key], scope) -%> - - <% end -%> -
  4. -<% end -%> -
diff --git a/vendor/plugins/active_scaffold/frontends/default/views/add_existing.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/add_existing.js.rjs deleted file mode 100644 index 50ac40c..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/add_existing.js.rjs +++ /dev/null @@ -1,17 +0,0 @@ -page.insert_html :top, active_scaffold_tbody_id, :partial => 'list_record', :locals => {:record => @record} -page.replace active_scaffold_calculations_id, :partial => 'list_calculations' if active_scaffold_config.list.columns.any? {|c| c.calculation?} -page << "ActiveScaffold.stripe($('#{active_scaffold_tbody_id}'))" -page << "ActiveScaffold.hide_empty_message('#{active_scaffold_tbody_id}','#{empty_message_id}');" -page << "ActiveScaffold.increment_record_count('#{active_scaffold_id}');" - -if (form_stays_open = true) - # why not just re-render the form? that wouldn't utilize a possible do_new override which sets default values. - page << "$('#{element_form_id}').reset()" - page.replace_html element_messages_id(:action => :add_existing), :partial => 'form_messages' - # have to delay the focus, because there's no "firstElement" in prototype until at least one element is not disabled - page.delay 0.1 do - page << "Form.focusFirstElement('#{element_form_id}');" - end -else - page << "$$('##{element_form_id(:action => :new_existing)} a.cancel').first().link.close();" -end diff --git a/vendor/plugins/active_scaffold/frontends/default/views/add_existing_form.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/add_existing_form.html.erb deleted file mode 100644 index 4957016..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/add_existing_form.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -
-
view"> - <%= render :partial => 'add_existing_form' -%> -
-
\ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/create.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/create.html.erb deleted file mode 100644 index 4647991..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/create.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -
-
view"> - <%= render :partial => 'create_form' -%> -
-
\ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/delete.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/delete.html.erb deleted file mode 100644 index bccc1b2..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/delete.html.erb +++ /dev/null @@ -1,13 +0,0 @@ -
-
- <%= form_tag params_for(:action => :destroy, :id => params[:id]), { :method => :delete } %> -

<%= as_(:are_you_sure) -%>

- - - - -
-
\ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/destroy.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/destroy.js.rjs deleted file mode 100644 index caf67ee..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/destroy.js.rjs +++ /dev/null @@ -1,10 +0,0 @@ -if controller.send(:successful?) - page << "$('#{action_link_id((respond_to?(:nested_habtm?) and nested_habtm? and active_scaffold_config.nested.shallow_delete) ? 'destroy_existing' : 'delete', params[:id])}').action_link.close_previous_adapter();" - page.remove element_row_id(:action => 'list', :id => params[:id]) - page << "ActiveScaffold.reload_if_empty('#{active_scaffold_tbody_id}','#{url_for(params_for(:action => :index, :id => nil, :page => [active_scaffold_config.list.user.page.to_i - 1, 1].max, :escape => false))}');" - page << "ActiveScaffold.stripe('#{active_scaffold_tbody_id}');" - page << "ActiveScaffold.decrement_record_count('#{active_scaffold_id}');" - page.replace active_scaffold_calculations_id, :partial => 'list_calculations' if active_scaffold_config.list.columns.any? {|c| c.calculation?} -end - -page.replace_html active_scaffold_messages_id, :partial => 'messages' diff --git a/vendor/plugins/active_scaffold/frontends/default/views/edit_associated.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/edit_associated.js.rjs deleted file mode 100644 index a9715c5..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/edit_associated.js.rjs +++ /dev/null @@ -1,20 +0,0 @@ -associated_form = render :partial => "#{subform_partial_for_column(@column)}_record", :locals => {:scope => @scope, :parent_record => @parent_record, :column => @column, :locked => @record.new_record? && @column.singular_association?} - -if @column.singular_association? - page << %| - associated = #{associated_form.to_json}; - if (current = $$('##{sub_form_list_id(:association => @column.name)} .association-record')[0]) { - Element.replace(current, associated) - } else { - new Insertion.Top('#{sub_form_list_id(:association => @column.name)}', associated) - } - | -else - unless @record.new_record? - column = active_scaffold_config_for(@record.class).columns[@record.class.primary_key] - id = active_scaffold_input_options(column, @scope)[:id] - page << "if (!$('#{id}')) {" - end - page.insert_html :bottom, sub_form_list_id(:association => @column.name), associated_form - page << "}" unless @record.new_record? -end diff --git a/vendor/plugins/active_scaffold/frontends/default/views/field_search.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/field_search.html.erb deleted file mode 100644 index e87af58..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/field_search.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -
-
- <%= render :partial => 'field_search' -%> -
-
\ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/form_messages.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/form_messages.js.rjs deleted file mode 100644 index 85478db..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/form_messages.js.rjs +++ /dev/null @@ -1 +0,0 @@ -page.replace_html element_messages_id, :partial => 'form_messages' \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/list.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/list.html.erb deleted file mode 100644 index 7548b2f..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/list.html.erb +++ /dev/null @@ -1,48 +0,0 @@ -
-
- <%= render :partial => 'list_header' %> -
- - - <% if active_scaffold_config.list.always_show_search %> - - - - <% else %> - - <% end %> - <% if params[:nested].nil? && active_scaffold_config.list.always_show_create %> - - - - <% end %> - -
-
- <%= render :partial => active_scaffold_config.list.search_partial %> -
-
-
- <%= render :partial => 'create_form_on_list' %> -
-
-
- <%= render :partial => 'list' %> -
-
- - diff --git a/vendor/plugins/active_scaffold/frontends/default/views/list.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/list.js.rjs deleted file mode 100644 index 7cbb923..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/list.js.rjs +++ /dev/null @@ -1 +0,0 @@ -page[active_scaffold_content_id].replace_html render(:partial => 'list', :layout => false) diff --git a/vendor/plugins/active_scaffold/frontends/default/views/mark.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/mark.js.rjs deleted file mode 100644 index d5bc871..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/mark.js.rjs +++ /dev/null @@ -1,6 +0,0 @@ -if params[:id] - # FIXME: It isn't right when there are filtered records by a search - page << "$('#{active_scaffold_id}').down('.mark_record').checked = #{@mark ? true : false};" -else - page << "$$('##{active_scaffold_tbody_id} > tr > td > .mark_record').each(function(checkbox) { checkbox.checked = #{@mark ? true : false};});" -end diff --git a/vendor/plugins/active_scaffold/frontends/default/views/on_create.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/on_create.js.rjs deleted file mode 100644 index 9350fef..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/on_create.js.rjs +++ /dev/null @@ -1,29 +0,0 @@ -form = element_form_id(:action => :create) -cancel_selector = "##{form} a.cancel".to_json - -if controller.send :successful? - if @insert_row - page.insert_html :top, active_scaffold_tbody_id, :partial => 'list_record', :locals => {:record => @record} - page.replace active_scaffold_calculations_id, :partial => 'list_calculations' if active_scaffold_config.list.columns.any? {|c| c.calculation?} - page << "ActiveScaffold.stripe($('#{active_scaffold_tbody_id}'))" - page << "ActiveScaffold.hide_empty_message('#{active_scaffold_tbody_id}','#{empty_message_id}');" - page << "ActiveScaffold.increment_record_count('#{active_scaffold_id}');" - page[element_row_id(:action => :list, :id => @record.id)].highlight - end - - if (active_scaffold_config.create.persistent) - page << "$$(#{cancel_selector}).first().link.reload();" - else - page << "$$(#{cancel_selector}).first().link.close();" - end - if (action = active_scaffold_config.create.action_after_create) - page << "var link = $('#{action_link_id action, @record.id}');" - page << "if (link) (function() { link.action_link.open() }).defer();" - end -else - page << "var l = $$(#{cancel_selector}).first().link;" - page.replace form, :partial => 'create_form', :locals => {:xhr => true} - page << "if (l) l.register_cancel_hooks();" - page[form].scroll_to -end -page.replace_html active_scaffold_messages_id, :partial => 'messages' diff --git a/vendor/plugins/active_scaffold/frontends/default/views/on_update.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/on_update.js.rjs deleted file mode 100644 index 29d34be..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/on_update.js.rjs +++ /dev/null @@ -1,18 +0,0 @@ -form = element_form_id(:action => :update) -cancel_selector = "##{form} a.cancel".to_json - -if controller.send :successful? - if active_scaffold_config.update.persistent - flash.now[:info] = 'Update Succeeded!' - else - updated_row = render :partial => 'list_record', :locals => {:record => @record} if params[:parent_controller].nil? - page << "$$(#{cancel_selector}).first().link.close('#{escape_javascript(updated_row)}');" - end - page.replace active_scaffold_calculations_id, :partial => 'list_calculations' if active_scaffold_config.list.columns.any? {|c| c.calculation?} -else - page << "var l = $$(#{cancel_selector}).first().link;" - page.replace form, :partial => 'update_form', :locals => {:xhr => true} - page << "if (l) l.register_cancel_hooks();" - page[form].scroll_to -end -page.replace_html active_scaffold_messages_id, :partial => 'messages' diff --git a/vendor/plugins/active_scaffold/frontends/default/views/render_field.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/render_field.js.rjs deleted file mode 100644 index fe381fa..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/render_field.js.rjs +++ /dev/null @@ -1 +0,0 @@ -page << render(:partial => 'render_fields.js', :object => @update_columns) diff --git a/vendor/plugins/active_scaffold/frontends/default/views/search.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/search.html.erb deleted file mode 100644 index 45a8096..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/search.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -
-
- <%= render :partial => 'search' -%> -
-
diff --git a/vendor/plugins/active_scaffold/frontends/default/views/show.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/show.html.erb deleted file mode 100644 index 0b36a91..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/show.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -
-
view"> - <%= render :partial => 'show' -%> -
-
\ No newline at end of file diff --git a/vendor/plugins/active_scaffold/frontends/default/views/update.html.erb b/vendor/plugins/active_scaffold/frontends/default/views/update.html.erb deleted file mode 100644 index d31da15..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/update.html.erb +++ /dev/null @@ -1,8 +0,0 @@ -
-
view"> - <% if active_scaffold_config.update.nested_links and active_scaffold_config.action_links.any? {|link| link.type == :member } -%> - <%= render :partial => 'update_actions', :locals => {:record => @record, :url_options => params_for(:action => :list, :id => @record.id)} %> - <% end -%> - <%= render :partial => 'update_form' -%> -
-
diff --git a/vendor/plugins/active_scaffold/frontends/default/views/update_column.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/update_column.js.rjs deleted file mode 100644 index 9c19a18..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/update_column.js.rjs +++ /dev/null @@ -1,13 +0,0 @@ -column_span_id = element_cell_id(:id => @record.id.to_s, :action => 'update_column', :name => params[:column]) -unless controller.send :successful? - page.alert(@record.errors.full_messages(active_scaffold_config).join("\n")) - @record.reload -end -column = active_scaffold_config.columns[params[:column]] -if column.inplace_edit - page.replace_html(column_span_id, format_inplace_edit_column(@record, column)) -else - formatted_value = get_column_value(@record, column) - page.replace_html(column_span_id, formatted_value) -end -page.replace_html(active_scaffold_calculations_id(column), render_column_calculation(column)) if column.calculation? diff --git a/vendor/plugins/active_scaffold/frontends/default/views/update_row.js.rjs b/vendor/plugins/active_scaffold/frontends/default/views/update_row.js.rjs deleted file mode 100644 index 238bcdc..0000000 --- a/vendor/plugins/active_scaffold/frontends/default/views/update_row.js.rjs +++ /dev/null @@ -1,2 +0,0 @@ -page.call 'ActiveScaffold.update_row', element_row_id(:action => 'list', :id => @record.id), render(:partial => 'list_record', :locals => {:record => @record}) -page.replace active_scaffold_calculations_id, :partial => 'list_calculations' if active_scaffold_config.list.columns.any? {|c| c.calculation?} diff --git a/vendor/plugins/active_scaffold/init.rb b/vendor/plugins/active_scaffold/init.rb deleted file mode 100755 index 9b147c7..0000000 --- a/vendor/plugins/active_scaffold/init.rb +++ /dev/null @@ -1,18 +0,0 @@ -## -## Initialize the environment -## -unless Rails::VERSION::MAJOR == 2 && Rails::VERSION::MINOR >= 3 && Rails::VERSION::TINY >= 8 - raise "This version of ActiveScaffold requires Rails 2.3.8 or higher. Please use an earlier version." -end - -require File.dirname(__FILE__) + '/environment' - -## -## Run the install assets script, too, just to make sure -## But at least rescue the action in production -## -begin - require File.dirname(__FILE__) + '/install_assets' -rescue - raise $! unless Rails.env == 'production' -end diff --git a/vendor/plugins/active_scaffold/install.rb b/vendor/plugins/active_scaffold/install.rb deleted file mode 100644 index 6aec94c..0000000 --- a/vendor/plugins/active_scaffold/install.rb +++ /dev/null @@ -1,39 +0,0 @@ -## -## Install ActiveScaffold assets into /public -## - -require File.dirname(__FILE__) + '/install_assets' - -## -## Install Counter -## -# -# What's going on here? -# We're incrementing a web counter so we can track SVN installs of ActiveScaffold -# -# How? -# We're making a GET request to errcount.com to update a simple counter. No data is transmitted. -# -# Why? -# So we can know how many people are using ActiveScaffold and modulate our level of effort accordingly. -# Despite numerous pleas our Googly overlords still only provide us with download stats for the zip distro. -# -# *Thanks for your understanding* -# - -class ErrCounter # using errcount.com - require "net/http" - - @@ACCOUNT_ID = 341 - @@SITE_DOMAIN = 'installs.activescaffold.com' - - def self.increment - @http = Net::HTTP.new("errcount.com") - resp, data = @http.get2("/ctr/#{@@ACCOUNT_ID}.js", {'Referer' => @@SITE_DOMAIN}) - end -end - -begin - ErrCounter.increment -rescue -end diff --git a/vendor/plugins/active_scaffold/install_assets.rb b/vendor/plugins/active_scaffold/install_assets.rb deleted file mode 100755 index 74d54ea..0000000 --- a/vendor/plugins/active_scaffold/install_assets.rb +++ /dev/null @@ -1,36 +0,0 @@ -# Workaround a problem with script/plugin and http-based repos. -# See http://dev.rubyonrails.org/ticket/8189 -Dir.chdir(Dir.getwd.sub(/vendor.*/, '')) do - -## -## Copy over asset files (javascript/css/images) from the plugin directory to public/ -## - -def copy_files(source_path, destination_path, directory) - source, destination = File.join(directory, source_path), File.join(Rails.root, destination_path) - FileUtils.mkdir_p(destination) unless File.exist?(destination) - FileUtils.cp_r(Dir.glob(source+'/*.*'), destination) -end - -directory = File.dirname(__FILE__) - -copy_files("/public", "/public", directory) - -available_frontends = Dir[File.join(directory, 'frontends', '*')].collect { |d| File.basename d } -[ :stylesheets, :javascripts, :images].each do |asset_type| - path = "/public/#{asset_type}/active_scaffold" - copy_files(path, path, directory) - - File.open(File.join(Rails.root, path, 'DO_NOT_EDIT'), 'w') do |f| - f.puts "Any changes made to files in sub-folders will be lost." - f.puts "See http://activescaffold.com/tutorials/faq#custom-css." - end - - available_frontends.each do |frontend| - source = "/frontends/#{frontend}/#{asset_type}/" - destination = "/public/#{asset_type}/active_scaffold/#{frontend}" - copy_files(source, destination, directory) - end -end - -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/active_record_permissions.rb b/vendor/plugins/active_scaffold/lib/active_record_permissions.rb deleted file mode 100644 index e861045..0000000 --- a/vendor/plugins/active_scaffold/lib/active_record_permissions.rb +++ /dev/null @@ -1,134 +0,0 @@ -# This module attempts to create permissions conventions for your ActiveRecord models. It supports english-based -# methods that let you restrict access per-model, per-record, per-column, per-action, and per-user. All at once. -# -# You may define instance methods in the following formats: -# def #{column}_authorized_for_#{action}? -# def #{column}_authorized? -# def authorized_for_#{action}? -# -# Your methods should allow for the following special cases: -# * cron scripts -# * guest users (or nil current_user objects) -module ActiveRecordPermissions - # ActiveRecordPermissions needs to know what method on your ApplicationController will return the current user, - # if available. This defaults to the :current_user method. You may configure this in your environment.rb if you - # have a different setup. - def self.current_user_method=(v); @@current_user_method = v; end - def self.current_user_method; @@current_user_method; end - @@current_user_method = :current_user - - # Whether the default permission is permissive or not - # If set to true, then everything's allowed until configured otherwise - def self.default_permission=(v); @@default_permission = v; end - def self.default_permission; @@default_permission; end - @@default_permission = true - - # This is a module aimed at making the current_user available to ActiveRecord models for permissions. - module ModelUserAccess - module Controller - def self.included(base) - base.prepend_before_filter :assign_current_user_to_models - end - - # We need to give the ActiveRecord classes a handle to the current user. We don't want to just pass the object, - # because the object may change (someone may log in or out). So we give ActiveRecord a proc that ties to the - # current_user_method on this ApplicationController. - def assign_current_user_to_models - ActiveRecord::Base.current_user_proc = proc {send(ActiveRecordPermissions.current_user_method)} - end - end - - module Model - def self.included(base) - base.extend ClassMethods - end - - module ClassMethods - # The proc to call that retrieves the current_user from the ApplicationController. - attr_accessor :current_user_proc - - # Class-level access to the current user - def current_user - ActiveRecord::Base.current_user_proc.call if ActiveRecord::Base.current_user_proc - end - end - - # Instance-level access to the current user - def current_user - self.class.current_user - end - end - end - - module Permissions - def self.included(base) - base.extend SecurityMethods - base.send :include, SecurityMethods - end - - # Because any class-level queries get delegated to the instance level via a new record, - # it's useful to know when the authorization query is meant for a specific record or not. - # But using new_record? is confusing, even though accurate. So this is basically just a wrapper. - def existing_record_check? - !new_record? - end - - module SecurityMethods - # A generic authorization query. This is what will be called programatically, since - # the actual permission methods can't be guaranteed to exist. And because we want to - # intelligently combine multiple applicable methods. - # - # options[:crud_type] should be a CRUD verb (:create, :read, :update, :destroy) - # options[:column] should be the name of a model attribute - # options[:action] is the name of a method - def authorized_for?(options = {}) - raise ArgumentError, "unknown crud type #{options[:crud_type]}" if options[:crud_type] and ![:create, :read, :update, :delete].include?(options[:crud_type]) - - # column_authorized_for_crud_type? has the highest priority over other methods, - # you can disable a crud verb and enable that verb for a column - # (for example, disable update and enable inplace_edit in a column) - method = column_and_crud_type_security_method(options[:column], options[:crud_type]) - return send(method) if method and respond_to?(method) - - # authorized_for_action? has higher priority than other methods, - # you can disable a crud verb and enable an action with that crud verb - # (for example, disable update and enable an action with update as crud type) - method = action_security_method(options[:action]) - return send(method) if method and respond_to?(method) - - # collect other possibly-related methods that actually exist - methods = [ - column_security_method(options[:column]), - crud_type_security_method(options[:crud_type]), - ].compact.select {|m| respond_to?(m)} - - # if any method returns false, then return false - return false if methods.any? {|m| !send(m)} - - # if any method actually exists then it must've returned true, so return true - return true unless methods.empty? - - # if no method exists, return the default permission - return ActiveRecordPermissions.default_permission - end - - private - - def column_security_method(column) - "#{column}_authorized?" if column - end - - def crud_type_security_method(crud_type) - "authorized_for_#{crud_type}?" if crud_type - end - - def action_security_method(action) - "authorized_for_#{action}?" if action - end - - def column_and_crud_type_security_method(column, crud_type) - "#{column}_authorized_for_#{crud_type}?" if column and crud_type - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold.rb b/vendor/plugins/active_scaffold/lib/active_scaffold.rb deleted file mode 100644 index 6ce327c..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold.rb +++ /dev/null @@ -1,217 +0,0 @@ -module ActiveScaffold - class ControllerNotFound < RuntimeError; end - class DependencyFailure < RuntimeError; end - class MalformedConstraint < RuntimeError; end - class RecordNotAllowed < SecurityError; end - class ActionNotAllowed < SecurityError; end - class ReverseAssociationRequired < RuntimeError; end - - def self.included(base) - base.extend(ClassMethods) - base.module_eval do - # TODO: these should be in actions/core - before_filter :handle_user_settings - end - end - - def self.set_defaults(&block) - ActiveScaffold::Config::Core.configure &block - end - - def active_scaffold_config - self.class.active_scaffold_config - end - - def active_scaffold_config_for(klass) - self.class.active_scaffold_config_for(klass) - end - - def active_scaffold_session_storage - id = params[:eid] || params[:controller] - session_index = "as:#{id}" - session[session_index] ||= {} - session[session_index] - end - - # at some point we need to pass the session and params into config. we'll just take care of that before any particular action occurs by passing those hashes off to the UserSettings class of each action. - def handle_user_settings - if self.class.uses_active_scaffold? - active_scaffold_config.actions.each do |action_name| - conf_instance = active_scaffold_config.send(action_name) rescue next - next if conf_instance.class::UserSettings == ActiveScaffold::Config::Base::UserSettings # if it hasn't been extended, skip it - active_scaffold_session_storage[action_name] ||= {} - conf_instance.user = conf_instance.class::UserSettings.new(conf_instance, active_scaffold_session_storage[action_name], params) - end - end - end - - module ClassMethods - def active_scaffold(model_id = nil, &block) - # initialize bridges here - ActiveScaffold::Bridge.run_all - - # converts Foo::BarController to 'bar' and FooBarsController to 'foo_bar' and AddressController to 'address' - model_id = self.to_s.split('::').last.sub(/Controller$/, '').pluralize.singularize.underscore unless model_id - - # run the configuration - @active_scaffold_config = ActiveScaffold::Config::Core.new(model_id) - @active_scaffold_config_block = block - self.links_for_associations - - @active_scaffold_overrides = [] - ActionController::Base.view_paths.each do |dir| - active_scaffold_overrides_dir = File.join(dir,"active_scaffold_overrides") - @active_scaffold_overrides << active_scaffold_overrides_dir if File.exists?(active_scaffold_overrides_dir) - end - @active_scaffold_overrides.uniq! # Fix rails duplicating some view_paths - @active_scaffold_frontends = [] - if active_scaffold_config.frontend.to_sym != :default - active_scaffold_custom_frontend_path = File.join(Rails.root, 'vendor', 'plugins', ActiveScaffold::Config::Core.plugin_directory, 'frontends', active_scaffold_config.frontend.to_s , 'views') - @active_scaffold_frontends << active_scaffold_custom_frontend_path - end - active_scaffold_default_frontend_path = File.join(Rails.root, 'vendor', 'plugins', ActiveScaffold::Config::Core.plugin_directory, 'frontends', 'default' , 'views') - @active_scaffold_frontends << active_scaffold_default_frontend_path - @active_scaffold_custom_paths = [] - - self.active_scaffold_superclasses_blocks.each {|superblock| self.active_scaffold_config.configure &superblock} - self.active_scaffold_config.configure &block if block_given? - self.active_scaffold_config._configure_sti unless self.active_scaffold_config.sti_children.nil? - self.active_scaffold_config._load_action_columns - - # defines the attribute read methods on the model, so record.send() doesn't find protected/private methods instead - klass = self.active_scaffold_config.model - klass.define_attribute_methods unless klass.generated_methods? - - # include the rest of the code into the controller: the action core and the included actions - module_eval do - include ActiveScaffold::Finder - include ActiveScaffold::Constraints - include ActiveScaffold::AttributeParams - include ActiveScaffold::Actions::Core - active_scaffold_config.actions.each do |mod| - name = mod.to_s.camelize - include "ActiveScaffold::Actions::#{name}".constantize - - # sneak the action links from the actions into the main set - if link = active_scaffold_config.send(mod).link rescue nil - active_scaffold_config.action_links << link - end - end - end - self.active_scaffold_config._add_sti_create_links if self.active_scaffold_config.add_sti_create_links? - end - - # Create the automatic column links. Note that this has to happen when configuration is *done*, because otherwise the Nested module could be disabled. Actually, it could still be disabled later, couldn't it? - def links_for_associations - return unless active_scaffold_config.actions.include? :list and active_scaffold_config.actions.include? :nested - active_scaffold_config.columns.each do |column| - next unless column.link.nil? and column.autolink? - if column.plural_association? - # note: we can't create nested scaffolds on :through associations because there's no reverse association. - column.set_link('nested', :parameters => {:associations => column.name.to_sym}, :html_options => {:class => column.name}) #unless column.through_association? - elsif column.polymorphic_association? - # note: we can't create inline forms on singular polymorphic associations - column.clear_link - else - model = column.association.klass - begin - controller = active_scaffold_controller_for(model) - rescue ActiveScaffold::ControllerNotFound - next - end - - actions = controller.active_scaffold_config.actions - column.actions_for_association_links.delete :new unless actions.include? :create - column.actions_for_association_links.delete :edit unless actions.include? :update - column.actions_for_association_links.delete :show unless actions.include? :show - column.set_link(:none, :controller => controller.controller_path, :crud_type => nil, :label => :create_model, :html_options => {:class => column.name}) - end - end - end - - def add_active_scaffold_path(path) - @active_scaffold_paths = nil # Force active_scaffold_paths to rebuild - @active_scaffold_custom_paths << path - end - - def add_active_scaffold_override_path(path) - @active_scaffold_paths = nil # Force active_scaffold_paths to rebuild - @active_scaffold_overrides.unshift path - end - - def active_scaffold_paths - return @active_scaffold_paths unless @active_scaffold_paths.nil? - - @active_scaffold_paths = ActionView::PathSet.new - @active_scaffold_paths.concat @active_scaffold_overrides unless @active_scaffold_overrides.nil? - @active_scaffold_paths.concat @active_scaffold_custom_paths unless @active_scaffold_custom_paths.nil? - @active_scaffold_paths.concat @active_scaffold_frontends unless @active_scaffold_frontends.nil? - @active_scaffold_paths - end - - def active_scaffold_config - if @active_scaffold_config.nil? - self.superclass.active_scaffold_config if self.superclass.respond_to? :active_scaffold_config - else - @active_scaffold_config - end - end - - def active_scaffold_config_block - @active_scaffold_config_block - end - - def active_scaffold_superclasses_blocks - blocks = [] - klass = self.superclass - while klass.respond_to? :active_scaffold_superclasses_blocks - blocks << klass.active_scaffold_config_block - klass = klass.superclass - end - blocks.compact.reverse - end - - def active_scaffold_config_for(klass) - begin - controller = active_scaffold_controller_for(klass) - rescue ActiveScaffold::ControllerNotFound - config = ActiveScaffold::Config::Core.new(klass) - config._load_action_columns - config - else - controller.active_scaffold_config - end - end - - # Tries to find a controller for the given ActiveRecord model. - # Searches in the namespace of the current controller for singular and plural versions of the conventional "#{model}Controller" syntax. - # You may override this method to customize the search routine. - def active_scaffold_controller_for(klass) - controller_namespace = self.to_s.split('::')[0...-1].join('::') + '::' - error_message = [] - [controller_namespace, ''].each do |namespace| - ["#{klass.to_s.underscore.pluralize}", "#{klass.to_s.underscore.pluralize.singularize}"].each do |controller_name| - begin - controller = "#{namespace}#{controller_name.camelize}Controller".constantize - rescue NameError => error - # Only rescue NameError associated with the controller constant not existing - not other compile errors - if error.message["uninitialized constant #{controller}"] - error_message << "#{namespace}#{controller_name.camelize}Controller" - next - else - raise - end - end - raise ActiveScaffold::ControllerNotFound, "#{controller} missing ActiveScaffold", caller unless controller.uses_active_scaffold? - raise ActiveScaffold::ControllerNotFound, "ActiveScaffold on #{controller} is not for #{klass} model.", caller unless controller.active_scaffold_config.model.to_s == klass.to_s - return controller - end - end - raise ActiveScaffold::ControllerNotFound, "Could not find " + error_message.join(" or "), caller - end - - def uses_active_scaffold? - !active_scaffold_config.nil? - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/common_search.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/common_search.rb deleted file mode 100644 index 05cbe00..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/common_search.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActiveScaffold::Actions - module CommonSearch - protected - def store_search_params_into_session - active_scaffold_session_storage[:search] = params.delete :search if params[:search] - end - - def search_params - active_scaffold_session_storage[:search] - end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def search_authorized? - authorized_for?(:crud_type => :read) - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/core.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/core.rb deleted file mode 100644 index e1d9557..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/core.rb +++ /dev/null @@ -1,152 +0,0 @@ -module ActiveScaffold::Actions - module Core - def self.included(base) - base.class_eval do - after_filter :clear_flashes - end - end - def render_field - @record = if params[:in_place_editing] - active_scaffold_config.model.find params[:id] - else - active_scaffold_config.model.new - end - column = active_scaffold_config.columns[params[:column]] - if params[:in_place_editing] - render :inline => "<%= active_scaffold_input_for(active_scaffold_config.columns[params[:update_column].to_sym]) %>" - elsif !column.nil? - if column.send_form_on_update_column - @record = update_record_from_params(@record, active_scaffold_config.update.columns, params[:record]) - else - value = column_value_from_param_value(@record, column, params[:value]) - @record.send "#{column.name}=", value - end - @update_columns = Array(params[:update_column]) - after_render_field(@record, column) - end - end - - protected - - # override this method if you want to do something after render_field - def after_render_field(record, column); end - - def authorized_for?(options = {}) - active_scaffold_config.model.authorized_for?(options) - end - - def clear_flashes - if request.xhr? - flash.keys.each do |flash_key| - flash[flash_key] = nil - end - end - end - - def marked_records - active_scaffold_session_storage[:marked_records] ||= Set.new - end - - def default_formats - [:html, :js, :json, :xml, :yaml] - end - # Returns true if the client accepts one of the MIME types passed to it - # ex: accepts? :html, :xml - def accepts?(*types) - for priority in request.accepts.compact - if priority == Mime::ALL - # Because IE always sends */* in the accepts header and we assume - # that if you really wanted XML or something else you would say so - # explicitly, we will assume */* to only ask for :html - return types.include?(:html) - elsif types.include?(priority.to_sym) - return true - end - end - false - end - - def response_status - if successful? - action_name == 'create' ? 201 : 200 - else - 422 - end - end - - # API response object that will be converted to XML/YAML/JSON using to_xxx - def response_object - @response_object = successful? ? (@record || @records) : @record.errors - end - - # Success is the existence of certain variables and the absence of errors (when applicable). - # Success can also be defined. - def successful? - if @successful.nil? - @records or (@record and @record.errors.count == 0 and @record.no_errors_in_associated?) - else - @successful - end - end - - def successful=(val) - @successful = (val) ? true : false - end - - # Redirect to the main page (override if the ActiveScaffold is used as a component on another controllers page) for Javascript degradation - def return_to_main - redirect_to main_path_to_return - end - - # Override this method on your controller to define conditions to be used when querying a recordset (e.g. for List). The return of this method should be any format compatible with the :conditions clause of ActiveRecord::Base's find. - def conditions_for_collection - end - - # Override this method on your controller to define joins to be used when querying a recordset (e.g. for List). The return of this method should be any format compatible with the :joins clause of ActiveRecord::Base's find. - def joins_for_collection - end - - # Override this method on your controller to provide custom finder options to the find() call. The return of this method should be a hash. - def custom_finder_options - {} - end - - #Overide this method on your controller to provide model with named scopes - def beginning_of_chain - active_scaffold_config.model - end - - # Builds search conditions by search params for column names. This allows urls like "contacts/list?company_id=5". - def conditions_from_params - conditions = nil - params.reject {|key, value| [:controller, :action, :id, :page, :sort, :sort_direction].include?(key.to_sym)}.each do |key, value| - next unless active_scaffold_config.model.column_names.include?(key) - if value.is_a?(Array) - conditions = merge_conditions(conditions, ["#{active_scaffold_config.model.table_name}.#{key.to_s} in (?)", value]) - else - conditions = merge_conditions(conditions, ["#{active_scaffold_config.model.table_name}.#{key.to_s} = ?", value]) - end - end - conditions - end - private - def respond_to_action(action) - respond_to do |type| - send("#{action}_formats").each do |format| - type.send(format){ send("#{action}_respond_to_#{format}") } - end - end - end - - def response_code_for_rescue(exception) - case exception - when ActiveScaffold::RecordNotAllowed - "403 Record Not Allowed" - when ActiveScaffold::ActionNotAllowed - "403 Action Not Allowed" - else - super - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/create.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/create.rb deleted file mode 100644 index e2460d3..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/create.rb +++ /dev/null @@ -1,152 +0,0 @@ -module ActiveScaffold::Actions - module Create - def self.included(base) - base.before_filter :create_authorized_filter, :only => [:new, :create] - base.prepend_before_filter :constraints_for_nested_create, :only => [:new, :create] - base.verify :method => :post, - :only => :create, - :redirect_to => { :action => :index } - end - - def new - do_new - respond_to_action(:new) - end - - def create - do_create - @insert_row = params[:parent_controller].nil? - respond_to_action(:create) - end - - protected - def response_location - url_for(params_for(:action => "show", :id => @record.id)) if successful? - end - - def new_respond_to_html - if successful? - render(:action => 'create') - else - return_to_main - end - end - - def new_respond_to_js - render(:partial => 'create_form') - end - - def create_respond_to_html - if params[:iframe]=='true' # was this an iframe post ? - responds_to_parent do - render :action => 'on_create.js' - end - else - if successful? - flash[:info] = as_(:created_model, :model => @record.to_label) - if action = active_scaffold_config.create.action_after_create - redirect_to params_for(:action => action, :id => @record.id) - elsif active_scaffold_config.create.persistent - redirect_to params_for(:action => "new") - else - return_to_main - end - else - if params[:nested].nil? && active_scaffold_config.actions.include?(:list) && active_scaffold_config.list.always_show_create - do_list - render(:action => 'list') - else - render(:action => 'create') - end - end - end - end - - def create_respond_to_js - render :action => 'on_create' - end - - def create_respond_to_xml - render :xml => response_object.to_xml(:only => active_scaffold_config.create.columns.names), :content_type => Mime::XML, :status => response_status, :location => response_location - end - - def create_respond_to_json - render :text => response_object.to_json(:only => active_scaffold_config.create.columns.names), :content_type => Mime::JSON, :status => response_status, :location => response_location - end - - def create_respond_to_yaml - render :text => Hash.from_xml(response_object.to_xml(:only => active_scaffold_config.create.columns.names)).to_yaml, :content_type => Mime::YAML, :status => response_status, :location => response_location - end - - def constraints_for_nested_create - if params[:parent_column] && params[:parent_id] - @old_eid = params[:eid] - @remove_eid = true - constraints = {params[:parent_column].to_sym => params[:parent_id]} - params[:eid] = Digest::MD5.hexdigest(params[:parent_controller] + params[:controller].to_s + constraints.to_s) - session["as:#{params[:eid]}"] = {:constraints => constraints} - end - end - - # A simple method to find and prepare an example new record for the form - # May be overridden to customize the behavior (add default values, for instance) - def do_new - @record = new_model - apply_constraints_to_record(@record) - params[:eid] = @old_eid if @remove_eid - @record - end - - # A somewhat complex method to actually create a new record. The complexity is from support for subforms and associated records. - # If you want to customize this behavior, consider using the +before_create_save+ and +after_create_save+ callbacks. - def do_create - begin - active_scaffold_config.model.transaction do - @record = update_record_from_params(new_model, active_scaffold_config.create.columns, params[:record]) - apply_constraints_to_record(@record, :allow_autosave => true) - params[:eid] = @old_eid if @remove_eid - before_create_save(@record) - self.successful = [@record.valid?, @record.associated_valid?].all? {|v| v == true} # this syntax avoids a short-circuit - if successful? - @record.save! and @record.save_associated! - after_create_save(@record) - end - end - rescue ActiveRecord::RecordInvalid - end - end - - def new_model - model = active_scaffold_config.model - if model.columns_hash[model.inheritance_column] - params = self.params # in new action inheritance_column must be in params - params = params[:record] || {} unless params[model.inheritance_column] # in create action must be inside record key - model = params.delete(model.inheritance_column).camelize.constantize if params[model.inheritance_column] - end - model.new - end - - # override this method if you want to inject data in the record (or its associated objects) before the save - def before_create_save(record); end - - # override this method if you want to do something after the save - def after_create_save(record); end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def create_authorized? - authorized_for?(:crud_type => :create) - end - private - def create_authorized_filter - link = active_scaffold_config.create.link || active_scaffold_config.create.class.link - raise ActiveScaffold::ActionNotAllowed unless self.send(link.security_method) - end - def new_formats - (default_formats + active_scaffold_config.formats).uniq - end - def create_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.create.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/delete.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/delete.rb deleted file mode 100644 index c2a3b4e..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/delete.rb +++ /dev/null @@ -1,73 +0,0 @@ -module ActiveScaffold::Actions - module Delete - def self.included(base) - base.before_filter :delete_authorized_filter, :only => [:delete, :destroy] - end - - # this method is for html mode. it provides "the missing action" (http://thelucid.com/articles/2006/07/26/simply-restful-the-missing-action). - # it also gives us delete confirmation for html mode. woo! - def delete - destroy_find_record - render :action => 'delete' - end - - def destroy - return redirect_to(params.merge(:action => :delete)) if request.get? - do_destroy - respond_to_action(:destroy) - end - - protected - def destroy_respond_to_html - flash[:info] = as_(:deleted_model, :model => @record.to_label) if self.successful? - return_to_main - end - - def destroy_respond_to_js - render(:action => 'destroy') - end - - def destroy_respond_to_xml - render :xml => successful? ? "" : response_object.to_xml(:only => active_scaffold_config.list.columns.names), :content_type => Mime::XML, :status => response_status - end - - def destroy_respond_to_json - render :text => successful? ? "" : response_object.to_json(:only => active_scaffold_config.list.columns.names), :content_type => Mime::JSON, :status => response_status - end - - def destroy_respond_to_yaml - render :text => successful? ? "" : Hash.from_xml(response_object.to_xml(:only => active_scaffold_config.list.columns.names)).to_yaml, :content_type => Mime::YAML, :status => response_status - end - - def destroy_find_record - @record = find_if_allowed(params[:id], :delete) - end - - # A simple method to handle the actual destroying of a record - # May be overridden to customize the behavior - def do_destroy - destroy_find_record - begin - self.successful = @record.destroy - marked_records.delete @record.id.to_s if successful? - rescue - flash[:warning] = as_(:cant_destroy_record, :record => @record.to_label) - self.successful = false - end - end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def delete_authorized? - authorized_for?(:crud_type => :delete) - end - private - def delete_authorized_filter - link = active_scaffold_config.delete.link || active_scaffold_config.delete.class.link - raise ActiveScaffold::ActionNotAllowed unless self.send(link.security_method) - end - def destroy_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.delete.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/field_search.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/field_search.rb deleted file mode 100644 index b7f6306..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/field_search.rb +++ /dev/null @@ -1,60 +0,0 @@ -module ActiveScaffold::Actions - module FieldSearch - include ActiveScaffold::Actions::CommonSearch - def self.included(base) - base.before_filter :search_authorized_filter, :only => :show_search - base.before_filter :store_search_params_into_session, :only => [:list, :index] - base.before_filter :do_search, :only => [:list, :index] - base.helper_method :field_search_params - end - - # FieldSearch uses params[:search] and not @record because search conditions do not always pass the Model's validations. - # This facilitates for example, textual searches against associations via .search_sql - def show_search - @record = active_scaffold_config.model.new - respond_to_action(:field_search) - end - - protected - def field_search_params - search_params || {} - end - - def field_search_respond_to_html - render(:action => "field_search") - end - - def field_search_respond_to_js - render(:partial => "field_search") - end - - def do_search - unless search_params.nil? - text_search = active_scaffold_config.field_search.text_search - search_conditions = [] - columns = active_scaffold_config.field_search.columns - search_params.each do |key, value| - next unless columns.include? key - search_conditions << self.class.condition_for_column(active_scaffold_config.columns[key], value, text_search) - end - search_conditions.compact! - self.active_scaffold_conditions = merge_conditions(self.active_scaffold_conditions, *search_conditions) - @filtered = !search_conditions.blank? - - includes_for_search_columns = columns.collect{ |column| column.includes}.flatten.uniq.compact - self.active_scaffold_includes.concat includes_for_search_columns - - active_scaffold_config.list.user.page = nil - end - end - - private - def search_authorized_filter - link = active_scaffold_config.field_search.link || active_scaffold_config.field_search.class.link - raise ActiveScaffold::ActionNotAllowed unless self.send(link.security_method) - end - def field_search_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.field_search.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/list.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/list.rb deleted file mode 100644 index a977d73..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/list.rb +++ /dev/null @@ -1,82 +0,0 @@ -module ActiveScaffold::Actions - module List - def self.included(base) - base.before_filter :list_authorized_filter, :only => [:index, :row, :list] - base.send :include, ActiveScaffold::Actions::Mark if base.active_scaffold_config.list.mark_records - end - - def index - list - end - - # get just a single row - def row - render :partial => 'list_record', :locals => {:record => find_if_allowed(params[:id], :read)} - end - - def list - do_list - do_new if active_scaffold_config.list.always_show_create - @record ||= active_scaffold_config.model.new if active_scaffold_config.list.always_show_search - respond_to_action(:list) - end - - protected - def list_respond_to_html - render :action => 'list', :layout => !respond_to?(:component_request?) || !component_request? - end - def list_respond_to_js - render :action => 'list.js' - end - def list_respond_to_xml - render :xml => response_object.to_xml(:only => active_scaffold_config.list.columns.names), :content_type => Mime::XML, :status => response_status - end - def list_respond_to_json - render :text => response_object.to_json(:only => active_scaffold_config.list.columns.names), :content_type => Mime::JSON, :status => response_status - end - def list_respond_to_yaml - render :text => Hash.from_xml(response_object.to_xml(:only => active_scaffold_config.list.columns.names)).to_yaml, :content_type => Mime::YAML, :status => response_status - end - - def set_includes_for_list_columns - includes_for_list_columns = active_scaffold_config.list.columns.collect{ |c| c.includes }.flatten.uniq.compact - self.active_scaffold_includes.concat includes_for_list_columns - end - - # The actual algorithm to prepare for the list view - def do_list - set_includes_for_list_columns - - options = { :sorting => active_scaffold_config.list.user.sorting, - :count_includes => active_scaffold_config.list.user.count_includes } - paginate = (params[:format].nil?) ? (accepts? :html, :js) : ['html', 'js'].include?(params[:format]) - if paginate - options.merge!({ - :per_page => active_scaffold_config.list.user.per_page, - :page => active_scaffold_config.list.user.page, - :pagination => active_scaffold_config.list.pagination - }) - end - - page = find_page(options) - if page.items.blank? && !page.pager.infinite? - page = page.pager.last - active_scaffold_config.list.user.page = page.number - end - @page, @records = page, page.items - end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def list_authorized? - authorized_for?(:crud_type => :read) - end - private - def list_authorized_filter - raise ActiveScaffold::ActionNotAllowed unless list_authorized? - end - def list_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.list.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/mark.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/mark.rb deleted file mode 100644 index d8bd7b7..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/mark.rb +++ /dev/null @@ -1,72 +0,0 @@ -module ActiveScaffold::Actions - module Mark - - def self.included(base) - base.before_filter :mark_authorized?, :only => :mark - #base.prepend_before_filter :assign_marked_records_to_model - base.helper_method :marked_records - end - - def mark - if mark? - do_mark - else - do_unmark - end - mark_respond_to_js - end - - protected - # We need to give the ActiveRecord classes a handle to currently marked records. We don't want to just pass the object, - # because the object may change. So we give ActiveRecord a proc that ties to the - # marked_records_method on this ApplicationController. - def assign_marked_records_to_model - active_scaffold_config.model.marked_records_proc = proc {send(:marked_records)} - end - - def mark? - params[:value] == 'true' - end - - def do_mark - if params[:id] - marked_records << params[:id] - else - each_record_in_scope {|record| marked_records << record.id.to_s} - end - end - - def do_unmark - if params[:id] - marked_records.delete params[:id] - else - each_record_in_scope {|record| marked_records.delete(record.id.to_s)} - end - end - - def each_record_in_scope - do_search if respond_to? :do_search - set_includes_for_list_columns - find_options = finder_options - find_options[:include] = nil if find_options[:conditions].nil? - beginning_of_chain.all(find_options).each {|record| yield record} - end - - def mark_respond_to_js - if params[:id] - do_search if respond_to? :do_search - set_includes_for_list_columns - count = beginning_of_chain.count(count_options(finder_options, active_scaffold_config.list.user.count_includes)) - @mark = marked_records.length >= count - else - @mark = mark? - end - end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def mark_authorized? - authorized_for?(:crud_type => :read) - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/nested.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/nested.rb deleted file mode 100644 index f4d416c..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/nested.rb +++ /dev/null @@ -1,217 +0,0 @@ -module ActiveScaffold::Actions - # The Nested module basically handles automatically linking controllers together. It does this by creating column links with the right parameters, and by providing any supporting systems (like a /:controller/nested action for returning associated scaffolds). - module Nested - - def self.included(base) - super - base.module_eval do - include ActiveScaffold::Actions::Nested::ChildMethods if active_scaffold_config.model.reflect_on_all_associations.any? {|a| a.macro == :has_and_belongs_to_many} - end - base.before_filter :include_habtm_actions - base.helper_method :nested_habtm? - end - - def nested - do_nested - respond_to_action(:nested) - end - - protected - def nested_respond_to_html - render :partial => 'nested', :layout => true - end - def nested_respond_to_js - render :partial => 'nested' - end - # A simple method to find the record we'll be nesting *from* - # May be overridden to customize the behavior - def do_nested - @record = find_if_allowed(params[:id], :read) - end - - def nested_authorized? - true - end - - def include_habtm_actions - if nested_habtm? - # Production mode is ok with adding a link everytime the scaffold is nested - we ar not ok with that. - active_scaffold_config.action_links.add('new_existing', :label => :add_existing, :type => :collection, :security_method => :add_existing_authorized?) unless active_scaffold_config.action_links['new_existing'] - if active_scaffold_config.nested.shallow_delete - active_scaffold_config.action_links.add('destroy_existing', :label => :remove, :type => :member, :confirm => :are_you_sure_to_delete, :method => :delete, :position => false, :security_method => :delete_existing_authorized?) unless active_scaffold_config.action_links['destroy_existing'] - active_scaffold_config.action_links.delete("delete") if active_scaffold_config.action_links['delete'] - end - else - # Production mode is caching this link into a non nested scaffold - active_scaffold_config.action_links.delete('new_existing') if active_scaffold_config.action_links['new_existing'] - - if active_scaffold_config.nested.shallow_delete - active_scaffold_config.action_links.delete("destroy_existing") if active_scaffold_config.action_links['destroy_existing'] - active_scaffold_config.action_links.add(ActiveScaffold::Config::Delete.link) unless active_scaffold_config.action_links['delete'] - end - - end - end - - def nested? - !params[:nested].nil? - end - - def nested_habtm? - begin - a = active_scaffold_config.columns[nested_association] - return a.association.macro == :has_and_belongs_to_many if a and nested? - false - rescue - raise ActiveScaffold::MalformedConstraint, constraint_error(active_scaffold_config.model, nested_association), caller - end - end - - def nested_association - return active_scaffold_constraints.keys.to_s.to_sym if nested? - nil - end - - def nested_parent_id - return active_scaffold_constraints.values.to_s if nested? - nil - end - private - def nested_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.nested.formats).uniq - end - end -end - -module ActiveScaffold::Actions::Nested - module ChildMethods - - def self.included(base) - super - base.verify :method => :post, - :only => :add_existing, - :redirect_to => { :action => :index } - end - - def new_existing - do_new - respond_to_action(:new_existing) - end - - def add_existing - do_add_existing - respond_to_action(:add_existing) - end - - def destroy_existing - return redirect_to(params.merge(:action => :delete)) if request.get? - do_destroy_existing - respond_to_action(:destroy_existing) - end - - protected - def new_existing_respond_to_html - if successful? - render(:action => 'add_existing_form') - else - return_to_main - end - end - def new_existing_respond_to_js - render(:partial => 'add_existing_form') - end - def add_existing_respond_to_html - if successful? - flash[:info] = as_(:created_model, :model => @record.to_label) - return_to_main - else - render(:action => 'add_existing_form') - end - end - def add_existing_respond_to_js - if successful? - render :action => 'add_existing' - else - render :action => 'form_messages' - end - end - def add_existing_respond_to_xml - render :xml => response_object.to_xml(:only => active_scaffold_config.list.columns.names), :content_type => Mime::XML, :status => response_status - end - def add_existing_respond_to_json - render :text => response_object.to_json(:only => active_scaffold_config.list.columns.names), :content_type => Mime::JSON, :status => response_status - end - def add_existing_respond_to_yaml - render :text => Hash.from_xml(response_object.to_xml(:only => active_scaffold_config.list.columns.names)).to_yaml, :content_type => Mime::YAML, :status => response_status - end - def destroy_existing_respond_to_html - flash[:info] = as_(:deleted_model, :model => @record.to_label) - return_to_main - end - - def destroy_existing_respond_to_js - render(:action => 'destroy') - end - - def destroy_existing_respond_to_xml - render :xml => successful? ? "" : response_object.to_xml(:only => active_scaffold_config.list.columns.names), :content_type => Mime::XML, :status => response_status - end - - def destroy_existing_respond_to_json - render :text => successful? ? "" : response_object.to_json(:only => active_scaffold_config.list.columns.names), :content_type => Mime::JSON, :status => response_status - end - - def destroy_existing_respond_to_yaml - render :text => successful? ? "" : Hash.from_xml(response_object.to_xml(:only => active_scaffold_config.list.columns.names)).to_yaml, :content_type => Mime::YAML, :status => response_status - end - - def add_existing_authorized? - true - end - def delete_existing_authorized? - true - end - - def after_create_save(record) - if params[:association_macro] == :has_and_belongs_to_many - params[:associated_id] = record - do_add_existing - end - end - - def nested_action_from_params - return params[:parent_model].constantize, nested_parent_id, params[:parent_column] - end - - # The actual "add_existing" algorithm - def do_add_existing - parent_model, id, association = nested_action_from_params - parent_record = find_if_allowed(id, :update, parent_model) - @record = active_scaffold_config.model.find(params[:associated_id]) - parent_record.send(association) << @record - parent_record.save - end - - def do_destroy_existing - if active_scaffold_config.nested.shallow_delete - parent_model, id, association = nested_action_from_params - @record = find_if_allowed(id, :update, parent_model) - collection = @record.send(association) - assoc_record = collection.find(params[:id]) - collection.delete(assoc_record) - else - do_destroy - end - end - private - def new_existing_formats - (default_formats + active_scaffold_config.formats).uniq - end - def add_existing_formats - (default_formats + active_scaffold_config.formats).uniq - end - def destroy_existing_formats - (default_formats + active_scaffold_config.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/search.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/search.rb deleted file mode 100644 index 8835099..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/search.rb +++ /dev/null @@ -1,54 +0,0 @@ -module ActiveScaffold::Actions - module Search - include ActiveScaffold::Actions::CommonSearch - def self.included(base) - base.before_filter :search_authorized_filter, :only => :show_search - base.before_filter :store_search_params_into_session, :only => [:list, :index] - base.before_filter :do_search, :only => [:list, :index] - base.helper_method :search_params - end - - def show_search - respond_to_action(:search) - end - - protected - def search_respond_to_html - render(:action => "search") - end - def search_respond_to_js - render(:partial => "search") - end - def do_search - query = search_params.to_s.strip rescue '' - - unless query.empty? - columns = active_scaffold_config.search.columns - text_search = active_scaffold_config.search.text_search - query = query.split(active_scaffold_config.search.split_terms) if active_scaffold_config.search.split_terms - search_conditions = self.class.create_conditions_for_columns(query, columns, text_search) - self.active_scaffold_conditions = merge_conditions(self.active_scaffold_conditions, search_conditions) - @filtered = !search_conditions.blank? - - includes_for_search_columns = columns.collect{ |column| column.includes}.flatten.uniq.compact - self.active_scaffold_includes.concat includes_for_search_columns - - active_scaffold_config.list.user.page = nil - end - end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def search_authorized? - authorized_for?(:crud_type => :read) - end - private - def search_authorized_filter - link = active_scaffold_config.search.link || active_scaffold_config.search.class.link - raise ActiveScaffold::ActionNotAllowed unless self.send(link.security_method) - end - def search_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.search.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/show.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/show.rb deleted file mode 100644 index 317c9d3..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/show.rb +++ /dev/null @@ -1,54 +0,0 @@ -module ActiveScaffold::Actions - module Show - def self.included(base) - base.before_filter :show_authorized_filter, :only => :show - end - - def show - do_show - successful? - respond_to_action(:show) - end - - protected - - def show_respond_to_json - render :text => response_object.to_json(:only => active_scaffold_config.show.columns.names), :content_type => Mime::JSON, :status => response_status - end - - def show_respond_to_yaml - render :text => Hash.from_xml(response_object.to_xml(:only => active_scaffold_config.show.columns.names)).to_yaml, :content_type => Mime::YAML, :status => response_status - end - - def show_respond_to_xml - render :xml => response_object.to_xml(:only => active_scaffold_config.show.columns.names), :content_type => Mime::XML, :status => response_status - end - - def show_respond_to_js - render :partial => 'show' - end - - def show_respond_to_html - render :action => 'show' - end - # A simple method to retrieve and prepare a record for showing. - # May be overridden to customize show routine - def do_show - @record = find_if_allowed(params[:id], :read) - end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def show_authorized? - authorized_for?(:crud_type => :read) - end - private - def show_authorized_filter - link = active_scaffold_config.show.link || active_scaffold_config.show.class.link - raise ActiveScaffold::ActionNotAllowed unless self.send(link.security_method) - end - def show_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.show.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/subform.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/subform.rb deleted file mode 100644 index 12e2808..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/subform.rb +++ /dev/null @@ -1,17 +0,0 @@ -module ActiveScaffold::Actions - module Subform - def edit_associated - @parent_record = params[:id].nil? ? active_scaffold_config.model.new : find_if_allowed(params[:id], :update) - @column = active_scaffold_config.columns[params[:association]] - - # NOTE: we don't check whether the user is allowed to update this record, because if not, we'll still let them associate the record. we'll just refuse to do more than associate, is all. - @record = @column.association.klass.find(params[:associated_id]) if params[:associated_id] - @record ||= @column.association.klass.new - - @scope = "[#{@column.name}]" - @scope += (@record.new_record?) ? "[#{(Time.now.to_f*1000).to_i.to_s}]" : "[#{@record.id}]" if @column.plural_association? - - render :action => 'edit_associated' - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/update.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/actions/update.rb deleted file mode 100644 index a37b9bf..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/actions/update.rb +++ /dev/null @@ -1,129 +0,0 @@ -module ActiveScaffold::Actions - module Update - def self.included(base) - base.before_filter :update_authorized_filter, :only => [:edit, :update] - base.verify :method => [:post, :put], - :only => :update, - :redirect_to => { :action => :index } - end - - def edit - do_edit - respond_to_action(:edit) - end - - def update - do_update - respond_to_action(:update) - end - - # for inline (inlist) editing - def update_column - do_update_column - render :action => 'update_column' - end - - protected - def edit_respond_to_html - if successful? - render(:action => 'update') - else - return_to_main - end - end - def edit_respond_to_js - render(:partial => 'update_form') - end - def update_respond_to_html - if params[:iframe]=='true' # was this an iframe post ? - responds_to_parent do - render :action => 'on_update.js' - end - else # just a regular post - if successful? - flash[:info] = as_(:updated_model, :model => @record.to_label) - return_to_main - else - render(:action => 'update') - end - end - end - def update_respond_to_js - render :action => 'on_update' - end - def update_respond_to_xml - render :xml => response_object.to_xml(:only => active_scaffold_config.update.columns.names), :content_type => Mime::XML, :status => response_status - end - def update_respond_to_json - render :text => response_object.to_json(:only => active_scaffold_config.update.columns.names), :content_type => Mime::JSON, :status => response_status - end - def update_respond_to_yaml - render :text => Hash.from_xml(response_object.to_xml(:only => active_scaffold_config.update.columns.names)).to_yaml, :content_type => Mime::YAML, :status => response_status - end - # A simple method to find and prepare a record for editing - # May be overridden to customize the record (set default values, etc.) - def do_edit - @record = find_if_allowed(params[:id], :update) - end - - # A complex method to update a record. The complexity comes from the support for subforms, and saving associated records. - # If you want to customize this algorithm, consider using the +before_update_save+ callback - def do_update - do_edit - begin - active_scaffold_config.model.transaction do - @record = update_record_from_params(@record, active_scaffold_config.update.columns, params[:record]) - before_update_save(@record) - self.successful = [@record.valid?, @record.associated_valid?].all? {|v| v == true} # this syntax avoids a short-circuit - if successful? - @record.save! and @record.save_associated! - after_update_save(@record) - end - end - rescue ActiveRecord::RecordInvalid - rescue ActiveRecord::StaleObjectError - @record.errors.add_to_base as_(:version_inconsistency) - self.successful=false - rescue ActiveRecord::RecordNotSaved - @record.errors.add_to_base as_(:failed_to_save_record) if @record.errors.empty? - self.successful = false - end - end - - def do_update_column - @record = active_scaffold_config.model.find(params[:id]) - if @record.authorized_for?(:crud_type => :update, :column => params[:column]) - column = active_scaffold_config.columns[params[:column].to_sym] - params[:value] ||= @record.column_for_attribute(params[:column]).default unless @record.column_for_attribute(params[:column]).nil? || @record.column_for_attribute(params[:column]).null - params[:value] = column_value_from_param_value(@record, column, params[:value]) unless column.nil? - @record.send("#{params[:column]}=", params[:value]) - before_update_save(@record) - @record.save - after_update_save(@record) - end - end - - # override this method if you want to inject data in the record (or its associated objects) before the save - def before_update_save(record); end - - # override this method if you want to do something after the save - def after_update_save(record); end - - # The default security delegates to ActiveRecordPermissions. - # You may override the method to customize. - def update_authorized? - authorized_for?(:crud_type => :update) - end - private - def update_authorized_filter - link = active_scaffold_config.update.link || active_scaffold_config.update.class.link - raise ActiveScaffold::ActionNotAllowed unless self.send(link.security_method) - end - def edit_formats - (default_formats + active_scaffold_config.formats).uniq - end - def update_formats - (default_formats + active_scaffold_config.formats + active_scaffold_config.update.formats).uniq - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/attribute_params.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/attribute_params.rb deleted file mode 100644 index 0600f7f..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/attribute_params.rb +++ /dev/null @@ -1,191 +0,0 @@ -module ActiveScaffold - # Provides support for param hashes assumed to be model attributes. - # Support is primarily needed for creating/editing associated records using a nested hash structure. - # - # Paradigm Params Hash (should write unit tests on this): - # params[:record] = { - # # a simple record attribute - # 'name' => 'John', - # # a plural association hash - # 'roles' => { - # # associate with an existing role - # '5' => {'id' => 5} - # # associate with an existing role and edit it - # '6' => {'id' => 6, 'name' => 'designer'} - # # create and associate a new role - # '124521' => {'name' => 'marketer'} - # } - # # a singular association hash - # 'location' => {'id' => 12, 'city' => 'New York'} - # } - # - # Simpler association structures are also supported, like: - # params[:record] = { - # # a simple record attribute - # 'name' => 'John', - # # a plural association ... all ids refer to existing records - # 'roles' => ['5', '6'], - # # a singular association ... all ids refer to existing records - # 'location' => '12' - # } - module AttributeParams - protected - # Takes attributes (as from params[:record]) and applies them to the parent_record. Also looks for - # association attributes and attempts to instantiate them as associated objects. - # - # This is a secure way to apply params to a record, because it's based on a loop over the columns - # set. The columns set will not yield unauthorized columns, and it will not yield unregistered columns. - def update_record_from_params(parent_record, columns, attributes) - crud_type = parent_record.new_record? ? :create : :update - return parent_record unless parent_record.authorized_for?(:crud_type => crud_type) - - multi_parameter_attributes = {} - attributes.each do |k, v| - next unless k.include? '(' - column_name = k.split('(').first.to_sym - multi_parameter_attributes[column_name] ||= [] - multi_parameter_attributes[column_name] << [k, v] - end - - columns.each :for => parent_record, :crud_type => crud_type, :flatten => true do |column| - # Set any passthrough parameters that may be associated with this column (ie, file column "keep" and "temp" attributes) - unless column.params.empty? - column.params.each{|p| parent_record.send("#{p}=", attributes[p]) if attributes.has_key? p} - end - - if multi_parameter_attributes.has_key? column.name - parent_record.send(:assign_multiparameter_attributes, multi_parameter_attributes[column.name]) - elsif attributes.has_key? column.name - value = column_value_from_param_value(parent_record, column, attributes[column.name]) - - # we avoid assigning a value that already exists because otherwise has_one associations will break (AR bug in has_one_association.rb#replace) - parent_record.send("#{column.name}=", value) unless parent_record.send(column.name) == value - - # plural associations may not actually appear in the params if all of the options have been unselected or cleared away. - # the "form_ui" check is necessary, becuase without it we have problems - # with subforms. the UI cuts out deep associations, which means they're not present in the - # params even though they're in the columns list. the result is that associations were being - # emptied out way too often. - elsif column.form_ui and column.plural_association? - parent_record.send("#{column.name}=", []) - end - end - - if parent_record.new_record? - parent_record.class.reflect_on_all_associations.each do |a| - next unless [:has_one, :has_many].include?(a.macro) and not (a.options[:through] || a.options[:finder_sql]) - next unless association_proxy = parent_record.send(a.name) - - raise ActiveScaffold::ReverseAssociationRequired, "Association #{a.name}: In order to support :has_one and :has_many where the parent record is new and the child record(s) validate the presence of the parent, ActiveScaffold requires the reverse association (the belongs_to)." unless a.reverse - - association_proxy = [association_proxy] if a.macro == :has_one - association_proxy.each { |record| record.send("#{a.reverse}=", parent_record) } - end - end - - parent_record - end - - def manage_nested_record_from_params(parent_record, column, attributes) - record = find_or_create_for_params(attributes, column, parent_record) - if record - record_columns = active_scaffold_config_for(column.association.klass).subform.columns - update_record_from_params(record, record_columns, attributes) - record.unsaved = true - end - record - end - - def column_value_from_param_value(parent_record, column, value) - # convert the value, possibly by instantiating associated objects - if value.is_a?(Hash) - # this is just for backwards compatibility. we should clean this up in 2.0. - if column.form_ui == :select - ids = if column.singular_association? - value[:id] - else - value.values.collect {|hash| hash[:id]} - end - (ids and not ids.empty?) ? column.association.klass.find(ids) : nil - - elsif column.singular_association? - manage_nested_record_from_params(parent_record, column, value) - elsif column.plural_association? - # sort by id or temporary id so new records are created in the same order as user write them - value.sort.collect {|key_value_pair| manage_nested_record_from_params(parent_record, column, key_value_pair[1])}.compact - else - value - end - else - if column.singular_association? - # it's a single id - column.association.klass.find(value) if value and not value.empty? - elsif column.plural_association? - # it's an array of ids - column.association.klass.find(value) if value and not value.empty? - elsif column.column && column.column.number? && column.options[:format] - column.number_to_native(value) - else - # convert empty strings into nil. this works better with 'null => true' columns (and validations), - # and 'null => false' columns should just convert back to an empty string. - # ... but we can at least check the ConnectionAdapter::Column object to see if nulls are allowed - value = nil if value.is_a? String and value.empty? and !column.column.nil? and column.column.null - value - end - end - end - - # Attempts to create or find an instance of klass (which must be an ActiveRecord object) from the - # request parameters given. If params[:id] exists it will attempt to find an existing object - # otherwise it will build a new one. - def find_or_create_for_params(params, parent_column, parent_record) - current = parent_record.send(parent_column.name) - klass = parent_column.association.klass - return nil if parent_column.show_blank_record?(current) and attributes_hash_is_empty?(params, klass) - - if params.has_key? :id - # modifying the current object of a singular association - if current and current.is_a? ActiveRecord::Base and current.id.to_s == params[:id] - return current - # modifying one of the current objects in a plural association - elsif current and current.respond_to?(:any?) and current.any? {|o| o.id.to_s == params[:id]} - return current.detect {|o| o.id.to_s == params[:id]} - # attaching an existing but not-current object - else - return klass.find(params[:id]) - end - else - if klass.authorized_for?(:crud_type => :create) - if parent_column.singular_association? - return parent_record.send("build_#{parent_column.name}") - else - return parent_record.send(parent_column.name).build - end - end - end - end - - # Determines whether the given attributes hash is "empty". - # This isn't a literal emptiness - it's an attempt to discern whether the user intended it to be empty or not. - def attributes_hash_is_empty?(hash, klass) - hash.all? do |key,value| - # convert any possible multi-parameter attributes like 'created_at(5i)' to simply 'created_at' - column_name = key.to_s.split('(').first - column = klass.columns_hash[column_name] - - # booleans and datetimes will always have a value. so we ignore them when checking whether the hash is empty. - # this could be a bad idea. but the current situation (excess record entry) seems worse. - next true if column and [:boolean, :datetime, :date, :time].include?(column.type) - - # defaults are pre-filled on the form. we can't use them to determine if the user intends a new row. - next true if column and value == column.default.to_s - - if value.is_a?(Hash) - attributes_hash_is_empty?(value, klass) - else - value.respond_to?(:empty?) ? value.empty? : false - end - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/base.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/base.rb deleted file mode 100644 index b83cae5..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/base.rb +++ /dev/null @@ -1,62 +0,0 @@ -module ActiveScaffold::Config - class Base - include ActiveScaffold::Configurable - extend ActiveScaffold::Configurable - - def initialize(core_config) - @core = core_config - end - - def self.inherited(subclass) - class << subclass - # the crud type of the action. possible values are :create, :read, :update, :delete, and nil. - # this is not a setting for the developer. it's self-description for the actions. - def crud_type; @crud_type; end - - protected - - def crud_type=(val) - raise ArgumentError, "unknown CRUD type #{val}" unless [:create, :read, :update, :delete].include?(val.to_sym) - @crud_type = val.to_sym - end - end - end - # delegate - def crud_type; self.class.crud_type end - - def label(model = nil) - as_(@label, :model => model || @core.label(:count => 1)) - end - - # the user property gets set to the instantiation of the local UserSettings class during the automatic instantiation of this class. - attr_accessor :user - - class UserSettings - def initialize(conf, storage, params) - # the session hash relevant to this action - @session = storage - # all the request params - @params = params - # the configuration object for this action - @conf = conf - end - end - - def formats - @formats ||= [] - end - - def formats=(val) - @formats=val - end - - private - - def columns=(val) - @columns = ActiveScaffold::DataStructures::ActionColumns.new(*val) - @columns.action = self - @columns.set_columns(@core.columns) if @columns.respond_to?(:set_columns) - @columns - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/core.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/core.rb deleted file mode 100644 index 1d8ea19..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/core.rb +++ /dev/null @@ -1,229 +0,0 @@ -module ActiveScaffold::Config - class Core < ActiveScaffold::Config::Base - # global level configuration - # -------------------------- - - # provides read/write access to the global Actions DataStructure - cattr_reader :actions - def self.actions=(val) - @@actions = ActiveScaffold::DataStructures::Actions.new(*val) - end - self.actions = [:create, :list, :search, :update, :delete, :show, :nested, :subform] - - # configures where the ActiveScaffold plugin itself is located. there is no instance version of this. - cattr_accessor :plugin_directory - @@plugin_directory = File.expand_path(__FILE__).match(/vendor\/plugins\/([^\/]*)/)[1] - - # lets you specify a global ActiveScaffold frontend. - cattr_accessor :frontend - @@frontend = :default - - # lets you specify a global ActiveScaffold theme for your frontend. - cattr_accessor :theme - @@theme = :default - - # lets you disable the DHTML history - def self.dhtml_history=(val) - @@dhtml_history = val - end - def self.dhtml_history? - @@dhtml_history ? true : false - end - @@dhtml_history = true - - # action links are used by actions to tie together. you can use them, too! this is a collection of ActiveScaffold::DataStructures::ActionLink objects. - cattr_reader :action_links - @@action_links = ActiveScaffold::DataStructures::ActionLinks.new - - # access to the permissions configuration. - # configuration options include: - # * current_user_method - what method on the controller returns the current user. default: :current_user - # * default_permission - what the default permission is. default: true - def self.security - ActiveRecordPermissions - end - - # columns that should be ignored for every model. these should be metadata columns like change dates, versions, etc. - # values in this array may be symbols or strings. - def self.ignore_columns - @@ignore_columns - end - def self.ignore_columns=(val) - @@ignore_columns = ActiveScaffold::DataStructures::Set.new(*val) - end - @@ignore_columns = ActiveScaffold::DataStructures::Set.new - - # lets you specify whether add a create link for each sti child - cattr_accessor :sti_create_links - - # instance-level configuration - # ---------------------------- - - # provides read/write access to the local Actions DataStructure - attr_reader :actions - def actions=(args) - @actions = ActiveScaffold::DataStructures::Actions.new(*args) - end - - # provides read/write access to the local Columns DataStructure - attr_reader :columns - def columns=(val) - @columns._inheritable = val.collect {|c| c.to_sym} - # Add virtual columns - @columns << val.collect {|c| c.to_sym unless @columns[c.to_sym]}.compact - end - - # lets you override the global ActiveScaffold frontend for a specific controller - attr_accessor :frontend - - # lets you override the global ActiveScaffold theme for a specific controller - attr_accessor :theme - - # lets you specify whether add a create link for each sti child for a specific controller - attr_accessor :sti_create_links - def add_sti_create_links? - self.sti_create_links and not self.sti_children.nil? - end - - # action links are used by actions to tie together. they appear as links for each record, or general links for the ActiveScaffold. - attr_reader :action_links - - # a generally-applicable name for this ActiveScaffold ... will be used for generating page/section headers - attr_writer :label - def label(options={}) - as_(@label, options) || model.human_name(options.merge(:default => options[:count].to_i == 1 ? model.name : model.name.pluralize)) - end - - # STI children models, use an array of model names - attr_accessor :sti_children - - ## - ## internal usage only below this point - ## ------------------------------------ - - def initialize(model_id) - # model_id is the only absolutely required configuration value. it is also not publicly accessible. - @model_id = model_id.to_s.pluralize.singularize - - # inherit the actions list directly from the global level - @actions = self.class.actions.clone - - # create a new default columns datastructure, since it doesn't make sense before now - attribute_names = self.model.columns.collect{ |c| c.name.to_sym }.sort_by { |c| c.to_s } - association_column_names = self.model.reflect_on_all_associations.collect{ |a| a.name.to_sym }.sort_by { |c| c.to_s } - @columns = ActiveScaffold::DataStructures::Columns.new(self.model, attribute_names + association_column_names) - - # and then, let's remove some columns from the inheritable set. - @columns.exclude(*self.class.ignore_columns) - @columns.exclude(*@columns.find_all { |c| c.column and (c.column.primary or c.column.name =~ /(_id|_count)$/) }.collect {|c| c.name}) - @columns.exclude(*self.model.reflect_on_all_associations.collect{|a| :"#{a.name}_type" if a.options[:polymorphic]}.compact) - - # inherit the global frontend - @frontend = self.class.frontend - @theme = self.class.theme - @sti_create_links = self.class.sti_create_links - - # inherit from the global set of action links - @action_links = self.class.action_links.clone - end - - # To be called after your finished configuration - def _load_action_columns - ActiveScaffold::DataStructures::ActionColumns.class_eval {include ActiveScaffold::DataStructures::ActionColumns::AfterConfiguration} - - # then, register the column objects - self.actions.each do |action_name| - action = self.send(action_name) - next unless action.respond_to? :columns - action.columns.set_columns(self.columns) - end - end - - # To be called after your finished configuration - def _configure_sti - column = self.model.inheritance_column - if sti_create_links - self.columns[column].form_ui ||= :hidden - else - self.columns[column].form_ui ||= :select - self.columns[column].options ||= {} - self.columns[column].options[:options] = self.sti_children.collect do |model_name| - [model_name.to_s.camelize.constantize.human_name, model_name.to_s.camelize] - end - end - end - - # To be called after include action modules - def _add_sti_create_links - new_action_link = @action_links['new'] - unless new_action_link.nil? - @action_links.delete('new') - self.sti_children.each do |child| - new_sti_link = Marshal.load(Marshal.dump(new_action_link)) # deep clone - new_sti_link.label = as_(:create_model, :model => child.to_s.camelize.constantize.human_name) - new_sti_link.parameters = {model.inheritance_column => child} - @action_links.add(new_sti_link) - end - end - end - - # configuration routing. - # we want to route calls named like an activated action to that action's global or local Config class. - # --------------------------- - def method_missing(name, *args) - @action_configs ||= {} - titled_name = name.to_s.camelcase - underscored_name = name.to_s.underscore.to_sym - klass = "ActiveScaffold::Config::#{titled_name}".constantize rescue nil - if klass - if @actions.include? underscored_name - return @action_configs[underscored_name] ||= klass.new(self) - else - raise "#{titled_name} is not enabled. Please enable it or remove any references in your configuration (e.g. config.#{underscored_name}.columns = [...])." - end - end - super - end - - def self.method_missing(name, *args) - klass = "ActiveScaffold::Config::#{name.to_s.titleize}".constantize rescue nil - if @@actions.include? name.to_s.underscore and klass - return eval("ActiveScaffold::Config::#{name.to_s.titleize}") - end - super - end - # some utility methods - # -------------------- - - def model_id - @model_id - end - - def model - @model ||= @model_id.to_s.camelize.constantize - end - - # warning - this won't work as a per-request dynamic attribute in rails 2.0. You'll need to interact with Controller#generic_view_paths - def inherited_view_paths - @inherited_view_paths||=[] - end - - # must be a class method so the layout doesn't depend on a controller that uses active_scaffold - # note that this is unaffected by per-controller frontend configuration. - def self.asset_path(filename, frontend = self.frontend) - "active_scaffold/#{frontend}/#{filename}" - end - - # must be a class method so the layout doesn't depend on a controller that uses active_scaffold - # note that this is unaffected by per-controller frontend configuration. - def self.javascripts(frontend = self.frontend) - javascript_dir = File.join(Rails.public_path, "javascripts", asset_path('', frontend)) - Dir.entries(javascript_dir).reject { |e| !e.match(/\.js$/) or (!self.dhtml_history? and e.match('dhtml_history')) } - end - - def self.available_frontends - frontends_dir = File.join(Rails.root, "vendor", "plugins", ActiveScaffold::Config::Core.plugin_directory, "frontends") - Dir.entries(frontends_dir).reject { |e| e.match(/^\./) } # Get rid of files that start with . - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/create.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/create.rb deleted file mode 100644 index 5a8e962..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/create.rb +++ /dev/null @@ -1,36 +0,0 @@ -module ActiveScaffold::Config - class Create < ActiveScaffold::Config::Form - self.crud_type = :create - def initialize(core_config) - super - @label = :create_model - self.persistent = self.class.persistent - self.action_after_create = self.class.action_after_create - end - - # global level configuration - # -------------------------- - # the ActionLink for this action - def self.link - @@link - end - def self.link=(val) - @@link = val - end - @@link = ActiveScaffold::DataStructures::ActionLink.new('new', :label => :create_new, :type => :collection, :security_method => :create_authorized?) - - # whether the form stays open after a create or not - cattr_accessor :persistent - @@persistent = false - - # whether update form is opened after a create or not - cattr_accessor :action_after_create - @@action_after_create = nil - - # whether the form stays open after a create or not - attr_accessor :persistent - - # whether the form stays open after a create or not - attr_accessor :action_after_create - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/delete.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/delete.rb deleted file mode 100644 index b23b5ac..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/delete.rb +++ /dev/null @@ -1,24 +0,0 @@ -module ActiveScaffold::Config - class Delete < Base - self.crud_type = :delete - - def initialize(core_config) - super - # start with the ActionLink defined globally - @link = self.class.link.clone - end - - # global level configuration - # -------------------------- - - # the ActionLink for this action - cattr_accessor :link - @@link = ActiveScaffold::DataStructures::ActionLink.new('delete', :label => :delete, :type => :member, :confirm => :are_you_sure_to_delete, :crud_type => :delete, :method => :delete, :position => false, :security_method => :delete_authorized?) - - # instance-level configuration - # ---------------------------- - - # the ActionLink for this action - attr_accessor :link - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/field_search.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/field_search.rb deleted file mode 100644 index a6b4ca6..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/field_search.rb +++ /dev/null @@ -1,55 +0,0 @@ -module ActiveScaffold::Config - class FieldSearch < Base - self.crud_type = :read - - def initialize(core_config) - super - @text_search = self.class.text_search - - # start with the ActionLink defined globally - @link = self.class.link.clone - end - - - # global level configuration - # -------------------------- - # the ActionLink for this action - cattr_reader :link - @@link = ActiveScaffold::DataStructures::ActionLink.new('show_search', :label => :search, :type => :collection, :security_method => :search_authorized?) - - # A flag for how the search should do full-text searching in the database: - # * :full: LIKE %?% - # * :start: LIKE ?% - # * :end: LIKE %? - # * false: LIKE ? - # Default is :full - cattr_accessor :text_search - @@text_search = :full - - # instance-level configuration - # ---------------------------- - - # provides access to the list of columns specifically meant for the Search to use - def columns - # we want to delay initializing to the @core.columns set for as long as possible. Too soon and .search_sql will not be available to .searchable? - unless @columns - self.columns = @core.columns._inheritable - self.columns.exclude @core.columns.active_record_class.locking_column.to_sym - end - @columns - end - - public :columns= - - # A flag for how the search should do full-text searching in the database: - # * :full: LIKE %?% - # * :start: LIKE ?% - # * :end: LIKE %? - # * false: LIKE ? - # Default is :full - attr_accessor :text_search - - # the ActionLink for this action - attr_accessor :link - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/form.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/form.rb deleted file mode 100644 index fb4b226..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/form.rb +++ /dev/null @@ -1,42 +0,0 @@ -module ActiveScaffold::Config - class Form < Base - def initialize(core_config) - super - # start with the ActionLink defined globally - @link = self.class.link.clone - - # no global setting here because multipart should only be set for specific forms - @multipart = false - end - - # global level configuration - # -------------------------- - - # instance-level configuration - # ---------------------------- - - # the ActionLink for this action - attr_accessor :link - - # the label for this Form action. used for the header. - attr_writer :label - - # provides access to the list of columns specifically meant for the Form to use - def columns - unless @columns # lazy evaluation - self.columns = @core.columns._inheritable - self.columns.exclude :created_on, :created_at, :updated_on, :updated_at - self.columns.exclude *@core.columns.collect{|c| c.name if c.polymorphic_association?}.compact - end - @columns - end - - public :columns= - - # whether the form should be multipart - attr_writer :multipart - def multipart? - @multipart ? true : false - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/list.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/list.rb deleted file mode 100644 index 4a69813..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/list.rb +++ /dev/null @@ -1,171 +0,0 @@ -module ActiveScaffold::Config - class List < Base - self.crud_type = :read - - def initialize(core_config) - super - # inherit from global scope - # full configuration path is: defaults => global table => local table - @per_page = self.class.per_page - @page_links_window = self.class.page_links_window - - # originates here - @sorting = ActiveScaffold::DataStructures::Sorting.new(@core.columns) - @sorting.set_default_sorting(@core.model) - - # inherit from global scope - @empty_field_text = self.class.empty_field_text - @association_join_text = self.class.association_join_text - @pagination = self.class.pagination - @show_search_reset = true - @mark_records = self.class.mark_records - end - - # global level configuration - # -------------------------- - # how many records to show per page - cattr_accessor :per_page - @@per_page = 15 - - # how many page links around current page to show - cattr_accessor :page_links_window - @@page_links_window = 2 - - # what string to use when a field is empty - cattr_accessor :empty_field_text - @@empty_field_text = '-' - - # what string to use to join records from plural associations - cattr_accessor :association_join_text - @@association_join_text = ', ' - - # What kind of pagination to use: - # * true: The usual pagination - # * :infinite: Treat the source as having an infinite number of pages (i.e. don't count the records; useful for large tables where counting is slow and we don't really care anyway) - # * false: Disable pagination - cattr_accessor :pagination - @@pagination = true - - # Add a checkbox in front of each record to mark them and use them with a batch action later - cattr_accessor :mark_records - - # instance-level configuration - # ---------------------------- - - # provides access to the list of columns specifically meant for the Table to use - def columns - self.columns = @core.columns._inheritable unless @columns # lazy evaluation - @columns - end - - public :columns= - - # how many rows to show at once - attr_accessor :per_page - - # how many page links around current page to show - attr_accessor :page_links_window - - # What kind of pagination to use: - # * true: The usual pagination - # * :infinite: Treat the source as having an infinite number of pages (i.e. don't count the records; useful for large tables where counting is slow and we don't really care anyway) - # * false: Disable pagination - attr_accessor :pagination - - # what string to use when a field is empty - attr_accessor :empty_field_text - - # what string to use to join records from plural associations - attr_accessor :association_join_text - - # show a link to reset the search next to filtered message - attr_accessor :show_search_reset - - # Add a checkbox in front of each record to mark them and use them with a batch action later - attr_accessor :mark_records - - # the default sorting. should be an array of hashes of {column_name => direction}, e.g. [{:a => 'desc'}, {:b => 'asc'}]. to just sort on one column, you can simply provide a hash, though, e.g. {:a => 'desc'}. - def sorting=(val) - val = [val] if val.is_a? Hash - sorting.clear - val.each { |clause| sorting.add *Array(clause).first } - end - def sorting - @sorting ||= ActiveScaffold::DataStructures::Sorting.new(@core.columns) - end - - # overwrite the includes used for the count sql query - attr_accessor :count_includes - - # the label for this List action. used for the header. - attr_writer :label - def label - @label ? as_(@label, :count => 2) : @core.label(:count => 2) - end - - attr_writer :no_entries_message - def no_entries_message - @no_entries_message ? @no_entries_message : :no_entries - end - - attr_writer :filtered_message - def filtered_message - @filtered_message ? @filtered_message : :filtered - end - - attr_writer :always_show_search - def always_show_search - @always_show_search && !search_partial.blank? - end - - def search_partial - return "search" if @core.actions.include?(:search) - return "field_search" if @core.actions.include?(:field_search) - end - - # always show create - attr_writer :always_show_create - def always_show_create - @always_show_create && @core.actions.include?(:create) - end - - class UserSettings < UserSettings - # This label has alread been localized. - def label - @session[:label] ? @session[:label] : @conf.label - end - - def per_page - @session['per_page'] = @params['limit'].to_i if @params.has_key? 'limit' - @session['per_page'] || @conf.per_page - end - - def page - @session['page'] = @params['page'] if @params.has_key? 'page' - @session['page'] || 1 - end - - def page=(value = nil) - @session['page'] = value - end - - def sorting - # we want to store as little as possible in the session, but we want to return a Sorting data structure. so we recreate it each page load based on session data. - @session['sort'] = [@params['sort'], @params['sort_direction']] if @params['sort'] and @params['sort_direction'] - @session['sort'] = nil if @params['sort_direction'] == 'reset' - - if @session['sort'] - sorting = @conf.sorting.clone - sorting.set(*@session['sort']) - return sorting - else - return @conf.sorting - end - end - - def count_includes - @conf.count_includes - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/nested.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/nested.rb deleted file mode 100644 index 233ae5f..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/nested.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveScaffold::Config - class Nested < Base - self.crud_type = :read - - def initialize(core_config) - super - @label = :add_existing_model - self.shallow_delete = self.class.shallow_delete - end - - # global level configuration - # -------------------------- - cattr_accessor :shallow_delete - @@shallow_delete = false - - # instance-level configuration - # ---------------------------- - attr_accessor :shallow_delete - - # Add a nested ActionLink - def add_link(label, models, options = {}) - options.reverse_merge! :security_method => :nested_authorized?, :position => :after - options.merge! :label => label, :type => :member, :parameters => {:associations => models.join(' ')} - options[:html_options] ||= {} - options[:html_options][:class] = [options[:html_options][:class], models.join(' ')].compact.join(' ') - @core.action_links.add('nested', options) - end - - # the label for this Nested action. used for the header. - attr_writer :label - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/search.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/search.rb deleted file mode 100644 index 11af10d..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/search.rb +++ /dev/null @@ -1,72 +0,0 @@ -module ActiveScaffold::Config - class Search < Base - self.crud_type = :read - - def initialize(core_config) - super - @text_search = self.class.text_search - @live = self.class.live? - @split_terms = self.class.split_terms - - # start with the ActionLink defined globally - @link = self.class.link.clone - end - - - # global level configuration - # -------------------------- - # the ActionLink for this action - cattr_accessor :link - @@link = ActiveScaffold::DataStructures::ActionLink.new('show_search', :label => :search, :type => :collection, :security_method => :search_authorized?) - - # A flag for how the search should do full-text searching in the database: - # * :full: LIKE %?% - # * :start: LIKE ?% - # * :end: LIKE %? - # * false: LIKE ? - # Default is :full - cattr_accessor :text_search - @@text_search = :full - - # whether submits the search as you type - cattr_writer :live - def self.live? - @@live - end - - # instance-level configuration - # ---------------------------- - - # provides access to the list of columns specifically meant for the Search to use - def columns - # we want to delay initializing to the @core.columns set for as long as possible. Too soon and .search_sql will not be available to .searchable? - unless @columns - self.columns = @core.columns.collect{|c| c.name if c.searchable? and c.column and c.column.text?}.compact - end - @columns - end - - public :columns= - - # A flag for how the search should do full-text searching in the database: - # * :full: LIKE %?% - # * :start: LIKE ?% - # * :end: LIKE %? - # * false: LIKE ? - # Default is :full - attr_accessor :text_search - - @@split_terms = " " - cattr_accessor :split_terms - attr_accessor :split_terms - - # the ActionLink for this action - attr_accessor :link - - # whether submits the search as you type - attr_writer :live - def live? - @live - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/show.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/show.rb deleted file mode 100644 index 41357ce..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/show.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveScaffold::Config - class Show < Base - self.crud_type = :read - - def initialize(core_config) - super - # start with the ActionLink defined globally - @link = self.class.link.clone - @label = :show_model - end - - # global level configuration - # -------------------------- - cattr_accessor :link - @@link = ActiveScaffold::DataStructures::ActionLink.new('show', :label => :show, :type => :member, :security_method => :show_authorized?) - # instance-level configuration - # ---------------------------- - - # the ActionLink for this action - attr_accessor :link - # the label for this action. used for the header. - attr_writer :label - - # provides access to the list of columns specifically meant for this action to use - def columns - self.columns = @core.columns._inheritable unless @columns # lazy evaluation - @columns - end - - public :columns= - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/subform.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/subform.rb deleted file mode 100644 index 1915986..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/subform.rb +++ /dev/null @@ -1,35 +0,0 @@ -module ActiveScaffold::Config - class Subform < Base - def initialize(core_config) - super - @layout = self.class.layout # default layout - end - - # global level configuration - # -------------------------- - - cattr_accessor :layout - @@layout = :horizontal - - # instance-level configuration - # ---------------------------- - - attr_accessor :layout - - # provides access to the list of columns specifically meant for the Sub-Form to use - def columns - # we want to delay initializing to the @core.update.columns set for as long as possible. but we have to eventually clone, or else have a configuration "leak" - unless @columns - if @core.actions.include? :update - @columns = @core.update.columns.clone - else - self.columns = @core.columns._inheritable - end - end - - @columns - end - - public :columns= - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/config/update.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/config/update.rb deleted file mode 100644 index 521414e..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/config/update.rb +++ /dev/null @@ -1,36 +0,0 @@ -module ActiveScaffold::Config - class Update < ActiveScaffold::Config::Form - self.crud_type = :update - def initialize(core_config) - super - self.nested_links = self.class.nested_links - self.persistent = self.class.persistent - @label = :update_model - end - - # global level configuration - # -------------------------- - # the ActionLink for this action - def self.link - @@link - end - def self.link=(val) - @@link = val - end - @@link = ActiveScaffold::DataStructures::ActionLink.new('edit', :label => :edit, :type => :member, :security_method => :update_authorized?) - - # whether the form stays open after an update or not - cattr_accessor :persistent - @@persistent = false - - # instance-level configuration - # ---------------------------- - - attr_accessor :nested_links - cattr_accessor :nested_links - @@nested_links = false - - # whether the form stays open after an update or not - attr_accessor :persistent - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/configurable.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/configurable.rb deleted file mode 100644 index aee4101..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/configurable.rb +++ /dev/null @@ -1,29 +0,0 @@ -module ActiveScaffold - # Exposes a +configure+ method that accepts a block and runs all contents of the block in two contexts, as opposed to the normal one. First, everything gets evaluated as part of the object including Configurable. Then, as a failover, missing methods and variables are evaluated in the original binding of the block. - # - # Note that this only works with "barewords". Constants, instance variables, and class variables are not currently supported in both contexts. - # - # May add the given functionality at both the class and instance level. For the former, use +extend+, and for the latter, use +include+. - module Configurable - def configure(&configuration_block) - return unless configuration_block - @configuration_binding = configuration_block.binding - ret = instance_exec self, &configuration_block - @configuration_binding = nil - return ret - end - - # this method will surely need tweaking. for example, i'm not sure if it should call super before or after it tries to eval with the binding. - def method_missing(name, *args) - begin - super - rescue NoMethodError, NameError - if @configuration_binding.nil? - raise $! - else - eval("self", @configuration_binding).send(name, *args) - end - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/constraints.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/constraints.rb deleted file mode 100644 index 4dbf864..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/constraints.rb +++ /dev/null @@ -1,173 +0,0 @@ -module ActiveScaffold - module Constraints - def self.included(base) - base.module_eval do - before_filter :register_constraints_with_action_columns - end - end - - protected - - # Returns the current constraints - def active_scaffold_constraints - return active_scaffold_session_storage[:constraints] || {} - end - - # For each enabled action, adds the constrained columns to the ActionColumns object (if it exists). - # This lets the ActionColumns object skip constrained columns. - # - # If the constraint value is a Hash, then we assume the constraint is a multi-level association constraint (the reverse of a has_many :through) and we do NOT register the constraint column. - def register_constraints_with_action_columns - constrained_fields = active_scaffold_constraints.reject{|k, v| v.is_a? Hash}.keys.collect{|k| k.to_sym} - - if self.class.uses_active_scaffold? - # we actually want to do this whether constrained_fields exist or not, so that we can reset the array when they don't - active_scaffold_config.actions.each do |action_name| - action = active_scaffold_config.send(action_name) - next unless action.respond_to? :columns - action.columns.constraint_columns = constrained_fields - end - end - end - - # Returns search conditions based on the current scaffold constraints. - # - # Supports constraints based on either a column name (in which case it checks for an association - # or just uses the search_sql) or a database field name. - # - # All of this work is primarily to support nested scaffolds in a manner generally useful for other - # embedded scaffolds. - def conditions_from_constraints - conditions = nil - active_scaffold_constraints.each do |k, v| - column = active_scaffold_config.columns[k] - constraint_condition = if column - # Assume this is a multi-level association constraint. - # example: - # data model: Park -> Den -> Bear - # constraint: :den => {:park => 5} - if v.is_a? Hash - far_association = column.association.klass.reflect_on_association(v.keys.first) - field = far_association.klass.primary_key - table = far_association.table_name - - active_scaffold_includes.concat([{k => v.keys.first}]) # e.g. {:den => :park} - constraint_condition_for("#{table}.#{field}", v.values.first) - - # association column constraint - elsif column.association - if column.association.macro == :has_and_belongs_to_many - active_scaffold_habtm_joins.concat column.includes - else - active_scaffold_includes.concat column.includes - end - condition_from_association_constraint(column.association, v) - - # regular column constraints - elsif column.searchable? - active_scaffold_includes.concat column.includes - constraint_condition_for(column.search_sql, v) - end - # unknown-to-activescaffold-but-real-database-column constraint - elsif active_scaffold_config.model.column_names.include? k.to_s - constraint_condition_for(k.to_s, v) - else - raise ActiveScaffold::MalformedConstraint, constraint_error(active_scaffold_config.model, k), caller - end - - conditions = merge_conditions(conditions, constraint_condition) - end - - conditions - end - - # We do NOT want to use .search_sql. If anything, search_sql will refer - # to a human-searchable value on the associated record. - def condition_from_association_constraint(association, value) - # when the reverse association is a :belongs_to, the id for the associated object only exists as - # the primary_key on the other table. so for :has_one and :has_many (when the reverse is :belongs_to), - # we have to use the other model's primary_key. - # - # please see the relevant tests for concrete examples. - field = if [:has_one, :has_many].include?(association.macro) - association.klass.primary_key - elsif [:has_and_belongs_to_many].include?(association.macro) - association.association_foreign_key - else - association.options[:foreign_key] || association.name.to_s.foreign_key - end - - table = case association.macro - when :has_and_belongs_to_many - association.options[:join_table] - - when :belongs_to - active_scaffold_config.model.table_name - - else - association.table_name - end - - if association.options[:primary_key] - value = association.klass.find(value).send(association.options[:primary_key]) - end - - condition = constraint_condition_for("#{table}.#{field}", value) - if association.options[:polymorphic] - condition = merge_conditions( - condition, - constraint_condition_for("#{table}.#{association.name}_type", params[:parent_model].to_s) - ) - end - - condition - end - - def constraint_error(klass, column_name) - "Malformed constraint `#{klass}##{column_name}'. If it's a legitimate column, and you are using a nested scaffold, please specify or double-check the reverse association name." - end - - # Applies constraints to the given record. - # - # Searches through the known columns for association columns. If the given constraint is an association, - # it assumes that the constraint value is an id. It then does a association.klass.find with the value - # and adds the associated object to the record. - # - # For some operations ActiveRecord will automatically update the database. That's not always ok. - # If it *is* ok (e.g. you're in a transaction), then set :allow_autosave to true. - def apply_constraints_to_record(record, options = {}) - options[:allow_autosave] = false if options[:allow_autosave].nil? - - active_scaffold_constraints.each do |k, v| - column = active_scaffold_config.columns[k] - if column and column.association - if column.plural_association? - record.send("#{k}").send(:<<, column.association.klass.find(v)) - elsif column.association.options[:polymorphic] - record.send("#{k}=", params[:parent_model].constantize.find(v)) - else # regular singular association - record.send("#{k}=", column.association.klass.find(v)) - - # setting the belongs_to side of a has_one isn't safe. if the has_one was already - # specified, rails won't automatically clear out the previous associated record. - # - # note that we can't take the extra step to correct this unless we're permitted to - # run operations where activerecord auto-saves the object. - reverse = column.association.klass.reflect_on_association(column.association.reverse) - if reverse.macro == :has_one and options[:allow_autosave] - record.send(k).send("#{column.association.reverse}=", record) - end - end - else - record.send("#{k}=", v) - end - end - end - - private - - def constraint_condition_for(sql, value) - value.nil? ? "#{sql} IS NULL" : ["#{sql} = ?", value] - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_columns.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_columns.rb deleted file mode 100644 index 6575c41..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_columns.rb +++ /dev/null @@ -1,101 +0,0 @@ -module ActiveScaffold::DataStructures - # A set of columns. These structures can be nested for organization. - class ActionColumns < Set - include ActiveScaffold::Configurable - - # this lets us refer back to the action responsible for this link, if it exists. - # the immediate need here is to get the crud_type so we can dynamically filter columns from the set. - attr_accessor :action - - # labels are useful for the Create/Update forms, when we display columns in a grouped fashion and want to name them separately - attr_writer :label - def label - as_(@label) if @label - end - - # Whether this column set is collapsed by default in contexts where collapsing is supported - attr_accessor :collapsed - - # nests a subgroup in the column set - def add_subgroup(label, &proc) - columns = ActiveScaffold::DataStructures::ActionColumns.new - columns.label = label - columns.action = self.action - columns.configure &proc - self.exclude columns.collect_columns - self.add columns - end - - def include?(item) - @set.each do |c| - return true if !c.is_a? Symbol and c.include? item - return true if c == item.to_sym - end - return false - end - - def names - self.collect(&:name) - end - - protected - - def collect_columns - @set.collect {|col| col.is_a?(ActiveScaffold::DataStructures::ActionColumns) ? col.collect_columns : col} - end - - # called during clone or dup. makes the clone/dup deeper. - def initialize_copy(from) - @set = from.instance_variable_get('@set').clone - end - - # A package of stuff to add after the configuration block. This is an attempt at making a certain level of functionality inaccessible during configuration, to reduce possible breakage from misuse. - # The bulk of the package is a means of connecting the referential column set (ActionColumns) with the actual column objects (Columns). This lets us iterate over the set and yield real column objects. - module AfterConfiguration - # Redefine the each method to yield actual Column objects. - # It will skip constrained and unauthorized columns. - # - # Options: - # * :flatten - whether to recursively iterate on nested sets. default is false. - # * :for - the record (or class) being iterated over. used for column-level security. default is the class. - def each(options = {}, &proc) - options[:for] ||= @columns.active_record_class - - @set.each do |item| - unless item.is_a? ActiveScaffold::DataStructures::ActionColumns - item = (@columns[item] || ActiveScaffold::DataStructures::Column.new(item.to_sym, @columns.active_record_class)) - # skip if this matches a constrained column - next if constraint_columns.include?(item.name.to_sym) - # skip if this matches the field_name of a constrained column - next if item.field_name and constraint_columns.include?(item.field_name.to_sym) - # skip this field if it's not authorized - next unless options[:for].authorized_for?(:action => options[:action], :crud_type => options[:crud_type] || self.action.crud_type, :column => item.name) - end - if item.is_a? ActiveScaffold::DataStructures::ActionColumns and options.has_key?(:flatten) and options[:flatten] - item.each(options, &proc) - else - yield item - end - end - end - - # registers a set of column objects (recursively, for all nested ActionColumns) - def set_columns(columns) - @columns = columns - # iterate over @set instead of self to avoid dealing with security queries - @set.each do |item| - item.set_columns(columns) if item.respond_to? :set_columns - end - end - - attr_writer :constraint_columns - def constraint_columns - @constraint_columns ||= [] - end - - def length - (@set - self.constraint_columns).length - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_link.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_link.rb deleted file mode 100644 index 46c2761..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_link.rb +++ /dev/null @@ -1,146 +0,0 @@ -module ActiveScaffold::DataStructures - class ActionLink - # provides a quick way to set any property of the object from a hash - def initialize(action, options = {}) - # set defaults - self.action = action.to_s - self.label = action - self.confirm = false - self.type = :collection - self.inline = true - self.method = :get - self.crud_type = :delete if [:destroy].include?(action.to_sym) - self.crud_type = :create if [:create, :new].include?(action.to_sym) - self.crud_type = :update if [:edit, :update].include?(action.to_sym) - self.crud_type ||= :read - self.parameters = {} - self.html_options = {} - - # apply quick properties - options.each_pair do |k, v| - setter = "#{k}=" - self.send(setter, v) if self.respond_to? setter - end - end - - # the action-path for this link. what page to request? this is required! - attr_accessor :action - - # the controller for this action link. if nil, the current controller should be assumed. - attr_accessor :controller - - # a hash of request parameters - attr_accessor :parameters - - # the RESTful method - attr_accessor :method - - # what string to use to represent this action - attr_writer :label - def label - @label.is_a?(Symbol) ? as_(@label) : @label - end - - # if the action requires confirmation - def confirm=(value) - @dhtml_confirm = nil if value - @confirm = value - end - def confirm(label = '') - @confirm.is_a?(String) ? @confirm : as_(@confirm, :label => label) - end - def confirm? - !!@confirm - end - - # if the action uses a DHTML based (i.e. 2-phase) confirmation - attr_accessor :dhtml_confirm - def dhtml_confirm=(value) - @confirm = nil if value - @dhtml_confirm = value - end - def dhtml_confirm? - !!@dhtml_confirm - end - - # what method to call on the controller to see if this action_link should be visible - # note that this is only the UI part of the security. to prevent URL hax0rz, you also need security on requests (e.g. don't execute update method unless authorized). - attr_writer :security_method - def security_method - @security_method || "#{self.action}_authorized?" - end - - def security_method_set? - !!@security_method - end - - # the crud type of the (eventual?) action. different than :method, because this crud action may not be imminent. - # this is used to determine record-level authorization (e.g. record.authorized_for?(:crud_type => link.crud_type). - # options are :create, :read, :update, and :delete - attr_accessor :crud_type - - # an "inline" link is inserted into the existing page - # exclusive with popup? and page? - def inline=(val) - @inline = (val == true) - self.popup = self.page = false if @inline - end - def inline?; @inline end - - # a "popup" link displays in a separate (browser?) window. this will eventually take arguments. - # exclusive with inline? and page? - def popup=(val) - @popup = (val == true) - if @popup - self.inline = self.page = false - - # the :method parameter doesn't mix with the :popup parameter - # when/if we start using DHTML popups, we can bring :method back - self.method = nil - end - end - def popup?; @popup end - - # a "page" link displays by reloading the current page - # exclusive with inline? and popup? - def page=(val) - @page = (val == true) - if @page - self.inline = self.popup = false - - # when :method is defined, ActionView adds an onclick to use a form ... - # so it's best to just empty out :method whenever possible. - # we only ever need to know @method = :get for things that default to POST. - # the only things that default to POST are forms and ajax calls. - # when @page = true, we don't use ajax. - self.method = nil if method == :get - end - end - def page?; @page end - - # where the result of this action should insert in the display. - # for :type => :collection, supported values are: - # :top - # :bottom - # :replace (for updating the entire table) - # false (no attempt at positioning) - # for :type => :member, supported values are: - # :before - # :replace - # :after - # false (no attempt at positioning) - attr_writer :position - def position - return @position unless @position.nil? or @position == true - return :replace if self.type == :member - return :top if self.type == :collection - raise "what should the default position be for #{self.type}?" - end - - # what type of link this is. currently supported values are :collection and :member. - attr_accessor :type - - # html options for the link - attr_accessor :html_options - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_links.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_links.rb deleted file mode 100644 index b36fb86..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/action_links.rb +++ /dev/null @@ -1,47 +0,0 @@ -module ActiveScaffold::DataStructures - class ActionLinks - include Enumerable - - def initialize - @set = [] - end - - # adds an ActionLink, creating one from the arguments if need be - def add(action, options = {}) - link = action.is_a?(ActiveScaffold::DataStructures::ActionLink) ? action : ActiveScaffold::DataStructures::ActionLink.new(action, options) - # NOTE: this duplicate check should be done by defining the comparison operator for an Action data structure - @set << link unless @set.any? {|a| a.action == link.action and a.controller == link.controller and a.parameters == link.parameters} - end - alias_method :<<, :add - - # finds an ActionLink by matching the action - def [](val) - @set.find {|item| item.action == val.to_s} - end - - def delete(val) - @set.delete_if{|item| item.action == val.to_s} - end - - # iterates over the links, possibly by type - def each(type = nil) - type = type.to_sym if type - @set.each {|item| - next if type and item.type != type - yield item - } - end - - def empty? - @set.size == 0 - end - - protected - - # called during clone or dup. makes the clone/dup deeper. - def initialize_copy(from) - @set = [] - from.instance_variable_get('@set').each { |link| @set << link.clone } - end - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/actions.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/actions.rb deleted file mode 100644 index 587138a..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/actions.rb +++ /dev/null @@ -1,45 +0,0 @@ -class ActiveScaffold::DataStructures::Actions - include Enumerable - - def initialize(*args) - @set = [] - self.add *args - end - - def exclude(*args) - args.collect! { |a| a.to_sym } # symbolize the args - @set.reject! { |m| args.include? m } # reject all actions specified - end - - def add(*args) - args.each { |arg| @set << arg.to_sym unless @set.include? arg.to_sym } - end - alias_method :<<, :add - - def each - @set.each {|item| yield item} - end - - def include?(val) - super val.to_sym - end - - # swaps one element in the list with the other. - # accepts arguments in any order. it just figures out which one is in the list and which one is not. - def swap(one, two) - if include? one - exclude one - add two - else - exclude two - add one - end - end - - protected - - # called during clone or dup. makes the clone/dup deeper. - def initialize_copy(from) - @set = from.instance_variable_get('@set').clone - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/column.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/column.rb deleted file mode 100644 index 18ab7db..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/data_structures/column.rb +++ /dev/null @@ -1,336 +0,0 @@ -module ActiveScaffold::DataStructures - class Column - include ActiveScaffold::Configurable - - attr_reader :active_record_class - - # this is the name of the getter on the ActiveRecord model. it is the only absolutely required attribute ... all others will be inferred from this name. - attr_accessor :name - - # Whether to enable inplace editing for this column. Currently works for text columns, in the List. - attr_reader :inplace_edit - def inplace_edit=(value) - self.clear_link if value - @inplace_edit = value - end - - # Whether this column set is collapsed by default in contexts where collapsing is supported - attr_accessor :collapsed - - # Whether to enable add_existing for this column - attr_accessor :allow_add_existing - - # Any extra parameters this particular column uses. This is for create/update purposes. - def params - # lazy initialize - @params ||= Set.new - end - - # the display-name of the column. this will be used, for instance, as the column title in the table and as the field name in the form. - # if left alone it will utilize human_attribute_name which includes localization - attr_writer :label - def label - as_(@label) || active_record_class.human_attribute_name(name.to_s) - end - - # a textual description of the column and its contents. this will be displayed with any associated form input widget, so you may want to consider adding a content example. - attr_writer :description - def description - if @description - @description - else - I18n.t name, :scope => [:activerecord, :description, active_record_class.to_s.underscore.to_sym], :default => '' - end - end - - # this will be /joined/ to the :name for the td's class attribute. useful if you want to style columns on different ActiveScaffolds the same way, but the columns have different names. - attr_accessor :css_class - - # whether the field is required or not. used on the form for visually indicating the fact to the user. - # TODO: move into predicate - attr_writer :required - def required? - @required - end - - # column to be updated in a form when this column changes - attr_accessor :update_column - - # send all the form instead of only new value when this column change - cattr_accessor :send_form_on_update_column - attr_accessor :send_form_on_update_column - - # sorting on a column can be configured four ways: - # sort = true default, uses intelligent sorting sql default - # sort = false sometimes sorting doesn't make sense - # sort = {:sql => ""} define your own sql for sorting. this should be result in a sortable value in SQL. ActiveScaffold will handle the ascending/descending. - # sort = {:method => ""} define ruby-side code for sorting. this is SLOW with large recordsets! - def sort=(value) - if value.is_a? Hash - value.assert_valid_keys(:sql, :method) - @sort = value - else - @sort = value ? true : false # force true or false - end - end - - def sort - self.initialize_sort if @sort === true - @sort - end - - def sortable? - sort != false && !sort.nil? - end - - # a configuration helper for the self.sort property. simply provides a method syntax instead of setter syntax. - def sort_by(options) - self.sort = options - end - - # supported options: - # * for association columns - # * :select - displays a simple - def usa_state_options_for_select(selected = nil, priority_states = nil) - if priority_states - state_options = options_for_select(priority_states + [['-------------', '']], :selected => selected, :disabled => '') - else - state_options = "" - end - - if priority_states && priority_states.include?(selected) - state_options += options_for_select(USASTATES - priority_states, :selected => selected) - else - state_options += options_for_select(USASTATES, :selected => selected) - end - - return state_options - end - # All the countries included in the country_options output. - COUNTRIES = [ - :afghanistan, - :aland_islands, - :albania, - :algeria, - :american_samoa, - :andorra, - :angola, - :anguilla, - :antarctica, - :antigua_and_barbuda, - :argentina, - :armenia, - :aruba, - :australia, - :austria, - :azerbaijan, - :bahamas, - :bahrain, - :bangladesh, - :barbados, - :belarus, - :belgium, - :belize, - :benin, - :bermuda, - :bhutan, - :bolivia, - :bosnia_and_herzegowina, - :botswana, - :bouvet_island, - :brazil, - :british_indian_ocean_territory, - :brunei_darussalam, - :bulgaria, - :burkina_faso, - :burundi, - :cambodia, - :cameroon, - :canada, - :cape_verde, - :cayman_islands, - :central_african_republic, - :chad, - :chile, - :china, - :christmas_island, - :cocos_keeling_islands, - :colombia, - :comoros, - :congo, - :congo_the_democratic_republic_of_the, - :cook_islands, - :costa_rica, - :cote_divoire, - :croatia, - :cuba, - :cyprus, - :czech_republic, - :denmark, - :djibouti, - :dominica, - :dominican_republic, - :ecuador, - :egypt, - :el_salvador, - :equatorial_guinea, - :eritrea, - :estonia, - :ethiopia, - :falkland_islands_malvinas, - :faroe_islands, - :fiji, - :finland, - :france, - :french_guiana, - :french_polynesia, - :french_southern_territories, - :gabon, - :gambia, - :georgia, - :germany, - :ghana, - :gibraltar, - :greece, - :greenland, - :grenada, - :guadeloupe, - :guam, - :guatemala, - :guernsey, - :guinea, - :guinea_bissau, - :guyana, - :haiti, - :heard_and_mcdonald_islands, - :holy_see_vatican_city_state, - :honduras, - :hong_kong, - :hungary, - :iceland, - :india, - :indonesia, - :iran_islamic_republic_of, - :iraq, - :ireland, - :isle_of_man, - :israel, - :italy, - :jamaica, - :japan, - :jersey, - :jordan, - :kazakhstan, - :kenya, - :kiribati, - :korea_democratic_peoples_republic_of, - :korea_republic_of, - :kuwait, - :kyrgyzstan, - :lao_peoples_democratic_republic, - :latvia, - :lebanon, - :lesotho, - :liberia, - :libyan_arab_jamahiriya, - :liechtenstein, - :lithuania, - :luxembourg, - :macao, - :macedonia_the_former_yugoslav_republic_of, - :madagascar, - :malawi, - :malaysia, - :maldives, - :mali, - :malta, - :marshall_islands, - :martinique, - :mauritania, - :mauritius, - :mayotte, - :mexico, - :micronesia_federated_states_of, - :moldova_republic_of, - :monaco, - :mongolia, - :montenegro, - :montserrat, - :morocco, - :mozambique, - :myanmar, - :namibia, - :nauru, - :nepal, - :netherlands, - :netherlands_antilles, - :new_caledonia, - :new_zealand, - :nicaragua, - :niger, - :nigeria, - :niue, - :norfolk_island, - :northern_mariana_islands, - :norway, - :oman, - :pakistan, - :palau, - :palestinian_territory_occupied, - :panama, - :papua_new_guinea, - :paraguay, - :peru, - :philippines, - :pitcairn, - :poland, - :portugal, - :puerto_rico, - :qatar, - :reunion, - :romania, - :russian_federation, - :rwanda, - :saint_barthelemy, - :saint_helena, - :saint_kitts_and_nevis, - :saint_lucia, - :saint_pierre_and_miquelon, - :saint_vincent_and_the_grenadines, - :samoa, - :san_marino, - :sao_tome_and_principe, - :saudi_arabia, - :senegal, - :serbia, - :seychelles, - :sierra_leone, - :singapore, - :slovakia, - :slovenia, - :solomon_islands, - :somalia, - :south_africa, - :south_georgia_and_the_south_sandwich_islands, - :spain, - :sri_lanka, - :sudan, - :suriname, - :svalbard_and_jan_mayen, - :swaziland, - :sweden, - :switzerland, - :syrian_arab_republic, - :taiwan_province_of_china, - :tajikistan, - :tanzania_united_republic_of, - :thailand, - :timor_leste, - :togo, - :tokelau, - :tonga, - :trinidad_and_tobago, - :tunisia, - :turkey, - :turkmenistan, - :turks_and_caicos_islands, - :tuvalu, - :uganda, - :ukraine, - :united_arab_emirates, - :united_kingdom, - :united_states, - :united_states_minor_outlying_islands, - :uruguay, - :uzbekistan, - :vanuatu, - :venezuela, - :viet_nam, - :virgin_islands_british, - :virgin_islands_us, - :wallis_and_futuna, - :western_sahara, - :yemen, - :zambia, - :zimbabwe] unless const_defined?("COUNTRIES") - - - USASTATES = [["Alabama", "AL"], ["Alaska", "AK"], ["Arizona", "AZ"], ["Arkansas", "AR"], ["California", "CA"], ["Colorado", "CO"], ["Connecticut", "CT"], ["Delaware", "DE"], ["District of Columbia", "DC"], ["Florida", "FL"], ["Georgia", "GA"], ["Hawaii", "HI"], ["Idaho", "ID"], ["Illinois", "IL"], ["Indiana", "IN"], ["Iowa", "IA"], ["Kansas", "KS"], ["Kentucky", "KY"], ["Louisiana", "LA"], ["Maine", "ME"], ["Maryland", "MD"], ["Massachusetts", "MA"], ["Michigan", "MI"], ["Minnesota", "MN"], ["Mississippi", "MS"], ["Missouri", "MO"], ["Montana", "MT"], ["Nebraska", "NE"], ["Nevada", "NV"], ["New Hampshire", "NH"], ["New Jersey", "NJ"], ["New Mexico", "NM"], ["New York", "NY"], ["North Carolina", "NC"], ["North Dakota", "ND"], ["Ohio", "OH"], ["Oklahoma", "OK"], ["Oregon", "OR"], ["Pennsylvania", "PA"], ["Rhode Island", "RI"], ["South Carolina", "SC"], ["South Dakota", "SD"], ["Tennessee", "TN"], ["Texas", "TX"], ["Utah", "UT"], ["Vermont", "VT"], ["Virginia", "VA"], ["Washington", "WA"], ["Wisconsin", "WI"], ["West Virginia", "WV"], ["Wyoming", "WY"]] unless const_defined?("USASTATES") - - class ActionView::Helpers::InstanceTag #:nodoc: - include CountryHelpers - - def to_country_select_tag(priority_countries, options, html_options) - html_options = html_options.stringify_keys - add_default_name_and_id(html_options) - value = value(object) - selected_value = options.has_key?(:selected) ? options[:selected] : value - content_tag("select", - add_options( - country_options_for_select(selected_value, priority_countries), - options, selected_value - ), html_options - ) - end - - def to_usa_state_select_tag(priority_states, options, html_options) - html_options = html_options.stringify_keys - add_default_name_and_id(html_options) - value = value(object) - selected_value = options.has_key?(:selected) ? options[:selected] : value - content_tag("select", add_options(usa_state_options_for_select(selected_value, priority_states), options, selected_value), html_options) - end - end - end - - module FormColumnHelpers - def active_scaffold_input_country(column, options) - select_options = {:prompt => as_(:_select_)} - select_options.merge!(options) - options.reverse_merge!(column.options).except!(:prompt, :priority) - options[:name] += '[]' if options[:multiple] - country_select(:record, column.name, column.options[:priority] || [:united_states], select_options, options) - end - - def active_scaffold_input_usa_state(column, options) - select_options = {:prompt => as_(:_select_)} - select_options.merge!(options) - options.reverse_merge!(column.options).except!(:prompt, :priority) - options[:name] += '[]' if options[:multiple] - usa_state_select(:record, column.name, column.options[:priority], select_options, options) - end - end - - module SearchColumnHelpers - def active_scaffold_search_country(column, options) - active_scaffold_input_country(column, options.merge!(:selected => options.delete(:value))) - end - - def active_scaffold_search_usa_state(column, options) - active_scaffold_input_usa_state(column, options.merge!(:selected => options.delete(:value))) - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/form_column_helpers.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/form_column_helpers.rb deleted file mode 100644 index 475dd27..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/form_column_helpers.rb +++ /dev/null @@ -1,338 +0,0 @@ -module ActiveScaffold - module Helpers - # Helpers that assist with the rendering of a Form Column - module FormColumnHelpers - # This method decides which input to use for the given column. - # It does not do any rendering. It only decides which method is responsible for rendering. - def active_scaffold_input_for(column, scope = nil, options = {}) - begin - options = active_scaffold_input_options(column, scope, options) - options = javascript_for_update_column(column, scope, options) - # first, check if the dev has created an override for this specific field - if override_form_field?(column) - send(override_form_field(column), @record, options) - # second, check if the dev has specified a valid form_ui for this column - elsif column.form_ui and override_input?(column.form_ui) - send(override_input(column.form_ui), column, options) - # fallback: we get to make the decision - else - if column.association - # if we get here, it's because the column has a form_ui but not one ActiveScaffold knows about. - raise "Unknown form_ui `#{column.form_ui}' for column `#{column.name}'" - elsif column.virtual? - active_scaffold_input_virtual(column, options) - - else # regular model attribute column - # if we (or someone else) have created a custom render option for the column type, use that - if override_input?(column.column.type) - send(override_input(column.column.type), column, options) - # final ultimate fallback: use rails' generic input method - else - # for textual fields we pass different options - text_types = [:text, :string, :integer, :float, :decimal] - date_types = [:date, :datetime, :time] - options = active_scaffold_input_text_options(options) if text_types.include?(column.column.type) - options = active_scaffold_input_date_options(column, options) if date_types.include?(column.column.type) - if column.column.type == :string && options[:maxlength].blank? - options[:maxlength] = column.column.limit - options[:size] ||= ActionView::Helpers::InstanceTag::DEFAULT_FIELD_OPTIONS["size"] - end - options[:value] = format_number_value(@record.send(column.name), column.options) if column.column.number? - input(:record, column.name, options.merge(column.options)) - end - end - end - rescue Exception => e - logger.error Time.now.to_s + "#{e.inspect} -- on the ActiveScaffold column = :#{column.name} in #{@controller.class}" - raise e - end - end - - alias form_column active_scaffold_input_for - - # the standard active scaffold options used for textual inputs - def active_scaffold_input_text_options(options = {}) - options[:autocomplete] = 'off' - options[:class] = "#{options[:class]} text-input".strip - options - end - - # the standard active scaffold options used for date, datetime and time inputs - def active_scaffold_input_date_options(column, options = {}) - options[:include_blank] = true if column.column.null - options[:prefix] = options[:name].gsub("[#{column.name}]", '') - options - end - - # the standard active scaffold options used for class, name and scope - def active_scaffold_input_options(column, scope = nil, options = {}) - name = scope ? "record#{scope}[#{column.name}]" : "record[#{column.name}]" - - # Fix for keeping unique IDs in subform - id_control = "record_#{column.name}_#{[params[:eid], params[:id]].compact.join '_'}" - id_control += scope.gsub(/(\[|\])/, '_').gsub('__', '_').gsub(/_$/, '') if scope - - { :name => name, :class => "#{column.name}-input", :id => id_control}.merge(options) - end - - def javascript_for_update_column(column, scope, options) - if column.update_column - form_action = :create - form_action = :update if params[:action] == 'edit' - url_params = { - :action => 'render_field', - :id => params[:id], - :column => column.name, - :update_column => column.update_column, - :eid => params[:eid], - :scope => scope - } - url_params[:controller] = controller.class.active_scaffold_controller_for(@record.class).controller_path if scope - ajax_options = {:method => :get, - :url => url_for(url_params), :with => column.send_form_on_update_column ? "Form.serialize('#{element_form_id(:action => form_action)}')" : "'value=' + this.value", - :after => "$('#{loading_indicator_id(:action => form_action, :id => params[:id])}').style.visibility = 'visible'; Form.disable('#{element_form_id(:action => form_action)}');", - :complete => "$('#{loading_indicator_id(:action => form_action, :id => params[:id])}').style.visibility = 'hidden'; Form.enable('#{element_form_id(:action => form_action)}');"} - options[:onchange] = "#{remote_function(ajax_options)};#{options[:onchange]}" - end - options - end - - ## - ## Form input methods - ## - - def active_scaffold_input_singular_association(column, html_options) - associated = @record.send(column.association.name) - - select_options = options_for_association(column.association) - select_options.unshift([ associated.to_label, associated.id ]) unless associated.nil? or select_options.find {|label, id| id == associated.id} - - selected = associated.nil? ? nil : associated.id - method = column.name - #html_options[:name] += '[id]' - options = {:selected => selected, :include_blank => as_(:_select_)} - - html_options.update(column.options[:html_options] || {}) - options.update(column.options) - select(:record, method, select_options.uniq, options, html_options) - end - - def active_scaffold_input_plural_association(column, options) - associated_options = @record.send(column.association.name).collect {|r| [r.to_label, r.id]} - select_options = associated_options | options_for_association(column.association) - return content_tag(:span, as_(:no_options), :id => options[:id]) if select_options.empty? - - html = "
    " - - associated_ids = associated_options.collect {|a| a[1]} - select_options.each_with_index do |option, i| - label, id = option - this_name = "#{options[:name]}[]" - this_id = "#{options[:id]}_#{i}_id" - html << "
  • " - html << check_box_tag(this_name, id, associated_ids.include?(id), :id => this_id) - html << "" - html << "
  • " - end - - html << '
' - html << javascript_tag("new DraggableLists('#{options[:id]}')") if column.options[:draggable_lists] - html - end - - def active_scaffold_translated_option(column, text, value = nil) - value = text if value.nil? - [(text.is_a?(Symbol) ? column.active_record_class.human_attribute_name(text) : text), value.to_s] - end - - def active_scaffold_translated_options(column) - column.options[:options].collect do |text, value| - active_scaffold_translated_option(column, text, value) - end - end - - def active_scaffold_input_select(column, html_options) - if column.singular_association? - active_scaffold_input_singular_association(column, html_options) - elsif column.plural_association? - active_scaffold_input_plural_association(column, html_options) - else - options = { :selected => @record.send(column.name).to_s } - options_for_select = active_scaffold_translated_options(column) - html_options.update(column.options[:html_options] || {}) - options.update(column.options) - select(:record, column.name, options_for_select, options, html_options) - end - end - - def active_scaffold_input_radio(column, html_options) - html_options.update(column.options[:html_options] || {}) - column.options[:options].inject('') do |html, (text, value)| - text, value = active_scaffold_translated_option(column, text, value) - html << content_tag(:label, radio_button(:record, column.name, value, html_options.merge(:id => html_options[:id] + '-' + value.to_s)) + text) - end - end - - def active_scaffold_input_checkbox(column, options) - check_box(:record, column.name, options.merge(column.options)) - end - - def active_scaffold_input_password(column, options) - options = active_scaffold_input_text_options(options) - password_field :record, column.name, options.merge(column.options) - end - - def active_scaffold_input_textarea(column, options) - text_area(:record, column.name, options.merge(:cols => column.options[:cols], :rows => column.options[:rows], :size => column.options[:size])) - end - - def active_scaffold_input_virtual(column, options) - options = active_scaffold_input_text_options(options) - text_field :record, column.name, options.merge(column.options) - end - - # - # Column.type-based inputs - # - - def active_scaffold_input_boolean(column, options) - select_options = [] - select_options << [as_(:_select_), nil] if column.column.null - select_options << [as_(:true), true] - select_options << [as_(:false), false] - - select_tag(options[:name], options_for_select(select_options, @record.send(column.name)), options) - end - - def onsubmit - end - - ## - ## Form column override signatures - ## - - # add functionality for overriding subform partials from association class path - def override_subform_partial?(column, subform_partial) - path, partial_name = partial_pieces(override_subform_partial(column, subform_partial)) - template_exists?(File.join(path, "_#{partial_name}")) - end - - def override_subform_partial(column, subform_partial) - File.join(active_scaffold_controller_for(column.association.klass).controller_path, subform_partial) if column_renders_as(column) == :subform - end - - def override_form_field_partial?(column) - path, partial_name = partial_pieces(override_form_field_partial(column)) - template_exists?(File.join(path, "_#{partial_name}"), true) - end - - # the naming convention for overriding form fields with helpers - def override_form_field_partial(column) - path = active_scaffold_controller_for(column.active_record_class).controller_path - File.join(path, "#{clean_column_name(column.name)}_form_column") - end - - def override_form_field(column) - method = override_form_field_name(column) - return method if respond_to?(method) - old_method = override_form_field_name(column, true) - if respond_to?(old_method) - ActiveSupport::Deprecation.warn("You are using an old naming schema for overrides, you should name the helper #{method} instead of #{old_method}") - old_method - end - end - alias_method :override_form_field?, :override_form_field - - # the naming convention for overriding form fields with helpers - def override_form_field_name(column, old = false) - "#{clean_class_name(column.active_record_class.name) + '_' unless old}#{clean_column_name(column.name)}_form_column" - end - - def override_input?(form_ui) - respond_to?(override_input(form_ui)) - end - - # the naming convention for overriding form input types with helpers - def override_input(form_ui) - "active_scaffold_input_#{form_ui}" - end - - def form_partial_for_column(column) - if override_form_field_partial?(column) - override_form_field_partial(column) - elsif column_renders_as(column) == :field or override_form_field?(column) - "form_attribute" - elsif column_renders_as(column) == :subform - "form_association" - elsif column_renders_as(column) == :hidden - "form_hidden_attribute" - end - end - - def subform_partial_for_column(column) - subform_partial = "#{active_scaffold_config_for(column.association.klass).subform.layout}_subform" - if override_subform_partial?(column, subform_partial) - override_subform_partial(column, subform_partial) - else - subform_partial - end - end - - ## - ## Macro-level rendering decisions for columns - ## - - def column_renders_as(column) - if column.is_a? ActiveScaffold::DataStructures::ActionColumns - return :subsection - elsif column.active_record_class.locking_column.to_s == column.name.to_s or column.form_ui == :hidden - return :hidden - elsif column.association.nil? or column.form_ui or !active_scaffold_config_for(column.association.klass).actions.include?(:subform) - return :field - else - return :subform - end - end - - def is_subsection?(column) - column_renders_as(column) == :subsection - end - - def is_subform?(column) - column_renders_as(column) == :subform - end - - def column_scope(column) - if column.plural_association? - "[#{column.name}][#{@record.id || generate_temporary_id}]" - else - "[#{column.name}]" - end - end - - def active_scaffold_add_existing_input(options) - if controller.respond_to?(:record_select_config) - remote_controller = active_scaffold_controller_for(record_select_config.model).controller_path - options.merge!(:controller => remote_controller) - options.merge!(active_scaffold_input_text_options) - record_select_field(options[:name], @record, options) - else - column = active_scaffold_config_for(params[:parent_model]).columns[params[:parent_column]] - select_options = options_for_select(options_for_association(column.association)) unless column.through_association? - select_options ||= options_for_select(active_scaffold_config.model.find(:all).collect {|c| [h(c.to_label), c.id]}) - select_tag 'associated_id', '' + select_options unless select_options.empty? - end - end - - def active_scaffold_add_existing_label - if controller.respond_to?(:record_select_config) - record_select_config.model.human_name - else - active_scaffold_config.model.human_name - end - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/id_helpers.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/id_helpers.rb deleted file mode 100644 index 93c956f..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/id_helpers.rb +++ /dev/null @@ -1,125 +0,0 @@ -module ActiveScaffold - module Helpers - # A bunch of helper methods to produce the common view ids - module IdHelpers - def id_from_controller(controller) - controller.to_s.gsub("/", "__").html_safe - end - - def controller_id - @controller_id ||= 'as_' + id_from_controller(params[:eid] || params[:parent_controller] || params[:controller]) - end - - def active_scaffold_id - "#{controller_id}-active-scaffold" - end - - def active_scaffold_content_id - "#{controller_id}-content" - end - - def active_scaffold_tbody_id - "#{controller_id}-tbody" - end - - def active_scaffold_messages_id - "#{controller_id}-messages" - end - - def active_scaffold_calculations_id(column = nil) - "#{controller_id}-calculations#{'-' + column.name.to_s if column}" - end - - def empty_message_id - "#{controller_id}-empty-message" - end - - def before_header_id - "#{controller_id}-search-container" - end - - def search_form_id - "#{controller_id}-search-form" - end - - def search_input_id - "#{controller_id}-search-input" - end - - def action_link_id(link_action,link_id) - "#{controller_id}-#{link_action}-#{link_id}-link" - end - - def active_scaffold_column_header_id(column) - name = column.respond_to?(:name) ? column.name : column.to_s - clean_id "#{controller_id}-#{name}-column" - end - - def element_row_id(options = {}) - options[:action] ||= params[:action] - options[:id] ||= params[:id] - options[:id] ||= params[:parent_id] - clean_id "#{controller_id}-#{options[:action]}-#{options[:id]}-row" - end - - def element_cell_id(options = {}) - options[:action] ||= params[:action] - options[:id] ||= params[:id] - options[:id] ||= params[:parent_id] - options[:name] ||= params[:name] - clean_id "#{controller_id}-#{options[:action]}-#{options[:id]}-#{options[:name]}-cell" - end - - def element_form_id(options = {}) - options[:action] ||= params[:action] - options[:id] ||= params[:id] - options[:id] ||= params[:parent_id] - clean_id "#{controller_id}-#{options[:action]}-#{options[:id]}-form" - end - - def association_subform_id(column) - klass = column.association.klass.to_s.underscore - clean_id "#{controller_id}-associated-#{klass}" - end - - def loading_indicator_id(options = {}) - options[:action] ||= params[:action] - unless options[:id] - clean_id "#{controller_id}-#{options[:action]}-loading-indicator" - else - clean_id "#{controller_id}-#{options[:action]}-#{options[:id]}-loading-indicator" - end - end - - def sub_form_id(options = {}) - options[:id] ||= params[:id] - options[:id] ||= params[:parent_id] - clean_id "#{controller_id}-#{options[:id]}-#{options[:association]}-subform" - end - - def sub_form_list_id(options = {}) - options[:id] ||= params[:id] - options[:id] ||= params[:parent_id] - clean_id "#{controller_id}-#{options[:id]}-#{options[:association]}-subform-list" - end - - def element_messages_id(options = {}) - options[:action] ||= params[:action] - options[:id] ||= params[:id] - options[:id] ||= params[:parent_id] - clean_id "#{controller_id}-#{options[:action]}-#{options[:id]}-messages" - end - - def action_iframe_id(options) - "#{controller_id}-#{options[:action]}-#{options[:id]}-iframe" - end - - private - - # whitelists id-safe characters - def clean_id(val) - val.gsub /[^-_0-9a-zA-Z]/, '-' - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/list_column_helpers.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/list_column_helpers.rb deleted file mode 100644 index 7c8cdc2..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/list_column_helpers.rb +++ /dev/null @@ -1,371 +0,0 @@ -# coding: utf-8 -module ActiveScaffold - module Helpers - # Helpers that assist with the rendering of a List Column - module ListColumnHelpers - def get_column_value(record, column) - begin - # check for an override helper - value = if column_override? column - # we only pass the record as the argument. we previously also passed the formatted_value, - # but mike perham pointed out that prohibited the usage of overrides to improve on the - # performance of our default formatting. see issue #138. - send(column_override(column), record) - # second, check if the dev has specified a valid list_ui for this column - elsif column.list_ui and override_column_ui?(column.list_ui) - send(override_column_ui(column.list_ui), column, record) - - elsif inplace_edit?(record, column) - active_scaffold_inplace_edit(record, column) - elsif column.column and override_column_ui?(column.column.type) - send(override_column_ui(column.column.type), column, record) - else - format_column_value(record, column) - end - - value = ' '.html_safe if value.nil? or (value.respond_to?(:empty?) and value.empty?) # fix for IE 6 - return value - rescue Exception => e - logger.error Time.now.to_s + "#{e.inspect} -- on the ActiveScaffold column = :#{column.name} in #{@controller.class}" - raise e - end - end - - # TODO: move empty_field_text and   logic in here? - # TODO: move active_scaffold_inplace_edit in here? - # TODO: we need to distinguish between the automatic links *we* create and the ones that the dev specified. some logic may not apply if the dev specified the link. - def render_list_column(text, column, record) - if column.link - link = column.link - associated = record.send(column.association.name) if column.association - url_options = params_for(:action => nil, :id => record.id, :link => text) - url_options[:parent_controller] = params[:controller] if link.controller and link.controller.to_s != params[:controller] - url_options[:id] = associated.id if associated and link.controller and link.controller.to_s != params[:controller] - - # setup automatic link - if column.autolink? # link to nested scaffold or inline form - link = action_link_to_inline_form(column, associated) if link.crud_type.nil? # automatic link to inline form (singular association) - return text if link.crud_type.nil? - if link.crud_type == :create - url_options[:link] = as_(link.label, :model => column.association.klass.human_name, :parent => column.association.active_record.human_name) - url_options[:parent_id] = record.id - url_options[:parent_column] = column.association.reverse - url_options[:parent_model] = record.class.name # needed for polymorphic associations - url_options.delete :id - end - end - - # check authorization - if column.association - associated_for_authorized = if associated.nil? || (associated.respond_to?(:blank?) && associated.blank?) - column.association.klass - elsif column.plural_association? - associated.first - else - associated - end - authorized = associated_for_authorized.authorized_for?(:crud_type => link.crud_type) - authorized = authorized and record.authorized_for?(:crud_type => :update, :column => column.name) if link.crud_type == :create - else - authorized = record.authorized_for?(:crud_type => link.crud_type) - end - return "#{text}" unless authorized - - render_action_link(link, url_options, record) - else - text - end - end - - # setup the action link to inline form - def action_link_to_inline_form(column, associated) - link = column.link.clone - if column_empty?(associated) # if association is empty, we only can link to create form - if column.actions_for_association_links.include?(:new) - link.action = 'new' - link.crud_type = :create - end - elsif column.actions_for_association_links.include?(:edit) - link.action = 'edit' - link.crud_type = :update - elsif column.actions_for_association_links.include?(:show) - link.action = 'show' - link.crud_type = :read - end - link - end - - # There are two basic ways to clean a column's value: h() and sanitize(). The latter is useful - # when the column contains *valid* html data, and you want to just disable any scripting. People - # can always use field overrides to clean data one way or the other, but having this override - # lets people decide which way it should happen by default. - # - # Why is it not a configuration option? Because it seems like a somewhat rare request. But it - # could eventually be an option in config.list (and config.show, I guess). - def clean_column_value(v) - h(v) - end - - ## - ## Overrides - ## - def active_scaffold_column_text(column, record) - truncate(clean_column_value(record.send(column.name)), :length => column.options[:truncate] || 50) - end - - def active_scaffold_column_checkbox(column, record) - if inplace_edit?(record, column) - id_options = {:id => record.id.to_s, :action => 'update_column', :name => column.name.to_s} - tag_options = {:id => element_cell_id(id_options), :class => "in_place_editor_field"} - content_tag(:span, format_column_checkbox(record, column), tag_options) - else - check_box(:record, column.name, :disabled => true, :id => nil, :object => record) - end - end - - def column_override_name(column, old = false) - "#{clean_class_name(column.active_record_class.name) + '_' unless old}#{clean_column_name(column.name)}_column" - end - - def column_override(column) - method = column_override_name(column) - return method if respond_to?(method) - old_method = column_override_name(column, true) - if respond_to?(old_method) - ActiveSupport::Deprecation.warn("You are using an old naming schema for overrides, you should name the helper #{method} instead of #{old_method}") - old_method - end - end - alias_method :column_override?, :column_override - - def override_column_ui?(list_ui) - respond_to?(override_column_ui(list_ui)) - end - - # the naming convention for overriding column types with helpers - def override_column_ui(list_ui) - "active_scaffold_column_#{list_ui}" - end - - ## - ## Formatting - ## - - def format_column_checkbox(record, column) - checked = ActionView::Helpers::InstanceTag.check_box_checked?(record.send(column.name), '1') - script = remote_function(:method => 'POST', :url => {:controller => params_for[:controller], :action => "update_column", :column => column.name, :id => record.id.to_s, :value => checked ? false : 1, :eid => params[:eid]}) - check_box(:record, column.name, :onclick => script, :id => nil, :object => record) - end - - def format_column_value(record, column, value = nil) - value ||= record.send(column.name) unless record.nil? - if value && column.association # cache association size before calling column_empty? - associated_size = value.size if column.plural_association? and column.associated_number? # get count before cache association - cache_association(value, column) - end - if column.association.nil? or column_empty?(value) - if column.form_ui == :select && column.options[:options] - text, val = column.options[:options].find {|text, val| (val.nil? ? text : val).to_s == value.to_s} - value = active_scaffold_translated_option(column, text, val).first if text - end - if value.is_a? Numeric - format_number_value(value, column.options) - else - format_value(value, column.options) - end - else - format_association_value(value, column, associated_size) - end - end - - def format_number_value(value, options = {}) - value = case options[:format] - when :size - number_to_human_size(value, options[:i18n_options] || {}) - when :percentage - number_to_percentage(value, options[:i18n_options] || {}) - when :currency - number_to_currency(value, options[:i18n_options] || {}) - when :i18n_number - number_with_delimiter(value, options[:i18n_options] || {}) - else - value - end - clean_column_value(value) - end - - def format_association_value(value, column, size) - case column.association.macro - when :has_one, :belongs_to - format_value(value.to_label) - when :has_many, :has_and_belongs_to_many - if column.associated_limit.nil? - firsts = value.collect { |v| clean_column_value(v.to_label) } - else - firsts = value.first(column.associated_limit) - firsts.collect! { |v| clean_column_value(v.to_label) } - firsts[column.associated_limit] = '…' if value.size > column.associated_limit - end - if column.associated_limit == 0 - size if column.associated_number? - else - joined_associated = firsts.join(active_scaffold_config.list.association_join_text) - joined_associated << " (#{size})" if column.associated_number? and column.associated_limit and value.size > column.associated_limit - joined_associated - end - end - end - - def format_value(column_value, options = {}) - value = if column_empty?(column_value) - active_scaffold_config.list.empty_field_text - elsif column_value.is_a?(Time) || column_value.is_a?(Date) - l(column_value, :format => options[:format] || :default) - elsif [FalseClass, TrueClass].include?(column_value.class) - as_(column_value.to_s.to_sym) - else - column_value.to_s - end - clean_column_value(value) - end - - def cache_association(value, column) - # we are not using eager loading, cache firsts records in order not to query the database in a future - unless value.loaded? - # load at least one record, is needed for column_empty? and checking permissions - if column.associated_limit.nil? - Rails.logger.warn "ActiveScaffold: Enable eager loading for #{column.name} association to reduce SQL queries" - else - value.target = value.find(:all, :limit => column.associated_limit + 1, :select => column.select_columns) - end - end - end - - # ========== - # = Inline Edit = - # ========== - - def inplace_edit?(record, column) - column.inplace_edit and record.authorized_for?(:crud_type => :update, :column => column.name) - end - - def inplace_edit_cloning?(column) - column.inplace_edit != :ajax and (override_form_field?(column) or column.form_ui or (column.column and override_input?(column.column.type))) - end - - def format_inplace_edit_column(record,column) - if column.list_ui == :checkbox - format_column_checkbox(record, column) - else - format_column_value(record, column) - end - end - - def active_scaffold_inplace_edit(record, column, options = {}) - formatted_column = options[:formatted_column] || format_column_value(record, column) - id_options = {:id => record.id.to_s, :action => 'update_column', :name => column.name.to_s} - tag_options = {:id => element_cell_id(id_options), :class => "in_place_editor_field"} - in_place_editor_options = { - :url => {:controller => params_for[:controller], :action => "update_column", :column => column.name, :id => record.id.to_s}, - :with => params[:eid] ? "Form.serialize(form) + '&eid=#{params[:eid]}'" : nil, - :click_to_edit_text => as_(:click_to_edit), - :cancel_text => as_(:cancel), - :loading_text => as_(:loading), - :save_text => as_(:update), - :saving_text => as_(:saving), - :ajax_options => "{method: 'post'}", - :script => true - } - - if inplace_edit_cloning?(column) - in_place_editor_options.merge!( - :inplace_pattern_selector => "##{active_scaffold_column_header_id(column)} .#{inplace_edit_control_css_class}", - :node_id_suffix => record.id.to_s, - :form_customization => 'element.clonePatternField();' - ) - elsif column.inplace_edit == :ajax - url = url_for(:controller => params_for[:controller], :action => 'render_field', :id => record.id, :column => column.name, :update_column => column.name, :in_place_editing => true, :escape => false) - plural = column.plural_association? && !override_form_field?(column) && [:select, :record_select].include?(column.form_ui) - in_place_editor_options[:form_customization] = "element.setFieldFromAjax('#{escape_javascript(url)}', {plural: #{!!plural}});" - elsif column.column.try(:type) == :text - in_place_editor_options[:rows] = column.options[:rows] || 5 - end - - in_place_editor_options.merge!(column.options) - content_tag(:span, formatted_column, tag_options) + active_scaffold_in_place_editor(tag_options[:id], in_place_editor_options) - end - - def inplace_edit_control(column) - if inplace_edit?(active_scaffold_config.model, column) and inplace_edit_cloning?(column) - @record = active_scaffold_config.model.new - column = column.clone - column.update_column = nil - column.form_ui = :select if (column.association && column.form_ui.nil?) - content_tag(:div, active_scaffold_input_for(column), {:style => "display:none;", :class => inplace_edit_control_css_class}) - end - end - - def inplace_edit_control_css_class - "as_inplace_pattern" - end - - def active_scaffold_in_place_editor(field_id, options = {}) - function = "new ActiveScaffold.InPlaceEditor(" - function << "'#{field_id}', " - function << "'#{url_for(options[:url])}'" - - js_options = {} - - if protect_against_forgery? - options[:with] ||= "Form.serialize(form)" - options[:with] += " + '&authenticity_token=' + encodeURIComponent('#{form_authenticity_token}')" - end - - js_options['cancelText'] = %('#{options[:cancel_text]}') if options[:cancel_text] - js_options['okText'] = %('#{options[:save_text]}') if options[:save_text] - js_options['okControl'] = %('#{options[:save_control_type]}') if options[:save_control_type] - js_options['cancelControl'] = %('#{options[:cancel_control_type]}') if options[:cancel_control_type] - js_options['loadingText'] = %('#{options[:loading_text]}') if options[:loading_text] - js_options['savingText'] = %('#{options[:saving_text]}') if options[:saving_text] - js_options['rows'] = options[:rows] if options[:rows] - js_options['cols'] = options[:cols] if options[:cols] - js_options['size'] = options[:size] if options[:size] - js_options['externalControl'] = "'#{options[:external_control]}'" if options[:external_control] - js_options['externalControlOnly'] = "true" if options[:external_control_only] - js_options['submitOnBlur'] = "'#{options[:submit_on_blur]}'" if options[:submit_on_blur] - js_options['loadTextURL'] = "'#{url_for(options[:load_text_url])}'" if options[:load_text_url] - js_options['ajaxOptions'] = options[:ajax_options] if options[:ajax_options] - js_options['htmlResponse'] = !options[:script] if options[:script] - js_options['callback'] = "function(form) { return #{options[:with]} }" if options[:with] - js_options['clickToEditText'] = %('#{options[:click_to_edit_text]}') if options[:click_to_edit_text] - js_options['textBetweenControls'] = %('#{options[:text_between_controls]}') if options[:text_between_controls] - js_options['highlightcolor'] = %('#{options[:highlight_color]}') if options[:highlight_color] - js_options['highlightendcolor'] = %('#{options[:highlight_end_color]}') if options[:highlight_end_color] - js_options['onFailure'] = "function(element, transport) { #{options[:failure]} }" if options[:failure] - js_options['onComplete'] = "function(transport, element) { #{options[:complete]} }" if options[:complete] - js_options['onEnterEditMode'] = "function(element) { #{options[:enter_editing]} }" if options[:enter_editing] - js_options['onLeaveEditMode'] = "function(element) { #{options[:exit_editing]} }" if options[:exit_editing] - js_options['onFormCustomization'] = "function(element, form) { #{options[:form_customization]} }" if options[:form_customization] - js_options['inplacePatternSelector'] = %('#{options[:inplace_pattern_selector]}') if options[:inplace_pattern_selector] - js_options['nodeIdSuffix'] = %('#{options[:node_id_suffix]}') if options[:node_id_suffix] - function << (', ' + options_for_javascript(js_options)) unless js_options.empty? - - function << ')' - - javascript_tag(function) - end - - def mark_record(checked, url_params = {}) - url_params.reverse_merge!(:controller => params_for[:controller], :action => 'mark', :eid => params[:eid]) - ajax_options = {:method => :put, - :url => url_for(url_params), - :with => "'value=' + this.checked", - :after => "var checkbox = this; this.disable();", - :complete => "checkbox.enable();"} - script = remote_function(ajax_options) - check_box_tag('mark', '1', checked, :onclick => script, :class => 'mark_record') - end - - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/pagination_helpers.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/pagination_helpers.rb deleted file mode 100644 index 5686341..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/pagination_helpers.rb +++ /dev/null @@ -1,63 +0,0 @@ -module ActiveScaffold - module Helpers - module PaginationHelpers - def pagination_ajax_link(page_number, params) - url = url_for params.merge(:page => page_number) - page_link = link_to_remote(page_number, - { :url => url, - :before => "addActiveScaffoldPageToHistory('#{url}', '#{controller_id}');", - :after => "$('#{loading_indicator_id(:action => :pagination)}').style.visibility = 'visible';", - :complete => "$('#{loading_indicator_id(:action => :pagination)}').style.visibility = 'hidden';", - :failure => "ActiveScaffold.report_500_response('#{active_scaffold_id}')", - :method => :get }, - { :href => url_for(params.merge(:page => page_number)) }) - end - - def pagination_ajax_links(current_page, params, window_size) - start_number = current_page.number - window_size - end_number = current_page.number + window_size - start_number = 1 if start_number <= 0 - if current_page.pager.infinite? - offsets = [20, 100] - else - end_number = current_page.pager.last.number if end_number > current_page.pager.last.number - end - - html = [] - unless start_number == 1 - last_page = 1 - html << pagination_ajax_link(last_page, params) - if current_page.pager.infinite? - offsets.reverse.each do |offset| - page = current_page.number - offset - if page < start_number && page > 1 - html << '..' if page > last_page + 1 - html << pagination_ajax_link(page, params) - last_page = page - end - end - end - html << ".." if start_number > last_page + 1 - end - - start_number.upto(end_number) do |num| - if current_page.number == num - html << content_tag(:span, num) - else - html << pagination_ajax_link(num, params) - end - end - - if current_page.pager.infinite? - offsets.each do |offset| - html << '..' << pagination_ajax_link(current_page.number + offset, params) - end - else - html << ".." unless end_number >= current_page.pager.last.number - 1 - html << pagination_ajax_link(current_page.pager.last.number, params) unless end_number == current_page.pager.last.number - end - html.join(' ').html_safe - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/search_column_helpers.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/search_column_helpers.rb deleted file mode 100644 index d232af0..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/search_column_helpers.rb +++ /dev/null @@ -1,211 +0,0 @@ -module ActiveScaffold - module Helpers - # Helpers that assist with the rendering of a Form Column - module SearchColumnHelpers - # This method decides which input to use for the given column. - # It does not do any rendering. It only decides which method is responsible for rendering. - def active_scaffold_search_for(column) - options = active_scaffold_search_options(column) - - # first, check if the dev has created an override for this specific field for search - if override_search_field?(column) - send(override_search_field(column), @record, options) - - # second, check if the dev has specified a valid search_ui for this column, using specific ui for searches - elsif column.search_ui and override_search?(column.search_ui) - send(override_search(column.search_ui), column, options) - - # third, check if the dev has specified a valid search_ui for this column, using generic ui for forms - elsif column.search_ui and override_input?(column.search_ui) - send(override_input(column.search_ui), column, options) - - # fourth, check if the dev has created an override for this specific field - elsif override_form_field?(column) - send(override_form_field(column), @record, options) - - # fallback: we get to make the decision - else - if column.association or column.virtual? - active_scaffold_search_text(column, options) - - else # regular model attribute column - # if we (or someone else) have created a custom render option for the column type, use that - if override_search?(column.column.type) - send(override_search(column.column.type), column, options) - # if we (or someone else) have created a custom render option for the column type, use that - elsif override_input?(column.column.type) - send(override_input(column.column.type), column, options) - # final ultimate fallback: use rails' generic input method - else - # for textual fields we pass different options - text_types = [:text, :string, :integer, :float, :decimal] - options = active_scaffold_input_text_options(options) if text_types.include?(column.column.type) - input(:record, column.name, options.merge(column.options)) - end - end - end - end - - # the standard active scaffold options used for class, name and scope - def active_scaffold_search_options(column) - { :name => "search[#{column.name}]", :class => "#{column.name}-input", :id => "search_#{column.name}", :value => field_search_params[column.name] } - end - - ## - ## Search input methods - ## - - def active_scaffold_search_multi_select(column, options) - associated = options.delete :value - associated = [associated].compact unless associated.is_a? Array - associated.collect!(&:to_i) - select_options = options_for_association(column.association, true) - return as_(:no_options) if select_options.empty? - - html = "
    " - - options[:name] += '[]' - select_options.each_with_index do |option, i| - label, id = option - this_id = "#{options[:id]}_#{i}_id" - html << "
  • " - html << check_box_tag(options[:name], id, associated.include?(id), :id => this_id) - html << "" - html << "
  • " - end - - html << '
' - html << javascript_tag("new DraggableLists('#{options[:id]}')") if column.options[:draggable_lists] - html - end - - def active_scaffold_search_select(column, html_options) - associated = html_options.delete :value - if column.association - associated = associated.is_a?(Array) ? associated.map(&:to_i) : associated.to_i unless associated.nil? - method = column.association.macro == :belongs_to ? column.association.primary_key_name : column.name - options_for_select = options_for_association(column.association, true) - else - method = column.name - options_for_select = active_scaffold_translated_options(column) - end - - options = { :selected => associated }.merge! column.options - html_options.merge! column.options[:html_options] || {} - if html_options[:multiple] - html_options[:name] += '[]' - else - options[:include_blank] ||= as_(:_select_) - end - select(:record, method, options_for_select, options, html_options) - end - - def active_scaffold_search_text(column, options) - text_field :record, column.name, active_scaffold_input_text_options(options) - end - - # we can't use active_scaffold_input_boolean because we need to have a nil value even when column can't be null - # to decide whether search for this field or not - def active_scaffold_search_boolean(column, options) - select_options = [] - select_options << [as_(:_select_), nil] - select_options << [as_(:true), true] - select_options << [as_(:false), false] - - select_tag(options[:name], options_for_select(select_options, column.column.type_cast(field_search_params[column.name]))) - end - # we can't use checkbox ui because it's not possible to decide whether search for this field or not - alias_method :active_scaffold_search_checkbox, :active_scaffold_search_boolean - - def field_search_params_range_values(column) - values = field_search_params[column.name] - return nil if values.nil? - return values[:opt], values[:from], values[:to] - end - - def include_null_comparators?(column) - return column.options[:null_comparators] if column.options.has_key? :null_comparators - if column.association - column.association.macro != :belongs_to || active_scaffold_config.columns[column.association.primary_key_name].column.try(:null) - else - column.column.try(:null) - end - end - - def active_scaffold_search_range(column, options) - opt_value, from_value, to_value = field_search_params_range_values(column) - select_options = ActiveScaffold::Finder::NumericComparators.collect {|comp| [as_(comp.downcase.to_sym), comp]} - select_options.unshift *ActiveScaffold::Finder::StringComparators.collect {|title, comp| [as_(title), comp]} if column.options[:string_comparators] || column.column.try(:text?) - select_options += ActiveScaffold::Finder::NullComparators.collect {|comp| [as_(comp.downcase.to_sym), comp]} if include_null_comparators? column - - html = [] - html << select_tag("#{options[:name]}[opt]", - options_for_select(select_options, opt_value), - :id => "#{options[:id]}_opt", - :onchange => "Element[this.value == 'BETWEEN' ? 'show' : 'hide']('#{options[:id]}_between');") - html << text_field_tag("#{options[:name]}[from]", from_value, active_scaffold_input_text_options(:id => options[:id], :size => 10)) - html << content_tag(:span, ' - ' + text_field_tag("#{options[:name]}[to]", to_value, - active_scaffold_input_text_options(:id => "#{options[:id]}_to", :size => 10)), - :id => "#{options[:id]}_between", :style => "display:none") - html * ' ' - end - alias_method :active_scaffold_search_integer, :active_scaffold_search_range - alias_method :active_scaffold_search_decimal, :active_scaffold_search_range - alias_method :active_scaffold_search_float, :active_scaffold_search_range - alias_method :active_scaffold_search_string, :active_scaffold_search_range - - def field_search_datetime_value(value) - DateTime.new(value[:year].to_i, value[:month].to_i, value[:day].to_i, value[:hour].to_i, value[:minute].to_i, value[:second].to_i) unless value.nil? || value[:year].blank? - end - - def active_scaffold_search_datetime(column, options) - opt_value, from_value, to_value = field_search_params_range_values(column) - options = column.options.merge(options) - helper = "select_#{'date' unless options[:discard_date]}#{'time' unless options[:discard_time]}" - html = [] - html << send(helper, field_search_datetime_value(from_value), {:include_blank => true, :prefix => "#{options[:name]}[from]"}.merge(options)) - html << send(helper, field_search_datetime_value(to_value), {:include_blank => true, :prefix => "#{options[:name]}[to]"}.merge(options)) - html * ' - ' - end - - def active_scaffold_search_date(column, options) - active_scaffold_search_datetime(column, options.merge!(:discard_time => true)) - end - def active_scaffold_search_time(column, options) - active_scaffold_search_datetime(column, options.merge!(:discard_date => true)) - end - alias_method :active_scaffold_search_timestamp, :active_scaffold_search_datetime - - ## - ## Search column override signatures - ## - - def override_search_field(column) - method = override_search_field_name(column) - return method if respond_to?(method) - old_method = override_search_field_name(column, true) - if respond_to?(old_method) - ActiveSupport::Deprecation.warn("You are using an old naming schema for overrides, you should name the helper #{method} instead of #{old_method}") - old_method - end - end - alias_method :override_search_field?, :override_search_field - - # the naming convention for overriding form fields with helpers - def override_search_field_name(column, old = false) - "#{clean_class_name(column.active_record_class.name) + '_' unless old}#{clean_column_name(column.name)}_search_column" - end - - def override_search?(search_ui) - respond_to?(override_search(search_ui)) - end - - # the naming convention for overriding search input types with helpers - def override_search(form_ui) - "active_scaffold_search_#{form_ui}" - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/show_column_helpers.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/show_column_helpers.rb deleted file mode 100644 index 27e5006..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/show_column_helpers.rb +++ /dev/null @@ -1,53 +0,0 @@ -module ActiveScaffold - module Helpers - # Helpers that assist with the rendering of a List Column - module ShowColumnHelpers - def show_column_value(record, column) - # check for an override helper - if show_column_override? column - # we only pass the record as the argument. we previously also passed the formatted_value, - # but mike perham pointed out that prohibited the usage of overrides to improve on the - # performance of our default formatting. see issue #138. - send(show_column_override(column), record) - # second, check if the dev has specified a valid list_ui for this column - elsif column.list_ui and override_show_column_ui?(column.list_ui) - send(override_show_column_ui(column.list_ui), column, record) - else - if column.column and override_show_column_ui?(column.column.type) - send(override_show_column_ui(column.column.type), column, record) - else - get_column_value(record, column) - end - end - end - - def active_scaffold_show_text(column, record) - simple_format(clean_column_value(record.send(column.name))) - end - - def show_column_override_name(column, old = false) - "#{clean_class_name(column.active_record_class.name) + '_' unless old}#{clean_column_name(column.name)}_show_column" - end - - def show_column_override(column) - method = show_column_override_name(column) - return method if respond_to?(method) - old_method = show_column_override_name(column, true) - if respond_to?(old_method) - ActiveSupport::Deprecation.warn("You are using an old naming schema for overrides, you should name the helper #{method} instead of #{old_method}") - old_method - end - end - alias_method :show_column_override?, :show_column_override - - def override_show_column_ui?(list_ui) - respond_to?(override_show_column_ui(list_ui)) - end - - # the naming convention for overriding show types with helpers - def override_show_column_ui(list_ui) - "active_scaffold_show_#{list_ui}" - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/view_helpers.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/view_helpers.rb deleted file mode 100755 index c0190da..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/helpers/view_helpers.rb +++ /dev/null @@ -1,230 +0,0 @@ -module ActiveScaffold - module Helpers - # All extra helpers that should be included in the View. - # Also a dumping ground for uncategorized helpers. - module ViewHelpers - include ActiveScaffold::Helpers::IdHelpers - include ActiveScaffold::Helpers::AssociationHelpers - include ActiveScaffold::Helpers::PaginationHelpers - include ActiveScaffold::Helpers::ListColumnHelpers - include ActiveScaffold::Helpers::ShowColumnHelpers - include ActiveScaffold::Helpers::FormColumnHelpers - include ActiveScaffold::Helpers::SearchColumnHelpers - include ActiveScaffold::Helpers::CountryHelpers - - ## - ## Delegates - ## - - # access to the configuration variable - def active_scaffold_config - @controller.class.active_scaffold_config - end - - def active_scaffold_config_for(*args) - @controller.class.active_scaffold_config_for(*args) - end - - def active_scaffold_controller_for(*args) - @controller.class.active_scaffold_controller_for(*args) - end - - ## - ## Uncategorized - ## - - def generate_temporary_id - (Time.now.to_f*1000).to_i.to_s - end - - # Turns [[label, value]] into " : "" - end - end - - # Should this column be displayed in the subform? - def in_subform?(column, parent_record) - return true unless column.association - - # Polymorphic associations can't appear because they *might* be the reverse association, and because you generally don't assign an association from the polymorphic side ... I think. - return false if column.polymorphic_association? - - # A column shouldn't be in the subform if it's the reverse association to the parent - return false if column.association.reverse_for?(parent_record.class) - - return true - end - - def form_remote_upload_tag(url_for_options = {}, options = {}) - onsubmits = options[:onsubmit] ? [ options[:onsubmit] ] : [ ] - # simulate a "loading". the setTimeout prevents the Form.disable from being called before the submit, so that data actually posts. - onsubmits << "setTimeout(function() { #{options[:loading]} }, 10); " - onsubmits << "return true" # make sure the form still submits - - options[:onsubmit] = onsubmits * ';' - options[:target] = action_iframe_id(url_for_options) - options[:multipart] = true - - output = form_tag(url_for_options, options) - output << "".html_safe - end - - # Provides list of javascripts to include with +javascript_include_tag+ - # You can use this with your javascripts like - # <%= javascript_include_tag :defaults, 'your_own_cool_script', active_scaffold_javascripts, :cache => true %> - def active_scaffold_javascripts(frontend = :default) - ActiveScaffold::Config::Core.javascripts(frontend).collect do |name| - ActiveScaffold::Config::Core.asset_path(name, frontend) - end - end - - # Provides stylesheets to include with +stylesheet_link_tag+ - def active_scaffold_stylesheets(frontend = :default) - [ActiveScaffold::Config::Core.asset_path("stylesheet.css", frontend)] - end - - # Provides stylesheets for IE to include with +stylesheet_link_tag+ - def active_scaffold_ie_stylesheets(frontend = :default) - [ActiveScaffold::Config::Core.asset_path("stylesheet-ie.css", frontend)] - end - - # easy way to include ActiveScaffold assets - def active_scaffold_includes(*args) - frontend = args.first.is_a?(Symbol) ? args.shift : :default - options = args.first.is_a?(Hash) ? args.shift : {} - js = javascript_include_tag(*active_scaffold_javascripts(frontend).push(options)) - - css = stylesheet_link_tag(*active_scaffold_stylesheets(frontend).push(options)) - options[:cache] += '_ie' if options[:cache].is_a? String - options[:concat] += '_ie' if options[:concat].is_a? String - ie_css = stylesheet_link_tag(*active_scaffold_ie_stylesheets(frontend).push(options)) - - "#{js}\n#{css}\n\n".html_safe - end - - # a general-use loading indicator (the "stuff is happening, please wait" feedback) - def loading_indicator_tag(options) - image_tag "/images/active_scaffold/default/indicator.gif", :style => "visibility:hidden;", :id => loading_indicator_id(options), :alt => "loading indicator", :class => "loading-indicator" - end - - # Creates a javascript-based link that toggles the visibility of some element on the page. - # By default, it toggles the visibility of the sibling after the one it's nested in. You may pass custom javascript logic in options[:of] to change that, though. For example, you could say :of => '$("my_div_id")'. - # You may also flag whether the other element is visible by default or not, and the initial text will adjust accordingly. - def link_to_visibility_toggle(options = {}) - options[:of] ||= '$(this.parentNode).next()' - options[:default_visible] = true if options[:default_visible].nil? - - link_text = options[:default_visible] ? as_(:hide) : as_(:show) - link_to_function link_text, "e = #{options[:of]}; e.toggle(); this.innerHTML = (e.style.display == 'none') ? '#{as_(:show)}' : '#{as_(:hide)}'", :class => 'visibility-toggle' - end - - def skip_action_link(link) - (link.security_method_set? or controller.respond_to? link.security_method) and !controller.send(link.security_method) - end - - def render_action_link(link, url_options, record = nil, html_options = {}) - url_options = url_options.clone - url_options[:action] = link.action - url_options[:controller] = link.controller if link.controller - url_options.delete(:search) if link.controller and link.controller.to_s != params[:controller] - url_options.merge! link.parameters if link.parameters - - html_options.reverse_merge! link.html_options.merge(:class => link.action) - if link.inline? - # NOTE this is in url_options instead of html_options on purpose. the reason is that the client-side - # action link javascript needs to submit the proper method, but the normal html_options[:method] - # argument leaves no way to extract the proper method from the rendered tag. - url_options[:_method] = link.method - - if link.method != :get and respond_to?(:protect_against_forgery?) and protect_against_forgery? - url_options[:authenticity_token] = form_authenticity_token - end - - # robd: protect against submitting get links as forms, since this causes annoying - # 'Do you wish to resubmit your form?' messages whenever you go back and forwards. - elsif link.method != :get - # Needs to be in html_options to as the adding _method to the url is no longer supported by Rails - html_options[:method] = link.method - end - - html_options[:confirm] = link.confirm(record.try(:to_label)) if link.confirm? - html_options[:position] = link.position if link.position and link.inline? - html_options[:class] += ' action' if link.inline? - html_options[:popup] = true if link.popup? - html_options[:id] = action_link_id("#{id_from_controller(url_options[:controller]) + '-' if url_options[:parent_controller]}" + "#{url_options[:associations].to_s + '-' if url_options[:associations]}" + url_options[:action].to_s,url_options[:id] || url_options[:parent_id]) - - if link.dhtml_confirm? - html_options[:class] += ' action' if !link.inline? - html_options[:page_link] = 'true' if !link.inline? - html_options[:dhtml_confirm] = link.dhtml_confirm.value - html_options[:onclick] = link.dhtml_confirm.onclick_function(controller,action_link_id(url_options[:action],url_options[:id] || url_options[:parent_id])) - end - html_options[:class] += " #{link.html_options[:class]}" unless link.html_options[:class].blank? - - # issue 260, use url_options[:link] if it exists. This prevents DB data from being localized. - label = url_options.delete(:link) || link.label - link_to label, url_options, html_options - end - - def column_class(column, column_value) - classes = [] - classes << "#{column.name}-column" - classes << column.css_class unless column.css_class.nil? - classes << 'empty' if column_empty? column_value - classes << 'sorted' if active_scaffold_config.list.user.sorting.sorts_on?(column) - classes << 'numeric' if column.column and [:decimal, :float, :integer].include?(column.column.type) - classes.join(' ') - end - - def column_empty?(column_value) - empty = column_value.nil? - empty ||= column_value.blank? if column_value.respond_to? :blank? - empty ||= [' '.html_safe, active_scaffold_config.list.empty_field_text].include? column_value if String === column_value - return empty - end - - def column_calculation(column) - conditions = controller.send(:all_conditions) - includes = active_scaffold_config.list.count_includes - includes ||= controller.send(:active_scaffold_includes) unless conditions.nil? - calculation = active_scaffold_config.model.calculate(column.calculate, column.name, :conditions => conditions, - :joins => controller.send(:joins_for_collection), :include => includes) - end - - def render_column_calculation(column) - calculation = column_calculation(column) - override_formatter = "render_#{column.name}_#{column.calculate}" - calculation = send(override_formatter, calculation) if respond_to? override_formatter - - "#{as_(column.calculate)}: #{format_column_value nil, column, calculation}" - end - - def column_show_add_existing(column) - (column.allow_add_existing and options_for_association_count(column.association) > 0) - end - - def column_show_add_new(column, associated, record) - value = column.plural_association? or (column.singular_association? and not associated.empty?) - value = false unless record.class.authorized_for?(:crud_type => :create) - value - end - - def controller_class - "#{h params[:controller]}-view" - end - - def clean_column_name(name) - name.to_s.gsub('?', '') - end - - def clean_class_name(name) - name.underscore.gsub('/', '_') - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/de.yml b/vendor/plugins/active_scaffold/lib/active_scaffold/locale/de.yml deleted file mode 100644 index 832f6a7..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/de.yml +++ /dev/null @@ -1,69 +0,0 @@ -'de': - active_scaffold: - add: 'Hinzufügen' - add_existing: 'Existierenden Eintrag hinzufügen' - add_existing_model: 'Existierende %{model} hinzufügen' - are_you_sure_to_delete: 'Sind Sie sicher?' - cancel: 'Abbrechen' - click_to_edit: 'Zum Editieren anklicken' - close: 'Schliessen' - create: 'Anlegen' - create_model: 'Lege %{model} an' - create_another: 'Weitere anlegen' - created_model: '%{model} anlegen' - create_new: 'Neu anlegen' - customize: 'Anpassen' - delete: 'Löschen' - deleted_model: '%{model} gelöscht' - delimiter: 'Trennzeichen' - download: 'Download' - edit: 'Bearbeiten' - export: 'Exportieren' - nested_for_model: '%{nested_model} für %{parent_model}' - filtered: '(Gefiltert)' - found: 'Gefunden' - hide: 'Verstecken' - live_search: 'Live-Suche' - loading: 'Lade…' - next: 'Vorwärts' - no_entries: 'Keine Einträge' - no_options: 'Keine Optionen' - omit_header: 'Lasse Header weg' - options: 'Optionen' - pdf: 'PDF' - previous: 'Zurück' - print: 'Drucken' - refresh: 'Neu laden' - remove: 'Entfernen' - remove_file: 'Entferne oder Ersetze Datei' - replace_with_new: 'Mit Neuer ersetzen' - revisions_for_model: 'Revisionen für %{model}' - reset: 'Zurücksetzen' - saving: 'Speichern…' - search: 'Suche' - search_terms: 'Suchbegriffe' - _select_: '- Auswählen -' - show: 'Anzeigen' - show_model: 'Zeige %{model} an' - _to_ : ' zu ' - update: 'Speichern' - update_model: 'Editiere %{model}' - updated_model: '%{model} aktualisiert' - '=': '=' - '>=': '>=' - '<=': '<=' - '>': '>' - '<': '<' - '!=': '!=' - between: 'Zwischen' - is_null: 'Is null' - is_not_null: 'Is not null' - contains: 'Contains' - begins_with: 'Begins with' - ends_with: 'Ends with' - - # error_messages - cant_destroy_record: "%{record} kann nicht gelöscht werden" - internal_error: 'Fehler bei der Verarbeitung (code 500, Interner Fehler)' - version_inconsistency: 'Inkonsistente Versionen - dieser Eintrag wurde verändert nachdem Sie mit der Bearbeitung begonnen haben.' - failed_to_save_record: 'Failed to save record cause of an unknown error' diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/en.yml b/vendor/plugins/active_scaffold/lib/active_scaffold/locale/en.yml deleted file mode 100644 index b14f20b..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/en.yml +++ /dev/null @@ -1,72 +0,0 @@ -'en': - active_scaffold: - add: 'Add' - add_existing: 'Add Existing' - add_existing_model: 'Add Existing %{model}' - are_you_sure_to_delete: 'Are you sure you want to delete %{label}?' - cancel: 'Cancel' - click_to_edit: 'Click to edit' - click_to_reset: 'Click to reset' - close: 'Close' - create: 'Create' - create_model: 'Create %{model}' - create_another: 'Create Another %{model}' - created_model: 'Created %{model}' - create_new: 'Create New' - customize: 'Customize' - delete: 'Delete' - deleted_model: 'Deleted %{model}' - delimiter: 'Delimiter' - download: 'Download' - edit: 'Edit' - export: 'Export' - nested_for_model: '%{nested_model} for %{parent_model}' - false: 'False' - filtered: '(Filtered)' - found: 'Found' - hide: 'Hide' - live_search: 'Live Search' - loading: 'Loading…' - next: 'Next' - no_entries: 'No Entries' - no_options: 'no options' - omit_header: 'Omit Header' - options: 'Options' - pdf: 'PDF' - previous: 'Previous' - print: 'Print' - refresh: 'Refresh' - remove: 'Remove' - remove_file: 'Remove or Replace file' - replace_with_new: 'Replace With New' - revisions_for_model: 'Revisions for %{model}' - reset: 'Reset' - saving: 'Saving…' - search: 'Search' - search_terms: 'Search Terms' - _select_: '- select -' - show: 'Show' - show_model: 'Show %{model}' - _to_ : ' to ' - true: 'True' - update: 'Update' - update_model: 'Update %{model}' - updated_model: 'Updated %{model}' - '=': '=' - '>=': '>=' - '<=': '<=' - '>': '>' - '<': '<' - '!=': '!=' - between: 'Between' - is_null: 'Is null' - is_not_null: 'Is not null' - contains: 'Contains' - begins_with: 'Begins with' - ends_with: 'Ends with' - - # error_messages - cant_destroy_record: "%{record} can't be destroyed" - internal_error: 'Request Failed (code 500, Internal Error)' - version_inconsistency: 'Version inconsistency - this record has been modified since you started editing it.' - failed_to_save_record: 'Failed to save record cause of an unknown error' diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/es.yml b/vendor/plugins/active_scaffold/lib/active_scaffold/locale/es.yml deleted file mode 100644 index 159058e..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/es.yml +++ /dev/null @@ -1,74 +0,0 @@ -es: - active_scaffold: - add: 'Añadir' - add_existing: 'Añadir Existente' - add_existing_model: 'Añadir %{model} Existente' - are_you_sure_to_delete: '¿Estás seguro de que quieres borrar %{label}?' - cancel: 'Cancelar' - click_to_edit: 'Pulsa para editar' - click_to_reset: 'Pulsa para restaurar' - close: 'Cerrar' - create: 'Crear' - create_model: 'Crear %{model}' - create_another: 'Crear Otro %{model}' - created_model: '%{model} creado' - create_new: 'Crear Nuevo' - customize: 'Personalizar' - delete: 'Borrar' - deleted_model: '%{model} borrado' - delimiter: 'Delimitador' - download: 'Descargar' - edit: 'Editar' - export: 'Exportar' - 'false': 'No' - filtered: '(Filtrado)' - found: - one: 'encontrado' - other: 'encontrados' - hide: 'Ocultar' - live_search: 'Buscar en Vivo' - loading: 'Cargando…' - nested_for_model: '%{nested_model} de %{parent_model}' - next: 'Siguiente' - no_entries: 'Sin entradas' - no_options: 'sin opciones' - omit_header: 'Omitir Cabecera' - options: 'Opciones' - pdf: 'PDF' - previous: 'Anterior' - print: 'Imprimir' - refresh: 'Recargar' - remove: 'Eliminar' - remove_file: 'Eliminar o Reemplazar archivo' - replace_with_new: 'Reemplazar con Nuevo' - revisions_for_model: 'Revisiones de %{model}' - reset: 'Restaurar' - saving: 'Guardando…' - search: 'Buscar' - search_terms: 'Términos a buscar' - _select_: '- seleccionar -' - show: 'Ver' - show_model: 'Ver %{model}' - _to_ : ' a ' - 'true': 'Sí' - update: 'Actualizar' - update_model: 'Actualizar %{model}' - updated_model: '%{model} actualizado' - '=': '=' - '>=': '>=' - '<=': '<=' - '>': '>' - '<': '<' - '!=': '!=' - between: 'Entre' - is_null: 'Es nulo' - is_not_null: 'No es nulo' - contains: 'Contiene' - begins_with: 'Empieza con' - ends_with: 'Termina con' - - # error_messages - cant_destroy_record: "No se pudo borrar %{record}" - internal_error: 'Petición fallida (código 500, error interno)' - version_inconsistency: 'Inconsistencia de versiones - este registro se ha modificado después de que empezó a editarlo.' - failed_to_save_record: 'Fallo al guardar el registro debido a un error desconocido' diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/fr.yml b/vendor/plugins/active_scaffold/lib/active_scaffold/locale/fr.yml deleted file mode 100644 index 74e8441..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/fr.yml +++ /dev/null @@ -1,68 +0,0 @@ -'fr': - active_scaffold: - add: 'Ajouter' - add_existing: 'Ajouter un(e) existant(e)' - add_existing_model: 'Ajouter un(e) %{model} existant(e)' - are_you_sure_to_delete: 'Êtes vous sûr?' - cancel: 'Annuler' - click_to_edit: 'Cliquer pour éditer' - close: 'Fermer' - create: 'Créer' - create_model: 'Créer %{model}' - create_another: 'Créer un autre' - created_model: '%{model} créé' - create_new: 'Créer un nouveau' - customize: 'Personnaliser' - delete: 'Supprimer' - deleted_model: 'Suppression de %{model}' - delimiter: 'Délimiteur' - download: 'Télécharger' - edit: 'Éditer' - export: 'Exporter' - nested_for_model: '%{nested_model} pour %{parent_model}' - filtered: '(Filtré)' - found: 'Trouvé' - hide: 'Cacher' - live_search: 'Recherche en temps réel' - loading: 'Chargement…' - next: 'Suivant' - no_entries: "Pas d'entrée" - no_options: "pas d'option" - omit_header: 'Omettre les en-têtes' - options: 'Options' - pdf: 'PDF' - previous: 'Précédent' - print: 'Imprimer' - refresh: 'Rafraîchir' - remove: 'Supprimer' - remove_file: 'Supprimer et remplacer le fichier' - replace_with_new: 'Remplacer avec le nouveau' - revisions_for_model: 'Révision pour %{model}' - reset: 'Annuler' - saving: 'Sauvegarder…' - search: 'Rechercher' - search_terms: 'Recherche de termes' - _select_: '- sélectionner -' - show: 'Montrer' - show_model: 'Montrer %{model}' - _to_ : ' à ' - update: 'Mettre à jour' - update_model: 'Mettre à jour le(/la) %{model}' - updated_model: 'Mis à jour de %{model}' - '=': '=' - '>=': '>=' - '<=': '<=' - '>': '>' - '<': '<' - '!=': '!=' - between: 'Entre' - is_null: 'Is null' - is_not_null: 'Is not null' - contains: 'Contains' - begins_with: 'Begins with' - ends_with: 'Ends with' - - # error_messages - internal_error: 'Erreur de la requête (code 500, Erreur interne)' - version_inconsistency: "Version incomplète - Cet enregistrement a été modifié depuis que vous avez commencé à l'éditer." - failed_to_save_record: 'Failed to save record cause of an unknown error' diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/hu.yml b/vendor/plugins/active_scaffold/lib/active_scaffold/locale/hu.yml deleted file mode 100644 index 0639dfa..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/hu.yml +++ /dev/null @@ -1,68 +0,0 @@ -hu: - active_scaffold: - add: 'Hozzáadás' - add_existing: 'Meglevő hozzáadása' - add_existing_model: 'Meglevő %{model} hozzáadása' - are_you_sure_to_delete: 'Biztos vagy benne?' - cancel: 'Mégse' - click_to_edit: 'Kattints a szerkesztéshez' - close: 'Bezárás' - create: 'Létrehozás' - create_model: '%{model} létrehozása' - create_another: 'Mégegy hozzáadása' - created_model: '%{model} létrehozva' - create_new: 'Új létrehozása' - customize: 'Testreszabás' - delete: 'Törlés' - deleted_model: '%{model} törölve' - delimiter: 'Elválasztó' - download: 'Letöltés' - edit: 'Szerkesztés' - export: 'Exportálás' - nested_for_model: '%{nested_model} / %{parent_model}' - filtered: '(Szűrt)' - found: 'Találat' - hide: 'Elrejtés' - live_search: 'Élő keresés' - loading: 'Betöltés…' - next: 'Következő' - no_entries: 'Nincs elem' - no_options: 'nincsenek' - omit_header: 'Fejléc nélkül' - options: 'Opciók' - pdf: 'PDF' - previous: 'Előző' - print: 'Nyomtatás' - refresh: 'Frissítés' - remove: 'Törlés' - remove_file: 'Fájl törlése, vagy cseréje' - replace_with_new: 'Csere újjal' - revisions_for_model: '%{model} revíziói' - reset: 'Alapállapot' - saving: 'Mentés…' - search: 'Keresés' - search_terms: 'Keresési kifejezések' - _select_: '- válassz -' - show: 'Mutatás' - show_model: '%{model} mutatása' - _to_ : ' – ' - update: 'Modosítás' - update_model: '%{model} modosítása' - updated_model: '%{model} módosítva' - '=': '=' - '>=': '>=' - '<=': '<=' - '>': '>' - '<': '<' - '!=': '!=' - between: 'Között' - is_null: 'Is null' - is_not_null: 'Is not null' - contains: 'Contains' - begins_with: 'Begins with' - ends_with: 'Ends with' - - # error_messages - internal_error: 'A lekérés sikertelen (code 500, Internal Error)' - version_inconsistency: 'Verzió ütközés - ezt a rekordot módosították mióta elkezdted szerkeszteni.' - failed_to_save_record: 'Failed to save record cause of an unknown error' diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/ja.yml b/vendor/plugins/active_scaffold/lib/active_scaffold/locale/ja.yml deleted file mode 100644 index d7402c8..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/ja.yml +++ /dev/null @@ -1,69 +0,0 @@ -ja: - active_scaffold: - add: '追加' - add_existing: '既存のものを追加' - add_existing_model: '既存の%{model}を追加' - are_you_sure_to_delete: '本当によいですか?' - cancel: 'キャンセル' - click_to_edit: 'クリックして編集' - close: '閉じる' - create: '作成' - create_model: '%{model}を作成' - create_another: '別のものを作成' - created_model: '%{model}を作成しました' - create_new: '新規作成' - customize: 'カスタマイズ' - delete: '削除' - deleted_model: '%{model}を削除しました' - delimiter: 'Delimiter' # needed? - download: 'ダウンロード' - edit: '編集' - export: 'Export' # needed? - nested_for_model: '%{parent_model}の%{nested_model}' - filtered: '(フィルタ中)' - found: '個ありました' - hide: '隠す' - live_search: 'その場で検索' - loading: '読み込み中…' - next: '次' - no_entries: '見つかりませんでした' - no_options: 'オプション無し' - omit_header: 'Omit Header' # needed? - options: 'オプション' - pdf: 'PDF' - previous: '前' - print: '印刷' - refresh: 'Refresh' # needed? - remove: '削除' - remove_file: 'ファイルを削除または置換' - replace_with_new: '新しいもので置換' - revisions_for_model: 'Revisions for %{model}' # neede? - reset: 'リセット' - saving: '保存中…' - search: '検索' - search_terms: '検索単語' - _select_: '- 選択してください -' - show: '表示' - show_model: '%{model}を表示' - _to_ : ' to ' # needed? - update: '更新' - update_model: '%{model}を更新' - updated_model: '%{model}を更新しました' - '=': '=' - '>=': '>=' - '<=': '<=' - '>': '>' - '<': '<' - '!=': '!=' - between: 'Between' # needed? - is_null: 'Is null' - is_not_null: 'Is not null' - contains: 'Contains' - begins_with: 'Begins with' - ends_with: 'Ends with' - - # error_messages - cant_destroy_record: "%{record}を削除で来ません" - internal_error: 'リクエストが失敗しました(コード500: 内部エラー)' - version_inconsistency: 'バージョンが一致しません - あなたが編集している間にこのレコードが変更されました。' - failed_to_save_record: 'Failed to save record cause of an unknown error' diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/ru.yml b/vendor/plugins/active_scaffold/lib/active_scaffold/locale/ru.yml deleted file mode 100644 index 541ec5a..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/locale/ru.yml +++ /dev/null @@ -1,72 +0,0 @@ -ru: - active_scaffold: - add: 'Добавить запись' - add_existing: 'Добавить существующую запись' - add_existing_model: 'Добавить существующую запись %{model}' - are_you_sure_to_delete: 'Удалить %{label}?' - cancel: 'Отмена' - click_to_edit: 'Нажмите для редактирования' - click_to_reset: 'Нажмите для сброса' - close: 'Закрыть' - create: 'Создать запись' - create_model: 'Создать запись %{model}' - create_another: 'Создать другую запись %{model}' - created_model: 'Создана запись %{model}' - create_new: 'Создать новую запись' - customize: 'Настроить' - delete: 'Удалить' - deleted_model: 'Удалена запись %{model}' - delimiter: 'Разделитель' - download: 'Загрузить' - edit: 'Изменить' - export: 'Экспорт' - nested_for_model: '%{parent_model} / %{nested_model}' - false: 'Нет' - filtered: '(Найденное)' - found: 'Найдено' - hide: 'Скрыть' - live_search: 'Поиск' - loading: 'Загрузка…' - next: 'Следующее' - no_entries: 'Нет записей' - no_options: 'Нет вариантов' - omit_header: 'Omit Header' - options: 'Настройки' - pdf: 'PDF' - previous: 'Предыдущее' - print: 'Распечатать' - refresh: 'Обновить' - remove: 'Удалить' - remove_file: 'Удалить или заменить файл' - replace_with_new: 'Заменить новым' - revisions_for_model: 'Редакции %{model}' - reset: 'Сбросить' - saving: 'Сохранение…' - search: 'Поиск' - search_terms: 'Ключевые слова' - _select_: '- выбрать -' - show: 'Показать' - show_model: 'Показать запись %{model}' - _to_ : ' to ' - true: 'Да' - update: 'Обновить запись' - update_model: 'Обновить запись %{model}' - updated_model: 'Обновлена запись %{model}' - '=': '=' - '>=': '>=' - '<=': '<=' - '>': '>' - '<': '<' - '!=': '!=' - between: 'В интервале' - is_null: 'Пусто' - is_not_null: 'Не пусто' - contains: 'Содержит' - begins_with: 'Начинается с' - ends_with: 'Оканчивается на' - - # error_messages - cant_destroy_record: 'Запись %{record} не может быть удалена' - internal_error: '500 Внутренняя ошибка сервера' - version_inconsistency: 'Несоответствие версий: эта запись была обновлена с того момента, как вы начали ее редактировать' - failed_to_save_record: 'Failed to save record cause of an unknown error' diff --git a/vendor/plugins/active_scaffold/lib/active_scaffold/marked_model.rb b/vendor/plugins/active_scaffold/lib/active_scaffold/marked_model.rb deleted file mode 100644 index b121b4c..0000000 --- a/vendor/plugins/active_scaffold/lib/active_scaffold/marked_model.rb +++ /dev/null @@ -1,38 +0,0 @@ -module ActiveScaffold - module MarkedModel - # This is a module aimed at making the make session_stored marked_records available to ActiveRecord models - - def self.included(base) - base.extend ClassMethods - base.named_scope :marked, lambda {{:conditions => {:id => base.marked_records.to_a}}} - end - - def marked - marked_records.include?(self.id) - end - - def marked=(value) - value = (value.downcase == 'true') if value.is_a? String - if value == true - marked_records << self.id if !marked - else - marked_records.delete(self.id) - end - end - - module ClassMethods - # The proc to call that retrieves the marked_records from the ApplicationController. - attr_accessor :marked_records_proc - - # Class-level access to the marked_records - def marked_records - (marked_records_proc.call || Set.new) if marked_records_proc - end - end - - # Instance-level access to the marked_records - def marked_records - self.class.marked_records - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/bridge.rb deleted file mode 100644 index 794177f..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/bridge.rb +++ /dev/null @@ -1,52 +0,0 @@ -module ActiveScaffold - def self.bridge(name, &block) - ActiveScaffold::Bridge.new(name, &block) - end - - class Bridge - attr_accessor :name - cattr_accessor :bridges - cattr_accessor :bridges_run - self.bridges = [] - - def initialize(name, &block) - self.name = name - @install = nil - # by convention and default, use the bridge name as the required constant for installation - @install_if = lambda { Object.const_defined?(name) } - self.instance_eval(&block) - - ActiveScaffold::Bridge.bridges << self - end - - # Set the install block - def install(&block) - @install = block - end - - # Set the install_if block (to check to see whether or not to install the block) - def install?(&block) - @install_if = block - end - - - def run - raise(ArgumentError, "install and install? not defined for bridge #{name}" ) unless @install && @install_if - @install.call if @install_if.call - end - - def self.run_all - return false if self.bridges_run - ActiveScaffold::Bridge.bridges.each{|bridge| - bridge.run - } - - - self.bridges_run=true - end - end -end - -Dir[File.join(File.dirname(__FILE__), "*/bridge.rb")].each{|bridge_require| - require bridge_require -} \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/bridge.rb deleted file mode 100644 index 1ca1b41..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/bridge.rb +++ /dev/null @@ -1,11 +0,0 @@ -ActiveScaffold.bridge "CalendarDateSelect" do - install do - # check to see if the old bridge was installed. If so, warn them - # we can detect this by checking to see if the bridge was installed before calling this code - if ActiveScaffold::Config::Core.instance_methods.include?("initialize_with_calendar_date_select") - raise RuntimeError, "We've detected that you have active_scaffold_calendar_date_select_bridge installed. This plugin has been moved to core. Please remove active_scaffold_calendar_date_select_bridge to prevent any conflicts" - end - - require File.join(File.dirname(__FILE__), "lib/as_cds_bridge.rb") - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/lib/as_cds_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/lib/as_cds_bridge.rb deleted file mode 100644 index 461f5f6..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/calendar_date_select/lib/as_cds_bridge.rb +++ /dev/null @@ -1,87 +0,0 @@ -module ActiveScaffold::Config - class Core < Base - - def initialize_with_calendar_date_select(model_id) - initialize_without_calendar_date_select(model_id) - - calendar_date_select_fields = self.model.columns.collect{|c| c.name.to_sym if [:date, :datetime].include?(c.type) }.compact - # check to see if file column was used on the model - return if calendar_date_select_fields.empty? - - # automatically set the forum_ui to a file column - calendar_date_select_fields.each{|field| - self.columns[field].form_ui = :calendar_date_select - } - end - - alias_method_chain :initialize, :calendar_date_select - - end -end - - -module ActiveScaffold - module CalendarDateSelectBridge - # Helpers that assist with the rendering of a Form Column - module FormColumnHelpers - def active_scaffold_input_calendar_date_select(column, options) - options[:class] = "#{options[:class]} text-input".strip - calendar_date_select("record", column.name, options.merge(column.options)) - end - end - - module SearchColumnHelpers - def active_scaffold_search_calendar_date_select(column, options) - opt_value, from_value, to_value = field_search_params_range_values(column) - options = column.options.merge(options).except!(:include_blank) - helper = "select_#{'date' unless options[:discard_date]}#{'time' unless options[:discard_time]}" - html = [] - html << calendar_date_select("record", column.name, options.merge(:name => "#{options[:name]}[from]", :id => "#{options[:id]}_from", :value => from_value)) - html << calendar_date_select("record", column.name, options.merge(:name => "#{options[:name]}[to]", :id => "#{options[:id]}_to", :value => to_value)) - html * ' - ' - end - end - - module ViewHelpers - # Provides stylesheets to include with +stylesheet_link_tag+ - def active_scaffold_stylesheets(frontend = :default) - super + [calendar_date_select_stylesheets] - end - - # Provides stylesheets to include with +stylesheet_link_tag+ - def active_scaffold_javascripts(frontend = :default) - super + [calendar_date_select_javascripts] - end - end - - module Finder - module ClassMethods - def condition_for_calendar_date_select_type(column, value, like_pattern) - conversion = column.column.type == :date ? 'to_date' : 'to_time' - from_value, to_value = ['from', 'to'].collect do |field| - Time.zone.parse(value[field]) rescue nil - end - - if from_value.nil? and to_value.nil? - nil - elsif !from_value - ["#{column.search_sql} <= ?", to_value.send(conversion).to_s(:db)] - elsif !to_value - ["#{column.search_sql} >= ?", from_value.send(conversion).to_s(:db)] - else - ["#{column.search_sql} BETWEEN ? AND ?", from_value.send(conversion).to_s(:db), to_value.send(conversion).to_s(:db)] - end - end - end - end - end -end - -ActionView::Base.class_eval do - include ActiveScaffold::CalendarDateSelectBridge::FormColumnHelpers - include ActiveScaffold::CalendarDateSelectBridge::SearchColumnHelpers - include ActiveScaffold::CalendarDateSelectBridge::ViewHelpers -end -ActiveScaffold::Finder::ClassMethods.module_eval do - include ActiveScaffold::CalendarDateSelectBridge::Finder::ClassMethods -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/dependent_protect/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/dependent_protect/bridge.rb deleted file mode 100644 index 3ed3ba4..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/dependent_protect/bridge.rb +++ /dev/null @@ -1,10 +0,0 @@ -ActiveScaffold.bridge "DependentProtect" do - install do - # check to see if the old bridge was installed. If so, warn them - # we can detect this by checking to see if the bridge was installed before calling this code - if ActiveRecord::Base.instance_methods.include?("authorized_for_delete?") - raise RuntimeError, "We've detected that you have active_scaffold_dependent_protect installed. This plugin has been moved to core. Please remove active_scaffold_dependent_protect to prevent any conflicts" - end - require File.join(File.dirname(__FILE__), "lib/dependent_protect_bridge.rb") - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/dependent_protect/lib/dependent_protect_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/dependent_protect/lib/dependent_protect_bridge.rb deleted file mode 100644 index 3db3e28..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/dependent_protect/lib/dependent_protect_bridge.rb +++ /dev/null @@ -1,11 +0,0 @@ -module DependentProtectSecurity - def self.included(base) - base.class_inheritable_accessor :dependent_associations - end - protected - def authorized_for_delete? - self.class.dependent_associations ||= self.class.reflect_on_all_associations.select {|assoc| assoc.options[:dependent] == :protect} - self.class.dependent_associations.all? {|assoc| self.send(assoc.name).blank?} - end -end -ActiveRecord::Base.class_eval { include DependentProtectSecurity } diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/bridge.rb deleted file mode 100644 index 94b2329..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/bridge.rb +++ /dev/null @@ -1,12 +0,0 @@ -ActiveScaffold.bridge "FileColumn" do - install do - if ActiveScaffold::Config::Core.instance_methods.include?("initialize_with_file_column") - raise RuntimeError, "We've detected that you have active_scaffold_file_column_bridge installed. This plugin has been moved to core. Please remove active_scaffold_file_column_bridge to prevent any conflicts" - end - - require File.join(File.dirname(__FILE__), "lib/as_file_column_bridge") - require File.join(File.dirname(__FILE__), "lib/form_ui") - require File.join(File.dirname(__FILE__), "lib/list_ui") - require File.join(File.dirname(__FILE__), "lib/file_column_helpers") - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/as_file_column_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/as_file_column_bridge.rb deleted file mode 100644 index 6f9cfb1..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/as_file_column_bridge.rb +++ /dev/null @@ -1,46 +0,0 @@ -ActiveScaffold::DataStructures::Column.class_eval do - attr_accessor :file_column_display -end - -module ActiveScaffold::Config - class Core < Base - attr_accessor :file_column_fields - def initialize_with_file_column(model_id) - initialize_without_file_column(model_id) - - return unless FileColumnHelpers.klass_has_file_column_fields?(self.model) - - self.model.send :extend, FileColumnHelpers - - # include the "delete" helpers for use with active scaffold, unless they are already included - self.model.generate_delete_helpers - - # switch on multipart - self.update.multipart = true - self.create.multipart = true - - self.model.file_column_fields.each{ |field| - configure_file_column_field(field) - } - end - - alias_method_chain :initialize, :file_column unless self.instance_methods.include?("initialize_without_file_column") - - def configure_file_column_field(field) - # set list_ui first because it gets its default value from form_ui - self.columns[field].list_ui ||= self.model.field_has_image_version?(field, "thumb") ? :thumbnail : :download_link_with_filename - self.columns[field].form_ui ||= :file_column - - # these 2 parameters are necessary helper attributes for the file column that must be allowed to be set to the model by active scaffold. - self.columns[field].params.add "#{field}_temp", "delete_#{field}" - - # set null to false so active_scaffold wont set it to null - # delete_file_column will take care of deleting a file or not. - self.model.columns_hash[field.to_s].instance_variable_set("@null", false) - - rescue - false - end - - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/file_column_helpers.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/file_column_helpers.rb deleted file mode 100644 index 9c60f1c..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/file_column_helpers.rb +++ /dev/null @@ -1,51 +0,0 @@ -module FileColumnHelpers - class << self - def file_column_fields(klass) - klass.instance_methods.grep(/_just_uploaded\?$/).collect{|m| m[0..-16].to_sym } - end - - def generate_delete_helpers(klass) - file_column_fields(klass).each { |field| - klass.send :class_eval, <<-EOF, __FILE__, __LINE__ + 1 unless klass.methods.include?("#{field}_with_delete=") - attr_reader :delete_#{field} - - def delete_#{field}=(value) - value = (value=="true") if String===value - return unless value - - # passing nil to the file column causes the file to be deleted. Don't delete if we just uploaded a file! - self.#{field} = nil unless self.#{field}_just_uploaded? - end - EOF - } - end - - def klass_has_file_column_fields?(klass) - true unless file_column_fields(klass).empty? - end - end - - def file_column_fields - @file_column_fields||=FileColumnHelpers.file_column_fields(self) - end - - def options_for_file_column_field(field) - self.allocate.send("#{field}_options") - end - - def field_has_image_version?(field, version="thumb") - begin - # the only way to get to the options of a particular field is to use the instance method - options = options_for_file_column_field(field) - versions = options[:magick][:versions] - raise unless versions.stringify_keys[version] - true - rescue - false - end - end - - def generate_delete_helpers - FileColumnHelpers.generate_delete_helpers(self) - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/form_ui.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/form_ui.rb deleted file mode 100644 index b169d8e..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/form_ui.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveScaffold - module Helpers - # Helpers that assist with the rendering of a Form Column - module FormColumnHelpers - def active_scaffold_input_file_column(column, options) - if @record.send(column.name) - # we already have a value? display the form for deletion. - content_tag( - :div, - content_tag( - :div, - get_column_value(@record, column) + " " + - hidden_field(:record, "delete_#{column.name}", :value => "false") + - " | " + - link_to_function(as_(:remove_file), "$(this).previous().value='true'; p=$(this).up(); p.hide(); p.next().show();"), - {} - ) + - content_tag( - :div, - file_column_field("record", column.name, options), - :style => "display: none" - ), - {} - ) - else - # no, just display the file_column_field - file_column_field("record", column.name, options) - end - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/list_ui.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/list_ui.rb deleted file mode 100644 index edb7199..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/lib/list_ui.rb +++ /dev/null @@ -1,26 +0,0 @@ -module ActiveScaffold - module Helpers - # Helpers that assist with the rendering of a List Column - module ListColumnHelpers - def active_scaffold_column_download_link_with_filename(column, record) - return nil if record.send(column.name).nil? - active_scaffold_column_download_link(column, record, File.basename(record.send(column.name))) - end - - def active_scaffold_column_download_link(column, record, label = nil) - return nil if record.send(column.name).nil? - label||=as_(:download) - link_to( label, url_for_file_column(record, column.name.to_s), :popup => true) - end - - def active_scaffold_column_thumbnail(column, record) - return nil if record.send(column.name).nil? - link_to( - image_tag(url_for_file_column(record, column.name.to_s, "thumb"), :border => 0), - url_for_file_column(record, column.name.to_s), - :popup => true) - end - - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/test/functional/file_column_keep_test.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/test/functional/file_column_keep_test.rb deleted file mode 100644 index fa2aeec..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/test/functional/file_column_keep_test.rb +++ /dev/null @@ -1,43 +0,0 @@ -require File.join(File.dirname(__FILE__), "../test_helper.rb") - -class DeleteFileColumnTest < Test::Unit::TestCase - def setup - DeleteFileColumn.generate_delete_helpers(MockModel) - @model = MockModel.new - @model.band_image = "coolio.jpg" - end - - def test__file_column_fields - assert_equal(1, @model.file_column_fields.length) - end - - def test__delete_band_image__boolean__should_delete - @model.delete_band_image = true - assert_nil @model.band_image - end - - def test__delete_band_image__string__should_delete - @model.delete_band_image = "true" - assert_nil @model.band_image - end - - - def test__delete_band_image__boolean_false__shouldnt_delete - @model.delete_band_image = false - assert_not_nil @model.band_image - end - - def test__delete_band_image__string_false__shouldnt_delete - @model.delete_band_image = "false" - assert_not_nil @model.band_image - end - - - def test__just_uploaded__shouldnt_delete - @model.band_image_just_uploaded = true - @model.delete_band_image = "true" - assert_not_nil(@model.band_image) - end - - -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/test/mock_model.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/test/mock_model.rb deleted file mode 100644 index 90fa827..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/test/mock_model.rb +++ /dev/null @@ -1,9 +0,0 @@ -class MockModel - attr_accessor :name - attr_accessor :bio - - attr_accessor :band_image - attr_accessor :band_image_just_uploaded - def band_image_just_uploaded?; self.band_image_just_uploaded ? true : false; end - -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/file_column/test/test_helper.rb b/vendor/plugins/active_scaffold/lib/bridges/file_column/test/test_helper.rb deleted file mode 100644 index 8d94577..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/file_column/test/test_helper.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'test/unit' -require "rubygems" -require 'active_support' - -for file in ["../lib/delete_file_column.rb", "mock_model.rb"] - require File.expand_path(File.join(File.dirname(__FILE__), file)) -end - - - -def dbg - require 'ruby-debug' - Debugger.start - debugger -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/paperclip/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/paperclip/bridge.rb deleted file mode 100644 index bdf507b..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/paperclip/bridge.rb +++ /dev/null @@ -1,13 +0,0 @@ -require File.join(File.dirname(__FILE__), "lib/paperclip_bridge_helpers") -ActiveScaffold.bridge "Paperclip" do - install do - if ActiveScaffold::Config::Core.instance_methods.include?("initialize_with_paperclip") - raise RuntimeError, "We've detected that you have active_scaffold_paperclip_bridge installed. This plugin has been moved to core. Please remove active_scaffold_paperclip_bridge to prevent any conflicts" - end - - require File.join(File.dirname(__FILE__), "lib/paperclip_bridge") - require File.join(File.dirname(__FILE__), "lib/form_ui") - require File.join(File.dirname(__FILE__), "lib/list_ui") - ActiveScaffold::Config::Core.send :include, ActiveScaffold::PaperclipBridge - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/form_ui.rb b/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/form_ui.rb deleted file mode 100644 index 025f1b6..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/form_ui.rb +++ /dev/null @@ -1,20 +0,0 @@ -module ActiveScaffold - module Helpers - module FormColumnHelpers - def active_scaffold_input_paperclip(column, options) - input = file_field(:record, column.name, options) - paperclip = @record.send("#{column.name}") - if paperclip.file? - content = active_scaffold_column_paperclip(column, @record) - content_tag(:div, - content + " | " + - link_to_function(as_(:remove_file), "$(this).next().value='true'; $(this).up().hide().next().show()") + - hidden_field(:record, "delete_#{column.name}", :value => "false") - ) + content_tag(:div, input, :style => "display: none") - else - input - end - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/list_ui.rb b/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/list_ui.rb deleted file mode 100644 index c06a351..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/list_ui.rb +++ /dev/null @@ -1,16 +0,0 @@ -module ActiveScaffold - module Helpers - module ListColumnHelpers - def active_scaffold_column_paperclip(column, record) - paperclip = record.send("#{column.name}") - return nil unless paperclip.file? - content = if paperclip.styles.include?(PaperclipBridgeHelpers.thumbnail_style) - image_tag(paperclip.url(PaperclipBridgeHelpers.thumbnail_style), :border => 0) - else - paperclip.original_filename - end - link_to(content, paperclip.url, :popup => true) - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge.rb deleted file mode 100644 index 38ac1bc..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveScaffold - module PaperclipBridge - def initialize_with_paperclip(model_id) - initialize_without_paperclip(model_id) - return if self.model.attachment_definitions.nil? - - self.update.multipart = true - self.create.multipart = true - - self.model.attachment_definitions.keys.each do |field| - configure_paperclip_field(field.to_sym) - # define the "delete" helper for use with active scaffold, unless it's already defined - PaperclipBridgeHelpers.generate_delete_helper(self.model, field) - end - end - - def self.included(base) - base.alias_method_chain :initialize, :paperclip - end - - private - def configure_paperclip_field(field) - self.columns << field - self.columns[field].form_ui ||= :paperclip - self.columns[field].params.add "delete_#{field}" - - [:file_name, :content_type, :file_size, :updated_at].each do |f| - self.columns.exclude("#{field}_#{f}".to_sym) - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge_helpers.rb b/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge_helpers.rb deleted file mode 100644 index 3dcb49d..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/paperclip/lib/paperclip_bridge_helpers.rb +++ /dev/null @@ -1,18 +0,0 @@ -module PaperclipBridgeHelpers - mattr_accessor :thumbnail_style - self.thumbnail_style = :thumbnail - - def self.generate_delete_helper(klass, field) - klass.class_eval <<-EOF, __FILE__, __LINE__ + 1 unless klass.methods.include?("delete_#{field}=") - attr_reader :delete_#{field} - - def delete_#{field}=(value) - value = (value == "true") if String === value - return unless value - - # passing nil to the file column causes the file to be deleted. Don't delete if we just uploaded a file! - self.#{field} = nil unless self.#{field}.dirty? - end - EOF - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/bridges/record_select/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/record_select/bridge.rb deleted file mode 100644 index f3ccb37..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/record_select/bridge.rb +++ /dev/null @@ -1,5 +0,0 @@ -ActiveScaffold.bridge "RecordSelect" do - install do - require File.join(File.dirname(__FILE__), "lib/record_select_bridge.rb") - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/record_select/lib/record_select_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/record_select/lib/record_select_bridge.rb deleted file mode 100644 index db5fef2..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/record_select/lib/record_select_bridge.rb +++ /dev/null @@ -1,79 +0,0 @@ -module ActiveScaffold - module RecordSelectBridge - def self.included(base) - base.class_eval do - include FormColumnHelpers - include SearchColumnHelpers - include ViewHelpers - end - end - - module ViewHelpers - def self.included(base) - base.alias_method_chain :active_scaffold_includes, :record_select - end - - def active_scaffold_includes_with_record_select(*args) - active_scaffold_includes_without_record_select(*args) + record_select_includes - end - end - - module FormColumnHelpers - # requires RecordSelect plugin to be installed and configured. - def active_scaffold_input_record_select(column, options) - if column.singular_association? - active_scaffold_record_select(column, options, @record.send(column.name), false) - elsif column.plural_association? - active_scaffold_record_select(column, options, @record.send(column.name), true) - end - end - - def active_scaffold_record_select(column, options, value, multiple) - unless column.association - raise ArgumentError, "record_select can only work against associations (and #{column.name} is not). A common mistake is to specify the foreign key field (like :user_id), instead of the association (:user)." - end - remote_controller = active_scaffold_controller_for(column.association.klass).controller_path - - # if the opposite association is a :belongs_to (in that case association in this class must be has_one or has_many) - # then only show records that have not been associated yet - if [:has_one, :has_many].include?(column.association.macro) - params.merge!({column.association.primary_key_name => ''}) - end - - record_select_options = {:controller => remote_controller, :id => options[:id]} - record_select_options.merge!(options) - record_select_options.merge!(active_scaffold_input_text_options) - record_select_options.merge!(column.options) - record_select_options[:onchange] = "function(id, label) { this.value = id; #{record_select_options[:onchange]} }" if record_select_options[:onchange] - - if multiple - record_multi_select_field(options[:name], value || [], record_select_options) - else - record_select_field(options[:name], value || column.association.klass.new, record_select_options) - end - end - end - - module SearchColumnHelpers - def active_scaffold_search_record_select(column, options) - begin - value = field_search_params[column.name] - value = unless value.blank? - if column.options[:multiple] - column.association.klass.find value.collect!(&:to_i) - else - column.association.klass.find(value.to_i) - end - end - rescue Exception => e - logger.error Time.now.to_s + "Sorry, we are not that smart yet. Attempted to restore search values to search fields but instead got -- #{e.inspect} -- on the ActiveScaffold column = :#{column.name} in #{@controller.class}" - raise e - end - - active_scaffold_record_select(column, options, value, column.options[:multiple]) - end - end - end -end - -ActionView::Base.class_eval { include ActiveScaffold::RecordSelectBridge } diff --git a/vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/bridge.rb deleted file mode 100644 index d676018..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/bridge.rb +++ /dev/null @@ -1,5 +0,0 @@ -ActiveScaffold.bridge "SemanticAttributes" do - install do - require File.join(File.dirname(__FILE__), "lib/semantic_attributes_bridge.rb") - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/lib/semantic_attributes_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/lib/semantic_attributes_bridge.rb deleted file mode 100644 index b953e03..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/semantic_attributes/lib/semantic_attributes_bridge.rb +++ /dev/null @@ -1,20 +0,0 @@ -module ActiveScaffold - module SemanticAttributesBridge - def self.included(base) - base.class_eval { alias_method_chain :initialize, :semantic_attributes } - end - - def initialize_with_semantic_attributes(name, active_record_class) - initialize_without_semantic_attributes(name, active_record_class) - self.required = !active_record_class.semantic_attributes[self.name].predicates.find {|p| p.allow_empty? == false }.nil? - active_record_class.semantic_attributes[self.name].predicates.find do |p| - sem_type = p.class.to_s.split('::')[1].underscore.to_sym - next if [:required, :association].include?(sem_type) - @form_ui = sem_type - end - end - end -end -ActiveScaffold::DataStructures::Column.class_eval do - include ActiveScaffold::SemanticAttributesBridge -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/tiny_mce/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/tiny_mce/bridge.rb deleted file mode 100644 index 09b8805..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/tiny_mce/bridge.rb +++ /dev/null @@ -1,5 +0,0 @@ -ActiveScaffold.bridge "TinyMCE" do - install do - require File.join(File.dirname(__FILE__), "lib/tiny_mce_bridge.rb") - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/tiny_mce/lib/tiny_mce_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/tiny_mce/lib/tiny_mce_bridge.rb deleted file mode 100644 index 5ab95ad..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/tiny_mce/lib/tiny_mce_bridge.rb +++ /dev/null @@ -1,57 +0,0 @@ -module ActiveScaffold - module TinyMceBridge - def self.included(base) - base.class_eval do - include FormColumnHelpers - include SearchColumnHelpers - include ViewHelpers - end - end - - module ViewHelpers - def self.included(base) - base.alias_method_chain :active_scaffold_includes, :tiny_mce - end - - def active_scaffold_includes_with_tiny_mce(*args) - tiny_mce_js = javascript_tag(%| -var action_link_close = ActiveScaffold.ActionLink.Abstract.prototype.close; -ActiveScaffold.ActionLink.Abstract.prototype.close = function() { - this.adapter.select('textarea.mceEditor').each(function(elem) { - tinyMCE.execCommand('mceRemoveControl', false, elem.id); - }); - action_link_close.apply(this); -}; - |) if using_tiny_mce? - active_scaffold_includes_without_tiny_mce(*args) + (include_tiny_mce_if_needed || '') + (tiny_mce_js || '') - end - end - - module FormColumnHelpers - def self.included(base) - base.alias_method_chain :onsubmit, :tiny_mce - end - - def active_scaffold_input_text_editor(column, options) - options[:class] = "#{options[:class]} mceEditor #{column.options[:class]}".strip - html = [] - html << send(override_input(:textarea), column, options) - html << javascript_tag("tinyMCE.execCommand('mceAddControl', false, '#{options[:id]}');") if request.xhr? || params[:iframe] - html.join "\n" - end - - def onsubmit_with_tiny_mce - submit_js = 'tinyMCE.triggerSave();this.select("textarea.mceEditor").each(function(elem) { tinyMCE.execCommand("mceRemoveControl", false, elem.id); });' if using_tiny_mce? - [onsubmit_without_tiny_mce, submit_js].compact.join ';' - end - end - - module SearchColumnHelpers - def self.included(base) - base.class_eval { alias_method :active_scaffold_search_text_editor, :active_scaffold_search_text } - end - end - end -end - -ActionView::Base.class_eval { include ActiveScaffold::TinyMceBridge } diff --git a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/bridge.rb deleted file mode 100644 index 878b762..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/bridge.rb +++ /dev/null @@ -1,9 +0,0 @@ -ActiveScaffold.bridge "UnobtrusiveDatePicker" do - install do - require File.join(File.dirname(__FILE__), "lib/unobtrusive_date_picker_bridge.rb") - require File.join(File.dirname(__FILE__), "lib/form_ui.rb") - require File.join(File.dirname(__FILE__), "lib/view_helpers.rb") - ActiveScaffold::Config::Core.send :include, ActiveScaffold::UnobtrusiveDatePickerBridge - ActiveScaffold::Helpers::ViewHelpers.send :include, ActiveScaffold::UnobtrusiveDatePickerHelpers - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/form_ui.rb b/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/form_ui.rb deleted file mode 100644 index 26c5df9..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/form_ui.rb +++ /dev/null @@ -1,14 +0,0 @@ -module ActiveScaffold - module Helpers - module FormColumnHelpers - def active_scaffold_input_datepicker(column, options) - method = "date#{'time' if column.column.type == :datetime}_select" - options[:include_blank] = true if column.column and column.column.null and [:date, :datetime, :time].include?(column.column.type) - html_options = options.update(column.options).delete(:html_options) || {} - options = active_scaffold_input_date_options(column, options) - args = [:record, column.name, options, html_options] - self.send(method, *args) + date_picker(*args) - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/unobtrusive_date_picker_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/unobtrusive_date_picker_bridge.rb deleted file mode 100644 index 69624ed..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/unobtrusive_date_picker_bridge.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveScaffold - module UnobtrusiveDatePickerBridge - def initialize_with_unobtrusive_date_picker(model_id) - initialize_without_unobtrusive_date_picker(model_id) - date_fields = self.model.columns.select {|c| [:date, :datetime].include?(c.type) } - - # automatically set the forum_ui to a file column - date_fields.each {|field| self.columns[field.name.to_sym].form_ui = :datepicker} - end - - def self.included(base) - base.alias_method_chain :initialize, :unobtrusive_date_picker - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/view_helpers.rb b/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/view_helpers.rb deleted file mode 100644 index 9811442..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/unobtrusive_date_picker/lib/view_helpers.rb +++ /dev/null @@ -1,16 +0,0 @@ -module ActiveScaffold - module UnobtrusiveDatePickerHelpers - def self.included(base) - base.alias_method_chain :active_scaffold_stylesheets, :date_picker - base.alias_method_chain :active_scaffold_javascripts, :date_picker - end - - def active_scaffold_stylesheets_with_date_picker(frontend = :default) - active_scaffold_stylesheets_without_date_picker(frontend) + unobtrusive_datepicker_stylesheets - end - - def active_scaffold_javascripts_with_date_picker(frontend = :default) - active_scaffold_javascripts_without_date_picker(frontend) + unobtrusive_datepicker_javascripts - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/validation_reflection/bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/validation_reflection/bridge.rb deleted file mode 100644 index 5b603d4..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/validation_reflection/bridge.rb +++ /dev/null @@ -1,9 +0,0 @@ -ActiveScaffold.bridge "ValidationReflection" do - install do - require File.join(File.dirname(__FILE__), "lib/validation_reflection_bridge.rb") - ActiveScaffold::DataStructures::Column.class_eval { include ActiveScaffold::ValidationReflectionBridge } - end - install? do - ActiveRecord::Base.respond_to? :reflect_on_validations_for - end -end diff --git a/vendor/plugins/active_scaffold/lib/bridges/validation_reflection/lib/validation_reflection_bridge.rb b/vendor/plugins/active_scaffold/lib/bridges/validation_reflection/lib/validation_reflection_bridge.rb deleted file mode 100644 index 403d708..0000000 --- a/vendor/plugins/active_scaffold/lib/bridges/validation_reflection/lib/validation_reflection_bridge.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActiveScaffold - module ValidationReflectionBridge - def self.included(base) - base.class_eval { alias_method_chain :initialize, :validation_reflection } - end - - def initialize_with_validation_reflection(name, active_record_class) - initialize_without_validation_reflection(name, active_record_class) - column_names = [name] - column_names << @association.primary_key_name if @association - self.required = column_names.any? do |column_name| - active_record_class.reflect_on_validations_for(column_name.to_sym).any? do |val| - val.macro == :validates_presence_of or (val.macro == :validates_inclusion_of and not val.options[:allow_nil] and not val.options[:allow_blank]) - end - end - end - end -end - diff --git a/vendor/plugins/active_scaffold/lib/dhtml_confirm.rb b/vendor/plugins/active_scaffold/lib/dhtml_confirm.rb deleted file mode 100644 index b9a4b0d..0000000 --- a/vendor/plugins/active_scaffold/lib/dhtml_confirm.rb +++ /dev/null @@ -1,54 +0,0 @@ -# Matt Mower -# -# A base class for creating DHTML confirmation types. -# -# The real work is done by the onclick_function and onclick_handler methods. In -# general it should only be required to override the default onclick_handler -# method and provide the specific Javascript required to invoke the DHTML confirm -# dialog of your choice. -# -# It is up to this dialog, if the user confirms the intended action, to invoke -# the function window.gFireModalLink() to trigger the intended action of the link. -# For example, using the Modalbox library, you would use something like: -# -# Modalbox.hide( { -# afterHide: function() { -# window.gFireModalLink(); -# } } ); -# -# By default the only action recognized is :value which is used to add a -# dhtml_confirm attribute to the link tag. This value is detected by the -# ActiveScaffold link and triggers the DHTML confirmation logic. -# -class DHTMLConfirm - attr_accessor :value, :message, :options - - def initialize( options = {} ) - @options = options - @value = @options.delete(:value) { |key| "yes" } - @message = @options.delete(:message) { |key| "Are you sure?" } - end - - def onclick_function( controller, link_id ) - script = <<-END -window.gFireModalLink = function() { - var link = $('#{link_id}').action_link; - link.open_action.call( link ); -}; -#{ensure_termination(onclick_handler(controller,link_id))} -return false; -END - # script = "window.gModalLink = $('#{link_id}').action_link;#{onclick_handler(controller,link_id)}return false;" - end - - def onclick_handler( controller, link_id ) - "" - end - -protected - def ensure_termination( expression ) - expression =~ /;$/ ? expression : "#{expression};" - end - -end - diff --git a/vendor/plugins/active_scaffold/lib/extensions/action_controller_rendering.rb b/vendor/plugins/active_scaffold/lib/extensions/action_controller_rendering.rb deleted file mode 100644 index eaadda4..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/action_controller_rendering.rb +++ /dev/null @@ -1,20 +0,0 @@ -# wrap the action rendering for ActiveScaffold controllers -module ActionController #:nodoc: - class Base - def render_with_active_scaffold(*args, &block) - if self.class.uses_active_scaffold? and params[:adapter] and @rendering_adapter.nil? - @rendering_adapter = true # recursion control - # if we need an adapter, then we render the actual stuff to a string and insert it into the adapter template - render :partial => params[:adapter][1..-1], - :locals => {:payload => render_to_string(args.first, &block)}, - :use_full_path => true, :layout => false - @rendering_adapter = nil # recursion control - else - render_without_active_scaffold(*args, &block) - end - end - alias_method_chain :render, :active_scaffold - - # Rails 2.x implementation is post-initialization on :active_scaffold method - end -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/action_view_rendering.rb b/vendor/plugins/active_scaffold/lib/extensions/action_view_rendering.rb deleted file mode 100644 index 06822df..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/action_view_rendering.rb +++ /dev/null @@ -1,99 +0,0 @@ -# wrap the action rendering for ActiveScaffold views -module ActionView #:nodoc: - class Base - # Adds two rendering options. - # - # ==render :super - # - # This syntax skips all template overrides and goes directly to the provided ActiveScaffold templates. - # Useful if you want to wrap an existing template. Just call super! - # - # ==render :active_scaffold => #{controller.to_s}, options = {}+ - # - # Lets you embed an ActiveScaffold by referencing the controller where it's configured. - # - # You may specify options[:constraints] for the embedded scaffold. These constraints have three effects: - # * the scaffold's only displays records matching the constraint - # * all new records created will be assigned the constrained values - # * constrained columns will be hidden (they're pretty boring at this point) - # - # You may also specify options[:conditions] for the embedded scaffold. These only do 1/3 of what - # constraints do (they only limit search results). Any format accepted by ActiveRecord::Base.find is valid. - # - # Defining options[:label] lets you completely customize the list title for the embedded scaffold. - # - def render_with_active_scaffold(*args, &block) - if args.first == :super - options = args[1] || {} - options[:locals] ||= {} - options[:locals].reverse_merge! @local_assigns - - known_extensions = [:erb, :rhtml, :rjs, :haml] - # search through call stack for a template file (normally matches on first caller) - # note that we can't use split(':').first because windoze boxen may have an extra colon to specify the drive letter. the - # solution is to count colons from the *right* of the string, not the left. see issue #299. - template_path = caller.find{|c| known_extensions.include?(c.split(':')[-3].split('.').last.to_sym) } - template = File.basename(template_path.split(':')[-3]) - template, format = template.split('.') - - # paths previous to current template_path must be ignored to avoid infinite loops when is called twice or more - index = 0 - controller.class.active_scaffold_paths.each_with_index do |active_scaffold_template_path, i| - index = i + 1 and break if template_path.include? active_scaffold_template_path - end - - active_scaffold_template = controller.class.active_scaffold_paths.slice(index..-1).find_template(template, format, false) - render(:file => active_scaffold_template, :locals => options[:locals]) - elsif args.first.is_a?(Hash) and args.first[:active_scaffold] - require 'digest/md5' - options = args.first - - remote_controller = options[:active_scaffold] - constraints = options[:constraints] - conditions = options[:conditions] - eid = Digest::MD5.hexdigest(params[:controller] + remote_controller.to_s + constraints.to_s + conditions.to_s) - session["as:#{eid}"] = {:constraints => constraints, :conditions => conditions, :list => {:label => args.first[:label]}} - options[:params] ||= {} - options[:params].merge! :eid => eid - - render_component :controller => remote_controller.to_s, :action => 'index', :params => options[:params] - else - render_without_active_scaffold(*args, &block) - end - end - alias_method_chain :render, :active_scaffold - - def partial_pieces(partial_path) - if partial_path.include?('/') - return File.dirname(partial_path), File.basename(partial_path) - else - return controller.class.controller_path, partial_path - end - end - - # This is the template finder logic, keep it updated with however we find stuff in rails - # currently this very similar to the logic in ActionBase::Base.render for options file - # TODO: Work with rails core team to find a better way to check for this. - def template_exists?(template_name, lookup_overrides = false) - begin - method = 'find_template' - method << '_without_active_scaffold' unless lookup_overrides - self.view_paths.send(method, template_name, @template_format) - return true - rescue ActionView::MissingTemplate => e - return false - end - end - end -end - -module ActionView::Renderable - def render_with_active_scaffold(view, local_assigns = {}) - old_local_assigns = view.instance_variable_get(:@local_assigns) - view.instance_variable_set(:@local_assigns, local_assigns) - output = render_without_active_scaffold(view, local_assigns) - view.instance_variable_set(:@local_assigns, old_local_assigns) - output - end - alias_method_chain :render, :active_scaffold -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/array.rb b/vendor/plugins/active_scaffold/lib/extensions/array.rb deleted file mode 100644 index 4c2f04a..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/array.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Array - # returns the value after the given value. wraps around. defaults to first element in array. - def after(value) - return nil unless include? value - self[(index(value).to_i + 1) % length] - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/extensions/component_response_with_namespacing.rb b/vendor/plugins/active_scaffold/lib/extensions/component_response_with_namespacing.rb deleted file mode 100644 index b700781..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/component_response_with_namespacing.rb +++ /dev/null @@ -1,17 +0,0 @@ -module ActionController #:nodoc: - module Components - module InstanceMethods - # Extracts the action_name from the request parameters and performs that action. - private - # This is to fix a bug in Rails. 1.2.2 was calling klass.controller_name instead of klass.controller_path, which was in turn setting the params[:controller] => "contacts", instead of params[:controller] => "two/contact". Submitted ticket #7545 - # Namespaces only supported in ActiveScaffold with Rails 1.2.2 - def component_response(options, reuse_response) - klass = component_class(options) - request = request_for_component(klass.controller_path, options) - new_response = reuse_response ? response : response.dup - - klass.process_with_components(request, new_response, self) - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/extensions/generic_view_paths.rb b/vendor/plugins/active_scaffold/lib/extensions/generic_view_paths.rb deleted file mode 100644 index e79adaa..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/generic_view_paths.rb +++ /dev/null @@ -1,33 +0,0 @@ -# wrap find_template to search in ActiveScaffold paths when template is missing -module ActionView #:nodoc: - class PathSet - attr_accessor :active_scaffold_paths - - def find_template_with_active_scaffold(original_template_path, format = nil, html_fallback = true) - begin - find_template_without_active_scaffold(original_template_path, format, html_fallback) - rescue MissingTemplate - if active_scaffold_paths && original_template_path.include?('/') - active_scaffold_paths.find_template_without_active_scaffold(original_template_path.split('/').last, format, html_fallback) - else - raise - end - end - end - alias_method_chain :find_template, :active_scaffold - end -end - -module ActionController #:nodoc: - class Base - def assign_names_with_active_scaffold - assign_names_without_active_scaffold - @template.view_paths.active_scaffold_paths = self.class.active_scaffold_paths if search_generic_view_paths? - end - alias_method_chain :assign_names, :active_scaffold - - def search_generic_view_paths? - !self.is_a?(ActionMailer::Base) && self.class.action_methods.include?(self.action_name) - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/localize.rb b/vendor/plugins/active_scaffold/lib/extensions/localize.rb deleted file mode 100644 index 671a463..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/localize.rb +++ /dev/null @@ -1,10 +0,0 @@ -class Object - def as_(key, options = {}) - unless key.blank? - text = I18n.translate "#{key}", {:scope => [:active_scaffold], :default => key.is_a?(String) ? key : key.to_s.titleize}.merge(options) - # text = nil if text.include?('translation missing:') - end - text ||= key - text - end -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/nil_id_in_url_params.rb b/vendor/plugins/active_scaffold/lib/extensions/nil_id_in_url_params.rb deleted file mode 100644 index 29be1d3..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/nil_id_in_url_params.rb +++ /dev/null @@ -1,7 +0,0 @@ -class ActionController::Routing::RouteSet - def generate_with_nil_id_awareness(*args) - args[0].delete(:id) if args[0][:id].nil? - generate_without_nil_id_awareness(*args) - end - alias_method_chain :generate, :nil_id_awareness -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/lib/extensions/paginator_extensions.rb b/vendor/plugins/active_scaffold/lib/extensions/paginator_extensions.rb deleted file mode 100644 index 63ebb65..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/paginator_extensions.rb +++ /dev/null @@ -1,26 +0,0 @@ -require 'paginator' - -class Paginator - - # Total number of pages - def number_of_pages_with_infinite - number_of_pages_without_infinite unless infinite? - end - alias_method_chain :number_of_pages, :infinite - - # Is this an "infinite" paginator - def infinite? - @count.nil? - end - - class Page - # Checks to see if there's a page after this one - def next_with_infinite? - return true if @pager.infinite? - next_without_infinite? - end - alias_method_chain :next?, :infinite - end - -end - diff --git a/vendor/plugins/active_scaffold/lib/extensions/resources.rb b/vendor/plugins/active_scaffold/lib/extensions/resources.rb deleted file mode 100644 index 3699174..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/resources.rb +++ /dev/null @@ -1,27 +0,0 @@ -module ActionController - module Resources - class Resource - ACTIVE_SCAFFOLD_ROUTING = { - :collection => {:show_search => :get, :edit_associated => :get, :list => :get, :new_existing => :get, :add_existing => :post, :render_field => :get, :mark => :put}, - :member => {:row => :get, :nested => :get, :edit_associated => :get, :add_association => :get, :update_column => :post, :destroy_existing => :delete, :render_field => :get, :delete => :get, :mark => :put} - } - - # by overwriting the attr_reader :options, we can parse out a special :active_scaffold flag just-in-time. - def options_with_active_scaffold - if @options.delete :active_scaffold - logger.info "ActiveScaffold: extending RESTful routes for #{@plural}" - @options[:collection] ||= {} - @options[:collection].merge! ACTIVE_SCAFFOLD_ROUTING[:collection] - @options[:member] ||= {} - @options[:member].merge! ACTIVE_SCAFFOLD_ROUTING[:member] - end - options_without_active_scaffold - end - alias_method_chain :options, :active_scaffold - - def logger - ActionController::Base::logger - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb b/vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb deleted file mode 100644 index d17e119..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/reverse_associations.rb +++ /dev/null @@ -1,62 +0,0 @@ -module ActiveRecord - module Reflection - class AssociationReflection #:nodoc: - def reverse_for?(klass) - reverse_matches_for(klass).empty? ? false : true - end - - attr_writer :reverse - def reverse - if @reverse.nil? and not self.options[:polymorphic] - reverse_matches = reverse_matches_for(self.class_name.constantize) rescue nil - # grab first association, or make a wild guess - @reverse = reverse_matches.blank? ? false : reverse_matches.first.name - end - @reverse - end - - protected - - def reverse_matches_for(klass) - reverse_matches = [] - - # stage 1 filter: collect associations that point back to this model and use the same primary_key_name - klass.reflect_on_all_associations.each do |assoc| - if self.options[:through] - # only iterate has_many :through associations - next unless assoc.options[:through] - next unless assoc.through_reflection.klass == self.through_reflection.klass - else - # skip over has_many :through associations - next if assoc.options[:through] - next unless assoc.options[:polymorphic] or assoc.class_name.constantize == self.active_record - - case [assoc.macro, self.macro].find_all{|m| m == :has_and_belongs_to_many}.length - # if both are a habtm, then match them based on the join table - when 2 - next unless assoc.options[:join_table] == self.options[:join_table] - - # if only one is a habtm, they do not match - when 1 - next - - # otherwise, match them based on the primary_key_name - when 0 - next unless assoc.primary_key_name.to_sym == self.primary_key_name.to_sym - end - end - - reverse_matches << assoc - end - - # stage 2 filter: name-based matching (association name vs self.active_record.to_s) - reverse_matches.find_all do |assoc| - self.active_record.to_s.underscore.include? assoc.name.to_s.pluralize.singularize - end if reverse_matches.length > 1 - - reverse_matches - end - - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/to_label.rb b/vendor/plugins/active_scaffold/lib/extensions/to_label.rb deleted file mode 100644 index 9faae7f..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/to_label.rb +++ /dev/null @@ -1,8 +0,0 @@ -# the ever-useful to_label method -class ActiveRecord::Base - def to_label - [:name, :label, :title, :to_s].each do |attribute| - return send(attribute).to_s if respond_to?(attribute) - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/unsaved_associated.rb b/vendor/plugins/active_scaffold/lib/extensions/unsaved_associated.rb deleted file mode 100644 index c2683c9..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/unsaved_associated.rb +++ /dev/null @@ -1,61 +0,0 @@ -# save and validation support for associations. -class ActiveRecord::Base - def associated_valid?(path = []) - return true if path.include?(self) # prevent recursion (if associated and parent are new records) - path << self - # using [].all? syntax to avoid a short-circuit - with_unsaved_associated { |a| [a.valid?, a.associated_valid?(path)].all? {|v| v == true} } - end - - def save_associated - with_unsaved_associated { |a| a.save and a.save_associated } - end - - def save_associated! - save_associated or raise(ActiveRecord::RecordNotSaved) - end - - def no_errors_in_associated? - with_unsaved_associated {|a| a.errors.count == 0 and a.no_errors_in_associated?} - end - - protected - - # Provide an override to allow the model to restrict which associations are considered - # by ActiveScaffolds update mechanism. This allows the model to restrict things like - # Acts-As-Versioned versions associations being traversed. - # - # By defining the method :scaffold_update_nofollow returning an array of associations - # these associations will not be traversed. - # By defining the method :scaffold_update_follow returning an array of associations, - # only those associations will be traversed. - # - # Otherwise the default behaviour of traversing all associations will be preserved. - def associations_for_update - if self.respond_to?( :scaffold_update_nofollow ) - self.class.reflect_on_all_associations.reject { |association| self.scaffold_update_nofollow.include?( association.name ) } - elsif self.respond_to?( :scaffold_update_follow ) - self.class.reflect_on_all_associations.select { |association| self.scaffold_update_follow.include?( association.name ) } - else - self.class.reflect_on_all_associations - end - end - - private - - # yields every associated object that has been instantiated and is flagged as unsaved. - # returns false if any yield returns false. - # returns true otherwise, even when none of the associations have been instantiated. build wrapper methods accordingly. - def with_unsaved_associated - associations_for_update.all? do |association| - association_proxy = send(association.name) - if association_proxy - records = association_proxy - records = [records] unless records.is_a? Array # convert singular associations into collections for ease of use - records.select {|r| r.unsaved? and not r.readonly?}.all? {|r| yield r} # must use select instead of find_all, which Rails overrides on association proxies for db access - else - true - end - end - end -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/unsaved_record.rb b/vendor/plugins/active_scaffold/lib/extensions/unsaved_record.rb deleted file mode 100644 index 00ed519..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/unsaved_record.rb +++ /dev/null @@ -1,20 +0,0 @@ -# a simple (manual) unsaved? flag and method. at least it automatically reverts after a save! -class ActiveRecord::Base - # acts like a dirty? flag, manually thrown during update_record_from_params. - def unsaved=(val) - @unsaved = (val) ? true : false - end - - # whether the unsaved? flag has been thrown - def unsaved? - @unsaved - end - - # automatically unsets the unsaved flag - def save_with_unsaved_flag(*args) - result = save_without_unsaved_flag(*args) - self.unsaved = false - return result - end - alias_method_chain :save, :unsaved_flag -end diff --git a/vendor/plugins/active_scaffold/lib/extensions/usa_state.rb b/vendor/plugins/active_scaffold/lib/extensions/usa_state.rb deleted file mode 100644 index 236f036..0000000 --- a/vendor/plugins/active_scaffold/lib/extensions/usa_state.rb +++ /dev/null @@ -1,46 +0,0 @@ -module ActionView - module Helpers - module FormOptionsHelper - - # Return a full select and option tags for the given object and method, using usa_state_options_for_select to generate the list of option . - def usa_state_select(object, method, priority_states = nil, options = {}, html_options = {}) - InstanceTag.new(object, method, self, options.delete(:object)).to_usa_state_select_tag(priority_states, options, html_options) - end - - - # Returns a string of option tags for the states in the United States. Supply a state name as +selected to - # have it marked as the selected option tag. Included also is the option to set a couple of +priority_states+ - # in case you want to highligh a local area - # NOTE: Only the option tags are returned from this method, wrap it in a
', active_scaffold_input_paperclip(config.columns[:logo], :name => 'record[logo]', :id => 'record_logo') - - @record.stubs(:logo).returns(stub(:file? => false)) - assert_dom_equal '', active_scaffold_input_paperclip(config.columns[:logo], :name => 'record[logo]', :id => 'record_logo') - end -end diff --git a/vendor/plugins/active_scaffold/test/bridges/tiny_mce_test.rb b/vendor/plugins/active_scaffold/test/bridges/tiny_mce_test.rb deleted file mode 100644 index 764e80e..0000000 --- a/vendor/plugins/active_scaffold/test/bridges/tiny_mce_test.rb +++ /dev/null @@ -1,27 +0,0 @@ -require 'test/unit' -require File.join(File.dirname(__FILE__), 'company') -require File.join(File.dirname(__FILE__), '../../lib/bridges/tiny_mce/lib/tiny_mce_bridge') - -class TinyMceTest < ActionView::TestCase - include ActiveScaffold::Helpers::ViewHelpers - include ActiveScaffold::TinyMceBridge - - def test_includes - assert_match /.*", active_scaffold_input_text_editor(config.columns[:name], :name => 'record[name]', :id => 'record_name', :class => 'name-input') - end - - protected - def include_tiny_mce_if_needed; end - def tiny_mce_js; end - def using_tiny_mce? - true - end -end diff --git a/vendor/plugins/active_scaffold/test/bridges/unobtrusive_date_picker_test.rb b/vendor/plugins/active_scaffold/test/bridges/unobtrusive_date_picker_test.rb deleted file mode 100644 index 98ee3bf..0000000 --- a/vendor/plugins/active_scaffold/test/bridges/unobtrusive_date_picker_test.rb +++ /dev/null @@ -1,49 +0,0 @@ -require 'test/unit' -require File.join(File.dirname(__FILE__), 'company') -require File.join(File.dirname(__FILE__), '../../lib/bridges/unobtrusive_date_picker/lib/unobtrusive_date_picker_bridge') -require File.join(File.dirname(__FILE__), '../../lib/bridges/unobtrusive_date_picker/lib/view_helpers') -require File.join(File.dirname(__FILE__), '../../lib/bridges/unobtrusive_date_picker/lib/form_ui') - -class UDPCore < ActiveScaffold::Config::Core - include ActiveScaffold::UnobtrusiveDatePickerBridge -end - -class UnobtrusiveDatePickerTest < ActionView::TestCase - include ActiveScaffold::Helpers::ViewHelpers - include ActiveScaffold::UnobtrusiveDatePickerHelpers - - def test_set_form_ui - config = UDPCore.new(:company) - assert_equal nil, config.columns[:name].form_ui, 'form_ui for name' - assert_equal :datepicker, config.columns[:date].form_ui, 'form_ui for date' - assert_equal :datepicker, config.columns[:datetime].form_ui, 'form_ui for datetime' - end - - def test_stylesheets - assert active_scaffold_stylesheets.include?('datepicker.css') - end - - def test_javascripts - assert active_scaffold_javascripts.include?('datepicker.js') - assert active_scaffold_javascripts.include?('datepicker_lang/es.js') - end - - def test_form_ui - config = UDPCore.new(:company) - self.expects(:date_select).returns('') - self.expects(:date_picker).returns('') - assert active_scaffold_input_datepicker(config.columns[:date], :name => 'record[date]', :id => 'record_date') - - self.expects(:datetime_select).returns('') - self.expects(:date_picker).returns('') - assert active_scaffold_input_datepicker(config.columns[:datetime], :name => 'record[datetime]', :id => 'record_datetime') - end - - private - def unobtrusive_datepicker_stylesheets - ['datepicker.css'] - end - def unobtrusive_datepicker_javascripts - ['datepicker.js', 'datepicker_lang/es.js'] - end -end diff --git a/vendor/plugins/active_scaffold/test/bridges/validation_reflection_test.rb b/vendor/plugins/active_scaffold/test/bridges/validation_reflection_test.rb deleted file mode 100644 index f838fea..0000000 --- a/vendor/plugins/active_scaffold/test/bridges/validation_reflection_test.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'test/unit' -require File.join(File.dirname(__FILE__), 'company') -require File.join(File.dirname(__FILE__), '../../lib/bridges/validation_reflection/lib/validation_reflection_bridge') - -class ColumnWithValidationReflection < ActiveScaffold::DataStructures::Column - include ActiveScaffold::ValidationReflectionBridge -end - -class ValidationReflectionTest < Test::Unit::TestCase - def test_set_required_for_validates_presence_of - Company.expects(:reflect_on_validations_for).with(:name).returns([stub(:macro => :validates_presence_of)]) - column = ColumnWithValidationReflection.new(:name, Company) - assert column.required? - end - - def test_set_required_for_validates_inclusion_of - Company.expects(:reflect_on_validations_for).with(:name).returns([stub(:macro => :validates_inclusion_of, :options => {})]) - column = ColumnWithValidationReflection.new(:name, Company) - assert column.required? - end - - def test_not_set_required_for_validates_inclusion_of_and_allow_nil - Company.expects(:reflect_on_validations_for).with(:name).returns([stub(:macro => :validates_inclusion_of, :options => {:allow_nil => true})]) - column = ColumnWithValidationReflection.new(:name, Company) - assert !column.required? - end - - def test_not_set_required_for_validates_inclusion_of_and_allow_blank - Company.expects(:reflect_on_validations_for).with(:name).returns([stub(:macro => :validates_inclusion_of, :options => {:allow_blank => true})]) - column = ColumnWithValidationReflection.new(:name, Company) - assert !column.required? - end - - def test_not_set_required_for_no_validation - Company.expects(:reflect_on_validations_for).with(:name).returns([]) - column = ColumnWithValidationReflection.new(:name, Company) - assert !column.required? - end - - def test_set_required_for_validates_presence_of_in_association - Company.stubs(:reflect_on_validations_for).returns([stub(:macro => :validates_presence_of)], []) - column = ColumnWithValidationReflection.new(:main_company, Company) - assert column.required? - end - - def test_set_required_for_validates_presence_of_in_foreign_key - Company.stubs(:reflect_on_validations_for).returns([], [stub(:macro => :validates_presence_of)]) - column = ColumnWithValidationReflection.new(:main_company, Company) - assert column.required? - end - - def test_not_set_required_for_no_validation_in_association_neither_foreign_key - Company.stubs(:reflect_on_validations_for).returns([]) - column = ColumnWithValidationReflection.new(:main_company, Company) - assert !column.required? - end -end diff --git a/vendor/plugins/active_scaffold/test/config/base_test.rb b/vendor/plugins/active_scaffold/test/config/base_test.rb deleted file mode 100644 index 9fab684..0000000 --- a/vendor/plugins/active_scaffold/test/config/base_test.rb +++ /dev/null @@ -1,15 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::BaseTest < Test::Unit::TestCase - def setup - @base = ActiveScaffold::Config::Base.new(ActiveScaffold::Config::Core.new(:model_stub)) - end - - def test_formats - assert_equal [], @base.formats - @base.formats << :pdf - assert_equal [:pdf], @base.formats - @base.formats = [:html] - assert_equal [:html], @base.formats - end -end diff --git a/vendor/plugins/active_scaffold/test/config/core_test.rb b/vendor/plugins/active_scaffold/test/config/core_test.rb deleted file mode 100644 index c1994d5..0000000 --- a/vendor/plugins/active_scaffold/test/config/core_test.rb +++ /dev/null @@ -1,58 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::CoreTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - end - - def test_default_options - assert !@config.add_sti_create_links? - assert !@config.sti_children - assert_equal [:create, :list, :search, :update, :delete, :show, :nested, :subform], @config.actions.to_a - assert_equal :default, @config.frontend - assert_equal :default, @config.theme - assert_equal 'ModelStub', @config.label(:count => 1) - assert_equal 'ModelStubs', @config.label - end - - def test_add_sti_children - @config.sti_create_links = true - assert !@config.add_sti_create_links? - @config.sti_children = [:a] - assert @config.add_sti_create_links? - end - - def test_sti_children - @config.sti_children = [:a] - assert_equal [:a], @config.sti_children - end - - def test_actions - assert @config.actions.include?(:create) - @config.actions = [:list] - assert !@config.actions.include?(:create) - assert_equal [:list], @config.actions.to_a - end - - def test_form_ui_in_sti - @config.columns << :type - - @config.sti_children = [:model_stub] - @config._configure_sti - assert_equal :select, @config.columns[:type].form_ui - assert_equal [['Modelstub', 'ModelStub']], @config.columns[:type].options[:options] - - @config.columns[:type].form_ui = nil - @config.sti_create_links = true - @config._configure_sti - assert_equal :hidden, @config.columns[:type].form_ui - end - - def test_sti_children_links - @config.sti_children = [:model_stub] - @config.sti_create_links = true - @config.action_links.add @config.create.link - @config._add_sti_create_links - assert_equal 'Create Modelstub', @config.action_links[:new].label - end -end diff --git a/vendor/plugins/active_scaffold/test/config/create_test.rb b/vendor/plugins/active_scaffold/test/config/create_test.rb deleted file mode 100644 index 0f9f002..0000000 --- a/vendor/plugins/active_scaffold/test/config/create_test.rb +++ /dev/null @@ -1,58 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::CreateTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - @default_link = @config.create.link - end - - def teardown - @config.create.link = @default_link - end - - def test_default_options - assert !@config.create.persistent - assert @config.create.action_after_create.nil? - assert_equal 'Create ModelStub', @config.create.label - end - - def test_link_defaults - link = @config.create.link - assert !link.page? - assert !link.popup? - assert !link.confirm? - assert_equal "new", link.action - assert_equal "Create New", link.label - assert link.inline? - blank = {} - assert_equal blank, link.html_options - assert_equal :get, link.method - assert_equal :collection, link.type - assert_equal :create, link.crud_type - assert_equal :create_authorized?, link.security_method - end - - def test_setting_link - @config.create.link = ActiveScaffold::DataStructures::ActionLink.new('update', :label => 'Monkeys') - assert_not_equal(@default_link, @config.create.link) - end - - def test_label - label = 'create new monkeys' - @config.create.label = label - assert_equal label, @config.create.label - I18n.backend.store_translations :en, :active_scaffold => {:create_new_model => 'Create new %{model}'} - @config.create.label = :create_new_model - assert_equal 'Create new ModelStub', @config.create.label - end - - def test_persistent - @config.create.persistent = true - assert @config.create.persistent - end - - def test_action_after_create - @config.create.action_after_create = :edit - assert_equal :edit, @config.create.action_after_create - end -end diff --git a/vendor/plugins/active_scaffold/test/config/delete_test.rb b/vendor/plugins/active_scaffold/test/config/delete_test.rb deleted file mode 100644 index 8d3f116..0000000 --- a/vendor/plugins/active_scaffold/test/config/delete_test.rb +++ /dev/null @@ -1,33 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::DeleteTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - @default_link = @config.delete.link - end - - def teardown - @config.delete.link = @default_link - end - - def test_link_defaults - link = @config.delete.link - assert !link.page? - assert !link.popup? - assert link.confirm? - assert_equal "delete", link.action - assert_equal "Delete", link.label - assert link.inline? - blank = {} - assert_equal blank, link.html_options - assert_equal :delete, link.method - assert_equal :member, link.type - assert_equal :delete, link.crud_type - assert_equal :delete_authorized?, link.security_method - end - - def test_setting_link - @config.delete.link = ActiveScaffold::DataStructures::ActionLink.new('update', :label => 'Monkeys') - assert_not_equal(@default_link, @config.delete.link) - end -end diff --git a/vendor/plugins/active_scaffold/test/config/field_search_test.rb b/vendor/plugins/active_scaffold/test/config/field_search_test.rb deleted file mode 100644 index ed6f9c4..0000000 --- a/vendor/plugins/active_scaffold/test/config/field_search_test.rb +++ /dev/null @@ -1,47 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::FieldSearchTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - @config.actions.swap :search, :field_search - @default_link = @config.field_search.link - end - - def teardown - @config.field_search.link = @default_link - end - - def test_default_options - assert_equal :full, @config.field_search.text_search - end - - def test_text_search - @config.field_search.text_search = :start - assert_equal :start, @config.field_search.text_search - @config.field_search.text_search = :end - assert_equal :end, @config.field_search.text_search - @config.field_search.text_search = false - assert !@config.field_search.text_search - end - - def test_link_defaults - link = @config.field_search.link - assert !link.page? - assert !link.popup? - assert !link.confirm? - assert_equal "show_search", link.action - assert_equal "Search", link.label - assert link.inline? - blank = {} - assert_equal blank, link.html_options - assert_equal :get, link.method - assert_equal :collection, link.type - assert_equal :read, link.crud_type - assert_equal :search_authorized?, link.security_method - end - - def test_setting_link - @config.field_search.link = ActiveScaffold::DataStructures::ActionLink.new('update', :label => 'Monkeys') - assert_not_equal(@default_link, @config.field_search.link) - end -end diff --git a/vendor/plugins/active_scaffold/test/config/list_test.rb b/vendor/plugins/active_scaffold/test/config/list_test.rb deleted file mode 100644 index 057e5e0..0000000 --- a/vendor/plugins/active_scaffold/test/config/list_test.rb +++ /dev/null @@ -1,129 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::ListTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - end - - def test_label - I18n.backend.store_translations :en, :active_scaffold => {:resource => {:one => 'Resource', :other => 'Resources'}} - @config.list.label = :resource - assert_equal 'Resources', @config.list.label - label = 'monkeys' - @config.list.label = label - assert_equal label, @config.list.label - end - - def test_default_options - assert_equal 15, @config.list.per_page - assert_equal 2, @config.list.page_links_window - assert_equal '-', @config.list.empty_field_text - assert_equal ', ', @config.list.association_join_text - assert_equal true, @config.list.pagination - assert_equal 'search', @config.list.search_partial - assert_equal :no_entries, @config.list.no_entries_message - assert_equal :filtered, @config.list.filtered_message - assert !@config.list.always_show_create - assert !@config.list.always_show_search - assert !@config.list.mark_records - assert @config.list.count_includes.nil? - assert_equal 'ModelStubs', @config.list.label - assert @config.list.sorting.sorts_on?(:id) - assert_equal 'ASC', @config.list.sorting.direction_of(:id) - end - - def test_empty_field_text - @config.list.empty_field_text = '(missing)' - assert_equal '(missing)', @config.list.empty_field_text - end - - def test_association_join_text - @config.list.association_join_text = '
' - assert_equal '
', @config.list.association_join_text - end - - def test_no_entries - @config.list.no_entries_message = 'No items' - assert_equal 'No items', @config.list.no_entries_message - end - - def test_filtered_message - @config.list.filtered_message = 'filtered items' - assert_equal 'filtered items', @config.list.filtered_message - end - - def test_pagination - @config.list.pagination = :infinite - assert_equal :infinite, @config.list.pagination - @config.list.pagination = false - assert !@config.list.pagination - end - - def test_sorting - @config.list.sorting = {:a => :desc} - assert @config.list.sorting.sorts_on?(:a) - assert_equal 'DESC', @config.list.sorting.direction_of(:a) - assert !@config.list.sorting.sorts_on?(:id) - - @config.list.sorting = [{:a => :asc}, {:b => :desc}] - assert @config.list.sorting.sorts_on?(:a) - assert_equal 'ASC', @config.list.sorting.direction_of(:a) - assert @config.list.sorting.sorts_on?(:b) - assert_equal 'DESC', @config.list.sorting.direction_of(:b) - assert !@config.list.sorting.sorts_on?(:id) - end - - def test_mark_records - @config.list.mark_records = true - assert @config.list.mark_records - end - - def test_per_page - per_page = 35 - @config.list.per_page = per_page - assert_equal per_page, @config.list.per_page - end - - def test_page_links_window - page_links_window = 3 - @config.list.page_links_window = page_links_window - assert_equal page_links_window, @config.list.page_links_window - end - - def test_always_show_create - always_show_create = true - @config.list.always_show_create = always_show_create - assert_equal always_show_create, @config.list.always_show_create - end - - def test_always_show_create_when_create_is_not_enabled - always_show_create = true - @config.list.always_show_create = always_show_create - @config.actions.exclude :create - assert_equal false, @config.list.always_show_create - end - - def test_always_show_search - @config.list.always_show_search = true - assert @config.list.always_show_search - assert_equal 'search', @config.list.search_partial - end - - def test_always_show_search_when_search_is_not_enabled - @config.list.always_show_search = true - @config.actions.exclude :search - assert_equal false, @config.list.always_show_search - end - - def test_always_show_search_when_field_search - @config.list.always_show_search = true - @config.actions.swap :search, :field_search - assert @config.list.always_show_search - assert_equal 'field_search', @config.list.search_partial - end - - def test_count_includes - @config.list.count_includes = [:assoc_1, :assoc_2] - assert_equal [:assoc_1, :assoc_2], @config.list.count_includes - end -end diff --git a/vendor/plugins/active_scaffold/test/config/nested_test.rb b/vendor/plugins/active_scaffold/test/config/nested_test.rb deleted file mode 100644 index c4445a9..0000000 --- a/vendor/plugins/active_scaffold/test/config/nested_test.rb +++ /dev/null @@ -1,44 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::NestedTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - end - - def test_default_options - assert !@config.nested.shallow_delete - assert_equal 'Add Existing ModelStub', @config.nested.label - end - - def test_label - label = 'nested monkeys' - @config.nested.label = label - assert_equal label, @config.nested.label - I18n.backend.store_translations :en, :active_scaffold => {:create_model => 'Add new %{model}'} - @config.nested.label = :create_model - assert_equal 'Add new ModelStub', @config.nested.label - end - - def test_shallow_delete - @config.nested.shallow_delete = true - assert @config.nested.shallow_delete - end - - def test_add_link - @config.nested.add_link :custom_link, [:assoc_1, :assoc_2] - link = @config.action_links['nested'] - assert_equal 'Custom Link', link.label - assert_equal 'nested', link.action - assert_equal :after, link.position - assert !link.page? - assert !link.popup? - assert !link.confirm? - assert link.inline? - assert_equal 'assoc_1 assoc_2', link.parameters[:associations] - assert_equal 'assoc_1 assoc_2', link.html_options[:class] - assert_equal :get, link.method - assert_equal :member, link.type - assert_equal :read, link.crud_type - assert_equal :nested_authorized?, link.security_method - end -end diff --git a/vendor/plugins/active_scaffold/test/config/search_test.rb b/vendor/plugins/active_scaffold/test/config/search_test.rb deleted file mode 100644 index 5db57a6..0000000 --- a/vendor/plugins/active_scaffold/test/config/search_test.rb +++ /dev/null @@ -1,60 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::SearchTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - @default_link = @config.search.link - end - - def teardown - @config.search.link = @default_link - end - - def test_default_options - assert_equal :full, @config.search.text_search - assert !@config.search.live? - assert_equal ' ', @config.search.split_terms - end - - def test_text_search - @config.search.text_search = :start - assert_equal :start, @config.search.text_search - @config.search.text_search = :end - assert_equal :end, @config.search.text_search - @config.search.text_search = false - assert !@config.search.text_search - end - - def test_live - @config.search.live = true - assert @config.search.live? - end - - def test_split_terms - @config.search.split_terms = nil - assert @config.search.split_terms.nil? - @config.search.split_terms = ',' - assert_equal ',', @config.search.split_terms - end - - def test_link_defaults - link = @config.search.link - assert !link.page? - assert !link.popup? - assert !link.confirm? - assert_equal "show_search", link.action - assert_equal "Search", link.label - assert link.inline? - blank = {} - assert_equal blank, link.html_options - assert_equal :get, link.method - assert_equal :collection, link.type - assert_equal :read, link.crud_type - assert_equal :search_authorized?, link.security_method - end - - def test_setting_link - @config.search.link = ActiveScaffold::DataStructures::ActionLink.new('update', :label => 'Monkeys') - assert_not_equal(@default_link, @config.search.link) - end -end diff --git a/vendor/plugins/active_scaffold/test/config/show_test.rb b/vendor/plugins/active_scaffold/test/config/show_test.rb deleted file mode 100644 index 5911041..0000000 --- a/vendor/plugins/active_scaffold/test/config/show_test.rb +++ /dev/null @@ -1,43 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::ShowTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - @default_link = @config.show.link - end - - def teardown - @config.show.link = @default_link - end - - def test_link_defaults - link = @config.show.link - assert !link.page? - assert !link.popup? - assert !link.confirm? - assert_equal "show", link.action - assert_equal "Show", link.label - assert link.inline? - blank = {} - assert_equal blank, link.html_options - assert_equal :get, link.method - assert_equal :member, link.type - assert_equal :read, link.crud_type - assert_equal :show_authorized?, link.security_method - end - - def test_setting_link - @config.show.link = ActiveScaffold::DataStructures::ActionLink.new('update', :label => 'Monkeys') - assert_not_equal(@default_link, @config.show.link) - end - - def test_label - label = 'show monkeys' - @config.show.label = label - assert_equal label, @config.show.label - I18n.backend.store_translations :en, :active_scaffold => {:view_model => 'View %{model}'} - @config.show.label = :view_model - assert_equal 'View ModelStub', @config.show.label - assert_equal 'View record', @config.show.label('record') - end -end diff --git a/vendor/plugins/active_scaffold/test/config/subform_test.rb b/vendor/plugins/active_scaffold/test/config/subform_test.rb deleted file mode 100644 index aed277f..0000000 --- a/vendor/plugins/active_scaffold/test/config/subform_test.rb +++ /dev/null @@ -1,17 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::SubformTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - end - - def test_defaults - assert_equal :horizontal, @config.subform.layout - end - - def test_setting_layout - layout = :vertical - @config.subform.layout = layout - assert_equal layout, @config.subform.layout - end -end diff --git a/vendor/plugins/active_scaffold/test/config/update_test.rb b/vendor/plugins/active_scaffold/test/config/update_test.rb deleted file mode 100644 index 4972278..0000000 --- a/vendor/plugins/active_scaffold/test/config/update_test.rb +++ /dev/null @@ -1,40 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class Config::UpdateTest < Test::Unit::TestCase - def setup - @config = ActiveScaffold::Config::Core.new :model_stub - end - - def test__params_for_columns__returns_all_params - @config._load_action_columns - @config.columns[:a].params.add :keep_a, :a_temp - assert @config.columns[:a].params.include?(:keep_a) - assert @config.columns[:a].params.include?(:a_temp) - end - - def test_default_options - assert !@config.update.persistent - assert !@config.update.nested_links - assert_equal 'Update ModelStub', @config.update.label - end - - def test_persistent - @config.update.persistent = true - assert @config.update.persistent - end - - def test_nested_links - @config.update.nested_links = true - assert @config.update.nested_links - end - - def test_label - label = 'update new monkeys' - @config.update.label = label - assert_equal label, @config.update.label - I18n.backend.store_translations :en, :active_scaffold => {:change_model => 'Change %{model}'} - @config.update.label = :change_model - assert_equal 'Change ModelStub', @config.update.label - assert_equal 'Change record', @config.update.label('record') - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/const_mocker.rb b/vendor/plugins/active_scaffold/test/const_mocker.rb deleted file mode 100644 index 32e1b80..0000000 --- a/vendor/plugins/active_scaffold/test/const_mocker.rb +++ /dev/null @@ -1,36 +0,0 @@ -class ConstMocker - def initialize(*const_names) - @const_names = const_names - @const_states = {} - @const_names.each{|const_name| - @const_states[const_name] = Object.const_defined?(const_name) ? Object.const_get(const_name) : nil - } - end - - def remove - @const_names.each{|const_name| - Object.send :remove_const, const_name if Object.const_defined?(const_name) - } - end - - def declare - @const_names.each{|const_name| - Object.class_eval "class #{const_name}; end;" unless Object.const_defined?(const_name) - } - end - - def restore - remove - - @const_states.each_pair{|const_name, const| - Object.const_set const_name, const if const - } - end - - def self.mock(*const_names, &block) - cm = new(*const_names) - yield(cm) - cm.restore - true - end -end diff --git a/vendor/plugins/active_scaffold/test/data_structures/action_columns_test.rb b/vendor/plugins/active_scaffold/test/data_structures/action_columns_test.rb deleted file mode 100644 index b99760f..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/action_columns_test.rb +++ /dev/null @@ -1,113 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -# require 'test/model_stub' -require File.join(File.dirname(__FILE__), '../../lib/active_scaffold/data_structures/set.rb') - -class ActionColumnsTest < Test::Unit::TestCase - def setup - @columns = ActiveScaffold::DataStructures::ActionColumns.new([:a, :b]) - end - - def test_label - assert_nothing_raised do - @columns.label = 'foo'; - end - assert @columns.label == 'foo' - end - - def test_initialization - assert @columns.include?(:a) - assert @columns.include?(:b) - assert !@columns.include?(:c) - end - - def test_exclude - # exclude with a symbol - assert @columns.include?(:b) - @columns.exclude :b - assert !@columns.include?(:b) - - # exclude with a string - assert @columns.include?(:a) - @columns.exclude 'a' - assert !@columns.include?(:a) - end - - def test_exclude_array - # exclude with a symbol - assert @columns.include?(:b) - @columns.exclude [:a, :b] - assert !@columns.include?(:b) - assert !@columns.include?(:a) - end - - def test_add - # try adding a simple column using a string - assert !@columns.include?(:c) - @columns.add 'c' - assert @columns.include?(:c) - - # try adding a simple column using a symbol - assert !@columns.include?(:d) - @columns.add :d - assert @columns.include?(:d) - - # test that << also adds - assert !@columns.include?(:e) - @columns << :e - assert @columns.include?(:e) - - # try adding an array of columns - assert !@columns.include?(:f) - @columns.add [:f, :g] - assert @columns.include?(:f) - assert @columns.include?(:g) - - end - - def test_length - assert_equal 2, @columns.length - end - - def test_add_subgroup - # first, use @columns.add directly - @c2 = ActiveScaffold::DataStructures::ActionColumns.new - @columns.add @c2 - assert @columns.any? { |c| c == @c2 } - - # then use the shortcut - @columns.add_subgroup 'foo' do - end - assert @columns.any? { |c| c.respond_to? :label and c.label == 'foo' } - end - - def test_block_config - @columns.configure do |config| - # we may use the config argument - config.add :c - # or we may not - exclude :b - add_subgroup 'my subgroup' do - add :e - end - end - - assert @columns.include?(:c) - assert !@columns.include?(:b) - @columns.each { |c| - next unless c.is_a? ActiveScaffold::DataStructures::Columns - assert c.include?(:e) - assert_equal 'my subgroup', c.name - } - end - - def test_include - @columns.add_subgroup 'foo' do - add :c - end - - assert @columns.include?(:a) - assert @columns.include?(:b) - assert @columns.include?(:c) - assert !@columns.include?(:d) - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/data_structures/action_link_test.rb b/vendor/plugins/active_scaffold/test/data_structures/action_link_test.rb deleted file mode 100644 index ff27bca..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/action_link_test.rb +++ /dev/null @@ -1,78 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ActionLinkTest < Test::Unit::TestCase - def setup - @link = ActiveScaffold::DataStructures::ActionLink.new('foo') - end - - def test_simple_attributes - assert_equal 'foo', @link.action - @link.action = 'bar' - assert_equal 'bar', @link.action - - hash = {:a => :b} - @link.parameters = hash - assert_equal hash, @link.parameters - - @link.label = 'hello world' - assert_equal 'hello world', @link.label - - assert !@link.confirm - @link.confirm = true - assert @link.confirm - - assert_equal 'bar_authorized?', @link.security_method - - assert_equal false, @link.security_method_set? - @link.security_method = 'blueberry_pie' - assert_equal true, @link.security_method_set? - assert_equal 'blueberry_pie', @link.security_method - - @link.type = :collection - assert_equal :collection, @link.type - @link.type = :member - assert_equal :member, @link.type - - assert_equal :get, @link.method - @link.method = :put - assert_equal :put, @link.method - end - - def test_position - @link.position = true - - @link.type = :collection - assert_equal :top, @link.position - - @link.type = :member - assert_equal :replace, @link.position - - @link.position = :before - assert_equal :before, @link.position - - @link.position = false - assert_equal false, @link.position - end - - def test_presentation_style - # default - assert @link.inline? - assert !@link.popup? - assert !@link.page? - - @link.popup = true - assert !@link.inline? - assert @link.popup? - assert !@link.page? - - @link.page = true - assert !@link.inline? - assert !@link.popup? - assert @link.page? - - @link.inline = true - assert @link.inline? - assert !@link.popup? - assert !@link.page? - end -end diff --git a/vendor/plugins/active_scaffold/test/data_structures/action_links_test.rb b/vendor/plugins/active_scaffold/test/data_structures/action_links_test.rb deleted file mode 100644 index 3809255..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/action_links_test.rb +++ /dev/null @@ -1,78 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ActionLinksTest < Test::Unit::TestCase - def setup - @links = ActiveScaffold::DataStructures::ActionLinks.new - end - - def test_add_and_find - # test adding with a shortcut - @links.add 'foo/bar' - - assert_equal 1, @links.find_all{true}.size - assert_equal 'foo/bar', @links.find_all{true}[0].action - assert_equal 'foo/bar', @links['foo/bar'].action - - # test adding an ActionLink object directly - @links.add ActiveScaffold::DataStructures::ActionLink.new('hello/world') - - assert_equal 2, @links.find_all{true}.size - - # test the << alias - @links << 'a/b' - - assert_equal 3, @links.find_all{true}.size - end - - def test_array_access - @link1 = ActiveScaffold::DataStructures::ActionLink.new 'foo/bar' - @link2 = ActiveScaffold::DataStructures::ActionLink.new 'hello_world' - - @links.add @link1 - @links.add @link2 - - assert_equal @link1, @links[@link1.action] - assert_equal @link2, @links[@link2.action] - end - - def test_empty - assert @links.empty? - @links.add 'a' - assert !@links.empty? - end - - def test_cloning - @links.add 'foo/bar' - @links_copy = @links.clone - - assert !@links.equal?(@links_copy) - assert !@links['foo/bar'].equal?(@links_copy['foo/bar']) - end - - def test_each - @links.add 'foo', :type => :collection - @links.add 'bar', :type => :member - - @links.each :collection do |link| - assert_equal 'foo', link.action - end - @links.each :member do |link| - assert_equal 'bar', link.action - end - end - - def test_delete - @links.add 'foo' - @links.add 'bar' - - @links.delete :foo - assert @links['foo'].nil? - begin - @links.delete :foo - @links.delete 'foo' - rescue - assert false, "deleting from action links when item doesn't exist should not throw an error" - end - assert !@links['bar'].nil? - end -end diff --git a/vendor/plugins/active_scaffold/test/data_structures/actions_test.rb b/vendor/plugins/active_scaffold/test/data_structures/actions_test.rb deleted file mode 100644 index a0eea23..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/actions_test.rb +++ /dev/null @@ -1,25 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ActionsTest < Test::Unit::TestCase - def setup - @actions = ActiveScaffold::DataStructures::Actions.new(:a, 'b') - end - - def test_initialization - assert @actions.include?('a') - assert @actions.include?(:b) - assert !@actions.include?(:c) - end - - def test_exclude - assert @actions.include?('b') - @actions.exclude :b - assert !@actions.include?(:b) - end - - def test_add - assert !@actions.include?(:c) - @actions.add 'c' - assert @actions.include?('c') - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/data_structures/association_column_test.rb b/vendor/plugins/active_scaffold/test/data_structures/association_column_test.rb deleted file mode 100644 index 0abe073..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/association_column_test.rb +++ /dev/null @@ -1,42 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -require File.join(File.dirname(__FILE__), '../model_stub') - -class AssociationColumnTest < Test::Unit::TestCase - def setup - @association_column = ActiveScaffold::DataStructures::Column.new('other_model', ModelStub) - end - - def test_virtuality - assert @association_column.association - assert !@association_column.virtual? - end - - def test_sorting - # sorting on association columns is method-based - hash = {:method => "other_model.to_s"} - assert_equal hash, @association_column.sort - end - - def test_searching - # by default searching on association columns uses primary key - assert @association_column.searchable? - assert_equal '"model_stubs"."id"', @association_column.search_sql - end - - def test_association - assert @association_column.association.is_a?(ActiveRecord::Reflection::AssociationReflection) - end - - def test_includes - assert_equal [:other_model], @association_column.includes - end - - def test_plurality - assert @association_column.singular_association? - assert !@association_column.plural_association? - - plural_association_column = ActiveScaffold::DataStructures::Column.new('other_models', ModelStub) - assert plural_association_column.plural_association? - assert !plural_association_column.singular_association? - end -end diff --git a/vendor/plugins/active_scaffold/test/data_structures/column_test.rb b/vendor/plugins/active_scaffold/test/data_structures/column_test.rb deleted file mode 100644 index 04dd1dc..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/column_test.rb +++ /dev/null @@ -1,185 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ColumnTest < Test::Unit::TestCase - def setup - @column = ActiveScaffold::DataStructures::Column.new(:a, ModelStub) - @association_col = ActiveScaffold::DataStructures::Column.new(:b, ModelStub) - @association_col.stubs(:polymorphic_association?).returns(false) - @association_col.instance_variable_set(:@association, true) - end - - def test_column - assert @column.column.is_a?(ActiveRecord::ConnectionAdapters::Column) - assert @column.column.name == 'a' - end - - def test_basic_properties - # test that it was set during initialization - assert_equal @column.name, :a - # test that we can change it - @column.name = :b - assert_equal @column.name, :b - - # label - @column.label = 'foo' - assert_equal 'foo', @column.label - - # description - @column.description = 'hello world' - assert_equal 'hello world', @column.description - - # css class - @column.css_class = 'style_me' - assert_equal 'style_me', @column.css_class - - # required - assert !@column.required?, 'default is false' - @column.required = true - assert @column.required?, 'can be changed' - - # calculation - assert !@column.calculation?, 'default is nil' - @column.calculate = :sum - assert @column.calculation?, 'can be changed' - end - - def test_field - assert_equal '"model_stubs"."a"', @column.send(:field) - end - - def test_table - assert_equal 'model_stubs', @column.send(:table) - end - - def test_equality - # create a separate columns object, and make sure it's not == - columns = ActiveScaffold::DataStructures::Columns.new(ModelStub, :a, :b) - assert columns != @column - - # create a separate action_columns object, and make sure it's not == - columns = ActiveScaffold::DataStructures::ActionColumns.new(:a, :b) - assert columns != @column - - # identity - assert @column == @column - - # string comparison - assert @column == 'a' - assert @column != 'fake' - - # symbol comparison - assert @column == :a - assert @column != :fake - - # comparison with different object of same type - column2 = ActiveScaffold::DataStructures::Column.new(:fake, ModelStub) - assert @column != column2 - column2.name = 'a' - assert @column == column2 - - # special comparisons - assert @column != nil - assert @column != '' - assert @column != 0 - end - - def test_ui - assert_nil @column.form_ui - assert_nil @column.list_ui - assert_nil @column.search_ui - assert_equal :select, @association_col.search_ui - - @column.form_ui = :calendar - assert_equal :calendar, @column.form_ui - assert_equal :calendar, @column.list_ui - assert_equal :calendar, @column.search_ui - - @association_col.form_ui = :record_select - assert_equal :record_select, @association_col.form_ui - assert_equal :record_select, @association_col.search_ui - - @column.search_ui = :record_select - @column.list_ui = :checkbox - assert_equal :calendar, @column.form_ui - assert_equal :checkbox, @column.list_ui - assert_equal :record_select, @column.search_ui - end - - def test_searchable - @column.search_sql = nil - assert !@column.searchable? - @column.search_sql = true - assert @column.searchable? - end - - def test_sortable - @column.sort = nil - assert !@column.sortable? - @column.sort = true - assert @column.sortable? - end - - def test_custom_search - @column.search_sql = true - assert_equal '"model_stubs"."a"', @column.search_sql - @column.search_sql = 'foobar' - assert_equal 'foobar', @column.search_sql - assert @column.searchable? - end - - def test_custom_sort - @column.sort = true - hash = {:sql => '"model_stubs"."a"'} - assert_equal hash, @column.sort - @column.sort_by :sql => 'foobar' - hash = {:sql => 'foobar'} - assert_equal hash, @column.sort - - some_proc = proc {'foobar'} - @column.sort_by :method => some_proc - hash = {:method => some_proc} - assert_equal hash, @column.sort - assert @column.sortable? - end - - def test_custom_sort__should_assert_keys - assert_raise(ArgumentError) { @column.sort_by :proc => "invalid config" } - assert_raise(ArgumentError) { @column.sort={:proc => "invalid config" } } - assert_nothing_raised(ArgumentError) {@column.sort_by :method => "method" } - assert_nothing_raised(ArgumentError) {@column.sort_by :sql => "method" } - end - - def test_config_block - @column.configure do |config| - # we can use the config object - config.name = 'foo' - # or not - self.label = 'hello' - end - - assert_equal 'foo', @column.name - assert_equal 'hello', @column.label - end - - def test_action_link - link = ActiveScaffold::DataStructures::ActionLink.new('foo/bar') - @column.set_link link - assert_equal link, @column.link - - @column.set_link 'hello_world' - assert_equal 'hello_world', @column.link.action - assert_equal @column.label, @column.link.label - end - - def test_includes - assert_equal [], @column.includes - - # make sure that when a non-array comes in, an array comes out - @column.includes = :column_name - assert_equal([:column_name], @column.includes) - - # make sure that when a non-array comes in, an array comes out - @column.includes = [:column_name] - assert_equal([:column_name], @column.includes) - end -end diff --git a/vendor/plugins/active_scaffold/test/data_structures/columns_test.rb b/vendor/plugins/active_scaffold/test/data_structures/columns_test.rb deleted file mode 100644 index 203e428..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/columns_test.rb +++ /dev/null @@ -1,69 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -# require 'test/model_stub' - -class ColumnsTest < Test::Unit::TestCase - def setup - @columns = ActiveScaffold::DataStructures::Columns.new(ModelStub, :a, :b) - end - - def test_initialization - assert_equal ModelStub, @columns.active_record_class - - assert @columns.include?('a'), 'checking via string' - assert @columns.include?(:b), 'checking via symbol' - assert !@columns.include?(:c) - end - - def test_add - assert !@columns.include?(:c) - @columns.add 'c' - assert @columns.include?('c') - - # test the alias - assert !@columns.include?(:d) - @columns << :d - assert @columns.include?(:d) - - # try adding an array of columns - assert !@columns.include?(:f) - @columns.add [:f, :g] - assert @columns.include?(:f) - assert @columns.include?(:g) - end - - def test_finders - # test some basic assumptions before testing the finders - assert @columns.include?(:a) - assert @columns[:a].is_a?(ActiveScaffold::DataStructures::Column) - - # test the single finders - assert @columns.find_by_name(:a).name == :a - assert @columns[:b].name == :b - - # test the collection finders - found = @columns.find_by_names(:a, :b) - assert found.any? {|c| c.name == :a} - assert found.any? {|c| c.name == :b} - end - - def test_each - @columns.each do |column| - assert [:a, :b].include?(column.name) - end - end - - def test_block_config - assert !@columns.include?(:d) - assert !@columns.include?(:c) - - @columns.configure do |config| - # test that we can use the config object - config << :d - # but test that we don't have to - add 'c' - end - - assert @columns.include?(:d) - assert @columns.include?(:c) - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/data_structures/error_message_test.rb b/vendor/plugins/active_scaffold/test/data_structures/error_message_test.rb deleted file mode 100644 index 1cd1fee..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/error_message_test.rb +++ /dev/null @@ -1,28 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ErrorMessageTest < Test::Unit::TestCase - def setup - @error = ActiveScaffold::DataStructures::ErrorMessage.new 'foo' - end - - def test_attributes - assert @error.public_attributes.has_key?(:error) - assert_equal 'foo', @error.public_attributes[:error] - end - - def test_xml - xml = Hash.from_xml(@error.to_xml) - assert xml.has_key?('errors') - assert xml['errors'].has_key?('error') - assert_equal 'foo', xml['errors']['error'] - end - - def test_yaml - yml = nil - assert_nothing_raised do - yml = YAML.load(@error.to_yaml) - end - assert yml.has_key?(:error) - assert_equal 'foo', yml[:error] - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/data_structures/set_test.rb b/vendor/plugins/active_scaffold/test/data_structures/set_test.rb deleted file mode 100644 index e1c044d..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/set_test.rb +++ /dev/null @@ -1,86 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -# require 'test/model_stub' - -class SetTest < Test::Unit::TestCase - def setup - @items = ActiveScaffold::DataStructures::Set.new(:a, :b) - end - - def test_initialization - assert @items.include?(:a) - assert @items.include?(:b) - assert !@items.include?(:c) - end - - def test_exclude - # exclude with a symbol - assert @items.include?(:b) - @items.exclude :b - assert !@items.include?(:b) - - # exclude with a string - assert @items.include?(:a) - @items.exclude 'a' - assert !@items.include?(:a) - end - - def test_exclude_array - # exclude with a symbol - assert @items.include?(:b) - @items.exclude [:a, :b] - assert !@items.include?(:b) - assert !@items.include?(:a) - end - - def test_remove - assert @items.include?(:a) - @items.remove 'a' - assert !@items.include?(:a) - end - - def test_add - # try adding a simple column using a string - assert !@items.include?(:c) - @items.add 'c' - assert @items.include?(:c) - - # try adding a simple column using a symbol - assert !@items.include?(:d) - @items.add :d - assert @items.include?(:d) - - # test that << also adds - assert !@items.include?(:e) - @items << "e" - assert @items.include?(:e) - - # try adding an array of columns - assert !@items.include?(:f) - @items.add [:f, :g] - assert @items.include?(:f) - assert @items.include?(:g) - - end - - def test_length - assert_equal 2, @items.length - end - - def test_block_config - @items.configure do |config| - # we may use the config argument - config.add :c - # or we may not - exclude :b - end - - assert @items.include?(:c) - assert !@items.include?(:b) - end - - def test_include - assert @items.include?(:a) - assert @items.include?(:b) - assert !@items.include?(:d) - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/data_structures/sorting_test.rb b/vendor/plugins/active_scaffold/test/data_structures/sorting_test.rb deleted file mode 100644 index 9d622a4..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/sorting_test.rb +++ /dev/null @@ -1,126 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -# require 'test/model_stub' - -class SortingTest < Test::Unit::TestCase - def setup - @columns = ActiveScaffold::DataStructures::Columns.new(ModelStub, :a, :b, :c, :d) - @sorting = ActiveScaffold::DataStructures::Sorting.new(@columns) - end - - def test_add - @sorting.add :a, 'ASC' - # test adding by symbol - assert @sorting.sorts_on?(:a) - # test adding an uppercase string direction - assert_equal 'ASC', @sorting.direction_of(:a) - - @sorting.add 'b', :ASC - # test adding by string - assert @sorting.sorts_on?(:b) - # test adding an uppercase symbol direction - assert_equal 'ASC', @sorting.direction_of(:b) - - @sorting.add @columns[:c], 'desc' - # test adding by object - assert @sorting.sorts_on?(:c) - # test adding a lowercase string direction - assert_equal 'DESC', @sorting.direction_of(:c) - - @sorting << [:d, :desc] - # testing adding with the alias - assert @sorting.sorts_on?(:d) - assert_equal 'DESC', @sorting.direction_of(:d) - - @sorting.clear - - # test adding without a direction (test default) - @sorting.add :a - assert_equal 'ASC', @sorting.direction_of(:a) - - # test adding a bad column - assert_raises ArgumentError do - @sorting.add :foo - end - - # test adding a bad direction - assert_raises ArgumentError do - @sorting.add :b, :FOO - end - end - - def test_set - @sorting.add :a, 'ASC' - assert @sorting.sorts_on?(:a) - - @sorting.set :b, 'DESC' - assert @sorting.instance_variable_get('@clauses').size == 1 - assert !@sorting.sorts_on?(:a) - assert @sorting.sorts_on?(:b) - assert_equal 'DESC', @sorting.direction_of(:b) - end - - def test_sorts_on - @sorting.add :a - @sorting.add :b - - assert @sorting.sorts_on?(:a) - assert @sorting.sorts_on?(:b) - assert !@sorting.sorts_on?(:c) - end - - def test_direction_of - @sorting.add :a, 'ASC' - @sorting.add :b, :DESC - - assert_equal 'ASC', @sorting.direction_of(:a) - assert_equal 'DESC', @sorting.direction_of(:b) - end - - def test_sorts_by_method - @columns[:a].sort_by :method => proc{0} - - #test pure method sorting: true - @sorting.add :a - assert @sorting.sorts_by_method? - - #test mixed sql/method sorting: raise error - assert_raise ArgumentError do - @sorting.add :b - end - - #test pure sql sorting: false - @sorting.clear - @sorting.add :b - assert !@sorting.sorts_by_method? - end - - def test_build_order_clause - assert @sorting.clause.nil? - - @sorting << [:a, 'desc'] - @sorting << [:b, 'asc'] - - assert_equal '"model_stubs"."a" DESC, "model_stubs"."b" ASC', @sorting.clause - end - - def test_set_default_sorting_with_simple_default_scope - model_stub_with_default_scope = ModelStub.clone - model_stub_with_default_scope.class_eval { default_scope :order => 'a' } - @sorting.set_default_sorting model_stub_with_default_scope - - assert @sorting.sorts_on?(:a) - assert_equal 'ASC', @sorting.direction_of(:a) - assert_nil @sorting.clause - end - - def test_set_default_sorting_with_complex_default_scope - model_stub_with_default_scope = ModelStub.clone - model_stub_with_default_scope.class_eval { default_scope :order => 'a DESC, players.last_name ASC' } - @sorting.set_default_sorting model_stub_with_default_scope - - assert @sorting.sorts_on?(:a) - assert_equal 'DESC', @sorting.direction_of(:a) - assert_equal 1, @sorting.instance_variable_get(:@clauses).size - assert_nil @sorting.clause - end -end diff --git a/vendor/plugins/active_scaffold/test/data_structures/standard_column_test.rb b/vendor/plugins/active_scaffold/test/data_structures/standard_column_test.rb deleted file mode 100644 index 22a919d..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/standard_column_test.rb +++ /dev/null @@ -1,24 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -# require 'test/model_stub' - -class StandardColumnTest < Test::Unit::TestCase - def setup - @standard_column = ActiveScaffold::DataStructures::Column.new(ModelStub.columns.first.name, ModelStub) - end - - def test_virtuality - assert @standard_column.column - assert !@standard_column.virtual? - end - - def test_sorting - hash = {:sql => '"model_stubs"."a"'} - assert @standard_column.sortable? - assert_equal hash, @standard_column.sort # check default - end - - def test_searching - assert @standard_column.searchable? - assert_equal '"model_stubs"."a"', @standard_column.search_sql # check default - end -end diff --git a/vendor/plugins/active_scaffold/test/data_structures/virtual_column_test.rb b/vendor/plugins/active_scaffold/test/data_structures/virtual_column_test.rb deleted file mode 100644 index 96607ce..0000000 --- a/vendor/plugins/active_scaffold/test/data_structures/virtual_column_test.rb +++ /dev/null @@ -1,23 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class VirtualColumnTest < Test::Unit::TestCase - def setup - @virtual_column = ActiveScaffold::DataStructures::Column.new(:fake, ModelStub) - end - - def test_virtuality - assert !@virtual_column.column - assert !@virtual_column.association - assert @virtual_column.virtual? - end - - def test_sorting - # right now, there's no intelligent sorting on virtual columns - assert !@virtual_column.sortable? - end - - def test_searching - # right now, there's no intelligent searching on virtual columns - assert !@virtual_column.searchable? - end -end diff --git a/vendor/plugins/active_scaffold/test/extensions/active_record_test.rb b/vendor/plugins/active_scaffold/test/extensions/active_record_test.rb deleted file mode 100644 index 6ad58b1..0000000 --- a/vendor/plugins/active_scaffold/test/extensions/active_record_test.rb +++ /dev/null @@ -1,45 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -#require 'test/model_stub' - -class ActiveRecordTest < Test::Unit::TestCase - def setup - @record = ModelStub.new - end - - def test_to_label - # without anything defined, it'll use the to_s method (e.g. #) - assert_match /^#<[a-z]+:0x[0-9a-f]+>$/i, @record.to_label - - class << @record - def to_s - 'to_s' - end - end - - assert_equal 'to_s', @record.to_label - - class << @record - def title - 'title' - end - end - - assert_equal 'title', @record.to_label - - class << @record - def label - 'label' - end - end - - assert_equal 'label', @record.to_label - - class << @record - def name - 'name' - end - end - - assert_equal 'name', @record.to_label - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/extensions/array_test.rb b/vendor/plugins/active_scaffold/test/extensions/array_test.rb deleted file mode 100644 index 3976fc2..0000000 --- a/vendor/plugins/active_scaffold/test/extensions/array_test.rb +++ /dev/null @@ -1,12 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ArrayTest < Test::Unit::TestCase - def test_after - @sequence = ['a', 'b', 'c'] - - assert_equal 'b', @sequence.after('a') - assert_equal 'c', @sequence.after('b') - assert_equal 'a', @sequence.after('c') - assert_equal nil, @sequence.after('d') - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/helpers/form_column_helpers_test.rb b/vendor/plugins/active_scaffold/test/helpers/form_column_helpers_test.rb deleted file mode 100644 index c7ed79a..0000000 --- a/vendor/plugins/active_scaffold/test/helpers/form_column_helpers_test.rb +++ /dev/null @@ -1,31 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class FormColumnHelpersTest < ActionView::TestCase - include ActiveScaffold::Helpers::FormColumnHelpers - - def setup - @column = ActiveScaffold::DataStructures::Column.new(:a, ModelStub) - @record = stub(:a => nil) - end - - def test_choices_for_select_form_ui_for_simple_column - @column.options[:options] = [:value_1, :value_2, :value_3] - assert_dom_equal '', active_scaffold_input_select(@column, {}) - - @column.options[:options] = %w(value_1 value_2 value_3) - assert_dom_equal '', active_scaffold_input_select(@column, {}) - - @column.options[:options] = [%w(text_1 value_1), %w(text_2 value_2), %w(text_3 value_3)] - assert_dom_equal '', active_scaffold_input_select(@column, {}) - - @column.options[:options] = [[:text_1, :value_1], [:text_2, :value_2], [:text_3, :value_3]] - assert_dom_equal '', active_scaffold_input_select(@column, {}) - end - - def test_options_for_select_form_ui_for_simple_column - @column.options = {:include_blank => 'None', :selected => 'value_2', :disabled => %w(value_1 value_3)} - @column.options[:options] = %w(value_1 value_2 value_3) - @column.options[:html_options] = {:class => 'big'} - assert_dom_equal '', active_scaffold_input_select(@column, {}) - end -end diff --git a/vendor/plugins/active_scaffold/test/helpers/list_column_helpers_test.rb b/vendor/plugins/active_scaffold/test/helpers/list_column_helpers_test.rb deleted file mode 100644 index 38f4c78..0000000 --- a/vendor/plugins/active_scaffold/test/helpers/list_column_helpers_test.rb +++ /dev/null @@ -1,42 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ListColumnHelpersTest < ActionView::TestCase - include ActiveScaffold::Helpers::ListColumnHelpers - include ActiveScaffold::Helpers::ViewHelpers - - def setup - @column = ActiveScaffold::DataStructures::Column.new(:a, ModelStub) - @column.form_ui = :select - @record = stub(:a => 'value_2') - @config = stub(:list => stub(:empty_field_text => '-', :association_join_text => ', ')) - @association_column = ActiveScaffold::DataStructures::Column.new(:b, ModelStub) - @association_column.stubs(:association).returns(stub(:macro => :has_many)) - end - - def test_options_for_select_list_ui_for_simple_column - @column.options[:options] = [:value_1, :value_2, :value_3] - assert_equal 'Value 2', format_column_value(@record, @column) - - @column.options[:options] = %w(value_1 value_2 value_3) - assert_equal 'value_2', format_column_value(@record, @column) - - @column.options[:options] = [%w(text_1 value_1), %w(text_2 value_2), %w(text_3 value_3)] - assert_equal 'text_2', format_column_value(@record, @column) - - @column.options[:options] = [[:text_1, :value_1], [:text_2, :value_2], [:text_3, :value_3]] - assert_equal 'Text 2', format_column_value(@record, @column) - end - - def test_association_join_text - value = [1, 2, 3, 4].map(&:to_s) - value.each {|v| v.stubs(:to_label).returns(v)} - assert_equal '1, 2, 3, … (4)', format_association_value(value, @association_column, value.size) - @config.list.stubs(:association_join_text => ',
') - assert_equal '1,
2,
3,
… (4)', format_association_value(value, @association_column, value.size) - end - - private - def active_scaffold_config - @config - end -end diff --git a/vendor/plugins/active_scaffold/test/helpers/pagination_helpers_test.rb b/vendor/plugins/active_scaffold/test/helpers/pagination_helpers_test.rb deleted file mode 100644 index bdf50c0..0000000 --- a/vendor/plugins/active_scaffold/test/helpers/pagination_helpers_test.rb +++ /dev/null @@ -1,59 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class PaginationHelpersTest < Test::Unit::TestCase - include ActiveScaffold::Helpers::PaginationHelpers - - def test_links - self.stubs(:pagination_ajax_link).returns('l') - - assert_equal '1', links(1, 1) - assert_equal '1 l', links(1, 2) - assert_equal '1 l l', links(1, 3) - assert_equal '1 l l l', links(1, 4) - assert_equal '1 l l .. l', links(1, 5) - assert_equal '1 l l .. l', links(1, 6) - - assert_equal 'l 2 l l .. l', links(2, 10) - assert_equal 'l l 3 l l .. l', links(3, 10) - assert_equal 'l l l 4 l l .. l', links(4, 10) - assert_equal 'l .. l l 5 l l .. l', links(5, 10) - assert_equal 'l .. l l 6 l l .. l', links(6, 10) - - assert_equal '1 l l l l', links(1, 5, 3) - assert_equal '1 l l l .. l', links(1, 6, 3) - assert_equal 'l l l l 5 l l l .. l', links(5, 10, 3) - assert_equal 'l .. l l l 6 l l l l', links(6, 10, 3) - assert_equal 'l .. l l l 6 l l l .. l', links(6, 20, 3) - end - - def test_links_with_infinite_pagination - self.stubs(:pagination_ajax_link).returns('l') - - assert_equal '1 l l .. l .. l', links(1, nil, 2, true) - assert_equal 'l 2 l l .. l .. l', links(2, nil, 2, true) - assert_equal 'l l 3 l l .. l .. l', links(3, nil, 2, true) - assert_equal 'l l l 4 l l .. l .. l', links(4, nil, 2, true) - assert_equal 'l .. l l 5 l l .. l .. l', links(5, nil, 2, true) - - assert_equal 'l .. l l 20 l l .. l .. l', links(20, nil, 2, true) - assert_equal 'l .. l l 21 l l .. l .. l', links(21, nil, 2, true) - assert_equal 'l l .. l l 22 l l .. l .. l', links(22, nil, 2, true) - assert_equal 'l .. l .. l l 23 l l .. l .. l', links(23, nil, 2, true) - - assert_equal 'l .. l .. l l 100 l l .. l .. l', links(100, nil, 2, true) - assert_equal 'l .. l .. l l 101 l l .. l .. l', links(101, nil, 2, true) - assert_equal 'l l .. l .. l l 102 l l .. l .. l', links(102, nil, 2, true) - assert_equal 'l .. l .. l .. l l 103 l l .. l .. l', links(103, nil, 2, true) - end - - private - def links(current, last_page, window_size = 2, infinite = false) - paginator = stub(:last => last_page = stub(:number => last_page), :infinite? => infinite) - current_page = stub(:number => current, :pager => paginator) - pagination_ajax_links(current_page, {}, window_size) - end - - def content_tag(tag, text) - text - end -end diff --git a/vendor/plugins/active_scaffold/test/misc/active_record_permissions_test.rb b/vendor/plugins/active_scaffold/test/misc/active_record_permissions_test.rb deleted file mode 100644 index 375c2e0..0000000 --- a/vendor/plugins/active_scaffold/test/misc/active_record_permissions_test.rb +++ /dev/null @@ -1,154 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class PermissionModel < ActiveRecord::Base - def self.columns; [] end - - def authorized_for_read?; true; end - def authorized_for_update?; false; end - #def authorized_for_create?; end - - def a1_authorized?; true; end - def a2_authorized?; false; end - #def a3_authorized?; end - - def b1_authorized?; true; end - def b2_authorized?; false; end - #def b3_authorized?; end - - def c1_authorized?; true; end - def c2_authorized?; false; end - #def c3_authorized?; end - - def a3_authorized_for_create?; true; end - def b3_authorized_for_create?; false; end - #def c3_authorized_for_create?; end - def a2_authorized_for_create?; true; end - def b2_authorized_for_create?; false; end - #def c2_authorized_for_create?; end - def a1_authorized_for_create?; true; end - def b1_authorized_for_create?; false; end - #def c1_authorized_for_create?; end - - def a3_authorized_for_read?; true; end - def b3_authorized_for_read?; false; end - #def c3_authorized_for_read?; end - def a2_authorized_for_read?; true; end - def b2_authorized_for_read?; false; end - #def c2_authorized_for_read?; end - def a1_authorized_for_read?; true; end - def b1_authorized_for_read?; false; end - #def c1_authorized_for_read?; end - - def a3_authorized_for_update?; true; end - def b3_authorized_for_update?; false; end - #def c3_authorized_for_update?; end - def a2_authorized_for_update?; true; end - def b2_authorized_for_update?; false; end - #def c2_authorized_for_update?; end - def a1_authorized_for_update?; true; end - def b1_authorized_for_update?; false; end - #def c1_authorized_for_update?; end -end - -class ActiveRecordPermissionsTest < Test::Unit::TestCase - def setup - @model = PermissionModel.new - end - - # Combinations Legend: - # columns are: crud_type method, column method, crud_type/column method - # symbols are: is (a)bsent, returns (f)alse, returns (t)rue, or n/a (_) - def test_method_combinations_with_default_true - ActiveRecordPermissions.default_permission = true - - pass(@model.authorized_for?(:column => :a3), '_a_') - fail(@model.authorized_for?(:column => :a2), '_f_') - pass(@model.authorized_for?(:column => :a1), '_t_') - - pass(@model.authorized_for?(:crud_type => :create), 'a__') - fail(@model.authorized_for?(:crud_type => :update), 'f__') - pass(@model.authorized_for?(:crud_type => :read), 't__') - - pass(@model.authorized_for?(:crud_type => :create, :column => :c3), 'aaa') - fail(@model.authorized_for?(:crud_type => :create, :column => :b3), 'aaf') - pass(@model.authorized_for?(:crud_type => :create, :column => :a3), 'aat') - fail(@model.authorized_for?(:crud_type => :create, :column => :c2), 'afa') - fail(@model.authorized_for?(:crud_type => :create, :column => :b2), 'aff') - pass(@model.authorized_for?(:crud_type => :create, :column => :a2), 'aft') - pass(@model.authorized_for?(:crud_type => :create, :column => :c1), 'ata') - fail(@model.authorized_for?(:crud_type => :create, :column => :b1), 'atf') - pass(@model.authorized_for?(:crud_type => :create, :column => :a1), 'att') - - fail(@model.authorized_for?(:crud_type => :update, :column => :c3), 'faa') - fail(@model.authorized_for?(:crud_type => :update, :column => :b3), 'faf') - pass(@model.authorized_for?(:crud_type => :update, :column => :a3), 'fat') - fail(@model.authorized_for?(:crud_type => :update, :column => :c2), 'ffa') - fail(@model.authorized_for?(:crud_type => :update, :column => :b2), 'fff') - pass(@model.authorized_for?(:crud_type => :update, :column => :a2), 'fft') - fail(@model.authorized_for?(:crud_type => :update, :column => :c1), 'fta') - fail(@model.authorized_for?(:crud_type => :update, :column => :b1), 'ftf') - pass(@model.authorized_for?(:crud_type => :update, :column => :a1), 'ftt') - - pass(@model.authorized_for?(:crud_type => :read, :column => :c3), 'taa') - fail(@model.authorized_for?(:crud_type => :read, :column => :b3), 'taf') - pass(@model.authorized_for?(:crud_type => :read, :column => :a3), 'tat') - fail(@model.authorized_for?(:crud_type => :read, :column => :c2), 'tfa') - fail(@model.authorized_for?(:crud_type => :read, :column => :b2), 'tff') - pass(@model.authorized_for?(:crud_type => :read, :column => :a2), 'tft') - pass(@model.authorized_for?(:crud_type => :read, :column => :c1), 'tta') - fail(@model.authorized_for?(:crud_type => :read, :column => :b1), 'ttf') - pass(@model.authorized_for?(:crud_type => :read, :column => :a1), 'ttt') - end - - def test_method_combinations_with_default_false - ActiveRecordPermissions.default_permission = false - - fail(@model.authorized_for?(:column => :a3), '_a_') - fail(@model.authorized_for?(:column => :a2), '_f_') - pass(@model.authorized_for?(:column => :a1), '_t_') - - fail(@model.authorized_for?(:crud_type => :create), 'a__') - fail(@model.authorized_for?(:crud_type => :update), 'f__') - pass(@model.authorized_for?(:crud_type => :read), 't__') - - fail(@model.authorized_for?(:crud_type => :create, :column => :c3), 'aaa') - fail(@model.authorized_for?(:crud_type => :create, :column => :b3), 'aaf') - pass(@model.authorized_for?(:crud_type => :create, :column => :a3), 'aat') - fail(@model.authorized_for?(:crud_type => :create, :column => :c2), 'afa') - fail(@model.authorized_for?(:crud_type => :create, :column => :b2), 'aff') - pass(@model.authorized_for?(:crud_type => :create, :column => :a2), 'aft') - pass(@model.authorized_for?(:crud_type => :create, :column => :c1), 'ata') - fail(@model.authorized_for?(:crud_type => :create, :column => :b1), 'atf') - pass(@model.authorized_for?(:crud_type => :create, :column => :a1), 'att') - - fail(@model.authorized_for?(:crud_type => :update, :column => :c3), 'faa') - fail(@model.authorized_for?(:crud_type => :update, :column => :b3), 'faf') - pass(@model.authorized_for?(:crud_type => :update, :column => :a3), 'fat') - fail(@model.authorized_for?(:crud_type => :update, :column => :c2), 'ffa') - fail(@model.authorized_for?(:crud_type => :update, :column => :b2), 'fff') - pass(@model.authorized_for?(:crud_type => :update, :column => :a2), 'fft') - fail(@model.authorized_for?(:crud_type => :update, :column => :c1), 'fta') - fail(@model.authorized_for?(:crud_type => :update, :column => :b1), 'ftf') - pass(@model.authorized_for?(:crud_type => :update, :column => :a1), 'ftt') - - pass(@model.authorized_for?(:crud_type => :read, :column => :c3), 'taa') - fail(@model.authorized_for?(:crud_type => :read, :column => :b3), 'taf') - pass(@model.authorized_for?(:crud_type => :read, :column => :a3), 'tat') - fail(@model.authorized_for?(:crud_type => :read, :column => :c2), 'tfa') - fail(@model.authorized_for?(:crud_type => :read, :column => :b2), 'tff') - pass(@model.authorized_for?(:crud_type => :read, :column => :a2), 'tft') - pass(@model.authorized_for?(:crud_type => :read, :column => :c1), 'tta') - fail(@model.authorized_for?(:crud_type => :read, :column => :b1), 'ttf') - pass(@model.authorized_for?(:crud_type => :read, :column => :a1), 'ttt') - end - - private - - def pass(value, message = nil) - assert value, "#{message} should pass" - end - - def fail(value, message = nil) - assert !value, "#{message} should fail" - end -end diff --git a/vendor/plugins/active_scaffold/test/misc/attribute_params_test.rb b/vendor/plugins/active_scaffold/test/misc/attribute_params_test.rb deleted file mode 100644 index b956aea..0000000 --- a/vendor/plugins/active_scaffold/test/misc/attribute_params_test.rb +++ /dev/null @@ -1,146 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class NumberModel < ActiveRecord::Base - abstract_class = true - def self.columns - @columns ||= [ActiveRecord::ConnectionAdapters::Column.new('number', '', 'double(10,2)')] - end -end - -class AttributeParamsTest < Test::Unit::TestCase - include ActiveScaffold::AttributeParams - - def setup - I18n.backend.store_translations :en, :number => {:format => { - :delimiter => ',', - :separator => '.' - }} - I18n.backend.store_translations :es, :number => {:format => { - :delimiter => '.', - :separator => ',' - }} - I18n.backend.store_translations :ru, :number => {:currency => { - :format => { - :separator => ',', - :delimiter => '' - } - }} - - @config = config_for('number_model') - class << @config.list.columns - include ActiveScaffold::DataStructures::ActionColumns::AfterConfiguration - end - @config.list.columns.set_columns @config.columns - end - - def teardown - I18n.locale = :en - end - - def test_english_format_with_decimal_separator_using_english_language - I18n.locale = :en - assert_equal 0.1, convert_number('.1') - assert_equal 0.1, convert_number('.100') - assert_equal 0.1, convert_number('0.1') - assert_equal 0.345, convert_number('0.345') - assert_equal 0.345, convert_number('+0.345') - assert_equal -0.345, convert_number('-0.345') - assert_equal 9.345, convert_number('9.345') - assert_equal 9.1, convert_number('9.1') - assert_equal 90.1, convert_number('90.1') - end - - def test_english_format_with_thousand_delimiter_using_english_language - I18n.locale = :en - assert_equal 1000, convert_number('1,000') - assert_equal 1000, convert_number('+1,000') - assert_equal -1000, convert_number('-1,000') - assert_equal 1000000, convert_number('1,000,000') - end - - def test_english_format_with_separator_and_delimiter_using_english_language - I18n.locale = :en - assert_equal 1234.1, convert_number('1,234.1') - assert_equal 1234.1, convert_number('1,234.100') - assert_equal 1234.345, convert_number('+1,234.345') - assert_equal -1234.345, convert_number('-1,234.345') - assert_equal 1234000.1, convert_number('1,234,000.100') - end - - def test_english_format_with_decimal_separator_using_spanish_language - I18n.locale = :es - assert_equal 0.1, convert_number('.1') - assert_equal 0.1, convert_number('0.1') - assert_equal 0.12, convert_number('+0.12') - assert_equal -0.12, convert_number('-0.12') - assert_equal 9.1, convert_number('9.1') - assert_equal 90.1, convert_number('90.1') - end - - def test_spanish_format_with_decimal_separator_using_spanish_language - I18n.locale = :es - assert_equal 0.1, convert_number(',1') - assert_equal 0.1, convert_number(',100') - assert_equal 0.1, convert_number('0,1') - assert_equal 0.345, convert_number('0,345') - assert_equal 0.345, convert_number('+0,345') - assert_equal -0.345, convert_number('-0,345') - assert_equal 9.1, convert_number('9,1') - assert_equal 90.1, convert_number('90,1') - assert_equal 9.1, convert_number('9,100') - end - - def test_spanish_format_with_thousand_delimiter_using_spanish_language - I18n.locale = :es - assert_equal 1000, convert_number('1.000') - assert_equal 1000, convert_number('+1.000') - assert_equal -1000, convert_number('-1.000') - assert_equal 1000000, convert_number('1.000.000') - end - - def test_spanish_format_with_separator_and_decimal_using_spanish_language - I18n.locale = :es - assert_equal 1230.1, convert_number('1.230,1') - assert_equal 1230.1, convert_number('1.230,100') - assert_equal 1234.345, convert_number('+1.234,345') - assert_equal -1234.345, convert_number('-1.234,345') - assert_equal 1234000.1, convert_number('1.234.000,100') - end - - def test_english_currency_format_with_decimal_separator_using_russian_language - I18n.locale = :ru - assert_equal 0.1, convert_number('.1', :currency) - assert_equal 0.1, convert_number('0.1', :currency) - assert_equal 0.12, convert_number('+0.12', :currency) - assert_equal -0.12, convert_number('-0.12', :currency) - assert_equal 9.1, convert_number('9.1', :currency) - assert_equal 90.1, convert_number('90.1', :currency) - end - - def test_russian_currency_format_with_decimal_separator_using_russian_language - I18n.locale = :ru - assert_equal 0.1, convert_number(',1', :currency) - assert_equal 0.1, convert_number(',100', :currency) - assert_equal 0.1, convert_number('0,1', :currency) - assert_equal 0.345, convert_number('0,345', :currency) - assert_equal 0.345, convert_number('+0,345', :currency) - assert_equal -0.345, convert_number('-0,345', :currency) - assert_equal 9.1, convert_number('9,1', :currency) - assert_equal 90.1, convert_number('90,1', :currency) - assert_equal 9.1, convert_number('9,100', :currency) - end - - def test_english_format_with_decimal_separator_with_no_localized_format - I18n.locale = :ru - assert_equal 0.1, convert_number('.1') - assert_equal 0.1, convert_number('0.1') - end - - private - def convert_number(value, format = nil) - record = NumberModel.new - @config.columns[:number].options[:format] = format unless format.nil? - update_record_from_params(record, @config.list.columns, HashWithIndifferentAccess.new({:number => value})) - record.number - end -end diff --git a/vendor/plugins/active_scaffold/test/misc/configurable_test.rb b/vendor/plugins/active_scaffold/test/misc/configurable_test.rb deleted file mode 100644 index e68e73f..0000000 --- a/vendor/plugins/active_scaffold/test/misc/configurable_test.rb +++ /dev/null @@ -1,96 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class ConfigurableClass - FOO = 'bar' - def foo; FOO end - def self.foo; FOO end -end - - -class ConfigurableTest < Test::Unit::TestCase - ## - ## constants and methods for tests to check against - ## - def hello; 'world' end - HELLO = 'world' - - def test_instance_configuration - ConfigurableClass.send :include, ActiveScaffold::Configurable - - configurable_class = ConfigurableClass.new - - ## - ## sanity checks - ## - # make sure the configure method is available - assert ConfigurableClass.respond_to?(:configure) - # make sure real functions still work - assert_equal 'bar', configurable_class.foo - # make sure other functions still don't work - assert_raise NoMethodError do - configurable_class.i_do_not_exist - end - - ## - ## test normal block behaviors - ## - # functions - assert_equal hello, configurable_class.configure {hello} - # variables - assert_equal configurable_class, configurable_class.configure {configurable_class} - # constants - assert_equal ConfigurableTest::HELLO, configurable_class.configure {ConfigurableTest::HELLO} - - ## - ## test extra "localized" block behavior - ## - # functions - assert_equal configurable_class.foo, configurable_class.configure {foo} - # constants - not working -# assert_equal configurable_class.FOO, configurable_class.configure {FOO} - - end - - def test_class_configuration - ConfigurableClass.send :extend, ActiveScaffold::Configurable - - ## - ## sanity checks - ## - # make sure the configure method is available - assert ConfigurableClass.respond_to?(:configure) - # make sure real functions still work - assert_equal 'bar', ConfigurableClass.foo - # make sure other functions still don't work - assert_raise NoMethodError do - ConfigurableClass.i_do_not_exist - end - - ## - ## test normal block behaviors - ## - # functions - assert_equal hello, ConfigurableClass.configure {hello} - # variables - assert_equal ConfigurableClass, ConfigurableClass.configure {ConfigurableClass} - # constants - assert_equal ConfigurableTest::HELLO, ConfigurableClass.configure {ConfigurableTest::HELLO} - - ## - ## test extra "localized" block behavior - ## - # functions - assert_equal ConfigurableClass.foo, ConfigurableClass.configure {foo} - # constants - not working -# assert_equal ConfigurableClass.FOO, ConfigurableClass.configure {FOO} - end - - def test_arity - ConfigurableClass.send :extend, ActiveScaffold::Configurable - - # this is the main style - assert_equal 'foo', ConfigurableClass.configure {'foo'} - # but we want to let people accept the configurable class as the first argument, too - assert_equal 'bar', ConfigurableClass.configure {|a| a.foo} - end -end \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/misc/constraints_test.rb b/vendor/plugins/active_scaffold/test/misc/constraints_test.rb deleted file mode 100644 index 3737e04..0000000 --- a/vendor/plugins/active_scaffold/test/misc/constraints_test.rb +++ /dev/null @@ -1,193 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -module ModelStubs - class ModelStub < ActiveRecord::Base - abstract_class = true - def self.columns; [ActiveRecord::ConnectionAdapters::Column.new('foo', '')] end - def self.table_name - to_s.split('::').last.underscore.pluralize - end - self.store_full_sti_class = false - end - - ## - ## Standard associations - ## - - class Address < ModelStub - belongs_to :addressable, :polymorphic => true - end - - class User < ModelStub - has_and_belongs_to_many :roles - has_one :subscription - has_one :address, :as => :addressable - end - - class Service < ModelStub - has_many :subscriptions - has_many :users, :through => :subscriptions - end - - class Subscription < ModelStub - belongs_to :service - belongs_to :user - end - - class Role < ModelStub - has_and_belongs_to_many :users - end - - ## - ## These versions of the associations require extra configuration to work properly - ## - - class OtherAddress < ModelStub - set_table_name 'addresses' - belongs_to :other_addressable, :polymorphic => true - end - - class OtherUser < ModelStub - set_table_name 'users' - has_and_belongs_to_many :other_roles, :class_name => 'ModelStubs::OtherRole', :foreign_key => 'user_id', :association_foreign_key => 'role_id', :join_table => 'roles_users' - has_one :other_subscription, :class_name => 'ModelStubs::OtherSubscription', :foreign_key => 'user_id' - has_one :other_address, :as => :other_addressable, :class_name => 'ModelStubs::OtherAddress', :foreign_key => 'addressable_id' - end - - class OtherService < ModelStub - set_table_name 'services' - has_many :other_subscriptions, :class_name => 'ModelStubs::OtherSubscription', :foreign_key => 'service_id' - has_many :other_users, :through => :other_subscriptions # :class_name and :foreign_key are ignored for :through - end - - class OtherSubscription < ModelStub - set_table_name 'subscriptions' - belongs_to :other_service, :class_name => 'ModelStubs::OtherService', :foreign_key => 'service_id' - belongs_to :other_user, :class_name => 'ModelStubs::OtherUser', :foreign_key => 'user_id' - end - - class OtherRole < ModelStub - set_table_name 'roles' - has_and_belongs_to_many :other_users, :class_name => 'ModelStubs::OtherUser', :foreign_key => 'role_id', :association_foreign_key => 'user_id', :join_table => 'roles_users' - end - - class PrimaryKeyUser < ModelStub - has_many :locations, :class_name => 'PrimaryKeyLocation', :foreign_key => :username, :primary_key => :name - end - - class PrimaryKeyLocation < ModelStub - belongs_to :user, :class_name => 'PrimaryKeyUser', :foreign_key => :username, :primary_key => :name - end -end - -class ConstraintsTestObject - # stub out what the mixin expects to find ... - def self.before_filter(*args); end - attr_accessor :active_scaffold_includes - attr_accessor :active_scaffold_habtm_joins - attr_accessor :active_scaffold_config - attr_accessor :params - def merge_conditions(old, new) - [old, new].compact.flatten - end - - # mixin the constraint code - include ActiveScaffold::Constraints - - # make the constraints read-write, instead of coming from the session - attr_accessor :active_scaffold_constraints - - def initialize - @active_scaffold_includes = [] - @active_scaffold_habtm_joins = [] - @params = {} - end -end - -class ConstraintsTest < Test::Unit::TestCase - def setup - @test_object = ConstraintsTestObject.new - end - - def test_constraint_conditions_for_default_associations - @test_object.active_scaffold_config = config_for('user') - # has_one (vs belongs_to) - assert_constraint_condition({:subscription => 5}, ['subscriptions.id = ?', 5], 'find the user with subscription #5') - # habtm (vs habtm) - assert_constraint_condition({:roles => 4}, ['roles_users.role_id = ?', 4], 'find all users with role #4') - # has_one (vs polymorphic) - assert_constraint_condition({:address => 11}, ['addresses.id = ?', 11], 'find the user with address #11') - # reverse of a has_many :through - assert_constraint_condition({:subscription => {:service => 5}}, ['services.id = ?', 5], 'find all users subscribed to service #5') - assert(@test_object.active_scaffold_includes.include?({:subscription => :service}), 'multi-level association include') - - @test_object.active_scaffold_config = config_for('subscription') - # belongs_to (vs has_one) - assert_constraint_condition({:user => 2}, ['subscriptions.user_id = ?', 2], 'find the subscription for user #2') - # belongs_to (vs has_many) - assert_constraint_condition({:service => 1}, ['subscriptions.service_id = ?', 1], 'find all subscriptions for service #1') - - @test_object.active_scaffold_config = config_for('service') - # has_many (vs belongs_to) - assert_constraint_condition({:subscriptions => 10}, ['subscriptions.id = ?', 10], 'find the service with subscription #10') - # has_many :through (through has_many) - assert_constraint_condition({:users => 7}, ['users.id = ?', 7], 'find the service with user #7') - - @test_object.active_scaffold_config = config_for('address') - # belongs_to :polymorphic => true - @test_object.params[:parent_model] = 'User' - assert_constraint_condition({:addressable => 14}, ['addresses.addressable_id = ?', 14, 'addresses.addressable_type = ?', 'User'], 'find all addresses for user #14') - end - - def test_constraint_conditions_for_configured_associations - @test_object.active_scaffold_config = config_for('other_user') - # has_one (vs belongs_to) - assert_constraint_condition({:other_subscription => 5}, ['subscriptions.id = ?', 5], 'find the user with subscription #5') - # habtm (vs habtm) - assert_constraint_condition({:other_roles => 4}, ['roles_users.role_id = ?', 4], 'find all users with role #4') - # has_one (vs polymorphic) - assert_constraint_condition({:other_address => 11}, ['addresses.id = ?', 11], 'find the user with address #11') - # reverse of a has_many :through - assert_constraint_condition({:other_subscription => {:other_service => 5}}, ['services.id = ?', 5], 'find all users subscribed to service #5') - - @test_object.active_scaffold_config = config_for('other_subscription') - # belongs_to (vs has_one) - assert_constraint_condition({:other_user => 2}, ['subscriptions.user_id = ?', 2], 'find the subscription for user #2') - # belongs_to (vs has_many) - assert_constraint_condition({:other_service => 1}, ['subscriptions.service_id = ?', 1], 'find all subscriptions for service #1') - - @test_object.active_scaffold_config = config_for('other_service') - # has_many (vs belongs_to) - assert_constraint_condition({:other_subscriptions => 10}, ['subscriptions.id = ?', 10], 'find the service with subscription #10') - # has_many :through (through has_many) - assert_constraint_condition({:other_users => 7}, ['users.id = ?', 7], 'find the service with user #7') - - @test_object.active_scaffold_config = config_for('other_address') - # belongs_to :polymorphic => true - @test_object.params[:parent_model] = 'OtherUser' - assert_constraint_condition({:other_addressable => 14}, ['addresses.other_addressable_id = ?', 14, 'addresses.other_addressable_type = ?', 'OtherUser'], 'find all addresses for user #14') - end - - def test_constraint_conditions_for_normal_attributes - @test_object.active_scaffold_config = config_for('user') - assert_constraint_condition({'foo' => 'bar'}, ['"users"."foo" = ?', 'bar'], 'normal column-based constraint') - end - - def test_constraint_conditions_for_associations_with_primary_key_option - @test_object.active_scaffold_config = config_for('primary_key_location') - #user = ModelStubs::PrimaryKeyUser.new(:id => 1, :name => 'User Name') - ModelStubs::PrimaryKeyUser.expects(:find).with(1).returns(stub(:id => 1, :name => 'User Name')) - assert_constraint_condition({'user' => 1}, ['primary_key_locations.username = ?', 'User Name'], 'association with primary-key constraint') - end - - protected - - def assert_constraint_condition(constraint, condition, message = nil) - @test_object.active_scaffold_constraints = constraint - assert_equal condition, @test_object.send(:conditions_from_constraints), message - end - - def config_for(klass, namespace = nil) - super(klass, "model_stubs/") - end -end diff --git a/vendor/plugins/active_scaffold/test/misc/finder_test.rb b/vendor/plugins/active_scaffold/test/misc/finder_test.rb deleted file mode 100644 index cc57c38..0000000 --- a/vendor/plugins/active_scaffold/test/misc/finder_test.rb +++ /dev/null @@ -1,92 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') -# require 'test/model_stub' - -class ClassWithFinder - include ActiveScaffold::Finder - def conditions_for_collection; end - def conditions_from_params; end - def conditions_from_constraints; end - def joins_for_collection; end - def custom_finder_options - {} - end - def beginning_of_chain - active_scaffold_config.model - end -end - -class FinderTest < Test::Unit::TestCase - def setup - @klass = ClassWithFinder.new - @klass.stubs(:active_scaffold_config).returns(mock { stubs(:model).returns(ModelStub) }) - @klass.stubs(:active_scaffold_session_storage).returns({}) - end - - def test_create_conditions_for_columns - columns = [ - ActiveScaffold::DataStructures::Column.new(:a, ModelStub), - ActiveScaffold::DataStructures::Column.new(:b, ModelStub) - ] - tokens = [ - 'foo', - 'bar' - ] - - expected_conditions = [ - '("model_stubs"."a" LIKE ? OR "model_stubs"."b" LIKE ?) AND ("model_stubs"."a" LIKE ? OR "model_stubs"."b" LIKE ?)', - '%foo%', '%foo%', '%bar%', '%bar%' - ] - assert_equal expected_conditions, ClassWithFinder.create_conditions_for_columns(tokens, columns) - - expected_conditions = [ - '("model_stubs"."a" LIKE ? OR "model_stubs"."b" LIKE ?)', - '%foo%', '%foo%' - ] - assert_equal expected_conditions, ClassWithFinder.create_conditions_for_columns('foo', columns) - - assert_equal nil, ClassWithFinder.create_conditions_for_columns('foo', []) - end - - def test_method_sorting - column = ActiveScaffold::DataStructures::Column.new('a', ModelStub) - column.sort_by :method => proc{self} - - collection = [16000, 2853, 98765, 6188, 4] - assert_equal collection.sort, @klass.send(:sort_collection_by_column, collection, column, 'asc') - assert_equal collection.sort.reverse, @klass.send(:sort_collection_by_column, collection, column, 'desc') - - collection = ['a', nil, 'b'] - result = nil - assert_nothing_raised do - result = @klass.send(:sort_collection_by_column, collection, column, 'asc') - end - assert_equal [nil, 'a', 'b'], result - - column.sort_by :method => 'self' - collection = [3, 1, 2] - assert_equal collection.sort, @klass.send(:sort_collection_by_column, collection, column, 'asc') - end - - def test_count_with_group - @klass.expects(:custom_finder_options).returns({:group => :a}) - ModelStub.expects(:count).returns(ActiveSupport::OrderedHash['foo', 5]) - ModelStub.expects(:find).with(:all, has_entries(:limit => 20, :offset => 0)) - page = @klass.send :find_page, :per_page => 20, :pagination => true - page.items - - assert_kind_of Integer, page.pager.count - assert_equal 1, page.pager.count - assert_nothing_raised { page.pager.number_of_pages } - end - - def test_disabled_pagination - ModelStub.expects(:find).with(:all, Not(has_entries(:limit => 20, :offset => 0))) - page = @klass.send :find_page, :per_page => 20, :pagination => false - page.items - end - - def test_infinite_pagination - ModelStub.expects(:count).never - page = @klass.send :find_page, :pagination => :infinite - end -end diff --git a/vendor/plugins/active_scaffold/test/misc/lang_test.rb b/vendor/plugins/active_scaffold/test/misc/lang_test.rb deleted file mode 100644 index bcd0600..0000000 --- a/vendor/plugins/active_scaffold/test/misc/lang_test.rb +++ /dev/null @@ -1,11 +0,0 @@ -require File.join(File.dirname(__FILE__), '../test_helper.rb') - -class LocalizationTest < Test::Unit::TestCase - - def test_localization - assert_equal "Dutch", as_(:dutch) - assert_equal "dutch", as_('dutch') - I18n.backend.store_translations :en, :active_scaffold => {:create_model => 'Create %{model}'} - assert_equal "Create Test", as_(:create_model, :model => 'Test') - end -end diff --git a/vendor/plugins/active_scaffold/test/mock_app/.gitignore b/vendor/plugins/active_scaffold/test/mock_app/.gitignore deleted file mode 100644 index bd6dd4a..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -tmp/ -log/ \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/mock_app/app/controllers/application_controller.rb b/vendor/plugins/active_scaffold/test/mock_app/app/controllers/application_controller.rb deleted file mode 100644 index 6635a3f..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/app/controllers/application_controller.rb +++ /dev/null @@ -1,10 +0,0 @@ -# Filters added to this controller apply to all controllers in the application. -# Likewise, all the methods added will be available for all controllers. - -class ApplicationController < ActionController::Base - helper :all # include all helpers, all the time - protect_from_forgery # See ActionController::RequestForgeryProtection for details - - # Scrub sensitive parameters from your log - # filter_parameter_logging :password -end diff --git a/vendor/plugins/active_scaffold/test/mock_app/app/helpers/application_helper.rb b/vendor/plugins/active_scaffold/test/mock_app/app/helpers/application_helper.rb deleted file mode 100644 index 22a7940..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/app/helpers/application_helper.rb +++ /dev/null @@ -1,3 +0,0 @@ -# Methods added to this helper will be available to all templates in the application. -module ApplicationHelper -end diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/boot.rb b/vendor/plugins/active_scaffold/test/mock_app/config/boot.rb deleted file mode 100644 index 0ad0f78..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/boot.rb +++ /dev/null @@ -1,110 +0,0 @@ -# Don't change this file! -# Configure your app in config/environment.rb and config/environments/*.rb - -RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT) - -module Rails - class << self - def boot! - unless booted? - preinitialize - pick_boot.run - end - end - - def booted? - defined? Rails::Initializer - end - - def pick_boot - (vendor_rails? ? VendorBoot : GemBoot).new - end - - def vendor_rails? - File.exist?("#{RAILS_ROOT}/vendor/rails") - end - - def preinitialize - load(preinitializer_path) if File.exist?(preinitializer_path) - end - - def preinitializer_path - "#{RAILS_ROOT}/config/preinitializer.rb" - end - end - - class Boot - def run - load_initializer - Rails::Initializer.run(:set_load_path) - end - end - - class VendorBoot < Boot - def load_initializer - require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer" - Rails::Initializer.run(:install_gem_spec_stubs) - Rails::GemDependency.add_frozen_gem_path - end - end - - class GemBoot < Boot - def load_initializer - self.class.load_rubygems - load_rails_gem - require 'initializer' - end - - def load_rails_gem - if version = self.class.gem_version - gem 'rails', version - else - gem 'rails' - end - rescue Gem::LoadError => load_error - $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.) - exit 1 - end - - class << self - def rubygems_version - Gem::RubyGemsVersion rescue nil - end - - def gem_version - if defined? RAILS_GEM_VERSION - RAILS_GEM_VERSION - elsif ENV.include?('RAILS_GEM_VERSION') - ENV['RAILS_GEM_VERSION'] - else - parse_gem_version(read_environment_rb) - end - end - - def load_rubygems - require 'rubygems' - min_version = '1.3.1' - unless rubygems_version >= min_version - $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) - exit 1 - end - - rescue LoadError - $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org) - exit 1 - end - - def parse_gem_version(text) - $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/ - end - - private - def read_environment_rb - File.read("#{RAILS_ROOT}/config/environment.rb") - end - end - end -end - -# All that for this: -Rails.boot! diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/database.yml b/vendor/plugins/active_scaffold/test/mock_app/config/database.yml deleted file mode 100644 index 6d6e3da..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/database.yml +++ /dev/null @@ -1,16 +0,0 @@ -# SQLite version 3.x -# gem install sqlite3-ruby (not necessary on OS X Leopard) -development: - adapter: sqlite3 - database: db/development.sqlite3 - pool: 5 - timeout: 5000 - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - adapter: sqlite3 - database: db/test.sqlite3 - pool: 5 - timeout: 5000 diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/environment.rb b/vendor/plugins/active_scaffold/test/mock_app/config/environment.rb deleted file mode 100644 index 8602ac9..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/environment.rb +++ /dev/null @@ -1,43 +0,0 @@ -# Be sure to restart your server when you modify this file - -# Specifies gem version of Rails to use when vendor/rails is not present -#RAILS_GEM_VERSION = '2.3.3' unless defined? RAILS_GEM_VERSION - -# Bootstrap the Rails environment, frameworks, and default configuration -require File.join(File.dirname(__FILE__), 'boot') - -Rails::Initializer.run do |config| - # Settings in config/environments/* take precedence over those specified here. - # Application configuration should go into files in config/initializers - # -- all .rb files in that directory are automatically loaded. - - # Add additional load paths for your own custom dirs - # config.load_paths += %W( #{RAILS_ROOT}/extras ) - - # Specify gems that this application depends on and have them installed with rake gems:install - # config.gem "bj" - # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" - # config.gem "sqlite3-ruby", :lib => "sqlite3" - # config.gem "aws-s3", :lib => "aws/s3" - - # Only load the plugins named here, in the order given (default is alphabetical). - # :all can be used as a placeholder for all plugins not explicitly named - # config.plugins = [ :exception_notification, :ssl_requirement, :all ] - config.plugin_paths += %W(#{RAILS_ROOT}/../../..) - config.plugins = [:active_scaffold] - - # Skip frameworks you're not going to use. To use Rails without a database, - # you must remove the Active Record framework. - # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] - - # Activate observers that should always be running - # config.active_record.observers = :cacher, :garbage_collector, :forum_observer - - # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. - # Run "rake -D time" for a list of tasks for finding time zone names. - config.time_zone = 'UTC' - - # 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}')] - # config.i18n.default_locale = :de -end diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/environments/development.rb b/vendor/plugins/active_scaffold/test/mock_app/config/environments/development.rb deleted file mode 100644 index 85c9a60..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/environments/development.rb +++ /dev/null @@ -1,17 +0,0 @@ -# Settings specified here will take precedence over those in config/environment.rb - -# 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_view.debug_rjs = true -config.action_controller.perform_caching = false - -# Don't care if the mailer can't send -config.action_mailer.raise_delivery_errors = false \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/environments/production.rb b/vendor/plugins/active_scaffold/test/mock_app/config/environments/production.rb deleted file mode 100644 index 27119d2..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/environments/production.rb +++ /dev/null @@ -1,28 +0,0 @@ -# Settings specified here will take precedence over those in config/environment.rb - -# The production environment is meant for finished, "live" apps. -# Code is not reloaded between requests -config.cache_classes = true - -# Full error reports are disabled and caching is turned on -config.action_controller.consider_all_requests_local = false -config.action_controller.perform_caching = true -config.action_view.cache_template_loading = true - -# See everything in the log (default is :info) -# config.log_level = :debug - -# Use a different logger for distributed setups -# config.logger = SyslogLogger.new - -# Use a different cache store in production -# config.cache_store = :mem_cache_store - -# Enable serving of images, stylesheets, and javascripts from an asset server -# config.action_controller.asset_host = "http://assets.example.com" - -# Disable delivery errors, bad email addresses will be ignored -# config.action_mailer.raise_delivery_errors = false - -# Enable threaded mode -# config.threadsafe! \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/environments/test.rb b/vendor/plugins/active_scaffold/test/mock_app/config/environments/test.rb deleted file mode 100644 index d6f80a4..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/environments/test.rb +++ /dev/null @@ -1,28 +0,0 @@ -# Settings specified here will take precedence over those in config/environment.rb - -# The test environment is used exclusively to run your application's -# test suite. You never need to work with it otherwise. Remember that -# your test database is "scratch space" for the test suite and is wiped -# and recreated between test runs. Don't rely on the data there! -config.cache_classes = true - -# 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 -config.action_view.cache_template_loading = true - -# Disable request forgery protection in test environment -config.action_controller.allow_forgery_protection = false - -# Tell Action Mailer not to deliver emails to the real world. -# The :test delivery method accumulates sent emails in the -# ActionMailer::Base.deliveries array. -config.action_mailer.delivery_method = :test - -# Use SQL instead of Active Record's schema dumper when creating the test database. -# This is necessary if your schema can't be completely dumped by the schema dumper, -# like if you have constraints or database-specific column types -# config.active_record.schema_format = :sql \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/backtrace_silencers.rb b/vendor/plugins/active_scaffold/test/mock_app/config/initializers/backtrace_silencers.rb deleted file mode 100644 index c2169ed..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/backtrace_silencers.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. -# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } - -# You can also remove all the silencers if you're trying do debug a problem that might steem from framework code. -# Rails.backtrace_cleaner.remove_silencers! \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/inflections.rb b/vendor/plugins/active_scaffold/test/mock_app/config/initializers/inflections.rb deleted file mode 100644 index d531b8b..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/inflections.rb +++ /dev/null @@ -1,10 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Add new inflection rules using the following format -# (all these examples are active by default): -# ActiveSupport::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 diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/mime_types.rb b/vendor/plugins/active_scaffold/test/mock_app/config/initializers/mime_types.rb deleted file mode 100644 index 72aca7e..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/mime_types.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Add new mime types for use in respond_to blocks: -# Mime::Type.register "text/richtext", :rtf -# Mime::Type.register_alias "text/html", :iphone diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/new_rails_defaults.rb b/vendor/plugins/active_scaffold/test/mock_app/config/initializers/new_rails_defaults.rb deleted file mode 100644 index 8ec3186..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/new_rails_defaults.rb +++ /dev/null @@ -1,19 +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 - -# 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/vendor/plugins/active_scaffold/test/mock_app/config/initializers/session_store.rb b/vendor/plugins/active_scaffold/test/mock_app/config/initializers/session_store.rb deleted file mode 100644 index 1428988..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/initializers/session_store.rb +++ /dev/null @@ -1,15 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Your secret key for verifying cookie session data integrity. -# If you change this key, all old sessions will become invalid! -# Make sure the secret is at least 30 characters and all random, -# no regular words or you'll be exposed to dictionary attacks. -ActionController::Base.session = { - :key => '_mock_app_session', - :secret => 'ed0122432f6132fc5c99c928dc133a0863df7f24b0f2d53ce9dc2e9885a9b1f944d8ac6390333e2f1a72f902554bdaca75024fb23eb11a4548b0af4731439be2' -} - -# Use the database for sessions instead of the cookie-based default, -# which shouldn't be used to store highly confidential information -# (create the session table with "rake db:sessions:create") -# ActionController::Base.session_store = :active_record_store diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/locales/en.yml b/vendor/plugins/active_scaffold/test/mock_app/config/locales/en.yml deleted file mode 100644 index f265c06..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/locales/en.yml +++ /dev/null @@ -1,5 +0,0 @@ -# Sample localization file for English. Add more files in this directory for other locales. -# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. - -en: - hello: "Hello world" \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/mock_app/config/routes.rb b/vendor/plugins/active_scaffold/test/mock_app/config/routes.rb deleted file mode 100644 index ea14ce1..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/config/routes.rb +++ /dev/null @@ -1,43 +0,0 @@ -ActionController::Routing::Routes.draw do |map| - # The priority is based upon order of creation: first created -> highest priority. - - # Sample of regular route: - # map.connect 'products/:id', :controller => 'catalog', :action => 'view' - # Keep in mind you can assign values other than :controller and :action - - # Sample of named route: - # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase' - # This route can be invoked with purchase_url(:id => product.id) - - # Sample resource route (maps HTTP verbs to controller actions automatically): - # map.resources :products - - # Sample resource route with options: - # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get } - - # Sample resource route with sub-resources: - # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller - - # Sample resource route with more complex sub-resources - # map.resources :products do |products| - # products.resources :comments - # products.resources :sales, :collection => { :recent => :get } - # end - - # Sample resource route within a namespace: - # map.namespace :admin do |admin| - # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb) - # admin.resources :products - # end - - # You can have the root of your site routed with map.root -- just remember to delete public/index.html. - # map.root :controller => "welcome" - - # See how all your routes lay out with "rake routes" - - # Install the default routes as the lowest priority. - # Note: These default routes make all actions in every controller accessible via GET requests. You should - # consider removing or commenting them out if you're using named routes and resources. - map.connect ':controller/:action/:id' - map.connect ':controller/:action/:id.:format' -end diff --git a/vendor/plugins/active_scaffold/test/mock_app/db/test.sqlite3 b/vendor/plugins/active_scaffold/test/mock_app/db/test.sqlite3 deleted file mode 100644 index 1db515f..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/db/test.sqlite3 +++ /dev/null @@ -1 +0,0 @@ -S \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/blank.html b/vendor/plugins/active_scaffold/test/mock_app/public/blank.html deleted file mode 100644 index b60bcc6..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/blank.html +++ /dev/null @@ -1,33 +0,0 @@ - - - - - -

blank.html - Needed for Internet Explorer's hidden IFrame

- - diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/DO_NOT_EDIT b/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/DO_NOT_EDIT deleted file mode 100644 index c5e44a3..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/DO_NOT_EDIT +++ /dev/null @@ -1,2 +0,0 @@ -Any changes made to files in sub-folders will be lost. -See http://activescaffold.com/tutorials/faq#custom-css. diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/add.gif b/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/add.gif deleted file mode 100644 index 51e6a2d53a13122a3e85de3bb56c22fee79de313..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 986 zcmZ?wbhEHb6krfw_|CxKz`$VLYU0>q>eOfM)NSR`ZROr$@7`zU(QD`4>)=1bA!v$s z$W))Oxh}D@Lz3qQC(I2?nje<3Ff46hWcsS0lvN>FE5kEaM`f>!%-s^62SO3~+arp% zMHO$0F5D4Sv@^P3Z(P~#_>$FWWoy#QHz(I_$gJL(T(dj1W^Y=>p4^%pnKe7I>UQMh zA4sY=kX(HztMX`8?SYKi<9Usnb6d9-v~Mfx-c{PMx4d&lMbF-g{*e?YgsW+kJ%pE(LbT%SCWpL0!C z30bC5csPmaplay`7s)1eegO&NYbFvIF1`{f_90jHC@{55RT5yiR1tjC{p|7zixWSJ z92RsMyHq)>J*n6#&cu}KFj45RE9*KLJBy146BJlY^qo2$%sS{ilaa-JjX>~}!)&~= t#}YgOJ~(n3`v=U)a60DH&@3pz@o*DsI|DN>tCd4Qg5$IE%*;#-)&TDaA-Mnm diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/arrow_down.gif b/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/arrow_down.gif deleted file mode 100644 index bcda8697b6ac9701b40499855afe5fc32a7f899e..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 853 zcmZ?wbhEHb6kuRy_|CvkRaI42SJ&9sxN6m^U%!6+{rmSn7%+^2(GVB`A)xq^g^>Z6 z6?8y;1?33_4kHGB76FG12?rV2h16sM4m2EYXXD}tSTRBINQbaySk8-pMQ*)fwskC? P3XeT{8T{lpI2fz}7^o(6 diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/arrow_up.gif b/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/arrow_up.gif deleted file mode 100644 index b5e3399e44967d6a029de64dd19ea9a653cc1c31..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 851 zcmZ?wbhEHb6kuRy_|CvkRaI42SJ&9sxN6m^U%!6+{rmSn7%+^2(GVB`A)xq^g^>Z6 z6?8y;1?33_4g&^$4jGPw1qYj%*aajS1Rgdpv2hvX%n(@A*dZ(%wWlLc`FOt&KbwHV Nrj(NmY|Kmy)&Qp2Bz6D* diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/close.gif b/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/close.gif deleted file mode 100644 index aa1b988cc99c95e9badcbd6ff2210ef7f990b310..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 960 zcmZ?wbhEHb6krf!_|Cu}R?IJ6%qLmSC0)rbSIZ<{&mdMHB9yKzoS`j}p(T;6Cz+!s zm9H;XsIOFPrdesNU1g)x$gJ7QZPhPt*x+Q_;p;J7KWx5z&g!DPbtSc1vs-o+Pd_tt z!O6+X&(7X+bMux*>$g4Lu=CmG{jatkzPtO_hrK61?LYtR$ocO_u0B71IyScpDC?d0pv1z&$YPXrN5bJChX6a9h=k{+Ck@Oj&eLKdAEbCq zWDQy|L7=gvYoeaxA(guEoyT++I zn$b9r%cFfhHe2K68PkBu*@^<$y+7xQ$wJ~;c5aBx$R=xq*41Wo zhwQus_VOgm0hughj}MhOvs#{>Vg09Y8WxjWUJY5YW zJ?&8eG!59Cz=|E%Ns@013KLWOLV)CObIIj_5{>{#k%TEAMs_GbdDV`x-iYsGH z#=Z{USAQA>NY(}X7=3{K8#o^IfD8vYgMn2$K}oI2VBRB#S&XxIHb|UVXSGe;amR7P zS2p)o76|ciA8|Qvq4aIax{H@ZnNanE3}Rqa1nNI*(8rR=r7=;>sb^kJkjQcgmhyRT z7B%Zv2=Mjp6aeYsgxksmwpAUdi^Z^yHIpx6qMGv@nUmU^jBC}J3SKO~=O-c|#O#_} zlpXt!wvdlubV z6`o{w!*|FkOH{$acy{5e#3#>^yGRm*%-h>*l%@ z5-iIjM2hF$SyUjT+!)}Z!6w}7$Q0o{&k5PNj6jb<0%#ITQY71o%t={F9B&Kvd{pF1 z3*_4q@n<(nzsvhN)Nl+6Z8W$ NR4SG~(qLh*1_1j1mLdQE diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/indicator.gif b/vendor/plugins/active_scaffold/test/mock_app/public/images/active_scaffold/default/indicator.gif deleted file mode 100644 index 9cb298eb4ac260aecbb06f8e701dc7f411286a85..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 725 zcmZ?wbhEHb6krfwSi}GVhRJ(_s`n};Un}m}J7wvyoqJCK1r`5u`?-b$J39ur8tEA@ zGlGPEvao{G>wpN5b_Qk#j$Hx=Cs>M47szcge6aWCvC?bDdr~9|c^pH!6B*WVpDy|v z_9N#ogXH3X4vzLCNj&W;Z0WWg##K)wxr`rdnuK8}KhRKnj$I0efQE`I<~9i+8R`=l za@qjd(8CEG0*Xf-D@DdgaUE3_mh@$sGF4NB5#6DDKr?MQb~zjYni;N{%cO{8W=~>> zw*bh@P0@Qq?QR=1tT~#@!!{vGu)szrcbnQIkJX0D8(0t~G6B8L2le`@(BJD#SM)Gm z65O=r=&fUnVTHPnJm#Ih7TB+_#z5h;d=2*+yUPLV2KU+Lz znjW2k>~(~p_8hCyfQFuk(Ox%2HTRnI1=|D-s|m*f`5ouzJlG{{Eu8U2>#zf7lk58L z3`~{I4hjqgY!gqZe)gDXl-#ANjpB7Cpfe#}&tf~XZspgcmd~D1W^-qn^CWPJup0C& zYg(jzbD!qzT`xsg)EuYmmOb&DnYEIMvEhfY(&ST*cvtOdoU|6n>kJGC6RnuP9dq3p zQ7sgFTVqbNyJxaMk4EOKm7mt8{}vIvy-PuXBQtQp?z<0 zz$iC3Twp04%8|>Id;^h=x)nmWpYQr$vHvQ^g$+9dT0*%PSmu>gNuvOO$0ks zMIj=HnnBRUR?tKXG11rxCU4&7dG4NbuvR2_mEvc)n?Cow;~Wve|KR^>9@p5l)|QB+ z$jmun3q#x>;ss-PW_mnr2MHVzLAl1RW&0?VkixF*4t!St0YVb2wnKdU(kmOHiL;aW zK8Xte%(k>MVGG$E4no6dcNnb>BhVHHGD&1pv4YZ68kE2V03t5#PCEFm7=ad$6)+3B zTCmn*?A?=u(o~ET7~-7g0)ZB=6|lumi4}B}MLgy~Ysy6)Q5%Al7|05&1z3Jpu>cF8 z3?VXs*3<}%h3`5Wld)N2zJnk%Agw<~3k)sPTLFd=F5;d8-bj-09SkQuynfflNcZLN z!^_37fdZvzrq=9~mp*($%mcDRKC&qvaaZuX+C=AT6O*~tHl>0mcP<_q>-z%$xO(@! zYluq5a8VQI$S@4?r*v;gPo!QQ%pX3A#>xx4t=w-L6COWx?aj&`f+!YePsFtj=hOQR zP3=E2j@9L7s8;T^&s?u(Hdpu?CubjMrGn{t_37>9$|AD)QE08weJlKn8|OyjL~7oP zC8mPT`jzuH*Dh^I0048RGafUIT)4H~*m8m>egI0iH=(LB%b@@O002ovPDHLkV1lw0 B3'; - element.parentNode.replaceChild(tempDiv.getElementsByTagName(tn).item(0), element); - } - else throw e; - } - } else { - var range = element.ownerDocument.createRange(); - /* patch to fix
replaces in Firefox. see http://dev.rubyonrails.org/ticket/8010 */ - range.selectNodeContents(element.parentNode); - element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()), element); - } - setTimeout(function() {html.evalScripts()}, 10); - return element; -}; - -/* - * URL modification support. Incomplete functionality. - */ -Object.extend(String.prototype, { - append_params: function(params) { - url = this; - if (url.indexOf('?') == -1) url += '?'; - else if (url.lastIndexOf('&') != url.length) url += '&'; - - url += $H(params).collect(function(item) { - return item.key + '=' + item.value; - }).join('&'); - - return url; - } -}); - -/* - * Prototype's implementation was throwing an error instead of false - */ -Element.Methods.Simulated = { - hasAttribute: function(element, attribute) { - var t = Element._attributeTranslations; - attribute = (t.names && t.names[attribute]) || attribute; - // Return false if we get an error here - try { - return $(element).getAttributeNode(attribute).specified; - } catch (e) { - return false; - } - } -}; - -/** - * A set of links. As a set, they can be controlled such that only one is "open" at a time, etc. - */ -ActiveScaffold.Actions = new Object(); -ActiveScaffold.Actions.Abstract = Class.create({ - initialize: function(links, target, loading_indicator, options) { - this.target = $(target); - this.loading_indicator = $(loading_indicator); - this.options = options; - this.links = links.collect(function(link) { - return this.instantiate_link(link); - }.bind(this)); - }, - - instantiate_link: function(link) { - throw 'unimplemented' - } -}); - -/** - * A DataStructures::ActionLink, represented in JavaScript. - * Concerned with AJAX-enabling a link and adapting the result for insertion into the table. - */ -ActiveScaffold.ActionLink = new Object(); -ActiveScaffold.ActionLink.Abstract = Class.create({ - initialize: function(a, target, loading_indicator) { - this.tag = $(a); - this.url = this.tag.href; - this.method = 'get'; - if(this.url.match('_method=delete')){ - this.method = 'delete'; - } else if(this.url.match('_method=post')){ - this.method = 'post'; - } else if(this.url.match('_method=put')){ - this.method = 'put'; - } - this.target = target; - this.loading_indicator = loading_indicator; - this.hide_target = false; - this.position = this.tag.getAttribute('position'); - this.page_link = this.tag.getAttribute('page_link'); - - this.onclick = this.tag.onclick; - this.tag.onclick = null; - this.tag.observe('click', function(event) { - this.open(); - Event.stop(event); - }.bind(this)); - - this.tag.action_link = this; - }, - - open: function() { - if (this.is_disabled()) return; - - if (this.tag.hasAttribute( "dhtml_confirm")) { - if (this.onclick) this.onclick(); - return; - } else { - if (this.onclick && !this.onclick()) return;//e.g. confirmation messages - this.open_action(); - } - }, - - open_action: function() { - if (this.position) this.disable(); - - if (this.page_link) { - window.location = this.url; - } else { - if (this.loading_indicator) this.loading_indicator.style.visibility = 'visible'; - new Ajax.Request(this.url, { - asynchronous: true, - evalScripts: true, - method: this.method, - onSuccess: function(request) { - if (this.position) { - this.insert(request.responseText); - if (this.hide_target) this.target.hide(); - } else { - request.evalResponse(); - } - }.bind(this), - - onFailure: function(request) { - ActiveScaffold.report_500_response(this.scaffold_id()); - if (this.position) this.enable() - }.bind(this), - - onComplete: function(request) { - if (this.loading_indicator) this.loading_indicator.style.visibility = 'hidden'; - }.bind(this) - }); - } - }, - - insert: function(content) { - throw 'unimplemented' - }, - - close: function() { - this.enable(); - this.adapter.remove(); - if (this.hide_target) this.target.show(); - }, - - close_handler: function(event) { - this.close(); - if (event) Event.stop(event); - }, - - register_cancel_hooks: function() { - // anything in the insert with a class of cancel gets the closer method, and a reference to this object for good measure - var self = this; - this.adapter.select('.cancel').each(function(elem) { - elem.observe('click', this.close_handler.bind(this)); - elem.link = self; - }.bind(this)) - }, - - reload: function() { - this.close(); - this.open(); - }, - - get_new_adapter_id: function() { - var id = 'adapter_'; - var i = 0; - while ($(id + i)) i++; - return id + i; - }, - - enable: function() { - return this.tag.removeClassName('disabled'); - }, - - disable: function() { - return this.tag.addClassName('disabled'); - }, - - is_disabled: function() { - return this.tag.hasClassName('disabled'); - }, - - scaffold_id: function() { - return this.tag.up('div.active-scaffold').id; - } -}); - -/** - * Concrete classes for record actions - */ -ActiveScaffold.Actions.Record = Class.create(ActiveScaffold.Actions.Abstract, { - instantiate_link: function(link) { - var l = new ActiveScaffold.ActionLink.Record(link, this.target, this.loading_indicator); - l.refresh_url = this.options.refresh_url; - if (link.hasClassName('delete')) { - l.url = l.url.replace(/\/delete(\?.*)?$/, '$1'); - l.url = l.url.replace(/\/delete\/(.*)/, '/destroy/$1'); - } - if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'}); - l.set = this; - return l; - } -}); - -ActiveScaffold.ActionLink.Record = Class.create(ActiveScaffold.ActionLink.Abstract, { - close_previous_adapter: function() { - this.set.links.each(function(item) { - if (item.url != this.url && item.is_disabled() && item.adapter) { - item.enable(); - item.adapter.remove(); - } - }.bind(this)); - }, - - insert: function(content) { - this.close_previous_adapter(); - - if (this.position == 'replace') { - this.position = 'after'; - this.hide_target = true; - } - - if (this.position == 'after') { - new Insertion.After(this.target, content); - this.adapter = this.target.next(); - } - else if (this.position == 'before') { - new Insertion.Before(this.target, content); - this.adapter = this.target.previous(); - } - else { - return false; - } - - this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this)); - this.register_cancel_hooks(); - - this.adapter.down('td').down().highlight(); - }, - - close: function($super, updatedRow) { - if (updatedRow) { - ActiveScaffold.update_row(this.target, updatedRow); - $super(); - } else { - new Ajax.Request(this.refresh_url, { - asynchronous: true, - evalScripts: true, - method: this.method, - onSuccess: function(request) { - ActiveScaffold.update_row(this.target, request.responseText); - $super(); - }.bind(this), - - onFailure: function(request) { - ActiveScaffold.report_500_response(this.scaffold_id()); - } - }); - } - }, - - enable: function() { - this.set.links.each(function(item) { - if (item.url != this.url) return; - item.tag.removeClassName('disabled'); - }.bind(this)); - }, - - disable: function() { - this.set.links.each(function(item) { - if (item.url != this.url) return; - item.tag.addClassName('disabled'); - }.bind(this)); - } -}); - -/** - * Concrete classes for table actions - */ -ActiveScaffold.Actions.Table = Class.create(ActiveScaffold.Actions.Abstract, { - instantiate_link: function(link) { - var l = new ActiveScaffold.ActionLink.Table(link, this.target, this.loading_indicator); - if (l.position) l.url = l.url.append_params({adapter: '_list_inline_adapter'}); - return l; - } -}); - -ActiveScaffold.ActionLink.Table = Class.create(ActiveScaffold.ActionLink.Abstract, { - insert: function(content) { - if (this.position == 'top') { - new Insertion.Top(this.target, content); - this.adapter = this.target.immediateDescendants().first(); - } - else { - throw 'Unknown position "' + this.position + '"' - } - - this.adapter.down('a.inline-adapter-close').observe('click', this.close_handler.bind(this)); - this.register_cancel_hooks(); - - this.adapter.down('td').down().highlight(); - } -}); - -if (Ajax.InPlaceEditor) { -ActiveScaffold.InPlaceEditor = Class.create(Ajax.InPlaceEditor, { - setFieldFromAjax: function(url, options) { - var ipe = this; - $(ipe._controls.editor).remove(); - new Ajax.Request(url, { - method: 'get', - onComplete: function(response) { - ipe._form.insert({top: response.responseText}); - if (options.plural) { - ipe._form.getElements().each(function(el) { - if (el.type != "submit" && el.type != "image") { - el.name = ipe.options.paramName + '[]'; - el.className = 'editor_field'; - } - }); - } else { - var fld = ipe._form.findFirstElement(); - fld.name = ipe.options.paramName; - fld.className = 'editor_field'; - if (ipe.options.submitOnBlur) - fld.onblur = ipe._boundSubmitHandler; - ipe._controls.editor = fld; - } - } - }); - }, - - clonePatternField: function() { - var patternNodes = this.getPatternNodes(this.options.inplacePatternSelector); - if (patternNodes.editNode == null) { - alert('did not find any matching node for ' + this.options.editFieldSelector); - return; - } - - var fld = patternNodes.editNode.cloneNode(true); - if (fld.id.length > 0) fld.id += this.options.nodeIdSuffix; - fld.name = this.options.paramName; - fld.className = 'editor_field'; - this.setValue(fld, this._controls.editor.value); - if (this.options.submitOnBlur) - fld.onblur = this._boundSubmitHandler; - $(this._controls.editor).remove(); - this._controls.editor = fld; - this._form.appendChild(this._controls.editor); - - $A(patternNodes.additionalNodes).each(function(node) { - var patternNode = node.cloneNode(true); - if (patternNode.id.length > 0) { - patternNode.id = patternNode.id + this.options.nodeIdSuffix; - } - this._form.appendChild(patternNode); - }.bind(this)); - }, - - getPatternNodes: function(inplacePatternSelector) { - var nodes = {editNode: null, additionalNodes: []}; - var selectedNodes = $$(inplacePatternSelector); - var firstNode = selectedNodes.first(); - - if (typeof(firstNode) !== 'undefined') { - // AS inplace_edit_control_container -> we have to select all child nodes - // Workaround for ie which does not support css > selector - if (firstNode.className.indexOf('as_inplace_pattern') !== -1) { - selectedNodes = firstNode.childElements(); - } - nodes.editNode = selectedNodes.first(); - selectedNodes.shift(); - nodes.additionalNodes = selectedNodes; - } - return nodes; - }, - - setValue: function(editField, textValue) { - var function_name = 'setValueFor' + editField.nodeName.toLowerCase(); - if (typeof(this[function_name]) == 'function') { - this[function_name](editField, textValue); - } else { - editField.value = textValue; - } - }, - - setValueForselect: function(editField, textValue) { - var len = editField.options.length; - var i = 0; - while (i < len && editField.options[i].text != textValue) { - i++; - } - if (i < len) { - editField.value = editField.options[i].value - } - } -}); -} diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/dhtml_history.js b/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/dhtml_history.js deleted file mode 100755 index 3bf6275..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/dhtml_history.js +++ /dev/null @@ -1,867 +0,0 @@ -/* -Copyright (c) 2007 Brian Dillard and Brad Neuberg: -Brian Dillard | Project Lead | bdillard@pathf.com | http://blogs.pathf.com/agileajax/ -Brad Neuberg | Original Project Creator | http://codinginparadise.org - -SVN r113 from http://code.google.com/p/reallysimplehistory -+ Changes by Ed Wildgoose - MailASail -+ Changed EncodeURIComponent -> EncodeURI -+ Changed DecodeURIComponent -> DecodeURI -+ Changed 'blank.html?' -> '/blank.html?' - -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. -*/ - -/* - dhtmlHistory: An object that provides history, history data, and bookmarking for DHTML and Ajax applications. - - dependencies: - * the historyStorage object included in this file. - -*/ -window.dhtmlHistory = { - - /*Public: User-agent booleans*/ - isIE: false, - isOpera: false, - isSafari: false, - isKonquerer: false, - isGecko: false, - isSupported: false, - - /*Public: Create the DHTML history infrastructure*/ - create: function(options) { - - /* - options - object to store initialization parameters - options.blankURL - string to override the default location of blank.html. Must end in "?" - options.debugMode - boolean that causes hidden form fields to be shown for development purposes. - options.toJSON - function to override default JSON stringifier - options.fromJSON - function to override default JSON parser - options.baseTitle - pattern for title changes; example: "Armchair DJ [@@@]" - @@@ will be replaced - */ - - var that = this; - - /*Set up the historyStorage object; pass in options bundle*/ - window.historyStorage.setup(options); - - /*Set up our base title if one is passed in*/ - if (options && options.baseTitle) { - if (options.baseTitle.indexOf("@@@") < 0 && historyStorage.debugMode) { - throw new Error("Programmer error: options.baseTitle must contain the replacement parameter" - + " '@@@' to be useful."); - } - this.baseTitle = options.baseTitle; - } - - /*set user-agent flags*/ - var UA = navigator.userAgent.toLowerCase(); - var platform = navigator.platform.toLowerCase(); - var vendor = navigator.vendor || ""; - if (vendor === "KDE") { - this.isKonqueror = true; - this.isSupported = false; - } else if (typeof window.opera !== "undefined") { - this.isOpera = true; - this.isSupported = true; - } else if (typeof document.all !== "undefined") { - this.isIE = true; - this.isSupported = true; - } else if (vendor.indexOf("Apple Computer, Inc.") > -1) { - this.isSafari = true; - this.isSupported = (platform.indexOf("mac") > -1); - } else if (UA.indexOf("gecko") != -1) { - this.isGecko = true; - this.isSupported = true; - } - - /*Create Safari/Opera-specific code*/ - if (this.isSafari) { - this.createSafari(); - } else if (this.isOpera) { - this.createOpera(); - } - - /*Get our initial location*/ - var initialHash = this.getCurrentLocation(); - - /*Save it as our current location*/ - this.currentLocation = initialHash; - - /*Now that we have a hash, create IE-specific code*/ - if (this.isIE) { - /*Optionally override the URL of IE's blank HTML file*/ - if (options && options.blankURL) { - var u = options.blankURL; - /*assign the value, adding the trailing ? if it's not passed in*/ - this.blankURL = (u.indexOf("?") != u.length - 1 - ? u + "?" - : u - ); - } - this.createIE(initialHash); - } - - /*Add an unload listener for the page; this is needed for FF 1.5+ because this browser caches all dynamic updates to the - page, which can break some of our logic related to testing whether this is the first instance a page has loaded or whether - it is being pulled from the cache*/ - - var unloadHandler = function() { - that.firstLoad = null; - }; - - this.addEventListener(window,'unload',unloadHandler); - - /*Determine if this is our first page load; for IE, we do this in this.iframeLoaded(), which is fired on pageload. We do it - there because we have no historyStorage at this point, which only exists after the page is finished loading in IE*/ - if (this.isIE) { - /*The iframe will get loaded on page load, and we want to ignore this fact*/ - this.ignoreLocationChange = true; - } else { - if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { - /*This is our first page load, so ignore the location change and add our special history entry*/ - this.ignoreLocationChange = true; - this.firstLoad = true; - historyStorage.put(this.PAGELOADEDSTRING, true); - } else { - /*This isn't our first page load, so indicate that we want to pay attention to this location change*/ - this.ignoreLocationChange = false; - this.firstLoad = false; - /*For browsers other than IE, fire a history change event; on IE, the event will be thrown automatically when its - hidden iframe reloads on page load. Unfortunately, we don't have any listeners yet; indicate that we want to fire - an event when a listener is added.*/ - this.fireOnNewListener = true; - } - } - - /*Other browsers can use a location handler that checks at regular intervals as their primary mechanism; we use it for IE as - well to handle an important edge case; see checkLocation() for details*/ - var locationHandler = function() { - that.checkLocation(); - }; - setInterval(locationHandler, 100); - }, - - /*Public: Initialize our DHTML history. You must call this after the page is finished loading. Optionally, you can pass your listener in - here so you don't need to make a separate call to addListener*/ - initialize: function(listener) { - - /*save original document title to plug in when we hit a null-key history point*/ - this.originalTitle = document.title; - - /*IE needs to be explicitly initialized. IE doesn't autofill form data until the page is finished loading, so we have to wait*/ - if (this.isIE) { - /*If this is the first time this page has loaded*/ - if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { - /*For IE, we do this in initialize(); for other browsers, we do it in create()*/ - this.fireOnNewListener = false; - this.firstLoad = true; - historyStorage.put(this.PAGELOADEDSTRING, true); - } - /*Else if this is a fake onload event*/ - else { - this.fireOnNewListener = true; - this.firstLoad = false; - } - } - /*optional convenience to save a separate call to addListener*/ - if (listener) { - this.addListener(listener); - } - }, - - /*Public: Adds a history change listener. Only one listener is supported at this time.*/ - addListener: function(listener) { - this.listener = listener; - /*If the page was just loaded and we should not ignore it, fire an event to our new listener now*/ - if (this.fireOnNewListener) { - this.fireHistoryEvent(this.currentLocation); - this.fireOnNewListener = false; - } - }, - - /*Public: Change the current HTML title*/ - changeTitle: function(historyData) { - var winTitle = (historyData && historyData.newTitle - /*Plug the new title into the pattern*/ - ? this.baseTitle.replace('@@@', historyData.newTitle) - /*Otherwise, if there is no new title, use the original document title. This is useful when some - history changes have title changes and some don't; we can automatically return to the original - title rather than leaving a misleading title in the title bar. The same goes for our "virgin" - (hashless) page state.*/ - : this.originalTitle - ); - /*No need to do anything if the title isn't changing*/ - if (document.title == winTitle) { - return; - } - - - /*Now change the DOM*/ - document.title = winTitle; - /*Change it in the iframe, too, for IE*/ - if (this.isIE) { - this.iframe.contentWindow.document.title = winTitle; - } - - /*If non-IE, reload the hash so the new title "sticks" in the browser history object*/ - if (!this.isIE && !this.isOpera) { - var hash = decodeURI(document.location.hash); - if (hash != "") { - var encodedHash = encodeURI(this.removeHash(hash)); - document.location.hash = encodedHash; - } else { - //document.location.hash = "#"; - } - } - }, - - /*Public: Add a history point. Parameters available: - * newLocation (required): - This will be the #hash value in the URL. Users can bookmark it. It will persist across sessions, so - your application should be able to restore itself to a specific state based on just this value. It - should be either a simple keyword for a viewstate or else a pseudo-querystring. - * historyData (optional): - This is for complex data that is relevant only to the current browsing session. It will be available - to your application until the browser is closed. If the user comes back to a bookmarked history point - during a later session, this data will no longer be available. Don't rely on it for application - re-initialization from a bookmark. - * historyData.newTitle (optional): - This will swap out the html attribute with a new value. If you have set a baseTitle using the - options bundle, the value will be plugged into the baseTitle by swapping out the @@@ replacement param. - */ - add: function(newLocation, historyData) { - - var that = this; - - /*Escape the location and remove any leading hash symbols*/ - var encodedLocation = encodeURI(this.removeHash(newLocation)); - - if (this.isSafari) { - - /*Store the history data into history storage - pass in unencoded newLocation since - historyStorage does its own encoding*/ - historyStorage.put(newLocation, historyData); - - /*Save this as our current location*/ - this.currentLocation = encodedLocation; - - /*Change the browser location*/ - window.location.hash = encodedLocation; - - /*Save this to the Safari form field*/ - this.putSafariState(encodedLocation); - - this.changeTitle(historyData); - - } else { - - /*Most browsers require that we wait a certain amount of time before changing the location, such - as 200 MS; rather than forcing external callers to use window.setTimeout to account for this, - we internally handle it by putting requests in a queue.*/ - var addImpl = function() { - - /*Indicate that the current wait time is now less*/ - if (that.currentWaitTime > 0) { - that.currentWaitTime = that.currentWaitTime - that.waitTime; - } - - /*IE has a strange bug; if the encodedLocation is the same as _any_ preexisting id in the - document, then the history action gets recorded twice; throw a programmer exception if - there is an element with this ID*/ - if (document.getElementById(encodedLocation) && that.debugMode) { - var e = "Exception: History locations can not have the same value as _any_ IDs that might be in the document," - + " due to a bug in IE; please ask the developer to choose a history location that does not match any HTML" - + " IDs in this document. The following ID is already taken and cannot be a location: " + newLocation; - throw new Error(e); - } - - /*Store the history data into history storage - pass in unencoded newLocation since - historyStorage does its own encoding*/ - historyStorage.put(newLocation, historyData); - - /*Indicate to the browser to ignore this upcomming location change since we're making it programmatically*/ - that.ignoreLocationChange = true; - - /*Indicate to IE that this is an atomic location change block*/ - that.ieAtomicLocationChange = true; - - /*Save this as our current location*/ - that.currentLocation = encodedLocation; - - /*Change the browser location*/ - window.location.hash = encodedLocation; - - /*Change the hidden iframe's location if on IE*/ - if (that.isIE) { - that.iframe.src = that.blankURL + encodedLocation; - } - - /*End of atomic location change block for IE*/ - that.ieAtomicLocationChange = false; - - that.changeTitle(historyData); - - }; - - /*Now queue up this add request*/ - window.setTimeout(addImpl, this.currentWaitTime); - - /*Indicate that the next request will have to wait for awhile*/ - this.currentWaitTime = this.currentWaitTime + this.waitTime; - } - }, - - /*Public*/ - isFirstLoad: function() { - return this.firstLoad; - }, - - /*Public*/ - getVersion: function() { - return this.VERSIONNUMBER; - }, - - /*- - - - - - - - - - - -*/ - - /*Private: Constant for our own internal history event called when the page is loaded*/ - PAGELOADEDSTRING: "DhtmlHistory_pageLoaded", - - VERSIONNUMBER: "0.8", - - /* - Private: Pattern for title changes. Example: "Armchair DJ [@@@]" where @@@ will be relaced by values passed to add(); - Default is just the title itself, hence "@@@" - */ - baseTitle: "@@@", - - /*Private: Placeholder variable for the original document title; will be set in ititialize()*/ - originalTitle: null, - - /*Private: URL for the blank html file we use for IE; can be overridden via the options bundle. Otherwise it must be served - in same directory as this library*/ - blankURL: "/blank.html?", - - /*Private: Our history change listener.*/ - listener: null, - - /*Private: MS to wait between add requests - will be reset for certain browsers*/ - waitTime: 200, - - /*Private: MS before an add request can execute*/ - currentWaitTime: 0, - - /*Private: Our current hash location, without the "#" symbol.*/ - currentLocation: null, - - /*Private: Hidden iframe used to IE to detect history changes*/ - iframe: null, - - /*Private: Flags and DOM references used only by Safari*/ - safariHistoryStartPoint: null, - safariStack: null, - safariLength: null, - - /*Private: Flag used to keep checkLocation() from doing anything when it discovers location changes we've made ourselves - programmatically with the add() method. Basically, add() sets this to true. When checkLocation() discovers it's true, - it refrains from firing our listener, then resets the flag to false for next cycle. That way, our listener only gets fired on - history change events triggered by the user via back/forward buttons and manual hash changes. This flag also helps us set up - IE's special iframe-based method of handling history changes.*/ - ignoreLocationChange: null, - - /*Private: A flag that indicates that we should fire a history change event when we are ready, i.e. after we are initialized and - we have a history change listener. This is needed due to an edge case in browsers other than IE; if you leave a page entirely - then return, we must fire this as a history change event. Unfortunately, we have lost all references to listeners from earlier, - because JavaScript clears out.*/ - fireOnNewListener: null, - - /*Private: A variable that indicates whether this is the first time this page has been loaded. If you go to a web page, leave it - for another one, and then return, the page's onload listener fires again. We need a way to differentiate between the first page - load and subsequent ones. This variable works hand in hand with the pageLoaded variable we store into historyStorage.*/ - firstLoad: null, - - /*Private: A variable to handle an important edge case in IE. In IE, if a user manually types an address into their browser's - location bar, we must intercept this by calling checkLocation() at regular intervals. However, if we are programmatically - changing the location bar ourselves using the add() method, we need to ignore these changes in checkLocation(). Unfortunately, - these changes take several lines of code to complete, so for the duration of those lines of code, we set this variable to true. - That signals to checkLocation() to ignore the change-in-progress. Once we're done with our chunk of location-change code in - add(), we set this back to false. We'll do the same thing when capturing user-entered address changes in checkLocation itself.*/ - ieAtomicLocationChange: null, - - /*Private: Generic utility function for attaching events*/ - addEventListener: function(o,e,l) { - if (o.addEventListener) { - o.addEventListener(e,l,false); - } else if (o.attachEvent) { - o.attachEvent('on'+e,function() { - l(window.event); - }); - } - }, - - - /*Private: Create IE-specific DOM nodes and overrides*/ - createIE: function(initialHash) { - /*write out a hidden iframe for IE and set the amount of time to wait between add() requests*/ - this.waitTime = 400;/*IE needs longer between history updates*/ - var styles = (historyStorage.debugMode - ? 'width: 800px;height:80px;border:1px solid black;' - : historyStorage.hideStyles - ); - var iframeID = "rshHistoryFrame"; - var iframeHTML = '<iframe frameborder="0" id="' + iframeID + '" style="' + styles + '" src="' + this.blankURL + initialHash + '"></iframe>'; - document.write(iframeHTML); - this.iframe = document.getElementById(iframeID); - }, - - /*Private: Create Opera-specific DOM nodes and overrides*/ - createOpera: function() { - this.waitTime = 400;/*Opera needs longer between history updates*/ - var imgHTML = '<img src="javascript:location.href=\'javascript:dhtmlHistory.checkLocation();\';" style="' + historyStorage.hideStyles + '" />'; - document.write(imgHTML); - }, - - /*Private: Create Safari-specific DOM nodes and overrides*/ - createSafari: function() { - var formID = "rshSafariForm"; - var stackID = "rshSafariStack"; - var lengthID = "rshSafariLength"; - var formStyles = historyStorage.debugMode ? historyStorage.showStyles : historyStorage.hideStyles; - var stackStyles = (historyStorage.debugMode - ? 'width: 800px;height:80px;border:1px solid black;' - : historyStorage.hideStyles - ); - var lengthStyles = (historyStorage.debugMode - ? 'width:800px;height:20px;border:1px solid black;margin:0;padding:0;' - : historyStorage.hideStyles - ); - var safariHTML = '<form id="' + formID + '" style="' + formStyles + '">' - + '<textarea style="' + stackStyles + '" id="' + stackID + '">[]</textarea>' - + '<input type="text" style="' + lengthStyles + '" id="' + lengthID + '" value=""/>' - + '</form>'; - document.write(safariHTML); - this.safariStack = document.getElementById(stackID); - this.safariLength = document.getElementById(lengthID); - if (!historyStorage.hasKey(this.PAGELOADEDSTRING)) { - this.safariHistoryStartPoint = history.length; - this.safariLength.value = this.safariHistoryStartPoint; - } else { - this.safariHistoryStartPoint = this.safariLength.value; - } - }, - - /*TODO: make this public again?*/ - /*Private: Get browser's current hash location; for Safari, read value from a hidden form field*/ - getCurrentLocation: function() { - var r = (this.isSafari - ? this.getSafariState() - : this.getCurrentHash() - ); - return r; - }, - - /*TODO: make this public again?*/ - /*Private: Manually parse the current url for a hash; tip of the hat to YUI*/ - getCurrentHash: function() { - var r = window.location.href; - var i = r.indexOf("#"); - return (i >= 0 - ? r.substr(i+1) - : "" - ); - }, - - /*Private: Safari method to read the history stack from a hidden form field*/ - getSafariStack: function() { - var r = this.safariStack.value; - return historyStorage.fromJSON(r); - }, - /*Private: Safari method to read from the history stack*/ - getSafariState: function() { - var stack = this.getSafariStack(); - var state = stack[history.length - this.safariHistoryStartPoint - 1]; - return state; - }, - /*Private: Safari method to write the history stack to a hidden form field*/ - putSafariState: function(newLocation) { - var stack = this.getSafariStack(); - stack[history.length - this.safariHistoryStartPoint] = newLocation; - this.safariStack.value = historyStorage.toJSON(stack); - }, - - /*Private: Notify the listener of new history changes.*/ - fireHistoryEvent: function(newHash) { - var decodedHash = decodeURI(newHash) - /*extract the value from our history storage for this hash*/ - var historyData = historyStorage.get(decodedHash); - this.changeTitle(historyData); - /*call our listener*/ - this.listener.call(null, decodedHash, historyData); - }, - - /*Private: See if the browser has changed location. This is the primary history mechanism for Firefox. For IE, we use this to - handle an important edge case: if a user manually types in a new hash value into their IE location bar and press enter, we want to - to intercept this and notify any history listener.*/ - checkLocation: function() { - - /*Ignore any location changes that we made ourselves for browsers other than IE*/ - if (!this.isIE && this.ignoreLocationChange) { - this.ignoreLocationChange = false; - return; - } - - /*If we are dealing with IE and we are in the middle of making a location change from an iframe, ignore it*/ - if (!this.isIE && this.ieAtomicLocationChange) { - return; - } - - /*Get hash location*/ - var hash = this.getCurrentLocation(); - - /*Do nothing if there's been no change*/ - if (hash == this.currentLocation) { - return; - } - - /*In IE, users manually entering locations into the browser; we do this by comparing the browser's location against the - iframe's location; if they differ, we are dealing with a manual event and need to place it inside our history, otherwise - we can return*/ - this.ieAtomicLocationChange = true; - - if (this.isIE && this.getIframeHash() != hash) { - this.iframe.src = this.blankURL + hash; - } - else if (this.isIE) { - /*the iframe is unchanged*/ - return; - } - - /*Save this new location*/ - this.currentLocation = hash; - - this.ieAtomicLocationChange = false; - - /*Notify listeners of the change*/ - this.fireHistoryEvent(hash); - }, - - /*Private: Get the current location of IE's hidden iframe.*/ - getIframeHash: function() { - var doc = this.iframe.contentWindow.document; - var hash = String(doc.location.search); - if (hash.length == 1 && hash.charAt(0) == "?") { - hash = ""; - } - else if (hash.length >= 2 && hash.charAt(0) == "?") { - hash = hash.substring(1); - } - return hash; - }, - - /*Private: Remove any leading hash that might be on a location.*/ - removeHash: function(hashValue) { - var r; - if (hashValue === null || hashValue === undefined) { - r = null; - } - else if (hashValue === "") { - r = ""; - } - else if (hashValue.length == 1 && hashValue.charAt(0) == "#") { - r = ""; - } - else if (hashValue.length > 1 && hashValue.charAt(0) == "#") { - r = hashValue.substring(1); - } - else { - r = hashValue; - } - return r; - }, - - /*Private: For IE, tell when the hidden iframe has finished loading.*/ - iframeLoaded: function(newLocation) { - /*ignore any location changes that we made ourselves*/ - if (this.ignoreLocationChange) { - this.ignoreLocationChange = false; - return; - } - - /*Get the new location*/ - var hash = String(newLocation.search); - if (hash.length == 1 && hash.charAt(0) == "?") { - hash = ""; - } - else if (hash.length >= 2 && hash.charAt(0) == "?") { - hash = hash.substring(1); - } - /*Keep the browser location bar in sync with the iframe hash*/ - window.location.hash = hash; - - /*Notify listeners of the change*/ - this.fireHistoryEvent(hash); - } - - -}; - -/* - historyStorage: An object that uses a hidden form to store history state across page loads. The mechanism for doing so relies on - the fact that browsers save the text in form data for the life of the browser session, which means the text is still there when - the user navigates back to the page. This object can be used independently of the dhtmlHistory object for caching of Ajax - session information. - - dependencies: - * json2007.js (included in a separate file) or alternate JSON methods passed in through an options bundle. -*/ -window.historyStorage = { - - /*Public: Set up our historyStorage object for use by dhtmlHistory or other objects*/ - setup: function(options) { - - /* - options - object to store initialization parameters - passed in from dhtmlHistory or directly into historyStorage - options.debugMode - boolean that causes hidden form fields to be shown for development purposes. - options.toJSON - function to override default JSON stringifier - options.fromJSON - function to override default JSON parser - */ - - /*process init parameters*/ - if (typeof options !== "undefined") { - if (options.debugMode) { - this.debugMode = options.debugMode; - } - if (options.toJSON) { - this.toJSON = options.toJSON; - } - if (options.fromJSON) { - this.fromJSON = options.fromJSON; - } - } - - /*write a hidden form and textarea into the page; we'll stow our history stack here*/ - var formID = "rshStorageForm"; - var textareaID = "rshStorageField"; - var formStyles = this.debugMode ? historyStorage.showStyles : historyStorage.hideStyles; - var textareaStyles = (historyStorage.debugMode - ? 'width: 800px;height:80px;border:1px solid black;' - : historyStorage.hideStyles - ); - var textareaHTML = '<form id="' + formID + '" style="' + formStyles + '">' - + '<textarea id="' + textareaID + '" style="' + textareaStyles + '"></textarea>' - + '</form>'; - document.write(textareaHTML); - this.storageField = document.getElementById(textareaID); - if (typeof window.opera !== "undefined") { - this.storageField.focus();/*Opera needs to focus this element before persisting values in it*/ - } - }, - - /*Public*/ - put: function(key, value) { - - var encodedKey = encodeURI(key); - - this.assertValidKey(encodedKey); - /*if we already have a value for this, remove the value before adding the new one*/ - if (this.hasKey(key)) { - this.remove(key); - } - /*store this new key*/ - this.storageHash[encodedKey] = value; - /*save and serialize the hashtable into the form*/ - this.saveHashTable(); - }, - - /*Public*/ - get: function(key) { - - var encodedKey = encodeURI(key); - - this.assertValidKey(encodedKey); - /*make sure the hash table has been loaded from the form*/ - this.loadHashTable(); - var value = this.storageHash[encodedKey]; - if (value === undefined) { - value = null; - } - return value; - }, - - /*Public*/ - remove: function(key) { - - var encodedKey = encodeURI(key); - - this.assertValidKey(encodedKey); - /*make sure the hash table has been loaded from the form*/ - this.loadHashTable(); - /*delete the value*/ - delete this.storageHash[encodedKey]; - /*serialize and save the hash table into the form*/ - this.saveHashTable(); - }, - - /*Public: Clears out all saved data.*/ - reset: function() { - this.storageField.value = ""; - this.storageHash = {}; - }, - - /*Public*/ - hasKey: function(key) { - - var encodedKey = encodeURI(key); - - this.assertValidKey(encodedKey); - /*make sure the hash table has been loaded from the form*/ - this.loadHashTable(); - return (typeof this.storageHash[encodedKey] !== "undefined"); - }, - - /*Public*/ - isValidKey: function(key) { - return (typeof key === "string"); - //TODO - should we ban hash signs and other special characters? - }, - - /*- - - - - - - - - - - -*/ - - /*Private - CSS strings utilized by both objects to hide or show behind-the-scenes DOM elements*/ - showStyles: 'border:0;margin:0;padding:0;', - hideStyles: 'left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;', - - /*Private - debug mode flag*/ - debugMode: false, - - /*Private: Our hash of key name/values.*/ - storageHash: {}, - - /*Private: If true, we have loaded our hash table out of the storage form.*/ - hashLoaded: false, - - /*Private: DOM reference to our history field*/ - storageField: null, - - /*Private: Assert that a key is valid; throw an exception if it not.*/ - assertValidKey: function(key) { - var isValid = this.isValidKey(key); - if (!isValid && this.debugMode) { - throw new Error("Please provide a valid key for window.historyStorage. Invalid key = " + key + "."); - } - }, - - /*Private: Load the hash table up from the form.*/ - loadHashTable: function() { - if (!this.hashLoaded) { - var serializedHashTable = this.storageField.value; - if (serializedHashTable !== "" && serializedHashTable !== null) { - this.storageHash = this.fromJSON(serializedHashTable); - this.hashLoaded = true; - } - } - }, - /*Private: Save the hash table into the form.*/ - saveHashTable: function() { - this.loadHashTable(); - var serializedHashTable = this.toJSON(this.storageHash); - this.storageField.value = serializedHashTable; - }, - /*Private: Bridges for our JSON implementations - both rely on 2007 JSON.org library - can be overridden by options bundle*/ - toJSON: function(o) { - return o.toJSONString(); - }, - fromJSON: function(s) { - return s.parseJSON(); - } -}; - - -/*******************************************************************/ -/** QueryString Object from http://adamv.com/dev/javascript/querystring */ -/* Client-side access to querystring name=value pairs - Version 1.3 - 28 May 2008 - - License (Simplified BSD): - http://adamv.com/dev/javascript/qslicense.txt -*/ -function Querystring(qs) { // optionally pass a querystring to parse - this.params = {}; - - if (qs == null) qs = location.search.substring(1, location.search.length); - if (qs.length == 0) return; - -// Turn <plus> back to <space> -// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1 - qs = qs.replace(/\+/g, ' '); - var args = qs.split('&'); // parse out name/value pairs separated via & - -// split out each name=value pair - for (var i = 0; i < args.length; i++) { - var pair = args[i].split('='); - var name = decodeURI(pair[0]); - - var value = (pair.length==2) - ? decodeURI(pair[1]) - : name; - - this.params[name] = value; - } -} - -Querystring.prototype.get = function(key, default_) { - var value = this.params[key]; - return (value != null) ? value : default_; -} - -Querystring.prototype.contains = function(key) { - var value = this.params[key]; - return (value != null); -} - -/*******************************************************************/ -/* Added by Ed Wildgoose - MailASail */ -/* Initialise the library and add our history callback */ -/*******************************************************************/ -window.dhtmlHistory.create({ - toJSON: function(o) { - return Object.toJSON(o); - } - , fromJSON: function(s) { - return s.evalJSON(); - } - - // Enable this to assist with debugging -// , debugMode: true - - // dhtmlHistory has been modified not to need the next line - // But left in for robustness when updating dhtmlHistory - , blankURL: '/blank.html?' -}); - -/** Our callback to receive history - change events. */ -var handleHistoryChange = function(pageId, pageData) { - if (!pageData) return; - var info = pageId.split(':'); - var id = info[0]; - pageData += '&_method=get'; - new Ajax.Request(pageData, {asynchronous:true, evalScripts:true, method: 'get', onLoading:function(request){Element.show(id+'-pagination-loading-indicator');}}); -} - -window.onload = function() { - dhtmlHistory.initialize(handleHistoryChange); -}; - diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/form_enhancements.js b/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/form_enhancements.js deleted file mode 100644 index 136c2c0..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/form_enhancements.js +++ /dev/null @@ -1,117 +0,0 @@ - -// TODO Change to dropping the name property off the input element when in example mode -TextFieldWithExample = Class.create(); -TextFieldWithExample.prototype = { - initialize: function(inputElementId, defaultText, options) { - this.setOptions(options); - - this.input = $(inputElementId); - this.name = this.input.name; - this.defaultText = defaultText; - this.createHiddenInput(); - - if (options.focus) this.input.focus(); - this.checkAndShowExample(); - if (options.focus) { - this.input.selectionStart = 0; - this.input.selectionEnd = 0; - } - - Event.observe(this.input, "blur", this.onBlur.bindAsEventListener(this)); - Event.observe(this.input, "focus", this.onFocus.bindAsEventListener(this)); - Event.observe(this.input, "select", this.onFocus.bindAsEventListener(this)); - Event.observe(this.input, "keydown", this.onKeyPress.bindAsEventListener(this)); - Event.observe(this.input, "click", this.onClick.bindAsEventListener(this)); - }, - createHiddenInput: function() { - this.hiddenInput = document.createElement("input"); - this.hiddenInput.type = "hidden"; - this.hiddenInput.value = ""; - this.input.parentNode.appendChild(this.hiddenInput); - }, - setOptions: function(options) { - this.options = { exampleClassName: 'example' }; - Object.extend(this.options, options || {}); - }, - onKeyPress: function(event) { - if (!event) var event = window.event; - var code = (event.which) ? event.which : event.keyCode - if (this.isAlphanumeric(code)) { - this.removeExample(); - } - }, - onBlur: function(event) { - this.checkAndShowExample(); - }, - onFocus: function(event) { - this.removeExample(); - }, - onClick: function(event) { - this.removeExample(); - }, - isAlphanumeric: function(keyCode) { - return keyCode >= 40 && keyCode <= 90; - }, - checkAndShowExample: function() { - if (this.input.value == '') { - this.input.value = this.defaultText; - this.input.name = null; - this.hiddenInput.name = this.name; - Element.addClassName(this.input, this.options.exampleClassName); - } - }, - removeExample: function() { - if (this.exampleShown()) { - this.input.value = ''; - this.input.name = this.name; - this.hiddenInput.name = null; - Element.removeClassName(this.input, this.options.exampleClassName); - } - }, - exampleShown: function() { - return Element.hasClassName(this.input, this.options.exampleClassName); - } -} - -Form.disable = function(form) { - var elements = this.getElements(form); - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - try { element.blur(); } catch (e) {} - element.disabled = 'disabled'; - Element.addClassName(element, 'disabled'); - } - } -Form.enable = function(form) { - var elements = this.getElements(form); - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - element.disabled = ''; - Element.removeClassName(element, 'disabled'); - } - } - -DraggableLists = Class.create({ - initialize: function(list) { - list = $(list).addClassName('draggable-list'); - var list_selected = list.cloneNode(false).addClassName('selected'); - list_selected.id += '_seleted'; - list.select('input[type=checkbox]').each(function(item) { - var li = item.up('li'); - li.down('label').htmlFor = null; - new Draggable(li, {revert: 'failure', ghosting: true}); - if (item.checked) list_selected.insert(li.remove()); - }); - list.insert({after: list_selected}); - Droppables.add(list, {hoverclass: 'hover', containment: list_selected.id, onDrop: this.drop_to_list}); - Droppables.add(list_selected, {hoverclass: 'hover', containment: list.id, onDrop: this.drop_to_list}); - list.undoPositioned(); // undo positioned to fix dragging from elements with overflow auto - list_selected.undoPositioned(); - }, - - drop_to_list: function(draggable, droppable, event) { - droppable.insert(draggable.remove()); - draggable.setStyle({left: '0px', top: '0px'}); - draggable.down('input').checked = droppable.hasClassName('selected'); - } -}); diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/rico_corner.js b/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/rico_corner.js deleted file mode 100644 index e6541f1..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/javascripts/active_scaffold/default/rico_corner.js +++ /dev/null @@ -1,370 +0,0 @@ -/** - * - * Copyright 2005 Sabre Airline Solutions - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this - * file except in compliance with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the - * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions - * and limitations under the License. - **/ - - -//-------------------- rico.js -var Rico = { - Version: '1.1.0', - prototypeVersion: parseFloat(Prototype.Version.split(".")[0] + "." + Prototype.Version.split(".")[1]) -} - -//-------------------- ricoColor.js -Rico.Color = Class.create(); - -Rico.Color.prototype = { - - initialize: function(red, green, blue) { - this.rgb = { r: red, g : green, b : blue }; - }, - - blend: function(other) { - this.rgb.r = Math.floor((this.rgb.r + other.rgb.r)/2); - this.rgb.g = Math.floor((this.rgb.g + other.rgb.g)/2); - this.rgb.b = Math.floor((this.rgb.b + other.rgb.b)/2); - }, - - asRGB: function() { - return "rgb(" + this.rgb.r + "," + this.rgb.g + "," + this.rgb.b + ")"; - }, - - asHex: function() { - return "#" + this.rgb.r.toColorPart() + this.rgb.g.toColorPart() + this.rgb.b.toColorPart(); - }, - - asHSB: function() { - return Rico.Color.RGBtoHSB(this.rgb.r, this.rgb.g, this.rgb.b); - }, - - toString: function() { - return this.asHex(); - } - -}; - -Rico.Color.createFromHex = function(hexCode) { - if(hexCode.length==4) { - var shortHexCode = hexCode; - var hexCode = '#'; - for(var i=1;i<4;i++) hexCode += (shortHexCode.charAt(i) + shortHexCode.charAt(i)); - } - if ( hexCode.indexOf('#') == 0 ) - hexCode = hexCode.substring(1); - var red = hexCode.substring(0,2); - var green = hexCode.substring(2,4); - var blue = hexCode.substring(4,6); - return new Rico.Color( parseInt(red,16), parseInt(green,16), parseInt(blue,16) ); -} - -/** - * Factory method for creating a color from the background of - * an HTML element. - */ -Rico.Color.createColorFromBackground = function(elem) { - - //var actualColor = RicoUtil.getElementsComputedStyle($(elem), "backgroundColor", "background-color"); // Changed to prototype style - var actualColor = $(elem).getStyle('backgroundColor'); - - if ( actualColor == "transparent" && elem.parentNode ) - return Rico.Color.createColorFromBackground(elem.parentNode); - - if ( actualColor == null ) - return new Rico.Color(255,255,255); - - if ( actualColor.indexOf("rgb(") == 0 ) { - var colors = actualColor.substring(4, actualColor.length - 1 ); - var colorArray = colors.split(","); - return new Rico.Color( parseInt( colorArray[0] ), - parseInt( colorArray[1] ), - parseInt( colorArray[2] ) ); - - } - else if ( actualColor.indexOf("#") == 0 ) { - return Rico.Color.createFromHex(actualColor); - } - else - return new Rico.Color(255,255,255); -} - -/* next two functions changed to mootools color.js functions */ -Rico.Color.HSBtoRGB = function(hue, saturation, brightness) { - - var br = Math.round(brightness / 100 * 255); - if (this[1] == 0){ - return [br, br, br]; - } else { - var hue = this[0] % 360; - var f = hue % 60; - var p = Math.round((brightness * (100 - saturation)) / 10000 * 255); - var q = Math.round((brightness * (6000 - saturation * f)) / 600000 * 255); - var t = Math.round((brightness * (6000 - saturation * (60 - f))) / 600000 * 255); - switch(Math.floor(hue / 60)){ - case 0: return { r : br, g : t, b : p }; - case 1: return { r : q, g : br, b : p }; - case 2: return { r : p, g : br, b : t }; - case 3: return { r : p, g : q, b : br }; - case 4: return { r : t, g : p, b : br }; - case 5: return { r : br, g : p, b : q }; - } - } - return false; - } - -Rico.Color.RGBtoHSB = function(red, green, blue) { - var hue, saturation, brightness; - var max = Math.max(red, green, blue), min = Math.min(red, green, blue); - var delta = max - min; - brightness = max / 255; - saturation = (max != 0) ? delta / max : 0; - if (saturation == 0){ - hue = 0; - } else { - var rr = (max - red) / delta; - var gr = (max - green) / delta; - var br = (max - blue) / delta; - if (red == max) hue = br - gr; - else if (green == max) hue = 2 + rr - br; - else hue = 4 + gr - rr; - hue /= 6; - if (hue < 0) hue++; - } - return { h : Math.round(hue * 360), s : Math.round(saturation * 100), b : Math.round(brightness * 100)}; -} - - -//-------------------- ricoCorner.js -Rico.Corner = { - - round: function(e, options) { - var e = $(e); - this._setOptions(options); - - var color = this.options.color; - if ( this.options.color == "fromElement" ) - color = this._background(e); - - var bgColor = this.options.bgColor; - if ( this.options.bgColor == "fromParent" ) - bgColor = this._background(e.offsetParent); - - this._roundCornersImpl(e, color, bgColor); - }, - - _roundCornersImpl: function(e, color, bgColor) { - if(this.options.border) - this._renderBorder(e,bgColor); - if(this._isTopRounded()) - this._roundTopCorners(e,color,bgColor); - if(this._isBottomRounded()) - this._roundBottomCorners(e,color,bgColor); - }, - - _renderBorder: function(el,bgColor) { - var borderValue = "1px solid " + this._borderColor(bgColor); - var borderL = "border-left: " + borderValue; - var borderR = "border-right: " + borderValue; - var style = "style='" + borderL + ";" + borderR + "'"; - el.innerHTML = "<div " + style + ">" + el.innerHTML + "</div>" - }, - - _roundTopCorners: function(el, color, bgColor) { - var corner = this._createCorner(bgColor); - for(var i=0 ; i < this.options.numSlices ; i++ ) - corner.appendChild(this._createCornerSlice(color,bgColor,i,"top")); - el.style.paddingTop = 0; - el.insertBefore(corner,el.firstChild); - }, - - _roundBottomCorners: function(el, color, bgColor) { - var corner = this._createCorner(bgColor); - for(var i=(this.options.numSlices-1) ; i >= 0 ; i-- ) - corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom")); - el.style.paddingBottom = 0; - el.appendChild(corner); - }, - - _createCorner: function(bgColor) { - var corner = document.createElement("div"); - corner.style.backgroundColor = (this._isTransparent() ? "transparent" : bgColor); - return corner; - }, - - _createCornerSlice: function(color,bgColor, n, position) { - var slice = document.createElement("span"); - - var inStyle = slice.style; - inStyle.backgroundColor = color; - inStyle.display = "block"; - inStyle.height = "1px"; - inStyle.overflow = "hidden"; - inStyle.fontSize = "1px"; - - var borderColor = this._borderColor(color,bgColor); - if ( this.options.border && n == 0 ) { - inStyle.borderTopStyle = "solid"; - inStyle.borderTopWidth = "1px"; - inStyle.borderLeftWidth = "0px"; - inStyle.borderRightWidth = "0px"; - inStyle.borderBottomWidth = "0px"; - inStyle.height = "0px"; // assumes css compliant box model - inStyle.borderColor = borderColor; - } - else if(borderColor) { - inStyle.borderColor = borderColor; - inStyle.borderStyle = "solid"; - inStyle.borderWidth = "0px 1px"; - } - - if ( !this.options.compact && (n == (this.options.numSlices-1)) ) - inStyle.height = "2px"; - - this._setMargin(slice, n, position); - this._setBorder(slice, n, position); - return slice; - }, - - _setOptions: function(options) { - this.options = { - corners : "all", - color : "fromElement", - bgColor : "fromParent", - blend : true, - border : false, - compact : false - } - Object.extend(this.options, options || {}); - - this.options.numSlices = this.options.compact ? 2 : 4; - if ( this._isTransparent() ) - this.options.blend = false; - }, - - _whichSideTop: function() { - if ( this._hasString(this.options.corners, "all", "top") ) - return ""; - - if ( this.options.corners.indexOf("tl") >= 0 && this.options.corners.indexOf("tr") >= 0 ) - return ""; - - if (this.options.corners.indexOf("tl") >= 0) - return "left"; - else if (this.options.corners.indexOf("tr") >= 0) - return "right"; - return ""; - }, - - _whichSideBottom: function() { - if ( this._hasString(this.options.corners, "all", "bottom") ) - return ""; - - if ( this.options.corners.indexOf("bl")>=0 && this.options.corners.indexOf("br")>=0 ) - return ""; - - if(this.options.corners.indexOf("bl") >=0) - return "left"; - else if(this.options.corners.indexOf("br")>=0) - return "right"; - return ""; - }, - - _borderColor : function(color,bgColor) { - if ( color == "transparent" ) - return bgColor; - else if ( this.options.border ) - return this.options.border; - else if ( this.options.blend ) - return this._blend( bgColor, color ); - else - return ""; - }, - - - _setMargin: function(el, n, corners) { - var marginSize = this._marginSize(n); - var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom(); - - if ( whichSide == "left" ) { - el.style.marginLeft = marginSize + "px"; el.style.marginRight = "0px"; - } - else if ( whichSide == "right" ) { - el.style.marginRight = marginSize + "px"; el.style.marginLeft = "0px"; - } - else { - el.style.marginLeft = marginSize + "px"; el.style.marginRight = marginSize + "px"; - } - }, - - _setBorder: function(el,n,corners) { - var borderSize = this._borderSize(n); - var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom(); - if ( whichSide == "left" ) { - el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = "0px"; - } - else if ( whichSide == "right" ) { - el.style.borderRightWidth = borderSize + "px"; el.style.borderLeftWidth = "0px"; - } - else { - el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px"; - } - if (this.options.border != false) - el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px"; - }, - - _marginSize: function(n) { - if ( this._isTransparent() ) - return 0; - - var marginSizes = [ 5, 3, 2, 1 ]; - var blendedMarginSizes = [ 3, 2, 1, 0 ]; - var compactMarginSizes = [ 2, 1 ]; - var smBlendedMarginSizes = [ 1, 0 ]; - - if ( this.options.compact && this.options.blend ) - return smBlendedMarginSizes[n]; - else if ( this.options.compact ) - return compactMarginSizes[n]; - else if ( this.options.blend ) - return blendedMarginSizes[n]; - else - return marginSizes[n]; - }, - - _borderSize: function(n) { - var transparentBorderSizes = [ 5, 3, 2, 1 ]; - var blendedBorderSizes = [ 2, 1, 1, 1 ]; - var compactBorderSizes = [ 1, 0 ]; - var actualBorderSizes = [ 0, 2, 0, 0 ]; - - if ( this.options.compact && (this.options.blend || this._isTransparent()) ) - return 1; - else if ( this.options.compact ) - return compactBorderSizes[n]; - else if ( this.options.blend ) - return blendedBorderSizes[n]; - else if ( this.options.border ) - return actualBorderSizes[n]; - else if ( this._isTransparent() ) - return transparentBorderSizes[n]; - return 0; - }, - - _hasString: function(str) { for(var i=1 ; i<arguments.length ; i++) if (str.indexOf(arguments[i]) >= 0) return true; return false; }, - _blend: function(c1, c2) { var cc1 = Rico.Color.createFromHex(c1); cc1.blend(Rico.Color.createFromHex(c2)); return cc1; }, - _background: function(el) { try { return Rico.Color.createColorFromBackground(el).asHex(); } catch(err) { return "#ffffff"; } }, - _isTransparent: function() { return this.options.color == "transparent"; }, - _isTopRounded: function() { return this._hasString(this.options.corners, "all", "top", "tl", "tr"); }, - _isBottomRounded: function() { return this._hasString(this.options.corners, "all", "bottom", "bl", "br"); }, - _hasSingleTextChild: function(el) { return el.childNodes.length == 1 && el.childNodes[0].nodeType == 3; } -} - diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/DO_NOT_EDIT b/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/DO_NOT_EDIT deleted file mode 100644 index c5e44a3..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/DO_NOT_EDIT +++ /dev/null @@ -1,2 +0,0 @@ -Any changes made to files in sub-folders will be lost. -See http://activescaffold.com/tutorials/faq#custom-css. diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet-ie.css b/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet-ie.css deleted file mode 100644 index 7992a64..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet-ie.css +++ /dev/null @@ -1,35 +0,0 @@ -/* IE hacks - ==================================== */ - -* html .active-scaffold-header, -.active-scaffold li.form-element, -.active-scaffold li.sub-section { -zoom: 1; -} - -* html .active-scaffold td .messages-container { -border-top: solid 1px #DAFFCD; -} - -* html .active-scaffold-header div.actions a.show_search { -background-image: none; -filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../../../images/active_scaffold/default/magnifier.png', sizingMethod='crop'); -} - -* html .active-scaffold .sub-form .association-record a.destroy { -background-image: none; -filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../../../images/active_scaffold/default/cross.png', sizingMethod='crop'); -} - -.active-scaffold-header div.actions a.disabled { -filter: alpha(opacity=50); -} - -.active-scaffold .show-view dd, -.active-scaffold li.form-element dd { -float: none; -} - -.active-scaffold li.form-element dt { -padding: 4px 0; -} diff --git a/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet.css b/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet.css deleted file mode 100644 index de55302..0000000 --- a/vendor/plugins/active_scaffold/test/mock_app/public/stylesheets/active_scaffold/default/stylesheet.css +++ /dev/null @@ -1,849 +0,0 @@ -/* - ActiveScaffold - (c) 2007 Richard White <rrwhite@gmail.com> - - ActiveScaffold is freely distributable under the terms of an MIT-style license. - - For details, see the ActiveScaffold web site: http://www.activescaffold.com/ -*/ - -.active-scaffold form, -.active-scaffold table, -.active-scaffold p, -.active-scaffold div, -.active-scaffold fieldset { -margin: 0; -padding: 0; -} - -.active-scaffold { -margin: 5px 0; -} - -.active-scaffold table { -width: 100%; -border-collapse: separate; -} - -.active-scaffold a, -.active-scaffold a:visited { -color: #06c; -text-decoration: none; -} - -.active-scaffold a.disabled { -color: #999; -} - -.active-scaffold a:hover { -background-color: #ff8; -} - -.active-scaffold .clear-fix { -clear: both; -} - -noscript.active-scaffold { -border-left: solid 5px #f66; -background-color: #fbb; -font-size: 11px; -font-weight: bold; -padding: 5px 20px 5px 5px; -color: #333; -} - -.active-scaffold .mark_record_column { - width: 1px; -} - -/* Header - ======================== */ - -.active-scaffold-header { -position: relative; -} - -.blue-theme .active-scaffold-header { -background-color: #005CB8; -} - -.active-scaffold-header h2 { -padding: 2px 0px; -margin: 0; -color: #555; -font: bold 160% arial, sans-serif; -} - -.blue-theme .active-scaffold-header h2 { -color: #fff; -padding: 2px 5px 4px 5px; -} - -.active-scaffold-header div.actions a { -float: right; -font: bold 14px arial; -letter-spacing: -1px; -text-decoration: none; -padding: 1px 2px; -white-space: nowrap; -margin-left: 5px; -background-position: 1px 50%; -background-repeat: no-repeat; -} - -.view .active-scaffold-header div.actions a { -float: left; -} - -.blue-theme .active-scaffold-header div.actions a { -color: #fff; -} - -.active-scaffold-header div.actions a.disabled { -color: #666; -opacity: 0.5; -} - -.blue-theme .active-scaffold-header div.actions a.disabled { -color: #fff; -opacity: 0.5; -} - -.active-scaffold-header div.actions a.new, -.active-scaffold-header div.actions a.new_existing, -.active-scaffold-header div.actions a.show_search { -padding-left: 19px; -background-position: 1px 50%; -background-repeat: no-repeat; -} - -.active-scaffold-header div.actions a.new, -.active-scaffold-header div.actions a.new_existing { -background-image: url(../../../images/active_scaffold/default/add.gif); -} - -.active-scaffold-header div.actions a.show_search { -background-image: url(../../../images/active_scaffold/default/magnifier.png); -} - -.blue-theme .active-scaffold-header div.actions a:hover { -background-color: #378CDF; -} - -.active-scaffold-header div.actions a.disabled:hover { -background-color: transparent; -cursor: default; -} - -.active-scaffold-header div.actions { -position: absolute; -right: 5px; -top: 5px; -text-align: right; -} - -/* Table :: Column Headers - ============================= */ - -.active-scaffold th { -background-color: #555; -text-align: left; -} - -.active-scaffold th a, -.active-scaffold th p { -font: bold 11px arial, sans-serif; -display: block; -background-color: #555; -} - -.active-scaffold th a, .active-scaffold th a:visited { -color: #fff; -padding: 2px 15px 2px 5px; -} - -.active-scaffold th p { -color: #eee; -padding: 2px 5px; -} - -.active-scaffold th a:hover { -background-color: #000; -color: #ff8; -} - -.active-scaffold th.sorted { -background-color: #333; -} - -.active-scaffold th.asc a, -.active-scaffold th.asc a:hover { -background: #333 url(../../../images/active_scaffold/default/arrow_up.gif) right 50% no-repeat; -} - -.active-scaffold th.desc a, -.active-scaffold th.desc a:hover { -background: #333 url(../../../images/active_scaffold/default/arrow_down.gif) right 50% no-repeat; -} - -.active-scaffold th.loading a, -.active-scaffold th.loading a:hover { -background: #333 url(../../../images/active_scaffold/default/indicator-small.gif) right 50% no-repeat; -} - -/* Table :: Record Rows - ============================= */ - -.active-scaffold tr.record { - background-color: #E6F2FF; -} -.active-scaffold tr.record td { -padding: 5px 4px; -color: #333; -font-family: Verdana, sans-serif; -font-size: 11px; -border-bottom: solid 1px #C5DBF7; -border-left: solid 1px #C5DBF7; -} - -.active-scaffold tr.even-record { -background-color: #fff; -} -.active-scaffold tr.even-record td { -border-left-color: #ddd; -} - -.active-scaffold tr.record td.sorted { -background-color: #B9DCFF; -border-bottom-color: #AFD0F5; -} - -.active-scaffold tr.even-record td.sorted { -background-color: #E6F2FF; -border-bottom-color: #AFD0F5; -} - -.active-scaffold tbody.records td.empty { -color: #999; -text-align: center; -} - -.active-scaffold td.numeric, -.active-scaffold-calculations td { -text-align: right; -} - -/* Table :: Actions (Edit, Delete) - ============================= */ - -.active-scaffold tr.record td.actions { -border-right: solid 1px #ccc; -padding: 0; -min-width: 1%; -} - -.active-scaffold tr.record td.actions table { -float: right; -width: auto; -margin-right: 5px; -} - -.active-scaffold tr.record td.actions table td { -border: none; -text-align: right; -padding: 0 2px; -} - -.active-scaffold tr.record td.actions a { -font: bold 11px verdana, sans-serif; -letter-spacing: -1px; -padding: 2px; -margin: 0 2px; -line-height: 16px; -white-space: nowrap; -} - -/* Table :: Inline Adapter - ============================= */ - -.active-scaffold .view { -background-color: #DAFFCD; -padding: 4px; -border: solid 1px #7FcF00; -} - -.active-scaffold tbody.records td.inline-adapter-cell .view { -border-top: none; -} - -.active-scaffold .before-header td.inline-adapter-cell .view { -border-bottom: none; -} - -.active-scaffold a.inline-adapter-close { -float: right; -text-indent: -4000px; -width: 16px; -height: 17px; -background: url(../../../images/active_scaffold/default/close.gif) 0 0 no-repeat; -} - -/* Nested - ======================== */ - -.blue-theme .active-scaffold .active-scaffold-header, -.blue-theme .active-scaffold .active-scaffold-footer { -background-color: #1F7F00; - -background: transparent; -} - -.active-scaffold .active-scaffold .active-scaffold-header { -margin-right: 25px; -} - -.active-scaffold .active-scaffold .active-scaffold-header h2 { -font-size: 12px; -font-weight: bold; -} - -.blue-theme .active-scaffold .active-scaffold-header h2, -.active-scaffold .active-scaffold .active-scaffold-footer { -color: #444; -} - -.active-scaffold .active-scaffold .active-scaffold-header div.actions { -top: 0px; -right: 0px; -} - -.active-scaffold .active-scaffold .active-scaffold-header div.actions a { -font: bold 11px verdana, sans-serif; -} - -.blue-theme .active-scaffold .active-scaffold-header div.actions a, -.blue-theme .active-scaffold .active-scaffold-header div.actions a:visited { -color: #06c; -} - -.blue-theme .active-scaffold .active-scaffold-header div.actions a:hover { -background-color: #ff8; -} - -.active-scaffold .active-scaffold .view { -background-color: transparent; -padding: 0px; -border: none; -} - -.active-scaffold .active-scaffold td { -background-color: #ECFFE7; -border-bottom: solid 1px #CDF7C5; -border-left: solid 1px #CDF7C5; -} - -.active-scaffold .active-scaffold td.inline-adapter-cell { -background-color: #FFFFBB; -padding: 4px; -border: solid 1px #DDDF37; -border-top: none; -} - -.active-scaffold .active-scaffold .active-scaffold td.inline-adapter-cell { -background-color: #DAFFCD; -padding: 4px; -border: solid 1px #7FcF00; -border-top: none; -} - -.active-scaffold .active-scaffold .active-scaffold-footer { -font-size: 11px; -} - -/* Footer - ========================== */ - -.active-scaffold-calculations td { -background-color: #eee; -border-top: 2px solid #005CB8; -font: bold 12px arial, sans-serif; -} - -.active-scaffold .active-scaffold-footer { -padding: 3px 0px 2px 0px; -border-bottom: none; -font: bold 12px arial, sans-serif; -} - -.blue-theme .active-scaffold-footer { -background-color: #005CB8; -color: #ccc; -} - -.active-scaffold-footer .active-scaffold-pagination { -float: right; -white-space: nowrap; -margin-right: 5px; -} - -.blue-theme .active-scaffold-footer .active-scaffold-records { -margin-left: 5px; -} - -.active-scaffold-footer a { -text-decoration: none; -letter-spacing: 0; -padding: 0 2px; -margin: 0 -2px; -font: bold 12px arial, sans-serif; -} - -.blue-theme .active-scaffold-footer a, -.blue-theme .active-scaffold-footer a:visited { -color: #fff; -} - -.blue-theme .active-scaffold-footer a:hover { -background-color: #378CDF; -} - -.active-scaffold-footer .next { -margin-left: 0; -padding-left: 5px; -border-left: solid 1px #ccc; -} - -.active-scaffold-footer .previous { -margin-right: 0; -padding-right: 5px; -border-right: solid 1px #ccc; -} - -/* Messages - ========================= */ - -.active-scaffold .messages-container, -.active-scaffold .active-scaffold .messages-container{ -padding: 0; -margin: 0 7px; -border: none; -} - -.active-scaffold .empty-message, .active-scaffold .filtered-message { -background-color: #e8e8e8; -padding: 4px; -text-align: center; -color: #666; -} - -.active-scaffold .message { -font-size: 11px; -font-weight: bold; -padding: 5px 20px 5px 5px; -color: #333; -position: relative; -margin: 2px 7px; -line-height: 12px; -} - -.active-scaffold .message a { -position: absolute; -right: 10px; -top: 4px; -padding: 0; -font: bold 11px verdana, sans-serif; -letter-spacing: -1px; -} - -.active-scaffold .messages-container .message { -margin: 0; -} - -.active-scaffold .error-message { -border-left: solid 5px #f66; -background-color: #fbb; -} - -.active-scaffold .warning-message { -border-left: solid 5px #ff6; -background-color: #ffb; -} - -.active-scaffold .info-message { -border-left: solid 5px #66f; -background-color: #bbf; -} - -/* Error Styling - ========================== */ - -.active-scaffold .errorExplanation { -background-color: #fcc; -margin: 2px 0; -border: solid 1px #f66; -} - -.active-scaffold fieldset { -clear: both; -} - -.active-scaffold .errorExplanation h2 { -padding: 2px 5px; -color: #333; -font-size: 11px; -margin: 0; -letter-spacing: 0; -font-family: Verdana; -background-color: #f66; -} - -.active-scaffold .errorExplanation ul { -margin: 0; -padding: 0 2px 4px 25px; -list-style: disc; -} - -.active-scaffold .errorExplanation p { -font-size: 11px; -padding: 2px 5px; -font-family: Verdana; -margin: 0; -} - -.active-scaffold .errorExplanation ul li { -font: bold 11px verdana; -letter-spacing: -1px; -margin: 0; -padding: 0; -background-color: transparent; -} - -/* Loading Indicators - ============================== */ - -.active-scaffold .loading-indicator { -vertical-align: text-bottom; -width: 16px; -margin: 0; -} - -.active-scaffold .active-scaffold-header .loading-indicator { -margin-top: 3px; -} - -/* Show - ============================= */ - -.active-scaffold .show-view dl { -margin-left: 5px; -} -.active-scaffold .show-view dl dl { -margin-left: 0px; -} - -.active-scaffold .show-view dt { -width: 12em; -float: left; -clear: left; -font: normal 11px verdana, sans-serif; -color: #555; -line-height: 16px; -} - -.active-scaffold .show-view dd { -float: left; -font: bold 14px arial; -padding-left: 5px; -margin-bottom: 5px; -} - -/* Form - ============================== */ - -.active-scaffold dl { -margin: 0; -} - -.active-scaffold .submit { -font-weight: bold; -font-size: 14px; -font-family: Arial, sans-serif; -letter-spacing: 0; -margin: 0; -margin-top: 5px; -} - -.active-scaffold form p { -clear: both; -} - -.active-scaffold fieldset { -border: none; -} - -.active-scaffold h4, -.active-scaffold h5 { -padding: 2px; -margin: 0; -text-transform: none; -color: #1F7F00; -letter-spacing: -1px; -font: bold 16px arial; -} - -.active-scaffold h5 { -padding: 0; -margin: 5px 0 2px 0; -font-size: 14px; -letter-spacing: 0; -} - -.active-scaffold ol { -clear: both; -float: none; -padding: 2px; -margin-left: 5px; -list-style: none; -} - -.active-scaffold p.form-footer { -clear: both; -} - -.active-scaffold a.cancel, -.active-scaffold p.form-footer a { -font: bold 14px arial, sans-serif; -letter-spacing: 0; -} - -/* Form :: Fields - ============================== */ - -.active-scaffold li.form-element { -clear: both; -padding-top: 2px; -} - -.active-scaffold label { -font: normal 11px verdana, sans-serif; -color: #555; -} - -.active-scaffold li.form-element dt { -float: left; -width: 12em; -padding: 6px 0; -} - -.active-scaffold li.form-element dd { -float: left; -} - -.active-scaffold .form dd { -margin: 0; -} - - -.active-scaffold .description { -color: #999; -font-size: 10px; -margin-left: 5px; -} - -.active-scaffold .required label { -font-weight: bold; -} - -.active-scaffold label.example { -font-size: 11px; -font-family: arial; -color: #888; -} - -.active-scaffold input.text-input, -.active-scaffold select { -font: bold 16px arial; -letter-spacing: -1px; -border: solid 1px #1F7F00; -} - -.active-scaffold input.text-input { -padding: 2px; -} - -.active-scaffold .fieldWithErrors input, -.active-scaffold .fieldWithErrors textarea, -.active-scaffold .fieldWithErrors select { -border: solid 1px #f00; -} - -.active-scaffold select { -padding: 1px; -} - -.active-scaffold input.example { -color: #aaa; -} - -.active-scaffold select:focus, -.active-scaffold input.text-input:focus { -background-color: #ffc; -} - -.active-scaffold textarea { -font-family: Arial, sans-serif; -font-size: 12px; -padding: 1px; -border: solid 1px #1F7F00; -} - -.active-scaffold .checkbox-list { -padding-left: 0px; -} - -.active-scaffold .checkbox-list li { -padding-right: 5px; -display: inline; -} - -.active-scaffold .checkbox-list li label { -padding: 0 0 0 2px; -} - -.active-scaffold .draggable-list { -float: left; -width: 300px; -margin-right: 15px; -min-height: 30px; -max-height: 100px; -overflow: auto; -background-color: #FFFF88; -} - -.active-scaffold .draggable-list.hover { -opacity: 0.5; -} - -.active-scaffold .draggable-list.selected { -background-color: #7FCF00; -} - -.active-scaffold .draggable-list li { -display: block; -} - -.active-scaffold .draggable-list input { -display: none; -} - -/* Form :: Sub-Sections - ============================== */ - -.active-scaffold li.sub-section { -clear: left; -padding: 5px 0; -} - -/* Form :: Association Sub-Forms - ============================== */ - -.active-scaffold .sub-form { -float: left; -clear: left; -padding: 5px 0; -padding-left: 5px; -} - -.active-scaffold .sub-form h5 { -margin-left: -5px; -} - -.active-scaffold .sub-form table, -.active-scaffold .sub-form table td { -width: auto; -background: none; -} - -.active-scaffold .sub-form table th { -font: normal 10px verdana, sans-serif; -color: #555; -padding: 0 5px 0 1px; -background: none; -} - -.active-scaffold .horizontal-sub-form td label { -display: none; -} - -.active-scaffold .sub-form .checkbox-list { -padding: 0 2px 2px 2px; -background-color: #fff; -border: solid 1px #1F7F00; -} - -.active-scaffold .sub-form .checkbox-list label { -display: block; -} - -.active-scaffold .sub-form table td { -border: none; -background-color: transparent; -padding: 1px; -vertical-align: top; -color: #999; -} - -.active-scaffold .sub-form .actions { -vertical-align: middle; -background-color: transparent; -clear: left; -} - -.active-scaffold .sub-form .association-record a.destroy { -font-weight: bold; -display: block; -height: 16px; -padding: 0; -width: 16px; -text-indent: -4000px; -background: url(../../../images/active_scaffold/default/cross.png) 0 0 no-repeat; -} - -.active-scaffold .sub-form .locked a.destroy { -display: none; -} - -.active-scaffold .sub-form .association-record a { -font: bold 12px arial; -} - -.active-scaffold .sub-form input.text-input, -.active-scaffold .sub-form select { -letter-spacing: 0; -font: bold 12px arial; -} - -.active-scaffold .sub-form .footer-wrapper { -margin-top: 3px; -margin-right: 10px; -} - -.active-scaffold .sub-form .footer { -color: #999; -padding: 3px 5px; -} - -.active-scaffold .sub-form .footer select, -.active-scaffold .sub-form .footer input { -font-weight: bold; -font-size: 12px; -padding: 0; -} - -.active-scaffold a.visibility-toggle { -font-size: 100%; -} - -.active-scaffold-found { - float:left; -} diff --git a/vendor/plugins/active_scaffold/test/model_stub.rb b/vendor/plugins/active_scaffold/test/model_stub.rb deleted file mode 100644 index 270e2f1..0000000 --- a/vendor/plugins/active_scaffold/test/model_stub.rb +++ /dev/null @@ -1,55 +0,0 @@ -class ModelStub < ActiveRecord::Base - abstract_class = true - has_one :other_model, :class_name => 'ModelStub' - has_many :other_models, :class_name => 'ModelStub' - - cattr_accessor :stubbed_columns - self.stubbed_columns = [:a, :b, :c, :d, :id] - attr_accessor *self.stubbed_columns - - @@nested_scope_calls = [] - cattr_accessor :nested_scope_calls - - named_scope :a_is_defined, :conditions => "a is not null" - named_scope :b_like, lambda {|pattern| {:conditions => ["b like ?", pattern]}} - - def self.a_is_defined - @@nested_scope_calls << :a_is_defined - self - end - - def self.b_like(pattern) - @@nested_scope_calls << :b_like - self - end - - def other_model=(val) - @other_model = val - end - def other_model - @other_model || nil - end - - def other_models=(val) - @other_models = val - end - def other_models - @other_models || [] - end - - def self.columns - @columns ||= self.stubbed_columns.map{|c| ActiveRecord::ConnectionAdapters::Column.new(c.to_s, '', 'varchar(255)') } - end - - def self.columns_hash - @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name.to_s] = column; hash } - end - - # column-level security methods, used for testing - def self.a_authorized_for_bar?(user) - true - end - def self.b_authorized?(user) - false - end -end diff --git a/vendor/plugins/active_scaffold/test/run_all.rb b/vendor/plugins/active_scaffold/test/run_all.rb deleted file mode 100644 index bf04f71..0000000 --- a/vendor/plugins/active_scaffold/test/run_all.rb +++ /dev/null @@ -1,8 +0,0 @@ -test_folders = %w[bridges config data_structures extensions misc] - -all_tests = test_folders.inject([]) {|output, folder| - output + Dir[File.join(File.dirname(__FILE__), "#{folder}/**/*.rb")] -} -all_tests.each{|filename| - require filename -} \ No newline at end of file diff --git a/vendor/plugins/active_scaffold/test/test_helper.rb b/vendor/plugins/active_scaffold/test/test_helper.rb deleted file mode 100644 index 1770d07..0000000 --- a/vendor/plugins/active_scaffold/test/test_helper.rb +++ /dev/null @@ -1,39 +0,0 @@ -require 'test/unit' -require 'rubygems' -require 'action_controller' -require 'action_view/test_case' -require 'mocha' -begin - require 'redgreen' -rescue LoadError -end - -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.join(File.dirname(__FILE__), 'mock_app') - -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config', 'environment.rb')) - -def load_schema - stdout = $stdout - $stdout = StringIO.new # suppress output while building the schema - load File.join(ENV['RAILS_ROOT'], 'db', 'schema.rb') - $stdout = stdout -end - -def silence_stderr(&block) - stderr = $stderr - $stderr = StringIO.new - yield - $stderr = stderr -end - -for file in %w[model_stub const_mocker] - require File.join(File.dirname(__FILE__), file) -end - -class Test::Unit::TestCase - protected - def config_for(klass, namespace = nil) - ActiveScaffold::Config::Core.new("#{namespace}#{klass.to_s.underscore.downcase}") - end -end diff --git a/vendor/plugins/active_scaffold/uninstall.rb b/vendor/plugins/active_scaffold/uninstall.rb deleted file mode 100644 index 21b9cb7..0000000 --- a/vendor/plugins/active_scaffold/uninstall.rb +++ /dev/null @@ -1,13 +0,0 @@ -## -## Delete public asset files -## - -require 'fileutils' - -directory = File.dirname(__FILE__) - -[ :stylesheets, :javascripts, :images].each do |asset_type| - path = File.join(directory, "../../../public/#{asset_type}/active_scaffold") - FileUtils.rm_r(path) -end -FileUtils.rm(File.join(directory, "../../../public/blank.html")) diff --git a/vendor/plugins/rails_xss/MIT-LICENSE b/vendor/plugins/rails_xss/MIT-LICENSE deleted file mode 100644 index ed44a7b..0000000 --- a/vendor/plugins/rails_xss/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2009 Koziarski Software Ltd. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/rails_xss/README.markdown b/vendor/plugins/rails_xss/README.markdown deleted file mode 100644 index 37cfd8f..0000000 --- a/vendor/plugins/rails_xss/README.markdown +++ /dev/null @@ -1,90 +0,0 @@ -RailsXss -======== - -This plugin replaces the default ERB template handlers with erubis, and switches the behaviour to escape by default rather than requiring you to escape. This is consistent with the behaviour in Rails 3.0. - -Strings now have a notion of "html safe", which is false by default. Whenever rails copies a string into the response body it checks whether or not the string is safe, safe strings are copied verbatim into the response body, but unsafe strings are escaped first. - -All the XSS-proof helpers like link_to and form_tag now return safe strings, and will continue to work unmodified. If you have your own helpers which return strings you *know* are safe, you will need to explicitly tell rails that they're safe. For an example, take the following helper. - - - def some_helper - (1..5).map do |i| - "<li>#{i}</li>" - end.join("\n") - end - -With this plugin installed, the html will be escaped. So you will need to do one of the following: - -1) Use the raw helper in your template. raw will ensure that your string is copied verbatim into the response body. - - <%= raw some_helper %> - -2) Mark the string as safe in the helper itself: - - def some_helper - (1..5).map do |i| - "<li>#{i}</li>" - end.join("\n").html_safe - end - -3) Use the safe_helper meta programming method: - - module ApplicationHelper - def some_helper - #... - end - safe_helper :some_helper - end - -Example -------- - -BEFORE: - - <%= params[:own_me] %> => XSS attack - <%=h params[:own_me] %> => No XSS - <%= @blog_post.content %> => Displays the HTML - -AFTER: - - <%= params[:own_me] %> => No XSS - <%=h params[:own_me] %> => No XSS (same result) - <%= @blog_post.content %> => *escapes* the HTML - <%= raw @blog_post.content %> => Displays the HTML - - -Gotchas ---- - -#### textilize and simple_format do *not* return safe strings - -Both these methods support arbitrary HTML and are *not* safe to embed directly in your document. You'll need to do something like: - - <%= sanitize(textilize(@blog_post.content_textile)) %> - -#### Safe strings aren't magic. - -Once a string has been marked as safe, the only operations which will maintain that HTML safety are String#<<, String#concat and String#+. All other operations are safety ignorant so it's still probably possible to break your app if you're doing something like - - value = something_safe - value.gsub!(/a/, params[:own_me]) - -Don't do that. - -#### String interpolation won't be safe, even when it 'should' be - - value = "#{something_safe}#{something_else_safe}" - value.html_safe? # => false - -This is intended functionality and can't be fixed. - -Getting Started -=============== - -1. Install rails 2.3.8 or higher, or freeze rails from 2-3-stable. -2. Install erubis (gem install erubis) -3. Install this plugin (ruby script/plugin install git://github.com/rails/rails_xss.git) -4. Report anything that breaks. - -Copyright (c) 2009 Koziarski Software Ltd, released under the MIT license. For full details see MIT-LICENSE included in this distribution. diff --git a/vendor/plugins/rails_xss/Rakefile b/vendor/plugins/rails_xss/Rakefile deleted file mode 100644 index 929ecbb..0000000 --- a/vendor/plugins/rails_xss/Rakefile +++ /dev/null @@ -1,23 +0,0 @@ -require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the rails_xss plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.libs << 'test' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the rails_xss plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'RailsXss' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end diff --git a/vendor/plugins/rails_xss/init.rb b/vendor/plugins/rails_xss/init.rb deleted file mode 100644 index 4f5a0ff..0000000 --- a/vendor/plugins/rails_xss/init.rb +++ /dev/null @@ -1,7 +0,0 @@ -unless $gems_rake_task - if Rails.version <= "2.3.07" - $stderr.puts "rails_xss requires Rails 2.3.8 or later. Please upgrade to enable automatic HTML safety." - else - require 'rails_xss' - end -end diff --git a/vendor/plugins/rails_xss/lib/rails_xss.rb b/vendor/plugins/rails_xss/lib/rails_xss.rb deleted file mode 100644 index 46d1b9a..0000000 --- a/vendor/plugins/rails_xss/lib/rails_xss.rb +++ /dev/null @@ -1,3 +0,0 @@ -require 'rails_xss/erubis' -require 'rails_xss/action_view' -require 'rails_xss/string_ext' diff --git a/vendor/plugins/rails_xss/lib/rails_xss/action_view.rb b/vendor/plugins/rails_xss/lib/rails_xss/action_view.rb deleted file mode 100644 index cf26fae..0000000 --- a/vendor/plugins/rails_xss/lib/rails_xss/action_view.rb +++ /dev/null @@ -1,87 +0,0 @@ -module ActionView - class Base - def self.xss_safe? - true - end - - module WithSafeOutputBuffer - # Rails version of with_output_buffer uses '' as the default buf - def with_output_buffer(buf = ActiveSupport::SafeBuffer.new) #:nodoc: - super buf - end - end - - include WithSafeOutputBuffer - end - - module Helpers - module TextHelper - def concat(string, unused_binding = nil) - if unused_binding - ActiveSupport::Deprecation.warn("The binding argument of #concat is no longer needed. Please remove it from your views and helpers.", caller) - end - - output_buffer.concat(string) - end - - def simple_format_with_escaping(text, html_options = {}) - simple_format_without_escaping(ERB::Util.h(text), html_options) - end - alias_method_chain :simple_format, :escaping - end - - module TagHelper - private - def content_tag_string_with_escaping(name, content, options, escape = true) - content_tag_string_without_escaping(name, ERB::Util.h(content), options, escape) - end - alias_method_chain :content_tag_string, :escaping - end - - module UrlHelper - def link_to(*args, &block) - if block_given? - options = args.first || {} - html_options = args.second - concat(link_to(capture(&block), options, html_options)) - else - name = args.first - options = args.second || {} - html_options = args.third - - url = url_for(options) - - if html_options - html_options = html_options.stringify_keys - href = html_options['href'] - convert_options_to_javascript!(html_options, url) - tag_options = tag_options(html_options) - else - tag_options = nil - end - - href_attr = "href=\"#{url}\"" unless href - "<a #{href_attr}#{tag_options}>#{ERB::Util.h(name || url)}</a>".html_safe - end - end - end - end -end - -module RailsXss - module SafeHelpers - def safe_helper(*names) - names.each do |helper_method_name| - aliased_target, punctuation = helper_method_name.to_s.sub(/([?!=])$/, ''), $1 - module_eval <<-END - def #{aliased_target}_with_xss_safety#{punctuation}(*args, &block) - raw(#{aliased_target}_without_xss_safety#{punctuation}(*args, &block)) - end - END - alias_method_chain helper_method_name, :xss_safety - end - end - end -end - -Module.class_eval { include RailsXss::SafeHelpers } diff --git a/vendor/plugins/rails_xss/lib/rails_xss/erubis.rb b/vendor/plugins/rails_xss/lib/rails_xss/erubis.rb deleted file mode 100644 index b58e24d..0000000 --- a/vendor/plugins/rails_xss/lib/rails_xss/erubis.rb +++ /dev/null @@ -1,33 +0,0 @@ -require 'erubis/helpers/rails_helper' - -module RailsXss - class Erubis < ::Erubis::Eruby - def add_preamble(src) - src << "@output_buffer = ActiveSupport::SafeBuffer.new;" - end - - def add_text(src, text) - return if text.empty? - src << "@output_buffer.safe_concat('" << escape_text(text) << "');" - end - - def add_expr_literal(src, code) - if code =~ /\s*raw\s+(.*)/ - src << "@output_buffer.safe_concat((" << $1 << ").to_s);" - else - src << '@output_buffer << ((' << code << ').to_s);' - end - end - - def add_expr_escaped(src, code) - src << '@output_buffer << ' << escaped_expr(code) << ';' - end - - def add_postamble(src) - src << '@output_buffer.to_s' - end - end -end - -Erubis::Helpers::RailsHelper.engine_class = RailsXss::Erubis -Erubis::Helpers::RailsHelper.show_src = false diff --git a/vendor/plugins/rails_xss/lib/rails_xss/string_ext.rb b/vendor/plugins/rails_xss/lib/rails_xss/string_ext.rb deleted file mode 100644 index ae21705..0000000 --- a/vendor/plugins/rails_xss/lib/rails_xss/string_ext.rb +++ /dev/null @@ -1,52 +0,0 @@ -require 'active_support/deprecation' - -ActiveSupport::SafeBuffer.class_eval do - def concat(value) - if value.html_safe? - super(value) - else - super(ERB::Util.h(value)) - end - end - alias << concat -end - -class String - def html_safe? - defined?(@_rails_html_safe) - end - - def html_safe! - ActiveSupport::Deprecation.warn("Use html_safe with your strings instead of html_safe! See http://yehudakatz.com/2010/02/01/safebuffers-and-rails-3-0/ for the full story.", caller) - @_rails_html_safe = true - self - end - - def add_with_safety(other) - result = add_without_safety(other) - if html_safe? && also_html_safe?(other) - result.html_safe! - else - result - end - end - alias_method :add_without_safety, :+ - alias_method :+, :add_with_safety - - def concat_with_safety(other_or_fixnum) - result = concat_without_safety(other_or_fixnum) - unless html_safe? && also_html_safe?(other_or_fixnum) - remove_instance_variable(:@_rails_html_safe) if defined?(@_rails_html_safe) - end - result - end - - alias_method_chain :concat, :safety - undef_method :<< - alias_method :<<, :concat_with_safety - - private - def also_html_safe?(other) - other.respond_to?(:html_safe?) && other.html_safe? - end -end diff --git a/vendor/plugins/rails_xss/lib/tasks/rails_xss_tasks.rake b/vendor/plugins/rails_xss/lib/tasks/rails_xss_tasks.rake deleted file mode 100644 index b8659f0..0000000 --- a/vendor/plugins/rails_xss/lib/tasks/rails_xss_tasks.rake +++ /dev/null @@ -1,4 +0,0 @@ -# desc "Explaining what the task does" -# task :rails_xss do -# # Task goes here -# end diff --git a/vendor/plugins/rails_xss/test/active_record_helper_test.rb b/vendor/plugins/rails_xss/test/active_record_helper_test.rb deleted file mode 100644 index 728ec0a..0000000 --- a/vendor/plugins/rails_xss/test/active_record_helper_test.rb +++ /dev/null @@ -1,74 +0,0 @@ -require 'test_helper' - -class ActiveRecordHelperTest < ActionView::TestCase - silence_warnings do - Post = Struct.new("Post", :title, :author_name, :body, :secret, :written_on) - Post.class_eval do - alias_method :title_before_type_cast, :title unless respond_to?(:title_before_type_cast) - alias_method :body_before_type_cast, :body unless respond_to?(:body_before_type_cast) - alias_method :author_name_before_type_cast, :author_name unless respond_to?(:author_name_before_type_cast) - end - end - - def setup_post - @post = Post.new - def @post.errors - Class.new { - def on(field) - case field.to_s - when "author_name" - "can't be empty" - when "body" - true - else - false - end - end - def empty?() false end - def count() 1 end - def full_messages() [ "Author name can't be empty" ] end - }.new - end - - def @post.new_record?() true end - def @post.to_param() nil end - - def @post.column_for_attribute(attr_name) - Post.content_columns.select { |column| column.name == attr_name }.first - end - - silence_warnings do - def Post.content_columns() [ Column.new(:string, "title", "Title"), Column.new(:text, "body", "Body") ] end - end - - @post.title = "Hello World" - @post.author_name = "" - @post.body = "Back to the hill and over it again!" - @post.secret = 1 - @post.written_on = Date.new(2004, 6, 15) - end - - def setup - setup_post - - @response = ActionController::TestResponse.new - - @controller = Object.new - def @controller.url_for(options) - options = options.symbolize_keys - - [options[:action], options[:id].to_param].compact.join('/') - end - end - - def test_text_field_with_errors_is_safe - assert text_field("post", "author_name").html_safe? - end - - def test_text_field_with_errors - assert_dom_equal( - %(<div class="fieldWithErrors"><input id="post_author_name" name="post[author_name]" size="30" type="text" value="" /></div>), - text_field("post", "author_name") - ) - end -end diff --git a/vendor/plugins/rails_xss/test/asset_tag_helper_test.rb b/vendor/plugins/rails_xss/test/asset_tag_helper_test.rb deleted file mode 100644 index f58feda..0000000 --- a/vendor/plugins/rails_xss/test/asset_tag_helper_test.rb +++ /dev/null @@ -1,49 +0,0 @@ -require 'test_helper' - -class AssetTagHelperTest < ActionView::TestCase - def setup - @controller = Class.new do - attr_accessor :request - def url_for(*args) "http://www.example.com" end - end.new - end - - def test_auto_discovery_link_tag - assert_dom_equal(%(<link href="http://www.example.com" rel="Not so alternate" title="ATOM" type="application/atom+xml" />), - auto_discovery_link_tag(:atom, {}, {:rel => "Not so alternate"})) - end - - def test_javascript_include_tag_with_blank_asset_id - ENV["RAILS_ASSET_ID"] = "" - assert_dom_equal(%(<script src="/javascripts/test.js" type="text/javascript"></script>\n<script src="/javascripts/prototype.js" type="text/javascript"></script>\n<script src="/javascripts/effects.js" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js" type="text/javascript"></script>\n<script src="/javascripts/controls.js" type="text/javascript"></script>\n<script src="/javascripts/application.js" type="text/javascript"></script>), - javascript_include_tag("test", :defaults)) - end - - def test_javascript_include_tag_with_given_asset_id - ENV["RAILS_ASSET_ID"] = "1" - assert_dom_equal(%(<script src="/javascripts/prototype.js?1" type="text/javascript"></script>\n<script src="/javascripts/effects.js?1" type="text/javascript"></script>\n<script src="/javascripts/dragdrop.js?1" type="text/javascript"></script>\n<script src="/javascripts/controls.js?1" type="text/javascript"></script>\n<script src="/javascripts/application.js?1" type="text/javascript"></script>), - javascript_include_tag(:defaults)) - ENV["RAILS_ASSET_ID"] = "" - end - - def test_javascript_include_tag_is_html_safe - assert javascript_include_tag(:defaults).html_safe? - assert javascript_include_tag("prototype").html_safe? - end - - def test_stylesheet_link_tag - assert_dom_equal(%(<link href="http://www.example.com/styles/style.css" media="screen" rel="stylesheet" type="text/css" />), - stylesheet_link_tag("http://www.example.com/styles/style")) - end - - def test_stylesheet_link_tag_is_html_safe - assert stylesheet_link_tag('dir/file').html_safe? - assert stylesheet_link_tag('dir/other/file', 'dir/file2').html_safe? - assert stylesheet_tag('dir/file', {}).html_safe? - end - - def test_image_tag - assert_dom_equal(%(<img alt="Mouse" onmouseover="this.src='/images/mouse_over.png'" onmouseout="this.src='/images/mouse.png'" src="/images/mouse.png" />), - image_tag("mouse.png", :mouseover => image_path("mouse_over.png"))) - end -end diff --git a/vendor/plugins/rails_xss/test/caching_test.rb b/vendor/plugins/rails_xss/test/caching_test.rb deleted file mode 100644 index 80c6750..0000000 --- a/vendor/plugins/rails_xss/test/caching_test.rb +++ /dev/null @@ -1,43 +0,0 @@ -require 'test_helper' - -CACHE_DIR = 'test_cache' -# Don't change '/../temp/' cavalierly or you might hose something you don't want hosed -FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR) -ActionController::Base.page_cache_directory = FILE_STORE_PATH -ActionController::Base.cache_store = :file_store, FILE_STORE_PATH - -class FragmentCachingTestController < ActionController::Base - def some_action; end; -end - -class FragmentCachingTest < ActionController::TestCase - def setup - ActionController::Base.perform_caching = true - @store = ActiveSupport::Cache::MemoryStore.new - ActionController::Base.cache_store = @store - @controller = FragmentCachingTestController.new - @params = {:controller => 'posts', :action => 'index'} - @request = ActionController::TestRequest.new - @response = ActionController::TestResponse.new - @controller.params = @params - @controller.request = @request - @controller.response = @response - @controller.send(:initialize_current_url) - @controller.send(:initialize_template_class, @response) - @controller.send(:assign_shortcuts, @request, @response) - end - - def test_html_safety - assert_nil @store.read('views/name') - content = 'value'.html_safe - assert_equal content, @controller.write_fragment('name', content) - - cached = @store.read('views/name') - assert_equal content, cached - assert_equal String, cached.class - - html_safe = @controller.read_fragment('name') - assert_equal content, html_safe - assert html_safe.html_safe? - end -end diff --git a/vendor/plugins/rails_xss/test/date_helper_test.rb b/vendor/plugins/rails_xss/test/date_helper_test.rb deleted file mode 100644 index daf0102..0000000 --- a/vendor/plugins/rails_xss/test/date_helper_test.rb +++ /dev/null @@ -1,29 +0,0 @@ -require 'test_helper' - -class DateHelperTest < ActionView::TestCase - silence_warnings do - Post = Struct.new("Post", :id, :written_on, :updated_at) - end - - def test_select_html_safety - assert select_day(16).html_safe? - assert select_month(8).html_safe? - assert select_year(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? - assert select_minute(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? - assert select_second(Time.mktime(2003, 8, 16, 8, 4, 18)).html_safe? - - assert select_minute(8, :use_hidden => true).html_safe? - assert select_month(8, :prompt => 'Choose month').html_safe? - - assert select_time(Time.mktime(2003, 8, 16, 8, 4, 18), {}, :class => 'selector').html_safe? - assert select_date(Time.mktime(2003, 8, 16), :date_separator => " / ", :start_year => 2003, :end_year => 2005, :prefix => "date[first]").html_safe? - end - - def test_object_select_html_safety - @post = Post.new - @post.written_on = Date.new(2004, 6, 15) - - assert date_select("post", "written_on", :default => Time.local(2006, 9, 19, 15, 16, 35), :include_blank => true).html_safe? - assert time_select("post", "written_on", :ignore_date => true).html_safe? - end -end diff --git a/vendor/plugins/rails_xss/test/deprecated_output_safety_test.rb b/vendor/plugins/rails_xss/test/deprecated_output_safety_test.rb deleted file mode 100644 index e16f7ce..0000000 --- a/vendor/plugins/rails_xss/test/deprecated_output_safety_test.rb +++ /dev/null @@ -1,112 +0,0 @@ -require 'test_helper' - -class DeprecatedOutputSafetyTest < ActiveSupport::TestCase - def setup - @string = "hello" - end - - test "A string can be marked safe using html_safe!" do - assert_deprecated do - @string.html_safe! - assert @string.html_safe? - end - end - - test "Marking a string safe returns the string using html_safe!" do - assert_deprecated do - assert_equal @string, @string.html_safe! - end - end - - test "Adding a safe string to another safe string returns a safe string using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @string.html_safe! - @combination = @other_string + @string - - assert_equal "otherhello", @combination - assert @combination.html_safe? - end - end - - test "Adding an unsafe string to a safe string returns an unsafe string using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @combination = @other_string + "<foo>" - @other_combination = @string + "<foo>" - - assert_equal "other<foo>", @combination - assert_equal "hello<foo>", @other_combination - - assert !@combination.html_safe? - assert !@other_combination.html_safe? - end - end - - test "Concatting safe onto unsafe yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other" - @string.html_safe! - - @other_string.concat(@string) - assert !@other_string.html_safe? - end - end - - test "Concatting unsafe onto safe yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - string = @other_string.concat("<foo>") - assert_equal "other<foo>", string - assert !string.html_safe? - end - end - - test "Concatting safe onto safe yields safe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @string.html_safe! - - @other_string.concat(@string) - assert @other_string.html_safe? - end - end - - test "Concatting safe onto unsafe with << yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other" - @string.html_safe! - - @other_string << @string - assert !@other_string.html_safe? - end - end - - test "Concatting unsafe onto safe with << yields unsafe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - string = @other_string << "<foo>" - assert_equal "other<foo>", string - assert !string.html_safe? - end - end - - test "Concatting safe onto safe with << yields safe using html_safe!" do - assert_deprecated do - @other_string = "other".html_safe! - @string.html_safe! - - @other_string << @string - assert @other_string.html_safe? - end - end - - test "Concatting a fixnum to safe always yields safe using html_safe!" do - assert_deprecated do - @string.html_safe! - @string.concat(13) - assert_equal "hello".concat(13), @string - assert @string.html_safe? - end - end -end diff --git a/vendor/plugins/rails_xss/test/erb_util_test.rb b/vendor/plugins/rails_xss/test/erb_util_test.rb deleted file mode 100644 index 9a04d38..0000000 --- a/vendor/plugins/rails_xss/test/erb_util_test.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'test_helper' - -class ErbUtilTest < Test::Unit::TestCase - include ERB::Util - - ERB::Util::HTML_ESCAPE.each do |given, expected| - define_method "test_html_escape_#{expected.gsub(/\W/, '')}" do - assert_equal expected, html_escape(given) - end - - unless given == '"' - define_method "test_json_escape_#{expected.gsub(/\W/, '')}" do - assert_equal ERB::Util::JSON_ESCAPE[given], json_escape(given) - end - end - end - - def test_html_escape_is_html_safe - escaped = h("<p>") - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - def test_html_escape_passes_html_escpe_unmodified - escaped = h("<p>".html_safe) - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - def test_rest_in_ascii - (0..127).to_a.map {|int| int.chr }.each do |chr| - next if %w(& " < >).include?(chr) - assert_equal chr, html_escape(chr) - end - end -end diff --git a/vendor/plugins/rails_xss/test/form_helper_test.rb b/vendor/plugins/rails_xss/test/form_helper_test.rb deleted file mode 100644 index 0503050..0000000 --- a/vendor/plugins/rails_xss/test/form_helper_test.rb +++ /dev/null @@ -1,1447 +0,0 @@ -require 'test_helper' - -silence_warnings do - Post = Struct.new(:title, :author_name, :body, :secret, :written_on, :cost) - Post.class_eval do - alias_method :title_before_type_cast, :title unless respond_to?(:title_before_type_cast) - alias_method :body_before_type_cast, :body unless respond_to?(:body_before_type_cast) - alias_method :author_name_before_type_cast, :author_name unless respond_to?(:author_name_before_type_cast) - alias_method :secret?, :secret - - def new_record=(boolean) - @new_record = boolean - end - - def new_record? - @new_record - end - - attr_accessor :author - def author_attributes=(attributes); end - - attr_accessor :comments - def comments_attributes=(attributes); end - - attr_accessor :tags - def tags_attributes=(attributes); end - end - - class Comment - attr_reader :id - attr_reader :post_id - def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end - def save; @id = 1; @post_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def name - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - - attr_accessor :relevances - def relevances_attributes=(attributes); end - - end - - class Tag - attr_reader :id - attr_reader :post_id - def initialize(id = nil, post_id = nil); @id, @post_id = id, post_id end - def save; @id = 1; @post_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def value - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - - attr_accessor :relevances - def relevances_attributes=(attributes); end - - end - - class CommentRelevance - attr_reader :id - attr_reader :comment_id - def initialize(id = nil, comment_id = nil); @id, @comment_id = id, comment_id end - def save; @id = 1; @comment_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def value - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - end - - class TagRelevance - attr_reader :id - attr_reader :tag_id - def initialize(id = nil, tag_id = nil); @id, @tag_id = id, tag_id end - def save; @id = 1; @tag_id = 1 end - def new_record?; @id.nil? end - def to_param; @id; end - def value - @id.nil? ? "new #{self.class.name.downcase}" : "#{self.class.name.downcase} ##{@id}" - end - end - - class Author < Comment - attr_accessor :post - def post_attributes=(attributes); end - end -end - -class FormHelperTest < ActionView::TestCase - tests ActionView::Helpers::FormHelper - - def setup - super - - # Create "label" locale for testing I18n label helpers - I18n.backend.store_translations 'label', { - :helpers => { - :label => { - :post => { - :body => "Write entire text here" - } - } - } - } - - @post = Post.new - @comment = Comment.new - def @post.errors() - Class.new{ - def on(field); "can't be empty" if field == "author_name"; end - def empty?() false end - def count() 1 end - def full_messages() [ "Author name can't be empty" ] end - }.new - end - def @post.id; 123; end - def @post.id_before_type_cast; 123; end - def @post.to_param; '123'; end - - @post.title = "Hello World" - @post.author_name = "" - @post.body = "Back to the hill and over it again!" - @post.secret = 1 - @post.written_on = Date.new(2004, 6, 15) - - def Post.human_attribute_name(attribute) - attribute.to_s == "cost" ? "Total cost" : attribute.to_s.humanize - end - - @controller = Class.new do - attr_reader :url_for_options - def url_for(options) - @url_for_options = options - "http://www.example.com" - end - end - @controller = @controller.new - end - - def test_label - assert_dom_equal('<label for="post_title">Title</label>', label("post", "title")) - assert_dom_equal('<label for="post_title">The title goes here</label>', label("post", "title", "The title goes here")) - assert_dom_equal( - '<label class="title_label" for="post_title">Title</label>', - label("post", "title", nil, :class => 'title_label') - ) - assert_dom_equal('<label for="post_secret">Secret?</label>', label("post", "secret?")) - end - - def test_label_with_symbols - assert_dom_equal('<label for="post_title">Title</label>', label(:post, :title)) - assert_dom_equal('<label for="post_secret">Secret?</label>', label(:post, :secret?)) - end - - def test_label_with_locales_strings - old_locale, I18n.locale = I18n.locale, :label - assert_dom_equal('<label for="post_body">Write entire text here</label>', label("post", "body")) - ensure - I18n.locale = old_locale - end - - def test_label_with_human_attribute_name - old_locale, I18n.locale = I18n.locale, :label - assert_dom_equal('<label for="post_cost">Total cost</label>', label(:post, :cost)) - ensure - I18n.locale = old_locale - end - - def test_label_with_locales_symbols - old_locale, I18n.locale = I18n.locale, :label - assert_dom_equal('<label for="post_body">Write entire text here</label>', label(:post, :body)) - ensure - I18n.locale = old_locale - end - - def test_label_with_for_attribute_as_symbol - assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, :for => "my_for")) - end - - def test_label_with_for_attribute_as_string - assert_dom_equal('<label for="my_for">Title</label>', label(:post, :title, nil, "for" => "my_for")) - end - - def test_label_with_id_attribute_as_symbol - assert_dom_equal('<label for="post_title" id="my_id">Title</label>', label(:post, :title, nil, :id => "my_id")) - end - - def test_label_with_id_attribute_as_string - assert_dom_equal('<label for="post_title" id="my_id">Title</label>', label(:post, :title, nil, "id" => "my_id")) - end - - def test_label_with_for_and_id_attributes_as_symbol - assert_dom_equal('<label for="my_for" id="my_id">Title</label>', label(:post, :title, nil, :for => "my_for", :id => "my_id")) - end - - def test_label_with_for_and_id_attributes_as_string - assert_dom_equal('<label for="my_for" id="my_id">Title</label>', label(:post, :title, nil, "for" => "my_for", "id" => "my_id")) - end - - def test_label_for_radio_buttons_with_value - assert_dom_equal('<label for="post_title_great_title">The title goes here</label>', label("post", "title", "The title goes here", :value => "great_title")) - assert_dom_equal('<label for="post_title_great_title">The title goes here</label>', label("post", "title", "The title goes here", :value => "great title")) - end - - def test_text_field - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title") - ) - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="password" value="Hello World" />', password_field("post", "title") - ) - assert_dom_equal( - '<input id="person_name" name="person[name]" size="30" type="password" />', password_field("person", "name") - ) - end - - def test_text_field_with_escapes - @post.title = "<b>Hello World</b>" - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="<b>Hello World</b>" />', text_field("post", "title") - ) - end - - def test_text_field_with_html_entities - @post.title = "The HTML Entity for & is &" - assert_dom_equal( - '<input id="post_title" name="post[title]" size="30" type="text" value="The HTML Entity for & is &amp;" />', - text_field("post", "title") - ) - end - - def test_text_field_with_options - expected = '<input id="post_title" name="post[title]" size="35" type="text" value="Hello World" />' - assert_dom_equal expected, text_field("post", "title", "size" => 35) - assert_dom_equal expected, text_field("post", "title", :size => 35) - end - - def test_text_field_assuming_size - expected = '<input id="post_title" maxlength="35" name="post[title]" size="35" type="text" value="Hello World" />' - assert_dom_equal expected, text_field("post", "title", "maxlength" => 35) - assert_dom_equal expected, text_field("post", "title", :maxlength => 35) - end - - def test_text_field_removing_size - expected = '<input id="post_title" maxlength="35" name="post[title]" type="text" value="Hello World" />' - assert_dom_equal expected, text_field("post", "title", "maxlength" => 35, "size" => nil) - assert_dom_equal expected, text_field("post", "title", :maxlength => 35, :size => nil) - end - - def test_text_field_doesnt_change_param_values - object_name = 'post[]' - expected = '<input id="post_123_title" name="post[123][title]" size="30" type="text" value="Hello World" />' - assert_equal expected, text_field(object_name, "title") - assert_equal object_name, "post[]" - end - - def test_hidden_field - assert_dom_equal '<input id="post_title" name="post[title]" type="hidden" value="Hello World" />', - hidden_field("post", "title") - assert_dom_equal '<input id="post_secret" name="post[secret]" type="hidden" value="1" />', - hidden_field("post", "secret?") - end - - def test_hidden_field_with_escapes - @post.title = "<b>Hello World</b>" - assert_dom_equal '<input id="post_title" name="post[title]" type="hidden" value="<b>Hello World</b>" />', - hidden_field("post", "title") - end - - def test_text_field_with_options - assert_dom_equal '<input id="post_title" name="post[title]" type="hidden" value="Something Else" />', - hidden_field("post", "title", :value => "Something Else") - end - - def test_check_box - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - @post.secret = 0 - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret" ,{"checked"=>"checked"}) - ) - @post.secret = true - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret?") - ) - - @post.secret = ['0'] - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - @post.secret = ['1'] - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret") - ) - end - - def test_check_box_with_explicit_checked_and_unchecked_values - @post.secret = "on" - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="off" /><input checked="checked" id="post_secret" name="post[secret]" type="checkbox" value="on" />', - check_box("post", "secret", {}, "on", "off") - ) - end - - def test_checkbox_disabled_still_submits_checked_value - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="1" /><input checked="checked" disabled="disabled" id="post_secret" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret", { :disabled => :true }) - ) - end - - def test_radio_button - assert_dom_equal('<input checked="checked" id="post_title_hello_world" name="post[title]" type="radio" value="Hello World" />', - radio_button("post", "title", "Hello World") - ) - assert_dom_equal('<input id="post_title_goodbye_world" name="post[title]" type="radio" value="Goodbye World" />', - radio_button("post", "title", "Goodbye World") - ) - assert_dom_equal('<input id="item_subobject_title_inside_world" name="item[subobject][title]" type="radio" value="inside world"/>', - radio_button("item[subobject]", "title", "inside world") - ) - end - - def test_radio_button_is_checked_with_integers - assert_dom_equal('<input checked="checked" id="post_secret_1" name="post[secret]" type="radio" value="1" />', - radio_button("post", "secret", "1") - ) - end - - def test_radio_button_respects_passed_in_id - assert_dom_equal('<input checked="checked" id="foo" name="post[secret]" type="radio" value="1" />', - radio_button("post", "secret", "1", :id=>"foo") - ) - end - - def test_radio_button_with_booleans - assert_dom_equal('<input id="post_secret_true" name="post[secret]" type="radio" value="true" />', - radio_button("post", "secret", true) - ) - - assert_dom_equal('<input id="post_secret_false" name="post[secret]" type="radio" value="false" />', - radio_button("post", "secret", false) - ) - end - - def test_text_area - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to the hill and over it again!</textarea>', - text_area("post", "body") - ) - end - - def test_text_area_with_escapes - @post.body = "Back to <i>the</i> hill and over it again!" - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Back to <i>the</i> hill and over it again!</textarea>', - text_area("post", "body") - ) - end - - def test_text_area_with_alternate_value - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">Testing alternate values.</textarea>', - text_area("post", "body", :value => 'Testing alternate values.') - ) - end - - def test_text_area_with_html_entities - @post.body = "The HTML Entity for & is &" - assert_dom_equal( - '<textarea cols="40" id="post_body" name="post[body]" rows="20">The HTML Entity for & is &amp;</textarea>', - text_area("post", "body") - ) - end - - def test_text_area_with_size_option - assert_dom_equal( - '<textarea cols="183" id="post_body" name="post[body]" rows="820">Back to the hill and over it again!</textarea>', - text_area("post", "body", :size => "183x820") - ) - end - - def test_explicit_name - assert_dom_equal( - '<input id="post_title" name="dont guess" size="30" type="text" value="Hello World" />', text_field("post", "title", "name" => "dont guess") - ) - assert_dom_equal( - '<textarea cols="40" id="post_body" name="really!" rows="20">Back to the hill and over it again!</textarea>', - text_area("post", "body", "name" => "really!") - ) - assert_dom_equal( - '<input name="i mean it" type="hidden" value="0" /><input checked="checked" id="post_secret" name="i mean it" type="checkbox" value="1" />', - check_box("post", "secret", "name" => "i mean it") - ) - assert_dom_equal text_field("post", "title", "name" => "dont guess"), - text_field("post", "title", :name => "dont guess") - assert_dom_equal text_area("post", "body", "name" => "really!"), - text_area("post", "body", :name => "really!") - assert_dom_equal check_box("post", "secret", "name" => "i mean it"), - check_box("post", "secret", :name => "i mean it") - end - - def test_explicit_id - assert_dom_equal( - '<input id="dont guess" name="post[title]" size="30" type="text" value="Hello World" />', text_field("post", "title", "id" => "dont guess") - ) - assert_dom_equal( - '<textarea cols="40" id="really!" name="post[body]" rows="20">Back to the hill and over it again!</textarea>', - text_area("post", "body", "id" => "really!") - ) - assert_dom_equal( - '<input name="post[secret]" type="hidden" value="0" /><input checked="checked" id="i mean it" name="post[secret]" type="checkbox" value="1" />', - check_box("post", "secret", "id" => "i mean it") - ) - assert_dom_equal text_field("post", "title", "id" => "dont guess"), - text_field("post", "title", :id => "dont guess") - assert_dom_equal text_area("post", "body", "id" => "really!"), - text_area("post", "body", :id => "really!") - assert_dom_equal check_box("post", "secret", "id" => "i mean it"), - check_box("post", "secret", :id => "i mean it") - end - - def test_auto_index - pid = @post.id - assert_dom_equal( - "<label for=\"post_#{pid}_title\">Title</label>", - label("post[]", "title") - ) - assert_dom_equal( - "<input id=\"post_#{pid}_title\" name=\"post[#{pid}][title]\" size=\"30\" type=\"text\" value=\"Hello World\" />", text_field("post[]","title") - ) - assert_dom_equal( - "<textarea cols=\"40\" id=\"post_#{pid}_body\" name=\"post[#{pid}][body]\" rows=\"20\">Back to the hill and over it again!</textarea>", - text_area("post[]", "body") - ) - assert_dom_equal( - "<input name=\"post[#{pid}][secret]\" type=\"hidden\" value=\"0\" /><input checked=\"checked\" id=\"post_#{pid}_secret\" name=\"post[#{pid}][secret]\" type=\"checkbox\" value=\"1\" />", - check_box("post[]", "secret") - ) - assert_dom_equal( -"<input checked=\"checked\" id=\"post_#{pid}_title_hello_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Hello World\" />", - radio_button("post[]", "title", "Hello World") - ) - assert_dom_equal("<input id=\"post_#{pid}_title_goodbye_world\" name=\"post[#{pid}][title]\" type=\"radio\" value=\"Goodbye World\" />", - radio_button("post[]", "title", "Goodbye World") - ) - end - - def test_form_for - form_for(:post, @post, :html => { :id => 'create-post' }) do |f| - concat f.label(:title) - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - concat f.submit('Create post') - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<label for='post_title'>Title</label>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "<input name='commit' id='post_submit' type='submit' value='Create post' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_method - form_for(:post, @post, :html => { :id => 'create-post', :method => :put }) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<div style='margin:0;padding:0;display:inline'><input name='_method' type='hidden' value='put' /></div>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_without_object - form_for(:post, :html => { :id => 'create-post' }) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_index - form_for("post[]", @post) do |f| - concat f.label(:title) - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<label for=\"post_123_title\">Title</label>" + - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' type='hidden' value='0' />" + - "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_nil_index_option_override - form_for("post[]", @post, :index => nil) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + - "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[][secret]' type='hidden' value='0' />" + - "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for - form_for(:post, @post) do |f| - f.fields_for(:comment, @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[comment][title]' size='30' type='text' id='post_comment_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_nested_collections - form_for('post[]', @post) do |f| - concat f.text_field(:title) - f.fields_for('comment[]', @comment) do |c| - concat c.text_field(:name) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<input name='post[123][comment][][name]' size='30' type='text' id='post_123_comment__name' value='new comment' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_and_parent_fields - form_for('post', @post, :index => 1) do |c| - concat c.text_field(:title) - c.fields_for('comment', @comment, :index => 1) do |r| - concat r.text_field(:name) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][title]' size='30' type='text' id='post_1_title' value='Hello World' />" + - "<input name='post[1][comment][1][name]' size='30' type='text' id='post_1_comment_1_name' value='new comment' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_index_and_nested_fields_for - form_for(:post, @post, :index => 1) do |f| - f.fields_for(:comment, @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][comment][title]' size='30' type='text' id='post_1_comment_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_on_both - form_for(:post, @post, :index => 1) do |f| - f.fields_for(:comment, @post, :index => 5) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][comment][5][title]' size='30' type='text' id='post_1_comment_5_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_auto_index - form_for("post[]", @post) do |f| - f.fields_for(:comment, @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][comment][title]' size='30' type='text' id='post_123_comment_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_radio_button - form_for(:post, @post) do |f| - f.fields_for(:comment, @post, :index => 5) do |c| - concat c.radio_button(:title, "hello") - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[comment][5][title]' type='radio' id='post_comment_5_title_hello' value='hello' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_auto_index_on_both - form_for("post[]", @post) do |f| - f.fields_for("comment[]", @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][comment][123][title]' size='30' type='text' id='post_123_comment_123_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_index_and_auto_index - form_for("post[]", @post) do |f| - f.fields_for(:comment, @post, :index => 5) do |c| - concat c.text_field(:title) - end - end - - form_for(:post, @post, :index => 1) do |f| - f.fields_for("comment[]", @post) do |c| - concat c.text_field(:title) - end - end - - expected = "<form action='http://www.example.com' method='post'>" + - "<input name='post[123][comment][5][title]' size='30' type='text' id='post_123_comment_5_title' value='Hello World' />" + - "</form>" + - "<form action='http://www.example.com' method='post'>" + - "<input name='post[1][comment][123][title]' size='30' type='text' id='post_1_comment_123_title' value='Hello World' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_a_new_record_on_a_nested_attributes_one_to_one_association - @post.author = Author.new - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:author) do |af| - concat af.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="new author" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_explicitly_passed_object_on_a_nested_attributes_one_to_one_association - form_for(:post, @post) do |f| - f.fields_for(:author, Author.new(123)) do |af| - assert_not_nil af.object - assert_equal 123, af.object.id - end - end - end - - def test_nested_fields_for_with_an_existing_record_on_a_nested_attributes_one_to_one_association - @post.author = Author.new(321) - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:author) do |af| - concat af.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_one_to_one_association_with_explicit_hidden_field_placement - @post.author = Author.new(321) - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:author) do |af| - concat af.hidden_field(:id) - concat af.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_author_attributes_id" name="post[author_attributes][id]" type="hidden" value="321" />' + - '<input id="post_author_attributes_name" name="post[author_attributes][name]" size="30" type="text" value="author #321" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association - @post.comments = Array.new(2) { |id| Comment.new(id + 1) } - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + - '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_nested_attributes_collection_association_with_explicit_hidden_field_placement - @post.comments = Array.new(2) { |id| Comment.new(id + 1) } - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.hidden_field(:id) - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_new_records_on_a_nested_attributes_collection_association - @post.comments = [Comment.new, Comment.new] - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="new comment" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_and_new_records_on_a_nested_attributes_collection_association - @post.comments = [Comment.new(321), Comment.new] - - form_for(:post, @post) do |f| - concat f.text_field(:title) - @post.comments.each do |comment| - f.fields_for(:comments, comment) do |cf| - concat cf.text_field(:name) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_an_empty_supplied_attributes_collection - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:comments, []) do |cf| - concat cf.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_with_existing_records_on_a_supplied_nested_attributes_collection - @post.comments = Array.new(2) { |id| Comment.new(id + 1) } - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:comments, @post.comments) do |cf| - concat cf.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #1" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="1" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="comment #2" />' + - '<input id="post_comments_attributes_1_id" name="post[comments_attributes][1][id]" type="hidden" value="2" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_for_on_a_nested_attributes_collection_association_yields_only_builder - @post.comments = [Comment.new(321), Comment.new] - yielded_comments = [] - - form_for(:post, @post) do |f| - concat f.text_field(:title) - f.fields_for(:comments) do |cf| - concat cf.text_field(:name) - yielded_comments << cf.object - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input name="post[title]" size="30" type="text" id="post_title" value="Hello World" />' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_comments_attributes_1_name" name="post[comments_attributes][1][name]" size="30" type="text" value="new comment" />' + - '</form>' - - assert_dom_equal expected, output_buffer - assert_equal yielded_comments, @post.comments - end - - def test_nested_fields_for_with_child_index_option_override_on_a_nested_attributes_collection_association - @post.comments = [] - - form_for(:post, @post) do |f| - f.fields_for(:comments, Comment.new(321), :child_index => 'abc') do |cf| - concat cf.text_field(:name) - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input id="post_comments_attributes_abc_name" name="post[comments_attributes][abc][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_abc_id" name="post[comments_attributes][abc][id]" type="hidden" value="321" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_nested_fields_uses_unique_indices_for_different_collection_associations - @post.comments = [Comment.new(321)] - @post.tags = [Tag.new(123), Tag.new(456)] - @post.comments[0].relevances = [] - @post.tags[0].relevances = [] - @post.tags[1].relevances = [] - form_for(:post, @post) do |f| - f.fields_for(:comments, @post.comments[0]) do |cf| - concat cf.text_field(:name) - cf.fields_for(:relevances, CommentRelevance.new(314)) do |crf| - concat crf.text_field(:value) - end - end - f.fields_for(:tags, @post.tags[0]) do |tf| - concat tf.text_field(:value) - tf.fields_for(:relevances, TagRelevance.new(3141)) do |trf| - concat trf.text_field(:value) - end - end - f.fields_for('tags', @post.tags[1]) do |tf| - concat tf.text_field(:value) - tf.fields_for(:relevances, TagRelevance.new(31415)) do |trf| - concat trf.text_field(:value) - end - end - end - - expected = '<form action="http://www.example.com" method="post">' + - '<input id="post_comments_attributes_0_name" name="post[comments_attributes][0][name]" size="30" type="text" value="comment #321" />' + - '<input id="post_comments_attributes_0_relevances_attributes_0_value" name="post[comments_attributes][0][relevances_attributes][0][value]" size="30" type="text" value="commentrelevance #314" />' + - '<input id="post_comments_attributes_0_relevances_attributes_0_id" name="post[comments_attributes][0][relevances_attributes][0][id]" type="hidden" value="314" />' + - '<input id="post_comments_attributes_0_id" name="post[comments_attributes][0][id]" type="hidden" value="321" />' + - '<input id="post_tags_attributes_0_value" name="post[tags_attributes][0][value]" size="30" type="text" value="tag #123" />' + - '<input id="post_tags_attributes_0_relevances_attributes_0_value" name="post[tags_attributes][0][relevances_attributes][0][value]" size="30" type="text" value="tagrelevance #3141" />' + - '<input id="post_tags_attributes_0_relevances_attributes_0_id" name="post[tags_attributes][0][relevances_attributes][0][id]" type="hidden" value="3141" />' + - '<input id="post_tags_attributes_0_id" name="post[tags_attributes][0][id]" type="hidden" value="123" />' + - '<input id="post_tags_attributes_1_value" name="post[tags_attributes][1][value]" size="30" type="text" value="tag #456" />' + - '<input id="post_tags_attributes_1_relevances_attributes_0_value" name="post[tags_attributes][1][relevances_attributes][0][value]" size="30" type="text" value="tagrelevance #31415" />' + - '<input id="post_tags_attributes_1_relevances_attributes_0_id" name="post[tags_attributes][1][relevances_attributes][0][id]" type="hidden" value="31415" />' + - '<input id="post_tags_attributes_1_id" name="post[tags_attributes][1][id]" type="hidden" value="456" />' + - '</form>' - - assert_dom_equal expected, output_buffer - end - - def test_fields_for - fields_for(:post, @post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_index - fields_for("post[]", @post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[123][title]' size='30' type='text' id='post_123_title' value='Hello World' />" + - "<textarea name='post[123][body]' id='post_123_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[123][secret]' type='hidden' value='0' />" + - "<input name='post[123][secret]' checked='checked' type='checkbox' id='post_123_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_nil_index_option_override - fields_for("post[]", @post, :index => nil) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[][title]' size='30' type='text' id='post__title' value='Hello World' />" + - "<textarea name='post[][body]' id='post__body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[][secret]' type='hidden' value='0' />" + - "<input name='post[][secret]' checked='checked' type='checkbox' id='post__secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_index_option_override - fields_for("post[]", @post, :index => "abc") do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[abc][title]' size='30' type='text' id='post_abc_title' value='Hello World' />" + - "<textarea name='post[abc][body]' id='post_abc_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[abc][secret]' type='hidden' value='0' />" + - "<input name='post[abc][secret]' checked='checked' type='checkbox' id='post_abc_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_without_object - fields_for(:post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_only_object - fields_for(@post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[secret]' type='hidden' value='0' />" + - "<input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' />" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_object_with_bracketed_name - fields_for("author[post]", @post) do |f| - concat f.label(:title) - concat f.text_field(:title) - end - - assert_dom_equal "<label for=\"author_post_title\">Title</label>" + - "<input name='author[post][title]' size='30' type='text' id='author_post_title' value='Hello World' />", - output_buffer - end - - def test_fields_for_object_with_bracketed_name_and_index - fields_for("author[post]", @post, :index => 1) do |f| - concat f.label(:title) - concat f.text_field(:title) - end - - assert_dom_equal "<label for=\"author_post_1_title\">Title</label>" + - "<input name='author[post][1][title]' size='30' type='text' id='author_post_1_title' value='Hello World' />", - output_buffer - end - - def test_form_builder_does_not_have_form_for_method - assert ! ActionView::Helpers::FormBuilder.instance_methods.include?('form_for') - end - - def test_form_for_and_fields_for - form_for(:post, @post, :html => { :id => 'create-post' }) do |post_form| - concat post_form.text_field(:title) - concat post_form.text_area(:body) - - fields_for(:parent_post, @post) do |parent_fields| - concat parent_fields.check_box(:secret) - end - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='parent_post[secret]' type='hidden' value='0' />" + - "<input name='parent_post[secret]' checked='checked' type='checkbox' id='parent_post_secret' value='1' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_and_fields_for_with_object - form_for(:post, @post, :html => { :id => 'create-post' }) do |post_form| - concat post_form.text_field(:title) - concat post_form.text_area(:body) - - post_form.fields_for(@comment) do |comment_fields| - concat comment_fields.text_field(:name) - end - end - - expected = - "<form action='http://www.example.com' id='create-post' method='post'>" + - "<input name='post[title]' size='30' type='text' id='post_title' value='Hello World' />" + - "<textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea>" + - "<input name='post[comment][name]' type='text' id='post_comment_name' value='new comment' size='30' />" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - class LabelledFormBuilder < ActionView::Helpers::FormBuilder - (field_helpers - %w(hidden_field)).each do |selector| - src, line = <<-END_SRC, __LINE__ + 1 - def #{selector}(field, *args, &proc) - ("<label for='\#{field}'>\#{field.to_s.humanize}:</label> " + super + "<br/>").html_safe - end - END_SRC - class_eval src, __FILE__, line - end - end - - def test_form_for_with_labelled_builder - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_default_form_builder - old_default_form_builder, ActionView::Base.default_form_builder = - ActionView::Base.default_form_builder, LabelledFormBuilder - - form_for(:post, @post) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<form action='http://www.example.com' method='post'>" + - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + - "</form>" - - assert_dom_equal expected, output_buffer - ensure - ActionView::Base.default_form_builder = old_default_form_builder - end - - def test_default_form_builder_with_active_record_helpers - form_for(:post, @post) do |f| - concat f.error_message_on('author_name') - concat f.error_messages - end - - expected = %(<form action='http://www.example.com' method='post'>) + - %(<div class='formError'>can't be empty</div>) + - %(<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited this post from being saved</h2><p>There were problems with the following fields:</p><ul><li>Author name can't be empty</li></ul></div>) + - %(</form>) - - assert_dom_equal expected, output_buffer - - end - - def test_default_form_builder_no_instance_variable - post = @post - @post = nil - - form_for(:post, post) do |f| - concat f.error_message_on('author_name') - concat f.error_messages - end - - expected = %(<form action='http://www.example.com' method='post'>) + - %(<div class='formError'>can't be empty</div>) + - %(<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited this post from being saved</h2><p>There were problems with the following fields:</p><ul><li>Author name can't be empty</li></ul></div>) + - %(</form>) - - assert_dom_equal expected, output_buffer - - end - - def test_default_form_builder_without_object - - form_for(:post) do |f| - concat f.error_message_on('author_name') - concat f.error_messages - end - - expected = %(<form action='http://www.example.com' method='post'>) + - %(<div class='formError'>can't be empty</div>) + - %(<div class="errorExplanation" id="errorExplanation"><h2>1 error prohibited this post from being saved</h2><p>There were problems with the following fields:</p><ul><li>Author name can't be empty</li></ul></div>) + - %(</form>) - - assert_dom_equal expected, output_buffer - - end - - # Perhaps this test should be moved to prototype helper tests. - def test_remote_form_for_with_labelled_builder - self.extend ActionView::Helpers::PrototypeHelper - - remote_form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - %(<form action="http://www.example.com" onsubmit="new Ajax.Request('http://www.example.com', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;" method="post">) + - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" + - "</form>" - - assert_dom_equal expected, output_buffer - end - - def test_fields_for_with_labelled_builder - fields_for(:post, @post, :builder => LabelledFormBuilder) do |f| - concat f.text_field(:title) - concat f.text_area(:body) - concat f.check_box(:secret) - end - - expected = - "<label for='title'>Title:</label> <input name='post[title]' size='30' type='text' id='post_title' value='Hello World' /><br/>" + - "<label for='body'>Body:</label> <textarea name='post[body]' id='post_body' rows='20' cols='40'>Back to the hill and over it again!</textarea><br/>" + - "<label for='secret'>Secret:</label> <input name='post[secret]' type='hidden' value='0' /><input name='post[secret]' checked='checked' type='checkbox' id='post_secret' value='1' /><br/>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_labelled_builder_with_nested_fields_for_without_options_hash - klass = nil - - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - f.fields_for(:comments, Comment.new) do |nested_fields| - klass = nested_fields.class - '' - end - end - - assert_equal LabelledFormBuilder, klass - end - - def test_form_for_with_labelled_builder_with_nested_fields_for_with_options_hash - klass = nil - - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - f.fields_for(:comments, Comment.new, :index => 'foo') do |nested_fields| - klass = nested_fields.class - '' - end - end - - assert_equal LabelledFormBuilder, klass - end - - class LabelledFormBuilderSubclass < LabelledFormBuilder; end - - def test_form_for_with_labelled_builder_with_nested_fields_for_with_custom_builder - klass = nil - - form_for(:post, @post, :builder => LabelledFormBuilder) do |f| - f.fields_for(:comments, Comment.new, :builder => LabelledFormBuilderSubclass) do |nested_fields| - klass = nested_fields.class - '' - end - end - - assert_equal LabelledFormBuilderSubclass, klass - end - - def test_form_for_with_html_options_adds_options_to_form_tag - form_for(:post, @post, :html => {:id => 'some_form', :class => 'some_class'}) do |f| end - expected = "<form action=\"http://www.example.com\" class=\"some_class\" id=\"some_form\" method=\"post\"></form>" - - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_string_url_option - form_for(:post, @post, :url => 'http://www.otherdomain.com') do |f| end - - assert_equal '<form action="http://www.otherdomain.com" method="post"></form>', output_buffer - end - - def test_form_for_with_hash_url_option - form_for(:post, @post, :url => {:controller => 'controller', :action => 'action'}) do |f| end - - assert_equal 'controller', @controller.url_for_options[:controller] - assert_equal 'action', @controller.url_for_options[:action] - end - - def test_form_for_with_record_url_option - form_for(:post, @post, :url => @post) do |f| end - - expected = "<form action=\"/posts/123\" method=\"post\"></form>" - assert_equal expected, output_buffer - end - - def test_form_for_with_existing_object - form_for(@post) do |f| end - - expected = "<form action=\"/posts/123\" class=\"edit_post\" id=\"edit_post_123\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"_method\" type=\"hidden\" value=\"put\" /></div></form>" - assert_equal expected, output_buffer - end - - def test_form_for_with_new_object - post = Post.new - post.new_record = true - def post.id() nil end - - form_for(post) do |f| end - - expected = "<form action=\"/posts\" class=\"new_post\" id=\"new_post\" method=\"post\"></form>" - assert_equal expected, output_buffer - end - - def test_form_for_with_existing_object_in_list - @post.new_record = false - @comment.save - - form_for([@post, @comment]) {} - - expected = %(<form action="#{comment_path(@post, @comment)}" class="edit_comment" id="edit_comment_1" method="post"><div style="margin:0;padding:0;display:inline"><input name="_method" type="hidden" value="put" /></div></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_new_object_in_list - @post.new_record = false - - form_for([@post, @comment]) {} - - expected = %(<form action="#{comments_path(@post)}" class="new_comment" id="new_comment" method="post"></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_existing_object_and_namespace_in_list - @post.new_record = false - @comment.save - - form_for([:admin, @post, @comment]) {} - - expected = %(<form action="#{admin_comment_path(@post, @comment)}" class="edit_comment" id="edit_comment_1" method="post"><div style="margin:0;padding:0;display:inline"><input name="_method" type="hidden" value="put" /></div></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_new_object_and_namespace_in_list - @post.new_record = false - - form_for([:admin, @post, @comment]) {} - - expected = %(<form action="#{admin_comments_path(@post)}" class="new_comment" id="new_comment" method="post"></form>) - assert_dom_equal expected, output_buffer - end - - def test_form_for_with_existing_object_and_custom_url - form_for(@post, :url => "/super_posts") do |f| end - - expected = "<form action=\"/super_posts\" class=\"edit_post\" id=\"edit_post_123\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"_method\" type=\"hidden\" value=\"put\" /></div></form>" - assert_equal expected, output_buffer - end - - def test_remote_form_for_with_html_options_adds_options_to_form_tag - self.extend ActionView::Helpers::PrototypeHelper - - remote_form_for(:post, @post, :html => {:id => 'some_form', :class => 'some_class'}) do |f| end - expected = "<form action=\"http://www.example.com\" class=\"some_class\" id=\"some_form\" method=\"post\" onsubmit=\"new Ajax.Request('http://www.example.com', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\"></form>" - - assert_dom_equal expected, output_buffer - end - - protected - def comments_path(post) - "/posts/#{post.id}/comments" - end - alias_method :post_comments_path, :comments_path - - def comment_path(post, comment) - "/posts/#{post.id}/comments/#{comment.id}" - end - alias_method :post_comment_path, :comment_path - - def admin_comments_path(post) - "/admin/posts/#{post.id}/comments" - end - alias_method :admin_post_comments_path, :admin_comments_path - - def admin_comment_path(post, comment) - "/admin/posts/#{post.id}/comments/#{comment.id}" - end - alias_method :admin_post_comment_path, :admin_comment_path - - def posts_path - "/posts" - end - - def post_path(post) - "/posts/#{post.id}" - end - - def protect_against_forgery? - false - end -end diff --git a/vendor/plugins/rails_xss/test/form_tag_helper_test.rb b/vendor/plugins/rails_xss/test/form_tag_helper_test.rb deleted file mode 100644 index 41eecee..0000000 --- a/vendor/plugins/rails_xss/test/form_tag_helper_test.rb +++ /dev/null @@ -1,354 +0,0 @@ -require 'test_helper' - -class FormTagHelperTest < ActionView::TestCase - def setup - @controller = Class.new do - def url_for(options) - "http://www.example.com" - end - end - @controller = @controller.new - end - - VALID_HTML_ID = /^[A-Za-z][-_:.A-Za-z0-9]*$/ # see http://www.w3.org/TR/html4/types.html#type-name - - def test_check_box_tag - actual = check_box_tag "admin" - expected = %(<input id="admin" name="admin" type="checkbox" value="1" />) - assert_dom_equal expected, actual - end - - def test_check_box_tag_id_sanitized - label_elem = root_elem(check_box_tag("project[2][admin]")) - assert_match VALID_HTML_ID, label_elem['id'] - end - - def test_form_tag - actual = form_tag - expected = %(<form action="http://www.example.com" method="post">) - assert_dom_equal expected, actual - end - - def test_form_tag_multipart - actual = form_tag({}, { 'multipart' => true }) - expected = %(<form action="http://www.example.com" enctype="multipart/form-data" method="post">) - assert_dom_equal expected, actual - end - - def test_form_tag_with_method_put - actual = form_tag({}, { :method => :put }) - expected = %(<form action="http://www.example.com" method="post"><div style='margin:0;padding:0;display:inline'><input type="hidden" name="_method" value="put" /></div>) - assert_dom_equal expected, actual - end - - def test_form_tag_with_method_delete - actual = form_tag({}, { :method => :delete }) - expected = %(<form action="http://www.example.com" method="post"><div style='margin:0;padding:0;display:inline'><input type="hidden" name="_method" value="delete" /></div>) - assert_dom_equal expected, actual - end - - def test_form_tag_with_block_in_erb - __in_erb_template = '' - form_tag("http://example.com") { concat "Hello world!" } - - expected = %(<form action="http://example.com" method="post">Hello world!</form>) - assert_dom_equal expected, output_buffer - end - - def test_form_tag_with_block_and_method_in_erb - __in_erb_template = '' - form_tag("http://example.com", :method => :put) { concat "Hello world!" } - - expected = %(<form action="http://example.com" method="post"><div style='margin:0;padding:0;display:inline'><input type="hidden" name="_method" value="put" /></div>Hello world!</form>) - assert_dom_equal expected, output_buffer - end - - def test_hidden_field_tag - actual = hidden_field_tag "id", 3 - expected = %(<input id="id" name="id" type="hidden" value="3" />) - assert_dom_equal expected, actual - end - - def test_hidden_field_tag_id_sanitized - input_elem = root_elem(hidden_field_tag("item[][title]")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_file_field_tag - assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" />", file_field_tag("picsplz") - end - - def test_file_field_tag_with_options - assert_dom_equal "<input name=\"picsplz\" type=\"file\" id=\"picsplz\" class=\"pix\"/>", file_field_tag("picsplz", :class => "pix") - end - - def test_password_field_tag - actual = password_field_tag - expected = %(<input id="password" name="password" type="password" />) - assert_dom_equal expected, actual - end - - def test_radio_button_tag - actual = radio_button_tag "people", "david" - expected = %(<input id="people_david" name="people" type="radio" value="david" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("num_people", 5) - expected = %(<input id="num_people_5" name="num_people" type="radio" value="5" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("gender", "m") + radio_button_tag("gender", "f") - expected = %(<input id="gender_m" name="gender" type="radio" value="m" /><input id="gender_f" name="gender" type="radio" value="f" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("opinion", "-1") + radio_button_tag("opinion", "1") - expected = %(<input id="opinion_-1" name="opinion" type="radio" value="-1" /><input id="opinion_1" name="opinion" type="radio" value="1" />) - assert_dom_equal expected, actual - - actual = radio_button_tag("person[gender]", "m") - expected = %(<input id="person_gender_m" name="person[gender]" type="radio" value="m" />) - assert_dom_equal expected, actual - end - - def test_select_tag - actual = select_tag "people", "<option>david</option>".html_safe - expected = %(<select id="people" name="people"><option>david</option></select>) - assert_dom_equal expected, actual - end - - def test_select_tag_with_multiple - actual = select_tag "colors", "<option>Red</option><option>Blue</option><option>Green</option>".html_safe, :multiple => :true - expected = %(<select id="colors" multiple="multiple" name="colors"><option>Red</option><option>Blue</option><option>Green</option></select>) - assert_dom_equal expected, actual - end - - def test_select_tag_disabled - actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :disabled => :true - expected = %(<select id="places" disabled="disabled" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>) - assert_dom_equal expected, actual - end - - def test_select_tag_id_sanitized - input_elem = root_elem(select_tag("project[1]people", "<option>david</option>")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_select_tag_with_array_options - assert_deprecated /array/ do - select_tag "people", ["<option>david</option>"] - end - end - - def test_text_area_tag_size_string - actual = text_area_tag "body", "hello world", "size" => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_size_symbol - actual = text_area_tag "body", "hello world", :size => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40">hello world</textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_should_disregard_size_if_its_given_as_an_integer - actual = text_area_tag "body", "hello world", :size => 20 - expected = %(<textarea id="body" name="body">hello world</textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_id_sanitized - input_elem = root_elem(text_area_tag("item[][description]")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_text_area_tag_escape_content - actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40" - expected = %(<textarea cols="20" id="body" name="body" rows="40"><b>hello world</b></textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_unescaped_content - actual = text_area_tag "body", "<b>hello world</b>", :size => "20x40", :escape => false - expected = %(<textarea cols="20" id="body" name="body" rows="40"><b>hello world</b></textarea>) - assert_dom_equal expected, actual - end - - def test_text_area_tag_unescaped_nil_content - actual = text_area_tag "body", nil, :escape => false - expected = %(<textarea id="body" name="body"></textarea>) - assert_dom_equal expected, actual - end - - def test_text_field_tag - actual = text_field_tag "title", "Hello!" - expected = %(<input id="title" name="title" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_class_string - actual = text_field_tag "title", "Hello!", "class" => "admin" - expected = %(<input class="admin" id="title" name="title" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_size_symbol - actual = text_field_tag "title", "Hello!", :size => 75 - expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_size_string - actual = text_field_tag "title", "Hello!", "size" => "75" - expected = %(<input id="title" name="title" size="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_maxlength_symbol - actual = text_field_tag "title", "Hello!", :maxlength => 75 - expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_maxlength_string - actual = text_field_tag "title", "Hello!", "maxlength" => "75" - expected = %(<input id="title" name="title" maxlength="75" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_disabled - actual = text_field_tag "title", "Hello!", :disabled => :true - expected = %(<input id="title" name="title" disabled="disabled" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_with_multiple_options - actual = text_field_tag "title", "Hello!", :size => 70, :maxlength => 80 - expected = %(<input id="title" name="title" size="70" maxlength="80" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_text_field_tag_id_sanitized - input_elem = root_elem(text_field_tag("item[][title]")) - assert_match VALID_HTML_ID, input_elem['id'] - end - - def test_label_tag_without_text - actual = label_tag "title" - expected = %(<label for="title">Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_with_symbol - actual = label_tag :title - expected = %(<label for="title">Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_with_text - actual = label_tag "title", "My Title" - expected = %(<label for="title">My Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_class_string - actual = label_tag "title", "My Title", "class" => "small_label" - expected = %(<label for="title" class="small_label">My Title</label>) - assert_dom_equal expected, actual - end - - def test_label_tag_id_sanitized - label_elem = root_elem(label_tag("item[title]")) - assert_match VALID_HTML_ID, label_elem['for'] - end - - def test_boolean_options - assert_dom_equal %(<input checked="checked" disabled="disabled" id="admin" name="admin" readonly="readonly" type="checkbox" value="1" />), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes") - assert_dom_equal %(<input checked="checked" id="admin" name="admin" type="checkbox" value="1" />), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil) - assert_dom_equal %(<input type="checkbox" />), tag(:input, :type => "checkbox", :checked => false) - assert_dom_equal %(<select id="people" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => true) - assert_dom_equal %(<select id="people_" multiple="multiple" name="people[]"><option>david</option></select>), select_tag("people[]", "<option>david</option>".html_safe, :multiple => true) - assert_dom_equal %(<select id="people" name="people"><option>david</option></select>), select_tag("people", "<option>david</option>".html_safe, :multiple => nil) - end - - def test_stringify_symbol_keys - actual = text_field_tag "title", "Hello!", :id => "admin" - expected = %(<input id="admin" name="title" type="text" value="Hello!" />) - assert_dom_equal expected, actual - end - - def test_submit_tag - assert_dom_equal( - %(<input name='commit' onclick="if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); }this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Saving...';alert('hello!');result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" type="submit" value="Save" />), - submit_tag("Save", :disable_with => "Saving...", :onclick => "alert('hello!')") - ) - end - - def test_submit_tag_with_no_onclick_options - assert_dom_equal( - %(<input name='commit' onclick="if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); }this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Saving...';result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" type="submit" value="Save" />), - submit_tag("Save", :disable_with => "Saving...") - ) - end - - def test_submit_tag_with_confirmation - assert_dom_equal( - %(<input name='commit' type='submit' value='Save' onclick="if (!confirm('Are you sure?')) return false; return true;"/>), - submit_tag("Save", :confirm => "Are you sure?") - ) - end - - def test_submit_tag_with_confirmation_and_with_disable_with - assert_dom_equal( - %(<input name="commit" onclick="if (!confirm('Are you sure?')) return false; if (window.hiddenCommit) { window.hiddenCommit.setAttribute('value', this.value); }else { hiddenCommit = document.createElement('input');hiddenCommit.type = 'hidden';hiddenCommit.value = this.value;hiddenCommit.name = this.name;this.form.appendChild(hiddenCommit); }this.setAttribute('originalValue', this.value);this.disabled = true;this.value='Saving...';result = (this.form.onsubmit ? (this.form.onsubmit() ? this.form.submit() : false) : this.form.submit());if (result == false) { this.value = this.getAttribute('originalValue');this.disabled = false; }return result;" type="submit" value="Save" />), - submit_tag("Save", :disable_with => "Saving...", :confirm => "Are you sure?") - ) - end - - def test_image_submit_tag_with_confirmation - assert_dom_equal( - %(<input type="image" src="/images/save.gif" onclick="return confirm('Are you sure?');"/>), - image_submit_tag("save.gif", :confirm => "Are you sure?") - ) - end - - def test_pass - assert_equal 1, 1 - end - - def test_field_set_tag_in_erb - __in_erb_template = '' - field_set_tag("Your details") { concat "Hello world!" } - - expected = %(<fieldset><legend>Your details</legend>Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - - self.output_buffer = ''.html_safe - field_set_tag { concat "Hello world!" } - - expected = %(<fieldset>Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - - self.output_buffer = ''.html_safe - field_set_tag('') { concat "Hello world!" } - - expected = %(<fieldset>Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - - self.output_buffer = ''.html_safe - field_set_tag('', :class => 'format') { concat "Hello world!" } - - expected = %(<fieldset class="format">Hello world!</fieldset>) - assert_dom_equal expected, output_buffer - end - - def protect_against_forgery? - false - end - - private - - def root_elem(rendered_content) - HTML::Document.new(rendered_content).root.children[0] - end -end diff --git a/vendor/plugins/rails_xss/test/output_safety_test.rb b/vendor/plugins/rails_xss/test/output_safety_test.rb deleted file mode 100644 index 2e37647..0000000 --- a/vendor/plugins/rails_xss/test/output_safety_test.rb +++ /dev/null @@ -1,115 +0,0 @@ -require 'test_helper' - -class OutputSafetyTest < ActiveSupport::TestCase - def setup - @string = "hello" - @object = Class.new(Object) do - def to_s - "other" - end - end.new - end - - test "A string is unsafe by default" do - assert !@string.html_safe? - end - - test "A string can be marked safe" do - string = @string.html_safe - assert string.html_safe? - end - - test "Marking a string safe returns the string" do - assert_equal @string, @string.html_safe - end - - test "A fixnum is safe by default" do - assert 5.html_safe? - end - - test "An object is unsafe by default" do - assert !@object.html_safe? - end - - test "Adding an object to a safe string returns a safe string" do - string = @string.html_safe - string << @object - - assert_equal "helloother", string - assert string.html_safe? - end - - test "Adding a safe string to another safe string returns a safe string" do - @other_string = "other".html_safe - string = @string.html_safe - @combination = @other_string + string - - assert_equal "otherhello", @combination - assert @combination.html_safe? - end - - test "Adding an unsafe string to a safe string escapes it and returns a safe string" do - @other_string = "other".html_safe - @combination = @other_string + "<foo>" - @other_combination = @string + "<foo>" - - assert_equal "other<foo>", @combination - assert_equal "hello<foo>", @other_combination - - assert @combination.html_safe? - assert !@other_combination.html_safe? - end - - test "Concatting safe onto unsafe yields unsafe" do - @other_string = "other" - - string = @string.html_safe - @other_string.concat(string) - assert !@other_string.html_safe? - end - - test "Concatting unsafe onto safe yields escaped safe" do - @other_string = "other".html_safe - string = @other_string.concat("<foo>") - assert_equal "other<foo>", string - assert string.html_safe? - end - - test "Concatting safe onto safe yields safe" do - @other_string = "other".html_safe - string = @string.html_safe - - @other_string.concat(string) - assert @other_string.html_safe? - end - - test "Concatting safe onto unsafe with << yields unsafe" do - @other_string = "other" - string = @string.html_safe - - @other_string << string - assert !@other_string.html_safe? - end - - test "Concatting unsafe onto safe with << yields escaped safe" do - @other_string = "other".html_safe - string = @other_string << "<foo>" - assert_equal "other<foo>", string - assert string.html_safe? - end - - test "Concatting safe onto safe with << yields safe" do - @other_string = "other".html_safe - string = @string.html_safe - - @other_string << string - assert @other_string.html_safe? - end - - test "Concatting a fixnum to safe always yields safe" do - string = @string.html_safe - string = string.concat(13) - assert_equal "hello".concat(13), string - assert string.html_safe? - end -end diff --git a/vendor/plugins/rails_xss/test/rails_xss_test.rb b/vendor/plugins/rails_xss/test/rails_xss_test.rb deleted file mode 100644 index b6268ba..0000000 --- a/vendor/plugins/rails_xss/test/rails_xss_test.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'test_helper' - -class RailsXssTest < ActiveSupport::TestCase - test "ERB::Util.h should mark its return value as safe and escape it" do - escaped = ERB::Util.h("<p>") - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - test "ERB::Util.h should leave previously safe strings alone " do - # TODO this seems easier to compose and reason about, but - # this should be verified - escaped = ERB::Util.h("<p>".html_safe) - assert_equal "<p>", escaped - assert escaped.html_safe? - end - - test "ERB::Util.h should not implode when passed a non-string" do - assert_nothing_raised do - assert_equal "1", ERB::Util.h(1) - end - end -end diff --git a/vendor/plugins/rails_xss/test/test_helper.rb b/vendor/plugins/rails_xss/test/test_helper.rb deleted file mode 100644 index caecd7f..0000000 --- a/vendor/plugins/rails_xss/test/test_helper.rb +++ /dev/null @@ -1,5 +0,0 @@ -abort 'RAILS_ROOT=/path/to/rails/2.3/app rake test' unless ENV['RAILS_ROOT'] -require File.expand_path('config/environment', ENV['RAILS_ROOT']) -require File.expand_path('../../init', __FILE__) -require 'active_support/test_case' -require 'test/unit' diff --git a/vendor/plugins/rails_xss/test/text_helper_test.rb b/vendor/plugins/rails_xss/test/text_helper_test.rb deleted file mode 100644 index f50be39..0000000 --- a/vendor/plugins/rails_xss/test/text_helper_test.rb +++ /dev/null @@ -1,17 +0,0 @@ -require 'test_helper' - -class TextHelperTest < ActionView::TestCase - - def setup - @controller = Class.new do - attr_accessor :request - def url_for(*args) "http://www.example.com" end - end.new - end - - def test_simple_format_with_escaping_html_options - assert_dom_equal(%(<p class="intro">It's nice to have options.</p>), - simple_format("It's nice to have options.", :class=>"intro")) - end - -end diff --git a/vendor/plugins/recordselect/CHANGELOG b/vendor/plugins/recordselect/CHANGELOG deleted file mode 100644 index 9583fb8..0000000 --- a/vendor/plugins/recordselect/CHANGELOG +++ /dev/null @@ -1,25 +0,0 @@ -1.0 -* record_select_field always searches on the latest string -* R.S. dialog closes on mousedown instead of click (because sometimes clicks are intercepted) -* R.S. layers over <select> boxes in IE 6 -* record_select_field now opens R.S. even when the field loads with focus -* new :onchange option for record_select_field, to observe selection events - -1.0rc1 -* helpers complain if the controller they're configured for doesn't use recordselect -* when using keyboard navigation, hitting "enter" to select a record no longer submits the form -* if text field is empty when dialog is closed, then recordselect will empty the hidden field as well (lets you deselect) -* support for multiple selections (record_multi_select_helper) -* param-based search conditions are smarter - can search numeric fields as well -* using record_select_conditions_from_controller instead of conditions_for_collection. also added a new record_select_includes override method. -* helpers now accept a :class option -* fixed bug with url escaping when helpers were configured with multiple parameters -* new :label configuration option. it's a proc - the default one calls record.to_label (for backwards compatibility). -* cleaned up merge_conditions to use activerecord's sanitize_sql. -* div.record-select-container now has a high z-index so it will by default be visible above other absolutely positioned elements. - -0.9 -stuff - -0.1 -stuff diff --git a/vendor/plugins/recordselect/MIT-LICENSE b/vendor/plugins/recordselect/MIT-LICENSE deleted file mode 100644 index ae724b0..0000000 --- a/vendor/plugins/recordselect/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2007 Lance Ivy - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/plugins/recordselect/README b/vendor/plugins/recordselect/README deleted file mode 100644 index 016edf1..0000000 --- a/vendor/plugins/recordselect/README +++ /dev/null @@ -1,11 +0,0 @@ -RecordSelect -============ - -(c) 2007 - Lance Ivy - -RecordSelect is a Rails widget to help you pick one record out of many. I designed it as a more usable and performant alternative to generating a massive dropdown list. It relies on AJAX for the cooler uses (all the provided view helpers rely on JavaScript?) but can also function in a pure-http fashion (although multi-select support is provided in a pure-JavaScript implementation). - -Please see the ActionView::Helpers::RecordSelectHelpers for the most common API. More documentation (and HOWTOs) can be found online at http://code.google.com/p/recordselect, and a demo application is available at http://recordselect.googlecode.com/svn/demo. - -= DEPENDENCIES -This depends on the excellent Paginator gem by Bruce Williams. This simple gem is available at paginator.rubyforge.org. \ No newline at end of file diff --git a/vendor/plugins/recordselect/Rakefile b/vendor/plugins/recordselect/Rakefile deleted file mode 100644 index 047c96c..0000000 --- a/vendor/plugins/recordselect/Rakefile +++ /dev/null @@ -1,23 +0,0 @@ -require 'rake' -require 'rake/testtask' -require 'rake/rdoctask' - -desc 'Default: run unit tests.' -task :default => :test - -desc 'Test the recordselect plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the recordselect plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'Recordselect' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') - rdoc.rdoc_files.include('assets/**/*.js') -end diff --git a/vendor/plugins/recordselect/app/helpers/record_select_helper.rb b/vendor/plugins/recordselect/app/helpers/record_select_helper.rb deleted file mode 100644 index d0c8466..0000000 --- a/vendor/plugins/recordselect/app/helpers/record_select_helper.rb +++ /dev/null @@ -1,187 +0,0 @@ -module RecordSelectHelper - # Print this from your layout to include everything necessary for RecordSelect to work. - # Well, not everything. You need Prototype too. - def record_select_includes - includes = ''.html_safe - includes << stylesheet_link_tag('record_select/record_select') - includes << javascript_include_tag('record_select/record_select') - includes - end - - # Adds a link on the page that toggles a RecordSelect widget from the given controller. - # - # *Options* - # +onselect+:: JavaScript code to handle selections client-side. This code has access to two variables: id, label. If the code returns false, the dialog will *not* close automatically. - # +params+:: Extra URL parameters. If any parameter is a column name, the parameter will be used as a search term to filter the result set. - def link_to_record_select(name, controller, options = {}) - options[:params] ||= {} - options[:params].merge!(:controller => controller, :action => :browse) - options[:onselect] = "function(id, label) {#{options[:onselect]}}" if options[:onselect] - options[:html] ||= {} - options[:html][:id] ||= "rs_#{rand(9999)}" - - assert_controller_responds(options[:params][:controller]) - - html = link_to_function(name, '', options[:html]) - html << javascript_tag("new RecordSelect.Dialog(#{options[:html][:id].to_json}, #{url_for(options[:params].merge(:escape => false)).to_json}, {onselect: #{options[:onselect] || ''}})") - - return html - end - - # Adds a RecordSelect-based form field. The field submits the record's id using a hidden input. - # - # *Arguments* - # +name+:: the input name that will be used to submit the selected record's id. - # +current+:: the currently selected object. provide a new record if there're none currently selected and you have not passed the optional :controller argument. - # - # *Options* - # +controller+:: The controller configured to provide the result set. Optional if you have standard resource controllers (e.g. UsersController for the User model), in which case the controller will be inferred from the class of +current+ (the second argument) - # +params+:: A hash of extra URL parameters - # +id+:: The id to use for the input. Defaults based on the input's name. - # +onchange+:: A JavaScript function that will be called whenever something new is selected. It should accept the new id as the first argument, and the new label as the second argument. For example, you could set onchange to be "function(id, label) {alert(id);}", or you could create a JavaScript function somewhere else and set onchange to be "my_function" (without the parantheses!). - def record_select_field(name, current, options = {}) - options[:controller] ||= current.class.to_s.pluralize.underscore - options[:params] ||= {} - options[:id] ||= name.gsub(/[\[\]]/, '_') - - controller = assert_controller_responds(options[:controller]) - - id = label = '' - if current and not current.new_record? - id = current.id - label = label_for_field(current, controller) - end - - url = url_for({:action => :browse, :controller => options[:controller], :escape => false}.merge(options[:params])) - - html = text_field_tag(name, nil, :autocomplete => 'off', :id => options[:id], :class => options[:class], :size => options[:size], :onfocus => "this.focused=true", :onblur => "this.focused=false") - html << javascript_tag("new RecordSelect.Single(#{options[:id].to_json}, #{url.to_json}, {id: #{id.to_json}, label: #{label.to_json}, onchange: #{options[:onchange] || ''.to_json}});") - - return html - end - - # Assists with the creation of an observer for the :onchange option of the record_select_field method. - # Currently only supports building an Ajax.Request based on the id of the selected record. - # - # options[:url] should be a hash with all the necessary options *except* :id. that parameter - # will be provided based on the selected record. - # - # Question: if selecting users, what's more likely? - # /users/5/categories - # /categories?user_id=5 - def record_select_observer(options = {}) - fn = "" - fn << "function(id, value) {" - fn << "var url = #{url_for(options[:url].merge(:id => ":id:")).to_json}.replace(/:id:/, id);" - fn << "new Ajax.Request(url);" - fn << "}" - end - - # Adds a RecordSelect-based form field for multiple selections. The values submit using a list of hidden inputs. - # - # *Arguments* - # +name+:: the input name that will be used to submit the selected records' ids. empty brackets will be appended to the name. - # +current+:: pass a collection of existing associated records - # - # *Options* - # +controller+:: The controller configured to provide the result set. - # +params+:: A hash of extra URL parameters - # +id+:: The id to use for the input. Defaults based on the input's name. - def record_multi_select_field(name, current, options = {}) - options[:controller] ||= current.first.class.to_s.pluralize.underscore - options[:params] ||= {} - options[:id] ||= name.gsub(/[\[\]]/, '_') - - controller = assert_controller_responds(options[:controller]) - - current = current.inject([]) { |memo, record| memo.push({:id => record.id, :label => label_for_field(record, controller)}) } - - url = url_for({:action => :browse, :controller => options[:controller], :escape => false}.merge(options[:params])) - - html = text_field_tag("#{name}[]", nil, :autocomplete => 'off', :id => options[:id], :class => options[:class], :onfocus => "this.focused=true", :onblur => "this.focused=false") - html << content_tag('ul', '', :class => 'record-select-list'); - html << javascript_tag("new RecordSelect.Multiple(#{options[:id].to_json}, #{url.to_json}, {current: #{current.to_json}});") - - return html - end - - # A helper to render RecordSelect partials - def render_record_select(options = {}) #:nodoc: - controller.send(:render_record_select, options) do |options| - render options - end - end - - # Provides view access to the RecordSelect configuration - def record_select_config #:nodoc: - controller.send :record_select_config - end - - # The id of the RecordSelect widget for the given controller. - def record_select_id(controller = nil) #:nodoc: - controller ||= params[:controller] - "record-select-#{controller.gsub('/', '_')}" - end - - def record_select_search_id(controller = nil) #:nodoc: - "#{record_select_id(controller)}-search" - end - - private - # render the record using the renderer and add a link to select the record - def render_record_in_list(record, controller_path) - text = render_record_from_config(record) - if record_select_config.link? - url_params = {:controller => controller_path, :action => :select, :id => record.id, :escape => false} - link_to_remote text, { - :url => url_params, - :method => :post, - :before => 'Element.toggleClassName(this, "selected")', - :condition => "RecordSelect.notify(this)" - }, :href => url_for(url_params) - else - text - end - end - - - # uses renderer (defaults to record_select_config.label) to determine how the given record renders. - def render_record_from_config(record, renderer = record_select_config.label) - case renderer - when Symbol, String - # return full-html from the named partial - render :partial => renderer.to_s, :locals => {:record => record} - - when Proc - # return an html-cleaned descriptive string - h renderer.call(record) - end - end - - # uses the result of render_record_from_config to snag an appropriate record label - # to display in a field. - # - # if given a controller, searches for a partial in its views path - def label_for_field(record, controller = self.controller) - renderer = controller.record_select_config.label - case renderer - when Symbol, String - # find the <label> element and grab its innerHTML - description = render_record_from_config(record, File.join(controller.controller_path, renderer.to_s)) - description.match(/<label[^>]*>(.*)<\/label>/)[1] - - when Proc - # just return the string - render_record_from_config(record, renderer) - end - end - - def assert_controller_responds(controller_name) - controller_name = "#{controller_name.camelize}Controller" - controller = controller_name.constantize - unless controller.uses_record_select? - raise "#{controller_name} has not been configured to use RecordSelect." - end - controller - end -end diff --git a/vendor/plugins/recordselect/app/views/record_select/_browse.html.erb b/vendor/plugins/recordselect/app/views/record_select/_browse.html.erb deleted file mode 100644 index 50f6986..0000000 --- a/vendor/plugins/recordselect/app/views/record_select/_browse.html.erb +++ /dev/null @@ -1,8 +0,0 @@ -<% -controller ||= params[:controller] -record_select_id = record_select_id(controller) --%> -<div class="record-select" id="<%= record_select_id -%>"> - <%= render_record_select :partial => 'search', :locals => {:controller => controller, :record_select_id => record_select_id} %> - <%= render_record_select :partial => 'list', :locals => {:controller => controller, :page => @page, :record_select_id => record_select_id} %> -</div> diff --git a/vendor/plugins/recordselect/app/views/record_select/_list.html.erb b/vendor/plugins/recordselect/app/views/record_select/_list.html.erb deleted file mode 100644 index deaf7c6..0000000 --- a/vendor/plugins/recordselect/app/views/record_select/_list.html.erb +++ /dev/null @@ -1,31 +0,0 @@ -<% -controller ||= params[:controller] - -pagination_url_params = params.merge(:controller => controller, :action => :browse, :search => params[:search], :update => 1) -prev_url = url_for(pagination_url_params.merge(:page => page.prev.number, :escape => false)) if page.prev? -next_url = url_for(pagination_url_params.merge(:page => page.next.number, :escape => false)) if page.next? --%> -<ol> - <li class="found"><%= rs_("%d %s found", page.pager.count, -record_select_config.model.to_s.pluralize.titleize.downcase) %></li> - <% if page.prev? -%> - <li class="pagination previous"> - <%= link_to_remote image_tag('record_select/previous.gif', :alt => rs_('Previous')) + " " + rs_("Previous %d", -page.pager.per_page), - {:url => prev_url, :method => :get}, - {:href => prev_url} %> - </li> - <% end -%> - <% page.items.each do |record| -%> - <li class="record <%= cycle 'odd', 'even' %>" id="rs<%= record.id -%>"> - <%= render_record_in_list(record, controller) %> - </li> - <% end -%> - <% if page.next? -%> - <li class="pagination next"> - <%= link_to_remote image_tag('record_select/next.gif', :alt => rs_('Next')) + " " + rs_("Next %d", page.pager.per_page) + " " , - {:url => next_url, :method => :get}, - {:href => next_url} %> - </li> - <% end -%> -</ol> diff --git a/vendor/plugins/recordselect/app/views/record_select/_search.html.erb b/vendor/plugins/recordselect/app/views/record_select/_search.html.erb deleted file mode 100644 index 6fb11a7..0000000 --- a/vendor/plugins/recordselect/app/views/record_select/_search.html.erb +++ /dev/null @@ -1,14 +0,0 @@ -<% search_url = url_for(params.merge(:controller => controller, :action => :browse, :page => 1, :update => 1, :escape => false)) -%> -<% form_remote_tag :url => search_url, :method => :get, - :html => { :action => search_url, :id => record_select_search_id } do %> - <%= text_field_tag 'search', params[:search], :autocomplete => 'off', :class => 'text-input' %> -<% end %> - -<script type="text/javascript"> -//<![CDATA[ -var i = $(<%= record_select_search_id.to_json.html_safe %>).down('input.text-input'); -Form.Element.AfterActivity(i, function() { - $(<%= record_select_search_id.to_json.html_safe %>).onsubmit(); -}, 0.35); -//]]> -</script> diff --git a/vendor/plugins/recordselect/app/views/record_select/browse.js.rjs b/vendor/plugins/recordselect/app/views/record_select/browse.js.rjs deleted file mode 100644 index d9f36b7..0000000 --- a/vendor/plugins/recordselect/app/views/record_select/browse.js.rjs +++ /dev/null @@ -1,4 +0,0 @@ -page.assign "data", render_record_select(:partial => 'list', :locals => {:page => @page}) -page.assign "elem", page.literal("$$('##{record_select_id} ol')[0]") - -page << %|if (elem) {Element.replace(elem, data)}| diff --git a/vendor/plugins/recordselect/assets/images/cross.gif b/vendor/plugins/recordselect/assets/images/cross.gif deleted file mode 100644 index 7008fdc1b4319d2b5fba4073bdaa1ac25c0d90bd..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 545 zcmZ?wbhEHb6krfwI2Ot9L`mhDmd;CE{a5;iFO5uJo0z?^v3qB0|JKgot-a$r2d9rf z($V?7v)g+Y_xG+IpIqHPxOseV^ZerB_07xYlaK!w-+-@v0iOdyzJ*474-Nks7V#}C z@>@jI|B&!+5z*fwqrXMP{0E9e#eR>D{T~tiJtppZY{HMY#Q)K8-{TX1#3%hoO!<|V z{39vlS5oTF<g{POY5$Xwf2E}V%*gtmp7A>~=T}zlubjL;*?GTn^MB_S{LjhzpI7j| zpzwb|(f@+tzlA0L3QPVMmi#F$`(IS@x1{`kN!h=$%Kt!A4n$RdD{KB&R{sZ)wg0MW z{{vBV-T#`pe|3%j>l*$8$)>jd?Op!|0x14uVdP?{XV75)0#KYVu-7%zH#N7kwzao= zd$j48NVIr|g*dioTLo*kI0Z!bm^Eow1ZoMjTDpb1=&76gs`IxSSceArd8zSr)GPaI zs=D*;s#oz;lCu}wrD*KxU~41A-mYNiEX%_tW-89wDz9%R!_~whU?j}cBCRXQ*}}*z T!rUs#(Z=xk(68V1jSSWRn>;oL diff --git a/vendor/plugins/recordselect/assets/images/next.gif b/vendor/plugins/recordselect/assets/images/next.gif deleted file mode 100644 index 664db5531f20543f603549fe76dbab4765d2fad1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 302 zcmZ?wbhEHb6krfwSZc-~;<#PZb*GruUNOG|;sJXlf)7YU9+8YZCY1z4CzbQg>J*)| zE<9see#xffylwdf`>G4h^_QJnuDQ2d^X|A7+;=-+>fOZYcax?+%v<oNXyN^mMUP4r zKPX*%zjVpt@+A){mp!Ol{;X!@!@3m@YgWFfTlu14)#Jw1j~Z7$Zdm=IVfCx_^-tP2 zyy)8aWWv_xleWK@x%=hJ-LDoNe6#q_+ZD&(tv&JnKVG2tlZBCs!Ja{f0SG{TVqo(= zFu%Y<N2>os2xn%<L^GeH6~{KYv`XGOW4tpdMgK;s;MyZTE5uk2PT65GKlsUkoHZs& g9*V0Z8s%8RIc52n!tL337~Acc8G0s6bY!pw0H)HP+W-In diff --git a/vendor/plugins/recordselect/assets/images/previous.gif b/vendor/plugins/recordselect/assets/images/previous.gif deleted file mode 100644 index 2dd047e304063f93399b1ebac33d0659914e898c..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 303 zcmZ?wbhEHb6krfwSZc~3Xs|)Zc#E(l5N#K6*eUA1SIld#c+dgKm?M%g$D~tF8pa<{ z&pT_LeNwCFylwdftC}m04c9zcuX(lK4CuTW+<P-}!riC|x8tYYNtk*!Y3i+{=?~Lp z+)kZ&KXvBA^jUW@XWz-5{V;p(gS`273l}^nTzIc&;r-GjkIR=ls9N^0YT478l@A+N zKW<+8xNZH@?#)koH$9uW<HgjSFJ|t3Icx8$|Ac_zPZmZl273k_1|R_WiGj`M!2ALa z9jX2kNhc<&l$lLiX0UjX?~>`4eb_R?JdDN9OkC2Dq!a8tu_qyJg}>It6pyeummIq) ddK_4T?AdswSeopaxS2cb85nyfdN?vz0|0H?oZtWe diff --git a/vendor/plugins/recordselect/assets/javascripts/record_select.js b/vendor/plugins/recordselect/assets/javascripts/record_select.js deleted file mode 100644 index d050f81..0000000 --- a/vendor/plugins/recordselect/assets/javascripts/record_select.js +++ /dev/null @@ -1,352 +0,0 @@ -Event.observe(window, 'load', function() {RecordSelect.document_loaded = true}); - -Form.Element.AfterActivity = function(element, callback, delay) { - element = $(element); - if (!delay) delay = 0.25; - new Form.Element.Observer(element, delay, function(element, value) { - // TODO: display loading indicator - if (element.activity_timer) clearTimeout(element.activity_timer); - element.activity_timer = setTimeout(function() { - callback(element.value); - }, delay * 1000 + 50); - }); -} - -var RecordSelect = new Object(); -RecordSelect.document_loaded = false; - -RecordSelect.notify = function(item) { - var e = Element.up(item, '.record-select-handler'); - var onselect = e.onselect || e.getAttribute('onselect'); - if (typeof onselect != 'function') onselect = eval(onselect); - if (onselect) - { - try { - onselect(item.parentNode.id.substr(2), (item.down('label') || item).innerHTML, e); - } catch(e) { - alert(e); - } - return false; - } - else return true; -} - -RecordSelect.Abstract = Class.create(); -Object.extend(RecordSelect.Abstract.prototype, { - /** - * obj - the id or element that will anchor the recordselect to the page - * url - the url to run the recordselect - * options - ??? (check concrete classes) - */ - initialize: function(obj, url, options) { - this.obj = $(obj); - this.url = url; - this.options = options; - this.container; - - if (RecordSelect.document_loaded) this.onload(); - else Event.observe(window, 'load', this.onload.bind(this)); - }, - - /** - * Finish the setup - IE doesn't like doing certain things before the page loads - * --override-- - */ - onload: function() {}, - - /** - * the onselect event handler - when someone clicks on a record - * --override-- - */ - onselect: function(id, value) { - alert(id + ': ' + value); - }, - - /** - * opens the recordselect - */ - open: function() { - if (this.is_open()) return; - - new Ajax.Updater(this.container, this.url, { - method: 'get', - evalScripts: true, - asynchronous: true, - onComplete: function() { - this.show(); - // needs to be mousedown so the event doesn't get canceled by other code (see issue #26) - Element.observe(document.body, 'mousedown', this.onbodyclick.bindAsEventListener(this)); - }.bind(this) - }); - }, - - /** - * positions and reveals the recordselect - */ - show: function() { - var offset = Position.cumulativeOffset(this.obj); - this.container.style.left = offset[0] + 'px'; - this.container.style.top = (Element.getHeight(this.obj) + offset[1]) + 'px'; - - if (this._use_iframe_mask()) { - this.container.insertAdjacentHTML('afterEnd', '<iframe src="javascript:false;" class="record-select-mask" />'); - var mask = this.container.next('iframe'); - mask.style.left = this.container.style.left; - mask.style.top = this.container.style.top; - } - - this.container.show(); - - if (this._use_iframe_mask()) { - var dimensions = this.container.immediateDescendants().first().getDimensions(); - mask.style.width = dimensions.width + 'px'; - mask.style.height = dimensions.height + 'px'; - } - }, - - /** - * closes the recordselect by emptying the container - */ - close: function() { - if (this._use_iframe_mask()) { - this.container.next('iframe').remove(); - } - - this.container.hide(); - // hopefully by using remove() instead of innerHTML we won't leak memory - this.container.immediateDescendants().invoke('remove'); - }, - - /** - * returns true/false for whether the recordselect is open - */ - is_open: function() { - return (!this.container.innerHTML.blank()) - }, - - /** - * when the user clicks outside the dropdown - */ - onbodyclick: function(ev) { - if (!this.is_open()) return; - var elem = $(Event.element(ev)); - var ancestors = elem.ancestors(); - ancestors.push(elem); - if (ancestors.include(this.container) || ancestors.include(this.obj)) return; - this.close(); - }, - - /** - * creates and initializes (and returns) the recordselect container - */ - create_container: function() { - new Insertion.Bottom(document.body, '<div class="record-select-container record-select-handler"></div>'); - e = document.body.childNodes[document.body.childNodes.length - 1]; - e.onselect = this.onselect.bind(this); - e.style.display = 'none'; - - return $(e); - }, - - /** - * all the behavior to respond to a text field as a search box - */ - _respond_to_text_field: function(text_field) { - // attach the events to start this party - text_field.observe('focus', this.open.bind(this)); - - // the autosearch event - needs to happen slightly late (keyup is later than keypress) - text_field.observe('keyup', function() { - if (!this.is_open()) return; - this.container.down('.text-input').value = text_field.value; - }.bind(this)); - - // keyboard navigation, if available - if (this.onkeypress) { - text_field.observe('keypress', this.onkeypress.bind(this)); - } - }, - - _use_iframe_mask: function() { - return this.container.insertAdjacentHTML ? true : false; - } -}); - -/** - * Adds keyboard navigation to RecordSelect objects - */ -Object.extend(RecordSelect.Abstract.prototype, { - current: null, - - /** - * keyboard navigation - where to intercept the keys is up to the concrete class - */ - onkeypress: function(ev) { - var elem; - switch (ev.keyCode) { - case Event.KEY_UP: - if (this.current && this.current.up('.record-select')) elem = this.current.previous(); - if (!elem) elem = this.container.getElementsBySelector('ol li.record').last(); - this.highlight(elem); - break; - case Event.KEY_DOWN: - if (this.current && this.current.up('.record-select')) elem = this.current.next(); - if (!elem) elem = this.container.getElementsBySelector('ol li.record').first(); - this.highlight(elem); - break; - case Event.KEY_SPACE: - case Event.KEY_RETURN: - if (this.current) this.current.down('a').onclick(); - break; - case Event.KEY_RIGHT: - elem = this.container.down('li.pagination.next'); - if (elem) elem.down('a').onclick(); - break; - case Event.KEY_LEFT: - elem = this.container.down('li.pagination.previous'); - if (elem) elem.down('a').onclick(); - break; - case Event.KEY_ESC: - this.close(); - break; - default: - return; - } - Event.stop(ev); // so "enter" doesn't submit the form, among other things(?) - }, - - /** - * moves the highlight to a new object - */ - highlight: function(obj) { - if (this.current) this.current.removeClassName('current'); - this.current = $(obj); - obj.addClassName('current'); - } -}); - -/** - * Used by link_to_record_select - * The options hash should contain a onselect: key, with a javascript function as value - */ -RecordSelect.Dialog = Class.create(); -RecordSelect.Dialog.prototype = Object.extend(new RecordSelect.Abstract(), { - onload: function() { - this.container = this.create_container(); - this.obj.observe('click', this.toggle.bind(this)); - - if (this.onkeypress) this.obj.observe('keypress', this.onkeypress.bind(this)); - }, - - onselect: function(id, value) { - if (this.options.onselect(id, value) != false) this.close(); - }, - - toggle: function() { - if (this.is_open()) this.close(); - else this.open(); - } -}); - -/** - * Used by record_select_field helper - * The options hash may contain id: and label: keys, designating the current value - * The options hash may also include an onchange: key, where the value is a javascript function (or eval-able string) for an callback routine. - */ -RecordSelect.Single = Class.create(); -RecordSelect.Single.prototype = Object.extend(new RecordSelect.Abstract(), { - onload: function() { - // initialize the container - this.container = this.create_container(); - this.container.addClassName('record-select-autocomplete'); - - // create the hidden input - new Insertion.After(this.obj, '<input type="hidden" name="" value="" />') - this.hidden_input = this.obj.next(); - - // transfer the input name from the text input to the hidden input - this.hidden_input.name = this.obj.name; - this.obj.name = ''; - - // initialize the values - this.set(this.options.id, this.options.label); - - this._respond_to_text_field(this.obj); - if (this.obj.focused) this.open(); // if it was focused before we could attach observers - }, - - close: function() { - // if they close the dialog with the text field empty, then delete the id value - if (this.obj.value == '') this.set('', ''); - - RecordSelect.Abstract.prototype.close.call(this); - }, - - onselect: function(id, value) { - this.set(id, value); - if (this.options.onchange) this.options.onchange(id, value); - this.close(); - }, - - /** - * sets the id/label - */ - set: function(id, label) { - this.obj.value = label; - this.hidden_input.value = id; - } -}); - -/** - * Used by record_multi_select_field helper. - * Options: - * list - the id (or object) of the <ul> to contain the <li>s of selected entries - * current - an array of id:/label: keys designating the currently selected entries - */ -RecordSelect.Multiple = Class.create(); -RecordSelect.Multiple.prototype = Object.extend(new RecordSelect.Abstract(), { - onload: function() { - // initialize the container - this.container = this.create_container(); - this.container.addClassName('record-select-autocomplete'); - - // decide where the <li> entries should be placed - if (this.options.list) this.list_container = $(this.options.list); - else this.list_container = this.obj.next('ul'); - - // take the input name from the text input, and store it for this.add() - this.input_name = this.obj.name; - this.obj.name = ''; - - // initialize the list - $A(this.options.current).each(function(c) { - this.add(c.id, c.label); - }.bind(this)); - - this._respond_to_text_field(this.obj); - if (this.obj.focused) this.open(); // if it was focused before we could attach observers - }, - - onselect: function(id, value) { - this.add(id, value); - this.close(); - }, - - /** - * Adds a record to the selected list - */ - add: function(id, label) { - // return silently if this value has already been selected - var already_selected = this.list_container.getElementsBySelector('input').any(function(i) { - return i.value == id - }); - if (already_selected) return; - - var entry = '<li>' - + '<a href="#" onclick="$(this.parentNode).remove(); return false;" class="remove">remove</a>' - + '<input type="hidden" name="' + this.input_name + '" value="' + id + '" />' - + '<label>' + label + '</label>' - + '</li>'; - new Insertion.Top(this.list_container, entry); - } -}); diff --git a/vendor/plugins/recordselect/assets/stylesheets/record_select.css b/vendor/plugins/recordselect/assets/stylesheets/record_select.css deleted file mode 100644 index b462dbd..0000000 --- a/vendor/plugins/recordselect/assets/stylesheets/record_select.css +++ /dev/null @@ -1,129 +0,0 @@ -.record-select { - width: 300px; - border: 1px solid #afd0f5; - font-family: sans-serif; - background-color: #fff; - font-size: 11px; -} - -.record-select img { - border-width: 0px; -} - -.record-select form { - display: inline; -} - -.record-select form .text-input { - width: 294px; - margin: 2px auto 1px auto; - display: block; - border: 1px solid #999; -} - -.record-select form input.example { - color: #999; - text-align: center; -} - -.record-select ol, -.record-select li { - margin: 0px; - padding: 0px; - list-style: none; - clear: both; -} - -.record-select a { - color: #0066cc; - text-decoration: none; -} - -.record-select ol a { - display: block; - zoom: 1; - background-color: #e6f2ff; - padding: 2px 4px; -} - -.record-select ol .even a { - background-color: #ffffff; -} - -.record-select ol .pagination a { - background-color: #eee; -} - -.record-select ol .previous a { - border-bottom: 1px solid #afd0f5; -} - -.record-select ol .next a { - border-top: 1px solid #afd0f5; -} - -.record-select ol .pagination a img { - vertical-align: middle; -} - -.record-select ol .found { - text-align: center; - font-style: italic; - color: #999; - padding: 1px 4px; - border-bottom: 1px solid #afd0f5; -} - -.record-select ol .current a, -.record-select ol a:hover { - background-color: #ffff88; -} - -.record-select ol a.selected { - background-color: #666; - color: #fff; -} - -.record-select-container { - position: absolute; - z-index: 100; -} - -iframe.record-select-mask { - /* to mask windowed elements in IE6 */ - position: absolute; - z-index: 99; - filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0); -} - -.record-select-autocomplete form .text-input { - display: none; -} - -.record-select-list { - padding: 0px; - margin: 0px; - list-style: none; -} - -.record-select-list li { - overflow: auto; - zoom: 1; - margin-left: 10px; - font-size: 80%; -} - -.record-select-list label { - float: left; -} - -.record-select-list a.remove { - display: block; - width: 0px; - height: 16px; - padding-left: 16px; - background: url('../../images/record_select/cross.gif') no-repeat 0 0; - overflow: hidden; - float: left; - margin-right: 5px; -} \ No newline at end of file diff --git a/vendor/plugins/recordselect/init.rb b/vendor/plugins/recordselect/init.rb deleted file mode 100644 index 70a5c48..0000000 --- a/vendor/plugins/recordselect/init.rb +++ /dev/null @@ -1,16 +0,0 @@ -require File.dirname(__FILE__) + '/lib/localization' -require File.dirname(__FILE__) + '/lib/extensions/active_record' - -ActionController::Base.send(:include, RecordSelect) -ActionView::Base.send(:include, RecordSelectHelper) -ActionView::Helpers::FormBuilder.send(:include, RecordSelect::FormBuilder) - -['stylesheets', 'images', 'javascripts'].each do |asset_type| - public_dir = File.join(RAILS_ROOT, 'public', asset_type, 'record_select') - local_dir = File.join(File.dirname(__FILE__), 'assets', asset_type) - FileUtils.mkdir public_dir unless File.exists? public_dir - Dir.entries(local_dir).each do |file| - next if file =~ /^\./ - FileUtils.cp File.join(local_dir, file), public_dir - end -end diff --git a/vendor/plugins/recordselect/install.rb b/vendor/plugins/recordselect/install.rb deleted file mode 100644 index f7732d3..0000000 --- a/vendor/plugins/recordselect/install.rb +++ /dev/null @@ -1 +0,0 @@ -# Install hook code here diff --git a/vendor/plugins/recordselect/lib/extensions/active_record.rb b/vendor/plugins/recordselect/lib/extensions/active_record.rb deleted file mode 100644 index 9358a82..0000000 --- a/vendor/plugins/recordselect/lib/extensions/active_record.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActiveRecord # :nodoc: - class Base # :nodoc: - unless method_defined? :to_label - def to_label - self.to_s - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/recordselect/lib/localization.rb b/vendor/plugins/recordselect/lib/localization.rb deleted file mode 100644 index 346b8af..0000000 --- a/vendor/plugins/recordselect/lib/localization.rb +++ /dev/null @@ -1,8 +0,0 @@ -# Provides a simple pass-through localizer for RecordSelect. If you want -# to localize RS, you need to override this method and route it to your -# own system. -class Object - def rs_(string_to_localize, *args) - args.empty? ? string_to_localize : (sprintf string_to_localize, *args) - end -end diff --git a/vendor/plugins/recordselect/lib/record_select.rb b/vendor/plugins/recordselect/lib/record_select.rb deleted file mode 100644 index c633ab2..0000000 --- a/vendor/plugins/recordselect/lib/record_select.rb +++ /dev/null @@ -1,36 +0,0 @@ -module RecordSelect - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - # Enables and configures RecordSelect on your controller. - # - # *Options* - # +model+:: defaults based on the name of the controller - # +per_page+:: records to show per page when browsing - # +notify+:: a method name to invoke when a record has been selected. - # +order_by+:: a SQL string to order the search results - # +search_on+:: an array of searchable fields - # +full_text_search+:: a boolean for whether to use a %?% search pattern or not. default is false. - # +label+:: a proc that accepts a record as argument and returns an option label. default is to call record.to_label instead. - # +include+:: as for ActiveRecord::Base#find. can help with search conditions or just help optimize rendering the results. - # +link+:: a boolean for whether wrap the text returned by label in a link or not. default is true. set to false when - # label returns html code which can't be inside a tag. You can use record_select_link_to_select in your proc - # or partial to add a link to select action - # - # You may also pass a block, which will be used as options[:notify]. - def record_select(options = {}) - options[:model] ||= self.to_s.split('::').last.sub(/Controller$/, '').pluralize.singularize.underscore - @record_select_config = RecordSelect::Config.new(options.delete(:model), options) - self.send :include, RecordSelect::Actions - self.send :include, RecordSelect::Conditions - end - - attr_reader :record_select_config - - def uses_record_select? - !record_select_config.nil? - end - end -end diff --git a/vendor/plugins/recordselect/lib/record_select/actions.rb b/vendor/plugins/recordselect/lib/record_select/actions.rb deleted file mode 100644 index 4559328..0000000 --- a/vendor/plugins/recordselect/lib/record_select/actions.rb +++ /dev/null @@ -1,68 +0,0 @@ -module RecordSelect - module Actions - # :method => :get - # params => [:page, :search] - def browse - conditions = record_select_conditions - klass = record_select_config.model - @count = klass.count(:conditions => conditions, :include => record_select_includes) - pager = ::Paginator.new(@count, record_select_config.per_page) do |offset, per_page| - klass.find(:all, :offset => offset, - :select => record_select_select||"*", - :include => [record_select_includes, record_select_config.include].flatten.compact, - :limit => per_page, - :conditions => conditions, - :order => record_select_config.order_by) - end - @page = pager.page(params[:page] || 1) - - respond_to do |wants| - wants.html { render_record_select :partial => 'browse'} - wants.js { - if params[:update] - render_record_select :template => 'browse', :format => :js, :layout => false - else - render_record_select :partial => 'browse' - end - } - wants.yaml {} - wants.xml {} - wants.json {} - end - end - - # :method => :post - # params => [:id] - def select - klass = record_select_config.model - record = klass.find(params[:id]) - if record_select_config.notify.is_a? Proc - record_select_config.notify.call(record) - elsif record_select_config.notify - send(record_select_config.notify, record) - end - render :nothing => true - end - - protected - - def record_select_config #:nodoc: - self.class.record_select_config - end - - def render_record_select(options = {}) #:nodoc: - [:template,:partial].each do |template_name| - if options[template_name] then - options[template_name] = File.join(record_select_views_path, options[template_name]) - end - end - if block_given? then yield options else render options end - end - - private - - def record_select_views_path - "record_select" - end - end -end diff --git a/vendor/plugins/recordselect/lib/record_select/conditions.rb b/vendor/plugins/recordselect/lib/record_select/conditions.rb deleted file mode 100644 index 601af19..0000000 --- a/vendor/plugins/recordselect/lib/record_select/conditions.rb +++ /dev/null @@ -1,91 +0,0 @@ -module RecordSelect - module Conditions - protected - # returns the combination of all conditions. - # conditions come from: - # * current search (params[:search]) - # * intelligent url params (e.g. params[:first_name] if first_name is a model column) - # * specific conditions supplied by the developer - def record_select_conditions - conditions = [] - - merge_conditions( - record_select_conditions_from_search, - record_select_conditions_from_params, - record_select_conditions_from_controller - ) - end - - # an override method. - # here you can provide custom conditions to define the selectable records. useful for situational restrictions. - def record_select_conditions_from_controller; end - - # another override method. - # define any association includes you want for the finder search. - def record_select_includes; end - - # define special list of selected fields, - # mainly to define extra fields that can be used for - # specialized sorting. - def record_select_select; end - - # generate conditions from params[:search] - # override this if you want to customize the search routine - def record_select_conditions_from_search - search_pattern = record_select_config.full_text_search? ? '%?%' : '?%' - - if params[:search] and !params[:search].strip.empty? - tokens = params[:search].strip.split(' ') - - where_clauses = record_select_config.search_on.collect { |sql| "#{sql} LIKE ?" } - phrase = "(#{where_clauses.join(' OR ')})" - - sql = ([phrase] * tokens.length).join(' AND ') - tokens = tokens.collect{ |value| [search_pattern.sub('?', value.downcase)] * record_select_config.search_on.length }.flatten - - conditions = [sql, *tokens] - end - end - - # instead of a shotgun approach, this assumes the user is - # searching vs some SQL field (possibly built with CONCAT()) - # similar to the record labels. -# def record_select_simple_conditions_from_search -# return unless params[:search] and not params[:search].empty? -# -# search_pattern = record_select_config.full_text_search? ? '%?%' : '?%' -# search_string = search_pattern.sub('?', value.downcase) -# -# ["LOWER(#{record_select_config.search_on})", search_pattern.sub('?', value.downcase)] -# end - - # generate conditions from the url parameters (e.g. users/browse?group_id=5) - def record_select_conditions_from_params - conditions = nil - params.each do |field, value| - next unless column = record_select_config.model.columns_hash[field] - conditions = merge_conditions( - conditions, - record_select_condition_for_column(column, value) - ) - end - conditions - end - - # generates an SQL condition for the given column/value - def record_select_condition_for_column(column, value) - if value.blank? and column.null - "#{column.name} IS NULL" - elsif column.text? - ["LOWER(#{column.name}) LIKE ?", value] - else - ["#{column.name} = ?", column.type_cast(value)] - end - end - - def merge_conditions(*conditions) #:nodoc: - c = conditions.find_all {|c| not c.nil? and not c.empty? } - c.empty? ? nil : c.collect{|c| record_select_config.model.send(:sanitize_sql, c)}.join(' AND ') - end - end -end diff --git a/vendor/plugins/recordselect/lib/record_select/config.rb b/vendor/plugins/recordselect/lib/record_select/config.rb deleted file mode 100644 index 864fe81..0000000 --- a/vendor/plugins/recordselect/lib/record_select/config.rb +++ /dev/null @@ -1,91 +0,0 @@ -module RecordSelect - # a write-once configuration object - class Config - def initialize(klass, options = {}) - @klass = klass - - @notify = block_given? ? proc : options[:notify] - - @per_page = options[:per_page] - - @search_on = [options[:search_on]].flatten - - @order_by = options[:order_by] - - @full_text_search = options[:full_text_search] - - @label = options[:label] - - @include = options[:include] - - @link = options[:link] - end - - # The model object we're browsing - def model - @model ||= klass.to_s.camelcase.constantize - end - - # Records to show on a page - def per_page - @per_page ||= 10 - end - - # The method name or proc to notify of a selection event. - # May not matter if the selection event is intercepted client-side. - def notify - @notify - end - - # A collection of fields to search. This is essentially raw SQL, so you could search on "CONCAT(first_name, ' ', last_name)" if you wanted to. - # NOTE: this does *NO* default transforms (such as LOWER()), that's left entirely up to you. - def search_on - @search_on ||= self.model.columns.collect{|c| c.name if [:text, :string].include? c.type}.compact - end - - def order_by - @order_by ||= "#{model.primary_key} ASC" unless @order_by == false - end - - def full_text_search? - @full_text_search ? true : false - end - - def include - @include - end - - # If a proc, must accept the record as an argument and return a descriptive string. - # - # If a symbol or string, must name a partial that renders a representation of the - # record. The partial should assume a local "record" variable, and should include a - # <label> tag, even if it's not visible. The contents of the <label> tag will be used - # to represent the record once it has been selected. For example: - # - # record_select_config.label = :user_description - # - # > app/views/users/_user_description.erb - # - # <div class="user_description"> - # <%= image_tag url_for_file_column(record, 'avatar') %> - # <label><%= record.username %></label> - # <p><%= record.quote %></p> - # </div> - # - def label - @label ||= proc {|r| r.to_label} - end - - # whether wrap the text returned by label in a link or not - def link? - @link.nil? ? true : @link - end - - protected - - # A singularized underscored version of the model we're browsing - def klass - @klass - end - end -end \ No newline at end of file diff --git a/vendor/plugins/recordselect/lib/record_select/form_builder.rb b/vendor/plugins/recordselect/lib/record_select/form_builder.rb deleted file mode 100644 index fbe53ad..0000000 --- a/vendor/plugins/recordselect/lib/record_select/form_builder.rb +++ /dev/null @@ -1,25 +0,0 @@ -module RecordSelect - module FormBuilder - def record_select(association, options = {}) - reflection = @object.class.reflect_on_association(association) - form_name = form_name_for_association(reflection) - current = @object.send(association) - options[:id] ||= "#{@object_name.gsub(/[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "")}_#{association}" - - if [:has_one, :belongs_to].include? reflection.macro - @template.record_select_field(form_name, current || reflection.klass.new, options) - else - options[:controller] ||= reflection.klass.to_s.pluralize.underscore - @template.record_multi_select_field(form_name, current, options) - end - end - - private - - def form_name_for_association(reflection) - key_name = (reflection.options[:foreign_key] || reflection.association_foreign_key) - key_name += "s" unless [:has_one, :belongs_to].include? reflection.macro - form_name = "#{@object_name}[#{key_name}]" - end - end -end diff --git a/vendor/plugins/recordselect/test/recordselect_test.rb b/vendor/plugins/recordselect/test/recordselect_test.rb deleted file mode 100644 index dcc7fd0..0000000 --- a/vendor/plugins/recordselect/test/recordselect_test.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'test/unit' - -class RecordselectTest < Test::Unit::TestCase - # Replace this with your real tests. - def test_this_plugin - flunk - end -end diff --git a/vendor/plugins/recordselect/uninstall.rb b/vendor/plugins/recordselect/uninstall.rb deleted file mode 100644 index 84aea34..0000000 --- a/vendor/plugins/recordselect/uninstall.rb +++ /dev/null @@ -1,4 +0,0 @@ -['stylesheets', 'images', 'javascripts'].each do |asset_type| - public_dir = File.join(RAILS_ROOT, 'public', asset_type, 'record_select') - FileUtils.rm_r public_dir -end \ No newline at end of file diff --git a/vendor/plugins/render_component/README b/vendor/plugins/render_component/README deleted file mode 100644 index a6a318a..0000000 --- a/vendor/plugins/render_component/README +++ /dev/null @@ -1,37 +0,0 @@ -Components allow you to call other actions for their rendered response while executing another action. You can either delegate -the entire response rendering or you can mix a partial response in with your other content. - - class WeblogController < ActionController::Base - # Performs a method and then lets hello_world output its render - def delegate_action - do_other_stuff_before_hello_world - render_component :controller => "greeter", :action => "hello_world", :params => { :person => "david" } - end - end - - class GreeterController < ActionController::Base - def hello_world - render :text => "#{params[:person]} says, Hello World!" - end - end - -The same can be done in a view to do a partial rendering: - - Let's see a greeting: - <%= render_component :controller => "greeter", :action => "hello_world" %> - -It is also possible to specify the controller as a class constant, bypassing the inflector -code to compute the controller class at runtime: - -<%= render_component :controller => GreeterController, :action => "hello_world" %> - -== When to use components - -Components should be used with care. They're significantly slower than simply splitting reusable parts into partials and -conceptually more complicated. Don't use components as a way of separating concerns inside a single application. Instead, -reserve components to those rare cases where you truly have reusable view and controller elements that can be employed -across many applications at once. - -So to repeat: Components are a special-purpose approach that can often be replaced with better use of partials and filters. - -Copyright (c) 2007 David Heinemeier Hansson, released under the MIT license \ No newline at end of file diff --git a/vendor/plugins/render_component/Rakefile b/vendor/plugins/render_component/Rakefile deleted file mode 100644 index 1eb4ef5..0000000 --- a/vendor/plugins/render_component/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 components plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = 'test/**/*_test.rb' - t.verbose = true -end - -desc 'Generate documentation for the components plugin.' -Rake::RDocTask.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'Components' - rdoc.options << '--line-numbers' << '--inline-source' - rdoc.rdoc_files.include('README') - rdoc.rdoc_files.include('lib/**/*.rb') -end \ No newline at end of file diff --git a/vendor/plugins/render_component/init.rb b/vendor/plugins/render_component/init.rb deleted file mode 100644 index b428c52..0000000 --- a/vendor/plugins/render_component/init.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'components' -ActionController::Base.send :include, Components diff --git a/vendor/plugins/render_component/lib/components.rb b/vendor/plugins/render_component/lib/components.rb deleted file mode 100644 index 101f6b4..0000000 --- a/vendor/plugins/render_component/lib/components.rb +++ /dev/null @@ -1,141 +0,0 @@ -module Components - def self.included(base) #:nodoc: - base.class_eval do - include InstanceMethods - extend ClassMethods - helper HelperMethods - - # If this controller was instantiated to process a component request, - # +parent_controller+ points to the instantiator of this controller. - attr_accessor :parent_controller - - alias_method_chain :process_cleanup, :render_component - alias_method_chain :session=, :render_component - alias_method_chain :flash, :render_component - alias_method_chain :perform_action, :render_component - alias_method_chain :send_response, :render_component - - alias_method :component_request?, :parent_controller - end - end - - module ClassMethods - # Track parent controller to identify component requests - def process_with_components(request, response, parent_controller = nil) #:nodoc: - controller = new - controller.parent_controller = parent_controller - controller.process(request, response) - end - end - - module HelperMethods - def render_component(options) - @controller.__send__(:render_component_as_string, options) - end - end - - module InstanceMethods - def perform_action_with_render_component - perform_action_without_render_component - remove_instance_variable(:@_flash) if defined? @_flash - end - - # Extracts the action_name from the request parameters and performs that action. - def process_with_components(request, response, method = :perform_action, *arguments) #:nodoc: - flash.discard if component_request? - process_without_components(request, response, method, *arguments) - end - - def send_response_with_render_component - response.prepare! unless component_request? - response - end - - protected - # Renders the component specified as the response for the current method - def render_component(options) #:doc: - component_logging(options) do - render_for_text(component_response(options, true).body, response.status) - end - end - - # Returns the component response as a string - def render_component_as_string(options) #:doc: - component_logging(options) do - response = component_response(options, false) - - if redirected = response.redirected_to - render_component_as_string(redirected) - else - response.body - end - end - end - - def flash_with_render_component(refresh = false) #:nodoc: - if !defined?(@_flash) || refresh - @_flash = - if defined?(@parent_controller) - @parent_controller.flash - else - flash_without_render_component - end - end - @_flash - end - - private - def component_response(options, reuse_response) - klass = component_class(options) - request = request_for_component(klass.controller_path, options) - new_response = reuse_response ? response : response.dup - - klass.process_with_components(request, new_response, self) - end - - # determine the controller class for the component request - def component_class(options) - if controller = options[:controller] - controller.is_a?(Class) ? controller : "#{controller.camelize}Controller".constantize - else - self.class - end - end - - # Create a new request object based on the current request. - # The new request inherits the session from the current request, - # bypassing any session options set for the component controller's class - def request_for_component(controller_path, options) - new_request = request.dup - new_request.session = request.session - - new_request.instance_variable_set( - :@parameters, - (options[:params] || {}).with_indifferent_access.update( - "controller" => controller_path, "action" => options[:action], "id" => options[:id] - ) - ) - - new_request - end - - def component_logging(options) - if logger - logger.info "Start rendering component (#{options.inspect}): " - result = yield - logger.info "\n\nEnd of component rendering" - result - else - yield - end - end - - def session_with_render_component=(options = {}) - session_without_render_component=(options) unless component_request? - end - - def process_cleanup_with_render_component - process_cleanup_without_render_component unless component_request? - end - end -end diff --git a/vendor/plugins/render_component/test/abstract_unit.rb b/vendor/plugins/render_component/test/abstract_unit.rb deleted file mode 100644 index f022971..0000000 --- a/vendor/plugins/render_component/test/abstract_unit.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'rubygems' -require 'test/unit' -require 'action_controller' -require 'action_controller/test_process' -ActionController::Routing::Routes.reload rescue nil - -$: << File.dirname(__FILE__) + "/../lib" -require File.dirname(__FILE__) + "/../init" diff --git a/vendor/plugins/render_component/test/components_test.rb b/vendor/plugins/render_component/test/components_test.rb deleted file mode 100644 index 53fcd7f..0000000 --- a/vendor/plugins/render_component/test/components_test.rb +++ /dev/null @@ -1,136 +0,0 @@ -require File.dirname(__FILE__) + '/abstract_unit' - -class CallerController < ActionController::Base - def calling_from_controller - render_component(:controller => "callee", :action => "being_called") - end - - def calling_from_controller_with_params - render_component(:controller => "callee", :action => "being_called", :params => { "name" => "David" }) - end - - def calling_from_controller_with_different_status_code - render_component(:controller => "callee", :action => "blowing_up") - end - - def calling_from_template - render :inline => "Ring, ring: <%= render_component(:controller => 'callee', :action => 'being_called') %>" - end - - def internal_caller - render :inline => "Are you there? <%= render_component(:action => 'internal_callee') %>" - end - - def internal_callee - render :text => "Yes, ma'am" - end - - def set_flash - render_component(:controller => "callee", :action => "set_flash") - end - - def use_flash - render_component(:controller => "callee", :action => "use_flash") - end - - def calling_redirected - render_component(:controller => "callee", :action => "redirected") - end - - def calling_redirected_as_string - render :inline => "<%= render_component(:controller => 'callee', :action => 'redirected') %>" - end - - def rescue_action(e) raise end -end - -class CalleeController < ActionController::Base - def being_called - render :text => "#{params[:name] || "Lady"} of the House, speaking" - end - - def blowing_up - render :text => "It's game over, man, just game over, man!", :status => 500 - end - - def set_flash - flash[:notice] = 'My stoney baby' - render :text => 'flash is set' - end - - def use_flash - render :text => flash[:notice] || 'no flash' - end - - def redirected - redirect_to :controller => "callee", :action => "being_called" - end - - def rescue_action(e) raise end -end - -class ComponentsTest < ActionController::TestCase - tests CallerController - - def test_calling_from_controller - get :calling_from_controller - assert_equal "Lady of the House, speaking", @response.body - end - - def test_calling_from_controller_with_params - get :calling_from_controller_with_params - assert_equal "David of the House, speaking", @response.body - end - - def test_calling_from_controller_with_different_status_code - get :calling_from_controller_with_different_status_code - assert_equal 500, @response.response_code - end - - def test_calling_from_template - get :calling_from_template - assert_equal "Ring, ring: Lady of the House, speaking", @response.body - end - - def test_etag_is_set_for_parent_template_when_calling_from_template - get :calling_from_template - expected_etag = etag_for("Ring, ring: Lady of the House, speaking") - assert_equal expected_etag, @response.headers['ETag'] - end - - def test_internal_calling - get :internal_caller - assert_equal "Are you there? Yes, ma'am", @response.body - end - - def test_flash - get :set_flash - assert_equal 'My stoney baby', flash[:notice] - get :use_flash - assert_equal 'My stoney baby', @response.body - get :use_flash - assert_equal 'no flash', @response.body - end - - def test_component_redirect_redirects - get :calling_redirected - - assert_redirected_to :controller=>"callee", :action => "being_called" - end - - def test_component_multiple_redirect_redirects - test_component_redirect_redirects - test_internal_calling - end - - def test_component_as_string_redirect_renders_redirected_action - get :calling_redirected_as_string - - assert_equal "Lady of the House, speaking", @response.body - end - - protected - def etag_for(text) - %("#{Digest::MD5.hexdigest(text)}") - end -end diff --git a/vendor/plugins/russian/CHANGELOG b/vendor/plugins/russian/CHANGELOG deleted file mode 100644 index 46183d6..0000000 --- a/vendor/plugins/russian/CHANGELOG +++ /dev/null @@ -1,98 +0,0 @@ -=== 0.2.5 - 23.12.2009 - -* Added support for multi-char substrings in Russian.transliterate [Alex Fortuna] -* Rails 2.3.5 error messages overloading compatibility (error messages overloading) (thanks Alex Eagle for bugreport) - -* Russian.transliterate: Теперь можно добавлять правила матчинга подстрок из нескольких символов ("Воробьёв", "Алябьев"). [Alex Fortuna] -* Rails 2.3.5: совместимость для перегрузки сообщений об ошибках (багрепорт -- Александр Орел) - -=== 0.2.4 - 12.11.2009 - -* Revert nested validation errors patch - -* Убран патч для вложенных сообщений валидации (не работал с Rails 2.3.3 и ниже) - -=== 0.2.3 - 9.11.2009 - -* Improve ActiveRecord translations [Dmitri Koulikoff] -* Fix nested validation errors with custom error message hack for Rails < 2.3.4 [valodzka] -* Added almost_x_years datetime translation - -* Улучшен перевод ActiveRecord [Dmitri Koulikoff] -* Исправлена ошибка, возникающая при вложенных сообщениях валидации при использовании хака для Rails < 2.3.4 [valodzka] -* Добавлен перевод для ключа даты/времени almost_x_years - -=== 0.2.2 - 17.09.2009 - -* Fix ^-prefixed error messages handling on Rails 2.3.4 - -* Для Rails 2.3.4 исправлена работа сообщений валидаций, начинающихся с "^" - -=== 0.2.1 - 5.09.2009 - -* Rails 2.3.4 compat (ActiveRecord::Error) and deprecation warning (use errors.full_messages.format from now on) [Alexander Semyonov/Yaroslav Markin] -* Added a couple of missing translations from Rails 2.3.4 -* transliteration: Ы now transforms to Y [Alex Fortuna] - -* Совместимость с Rails 2.3.4 (ActiveRecord::Error) и устаревшее форматирование через "^" (теперь надо использовать errors.full_messages.format) [Alexander Semyonov/Yaroslav Markin] -* Добавлена пара недостающих переводов из Rails 2.3.4 -* транслитерация: Ы теперь превращается в Y [Alex Fortuna] - -=== 0.2.0 - 16.03.2009 - -* number_to_human_size() translations: using edge format (Rails 2.3) -* i18n gem updated (0.1.3) -* Rails 2.3 compat - -* Перевод для number_to_human_size(): испольуется форматирование из edge (Rails 2.3) -* Обновлен gem i18n до версии 0.1.3 -* Совместимость с Rails 2.3 - -=== 0.1.3 - 27.12.2008 - -* Add support.array.words_connector/two_words_connector/last_word_connector (Array#to_sentence) (Rails Edge) -* Add datetime.prompts translations (Rails Edge) - -* Добавлены переводы для Array#to_sentence (Rails Edge) -* Добавлены переводы для datetime.prompts (Rails Edge) - -=== 0.1.2 - 4.11.2008 - -Fixed I18n.load_path ordering, translations shipped with russian gem will no longer overwrite your own translations (thanks Dmitrij Smalko for bugreport). - -Поправлено добавление переводов russian в I18n.load_path, теперь переводы из russian не будут замещать ваши собственные переводы (спасибо Dmitrij Smalko за обнаружение ошибки). - -=== 0.1.1 - 24.11.2008 - -Added number.human.storage_units translation key (Rails Edge). - -Добавлен ключ number.human.storage_units (появился в Rails Edge). - -=== 0.1.0 - 22.11.2008 - -No changes, Rails 2.2 released - -=== 0.0.9 - 21.11.2008 - -* Updated I18n gem due to locale changes (0.1.1) -* NB! I18n changed default locale from :'en-US' to :'en', same recommended for other locales by default -* NB!! Russian locale is now :'ru' NOT :'ru-RU', update your locale files. - -* I18n gem обновился до 0.1.1 в связи с изменениями в названиях локалей -* ВНИМАНИЕ: локаль по умолчанию I18n теперь называется не :'en-US' а :'en', такой же способ именования рекомендуется и для других локалей -* ВНИМАНИЕ! Локаль русского языка теперь называется :'ru' а не :'ru-RU'. Не забудьте обновить ваши файлы переводов. - -=== 0.0.8 - 20.11.2008 - -* Introduce transliteration (Russian.translit, Russian.transliterate) -* Add an ActiveSupport hack for #parameterize - -* Добавилась поддержка транслитерации (Russian.translit, Russian.transliterate) -* Добавился хак для #parameterize ActiveSupport (генерация "красивых" URL) - -=== 0.0.7 - 09.11.2008 - -* Updated I18n gem - -* Новая версия gem I18n - diff --git a/vendor/plugins/russian/LICENSE b/vendor/plugins/russian/LICENSE deleted file mode 100644 index d7ddf0c..0000000 --- a/vendor/plugins/russian/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008 Yaroslav Markin - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/plugins/russian/README.textile b/vendor/plugins/russian/README.textile deleted file mode 100644 index 0fd99f5..0000000 --- a/vendor/plugins/russian/README.textile +++ /dev/null @@ -1,297 +0,0 @@ -h1. Russian - -Поддержка русского языка для Ruby и Rails при помощи библиотеки I18n. - -Russian language support for Ruby and Rails, using I18n library. - -h3. If you don't speak Russian - -This code may still be useful for you and Ruby I18n community. You can learn how to create custom backends for I18n and how to provide support of "standalone" (as defined in "Unicode CLDR":http://unicode.org/cldr/) month names with I18n and Rails, and also how to add dead simple pluralization rules into your translation tables. This library also includes a module (@Russian@) with a set of helpers to provide simplistic pluralization and @strftime@ for Russian language -- in a way that is easier than using I18n methods. - -Feel free to shoot an email to Yaroslav Markin ("yaroslav@markin.net":mailto:yaroslav@markin.net) - -h1. Что это - -Russian -- это библиотека для полноценной поддержки русского языка (форматирование даты и времени, плюрализация, локализация в целом) для Ruby и Ruby on Rails. - -Цель проекта -- построить полноценную среду для русской локализации Ruby и Rails проектов, при этом используя минимально возможное количество хаков, сохраняя при этом поддержку локализации приложения на другие языки, а также форсировать включение в основную ветку I18n и Rails всех функций локализации, необходимых для работы с русским языком. - -Russian использует библиотеку I18n (включена в поставку), несколько хаков поверх нее (собственный бекэнд с поддержкой специфичного для русского форматирования даты и времени, поддержкой плюрализации), несколько хаков поверх Rails (хаки хелперов даты-времени, хак для сообщений валидации) и файлы переводов, а также набор хелперов, упрощающий работу с русским языком (простая плюрализация, простой strftime и др.). - -Russian стремится быть минимально деструктивной для окружения и быть полностью совместимой с другими языками (таким образом, когда приложение использует Russian и собственный бекэнд Russian, оно остается полностью совместимым с Rails i18n). - -h2. Что такое I18n - -Библиотека I18n входит в состав Ruby on Rails начиная с версии 2.2. В перспективе I18n -- это самое простое и недеструктивное решение для локализации и интернационализации Rails приложений, но в текущей версии отсутствовала поддержка нескольких важных возможностей, специфичных для русского языка. Таким образом, русский язык для локализации в Rails 2.2 фактически не поддерживался. - -Для исправления этого досадного недоразумения появилась библиотека Russian (подробнее см. _Использование_). - -h1. Требования - -* Ruby 1.8 (тестировалось на 1.8.6); -* Для использования с Rails нужна версия не ниже 2.2; -* Для тестирования библиотеки вам понадобится RSpec. - -h1. Установка - -Страница Russian на github -- "http://github.com/yaroslav/russian/":http://github.com/yaroslav/russian/ - -Gem можно устанавливать с "Gemcutter":http://gemcutter.org (предпочтительно) и с RubyForge. - -Для установки: - -@gem install russian@ - -h2. Ruby on Rails - -Существует два варианта использования Russian вместе с Rails: - -1. Установка gem - -"Релизные" версии библиотеки для стабильных версий Rails. - -В файле @config/environment.rb@ сделайте ссылку на gem @russian@ с Gemcutter: - -<pre><code> -Rails::Initializer.run do |config| - config.gem 'russian', :source => 'http://gemcutter.org' -end -</code></pre> - -Чтобы установить gem, используйте команду - -@rake gems:install@. - -2. Установка плагина - -Последняя версия из master-ветки, чаще всего для использования с последней (пререлизной) версией Rails. - -Для того, чтобы установить Russian как плагин к Rails, используйте команду - -@script/plugin install git://github.com/yaroslav/russian.git@ - -Для Windows можно использовать версию git, расположенную по адресу: "http://code.google.com/p/msysgit/":http://code.google.com/p/msysgit/ - -h1. Использование - -При загрузке Russian включает: - -* библиотеку I18n если она еще не используется (например, если Russian используется отдельно от Rails) -* собственный класс для I18n бекэнда (полностью совместим со стандартным бекэндом) -* перегрузку хелперов даты для Rails (если Rails загружен) -* пререгрузку обработки сообщений валидации для ActiveRecord (если Rails загружен) - -При инициализации: - -* заменяется бэкэнд I18n со стандартного на собственный бекэнд Russian (@I18n::Backend::Advanced@) -* _NB:_ локаль русского языка (@:'ru'@) становится локалью по умолчанию -* загружаются все файлы переводов, в том числе переводы для Rails. - -После этого можно использовать все стандартные функции библиотеки I18n, пользоваться измененным функционалом для лучшей поддержки русского языка, или использовать хелперы модуля Russian для еще более простой работы с русским языком. - -h2. Отличия от стандартной библиотеки I18n - -1. Поддержка двух видов названий месяцев -- контекст ("сентября") и отдельностоящее ("Сентябрь"). - -Для этого перегружена функция локализации, теперь название месяца используется в зависимости от контекста. В словарях Russian определены оба варианта. - -Перегрузка недеструктивная: если для какого-то другого языка не определены два варианта названий месяцев, ошибки не возникнет. - -Аналогично есть поддержка двух видов названий дней недели. - -2. Плюрализация - -Стандартно I18n поддерживается только плюрализация по английским правилам; бекэнд, использующийся в Russian, позволяет каждому языку определять правила плюрализации в таблице переводов, задавая их как @Proc@. - -Перегрузка недеструктивная: если правила в таблице нет, используется правило по умолчанию (английский язык). - -Правила для русского языка включены. - -h1. Справочник - -h2. Примеры и справка по переводам (I18n) - -Небольшую справку по переводам (I18n) и пример того, как можно переводить имена моделей, атрибутов, и многие другие вещи, определенные в Rails или I18n, можно посмотреть в директории @lib/russian/locale@. Там находятся файлы переводов, которые используются в Russian, со всеми комментариями. - -h2. Вспомогательные методы модуля Russian - -<pre><code> -Russian.locale -Russian::LOCALE -</code></pre> - --- возвращает локаль русского языка (@:'ru'@). - -<pre><code> -Russian::i18n_backend_class -</code></pre> - --- возвращает класс собственного бекенда I18n - -<pre><code> -Russian::init_i18n -</code></pre> - --- инициализация Russian. Включение бекэнда, русский язык по умолчанию, загрузка переводов. - -_NB:_ Выполняется автоматически при загрузке. - -<pre><code> -Russian::translate -Russian::t -</code></pre> - --- прокси для метода @translate@ I18n, форсирует использование русской локали. - -<pre><code> -Russian::localize -Russian::l -</code></pre> - --- прокси для метода @localize@ I18n, форсирует использование русской локали. - -<pre><code> -Russian::strftime - -Russian::strftime(Time.now) -=> "Пн, 01 сент. 2008, 11:12:43 +0300" -Russian::strftime(Time.now, "%d %B") ->> "01 сентября" -Russian::strftime(Time.now, "%B") -=> "Сентябрь" -</code></pre> - --- @strftime@ с форсированием русской локали (упрощенный вариант @localize@) - -<pre><code> -Russian::pluralize -Russian::p - -Russian.p(1, "вещь", "вещи", "вещей") -=> "вещь" -Russian.p(2, "вещь", "вещи", "вещей") -=> "вещи" -Russian.p(10, "вещь", "вещи", "вещей") -=> "вещей" -Russian.p(3.14, "вещь", "вещи", "вещей", "вещи") # последний вариант используется для дробных величин -=> "вещи" -</code></pre> - --- упрощенная (без использования хешей I18n) плюрализация для русского языка - -<pre><code> -Russian::transliterate -Russian::translit - -Russian.translit("рубин") -=> "rubin" -Russian.translit("Hallo Юлику Тарханову") -=> "Hallo Yuliku Tarhanovu" -</code></pre> - --- транслитерация русских букв в строке. - - -h2. Ruby on Rails - -h3. Переводы - -При использовании с Ruby on Rails загружаются все стандартные переводы, и русский язык становится годным к использованию для локализации. В поставку включены все нужные переводы для ActionView, ActiveRecord, ActiveSupport, которые можно переопределять по необходимости стандартными средствами I18n. - -h3. Хелперы - -Хелперы даты-времени получают ключ @:use_standalone_month_names@ для форсирования отображения отдельностоящего названия месяца ("Сентябрь" а не "сентября"). Такое имя месяца используется когда включен ключ @:use_standalone_month_names@ (для отдельностоящего @select_month@ он включается по умолчанию), либо когда есть ключ @:discard_day@. - -В Russian включен плагин i18n_label, который подставляет в форм-хелпер @label@ перевод атрибута из таблицы переводов I18n. Например: - -* в файле переводов: - -<pre><code> -ru: - activerecord: - attributes: - user: - name: "Имя" -</code></pre> - -* во view: - -<pre><code> -<% form_for @user do |f| %> - <%= f.label :name %> -<% end %> -</code></pre> - -Даст: - -<pre><code> -<label for="user_name">Имя</label> -</code></pre> - -h3. Валидация - -До версии Rails 2.3.4 форматирование сообщений об ошибках не было гибким, и для нормального отображения ошибок на русском языке приходилось испольковать хаки. Если вы используете Rails 2.3.4 и выше, пропустите этот пункт (используйте ключ переводов @activerecord.errors.full_messages.format@). - -Для Rails 2.3.3 и ниже обработка ошибок в ActiveRecord перегружается -- в Russian включен популярный плагин custom_error_message, с помощью которого можно переопределять стандартное отображение сообщений об ошибках. Так, например, - -@validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение'@ - -даст сообщение - -@Accepted terms нужно принять соглашение@ - -или, например - -@Соглашение об использовании нужно принять соглашение@ - -если вы указали перевод для имени атрибута. - -Но - -@validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение'@ - -даст сообщение - -@Нужно принять соглашение@ - -_NB:_ в сообщениях валидации можно использовать такие макросы как @{{attribute}}@, @{{value}}@ -- подробнее см. документацию по I18n. - -h3. Параметризация строк - -Перегружается метод @parameterize@ инфлектора ActiveSupport (он же -- @String#parameterize@), теперь в нем идет транслитерация букв русского алфавита. - -Пример: - -<pre><code> -class Person - def to_param - "#{id}-#{name.parameterize}" - end -end - -@person = Person.find(1) -# => #<Person id: 1, name: "Дональд Кнут"> - -<%= link_to(@person.name, person_path(@person)) %> -# => <a href="/person/1-donald-knut">Дональд Кнут</a> -</code></pre> - -h1. Авторы - -Для сообщений об ошибках, обнаруженных неточностях и предложений: - -* "Ярослав Маркин":http://yaroslav.markin.net ("yaroslav@markin.net":mailto:yaroslav@markin.net) - -При участии: - -* "Юлика Тарханова":http://julik.nl -* "Евгения Пименова":http://libc.st/ -* "Дмитрия Смалько":http://github.com/dsmalko -* "Алексея Фортуны":http://github.com/dadooda -* "Антона Агеева":http://blog.antage.name/ -* "Александра Семенова":http://rotuka.com/ -* "valodzka":http://github.com/valodzka - -Огромное спасибо: - -"Юлику Тарханову":http://julik.nl за "rutils":http://rutils.rubyforge.org/ diff --git a/vendor/plugins/russian/Rakefile b/vendor/plugins/russian/Rakefile deleted file mode 100644 index 1b8d90e..0000000 --- a/vendor/plugins/russian/Rakefile +++ /dev/null @@ -1,55 +0,0 @@ -require 'rubygems' -require 'rake/gempackagetask' -require 'spec/rake/spectask' -require 'rubygems/specification' -require 'date' - -GEM = "russian" -GEM_VERSION = "0.2.5" -AUTHOR = "Yaroslav Markin" -EMAIL = "yaroslav@markin.net" -HOMEPAGE = "http://github.com/yaroslav/russian/" -SUMMARY = "Russian language support for Ruby and Rails" - -spec = Gem::Specification.new do |s| - s.name = GEM - s.version = GEM_VERSION - s.platform = Gem::Platform::RUBY - s.has_rdoc = true - s.extra_rdoc_files = ["README.textile", "LICENSE", "CHANGELOG", "TODO"] - s.summary = SUMMARY - s.description = s.summary - s.author = AUTHOR - s.email = EMAIL - s.homepage = HOMEPAGE - - # Uncomment this to add a dependency - # s.add_dependency "foo" - - s.require_path = 'lib' - s.autorequire = GEM - s.files = %w(LICENSE README.textile Rakefile CHANGELOG TODO init.rb) + Dir.glob("{lib,spec}/**/*") -end - -Rake::GemPackageTask.new(spec) do |pkg| - pkg.gem_spec = spec -end - -task :default => :spec -desc "Run specs" -Spec::Rake::SpecTask.new do |t| - t.spec_files = FileList['spec/**/*_spec.rb'] - t.spec_opts = %w(-fs --color) -end - -desc "install the gem locally" -task :install => [:package] do - sh %{sudo gem install pkg/#{GEM}-#{GEM_VERSION}} -end - -desc "create a gemspec file" -task :make_spec do - File.open("#{GEM}.gemspec", "w") do |file| - file.puts spec.to_ruby - end -end diff --git a/vendor/plugins/russian/TODO b/vendor/plugins/russian/TODO deleted file mode 100644 index b8a8be2..0000000 --- a/vendor/plugins/russian/TODO +++ /dev/null @@ -1,10 +0,0 @@ -TODO -==== -* RDoc -* check Unicode CLDR to ensure all datetime formats are correct -* refactor Advanced backend localize method (looks ugly) -* refactor DateTimeSelector#translated_month_names - -Questionable -============ -* integration specs for rails hacks diff --git a/vendor/plugins/russian/init.rb b/vendor/plugins/russian/init.rb deleted file mode 100644 index 3c96a6d..0000000 --- a/vendor/plugins/russian/init.rb +++ /dev/null @@ -1,3 +0,0 @@ -# Rails plugin init -require 'russian' - diff --git a/vendor/plugins/russian/lib/russian.rb b/vendor/plugins/russian/lib/russian.rb deleted file mode 100644 index 38d6116..0000000 --- a/vendor/plugins/russian/lib/russian.rb +++ /dev/null @@ -1,119 +0,0 @@ -# -*- encoding: utf-8 -*- - -if RUBY_VERSION < "1.9" - $KCODE = 'u' -end - -$:.push File.join(File.dirname(__FILE__), 'russian') -require 'transliteration' - -# I18n require -unless defined?(I18n) - $:.push File.join(File.dirname(__FILE__), 'vendor', 'i18n', 'lib') - require 'i18n' -end -# Advanced backend -require 'backend/advanced' - -# Rails hacks -require 'active_record_ext/custom_error_message' if defined?(ActiveRecord) -if defined?(ActionView::Helpers) - require 'action_view_ext/helpers/date_helper' - require 'vendor/i18n_label/init' -end -require 'active_support_ext/parameterize' if defined?(ActiveSupport::Inflector) - -module Russian - extend self - - module VERSION - MAJOR = 0 - MINOR = 2 - TINY = 5 - - STRING = [MAJOR, MINOR, TINY].join('.') - end - - # Russian locale - LOCALE = :'ru' - - # Russian locale - def locale - LOCALE - end - - # Returns custom backend class for usage with Russian library - # - # See I18n::Backend - def i18n_backend_class - I18n::Backend::Advanced - end - - # Init Russian i18n: set custom backend, set default locale to Russian locale, load all translations - # shipped with library. - def init_i18n - I18n.backend = Russian.i18n_backend_class.new - I18n.default_locale = LOCALE - I18n.load_path.unshift(*locale_files) - end - - # See I18n::translate - def translate(key, options = {}) - I18n.translate(key, options.merge({ :locale => LOCALE })) - end - alias :t :translate - - # See I18n::localize - def localize(object, options = {}) - I18n.localize(object, options.merge({ :locale => LOCALE })) - end - alias :l :localize - - # strftime() proxy with Russian localization - def strftime(object, format = :default) - localize(object, { :format => format }) - end - - # Simple pluralization proxy - # - # Usage: - # Russian.pluralize(1, "вещь", "вещи", "вещей") - # Russian.pluralize(3.14, "вещь", "вещи", "вещей", "вещи") - def pluralize(n, *variants) - raise ArgumentError, "Must have a Numeric as a first parameter" unless n.is_a?(Numeric) - raise ArgumentError, "Must have at least 3 variants for pluralization" if variants.size < 3 - raise ArgumentError, "Must have at least 4 variants for pluralization" if (variants.size < 4 && n != n.round) - variants_hash = pluralization_variants_to_hash(*variants) - I18n.backend.send(:pluralize, LOCALE, variants_hash, n) - end - alias :p :pluralize - - # Transliteration for russian language - # - # Usage: - # Russian.translit("рубин") - # Russian.transliterate("рубин") - def transliterate(str) - Russian::Transliteration.transliterate(str) - end - alias :translit :transliterate - - protected - # Returns all locale files shipped with library - def locale_files - Dir[File.join(File.dirname(__FILE__), "russian", "locale", "**/*")] - end - - # Converts an array of pluralization variants to a Hash that can be used - # with I18n pluralization. - def pluralization_variants_to_hash(*variants) - { - :one => variants[0], - :few => variants[1], - :many => variants[2], - :other => variants[3] - } - end -end - -Russian.init_i18n diff --git a/vendor/plugins/russian/lib/russian/action_view_ext/helpers/date_helper.rb b/vendor/plugins/russian/lib/russian/action_view_ext/helpers/date_helper.rb deleted file mode 100644 index cf631fe..0000000 --- a/vendor/plugins/russian/lib/russian/action_view_ext/helpers/date_helper.rb +++ /dev/null @@ -1,112 +0,0 @@ -# -*- encoding: utf-8 -*- - -# Заменяет хелпер Rails <tt>select_month</tt> и метод <tt>translated_month_names</tt> -# для поддержки функционала "отдельностоящих имен месяцев". -# -# Теперь можно использовать и полные, и сокращенные название месяцев в двух вариантах -- контекстном -# (по умолчанию) и отдельностоящем (если в текущем языке есть соответствующие переводы). -# Теперь хелперы поддерживают ключ <tt>:use_standalone_month_names</tt>, хелпер <tt>select_month</tt> -# устанавливает его по умолчанию. -# Отдельностоящие имена месяцев также используютс когда указан ключ <tt>:discard_day</tt>. -# -# -# Replaces Rails <tt>select_month</tt> helper and <tt>translated_month_names</tt> private method to provide -# "standalone month names" feature. -# -# It is now possible to use both abbreviated and full month names in two variants (if current locale provides them). -# All date helpers support <tt>:use_standalone_month_names</tt> key now, <tt>select_month</tt> helper sets -# it to true by default. -# Standalone month names are also used when <tt>:discard_day</tt> key is provided. -if defined?(ActionView::Helpers::DateTimeSelector) && ActionView::Helpers::DateTimeSelector.private_instance_methods.include?("translated_month_names") - module ActionView - module Helpers - module DateHelper - # Returns a select tag with options for each of the months January through December with the current month - # selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are - # used as values (what's submitted to the server). It's also possible to use month numbers for the presentation - # instead of names -- set the <tt>:use_month_numbers</tt> key in +options+ to true for this to happen. If you - # want both numbers and names, set the <tt>:add_month_numbers</tt> key in +options+ to true. If you would prefer - # to show month names as abbreviations, set the <tt>:use_short_month</tt> key in +options+ to true. If you want - # to use your own month names, set the <tt>:use_month_names</tt> key in +options+ to an array of 12 month names. - # You can also choose if you want to use i18n standalone month names or default month names -- you can - # force standalone month names usage by using <tt>:use_standalone_month_names</tt> key. - # Override the field name using the <tt>:field_name</tt> option, 'month' by default. - # - # - # Также поддерживается ключ <tt>:use_standalone_month_names</tt> для явного указания о необходимости - # использования отдельностоящих имен месяцев, если текущий язык их поддерживает. - # - # - # ==== Examples - # # Generates a select field for months that defaults to the current month that - # # will use keys like "January", "March". - # select_month(Date.today) - # - # # Generates a select field for months that defaults to the current month that - # # is named "start" rather than "month" - # select_month(Date.today, :field_name => 'start') - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "1", "3". - # select_month(Date.today, :use_month_numbers => true) - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "1 - January", "3 - March". - # select_month(Date.today, :add_month_numbers => true) - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "Jan", "Mar". - # select_month(Date.today, :use_short_month => true) - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "Januar", "Marts." - # select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...)) - # - def select_month(date, options = {}, html_options = {}) - DateTimeSelector.new(date, options.merge(:use_standalone_month_names => true), html_options).select_month - end - end - - class DateTimeSelector #:nodoc: - private - # Returns translated month names - # => [nil, "January", "February", "March", - # "April", "May", "June", "July", - # "August", "September", "October", - # "November", "December"] - # - # If :use_short_month option is set - # => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", - # "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - # - # Also looks up if <tt>:discard_day</tt> or <tt>:use_standalone_month_names</tt> option is set - # and uses i18n standalone month names if so. - # - # - # Также в зависимости от использования ключей <tt>:discard_day</tt> или <tt>:use_standalone_month_names</tt> - # убеждается, есть ли соотвествующие переводы в текущем языке и использует "отдельностоящие" названия - # месяцев по необходимости - def translated_month_names - begin - if @options[:use_short_month] - if (@options[:discard_day] || @options[:use_standalone_month_names]) && I18n.translate(:'date.standalone_abbr_month_names') - key = :'date.standalone_abbr_month_names' - else - key = :'date.abbr_month_names' - end - else - if (@options[:discard_day] || @options[:use_standalone_month_names]) && I18n.translate(:'date.standalone_month_names') - key = :'date.standalone_month_names' - else - key = :'date.month_names' - end - end - - I18n.translate(key, :locale => @options[:locale]) - end - end - - end - end - end -end # if defined? \ No newline at end of file diff --git a/vendor/plugins/russian/lib/russian/active_record_ext/custom_error_message.rb b/vendor/plugins/russian/lib/russian/active_record_ext/custom_error_message.rb deleted file mode 100644 index 0c368fa..0000000 --- a/vendor/plugins/russian/lib/russian/active_record_ext/custom_error_message.rb +++ /dev/null @@ -1,163 +0,0 @@ -# -*- encoding: utf-8 -*- - -if defined?(ActiveRecord::Error) # Rails 2.3.4+ - module ActiveRecord - class Error - protected - if instance_methods.include?('default_options') # Rails 2.3.5+ - # Redefine the ActiveRecord::Error::generate_full_message method: - # Returns all the full error messages in an array. 'Base' messages are handled as usual. - # Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^' - # in which case the attribute name is omitted. - # E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service' - # - # - # Переопределяет метод ActiveRecord::Error::generate_full_message. Сообщения об ошибках для атрибутов - # теперь не имеют префикса с названием атрибута если в сообщении об ошибке первым символом указан "^". - # - # Так, например, - # - # validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение' - # - # даст сообщение - # - # Accepted terms нужно принять соглашение - # - # однако, - # - # validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение' - # - # даст сообщение - # - # Нужно принять соглашение - def generate_full_message(options = {}) - keys = [ - :"full_messages.#{@message}", - :'full_messages.format', - '{{attribute}} {{message}}' - ] - - if self.message.is_a?(String) && self.message =~ /^\^/ - ActiveSupport::Deprecation.warn("Using '^' hack for ActiveRecord error messages has been deprecated. Please use errors.full_messages.format I18n key for formatting") - - options[:full_message] = self.message[1..-1] - - keys = [ - :"full_messages.#{@message}", - '{{full_message}}' - ] - else - keys = [ - :"full_messages.#{@message}", - :'full_messages.format', - '{{attribute}} {{message}}' - ] - end - - options.merge!(:default => keys, :message => self.message) - - I18n.translate(keys.shift, options) - end - else # Rails 2.3.4 - # Redefine the ActiveRecord::Error::generate_full_message method: - # Returns all the full error messages in an array. 'Base' messages are handled as usual. - # Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^' - # in which case the attribute name is omitted. - # E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service' - # - # - # Переопределяет метод ActiveRecord::Error::generate_full_message. Сообщения об ошибках для атрибутов - # теперь не имеют префикса с названием атрибута если в сообщении об ошибке первым символом указан "^". - # - # Так, например, - # - # validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение' - # - # даст сообщение - # - # Accepted terms нужно принять соглашение - # - # однако, - # - # validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение' - # - # даст сообщение - # - # Нужно принять соглашение - def generate_full_message(message, options = {}) - options.reverse_merge! :message => self.message, - :model => @base.class.human_name, - :attribute => @base.class.human_attribute_name(attribute.to_s), - :value => value - - key = :"full_messages.#{@message}" - defaults = [:'full_messages.format', '{{attribute}} {{message}}'] - - if options[:message].is_a?(String) && options[:message] =~ /^\^/ - ActiveSupport::Deprecation.warn("Using '^' hack for ActiveRecord error messages has been deprecated. Please use errors.full_messages.format I18n key for formatting") - - options[:full_message] = options[:message][1..-1] - defaults = [:"full_messages.#{@message}.format", '{{full_message}}'] - end - - I18n.t(key, options.merge(:default => defaults, :scope => [:activerecord, :errors])) - end - end - end - end - -else # Rails 2.3.3- - module ActiveRecord - class Errors - # DEPRECATED as of Rails 2.3.4 - # - # The following is taken from custom_error_message plugin by David Easley - # (http://rubyforge.org/projects/custom-err-msg/) - # - # Redefine the ActiveRecord::Errors::full_messages method: - # Returns all the full error messages in an array. 'Base' messages are handled as usual. - # Non-base messages are prefixed with the attribute name as usual UNLESS they begin with '^' - # in which case the attribute name is omitted. - # E.g. validates_acceptance_of :accepted_terms, :message => '^Please accept the terms of service' - # - # - # Переопределяет метод ActiveRecord::Errors::full_messages. Сообщения об ошибках для атрибутов - # теперь не имеют префикса с названием атрибута если в сообщении об ошибке первым символом указан "^". - # - # Так, например, - # - # validates_acceptance_of :accepted_terms, :message => 'нужно принять соглашение' - # - # даст сообщение - # - # Accepted terms нужно принять соглашение - # - # однако, - # - # validates_acceptance_of :accepted_terms, :message => '^Нужно принять соглашение' - # - # даст сообщение - # - # Нужно принять соглашение - def full_messages - full_messages = [] - - @errors.each_key do |attr| - @errors[attr].each do |msg| - next if msg.nil? - - if attr == "base" - full_messages << msg - elsif msg =~ /^\^/ - full_messages << msg[1..-1] - else - full_messages << @base.class.human_attribute_name(attr) + " " + msg - end - end - end - - return full_messages - end - end - end -end diff --git a/vendor/plugins/russian/lib/russian/active_support_ext/parameterize.rb b/vendor/plugins/russian/lib/russian/active_support_ext/parameterize.rb deleted file mode 100644 index dd89b02..0000000 --- a/vendor/plugins/russian/lib/russian/active_support_ext/parameterize.rb +++ /dev/null @@ -1,31 +0,0 @@ -# -*- encoding: utf-8 -*- - -module ActiveSupport - module Inflector - # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. - # Transliterates all russian characters in string first, then passes it to ActiveSupport Inflector. - # - # Заменяет все спецсимволы в строке так, что результат может использоваться как часть "красивого" URL. - # От стандартного ActiveSupport Inflector отличается тем, что сначала производится транслитерация - # букв русского алфавита. - # - # ==== Examples - # - # class Person - # def to_param - # "#{id}-#{name.parameterize}" - # end - # end - # - # @person = Person.find(1) - # # => #<Person id: 1, name: "Дональд Кнут"> - # - # <%= link_to(@person.name, person_path %> - # # => <a href="/person/1-donald-knut">Дональд Кнут</a> - def parameterize_with_russian(string, sep = '-') - parameterize_without_russian(Russian::transliterate(string), sep) - end - alias_method :parameterize_without_russian, :parameterize - alias_method :parameterize, :parameterize_with_russian - end -end diff --git a/vendor/plugins/russian/lib/russian/backend/advanced.rb b/vendor/plugins/russian/lib/russian/backend/advanced.rb deleted file mode 100644 index 936283c..0000000 --- a/vendor/plugins/russian/lib/russian/backend/advanced.rb +++ /dev/null @@ -1,132 +0,0 @@ -# -*- encoding: utf-8 -*- - -module I18n - module Backend - # "Продвинутый" бекэнд для I18n. - # - # Наследует Simple бекэнд и полностью с ним совместим. Добаляет поддержку - # для отдельностоящих/контекстных названий дней недели и месяцев. - # Также позволяет каждому языку использовать собственные правила плюрализации, - # объявленные как Proc (<tt>lambda</tt>). - # - # - # Advanced I18n backend. - # - # Extends Simple backend. Allows usage of "standalone" keys - # for DateTime localization and usage of user-defined Proc (lambda) pluralization - # methods in translation tables. - class Advanced < Simple - LOCALIZE_ABBR_MONTH_NAMES_MATCH = /(%d|%e)?(\s*)(%b)/ - LOCALIZE_MONTH_NAMES_MATCH = /(%d|%e)?(\s*)(%B)/ - LOCALIZE_STANDALONE_ABBR_DAY_NAMES_MATCH = /^%a/ - LOCALIZE_STANDALONE_DAY_NAMES_MATCH = /^%A/ - - # Acts the same as +strftime+, but returns a localized version of the - # formatted date string. Takes a key from the date/time formats - # translations as a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>). - # - # - # Метод отличается от <tt>localize</tt> в Simple бекэнде поддержкой - # отдельностоящих/контекстных названий дней недели и месяцев. - # - # - # Note that it differs from <tt>localize</tt> in Simple< backend by checking for - # "standalone" month name/day name keys in translation and using them if available. - def localize(locale, object, format = :default) - raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime) - - type = object.respond_to?(:sec) ? 'time' : 'date' - # TODO only translate these if format is a String? - formats = translate(locale, :"#{type}.formats") - format = formats[format.to_sym] if formats && formats[format.to_sym] - # TODO raise exception unless format found? - format = format.to_s.dup - - # TODO only translate these if the format string is actually present - # TODO check which format strings are present, then bulk translate then, then replace them - - if lookup(locale, :"date.standalone_abbr_day_names") - format.gsub!(LOCALIZE_STANDALONE_ABBR_DAY_NAMES_MATCH, - translate(locale, :"date.standalone_abbr_day_names")[object.wday]) - end - format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday]) - - if lookup(locale, :"date.standalone_day_names") - format.gsub!(LOCALIZE_STANDALONE_DAY_NAMES_MATCH, - translate(locale, :"date.standalone_day_names")[object.wday]) - end - format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday]) - - if lookup(locale, :"date.standalone_abbr_month_names") - format.gsub!(LOCALIZE_ABBR_MONTH_NAMES_MATCH) do - $1 ? $1 + $2 + translate(locale, :"date.abbr_month_names")[object.mon] : - $2 + translate(locale, :"date.standalone_abbr_month_names")[object.mon] - end - else - format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon]) - end - - if lookup(locale, :"date.standalone_month_names") - format.gsub!(LOCALIZE_MONTH_NAMES_MATCH) do - $1 ? $1 + $2 + translate(locale, :"date.month_names")[object.mon] : - $2 + translate(locale, :"date.standalone_month_names")[object.mon] - end - else - format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon]) - end - - format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour - object.strftime(format) - end - - protected - # Использует правила плюрализации из таблицы переводов для языка (если присутствуют), - # иначе использует правило плюрализации по умолчанию (английский язык). - # - # Пример задания правила в таблице переводов: - # - # store_translations :'en', { - # :pluralize => lambda { |n| n == 1 ? :one : :other } - # } - # - # Правило должно возвращать один из символов для таблицы переводов: - # :zero, :one, :two, :few, :many, :other - # - # - # Picks a pluralization rule specified in translation tables for a language or - # uses default pluralization rules. - # - # This is how pluralization rules are defined in translation tables, English - # language for example: - # - # store_translations :'en', { - # :pluralize => lambda { |n| n == 1 ? :one : :other } - # } - # - # Rule must return a symbol to use with pluralization, it must be one of: - # :zero, :one, :two, :few, :many, :other - def pluralize(locale, entry, count) - return entry unless entry.is_a?(Hash) and count - - key = :zero if count == 0 && entry.has_key?(:zero) - locale_pluralize = lookup(locale, :pluralize) - if locale_pluralize && locale_pluralize.respond_to?(:call) - key ||= locale_pluralize.call(count) - else - key ||= default_pluralizer(count) - end - raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key) - - entry[key] - end - - # Default pluralizer, used if pluralization rule is not defined in translations. - # - # Uses English pluralization rules -- it will pick the first translation if count is not equal to 1 - # and the second translation if it is equal to 1. - def default_pluralizer(count) - count == 1 ? :one : :other - end - end - end -end diff --git a/vendor/plugins/russian/lib/russian/locale/actionview.yml b/vendor/plugins/russian/lib/russian/locale/actionview.yml deleted file mode 100644 index f0ca91d..0000000 --- a/vendor/plugins/russian/lib/russian/locale/actionview.yml +++ /dev/null @@ -1,162 +0,0 @@ -ru: - number: - # Используется в number_with_delimiter() - # Также является установками по умолчанию для 'currency', 'percentage', 'precision', 'human' - # - # Used in number_with_delimiter() - # These are also the defaults for 'currency', 'percentage', 'precision', and 'human' - format: - # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5) - separator: "." - # Delimets thousands (e.g. 1,000,000 is a million) (always in groups of three) - delimiter: " " - # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00) - precision: 3 - - # Used in number_to_currency() - currency: - format: - # Формат отображения валюты и обозначение самой валюты - # - # - # Where is the currency sign? %u is the currency unit, %n the number (default: $5.00) - format: "%n %u" - unit: "руб." - # These three are to override number.format and are optional - separator: "." - delimiter: " " - precision: 2 - - # Used in number_to_percentage() - percentage: - format: - # These three are to override number.format and are optional - # separator: - delimiter: "" - - # Used in number_to_precision() - precision: - format: - # These three are to override number.format and are optional - # separator: - delimiter: "" - # precision: - - # Used in number_to_human_size() - human: - format: - # These three are to override number.format and are optional - # separator: - delimiter: "" - precision: 1 - - # Rails 2.2 - # storage_units: [байт, КБ, МБ, ГБ, ТБ] - - # Rails 2.3 - storage_units: - # Storage units output formatting. - # %u is the storage unit, %n is the number (default: 2 MB) - format: "%n %u" - units: - byte: - one: "байт" - few: "байта" - many: "байт" - other: "байта" - kb: "КБ" - mb: "МБ" - gb: "ГБ" - tb: "ТБ" - - # Используется в хелперах distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words() - # - # - # Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words() - datetime: - distance_in_words: - half_a_minute: "меньше минуты" - less_than_x_seconds: - one: "меньше {{count}} секунды" - few: "меньше {{count}} секунд" - many: "меньше {{count}} секунд" - other: "меньше {{count}} секунды" - x_seconds: - one: "{{count}} секунда" - few: "{{count}} секунды" - many: "{{count}} секунд" - other: "{{count}} секунды" - less_than_x_minutes: - one: "меньше {{count}} минуты" - few: "меньше {{count}} минут" - many: "меньше {{count}} минут" - other: "меньше {{count}} минуты" - x_minutes: - one: "{{count}} минуту" - few: "{{count}} минуты" - many: "{{count}} минут" - other: "{{count}} минуты" - about_x_hours: - one: "около {{count}} часа" - few: "около {{count}} часов" - many: "около {{count}} часов" - other: "около {{count}} часа" - x_days: - one: "{{count}} день" - few: "{{count}} дня" - many: "{{count}} дней" - other: "{{count}} дня" - about_x_months: - one: "около {{count}} месяца" - few: "около {{count}} месяцев" - many: "около {{count}} месяцев" - other: "около {{count}} месяца" - x_months: - one: "{{count}} месяц" - few: "{{count}} месяца" - many: "{{count}} месяцев" - other: "{{count}} месяца" - about_x_years: - one: "около {{count}} года" - few: "около {{count}} лет" - many: "около {{count}} лет" - other: "около {{count}} лет" - over_x_years: - one: "больше {{count}} года" - few: "больше {{count}} лет" - many: "больше {{count}} лет" - other: "больше {{count}} лет" - almost_x_years: - one: "почти {{count}} год" - few: "почти {{count}} года" - many: "почти {{count}} лет" - other: "почти {{count}} лет" - prompts: - year: "Год" - month: "Месяц" - day: "День" - hour: "Часов" - minute: "Минут" - second: "Секунд" - - # Используется в хелпере error_messages_for - activerecord: - errors: - template: - # Заголовок сообщения об ошибке - header: - one: "{{model}}: сохранение не удалось из-за {{count}} ошибки" - few: "{{model}}: сохранение не удалось из-за {{count}} ошибок" - many: "{{model}}: сохранение не удалось из-за {{count}} ошибок" - other: "{{model}}: сохранение не удалось из-за {{count}} ошибки" - - # Первый параграф сообщения об ошибке. Можно использовать макрос {{count}} - # - # - # The variable :count is also available - body: "Проблемы возникли со следующими полями:" - - support: - select: - # default value for :prompt => true in FormOptionsHelper - prompt: "Выберите: " diff --git a/vendor/plugins/russian/lib/russian/locale/activerecord.yml b/vendor/plugins/russian/lib/russian/locale/activerecord.yml deleted file mode 100644 index 0e61c13..0000000 --- a/vendor/plugins/russian/lib/russian/locale/activerecord.yml +++ /dev/null @@ -1,95 +0,0 @@ -ru: - activerecord: - # Сообщения об ошибке (валидации) ActiveRecord - errors: - # Для всех сообщений доступны макросы {{model}}, {{attribute}}, {{value}}. - # Для некоторых доступен макрос {{count}} -- в этом случае можно задать несколько вариантов - # сообщения (плюрализация) - # - # Также можно использовать сообщения, начинающиеся с "^" -- в этом случае - # в списке ошибок валидации перед конкретным сообщением не будет выводиться имя атрибута. - # - # - # The values :model, :attribute and :value are always available for interpolation - # The value :count is available when applicable. Can be used for pluralization. - # - # You can use ^-prefixed messages as well to get rid of human attribute name appearing - # before your message in validation messages. - messages: - inclusion: "имеет непредусмотренное значение" - exclusion: "имеет зарезервированное значение" - invalid: "имеет неверное значение" - confirmation: "не совпадает с подтверждением" - accepted: "нужно подтвердить" - empty: "не может быть пустым" - blank: "не может быть пустым" - too_long: - one: "слишком большой длины (не может быть больше чем {{count}} символ)" - few: "слишком большой длины (не может быть больше чем {{count}} символа)" - many: "слишком большой длины (не может быть больше чем {{count}} символов)" - other: "слишком большой длины (не может быть больше чем {{count}} символа)" - too_short: - one: "недостаточной длины (не может быть меньше {{count}} символа)" - few: "недостаточной длины (не может быть меньше {{count}} символов)" - many: "недостаточной длины (не может быть меньше {{count}} символов)" - other: "недостаточной длины (не может быть меньше {{count}} символа)" - wrong_length: - one: "неверной длины (может быть длиной ровно {{count}} символ)" - few: "неверной длины (может быть длиной ровно {{count}} символа)" - many: "неверной длины (может быть длиной ровно {{count}} символов)" - other: "неверной длины (может быть длиной ровно {{count}} символа)" - taken: "уже существует" - not_a_number: "не является числом" - greater_than: "может иметь лишь значение большее {{count}}" - greater_than_or_equal_to: "может иметь лишь значение большее или равное {{count}}" - equal_to: "может иметь лишь значение, равное {{count}}" - less_than: "может иметь лишь значение меньшее чем {{count}}" - less_than_or_equal_to: "может иметь значение меньшее или равное {{count}}" - odd: "может иметь лишь четное значение" - even: "может иметь лишь нечетное значение" - record_invalid: "Возникли ошибки: {{errors}}" - - full_messages: - format: "{{attribute}} {{message}}" - - # Можно добавить собственные сообщения об ошибке тут или задавать их в контексте атрибута. - # - # - # Append your own errors here or at the model/attributes scope. - # - # - # Например, - # models: - # user: - # # Задает сообщение об ошибке (пустое значение) для атрибутов модели User - # # Можно использовать макросы {{model}}, {{attribute}}. - # # Также можно использовать сообщения, начинающиеся с "^" -- в этом случае - # # в списке ошибок валидации перед конкретным сообщением не будет выводиться имя атрибута. - # blank: "собственное сообщение об ошибке (пустой атрибут) для модели {{model}} и атрибута {{attribute}}" - # attributes: - # # Также можно задавать собственные сообщения об ошибке для конкретных атрибутов модели. - # # Ниже определим собственное сообщение об ошибке для атрибута name модели User. - # name: - # blank: "Атрибут {{attribute}} особенный -- у него свое сообщение об ошибке при пустом атрибуте" - models: - - # Перевод названий моделей. Используется в Model.human_name(). - # - #models: - # Например, - # user: "Пользователь" - # переведет модель User как "Пользователь". - # - # - # Overrides default messages - - # Перевод названий атрибутов моделей. Используется в Model.human_attribute_name(attribute). - #attributes: - # Например, - # user: - # name: "Имя" - # переведет атрибут name модели User как "Имя". - # - # - # Overrides model and default messages. - diff --git a/vendor/plugins/russian/lib/russian/locale/activesupport.yml b/vendor/plugins/russian/lib/russian/locale/activesupport.yml deleted file mode 100644 index b67c62e..0000000 --- a/vendor/plugins/russian/lib/russian/locale/activesupport.yml +++ /dev/null @@ -1,16 +0,0 @@ -ru: -# Используется в array.to_sentence -# -# -# Used in array.to_sentence. - support: - array: - # Rails 2.2 - sentence_connector: "и" - skip_last_comma: true - - # Rails 2.3 - words_connector: ", " - two_words_connector: " и " - last_word_connector: " и " - diff --git a/vendor/plugins/russian/lib/russian/locale/datetime.yml b/vendor/plugins/russian/lib/russian/locale/datetime.yml deleted file mode 100644 index 534c9f0..0000000 --- a/vendor/plugins/russian/lib/russian/locale/datetime.yml +++ /dev/null @@ -1,46 +0,0 @@ -ru: - date: - formats: - # Форматы указываются в виде, поддерживаемом strftime. - # По умолчанию используется default. - # Можно добавлять собственные форматы - # - # - # Use the strftime parameters for formats. - # When no format has been given, it uses default. - # You can provide other formats here if you like! - default: "%d.%m.%Y" - short: "%d %b" - long: "%d %B %Y" - - # Названия дней недели -- контекстные и отдельностоящие - day_names: [воскресенье, понедельник, вторник, среда, четверг, пятница, суббота] - standalone_day_names: [Воскресенье, Понедельник, Вторник, Среда, Четверг, Пятница, Суббота] - abbr_day_names: [Вс, Пн, Вт, Ср, Чт, Пт, Сб] - - # Названия месяцев -- сокращенные и полные, плюс отдельностоящие. - # Не забудьте nil в начале массиве (~) - # - # - # Don't forget the nil at the beginning; there's no such thing as a 0th month - month_names: [~, января, февраля, марта, апреля, мая, июня, июля, августа, сентября, октября, ноября, декабря] - standalone_month_names: [~, Январь, Февраль, Март, Апрель, Май, Июнь, Июль, Август, Сентябрь, Октябрь, Ноябрь, Декабрь] - abbr_month_names: [~, янв., февр., марта, апр., мая, июня, июля, авг., сент., окт., нояб., дек.] - standalone_abbr_month_names: [~, янв., февр., март, апр., май, июнь, июль, авг., сент., окт., нояб., дек.] - - # Порядок компонентов даты для хелперов - # - # - # Used in date_select and datime_select. - order: [ :day, :month, :year ] - - time: - # Форматы времени - formats: - default: "%a, %d %b %Y, %H:%M:%S %z" - short: "%d %b, %H:%M" - long: "%d %B %Y, %H:%M" - - # am/pm решено перевести как "утра/вечера" :) - am: "утра" - pm: "вечера" diff --git a/vendor/plugins/russian/lib/russian/locale/pluralize.rb b/vendor/plugins/russian/lib/russian/locale/pluralize.rb deleted file mode 100644 index 21f9dda..0000000 --- a/vendor/plugins/russian/lib/russian/locale/pluralize.rb +++ /dev/null @@ -1,25 +0,0 @@ -# -*- encoding: utf-8 -*- - -{ - :'ru' => { - :pluralize => lambda { |n| - # Правило плюрализации для русского языка, взято из CLDR, http://unicode.org/cldr/ - # - # - # Russian language pluralization rules, taken from CLDR project, http://unicode.org/cldr/ - # - # one -> n mod 10 is 1 and n mod 100 is not 11; - # few -> n mod 10 in 2..4 and n mod 100 not in 12..14; - # many -> n mod 10 is 0 or n mod 10 in 5..9 or n mod 100 in 11..14; - # other -> everything else - # - # Пример - # - # :one = 1, 21, 31, 41, 51, 61... - # :few = 2-4, 22-24, 32-34... - # :many = 0, 5-20, 25-30, 35-40... - # :other = 1.31, 2.31, 5.31... - n % 10 == 1 && n % 100 != 11 ? :one : [2, 3, 4].include?(n % 10) && ![12, 13, 14].include?(n % 100) ? :few : n % 10 == 0 || [5, 6, 7, 8, 9].include?(n % 10) || [11, 12, 13, 14].include?(n % 100) ? :many : :other - } - } -} \ No newline at end of file diff --git a/vendor/plugins/russian/lib/russian/transliteration.rb b/vendor/plugins/russian/lib/russian/transliteration.rb deleted file mode 100644 index 27f89af..0000000 --- a/vendor/plugins/russian/lib/russian/transliteration.rb +++ /dev/null @@ -1,72 +0,0 @@ -# -*- encoding: utf-8 -*- - -module Russian - # Russian transliteration - # - # Транслитерация для букв русского алфавита - module Transliteration - extend self - - # Transliteration heavily based on rutils gem by Julian "julik" Tarkhanov and Co. - # <http://rutils.rubyforge.org/> - # Cleaned up and optimized. - - LOWER_SINGLE = { - "і"=>"i","ґ"=>"g","ё"=>"yo","№"=>"#","є"=>"e", - "ї"=>"yi","а"=>"a","б"=>"b", - "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"zh", - "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l", - "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r", - "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h", - "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"'", - "ы"=>"y","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya", - } - LOWER_MULTI = { - "ье"=>"ie", - "ьё"=>"ie", - } - - UPPER_SINGLE = { - "Ґ"=>"G","Ё"=>"YO","Є"=>"E","Ї"=>"YI","І"=>"I", - "А"=>"A","Б"=>"B","В"=>"V","Г"=>"G", - "Д"=>"D","Е"=>"E","Ж"=>"ZH","З"=>"Z","И"=>"I", - "Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N", - "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T", - "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"TS","Ч"=>"CH", - "Ш"=>"SH","Щ"=>"SCH","Ъ"=>"'","Ы"=>"Y","Ь"=>"", - "Э"=>"E","Ю"=>"YU","Я"=>"YA", - } - UPPER_MULTI = { - "ЬЕ"=>"IE", - "ЬЁ"=>"IE", - } - - LOWER = (LOWER_SINGLE.merge(LOWER_MULTI)).freeze - UPPER = (UPPER_SINGLE.merge(UPPER_MULTI)).freeze - MULTI_KEYS = (LOWER_MULTI.merge(UPPER_MULTI)).keys.sort_by {|s| s.length}.reverse.freeze - - # Transliterate a string with russian characters - # - # Возвращает строку, в которой все буквы русского алфавита заменены на похожую по звучанию латиницу - def transliterate(str) - chars = str.scan(%r{#{MULTI_KEYS.join '|'}|\w|.}) - - result = "" - - chars.each_with_index do |char, index| - if UPPER.has_key?(char) && LOWER.has_key?(chars[index+1]) - # combined case - result << UPPER[char].downcase.capitalize - elsif UPPER.has_key?(char) - result << UPPER[char] - elsif LOWER.has_key?(char) - result << LOWER[char] - else - result << char - end - end - - result - end - end -end \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/.gitignore b/vendor/plugins/russian/lib/vendor/i18n/.gitignore deleted file mode 100644 index 0f41a39..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.DS_Store -test/rails/fixtures -doc diff --git a/vendor/plugins/russian/lib/vendor/i18n/MIT-LICENSE b/vendor/plugins/russian/lib/vendor/i18n/MIT-LICENSE deleted file mode 100755 index ed8e9ee..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2008 The Ruby I18n team - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/README.textile b/vendor/plugins/russian/lib/vendor/i18n/README.textile deleted file mode 100644 index a07fc84..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/README.textile +++ /dev/null @@ -1,20 +0,0 @@ -h1. Ruby I18n gem - -I18n and localization solution for Ruby. - -For information please refer to http://rails-i18n.org - -h2. Authors - -* "Matt Aimonetti":http://railsontherun.com -* "Sven Fuchs":http://www.artweb-design.de -* "Joshua Harvey":http://www.workingwithrails.com/person/759-joshua-harvey -* "Saimon Moore":http://saimonmoore.net -* "Stephan Soller":http://www.arkanis-development.de - -h2. License - -MIT License. See the included MIT-LICENCE file. - - - diff --git a/vendor/plugins/russian/lib/vendor/i18n/Rakefile b/vendor/plugins/russian/lib/vendor/i18n/Rakefile deleted file mode 100644 index 2164e13..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/Rakefile +++ /dev/null @@ -1,5 +0,0 @@ -task :default => [:test] - -task :test do - ruby "test/all.rb" -end diff --git a/vendor/plugins/russian/lib/vendor/i18n/i18n.gemspec b/vendor/plugins/russian/lib/vendor/i18n/i18n.gemspec deleted file mode 100644 index f102689..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/i18n.gemspec +++ /dev/null @@ -1,27 +0,0 @@ -Gem::Specification.new do |s| - s.name = "i18n" - s.version = "0.1.3" - s.date = "2009-01-09" - s.summary = "Internationalization support for Ruby" - s.email = "rails-i18n@googlegroups.com" - s.homepage = "http://rails-i18n.org" - s.description = "Add Internationalization support to your Ruby application." - s.has_rdoc = false - s.authors = ['Sven Fuchs', 'Joshua Harvey', 'Matt Aimonetti', 'Stephan Soller', 'Saimon Moore'] - s.files = [ - 'i18n.gemspec', - 'lib/i18n/backend/simple.rb', - 'lib/i18n/exceptions.rb', - 'lib/i18n.rb', - 'MIT-LICENSE', - 'README.textile' - ] - s.test_files = [ - 'test/all.rb', - 'test/i18n_exceptions_test.rb', - 'test/i18n_test.rb', - 'test/locale/en.rb', - 'test/locale/en.yml', - 'test/simple_backend_test.rb' - ] -end diff --git a/vendor/plugins/russian/lib/vendor/i18n/lib/i18n.rb b/vendor/plugins/russian/lib/vendor/i18n/lib/i18n.rb deleted file mode 100755 index 76361be..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/lib/i18n.rb +++ /dev/null @@ -1,199 +0,0 @@ -# Authors:: Matt Aimonetti (http://railsontherun.com/), -# Sven Fuchs (http://www.artweb-design.de), -# Joshua Harvey (http://www.workingwithrails.com/person/759-joshua-harvey), -# Saimon Moore (http://saimonmoore.net), -# Stephan Soller (http://www.arkanis-development.de/) -# Copyright:: Copyright (c) 2008 The Ruby i18n Team -# License:: MIT -require 'i18n/backend/simple' -require 'i18n/exceptions' - -module I18n - @@backend = nil - @@load_path = nil - @@default_locale = :'en' - @@exception_handler = :default_exception_handler - - class << self - # Returns the current backend. Defaults to +Backend::Simple+. - def backend - @@backend ||= Backend::Simple.new - end - - # Sets the current backend. Used to set a custom backend. - def backend=(backend) - @@backend = backend - end - - # Returns the current default locale. Defaults to :'en' - def default_locale - @@default_locale - end - - # Sets the current default locale. Used to set a custom default locale. - def default_locale=(locale) - @@default_locale = locale - end - - # Returns the current locale. Defaults to I18n.default_locale. - def locale - Thread.current[:locale] ||= default_locale - end - - # Sets the current locale pseudo-globally, i.e. in the Thread.current hash. - def locale=(locale) - Thread.current[:locale] = locale - end - - # Returns an array of locales for which translations are available - def available_locales - backend.available_locales - end - - # Sets the exception handler. - def exception_handler=(exception_handler) - @@exception_handler = exception_handler - end - - # Allow clients to register paths providing translation data sources. The - # backend defines acceptable sources. - # - # E.g. the provided SimpleBackend accepts a list of paths to translation - # files which are either named *.rb and contain plain Ruby Hashes or are - # named *.yml and contain YAML data. So for the SimpleBackend clients may - # register translation files like this: - # I18n.load_path << 'path/to/locale/en.yml' - def load_path - @@load_path ||= [] - end - - # Sets the load path instance. Custom implementations are expected to - # behave like a Ruby Array. - def load_path=(load_path) - @@load_path = load_path - end - - # Tells the backend to reload translations. Used in situations like the - # Rails development environment. Backends can implement whatever strategy - # is useful. - def reload! - backend.reload! - end - - # Translates, pluralizes and interpolates a given key using a given locale, - # scope, and default, as well as interpolation values. - # - # *LOOKUP* - # - # Translation data is organized as a nested hash using the upper-level keys - # as namespaces. <em>E.g.</em>, ActionView ships with the translation: - # <tt>:date => {:formats => {:short => "%b %d"}}</tt>. - # - # Translations can be looked up at any level of this hash using the key argument - # and the scope option. <em>E.g.</em>, in this example <tt>I18n.t :date</tt> - # returns the whole translations hash <tt>{:formats => {:short => "%b %d"}}</tt>. - # - # Key can be either a single key or a dot-separated key (both Strings and Symbols - # work). <em>E.g.</em>, the short format can be looked up using both: - # I18n.t 'date.formats.short' - # I18n.t :'date.formats.short' - # - # Scope can be either a single key, a dot-separated key or an array of keys - # or dot-separated keys. Keys and scopes can be combined freely. So these - # examples will all look up the same short date format: - # I18n.t 'date.formats.short' - # I18n.t 'formats.short', :scope => 'date' - # I18n.t 'short', :scope => 'date.formats' - # I18n.t 'short', :scope => %w(date formats) - # - # *INTERPOLATION* - # - # Translations can contain interpolation variables which will be replaced by - # values passed to #translate as part of the options hash, with the keys matching - # the interpolation variable names. - # - # <em>E.g.</em>, with a translation <tt>:foo => "foo {{bar}}"</tt> the option - # value for the key +bar+ will be interpolated into the translation: - # I18n.t :foo, :bar => 'baz' # => 'foo baz' - # - # *PLURALIZATION* - # - # Translation data can contain pluralized translations. Pluralized translations - # are arrays of singluar/plural versions of translations like <tt>['Foo', 'Foos']</tt>. - # - # Note that <tt>I18n::Backend::Simple</tt> only supports an algorithm for English - # pluralization rules. Other algorithms can be supported by custom backends. - # - # This returns the singular version of a pluralized translation: - # I18n.t :foo, :count => 1 # => 'Foo' - # - # These both return the plural version of a pluralized translation: - # I18n.t :foo, :count => 0 # => 'Foos' - # I18n.t :foo, :count => 2 # => 'Foos' - # - # The <tt>:count</tt> option can be used both for pluralization and interpolation. - # <em>E.g.</em>, with the translation - # <tt>:foo => ['{{count}} foo', '{{count}} foos']</tt>, count will - # be interpolated to the pluralized translation: - # I18n.t :foo, :count => 1 # => '1 foo' - # - # *DEFAULTS* - # - # This returns the translation for <tt>:foo</tt> or <tt>default</tt> if no translation was found: - # I18n.t :foo, :default => 'default' - # - # This returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> if no - # translation for <tt>:foo</tt> was found: - # I18n.t :foo, :default => :bar - # - # Returns the translation for <tt>:foo</tt> or the translation for <tt>:bar</tt> - # or <tt>default</tt> if no translations for <tt>:foo</tt> and <tt>:bar</tt> were found. - # I18n.t :foo, :default => [:bar, 'default'] - # - # <b>BULK LOOKUP</b> - # - # This returns an array with the translations for <tt>:foo</tt> and <tt>:bar</tt>. - # I18n.t [:foo, :bar] - # - # Can be used with dot-separated nested keys: - # I18n.t [:'baz.foo', :'baz.bar'] - # - # Which is the same as using a scope option: - # I18n.t [:foo, :bar], :scope => :baz - def translate(key, options = {}) - locale = options.delete(:locale) || I18n.locale - backend.translate(locale, key, options) - rescue I18n::ArgumentError => e - raise e if options[:raise] - send(@@exception_handler, e, locale, key, options) - end - alias :t :translate - - # Localizes certain objects, such as dates and numbers to local formatting. - def localize(object, options = {}) - locale = options[:locale] || I18n.locale - format = options[:format] || :default - backend.localize(locale, object, format) - end - alias :l :localize - - protected - # Handles exceptions raised in the backend. All exceptions except for - # MissingTranslationData exceptions are re-raised. When a MissingTranslationData - # was caught and the option :raise is not set the handler returns an error - # message string containing the key/scope. - def default_exception_handler(exception, locale, key, options) - return exception.message if MissingTranslationData === exception - raise exception - end - - # Merges the given locale, key and scope into a single array of keys. - # Splits keys that contain dots into multiple keys. Makes sure all - # keys are Symbols. - def normalize_translation_keys(locale, key, scope) - keys = [locale] + Array(scope) + [key] - keys = keys.map { |k| k.to_s.split(/\./) } - keys.flatten.map { |k| k.to_sym } - end - end -end diff --git a/vendor/plugins/russian/lib/vendor/i18n/lib/i18n/backend/simple.rb b/vendor/plugins/russian/lib/vendor/i18n/lib/i18n/backend/simple.rb deleted file mode 100644 index c09acd7..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/lib/i18n/backend/simple.rb +++ /dev/null @@ -1,214 +0,0 @@ -require 'yaml' - -module I18n - module Backend - class Simple - INTERPOLATION_RESERVED_KEYS = %w(scope default) - MATCH = /(\\\\)?\{\{([^\}]+)\}\}/ - - # Accepts a list of paths to translation files. Loads translations from - # plain Ruby (*.rb) or YAML files (*.yml). See #load_rb and #load_yml - # for details. - def load_translations(*filenames) - filenames.each { |filename| load_file(filename) } - end - - # Stores translations for the given locale in memory. - # This uses a deep merge for the translations hash, so existing - # translations will be overwritten by new ones only at the deepest - # level of the hash. - def store_translations(locale, data) - merge_translations(locale, data) - end - - def translate(locale, key, options = {}) - raise InvalidLocale.new(locale) if locale.nil? - return key.map { |k| translate(locale, k, options) } if key.is_a? Array - - reserved = :scope, :default - count, scope, default = options.values_at(:count, *reserved) - options.delete(:default) - values = options.reject { |name, value| reserved.include?(name) } - - entry = lookup(locale, key, scope) - if entry.nil? - entry = default(locale, default, options) - if entry.nil? - raise(I18n::MissingTranslationData.new(locale, key, options)) - end - end - entry = pluralize(locale, entry, count) - entry = interpolate(locale, entry, values) - entry - end - - # Acts the same as +strftime+, but returns a localized version of the - # formatted date string. Takes a key from the date/time formats - # translations as a format argument (<em>e.g.</em>, <tt>:short</tt> in <tt>:'date.formats'</tt>). - def localize(locale, object, format = :default) - raise ArgumentError, "Object must be a Date, DateTime or Time object. #{object.inspect} given." unless object.respond_to?(:strftime) - - type = object.respond_to?(:sec) ? 'time' : 'date' - # TODO only translate these if format is a String? - formats = translate(locale, :"#{type}.formats") - format = formats[format.to_sym] if formats && formats[format.to_sym] - # TODO raise exception unless format found? - format = format.to_s.dup - - # TODO only translate these if the format string is actually present - # TODO check which format strings are present, then bulk translate then, then replace them - format.gsub!(/%a/, translate(locale, :"date.abbr_day_names")[object.wday]) - format.gsub!(/%A/, translate(locale, :"date.day_names")[object.wday]) - format.gsub!(/%b/, translate(locale, :"date.abbr_month_names")[object.mon]) - format.gsub!(/%B/, translate(locale, :"date.month_names")[object.mon]) - format.gsub!(/%p/, translate(locale, :"time.#{object.hour < 12 ? :am : :pm}")) if object.respond_to? :hour - object.strftime(format) - end - - def initialized? - @initialized ||= false - end - - # Returns an array of locales for which translations are available - def available_locales - init_translations unless initialized? - translations.keys - end - - def reload! - @initialized = false - @translations = nil - end - - protected - def init_translations - load_translations(*I18n.load_path.flatten) - @initialized = true - end - - def translations - @translations ||= {} - end - - # Looks up a translation from the translations hash. Returns nil if - # eiher key is nil, or locale, scope or key do not exist as a key in the - # nested translations hash. Splits keys or scopes containing dots - # into multiple keys, i.e. <tt>currency.format</tt> is regarded the same as - # <tt>%w(currency format)</tt>. - def lookup(locale, key, scope = []) - return unless key - init_translations unless initialized? - keys = I18n.send(:normalize_translation_keys, locale, key, scope) - keys.inject(translations) do |result, k| - if (x = result[k.to_sym]).nil? - return nil - else - x - end - end - end - - # Evaluates a default translation. - # If the given default is a String it is used literally. If it is a Symbol - # it will be translated with the given options. If it is an Array the first - # translation yielded will be returned. - # - # <em>I.e.</em>, <tt>default(locale, [:foo, 'default'])</tt> will return +default+ if - # <tt>translate(locale, :foo)</tt> does not yield a result. - def default(locale, default, options = {}) - case default - when String then default - when Symbol then translate locale, default, options - when Array then default.each do |obj| - result = default(locale, obj, options.dup) and return result - end and nil - end - rescue MissingTranslationData - nil - end - - # Picks a translation from an array according to English pluralization - # rules. It will pick the first translation if count is not equal to 1 - # and the second translation if it is equal to 1. Other backends can - # implement more flexible or complex pluralization rules. - def pluralize(locale, entry, count) - return entry unless entry.is_a?(Hash) and count - # raise InvalidPluralizationData.new(entry, count) unless entry.is_a?(Hash) - key = :zero if count == 0 && entry.has_key?(:zero) - key ||= count == 1 ? :one : :other - raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key) - entry[key] - end - - # Interpolates values into a given string. - # - # interpolate "file {{file}} opened by \\{{user}}", :file => 'test.txt', :user => 'Mr. X' - # # => "file test.txt opened by {{user}}" - # - # Note that you have to double escape the <tt>\\</tt> when you want to escape - # the <tt>{{...}}</tt> key in a string (once for the string and once for the - # interpolation). - def interpolate(locale, string, values = {}) - return string unless string.is_a?(String) - - string.gsub(MATCH) do - escaped, pattern, key = $1, $2, $2.to_sym - - if escaped - pattern - elsif INTERPOLATION_RESERVED_KEYS.include?(pattern) - raise ReservedInterpolationKey.new(pattern, string) - elsif !values.include?(key) - raise MissingInterpolationArgument.new(pattern, string) - else - values[key].to_s - end - end - end - - # Loads a single translations file by delegating to #load_rb or - # #load_yml depending on the file extension and directly merges the - # data to the existing translations. Raises I18n::UnknownFileType - # for all other file extensions. - def load_file(filename) - type = File.extname(filename).tr('.', '').downcase - raise UnknownFileType.new(type, filename) unless respond_to?(:"load_#{type}") - data = send :"load_#{type}", filename # TODO raise a meaningful exception if this does not yield a Hash - data.each { |locale, d| merge_translations(locale, d) } - end - - # Loads a plain Ruby translations file. eval'ing the file must yield - # a Hash containing translation data with locales as toplevel keys. - def load_rb(filename) - eval(IO.read(filename), binding, filename) - end - - # Loads a YAML translations file. The data must have locales as - # toplevel keys. - def load_yml(filename) - YAML::load(IO.read(filename)) - end - - # Deep merges the given translations hash with the existing translations - # for the given locale - def merge_translations(locale, data) - locale = locale.to_sym - translations[locale] ||= {} - data = deep_symbolize_keys(data) - - # 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 } - translations[locale].merge!(data, &merger) - end - - # Return a new hash with all keys and nested keys converted to symbols. - def deep_symbolize_keys(hash) - hash.inject({}) { |result, (key, value)| - value = deep_symbolize_keys(value) if value.is_a? Hash - result[(key.to_sym rescue key) || key] = value - result - } - end - end - end -end \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/lib/i18n/exceptions.rb b/vendor/plugins/russian/lib/vendor/i18n/lib/i18n/exceptions.rb deleted file mode 100644 index b5cea7a..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/lib/i18n/exceptions.rb +++ /dev/null @@ -1,53 +0,0 @@ -module I18n - class ArgumentError < ::ArgumentError; end - - class InvalidLocale < ArgumentError - attr_reader :locale - def initialize(locale) - @locale = locale - super "#{locale.inspect} is not a valid locale" - end - end - - class MissingTranslationData < ArgumentError - attr_reader :locale, :key, :options - def initialize(locale, key, options) - @key, @locale, @options = key, locale, options - keys = I18n.send(:normalize_translation_keys, locale, key, options[:scope]) - keys << 'no key' if keys.size < 2 - super "translation missing: #{keys.join(', ')}" - end - end - - class InvalidPluralizationData < ArgumentError - attr_reader :entry, :count - def initialize(entry, count) - @entry, @count = entry, count - super "translation data #{entry.inspect} can not be used with :count => #{count}" - end - end - - class MissingInterpolationArgument < ArgumentError - attr_reader :key, :string - def initialize(key, string) - @key, @string = key, string - super "interpolation argument #{key} missing in #{string.inspect}" - end - end - - class ReservedInterpolationKey < ArgumentError - attr_reader :key, :string - def initialize(key, string) - @key, @string = key, string - super "reserved key #{key.inspect} used in #{string.inspect}" - end - end - - class UnknownFileType < ArgumentError - attr_reader :type, :filename - def initialize(type, filename) - @type, @filename = type, filename - super "can not load translations from #{filename}, the file type #{type} is not known" - end - end -end \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/test/all.rb b/vendor/plugins/russian/lib/vendor/i18n/test/all.rb deleted file mode 100644 index 353712d..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/test/all.rb +++ /dev/null @@ -1,5 +0,0 @@ -dir = File.dirname(__FILE__) -require dir + '/i18n_test.rb' -require dir + '/simple_backend_test.rb' -require dir + '/i18n_exceptions_test.rb' -# *require* dir + '/custom_backend_test.rb' \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/test/i18n_exceptions_test.rb b/vendor/plugins/russian/lib/vendor/i18n/test/i18n_exceptions_test.rb deleted file mode 100644 index dfcba69..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/test/i18n_exceptions_test.rb +++ /dev/null @@ -1,100 +0,0 @@ -$:.unshift "lib" - -require 'rubygems' -require 'test/unit' -require 'mocha' -require 'i18n' -require 'active_support' - -class I18nExceptionsTest < Test::Unit::TestCase - def test_invalid_locale_stores_locale - force_invalid_locale - rescue I18n::ArgumentError => e - assert_nil e.locale - end - - def test_invalid_locale_message - force_invalid_locale - rescue I18n::ArgumentError => e - assert_equal 'nil is not a valid locale', e.message - end - - def test_missing_translation_data_stores_locale_key_and_options - force_missing_translation_data - rescue I18n::ArgumentError => e - options = {:scope => :bar} - assert_equal 'de', e.locale - assert_equal :foo, e.key - assert_equal options, e.options - end - - def test_missing_translation_data_message - force_missing_translation_data - rescue I18n::ArgumentError => e - assert_equal 'translation missing: de, bar, foo', e.message - end - - def test_invalid_pluralization_data_stores_entry_and_count - force_invalid_pluralization_data - rescue I18n::ArgumentError => e - assert_equal [:bar], e.entry - assert_equal 1, e.count - end - - def test_invalid_pluralization_data_message - force_invalid_pluralization_data - rescue I18n::ArgumentError => e - assert_equal 'translation data [:bar] can not be used with :count => 1', e.message - end - - def test_missing_interpolation_argument_stores_key_and_string - force_missing_interpolation_argument - rescue I18n::ArgumentError => e - assert_equal 'bar', e.key - assert_equal "{{bar}}", e.string - end - - def test_missing_interpolation_argument_message - force_missing_interpolation_argument - rescue I18n::ArgumentError => e - assert_equal 'interpolation argument bar missing in "{{bar}}"', e.message - end - - def test_reserved_interpolation_key_stores_key_and_string - force_reserved_interpolation_key - rescue I18n::ArgumentError => e - assert_equal 'scope', e.key - assert_equal "{{scope}}", e.string - end - - def test_reserved_interpolation_key_message - force_reserved_interpolation_key - rescue I18n::ArgumentError => e - assert_equal 'reserved key "scope" used in "{{scope}}"', e.message - end - - private - def force_invalid_locale - I18n.backend.translate nil, :foo - end - - def force_missing_translation_data - I18n.backend.store_translations 'de', :bar => nil - I18n.backend.translate 'de', :foo, :scope => :bar - end - - def force_invalid_pluralization_data - I18n.backend.store_translations 'de', :foo => [:bar] - I18n.backend.translate 'de', :foo, :count => 1 - end - - def force_missing_interpolation_argument - I18n.backend.store_translations 'de', :foo => "{{bar}}" - I18n.backend.translate 'de', :foo, :baz => 'baz' - end - - def force_reserved_interpolation_key - I18n.backend.store_translations 'de', :foo => "{{scope}}" - I18n.backend.translate 'de', :foo, :baz => 'baz' - end -end \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/test/i18n_test.rb b/vendor/plugins/russian/lib/vendor/i18n/test/i18n_test.rb deleted file mode 100644 index bbb35ec..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/test/i18n_test.rb +++ /dev/null @@ -1,125 +0,0 @@ -$:.unshift "lib" - -require 'rubygems' -require 'test/unit' -require 'mocha' -require 'i18n' -require 'active_support' - -class I18nTest < Test::Unit::TestCase - def setup - I18n.backend.store_translations :'en', { - :currency => { - :format => { - :separator => '.', - :delimiter => ',', - } - } - } - end - - def test_uses_simple_backend_set_by_default - assert I18n.backend.is_a?(I18n::Backend::Simple) - end - - def test_can_set_backend - assert_nothing_raised{ I18n.backend = self } - assert_equal self, I18n.backend - I18n.backend = I18n::Backend::Simple.new - end - - def test_uses_en_us_as_default_locale_by_default - assert_equal 'en', I18n.default_locale - end - - def test_can_set_default_locale - assert_nothing_raised{ I18n.default_locale = 'de' } - assert_equal 'de', I18n.default_locale - I18n.default_locale = 'en' - end - - def test_uses_default_locale_as_locale_by_default - assert_equal I18n.default_locale, I18n.locale - end - - def test_can_set_locale_to_thread_current - assert_nothing_raised{ I18n.locale = 'de' } - assert_equal 'de', I18n.locale - assert_equal 'de', Thread.current[:locale] - I18n.locale = 'en' - end - - def test_can_set_exception_handler - assert_nothing_raised{ I18n.exception_handler = :custom_exception_handler } - I18n.exception_handler = :default_exception_handler # revert it - end - - def test_uses_custom_exception_handler - I18n.exception_handler = :custom_exception_handler - I18n.expects(:custom_exception_handler) - I18n.translate :bogus - I18n.exception_handler = :default_exception_handler # revert it - end - - def test_delegates_translate_to_backend - I18n.backend.expects(:translate).with 'de', :foo, {} - I18n.translate :foo, :locale => 'de' - end - - def test_delegates_localize_to_backend - I18n.backend.expects(:localize).with 'de', :whatever, :default - I18n.localize :whatever, :locale => 'de' - end - - def test_translate_given_no_locale_uses_i18n_locale - I18n.backend.expects(:translate).with 'en', :foo, {} - I18n.translate :foo - end - - def test_translate_on_nested_symbol_keys_works - assert_equal ".", I18n.t(:'currency.format.separator') - end - - def test_translate_with_nested_string_keys_works - assert_equal ".", I18n.t('currency.format.separator') - end - - def test_translate_with_array_as_scope_works - assert_equal ".", I18n.t(:separator, :scope => ['currency.format']) - end - - def test_translate_with_array_containing_dot_separated_strings_as_scope_works - assert_equal ".", I18n.t(:separator, :scope => ['currency.format']) - end - - def test_translate_with_key_array_and_dot_separated_scope_works - assert_equal [".", ","], I18n.t(%w(separator delimiter), :scope => 'currency.format') - end - - def test_translate_with_dot_separated_key_array_and_scope_works - assert_equal [".", ","], I18n.t(%w(format.separator format.delimiter), :scope => 'currency') - end - - def test_translate_with_options_using_scope_works - I18n.backend.expects(:translate).with('de', :precision, :scope => :"currency.format") - I18n.with_options :locale => 'de', :scope => :'currency.format' do |locale| - locale.t :precision - end - end - - # def test_translate_given_no_args_raises_missing_translation_data - # assert_equal "translation missing: en, no key", I18n.t - # end - - def test_translate_given_a_bogus_key_raises_missing_translation_data - assert_equal "translation missing: en, bogus", I18n.t(:bogus) - end - - def test_localize_nil_raises_argument_error - assert_raises(I18n::ArgumentError) { I18n.l nil } - end - - def test_localize_object_raises_argument_error - assert_raises(I18n::ArgumentError) { I18n.l Object.new } - end -end diff --git a/vendor/plugins/russian/lib/vendor/i18n/test/locale/en.rb b/vendor/plugins/russian/lib/vendor/i18n/test/locale/en.rb deleted file mode 100644 index 6044ce1..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/test/locale/en.rb +++ /dev/null @@ -1 +0,0 @@ -{:'en-Ruby' => {:foo => {:bar => "baz"}}} \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/test/locale/en.yml b/vendor/plugins/russian/lib/vendor/i18n/test/locale/en.yml deleted file mode 100644 index 0b298c9..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/test/locale/en.yml +++ /dev/null @@ -1,3 +0,0 @@ -en-Yaml: - foo: - bar: baz \ No newline at end of file diff --git a/vendor/plugins/russian/lib/vendor/i18n/test/simple_backend_test.rb b/vendor/plugins/russian/lib/vendor/i18n/test/simple_backend_test.rb deleted file mode 100644 index 7b7b137..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n/test/simple_backend_test.rb +++ /dev/null @@ -1,568 +0,0 @@ -# encoding: utf-8 -$:.unshift "lib" - -require 'rubygems' -require 'test/unit' -require 'mocha' -require 'i18n' -require 'time' -require 'yaml' - -module I18nSimpleBackendTestSetup - def setup_backend - # backend_reset_translations! - @backend = I18n::Backend::Simple.new - @backend.store_translations 'en', :foo => {:bar => 'bar', :baz => 'baz'} - @locale_dir = File.dirname(__FILE__) + '/locale' - end - alias :setup :setup_backend - - # def backend_reset_translations! - # I18n::Backend::Simple::ClassMethods.send :class_variable_set, :@@translations, {} - # end - - def backend_get_translations - # I18n::Backend::Simple::ClassMethods.send :class_variable_get, :@@translations - @backend.instance_variable_get :@translations - end - - def add_datetime_translations - @backend.store_translations :'de', { - :date => { - :formats => { - :default => "%d.%m.%Y", - :short => "%d. %b", - :long => "%d. %B %Y", - }, - :day_names => %w(Sonntag Montag Dienstag Mittwoch Donnerstag Freitag Samstag), - :abbr_day_names => %w(So Mo Di Mi Do Fr Sa), - :month_names => %w(Januar Februar März April Mai Juni Juli August September Oktober November Dezember).unshift(nil), - :abbr_month_names => %w(Jan Feb Mar Apr Mai Jun Jul Aug Sep Okt Nov Dez).unshift(nil), - :order => [:day, :month, :year] - }, - :time => { - :formats => { - :default => "%a, %d. %b %Y %H:%M:%S %z", - :short => "%d. %b %H:%M", - :long => "%d. %B %Y %H:%M", - }, - :am => 'am', - :pm => 'pm' - }, - :datetime => { - :distance_in_words => { - :half_a_minute => 'half a minute', - :less_than_x_seconds => { - :one => 'less than 1 second', - :other => 'less than {{count}} seconds' - }, - :x_seconds => { - :one => '1 second', - :other => '{{count}} seconds' - }, - :less_than_x_minutes => { - :one => 'less than a minute', - :other => 'less than {{count}} minutes' - }, - :x_minutes => { - :one => '1 minute', - :other => '{{count}} minutes' - }, - :about_x_hours => { - :one => 'about 1 hour', - :other => 'about {{count}} hours' - }, - :x_days => { - :one => '1 day', - :other => '{{count}} days' - }, - :about_x_months => { - :one => 'about 1 month', - :other => 'about {{count}} months' - }, - :x_months => { - :one => '1 month', - :other => '{{count}} months' - }, - :about_x_years => { - :one => 'about 1 year', - :other => 'about {{count}} year' - }, - :over_x_years => { - :one => 'over 1 year', - :other => 'over {{count}} years' - } - } - } - } - end -end - -class I18nSimpleBackendTranslationsTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_store_translations_adds_translations # no, really :-) - @backend.store_translations :'en', :foo => 'bar' - assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations - end - - def test_store_translations_deep_merges_translations - @backend.store_translations :'en', :foo => {:bar => 'bar'} - @backend.store_translations :'en', :foo => {:baz => 'baz'} - assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations - end - - def test_store_translations_forces_locale_to_sym - @backend.store_translations 'en', :foo => 'bar' - assert_equal Hash[:'en', {:foo => 'bar'}], backend_get_translations - end - - def test_store_translations_converts_keys_to_symbols - # backend_reset_translations! - @backend.store_translations 'en', 'foo' => {'bar' => 'bar', 'baz' => 'baz'} - assert_equal Hash[:'en', {:foo => {:bar => 'bar', :baz => 'baz'}}], backend_get_translations - end -end - -class I18nSimpleBackendAvailableLocalesTest < Test::Unit::TestCase - def test_available_locales - @backend = I18n::Backend::Simple.new - @backend.store_translations 'de', :foo => 'bar' - @backend.store_translations 'en', :foo => 'foo' - - assert_equal ['de', 'en'], @backend.available_locales.map{|locale| locale.to_s }.sort - end -end - -class I18nSimpleBackendTranslateTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_translate_calls_lookup_with_locale_given - @backend.expects(:lookup).with('de', :bar, [:foo]).returns 'bar' - @backend.translate 'de', :bar, :scope => [:foo] - end - - def test_given_no_keys_it_returns_the_default - assert_equal 'default', @backend.translate('en', nil, :default => 'default') - end - - def test_translate_given_a_symbol_as_a_default_translates_the_symbol - assert_equal 'bar', @backend.translate('en', nil, :scope => [:foo], :default => :bar) - end - - def test_translate_given_an_array_as_default_uses_the_first_match - assert_equal 'bar', @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :bar]) - end - - def test_translate_given_an_array_of_inexistent_keys_it_raises_missing_translation_data - assert_raises I18n::MissingTranslationData do - @backend.translate('en', :does_not_exist, :scope => [:foo], :default => [:does_not_exist_2, :does_not_exist_3]) - end - end - - def test_translate_an_array_of_keys_translates_all_of_them - assert_equal %w(bar baz), @backend.translate('en', [:bar, :baz], :scope => [:foo]) - end - - def test_translate_calls_pluralize - @backend.expects(:pluralize).with 'en', 'bar', 1 - @backend.translate 'en', :bar, :scope => [:foo], :count => 1 - end - - def test_translate_calls_interpolate - @backend.expects(:interpolate).with 'en', 'bar', {} - @backend.translate 'en', :bar, :scope => [:foo] - end - - def test_translate_calls_interpolate_including_count_as_a_value - @backend.expects(:interpolate).with 'en', 'bar', {:count => 1} - @backend.translate 'en', :bar, :scope => [:foo], :count => 1 - end - - def test_translate_given_nil_as_a_locale_raises_an_argument_error - assert_raises(I18n::InvalidLocale){ @backend.translate nil, :bar } - end - - def test_translate_with_a_bogus_key_and_no_default_raises_missing_translation_data - assert_raises(I18n::MissingTranslationData){ @backend.translate 'de', :bogus } - end -end - -class I18nSimpleBackendLookupTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - # useful because this way we can use the backend with no key for interpolation/pluralization - def test_lookup_given_nil_as_a_key_returns_nil - assert_nil @backend.send(:lookup, 'en', nil) - end - - def test_lookup_given_nested_keys_looks_up_a_nested_hash_value - assert_equal 'bar', @backend.send(:lookup, 'en', :bar, [:foo]) - end -end - -class I18nSimpleBackendPluralizeTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_pluralize_given_nil_returns_the_given_entry - entry = {:one => 'bar', :other => 'bars'} - assert_equal entry, @backend.send(:pluralize, nil, entry, nil) - end - - def test_pluralize_given_0_returns_zero_string_if_zero_key_given - assert_equal 'zero', @backend.send(:pluralize, nil, {:zero => 'zero', :one => 'bar', :other => 'bars'}, 0) - end - - def test_pluralize_given_0_returns_plural_string_if_no_zero_key_given - assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 0) - end - - def test_pluralize_given_1_returns_singular_string - assert_equal 'bar', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 1) - end - - def test_pluralize_given_2_returns_plural_string - assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 2) - end - - def test_pluralize_given_3_returns_plural_string - assert_equal 'bars', @backend.send(:pluralize, nil, {:one => 'bar', :other => 'bars'}, 3) - end - - def test_interpolate_given_incomplete_pluralization_data_raises_invalid_pluralization_data - assert_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, {:one => 'bar'}, 2) } - end - - # def test_interpolate_given_a_string_raises_invalid_pluralization_data - # assert_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, 'bar', 2) } - # end - # - # def test_interpolate_given_an_array_raises_invalid_pluralization_data - # assert_raises(I18n::InvalidPluralizationData){ @backend.send(:pluralize, nil, ['bar'], 2) } - # end -end - -class I18nSimpleBackendInterpolateTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_interpolate_given_a_value_hash_interpolates_the_values_to_the_string - assert_equal 'Hi David!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'David') - end - - def test_interpolate_given_a_value_hash_interpolates_into_unicode_string - assert_equal 'Häi David!', @backend.send(:interpolate, nil, 'Häi {{name}}!', :name => 'David') - end - - def test_interpolate_given_an_unicode_value_hash_interpolates_to_the_string - assert_equal 'Hi ゆきひろ!', @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => 'ゆきひろ') - end - - def test_interpolate_given_an_unicode_value_hash_interpolates_into_unicode_string - assert_equal 'こんにちは、ゆきひろさん!', @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => 'ゆきひろ') - end - - if Kernel.const_defined?(:Encoding) - def test_interpolate_given_a_non_unicode_multibyte_value_hash_interpolates_into_a_string_with_the_same_encoding - assert_equal euc_jp('Hi ゆきひろ!'), @backend.send(:interpolate, nil, 'Hi {{name}}!', :name => euc_jp('ゆきひろ')) - end - - def test_interpolate_given_an_unicode_value_hash_into_a_non_unicode_multibyte_string_raises_encoding_compatibility_error - assert_raises(Encoding::CompatibilityError) do - @backend.send(:interpolate, nil, euc_jp('こんにちは、{{name}}さん!'), :name => 'ゆきひろ') - end - end - - def test_interpolate_given_a_non_unicode_multibyte_value_hash_into_an_unicode_string_raises_encoding_compatibility_error - assert_raises(Encoding::CompatibilityError) do - @backend.send(:interpolate, nil, 'こんにちは、{{name}}さん!', :name => euc_jp('ゆきひろ')) - end - end - end - - def test_interpolate_given_nil_as_a_string_returns_nil - assert_nil @backend.send(:interpolate, nil, nil, :name => 'David') - end - - def test_interpolate_given_an_non_string_as_a_string_returns_nil - assert_equal [], @backend.send(:interpolate, nil, [], :name => 'David') - end - - def test_interpolate_given_a_values_hash_with_nil_values_interpolates_the_string - assert_equal 'Hi !', @backend.send(:interpolate, nil, 'Hi {{name}}!', {:name => nil}) - end - - def test_interpolate_given_an_empty_values_hash_raises_missing_interpolation_argument - assert_raises(I18n::MissingInterpolationArgument) { @backend.send(:interpolate, nil, 'Hi {{name}}!', {}) } - end - - def test_interpolate_given_a_string_containing_a_reserved_key_raises_reserved_interpolation_key - assert_raises(I18n::ReservedInterpolationKey) { @backend.send(:interpolate, nil, '{{default}}', {:default => nil}) } - end - - private - - def euc_jp(string) - string.encode!(Encoding::EUC_JP) - end -end - -class I18nSimpleBackendLocalizeDateTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @backend = I18n::Backend::Simple.new - add_datetime_translations - @date = Date.new 2008, 1, 1 - end - - def test_translate_given_the_short_format_it_uses_it - assert_equal '01. Jan', @backend.localize('de', @date, :short) - end - - def test_translate_given_the_long_format_it_uses_it - assert_equal '01. Januar 2008', @backend.localize('de', @date, :long) - end - - def test_translate_given_the_default_format_it_uses_it - assert_equal '01.01.2008', @backend.localize('de', @date, :default) - end - - def test_translate_given_a_day_name_format_it_returns_a_day_name - assert_equal 'Dienstag', @backend.localize('de', @date, '%A') - end - - def test_translate_given_an_abbr_day_name_format_it_returns_an_abbrevated_day_name - assert_equal 'Di', @backend.localize('de', @date, '%a') - end - - def test_translate_given_a_month_name_format_it_returns_a_month_name - assert_equal 'Januar', @backend.localize('de', @date, '%B') - end - - def test_translate_given_an_abbr_month_name_format_it_returns_an_abbrevated_month_name - assert_equal 'Jan', @backend.localize('de', @date, '%b') - end - - def test_translate_given_no_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @date } - end - - def test_translate_given_an_unknown_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @date, '%x' } - end - - def test_localize_nil_raises_argument_error - assert_raises(I18n::ArgumentError) { @backend.localize 'de', nil } - end - - def test_localize_object_raises_argument_error - assert_raises(I18n::ArgumentError) { @backend.localize 'de', Object.new } - end -end - -class I18nSimpleBackendLocalizeDateTimeTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @backend = I18n::Backend::Simple.new - add_datetime_translations - @morning = DateTime.new 2008, 1, 1, 6 - @evening = DateTime.new 2008, 1, 1, 18 - end - - def test_translate_given_the_short_format_it_uses_it - assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short) - end - - def test_translate_given_the_long_format_it_uses_it - assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long) - end - - def test_translate_given_the_default_format_it_uses_it - assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default) - end - - def test_translate_given_a_day_name_format_it_returns_the_correct_day_name - assert_equal 'Dienstag', @backend.localize('de', @morning, '%A') - end - - def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name - assert_equal 'Di', @backend.localize('de', @morning, '%a') - end - - def test_translate_given_a_month_name_format_it_returns_the_correct_month_name - assert_equal 'Januar', @backend.localize('de', @morning, '%B') - end - - def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name - assert_equal 'Jan', @backend.localize('de', @morning, '%b') - end - - def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator - assert_equal 'am', @backend.localize('de', @morning, '%p') - assert_equal 'pm', @backend.localize('de', @evening, '%p') - end - - def test_translate_given_no_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning } - end - - def test_translate_given_an_unknown_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning, '%x' } - end -end - -class I18nSimpleBackendLocalizeTimeTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @old_timezone, ENV['TZ'] = ENV['TZ'], 'UTC' - @backend = I18n::Backend::Simple.new - add_datetime_translations - @morning = Time.parse '2008-01-01 6:00 UTC' - @evening = Time.parse '2008-01-01 18:00 UTC' - end - - def teardown - @old_timezone ? ENV['TZ'] = @old_timezone : ENV.delete('TZ') - end - - def test_translate_given_the_short_format_it_uses_it - assert_equal '01. Jan 06:00', @backend.localize('de', @morning, :short) - end - - def test_translate_given_the_long_format_it_uses_it - assert_equal '01. Januar 2008 06:00', @backend.localize('de', @morning, :long) - end - - # TODO Seems to break on Windows because ENV['TZ'] is ignored. What's a better way to do this? - # def test_translate_given_the_default_format_it_uses_it - # assert_equal 'Di, 01. Jan 2008 06:00:00 +0000', @backend.localize('de', @morning, :default) - # end - - def test_translate_given_a_day_name_format_it_returns_the_correct_day_name - assert_equal 'Dienstag', @backend.localize('de', @morning, '%A') - end - - def test_translate_given_an_abbr_day_name_format_it_returns_the_correct_abbrevated_day_name - assert_equal 'Di', @backend.localize('de', @morning, '%a') - end - - def test_translate_given_a_month_name_format_it_returns_the_correct_month_name - assert_equal 'Januar', @backend.localize('de', @morning, '%B') - end - - def test_translate_given_an_abbr_month_name_format_it_returns_the_correct_abbrevated_month_name - assert_equal 'Jan', @backend.localize('de', @morning, '%b') - end - - def test_translate_given_a_meridian_indicator_format_it_returns_the_correct_meridian_indicator - assert_equal 'am', @backend.localize('de', @morning, '%p') - assert_equal 'pm', @backend.localize('de', @evening, '%p') - end - - def test_translate_given_no_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning } - end - - def test_translate_given_an_unknown_format_it_does_not_fail - assert_nothing_raised{ @backend.localize 'de', @morning, '%x' } - end -end - -class I18nSimpleBackendHelperMethodsTest < Test::Unit::TestCase - def setup - @backend = I18n::Backend::Simple.new - end - - def test_deep_symbolize_keys_works - result = @backend.send :deep_symbolize_keys, 'foo' => {'bar' => {'baz' => 'bar'}} - expected = {:foo => {:bar => {:baz => 'bar'}}} - assert_equal expected, result - end -end - -class I18nSimpleBackendLoadTranslationsTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def test_load_translations_with_unknown_file_type_raises_exception - assert_raises(I18n::UnknownFileType) { @backend.load_translations "#{@locale_dir}/en.xml" } - end - - def test_load_translations_with_ruby_file_type_does_not_raise_exception - assert_nothing_raised { @backend.load_translations "#{@locale_dir}/en.rb" } - end - - def test_load_rb_loads_data_from_ruby_file - data = @backend.send :load_rb, "#{@locale_dir}/en.rb" - assert_equal({:'en-Ruby' => {:foo => {:bar => "baz"}}}, data) - end - - def test_load_rb_loads_data_from_yaml_file - data = @backend.send :load_yml, "#{@locale_dir}/en.yml" - assert_equal({'en-Yaml' => {'foo' => {'bar' => 'baz'}}}, data) - end - - def test_load_translations_loads_from_different_file_formats - @backend = I18n::Backend::Simple.new - @backend.load_translations "#{@locale_dir}/en.rb", "#{@locale_dir}/en.yml" - expected = { - :'en-Ruby' => {:foo => {:bar => "baz"}}, - :'en-Yaml' => {:foo => {:bar => "baz"}} - } - assert_equal expected, backend_get_translations - end -end - -class I18nSimpleBackendLoadPathTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def teardown - I18n.load_path = [] - end - - def test_nested_load_paths_do_not_break_locale_loading - @backend = I18n::Backend::Simple.new - I18n.load_path = [[File.dirname(__FILE__) + '/locale/en.yml']] - assert_nil backend_get_translations - assert_nothing_raised { @backend.send :init_translations } - assert_not_nil backend_get_translations - end - - def test_adding_arrays_of_filenames_to_load_path_do_not_break_locale_loading - @backend = I18n::Backend::Simple.new - I18n.load_path << Dir[File.dirname(__FILE__) + '/locale/*.{rb,yml}'] - assert_nil backend_get_translations - assert_nothing_raised { @backend.send :init_translations } - assert_not_nil backend_get_translations - end -end - -class I18nSimpleBackendReloadTranslationsTest < Test::Unit::TestCase - include I18nSimpleBackendTestSetup - - def setup - @backend = I18n::Backend::Simple.new - I18n.load_path = [File.dirname(__FILE__) + '/locale/en.yml'] - assert_nil backend_get_translations - @backend.send :init_translations - end - - def teardown - I18n.load_path = [] - end - - def test_setup - assert_not_nil backend_get_translations - end - - def test_reload_translations_unloads_translations - @backend.reload! - assert_nil backend_get_translations - end - - def test_reload_translations_uninitializes_translations - @backend.reload! - assert_equal @backend.initialized?, false - end -end diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/README.textile b/vendor/plugins/russian/lib/vendor/i18n_label/README.textile deleted file mode 100644 index 0b2b84c..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/README.textile +++ /dev/null @@ -1,38 +0,0 @@ -h1. I18nLabel - -Since labels don't use I18n in Rails 2.2 (I was too late in submitting the -patch), we'd have to make due with a plugin. - -Installation and configuration consists of 1 easy steps: - -# Run: - - ./script/plugin install git://github.com/iain/i18n_label.git - - -h1. Example - -In your translation file: - - en-US: - activerecord: - attributes: - topic: - name: A nice name - -In your view: - - <% form_for @topic do |f| %> - <%= f.label :name %> - <% end %> - -The result is: - - <label for="topic_name">A nice name</label> (please ignore the minor problem with html in github) - - - -For more information about where to put your translations, -visit "my blog":http://iain.nl/2008/09/translating-activerecord/ - -Copyright (c) 2008 "Iain Hecker":http://iain.nl/, released under the MIT license diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/Rakefile b/vendor/plugins/russian/lib/vendor/i18n_label/Rakefile deleted file mode 100644 index 7e1954b..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/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/vendor/plugins/russian/lib/vendor/i18n_label/init.rb b/vendor/plugins/russian/lib/vendor/i18n_label/init.rb deleted file mode 100644 index 4ac770b..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/init.rb +++ /dev/null @@ -1 +0,0 @@ -require File.dirname(__FILE__) + '/lib/i18n_label.rb' diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/install.rb b/vendor/plugins/russian/lib/vendor/i18n_label/install.rb deleted file mode 100644 index 200c922..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/install.rb +++ /dev/null @@ -1 +0,0 @@ -File.readlines(File.dirname(__FILE__)+'/README.textile').each { |line| puts line } diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/lib/i18n_label.rb b/vendor/plugins/russian/lib/vendor/i18n_label/lib/i18n_label.rb deleted file mode 100644 index 0b36b49..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/lib/i18n_label.rb +++ /dev/null @@ -1,23 +0,0 @@ -# Just replace the method... -module ActionView - module Helpers - class InstanceTag - def to_label_tag(text = nil, options = {}) - options = options.stringify_keys - name_and_id = options.dup - add_default_name_and_id(name_and_id) - options.delete("index") - options["for"] ||= name_and_id["id"] - if text.blank? - content = method_name.humanize - if object.class.respond_to?(:human_attribute_name) - content = object.class.human_attribute_name(method_name) - end - else - content = text.to_s - end - label_tag(name_and_id["id"], content, options) - end - end - end -end diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/spec/i18n_label_spec.rb b/vendor/plugins/russian/lib/vendor/i18n_label/spec/i18n_label_spec.rb deleted file mode 100644 index 4ed8d8d..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/spec/i18n_label_spec.rb +++ /dev/null @@ -1,20 +0,0 @@ -require File.dirname(__FILE__) + '/spec_helper' - -# give a model to play with -class Reply < ActiveRecord::Base - attr_accessor :title -end - -describe ActionView::Helpers do - - # NOTE gives deprication warning in RSpec 1.1.4: - # Modules will no longer be automatically included in RSpec version 1.1.4. Called from ./spec/i18n_label_spec.rb:15 - it "label should make a call to human_attribute_name" do - Reply.should_receive(:human_attribute_name).with('title').and_return("translated title") - reply = mock_model(Reply) - fields_for(reply) do |f| - f.label(:title).should == "<label for=\"reply_title\">translated title</label>" - end - end - -end diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/spec/spec_helper.rb b/vendor/plugins/russian/lib/vendor/i18n_label/spec/spec_helper.rb deleted file mode 100644 index 3424846..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/spec/spec_helper.rb +++ /dev/null @@ -1,10 +0,0 @@ -begin - require File.dirname(__FILE__) + '/../../../../spec/spec_helper' -rescue LoadError - puts "You need to install rspec in your base app" - exit -end - -plugin_spec_dir = File.dirname(__FILE__) -ActiveRecord::Base.logger = Logger.new(plugin_spec_dir + "/debug.log") - diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/tasks/i18n_label_tasks.rake b/vendor/plugins/russian/lib/vendor/i18n_label/tasks/i18n_label_tasks.rake deleted file mode 100644 index 1d823e1..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/tasks/i18n_label_tasks.rake +++ /dev/null @@ -1,4 +0,0 @@ -# desc "Explaining what the task does" -# task :i18n_label do -# # Task goes here -# end diff --git a/vendor/plugins/russian/lib/vendor/i18n_label/uninstall.rb b/vendor/plugins/russian/lib/vendor/i18n_label/uninstall.rb deleted file mode 100644 index c5836c2..0000000 --- a/vendor/plugins/russian/lib/vendor/i18n_label/uninstall.rb +++ /dev/null @@ -1 +0,0 @@ -puts "Bye!" diff --git a/vendor/plugins/russian/russian.gemspec b/vendor/plugins/russian/russian.gemspec deleted file mode 100644 index 06910e9..0000000 --- a/vendor/plugins/russian/russian.gemspec +++ /dev/null @@ -1,29 +0,0 @@ -# -*- encoding: utf-8 -*- - -Gem::Specification.new do |s| - s.name = %q{russian} - s.version = "0.2.5" - - s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= - s.authors = ["Yaroslav Markin"] - s.autorequire = %q{russian} - s.date = %q{2009-12-23} - s.description = %q{Russian language support for Ruby and Rails} - s.email = %q{yaroslav@markin.net} - s.extra_rdoc_files = ["README.textile", "LICENSE", "CHANGELOG", "TODO"] - s.files = ["LICENSE", "README.textile", "Rakefile", "CHANGELOG", "TODO", "init.rb", "lib/russian", "lib/russian/action_view_ext", "lib/russian/action_view_ext/helpers", "lib/russian/action_view_ext/helpers/date_helper.rb", "lib/russian/active_record_ext", "lib/russian/active_record_ext/custom_error_message.rb", "lib/russian/active_support_ext", "lib/russian/active_support_ext/parameterize.rb", "lib/russian/backend", "lib/russian/backend/advanced.rb", "lib/russian/locale", "lib/russian/locale/actionview.yml", "lib/russian/locale/activerecord.yml", "lib/russian/locale/activesupport.yml", "lib/russian/locale/datetime.yml", "lib/russian/locale/pluralize.rb", "lib/russian/transliteration.rb", "lib/russian.rb", "lib/vendor", "lib/vendor/i18n", "lib/vendor/i18n/i18n.gemspec", "lib/vendor/i18n/lib", "lib/vendor/i18n/lib/i18n", "lib/vendor/i18n/lib/i18n/backend", "lib/vendor/i18n/lib/i18n/backend/simple.rb", "lib/vendor/i18n/lib/i18n/exceptions.rb", "lib/vendor/i18n/lib/i18n.rb", "lib/vendor/i18n/MIT-LICENSE", "lib/vendor/i18n/Rakefile", "lib/vendor/i18n/README.textile", "lib/vendor/i18n/test", "lib/vendor/i18n/test/all.rb", "lib/vendor/i18n/test/i18n_exceptions_test.rb", "lib/vendor/i18n/test/i18n_test.rb", "lib/vendor/i18n/test/locale", "lib/vendor/i18n/test/locale/en.rb", "lib/vendor/i18n/test/locale/en.yml", "lib/vendor/i18n/test/simple_backend_test.rb", "lib/vendor/i18n_label", "lib/vendor/i18n_label/init.rb", "lib/vendor/i18n_label/install.rb", "lib/vendor/i18n_label/lib", "lib/vendor/i18n_label/lib/i18n_label.rb", "lib/vendor/i18n_label/Rakefile", "lib/vendor/i18n_label/README.textile", "lib/vendor/i18n_label/spec", "lib/vendor/i18n_label/spec/i18n_label_spec.rb", "lib/vendor/i18n_label/spec/spec_helper.rb", "lib/vendor/i18n_label/tasks", "lib/vendor/i18n_label/tasks/i18n_label_tasks.rake", "lib/vendor/i18n_label/uninstall.rb", "spec/fixtures", "spec/fixtures/en.yml", "spec/fixtures/ru.yml", "spec/i18n", "spec/i18n/locale", "spec/i18n/locale/datetime_spec.rb", "spec/i18n/locale/pluralization_spec.rb", "spec/locale_spec.rb", "spec/russian_spec.rb", "spec/spec_helper.rb", "spec/transliteration_spec.rb"] - s.homepage = %q{http://github.com/yaroslav/russian/} - s.require_paths = ["lib"] - s.rubygems_version = %q{1.3.5} - s.summary = %q{Russian language support for Ruby and Rails} - - if s.respond_to? :specification_version then - current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION - s.specification_version = 3 - - if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then - else - end - else - end -end diff --git a/vendor/plugins/russian/spec/fixtures/en.yml b/vendor/plugins/russian/spec/fixtures/en.yml deleted file mode 100644 index a0c18ac..0000000 --- a/vendor/plugins/russian/spec/fixtures/en.yml +++ /dev/null @@ -1,4 +0,0 @@ -# Fixture dummy translation -# Need this to test if we preserve translation data that is already loaded when switching backends -en: - foo: "bar" diff --git a/vendor/plugins/russian/spec/fixtures/ru.yml b/vendor/plugins/russian/spec/fixtures/ru.yml deleted file mode 100644 index 8de5b7a..0000000 --- a/vendor/plugins/russian/spec/fixtures/ru.yml +++ /dev/null @@ -1,4 +0,0 @@ -ru: - date: - formats: - default: "override" diff --git a/vendor/plugins/russian/spec/i18n/locale/datetime_spec.rb b/vendor/plugins/russian/spec/i18n/locale/datetime_spec.rb deleted file mode 100644 index a9a76f6..0000000 --- a/vendor/plugins/russian/spec/i18n/locale/datetime_spec.rb +++ /dev/null @@ -1,93 +0,0 @@ -# -*- encoding: utf-8 -*- - -require File.dirname(__FILE__) + '/../../spec_helper' - -describe I18n, "Russian Date/Time localization" do - before(:all) do - @date = Date.parse("1985-12-01") - @time = Time.local(1985, 12, 01, 16, 05) - end - - describe "with date formats" do - it "should use default format" do - l(@date).should == "01.12.1985" - end - - it "should use short format" do - l(@date, :format => :short).should == "01 дек." - end - - it "should use long format" do - l(@date, :format => :long).should == "01 декабря 1985" - end - end - - describe "with date day names" do - it "should use day names" do - l(@date, :format => "%d %B (%A)").should == "01 декабря (воскресенье)" - l(@date, :format => "%d %B %Y года было %A").should == "01 декабря 1985 года было воскресенье" - end - - it "should use standalone day names" do - l(@date, :format => "%A").should == "Воскресенье" - l(@date, :format => "%A, %d %B").should == "Воскресенье, 01 декабря" - end - - it "should use abbreviated day names" do - l(@date, :format => "%a").should == "Вс" - l(@date, :format => "%a, %d %b %Y").should == "Вс, 01 дек. 1985" - end - end - - describe "with month names" do - it "should use month names" do - l(@date, :format => "%d %B").should == "01 декабря" - l(@date, :format => "%e %B %Y").should == " 1 декабря 1985" - end - - it "should use standalone month names" do - l(@date, :format => "%B").should == "Декабрь" - l(@date, :format => "%B %Y").should == "Декабрь 1985" - end - - it "should use abbreviated month names" do - @date = Date.parse("1985-03-01") - l(@date, :format => "%d %b").should == "01 марта" - l(@date, :format => "%e %b %Y").should == " 1 марта 1985" - end - - it "should use standalone abbreviated month names" do - @date = Date.parse("1985-03-01") - l(@date, :format => "%b").should == "март" - l(@date, :format => "%b %Y").should == "март 1985" - end - end - - it "should define default date components order: day, month, year" do - I18n.backend.translate(Russian.locale, :"date.order").should == [:day, :month, :year] - end - - describe "with time formats" do - it "should use default format" do - l(@time).should =~ /^Вс, 01 дек. 1985, 16:05:00/ - end - - it "should use short format" do - l(@time, :format => :short).should == "01 дек., 16:05" - end - - it "should use long format" do - l(@time, :format => :long).should == "01 декабря 1985, 16:05" - end - - it "should define am and pm" do - I18n.backend.translate(Russian.locale, :"time.am").should_not be_nil - I18n.backend.translate(Russian.locale, :"time.pm").should_not be_nil - end - end - - protected - def l(object, options = {}) - I18n.l(object, options.merge( { :locale => Russian.locale })) - end -end diff --git a/vendor/plugins/russian/spec/i18n/locale/pluralization_spec.rb b/vendor/plugins/russian/spec/i18n/locale/pluralization_spec.rb deleted file mode 100644 index da15865..0000000 --- a/vendor/plugins/russian/spec/i18n/locale/pluralization_spec.rb +++ /dev/null @@ -1,28 +0,0 @@ -# -*- encoding: utf-8 -*- - -require File.dirname(__FILE__) + '/../../spec_helper' - -describe I18n, "Russian pluralization" do - before(:each) do - @hash = {} - %w(one few many other).each do |key| - @hash[key.to_sym] = key - end - @backend = I18n.backend - end - - it "should pluralize correctly" do - @backend.send(:pluralize, :'ru', @hash, 1).should == 'one' - @backend.send(:pluralize, :'ru', @hash, 2).should == 'few' - @backend.send(:pluralize, :'ru', @hash, 3).should == 'few' - @backend.send(:pluralize, :'ru', @hash, 5).should == 'many' - @backend.send(:pluralize, :'ru', @hash, 10).should == 'many' - @backend.send(:pluralize, :'ru', @hash, 11).should == 'many' - @backend.send(:pluralize, :'ru', @hash, 21).should == 'one' - @backend.send(:pluralize, :'ru', @hash, 29).should == 'many' - @backend.send(:pluralize, :'ru', @hash, 131).should == 'one' - @backend.send(:pluralize, :'ru', @hash, 1.31).should == 'other' - @backend.send(:pluralize, :'ru', @hash, 2.31).should == 'other' - @backend.send(:pluralize, :'ru', @hash, 3.31).should == 'other' - end -end \ No newline at end of file diff --git a/vendor/plugins/russian/spec/locale_spec.rb b/vendor/plugins/russian/spec/locale_spec.rb deleted file mode 100644 index 9605449..0000000 --- a/vendor/plugins/russian/spec/locale_spec.rb +++ /dev/null @@ -1,129 +0,0 @@ -# -*- encoding: utf-8 -*- - -require File.dirname(__FILE__) + '/spec_helper' - -describe Russian, "loading locales" do - before(:all) do - Russian.init_i18n - end - - %w( - date.formats.default - date.formats.short - date.formats.long - date.day_names - date.standalone_day_names - date.abbr_day_names - date.month_names - date.standalone_month_names - date.abbr_month_names - date.standalone_abbr_month_names - date.order - - time.formats.default - time.formats.short - time.formats.long - time.am - time.pm - ).each do |key| - it "should define '#{key}' in datetime translations" do - lookup(key).should_not be_nil - end - end - - it "should load pluralization rules" do - lookup(:"pluralize").should_not be_nil - lookup(:"pluralize").is_a?(Proc).should be_true - end - - %w( - number.format.separator - number.format.delimiter - number.format.precision - number.currency.format.format - number.currency.format.unit - number.currency.format.separator - number.currency.format.delimiter - number.currency.format.precision - number.percentage.format.delimiter - number.precision.format.delimiter - number.human.format.delimiter - number.human.format.precision - number.human.storage_units - - datetime.distance_in_words.half_a_minute - datetime.distance_in_words.less_than_x_seconds - datetime.distance_in_words.x_seconds - datetime.distance_in_words.less_than_x_minutes - datetime.distance_in_words.x_minutes - datetime.distance_in_words.about_x_hours - datetime.distance_in_words.x_days - datetime.distance_in_words.about_x_months - datetime.distance_in_words.x_months - datetime.distance_in_words.about_x_years - datetime.distance_in_words.over_x_years - datetime.distance_in_words.almost_x_years - - datetime.prompts.year - datetime.prompts.month - datetime.prompts.day - datetime.prompts.hour - datetime.prompts.minute - datetime.prompts.second - - activerecord.errors.template.header - activerecord.errors.template.body - - support.select.prompt - ).each do |key| - it "should define '#{key}' in actionview translations" do - lookup(key).should_not be_nil - end - end - - %w( - activerecord.errors.messages.inclusion - activerecord.errors.messages.exclusion - activerecord.errors.messages.invalid - activerecord.errors.messages.confirmation - activerecord.errors.messages.accepted - activerecord.errors.messages.empty - activerecord.errors.messages.blank - activerecord.errors.messages.too_long - activerecord.errors.messages.too_short - activerecord.errors.messages.wrong_length - activerecord.errors.messages.taken - activerecord.errors.messages.not_a_number - activerecord.errors.messages.greater_than - activerecord.errors.messages.greater_than_or_equal_to - activerecord.errors.messages.equal_to - activerecord.errors.messages.less_than - activerecord.errors.messages.less_than_or_equal_to - activerecord.errors.messages.odd - activerecord.errors.messages.even - activerecord.errors.messages.record_invalid - - activerecord.errors.full_messages.format - ).each do |key| - it "should define '#{key}' in activerecord translations" do - lookup(key).should_not be_nil - end - end - - %w( - support.array.sentence_connector - support.array.skip_last_comma - - support.array.words_connector - support.array.two_words_connector - support.array.last_word_connector - ).each do |key| - it "should define '#{key}' in activesupport translations" do - lookup(key).should_not be_nil - end - end - - def lookup(*args) - I18n.backend.send(:lookup, Russian.locale, *args) - end -end diff --git a/vendor/plugins/russian/spec/russian_spec.rb b/vendor/plugins/russian/spec/russian_spec.rb deleted file mode 100644 index cc53d27..0000000 --- a/vendor/plugins/russian/spec/russian_spec.rb +++ /dev/null @@ -1,136 +0,0 @@ -# -*- encoding: utf-8 -*- - -require File.dirname(__FILE__) + '/spec_helper' - -describe Russian, "VERSION" do - it "should be defined" do - %w(MAJOR MINOR TINY STRING).each do |v| - Russian::VERSION.const_defined?(v).should == true - end - end -end - -describe Russian do - describe "with locale" do - it "should define :'ru' LOCALE" do - Russian::LOCALE.should == :'ru' - end - - it "should provide 'locale' proxy" do - Russian.locale.should == Russian::LOCALE - end - end - - describe "with custom backend class" do - it "should define i18n_backend_class" do - Russian.i18n_backend_class.should == I18n::Backend::Advanced - end - end - - describe "during i18n initialization" do - after(:each) do - I18n.load_path = [] - Russian.init_i18n - end - - it "should set I18n backend to an instance of a custom backend" do - Russian.init_i18n - I18n.backend.class.should == Russian.i18n_backend_class - end - - it "should keep existing translations while switching backends" do - I18n.load_path << File.join(File.dirname(__FILE__), 'fixtures', 'en.yml') - Russian.init_i18n - I18n.t(:foo, :locale => :'en').should == "bar" - end - - it "should keep existing :ru translations while switching backends" do - I18n.load_path << File.join(File.dirname(__FILE__), 'fixtures', 'ru.yml') - Russian.init_i18n - I18n.t(:'date.formats.default', :locale => :'ru').should == "override" - end - - it "should set default locale to Russian locale" do - Russian.init_i18n - I18n.default_locale.should == Russian.locale - end - end - - describe "with localize proxy" do - before(:all) do - @time = mock(:time) - @options = { :format => "%d %B %Y" } - end - - %w(l localize).each do |method| - it "'#{method}' should call I18n backend localize" do - I18n.should_receive(:localize).with(@time, @options.merge({ :locale => Russian.locale })) - Russian.send(method, @time, @options) - end - end - end - - describe "with translate proxy" do - before(:all) do - @object = :bar - @options = { :scope => :foo } - end - - %w(t translate).each do |method| - it "'#{method}' should call I18n backend translate" do - I18n.should_receive(:translate).with(@object, @options.merge({ :locale => Russian.locale })) - Russian.send(method, @object, @options) - end - end - end - - describe "strftime" do - before(:all) do - @time = mock(:time) - end - - it "should call localize with object and format" do - format = "%d %B %Y" - Russian.should_receive(:localize).with(@time, { :format => format }) - Russian.strftime(@time, format) - end - - it "should call localize with object and default format when format is not specified" do - Russian.should_receive(:localize).with(@time, { :format => :default }) - Russian.strftime(@time) - end - end - - describe "with pluralization" do - %w(p pluralize).each do |method| - it "'#{method}' should pluralize with variants given" do - variants = %w(вещь вещи вещей вещи) - - Russian.send(method, 1, *variants).should == "вещь" - Russian.send(method, 2, *variants).should == 'вещи' - Russian.send(method, 3, *variants).should == 'вещи' - Russian.send(method, 5, *variants).should == 'вещей' - Russian.send(method, 10, *variants).should == 'вещей' - Russian.send(method, 21, *variants).should == 'вещь' - Russian.send(method, 29, *variants).should == 'вещей' - Russian.send(method, 129, *variants).should == 'вещей' - Russian.send(method, 131, *variants).should == 'вещь' - Russian.send(method, 3.14, *variants).should == 'вещи' - end - - it "should raise an exception when first parameter is not a number" do - lambda { Russian.send(method, nil, "вещь", "вещи", "вещей") }.should raise_error(ArgumentError) - lambda { Russian.send(method, "вещь", "вещь", "вещи", "вещей") }.should raise_error(ArgumentError) - end - - it "should raise an exception when there are not enough variants" do - lambda { Russian.send(method, 1) }.should raise_error(ArgumentError) - lambda { Russian.send(method, 1, "вещь") }.should raise_error(ArgumentError) - lambda { Russian.send(method, 1, "вещь", "вещи") }.should raise_error(ArgumentError) - lambda { Russian.send(method, 1, "вещь", "вещи", "вещей") }.should_not raise_error(ArgumentError) - lambda { Russian.send(method, 3.14, "вещь", "вещи", "вещей") }.should raise_error(ArgumentError) - lambda { Russian.send(method, 3.14, "вещь", "вещи", "вещей", "вещи") }.should_not raise_error(ArgumentError) - end - end - end -end diff --git a/vendor/plugins/russian/spec/spec_helper.rb b/vendor/plugins/russian/spec/spec_helper.rb deleted file mode 100644 index b533437..0000000 --- a/vendor/plugins/russian/spec/spec_helper.rb +++ /dev/null @@ -1,7 +0,0 @@ -# -*- encoding: utf-8 -*- - -$TESTING=true -$:.unshift File.join(File.dirname(__FILE__), '..', 'lib') - -require 'russian' - diff --git a/vendor/plugins/russian/spec/transliteration_spec.rb b/vendor/plugins/russian/spec/transliteration_spec.rb deleted file mode 100644 index a4f256b..0000000 --- a/vendor/plugins/russian/spec/transliteration_spec.rb +++ /dev/null @@ -1,51 +0,0 @@ -# -*- encoding: utf-8 -*- - -require File.dirname(__FILE__) + '/spec_helper' - -describe Russian do - describe "transliteration" do - def t(str) - Russian::transliterate(str) - end - - %w(transliterate translit).each do |method| - it "'#{method}' method should perform transliteration" do - str = mock(:str) - Russian::Transliteration.should_receive(:transliterate).with(str) - Russian.send(method, str) - end - end - - # These tests are from rutils, <http://rutils.rubyforge.org>. - - it "should transliterate properly" do - t("Это просто некий текст").should == "Eto prosto nekiy tekst" - t("щ").should == "sch" - t("стансы").should == "stansy" - t("упущение").should == "upuschenie" - t("ш").should == "sh" - t("Ш").should == "SH" - t("ц").should == "ts" - end - - it "should properly transliterate mixed russian-english strings" do - t("Это кусок строки русских букв v peremeshku s latinizey i амперсандом (pozor!) & something").should == - "Eto kusok stroki russkih bukv v peremeshku s latinizey i ampersandom (pozor!) & something" - end - - it "should properly transliterate mixed case chars in a string" do - t("НЕВЕРОЯТНОЕ УПУЩЕНИЕ").should == "NEVEROYATNOE UPUSCHENIE" - t("Невероятное Упущение").should == "Neveroyatnoe Upuschenie" - t("Шерстяной Заяц").should == "Sherstyanoy Zayats" - t("Н.П. Шерстяков").should == "N.P. Sherstyakov" - t("ШАРОВАРЫ").should == "SHAROVARY" - end - - it "should work for multi-char substrings" do - t("38 воробьёв").should == "38 vorobiev" - t("Вася Воробьёв").should == "Vasya Vorobiev" - t("Алябьев").should == "Alyabiev" - t("АЛЯБЬЕВ").should == "ALYABIEV" - end - end -end \ No newline at end of file