3mix-castronaut 0.5.0.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (904) hide show
  1. data/MIT-LICENSE +20 -0
  2. data/README.textile +75 -0
  3. data/Rakefile +105 -0
  4. data/app/config.rb +15 -0
  5. data/app/config.ru +24 -0
  6. data/app/controllers/application.rb +47 -0
  7. data/app/public/javascripts/application.js +3 -0
  8. data/app/public/javascripts/jquery.js +32 -0
  9. data/app/public/stylesheets/screen.css +122 -0
  10. data/app/views/layout.erb +27 -0
  11. data/app/views/login.erb +31 -0
  12. data/app/views/logout.erb +13 -0
  13. data/app/views/proxy_validate.erb +25 -0
  14. data/app/views/service_validate.erb +18 -0
  15. data/bin/castronaut +48 -0
  16. data/castronaut.rb +7 -0
  17. data/config/castronaut.example.yml +47 -0
  18. data/config/nginx_vhost.conf +24 -0
  19. data/config/thin_config.yml +13 -0
  20. data/lib/castronaut/adapters/active_record_adapter.rb +20 -0
  21. data/lib/castronaut/adapters/development/adapter.rb +13 -0
  22. data/lib/castronaut/adapters/development/user.rb +25 -0
  23. data/lib/castronaut/adapters/ldap/adapter.rb +15 -0
  24. data/lib/castronaut/adapters/ldap/user.rb +40 -0
  25. data/lib/castronaut/adapters/restful_authentication/adapter.rb +21 -0
  26. data/lib/castronaut/adapters/restful_authentication/user.rb +50 -0
  27. data/lib/castronaut/adapters.rb +17 -0
  28. data/lib/castronaut/authentication_result.rb +27 -0
  29. data/lib/castronaut/configuration.rb +95 -0
  30. data/lib/castronaut/db/001_create_cas_database.rb +47 -0
  31. data/lib/castronaut/db/002_change_username_to_identifier.rb +11 -0
  32. data/lib/castronaut/db/003_add_extra_info.rb +11 -0
  33. data/lib/castronaut/models/consumeable.rb +18 -0
  34. data/lib/castronaut/models/dispenser.rb +14 -0
  35. data/lib/castronaut/models/login_ticket.rb +53 -0
  36. data/lib/castronaut/models/proxy_granting_ticket.rb +69 -0
  37. data/lib/castronaut/models/proxy_ticket.rb +43 -0
  38. data/lib/castronaut/models/service_ticket.rb +100 -0
  39. data/lib/castronaut/models/ticket_granting_ticket.rb +70 -0
  40. data/lib/castronaut/presenters/base.rb +32 -0
  41. data/lib/castronaut/presenters/login.rb +60 -0
  42. data/lib/castronaut/presenters/logout.rb +40 -0
  43. data/lib/castronaut/presenters/process_login.rb +127 -0
  44. data/lib/castronaut/presenters/proxy_validate.rb +49 -0
  45. data/lib/castronaut/presenters/service_validate.rb +43 -0
  46. data/lib/castronaut/ticket_result.rb +27 -0
  47. data/lib/castronaut/utilities/random_string.rb +24 -0
  48. data/lib/castronaut.rb +34 -0
  49. data/lib/version.rb +5 -0
  50. data/spec/app/controllers/application_spec.rb +89 -0
  51. data/spec/castronaut/adapters/development/adapter_spec.rb +14 -0
  52. data/spec/castronaut/adapters/development/user_spec.rb +55 -0
  53. data/spec/castronaut/adapters/ldap/adapter_spec.rb +14 -0
  54. data/spec/castronaut/adapters/ldap/user_spec.rb +25 -0
  55. data/spec/castronaut/adapters/restful_authentication/adapter_spec.rb +14 -0
  56. data/spec/castronaut/adapters/restful_authentication/user_spec.rb +108 -0
  57. data/spec/castronaut/adapters_spec.rb +13 -0
  58. data/spec/castronaut/authentication_result_spec.rb +20 -0
  59. data/spec/castronaut/configuration_spec.rb +172 -0
  60. data/spec/castronaut/models/consumeable_spec.rb +39 -0
  61. data/spec/castronaut/models/dispenser_spec.rb +30 -0
  62. data/spec/castronaut/models/login_ticket_spec.rb +107 -0
  63. data/spec/castronaut/models/proxy_granting_ticket_spec.rb +302 -0
  64. data/spec/castronaut/models/proxy_ticket_spec.rb +109 -0
  65. data/spec/castronaut/models/service_ticket_spec.rb +269 -0
  66. data/spec/castronaut/models/ticket_granting_ticket_spec.rb +89 -0
  67. data/spec/castronaut/presenters/login_spec.rb +152 -0
  68. data/spec/castronaut/presenters/logout_spec.rb +85 -0
  69. data/spec/castronaut/presenters/process_login_spec.rb +300 -0
  70. data/spec/castronaut/presenters/proxy_validate_spec.rb +103 -0
  71. data/spec/castronaut/presenters/service_validate_spec.rb +86 -0
  72. data/spec/castronaut/ticket_result_spec.rb +42 -0
  73. data/spec/castronaut/utilities/random_string_spec.rb +14 -0
  74. data/spec/castronaut_spec.rb +26 -0
  75. data/spec/spec.opts +2 -0
  76. data/spec/spec_controller_helper.rb +17 -0
  77. data/spec/spec_helper.rb +49 -0
  78. data/spec/spec_rails_mocks.rb +132 -0
  79. data/vendor/activerecord/CHANGELOG +5753 -0
  80. data/vendor/activerecord/README +351 -0
  81. data/vendor/activerecord/RUNNING_UNIT_TESTS +36 -0
  82. data/vendor/activerecord/Rakefile +248 -0
  83. data/vendor/activerecord/examples/associations.png +0 -0
  84. data/vendor/activerecord/install.rb +30 -0
  85. data/vendor/activerecord/lib/active_record/aggregations.rb +189 -0
  86. data/vendor/activerecord/lib/active_record/association_preload.rb +282 -0
  87. data/vendor/activerecord/lib/active_record/associations/association_collection.rb +368 -0
  88. data/vendor/activerecord/lib/active_record/associations/association_proxy.rb +220 -0
  89. data/vendor/activerecord/lib/active_record/associations/belongs_to_association.rb +58 -0
  90. data/vendor/activerecord/lib/active_record/associations/belongs_to_polymorphic_association.rb +49 -0
  91. data/vendor/activerecord/lib/active_record/associations/has_and_belongs_to_many_association.rb +111 -0
  92. data/vendor/activerecord/lib/active_record/associations/has_many_association.rb +121 -0
  93. data/vendor/activerecord/lib/active_record/associations/has_many_through_association.rb +254 -0
  94. data/vendor/activerecord/lib/active_record/associations/has_one_association.rb +98 -0
  95. data/vendor/activerecord/lib/active_record/associations/has_one_through_association.rb +32 -0
  96. data/vendor/activerecord/lib/active_record/associations.rb +2012 -0
  97. data/vendor/activerecord/lib/active_record/attribute_methods.rb +379 -0
  98. data/vendor/activerecord/lib/active_record/base.rb +2744 -0
  99. data/vendor/activerecord/lib/active_record/calculations.rb +288 -0
  100. data/vendor/activerecord/lib/active_record/callbacks.rb +312 -0
  101. data/vendor/activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +309 -0
  102. data/vendor/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +176 -0
  103. data/vendor/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb +93 -0
  104. data/vendor/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +69 -0
  105. data/vendor/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +664 -0
  106. data/vendor/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +428 -0
  107. data/vendor/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +169 -0
  108. data/vendor/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +559 -0
  109. data/vendor/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +994 -0
  110. data/vendor/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +34 -0
  111. data/vendor/activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb +418 -0
  112. data/vendor/activerecord/lib/active_record/dirty.rb +165 -0
  113. data/vendor/activerecord/lib/active_record/fixtures.rb +997 -0
  114. data/vendor/activerecord/lib/active_record/locking/optimistic.rb +148 -0
  115. data/vendor/activerecord/lib/active_record/locking/pessimistic.rb +77 -0
  116. data/vendor/activerecord/lib/active_record/migration.rb +523 -0
  117. data/vendor/activerecord/lib/active_record/named_scope.rb +168 -0
  118. data/vendor/activerecord/lib/active_record/observer.rb +197 -0
  119. data/vendor/activerecord/lib/active_record/query_cache.rb +21 -0
  120. data/vendor/activerecord/lib/active_record/reflection.rb +239 -0
  121. data/vendor/activerecord/lib/active_record/schema.rb +51 -0
  122. data/vendor/activerecord/lib/active_record/schema_dumper.rb +171 -0
  123. data/vendor/activerecord/lib/active_record/serialization.rb +98 -0
  124. data/vendor/activerecord/lib/active_record/serializers/json_serializer.rb +80 -0
  125. data/vendor/activerecord/lib/active_record/serializers/xml_serializer.rb +338 -0
  126. data/vendor/activerecord/lib/active_record/test_case.rb +47 -0
  127. data/vendor/activerecord/lib/active_record/timestamp.rb +41 -0
  128. data/vendor/activerecord/lib/active_record/transactions.rb +130 -0
  129. data/vendor/activerecord/lib/active_record/validations.rb +971 -0
  130. data/vendor/activerecord/lib/active_record/vendor/mysql.rb +1214 -0
  131. data/vendor/activerecord/lib/active_record/version.rb +9 -0
  132. data/vendor/activerecord/lib/active_record.rb +80 -0
  133. data/vendor/activerecord/lib/activerecord.rb +1 -0
  134. data/vendor/activerecord/test/assets/example.log +1 -0
  135. data/vendor/activerecord/test/assets/flowers.jpg +0 -0
  136. data/vendor/activerecord/test/cases/aaa_create_tables_test.rb +24 -0
  137. data/vendor/activerecord/test/cases/active_schema_test_mysql.rb +95 -0
  138. data/vendor/activerecord/test/cases/active_schema_test_postgresql.rb +24 -0
  139. data/vendor/activerecord/test/cases/adapter_test.rb +127 -0
  140. data/vendor/activerecord/test/cases/adapter_test_sqlserver.rb +95 -0
  141. data/vendor/activerecord/test/cases/aggregations_test.rb +128 -0
  142. data/vendor/activerecord/test/cases/ar_schema_test.rb +33 -0
  143. data/vendor/activerecord/test/cases/associations/belongs_to_associations_test.rb +431 -0
  144. data/vendor/activerecord/test/cases/associations/callbacks_test.rb +161 -0
  145. data/vendor/activerecord/test/cases/associations/cascaded_eager_loading_test.rb +123 -0
  146. data/vendor/activerecord/test/cases/associations/eager_load_includes_full_sti_class_test.rb +36 -0
  147. data/vendor/activerecord/test/cases/associations/eager_load_nested_include_test.rb +83 -0
  148. data/vendor/activerecord/test/cases/associations/eager_singularization_test.rb +145 -0
  149. data/vendor/activerecord/test/cases/associations/eager_test.rb +636 -0
  150. data/vendor/activerecord/test/cases/associations/extension_test.rb +47 -0
  151. data/vendor/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +706 -0
  152. data/vendor/activerecord/test/cases/associations/has_many_associations_test.rb +1034 -0
  153. data/vendor/activerecord/test/cases/associations/has_many_through_associations_test.rb +200 -0
  154. data/vendor/activerecord/test/cases/associations/has_one_associations_test.rb +345 -0
  155. data/vendor/activerecord/test/cases/associations/has_one_through_associations_test.rb +113 -0
  156. data/vendor/activerecord/test/cases/associations/inner_join_association_test.rb +88 -0
  157. data/vendor/activerecord/test/cases/associations/join_model_test.rb +714 -0
  158. data/vendor/activerecord/test/cases/associations_test.rb +262 -0
  159. data/vendor/activerecord/test/cases/attribute_methods_test.rb +238 -0
  160. data/vendor/activerecord/test/cases/base_test.rb +1997 -0
  161. data/vendor/activerecord/test/cases/binary_test.rb +34 -0
  162. data/vendor/activerecord/test/cases/calculations_test.rb +323 -0
  163. data/vendor/activerecord/test/cases/callbacks_test.rb +400 -0
  164. data/vendor/activerecord/test/cases/class_inheritable_attributes_test.rb +32 -0
  165. data/vendor/activerecord/test/cases/column_alias_test.rb +17 -0
  166. data/vendor/activerecord/test/cases/column_definition_test.rb +36 -0
  167. data/vendor/activerecord/test/cases/connection_test_firebird.rb +8 -0
  168. data/vendor/activerecord/test/cases/connection_test_mysql.rb +30 -0
  169. data/vendor/activerecord/test/cases/copy_table_test_sqlite.rb +69 -0
  170. data/vendor/activerecord/test/cases/database_statements_test.rb +12 -0
  171. data/vendor/activerecord/test/cases/datatype_test_postgresql.rb +203 -0
  172. data/vendor/activerecord/test/cases/date_time_test.rb +37 -0
  173. data/vendor/activerecord/test/cases/default_test_firebird.rb +16 -0
  174. data/vendor/activerecord/test/cases/defaults_test.rb +69 -0
  175. data/vendor/activerecord/test/cases/deprecated_finder_test.rb +30 -0
  176. data/vendor/activerecord/test/cases/dirty_test.rb +257 -0
  177. data/vendor/activerecord/test/cases/finder_respond_to_test.rb +76 -0
  178. data/vendor/activerecord/test/cases/finder_test.rb +890 -0
  179. data/vendor/activerecord/test/cases/fixtures_test.rb +626 -0
  180. data/vendor/activerecord/test/cases/helper.rb +47 -0
  181. data/vendor/activerecord/test/cases/inheritance_test.rb +262 -0
  182. data/vendor/activerecord/test/cases/invalid_date_test.rb +24 -0
  183. data/vendor/activerecord/test/cases/json_serialization_test.rb +205 -0
  184. data/vendor/activerecord/test/cases/lifecycle_test.rb +193 -0
  185. data/vendor/activerecord/test/cases/locking_test.rb +309 -0
  186. data/vendor/activerecord/test/cases/method_scoping_test.rb +462 -0
  187. data/vendor/activerecord/test/cases/migration_test.rb +1444 -0
  188. data/vendor/activerecord/test/cases/migration_test_firebird.rb +124 -0
  189. data/vendor/activerecord/test/cases/mixin_test.rb +96 -0
  190. data/vendor/activerecord/test/cases/modules_test.rb +39 -0
  191. data/vendor/activerecord/test/cases/multiple_db_test.rb +60 -0
  192. data/vendor/activerecord/test/cases/named_scope_test.rb +206 -0
  193. data/vendor/activerecord/test/cases/pk_test.rb +101 -0
  194. data/vendor/activerecord/test/cases/query_cache_test.rb +127 -0
  195. data/vendor/activerecord/test/cases/readonly_test.rb +107 -0
  196. data/vendor/activerecord/test/cases/reflection_test.rb +176 -0
  197. data/vendor/activerecord/test/cases/reserved_word_test_mysql.rb +176 -0
  198. data/vendor/activerecord/test/cases/schema_authorization_test_postgresql.rb +75 -0
  199. data/vendor/activerecord/test/cases/schema_dumper_test.rb +184 -0
  200. data/vendor/activerecord/test/cases/schema_test_postgresql.rb +102 -0
  201. data/vendor/activerecord/test/cases/serialization_test.rb +47 -0
  202. data/vendor/activerecord/test/cases/synonym_test_oracle.rb +17 -0
  203. data/vendor/activerecord/test/cases/table_name_test_sqlserver.rb +23 -0
  204. data/vendor/activerecord/test/cases/threaded_connections_test.rb +48 -0
  205. data/vendor/activerecord/test/cases/transactions_test.rb +307 -0
  206. data/vendor/activerecord/test/cases/unconnected_test.rb +32 -0
  207. data/vendor/activerecord/test/cases/validations_test.rb +1534 -0
  208. data/vendor/activerecord/test/cases/xml_serialization_test.rb +202 -0
  209. data/vendor/activerecord/test/config.rb +5 -0
  210. data/vendor/activerecord/test/connections/native_db2/connection.rb +25 -0
  211. data/vendor/activerecord/test/connections/native_firebird/connection.rb +26 -0
  212. data/vendor/activerecord/test/connections/native_frontbase/connection.rb +27 -0
  213. data/vendor/activerecord/test/connections/native_mysql/connection.rb +27 -0
  214. data/vendor/activerecord/test/connections/native_openbase/connection.rb +21 -0
  215. data/vendor/activerecord/test/connections/native_oracle/connection.rb +27 -0
  216. data/vendor/activerecord/test/connections/native_postgresql/connection.rb +21 -0
  217. data/vendor/activerecord/test/connections/native_sqlite/connection.rb +25 -0
  218. data/vendor/activerecord/test/connections/native_sqlite3/connection.rb +25 -0
  219. data/vendor/activerecord/test/connections/native_sqlite3/in_memory_connection.rb +18 -0
  220. data/vendor/activerecord/test/connections/native_sybase/connection.rb +23 -0
  221. data/vendor/activerecord/test/debug.log +358 -0
  222. data/vendor/activerecord/test/fixtures/accounts.yml +28 -0
  223. data/vendor/activerecord/test/fixtures/all/developers.yml +0 -0
  224. data/vendor/activerecord/test/fixtures/all/people.csv +0 -0
  225. data/vendor/activerecord/test/fixtures/all/tasks.yml +0 -0
  226. data/vendor/activerecord/test/fixtures/author_addresses.yml +5 -0
  227. data/vendor/activerecord/test/fixtures/author_favorites.yml +4 -0
  228. data/vendor/activerecord/test/fixtures/authors.yml +9 -0
  229. data/vendor/activerecord/test/fixtures/binaries.yml +132 -0
  230. data/vendor/activerecord/test/fixtures/books.yml +7 -0
  231. data/vendor/activerecord/test/fixtures/categories/special_categories.yml +9 -0
  232. data/vendor/activerecord/test/fixtures/categories/subsubdir/arbitrary_filename.yml +4 -0
  233. data/vendor/activerecord/test/fixtures/categories.yml +14 -0
  234. data/vendor/activerecord/test/fixtures/categories_ordered.yml +7 -0
  235. data/vendor/activerecord/test/fixtures/categories_posts.yml +23 -0
  236. data/vendor/activerecord/test/fixtures/categorizations.yml +17 -0
  237. data/vendor/activerecord/test/fixtures/clubs.yml +6 -0
  238. data/vendor/activerecord/test/fixtures/comments.yml +59 -0
  239. data/vendor/activerecord/test/fixtures/companies.yml +55 -0
  240. data/vendor/activerecord/test/fixtures/computers.yml +4 -0
  241. data/vendor/activerecord/test/fixtures/courses.yml +7 -0
  242. data/vendor/activerecord/test/fixtures/customers.yml +17 -0
  243. data/vendor/activerecord/test/fixtures/developers.yml +21 -0
  244. data/vendor/activerecord/test/fixtures/developers_projects.yml +17 -0
  245. data/vendor/activerecord/test/fixtures/edges.yml +6 -0
  246. data/vendor/activerecord/test/fixtures/entrants.yml +14 -0
  247. data/vendor/activerecord/test/fixtures/fixture_database.sqlite3 +0 -0
  248. data/vendor/activerecord/test/fixtures/fixture_database_2.sqlite3 +0 -0
  249. data/vendor/activerecord/test/fixtures/fk_test_has_fk.yml +3 -0
  250. data/vendor/activerecord/test/fixtures/fk_test_has_pk.yml +2 -0
  251. data/vendor/activerecord/test/fixtures/funny_jokes.yml +10 -0
  252. data/vendor/activerecord/test/fixtures/items.yml +4 -0
  253. data/vendor/activerecord/test/fixtures/jobs.yml +7 -0
  254. data/vendor/activerecord/test/fixtures/legacy_things.yml +3 -0
  255. data/vendor/activerecord/test/fixtures/mateys.yml +4 -0
  256. data/vendor/activerecord/test/fixtures/members.yml +4 -0
  257. data/vendor/activerecord/test/fixtures/memberships.yml +20 -0
  258. data/vendor/activerecord/test/fixtures/minimalistics.yml +2 -0
  259. data/vendor/activerecord/test/fixtures/mixed_case_monkeys.yml +6 -0
  260. data/vendor/activerecord/test/fixtures/mixins.yml +29 -0
  261. data/vendor/activerecord/test/fixtures/movies.yml +7 -0
  262. data/vendor/activerecord/test/fixtures/naked/csv/accounts.csv +1 -0
  263. data/vendor/activerecord/test/fixtures/naked/yml/accounts.yml +1 -0
  264. data/vendor/activerecord/test/fixtures/naked/yml/companies.yml +1 -0
  265. data/vendor/activerecord/test/fixtures/naked/yml/courses.yml +1 -0
  266. data/vendor/activerecord/test/fixtures/owners.yml +7 -0
  267. data/vendor/activerecord/test/fixtures/parrots.yml +27 -0
  268. data/vendor/activerecord/test/fixtures/parrots_pirates.yml +7 -0
  269. data/vendor/activerecord/test/fixtures/people.yml +6 -0
  270. data/vendor/activerecord/test/fixtures/pets.yml +14 -0
  271. data/vendor/activerecord/test/fixtures/pirates.yml +9 -0
  272. data/vendor/activerecord/test/fixtures/posts.yml +49 -0
  273. data/vendor/activerecord/test/fixtures/price_estimates.yml +7 -0
  274. data/vendor/activerecord/test/fixtures/projects.yml +7 -0
  275. data/vendor/activerecord/test/fixtures/readers.yml +9 -0
  276. data/vendor/activerecord/test/fixtures/references.yml +17 -0
  277. data/vendor/activerecord/test/fixtures/reserved_words/distinct.yml +5 -0
  278. data/vendor/activerecord/test/fixtures/reserved_words/distincts_selects.yml +11 -0
  279. data/vendor/activerecord/test/fixtures/reserved_words/group.yml +14 -0
  280. data/vendor/activerecord/test/fixtures/reserved_words/select.yml +8 -0
  281. data/vendor/activerecord/test/fixtures/reserved_words/values.yml +7 -0
  282. data/vendor/activerecord/test/fixtures/ships.yml +5 -0
  283. data/vendor/activerecord/test/fixtures/sponsors.yml +9 -0
  284. data/vendor/activerecord/test/fixtures/subscribers.yml +7 -0
  285. data/vendor/activerecord/test/fixtures/subscriptions.yml +12 -0
  286. data/vendor/activerecord/test/fixtures/taggings.yml +28 -0
  287. data/vendor/activerecord/test/fixtures/tags.yml +7 -0
  288. data/vendor/activerecord/test/fixtures/tasks.yml +7 -0
  289. data/vendor/activerecord/test/fixtures/topics.yml +42 -0
  290. data/vendor/activerecord/test/fixtures/treasures.yml +10 -0
  291. data/vendor/activerecord/test/fixtures/vertices.yml +4 -0
  292. data/vendor/activerecord/test/fixtures/warehouse-things.yml +3 -0
  293. data/vendor/activerecord/test/migrations/decimal/1_give_me_big_numbers.rb +15 -0
  294. data/vendor/activerecord/test/migrations/duplicate/1_people_have_last_names.rb +9 -0
  295. data/vendor/activerecord/test/migrations/duplicate/2_we_need_reminders.rb +12 -0
  296. data/vendor/activerecord/test/migrations/duplicate/3_foo.rb +7 -0
  297. data/vendor/activerecord/test/migrations/duplicate/3_innocent_jointable.rb +12 -0
  298. data/vendor/activerecord/test/migrations/duplicate_names/20080507052938_chunky.rb +7 -0
  299. data/vendor/activerecord/test/migrations/duplicate_names/20080507053028_chunky.rb +7 -0
  300. data/vendor/activerecord/test/migrations/interleaved/pass_1/3_innocent_jointable.rb +12 -0
  301. data/vendor/activerecord/test/migrations/interleaved/pass_2/1_people_have_last_names.rb +9 -0
  302. data/vendor/activerecord/test/migrations/interleaved/pass_2/3_innocent_jointable.rb +12 -0
  303. data/vendor/activerecord/test/migrations/interleaved/pass_3/1_people_have_last_names.rb +9 -0
  304. data/vendor/activerecord/test/migrations/interleaved/pass_3/2_i_raise_on_down.rb +8 -0
  305. data/vendor/activerecord/test/migrations/interleaved/pass_3/3_innocent_jointable.rb +12 -0
  306. data/vendor/activerecord/test/migrations/missing/1000_people_have_middle_names.rb +9 -0
  307. data/vendor/activerecord/test/migrations/missing/1_people_have_last_names.rb +9 -0
  308. data/vendor/activerecord/test/migrations/missing/3_we_need_reminders.rb +12 -0
  309. data/vendor/activerecord/test/migrations/missing/4_innocent_jointable.rb +12 -0
  310. data/vendor/activerecord/test/migrations/valid/1_people_have_last_names.rb +9 -0
  311. data/vendor/activerecord/test/migrations/valid/2_we_need_reminders.rb +12 -0
  312. data/vendor/activerecord/test/migrations/valid/3_innocent_jointable.rb +12 -0
  313. data/vendor/activerecord/test/models/author.rb +137 -0
  314. data/vendor/activerecord/test/models/auto_id.rb +4 -0
  315. data/vendor/activerecord/test/models/binary.rb +2 -0
  316. data/vendor/activerecord/test/models/book.rb +4 -0
  317. data/vendor/activerecord/test/models/categorization.rb +5 -0
  318. data/vendor/activerecord/test/models/category.rb +30 -0
  319. data/vendor/activerecord/test/models/citation.rb +6 -0
  320. data/vendor/activerecord/test/models/club.rb +7 -0
  321. data/vendor/activerecord/test/models/column_name.rb +3 -0
  322. data/vendor/activerecord/test/models/comment.rb +25 -0
  323. data/vendor/activerecord/test/models/company.rb +132 -0
  324. data/vendor/activerecord/test/models/company_in_module.rb +61 -0
  325. data/vendor/activerecord/test/models/computer.rb +3 -0
  326. data/vendor/activerecord/test/models/contact.rb +16 -0
  327. data/vendor/activerecord/test/models/course.rb +3 -0
  328. data/vendor/activerecord/test/models/customer.rb +55 -0
  329. data/vendor/activerecord/test/models/default.rb +2 -0
  330. data/vendor/activerecord/test/models/developer.rb +79 -0
  331. data/vendor/activerecord/test/models/edge.rb +5 -0
  332. data/vendor/activerecord/test/models/entrant.rb +3 -0
  333. data/vendor/activerecord/test/models/guid.rb +2 -0
  334. data/vendor/activerecord/test/models/item.rb +7 -0
  335. data/vendor/activerecord/test/models/job.rb +5 -0
  336. data/vendor/activerecord/test/models/joke.rb +3 -0
  337. data/vendor/activerecord/test/models/keyboard.rb +3 -0
  338. data/vendor/activerecord/test/models/legacy_thing.rb +3 -0
  339. data/vendor/activerecord/test/models/matey.rb +4 -0
  340. data/vendor/activerecord/test/models/member.rb +9 -0
  341. data/vendor/activerecord/test/models/membership.rb +9 -0
  342. data/vendor/activerecord/test/models/minimalistic.rb +2 -0
  343. data/vendor/activerecord/test/models/mixed_case_monkey.rb +3 -0
  344. data/vendor/activerecord/test/models/movie.rb +5 -0
  345. data/vendor/activerecord/test/models/order.rb +4 -0
  346. data/vendor/activerecord/test/models/owner.rb +4 -0
  347. data/vendor/activerecord/test/models/parrot.rb +13 -0
  348. data/vendor/activerecord/test/models/person.rb +10 -0
  349. data/vendor/activerecord/test/models/pet.rb +4 -0
  350. data/vendor/activerecord/test/models/pirate.rb +9 -0
  351. data/vendor/activerecord/test/models/post.rb +85 -0
  352. data/vendor/activerecord/test/models/price_estimate.rb +3 -0
  353. data/vendor/activerecord/test/models/project.rb +29 -0
  354. data/vendor/activerecord/test/models/reader.rb +4 -0
  355. data/vendor/activerecord/test/models/reference.rb +4 -0
  356. data/vendor/activerecord/test/models/reply.rb +39 -0
  357. data/vendor/activerecord/test/models/ship.rb +3 -0
  358. data/vendor/activerecord/test/models/sponsor.rb +4 -0
  359. data/vendor/activerecord/test/models/subject.rb +4 -0
  360. data/vendor/activerecord/test/models/subscriber.rb +8 -0
  361. data/vendor/activerecord/test/models/subscription.rb +4 -0
  362. data/vendor/activerecord/test/models/tag.rb +7 -0
  363. data/vendor/activerecord/test/models/tagging.rb +10 -0
  364. data/vendor/activerecord/test/models/task.rb +3 -0
  365. data/vendor/activerecord/test/models/topic.rb +66 -0
  366. data/vendor/activerecord/test/models/treasure.rb +6 -0
  367. data/vendor/activerecord/test/models/vertex.rb +9 -0
  368. data/vendor/activerecord/test/models/warehouse_thing.rb +5 -0
  369. data/vendor/activerecord/test/schema/mysql_specific_schema.rb +12 -0
  370. data/vendor/activerecord/test/schema/postgresql_specific_schema.rb +103 -0
  371. data/vendor/activerecord/test/schema/schema.rb +429 -0
  372. data/vendor/activerecord/test/schema/schema2.rb +6 -0
  373. data/vendor/activerecord/test/schema/sqlite_specific_schema.rb +25 -0
  374. data/vendor/activerecord/test/schema/sqlserver_specific_schema.rb +5 -0
  375. data/vendor/activesupport/CHANGELOG +1193 -0
  376. data/vendor/activesupport/README +43 -0
  377. data/vendor/activesupport/lib/active_support/base64.rb +22 -0
  378. data/vendor/activesupport/lib/active_support/basic_object.rb +24 -0
  379. data/vendor/activesupport/lib/active_support/buffered_logger.rb +121 -0
  380. data/vendor/activesupport/lib/active_support/cache/compressed_mem_cache_store.rb +15 -0
  381. data/vendor/activesupport/lib/active_support/cache/drb_store.rb +15 -0
  382. data/vendor/activesupport/lib/active_support/cache/file_store.rb +70 -0
  383. data/vendor/activesupport/lib/active_support/cache/mem_cache_store.rb +100 -0
  384. data/vendor/activesupport/lib/active_support/cache/memory_store.rb +38 -0
  385. data/vendor/activesupport/lib/active_support/cache.rb +147 -0
  386. data/vendor/activesupport/lib/active_support/callbacks.rb +275 -0
  387. data/vendor/activesupport/lib/active_support/clean_logger.rb +127 -0
  388. data/vendor/activesupport/lib/active_support/core_ext/array/access.rb +26 -0
  389. data/vendor/activesupport/lib/active_support/core_ext/array/conversions.rb +178 -0
  390. data/vendor/activesupport/lib/active_support/core_ext/array/extract_options.rb +20 -0
  391. data/vendor/activesupport/lib/active_support/core_ext/array/grouping.rb +63 -0
  392. data/vendor/activesupport/lib/active_support/core_ext/array/random_access.rb +12 -0
  393. data/vendor/activesupport/lib/active_support/core_ext/array.rb +13 -0
  394. data/vendor/activesupport/lib/active_support/core_ext/base64/encoding.rb +13 -0
  395. data/vendor/activesupport/lib/active_support/core_ext/base64.rb +4 -0
  396. data/vendor/activesupport/lib/active_support/core_ext/benchmark.rb +12 -0
  397. data/vendor/activesupport/lib/active_support/core_ext/bigdecimal/conversions.rb +41 -0
  398. data/vendor/activesupport/lib/active_support/core_ext/bigdecimal.rb +6 -0
  399. data/vendor/activesupport/lib/active_support/core_ext/blank.rb +53 -0
  400. data/vendor/activesupport/lib/active_support/core_ext/cgi/escape_skipping_slashes.rb +14 -0
  401. data/vendor/activesupport/lib/active_support/core_ext/cgi.rb +5 -0
  402. data/vendor/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb +54 -0
  403. data/vendor/activesupport/lib/active_support/core_ext/class/delegating_attributes.rb +46 -0
  404. data/vendor/activesupport/lib/active_support/core_ext/class/inheritable_attributes.rb +140 -0
  405. data/vendor/activesupport/lib/active_support/core_ext/class/removal.rb +50 -0
  406. data/vendor/activesupport/lib/active_support/core_ext/class.rb +4 -0
  407. data/vendor/activesupport/lib/active_support/core_ext/date/behavior.rb +39 -0
  408. data/vendor/activesupport/lib/active_support/core_ext/date/calculations.rb +215 -0
  409. data/vendor/activesupport/lib/active_support/core_ext/date/conversions.rb +107 -0
  410. data/vendor/activesupport/lib/active_support/core_ext/date.rb +10 -0
  411. data/vendor/activesupport/lib/active_support/core_ext/date_time/calculations.rb +112 -0
  412. data/vendor/activesupport/lib/active_support/core_ext/date_time/conversions.rb +96 -0
  413. data/vendor/activesupport/lib/active_support/core_ext/date_time.rb +12 -0
  414. data/vendor/activesupport/lib/active_support/core_ext/duplicable.rb +37 -0
  415. data/vendor/activesupport/lib/active_support/core_ext/enumerable.rb +69 -0
  416. data/vendor/activesupport/lib/active_support/core_ext/exception.rb +41 -0
  417. data/vendor/activesupport/lib/active_support/core_ext/file.rb +21 -0
  418. data/vendor/activesupport/lib/active_support/core_ext/float/rounding.rb +24 -0
  419. data/vendor/activesupport/lib/active_support/core_ext/float.rb +5 -0
  420. data/vendor/activesupport/lib/active_support/core_ext/hash/conversions.rb +259 -0
  421. data/vendor/activesupport/lib/active_support/core_ext/hash/diff.rb +19 -0
  422. data/vendor/activesupport/lib/active_support/core_ext/hash/except.rb +25 -0
  423. data/vendor/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb +137 -0
  424. data/vendor/activesupport/lib/active_support/core_ext/hash/keys.rb +52 -0
  425. data/vendor/activesupport/lib/active_support/core_ext/hash/reverse_merge.rb +28 -0
  426. data/vendor/activesupport/lib/active_support/core_ext/hash/slice.rb +30 -0
  427. data/vendor/activesupport/lib/active_support/core_ext/hash.rb +13 -0
  428. data/vendor/activesupport/lib/active_support/core_ext/integer/even_odd.rb +29 -0
  429. data/vendor/activesupport/lib/active_support/core_ext/integer/inflections.rb +20 -0
  430. data/vendor/activesupport/lib/active_support/core_ext/integer.rb +7 -0
  431. data/vendor/activesupport/lib/active_support/core_ext/kernel/agnostics.rb +11 -0
  432. data/vendor/activesupport/lib/active_support/core_ext/kernel/daemonizing.rb +7 -0
  433. data/vendor/activesupport/lib/active_support/core_ext/kernel/debugger.rb +13 -0
  434. data/vendor/activesupport/lib/active_support/core_ext/kernel/reporting.rb +59 -0
  435. data/vendor/activesupport/lib/active_support/core_ext/kernel/requires.rb +24 -0
  436. data/vendor/activesupport/lib/active_support/core_ext/kernel.rb +5 -0
  437. data/vendor/activesupport/lib/active_support/core_ext/load_error.rb +38 -0
  438. data/vendor/activesupport/lib/active_support/core_ext/logger.rb +16 -0
  439. data/vendor/activesupport/lib/active_support/core_ext/module/aliasing.rb +70 -0
  440. data/vendor/activesupport/lib/active_support/core_ext/module/attr_accessor_with_default.rb +31 -0
  441. data/vendor/activesupport/lib/active_support/core_ext/module/attr_internal.rb +32 -0
  442. data/vendor/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb +58 -0
  443. data/vendor/activesupport/lib/active_support/core_ext/module/delegation.rb +64 -0
  444. data/vendor/activesupport/lib/active_support/core_ext/module/inclusion.rb +30 -0
  445. data/vendor/activesupport/lib/active_support/core_ext/module/introspection.rb +75 -0
  446. data/vendor/activesupport/lib/active_support/core_ext/module/loading.rb +23 -0
  447. data/vendor/activesupport/lib/active_support/core_ext/module/model_naming.rb +22 -0
  448. data/vendor/activesupport/lib/active_support/core_ext/module.rb +13 -0
  449. data/vendor/activesupport/lib/active_support/core_ext/name_error.rb +17 -0
  450. data/vendor/activesupport/lib/active_support/core_ext/numeric/bytes.rb +44 -0
  451. data/vendor/activesupport/lib/active_support/core_ext/numeric/conversions.rb +19 -0
  452. data/vendor/activesupport/lib/active_support/core_ext/numeric/time.rb +91 -0
  453. data/vendor/activesupport/lib/active_support/core_ext/numeric.rb +9 -0
  454. data/vendor/activesupport/lib/active_support/core_ext/object/conversions.rb +14 -0
  455. data/vendor/activesupport/lib/active_support/core_ext/object/extending.rb +59 -0
  456. data/vendor/activesupport/lib/active_support/core_ext/object/instance_variables.rb +74 -0
  457. data/vendor/activesupport/lib/active_support/core_ext/object/misc.rb +59 -0
  458. data/vendor/activesupport/lib/active_support/core_ext/object.rb +4 -0
  459. data/vendor/activesupport/lib/active_support/core_ext/pathname/clean_within.rb +14 -0
  460. data/vendor/activesupport/lib/active_support/core_ext/pathname.rb +7 -0
  461. data/vendor/activesupport/lib/active_support/core_ext/proc.rb +12 -0
  462. data/vendor/activesupport/lib/active_support/core_ext/process/daemon.rb +25 -0
  463. data/vendor/activesupport/lib/active_support/core_ext/process.rb +1 -0
  464. data/vendor/activesupport/lib/active_support/core_ext/range/blockless_step.rb +32 -0
  465. data/vendor/activesupport/lib/active_support/core_ext/range/conversions.rb +27 -0
  466. data/vendor/activesupport/lib/active_support/core_ext/range/include_range.rb +30 -0
  467. data/vendor/activesupport/lib/active_support/core_ext/range/overlaps.rb +15 -0
  468. data/vendor/activesupport/lib/active_support/core_ext/range.rb +11 -0
  469. data/vendor/activesupport/lib/active_support/core_ext/rexml.rb +35 -0
  470. data/vendor/activesupport/lib/active_support/core_ext/string/access.rb +82 -0
  471. data/vendor/activesupport/lib/active_support/core_ext/string/conversions.rb +28 -0
  472. data/vendor/activesupport/lib/active_support/core_ext/string/filters.rb +26 -0
  473. data/vendor/activesupport/lib/active_support/core_ext/string/inflections.rb +148 -0
  474. data/vendor/activesupport/lib/active_support/core_ext/string/iterators.rb +21 -0
  475. data/vendor/activesupport/lib/active_support/core_ext/string/starts_ends_with.rb +35 -0
  476. data/vendor/activesupport/lib/active_support/core_ext/string/unicode.rb +66 -0
  477. data/vendor/activesupport/lib/active_support/core_ext/string/xchar.rb +11 -0
  478. data/vendor/activesupport/lib/active_support/core_ext/string.rb +18 -0
  479. data/vendor/activesupport/lib/active_support/core_ext/symbol.rb +14 -0
  480. data/vendor/activesupport/lib/active_support/core_ext/test/unit/assertions.rb +64 -0
  481. data/vendor/activesupport/lib/active_support/core_ext/test.rb +1 -0
  482. data/vendor/activesupport/lib/active_support/core_ext/time/behavior.rb +13 -0
  483. data/vendor/activesupport/lib/active_support/core_ext/time/calculations.rb +276 -0
  484. data/vendor/activesupport/lib/active_support/core_ext/time/conversions.rb +89 -0
  485. data/vendor/activesupport/lib/active_support/core_ext/time/zones.rb +86 -0
  486. data/vendor/activesupport/lib/active_support/core_ext/time.rb +42 -0
  487. data/vendor/activesupport/lib/active_support/core_ext.rb +4 -0
  488. data/vendor/activesupport/lib/active_support/dependencies.rb +553 -0
  489. data/vendor/activesupport/lib/active_support/deprecation.rb +223 -0
  490. data/vendor/activesupport/lib/active_support/duration.rb +96 -0
  491. data/vendor/activesupport/lib/active_support/gzip.rb +25 -0
  492. data/vendor/activesupport/lib/active_support/inflections.rb +55 -0
  493. data/vendor/activesupport/lib/active_support/inflector.rb +313 -0
  494. data/vendor/activesupport/lib/active_support/json/decoding.rb +63 -0
  495. data/vendor/activesupport/lib/active_support/json/encoders/date.rb +14 -0
  496. data/vendor/activesupport/lib/active_support/json/encoders/date_time.rb +14 -0
  497. data/vendor/activesupport/lib/active_support/json/encoders/enumerable.rb +12 -0
  498. data/vendor/activesupport/lib/active_support/json/encoders/false_class.rb +5 -0
  499. data/vendor/activesupport/lib/active_support/json/encoders/hash.rb +47 -0
  500. data/vendor/activesupport/lib/active_support/json/encoders/nil_class.rb +5 -0
  501. data/vendor/activesupport/lib/active_support/json/encoders/numeric.rb +5 -0
  502. data/vendor/activesupport/lib/active_support/json/encoders/object.rb +6 -0
  503. data/vendor/activesupport/lib/active_support/json/encoders/regexp.rb +5 -0
  504. data/vendor/activesupport/lib/active_support/json/encoders/string.rb +36 -0
  505. data/vendor/activesupport/lib/active_support/json/encoders/symbol.rb +5 -0
  506. data/vendor/activesupport/lib/active_support/json/encoders/time.rb +14 -0
  507. data/vendor/activesupport/lib/active_support/json/encoders/true_class.rb +5 -0
  508. data/vendor/activesupport/lib/active_support/json/encoding.rb +37 -0
  509. data/vendor/activesupport/lib/active_support/json/variable.rb +10 -0
  510. data/vendor/activesupport/lib/active_support/json.rb +23 -0
  511. data/vendor/activesupport/lib/active_support/multibyte/chars.rb +137 -0
  512. data/vendor/activesupport/lib/active_support/multibyte/generators/generate_tables.rb +149 -0
  513. data/vendor/activesupport/lib/active_support/multibyte/handlers/passthru_handler.rb +9 -0
  514. data/vendor/activesupport/lib/active_support/multibyte/handlers/utf8_handler.rb +564 -0
  515. data/vendor/activesupport/lib/active_support/multibyte/handlers/utf8_handler_proc.rb +43 -0
  516. data/vendor/activesupport/lib/active_support/multibyte.rb +9 -0
  517. data/vendor/activesupport/lib/active_support/option_merger.rb +25 -0
  518. data/vendor/activesupport/lib/active_support/ordered_hash.rb +43 -0
  519. data/vendor/activesupport/lib/active_support/ordered_options.rb +19 -0
  520. data/vendor/activesupport/lib/active_support/string_inquirer.rb +11 -0
  521. data/vendor/activesupport/lib/active_support/test_case.rb +13 -0
  522. data/vendor/activesupport/lib/active_support/testing/default.rb +9 -0
  523. data/vendor/activesupport/lib/active_support/testing/setup_and_teardown.rb +93 -0
  524. data/vendor/activesupport/lib/active_support/time_with_zone.rb +304 -0
  525. data/vendor/activesupport/lib/active_support/values/time_zone.rb +396 -0
  526. data/vendor/activesupport/lib/active_support/values/unicode_tables.dat +0 -0
  527. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/blankslate.rb +113 -0
  528. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/builder/blankslate.rb +20 -0
  529. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/builder/css.rb +250 -0
  530. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xchar.rb +115 -0
  531. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlbase.rb +139 -0
  532. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlevents.rb +63 -0
  533. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/builder/xmlmarkup.rb +328 -0
  534. data/vendor/activesupport/lib/active_support/vendor/builder-2.1.2/builder.rb +13 -0
  535. data/vendor/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb +849 -0
  536. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/data_timezone.rb +47 -0
  537. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/data_timezone_info.rb +228 -0
  538. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Africa/Algiers.rb +55 -0
  539. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Africa/Cairo.rb +219 -0
  540. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Africa/Casablanca.rb +40 -0
  541. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Africa/Harare.rb +18 -0
  542. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Africa/Johannesburg.rb +25 -0
  543. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Africa/Monrovia.rb +22 -0
  544. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Africa/Nairobi.rb +23 -0
  545. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Argentina/Buenos_Aires.rb +166 -0
  546. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Argentina/San_Juan.rb +170 -0
  547. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Bogota.rb +23 -0
  548. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Caracas.rb +23 -0
  549. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Chicago.rb +283 -0
  550. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Chihuahua.rb +136 -0
  551. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Denver.rb +204 -0
  552. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Godthab.rb +161 -0
  553. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Guatemala.rb +27 -0
  554. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Halifax.rb +274 -0
  555. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Indiana/Indianapolis.rb +149 -0
  556. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Juneau.rb +194 -0
  557. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/La_Paz.rb +22 -0
  558. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Lima.rb +35 -0
  559. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Los_Angeles.rb +232 -0
  560. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Mazatlan.rb +139 -0
  561. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Mexico_City.rb +144 -0
  562. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Monterrey.rb +131 -0
  563. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/New_York.rb +282 -0
  564. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Phoenix.rb +30 -0
  565. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Regina.rb +74 -0
  566. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Santiago.rb +205 -0
  567. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/St_Johns.rb +288 -0
  568. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/America/Tijuana.rb +196 -0
  569. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Almaty.rb +67 -0
  570. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Baghdad.rb +73 -0
  571. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Baku.rb +161 -0
  572. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Bangkok.rb +20 -0
  573. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Chongqing.rb +33 -0
  574. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Dhaka.rb +27 -0
  575. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Hong_Kong.rb +87 -0
  576. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Irkutsk.rb +165 -0
  577. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Jakarta.rb +30 -0
  578. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Jerusalem.rb +163 -0
  579. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Kabul.rb +20 -0
  580. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Kamchatka.rb +163 -0
  581. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Karachi.rb +30 -0
  582. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Katmandu.rb +20 -0
  583. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Kolkata.rb +25 -0
  584. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Krasnoyarsk.rb +163 -0
  585. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Kuala_Lumpur.rb +31 -0
  586. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Kuwait.rb +18 -0
  587. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Magadan.rb +163 -0
  588. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Muscat.rb +18 -0
  589. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Novosibirsk.rb +164 -0
  590. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Rangoon.rb +24 -0
  591. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Riyadh.rb +18 -0
  592. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Seoul.rb +34 -0
  593. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Shanghai.rb +35 -0
  594. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Singapore.rb +33 -0
  595. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Taipei.rb +59 -0
  596. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Tashkent.rb +47 -0
  597. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Tbilisi.rb +78 -0
  598. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Tehran.rb +121 -0
  599. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Tokyo.rb +30 -0
  600. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Ulaanbaatar.rb +65 -0
  601. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Urumqi.rb +33 -0
  602. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Vladivostok.rb +164 -0
  603. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Yakutsk.rb +163 -0
  604. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Yekaterinburg.rb +165 -0
  605. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Asia/Yerevan.rb +165 -0
  606. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Atlantic/Azores.rb +270 -0
  607. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Atlantic/Cape_Verde.rb +23 -0
  608. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Atlantic/South_Georgia.rb +18 -0
  609. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Australia/Adelaide.rb +187 -0
  610. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Australia/Brisbane.rb +35 -0
  611. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Australia/Darwin.rb +29 -0
  612. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Australia/Hobart.rb +193 -0
  613. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Australia/Melbourne.rb +185 -0
  614. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Australia/Perth.rb +37 -0
  615. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Australia/Sydney.rb +185 -0
  616. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Etc/UTC.rb +16 -0
  617. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Amsterdam.rb +228 -0
  618. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Athens.rb +185 -0
  619. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Belgrade.rb +163 -0
  620. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Berlin.rb +188 -0
  621. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Bratislava.rb +13 -0
  622. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Brussels.rb +232 -0
  623. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Bucharest.rb +181 -0
  624. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Budapest.rb +197 -0
  625. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Copenhagen.rb +179 -0
  626. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Dublin.rb +276 -0
  627. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Helsinki.rb +163 -0
  628. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Istanbul.rb +218 -0
  629. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Kiev.rb +168 -0
  630. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Lisbon.rb +268 -0
  631. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Ljubljana.rb +13 -0
  632. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/London.rb +288 -0
  633. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Madrid.rb +211 -0
  634. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Minsk.rb +170 -0
  635. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Moscow.rb +181 -0
  636. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Paris.rb +232 -0
  637. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Prague.rb +187 -0
  638. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Riga.rb +176 -0
  639. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Rome.rb +215 -0
  640. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Sarajevo.rb +13 -0
  641. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Skopje.rb +13 -0
  642. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Sofia.rb +173 -0
  643. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Stockholm.rb +165 -0
  644. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Tallinn.rb +172 -0
  645. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Vienna.rb +183 -0
  646. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Vilnius.rb +170 -0
  647. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Warsaw.rb +212 -0
  648. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Europe/Zagreb.rb +13 -0
  649. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Auckland.rb +202 -0
  650. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Fiji.rb +23 -0
  651. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Guam.rb +22 -0
  652. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Honolulu.rb +28 -0
  653. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Majuro.rb +20 -0
  654. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Midway.rb +25 -0
  655. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Noumea.rb +25 -0
  656. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Pago_Pago.rb +26 -0
  657. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Port_Moresby.rb +20 -0
  658. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/definitions/Pacific/Tongatapu.rb +27 -0
  659. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/info_timezone.rb +52 -0
  660. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/linked_timezone.rb +51 -0
  661. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/linked_timezone_info.rb +44 -0
  662. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/offset_rationals.rb +95 -0
  663. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/time_or_datetime.rb +292 -0
  664. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/timezone.rb +508 -0
  665. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/timezone_definition.rb +56 -0
  666. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/timezone_info.rb +40 -0
  667. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/timezone_offset_info.rb +94 -0
  668. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/timezone_period.rb +198 -0
  669. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo/timezone_transition_info.rb +138 -0
  670. data/vendor/activesupport/lib/active_support/vendor/tzinfo-0.3.9/tzinfo.rb +33 -0
  671. data/vendor/activesupport/lib/active_support/vendor/xml-simple-1.0.11/xmlsimple.rb +1021 -0
  672. data/vendor/activesupport/lib/active_support/vendor.rb +26 -0
  673. data/vendor/activesupport/lib/active_support/version.rb +9 -0
  674. data/vendor/activesupport/lib/active_support/whiny_nil.rb +58 -0
  675. data/vendor/activesupport/lib/active_support.rb +61 -0
  676. data/vendor/activesupport/lib/activesupport.rb +1 -0
  677. data/vendor/isaac/LICENSE +26 -0
  678. data/vendor/isaac/README +78 -0
  679. data/vendor/isaac/TODO +3 -0
  680. data/vendor/isaac/VERSIONS +3 -0
  681. data/vendor/isaac/crypt/ISAAC.rb +171 -0
  682. data/vendor/isaac/isaac.gemspec +39 -0
  683. data/vendor/isaac/setup.rb +596 -0
  684. data/vendor/isaac/test/TC_ISAAC.rb +76 -0
  685. data/vendor/json/CHANGES +93 -0
  686. data/vendor/json/GPL +340 -0
  687. data/vendor/json/README +78 -0
  688. data/vendor/json/RUBY +58 -0
  689. data/vendor/json/Rakefile +309 -0
  690. data/vendor/json/TODO +1 -0
  691. data/vendor/json/VERSION +1 -0
  692. data/vendor/json/benchmarks/benchmark.txt +133 -0
  693. data/vendor/json/benchmarks/benchmark_generator.rb +48 -0
  694. data/vendor/json/benchmarks/benchmark_parser.rb +26 -0
  695. data/vendor/json/benchmarks/benchmark_rails.rb +26 -0
  696. data/vendor/json/bin/edit_json.rb +10 -0
  697. data/vendor/json/bin/prettify_json.rb +76 -0
  698. data/vendor/json/data/example.json +1 -0
  699. data/vendor/json/data/index.html +38 -0
  700. data/vendor/json/data/prototype.js +4184 -0
  701. data/vendor/json/ext/json/ext/generator/extconf.rb +9 -0
  702. data/vendor/json/ext/json/ext/generator/generator.c +875 -0
  703. data/vendor/json/ext/json/ext/generator/unicode.c +182 -0
  704. data/vendor/json/ext/json/ext/generator/unicode.h +53 -0
  705. data/vendor/json/ext/json/ext/parser/extconf.rb +9 -0
  706. data/vendor/json/ext/json/ext/parser/parser.c +1758 -0
  707. data/vendor/json/ext/json/ext/parser/parser.rl +638 -0
  708. data/vendor/json/ext/json/ext/parser/unicode.c +154 -0
  709. data/vendor/json/ext/json/ext/parser/unicode.h +58 -0
  710. data/vendor/json/install.rb +26 -0
  711. data/vendor/json/lib/json/Array.xpm +21 -0
  712. data/vendor/json/lib/json/FalseClass.xpm +21 -0
  713. data/vendor/json/lib/json/Hash.xpm +21 -0
  714. data/vendor/json/lib/json/Key.xpm +73 -0
  715. data/vendor/json/lib/json/NilClass.xpm +21 -0
  716. data/vendor/json/lib/json/Numeric.xpm +28 -0
  717. data/vendor/json/lib/json/String.xpm +96 -0
  718. data/vendor/json/lib/json/TrueClass.xpm +21 -0
  719. data/vendor/json/lib/json/add/core.rb +135 -0
  720. data/vendor/json/lib/json/add/rails.rb +58 -0
  721. data/vendor/json/lib/json/common.rb +354 -0
  722. data/vendor/json/lib/json/editor.rb +1362 -0
  723. data/vendor/json/lib/json/ext.rb +13 -0
  724. data/vendor/json/lib/json/json.xpm +1499 -0
  725. data/vendor/json/lib/json/pure/generator.rb +394 -0
  726. data/vendor/json/lib/json/pure/parser.rb +259 -0
  727. data/vendor/json/lib/json/pure.rb +75 -0
  728. data/vendor/json/lib/json/version.rb +9 -0
  729. data/vendor/json/lib/json.rb +235 -0
  730. data/vendor/json/tests/fixtures/fail1.json +1 -0
  731. data/vendor/json/tests/fixtures/fail10.json +1 -0
  732. data/vendor/json/tests/fixtures/fail11.json +1 -0
  733. data/vendor/json/tests/fixtures/fail12.json +1 -0
  734. data/vendor/json/tests/fixtures/fail13.json +1 -0
  735. data/vendor/json/tests/fixtures/fail14.json +1 -0
  736. data/vendor/json/tests/fixtures/fail18.json +1 -0
  737. data/vendor/json/tests/fixtures/fail19.json +1 -0
  738. data/vendor/json/tests/fixtures/fail2.json +1 -0
  739. data/vendor/json/tests/fixtures/fail20.json +1 -0
  740. data/vendor/json/tests/fixtures/fail21.json +1 -0
  741. data/vendor/json/tests/fixtures/fail22.json +1 -0
  742. data/vendor/json/tests/fixtures/fail23.json +1 -0
  743. data/vendor/json/tests/fixtures/fail24.json +1 -0
  744. data/vendor/json/tests/fixtures/fail25.json +1 -0
  745. data/vendor/json/tests/fixtures/fail27.json +2 -0
  746. data/vendor/json/tests/fixtures/fail28.json +2 -0
  747. data/vendor/json/tests/fixtures/fail3.json +1 -0
  748. data/vendor/json/tests/fixtures/fail4.json +1 -0
  749. data/vendor/json/tests/fixtures/fail5.json +1 -0
  750. data/vendor/json/tests/fixtures/fail6.json +1 -0
  751. data/vendor/json/tests/fixtures/fail7.json +1 -0
  752. data/vendor/json/tests/fixtures/fail8.json +1 -0
  753. data/vendor/json/tests/fixtures/fail9.json +1 -0
  754. data/vendor/json/tests/fixtures/pass1.json +56 -0
  755. data/vendor/json/tests/fixtures/pass15.json +1 -0
  756. data/vendor/json/tests/fixtures/pass16.json +1 -0
  757. data/vendor/json/tests/fixtures/pass17.json +1 -0
  758. data/vendor/json/tests/fixtures/pass2.json +1 -0
  759. data/vendor/json/tests/fixtures/pass26.json +1 -0
  760. data/vendor/json/tests/fixtures/pass3.json +6 -0
  761. data/vendor/json/tests/runner.rb +25 -0
  762. data/vendor/json/tests/test_json.rb +293 -0
  763. data/vendor/json/tests/test_json_addition.rb +161 -0
  764. data/vendor/json/tests/test_json_fixtures.rb +30 -0
  765. data/vendor/json/tests/test_json_generate.rb +100 -0
  766. data/vendor/json/tests/test_json_rails.rb +118 -0
  767. data/vendor/json/tests/test_json_unicode.rb +61 -0
  768. data/vendor/json/tools/fuzz.rb +140 -0
  769. data/vendor/json/tools/server.rb +62 -0
  770. data/vendor/rack/AUTHORS +8 -0
  771. data/vendor/rack/COPYING +18 -0
  772. data/vendor/rack/KNOWN-ISSUES +18 -0
  773. data/vendor/rack/RDOX +265 -0
  774. data/vendor/rack/README +287 -0
  775. data/vendor/rack/Rakefile +179 -0
  776. data/vendor/rack/SPEC +126 -0
  777. data/vendor/rack/bin/rackup +172 -0
  778. data/vendor/rack/contrib/rack_logo.svg +111 -0
  779. data/vendor/rack/example/lobster.ru +4 -0
  780. data/vendor/rack/example/protectedlobster.rb +14 -0
  781. data/vendor/rack/example/protectedlobster.ru +8 -0
  782. data/vendor/rack/lib/rack/adapter/camping.rb +22 -0
  783. data/vendor/rack/lib/rack/auth/abstract/handler.rb +28 -0
  784. data/vendor/rack/lib/rack/auth/abstract/request.rb +37 -0
  785. data/vendor/rack/lib/rack/auth/basic.rb +58 -0
  786. data/vendor/rack/lib/rack/auth/digest/md5.rb +124 -0
  787. data/vendor/rack/lib/rack/auth/digest/nonce.rb +51 -0
  788. data/vendor/rack/lib/rack/auth/digest/params.rb +55 -0
  789. data/vendor/rack/lib/rack/auth/digest/request.rb +40 -0
  790. data/vendor/rack/lib/rack/auth/openid.rb +437 -0
  791. data/vendor/rack/lib/rack/builder.rb +56 -0
  792. data/vendor/rack/lib/rack/cascade.rb +36 -0
  793. data/vendor/rack/lib/rack/commonlogger.rb +61 -0
  794. data/vendor/rack/lib/rack/deflater.rb +63 -0
  795. data/vendor/rack/lib/rack/directory.rb +158 -0
  796. data/vendor/rack/lib/rack/file.rb +116 -0
  797. data/vendor/rack/lib/rack/handler/cgi.rb +57 -0
  798. data/vendor/rack/lib/rack/handler/evented_mongrel.rb +8 -0
  799. data/vendor/rack/lib/rack/handler/fastcgi.rb +84 -0
  800. data/vendor/rack/lib/rack/handler/lsws.rb +52 -0
  801. data/vendor/rack/lib/rack/handler/mongrel.rb +78 -0
  802. data/vendor/rack/lib/rack/handler/scgi.rb +57 -0
  803. data/vendor/rack/lib/rack/handler/webrick.rb +57 -0
  804. data/vendor/rack/lib/rack/handler.rb +44 -0
  805. data/vendor/rack/lib/rack/lint.rb +401 -0
  806. data/vendor/rack/lib/rack/lobster.rb +65 -0
  807. data/vendor/rack/lib/rack/mock.rb +160 -0
  808. data/vendor/rack/lib/rack/recursive.rb +57 -0
  809. data/vendor/rack/lib/rack/reloader.rb +64 -0
  810. data/vendor/rack/lib/rack/request.rb +209 -0
  811. data/vendor/rack/lib/rack/response.rb +166 -0
  812. data/vendor/rack/lib/rack/session/abstract/id.rb +140 -0
  813. data/vendor/rack/lib/rack/session/cookie.rb +71 -0
  814. data/vendor/rack/lib/rack/session/memcache.rb +97 -0
  815. data/vendor/rack/lib/rack/session/pool.rb +73 -0
  816. data/vendor/rack/lib/rack/showexceptions.rb +344 -0
  817. data/vendor/rack/lib/rack/showstatus.rb +105 -0
  818. data/vendor/rack/lib/rack/static.rb +38 -0
  819. data/vendor/rack/lib/rack/urlmap.rb +48 -0
  820. data/vendor/rack/lib/rack/utils.rb +318 -0
  821. data/vendor/rack/lib/rack.rb +81 -0
  822. data/vendor/rack/test/cgi/lighttpd.conf +20 -0
  823. data/vendor/rack/test/cgi/test +9 -0
  824. data/vendor/rack/test/cgi/test.fcgi +8 -0
  825. data/vendor/rack/test/cgi/test.ru +7 -0
  826. data/vendor/rack/test/spec_rack_auth_basic.rb +69 -0
  827. data/vendor/rack/test/spec_rack_auth_digest.rb +169 -0
  828. data/vendor/rack/test/spec_rack_auth_openid.rb +137 -0
  829. data/vendor/rack/test/spec_rack_builder.rb +50 -0
  830. data/vendor/rack/test/spec_rack_camping.rb +51 -0
  831. data/vendor/rack/test/spec_rack_cascade.rb +50 -0
  832. data/vendor/rack/test/spec_rack_cgi.rb +89 -0
  833. data/vendor/rack/test/spec_rack_commonlogger.rb +32 -0
  834. data/vendor/rack/test/spec_rack_deflater.rb +70 -0
  835. data/vendor/rack/test/spec_rack_directory.rb +56 -0
  836. data/vendor/rack/test/spec_rack_fastcgi.rb +89 -0
  837. data/vendor/rack/test/spec_rack_file.rb +50 -0
  838. data/vendor/rack/test/spec_rack_handler.rb +24 -0
  839. data/vendor/rack/test/spec_rack_lint.rb +303 -0
  840. data/vendor/rack/test/spec_rack_lobster.rb +45 -0
  841. data/vendor/rack/test/spec_rack_mock.rb +152 -0
  842. data/vendor/rack/test/spec_rack_mongrel.rb +170 -0
  843. data/vendor/rack/test/spec_rack_recursive.rb +77 -0
  844. data/vendor/rack/test/spec_rack_request.rb +401 -0
  845. data/vendor/rack/test/spec_rack_response.rb +167 -0
  846. data/vendor/rack/test/spec_rack_session_cookie.rb +49 -0
  847. data/vendor/rack/test/spec_rack_session_memcache.rb +132 -0
  848. data/vendor/rack/test/spec_rack_session_pool.rb +84 -0
  849. data/vendor/rack/test/spec_rack_showexceptions.rb +21 -0
  850. data/vendor/rack/test/spec_rack_showstatus.rb +72 -0
  851. data/vendor/rack/test/spec_rack_static.rb +37 -0
  852. data/vendor/rack/test/spec_rack_urlmap.rb +175 -0
  853. data/vendor/rack/test/spec_rack_utils.rb +174 -0
  854. data/vendor/rack/test/spec_rack_webrick.rb +106 -0
  855. data/vendor/rack/test/testrequest.rb +45 -0
  856. data/vendor/sinatra/CHANGELOG +64 -0
  857. data/vendor/sinatra/LICENSE +22 -0
  858. data/vendor/sinatra/README.rdoc +533 -0
  859. data/vendor/sinatra/Rakefile +111 -0
  860. data/vendor/sinatra/images/404.png +0 -0
  861. data/vendor/sinatra/images/500.png +0 -0
  862. data/vendor/sinatra/lib/sinatra/rack/handler/mongrel.rb +85 -0
  863. data/vendor/sinatra/lib/sinatra/test/methods.rb +76 -0
  864. data/vendor/sinatra/lib/sinatra/test/rspec.rb +10 -0
  865. data/vendor/sinatra/lib/sinatra/test/spec.rb +10 -0
  866. data/vendor/sinatra/lib/sinatra/test/unit.rb +13 -0
  867. data/vendor/sinatra/lib/sinatra.rb +1477 -0
  868. data/vendor/sinatra/sinatra.gemspec +78 -0
  869. data/vendor/sinatra/test/app_test.rb +299 -0
  870. data/vendor/sinatra/test/application_test.rb +318 -0
  871. data/vendor/sinatra/test/builder_test.rb +101 -0
  872. data/vendor/sinatra/test/custom_error_test.rb +62 -0
  873. data/vendor/sinatra/test/erb_test.rb +136 -0
  874. data/vendor/sinatra/test/event_context_test.rb +15 -0
  875. data/vendor/sinatra/test/events_test.rb +47 -0
  876. data/vendor/sinatra/test/filter_test.rb +30 -0
  877. data/vendor/sinatra/test/haml_test.rb +233 -0
  878. data/vendor/sinatra/test/helper.rb +7 -0
  879. data/vendor/sinatra/test/mapped_error_test.rb +72 -0
  880. data/vendor/sinatra/test/pipeline_test.rb +66 -0
  881. data/vendor/sinatra/test/public/foo.xml +1 -0
  882. data/vendor/sinatra/test/sass_test.rb +57 -0
  883. data/vendor/sinatra/test/sessions_test.rb +39 -0
  884. data/vendor/sinatra/test/streaming_test.rb +118 -0
  885. data/vendor/sinatra/test/sym_params_test.rb +19 -0
  886. data/vendor/sinatra/test/template_test.rb +30 -0
  887. data/vendor/sinatra/test/use_in_file_templates_test.rb +47 -0
  888. data/vendor/sinatra/test/views/foo.builder +1 -0
  889. data/vendor/sinatra/test/views/foo.erb +1 -0
  890. data/vendor/sinatra/test/views/foo.haml +1 -0
  891. data/vendor/sinatra/test/views/foo.sass +2 -0
  892. data/vendor/sinatra/test/views/foo_layout.erb +2 -0
  893. data/vendor/sinatra/test/views/foo_layout.haml +2 -0
  894. data/vendor/sinatra/test/views/layout_test/foo.builder +1 -0
  895. data/vendor/sinatra/test/views/layout_test/foo.erb +1 -0
  896. data/vendor/sinatra/test/views/layout_test/foo.haml +1 -0
  897. data/vendor/sinatra/test/views/layout_test/foo.sass +2 -0
  898. data/vendor/sinatra/test/views/layout_test/layout.builder +3 -0
  899. data/vendor/sinatra/test/views/layout_test/layout.erb +1 -0
  900. data/vendor/sinatra/test/views/layout_test/layout.haml +1 -0
  901. data/vendor/sinatra/test/views/layout_test/layout.sass +2 -0
  902. data/vendor/sinatra/test/views/no_layout/no_layout.builder +1 -0
  903. data/vendor/sinatra/test/views/no_layout/no_layout.haml +1 -0
  904. metadata +1121 -0
@@ -0,0 +1,2744 @@
1
+ require 'yaml'
2
+ require 'set'
3
+
4
+ module ActiveRecord #:nodoc:
5
+ # Generic Active Record exception class.
6
+ class ActiveRecordError < StandardError
7
+ end
8
+
9
+ # Raised when the single-table inheritance mechanism failes to locate the subclass
10
+ # (for example due to improper usage of column that +inheritance_column+ points to).
11
+ class SubclassNotFound < ActiveRecordError #:nodoc:
12
+ end
13
+
14
+ # Raised when an object assigned to an association has an incorrect type.
15
+ #
16
+ # class Ticket < ActiveRecord::Base
17
+ # has_many :patches
18
+ # end
19
+ #
20
+ # class Patch < ActiveRecord::Base
21
+ # belongs_to :ticket
22
+ # end
23
+ #
24
+ # # Comments are not patches, this assignment raises AssociationTypeMismatch.
25
+ # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
26
+ class AssociationTypeMismatch < ActiveRecordError
27
+ end
28
+
29
+ # Raised when unserialized object's type mismatches one specified for serializable field.
30
+ class SerializationTypeMismatch < ActiveRecordError
31
+ end
32
+
33
+ # Raised when adapter not specified on connection (or configuration file <tt>config/database.yml</tt> misses adapter field).
34
+ class AdapterNotSpecified < ActiveRecordError
35
+ end
36
+
37
+ # Raised when Active Record cannot find database adapter specified in <tt>config/database.yml</tt> or programmatically.
38
+ class AdapterNotFound < ActiveRecordError
39
+ end
40
+
41
+ # Raised when connection to the database could not been established (for example when <tt>connection=</tt> is given a nil object).
42
+ class ConnectionNotEstablished < ActiveRecordError
43
+ end
44
+
45
+ # Raised when Active Record cannot find record by given id or set of ids.
46
+ class RecordNotFound < ActiveRecordError
47
+ end
48
+
49
+ # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be
50
+ # saved because record is invalid.
51
+ class RecordNotSaved < ActiveRecordError
52
+ end
53
+
54
+ # Raised when SQL statement cannot be executed by the database (for example, it's often the case for MySQL when Ruby driver used is too old).
55
+ class StatementInvalid < ActiveRecordError
56
+ end
57
+
58
+ # Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
59
+ # does not match number of expected variables.
60
+ #
61
+ # For example, in
62
+ #
63
+ # Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
64
+ #
65
+ # two placeholders are given but only one variable to fill them.
66
+ class PreparedStatementInvalid < ActiveRecordError
67
+ end
68
+
69
+ # Raised on attempt to save stale record. Record is stale when it's being saved in another query after
70
+ # instantiation, for example, when two users edit the same wiki page and one starts editing and saves
71
+ # the page before the other.
72
+ #
73
+ # Read more about optimistic locking in ActiveRecord::Locking module RDoc.
74
+ class StaleObjectError < ActiveRecordError
75
+ end
76
+
77
+ # Raised when association is being configured improperly or
78
+ # user tries to use offset and limit together with has_many or has_and_belongs_to_many associations.
79
+ class ConfigurationError < ActiveRecordError
80
+ end
81
+
82
+ # Raised on attempt to update record that is instantiated as read only.
83
+ class ReadOnlyRecord < ActiveRecordError
84
+ end
85
+
86
+ # Used by Active Record transaction mechanism to distinguish rollback from other exceptional situations.
87
+ # You can use it to roll your transaction back explicitly in the block passed to +transaction+ method.
88
+ class Rollback < ActiveRecordError
89
+ end
90
+
91
+ # Raised when attribute has a name reserved by Active Record (when attribute has name of one of Active Record instance methods).
92
+ class DangerousAttributeError < ActiveRecordError
93
+ end
94
+
95
+ # Raised when you've tried to access a column which wasn't loaded by your finder.
96
+ # Typically this is because <tt>:select</tt> has been specified.
97
+ class MissingAttributeError < NoMethodError
98
+ end
99
+
100
+ # Raised when an error occured while doing a mass assignment to an attribute through the
101
+ # <tt>attributes=</tt> method. The exception has an +attribute+ property that is the name of the
102
+ # offending attribute.
103
+ class AttributeAssignmentError < ActiveRecordError
104
+ attr_reader :exception, :attribute
105
+ def initialize(message, exception, attribute)
106
+ @exception = exception
107
+ @attribute = attribute
108
+ @message = message
109
+ end
110
+ end
111
+
112
+ # Raised when there are multiple errors while doing a mass assignment through the +attributes+
113
+ # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError
114
+ # objects, each corresponding to the error while assigning to an attribute.
115
+ class MultiparameterAssignmentErrors < ActiveRecordError
116
+ attr_reader :errors
117
+ def initialize(errors)
118
+ @errors = errors
119
+ end
120
+ end
121
+
122
+ # Active Record objects don't specify their attributes directly, but rather infer them from the table definition with
123
+ # which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change
124
+ # is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain
125
+ # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.
126
+ #
127
+ # See the mapping rules in table_name and the full example in link:files/README.html for more insight.
128
+ #
129
+ # == Creation
130
+ #
131
+ # Active Records accept constructor parameters either in a hash or as a block. The hash method is especially useful when
132
+ # you're receiving the data from somewhere else, like an HTTP request. It works like this:
133
+ #
134
+ # user = User.new(:name => "David", :occupation => "Code Artist")
135
+ # user.name # => "David"
136
+ #
137
+ # You can also use block initialization:
138
+ #
139
+ # user = User.new do |u|
140
+ # u.name = "David"
141
+ # u.occupation = "Code Artist"
142
+ # end
143
+ #
144
+ # And of course you can just create a bare object and specify the attributes after the fact:
145
+ #
146
+ # user = User.new
147
+ # user.name = "David"
148
+ # user.occupation = "Code Artist"
149
+ #
150
+ # == Conditions
151
+ #
152
+ # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement.
153
+ # The array form is to be used when the condition input is tainted and requires sanitization. The string form can
154
+ # be used for statements that don't involve tainted data. The hash form works much like the array form, except
155
+ # only equality and range is possible. Examples:
156
+ #
157
+ # class User < ActiveRecord::Base
158
+ # def self.authenticate_unsafely(user_name, password)
159
+ # find(:first, :conditions => "user_name = '#{user_name}' AND password = '#{password}'")
160
+ # end
161
+ #
162
+ # def self.authenticate_safely(user_name, password)
163
+ # find(:first, :conditions => [ "user_name = ? AND password = ?", user_name, password ])
164
+ # end
165
+ #
166
+ # def self.authenticate_safely_simply(user_name, password)
167
+ # find(:first, :conditions => { :user_name => user_name, :password => password })
168
+ # end
169
+ # end
170
+ #
171
+ # The <tt>authenticate_unsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection
172
+ # attacks if the <tt>user_name</tt> and +password+ parameters come directly from an HTTP request. The <tt>authenticate_safely</tt> and
173
+ # <tt>authenticate_safely_simply</tt> both will sanitize the <tt>user_name</tt> and +password+ before inserting them in the query,
174
+ # which will ensure that an attacker can't escape the query and fake the login (or worse).
175
+ #
176
+ # When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth
177
+ # question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing
178
+ # the question marks with symbols and supplying a hash with values for the matching symbol keys:
179
+ #
180
+ # Company.find(:first, :conditions => [
181
+ # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
182
+ # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
183
+ # ])
184
+ #
185
+ # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
186
+ # operator. For instance:
187
+ #
188
+ # Student.find(:all, :conditions => { :first_name => "Harvey", :status => 1 })
189
+ # Student.find(:all, :conditions => params[:student])
190
+ #
191
+ # A range may be used in the hash to use the SQL BETWEEN operator:
192
+ #
193
+ # Student.find(:all, :conditions => { :grade => 9..12 })
194
+ #
195
+ # An array may be used in the hash to use the SQL IN operator:
196
+ #
197
+ # Student.find(:all, :conditions => { :grade => [9,11,12] })
198
+ #
199
+ # == Overwriting default accessors
200
+ #
201
+ # All column values are automatically available through basic accessors on the Active Record object, but sometimes you
202
+ # want to specialize this behavior. This can be done by overwriting the default accessors (using the same
203
+ # name as the attribute) and calling <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually change things.
204
+ # Example:
205
+ #
206
+ # class Song < ActiveRecord::Base
207
+ # # Uses an integer of seconds to hold the length of the song
208
+ #
209
+ # def length=(minutes)
210
+ # write_attribute(:length, minutes.to_i * 60)
211
+ # end
212
+ #
213
+ # def length
214
+ # read_attribute(:length) / 60
215
+ # end
216
+ # end
217
+ #
218
+ # You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt> instead of <tt>write_attribute(:attribute, value)</tt> and
219
+ # <tt>read_attribute(:attribute)</tt> as a shorter form.
220
+ #
221
+ # == Attribute query methods
222
+ #
223
+ # In addition to the basic accessors, query methods are also automatically available on the Active Record object.
224
+ # Query methods allow you to test whether an attribute value is present.
225
+ #
226
+ # For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
227
+ # to determine whether the user has a name:
228
+ #
229
+ # user = User.new(:name => "David")
230
+ # user.name? # => true
231
+ #
232
+ # anonymous = User.new(:name => "")
233
+ # anonymous.name? # => false
234
+ #
235
+ # == Accessing attributes before they have been typecasted
236
+ #
237
+ # Sometimes you want to be able to read the raw attribute data without having the column-determined typecast run its course first.
238
+ # That can be done by using the <tt><attribute>_before_type_cast</tt> accessors that all attributes have. For example, if your Account model
239
+ # has a <tt>balance</tt> attribute, you can call <tt>account.balance_before_type_cast</tt> or <tt>account.id_before_type_cast</tt>.
240
+ #
241
+ # This is especially useful in validation situations where the user might supply a string for an integer field and you want to display
242
+ # the original string back in an error message. Accessing the attribute normally would typecast the string to 0, which isn't what you
243
+ # want.
244
+ #
245
+ # == Dynamic attribute-based finders
246
+ #
247
+ # Dynamic attribute-based finders are a cleaner way of getting (and/or creating) objects by simple queries without turning to SQL. They work by
248
+ # appending the name of an attribute to <tt>find_by_</tt> or <tt>find_all_by_</tt>, so you get finders like <tt>Person.find_by_user_name</tt>,
249
+ # <tt>Person.find_all_by_last_name</tt>, and <tt>Payment.find_by_transaction_id</tt>. So instead of writing
250
+ # <tt>Person.find(:first, :conditions => ["user_name = ?", user_name])</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
251
+ # And instead of writing <tt>Person.find(:all, :conditions => ["last_name = ?", last_name])</tt>, you just do <tt>Person.find_all_by_last_name(last_name)</tt>.
252
+ #
253
+ # It's also possible to use multiple attributes in the same find by separating them with "_and_", so you get finders like
254
+ # <tt>Person.find_by_user_name_and_password</tt> or even <tt>Payment.find_by_purchaser_and_state_and_country</tt>. So instead of writing
255
+ # <tt>Person.find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])</tt>, you just do
256
+ # <tt>Person.find_by_user_name_and_password(user_name, password)</tt>.
257
+ #
258
+ # It's even possible to use all the additional parameters to find. For example, the full interface for <tt>Payment.find_all_by_amount</tt>
259
+ # is actually <tt>Payment.find_all_by_amount(amount, options)</tt>. And the full interface to <tt>Person.find_by_user_name</tt> is
260
+ # actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
261
+ #
262
+ # The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
263
+ # <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
264
+ #
265
+ # # No 'Summer' tag exists
266
+ # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
267
+ #
268
+ # # Now the 'Summer' tag does exist
269
+ # Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
270
+ #
271
+ # # Now 'Bob' exist and is an 'admin'
272
+ # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
273
+ #
274
+ # Use the <tt>find_or_initialize_by_</tt> finder if you want to return a new record without saving it first. Protected attributes won't be setted unless they are given in a block. For example:
275
+ #
276
+ # # No 'Winter' tag exists
277
+ # winter = Tag.find_or_initialize_by_name("Winter")
278
+ # winter.new_record? # true
279
+ #
280
+ # To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
281
+ # a list of parameters. For example:
282
+ #
283
+ # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
284
+ #
285
+ # That will either find an existing tag named "rails", or create a new one while setting the user that created it.
286
+ #
287
+ # == Saving arrays, hashes, and other non-mappable objects in text columns
288
+ #
289
+ # Active Record can serialize any object in text columns using YAML. To do so, you must specify this with a call to the class method +serialize+.
290
+ # This makes it possible to store arrays, hashes, and other non-mappable objects without doing any additional work. Example:
291
+ #
292
+ # class User < ActiveRecord::Base
293
+ # serialize :preferences
294
+ # end
295
+ #
296
+ # user = User.create(:preferences => { "background" => "black", "display" => large })
297
+ # User.find(user.id).preferences # => { "background" => "black", "display" => large }
298
+ #
299
+ # You can also specify a class option as the second parameter that'll raise an exception if a serialized object is retrieved as a
300
+ # descendent of a class not in the hierarchy. Example:
301
+ #
302
+ # class User < ActiveRecord::Base
303
+ # serialize :preferences, Hash
304
+ # end
305
+ #
306
+ # user = User.create(:preferences => %w( one two three ))
307
+ # User.find(user.id).preferences # raises SerializationTypeMismatch
308
+ #
309
+ # == Single table inheritance
310
+ #
311
+ # Active Record allows inheritance by storing the name of the class in a column that by default is named "type" (can be changed
312
+ # by overwriting <tt>Base.inheritance_column</tt>). This means that an inheritance looking like this:
313
+ #
314
+ # class Company < ActiveRecord::Base; end
315
+ # class Firm < Company; end
316
+ # class Client < Company; end
317
+ # class PriorityClient < Client; end
318
+ #
319
+ # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in the companies table with type = "Firm". You can then
320
+ # fetch this row again using <tt>Company.find(:first, "name = '37signals'")</tt> and it will return a Firm object.
321
+ #
322
+ # If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just
323
+ # like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
324
+ #
325
+ # Note, all the attributes for all the cases are kept in the same table. Read more:
326
+ # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html
327
+ #
328
+ # == Connection to multiple databases in different models
329
+ #
330
+ # Connections are usually created through ActiveRecord::Base.establish_connection and retrieved by ActiveRecord::Base.connection.
331
+ # All classes inheriting from ActiveRecord::Base will use this connection. But you can also set a class-specific connection.
332
+ # For example, if Course is an ActiveRecord::Base, but resides in a different database, you can just say <tt>Course.establish_connection</tt>
333
+ # and Course and all of its subclasses will use this connection instead.
334
+ #
335
+ # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is a Hash indexed by the class. If a connection is
336
+ # requested, the retrieve_connection method will go up the class-hierarchy until a connection is found in the connection pool.
337
+ #
338
+ # == Exceptions
339
+ #
340
+ # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record.
341
+ # * AdapterNotSpecified - The configuration hash used in <tt>establish_connection</tt> didn't include an
342
+ # <tt>:adapter</tt> key.
343
+ # * AdapterNotFound - The <tt>:adapter</tt> key used in <tt>establish_connection</tt> specified a non-existent adapter
344
+ # (or a bad spelling of an existing one).
345
+ # * AssociationTypeMismatch - The object assigned to the association wasn't of the type specified in the association definition.
346
+ # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter.
347
+ # * ConnectionNotEstablished+ - No connection has been established. Use <tt>establish_connection</tt> before querying.
348
+ # * RecordNotFound - No record responded to the +find+ method. Either the row with the given ID doesn't exist
349
+ # or the row didn't meet the additional restrictions. Some +find+ calls do not raise this exception to signal
350
+ # nothing was found, please check its documentation for further details.
351
+ # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message.
352
+ # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the
353
+ # <tt>attributes=</tt> method. The +errors+ property of this exception contains an array of AttributeAssignmentError
354
+ # objects that should be inspected to determine which attributes triggered the errors.
355
+ # * AttributeAssignmentError - An error occurred while doing a mass assignment through the <tt>attributes=</tt> method.
356
+ # You can inspect the +attribute+ property of the exception object to determine which attribute triggered the error.
357
+ #
358
+ # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level).
359
+ # So it's possible to assign a logger to the class through <tt>Base.logger=</tt> which will then be used by all
360
+ # instances in the current object space.
361
+ class Base
362
+ # Accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed
363
+ # on to any new database connections made and which can be retrieved on both a class and instance level by calling +logger+.
364
+ cattr_accessor :logger, :instance_writer => false
365
+
366
+ def self.inherited(child) #:nodoc:
367
+ @@subclasses[self] ||= []
368
+ @@subclasses[self] << child
369
+ super
370
+ end
371
+
372
+ def self.reset_subclasses #:nodoc:
373
+ nonreloadables = []
374
+ subclasses.each do |klass|
375
+ unless ActiveSupport::Dependencies.autoloaded? klass
376
+ nonreloadables << klass
377
+ next
378
+ end
379
+ klass.instance_variables.each { |var| klass.send(:remove_instance_variable, var) }
380
+ klass.instance_methods(false).each { |m| klass.send :undef_method, m }
381
+ end
382
+ @@subclasses = {}
383
+ nonreloadables.each { |klass| (@@subclasses[klass.superclass] ||= []) << klass }
384
+ end
385
+
386
+ @@subclasses = {}
387
+
388
+ cattr_accessor :configurations, :instance_writer => false
389
+ @@configurations = {}
390
+
391
+ # Accessor for the prefix type that will be prepended to every primary key column name. The options are :table_name and
392
+ # :table_name_with_underscore. If the first is specified, the Product class will look for "productid" instead of "id" as
393
+ # the primary column. If the latter is specified, the Product class will look for "product_id" instead of "id". Remember
394
+ # that this is a global setting for all Active Records.
395
+ cattr_accessor :primary_key_prefix_type, :instance_writer => false
396
+ @@primary_key_prefix_type = nil
397
+
398
+ # Accessor for the name of the prefix string to prepend to every table name. So if set to "basecamp_", all
399
+ # table names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient way of creating a namespace
400
+ # for tables in a shared database. By default, the prefix is the empty string.
401
+ cattr_accessor :table_name_prefix, :instance_writer => false
402
+ @@table_name_prefix = ""
403
+
404
+ # Works like +table_name_prefix+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp",
405
+ # "people_basecamp"). By default, the suffix is the empty string.
406
+ cattr_accessor :table_name_suffix, :instance_writer => false
407
+ @@table_name_suffix = ""
408
+
409
+ # Indicates whether table names should be the pluralized versions of the corresponding class names.
410
+ # If true, the default table name for a Product class will be +products+. If false, it would just be +product+.
411
+ # See table_name for the full rules on table/class naming. This is true, by default.
412
+ cattr_accessor :pluralize_table_names, :instance_writer => false
413
+ @@pluralize_table_names = true
414
+
415
+ # Determines whether to use ANSI codes to colorize the logging statements committed by the connection adapter. These colors
416
+ # make it much easier to overview things during debugging (when used through a reader like +tail+ and on a black background), but
417
+ # may complicate matters if you use software like syslog. This is true, by default.
418
+ cattr_accessor :colorize_logging, :instance_writer => false
419
+ @@colorize_logging = true
420
+
421
+ # Determines whether to use Time.local (using :local) or Time.utc (using :utc) when pulling dates and times from the database.
422
+ # This is set to :local by default.
423
+ cattr_accessor :default_timezone, :instance_writer => false
424
+ @@default_timezone = :local
425
+
426
+ # Determines whether to use a connection for each thread, or a single shared connection for all threads.
427
+ # Defaults to false. If you're writing a threaded application, set to true
428
+ # and periodically call verify_active_connections! to clear out connections
429
+ # assigned to stale threads.
430
+ cattr_accessor :allow_concurrency, :instance_writer => false
431
+ @@allow_concurrency = false
432
+
433
+ # Specifies the format to use when dumping the database schema with Rails'
434
+ # Rakefile. If :sql, the schema is dumped as (potentially database-
435
+ # specific) SQL statements. If :ruby, the schema is dumped as an
436
+ # ActiveRecord::Schema file which can be loaded into any database that
437
+ # supports migrations. Use :ruby if you want to have different database
438
+ # adapters for, e.g., your development and test environments.
439
+ cattr_accessor :schema_format , :instance_writer => false
440
+ @@schema_format = :ruby
441
+
442
+ # Specify whether or not to use timestamps for migration numbers
443
+ cattr_accessor :timestamped_migrations , :instance_writer => false
444
+ @@timestamped_migrations = true
445
+
446
+ # Determine whether to store the full constant name including namespace when using STI
447
+ superclass_delegating_accessor :store_full_sti_class
448
+ self.store_full_sti_class = false
449
+
450
+ class << self # Class methods
451
+ # Find operates with four different retrieval approaches:
452
+ #
453
+ # * Find by id - This can either be a specific id (1), a list of ids (1, 5, 6), or an array of ids ([5, 6, 10]).
454
+ # If no record can be found for all of the listed ids, then RecordNotFound will be raised.
455
+ # * Find first - This will return the first record matched by the options used. These options can either be specific
456
+ # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
457
+ # <tt>Model.find(:first, *args)</tt> or its shortcut <tt>Model.first(*args)</tt>.
458
+ # * Find last - This will return the last record matched by the options used. These options can either be specific
459
+ # conditions or merely an order. If no record can be matched, +nil+ is returned. Use
460
+ # <tt>Model.find(:last, *args)</tt> or its shortcut <tt>Model.last(*args)</tt>.
461
+ # * Find all - This will return all the records matched by the options used.
462
+ # If no records are found, an empty array is returned. Use
463
+ # <tt>Model.find(:all, *args)</tt> or its shortcut <tt>Model.all(*args)</tt>.
464
+ #
465
+ # All approaches accept an options hash as their last parameter.
466
+ #
467
+ # ==== Attributes
468
+ #
469
+ # * <tt>:conditions</tt> - An SQL fragment like "administrator = 1" or <tt>[ "user_name = ?", username ]</tt>. See conditions in the intro.
470
+ # * <tt>:order</tt> - An SQL fragment like "created_at DESC, name".
471
+ # * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
472
+ # * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
473
+ # * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip rows 0 through 4.
474
+ # * <tt>:joins</tt> - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
475
+ # or named associations in the same form used for the <tt>:include</tt> option, which will perform an <tt>INNER JOIN</tt> on the associated table(s).
476
+ # If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
477
+ # Pass <tt>:readonly => false</tt> to override.
478
+ # * <tt>:include</tt> - Names associations that should be loaded alongside. The symbols named refer
479
+ # to already defined associations. See eager loading under Associations.
480
+ # * <tt>:select</tt> - By default, this is "*" as in "SELECT * FROM", but can be changed if you, for example, want to do a join but not
481
+ # include the joined columns.
482
+ # * <tt>:from</tt> - By default, this is the table name of the class, but can be changed to an alternate table name (or even the name
483
+ # of a database view).
484
+ # * <tt>:readonly</tt> - Mark the returned records read-only so they cannot be saved or updated.
485
+ # * <tt>:lock</tt> - An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
486
+ # <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
487
+ #
488
+ # ==== Examples
489
+ #
490
+ # # find by id
491
+ # Person.find(1) # returns the object for ID = 1
492
+ # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6)
493
+ # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17)
494
+ # Person.find([1]) # returns an array for the object with ID = 1
495
+ # Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
496
+ #
497
+ # Note that returned records may not be in the same order as the ids you
498
+ # provide since database rows are unordered. Give an explicit <tt>:order</tt>
499
+ # to ensure the results are sorted.
500
+ #
501
+ # ==== Examples
502
+ #
503
+ # # find first
504
+ # Person.find(:first) # returns the first object fetched by SELECT * FROM people
505
+ # Person.find(:first, :conditions => [ "user_name = ?", user_name])
506
+ # Person.find(:first, :order => "created_on DESC", :offset => 5)
507
+ #
508
+ # # find last
509
+ # Person.find(:last) # returns the last object fetched by SELECT * FROM people
510
+ # Person.find(:last, :conditions => [ "user_name = ?", user_name])
511
+ # Person.find(:last, :order => "created_on DESC", :offset => 5)
512
+ #
513
+ # # find all
514
+ # Person.find(:all) # returns an array of objects for all the rows fetched by SELECT * FROM people
515
+ # Person.find(:all, :conditions => [ "category IN (?)", categories], :limit => 50)
516
+ # Person.find(:all, :conditions => { :friends => ["Bob", "Steve", "Fred"] }
517
+ # Person.find(:all, :offset => 10, :limit => 10)
518
+ # Person.find(:all, :include => [ :account, :friends ])
519
+ # Person.find(:all, :group => "category")
520
+ #
521
+ # Example for find with a lock: Imagine two concurrent transactions:
522
+ # each will read <tt>person.visits == 2</tt>, add 1 to it, and save, resulting
523
+ # in two saves of <tt>person.visits = 3</tt>. By locking the row, the second
524
+ # transaction has to wait until the first is finished; we get the
525
+ # expected <tt>person.visits == 4</tt>.
526
+ #
527
+ # Person.transaction do
528
+ # person = Person.find(1, :lock => true)
529
+ # person.visits += 1
530
+ # person.save!
531
+ # end
532
+ def find(*args)
533
+ options = args.extract_options!
534
+ validate_find_options(options)
535
+ set_readonly_option!(options)
536
+
537
+ case args.first
538
+ when :first then find_initial(options)
539
+ when :last then find_last(options)
540
+ when :all then find_every(options)
541
+ else find_from_ids(args, options)
542
+ end
543
+ end
544
+
545
+ # A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
546
+ # same arguments to this method as you can to <tt>find(:first)</tt>.
547
+ def first(*args)
548
+ find(:first, *args)
549
+ end
550
+
551
+ # A convenience wrapper for <tt>find(:last, *args)</tt>. You can pass in all the
552
+ # same arguments to this method as you can to <tt>find(:last)</tt>.
553
+ def last(*args)
554
+ find(:last, *args)
555
+ end
556
+
557
+ # This is an alias for find(:all). You can pass in all the same arguments to this method as you can
558
+ # to find(:all)
559
+ def all(*args)
560
+ find(:all, *args)
561
+ end
562
+
563
+ # Executes a custom SQL query against your database and returns all the results. The results will
564
+ # be returned as an array with columns requested encapsulated as attributes of the model you call
565
+ # this method from. If you call +Product.find_by_sql+ then the results will be returned in a Product
566
+ # object with the attributes you specified in the SQL query.
567
+ #
568
+ # If you call a complicated SQL query which spans multiple tables the columns specified by the
569
+ # SELECT will be attributes of the model, whether or not they are columns of the corresponding
570
+ # table.
571
+ #
572
+ # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be
573
+ # no database agnostic conversions performed. This should be a last resort because using, for example,
574
+ # MySQL specific terms will lock you to using that particular database engine or require you to
575
+ # change your call if you switch engines
576
+ #
577
+ # ==== Examples
578
+ # # A simple SQL query spanning multiple tables
579
+ # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
580
+ # > [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]
581
+ #
582
+ # # You can use the same string replacement techniques as you can with ActiveRecord#find
583
+ # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]
584
+ # > [#<Post:0x36bff9c @attributes={"first_name"=>"The Cheap Man Buys Twice"}>, ...]
585
+ def find_by_sql(sql)
586
+ connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
587
+ end
588
+
589
+ # Checks whether a record exists in the database that matches conditions given. These conditions
590
+ # can either be a single integer representing a primary key id to be found, or a condition to be
591
+ # matched like using ActiveRecord#find.
592
+ #
593
+ # The +id_or_conditions+ parameter can be an Integer or a String if you want to search the primary key
594
+ # column of the table for a matching id, or if you're looking to match against a condition you can use
595
+ # an Array or a Hash.
596
+ #
597
+ # Possible gotcha: You can't pass in a condition as a string e.g. "name = 'Jamie'", this would be
598
+ # sanitized and then queried against the primary key column as "id = 'name = \'Jamie"
599
+ #
600
+ # ==== Examples
601
+ # Person.exists?(5)
602
+ # Person.exists?('5')
603
+ # Person.exists?(:name => "David")
604
+ # Person.exists?(['name LIKE ?', "%#{query}%"])
605
+ def exists?(id_or_conditions)
606
+ connection.select_all(
607
+ construct_finder_sql(
608
+ :select => "#{quoted_table_name}.#{primary_key}",
609
+ :conditions => expand_id_conditions(id_or_conditions),
610
+ :limit => 1
611
+ ),
612
+ "#{name} Exists"
613
+ ).size > 0
614
+ end
615
+
616
+ # Creates an object (or multiple objects) and saves it to the database, if validations pass.
617
+ # The resulting object is returned whether the object was saved successfully to the database or not.
618
+ #
619
+ # The +attributes+ parameter can be either be a Hash or an Array of Hashes. These Hashes describe the
620
+ # attributes on the objects that are to be created.
621
+ #
622
+ # ==== Examples
623
+ # # Create a single new object
624
+ # User.create(:first_name => 'Jamie')
625
+ #
626
+ # # Create an Array of new objects
627
+ # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }])
628
+ #
629
+ # # Create a single object and pass it into a block to set other attributes.
630
+ # User.create(:first_name => 'Jamie') do |u|
631
+ # u.is_admin = false
632
+ # end
633
+ #
634
+ # # Creating an Array of new objects using a block, where the block is executed for each object:
635
+ # User.create([{ :first_name => 'Jamie' }, { :first_name => 'Jeremy' }]) do |u|
636
+ # u.is_admin = false
637
+ # end
638
+ def create(attributes = nil, &block)
639
+ if attributes.is_a?(Array)
640
+ attributes.collect { |attr| create(attr, &block) }
641
+ else
642
+ object = new(attributes)
643
+ yield(object) if block_given?
644
+ object.save
645
+ object
646
+ end
647
+ end
648
+
649
+ # Updates an object (or multiple objects) and saves it to the database, if validations pass.
650
+ # The resulting object is returned whether the object was saved successfully to the database or not.
651
+ #
652
+ # ==== Attributes
653
+ #
654
+ # * +id+ - This should be the id or an array of ids to be updated.
655
+ # * +attributes+ - This should be a Hash of attributes to be set on the object, or an array of Hashes.
656
+ #
657
+ # ==== Examples
658
+ #
659
+ # # Updating one record:
660
+ # Person.update(15, { :user_name => 'Samuel', :group => 'expert' })
661
+ #
662
+ # # Updating multiple records:
663
+ # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } }
664
+ # Person.update(people.keys, people.values)
665
+ def update(id, attributes)
666
+ if id.is_a?(Array)
667
+ idx = -1
668
+ id.collect { |one_id| idx += 1; update(one_id, attributes[idx]) }
669
+ else
670
+ object = find(id)
671
+ object.update_attributes(attributes)
672
+ object
673
+ end
674
+ end
675
+
676
+ # Delete an object (or multiple objects) where the +id+ given matches the primary_key. A SQL +DELETE+ command
677
+ # is executed on the database which means that no callbacks are fired off running this. This is an efficient method
678
+ # of deleting records that don't need cleaning up after or other actions to be taken.
679
+ #
680
+ # Objects are _not_ instantiated with this method.
681
+ #
682
+ # ==== Attributes
683
+ #
684
+ # * +id+ - Can be either an Integer or an Array of Integers.
685
+ #
686
+ # ==== Examples
687
+ #
688
+ # # Delete a single object
689
+ # Todo.delete(1)
690
+ #
691
+ # # Delete multiple objects
692
+ # todos = [1,2,3]
693
+ # Todo.delete(todos)
694
+ def delete(id)
695
+ delete_all([ "#{connection.quote_column_name(primary_key)} IN (?)", id ])
696
+ end
697
+
698
+ # Destroy an object (or multiple objects) that has the given id, the object is instantiated first,
699
+ # therefore all callbacks and filters are fired off before the object is deleted. This method is
700
+ # less efficient than ActiveRecord#delete but allows cleanup methods and other actions to be run.
701
+ #
702
+ # This essentially finds the object (or multiple objects) with the given id, creates a new object
703
+ # from the attributes, and then calls destroy on it.
704
+ #
705
+ # ==== Attributes
706
+ #
707
+ # * +id+ - Can be either an Integer or an Array of Integers.
708
+ #
709
+ # ==== Examples
710
+ #
711
+ # # Destroy a single object
712
+ # Todo.destroy(1)
713
+ #
714
+ # # Destroy multiple objects
715
+ # todos = [1,2,3]
716
+ # Todo.destroy(todos)
717
+ def destroy(id)
718
+ if id.is_a?(Array)
719
+ id.map { |one_id| destroy(one_id) }
720
+ else
721
+ find(id).destroy
722
+ end
723
+ end
724
+
725
+ # Updates all records with details given if they match a set of conditions supplied, limits and order can
726
+ # also be supplied.
727
+ #
728
+ # ==== Attributes
729
+ #
730
+ # * +updates+ - A String of column and value pairs that will be set on any records that match conditions.
731
+ # * +conditions+ - An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
732
+ # See conditions in the intro for more info.
733
+ # * +options+ - Additional options are <tt>:limit</tt> and/or <tt>:order</tt>, see the examples for usage.
734
+ #
735
+ # ==== Examples
736
+ #
737
+ # # Update all billing objects with the 3 different attributes given
738
+ # Billing.update_all( "category = 'authorized', approved = 1, author = 'David'" )
739
+ #
740
+ # # Update records that match our conditions
741
+ # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'" )
742
+ #
743
+ # # Update records that match our conditions but limit it to 5 ordered by date
744
+ # Billing.update_all( "author = 'David'", "title LIKE '%Rails%'",
745
+ # :order => 'created_at', :limit => 5 )
746
+ def update_all(updates, conditions = nil, options = {})
747
+ sql = "UPDATE #{quoted_table_name} SET #{sanitize_sql_for_assignment(updates)} "
748
+ scope = scope(:find)
749
+ add_conditions!(sql, conditions, scope)
750
+ add_order!(sql, options[:order], nil)
751
+ add_limit!(sql, options, nil)
752
+ connection.update(sql, "#{name} Update")
753
+ end
754
+
755
+ # Destroys the records matching +conditions+ by instantiating each record and calling the destroy method.
756
+ # This means at least 2*N database queries to destroy N records, so avoid destroy_all if you are deleting
757
+ # many records. If you want to simply delete records without worrying about dependent associations or
758
+ # callbacks, use the much faster +delete_all+ method instead.
759
+ #
760
+ # ==== Attributes
761
+ #
762
+ # * +conditions+ - Conditions are specified the same way as with +find+ method.
763
+ #
764
+ # ==== Example
765
+ #
766
+ # Person.destroy_all "last_login < '2004-04-04'"
767
+ #
768
+ # This loads and destroys each person one by one, including its dependent associations and before_ and
769
+ # after_destroy callbacks.
770
+ def destroy_all(conditions = nil)
771
+ find(:all, :conditions => conditions).each { |object| object.destroy }
772
+ end
773
+
774
+ # Deletes the records matching +conditions+ without instantiating the records first, and hence not
775
+ # calling the destroy method and invoking callbacks. This is a single SQL query, much more efficient
776
+ # than destroy_all.
777
+ #
778
+ # ==== Attributes
779
+ #
780
+ # * +conditions+ - Conditions are specified the same way as with +find+ method.
781
+ #
782
+ # ==== Example
783
+ #
784
+ # Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
785
+ #
786
+ # This deletes the affected posts all at once with a single DELETE query. If you need to destroy dependent
787
+ # associations or call your before_ or after_destroy callbacks, use the +destroy_all+ method instead.
788
+ def delete_all(conditions = nil)
789
+ sql = "DELETE FROM #{quoted_table_name} "
790
+ add_conditions!(sql, conditions, scope(:find))
791
+ connection.delete(sql, "#{name} Delete all")
792
+ end
793
+
794
+ # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.
795
+ # The use of this method should be restricted to complicated SQL queries that can't be executed
796
+ # using the ActiveRecord::Calculations class methods. Look into those before using this.
797
+ #
798
+ # ==== Attributes
799
+ #
800
+ # * +sql+ - An SQL statement which should return a count query from the database, see the example below.
801
+ #
802
+ # ==== Examples
803
+ #
804
+ # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id"
805
+ def count_by_sql(sql)
806
+ sql = sanitize_conditions(sql)
807
+ connection.select_value(sql, "#{name} Count").to_i
808
+ end
809
+
810
+ # A generic "counter updater" implementation, intended primarily to be
811
+ # used by increment_counter and decrement_counter, but which may also
812
+ # be useful on its own. It simply does a direct SQL update for the record
813
+ # with the given ID, altering the given hash of counters by the amount
814
+ # given by the corresponding value:
815
+ #
816
+ # ==== Attributes
817
+ #
818
+ # * +id+ - The id of the object you wish to update a counter on.
819
+ # * +counters+ - An Array of Hashes containing the names of the fields
820
+ # to update as keys and the amount to update the field by as values.
821
+ #
822
+ # ==== Examples
823
+ #
824
+ # # For the Post with id of 5, decrement the comment_count by 1, and
825
+ # # increment the action_count by 1
826
+ # Post.update_counters 5, :comment_count => -1, :action_count => 1
827
+ # # Executes the following SQL:
828
+ # # UPDATE posts
829
+ # # SET comment_count = comment_count - 1,
830
+ # # action_count = action_count + 1
831
+ # # WHERE id = 5
832
+ def update_counters(id, counters)
833
+ updates = counters.inject([]) { |list, (counter_name, increment)|
834
+ sign = increment < 0 ? "-" : "+"
835
+ list << "#{connection.quote_column_name(counter_name)} = COALESCE(#{connection.quote_column_name(counter_name)}, 0) #{sign} #{increment.abs}"
836
+ }.join(", ")
837
+ update_all(updates, "#{connection.quote_column_name(primary_key)} = #{quote_value(id)}")
838
+ end
839
+
840
+ # Increment a number field by one, usually representing a count.
841
+ #
842
+ # This is used for caching aggregate values, so that they don't need to be computed every time.
843
+ # For example, a DiscussionBoard may cache post_count and comment_count otherwise every time the board is
844
+ # shown it would have to run an SQL query to find how many posts and comments there are.
845
+ #
846
+ # ==== Attributes
847
+ #
848
+ # * +counter_name+ - The name of the field that should be incremented.
849
+ # * +id+ - The id of the object that should be incremented.
850
+ #
851
+ # ==== Examples
852
+ #
853
+ # # Increment the post_count column for the record with an id of 5
854
+ # DiscussionBoard.increment_counter(:post_count, 5)
855
+ def increment_counter(counter_name, id)
856
+ update_counters(id, counter_name => 1)
857
+ end
858
+
859
+ # Decrement a number field by one, usually representing a count.
860
+ #
861
+ # This works the same as increment_counter but reduces the column value by 1 instead of increasing it.
862
+ #
863
+ # ==== Attributes
864
+ #
865
+ # * +counter_name+ - The name of the field that should be decremented.
866
+ # * +id+ - The id of the object that should be decremented.
867
+ #
868
+ # ==== Examples
869
+ #
870
+ # # Decrement the post_count column for the record with an id of 5
871
+ # DiscussionBoard.decrement_counter(:post_count, 5)
872
+ def decrement_counter(counter_name, id)
873
+ update_counters(id, counter_name => -1)
874
+ end
875
+
876
+
877
+ # Attributes named in this macro are protected from mass-assignment,
878
+ # such as <tt>new(attributes)</tt>,
879
+ # <tt>update_attributes(attributes)</tt>, or
880
+ # <tt>attributes=(attributes)</tt>.
881
+ #
882
+ # Mass-assignment to these attributes will simply be ignored, to assign
883
+ # to them you can use direct writer methods. This is meant to protect
884
+ # sensitive attributes from being overwritten by malicious users
885
+ # tampering with URLs or forms.
886
+ #
887
+ # class Customer < ActiveRecord::Base
888
+ # attr_protected :credit_rating
889
+ # end
890
+ #
891
+ # customer = Customer.new("name" => David, "credit_rating" => "Excellent")
892
+ # customer.credit_rating # => nil
893
+ # customer.attributes = { "description" => "Jolly fellow", "credit_rating" => "Superb" }
894
+ # customer.credit_rating # => nil
895
+ #
896
+ # customer.credit_rating = "Average"
897
+ # customer.credit_rating # => "Average"
898
+ #
899
+ # To start from an all-closed default and enable attributes as needed,
900
+ # have a look at +attr_accessible+.
901
+ def attr_protected(*attributes)
902
+ write_inheritable_attribute("attr_protected", Set.new(attributes.map(&:to_s)) + (protected_attributes || []))
903
+ end
904
+
905
+ # Returns an array of all the attributes that have been protected from mass-assignment.
906
+ def protected_attributes # :nodoc:
907
+ read_inheritable_attribute("attr_protected")
908
+ end
909
+
910
+ # Specifies a white list of model attributes that can be set via
911
+ # mass-assignment, such as <tt>new(attributes)</tt>,
912
+ # <tt>update_attributes(attributes)</tt>, or
913
+ # <tt>attributes=(attributes)</tt>
914
+ #
915
+ # This is the opposite of the +attr_protected+ macro: Mass-assignment
916
+ # will only set attributes in this list, to assign to the rest of
917
+ # attributes you can use direct writer methods. This is meant to protect
918
+ # sensitive attributes from being overwritten by malicious users
919
+ # tampering with URLs or forms. If you'd rather start from an all-open
920
+ # default and restrict attributes as needed, have a look at
921
+ # +attr_protected+.
922
+ #
923
+ # class Customer < ActiveRecord::Base
924
+ # attr_accessible :name, :nickname
925
+ # end
926
+ #
927
+ # customer = Customer.new(:name => "David", :nickname => "Dave", :credit_rating => "Excellent")
928
+ # customer.credit_rating # => nil
929
+ # customer.attributes = { :name => "Jolly fellow", :credit_rating => "Superb" }
930
+ # customer.credit_rating # => nil
931
+ #
932
+ # customer.credit_rating = "Average"
933
+ # customer.credit_rating # => "Average"
934
+ def attr_accessible(*attributes)
935
+ write_inheritable_attribute("attr_accessible", Set.new(attributes.map(&:to_s)) + (accessible_attributes || []))
936
+ end
937
+
938
+ # Returns an array of all the attributes that have been made accessible to mass-assignment.
939
+ def accessible_attributes # :nodoc:
940
+ read_inheritable_attribute("attr_accessible")
941
+ end
942
+
943
+ # Attributes listed as readonly can be set for a new record, but will be ignored in database updates afterwards.
944
+ def attr_readonly(*attributes)
945
+ write_inheritable_attribute("attr_readonly", Set.new(attributes.map(&:to_s)) + (readonly_attributes || []))
946
+ end
947
+
948
+ # Returns an array of all the attributes that have been specified as readonly.
949
+ def readonly_attributes
950
+ read_inheritable_attribute("attr_readonly")
951
+ end
952
+
953
+ # If you have an attribute that needs to be saved to the database as an object, and retrieved as the same object,
954
+ # then specify the name of that attribute using this method and it will be handled automatically.
955
+ # The serialization is done through YAML. If +class_name+ is specified, the serialized object must be of that
956
+ # class on retrieval or SerializationTypeMismatch will be raised.
957
+ #
958
+ # ==== Attributes
959
+ #
960
+ # * +attr_name+ - The field name that should be serialized.
961
+ # * +class_name+ - Optional, class name that the object type should be equal to.
962
+ #
963
+ # ==== Example
964
+ # # Serialize a preferences attribute
965
+ # class User
966
+ # serialize :preferences
967
+ # end
968
+ def serialize(attr_name, class_name = Object)
969
+ serialized_attributes[attr_name.to_s] = class_name
970
+ end
971
+
972
+ # Returns a hash of all the attributes that have been specified for serialization as keys and their class restriction as values.
973
+ def serialized_attributes
974
+ read_inheritable_attribute("attr_serialized") or write_inheritable_attribute("attr_serialized", {})
975
+ end
976
+
977
+
978
+ # Guesses the table name (in forced lower-case) based on the name of the class in the inheritance hierarchy descending
979
+ # directly from ActiveRecord::Base. So if the hierarchy looks like: Reply < Message < ActiveRecord::Base, then Message is used
980
+ # to guess the table name even when called on Reply. The rules used to do the guess are handled by the Inflector class
981
+ # in Active Support, which knows almost all common English inflections. You can add new inflections in config/initializers/inflections.rb.
982
+ #
983
+ # Nested classes are given table names prefixed by the singular form of
984
+ # the parent's table name. Enclosing modules are not considered.
985
+ #
986
+ # ==== Examples
987
+ #
988
+ # class Invoice < ActiveRecord::Base; end;
989
+ # file class table_name
990
+ # invoice.rb Invoice invoices
991
+ #
992
+ # class Invoice < ActiveRecord::Base; class Lineitem < ActiveRecord::Base; end; end;
993
+ # file class table_name
994
+ # invoice.rb Invoice::Lineitem invoice_lineitems
995
+ #
996
+ # module Invoice; class Lineitem < ActiveRecord::Base; end; end;
997
+ # file class table_name
998
+ # invoice/lineitem.rb Invoice::Lineitem lineitems
999
+ #
1000
+ # Additionally, the class-level +table_name_prefix+ is prepended and the
1001
+ # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix,
1002
+ # the table name guess for an Invoice class becomes "myapp_invoices".
1003
+ # Invoice::Lineitem becomes "myapp_invoice_lineitems".
1004
+ #
1005
+ # You can also overwrite this class method to allow for unguessable
1006
+ # links, such as a Mouse class with a link to a "mice" table. Example:
1007
+ #
1008
+ # class Mouse < ActiveRecord::Base
1009
+ # set_table_name "mice"
1010
+ # end
1011
+ def table_name
1012
+ reset_table_name
1013
+ end
1014
+
1015
+ def reset_table_name #:nodoc:
1016
+ base = base_class
1017
+
1018
+ name =
1019
+ # STI subclasses always use their superclass' table.
1020
+ unless self == base
1021
+ base.table_name
1022
+ else
1023
+ # Nested classes are prefixed with singular parent table name.
1024
+ if parent < ActiveRecord::Base && !parent.abstract_class?
1025
+ contained = parent.table_name
1026
+ contained = contained.singularize if parent.pluralize_table_names
1027
+ contained << '_'
1028
+ end
1029
+ name = "#{table_name_prefix}#{contained}#{undecorated_table_name(base.name)}#{table_name_suffix}"
1030
+ end
1031
+
1032
+ set_table_name(name)
1033
+ name
1034
+ end
1035
+
1036
+ # Defines the primary key field -- can be overridden in subclasses. Overwriting will negate any effect of the
1037
+ # primary_key_prefix_type setting, though.
1038
+ def primary_key
1039
+ reset_primary_key
1040
+ end
1041
+
1042
+ def reset_primary_key #:nodoc:
1043
+ key = get_primary_key(base_class.name)
1044
+ set_primary_key(key)
1045
+ key
1046
+ end
1047
+
1048
+ def get_primary_key(base_name) #:nodoc:
1049
+ key = 'id'
1050
+ case primary_key_prefix_type
1051
+ when :table_name
1052
+ key = base_name.to_s.foreign_key(false)
1053
+ when :table_name_with_underscore
1054
+ key = base_name.to_s.foreign_key
1055
+ end
1056
+ key
1057
+ end
1058
+
1059
+ # Defines the column name for use with single table inheritance
1060
+ # -- can be set in subclasses like so: self.inheritance_column = "type_id"
1061
+ def inheritance_column
1062
+ @inheritance_column ||= "type".freeze
1063
+ end
1064
+
1065
+ # Lazy-set the sequence name to the connection's default. This method
1066
+ # is only ever called once since set_sequence_name overrides it.
1067
+ def sequence_name #:nodoc:
1068
+ reset_sequence_name
1069
+ end
1070
+
1071
+ def reset_sequence_name #:nodoc:
1072
+ default = connection.default_sequence_name(table_name, primary_key)
1073
+ set_sequence_name(default)
1074
+ default
1075
+ end
1076
+
1077
+ # Sets the table name to use to the given value, or (if the value
1078
+ # is nil or false) to the value returned by the given block.
1079
+ #
1080
+ # class Project < ActiveRecord::Base
1081
+ # set_table_name "project"
1082
+ # end
1083
+ def set_table_name(value = nil, &block)
1084
+ define_attr_method :table_name, value, &block
1085
+ end
1086
+ alias :table_name= :set_table_name
1087
+
1088
+ # Sets the name of the primary key column to use to the given value,
1089
+ # or (if the value is nil or false) to the value returned by the given
1090
+ # block.
1091
+ #
1092
+ # class Project < ActiveRecord::Base
1093
+ # set_primary_key "sysid"
1094
+ # end
1095
+ def set_primary_key(value = nil, &block)
1096
+ define_attr_method :primary_key, value, &block
1097
+ end
1098
+ alias :primary_key= :set_primary_key
1099
+
1100
+ # Sets the name of the inheritance column to use to the given value,
1101
+ # or (if the value # is nil or false) to the value returned by the
1102
+ # given block.
1103
+ #
1104
+ # class Project < ActiveRecord::Base
1105
+ # set_inheritance_column do
1106
+ # original_inheritance_column + "_id"
1107
+ # end
1108
+ # end
1109
+ def set_inheritance_column(value = nil, &block)
1110
+ define_attr_method :inheritance_column, value, &block
1111
+ end
1112
+ alias :inheritance_column= :set_inheritance_column
1113
+
1114
+ # Sets the name of the sequence to use when generating ids to the given
1115
+ # value, or (if the value is nil or false) to the value returned by the
1116
+ # given block. This is required for Oracle and is useful for any
1117
+ # database which relies on sequences for primary key generation.
1118
+ #
1119
+ # If a sequence name is not explicitly set when using Oracle or Firebird,
1120
+ # it will default to the commonly used pattern of: #{table_name}_seq
1121
+ #
1122
+ # If a sequence name is not explicitly set when using PostgreSQL, it
1123
+ # will discover the sequence corresponding to your primary key for you.
1124
+ #
1125
+ # class Project < ActiveRecord::Base
1126
+ # set_sequence_name "projectseq" # default would have been "project_seq"
1127
+ # end
1128
+ def set_sequence_name(value = nil, &block)
1129
+ define_attr_method :sequence_name, value, &block
1130
+ end
1131
+ alias :sequence_name= :set_sequence_name
1132
+
1133
+ # Turns the +table_name+ back into a class name following the reverse rules of +table_name+.
1134
+ def class_name(table_name = table_name) # :nodoc:
1135
+ # remove any prefix and/or suffix from the table name
1136
+ class_name = table_name[table_name_prefix.length..-(table_name_suffix.length + 1)].camelize
1137
+ class_name = class_name.singularize if pluralize_table_names
1138
+ class_name
1139
+ end
1140
+
1141
+ # Indicates whether the table associated with this class exists
1142
+ def table_exists?
1143
+ connection.table_exists?(table_name)
1144
+ end
1145
+
1146
+ # Returns an array of column objects for the table associated with this class.
1147
+ def columns
1148
+ unless defined?(@columns) && @columns
1149
+ @columns = connection.columns(table_name, "#{name} Columns")
1150
+ @columns.each { |column| column.primary = column.name == primary_key }
1151
+ end
1152
+ @columns
1153
+ end
1154
+
1155
+ # Returns a hash of column objects for the table associated with this class.
1156
+ def columns_hash
1157
+ @columns_hash ||= columns.inject({}) { |hash, column| hash[column.name] = column; hash }
1158
+ end
1159
+
1160
+ # Returns an array of column names as strings.
1161
+ def column_names
1162
+ @column_names ||= columns.map { |column| column.name }
1163
+ end
1164
+
1165
+ # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
1166
+ # and columns used for single table inheritance have been removed.
1167
+ def content_columns
1168
+ @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
1169
+ end
1170
+
1171
+ # Returns a hash of all the methods added to query each of the columns in the table with the name of the method as the key
1172
+ # and true as the value. This makes it possible to do O(1) lookups in respond_to? to check if a given method for attribute
1173
+ # is available.
1174
+ def column_methods_hash #:nodoc:
1175
+ @dynamic_methods_hash ||= column_names.inject(Hash.new(false)) do |methods, attr|
1176
+ attr_name = attr.to_s
1177
+ methods[attr.to_sym] = attr_name
1178
+ methods["#{attr}=".to_sym] = attr_name
1179
+ methods["#{attr}?".to_sym] = attr_name
1180
+ methods["#{attr}_before_type_cast".to_sym] = attr_name
1181
+ methods
1182
+ end
1183
+ end
1184
+
1185
+ # Resets all the cached information about columns, which will cause them to be reloaded on the next request.
1186
+ def reset_column_information
1187
+ generated_methods.each { |name| undef_method(name) }
1188
+ @column_names = @columns = @columns_hash = @content_columns = @dynamic_methods_hash = @generated_methods = @inheritance_column = nil
1189
+ end
1190
+
1191
+ def reset_column_information_and_inheritable_attributes_for_all_subclasses#:nodoc:
1192
+ subclasses.each { |klass| klass.reset_inheritable_attributes; klass.reset_column_information }
1193
+ end
1194
+
1195
+ # Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
1196
+ # Person.human_attribute_name("first_name") # => "First name"
1197
+ # Deprecated in favor of just calling "first_name".humanize
1198
+ def human_attribute_name(attribute_key_name) #:nodoc:
1199
+ attribute_key_name.humanize
1200
+ end
1201
+
1202
+ # True if this isn't a concrete subclass needing a STI type condition.
1203
+ def descends_from_active_record?
1204
+ if superclass.abstract_class?
1205
+ superclass.descends_from_active_record?
1206
+ else
1207
+ superclass == Base || !columns_hash.include?(inheritance_column)
1208
+ end
1209
+ end
1210
+
1211
+ def finder_needs_type_condition? #:nodoc:
1212
+ # This is like this because benchmarking justifies the strange :false stuff
1213
+ :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true)
1214
+ end
1215
+
1216
+ # Returns a string like 'Post id:integer, title:string, body:text'
1217
+ def inspect
1218
+ if self == Base
1219
+ super
1220
+ elsif abstract_class?
1221
+ "#{super}(abstract)"
1222
+ elsif table_exists?
1223
+ attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
1224
+ "#{super}(#{attr_list})"
1225
+ else
1226
+ "#{super}(Table doesn't exist)"
1227
+ end
1228
+ end
1229
+
1230
+
1231
+ def quote_value(value, column = nil) #:nodoc:
1232
+ connection.quote(value,column)
1233
+ end
1234
+
1235
+ # Used to sanitize objects before they're used in an SQL SELECT statement. Delegates to <tt>connection.quote</tt>.
1236
+ def sanitize(object) #:nodoc:
1237
+ connection.quote(object)
1238
+ end
1239
+
1240
+ # Log and benchmark multiple statements in a single block. Example:
1241
+ #
1242
+ # Project.benchmark("Creating project") do
1243
+ # project = Project.create("name" => "stuff")
1244
+ # project.create_manager("name" => "David")
1245
+ # project.milestones << Milestone.find(:all)
1246
+ # end
1247
+ #
1248
+ # The benchmark is only recorded if the current level of the logger is less than or equal to the <tt>log_level</tt>,
1249
+ # which makes it easy to include benchmarking statements in production software that will remain inexpensive because
1250
+ # the benchmark will only be conducted if the log level is low enough.
1251
+ #
1252
+ # The logging of the multiple statements is turned off unless <tt>use_silence</tt> is set to false.
1253
+ def benchmark(title, log_level = Logger::DEBUG, use_silence = true)
1254
+ if logger && logger.level <= log_level
1255
+ result = nil
1256
+ seconds = Benchmark.realtime { result = use_silence ? silence { yield } : yield }
1257
+ logger.add(log_level, "#{title} (#{'%.5f' % seconds})")
1258
+ result
1259
+ else
1260
+ yield
1261
+ end
1262
+ end
1263
+
1264
+ # Silences the logger for the duration of the block.
1265
+ def silence
1266
+ old_logger_level, logger.level = logger.level, Logger::ERROR if logger
1267
+ yield
1268
+ ensure
1269
+ logger.level = old_logger_level if logger
1270
+ end
1271
+
1272
+ # Overwrite the default class equality method to provide support for association proxies.
1273
+ def ===(object)
1274
+ object.is_a?(self)
1275
+ end
1276
+
1277
+ # Returns the base AR subclass that this class descends from. If A
1278
+ # extends AR::Base, A.base_class will return A. If B descends from A
1279
+ # through some arbitrarily deep hierarchy, B.base_class will return A.
1280
+ def base_class
1281
+ class_of_active_record_descendant(self)
1282
+ end
1283
+
1284
+ # Set this to true if this is an abstract class (see <tt>abstract_class?</tt>).
1285
+ attr_accessor :abstract_class
1286
+
1287
+ # Returns whether this class is a base AR class. If A is a base class and
1288
+ # B descends from A, then B.base_class will return B.
1289
+ def abstract_class?
1290
+ defined?(@abstract_class) && @abstract_class == true
1291
+ end
1292
+
1293
+ def respond_to?(method_id, include_private = false)
1294
+ if match = matches_dynamic_finder?(method_id) || matches_dynamic_finder_with_initialize_or_create?(method_id)
1295
+ return true if all_attributes_exists?(extract_attribute_names_from_match(match))
1296
+ end
1297
+ super
1298
+ end
1299
+
1300
+ def sti_name
1301
+ store_full_sti_class ? name : name.demodulize
1302
+ end
1303
+
1304
+ private
1305
+ def find_initial(options)
1306
+ options.update(:limit => 1)
1307
+ find_every(options).first
1308
+ end
1309
+
1310
+ def find_last(options)
1311
+ order = options[:order]
1312
+
1313
+ if order
1314
+ order = reverse_sql_order(order)
1315
+ elsif !scoped?(:find, :order)
1316
+ order = "#{table_name}.#{primary_key} DESC"
1317
+ end
1318
+
1319
+ if scoped?(:find, :order)
1320
+ scoped_order = reverse_sql_order(scope(:find, :order))
1321
+ scoped_methods.select { |s| s[:find].update(:order => scoped_order) }
1322
+ end
1323
+
1324
+ find_initial(options.merge({ :order => order }))
1325
+ end
1326
+
1327
+ def reverse_sql_order(order_query)
1328
+ reversed_query = order_query.split(/,/).each { |s|
1329
+ if s.match(/\s(asc|ASC)$/)
1330
+ s.gsub!(/\s(asc|ASC)$/, ' DESC')
1331
+ elsif s.match(/\s(desc|DESC)$/)
1332
+ s.gsub!(/\s(desc|DESC)$/, ' ASC')
1333
+ elsif !s.match(/\s(asc|ASC|desc|DESC)$/)
1334
+ s.concat(' DESC')
1335
+ end
1336
+ }.join(',')
1337
+ end
1338
+
1339
+ def find_every(options)
1340
+ include_associations = merge_includes(scope(:find, :include), options[:include])
1341
+
1342
+ if include_associations.any? && references_eager_loaded_tables?(options)
1343
+ records = find_with_associations(options)
1344
+ else
1345
+ records = find_by_sql(construct_finder_sql(options))
1346
+ if include_associations.any?
1347
+ preload_associations(records, include_associations)
1348
+ end
1349
+ end
1350
+
1351
+ records.each { |record| record.readonly! } if options[:readonly]
1352
+
1353
+ records
1354
+ end
1355
+
1356
+ def find_from_ids(ids, options)
1357
+ expects_array = ids.first.kind_of?(Array)
1358
+ return ids.first if expects_array && ids.first.empty?
1359
+
1360
+ ids = ids.flatten.compact.uniq
1361
+
1362
+ case ids.size
1363
+ when 0
1364
+ raise RecordNotFound, "Couldn't find #{name} without an ID"
1365
+ when 1
1366
+ result = find_one(ids.first, options)
1367
+ expects_array ? [ result ] : result
1368
+ else
1369
+ find_some(ids, options)
1370
+ end
1371
+ end
1372
+
1373
+ def find_one(id, options)
1374
+ conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
1375
+ options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} = #{quote_value(id,columns_hash[primary_key])}#{conditions}"
1376
+
1377
+ # Use find_every(options).first since the primary key condition
1378
+ # already ensures we have a single record. Using find_initial adds
1379
+ # a superfluous :limit => 1.
1380
+ if result = find_every(options).first
1381
+ result
1382
+ else
1383
+ raise RecordNotFound, "Couldn't find #{name} with ID=#{id}#{conditions}"
1384
+ end
1385
+ end
1386
+
1387
+ def find_some(ids, options)
1388
+ conditions = " AND (#{sanitize_sql(options[:conditions])})" if options[:conditions]
1389
+ ids_list = ids.map { |id| quote_value(id,columns_hash[primary_key]) }.join(',')
1390
+ options.update :conditions => "#{quoted_table_name}.#{connection.quote_column_name(primary_key)} IN (#{ids_list})#{conditions}"
1391
+
1392
+ result = find_every(options)
1393
+
1394
+ # Determine expected size from limit and offset, not just ids.size.
1395
+ expected_size =
1396
+ if options[:limit] && ids.size > options[:limit]
1397
+ options[:limit]
1398
+ else
1399
+ ids.size
1400
+ end
1401
+
1402
+ # 11 ids with limit 3, offset 9 should give 2 results.
1403
+ if options[:offset] && (ids.size - options[:offset] < expected_size)
1404
+ expected_size = ids.size - options[:offset]
1405
+ end
1406
+
1407
+ if result.size == expected_size
1408
+ result
1409
+ else
1410
+ raise RecordNotFound, "Couldn't find all #{name.pluralize} with IDs (#{ids_list})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
1411
+ end
1412
+ end
1413
+
1414
+ # Finder methods must instantiate through this method to work with the
1415
+ # single-table inheritance model that makes it possible to create
1416
+ # objects of different types from the same table.
1417
+ def instantiate(record)
1418
+ object =
1419
+ if subclass_name = record[inheritance_column]
1420
+ # No type given.
1421
+ if subclass_name.empty?
1422
+ allocate
1423
+
1424
+ else
1425
+ # Ignore type if no column is present since it was probably
1426
+ # pulled in from a sloppy join.
1427
+ unless columns_hash.include?(inheritance_column)
1428
+ allocate
1429
+
1430
+ else
1431
+ begin
1432
+ compute_type(subclass_name).allocate
1433
+ rescue NameError
1434
+ raise SubclassNotFound,
1435
+ "The single-table inheritance mechanism failed to locate the subclass: '#{record[inheritance_column]}'. " +
1436
+ "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " +
1437
+ "Please rename this column if you didn't intend it to be used for storing the inheritance class " +
1438
+ "or overwrite #{self.to_s}.inheritance_column to use another column for that information."
1439
+ end
1440
+ end
1441
+ end
1442
+ else
1443
+ allocate
1444
+ end
1445
+
1446
+ object.instance_variable_set("@attributes", record)
1447
+ object.instance_variable_set("@attributes_cache", Hash.new)
1448
+
1449
+ if object.respond_to_without_attributes?(:after_find)
1450
+ object.send(:callback, :after_find)
1451
+ end
1452
+
1453
+ if object.respond_to_without_attributes?(:after_initialize)
1454
+ object.send(:callback, :after_initialize)
1455
+ end
1456
+
1457
+ object
1458
+ end
1459
+
1460
+ # Nest the type name in the same module as this class.
1461
+ # Bar is "MyApp::Business::Bar" relative to MyApp::Business::Foo
1462
+ def type_name_with_module(type_name)
1463
+ if store_full_sti_class
1464
+ type_name
1465
+ else
1466
+ (/^::/ =~ type_name) ? type_name : "#{parent.name}::#{type_name}"
1467
+ end
1468
+ end
1469
+
1470
+ def construct_finder_sql(options)
1471
+ scope = scope(:find)
1472
+ sql = "SELECT #{options[:select] || (scope && scope[:select]) || ((options[:joins] || (scope && scope[:joins])) && quoted_table_name + '.*') || '*'} "
1473
+ sql << "FROM #{(scope && scope[:from]) || options[:from] || quoted_table_name} "
1474
+
1475
+ add_joins!(sql, options, scope)
1476
+ add_conditions!(sql, options[:conditions], scope)
1477
+
1478
+ add_group!(sql, options[:group], scope)
1479
+ add_order!(sql, options[:order], scope)
1480
+ add_limit!(sql, options, scope)
1481
+ add_lock!(sql, options, scope)
1482
+
1483
+ sql
1484
+ end
1485
+
1486
+ # Merges includes so that the result is a valid +include+
1487
+ def merge_includes(first, second)
1488
+ (safe_to_array(first) + safe_to_array(second)).uniq
1489
+ end
1490
+
1491
+ # Merges conditions so that the result is a valid +condition+
1492
+ def merge_conditions(*conditions)
1493
+ segments = []
1494
+
1495
+ conditions.each do |condition|
1496
+ unless condition.blank?
1497
+ sql = sanitize_sql(condition)
1498
+ segments << sql unless sql.blank?
1499
+ end
1500
+ end
1501
+
1502
+ "(#{segments.join(') AND (')})" unless segments.empty?
1503
+ end
1504
+
1505
+ # Object#to_a is deprecated, though it does have the desired behavior
1506
+ def safe_to_array(o)
1507
+ case o
1508
+ when NilClass
1509
+ []
1510
+ when Array
1511
+ o
1512
+ else
1513
+ [o]
1514
+ end
1515
+ end
1516
+
1517
+ def add_order!(sql, order, scope = :auto)
1518
+ scope = scope(:find) if :auto == scope
1519
+ scoped_order = scope[:order] if scope
1520
+ if order
1521
+ sql << " ORDER BY #{order}"
1522
+ sql << ", #{scoped_order}" if scoped_order
1523
+ else
1524
+ sql << " ORDER BY #{scoped_order}" if scoped_order
1525
+ end
1526
+ end
1527
+
1528
+ def add_group!(sql, group, scope = :auto)
1529
+ if group
1530
+ sql << " GROUP BY #{group}"
1531
+ else
1532
+ scope = scope(:find) if :auto == scope
1533
+ if scope && (scoped_group = scope[:group])
1534
+ sql << " GROUP BY #{scoped_group}"
1535
+ end
1536
+ end
1537
+ end
1538
+
1539
+ # The optional scope argument is for the current <tt>:find</tt> scope.
1540
+ def add_limit!(sql, options, scope = :auto)
1541
+ scope = scope(:find) if :auto == scope
1542
+
1543
+ if scope
1544
+ options[:limit] ||= scope[:limit]
1545
+ options[:offset] ||= scope[:offset]
1546
+ end
1547
+
1548
+ connection.add_limit_offset!(sql, options)
1549
+ end
1550
+
1551
+ # The optional scope argument is for the current <tt>:find</tt> scope.
1552
+ # The <tt>:lock</tt> option has precedence over a scoped <tt>:lock</tt>.
1553
+ def add_lock!(sql, options, scope = :auto)
1554
+ scope = scope(:find) if :auto == scope
1555
+ options = options.reverse_merge(:lock => scope[:lock]) if scope
1556
+ connection.add_lock!(sql, options)
1557
+ end
1558
+
1559
+ # The optional scope argument is for the current <tt>:find</tt> scope.
1560
+ def add_joins!(sql, options, scope = :auto)
1561
+ scope = scope(:find) if :auto == scope
1562
+ [(scope && scope[:joins]), options[:joins]].each do |join|
1563
+ case join
1564
+ when Symbol, Hash, Array
1565
+ join_dependency = ActiveRecord::Associations::ClassMethods::InnerJoinDependency.new(self, join, nil)
1566
+ sql << " #{join_dependency.join_associations.collect { |assoc| assoc.association_join }.join} "
1567
+ else
1568
+ sql << " #{join} "
1569
+ end
1570
+ end
1571
+ end
1572
+
1573
+ # Adds a sanitized version of +conditions+ to the +sql+ string. Note that the passed-in +sql+ string is changed.
1574
+ # The optional scope argument is for the current <tt>:find</tt> scope.
1575
+ def add_conditions!(sql, conditions, scope = :auto)
1576
+ scope = scope(:find) if :auto == scope
1577
+ conditions = [conditions]
1578
+ conditions << scope[:conditions] if scope
1579
+ conditions << type_condition if finder_needs_type_condition?
1580
+ merged_conditions = merge_conditions(*conditions)
1581
+ sql << "WHERE #{merged_conditions} " unless merged_conditions.blank?
1582
+ end
1583
+
1584
+ def type_condition(table_alias=nil)
1585
+ quoted_table_alias = self.connection.quote_table_name(table_alias || table_name)
1586
+ quoted_inheritance_column = connection.quote_column_name(inheritance_column)
1587
+ type_condition = subclasses.inject("#{quoted_table_alias}.#{quoted_inheritance_column} = '#{sti_name}' ") do |condition, subclass|
1588
+ condition << "OR #{quoted_table_alias}.#{quoted_inheritance_column} = '#{subclass.sti_name}' "
1589
+ end
1590
+
1591
+ " (#{type_condition}) "
1592
+ end
1593
+
1594
+ # Guesses the table name, but does not decorate it with prefix and suffix information.
1595
+ def undecorated_table_name(class_name = base_class.name)
1596
+ table_name = class_name.to_s.demodulize.underscore
1597
+ table_name = table_name.pluralize if pluralize_table_names
1598
+ table_name
1599
+ end
1600
+
1601
+ # Enables dynamic finders like find_by_user_name(user_name) and find_by_user_name_and_password(user_name, password) that are turned into
1602
+ # find(:first, :conditions => ["user_name = ?", user_name]) and find(:first, :conditions => ["user_name = ? AND password = ?", user_name, password])
1603
+ # respectively. Also works for find(:all) by using find_all_by_amount(50) that is turned into find(:all, :conditions => ["amount = ?", 50]).
1604
+ #
1605
+ # It's even possible to use all the additional parameters to find. For example, the full interface for find_all_by_amount
1606
+ # is actually find_all_by_amount(amount, options).
1607
+ #
1608
+ # This also enables you to initialize a record if it is not found, such as find_or_initialize_by_amount(amount)
1609
+ # or find_or_create_by_user_and_password(user, password).
1610
+ #
1611
+ # Each dynamic finder or initializer/creator is also defined in the class after it is first invoked, so that future
1612
+ # attempts to use it do not run through method_missing.
1613
+ def method_missing(method_id, *arguments)
1614
+ if match = matches_dynamic_finder?(method_id)
1615
+ finder = determine_finder(match)
1616
+
1617
+ attribute_names = extract_attribute_names_from_match(match)
1618
+ super unless all_attributes_exists?(attribute_names)
1619
+
1620
+ self.class_eval %{
1621
+ def self.#{method_id}(*args)
1622
+ options = args.extract_options!
1623
+ attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args)
1624
+ finder_options = { :conditions => attributes }
1625
+ validate_find_options(options)
1626
+ set_readonly_option!(options)
1627
+
1628
+ if options[:conditions]
1629
+ with_scope(:find => finder_options) do
1630
+ ActiveSupport::Deprecation.silence { send(:#{finder}, options) }
1631
+ end
1632
+ else
1633
+ ActiveSupport::Deprecation.silence { send(:#{finder}, options.merge(finder_options)) }
1634
+ end
1635
+ end
1636
+ }, __FILE__, __LINE__
1637
+ send(method_id, *arguments)
1638
+ elsif match = matches_dynamic_finder_with_initialize_or_create?(method_id)
1639
+ instantiator = determine_instantiator(match)
1640
+ attribute_names = extract_attribute_names_from_match(match)
1641
+ super unless all_attributes_exists?(attribute_names)
1642
+
1643
+ self.class_eval %{
1644
+ def self.#{method_id}(*args)
1645
+ guard_protected_attributes = false
1646
+
1647
+ if args[0].is_a?(Hash)
1648
+ guard_protected_attributes = true
1649
+ attributes = args[0].with_indifferent_access
1650
+ find_attributes = attributes.slice(*[:#{attribute_names.join(',:')}])
1651
+ else
1652
+ find_attributes = attributes = construct_attributes_from_arguments([:#{attribute_names.join(',:')}], args)
1653
+ end
1654
+
1655
+ options = { :conditions => find_attributes }
1656
+ set_readonly_option!(options)
1657
+
1658
+ record = find_initial(options)
1659
+
1660
+ if record.nil?
1661
+ record = self.new { |r| r.send(:attributes=, attributes, guard_protected_attributes) }
1662
+ #{'yield(record) if block_given?'}
1663
+ #{'record.save' if instantiator == :create}
1664
+ record
1665
+ else
1666
+ record
1667
+ end
1668
+ end
1669
+ }, __FILE__, __LINE__
1670
+ send(method_id, *arguments)
1671
+ else
1672
+ super
1673
+ end
1674
+ end
1675
+
1676
+ def matches_dynamic_finder?(method_id)
1677
+ /^find_(all_by|by)_([_a-zA-Z]\w*)$/.match(method_id.to_s)
1678
+ end
1679
+
1680
+ def matches_dynamic_finder_with_initialize_or_create?(method_id)
1681
+ /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/.match(method_id.to_s)
1682
+ end
1683
+
1684
+ def determine_finder(match)
1685
+ match.captures.first == 'all_by' ? :find_every : :find_initial
1686
+ end
1687
+
1688
+ def determine_instantiator(match)
1689
+ match.captures.first == 'initialize' ? :new : :create
1690
+ end
1691
+
1692
+ def extract_attribute_names_from_match(match)
1693
+ match.captures.last.split('_and_')
1694
+ end
1695
+
1696
+ def construct_attributes_from_arguments(attribute_names, arguments)
1697
+ attributes = {}
1698
+ attribute_names.each_with_index { |name, idx| attributes[name] = arguments[idx] }
1699
+ attributes
1700
+ end
1701
+
1702
+ # Similar in purpose to +expand_hash_conditions_for_aggregates+.
1703
+ def expand_attribute_names_for_aggregates(attribute_names)
1704
+ expanded_attribute_names = []
1705
+ attribute_names.each do |attribute_name|
1706
+ unless (aggregation = reflect_on_aggregation(attribute_name.to_sym)).nil?
1707
+ aggregate_mapping(aggregation).each do |field_attr, aggregate_attr|
1708
+ expanded_attribute_names << field_attr
1709
+ end
1710
+ else
1711
+ expanded_attribute_names << attribute_name
1712
+ end
1713
+ end
1714
+ expanded_attribute_names
1715
+ end
1716
+
1717
+ def all_attributes_exists?(attribute_names)
1718
+ attribute_names = expand_attribute_names_for_aggregates(attribute_names)
1719
+ attribute_names.all? { |name| column_methods_hash.include?(name.to_sym) }
1720
+ end
1721
+
1722
+ def attribute_condition(argument)
1723
+ case argument
1724
+ when nil then "IS ?"
1725
+ when Array, ActiveRecord::Associations::AssociationCollection, ActiveRecord::NamedScope::Scope then "IN (?)"
1726
+ when Range then "BETWEEN ? AND ?"
1727
+ else "= ?"
1728
+ end
1729
+ end
1730
+
1731
+ # Interpret Array and Hash as conditions and anything else as an id.
1732
+ def expand_id_conditions(id_or_conditions)
1733
+ case id_or_conditions
1734
+ when Array, Hash then id_or_conditions
1735
+ else sanitize_sql(primary_key => id_or_conditions)
1736
+ end
1737
+ end
1738
+
1739
+
1740
+ # Defines an "attribute" method (like +inheritance_column+ or
1741
+ # +table_name+). A new (class) method will be created with the
1742
+ # given name. If a value is specified, the new method will
1743
+ # return that value (as a string). Otherwise, the given block
1744
+ # will be used to compute the value of the method.
1745
+ #
1746
+ # The original method will be aliased, with the new name being
1747
+ # prefixed with "original_". This allows the new method to
1748
+ # access the original value.
1749
+ #
1750
+ # Example:
1751
+ #
1752
+ # class A < ActiveRecord::Base
1753
+ # define_attr_method :primary_key, "sysid"
1754
+ # define_attr_method( :inheritance_column ) do
1755
+ # original_inheritance_column + "_id"
1756
+ # end
1757
+ # end
1758
+ def define_attr_method(name, value=nil, &block)
1759
+ sing = class << self; self; end
1760
+ sing.send :alias_method, "original_#{name}", name
1761
+ if block_given?
1762
+ sing.send :define_method, name, &block
1763
+ else
1764
+ # use eval instead of a block to work around a memory leak in dev
1765
+ # mode in fcgi
1766
+ sing.class_eval "def #{name}; #{value.to_s.inspect}; end"
1767
+ end
1768
+ end
1769
+
1770
+ protected
1771
+ # Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
1772
+ # method_name may be <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
1773
+ # <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. <tt>:create</tt> parameters are an attributes hash.
1774
+ #
1775
+ # class Article < ActiveRecord::Base
1776
+ # def self.create_with_scope
1777
+ # with_scope(:find => { :conditions => "blog_id = 1" }, :create => { :blog_id => 1 }) do
1778
+ # find(1) # => SELECT * from articles WHERE blog_id = 1 AND id = 1
1779
+ # a = create(1)
1780
+ # a.blog_id # => 1
1781
+ # end
1782
+ # end
1783
+ # end
1784
+ #
1785
+ # In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
1786
+ # <tt>:conditions</tt> and <tt>:include</tt> options in <tt>:find</tt>, which are merged.
1787
+ #
1788
+ # class Article < ActiveRecord::Base
1789
+ # def self.find_with_scope
1790
+ # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }, :create => { :blog_id => 1 }) do
1791
+ # with_scope(:find => { :limit => 10 })
1792
+ # find(:all) # => SELECT * from articles WHERE blog_id = 1 LIMIT 10
1793
+ # end
1794
+ # with_scope(:find => { :conditions => "author_id = 3" })
1795
+ # find(:all) # => SELECT * from articles WHERE blog_id = 1 AND author_id = 3 LIMIT 1
1796
+ # end
1797
+ # end
1798
+ # end
1799
+ # end
1800
+ #
1801
+ # You can ignore any previous scopings by using the <tt>with_exclusive_scope</tt> method.
1802
+ #
1803
+ # class Article < ActiveRecord::Base
1804
+ # def self.find_with_exclusive_scope
1805
+ # with_scope(:find => { :conditions => "blog_id = 1", :limit => 1 }) do
1806
+ # with_exclusive_scope(:find => { :limit => 10 })
1807
+ # find(:all) # => SELECT * from articles LIMIT 10
1808
+ # end
1809
+ # end
1810
+ # end
1811
+ # end
1812
+ def with_scope(method_scoping = {}, action = :merge, &block)
1813
+ method_scoping = method_scoping.method_scoping if method_scoping.respond_to?(:method_scoping)
1814
+
1815
+ # Dup first and second level of hash (method and params).
1816
+ method_scoping = method_scoping.inject({}) do |hash, (method, params)|
1817
+ hash[method] = (params == true) ? params : params.dup
1818
+ hash
1819
+ end
1820
+
1821
+ method_scoping.assert_valid_keys([ :find, :create ])
1822
+
1823
+ if f = method_scoping[:find]
1824
+ f.assert_valid_keys(VALID_FIND_OPTIONS)
1825
+ set_readonly_option! f
1826
+ end
1827
+
1828
+ # Merge scopings
1829
+ if action == :merge && current_scoped_methods
1830
+ method_scoping = current_scoped_methods.inject(method_scoping) do |hash, (method, params)|
1831
+ case hash[method]
1832
+ when Hash
1833
+ if method == :find
1834
+ (hash[method].keys + params.keys).uniq.each do |key|
1835
+ merge = hash[method][key] && params[key] # merge if both scopes have the same key
1836
+ if key == :conditions && merge
1837
+ hash[method][key] = merge_conditions(params[key], hash[method][key])
1838
+ elsif key == :include && merge
1839
+ hash[method][key] = merge_includes(hash[method][key], params[key]).uniq
1840
+ else
1841
+ hash[method][key] = hash[method][key] || params[key]
1842
+ end
1843
+ end
1844
+ else
1845
+ hash[method] = params.merge(hash[method])
1846
+ end
1847
+ else
1848
+ hash[method] = params
1849
+ end
1850
+ hash
1851
+ end
1852
+ end
1853
+
1854
+ self.scoped_methods << method_scoping
1855
+
1856
+ begin
1857
+ yield
1858
+ ensure
1859
+ self.scoped_methods.pop
1860
+ end
1861
+ end
1862
+
1863
+ # Works like with_scope, but discards any nested properties.
1864
+ def with_exclusive_scope(method_scoping = {}, &block)
1865
+ with_scope(method_scoping, :overwrite, &block)
1866
+ end
1867
+
1868
+ def subclasses #:nodoc:
1869
+ @@subclasses[self] ||= []
1870
+ @@subclasses[self] + extra = @@subclasses[self].inject([]) {|list, subclass| list + subclass.subclasses }
1871
+ end
1872
+
1873
+ # Test whether the given method and optional key are scoped.
1874
+ def scoped?(method, key = nil) #:nodoc:
1875
+ if current_scoped_methods && (scope = current_scoped_methods[method])
1876
+ !key || scope.has_key?(key)
1877
+ end
1878
+ end
1879
+
1880
+ # Retrieve the scope for the given method and optional key.
1881
+ def scope(method, key = nil) #:nodoc:
1882
+ if current_scoped_methods && (scope = current_scoped_methods[method])
1883
+ key ? scope[key] : scope
1884
+ end
1885
+ end
1886
+
1887
+ def thread_safe_scoped_methods #:nodoc:
1888
+ scoped_methods = (Thread.current[:scoped_methods] ||= {})
1889
+ scoped_methods[self] ||= []
1890
+ end
1891
+
1892
+ def single_threaded_scoped_methods #:nodoc:
1893
+ @scoped_methods ||= []
1894
+ end
1895
+
1896
+ # pick up the correct scoped_methods version from @@allow_concurrency
1897
+ if @@allow_concurrency
1898
+ alias_method :scoped_methods, :thread_safe_scoped_methods
1899
+ else
1900
+ alias_method :scoped_methods, :single_threaded_scoped_methods
1901
+ end
1902
+
1903
+ def current_scoped_methods #:nodoc:
1904
+ scoped_methods.last
1905
+ end
1906
+
1907
+ # Returns the class type of the record using the current module as a prefix. So descendents of
1908
+ # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass.
1909
+ def compute_type(type_name)
1910
+ modularized_name = type_name_with_module(type_name)
1911
+ begin
1912
+ class_eval(modularized_name, __FILE__, __LINE__)
1913
+ rescue NameError
1914
+ class_eval(type_name, __FILE__, __LINE__)
1915
+ end
1916
+ end
1917
+
1918
+ # Returns the class descending directly from Active Record in the inheritance hierarchy.
1919
+ def class_of_active_record_descendant(klass)
1920
+ if klass.superclass == Base || klass.superclass.abstract_class?
1921
+ klass
1922
+ elsif klass.superclass.nil?
1923
+ raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord"
1924
+ else
1925
+ class_of_active_record_descendant(klass.superclass)
1926
+ end
1927
+ end
1928
+
1929
+ # Returns the name of the class descending directly from Active Record in the inheritance hierarchy.
1930
+ def class_name_of_active_record_descendant(klass) #:nodoc:
1931
+ klass.base_class.name
1932
+ end
1933
+
1934
+ # Accepts an array, hash, or string of SQL conditions and sanitizes
1935
+ # them into a valid SQL fragment for a WHERE clause.
1936
+ # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
1937
+ # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
1938
+ # "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
1939
+ def sanitize_sql_for_conditions(condition)
1940
+ return nil if condition.blank?
1941
+
1942
+ case condition
1943
+ when Array; sanitize_sql_array(condition)
1944
+ when Hash; sanitize_sql_hash_for_conditions(condition)
1945
+ else condition
1946
+ end
1947
+ end
1948
+ alias_method :sanitize_sql, :sanitize_sql_for_conditions
1949
+
1950
+ # Accepts an array, hash, or string of SQL conditions and sanitizes
1951
+ # them into a valid SQL fragment for a SET clause.
1952
+ # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'"
1953
+ def sanitize_sql_for_assignment(assignments)
1954
+ case assignments
1955
+ when Array; sanitize_sql_array(assignments)
1956
+ when Hash; sanitize_sql_hash_for_assignment(assignments)
1957
+ else assignments
1958
+ end
1959
+ end
1960
+
1961
+ def aggregate_mapping(reflection)
1962
+ mapping = reflection.options[:mapping] || [reflection.name, reflection.name]
1963
+ mapping.first.is_a?(Array) ? mapping : [mapping]
1964
+ end
1965
+
1966
+ # Accepts a hash of SQL conditions and replaces those attributes
1967
+ # that correspond to a +composed_of+ relationship with their expanded
1968
+ # aggregate attribute values.
1969
+ # Given:
1970
+ # class Person < ActiveRecord::Base
1971
+ # composed_of :address, :class_name => "Address",
1972
+ # :mapping => [%w(address_street street), %w(address_city city)]
1973
+ # end
1974
+ # Then:
1975
+ # { :address => Address.new("813 abc st.", "chicago") }
1976
+ # # => { :address_street => "813 abc st.", :address_city => "chicago" }
1977
+ def expand_hash_conditions_for_aggregates(attrs)
1978
+ expanded_attrs = {}
1979
+ attrs.each do |attr, value|
1980
+ unless (aggregation = reflect_on_aggregation(attr.to_sym)).nil?
1981
+ mapping = aggregate_mapping(aggregation)
1982
+ mapping.each do |field_attr, aggregate_attr|
1983
+ if mapping.size == 1 && !value.respond_to?(aggregate_attr)
1984
+ expanded_attrs[field_attr] = value
1985
+ else
1986
+ expanded_attrs[field_attr] = value.send(aggregate_attr)
1987
+ end
1988
+ end
1989
+ else
1990
+ expanded_attrs[attr] = value
1991
+ end
1992
+ end
1993
+ expanded_attrs
1994
+ end
1995
+
1996
+ # Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
1997
+ # { :name => "foo'bar", :group_id => 4 }
1998
+ # # => "name='foo''bar' and group_id= 4"
1999
+ # { :status => nil, :group_id => [1,2,3] }
2000
+ # # => "status IS NULL and group_id IN (1,2,3)"
2001
+ # { :age => 13..18 }
2002
+ # # => "age BETWEEN 13 AND 18"
2003
+ # { 'other_records.id' => 7 }
2004
+ # # => "`other_records`.`id` = 7"
2005
+ # And for value objects on a composed_of relationship:
2006
+ # { :address => Address.new("123 abc st.", "chicago") }
2007
+ # # => "address_street='123 abc st.' and address_city='chicago'"
2008
+ def sanitize_sql_hash_for_conditions(attrs)
2009
+ attrs = expand_hash_conditions_for_aggregates(attrs)
2010
+
2011
+ conditions = attrs.map do |attr, value|
2012
+ attr = attr.to_s
2013
+
2014
+ # Extract table name from qualified attribute names.
2015
+ if attr.include?('.')
2016
+ table_name, attr = attr.split('.', 2)
2017
+ table_name = connection.quote_table_name(table_name)
2018
+ else
2019
+ table_name = quoted_table_name
2020
+ end
2021
+
2022
+ "#{table_name}.#{connection.quote_column_name(attr)} #{attribute_condition(value)}"
2023
+ end.join(' AND ')
2024
+
2025
+ replace_bind_variables(conditions, expand_range_bind_variables(attrs.values))
2026
+ end
2027
+ alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
2028
+
2029
+ # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
2030
+ # { :status => nil, :group_id => 1 }
2031
+ # # => "status = NULL , group_id = 1"
2032
+ def sanitize_sql_hash_for_assignment(attrs)
2033
+ attrs.map do |attr, value|
2034
+ "#{connection.quote_column_name(attr)} = #{quote_bound_value(value)}"
2035
+ end.join(', ')
2036
+ end
2037
+
2038
+ # Accepts an array of conditions. The array has each value
2039
+ # sanitized and interpolated into the SQL statement.
2040
+ # ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
2041
+ def sanitize_sql_array(ary)
2042
+ statement, *values = ary
2043
+ if values.first.is_a?(Hash) and statement =~ /:\w+/
2044
+ replace_named_bind_variables(statement, values.first)
2045
+ elsif statement.include?('?')
2046
+ replace_bind_variables(statement, values)
2047
+ else
2048
+ statement % values.collect { |value| connection.quote_string(value.to_s) }
2049
+ end
2050
+ end
2051
+
2052
+ alias_method :sanitize_conditions, :sanitize_sql
2053
+
2054
+ def replace_bind_variables(statement, values) #:nodoc:
2055
+ raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
2056
+ bound = values.dup
2057
+ statement.gsub('?') { quote_bound_value(bound.shift) }
2058
+ end
2059
+
2060
+ def replace_named_bind_variables(statement, bind_vars) #:nodoc:
2061
+ statement.gsub(/(:?):([a-zA-Z]\w*)/) do
2062
+ if $1 == ':' # skip postgresql casts
2063
+ $& # return the whole match
2064
+ elsif bind_vars.include?(match = $2.to_sym)
2065
+ quote_bound_value(bind_vars[match])
2066
+ else
2067
+ raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
2068
+ end
2069
+ end
2070
+ end
2071
+
2072
+ def expand_range_bind_variables(bind_vars) #:nodoc:
2073
+ expanded = []
2074
+
2075
+ bind_vars.each do |var|
2076
+ if var.is_a?(Range)
2077
+ expanded << var.first
2078
+ expanded << var.last
2079
+ else
2080
+ expanded << var
2081
+ end
2082
+ end
2083
+
2084
+ expanded
2085
+ end
2086
+
2087
+ def quote_bound_value(value) #:nodoc:
2088
+ if value.respond_to?(:map) && !value.is_a?(String)
2089
+ if value.respond_to?(:empty?) && value.empty?
2090
+ connection.quote(nil)
2091
+ else
2092
+ value.map { |v| connection.quote(v) }.join(',')
2093
+ end
2094
+ else
2095
+ connection.quote(value)
2096
+ end
2097
+ end
2098
+
2099
+ def raise_if_bind_arity_mismatch(statement, expected, provided) #:nodoc:
2100
+ unless expected == provided
2101
+ raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}"
2102
+ end
2103
+ end
2104
+
2105
+ VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset,
2106
+ :order, :select, :readonly, :group, :from, :lock ]
2107
+
2108
+ def validate_find_options(options) #:nodoc:
2109
+ options.assert_valid_keys(VALID_FIND_OPTIONS)
2110
+ end
2111
+
2112
+ def set_readonly_option!(options) #:nodoc:
2113
+ # Inherit :readonly from finder scope if set. Otherwise,
2114
+ # if :joins is not blank then :readonly defaults to true.
2115
+ unless options.has_key?(:readonly)
2116
+ if scoped_readonly = scope(:find, :readonly)
2117
+ options[:readonly] = scoped_readonly
2118
+ elsif !options[:joins].blank? && !options[:select]
2119
+ options[:readonly] = true
2120
+ end
2121
+ end
2122
+ end
2123
+
2124
+ def encode_quoted_value(value) #:nodoc:
2125
+ quoted_value = connection.quote(value)
2126
+ quoted_value = "'#{quoted_value[1..-2].gsub(/\'/, "\\\\'")}'" if quoted_value.include?("\\\'") # (for ruby mode) "
2127
+ quoted_value
2128
+ end
2129
+ end
2130
+
2131
+ public
2132
+ # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
2133
+ # attributes but not yet saved (pass a hash with key names matching the associated table column names).
2134
+ # In both instances, valid attribute keys are determined by the column names of the associated table --
2135
+ # hence you can't have attributes that aren't part of the table columns.
2136
+ def initialize(attributes = nil)
2137
+ @attributes = attributes_from_column_definition
2138
+ @attributes_cache = {}
2139
+ @new_record = true
2140
+ ensure_proper_type
2141
+ self.attributes = attributes unless attributes.nil?
2142
+ self.class.send(:scope, :create).each { |att,value| self.send("#{att}=", value) } if self.class.send(:scoped?, :create)
2143
+ result = yield self if block_given?
2144
+ callback(:after_initialize) if respond_to_without_attributes?(:after_initialize)
2145
+ result
2146
+ end
2147
+
2148
+ # A model instance's primary key is always available as model.id
2149
+ # whether you name it the default 'id' or set it to something else.
2150
+ def id
2151
+ attr_name = self.class.primary_key
2152
+ column = column_for_attribute(attr_name)
2153
+
2154
+ self.class.send(:define_read_method, :id, attr_name, column)
2155
+ # now that the method exists, call it
2156
+ self.send attr_name.to_sym
2157
+
2158
+ end
2159
+
2160
+ # Enables Active Record objects to be used as URL parameters in Action Pack automatically.
2161
+ def to_param
2162
+ # We can't use alias_method here, because method 'id' optimizes itself on the fly.
2163
+ (id = self.id) ? id.to_s : nil # Be sure to stringify the id for routes
2164
+ end
2165
+
2166
+ # Returns a cache key that can be used to identify this record.
2167
+ #
2168
+ # ==== Examples
2169
+ #
2170
+ # Product.new.cache_key # => "products/new"
2171
+ # Product.find(5).cache_key # => "products/5" (updated_at not available)
2172
+ # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available)
2173
+ def cache_key
2174
+ case
2175
+ when new_record?
2176
+ "#{self.class.name.tableize}/new"
2177
+ when self[:updated_at]
2178
+ "#{self.class.name.tableize}/#{id}-#{updated_at.to_s(:number)}"
2179
+ else
2180
+ "#{self.class.name.tableize}/#{id}"
2181
+ end
2182
+ end
2183
+
2184
+ def id_before_type_cast #:nodoc:
2185
+ read_attribute_before_type_cast(self.class.primary_key)
2186
+ end
2187
+
2188
+ def quoted_id #:nodoc:
2189
+ quote_value(id, column_for_attribute(self.class.primary_key))
2190
+ end
2191
+
2192
+ # Sets the primary ID.
2193
+ def id=(value)
2194
+ write_attribute(self.class.primary_key, value)
2195
+ end
2196
+
2197
+ # Returns true if this object hasn't been saved yet -- that is, a record for the object doesn't exist yet.
2198
+ def new_record?
2199
+ defined?(@new_record) && @new_record
2200
+ end
2201
+
2202
+ # * No record exists: Creates a new record with values matching those of the object attributes.
2203
+ # * A record does exist: Updates the record with values matching those of the object attributes.
2204
+ #
2205
+ # Note: If your model specifies any validations then the method declaration dynamically
2206
+ # changes to:
2207
+ # save(perform_validation=true)
2208
+ # Calling save(false) saves the model without running validations.
2209
+ # See ActiveRecord::Validations for more information.
2210
+ def save
2211
+ create_or_update
2212
+ end
2213
+
2214
+ # Attempts to save the record, but instead of just returning false if it couldn't happen, it raises a
2215
+ # RecordNotSaved exception
2216
+ def save!
2217
+ create_or_update || raise(RecordNotSaved)
2218
+ end
2219
+
2220
+ # Deletes the record in the database and freezes this instance to reflect that no changes should
2221
+ # be made (since they can't be persisted).
2222
+ def destroy
2223
+ unless new_record?
2224
+ connection.delete <<-end_sql, "#{self.class.name} Destroy"
2225
+ DELETE FROM #{self.class.quoted_table_name}
2226
+ WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quoted_id}
2227
+ end_sql
2228
+ end
2229
+
2230
+ freeze
2231
+ end
2232
+
2233
+ # Returns a clone of the record that hasn't been assigned an id yet and
2234
+ # is treated as a new record. Note that this is a "shallow" clone:
2235
+ # it copies the object's attributes only, not its associations.
2236
+ # The extent of a "deep" clone is application-specific and is therefore
2237
+ # left to the application to implement according to its need.
2238
+ def clone
2239
+ attrs = clone_attributes(:read_attribute_before_type_cast)
2240
+ attrs.delete(self.class.primary_key)
2241
+ record = self.class.new
2242
+ record.send :instance_variable_set, '@attributes', attrs
2243
+ record
2244
+ end
2245
+
2246
+ # Returns an instance of the specified +klass+ with the attributes of the current record. This is mostly useful in relation to
2247
+ # single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record
2248
+ # identification in Action Pack to allow, say, <tt>Client < Company</tt> to do something like render <tt>:partial => @client.becomes(Company)</tt>
2249
+ # to render that instance using the companies/company partial instead of clients/client.
2250
+ #
2251
+ # Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either
2252
+ # instance will affect the other.
2253
+ def becomes(klass)
2254
+ returning klass.new do |became|
2255
+ became.instance_variable_set("@attributes", @attributes)
2256
+ became.instance_variable_set("@attributes_cache", @attributes_cache)
2257
+ became.instance_variable_set("@new_record", new_record?)
2258
+ end
2259
+ end
2260
+
2261
+ # Updates a single attribute and saves the record. This is especially useful for boolean flags on existing records.
2262
+ # Note: This method is overwritten by the Validation module that'll make sure that updates made with this method
2263
+ # aren't subjected to validation checks. Hence, attributes can be updated even if the full object isn't valid.
2264
+ def update_attribute(name, value)
2265
+ send(name.to_s + '=', value)
2266
+ save
2267
+ end
2268
+
2269
+ # Updates all the attributes from the passed-in Hash and saves the record. If the object is invalid, the saving will
2270
+ # fail and false will be returned.
2271
+ def update_attributes(attributes)
2272
+ self.attributes = attributes
2273
+ save
2274
+ end
2275
+
2276
+ # Updates an object just like Base.update_attributes but calls save! instead of save so an exception is raised if the record is invalid.
2277
+ def update_attributes!(attributes)
2278
+ self.attributes = attributes
2279
+ save!
2280
+ end
2281
+
2282
+ # Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1).
2283
+ # The increment is performed directly on the underlying attribute, no setter is invoked.
2284
+ # Only makes sense for number-based attributes. Returns +self+.
2285
+ def increment(attribute, by = 1)
2286
+ self[attribute] ||= 0
2287
+ self[attribute] += by
2288
+ self
2289
+ end
2290
+
2291
+ # Wrapper around +increment+ that saves the record. This method differs from
2292
+ # its non-bang version in that it passes through the attribute setter.
2293
+ # Saving is not subjected to validation checks. Returns +true+ if the
2294
+ # record could be saved.
2295
+ def increment!(attribute, by = 1)
2296
+ increment(attribute, by).update_attribute(attribute, self[attribute])
2297
+ end
2298
+
2299
+ # Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1).
2300
+ # The decrement is performed directly on the underlying attribute, no setter is invoked.
2301
+ # Only makes sense for number-based attributes. Returns +self+.
2302
+ def decrement(attribute, by = 1)
2303
+ self[attribute] ||= 0
2304
+ self[attribute] -= by
2305
+ self
2306
+ end
2307
+
2308
+ # Wrapper around +decrement+ that saves the record. This method differs from
2309
+ # its non-bang version in that it passes through the attribute setter.
2310
+ # Saving is not subjected to validation checks. Returns +true+ if the
2311
+ # record could be saved.
2312
+ def decrement!(attribute, by = 1)
2313
+ decrement(attribute, by).update_attribute(attribute, self[attribute])
2314
+ end
2315
+
2316
+ # Assigns to +attribute+ the boolean opposite of <tt>attribute?</tt>. So
2317
+ # if the predicate returns +true+ the attribute will become +false+. This
2318
+ # method toggles directly the underlying value without calling any setter.
2319
+ # Returns +self+.
2320
+ def toggle(attribute)
2321
+ self[attribute] = !send("#{attribute}?")
2322
+ self
2323
+ end
2324
+
2325
+ # Wrapper around +toggle+ that saves the record. This method differs from
2326
+ # its non-bang version in that it passes through the attribute setter.
2327
+ # Saving is not subjected to validation checks. Returns +true+ if the
2328
+ # record could be saved.
2329
+ def toggle!(attribute)
2330
+ toggle(attribute).update_attribute(attribute, self[attribute])
2331
+ end
2332
+
2333
+ # Reloads the attributes of this object from the database.
2334
+ # The optional options argument is passed to find when reloading so you
2335
+ # may do e.g. record.reload(:lock => true) to reload the same record with
2336
+ # an exclusive row lock.
2337
+ def reload(options = nil)
2338
+ clear_aggregation_cache
2339
+ clear_association_cache
2340
+ @attributes.update(self.class.find(self.id, options).instance_variable_get('@attributes'))
2341
+ @attributes_cache = {}
2342
+ self
2343
+ end
2344
+
2345
+ # Returns the value of the attribute identified by <tt>attr_name</tt> after it has been typecast (for example,
2346
+ # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)).
2347
+ # (Alias for the protected read_attribute method).
2348
+ def [](attr_name)
2349
+ read_attribute(attr_name)
2350
+ end
2351
+
2352
+ # Updates the attribute identified by <tt>attr_name</tt> with the specified +value+.
2353
+ # (Alias for the protected write_attribute method).
2354
+ def []=(attr_name, value)
2355
+ write_attribute(attr_name, value)
2356
+ end
2357
+
2358
+ # Allows you to set all the attributes at once by passing in a hash with keys
2359
+ # matching the attribute names (which again matches the column names). Sensitive attributes can be protected
2360
+ # from this form of mass-assignment by using the +attr_protected+ macro. Or you can alternatively
2361
+ # specify which attributes *can* be accessed with the +attr_accessible+ macro. Then all the
2362
+ # attributes not included in that won't be allowed to be mass-assigned.
2363
+ def attributes=(new_attributes, guard_protected_attributes = true)
2364
+ return if new_attributes.nil?
2365
+ attributes = new_attributes.dup
2366
+ attributes.stringify_keys!
2367
+
2368
+ multi_parameter_attributes = []
2369
+ attributes = remove_attributes_protected_from_mass_assignment(attributes) if guard_protected_attributes
2370
+
2371
+ attributes.each do |k, v|
2372
+ k.include?("(") ? multi_parameter_attributes << [ k, v ] : send(k + "=", v)
2373
+ end
2374
+
2375
+ assign_multiparameter_attributes(multi_parameter_attributes)
2376
+ end
2377
+
2378
+
2379
+ # Returns a hash of all the attributes with their names as keys and the values of the attributes as values.
2380
+ def attributes
2381
+ self.attribute_names.inject({}) do |attrs, name|
2382
+ attrs[name] = read_attribute(name)
2383
+ attrs
2384
+ end
2385
+ end
2386
+
2387
+ # Returns a hash of attributes before typecasting and deserialization.
2388
+ def attributes_before_type_cast
2389
+ self.attribute_names.inject({}) do |attrs, name|
2390
+ attrs[name] = read_attribute_before_type_cast(name)
2391
+ attrs
2392
+ end
2393
+ end
2394
+
2395
+ # Format attributes nicely for inspect.
2396
+ def attribute_for_inspect(attr_name)
2397
+ value = read_attribute(attr_name)
2398
+
2399
+ if value.is_a?(String) && value.length > 50
2400
+ "#{value[0..50]}...".inspect
2401
+ elsif value.is_a?(Date) || value.is_a?(Time)
2402
+ %("#{value.to_s(:db)}")
2403
+ else
2404
+ value.inspect
2405
+ end
2406
+ end
2407
+
2408
+ # Returns true if the specified +attribute+ has been set by the user or by a database load and is neither
2409
+ # nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings).
2410
+ def attribute_present?(attribute)
2411
+ value = read_attribute(attribute)
2412
+ !value.blank?
2413
+ end
2414
+
2415
+ # Returns true if the given attribute is in the attributes hash
2416
+ def has_attribute?(attr_name)
2417
+ @attributes.has_key?(attr_name.to_s)
2418
+ end
2419
+
2420
+ # Returns an array of names for the attributes available on this object sorted alphabetically.
2421
+ def attribute_names
2422
+ @attributes.keys.sort
2423
+ end
2424
+
2425
+ # Returns the column object for the named attribute.
2426
+ def column_for_attribute(name)
2427
+ self.class.columns_hash[name.to_s]
2428
+ end
2429
+
2430
+ # Returns true if the +comparison_object+ is the same object, or is of the same type and has the same id.
2431
+ def ==(comparison_object)
2432
+ comparison_object.equal?(self) ||
2433
+ (comparison_object.instance_of?(self.class) &&
2434
+ comparison_object.id == id &&
2435
+ !comparison_object.new_record?)
2436
+ end
2437
+
2438
+ # Delegates to ==
2439
+ def eql?(comparison_object)
2440
+ self == (comparison_object)
2441
+ end
2442
+
2443
+ # Delegates to id in order to allow two records of the same type and id to work with something like:
2444
+ # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
2445
+ def hash
2446
+ id.hash
2447
+ end
2448
+
2449
+ # Freeze the attributes hash such that associations are still accessible, even on destroyed records.
2450
+ def freeze
2451
+ @attributes.freeze; self
2452
+ end
2453
+
2454
+ # Returns +true+ if the attributes hash has been frozen.
2455
+ def frozen?
2456
+ @attributes.frozen?
2457
+ end
2458
+
2459
+ # Returns +true+ if the record is read only. Records loaded through joins with piggy-back
2460
+ # attributes will be marked as read only since they cannot be saved.
2461
+ def readonly?
2462
+ defined?(@readonly) && @readonly == true
2463
+ end
2464
+
2465
+ # Marks this record as read only.
2466
+ def readonly!
2467
+ @readonly = true
2468
+ end
2469
+
2470
+ # Returns the contents of the record as a nicely formatted string.
2471
+ def inspect
2472
+ attributes_as_nice_string = self.class.column_names.collect { |name|
2473
+ if has_attribute?(name) || new_record?
2474
+ "#{name}: #{attribute_for_inspect(name)}"
2475
+ end
2476
+ }.compact.join(", ")
2477
+ "#<#{self.class} #{attributes_as_nice_string}>"
2478
+ end
2479
+
2480
+ private
2481
+ def create_or_update
2482
+ raise ReadOnlyRecord if readonly?
2483
+ result = new_record? ? create : update
2484
+ result != false
2485
+ end
2486
+
2487
+ # Updates the associated record with values matching those of the instance attributes.
2488
+ # Returns the number of affected rows.
2489
+ def update(attribute_names = @attributes.keys)
2490
+ quoted_attributes = attributes_with_quotes(false, false, attribute_names)
2491
+ return 0 if quoted_attributes.empty?
2492
+ connection.update(
2493
+ "UPDATE #{self.class.quoted_table_name} " +
2494
+ "SET #{quoted_comma_pair_list(connection, quoted_attributes)} " +
2495
+ "WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quote_value(id)}",
2496
+ "#{self.class.name} Update"
2497
+ )
2498
+ end
2499
+
2500
+ # Creates a record with values matching those of the instance attributes
2501
+ # and returns its id.
2502
+ def create
2503
+ if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
2504
+ self.id = connection.next_sequence_value(self.class.sequence_name)
2505
+ end
2506
+
2507
+ quoted_attributes = attributes_with_quotes
2508
+
2509
+ statement = if quoted_attributes.empty?
2510
+ connection.empty_insert_statement(self.class.table_name)
2511
+ else
2512
+ "INSERT INTO #{self.class.quoted_table_name} " +
2513
+ "(#{quoted_column_names.join(', ')}) " +
2514
+ "VALUES(#{quoted_attributes.values.join(', ')})"
2515
+ end
2516
+
2517
+ self.id = connection.insert(statement, "#{self.class.name} Create",
2518
+ self.class.primary_key, self.id, self.class.sequence_name)
2519
+
2520
+ @new_record = false
2521
+ id
2522
+ end
2523
+
2524
+ # Sets the attribute used for single table inheritance to this class name if this is not the ActiveRecord::Base descendent.
2525
+ # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to do Reply.new without having to
2526
+ # set <tt>Reply[Reply.inheritance_column] = "Reply"</tt> yourself. No such attribute would be set for objects of the
2527
+ # Message class in that example.
2528
+ def ensure_proper_type
2529
+ unless self.class.descends_from_active_record?
2530
+ write_attribute(self.class.inheritance_column, self.class.sti_name)
2531
+ end
2532
+ end
2533
+
2534
+ def convert_number_column_value(value)
2535
+ case value
2536
+ when FalseClass; 0
2537
+ when TrueClass; 1
2538
+ when ''; nil
2539
+ else value
2540
+ end
2541
+ end
2542
+
2543
+ def remove_attributes_protected_from_mass_assignment(attributes)
2544
+ safe_attributes =
2545
+ if self.class.accessible_attributes.nil? && self.class.protected_attributes.nil?
2546
+ attributes.reject { |key, value| attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2547
+ elsif self.class.protected_attributes.nil?
2548
+ attributes.reject { |key, value| !self.class.accessible_attributes.include?(key.gsub(/\(.+/, "")) || attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2549
+ elsif self.class.accessible_attributes.nil?
2550
+ attributes.reject { |key, value| self.class.protected_attributes.include?(key.gsub(/\(.+/,"")) || attributes_protected_by_default.include?(key.gsub(/\(.+/, "")) }
2551
+ else
2552
+ raise "Declare either attr_protected or attr_accessible for #{self.class}, but not both."
2553
+ end
2554
+
2555
+ removed_attributes = attributes.keys - safe_attributes.keys
2556
+
2557
+ if removed_attributes.any?
2558
+ logger.debug "WARNING: Can't mass-assign these protected attributes: #{removed_attributes.join(', ')}"
2559
+ end
2560
+
2561
+ safe_attributes
2562
+ end
2563
+
2564
+ # Removes attributes which have been marked as readonly.
2565
+ def remove_readonly_attributes(attributes)
2566
+ unless self.class.readonly_attributes.nil?
2567
+ attributes.delete_if { |key, value| self.class.readonly_attributes.include?(key.gsub(/\(.+/,"")) }
2568
+ else
2569
+ attributes
2570
+ end
2571
+ end
2572
+
2573
+ # The primary key and inheritance column can never be set by mass-assignment for security reasons.
2574
+ def attributes_protected_by_default
2575
+ default = [ self.class.primary_key, self.class.inheritance_column ]
2576
+ default << 'id' unless self.class.primary_key.eql? 'id'
2577
+ default
2578
+ end
2579
+
2580
+ # Returns a copy of the attributes hash where all the values have been safely quoted for use in
2581
+ # an SQL statement.
2582
+ def attributes_with_quotes(include_primary_key = true, include_readonly_attributes = true, attribute_names = @attributes.keys)
2583
+ quoted = {}
2584
+ connection = self.class.connection
2585
+ attribute_names.each do |name|
2586
+ if (column = column_for_attribute(name)) && (include_primary_key || !column.primary)
2587
+ value = read_attribute(name)
2588
+
2589
+ # We need explicit to_yaml because quote() does not properly convert Time/Date fields to YAML.
2590
+ if value && self.class.serialized_attributes.has_key?(name) && (value.acts_like?(:date) || value.acts_like?(:time))
2591
+ value = value.to_yaml
2592
+ end
2593
+
2594
+ quoted[name] = connection.quote(value, column)
2595
+ end
2596
+ end
2597
+ include_readonly_attributes ? quoted : remove_readonly_attributes(quoted)
2598
+ end
2599
+
2600
+ # Quote strings appropriately for SQL statements.
2601
+ def quote_value(value, column = nil)
2602
+ self.class.connection.quote(value, column)
2603
+ end
2604
+
2605
+ # Interpolate custom SQL string in instance context.
2606
+ # Optional record argument is meant for custom insert_sql.
2607
+ def interpolate_sql(sql, record = nil)
2608
+ instance_eval("%@#{sql.gsub('@', '\@')}@")
2609
+ end
2610
+
2611
+ # Initializes the attributes array with keys matching the columns from the linked table and
2612
+ # the values matching the corresponding default value of that column, so
2613
+ # that a new instance, or one populated from a passed-in Hash, still has all the attributes
2614
+ # that instances loaded from the database would.
2615
+ def attributes_from_column_definition
2616
+ self.class.columns.inject({}) do |attributes, column|
2617
+ attributes[column.name] = column.default unless column.name == self.class.primary_key
2618
+ attributes
2619
+ end
2620
+ end
2621
+
2622
+ # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done
2623
+ # by calling new on the column type or aggregation type (through composed_of) object with these parameters.
2624
+ # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate
2625
+ # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the
2626
+ # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Fixnum, f for Float,
2627
+ # s for String, and a for Array. If all the values for a given attribute are empty, the attribute will be set to nil.
2628
+ def assign_multiparameter_attributes(pairs)
2629
+ execute_callstack_for_multiparameter_attributes(
2630
+ extract_callstack_for_multiparameter_attributes(pairs)
2631
+ )
2632
+ end
2633
+
2634
+ def instantiate_time_object(name, values)
2635
+ if self.class.time_zone_aware_attributes && !self.class.skip_time_zone_conversion_for_attributes.include?(name.to_sym)
2636
+ Time.zone.local(*values)
2637
+ else
2638
+ Time.time_with_datetime_fallback(@@default_timezone, *values)
2639
+ end
2640
+ end
2641
+
2642
+ def execute_callstack_for_multiparameter_attributes(callstack)
2643
+ errors = []
2644
+ callstack.each do |name, values|
2645
+ klass = (self.class.reflect_on_aggregation(name.to_sym) || column_for_attribute(name)).klass
2646
+ if values.empty?
2647
+ send(name + "=", nil)
2648
+ else
2649
+ begin
2650
+ value = if Time == klass
2651
+ instantiate_time_object(name, values)
2652
+ elsif Date == klass
2653
+ begin
2654
+ Date.new(*values)
2655
+ rescue ArgumentError => ex # if Date.new raises an exception on an invalid date
2656
+ instantiate_time_object(name, values).to_date # we instantiate Time object and convert it back to a date thus using Time's logic in handling invalid dates
2657
+ end
2658
+ else
2659
+ klass.new(*values)
2660
+ end
2661
+
2662
+ send(name + "=", value)
2663
+ rescue => ex
2664
+ errors << AttributeAssignmentError.new("error on assignment #{values.inspect} to #{name}", ex, name)
2665
+ end
2666
+ end
2667
+ end
2668
+ unless errors.empty?
2669
+ raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes"
2670
+ end
2671
+ end
2672
+
2673
+ def extract_callstack_for_multiparameter_attributes(pairs)
2674
+ attributes = { }
2675
+
2676
+ for pair in pairs
2677
+ multiparameter_name, value = pair
2678
+ attribute_name = multiparameter_name.split("(").first
2679
+ attributes[attribute_name] = [] unless attributes.include?(attribute_name)
2680
+
2681
+ unless value.empty?
2682
+ attributes[attribute_name] <<
2683
+ [ find_parameter_position(multiparameter_name), type_cast_attribute_value(multiparameter_name, value) ]
2684
+ end
2685
+ end
2686
+
2687
+ attributes.each { |name, values| attributes[name] = values.sort_by{ |v| v.first }.collect { |v| v.last } }
2688
+ end
2689
+
2690
+ def type_cast_attribute_value(multiparameter_name, value)
2691
+ multiparameter_name =~ /\([0-9]*([a-z])\)/ ? value.send("to_" + $1) : value
2692
+ end
2693
+
2694
+ def find_parameter_position(multiparameter_name)
2695
+ multiparameter_name.scan(/\(([0-9]*).*\)/).first.first
2696
+ end
2697
+
2698
+ # Returns a comma-separated pair list, like "key1 = val1, key2 = val2".
2699
+ def comma_pair_list(hash)
2700
+ hash.inject([]) { |list, pair| list << "#{pair.first} = #{pair.last}" }.join(", ")
2701
+ end
2702
+
2703
+ def quoted_column_names(attributes = attributes_with_quotes)
2704
+ connection = self.class.connection
2705
+ attributes.keys.collect do |column_name|
2706
+ connection.quote_column_name(column_name)
2707
+ end
2708
+ end
2709
+
2710
+ def self.quoted_table_name
2711
+ self.connection.quote_table_name(self.table_name)
2712
+ end
2713
+
2714
+ def quote_columns(quoter, hash)
2715
+ hash.inject({}) do |quoted, (name, value)|
2716
+ quoted[quoter.quote_column_name(name)] = value
2717
+ quoted
2718
+ end
2719
+ end
2720
+
2721
+ def quoted_comma_pair_list(quoter, hash)
2722
+ comma_pair_list(quote_columns(quoter, hash))
2723
+ end
2724
+
2725
+ def object_from_yaml(string)
2726
+ return string unless string.is_a?(String)
2727
+ YAML::load(string) rescue string
2728
+ end
2729
+
2730
+ def clone_attributes(reader_method = :read_attribute, attributes = {})
2731
+ self.attribute_names.inject(attributes) do |attrs, name|
2732
+ attrs[name] = clone_attribute_value(reader_method, name)
2733
+ attrs
2734
+ end
2735
+ end
2736
+
2737
+ def clone_attribute_value(reader_method, attribute_name)
2738
+ value = send(reader_method, attribute_name)
2739
+ value.duplicable? ? value.clone : value
2740
+ rescue TypeError, NoMethodError
2741
+ value
2742
+ end
2743
+ end
2744
+ end