diff --git a/debian/gems-compat/actioncable-5.1.7/CHANGELOG.md b/debian/gems-compat/actioncable-5.1.7/CHANGELOG.md deleted file mode 100644 index a4bff86f8d..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,118 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* No changes. - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* No changes. - - -## Rails 5.1.5 (February 14, 2018) ## - -* Support redis-rb 4.0. - - *Jeremy Daer* - - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* No changes. - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* No changes. - - -## Rails 5.1.2 (June 26, 2017) ## - -* No changes. - - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* ActionCable socket errors are now logged to the console - - Previously any socket errors were ignored and this made it hard to diagnose socket issues (e.g. as discussed in #28362). - - *Edward Poot* - -* Redis subscription adapters now support `channel_prefix` option in `cable.yml` - - Avoids channel name collisions when multiple apps use the same Redis server. - - *Chad Ingram* - -* Permit same-origin connections by default. - - Added new option `config.action_cable.allow_same_origin_as_host = false` - to disable this behaviour. - - *Dávid Halász*, *Matthew Draper* - -* Prevent race where the client could receive and act upon a - subscription confirmation before the channel's `subscribed` method - completed. - - Fixes #25381. - - *Vladimir Dementyev* - -* Buffer now writes to WebSocket connections, to avoid blocking threads - that could be doing more useful things. - - *Matthew Draper*, *Tinco Andringa* - -* Protect against concurrent writes to a WebSocket connection from - multiple threads; the underlying OS write is not always threadsafe. - - *Tinco Andringa* - -* Add `ActiveSupport::Notifications` hook to `Broadcaster#broadcast`. - - *Matthew Wear* - -* Close hijacked socket when connection is shut down. - - Fixes #25613. - - *Tinco Andringa* - - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actioncable/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/actioncable-5.1.7/MIT-LICENSE b/debian/gems-compat/actioncable-5.1.7/MIT-LICENSE deleted file mode 100644 index 1a0e653b69..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2015-2017 Basecamp, LLC - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/actioncable-5.1.7/README.md b/debian/gems-compat/actioncable-5.1.7/README.md deleted file mode 100644 index e044f54b45..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/README.md +++ /dev/null @@ -1,567 +0,0 @@ -# Action Cable – Integrated WebSockets for Rails - -Action Cable seamlessly integrates WebSockets with the rest of your Rails application. -It allows for real-time features to be written in Ruby in the same style -and form as the rest of your Rails application, while still being performant -and scalable. It's a full-stack offering that provides both a client-side -JavaScript framework and a server-side Ruby framework. You have access to your full -domain model written with Active Record or your ORM of choice. - -## Terminology - -A single Action Cable server can handle multiple connection instances. It has one -connection instance per WebSocket connection. A single user may have multiple -WebSockets open to your application if they use multiple browser tabs or devices. -The client of a WebSocket connection is called the consumer. - -Each consumer can in turn subscribe to multiple cable channels. Each channel encapsulates -a logical unit of work, similar to what a controller does in a regular MVC setup. For example, -you could have a `ChatChannel` and an `AppearancesChannel`, and a consumer could be subscribed to either -or to both of these channels. At the very least, a consumer should be subscribed to one channel. - -When the consumer is subscribed to a channel, they act as a subscriber. The connection between -the subscriber and the channel is, surprise-surprise, called a subscription. A consumer -can act as a subscriber to a given channel any number of times. For example, a consumer -could subscribe to multiple chat rooms at the same time. (And remember that a physical user may -have multiple consumers, one per tab/device open to your connection). - -Each channel can then again be streaming zero or more broadcastings. A broadcasting is a -pubsub link where anything transmitted by the broadcaster is sent directly to the channel -subscribers who are streaming that named broadcasting. - -As you can see, this is a fairly deep architectural stack. There's a lot of new terminology -to identify the new pieces, and on top of that, you're dealing with both client and server side -reflections of each unit. - -## Examples - -### A full-stack example - -The first thing you must do is define your `ApplicationCable::Connection` class in Ruby. This -is the place where you authorize the incoming connection, and proceed to establish it, -if all is well. Here's the simplest example starting with the server-side connection class: - -```ruby -# app/channels/application_cable/connection.rb -module ApplicationCable - class Connection < ActionCable::Connection::Base - identified_by :current_user - - def connect - self.current_user = find_verified_user - end - - private - def find_verified_user - if verified_user = User.find_by(id: cookies.signed[:user_id]) - verified_user - else - reject_unauthorized_connection - end - end - end -end -``` -Here `identified_by` is a connection identifier that can be used to find the specific connection again or later. -Note that anything marked as an identifier will automatically create a delegate by the same name on any channel instances created off the connection. - -This relies on the fact that you will already have handled authentication of the user, and -that a successful authentication sets a signed cookie with the `user_id`. This cookie is then -automatically sent to the connection instance when a new connection is attempted, and you -use that to set the `current_user`. By identifying the connection by this same current_user, -you're also ensuring that you can later retrieve all open connections by a given user (and -potentially disconnect them all if the user is deleted or deauthorized). - -Next, you should define your `ApplicationCable::Channel` class in Ruby. This is the place where you put -shared logic between your channels. - -```ruby -# app/channels/application_cable/channel.rb -module ApplicationCable - class Channel < ActionCable::Channel::Base - end -end -``` - -The client-side needs to setup a consumer instance of this connection. That's done like so: - -```js -// app/assets/javascripts/cable.js -//= require action_cable -//= require_self -//= require_tree ./channels - -(function() { - this.App || (this.App = {}); - - App.cable = ActionCable.createConsumer("ws://cable.example.com"); -}).call(this); -``` - -The `ws://cable.example.com` address must point to your Action Cable server(s), and it -must share a cookie namespace with the rest of the application (which may live under http://example.com). -This ensures that the signed cookie will be correctly sent. - -That's all you need to establish the connection! But of course, this isn't very useful in -itself. This just gives you the plumbing. To make stuff happen, you need content. That content -is defined by declaring channels on the server and allowing the consumer to subscribe to them. - - -### Channel example 1: User appearances - -Here's a simple example of a channel that tracks whether a user is online or not, and also what page they are currently on. -(This is useful for creating presence features like showing a green dot next to a user's name if they're online). - -First you declare the server-side channel: - -```ruby -# app/channels/appearance_channel.rb -class AppearanceChannel < ApplicationCable::Channel - def subscribed - current_user.appear - end - - def unsubscribed - current_user.disappear - end - - def appear(data) - current_user.appear on: data['appearing_on'] - end - - def away - current_user.away - end -end -``` - -The `#subscribed` callback is invoked when, as we'll show below, a client-side subscription is initiated. In this case, -we take that opportunity to say "the current user has indeed appeared". That appear/disappear API could be backed by -Redis or a database or whatever else. Here's what the client-side of that looks like: - -```coffeescript -# app/assets/javascripts/cable/subscriptions/appearance.coffee -App.cable.subscriptions.create "AppearanceChannel", - # Called when the subscription is ready for use on the server - connected: -> - @install() - @appear() - - # Called when the WebSocket connection is closed - disconnected: -> - @uninstall() - - # Called when the subscription is rejected by the server - rejected: -> - @uninstall() - - appear: -> - # Calls `AppearanceChannel#appear(data)` on the server - @perform("appear", appearing_on: $("main").data("appearing-on")) - - away: -> - # Calls `AppearanceChannel#away` on the server - @perform("away") - - - buttonSelector = "[data-behavior~=appear_away]" - - install: -> - $(document).on "turbolinks:load.appearance", => - @appear() - - $(document).on "click.appearance", buttonSelector, => - @away() - false - - $(buttonSelector).show() - - uninstall: -> - $(document).off(".appearance") - $(buttonSelector).hide() -``` - -Simply calling `App.cable.subscriptions.create` will setup the subscription, which will call `AppearanceChannel#subscribed`, -which in turn is linked to the original `App.cable` -> `ApplicationCable::Connection` instances. - -Next, we link the client-side `appear` method to `AppearanceChannel#appear(data)`. This is possible because the server-side -channel instance will automatically expose the public methods declared on the class (minus the callbacks), so that these -can be reached as remote procedure calls via a subscription's `perform` method. - -### Channel example 2: Receiving new web notifications - -The appearance example was all about exposing server functionality to client-side invocation over the WebSocket connection. -But the great thing about WebSockets is that it's a two-way street. So now let's show an example where the server invokes -an action on the client. - -This is a web notification channel that allows you to trigger client-side web notifications when you broadcast to the right -streams: - -```ruby -# app/channels/web_notifications_channel.rb -class WebNotificationsChannel < ApplicationCable::Channel - def subscribed - stream_from "web_notifications_#{current_user.id}" - end -end -``` - -```coffeescript -# Client-side, which assumes you've already requested the right to send web notifications -App.cable.subscriptions.create "WebNotificationsChannel", - received: (data) -> - new Notification data["title"], body: data["body"] -``` - -```ruby -# Somewhere in your app this is called, perhaps from a NewCommentJob -ActionCable.server.broadcast \ - "web_notifications_#{current_user.id}", { title: 'New things!', body: 'All the news that is fit to print' } -``` - -The `ActionCable.server.broadcast` call places a message in the Action Cable pubsub queue under a separate broadcasting name for each user. For a user with an ID of 1, the broadcasting name would be `web_notifications_1`. -The channel has been instructed to stream everything that arrives at `web_notifications_1` directly to the client by invoking the -`#received(data)` callback. The data is the hash sent as the second parameter to the server-side broadcast call, JSON encoded for the trip -across the wire, and unpacked for the data argument arriving to `#received`. - - -### Passing Parameters to Channel - -You can pass parameters from the client side to the server side when creating a subscription. For example: - -```ruby -# app/channels/chat_channel.rb -class ChatChannel < ApplicationCable::Channel - def subscribed - stream_from "chat_#{params[:room]}" - end -end -``` - -If you pass an object as the first argument to `subscriptions.create`, that object will become the params hash in your cable channel. The keyword `channel` is required. - -```coffeescript -# Client-side, which assumes you've already requested the right to send web notifications -App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" }, - received: (data) -> - @appendLine(data) - - appendLine: (data) -> - html = @createLine(data) - $("[data-chat-room='Best Room']").append(html) - - createLine: (data) -> - """ -
- #{data["sent_by"]} - #{data["body"]} -
- """ -``` - -```ruby -# Somewhere in your app this is called, perhaps from a NewCommentJob -ActionCable.server.broadcast \ - "chat_#{room}", { sent_by: 'Paul', body: 'This is a cool chat app.' } -``` - - -### Rebroadcasting message - -A common use case is to rebroadcast a message sent by one client to any other connected clients. - -```ruby -# app/channels/chat_channel.rb -class ChatChannel < ApplicationCable::Channel - def subscribed - stream_from "chat_#{params[:room]}" - end - - def receive(data) - ActionCable.server.broadcast "chat_#{params[:room]}", data - end -end -``` - -```coffeescript -# Client-side, which assumes you've already requested the right to send web notifications -App.chatChannel = App.cable.subscriptions.create { channel: "ChatChannel", room: "Best Room" }, - received: (data) -> - # data => { sent_by: "Paul", body: "This is a cool chat app." } - -App.chatChannel.send({ sent_by: "Paul", body: "This is a cool chat app." }) -``` - -The rebroadcast will be received by all connected clients, _including_ the client that sent the message. Note that params are the same as they were when you subscribed to the channel. - - -### More complete examples - -See the [rails/actioncable-examples](https://github.com/rails/actioncable-examples) repository for a full example of how to setup Action Cable in a Rails app, and how to add channels. - -## Configuration - -Action Cable has three required configurations: a subscription adapter, allowed request origins, and the cable server URL (which can optionally be set on the client side). - -### Redis - -By default, `ActionCable::Server::Base` will look for a configuration file in `Rails.root.join('config/cable.yml')`. -This file must specify an adapter and a URL for each Rails environment. It may use the following format: - -```yaml -production: &production - adapter: redis - url: redis://10.10.3.153:6381 -development: &development - adapter: redis - url: redis://localhost:6379 -test: *development -``` - -You can also change the location of the Action Cable config file in a Rails initializer with something like: - -```ruby -Rails.application.paths.add "config/cable", with: "somewhere/else/cable.yml" -``` - -### Allowed Request Origins - -Action Cable will only accept requests from specific origins. - -By default, only an origin matching the cable server itself will be permitted. -Additional origins can be specified using strings or regular expressions, provided in an array. - -```ruby -Rails.application.config.action_cable.allowed_request_origins = ['http://rubyonrails.com', /http:\/\/ruby.*/] -``` - -When running in the development environment, this defaults to "http://localhost:3000". - -To disable protection and allow requests from any origin: - -```ruby -Rails.application.config.action_cable.disable_request_forgery_protection = true -``` - -To disable automatic access for same-origin requests, and strictly allow -only the configured origins: - -```ruby -Rails.application.config.action_cable.allow_same_origin_as_host = false -``` - -### Consumer Configuration - -Once you have decided how to run your cable server (see below), you must provide the server URL (or path) to your client-side setup. -There are two ways you can do this. - -The first is to simply pass it in when creating your consumer. For a standalone server, -this would be something like: `App.cable = ActionCable.createConsumer("ws://example.com:28080")`, and for an in-app server, -something like: `App.cable = ActionCable.createConsumer("/cable")`. - -The second option is to pass the server URL through the `action_cable_meta_tag` in your layout. -This uses a URL or path typically set via `config.action_cable.url` in the environment configuration files, or defaults to "/cable". - -This method is especially useful if your WebSocket URL might change between environments. If you host your production server via https, you will need to use the wss scheme -for your Action Cable server, but development might remain http and use the ws scheme. You might use localhost in development and your -domain in production. - -In any case, to vary the WebSocket URL between environments, add the following configuration to each environment: - -```ruby -config.action_cable.url = "ws://example.com:28080" -``` - -Then add the following line to your layout before your JavaScript tag: - -```erb -<%= action_cable_meta_tag %> -``` - -And finally, create your consumer like so: - -```coffeescript -App.cable = ActionCable.createConsumer() -``` - -### Other Configurations - -The other common option to configure is the log tags applied to the per-connection logger. Here's an example that uses the user account id if available, else "no-account" while tagging: - -```ruby -config.action_cable.log_tags = [ - -> request { request.env['user_account_id'] || "no-account" }, - :action_cable, - -> request { request.uuid } -] -``` - -For a full list of all configuration options, see the `ActionCable::Server::Configuration` class. - -Also note that your server must provide at least the same number of database connections as you have workers. The default worker pool is set to 4, so that means you have to make at least that available. You can change that in `config/database.yml` through the `pool` attribute. - - -## Running the cable server - -### Standalone -The cable server(s) is separated from your normal application server. It's still a Rack application, but it is its own Rack -application. The recommended basic setup is as follows: - -```ruby -# cable/config.ru -require ::File.expand_path('../../config/environment', __FILE__) -Rails.application.eager_load! - -run ActionCable.server -``` - -Then you start the server using a binstub in bin/cable ala: -```sh -#!/bin/bash -bundle exec puma -p 28080 cable/config.ru -``` - -The above will start a cable server on port 28080. - -### In app - -If you are using a server that supports the [Rack socket hijacking API](http://www.rubydoc.info/github/rack/rack/file/SPEC#Hijacking), Action Cable can run alongside your Rails application. For example, to listen for WebSocket requests on `/websocket`, specify that path to `config.action_cable.mount_path`: - -```ruby -# config/application.rb -class Application < Rails::Application - config.action_cable.mount_path = '/websocket' -end -``` - -For every instance of your server you create and for every worker your server spawns, you will also have a new instance of Action Cable, but the use of Redis keeps messages synced across connections. - -### Notes - -Beware that currently, the cable server will _not_ auto-reload any changes in the framework. As we've discussed, long-running cable connections mean long-running objects. We don't yet have a way of reloading the classes of those objects in a safe manner. So when you change your channels, or the model your channels use, you must restart the cable server. - -We'll get all this abstracted properly when the framework is integrated into Rails. - -The WebSocket server doesn't have access to the session, but it has access to the cookies. This can be used when you need to handle authentication. You can see one way of doing that with Devise in this [article](http://www.rubytutorial.io/actioncable-devise-authentication). - -## Dependencies - -Action Cable provides a subscription adapter interface to process its pubsub internals. By default, asynchronous, inline, PostgreSQL, evented Redis, and non-evented Redis adapters are included. The default adapter in new Rails applications is the asynchronous (`async`) adapter. To create your own adapter, you can look at `ActionCable::SubscriptionAdapter::Base` for all methods that must be implemented, and any of the adapters included within Action Cable as example implementations. - -The Ruby side of things is built on top of [websocket-driver](https://github.com/faye/websocket-driver-ruby), [nio4r](https://github.com/celluloid/nio4r), and [concurrent-ruby](https://github.com/ruby-concurrency/concurrent-ruby). - - -## Deployment - -Action Cable is powered by a combination of WebSockets and threads. All of the -connection management is handled internally by utilizing Ruby’s native thread -support, which means you can use all your regular Rails models with no problems -as long as you haven’t committed any thread-safety sins. - -The Action Cable server does _not_ need to be a multi-threaded application server. -This is because Action Cable uses the [Rack socket hijacking API](http://www.rubydoc.info/github/rack/rack/file/SPEC#Hijacking) -to take over control of connections from the application server. Action Cable -then manages connections internally, in a multithreaded manner, regardless of -whether the application server is multi-threaded or not. So Action Cable works -with all the popular application servers -- Unicorn, Puma and Passenger. - -Action Cable does not work with WEBrick, because WEBrick does not support the -Rack socket hijacking API. - -## Frontend assets - -Action Cable's frontend assets are distributed through two channels: the -official gem and npm package, both titled `actioncable`. - -### Gem usage - -Through the `actioncable` gem, Action Cable's frontend assets are -available through the Rails Asset Pipeline. Create a `cable.js` or -`cable.coffee` file (this is automatically done for you with Rails -generators), and then simply require the assets: - -In JavaScript... - -```javascript -//= require action_cable -``` - -... and in CoffeeScript: - -```coffeescript -#= require action_cable -``` - -### npm usage - -In addition to being available through the `actioncable` gem, Action Cable's -frontend JS assets are also bundled in an officially supported npm module, -intended for usage in standalone frontend applications that communicate with a -Rails application. A common use case for this could be if you have a decoupled -frontend application written in React, Ember.js, etc. and want to add real-time -WebSocket functionality. - -### Installation - -``` -npm install actioncable --save -``` - -### Usage - -The `ActionCable` constant is available as a `require`-able module, so -you only have to require the package to gain access to the API that is -provided. - -In JavaScript... - -```javascript -ActionCable = require('actioncable') - -var cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable') - -cable.subscriptions.create('AppearanceChannel', { - // normal channel code goes here... -}); -``` - -and in CoffeeScript... - -```coffeescript -ActionCable = require('actioncable') - -cable = ActionCable.createConsumer('wss://RAILS-API-PATH.com/cable') - -cable.subscriptions.create 'AppearanceChannel', - # normal channel code goes here... -``` - -## Download and Installation - -The latest version of Action Cable can be installed with [RubyGems](#gem-usage), -or with [npm](#npm-usage). - -Source code can be downloaded as part of the Rails project on GitHub - -* https://github.com/rails/rails/tree/master/actioncable - -## License - -Action Cable is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -## Support - -API documentation is at: - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/actioncable-5.1.7/actioncable.gemspec b/debian/gems-compat/actioncable-5.1.7/actioncable.gemspec deleted file mode 100644 index e1a14cf728..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/actioncable.gemspec +++ /dev/null @@ -1,42 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: actioncable 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "actioncable".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/actioncable/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/actioncable" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["Pratik Naik".freeze, "David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "Structure many real-time application concerns into channels over a single WebSocket connection.".freeze - s.email = ["pratiknaik@gmail.com".freeze, "david@loudthinking.com".freeze] - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.md".freeze, "lib/action_cable.rb".freeze, "lib/action_cable/channel.rb".freeze, "lib/action_cable/channel/base.rb".freeze, "lib/action_cable/channel/broadcasting.rb".freeze, "lib/action_cable/channel/callbacks.rb".freeze, "lib/action_cable/channel/naming.rb".freeze, "lib/action_cable/channel/periodic_timers.rb".freeze, "lib/action_cable/channel/streams.rb".freeze, "lib/action_cable/connection.rb".freeze, "lib/action_cable/connection/authorization.rb".freeze, "lib/action_cable/connection/base.rb".freeze, "lib/action_cable/connection/client_socket.rb".freeze, "lib/action_cable/connection/identification.rb".freeze, "lib/action_cable/connection/internal_channel.rb".freeze, "lib/action_cable/connection/message_buffer.rb".freeze, "lib/action_cable/connection/stream.rb".freeze, "lib/action_cable/connection/stream_event_loop.rb".freeze, "lib/action_cable/connection/subscriptions.rb".freeze, "lib/action_cable/connection/tagged_logger_proxy.rb".freeze, "lib/action_cable/connection/web_socket.rb".freeze, "lib/action_cable/engine.rb".freeze, "lib/action_cable/gem_version.rb".freeze, "lib/action_cable/helpers/action_cable_helper.rb".freeze, "lib/action_cable/remote_connections.rb".freeze, "lib/action_cable/server.rb".freeze, "lib/action_cable/server/base.rb".freeze, "lib/action_cable/server/broadcasting.rb".freeze, "lib/action_cable/server/configuration.rb".freeze, "lib/action_cable/server/connections.rb".freeze, "lib/action_cable/server/worker.rb".freeze, "lib/action_cable/server/worker/active_record_connection_management.rb".freeze, "lib/action_cable/subscription_adapter.rb".freeze, "lib/action_cable/subscription_adapter/async.rb".freeze, "lib/action_cable/subscription_adapter/base.rb".freeze, "lib/action_cable/subscription_adapter/channel_prefix.rb".freeze, "lib/action_cable/subscription_adapter/evented_redis.rb".freeze, "lib/action_cable/subscription_adapter/inline.rb".freeze, "lib/action_cable/subscription_adapter/postgresql.rb".freeze, "lib/action_cable/subscription_adapter/redis.rb".freeze, "lib/action_cable/subscription_adapter/subscriber_map.rb".freeze, "lib/action_cable/version.rb".freeze, "lib/assets/compiled/action_cable.js".freeze, "lib/rails/generators/channel/USAGE".freeze, "lib/rails/generators/channel/channel_generator.rb".freeze, "lib/rails/generators/channel/templates/application_cable/channel.rb".freeze, "lib/rails/generators/channel/templates/application_cable/connection.rb".freeze, "lib/rails/generators/channel/templates/assets/cable.js".freeze, "lib/rails/generators/channel/templates/assets/channel.coffee".freeze, "lib/rails/generators/channel/templates/assets/channel.js".freeze, "lib/rails/generators/channel/templates/channel.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.rubygems_version = "2.7.6.2".freeze - s.summary = "WebSocket framework for Rails.".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["~> 2.0"]) - s.add_runtime_dependency(%q.freeze, ["~> 0.6.1"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, ["~> 0.6.1"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, ["~> 0.6.1"]) - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable.rb deleted file mode 100644 index c2d3550acb..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable.rb +++ /dev/null @@ -1,52 +0,0 @@ -#-- -# Copyright (c) 2015-2017 Basecamp, LLC -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "active_support" -require "active_support/rails" -require "action_cable/version" - -module ActionCable - extend ActiveSupport::Autoload - - INTERNAL = { - message_types: { - welcome: "welcome".freeze, - ping: "ping".freeze, - confirmation: "confirm_subscription".freeze, - rejection: "reject_subscription".freeze - }, - default_mount_path: "/cable".freeze, - protocols: ["actioncable-v1-json".freeze, "actioncable-unsupported".freeze].freeze - } - - # Singleton instance of the server - module_function def server - @server ||= ActionCable::Server::Base.new - end - - autoload :Server - autoload :Connection - autoload :Channel - autoload :RemoteConnections - autoload :SubscriptionAdapter -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel.rb deleted file mode 100644 index 7ae262ce5f..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel.rb +++ /dev/null @@ -1,14 +0,0 @@ -module ActionCable - module Channel - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Base - autoload :Broadcasting - autoload :Callbacks - autoload :Naming - autoload :PeriodicTimers - autoload :Streams - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/base.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/base.rb deleted file mode 100644 index 718f630f58..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/base.rb +++ /dev/null @@ -1,301 +0,0 @@ -require "set" - -module ActionCable - module Channel - # The channel provides the basic structure of grouping behavior into logical units when communicating over the WebSocket connection. - # You can think of a channel like a form of controller, but one that's capable of pushing content to the subscriber in addition to simply - # responding to the subscriber's direct requests. - # - # Channel instances are long-lived. A channel object will be instantiated when the cable consumer becomes a subscriber, and then - # lives until the consumer disconnects. This may be seconds, minutes, hours, or even days. That means you have to take special care - # not to do anything silly in a channel that would balloon its memory footprint or whatever. The references are forever, so they won't be released - # as is normally the case with a controller instance that gets thrown away after every request. - # - # Long-lived channels (and connections) also mean you're responsible for ensuring that the data is fresh. If you hold a reference to a user - # record, but the name is changed while that reference is held, you may be sending stale data if you don't take precautions to avoid it. - # - # The upside of long-lived channel instances is that you can use instance variables to keep reference to objects that future subscriber requests - # can interact with. Here's a quick example: - # - # class ChatChannel < ApplicationCable::Channel - # def subscribed - # @room = Chat::Room[params[:room_number]] - # end - # - # def speak(data) - # @room.speak data, user: current_user - # end - # end - # - # The #speak action simply uses the Chat::Room object that was created when the channel was first subscribed to by the consumer when that - # subscriber wants to say something in the room. - # - # == Action processing - # - # Unlike subclasses of ActionController::Base, channels do not follow a RESTful - # constraint form for their actions. Instead, Action Cable operates through a - # remote-procedure call model. You can declare any public method on the - # channel (optionally taking a data argument), and this method is - # automatically exposed as callable to the client. - # - # Example: - # - # class AppearanceChannel < ApplicationCable::Channel - # def subscribed - # @connection_token = generate_connection_token - # end - # - # def unsubscribed - # current_user.disappear @connection_token - # end - # - # def appear(data) - # current_user.appear @connection_token, on: data['appearing_on'] - # end - # - # def away - # current_user.away @connection_token - # end - # - # private - # def generate_connection_token - # SecureRandom.hex(36) - # end - # end - # - # In this example, the subscribed and unsubscribed methods are not callable methods, as they - # were already declared in ActionCable::Channel::Base, but #appear - # and #away are. #generate_connection_token is also not - # callable, since it's a private method. You'll see that appear accepts a data - # parameter, which it then uses as part of its model call. #away - # does not, since it's simply a trigger action. - # - # Also note that in this example, current_user is available because - # it was marked as an identifying attribute on the connection. All such - # identifiers will automatically create a delegation method of the same name - # on the channel instance. - # - # == Rejecting subscription requests - # - # A channel can reject a subscription request in the #subscribed callback by - # invoking the #reject method: - # - # class ChatChannel < ApplicationCable::Channel - # def subscribed - # @room = Chat::Room[params[:room_number]] - # reject unless current_user.can_access?(@room) - # end - # end - # - # In this example, the subscription will be rejected if the - # current_user does not have access to the chat room. On the - # client-side, the Channel#rejected callback will get invoked when - # the server rejects the subscription request. - class Base - include Callbacks - include PeriodicTimers - include Streams - include Naming - include Broadcasting - - attr_reader :params, :connection, :identifier - delegate :logger, to: :connection - - class << self - # A list of method names that should be considered actions. This - # includes all public instance methods on a channel, less - # any internal methods (defined on Base), adding back in - # any methods that are internal, but still exist on the class - # itself. - # - # ==== Returns - # * Set - A set of all methods that should be considered actions. - def action_methods - @action_methods ||= begin - # All public instance methods of this class, including ancestors - methods = (public_instance_methods(true) - - # Except for public instance methods of Base and its ancestors - ActionCable::Channel::Base.public_instance_methods(true) + - # Be sure to include shadowed public instance methods of this class - public_instance_methods(false)).uniq.map(&:to_s) - methods.to_set - end - end - - private - # action_methods are cached and there is sometimes need to refresh - # them. ::clear_action_methods! allows you to do that, so next time - # you run action_methods, they will be recalculated. - def clear_action_methods! # :doc: - @action_methods = nil - end - - # Refresh the cached action_methods when a new action_method is added. - def method_added(name) # :doc: - super - clear_action_methods! - end - end - - def initialize(connection, identifier, params = {}) - @connection = connection - @identifier = identifier - @params = params - - # When a channel is streaming via pubsub, we want to delay the confirmation - # transmission until pubsub subscription is confirmed. - # - # The counter starts at 1 because it's awaiting a call to #subscribe_to_channel - @defer_subscription_confirmation_counter = Concurrent::AtomicFixnum.new(1) - - @reject_subscription = nil - @subscription_confirmation_sent = nil - - delegate_connection_identifiers - end - - # Extract the action name from the passed data and process it via the channel. The process will ensure - # that the action requested is a public method on the channel declared by the user (so not one of the callbacks - # like #subscribed). - def perform_action(data) - action = extract_action(data) - - if processable_action?(action) - payload = { channel_class: self.class.name, action: action, data: data } - ActiveSupport::Notifications.instrument("perform_action.action_cable", payload) do - dispatch_action(action, data) - end - else - logger.error "Unable to process #{action_signature(action, data)}" - end - end - - # This method is called after subscription has been added to the connection - # and confirms or rejects the subscription. - def subscribe_to_channel - run_callbacks :subscribe do - subscribed - end - - reject_subscription if subscription_rejected? - ensure_confirmation_sent - end - - # Called by the cable connection when it's cut, so the channel has a chance to cleanup with callbacks. - # This method is not intended to be called directly by the user. Instead, overwrite the #unsubscribed callback. - def unsubscribe_from_channel # :nodoc: - run_callbacks :unsubscribe do - unsubscribed - end - end - - private - # Called once a consumer has become a subscriber of the channel. Usually the place to setup any streams - # you want this channel to be sending to the subscriber. - def subscribed # :doc: - # Override in subclasses - end - - # Called once a consumer has cut its cable connection. Can be used for cleaning up connections or marking - # users as offline or the like. - def unsubscribed # :doc: - # Override in subclasses - end - - # Transmit a hash of data to the subscriber. The hash will automatically be wrapped in a JSON envelope with - # the proper channel identifier marked as the recipient. - def transmit(data, via: nil) # :doc: - logger.debug "#{self.class.name} transmitting #{data.inspect.truncate(300)}".tap { |m| m << " (via #{via})" if via } - - payload = { channel_class: self.class.name, data: data, via: via } - ActiveSupport::Notifications.instrument("transmit.action_cable", payload) do - connection.transmit identifier: @identifier, message: data - end - end - - def ensure_confirmation_sent # :doc: - return if subscription_rejected? - @defer_subscription_confirmation_counter.decrement - transmit_subscription_confirmation unless defer_subscription_confirmation? - end - - def defer_subscription_confirmation! # :doc: - @defer_subscription_confirmation_counter.increment - end - - def defer_subscription_confirmation? # :doc: - @defer_subscription_confirmation_counter.value > 0 - end - - def subscription_confirmation_sent? # :doc: - @subscription_confirmation_sent - end - - def reject # :doc: - @reject_subscription = true - end - - def subscription_rejected? # :doc: - @reject_subscription - end - - def delegate_connection_identifiers - connection.identifiers.each do |identifier| - define_singleton_method(identifier) do - connection.send(identifier) - end - end - end - - def extract_action(data) - (data["action"].presence || :receive).to_sym - end - - def processable_action?(action) - self.class.action_methods.include?(action.to_s) unless subscription_rejected? - end - - def dispatch_action(action, data) - logger.info action_signature(action, data) - - if method(action).arity == 1 - public_send action, data - else - public_send action - end - end - - def action_signature(action, data) - "#{self.class.name}##{action}".tap do |signature| - if (arguments = data.except("action")).any? - signature << "(#{arguments.inspect})" - end - end - end - - def transmit_subscription_confirmation - unless subscription_confirmation_sent? - logger.info "#{self.class.name} is transmitting the subscription confirmation" - - ActiveSupport::Notifications.instrument("transmit_subscription_confirmation.action_cable", channel_class: self.class.name) do - connection.transmit identifier: @identifier, type: ActionCable::INTERNAL[:message_types][:confirmation] - @subscription_confirmation_sent = true - end - end - end - - def reject_subscription - connection.subscriptions.remove_subscription self - transmit_subscription_rejection - end - - def transmit_subscription_rejection - logger.info "#{self.class.name} is transmitting the subscription rejection" - - ActiveSupport::Notifications.instrument("transmit_subscription_rejection.action_cable", channel_class: self.class.name) do - connection.transmit identifier: @identifier, type: ActionCable::INTERNAL[:message_types][:rejection] - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/broadcasting.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/broadcasting.rb deleted file mode 100644 index 23ed4ec943..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/broadcasting.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "active_support/core_ext/object/to_param" - -module ActionCable - module Channel - module Broadcasting - extend ActiveSupport::Concern - - delegate :broadcasting_for, to: :class - - class_methods do - # Broadcast a hash to a unique broadcasting for this model in this channel. - def broadcast_to(model, message) - ActionCable.server.broadcast(broadcasting_for([ channel_name, model ]), message) - end - - def broadcasting_for(model) #:nodoc: - case - when model.is_a?(Array) - model.map { |m| broadcasting_for(m) }.join(":") - when model.respond_to?(:to_gid_param) - model.to_gid_param - else - model.to_param - end - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/callbacks.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/callbacks.rb deleted file mode 100644 index c740132c94..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/callbacks.rb +++ /dev/null @@ -1,35 +0,0 @@ -require "active_support/callbacks" - -module ActionCable - module Channel - module Callbacks - extend ActiveSupport::Concern - include ActiveSupport::Callbacks - - included do - define_callbacks :subscribe - define_callbacks :unsubscribe - end - - class_methods do - def before_subscribe(*methods, &block) - set_callback(:subscribe, :before, *methods, &block) - end - - def after_subscribe(*methods, &block) - set_callback(:subscribe, :after, *methods, &block) - end - alias_method :on_subscribe, :after_subscribe - - def before_unsubscribe(*methods, &block) - set_callback(:unsubscribe, :before, *methods, &block) - end - - def after_unsubscribe(*methods, &block) - set_callback(:unsubscribe, :after, *methods, &block) - end - alias_method :on_unsubscribe, :after_unsubscribe - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/naming.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/naming.rb deleted file mode 100644 index b565cb3cac..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/naming.rb +++ /dev/null @@ -1,23 +0,0 @@ -module ActionCable - module Channel - module Naming - extend ActiveSupport::Concern - - class_methods do - # Returns the name of the channel, underscored, without the Channel ending. - # If the channel is in a namespace, then the namespaces are represented by single - # colon separators in the channel name. - # - # ChatChannel.channel_name # => 'chat' - # Chats::AppearancesChannel.channel_name # => 'chats:appearances' - # FooChats::BarAppearancesChannel.channel_name # => 'foo_chats:bar_appearances' - def channel_name - @channel_name ||= name.sub(/Channel$/, "").gsub("::", ":").underscore - end - end - - # Delegates to the class' channel_name - delegate :channel_name, to: :class - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/periodic_timers.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/periodic_timers.rb deleted file mode 100644 index c9daa0bcd3..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/periodic_timers.rb +++ /dev/null @@ -1,77 +0,0 @@ -module ActionCable - module Channel - module PeriodicTimers - extend ActiveSupport::Concern - - included do - class_attribute :periodic_timers, instance_reader: false - self.periodic_timers = [] - - after_subscribe :start_periodic_timers - after_unsubscribe :stop_periodic_timers - end - - module ClassMethods - # Periodically performs a task on the channel, like updating an online - # user counter, polling a backend for new status messages, sending - # regular "heartbeat" messages, or doing some internal work and giving - # progress updates. - # - # Pass a method name or lambda argument or provide a block to call. - # Specify the calling period in seconds using the every: - # keyword argument. - # - # periodically :transmit_progress, every: 5.seconds - # - # periodically every: 3.minutes do - # transmit action: :update_count, count: current_count - # end - # - def periodically(callback_or_method_name = nil, every:, &block) - callback = - if block_given? - raise ArgumentError, "Pass a block or provide a callback arg, not both" if callback_or_method_name - block - else - case callback_or_method_name - when Proc - callback_or_method_name - when Symbol - -> { __send__ callback_or_method_name } - else - raise ArgumentError, "Expected a Symbol method name or a Proc, got #{callback_or_method_name.inspect}" - end - end - - unless every.kind_of?(Numeric) && every > 0 - raise ArgumentError, "Expected every: to be a positive number of seconds, got #{every.inspect}" - end - - self.periodic_timers += [[ callback, every: every ]] - end - end - - private - def active_periodic_timers - @active_periodic_timers ||= [] - end - - def start_periodic_timers - self.class.periodic_timers.each do |callback, options| - active_periodic_timers << start_periodic_timer(callback, every: options.fetch(:every)) - end - end - - def start_periodic_timer(callback, every:) - connection.server.event_loop.timer every do - connection.worker_pool.async_exec self, connection: connection, &callback - end - end - - def stop_periodic_timers - active_periodic_timers.each { |timer| timer.shutdown } - active_periodic_timers.clear - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/streams.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/streams.rb deleted file mode 100644 index dbba333353..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/channel/streams.rb +++ /dev/null @@ -1,174 +0,0 @@ -module ActionCable - module Channel - # Streams allow channels to route broadcastings to the subscriber. A broadcasting is, as discussed elsewhere, a pubsub queue where any data - # placed into it is automatically sent to the clients that are connected at that time. It's purely an online queue, though. If you're not - # streaming a broadcasting at the very moment it sends out an update, you will not get that update, even if you connect after it has been sent. - # - # Most commonly, the streamed broadcast is sent straight to the subscriber on the client-side. The channel just acts as a connector between - # the two parties (the broadcaster and the channel subscriber). Here's an example of a channel that allows subscribers to get all new - # comments on a given page: - # - # class CommentsChannel < ApplicationCable::Channel - # def follow(data) - # stream_from "comments_for_#{data['recording_id']}" - # end - # - # def unfollow - # stop_all_streams - # end - # end - # - # Based on the above example, the subscribers of this channel will get whatever data is put into the, - # let's say, comments_for_45 broadcasting as soon as it's put there. - # - # An example broadcasting for this channel looks like so: - # - # ActionCable.server.broadcast "comments_for_45", author: 'DHH', content: 'Rails is just swell' - # - # If you have a stream that is related to a model, then the broadcasting used can be generated from the model and channel. - # The following example would subscribe to a broadcasting like comments:Z2lkOi8vVGVzdEFwcC9Qb3N0LzE. - # - # class CommentsChannel < ApplicationCable::Channel - # def subscribed - # post = Post.find(params[:id]) - # stream_for post - # end - # end - # - # You can then broadcast to this channel using: - # - # CommentsChannel.broadcast_to(@post, @comment) - # - # If you don't just want to parlay the broadcast unfiltered to the subscriber, you can also supply a callback that lets you alter what is sent out. - # The below example shows how you can use this to provide performance introspection in the process: - # - # class ChatChannel < ApplicationCable::Channel - # def subscribed - # @room = Chat::Room[params[:room_number]] - # - # stream_for @room, coder: ActiveSupport::JSON do |message| - # if message['originated_at'].present? - # elapsed_time = (Time.now.to_f - message['originated_at']).round(2) - # - # ActiveSupport::Notifications.instrument :performance, measurement: 'Chat.message_delay', value: elapsed_time, action: :timing - # logger.info "Message took #{elapsed_time}s to arrive" - # end - # - # transmit message - # end - # end - # end - # - # You can stop streaming from all broadcasts by calling #stop_all_streams. - module Streams - extend ActiveSupport::Concern - - included do - on_unsubscribe :stop_all_streams - end - - # Start streaming from the named broadcasting pubsub queue. Optionally, you can pass a callback that'll be used - # instead of the default of just transmitting the updates straight to the subscriber. - # Pass coder: ActiveSupport::JSON to decode messages as JSON before passing to the callback. - # Defaults to coder: nil which does no decoding, passes raw messages. - def stream_from(broadcasting, callback = nil, coder: nil, &block) - broadcasting = String(broadcasting) - - # Don't send the confirmation until pubsub#subscribe is successful - defer_subscription_confirmation! - - # Build a stream handler by wrapping the user-provided callback with - # a decoder or defaulting to a JSON-decoding retransmitter. - handler = worker_pool_stream_handler(broadcasting, callback || block, coder: coder) - streams << [ broadcasting, handler ] - - connection.server.event_loop.post do - pubsub.subscribe(broadcasting, handler, lambda do - ensure_confirmation_sent - logger.info "#{self.class.name} is streaming from #{broadcasting}" - end) - end - end - - # Start streaming the pubsub queue for the model in this channel. Optionally, you can pass a - # callback that'll be used instead of the default of just transmitting the updates straight - # to the subscriber. - # - # Pass coder: ActiveSupport::JSON to decode messages as JSON before passing to the callback. - # Defaults to coder: nil which does no decoding, passes raw messages. - def stream_for(model, callback = nil, coder: nil, &block) - stream_from(broadcasting_for([ channel_name, model ]), callback || block, coder: coder) - end - - # Unsubscribes all streams associated with this channel from the pubsub queue. - def stop_all_streams - streams.each do |broadcasting, callback| - pubsub.unsubscribe broadcasting, callback - logger.info "#{self.class.name} stopped streaming from #{broadcasting}" - end.clear - end - - private - delegate :pubsub, to: :connection - - def streams - @_streams ||= [] - end - - # Always wrap the outermost handler to invoke the user handler on the - # worker pool rather than blocking the event loop. - def worker_pool_stream_handler(broadcasting, user_handler, coder: nil) - handler = stream_handler(broadcasting, user_handler, coder: coder) - - -> message do - connection.worker_pool.async_invoke handler, :call, message, connection: connection - end - end - - # May be overridden to add instrumentation, logging, specialized error - # handling, or other forms of handler decoration. - # - # TODO: Tests demonstrating this. - def stream_handler(broadcasting, user_handler, coder: nil) - if user_handler - stream_decoder user_handler, coder: coder - else - default_stream_handler broadcasting, coder: coder - end - end - - # May be overridden to change the default stream handling behavior - # which decodes JSON and transmits to the client. - # - # TODO: Tests demonstrating this. - # - # TODO: Room for optimization. Update transmit API to be coder-aware - # so we can no-op when pubsub and connection are both JSON-encoded. - # Then we can skip decode+encode if we're just proxying messages. - def default_stream_handler(broadcasting, coder:) - coder ||= ActiveSupport::JSON - stream_transmitter stream_decoder(coder: coder), broadcasting: broadcasting - end - - def stream_decoder(handler = identity_handler, coder:) - if coder - -> message { handler.(coder.decode(message)) } - else - handler - end - end - - def stream_transmitter(handler = identity_handler, broadcasting:) - via = "streamed from #{broadcasting}" - - -> (message) do - transmit handler.(message), via: via - end - end - - def identity_handler - -> message { message } - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection.rb deleted file mode 100644 index 902efb07e2..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActionCable - module Connection - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Authorization - autoload :Base - autoload :ClientSocket - autoload :Identification - autoload :InternalChannel - autoload :MessageBuffer - autoload :Stream - autoload :StreamEventLoop - autoload :Subscriptions - autoload :TaggedLoggerProxy - autoload :WebSocket - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/authorization.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/authorization.rb deleted file mode 100644 index 989a67d6df..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/authorization.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActionCable - module Connection - module Authorization - class UnauthorizedError < StandardError; end - - # Closes the \WebSocket connection if it is open and returns a 404 "File not Found" response. - def reject_unauthorized_connection - logger.error "An unauthorized connection attempt was rejected" - raise UnauthorizedError - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/base.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/base.rb deleted file mode 100644 index ac5f405dea..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/base.rb +++ /dev/null @@ -1,258 +0,0 @@ -require "action_dispatch" - -module ActionCable - module Connection - # For every WebSocket connection the Action Cable server accepts, a Connection object will be instantiated. This instance becomes the parent - # of all of the channel subscriptions that are created from there on. Incoming messages are then routed to these channel subscriptions - # based on an identifier sent by the Action Cable consumer. The Connection itself does not deal with any specific application logic beyond - # authentication and authorization. - # - # Here's a basic example: - # - # module ApplicationCable - # class Connection < ActionCable::Connection::Base - # identified_by :current_user - # - # def connect - # self.current_user = find_verified_user - # logger.add_tags current_user.name - # end - # - # def disconnect - # # Any cleanup work needed when the cable connection is cut. - # end - # - # private - # def find_verified_user - # User.find_by_identity(cookies.signed[:identity_id]) || - # reject_unauthorized_connection - # end - # end - # end - # - # First, we declare that this connection can be identified by its current_user. This allows us to later be able to find all connections - # established for that current_user (and potentially disconnect them). You can declare as many - # identification indexes as you like. Declaring an identification means that an attr_accessor is automatically set for that key. - # - # Second, we rely on the fact that the WebSocket connection is established with the cookies from the domain being sent along. This makes - # it easy to use signed cookies that were set when logging in via a web interface to authorize the WebSocket connection. - # - # Finally, we add a tag to the connection-specific logger with the name of the current user to easily distinguish their messages in the log. - # - # Pretty simple, eh? - class Base - include Identification - include InternalChannel - include Authorization - - attr_reader :server, :env, :subscriptions, :logger, :worker_pool, :protocol - delegate :event_loop, :pubsub, to: :server - - def initialize(server, env, coder: ActiveSupport::JSON) - @server, @env, @coder = server, env, coder - - @worker_pool = server.worker_pool - @logger = new_tagged_logger - - @websocket = ActionCable::Connection::WebSocket.new(env, self, event_loop) - @subscriptions = ActionCable::Connection::Subscriptions.new(self) - @message_buffer = ActionCable::Connection::MessageBuffer.new(self) - - @_internal_subscriptions = nil - @started_at = Time.now - end - - # Called by the server when a new WebSocket connection is established. This configures the callbacks intended for overwriting by the user. - # This method should not be called directly -- instead rely upon on the #connect (and #disconnect) callbacks. - def process #:nodoc: - logger.info started_request_message - - if websocket.possible? && allow_request_origin? - respond_to_successful_request - else - respond_to_invalid_request - end - end - - # Decodes WebSocket messages and dispatches them to subscribed channels. - # WebSocket message transfer encoding is always JSON. - def receive(websocket_message) #:nodoc: - send_async :dispatch_websocket_message, websocket_message - end - - def dispatch_websocket_message(websocket_message) #:nodoc: - if websocket.alive? - subscriptions.execute_command decode(websocket_message) - else - logger.error "Ignoring message processed after the WebSocket was closed: #{websocket_message.inspect})" - end - end - - def transmit(cable_message) # :nodoc: - websocket.transmit encode(cable_message) - end - - # Close the WebSocket connection. - def close - websocket.close - end - - # Invoke a method on the connection asynchronously through the pool of thread workers. - def send_async(method, *arguments) - worker_pool.async_invoke(self, method, *arguments) - end - - # Return a basic hash of statistics for the connection keyed with identifier, started_at, subscriptions, and request_id. - # This can be returned by a health check against the connection. - def statistics - { - identifier: connection_identifier, - started_at: @started_at, - subscriptions: subscriptions.identifiers, - request_id: @env["action_dispatch.request_id"] - } - end - - def beat - transmit type: ActionCable::INTERNAL[:message_types][:ping], message: Time.now.to_i - end - - def on_open # :nodoc: - send_async :handle_open - end - - def on_message(message) # :nodoc: - message_buffer.append message - end - - def on_error(message) # :nodoc: - # log errors to make diagnosing socket errors easier - logger.error "WebSocket error occurred: #{message}" - end - - def on_close(reason, code) # :nodoc: - send_async :handle_close - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - attr_reader :websocket - attr_reader :message_buffer - - private - # The request that initiated the WebSocket connection is available here. This gives access to the environment, cookies, etc. - def request # :doc: - @request ||= begin - environment = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application - ActionDispatch::Request.new(environment || env) - end - end - - # The cookies of the request that initiated the WebSocket connection. Useful for performing authorization checks. - def cookies # :doc: - request.cookie_jar - end - - def encode(cable_message) - @coder.encode cable_message - end - - def decode(websocket_message) - @coder.decode websocket_message - end - - def handle_open - @protocol = websocket.protocol - connect if respond_to?(:connect) - subscribe_to_internal_channel - send_welcome_message - - message_buffer.process! - server.add_connection(self) - rescue ActionCable::Connection::Authorization::UnauthorizedError - respond_to_invalid_request - end - - def handle_close - logger.info finished_request_message - - server.remove_connection(self) - - subscriptions.unsubscribe_from_all - unsubscribe_from_internal_channel - - disconnect if respond_to?(:disconnect) - end - - def send_welcome_message - # Send welcome message to the internal connection monitor channel. - # This ensures the connection monitor state is reset after a successful - # websocket connection. - transmit type: ActionCable::INTERNAL[:message_types][:welcome] - end - - def allow_request_origin? - return true if server.config.disable_request_forgery_protection - - proto = Rack::Request.new(env).ssl? ? "https" : "http" - if server.config.allow_same_origin_as_host && env["HTTP_ORIGIN"] == "#{proto}://#{env['HTTP_HOST']}" - true - elsif Array(server.config.allowed_request_origins).any? { |allowed_origin| allowed_origin === env["HTTP_ORIGIN"] } - true - else - logger.error("Request origin not allowed: #{env['HTTP_ORIGIN']}") - false - end - end - - def respond_to_successful_request - logger.info successful_request_message - websocket.rack_response - end - - def respond_to_invalid_request - close if websocket.alive? - - logger.error invalid_request_message - logger.info finished_request_message - [ 404, { "Content-Type" => "text/plain" }, [ "Page not found" ] ] - end - - # Tags are declared in the server but computed in the connection. This allows us per-connection tailored tags. - def new_tagged_logger - TaggedLoggerProxy.new server.logger, - tags: server.config.log_tags.map { |tag| tag.respond_to?(:call) ? tag.call(request) : tag.to_s.camelize } - end - - def started_request_message - 'Started %s "%s"%s for %s at %s' % [ - request.request_method, - request.filtered_path, - websocket.possible? ? " [WebSocket]" : "[non-WebSocket]", - request.ip, - Time.now.to_s ] - end - - def finished_request_message - 'Finished "%s"%s for %s at %s' % [ - request.filtered_path, - websocket.possible? ? " [WebSocket]" : "[non-WebSocket]", - request.ip, - Time.now.to_s ] - end - - def invalid_request_message - "Failed to upgrade to WebSocket (REQUEST_METHOD: %s, HTTP_CONNECTION: %s, HTTP_UPGRADE: %s)" % [ - env["REQUEST_METHOD"], env["HTTP_CONNECTION"], env["HTTP_UPGRADE"] - ] - end - - def successful_request_message - "Successfully upgraded to WebSocket (REQUEST_METHOD: %s, HTTP_CONNECTION: %s, HTTP_UPGRADE: %s)" % [ - env["REQUEST_METHOD"], env["HTTP_CONNECTION"], env["HTTP_UPGRADE"] - ] - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/client_socket.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/client_socket.rb deleted file mode 100644 index c7e30e78c8..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/client_socket.rb +++ /dev/null @@ -1,155 +0,0 @@ -require "websocket/driver" - -module ActionCable - module Connection - #-- - # This class is heavily based on faye-websocket-ruby - # - # Copyright (c) 2010-2015 James Coglan - class ClientSocket # :nodoc: - def self.determine_url(env) - scheme = secure_request?(env) ? "wss:" : "ws:" - "#{ scheme }//#{ env['HTTP_HOST'] }#{ env['REQUEST_URI'] }" - end - - def self.secure_request?(env) - return true if env["HTTPS"] == "on" - return true if env["HTTP_X_FORWARDED_SSL"] == "on" - return true if env["HTTP_X_FORWARDED_SCHEME"] == "https" - return true if env["HTTP_X_FORWARDED_PROTO"] == "https" - return true if env["rack.url_scheme"] == "https" - - return false - end - - CONNECTING = 0 - OPEN = 1 - CLOSING = 2 - CLOSED = 3 - - attr_reader :env, :url - - def initialize(env, event_target, event_loop, protocols) - @env = env - @event_target = event_target - @event_loop = event_loop - - @url = ClientSocket.determine_url(@env) - - @driver = @driver_started = nil - @close_params = ["", 1006] - - @ready_state = CONNECTING - - # The driver calls +env+, +url+, and +write+ - @driver = ::WebSocket::Driver.rack(self, protocols: protocols) - - @driver.on(:open) { |e| open } - @driver.on(:message) { |e| receive_message(e.data) } - @driver.on(:close) { |e| begin_close(e.reason, e.code) } - @driver.on(:error) { |e| emit_error(e.message) } - - @stream = ActionCable::Connection::Stream.new(@event_loop, self) - end - - def start_driver - return if @driver.nil? || @driver_started - @stream.hijack_rack_socket - - if callback = @env["async.callback"] - callback.call([101, {}, @stream]) - end - - @driver_started = true - @driver.start - end - - def rack_response - start_driver - [ -1, {}, [] ] - end - - def write(data) - @stream.write(data) - rescue => e - emit_error e.message - end - - def transmit(message) - return false if @ready_state > OPEN - case message - when Numeric then @driver.text(message.to_s) - when String then @driver.text(message) - when Array then @driver.binary(message) - else false - end - end - - def close(code = nil, reason = nil) - code ||= 1000 - reason ||= "" - - unless code == 1000 || (code >= 3000 && code <= 4999) - raise ArgumentError, "Failed to execute 'close' on WebSocket: " \ - "The code must be either 1000, or between 3000 and 4999. " \ - "#{code} is neither." - end - - @ready_state = CLOSING unless @ready_state == CLOSED - @driver.close(reason, code) - end - - def parse(data) - @driver.parse(data) - end - - def client_gone - finalize_close - end - - def alive? - @ready_state == OPEN - end - - def protocol - @driver.protocol - end - - private - def open - return unless @ready_state == CONNECTING - @ready_state = OPEN - - @event_target.on_open - end - - def receive_message(data) - return unless @ready_state == OPEN - - @event_target.on_message(data) - end - - def emit_error(message) - return if @ready_state >= CLOSING - - @event_target.on_error(message) - end - - def begin_close(reason, code) - return if @ready_state == CLOSED - @ready_state = CLOSING - @close_params = [reason, code] - - @stream.shutdown if @stream - finalize_close - end - - def finalize_close - return if @ready_state == CLOSED - @ready_state = CLOSED - - @event_target.on_close(*@close_params) - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/identification.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/identification.rb deleted file mode 100644 index c91a1d1fd7..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/identification.rb +++ /dev/null @@ -1,46 +0,0 @@ -require "set" - -module ActionCable - module Connection - module Identification - extend ActiveSupport::Concern - - included do - class_attribute :identifiers - self.identifiers = Set.new - end - - class_methods do - # Mark a key as being a connection identifier index that can then be used to find the specific connection again later. - # Common identifiers are current_user and current_account, but could be anything, really. - # - # Note that anything marked as an identifier will automatically create a delegate by the same name on any - # channel instances created off the connection. - def identified_by(*identifiers) - Array(identifiers).each { |identifier| attr_accessor identifier } - self.identifiers += identifiers - end - end - - # Return a single connection identifier that combines the value of all the registered identifiers into a single gid. - def connection_identifier - unless defined? @connection_identifier - @connection_identifier = connection_gid identifiers.map { |id| instance_variable_get("@#{id}") }.compact - end - - @connection_identifier - end - - private - def connection_gid(ids) - ids.map do |o| - if o.respond_to? :to_gid_param - o.to_gid_param - else - o.to_s - end - end.sort.join(":") - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/internal_channel.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/internal_channel.rb deleted file mode 100644 index 8f0ec766c3..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/internal_channel.rb +++ /dev/null @@ -1,43 +0,0 @@ -module ActionCable - module Connection - # Makes it possible for the RemoteConnection to disconnect a specific connection. - module InternalChannel - extend ActiveSupport::Concern - - private - def internal_channel - "action_cable/#{connection_identifier}" - end - - def subscribe_to_internal_channel - if connection_identifier.present? - callback = -> (message) { process_internal_message decode(message) } - @_internal_subscriptions ||= [] - @_internal_subscriptions << [ internal_channel, callback ] - - server.event_loop.post { pubsub.subscribe(internal_channel, callback) } - logger.info "Registered connection (#{connection_identifier})" - end - end - - def unsubscribe_from_internal_channel - if @_internal_subscriptions.present? - @_internal_subscriptions.each { |channel, callback| server.event_loop.post { pubsub.unsubscribe(channel, callback) } } - end - end - - def process_internal_message(message) - case message["type"] - when "disconnect" - logger.info "Removing connection (#{connection_identifier})" - websocket.close - end - rescue Exception => e - logger.error "There was an exception - #{e.class}(#{e.message})" - logger.error e.backtrace.join("\n") - - close - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/message_buffer.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/message_buffer.rb deleted file mode 100644 index 4ccd322644..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/message_buffer.rb +++ /dev/null @@ -1,55 +0,0 @@ -module ActionCable - module Connection - # Allows us to buffer messages received from the WebSocket before the Connection has been fully initialized, and is ready to receive them. - class MessageBuffer # :nodoc: - def initialize(connection) - @connection = connection - @buffered_messages = [] - end - - def append(message) - if valid? message - if processing? - receive message - else - buffer message - end - else - connection.logger.error "Couldn't handle non-string message: #{message.class}" - end - end - - def processing? - @processing - end - - def process! - @processing = true - receive_buffered_messages - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - attr_reader :connection - attr_reader :buffered_messages - - private - def valid?(message) - message.is_a?(String) - end - - def receive(message) - connection.receive message - end - - def buffer(message) - buffered_messages << message - end - - def receive_buffered_messages - receive buffered_messages.shift until buffered_messages.empty? - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/stream.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/stream.rb deleted file mode 100644 index e620b93845..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/stream.rb +++ /dev/null @@ -1,113 +0,0 @@ -require "thread" - -module ActionCable - module Connection - #-- - # This class is heavily based on faye-websocket-ruby - # - # Copyright (c) 2010-2015 James Coglan - class Stream # :nodoc: - def initialize(event_loop, socket) - @event_loop = event_loop - @socket_object = socket - @stream_send = socket.env["stream.send"] - - @rack_hijack_io = nil - @write_lock = Mutex.new - - @write_head = nil - @write_buffer = Queue.new - end - - def each(&callback) - @stream_send ||= callback - end - - def close - shutdown - @socket_object.client_gone - end - - def shutdown - clean_rack_hijack - end - - def write(data) - if @stream_send - return @stream_send.call(data) - end - - if @write_lock.try_lock - begin - if @write_head.nil? && @write_buffer.empty? - written = @rack_hijack_io.write_nonblock(data, exception: false) - - case written - when :wait_writable - # proceed below - when data.bytesize - return data.bytesize - else - @write_head = data.byteslice(written, data.bytesize) - @event_loop.writes_pending @rack_hijack_io - - return data.bytesize - end - end - ensure - @write_lock.unlock - end - end - - @write_buffer << data - @event_loop.writes_pending @rack_hijack_io - - data.bytesize - rescue EOFError, Errno::ECONNRESET - @socket_object.client_gone - end - - def flush_write_buffer - @write_lock.synchronize do - loop do - if @write_head.nil? - return true if @write_buffer.empty? - @write_head = @write_buffer.pop - end - - written = @rack_hijack_io.write_nonblock(@write_head, exception: false) - case written - when :wait_writable - return false - when @write_head.bytesize - @write_head = nil - else - @write_head = @write_head.byteslice(written, @write_head.bytesize) - return false - end - end - end - end - - def receive(data) - @socket_object.parse(data) - end - - def hijack_rack_socket - return unless @socket_object.env["rack.hijack"] - - @socket_object.env["rack.hijack"].call - @rack_hijack_io = @socket_object.env["rack.hijack_io"] - - @event_loop.attach(@rack_hijack_io, self) - end - - private - def clean_rack_hijack - return unless @rack_hijack_io - @event_loop.detach(@rack_hijack_io, self) - @rack_hijack_io = nil - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/stream_event_loop.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/stream_event_loop.rb deleted file mode 100644 index 2d1af0ff9f..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/stream_event_loop.rb +++ /dev/null @@ -1,134 +0,0 @@ -require "nio" -require "thread" - -module ActionCable - module Connection - class StreamEventLoop - def initialize - @nio = @executor = @thread = nil - @map = {} - @stopping = false - @todo = Queue.new - - @spawn_mutex = Mutex.new - end - - def timer(interval, &block) - Concurrent::TimerTask.new(execution_interval: interval, &block).tap(&:execute) - end - - def post(task = nil, &block) - task ||= block - - spawn - @executor << task - end - - def attach(io, stream) - @todo << lambda do - @map[io] = @nio.register(io, :r) - @map[io].value = stream - end - wakeup - end - - def detach(io, stream) - @todo << lambda do - @nio.deregister io - @map.delete io - io.close - end - wakeup - end - - def writes_pending(io) - @todo << lambda do - if monitor = @map[io] - monitor.interests = :rw - end - end - wakeup - end - - def stop - @stopping = true - wakeup if @nio - end - - private - def spawn - return if @thread && @thread.status - - @spawn_mutex.synchronize do - return if @thread && @thread.status - - @nio ||= NIO::Selector.new - - @executor ||= Concurrent::ThreadPoolExecutor.new( - min_threads: 1, - max_threads: 10, - max_queue: 0, - ) - - @thread = Thread.new { run } - - return true - end - end - - def wakeup - spawn || @nio.wakeup - end - - def run - loop do - if @stopping - @nio.close - break - end - - until @todo.empty? - @todo.pop(true).call - end - - next unless monitors = @nio.select - - monitors.each do |monitor| - io = monitor.io - stream = monitor.value - - begin - if monitor.writable? - if stream.flush_write_buffer - monitor.interests = :r - end - next unless monitor.readable? - end - - incoming = io.read_nonblock(4096, exception: false) - case incoming - when :wait_readable - next - when nil - stream.close - else - stream.receive incoming - end - rescue - # We expect one of EOFError or Errno::ECONNRESET in - # normal operation (when the client goes away). But if - # anything else goes wrong, this is still the best way - # to handle it. - begin - stream.close - rescue - @nio.deregister io - @map.delete io - end - end - end - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/subscriptions.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/subscriptions.rb deleted file mode 100644 index 44bce1e195..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/subscriptions.rb +++ /dev/null @@ -1,81 +0,0 @@ -require "active_support/core_ext/hash/indifferent_access" - -module ActionCable - module Connection - # Collection class for all the channel subscriptions established on a given connection. Responsible for routing incoming commands that arrive on - # the connection to the proper channel. - class Subscriptions # :nodoc: - def initialize(connection) - @connection = connection - @subscriptions = {} - end - - def execute_command(data) - case data["command"] - when "subscribe" then add data - when "unsubscribe" then remove data - when "message" then perform_action data - else - logger.error "Received unrecognized command in #{data.inspect}" - end - rescue Exception => e - logger.error "Could not execute command from (#{data.inspect}) [#{e.class} - #{e.message}]: #{e.backtrace.first(5).join(" | ")}" - end - - def add(data) - id_key = data["identifier"] - id_options = ActiveSupport::JSON.decode(id_key).with_indifferent_access - - return if subscriptions.key?(id_key) - - subscription_klass = id_options[:channel].safe_constantize - - if subscription_klass && ActionCable::Channel::Base >= subscription_klass - subscription = subscription_klass.new(connection, id_key, id_options) - subscriptions[id_key] = subscription - subscription.subscribe_to_channel - else - logger.error "Subscription class not found: #{id_options[:channel].inspect}" - end - end - - def remove(data) - logger.info "Unsubscribing from channel: #{data['identifier']}" - remove_subscription subscriptions[data["identifier"]] - end - - def remove_subscription(subscription) - subscription.unsubscribe_from_channel - subscriptions.delete(subscription.identifier) - end - - def perform_action(data) - find(data).perform_action ActiveSupport::JSON.decode(data["data"]) - end - - def identifiers - subscriptions.keys - end - - def unsubscribe_from_all - subscriptions.each { |id, channel| remove_subscription(channel) } - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - attr_reader :connection, :subscriptions - - private - delegate :logger, to: :connection - - def find(data) - if subscription = subscriptions[data["identifier"]] - subscription - else - raise "Unable to find subscription with identifier: #{data['identifier']}" - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/tagged_logger_proxy.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/tagged_logger_proxy.rb deleted file mode 100644 index aef549aa86..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/tagged_logger_proxy.rb +++ /dev/null @@ -1,40 +0,0 @@ -module ActionCable - module Connection - # Allows the use of per-connection tags against the server logger. This wouldn't work using the traditional - # ActiveSupport::TaggedLogging enhanced Rails.logger, as that logger will reset the tags between requests. - # The connection is long-lived, so it needs its own set of tags for its independent duration. - class TaggedLoggerProxy - attr_reader :tags - - def initialize(logger, tags:) - @logger = logger - @tags = tags.flatten - end - - def add_tags(*tags) - @tags += tags.flatten - @tags = @tags.uniq - end - - def tag(logger) - if logger.respond_to?(:tagged) - current_tags = tags - logger.formatter.current_tags - logger.tagged(*current_tags) { yield } - else - yield - end - end - - %i( debug info warn error fatal unknown ).each do |severity| - define_method(severity) do |message| - log severity, message - end - end - - private - def log(type, message) # :doc: - tag(@logger) { @logger.send type, message } - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/web_socket.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/web_socket.rb deleted file mode 100644 index 03eb6e2ea8..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/connection/web_socket.rb +++ /dev/null @@ -1,41 +0,0 @@ -require "websocket/driver" - -module ActionCable - module Connection - # Wrap the real socket to minimize the externally-presented API - class WebSocket - def initialize(env, event_target, event_loop, protocols: ActionCable::INTERNAL[:protocols]) - @websocket = ::WebSocket::Driver.websocket?(env) ? ClientSocket.new(env, event_target, event_loop, protocols) : nil - end - - def possible? - websocket - end - - def alive? - websocket && websocket.alive? - end - - def transmit(data) - websocket.transmit data - end - - def close - websocket.close - end - - def protocol - websocket.protocol - end - - def rack_response - websocket.rack_response - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - attr_reader :websocket - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/engine.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/engine.rb deleted file mode 100644 index 63a26636a0..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/engine.rb +++ /dev/null @@ -1,77 +0,0 @@ -require "rails" -require "action_cable" -require "action_cable/helpers/action_cable_helper" -require "active_support/core_ext/hash/indifferent_access" - -module ActionCable - class Engine < Rails::Engine # :nodoc: - config.action_cable = ActiveSupport::OrderedOptions.new - config.action_cable.mount_path = ActionCable::INTERNAL[:default_mount_path] - - config.eager_load_namespaces << ActionCable - - initializer "action_cable.helpers" do - ActiveSupport.on_load(:action_view) do - include ActionCable::Helpers::ActionCableHelper - end - end - - initializer "action_cable.logger" do - ActiveSupport.on_load(:action_cable) { self.logger ||= ::Rails.logger } - end - - initializer "action_cable.set_configs" do |app| - options = app.config.action_cable - options.allowed_request_origins ||= /https?:\/\/localhost:\d+/ if ::Rails.env.development? - - app.paths.add "config/cable", with: "config/cable.yml" - - ActiveSupport.on_load(:action_cable) do - if (config_path = Pathname.new(app.config.paths["config/cable"].first)).exist? - self.cable = Rails.application.config_for(config_path).with_indifferent_access - end - - previous_connection_class = connection_class - self.connection_class = -> { "ApplicationCable::Connection".safe_constantize || previous_connection_class.call } - - options.each { |k, v| send("#{k}=", v) } - end - end - - initializer "action_cable.routes" do - config.after_initialize do |app| - config = app.config - unless config.action_cable.mount_path.nil? - app.routes.prepend do - mount ActionCable.server => config.action_cable.mount_path, internal: true - end - end - end - end - - initializer "action_cable.set_work_hooks" do |app| - ActiveSupport.on_load(:action_cable) do - ActionCable::Server::Worker.set_callback :work, :around, prepend: true do |_, inner| - app.executor.wrap do - # If we took a while to get the lock, we may have been halted - # in the meantime. As we haven't started doing any real work - # yet, we should pretend that we never made it off the queue. - unless stopping? - inner.call - end - end - end - - wrap = lambda do |_, inner| - app.executor.wrap(&inner) - end - ActionCable::Channel::Base.set_callback :subscribe, :around, prepend: true, &wrap - ActionCable::Channel::Base.set_callback :unsubscribe, :around, prepend: true, &wrap - - app.reloader.before_class_unload do - ActionCable.server.restart - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/gem_version.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/gem_version.rb deleted file mode 100644 index d088e7faf2..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActionCable - # Returns the version of the currently loaded Action Cable as a Gem::Version. - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/helpers/action_cable_helper.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/helpers/action_cable_helper.rb deleted file mode 100644 index f53be0bc31..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/helpers/action_cable_helper.rb +++ /dev/null @@ -1,40 +0,0 @@ -module ActionCable - module Helpers - module ActionCableHelper - # Returns an "action-cable-url" meta tag with the value of the URL specified in your - # configuration. Ensure this is above your JavaScript tag: - # - # - # <%= action_cable_meta_tag %> - # <%= javascript_include_tag 'application', 'data-turbolinks-track' => 'reload' %> - # - # - # This is then used by Action Cable to determine the URL of your WebSocket server. - # Your CoffeeScript can then connect to the server without needing to specify the - # URL directly: - # - # #= require cable - # @App = {} - # App.cable = Cable.createConsumer() - # - # Make sure to specify the correct server location in each of your environment - # config files: - # - # config.action_cable.mount_path = "/cable123" - # <%= action_cable_meta_tag %> would render: - # => - # - # config.action_cable.url = "ws://actioncable.com" - # <%= action_cable_meta_tag %> would render: - # => - # - def action_cable_meta_tag - tag "meta", name: "action-cable-url", content: ( - ActionCable.server.config.url || - ActionCable.server.config.mount_path || - raise("No Action Cable URL configured -- please configure this at config.action_cable.url") - ) - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/remote_connections.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/remote_connections.rb deleted file mode 100644 index d2856bc6ae..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/remote_connections.rb +++ /dev/null @@ -1,66 +0,0 @@ -module ActionCable - # If you need to disconnect a given connection, you can go through the - # RemoteConnections. You can find the connections you're looking for by - # searching for the identifier declared on the connection. For example: - # - # module ApplicationCable - # class Connection < ActionCable::Connection::Base - # identified_by :current_user - # .... - # end - # end - # - # ActionCable.server.remote_connections.where(current_user: User.find(1)).disconnect - # - # This will disconnect all the connections established for - # User.find(1), across all servers running on all machines, because - # it uses the internal channel that all of these servers are subscribed to. - class RemoteConnections - attr_reader :server - - def initialize(server) - @server = server - end - - def where(identifier) - RemoteConnection.new(server, identifier) - end - - private - # Represents a single remote connection found via ActionCable.server.remote_connections.where(*). - # Exists solely for the purpose of calling #disconnect on that connection. - class RemoteConnection - class InvalidIdentifiersError < StandardError; end - - include Connection::Identification, Connection::InternalChannel - - def initialize(server, ids) - @server = server - set_identifier_instance_vars(ids) - end - - # Uses the internal channel to disconnect the connection. - def disconnect - server.broadcast internal_channel, type: "disconnect" - end - - # Returns all the identifiers that were applied to this connection. - def identifiers - server.connection_identifiers - end - - private - attr_reader :server - - def set_identifier_instance_vars(ids) - raise InvalidIdentifiersError unless valid_identifiers?(ids) - ids.each { |k, v| instance_variable_set("@#{k}", v) } - end - - def valid_identifiers?(ids) - keys = ids.keys - identifiers.all? { |id| keys.include?(id) } - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server.rb deleted file mode 100644 index 22f9353825..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActionCable - module Server - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Base - autoload :Broadcasting - autoload :Connections - autoload :Configuration - - autoload :Worker - autoload :ActiveRecordConnectionManagement, "action_cable/server/worker/active_record_connection_management" - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/base.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/base.rb deleted file mode 100644 index 419eccd73c..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/base.rb +++ /dev/null @@ -1,87 +0,0 @@ -require "monitor" - -module ActionCable - module Server - # A singleton ActionCable::Server instance is available via ActionCable.server. It's used by the Rack process that starts the Action Cable server, but - # is also used by the user to reach the RemoteConnections object, which is used for finding and disconnecting connections across all servers. - # - # Also, this is the server instance used for broadcasting. See Broadcasting for more information. - class Base - include ActionCable::Server::Broadcasting - include ActionCable::Server::Connections - - cattr_accessor(:config, instance_accessor: true) { ActionCable::Server::Configuration.new } - - def self.logger; config.logger; end - delegate :logger, to: :config - - attr_reader :mutex - - def initialize - @mutex = Monitor.new - @remote_connections = @event_loop = @worker_pool = @pubsub = nil - end - - # Called by Rack to setup the server. - def call(env) - setup_heartbeat_timer - config.connection_class.call.new(self, env).process - end - - # Disconnect all the connections identified by `identifiers` on this server or any others via RemoteConnections. - def disconnect(identifiers) - remote_connections.where(identifiers).disconnect - end - - def restart - connections.each(&:close) - - @mutex.synchronize do - # Shutdown the worker pool - @worker_pool.halt if @worker_pool - @worker_pool = nil - - # Shutdown the pub/sub adapter - @pubsub.shutdown if @pubsub - @pubsub = nil - end - end - - # Gateway to RemoteConnections. See that class for details. - def remote_connections - @remote_connections || @mutex.synchronize { @remote_connections ||= RemoteConnections.new(self) } - end - - def event_loop - @event_loop || @mutex.synchronize { @event_loop ||= ActionCable::Connection::StreamEventLoop.new } - end - - # The worker pool is where we run connection callbacks and channel actions. We do as little as possible on the server's main thread. - # The worker pool is an executor service that's backed by a pool of threads working from a task queue. The thread pool size maxes out - # at 4 worker threads by default. Tune the size yourself with config.action_cable.worker_pool_size. - # - # Using Active Record, Redis, etc within your channel actions means you'll get a separate connection from each thread in the worker pool. - # Plan your deployment accordingly: 5 servers each running 5 Puma workers each running an 8-thread worker pool means at least 200 database - # connections. - # - # Also, ensure that your database connection pool size is as least as large as your worker pool size. Otherwise, workers may oversubscribe - # the database connection pool and block while they wait for other workers to release their connections. Use a smaller worker pool or a larger - # database connection pool instead. - def worker_pool - @worker_pool || @mutex.synchronize { @worker_pool ||= ActionCable::Server::Worker.new(max_size: config.worker_pool_size) } - end - - # Adapter used for all streams/broadcasting. - def pubsub - @pubsub || @mutex.synchronize { @pubsub ||= config.pubsub_adapter.new(self) } - end - - # All of the identifiers applied to the connection class associated with this server. - def connection_identifiers - config.connection_class.call.identifiers - end - end - - ActiveSupport.run_load_hooks(:action_cable, Base.config) - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/broadcasting.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/broadcasting.rb deleted file mode 100644 index 7fcd6c6587..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/broadcasting.rb +++ /dev/null @@ -1,52 +0,0 @@ -module ActionCable - module Server - # Broadcasting is how other parts of your application can send messages to a channel's subscribers. As explained in Channel, most of the time, these - # broadcastings are streamed directly to the clients subscribed to the named broadcasting. Let's explain with a full-stack example: - # - # class WebNotificationsChannel < ApplicationCable::Channel - # def subscribed - # stream_from "web_notifications_#{current_user.id}" - # end - # end - # - # # Somewhere in your app this is called, perhaps from a NewCommentJob: - # ActionCable.server.broadcast \ - # "web_notifications_1", { title: "New things!", body: "All that's fit for print" } - # - # # Client-side CoffeeScript, which assumes you've already requested the right to send web notifications: - # App.cable.subscriptions.create "WebNotificationsChannel", - # received: (data) -> - # new Notification data['title'], body: data['body'] - module Broadcasting - # Broadcast a hash directly to a named broadcasting. This will later be JSON encoded. - def broadcast(broadcasting, message, coder: ActiveSupport::JSON) - broadcaster_for(broadcasting, coder: coder).broadcast(message) - end - - # Returns a broadcaster for a named broadcasting that can be reused. Useful when you have an object that - # may need multiple spots to transmit to a specific broadcasting over and over. - def broadcaster_for(broadcasting, coder: ActiveSupport::JSON) - Broadcaster.new(self, String(broadcasting), coder: coder) - end - - private - class Broadcaster - attr_reader :server, :broadcasting, :coder - - def initialize(server, broadcasting, coder:) - @server, @broadcasting, @coder = server, broadcasting, coder - end - - def broadcast(message) - server.logger.debug "[ActionCable] Broadcasting to #{broadcasting}: #{message.inspect}" - - payload = { broadcasting: broadcasting, message: message, coder: coder } - ActiveSupport::Notifications.instrument("broadcast.action_cable", payload) do - encoded = coder ? coder.encode(message) : message - server.pubsub.broadcast broadcasting, encoded - end - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/configuration.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/configuration.rb deleted file mode 100644 index 17e0dee064..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/configuration.rb +++ /dev/null @@ -1,41 +0,0 @@ -module ActionCable - module Server - # An instance of this configuration object is available via ActionCable.server.config, which allows you to tweak Action Cable configuration - # in a Rails config initializer. - class Configuration - attr_accessor :logger, :log_tags - attr_accessor :connection_class, :worker_pool_size - attr_accessor :disable_request_forgery_protection, :allowed_request_origins, :allow_same_origin_as_host - attr_accessor :cable, :url, :mount_path - - def initialize - @log_tags = [] - - @connection_class = -> { ActionCable::Connection::Base } - @worker_pool_size = 4 - - @disable_request_forgery_protection = false - @allow_same_origin_as_host = true - end - - # Returns constant of subscription adapter specified in config/cable.yml. - # If the adapter cannot be found, this will default to the Redis adapter. - # Also makes sure proper dependencies are required. - def pubsub_adapter - adapter = (cable.fetch("adapter") { "redis" }) - path_to_adapter = "action_cable/subscription_adapter/#{adapter}" - begin - require path_to_adapter - rescue Gem::LoadError => e - raise Gem::LoadError, "Specified '#{adapter}' for Action Cable pubsub adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile (and ensure its version is at the minimum required by Action Cable)." - rescue LoadError => e - raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/cable.yml is valid. If you use an adapter other than 'postgresql' or 'redis' add the necessary adapter gem to the Gemfile.", e.backtrace - end - - adapter = adapter.camelize - adapter = "PostgreSQL" if adapter == "Postgresql" - "ActionCable::SubscriptionAdapter::#{adapter}".constantize - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/connections.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/connections.rb deleted file mode 100644 index 5e61b4e335..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/connections.rb +++ /dev/null @@ -1,34 +0,0 @@ -module ActionCable - module Server - # Collection class for all the connections that have been established on this specific server. Remember, usually you'll run many Action Cable servers, so - # you can't use this collection as a full list of all of the connections established against your application. Instead, use RemoteConnections for that. - module Connections # :nodoc: - BEAT_INTERVAL = 3 - - def connections - @connections ||= [] - end - - def add_connection(connection) - connections << connection - end - - def remove_connection(connection) - connections.delete connection - end - - # WebSocket connection implementations differ on when they'll mark a connection as stale. We basically never want a connection to go stale, as you - # then can't rely on being able to communicate with the connection. To solve this, a 3 second heartbeat runs on all connections. If the beat fails, we automatically - # disconnect. - def setup_heartbeat_timer - @heartbeat_timer ||= event_loop.timer(BEAT_INTERVAL) do - event_loop.post { connections.map(&:beat) } - end - end - - def open_connections_statistics - connections.map(&:statistics) - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/worker.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/worker.rb deleted file mode 100644 index 43639c27af..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/worker.rb +++ /dev/null @@ -1,75 +0,0 @@ -require "active_support/callbacks" -require "active_support/core_ext/module/attribute_accessors_per_thread" -require "concurrent" - -module ActionCable - module Server - # Worker used by Server.send_async to do connection work in threads. - class Worker # :nodoc: - include ActiveSupport::Callbacks - - thread_mattr_accessor :connection - define_callbacks :work - include ActiveRecordConnectionManagement - - attr_reader :executor - - def initialize(max_size: 5) - @executor = Concurrent::ThreadPoolExecutor.new( - min_threads: 1, - max_threads: max_size, - max_queue: 0, - ) - end - - # Stop processing work: any work that has not already started - # running will be discarded from the queue - def halt - @executor.shutdown - end - - def stopping? - @executor.shuttingdown? - end - - def work(connection) - self.connection = connection - - run_callbacks :work do - yield - end - ensure - self.connection = nil - end - - def async_exec(receiver, *args, connection:, &block) - async_invoke receiver, :instance_exec, *args, connection: connection, &block - end - - def async_invoke(receiver, method, *args, connection: receiver, &block) - @executor.post do - invoke(receiver, method, *args, connection: connection, &block) - end - end - - def invoke(receiver, method, *args, connection:, &block) - work(connection) do - begin - receiver.send method, *args, &block - rescue Exception => e - logger.error "There was an exception - #{e.class}(#{e.message})" - logger.error e.backtrace.join("\n") - - receiver.handle_exception if receiver.respond_to?(:handle_exception) - end - end - end - - private - - def logger - ActionCable.server.logger - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/worker/active_record_connection_management.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/worker/active_record_connection_management.rb deleted file mode 100644 index c1e4aa8103..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/server/worker/active_record_connection_management.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActionCable - module Server - class Worker - module ActiveRecordConnectionManagement - extend ActiveSupport::Concern - - included do - if defined?(ActiveRecord::Base) - set_callback :work, :around, :with_database_connections - end - end - - def with_database_connections - connection.logger.tag(ActiveRecord::Base.logger) { yield } - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter.rb deleted file mode 100644 index 596269ab9b..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActionCable - module SubscriptionAdapter - extend ActiveSupport::Autoload - - autoload :Base - autoload :SubscriberMap - autoload :ChannelPrefix - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/async.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/async.rb deleted file mode 100644 index 46819dbfec..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/async.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "action_cable/subscription_adapter/inline" - -module ActionCable - module SubscriptionAdapter - class Async < Inline # :nodoc: - private - def new_subscriber_map - AsyncSubscriberMap.new(server.event_loop) - end - - class AsyncSubscriberMap < SubscriberMap - def initialize(event_loop) - @event_loop = event_loop - super() - end - - def add_subscriber(*) - @event_loop.post { super } - end - - def invoke_callback(*) - @event_loop.post { super } - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/base.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/base.rb deleted file mode 100644 index 796db5ffa3..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/base.rb +++ /dev/null @@ -1,28 +0,0 @@ -module ActionCable - module SubscriptionAdapter - class Base - attr_reader :logger, :server - - def initialize(server) - @server = server - @logger = @server.logger - end - - def broadcast(channel, payload) - raise NotImplementedError - end - - def subscribe(channel, message_callback, success_callback = nil) - raise NotImplementedError - end - - def unsubscribe(channel, message_callback) - raise NotImplementedError - end - - def shutdown - raise NotImplementedError - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/channel_prefix.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/channel_prefix.rb deleted file mode 100644 index 8b293cc785..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/channel_prefix.rb +++ /dev/null @@ -1,26 +0,0 @@ -module ActionCable - module SubscriptionAdapter - module ChannelPrefix # :nodoc: - def broadcast(channel, payload) - channel = channel_with_prefix(channel) - super - end - - def subscribe(channel, callback, success_callback = nil) - channel = channel_with_prefix(channel) - super - end - - def unsubscribe(channel, callback) - channel = channel_with_prefix(channel) - super - end - - private - # Returns the channel name, including channel_prefix specified in cable.yml - def channel_with_prefix(channel) - [@server.config.cable[:channel_prefix], channel].compact.join(":") - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/evented_redis.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/evented_redis.rb deleted file mode 100644 index eaddd450ee..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/evented_redis.rb +++ /dev/null @@ -1,87 +0,0 @@ -require "thread" - -gem "em-hiredis", "~> 0.3.0" -gem "redis", ">= 3", "< 5" -require "em-hiredis" -require "redis" - -EventMachine.epoll if EventMachine.epoll? -EventMachine.kqueue if EventMachine.kqueue? - -module ActionCable - module SubscriptionAdapter - class EventedRedis < Base # :nodoc: - prepend ChannelPrefix - - @@mutex = Mutex.new - - # Overwrite this factory method for EventMachine Redis connections if you want to use a different Redis connection library than EM::Hiredis. - # This is needed, for example, when using Makara proxies for distributed Redis. - cattr_accessor(:em_redis_connector) { ->(config) { EM::Hiredis.connect(config[:url]) } } - - # Overwrite this factory method for Redis connections if you want to use a different Redis connection library than Redis. - # This is needed, for example, when using Makara proxies for distributed Redis. - cattr_accessor(:redis_connector) { ->(config) { ::Redis.new(url: config[:url]) } } - - def initialize(*) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - The "evented_redis" subscription adapter is deprecated and - will be removed in Rails 5.2. Please use the "redis" adapter - instead. - MSG - - super - @redis_connection_for_broadcasts = @redis_connection_for_subscriptions = nil - end - - def broadcast(channel, payload) - redis_connection_for_broadcasts.publish(channel, payload) - end - - def subscribe(channel, message_callback, success_callback = nil) - redis_connection_for_subscriptions.pubsub.subscribe(channel, &message_callback).tap do |result| - result.callback { |reply| success_callback.call } if success_callback - end - end - - def unsubscribe(channel, message_callback) - redis_connection_for_subscriptions.pubsub.unsubscribe_proc(channel, message_callback) - end - - def shutdown - redis_connection_for_subscriptions.pubsub.close_connection - @redis_connection_for_subscriptions = nil - end - - private - def redis_connection_for_subscriptions - ensure_reactor_running - @redis_connection_for_subscriptions || @server.mutex.synchronize do - @redis_connection_for_subscriptions ||= self.class.em_redis_connector.call(@server.config.cable).tap do |redis| - redis.on(:reconnect_failed) do - @logger.error "[ActionCable] Redis reconnect failed." - end - - redis.on(:failed) do - @logger.error "[ActionCable] Redis connection has failed." - end - end - end - end - - def redis_connection_for_broadcasts - @redis_connection_for_broadcasts || @server.mutex.synchronize do - @redis_connection_for_broadcasts ||= self.class.redis_connector.call(@server.config.cable) - end - end - - def ensure_reactor_running - return if EventMachine.reactor_running? && EventMachine.reactor_thread - @@mutex.synchronize do - Thread.new { EventMachine.run } unless EventMachine.reactor_running? - Thread.pass until EventMachine.reactor_running? && EventMachine.reactor_thread - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/inline.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/inline.rb deleted file mode 100644 index 81357faead..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/inline.rb +++ /dev/null @@ -1,35 +0,0 @@ -module ActionCable - module SubscriptionAdapter - class Inline < Base # :nodoc: - def initialize(*) - super - @subscriber_map = nil - end - - def broadcast(channel, payload) - subscriber_map.broadcast(channel, payload) - end - - def subscribe(channel, callback, success_callback = nil) - subscriber_map.add_subscriber(channel, callback, success_callback) - end - - def unsubscribe(channel, callback) - subscriber_map.remove_subscriber(channel, callback) - end - - def shutdown - # nothing to do - end - - private - def subscriber_map - @subscriber_map || @server.mutex.synchronize { @subscriber_map ||= new_subscriber_map } - end - - def new_subscriber_map - SubscriberMap.new - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/postgresql.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/postgresql.rb deleted file mode 100644 index 05d5a65c7e..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/postgresql.rb +++ /dev/null @@ -1,107 +0,0 @@ -gem "pg", ">= 0.18", "< 2.0" -require "pg" -require "thread" - -module ActionCable - module SubscriptionAdapter - class PostgreSQL < Base # :nodoc: - def initialize(*) - super - @listener = nil - end - - def broadcast(channel, payload) - with_connection do |pg_conn| - pg_conn.exec("NOTIFY #{pg_conn.escape_identifier(channel)}, '#{pg_conn.escape_string(payload)}'") - end - end - - def subscribe(channel, callback, success_callback = nil) - listener.add_subscriber(channel, callback, success_callback) - end - - def unsubscribe(channel, callback) - listener.remove_subscriber(channel, callback) - end - - def shutdown - listener.shutdown - end - - def with_connection(&block) # :nodoc: - ActiveRecord::Base.connection_pool.with_connection do |ar_conn| - pg_conn = ar_conn.raw_connection - - unless pg_conn.is_a?(PG::Connection) - raise "The Active Record database must be PostgreSQL in order to use the PostgreSQL Action Cable storage adapter" - end - - yield pg_conn - end - end - - private - def listener - @listener || @server.mutex.synchronize { @listener ||= Listener.new(self, @server.event_loop) } - end - - class Listener < SubscriberMap - def initialize(adapter, event_loop) - super() - - @adapter = adapter - @event_loop = event_loop - @queue = Queue.new - - @thread = Thread.new do - Thread.current.abort_on_exception = true - listen - end - end - - def listen - @adapter.with_connection do |pg_conn| - catch :shutdown do - loop do - until @queue.empty? - action, channel, callback = @queue.pop(true) - - case action - when :listen - pg_conn.exec("LISTEN #{pg_conn.escape_identifier channel}") - @event_loop.post(&callback) if callback - when :unlisten - pg_conn.exec("UNLISTEN #{pg_conn.escape_identifier channel}") - when :shutdown - throw :shutdown - end - end - - pg_conn.wait_for_notify(1) do |chan, pid, message| - broadcast(chan, message) - end - end - end - end - end - - def shutdown - @queue.push([:shutdown]) - Thread.pass while @thread.alive? - end - - def add_channel(channel, on_success) - @queue.push([:listen, channel, on_success]) - end - - def remove_channel(channel) - @queue.push([:unlisten, channel]) - end - - def invoke_callback(*) - @event_loop.post { super } - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/redis.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/redis.rb deleted file mode 100644 index e7e7f061c4..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/redis.rb +++ /dev/null @@ -1,174 +0,0 @@ -require "thread" - -gem "redis", ">= 3", "< 5" -require "redis" - -module ActionCable - module SubscriptionAdapter - class Redis < Base # :nodoc: - prepend ChannelPrefix - - # Overwrite this factory method for redis connections if you want to use a different Redis library than Redis. - # This is needed, for example, when using Makara proxies for distributed Redis. - cattr_accessor(:redis_connector) { ->(config) { ::Redis.new(url: config[:url]) } } - - def initialize(*) - super - @listener = nil - @redis_connection_for_broadcasts = nil - end - - def broadcast(channel, payload) - redis_connection_for_broadcasts.publish(channel, payload) - end - - def subscribe(channel, callback, success_callback = nil) - listener.add_subscriber(channel, callback, success_callback) - end - - def unsubscribe(channel, callback) - listener.remove_subscriber(channel, callback) - end - - def shutdown - @listener.shutdown if @listener - end - - def redis_connection_for_subscriptions - redis_connection - end - - private - def listener - @listener || @server.mutex.synchronize { @listener ||= Listener.new(self, @server.event_loop) } - end - - def redis_connection_for_broadcasts - @redis_connection_for_broadcasts || @server.mutex.synchronize do - @redis_connection_for_broadcasts ||= redis_connection - end - end - - def redis_connection - self.class.redis_connector.call(@server.config.cable) - end - - class Listener < SubscriberMap - def initialize(adapter, event_loop) - super() - - @adapter = adapter - @event_loop = event_loop - - @subscribe_callbacks = Hash.new { |h, k| h[k] = [] } - @subscription_lock = Mutex.new - - @raw_client = nil - - @when_connected = [] - - @thread = nil - end - - def listen(conn) - conn.without_reconnect do - original_client = conn.respond_to?(:_client) ? conn._client : conn.client - - conn.subscribe("_action_cable_internal") do |on| - on.subscribe do |chan, count| - @subscription_lock.synchronize do - if count == 1 - @raw_client = original_client - - until @when_connected.empty? - @when_connected.shift.call - end - end - - if callbacks = @subscribe_callbacks[chan] - next_callback = callbacks.shift - @event_loop.post(&next_callback) if next_callback - @subscribe_callbacks.delete(chan) if callbacks.empty? - end - end - end - - on.message do |chan, message| - broadcast(chan, message) - end - - on.unsubscribe do |chan, count| - if count == 0 - @subscription_lock.synchronize do - @raw_client = nil - end - end - end - end - end - end - - def shutdown - @subscription_lock.synchronize do - return if @thread.nil? - - when_connected do - send_command("unsubscribe") - @raw_client = nil - end - end - - Thread.pass while @thread.alive? - end - - def add_channel(channel, on_success) - @subscription_lock.synchronize do - ensure_listener_running - @subscribe_callbacks[channel] << on_success - when_connected { send_command("subscribe", channel) } - end - end - - def remove_channel(channel) - @subscription_lock.synchronize do - when_connected { send_command("unsubscribe", channel) } - end - end - - def invoke_callback(*) - @event_loop.post { super } - end - - private - def ensure_listener_running - @thread ||= Thread.new do - Thread.current.abort_on_exception = true - - conn = @adapter.redis_connection_for_subscriptions - listen conn - end - end - - def when_connected(&block) - if @raw_client - block.call - else - @when_connected << block - end - end - - def send_command(*command) - @raw_client.write(command) - - very_raw_connection = - @raw_client.connection.instance_variable_defined?(:@connection) && - @raw_client.connection.instance_variable_get(:@connection) - - if very_raw_connection && very_raw_connection.respond_to?(:flush) - very_raw_connection.flush - end - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/subscriber_map.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/subscriber_map.rb deleted file mode 100644 index 4cce86dcca..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/subscription_adapter/subscriber_map.rb +++ /dev/null @@ -1,57 +0,0 @@ -module ActionCable - module SubscriptionAdapter - class SubscriberMap - def initialize - @subscribers = Hash.new { |h, k| h[k] = [] } - @sync = Mutex.new - end - - def add_subscriber(channel, subscriber, on_success) - @sync.synchronize do - new_channel = !@subscribers.key?(channel) - - @subscribers[channel] << subscriber - - if new_channel - add_channel channel, on_success - elsif on_success - on_success.call - end - end - end - - def remove_subscriber(channel, subscriber) - @sync.synchronize do - @subscribers[channel].delete(subscriber) - - if @subscribers[channel].empty? - @subscribers.delete channel - remove_channel channel - end - end - end - - def broadcast(channel, message) - list = @sync.synchronize do - return if !@subscribers.key?(channel) - @subscribers[channel].dup - end - - list.each do |subscriber| - invoke_callback(subscriber, message) - end - end - - def add_channel(channel, on_success) - on_success.call if on_success - end - - def remove_channel(channel) - end - - def invoke_callback(callback, message) - callback.call message - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/version.rb b/debian/gems-compat/actioncable-5.1.7/lib/action_cable/version.rb deleted file mode 100644 index d6081409f0..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/action_cable/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module ActionCable - # Returns the version of the currently loaded Action Cable as a Gem::Version - def self.version - gem_version - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/assets/compiled/action_cable.js b/debian/gems-compat/actioncable-5.1.7/lib/assets/compiled/action_cable.js deleted file mode 100644 index 960f8516d3..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/assets/compiled/action_cable.js +++ /dev/null @@ -1,601 +0,0 @@ -(function() { - var context = this; - - (function() { - (function() { - var slice = [].slice; - - this.ActionCable = { - INTERNAL: { - "message_types": { - "welcome": "welcome", - "ping": "ping", - "confirmation": "confirm_subscription", - "rejection": "reject_subscription" - }, - "default_mount_path": "/cable", - "protocols": ["actioncable-v1-json", "actioncable-unsupported"] - }, - WebSocket: window.WebSocket, - logger: window.console, - createConsumer: function(url) { - var ref; - if (url == null) { - url = (ref = this.getConfig("url")) != null ? ref : this.INTERNAL.default_mount_path; - } - return new ActionCable.Consumer(this.createWebSocketURL(url)); - }, - getConfig: function(name) { - var element; - element = document.head.querySelector("meta[name='action-cable-" + name + "']"); - return element != null ? element.getAttribute("content") : void 0; - }, - createWebSocketURL: function(url) { - var a; - if (url && !/^wss?:/i.test(url)) { - a = document.createElement("a"); - a.href = url; - a.href = a.href; - a.protocol = a.protocol.replace("http", "ws"); - return a.href; - } else { - return url; - } - }, - startDebugging: function() { - return this.debugging = true; - }, - stopDebugging: function() { - return this.debugging = null; - }, - log: function() { - var messages, ref; - messages = 1 <= arguments.length ? slice.call(arguments, 0) : []; - if (this.debugging) { - messages.push(Date.now()); - return (ref = this.logger).log.apply(ref, ["[ActionCable]"].concat(slice.call(messages))); - } - } - }; - - }).call(this); - }).call(context); - - var ActionCable = context.ActionCable; - - (function() { - (function() { - var bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; - - ActionCable.ConnectionMonitor = (function() { - var clamp, now, secondsSince; - - ConnectionMonitor.pollInterval = { - min: 3, - max: 30 - }; - - ConnectionMonitor.staleThreshold = 6; - - function ConnectionMonitor(connection) { - this.connection = connection; - this.visibilityDidChange = bind(this.visibilityDidChange, this); - this.reconnectAttempts = 0; - } - - ConnectionMonitor.prototype.start = function() { - if (!this.isRunning()) { - this.startedAt = now(); - delete this.stoppedAt; - this.startPolling(); - document.addEventListener("visibilitychange", this.visibilityDidChange); - return ActionCable.log("ConnectionMonitor started. pollInterval = " + (this.getPollInterval()) + " ms"); - } - }; - - ConnectionMonitor.prototype.stop = function() { - if (this.isRunning()) { - this.stoppedAt = now(); - this.stopPolling(); - document.removeEventListener("visibilitychange", this.visibilityDidChange); - return ActionCable.log("ConnectionMonitor stopped"); - } - }; - - ConnectionMonitor.prototype.isRunning = function() { - return (this.startedAt != null) && (this.stoppedAt == null); - }; - - ConnectionMonitor.prototype.recordPing = function() { - return this.pingedAt = now(); - }; - - ConnectionMonitor.prototype.recordConnect = function() { - this.reconnectAttempts = 0; - this.recordPing(); - delete this.disconnectedAt; - return ActionCable.log("ConnectionMonitor recorded connect"); - }; - - ConnectionMonitor.prototype.recordDisconnect = function() { - this.disconnectedAt = now(); - return ActionCable.log("ConnectionMonitor recorded disconnect"); - }; - - ConnectionMonitor.prototype.startPolling = function() { - this.stopPolling(); - return this.poll(); - }; - - ConnectionMonitor.prototype.stopPolling = function() { - return clearTimeout(this.pollTimeout); - }; - - ConnectionMonitor.prototype.poll = function() { - return this.pollTimeout = setTimeout((function(_this) { - return function() { - _this.reconnectIfStale(); - return _this.poll(); - }; - })(this), this.getPollInterval()); - }; - - ConnectionMonitor.prototype.getPollInterval = function() { - var interval, max, min, ref; - ref = this.constructor.pollInterval, min = ref.min, max = ref.max; - interval = 5 * Math.log(this.reconnectAttempts + 1); - return Math.round(clamp(interval, min, max) * 1000); - }; - - ConnectionMonitor.prototype.reconnectIfStale = function() { - if (this.connectionIsStale()) { - ActionCable.log("ConnectionMonitor detected stale connection. reconnectAttempts = " + this.reconnectAttempts + ", pollInterval = " + (this.getPollInterval()) + " ms, time disconnected = " + (secondsSince(this.disconnectedAt)) + " s, stale threshold = " + this.constructor.staleThreshold + " s"); - this.reconnectAttempts++; - if (this.disconnectedRecently()) { - return ActionCable.log("ConnectionMonitor skipping reopening recent disconnect"); - } else { - ActionCable.log("ConnectionMonitor reopening"); - return this.connection.reopen(); - } - } - }; - - ConnectionMonitor.prototype.connectionIsStale = function() { - var ref; - return secondsSince((ref = this.pingedAt) != null ? ref : this.startedAt) > this.constructor.staleThreshold; - }; - - ConnectionMonitor.prototype.disconnectedRecently = function() { - return this.disconnectedAt && secondsSince(this.disconnectedAt) < this.constructor.staleThreshold; - }; - - ConnectionMonitor.prototype.visibilityDidChange = function() { - if (document.visibilityState === "visible") { - return setTimeout((function(_this) { - return function() { - if (_this.connectionIsStale() || !_this.connection.isOpen()) { - ActionCable.log("ConnectionMonitor reopening stale connection on visibilitychange. visbilityState = " + document.visibilityState); - return _this.connection.reopen(); - } - }; - })(this), 200); - } - }; - - now = function() { - return new Date().getTime(); - }; - - secondsSince = function(time) { - return (now() - time) / 1000; - }; - - clamp = function(number, min, max) { - return Math.max(min, Math.min(max, number)); - }; - - return ConnectionMonitor; - - })(); - - }).call(this); - (function() { - var i, message_types, protocols, ref, supportedProtocols, unsupportedProtocol, - slice = [].slice, - bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, - indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; - - ref = ActionCable.INTERNAL, message_types = ref.message_types, protocols = ref.protocols; - - supportedProtocols = 2 <= protocols.length ? slice.call(protocols, 0, i = protocols.length - 1) : (i = 0, []), unsupportedProtocol = protocols[i++]; - - ActionCable.Connection = (function() { - Connection.reopenDelay = 500; - - function Connection(consumer) { - this.consumer = consumer; - this.open = bind(this.open, this); - this.subscriptions = this.consumer.subscriptions; - this.monitor = new ActionCable.ConnectionMonitor(this); - this.disconnected = true; - } - - Connection.prototype.send = function(data) { - if (this.isOpen()) { - this.webSocket.send(JSON.stringify(data)); - return true; - } else { - return false; - } - }; - - Connection.prototype.open = function() { - if (this.isActive()) { - ActionCable.log("Attempted to open WebSocket, but existing socket is " + (this.getState())); - return false; - } else { - ActionCable.log("Opening WebSocket, current state is " + (this.getState()) + ", subprotocols: " + protocols); - if (this.webSocket != null) { - this.uninstallEventHandlers(); - } - this.webSocket = new ActionCable.WebSocket(this.consumer.url, protocols); - this.installEventHandlers(); - this.monitor.start(); - return true; - } - }; - - Connection.prototype.close = function(arg) { - var allowReconnect, ref1; - allowReconnect = (arg != null ? arg : { - allowReconnect: true - }).allowReconnect; - if (!allowReconnect) { - this.monitor.stop(); - } - if (this.isActive()) { - return (ref1 = this.webSocket) != null ? ref1.close() : void 0; - } - }; - - Connection.prototype.reopen = function() { - var error; - ActionCable.log("Reopening WebSocket, current state is " + (this.getState())); - if (this.isActive()) { - try { - return this.close(); - } catch (error1) { - error = error1; - return ActionCable.log("Failed to reopen WebSocket", error); - } finally { - ActionCable.log("Reopening WebSocket in " + this.constructor.reopenDelay + "ms"); - setTimeout(this.open, this.constructor.reopenDelay); - } - } else { - return this.open(); - } - }; - - Connection.prototype.getProtocol = function() { - var ref1; - return (ref1 = this.webSocket) != null ? ref1.protocol : void 0; - }; - - Connection.prototype.isOpen = function() { - return this.isState("open"); - }; - - Connection.prototype.isActive = function() { - return this.isState("open", "connecting"); - }; - - Connection.prototype.isProtocolSupported = function() { - var ref1; - return ref1 = this.getProtocol(), indexOf.call(supportedProtocols, ref1) >= 0; - }; - - Connection.prototype.isState = function() { - var ref1, states; - states = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return ref1 = this.getState(), indexOf.call(states, ref1) >= 0; - }; - - Connection.prototype.getState = function() { - var ref1, state, value; - for (state in WebSocket) { - value = WebSocket[state]; - if (value === ((ref1 = this.webSocket) != null ? ref1.readyState : void 0)) { - return state.toLowerCase(); - } - } - return null; - }; - - Connection.prototype.installEventHandlers = function() { - var eventName, handler; - for (eventName in this.events) { - handler = this.events[eventName].bind(this); - this.webSocket["on" + eventName] = handler; - } - }; - - Connection.prototype.uninstallEventHandlers = function() { - var eventName; - for (eventName in this.events) { - this.webSocket["on" + eventName] = function() {}; - } - }; - - Connection.prototype.events = { - message: function(event) { - var identifier, message, ref1, type; - if (!this.isProtocolSupported()) { - return; - } - ref1 = JSON.parse(event.data), identifier = ref1.identifier, message = ref1.message, type = ref1.type; - switch (type) { - case message_types.welcome: - this.monitor.recordConnect(); - return this.subscriptions.reload(); - case message_types.ping: - return this.monitor.recordPing(); - case message_types.confirmation: - return this.subscriptions.notify(identifier, "connected"); - case message_types.rejection: - return this.subscriptions.reject(identifier); - default: - return this.subscriptions.notify(identifier, "received", message); - } - }, - open: function() { - ActionCable.log("WebSocket onopen event, using '" + (this.getProtocol()) + "' subprotocol"); - this.disconnected = false; - if (!this.isProtocolSupported()) { - ActionCable.log("Protocol is unsupported. Stopping monitor and disconnecting."); - return this.close({ - allowReconnect: false - }); - } - }, - close: function(event) { - ActionCable.log("WebSocket onclose event"); - if (this.disconnected) { - return; - } - this.disconnected = true; - this.monitor.recordDisconnect(); - return this.subscriptions.notifyAll("disconnected", { - willAttemptReconnect: this.monitor.isRunning() - }); - }, - error: function() { - return ActionCable.log("WebSocket onerror event"); - } - }; - - return Connection; - - })(); - - }).call(this); - (function() { - var slice = [].slice; - - ActionCable.Subscriptions = (function() { - function Subscriptions(consumer) { - this.consumer = consumer; - this.subscriptions = []; - } - - Subscriptions.prototype.create = function(channelName, mixin) { - var channel, params, subscription; - channel = channelName; - params = typeof channel === "object" ? channel : { - channel: channel - }; - subscription = new ActionCable.Subscription(this.consumer, params, mixin); - return this.add(subscription); - }; - - Subscriptions.prototype.add = function(subscription) { - this.subscriptions.push(subscription); - this.consumer.ensureActiveConnection(); - this.notify(subscription, "initialized"); - this.sendCommand(subscription, "subscribe"); - return subscription; - }; - - Subscriptions.prototype.remove = function(subscription) { - this.forget(subscription); - if (!this.findAll(subscription.identifier).length) { - this.sendCommand(subscription, "unsubscribe"); - } - return subscription; - }; - - Subscriptions.prototype.reject = function(identifier) { - var i, len, ref, results, subscription; - ref = this.findAll(identifier); - results = []; - for (i = 0, len = ref.length; i < len; i++) { - subscription = ref[i]; - this.forget(subscription); - this.notify(subscription, "rejected"); - results.push(subscription); - } - return results; - }; - - Subscriptions.prototype.forget = function(subscription) { - var s; - this.subscriptions = (function() { - var i, len, ref, results; - ref = this.subscriptions; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - s = ref[i]; - if (s !== subscription) { - results.push(s); - } - } - return results; - }).call(this); - return subscription; - }; - - Subscriptions.prototype.findAll = function(identifier) { - var i, len, ref, results, s; - ref = this.subscriptions; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - s = ref[i]; - if (s.identifier === identifier) { - results.push(s); - } - } - return results; - }; - - Subscriptions.prototype.reload = function() { - var i, len, ref, results, subscription; - ref = this.subscriptions; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - subscription = ref[i]; - results.push(this.sendCommand(subscription, "subscribe")); - } - return results; - }; - - Subscriptions.prototype.notifyAll = function() { - var args, callbackName, i, len, ref, results, subscription; - callbackName = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : []; - ref = this.subscriptions; - results = []; - for (i = 0, len = ref.length; i < len; i++) { - subscription = ref[i]; - results.push(this.notify.apply(this, [subscription, callbackName].concat(slice.call(args)))); - } - return results; - }; - - Subscriptions.prototype.notify = function() { - var args, callbackName, i, len, results, subscription, subscriptions; - subscription = arguments[0], callbackName = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : []; - if (typeof subscription === "string") { - subscriptions = this.findAll(subscription); - } else { - subscriptions = [subscription]; - } - results = []; - for (i = 0, len = subscriptions.length; i < len; i++) { - subscription = subscriptions[i]; - results.push(typeof subscription[callbackName] === "function" ? subscription[callbackName].apply(subscription, args) : void 0); - } - return results; - }; - - Subscriptions.prototype.sendCommand = function(subscription, command) { - var identifier; - identifier = subscription.identifier; - return this.consumer.send({ - command: command, - identifier: identifier - }); - }; - - return Subscriptions; - - })(); - - }).call(this); - (function() { - ActionCable.Subscription = (function() { - var extend; - - function Subscription(consumer, params, mixin) { - this.consumer = consumer; - if (params == null) { - params = {}; - } - this.identifier = JSON.stringify(params); - extend(this, mixin); - } - - Subscription.prototype.perform = function(action, data) { - if (data == null) { - data = {}; - } - data.action = action; - return this.send(data); - }; - - Subscription.prototype.send = function(data) { - return this.consumer.send({ - command: "message", - identifier: this.identifier, - data: JSON.stringify(data) - }); - }; - - Subscription.prototype.unsubscribe = function() { - return this.consumer.subscriptions.remove(this); - }; - - extend = function(object, properties) { - var key, value; - if (properties != null) { - for (key in properties) { - value = properties[key]; - object[key] = value; - } - } - return object; - }; - - return Subscription; - - })(); - - }).call(this); - (function() { - ActionCable.Consumer = (function() { - function Consumer(url) { - this.url = url; - this.subscriptions = new ActionCable.Subscriptions(this); - this.connection = new ActionCable.Connection(this); - } - - Consumer.prototype.send = function(data) { - return this.connection.send(data); - }; - - Consumer.prototype.connect = function() { - return this.connection.open(); - }; - - Consumer.prototype.disconnect = function() { - return this.connection.close({ - allowReconnect: false - }); - }; - - Consumer.prototype.ensureActiveConnection = function() { - if (!this.connection.isActive()) { - return this.connection.open(); - } - }; - - return Consumer; - - })(); - - }).call(this); - }).call(this); - - if (typeof module === "object" && module.exports) { - module.exports = ActionCable; - } else if (typeof define === "function" && define.amd) { - define(ActionCable); - } -}).call(this); diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/USAGE b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/USAGE deleted file mode 100644 index dd109fda80..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/USAGE +++ /dev/null @@ -1,14 +0,0 @@ -Description: -============ - Stubs out a new cable channel for the server (in Ruby) and client (in CoffeeScript). - Pass the channel name, either CamelCased or under_scored, and an optional list of channel actions as arguments. - - Note: Turn on the cable connection in app/assets/javascripts/cable.js after generating any channels. - -Example: -======== - rails generate channel Chat speak - - creates a Chat channel class and CoffeeScript asset: - Channel: app/channels/chat_channel.rb - Assets: app/assets/javascripts/channels/chat.coffee diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/channel_generator.rb b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/channel_generator.rb deleted file mode 100644 index 984b78bc9c..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/channel_generator.rb +++ /dev/null @@ -1,47 +0,0 @@ -module Rails - module Generators - class ChannelGenerator < NamedBase - source_root File.expand_path("../templates", __FILE__) - - argument :actions, type: :array, default: [], banner: "method method" - - class_option :assets, type: :boolean - - check_class_collision suffix: "Channel" - - def create_channel_file - template "channel.rb", File.join("app/channels", class_path, "#{file_name}_channel.rb") - - if options[:assets] - if behavior == :invoke - template "assets/cable.js", "app/assets/javascripts/cable.js" - end - - js_template "assets/channel", File.join("app/assets/javascripts/channels", class_path, "#{file_name}") - end - - generate_application_cable_files - end - - private - def file_name - @_file_name ||= super.gsub(/_channel/i, "") - end - - # FIXME: Change these files to symlinks once RubyGems 2.5.0 is required. - def generate_application_cable_files - return if behavior != :invoke - - files = [ - "application_cable/channel.rb", - "application_cable/connection.rb" - ] - - files.each do |name| - path = File.join("app/channels/", name) - template(name, path) if !File.exist?(path) - end - end - end - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/application_cable/channel.rb b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/application_cable/channel.rb deleted file mode 100644 index d672697283..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/application_cable/channel.rb +++ /dev/null @@ -1,4 +0,0 @@ -module ApplicationCable - class Channel < ActionCable::Channel::Base - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/application_cable/connection.rb b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/application_cable/connection.rb deleted file mode 100644 index 0ff5442f47..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/application_cable/connection.rb +++ /dev/null @@ -1,4 +0,0 @@ -module ApplicationCable - class Connection < ActionCable::Connection::Base - end -end diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/cable.js b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/cable.js deleted file mode 100644 index 739aa5f022..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/cable.js +++ /dev/null @@ -1,13 +0,0 @@ -// Action Cable provides the framework to deal with WebSockets in Rails. -// You can generate new channels where WebSocket features live using the `rails generate channel` command. -// -//= require action_cable -//= require_self -//= require_tree ./channels - -(function() { - this.App || (this.App = {}); - - App.cable = ActionCable.createConsumer(); - -}).call(this); diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/channel.coffee b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/channel.coffee deleted file mode 100644 index 5467811aba..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/channel.coffee +++ /dev/null @@ -1,14 +0,0 @@ -App.<%= class_name.underscore %> = App.cable.subscriptions.create "<%= class_name %>Channel", - connected: -> - # Called when the subscription is ready for use on the server - - disconnected: -> - # Called when the subscription has been terminated by the server - - received: (data) -> - # Called when there's incoming data on the websocket for this channel -<% actions.each do |action| -%> - - <%= action %>: -> - @perform '<%= action %>' -<% end -%> diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/channel.js b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/channel.js deleted file mode 100644 index ab0e68b11a..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/assets/channel.js +++ /dev/null @@ -1,18 +0,0 @@ -App.<%= class_name.underscore %> = App.cable.subscriptions.create("<%= class_name %>Channel", { - connected: function() { - // Called when the subscription is ready for use on the server - }, - - disconnected: function() { - // Called when the subscription has been terminated by the server - }, - - received: function(data) { - // Called when there's incoming data on the websocket for this channel - }<%= actions.any? ? ",\n" : '' %> -<% actions.each do |action| -%> - <%=action %>: function() { - return this.perform('<%= action %>'); - }<%= action == actions[-1] ? '' : ",\n" %> -<% end -%> -}); diff --git a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/channel.rb b/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/channel.rb deleted file mode 100644 index 4bcfb2be4d..0000000000 --- a/debian/gems-compat/actioncable-5.1.7/lib/rails/generators/channel/templates/channel.rb +++ /dev/null @@ -1,16 +0,0 @@ -<% module_namespacing do -%> -class <%= class_name %>Channel < ApplicationCable::Channel - def subscribed - # stream_from "some_channel" - end - - def unsubscribed - # Any cleanup needed when channel is unsubscribed - end -<% actions.each do |action| -%> - - def <%= action %> - end -<% end -%> -end -<% end -%> diff --git a/debian/gems-compat/actionmailer-5.1.7/CHANGELOG.md b/debian/gems-compat/actionmailer-5.1.7/CHANGELOG.md deleted file mode 100644 index 580886da70..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,101 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* No changes. - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* No changes. - - -## Rails 5.1.5 (February 14, 2018) ## - -* Bring back proc with arity of 1 in `ActionMailer::Base.default` proc - since it was supported in Rails 5.0 but not deprecated. - - *Jimmy Bourassa* - - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* No changes. - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* No changes. - - -## Rails 5.1.2 (June 26, 2017) ## - -* No changes. - - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* Add `:args` to `process.action_mailer` event. - - *Yuji Yaginuma* - -* Add parameterized invocation of mailers as a way to share before filters and defaults between actions. - See `ActionMailer::Parameterized` for a full example of the benefit. - - *DHH* - -* Allow lambdas to be used as lazy defaults in addition to procs. - - *DHH* - -* Mime type: allow to custom content type when setting body in headers - and attachments. - - Example: - - def test_emails - attachments["invoice.pdf"] = "This is test File content" - mail(body: "Hello there", content_type: "text/html") - end - - *Minh Quy* - -* Exception handling: use `rescue_from` to handle exceptions raised by - mailer actions, by message delivery, and by deferred delivery jobs. - - *Jeremy Daer* - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actionmailer/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/actionmailer-5.1.7/MIT-LICENSE b/debian/gems-compat/actionmailer-5.1.7/MIT-LICENSE deleted file mode 100644 index ac810e86d0..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2004-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/debian/gems-compat/actionmailer-5.1.7/README.rdoc b/debian/gems-compat/actionmailer-5.1.7/README.rdoc deleted file mode 100644 index 397ebe4201..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/README.rdoc +++ /dev/null @@ -1,175 +0,0 @@ -= Action Mailer -- Easy email delivery and testing - -Action Mailer is a framework for designing email service layers. These layers -are used to consolidate code for sending out forgotten passwords, welcome -wishes on signup, invoices for billing, and any other use case that requires -a written notification to either a person or another system. - -Action Mailer is in essence a wrapper around Action Controller and the -Mail gem. It provides a way to make emails using templates in the same -way that Action Controller renders views using templates. - -Additionally, an Action Mailer class can be used to process incoming email, -such as allowing a blog to accept new posts from an email (which could even -have been sent from a phone). - -== Sending emails - -The framework works by initializing any instance variables you want to be -available in the email template, followed by a call to +mail+ to deliver -the email. - -This can be as simple as: - - class Notifier < ActionMailer::Base - default from: 'system@loudthinking.com' - - def welcome(recipient) - @recipient = recipient - mail(to: recipient, - subject: "[Signed up] Welcome #{recipient}") - end - end - -The body of the email is created by using an Action View template (regular -ERB) that has the instance variables that are declared in the mailer action. - -So the corresponding body template for the method above could look like this: - - Hello there, - - Mr. <%= @recipient %> - - Thank you for signing up! - -If the recipient was given as "david@loudthinking.com", the email -generated would look like this: - - Date: Mon, 25 Jan 2010 22:48:09 +1100 - From: system@loudthinking.com - To: david@loudthinking.com - Message-ID: <4b5d84f9dd6a5_7380800b81ac29578@void.loudthinking.com.mail> - Subject: [Signed up] Welcome david@loudthinking.com - Mime-Version: 1.0 - Content-Type: text/plain; - charset="US-ASCII"; - Content-Transfer-Encoding: 7bit - - Hello there, - - Mr. david@loudthinking.com - - Thank you for signing up! - -In order to send mails, you simply call the method and then call +deliver_now+ on the return value. - -Calling the method returns a Mail Message object: - - message = Notifier.welcome("david@loudthinking.com") # => Returns a Mail::Message object - message.deliver_now # => delivers the email - -Or you can just chain the methods together like: - - Notifier.welcome("david@loudthinking.com").deliver_now # Creates the email and sends it immediately - -== Setting defaults - -It is possible to set default values that will be used in every method in your -Action Mailer class. To implement this functionality, you just call the public -class method +default+ which you get for free from ActionMailer::Base. -This method accepts a Hash as the parameter. You can use any of the headers, -email messages have, like +:from+ as the key. You can also pass in a string as -the key, like "Content-Type", but Action Mailer does this out of the box for you, -so you won't need to worry about that. Finally, it is also possible to pass in a -Proc that will get evaluated when it is needed. - -Note that every value you set with this method will get overwritten if you use the -same key in your mailer method. - -Example: - - class AuthenticationMailer < ActionMailer::Base - default from: "awesome@application.com", subject: Proc.new { "E-mail was generated at #{Time.now}" } - ..... - end - -== Receiving emails - -To receive emails, you need to implement a public instance method called -+receive+ that takes an email object as its single parameter. The Action Mailer -framework has a corresponding class method, which is also called +receive+, that -accepts a raw, unprocessed email as a string, which it then turns into the email -object and calls the receive instance method. - -Example: - - class Mailman < ActionMailer::Base - def receive(email) - page = Page.find_by(address: email.to.first) - page.emails.create( - subject: email.subject, body: email.body - ) - - if email.has_attachments? - email.attachments.each do |attachment| - page.attachments.create({ - file: attachment, description: email.subject - }) - end - end - end - end - -This Mailman can be the target for Postfix or other MTAs. In Rails, you would use -the runner in the trivial case like this: - - rails runner 'Mailman.receive(STDIN.read)' - -However, invoking Rails in the runner for each mail to be received is very -resource intensive. A single instance of Rails should be run within a daemon, if -it is going to process more than just a limited amount of email. - -== Configuration - -The Base class has the full list of configuration options. Here's an example: - - ActionMailer::Base.smtp_settings = { - address: 'smtp.yourserver.com', # default: localhost - port: '25', # default: 25 - user_name: 'user', - password: 'pass', - authentication: :plain # :plain, :login or :cram_md5 - } - - -== Download and installation - -The latest version of Action Mailer can be installed with RubyGems: - - $ gem install actionmailer - -Source code can be downloaded as part of the Rails project on GitHub - -* https://github.com/rails/rails/tree/master/actionmailer - - -== License - -Action Mailer is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -== Support - -API documentation is at - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/actionmailer-5.1.7/actionmailer.gemspec b/debian/gems-compat/actionmailer-5.1.7/actionmailer.gemspec deleted file mode 100644 index 845d546ed6..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/actionmailer.gemspec +++ /dev/null @@ -1,49 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: actionmailer 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "actionmailer".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/actionmailer/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/actionmailer" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.".freeze - s.email = "david@loudthinking.com".freeze - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.rdoc".freeze, "lib/action_mailer.rb".freeze, "lib/action_mailer/base.rb".freeze, "lib/action_mailer/collector.rb".freeze, "lib/action_mailer/delivery_job.rb".freeze, "lib/action_mailer/delivery_methods.rb".freeze, "lib/action_mailer/gem_version.rb".freeze, "lib/action_mailer/inline_preview_interceptor.rb".freeze, "lib/action_mailer/log_subscriber.rb".freeze, "lib/action_mailer/mail_helper.rb".freeze, "lib/action_mailer/message_delivery.rb".freeze, "lib/action_mailer/parameterized.rb".freeze, "lib/action_mailer/preview.rb".freeze, "lib/action_mailer/railtie.rb".freeze, "lib/action_mailer/rescuable.rb".freeze, "lib/action_mailer/test_case.rb".freeze, "lib/action_mailer/test_helper.rb".freeze, "lib/action_mailer/version.rb".freeze, "lib/rails/generators/mailer/USAGE".freeze, "lib/rails/generators/mailer/mailer_generator.rb".freeze, "lib/rails/generators/mailer/templates/application_mailer.rb".freeze, "lib/rails/generators/mailer/templates/mailer.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.requirements = ["none".freeze] - s.rubygems_version = "2.7.6.2".freeze - s.summary = "Email composition, delivery, and receiving framework (part of Rails).".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, [">= 2.5.4", "~> 2.5"]) - s.add_runtime_dependency(%q.freeze, ["~> 2.0"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 2.5.4", "~> 2.5"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 2.5.4", "~> 2.5"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer.rb deleted file mode 100644 index 8e59f033d0..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer.rb +++ /dev/null @@ -1,60 +0,0 @@ -#-- -# Copyright (c) 2004-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "abstract_controller" -require "action_mailer/version" - -# Common Active Support usage in Action Mailer -require "active_support" -require "active_support/rails" -require "active_support/core_ext/class" -require "active_support/core_ext/module/attr_internal" -require "active_support/core_ext/string/inflections" -require "active_support/lazy_load_hooks" - -module ActionMailer - extend ::ActiveSupport::Autoload - - eager_autoload do - autoload :Collector - end - - autoload :Base - autoload :DeliveryMethods - autoload :InlinePreviewInterceptor - autoload :MailHelper - autoload :Parameterized - autoload :Preview - autoload :Previews, "action_mailer/preview" - autoload :TestCase - autoload :TestHelper - autoload :MessageDelivery - autoload :DeliveryJob -end - -autoload :Mime, "action_dispatch/http/mime_type" - -ActiveSupport.on_load(:action_view) do - ActionView::Base.default_formats ||= Mime::SET.symbols - ActionView::Template::Types.delegate_to Mime -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/base.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/base.rb deleted file mode 100644 index 4143ab4451..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/base.rb +++ /dev/null @@ -1,993 +0,0 @@ -require "mail" -require "action_mailer/collector" -require "active_support/core_ext/string/inflections" -require "active_support/core_ext/hash/except" -require "active_support/core_ext/module/anonymous" - -require "action_mailer/log_subscriber" -require "action_mailer/rescuable" - -module ActionMailer - # Action Mailer allows you to send email from your application using a mailer model and views. - # - # = Mailer Models - # - # To use Action Mailer, you need to create a mailer model. - # - # $ rails generate mailer Notifier - # - # The generated model inherits from ApplicationMailer which in turn - # inherits from ActionMailer::Base. A mailer model defines methods - # used to generate an email message. In these methods, you can setup variables to be used in - # the mailer views, options on the mail itself such as the :from address, and attachments. - # - # class ApplicationMailer < ActionMailer::Base - # default from: 'from@example.com' - # layout 'mailer' - # end - # - # class NotifierMailer < ApplicationMailer - # default from: 'no-reply@example.com', - # return_path: 'system@example.com' - # - # def welcome(recipient) - # @account = recipient - # mail(to: recipient.email_address_with_name, - # bcc: ["bcc@example.com", "Order Watcher "]) - # end - # end - # - # Within the mailer method, you have access to the following methods: - # - # * attachments[]= - Allows you to add attachments to your email in an intuitive - # manner; attachments['filename.png'] = File.read('path/to/filename.png') - # - # * attachments.inline[]= - Allows you to add an inline attachment to your email - # in the same manner as attachments[]= - # - # * headers[]= - Allows you to specify any header field in your email such - # as headers['X-No-Spam'] = 'True'. Note that declaring a header multiple times - # will add many fields of the same name. Read #headers doc for more information. - # - # * headers(hash) - Allows you to specify multiple headers in your email such - # as headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'}) - # - # * mail - Allows you to specify email to be sent. - # - # The hash passed to the mail method allows you to specify any header that a Mail::Message - # will accept (any valid email header including optional fields). - # - # The mail method, if not passed a block, will inspect your views and send all the views with - # the same name as the method, so the above action would send the +welcome.text.erb+ view - # file as well as the +welcome.html.erb+ view file in a +multipart/alternative+ email. - # - # If you want to explicitly render only certain templates, pass a block: - # - # mail(to: user.email) do |format| - # format.text - # format.html - # end - # - # The block syntax is also useful in providing information specific to a part: - # - # mail(to: user.email) do |format| - # format.text(content_transfer_encoding: "base64") - # format.html - # end - # - # Or even to render a special view: - # - # mail(to: user.email) do |format| - # format.text - # format.html { render "some_other_template" } - # end - # - # = Mailer views - # - # Like Action Controller, each mailer class has a corresponding view directory in which each - # method of the class looks for a template with its name. - # - # To define a template to be used with a mailer, create an .erb file with the same - # name as the method in your mailer model. For example, in the mailer defined above, the template at - # app/views/notifier_mailer/welcome.text.erb would be used to generate the email. - # - # Variables defined in the methods of your mailer model are accessible as instance variables in their - # corresponding view. - # - # Emails by default are sent in plain text, so a sample view for our model example might look like this: - # - # Hi <%= @account.name %>, - # Thanks for joining our service! Please check back often. - # - # You can even use Action View helpers in these views. For example: - # - # You got a new note! - # <%= truncate(@note.body, length: 25) %> - # - # If you need to access the subject, from or the recipients in the view, you can do that through message object: - # - # You got a new note from <%= message.from %>! - # <%= truncate(@note.body, length: 25) %> - # - # - # = Generating URLs - # - # URLs can be generated in mailer views using url_for or named routes. Unlike controllers from - # Action Pack, the mailer instance doesn't have any context about the incoming request, so you'll need - # to provide all of the details needed to generate a URL. - # - # When using url_for you'll need to provide the :host, :controller, and :action: - # - # <%= url_for(host: "example.com", controller: "welcome", action: "greeting") %> - # - # When using named routes you only need to supply the :host: - # - # <%= users_url(host: "example.com") %> - # - # You should use the named_route_url style (which generates absolute URLs) and avoid using the - # named_route_path style (which generates relative URLs), since clients reading the mail will - # have no concept of a current URL from which to determine a relative path. - # - # It is also possible to set a default host that will be used in all mailers by setting the :host - # option as a configuration option in config/application.rb: - # - # config.action_mailer.default_url_options = { host: "example.com" } - # - # You can also define a default_url_options method on individual mailers to override these - # default settings per-mailer. - # - # By default when config.force_ssl is true, URLs generated for hosts will use the HTTPS protocol. - # - # = Sending mail - # - # Once a mailer action and template are defined, you can deliver your message or defer its creation and - # delivery for later: - # - # NotifierMailer.welcome(User.first).deliver_now # sends the email - # mail = NotifierMailer.welcome(User.first) # => an ActionMailer::MessageDelivery object - # mail.deliver_now # generates and sends the email now - # - # The ActionMailer::MessageDelivery class is a wrapper around a delegate that will call - # your method to generate the mail. If you want direct access to the delegator, or Mail::Message, - # you can call the message method on the ActionMailer::MessageDelivery object. - # - # NotifierMailer.welcome(User.first).message # => a Mail::Message object - # - # Action Mailer is nicely integrated with Active Job so you can generate and send emails in the background - # (example: outside of the request-response cycle, so the user doesn't have to wait on it): - # - # NotifierMailer.welcome(User.first).deliver_later # enqueue the email sending to Active Job - # - # Note that deliver_later will execute your method from the background job. - # - # You never instantiate your mailer class. Rather, you just call the method you defined on the class itself. - # All instance methods are expected to return a message object to be sent. - # - # = Multipart Emails - # - # Multipart messages can also be used implicitly because Action Mailer will automatically detect and use - # multipart templates, where each template is named after the name of the action, followed by the content - # type. Each such detected template will be added to the message, as a separate part. - # - # For example, if the following templates exist: - # * signup_notification.text.erb - # * signup_notification.html.erb - # * signup_notification.xml.builder - # * signup_notification.yml.erb - # - # Each would be rendered and added as a separate part to the message, with the corresponding content - # type. The content type for the entire message is automatically set to multipart/alternative, - # which indicates that the email contains multiple different representations of the same email - # body. The same instance variables defined in the action are passed to all email templates. - # - # Implicit template rendering is not performed if any attachments or parts have been added to the email. - # This means that you'll have to manually add each part to the email and set the content type of the email - # to multipart/alternative. - # - # = Attachments - # - # Sending attachment in emails is easy: - # - # class NotifierMailer < ApplicationMailer - # def welcome(recipient) - # attachments['free_book.pdf'] = File.read('path/to/file.pdf') - # mail(to: recipient, subject: "New account information") - # end - # end - # - # Which will (if it had both a welcome.text.erb and welcome.html.erb - # template in the view directory), send a complete multipart/mixed email with two parts, - # the first part being a multipart/alternative with the text and HTML email parts inside, - # and the second being a application/pdf with a Base64 encoded copy of the file.pdf book - # with the filename +free_book.pdf+. - # - # If you need to send attachments with no content, you need to create an empty view for it, - # or add an empty body parameter like this: - # - # class NotifierMailer < ApplicationMailer - # def welcome(recipient) - # attachments['free_book.pdf'] = File.read('path/to/file.pdf') - # mail(to: recipient, subject: "New account information", body: "") - # end - # end - # - # You can also send attachments with html template, in this case you need to add body, attachments, - # and custom content type like this: - # - # class NotifierMailer < ApplicationMailer - # def welcome(recipient) - # attachments["free_book.pdf"] = File.read("path/to/file.pdf") - # mail(to: recipient, - # subject: "New account information", - # content_type: "text/html", - # body: "Hello there") - # end - # end - # - # = Inline Attachments - # - # You can also specify that a file should be displayed inline with other HTML. This is useful - # if you want to display a corporate logo or a photo. - # - # class NotifierMailer < ApplicationMailer - # def welcome(recipient) - # attachments.inline['photo.png'] = File.read('path/to/photo.png') - # mail(to: recipient, subject: "Here is what we look like") - # end - # end - # - # And then to reference the image in the view, you create a welcome.html.erb file and - # make a call to +image_tag+ passing in the attachment you want to display and then call - # +url+ on the attachment to get the relative content id path for the image source: - # - #

Please Don't Cringe

- # - # <%= image_tag attachments['photo.png'].url -%> - # - # As we are using Action View's +image_tag+ method, you can pass in any other options you want: - # - #

Please Don't Cringe

- # - # <%= image_tag attachments['photo.png'].url, alt: 'Our Photo', class: 'photo' -%> - # - # = Observing and Intercepting Mails - # - # Action Mailer provides hooks into the Mail observer and interceptor methods. These allow you to - # register classes that are called during the mail delivery life cycle. - # - # An observer class must implement the :delivered_email(message) method which will be - # called once for every email sent after the email has been sent. - # - # An interceptor class must implement the :delivering_email(message) method which will be - # called before the email is sent, allowing you to make modifications to the email before it hits - # the delivery agents. Your class should make any needed modifications directly to the passed - # in Mail::Message instance. - # - # = Default Hash - # - # Action Mailer provides some intelligent defaults for your emails, these are usually specified in a - # default method inside the class definition: - # - # class NotifierMailer < ApplicationMailer - # default sender: 'system@example.com' - # end - # - # You can pass in any header value that a Mail::Message accepts. Out of the box, - # ActionMailer::Base sets the following: - # - # * mime_version: "1.0" - # * charset: "UTF-8" - # * content_type: "text/plain" - # * parts_order: [ "text/plain", "text/enriched", "text/html" ] - # - # parts_order and charset are not actually valid Mail::Message header fields, - # but Action Mailer translates them appropriately and sets the correct values. - # - # As you can pass in any header, you need to either quote the header as a string, or pass it in as - # an underscored symbol, so the following will work: - # - # class NotifierMailer < ApplicationMailer - # default 'Content-Transfer-Encoding' => '7bit', - # content_description: 'This is a description' - # end - # - # Finally, Action Mailer also supports passing Proc and Lambda objects into the default hash, - # so you can define methods that evaluate as the message is being generated: - # - # class NotifierMailer < ApplicationMailer - # default 'X-Special-Header' => Proc.new { my_method }, to: -> { @inviter.email_address } - # - # private - # def my_method - # 'some complex call' - # end - # end - # - # Note that the proc/lambda is evaluated right at the start of the mail message generation, so if you - # set something in the default hash using a proc, and then set the same thing inside of your - # mailer method, it will get overwritten by the mailer method. - # - # It is also possible to set these default options that will be used in all mailers through - # the default_options= configuration in config/application.rb: - # - # config.action_mailer.default_options = { from: "no-reply@example.org" } - # - # = Callbacks - # - # You can specify callbacks using before_action and after_action for configuring your messages. - # This may be useful, for example, when you want to add default inline attachments for all - # messages sent out by a certain mailer class: - # - # class NotifierMailer < ApplicationMailer - # before_action :add_inline_attachment! - # - # def welcome - # mail - # end - # - # private - # def add_inline_attachment! - # attachments.inline["footer.jpg"] = File.read('/path/to/filename.jpg') - # end - # end - # - # Callbacks in Action Mailer are implemented using - # AbstractController::Callbacks, so you can define and configure - # callbacks in the same manner that you would use callbacks in classes that - # inherit from ActionController::Base. - # - # Note that unless you have a specific reason to do so, you should prefer - # using before_action rather than after_action in your - # Action Mailer classes so that headers are parsed properly. - # - # = Previewing emails - # - # You can preview your email templates visually by adding a mailer preview file to the - # ActionMailer::Base.preview_path. Since most emails do something interesting - # with database data, you'll need to write some scenarios to load messages with fake data: - # - # class NotifierMailerPreview < ActionMailer::Preview - # def welcome - # NotifierMailer.welcome(User.first) - # end - # end - # - # Methods must return a Mail::Message object which can be generated by calling the mailer - # method without the additional deliver_now / deliver_later. The location of the - # mailer previews directory can be configured using the preview_path option which has a default - # of test/mailers/previews: - # - # config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews" - # - # An overview of all previews is accessible at http://localhost:3000/rails/mailers - # on a running development server instance. - # - # Previews can also be intercepted in a similar manner as deliveries can be by registering - # a preview interceptor that has a previewing_email method: - # - # class CssInlineStyler - # def self.previewing_email(message) - # # inline CSS styles - # end - # end - # - # config.action_mailer.preview_interceptors :css_inline_styler - # - # Note that interceptors need to be registered both with register_interceptor - # and register_preview_interceptor if they should operate on both sending and - # previewing emails. - # - # = Configuration options - # - # These options are specified on the class level, like - # ActionMailer::Base.raise_delivery_errors = true - # - # * default_options - You can pass this in at a class level as well as within the class itself as - # per the above section. - # - # * logger - the logger is used for generating information on the mailing run if available. - # Can be set to +nil+ for no logging. Compatible with both Ruby's own +Logger+ and Log4r loggers. - # - # * smtp_settings - Allows detailed configuration for :smtp delivery method: - # * :address - Allows you to use a remote mail server. Just change it from its default - # "localhost" setting. - # * :port - On the off chance that your mail server doesn't run on port 25, you can change it. - # * :domain - If you need to specify a HELO domain, you can do it here. - # * :user_name - If your mail server requires authentication, set the username in this setting. - # * :password - If your mail server requires authentication, set the password in this setting. - # * :authentication - If your mail server requires authentication, you need to specify the - # authentication type here. - # This is a symbol and one of :plain (will send the password Base64 encoded), :login (will - # send the password Base64 encoded) or :cram_md5 (combines a Challenge/Response mechanism to exchange - # information and a cryptographic Message Digest 5 algorithm to hash important information) - # * :enable_starttls_auto - Detects if STARTTLS is enabled in your SMTP server and starts - # to use it. Defaults to true. - # * :openssl_verify_mode - When using TLS, you can set how OpenSSL checks the certificate. This is - # really useful if you need to validate a self-signed and/or a wildcard certificate. You can use the name - # of an OpenSSL verify constant ('none' or 'peer') or directly the constant - # (OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER). - # :ssl/:tls Enables the SMTP connection to use SMTP/TLS (SMTPS: SMTP over direct TLS connection) - # - # * sendmail_settings - Allows you to override options for the :sendmail delivery method. - # * :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. - # * :arguments - The command line arguments. Defaults to -i with -f sender@address - # added automatically before the message is sent. - # - # * file_settings - Allows you to override options for the :file delivery method. - # * :location - The directory into which emails will be written. Defaults to the application - # tmp/mails. - # - # * raise_delivery_errors - Whether or not errors should be raised if the email fails to be delivered. - # - # * delivery_method - Defines a delivery method. Possible values are :smtp (default), - # :sendmail, :test, and :file. Or you may provide a custom delivery method - # object e.g. +MyOwnDeliveryMethodClass+. See the Mail gem documentation on the interface you need to - # implement for a custom delivery agent. - # - # * perform_deliveries - Determines whether emails are actually sent from Action Mailer when you - # call .deliver on an email message or on an Action Mailer method. This is on by default but can - # be turned off to aid in functional testing. - # - # * deliveries - Keeps an array of all the emails sent out through the Action Mailer with - # delivery_method :test. Most useful for unit and functional testing. - # - # * deliver_later_queue_name - The name of the queue used with deliver_later. Defaults to +mailers+. - class Base < AbstractController::Base - include DeliveryMethods - include Rescuable - include Parameterized - include Previews - - abstract! - - include AbstractController::Rendering - - include AbstractController::Logger - include AbstractController::Helpers - include AbstractController::Translation - include AbstractController::AssetPaths - include AbstractController::Callbacks - include AbstractController::Caching - - include ActionView::Layouts - - PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + [:@_action_has_layout] - - def _protected_ivars # :nodoc: - PROTECTED_IVARS - end - - helper ActionMailer::MailHelper - - class_attribute :default_params - self.default_params = { - mime_version: "1.0", - charset: "UTF-8", - content_type: "text/plain", - parts_order: [ "text/plain", "text/enriched", "text/html" ] - }.freeze - - class << self - # Register one or more Observers which will be notified when mail is delivered. - def register_observers(*observers) - observers.flatten.compact.each { |observer| register_observer(observer) } - end - - # Register one or more Interceptors which will be called before mail is sent. - def register_interceptors(*interceptors) - interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) } - end - - # Register an Observer which will be notified when mail is delivered. - # Either a class, string or symbol can be passed in as the Observer. - # If a string or symbol is passed in it will be camelized and constantized. - def register_observer(observer) - Mail.register_observer(observer_class_for(observer)) - end - - # Register an Interceptor which will be called before mail is sent. - # Either a class, string or symbol can be passed in as the Interceptor. - # If a string or symbol is passed in it will be camelized and constantized. - def register_interceptor(interceptor) - Mail.register_interceptor(observer_class_for(interceptor)) - end - - def observer_class_for(value) # :nodoc: - case value - when String, Symbol - value.to_s.camelize.constantize - else - value - end - end - private :observer_class_for - - # Returns the name of the current mailer. This method is also being used as a path for a view lookup. - # If this is an anonymous mailer, this method will return +anonymous+ instead. - def mailer_name - @mailer_name ||= anonymous? ? "anonymous" : name.underscore - end - # Allows to set the name of current mailer. - attr_writer :mailer_name - alias :controller_path :mailer_name - - # Sets the defaults through app configuration: - # - # config.action_mailer.default(from: "no-reply@example.org") - # - # Aliased by ::default_options= - def default(value = nil) - self.default_params = default_params.merge(value).freeze if value - default_params - end - # Allows to set defaults through app configuration: - # - # config.action_mailer.default_options = { from: "no-reply@example.org" } - alias :default_options= :default - - # Receives a raw email, parses it into an email object, decodes it, - # instantiates a new mailer, and passes the email object to the mailer - # object's +receive+ method. - # - # If you want your mailer to be able to process incoming messages, you'll - # need to implement a +receive+ method that accepts the raw email string - # as a parameter: - # - # class MyMailer < ActionMailer::Base - # def receive(mail) - # # ... - # end - # end - def receive(raw_mail) - ActiveSupport::Notifications.instrument("receive.action_mailer") do |payload| - mail = Mail.new(raw_mail) - set_payload_for_mail(payload, mail) - new.receive(mail) - end - end - - # Wraps an email delivery inside of ActiveSupport::Notifications instrumentation. - # - # This method is actually called by the Mail::Message object itself - # through a callback when you call :deliver on the Mail::Message, - # calling +deliver_mail+ directly and passing a Mail::Message will do - # nothing except tell the logger you sent the email. - def deliver_mail(mail) #:nodoc: - ActiveSupport::Notifications.instrument("deliver.action_mailer") do |payload| - set_payload_for_mail(payload, mail) - yield # Let Mail do the delivery actions - end - end - - private - - def set_payload_for_mail(payload, mail) - payload[:mailer] = name - payload[:message_id] = mail.message_id - payload[:subject] = mail.subject - payload[:to] = mail.to - payload[:from] = mail.from - payload[:bcc] = mail.bcc if mail.bcc.present? - payload[:cc] = mail.cc if mail.cc.present? - payload[:date] = mail.date - payload[:mail] = mail.encoded - end - - def method_missing(method_name, *args) - if action_methods.include?(method_name.to_s) - MessageDelivery.new(self, method_name, *args) - else - super - end - end - - def respond_to_missing?(method, include_all = false) - action_methods.include?(method.to_s) || super - end - end - - attr_internal :message - - # Instantiate a new mailer object. If +method_name+ is not +nil+, the mailer - # will be initialized according to the named method. If not, the mailer will - # remain uninitialized (useful when you only need to invoke the "receive" - # method, for instance). - def initialize - super() - @_mail_was_called = false - @_message = Mail.new - end - - def process(method_name, *args) #:nodoc: - payload = { - mailer: self.class.name, - action: method_name, - args: args - } - - ActiveSupport::Notifications.instrument("process.action_mailer", payload) do - super - @_message = NullMail.new unless @_mail_was_called - end - end - - class NullMail #:nodoc: - def body; "" end - def header; {} end - - def respond_to?(string, include_all = false) - true - end - - def method_missing(*args) - nil - end - end - - # Returns the name of the mailer object. - def mailer_name - self.class.mailer_name - end - - # Allows you to pass random and unusual headers to the new Mail::Message - # object which will add them to itself. - # - # headers['X-Special-Domain-Specific-Header'] = "SecretValue" - # - # You can also pass a hash into headers of header field names and values, - # which will then be set on the Mail::Message object: - # - # headers 'X-Special-Domain-Specific-Header' => "SecretValue", - # 'In-Reply-To' => incoming.message_id - # - # The resulting Mail::Message will have the following in its header: - # - # X-Special-Domain-Specific-Header: SecretValue - # - # Note about replacing already defined headers: - # - # * +subject+ - # * +sender+ - # * +from+ - # * +to+ - # * +cc+ - # * +bcc+ - # * +reply-to+ - # * +orig-date+ - # * +message-id+ - # * +references+ - # - # Fields can only appear once in email headers while other fields such as - # X-Anything can appear multiple times. - # - # If you want to replace any header which already exists, first set it to - # +nil+ in order to reset the value otherwise another field will be added - # for the same header. - def headers(args = nil) - if args - @_message.headers(args) - else - @_message - end - end - - # Allows you to add attachments to an email, like so: - # - # mail.attachments['filename.jpg'] = File.read('/path/to/filename.jpg') - # - # If you do this, then Mail will take the file name and work out the mime type. - # It will also set the Content-Type, Content-Disposition, Content-Transfer-Encoding - # and encode the contents of the attachment in Base64. - # - # You can also specify overrides if you want by passing a hash instead of a string: - # - # mail.attachments['filename.jpg'] = {mime_type: 'application/gzip', - # content: File.read('/path/to/filename.jpg')} - # - # If you want to use encoding other than Base64 then you will need to pass encoding - # type along with the pre-encoded content as Mail doesn't know how to decode the - # data: - # - # file_content = SpecialEncode(File.read('/path/to/filename.jpg')) - # mail.attachments['filename.jpg'] = {mime_type: 'application/gzip', - # encoding: 'SpecialEncoding', - # content: file_content } - # - # You can also search for specific attachments: - # - # # By Filename - # mail.attachments['filename.jpg'] # => Mail::Part object or nil - # - # # or by index - # mail.attachments[0] # => Mail::Part (first attachment) - # - def attachments - if @_mail_was_called - LateAttachmentsProxy.new(@_message.attachments) - else - @_message.attachments - end - end - - class LateAttachmentsProxy < SimpleDelegator - def inline; _raise_error end - def []=(_name, _content); _raise_error end - - private - def _raise_error - raise RuntimeError, "Can't add attachments after `mail` was called.\n" \ - "Make sure to use `attachments[]=` before calling `mail`." - end - end - - # The main method that creates the message and renders the email templates. There are - # two ways to call this method, with a block, or without a block. - # - # It accepts a headers hash. This hash allows you to specify - # the most used headers in an email message, these are: - # - # * +:subject+ - The subject of the message, if this is omitted, Action Mailer will - # ask the Rails I18n class for a translated +:subject+ in the scope of - # [mailer_scope, action_name] or if this is missing, will translate the - # humanized version of the +action_name+ - # * +:to+ - Who the message is destined for, can be a string of addresses, or an array - # of addresses. - # * +:from+ - Who the message is from - # * +:cc+ - Who you would like to Carbon-Copy on this email, can be a string of addresses, - # or an array of addresses. - # * +:bcc+ - Who you would like to Blind-Carbon-Copy on this email, can be a string of - # addresses, or an array of addresses. - # * +:reply_to+ - Who to set the Reply-To header of the email to. - # * +:date+ - The date to say the email was sent on. - # - # You can set default values for any of the above headers (except +:date+) - # by using the ::default class method: - # - # class Notifier < ActionMailer::Base - # default from: 'no-reply@test.lindsaar.net', - # bcc: 'email_logger@test.lindsaar.net', - # reply_to: 'bounces@test.lindsaar.net' - # end - # - # If you need other headers not listed above, you can either pass them in - # as part of the headers hash or use the headers['name'] = value - # method. - # - # When a +:return_path+ is specified as header, that value will be used as - # the 'envelope from' address for the Mail message. Setting this is useful - # when you want delivery notifications sent to a different address than the - # one in +:from+. Mail will actually use the +:return_path+ in preference - # to the +:sender+ in preference to the +:from+ field for the 'envelope - # from' value. - # - # If you do not pass a block to the +mail+ method, it will find all - # templates in the view paths using by default the mailer name and the - # method name that it is being called from, it will then create parts for - # each of these templates intelligently, making educated guesses on correct - # content type and sequence, and return a fully prepared Mail::Message - # ready to call :deliver on to send. - # - # For example: - # - # class Notifier < ActionMailer::Base - # default from: 'no-reply@test.lindsaar.net' - # - # def welcome - # mail(to: 'mikel@test.lindsaar.net') - # end - # end - # - # Will look for all templates at "app/views/notifier" with name "welcome". - # If no welcome template exists, it will raise an ActionView::MissingTemplate error. - # - # However, those can be customized: - # - # mail(template_path: 'notifications', template_name: 'another') - # - # And now it will look for all templates at "app/views/notifications" with name "another". - # - # If you do pass a block, you can render specific templates of your choice: - # - # mail(to: 'mikel@test.lindsaar.net') do |format| - # format.text - # format.html - # end - # - # You can even render plain text directly without using a template: - # - # mail(to: 'mikel@test.lindsaar.net') do |format| - # format.text { render plain: "Hello Mikel!" } - # format.html { render html: "

Hello Mikel!

".html_safe } - # end - # - # Which will render a +multipart/alternative+ email with +text/plain+ and - # +text/html+ parts. - # - # The block syntax also allows you to customize the part headers if desired: - # - # mail(to: 'mikel@test.lindsaar.net') do |format| - # format.text(content_transfer_encoding: "base64") - # format.html - # end - # - def mail(headers = {}, &block) - return message if @_mail_was_called && headers.blank? && !block - - # At the beginning, do not consider class default for content_type - content_type = headers[:content_type] - - headers = apply_defaults(headers) - - # Apply charset at the beginning so all fields are properly quoted - message.charset = charset = headers[:charset] - - # Set configure delivery behavior - wrap_delivery_behavior!(headers[:delivery_method], headers[:delivery_method_options]) - - assign_headers_to_message(message, headers) - - # Render the templates and blocks - responses = collect_responses(headers, &block) - @_mail_was_called = true - - create_parts_from_responses(message, responses) - - # Setup content type, reapply charset and handle parts order - message.content_type = set_content_type(message, content_type, headers[:content_type]) - message.charset = charset - - if message.multipart? - message.body.set_sort_order(headers[:parts_order]) - message.body.sort_parts! - end - - message - end - - private - - # Used by #mail to set the content type of the message. - # - # It will use the given +user_content_type+, or multipart if the mail - # message has any attachments. If the attachments are inline, the content - # type will be "multipart/related", otherwise "multipart/mixed". - # - # If there is no content type passed in via headers, and there are no - # attachments, or the message is multipart, then the default content type is - # used. - def set_content_type(m, user_content_type, class_default) # :doc: - params = m.content_type_parameters || {} - case - when user_content_type.present? - user_content_type - when m.has_attachments? - if m.attachments.detect(&:inline?) - ["multipart", "related", params] - else - ["multipart", "mixed", params] - end - when m.multipart? - ["multipart", "alternative", params] - else - m.content_type || class_default - end - end - - # Translates the +subject+ using Rails I18n class under [mailer_scope, action_name] scope. - # If it does not find a translation for the +subject+ under the specified scope it will default to a - # humanized version of the action_name. - # If the subject has interpolations, you can pass them through the +interpolations+ parameter. - def default_i18n_subject(interpolations = {}) # :doc: - mailer_scope = self.class.mailer_name.tr("/", ".") - I18n.t(:subject, interpolations.merge(scope: [mailer_scope, action_name], default: action_name.humanize)) - end - - # Emails do not support relative path links. - def self.supports_path? # :doc: - false - end - - def apply_defaults(headers) - default_values = self.class.default.map do |key, value| - [ - key, - compute_default(value) - ] - end.to_h - - headers_with_defaults = headers.reverse_merge(default_values) - headers_with_defaults[:subject] ||= default_i18n_subject - headers_with_defaults - end - - def compute_default(value) - return value unless value.is_a?(Proc) - - if value.arity == 1 - instance_exec(self, &value) - else - instance_exec(&value) - end - end - - def assign_headers_to_message(message, headers) - assignable = headers.except(:parts_order, :content_type, :body, :template_name, - :template_path, :delivery_method, :delivery_method_options) - assignable.each { |k, v| message[k] = v } - end - - def collect_responses(headers) - if block_given? - collector = ActionMailer::Collector.new(lookup_context) { render(action_name) } - yield(collector) - collector.responses - elsif headers[:body] - collect_responses_from_text(headers) - else - collect_responses_from_templates(headers) - end - end - - def collect_responses_from_text(headers) - [{ - body: headers.delete(:body), - content_type: headers[:content_type] || "text/plain" - }] - end - - def collect_responses_from_templates(headers) - templates_path = headers[:template_path] || self.class.mailer_name - templates_name = headers[:template_name] || action_name - - each_template(Array(templates_path), templates_name).map do |template| - self.formats = template.formats - { - body: render(template: template), - content_type: template.type.to_s - } - end - end - - def each_template(paths, name, &block) - templates = lookup_context.find_all(name, paths) - if templates.empty? - raise ActionView::MissingTemplate.new(paths, name, paths, false, "mailer") - else - templates.uniq(&:formats).each(&block) - end - end - - def create_parts_from_responses(m, responses) - if responses.size == 1 && !m.has_attachments? - responses[0].each { |k, v| m[k] = v } - elsif responses.size > 1 && m.has_attachments? - container = Mail::Part.new - container.content_type = "multipart/alternative" - responses.each { |r| insert_part(container, r, m.charset) } - m.add_part(container) - else - responses.each { |r| insert_part(m, r, m.charset) } - end - end - - def insert_part(container, response, charset) - response[:charset] ||= charset - part = Mail::Part.new(response) - container.add_part(part) - end - - # This and #instrument_name is for caching instrument - def instrument_payload(key) - { - mailer: mailer_name, - key: key - } - end - - def instrument_name - "action_mailer".freeze - end - - ActiveSupport.run_load_hooks(:action_mailer, self) - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/collector.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/collector.rb deleted file mode 100644 index d97a73d65a..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/collector.rb +++ /dev/null @@ -1,30 +0,0 @@ -require "abstract_controller/collector" -require "active_support/core_ext/hash/reverse_merge" -require "active_support/core_ext/array/extract_options" - -module ActionMailer - class Collector - include AbstractController::Collector - attr_reader :responses - - def initialize(context, &block) - @context = context - @responses = [] - @default_render = block - end - - def any(*args, &block) - options = args.extract_options! - raise ArgumentError, "You have to supply at least one format" if args.empty? - args.each { |type| send(type, options.dup, &block) } - end - alias :all :any - - def custom(mime, options = {}) - options.reverse_merge!(content_type: mime.to_s) - @context.formats = [mime.to_sym] - options[:body] = block_given? ? yield : @default_render.call - @responses << options - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/delivery_job.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/delivery_job.rb deleted file mode 100644 index a617daa87e..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/delivery_job.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "active_job" - -module ActionMailer - # The ActionMailer::DeliveryJob class is used when you - # want to send emails outside of the request-response cycle. - # - # Exceptions are rescued and handled by the mailer class. - class DeliveryJob < ActiveJob::Base # :nodoc: - queue_as { ActionMailer::Base.deliver_later_queue_name } - - rescue_from StandardError, with: :handle_exception_with_mailer_class - - def perform(mailer, mail_method, delivery_method, *args) #:nodoc: - mailer.constantize.public_send(mail_method, *args).send(delivery_method) - end - - private - # "Deserialize" the mailer class name by hand in case another argument - # (like a Global ID reference) raised DeserializationError. - def mailer_class - if mailer = Array(@serialized_arguments).first || Array(arguments).first - mailer.constantize - end - end - - def handle_exception_with_mailer_class(exception) - if klass = mailer_class - klass.handle_exception exception - else - raise exception - end - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/delivery_methods.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/delivery_methods.rb deleted file mode 100644 index bcc4ef03cf..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/delivery_methods.rb +++ /dev/null @@ -1,87 +0,0 @@ -require "tmpdir" - -module ActionMailer - # This module handles everything related to mail delivery, from registering - # new delivery methods to configuring the mail object to be sent. - module DeliveryMethods - extend ActiveSupport::Concern - - included do - class_attribute :delivery_methods, :delivery_method - - # Do not make this inheritable, because we always want it to propagate - cattr_accessor :raise_delivery_errors - self.raise_delivery_errors = true - - cattr_accessor :perform_deliveries - self.perform_deliveries = true - - cattr_accessor :deliver_later_queue_name - self.deliver_later_queue_name = :mailers - - self.delivery_methods = {}.freeze - self.delivery_method = :smtp - - add_delivery_method :smtp, Mail::SMTP, - address: "localhost", - port: 25, - domain: "localhost.localdomain", - user_name: nil, - password: nil, - authentication: nil, - enable_starttls_auto: true - - add_delivery_method :file, Mail::FileDelivery, - location: defined?(Rails.root) ? "#{Rails.root}/tmp/mails" : "#{Dir.tmpdir}/mails" - - add_delivery_method :sendmail, Mail::Sendmail, - location: "/usr/sbin/sendmail", - arguments: "-i" - - add_delivery_method :test, Mail::TestMailer - end - - # Helpers for creating and wrapping delivery behavior, used by DeliveryMethods. - module ClassMethods - # Provides a list of emails that have been delivered by Mail::TestMailer - delegate :deliveries, :deliveries=, to: Mail::TestMailer - - # Adds a new delivery method through the given class using the given - # symbol as alias and the default options supplied. - # - # add_delivery_method :sendmail, Mail::Sendmail, - # location: '/usr/sbin/sendmail', - # arguments: '-i' - def add_delivery_method(symbol, klass, default_options = {}) - class_attribute(:"#{symbol}_settings") unless respond_to?(:"#{symbol}_settings") - send(:"#{symbol}_settings=", default_options) - self.delivery_methods = delivery_methods.merge(symbol.to_sym => klass).freeze - end - - def wrap_delivery_behavior(mail, method = nil, options = nil) # :nodoc: - method ||= delivery_method - mail.delivery_handler = self - - case method - when NilClass - raise "Delivery method cannot be nil" - when Symbol - if klass = delivery_methods[method] - mail.delivery_method(klass, (send(:"#{method}_settings") || {}).merge(options || {})) - else - raise "Invalid delivery method #{method.inspect}" - end - else - mail.delivery_method(method) - end - - mail.perform_deliveries = perform_deliveries - mail.raise_delivery_errors = raise_delivery_errors - end - end - - def wrap_delivery_behavior!(*args) # :nodoc: - self.class.wrap_delivery_behavior(message, *args) - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/gem_version.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/gem_version.rb deleted file mode 100644 index 9e4e29f6d0..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActionMailer - # Returns the version of the currently loaded Action Mailer as a Gem::Version. - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/inline_preview_interceptor.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/inline_preview_interceptor.rb deleted file mode 100644 index 980415afe0..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/inline_preview_interceptor.rb +++ /dev/null @@ -1,57 +0,0 @@ -require "base64" - -module ActionMailer - # Implements a mailer preview interceptor that converts image tag src attributes - # that use inline cid: style urls to data: style urls so that they are visible - # when previewing an HTML email in a web browser. - # - # This interceptor is enabled by default. To disable it, delete it from the - # ActionMailer::Base.preview_interceptors array: - # - # ActionMailer::Base.preview_interceptors.delete(ActionMailer::InlinePreviewInterceptor) - # - class InlinePreviewInterceptor - PATTERN = /src=(?:"cid:[^"]+"|'cid:[^']+')/i - - include Base64 - - def self.previewing_email(message) #:nodoc: - new(message).transform! - end - - def initialize(message) #:nodoc: - @message = message - end - - def transform! #:nodoc: - return message if html_part.blank? - - html_part.body = html_part.decoded.gsub(PATTERN) do |match| - if part = find_part(match[9..-2]) - %[src="#{data_url(part)}"] - else - match - end - end - - message - end - - private - def message - @message - end - - def html_part - @html_part ||= message.html_part - end - - def data_url(part) - "data:#{part.mime_type};base64,#{strict_encode64(part.body.raw_source)}" - end - - def find_part(cid) - message.all_parts.find { |p| p.attachment? && p.cid == cid } - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/log_subscriber.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/log_subscriber.rb deleted file mode 100644 index 2c058ccf66..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/log_subscriber.rb +++ /dev/null @@ -1,39 +0,0 @@ -require "active_support/log_subscriber" - -module ActionMailer - # Implements the ActiveSupport::LogSubscriber for logging notifications when - # email is delivered or received. - class LogSubscriber < ActiveSupport::LogSubscriber - # An email was delivered. - def deliver(event) - info do - recipients = Array(event.payload[:to]).join(", ") - "Sent mail to #{recipients} (#{event.duration.round(1)}ms)" - end - - debug { event.payload[:mail] } - end - - # An email was received. - def receive(event) - info { "Received mail (#{event.duration.round(1)}ms)" } - debug { event.payload[:mail] } - end - - # An email was generated. - def process(event) - debug do - mailer = event.payload[:mailer] - action = event.payload[:action] - "#{mailer}##{action}: processed outbound mail in #{event.duration.round(1)}ms" - end - end - - # Use the logger configured for ActionMailer::Base. - def logger - ActionMailer::Base.logger - end - end -end - -ActionMailer::LogSubscriber.attach_to :action_mailer diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/mail_helper.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/mail_helper.rb deleted file mode 100644 index e04fc08866..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/mail_helper.rb +++ /dev/null @@ -1,70 +0,0 @@ -module ActionMailer - # Provides helper methods for ActionMailer::Base that can be used for easily - # formatting messages, accessing mailer or message instances, and the - # attachments list. - module MailHelper - # Take the text and format it, indented two spaces for each line, and - # wrapped at 72 columns: - # - # text = <<-TEXT - # This is - # the paragraph. - # - # * item1 * item2 - # TEXT - # - # block_format text - # # => " This is the paragraph.\n\n * item1\n * item2\n" - def block_format(text) - formatted = text.split(/\n\r?\n/).collect { |paragraph| - format_paragraph(paragraph) - }.join("\n\n") - - # Make list points stand on their own line - formatted.gsub!(/[ ]*([*]+) ([^*]*)/) { " #{$1} #{$2.strip}\n" } - formatted.gsub!(/[ ]*([#]+) ([^#]*)/) { " #{$1} #{$2.strip}\n" } - - formatted - end - - # Access the mailer instance. - def mailer - @_controller - end - - # Access the message instance. - def message - @_message - end - - # Access the message attachments list. - def attachments - mailer.attachments - end - - # Returns +text+ wrapped at +len+ columns and indented +indent+ spaces. - # By default column length +len+ equals 72 characters and indent - # +indent+ equal two spaces. - # - # my_text = 'Here is a sample text with more than 40 characters' - # - # format_paragraph(my_text, 25, 4) - # # => " Here is a sample text with\n more than 40 characters" - def format_paragraph(text, len = 72, indent = 2) - sentences = [[]] - - text.split.each do |word| - if sentences.first.present? && (sentences.last + [word]).join(" ").length > len - sentences << [word] - else - sentences.last << word - end - end - - indentation = " " * indent - sentences.map! { |sentence| - "#{indentation}#{sentence.join(' ')}" - }.join "\n" - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/message_delivery.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/message_delivery.rb deleted file mode 100644 index cf7c57e6bf..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/message_delivery.rb +++ /dev/null @@ -1,125 +0,0 @@ -require "delegate" - -module ActionMailer - # The ActionMailer::MessageDelivery class is used by - # ActionMailer::Base when creating a new mailer. - # MessageDelivery is a wrapper (+Delegator+ subclass) around a lazy - # created Mail::Message. You can get direct access to the - # Mail::Message, deliver the email or schedule the email to be sent - # through Active Job. - # - # Notifier.welcome(User.first) # an ActionMailer::MessageDelivery object - # Notifier.welcome(User.first).deliver_now # sends the email - # Notifier.welcome(User.first).deliver_later # enqueue email delivery as a job through Active Job - # Notifier.welcome(User.first).message # a Mail::Message object - class MessageDelivery < Delegator - def initialize(mailer_class, action, *args) #:nodoc: - @mailer_class, @action, @args = mailer_class, action, args - - # The mail is only processed if we try to call any methods on it. - # Typical usage will leave it unloaded and call deliver_later. - @processed_mailer = nil - @mail_message = nil - end - - # Method calls are delegated to the Mail::Message that's ready to deliver. - def __getobj__ #:nodoc: - @mail_message ||= processed_mailer.message - end - - # Unused except for delegator internals (dup, marshaling). - def __setobj__(mail_message) #:nodoc: - @mail_message = mail_message - end - - # Returns the resulting Mail::Message - def message - __getobj__ - end - - # Was the delegate loaded, causing the mailer action to be processed? - def processed? - @processed_mailer || @mail_message - end - - # Enqueues the email to be delivered through Active Job. When the - # job runs it will send the email using +deliver_now!+. That means - # that the message will be sent bypassing checking +perform_deliveries+ - # and +raise_delivery_errors+, so use with caution. - # - # Notifier.welcome(User.first).deliver_later! - # Notifier.welcome(User.first).deliver_later!(wait: 1.hour) - # Notifier.welcome(User.first).deliver_later!(wait_until: 10.hours.from_now) - # - # Options: - # - # * :wait - Enqueue the email to be delivered with a delay - # * :wait_until - Enqueue the email to be delivered at (after) a specific date / time - # * :queue - Enqueue the email on the specified queue - def deliver_later!(options = {}) - enqueue_delivery :deliver_now!, options - end - - # Enqueues the email to be delivered through Active Job. When the - # job runs it will send the email using +deliver_now+. - # - # Notifier.welcome(User.first).deliver_later - # Notifier.welcome(User.first).deliver_later(wait: 1.hour) - # Notifier.welcome(User.first).deliver_later(wait_until: 10.hours.from_now) - # - # Options: - # - # * :wait - Enqueue the email to be delivered with a delay. - # * :wait_until - Enqueue the email to be delivered at (after) a specific date / time. - # * :queue - Enqueue the email on the specified queue. - def deliver_later(options = {}) - enqueue_delivery :deliver_now, options - end - - # Delivers an email without checking +perform_deliveries+ and +raise_delivery_errors+, - # so use with caution. - # - # Notifier.welcome(User.first).deliver_now! - # - def deliver_now! - processed_mailer.handle_exceptions do - message.deliver! - end - end - - # Delivers an email: - # - # Notifier.welcome(User.first).deliver_now - # - def deliver_now - processed_mailer.handle_exceptions do - message.deliver - end - end - - private - # Returns the processed Mailer instance. We keep this instance - # on hand so we can delegate exception handling to it. - def processed_mailer - @processed_mailer ||= @mailer_class.new.tap do |mailer| - mailer.process @action, *@args - end - end - - def enqueue_delivery(delivery_method, options = {}) - if processed? - ::Kernel.raise "You've accessed the message before asking to " \ - "deliver it later, so you may have made local changes that would " \ - "be silently lost if we enqueued a job to deliver it. Why? Only " \ - "the mailer method *arguments* are passed with the delivery job! " \ - "Do not access the message in any way if you mean to deliver it " \ - "later. Workarounds: 1. don't touch the message before calling " \ - "#deliver_later, 2. only touch the message *within your mailer " \ - "method*, or 3. use a custom Active Job instead of #deliver_later." - else - args = @mailer_class.name, @action.to_s, delivery_method.to_s, *@args - ::ActionMailer::DeliveryJob.set(options).perform_later(*args) - end - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/parameterized.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/parameterized.rb deleted file mode 100644 index 3acacc1f14..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/parameterized.rb +++ /dev/null @@ -1,152 +0,0 @@ -module ActionMailer - # Provides the option to parameterize mailers in order to share instance variable - # setup, processing, and common headers. - # - # Consider this example that does not use parameterization: - # - # class InvitationsMailer < ApplicationMailer - # def account_invitation(inviter, invitee) - # @account = inviter.account - # @inviter = inviter - # @invitee = invitee - # - # subject = "#{@inviter.name} invited you to their Basecamp (#{@account.name})" - # - # mail \ - # subject: subject, - # to: invitee.email_address, - # from: common_address(inviter), - # reply_to: inviter.email_address_with_name - # end - # - # def project_invitation(project, inviter, invitee) - # @account = inviter.account - # @project = project - # @inviter = inviter - # @invitee = invitee - # @summarizer = ProjectInvitationSummarizer.new(@project.bucket) - # - # subject = "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})" - # - # mail \ - # subject: subject, - # to: invitee.email_address, - # from: common_address(inviter), - # reply_to: inviter.email_address_with_name - # end - # - # def bulk_project_invitation(projects, inviter, invitee) - # @account = inviter.account - # @projects = projects.sort_by(&:name) - # @inviter = inviter - # @invitee = invitee - # - # subject = "#{@inviter.name.familiar} added you to some new stuff in Basecamp (#{@account.name})" - # - # mail \ - # subject: subject, - # to: invitee.email_address, - # from: common_address(inviter), - # reply_to: inviter.email_address_with_name - # end - # end - # - # InvitationsMailer.account_invitation(person_a, person_b).deliver_later - # - # Using parameterized mailers, this can be rewritten as: - # - # class InvitationsMailer < ApplicationMailer - # before_action { @inviter, @invitee = params[:inviter], params[:invitee] } - # before_action { @account = params[:inviter].account } - # - # default to: -> { @invitee.email_address }, - # from: -> { common_address(@inviter) }, - # reply_to: -> { @inviter.email_address_with_name } - # - # def account_invitation - # mail subject: "#{@inviter.name} invited you to their Basecamp (#{@account.name})" - # end - # - # def project_invitation - # @project = params[:project] - # @summarizer = ProjectInvitationSummarizer.new(@project.bucket) - # - # mail subject: "#{@inviter.name.familiar} added you to a project in Basecamp (#{@account.name})" - # end - # - # def bulk_project_invitation - # @projects = params[:projects].sort_by(&:name) - # - # mail subject: "#{@inviter.name.familiar} added you to some new stuff in Basecamp (#{@account.name})" - # end - # end - # - # InvitationsMailer.with(inviter: person_a, invitee: person_b).account_invitation.deliver_later - module Parameterized - extend ActiveSupport::Concern - - included do - attr_accessor :params - end - - module ClassMethods - # Provide the parameters to the mailer in order to use them in the instance methods and callbacks. - # - # InvitationsMailer.with(inviter: person_a, invitee: person_b).account_invitation.deliver_later - # - # See Parameterized documentation for full example. - def with(params) - ActionMailer::Parameterized::Mailer.new(self, params) - end - end - - class Mailer # :nodoc: - def initialize(mailer, params) - @mailer, @params = mailer, params - end - - private - def method_missing(method_name, *args) - if @mailer.action_methods.include?(method_name.to_s) - ActionMailer::Parameterized::MessageDelivery.new(@mailer, method_name, @params, *args) - else - super - end - end - - def respond_to_missing?(method, include_all = false) - @mailer.respond_to?(method, include_all) - end - end - - class MessageDelivery < ActionMailer::MessageDelivery # :nodoc: - def initialize(mailer_class, action, params, *args) - super(mailer_class, action, *args) - @params = params - end - - private - def processed_mailer - @processed_mailer ||= @mailer_class.new.tap do |mailer| - mailer.params = @params - mailer.process @action, *@args - end - end - - def enqueue_delivery(delivery_method, options = {}) - if processed? - super - else - args = @mailer_class.name, @action.to_s, delivery_method.to_s, @params, *@args - ActionMailer::Parameterized::DeliveryJob.set(options).perform_later(*args) - end - end - end - - class DeliveryJob < ActionMailer::DeliveryJob # :nodoc: - def perform(mailer, mail_method, delivery_method, params, *args) - mailer.constantize.with(params).public_send(mail_method, *args).send(delivery_method) - end - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/preview.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/preview.rb deleted file mode 100644 index b0152aff03..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/preview.rb +++ /dev/null @@ -1,119 +0,0 @@ -require "active_support/descendants_tracker" - -module ActionMailer - module Previews #:nodoc: - extend ActiveSupport::Concern - - included do - # Set the location of mailer previews through app configuration: - # - # config.action_mailer.preview_path = "#{Rails.root}/lib/mailer_previews" - # - mattr_accessor :preview_path, instance_writer: false - - # Enable or disable mailer previews through app configuration: - # - # config.action_mailer.show_previews = true - # - # Defaults to true for development environment - # - mattr_accessor :show_previews, instance_writer: false - - # :nodoc: - mattr_accessor :preview_interceptors, instance_writer: false - self.preview_interceptors = [ActionMailer::InlinePreviewInterceptor] - end - - module ClassMethods - # Register one or more Interceptors which will be called before mail is previewed. - def register_preview_interceptors(*interceptors) - interceptors.flatten.compact.each { |interceptor| register_preview_interceptor(interceptor) } - end - - # Register an Interceptor which will be called before mail is previewed. - # Either a class or a string can be passed in as the Interceptor. If a - # string is passed in it will be constantized. - def register_preview_interceptor(interceptor) - preview_interceptor = \ - case interceptor - when String, Symbol - interceptor.to_s.camelize.constantize - else - interceptor - end - - unless preview_interceptors.include?(preview_interceptor) - preview_interceptors << preview_interceptor - end - end - end - end - - class Preview - extend ActiveSupport::DescendantsTracker - - class << self - # Returns all mailer preview classes. - def all - load_previews if descendants.empty? - descendants - end - - # Returns the mail object for the given email name. The registered preview - # interceptors will be informed so that they can transform the message - # as they would if the mail was actually being delivered. - def call(email) - preview = new - message = preview.public_send(email) - inform_preview_interceptors(message) - message - end - - # Returns all of the available email previews. - def emails - public_instance_methods(false).map(&:to_s).sort - end - - # Returns true if the email exists. - def email_exists?(email) - emails.include?(email) - end - - # Returns true if the preview exists. - def exists?(preview) - all.any? { |p| p.preview_name == preview } - end - - # Find a mailer preview by its underscored class name. - def find(preview) - all.find { |p| p.preview_name == preview } - end - - # Returns the underscored name of the mailer preview without the suffix. - def preview_name - name.sub(/Preview$/, "").underscore - end - - private - def load_previews - if preview_path - Dir["#{preview_path}/**/*_preview.rb"].each { |file| require_dependency file } - end - end - - def preview_path - Base.preview_path - end - - def show_previews - Base.show_previews - end - - def inform_preview_interceptors(message) - Base.preview_interceptors.each do |interceptor| - interceptor.previewing_email(message) - end - end - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/railtie.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/railtie.rb deleted file mode 100644 index 913df8cf93..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/railtie.rb +++ /dev/null @@ -1,74 +0,0 @@ -require "active_job/railtie" -require "action_mailer" -require "rails" -require "abstract_controller/railties/routes_helpers" - -module ActionMailer - class Railtie < Rails::Railtie # :nodoc: - config.action_mailer = ActiveSupport::OrderedOptions.new - config.eager_load_namespaces << ActionMailer - - initializer "action_mailer.logger" do - ActiveSupport.on_load(:action_mailer) { self.logger ||= Rails.logger } - end - - initializer "action_mailer.set_configs" do |app| - paths = app.config.paths - options = app.config.action_mailer - - if app.config.force_ssl - options.default_url_options ||= {} - options.default_url_options[:protocol] ||= "https" - end - - options.assets_dir ||= paths["public"].first - options.javascripts_dir ||= paths["public/javascripts"].first - options.stylesheets_dir ||= paths["public/stylesheets"].first - options.show_previews = Rails.env.development? if options.show_previews.nil? - options.cache_store ||= Rails.cache - - if options.show_previews - options.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/test/mailers/previews" : nil - end - - # make sure readers methods get compiled - options.asset_host ||= app.config.asset_host - options.relative_url_root ||= app.config.relative_url_root - - ActiveSupport.on_load(:action_mailer) do - include AbstractController::UrlFor - extend ::AbstractController::Railties::RoutesHelpers.with(app.routes, false) - include app.routes.mounted_helpers - - register_interceptors(options.delete(:interceptors)) - register_preview_interceptors(options.delete(:preview_interceptors)) - register_observers(options.delete(:observers)) - - options.each { |k, v| send("#{k}=", v) } - end - - ActiveSupport.on_load(:action_dispatch_integration_test) { include ActionMailer::TestCase::ClearTestDeliveries } - end - - initializer "action_mailer.compile_config_methods" do - ActiveSupport.on_load(:action_mailer) do - config.compile_methods! if config.respond_to?(:compile_methods!) - end - end - - config.after_initialize do |app| - options = app.config.action_mailer - - if options.show_previews - app.routes.prepend do - get "/rails/mailers" => "rails/mailers#index", internal: true - get "/rails/mailers/*path" => "rails/mailers#preview", internal: true - end - - if options.preview_path - ActiveSupport::Dependencies.autoload_paths << options.preview_path - end - end - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/rescuable.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/rescuable.rb deleted file mode 100644 index f2eabfa057..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/rescuable.rb +++ /dev/null @@ -1,27 +0,0 @@ -module ActionMailer #:nodoc: - # Provides `rescue_from` for mailers. Wraps mailer action processing, - # mail job processing, and mail delivery. - module Rescuable - extend ActiveSupport::Concern - include ActiveSupport::Rescuable - - class_methods do - def handle_exception(exception) #:nodoc: - rescue_with_handler(exception) || raise(exception) - end - end - - def handle_exceptions #:nodoc: - yield - rescue => exception - rescue_with_handler(exception) || raise - end - - private - def process(*) - handle_exceptions do - super - end - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/test_case.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/test_case.rb deleted file mode 100644 index 9ead03a40c..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/test_case.rb +++ /dev/null @@ -1,121 +0,0 @@ -require "active_support/test_case" -require "rails-dom-testing" - -module ActionMailer - class NonInferrableMailerError < ::StandardError - def initialize(name) - super "Unable to determine the mailer to test from #{name}. " \ - "You'll need to specify it using tests YourMailer in your " \ - "test case definition" - end - end - - class TestCase < ActiveSupport::TestCase - module ClearTestDeliveries - extend ActiveSupport::Concern - - included do - setup :clear_test_deliveries - teardown :clear_test_deliveries - end - - private - - def clear_test_deliveries - if ActionMailer::Base.delivery_method == :test - ActionMailer::Base.deliveries.clear - end - end - end - - module Behavior - extend ActiveSupport::Concern - - include ActiveSupport::Testing::ConstantLookup - include TestHelper - include Rails::Dom::Testing::Assertions::SelectorAssertions - include Rails::Dom::Testing::Assertions::DomAssertions - - included do - class_attribute :_mailer_class - setup :initialize_test_deliveries - setup :set_expected_mail - teardown :restore_test_deliveries - ActiveSupport.run_load_hooks(:action_mailer_test_case, self) - end - - module ClassMethods - def tests(mailer) - case mailer - when String, Symbol - self._mailer_class = mailer.to_s.camelize.constantize - when Module - self._mailer_class = mailer - else - raise NonInferrableMailerError.new(mailer) - end - end - - def mailer_class - if mailer = _mailer_class - mailer - else - tests determine_default_mailer(name) - end - end - - def determine_default_mailer(name) - mailer = determine_constant_from_test_name(name) do |constant| - Class === constant && constant < ActionMailer::Base - end - raise NonInferrableMailerError.new(name) if mailer.nil? - mailer - end - end - - private - - def initialize_test_deliveries - set_delivery_method :test - @old_perform_deliveries = ActionMailer::Base.perform_deliveries - ActionMailer::Base.perform_deliveries = true - ActionMailer::Base.deliveries.clear - end - - def restore_test_deliveries - restore_delivery_method - ActionMailer::Base.perform_deliveries = @old_perform_deliveries - end - - def set_delivery_method(method) - @old_delivery_method = ActionMailer::Base.delivery_method - ActionMailer::Base.delivery_method = method - end - - def restore_delivery_method - ActionMailer::Base.deliveries.clear - ActionMailer::Base.delivery_method = @old_delivery_method - end - - def set_expected_mail - @expected = Mail.new - @expected.content_type ["text", "plain", { "charset" => charset }] - @expected.mime_version = "1.0" - end - - def charset - "UTF-8" - end - - def encode(subject) - Mail::Encodings.q_value_encode(subject, charset) - end - - def read_fixture(action) - IO.readlines(File.join(Rails.root, "test", "fixtures", self.class.mailer_class.name.underscore, action)) - end - end - - include Behavior - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/test_helper.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/test_helper.rb deleted file mode 100644 index c30fb1fc18..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/test_helper.rb +++ /dev/null @@ -1,113 +0,0 @@ -require "active_job" - -module ActionMailer - # Provides helper methods for testing Action Mailer, including #assert_emails - # and #assert_no_emails. - module TestHelper - include ActiveJob::TestHelper - - # Asserts that the number of emails sent matches the given number. - # - # def test_emails - # assert_emails 0 - # ContactMailer.welcome.deliver_now - # assert_emails 1 - # ContactMailer.welcome.deliver_now - # assert_emails 2 - # end - # - # If a block is passed, that block should cause the specified number of - # emails to be sent. - # - # def test_emails_again - # assert_emails 1 do - # ContactMailer.welcome.deliver_now - # end - # - # assert_emails 2 do - # ContactMailer.welcome.deliver_now - # ContactMailer.welcome.deliver_now - # end - # end - def assert_emails(number) - if block_given? - original_count = ActionMailer::Base.deliveries.size - yield - new_count = ActionMailer::Base.deliveries.size - assert_equal number, new_count - original_count, "#{number} emails expected, but #{new_count - original_count} were sent" - else - assert_equal number, ActionMailer::Base.deliveries.size - end - end - - # Asserts that no emails have been sent. - # - # def test_emails - # assert_no_emails - # ContactMailer.welcome.deliver_now - # assert_emails 1 - # end - # - # If a block is passed, that block should not cause any emails to be sent. - # - # def test_emails_again - # assert_no_emails do - # # No emails should be sent from this block - # end - # end - # - # Note: This assertion is simply a shortcut for: - # - # assert_emails 0 - def assert_no_emails(&block) - assert_emails 0, &block - end - - # Asserts that the number of emails enqueued for later delivery matches - # the given number. - # - # def test_emails - # assert_enqueued_emails 0 - # ContactMailer.welcome.deliver_later - # assert_enqueued_emails 1 - # ContactMailer.welcome.deliver_later - # assert_enqueued_emails 2 - # end - # - # If a block is passed, that block should cause the specified number of - # emails to be enqueued. - # - # def test_emails_again - # assert_enqueued_emails 1 do - # ContactMailer.welcome.deliver_later - # end - # - # assert_enqueued_emails 2 do - # ContactMailer.welcome.deliver_later - # ContactMailer.welcome.deliver_later - # end - # end - def assert_enqueued_emails(number, &block) - assert_enqueued_jobs number, only: [ ActionMailer::DeliveryJob, ActionMailer::Parameterized::DeliveryJob ], &block - end - - # Asserts that no emails are enqueued for later delivery. - # - # def test_no_emails - # assert_no_enqueued_emails - # ContactMailer.welcome.deliver_later - # assert_enqueued_emails 1 - # end - # - # If a block is provided, it should not cause any emails to be enqueued. - # - # def test_no_emails - # assert_no_enqueued_emails do - # # No emails should be enqueued from this block - # end - # end - def assert_no_enqueued_emails(&block) - assert_no_enqueued_jobs only: [ ActionMailer::DeliveryJob, ActionMailer::Parameterized::DeliveryJob ], &block - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/version.rb b/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/version.rb deleted file mode 100644 index 8452d6370e..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/action_mailer/version.rb +++ /dev/null @@ -1,9 +0,0 @@ -require_relative "gem_version" - -module ActionMailer - # Returns the version of the currently loaded Action Mailer as a - # Gem::Version. - def self.version - gem_version - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/USAGE b/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/USAGE deleted file mode 100644 index 2b0a078109..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/USAGE +++ /dev/null @@ -1,17 +0,0 @@ -Description: -============ - Stubs out a new mailer and its views. Passes the mailer name, either - CamelCased or under_scored, and an optional list of emails as arguments. - - This generates a mailer class in app/mailers and invokes your template - engine and test framework generators. - -Example: -======== - rails generate mailer Notifications signup forgot_password invoice - - creates a Notifications mailer class, views, and test: - Mailer: app/mailers/notifications_mailer.rb - Views: app/views/notifications_mailer/signup.text.erb [...] - Test: test/mailers/notifications_mailer_test.rb - diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/mailer_generator.rb b/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/mailer_generator.rb deleted file mode 100644 index 99fe4544f1..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/mailer_generator.rb +++ /dev/null @@ -1,36 +0,0 @@ -module Rails - module Generators - class MailerGenerator < NamedBase - source_root File.expand_path("../templates", __FILE__) - - argument :actions, type: :array, default: [], banner: "method method" - - check_class_collision suffix: "Mailer" - - def create_mailer_file - template "mailer.rb", File.join("app/mailers", class_path, "#{file_name}_mailer.rb") - - in_root do - if behavior == :invoke && !File.exist?(application_mailer_file_name) - template "application_mailer.rb", application_mailer_file_name - end - end - end - - hook_for :template_engine, :test_framework - - private - def file_name # :doc: - @_file_name ||= super.gsub(/_mailer/i, "") - end - - def application_mailer_file_name - @_application_mailer_file_name ||= if mountable_engine? - "app/mailers/#{namespaced_path}/application_mailer.rb" - else - "app/mailers/application_mailer.rb" - end - end - end - end -end diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/templates/application_mailer.rb b/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/templates/application_mailer.rb deleted file mode 100644 index 00fb9bd48f..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/templates/application_mailer.rb +++ /dev/null @@ -1,6 +0,0 @@ -<% module_namespacing do -%> -class ApplicationMailer < ActionMailer::Base - default from: 'from@example.com' - layout 'mailer' -end -<% end %> diff --git a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/templates/mailer.rb b/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/templates/mailer.rb deleted file mode 100644 index 348d314758..0000000000 --- a/debian/gems-compat/actionmailer-5.1.7/lib/rails/generators/mailer/templates/mailer.rb +++ /dev/null @@ -1,17 +0,0 @@ -<% module_namespacing do -%> -class <%= class_name %>Mailer < ApplicationMailer -<% actions.each do |action| -%> - - # Subject can be set in your I18n file at config/locales/en.yml - # with the following lookup: - # - # en.<%= file_path.tr("/",".") %>_mailer.<%= action %>.subject - # - def <%= action %> - @greeting = "Hi" - - mail to: "to@example.org" - end -<% end -%> -end -<% end -%> diff --git a/debian/gems-compat/actionpack-5.1.7/CHANGELOG.md b/debian/gems-compat/actionpack-5.1.7/CHANGELOG.md deleted file mode 100644 index 3cd48e3241..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,559 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* No changes. - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* Check exclude before flagging cookies as secure. - - *Catherine Khuu* - - -## Rails 5.1.5 (February 14, 2018) ## - -* Fix optimized url helpers when using relative url root - - Fixes #31220. - - *Andrew White* - -* Ensure dev and prod puma configs do not clobber `ActionDispatch::SystemTesting` defaults. Adds workers: 0 and daemon: false - - *Max Schwenk* - -## Rails 5.1.4 (September 07, 2017) ## - -* Make `take_failed_screenshot` work within engine. - - Fixes #30405. - - *Yuji Yaginuma* - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* No changes. - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* No changes. - - -## Rails 5.1.2 (June 26, 2017) ## - -* Fallback `ActionController::Parameters#to_s` to `Hash#to_s`. - - *Kir Shatrov* - -* `driven_by` now registers poltergeist and capybara-webkit - - If driver poltergeist or capybara-webkit is set for System Tests, - `driven_by` will register the driver and set additional options passed via - `:options` param. - - Refer to drivers documentation to learn what options can be passed. - - *Mario Chavez* - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* Raise exception when calling `to_h` and `to_hash` in an unpermitted Parameters. - - Before we returned either an empty hash or only the always permitted parameters - (`:controller` and `:action` by default). - - The previous behavior was dangerous because in order to get the attributes users - usually fallback to use `to_unsafe_h that` could potentially introduce security issues. - - *Rafael Mendonça França* - -* Deprecate `config.action_controller.raise_on_unfiltered_parameters`. - - This option has no effect in Rails 5.1. - - *Rafael Mendonça França* - -* Use more specific check for :format in route path - - The current check for whether to add an optional format to the path is very lax - and will match things like `:format_id` where there are nested resources, e.g: - - ``` ruby - resources :formats do - resources :items - end - ``` - - Fix this by using a more restrictive regex pattern that looks for the patterns - `(.:format)`, `.:format` or `/` at the end of the path. Note that we need to - allow for multiple closing parenthesis since the route may be of this form: - - ``` ruby - get "/books(/:action(.:format))", controller: "books" - ``` - - This probably isn't what's intended since it means that the default index action - route doesn't support a format but we have a test for it so we need to allow it. - - Fixes #28517. - - *Andrew White* - -* Add `action_controller_api` and `action_controller_base` load hooks to be called in `ActiveSupport.on_load` - - `ActionController::Base` and `ActionController::API` have differing implementations. This means that - the one umbrella hook `action_controller` is not able to address certain situations where a method - may not exist in a certain implementation. - - This is fixed by adding two new hooks so you can target `ActionController::Base` vs `ActionController::API` - - Fixes #27013. - - *Julian Nadeau* - -* Don't include default headers in `ActionController::Metal` responses - - The commit e16afe6 introduced an unintentional change of behavior where the default - headers were included in responses from `ActionController::Metal` based controllers. - This is now reverted to the previous behavior of having no default headers. - - Fixes #25820. - - *Jon Moss* - -* Fix `NameError` raised in `ActionController::Renderer#with_defaults` - - *Hiroyuki Ishii* - -* Added `#reverse_merge` and `#reverse_merge!` methods to `ActionController::Parameters` - - *Edouard Chin*, *Mitsutaka Mimura* - -* Fix malformed URLS when using `ApplicationController.renderer` - - The Rack environment variable `rack.url_scheme` was not being set so `scheme` was - returning `nil`. This caused URLs to be malformed with the default settings. - Fix this by setting `rack.url_scheme` when the environment is normalized. - - Fixes #28151. - - *George Vrettos* - -* Commit flash changes when using a redirect route. - - Fixes #27992. - - *Andrew White* - -* Prefer `remove_method` over `undef_method` when reloading routes - - When `undef_method` is used it prevents access to other implementations of that - url helper in the ancestor chain so use `remove_method` instead to restore access. - - *Andrew White* - -* Add the `resolve` method to the routing DSL - - This new method allows customization of the polymorphic mapping of models: - - ``` ruby - resource :basket - resolve("Basket") { [:basket] } - ``` - - ``` erb - <%= form_for @basket do |form| %> - - <% end %> - ``` - - This generates the correct singular URL for the form instead of the default - resources member url, e.g. `/basket` vs. `/basket/:id`. - - Fixes #1769. - - *Andrew White* - -* Add the `direct` method to the routing DSL - - This new method allows creation of custom url helpers, e.g: - - ``` ruby - direct(:apple) { "http://www.apple.com" } - - >> apple_url - => "http://www.apple.com" - ``` - - This has the advantage of being available everywhere url helpers are available - unlike custom url helpers defined in helper modules, etc. - - *Andrew White* - -* Add `ActionDispatch::SystemTestCase` to Action Pack - - Adds Capybara integration directly into Rails through Action Pack! - - See PR [#26703](https://github.com/rails/rails/pull/26703) - - *Eileen M. Uchitelle* - -* Remove deprecated `.to_prepare`, `.to_cleanup`, `.prepare!` and `.cleanup!` from `ActionDispatch::Reloader`. - - *Rafael Mendonça França* - -* Remove deprecated `ActionDispatch::Callbacks.to_prepare` and `ActionDispatch::Callbacks.to_cleanup`. - - *Rafael Mendonça França* - -* Remove deprecated `ActionController::Metal.call`. - - *Rafael Mendonça França* - -* Remove deprecated `ActionController::Metal#env`. - - *Rafael Mendonça França* - -* Make `with_routing` test helper work when testing controllers inheriting from `ActionController::API` - - *Julia López* - -* Use accept header in integration tests with `as: :json` - - Instead of appending the `format` to the request path, Rails will figure - out the format from the header instead. - - This allows devs to use `:as` on routes that don't have a format. - - Fixes #27144. - - *Kasper Timm Hansen* - -* Reset a new session directly after its creation in `ActionDispatch::IntegrationTest#open_session`. - - Fixes #22742. - - *Tawan Sierek* - -* Fixes incorrect output from `rails routes` when using singular resources. - - Fixes #26606. - - *Erick Reyna* - -* Fixes multiple calls to `logger.fatal` instead of a single call, - for every line in an exception backtrace, when printing trace - from `DebugExceptions` middleware. - - Fixes #26134. - - *Vipul A M* - -* Add support for arbitrary hashes in strong parameters: - - ```ruby - params.permit(preferences: {}) - ``` - - *Xavier Noria* - -* Add `ActionController::Parameters#merge!`, which behaves the same as `Hash#merge!`. - - *Yuji Yaginuma* - -* Allow keys not found in `RACK_KEY_TRANSLATION` for setting the environment when rendering - arbitrary templates. - - *Sammy Larbi* - -* Remove deprecated support to non-keyword arguments in `ActionDispatch::IntegrationTest#process`, - `#get`, `#post`, `#patch`, `#put`, `#delete`, and `#head`. - - *Rafael Mendonça França* - -* Remove deprecated `ActionDispatch::IntegrationTest#*_via_redirect`. - - *Rafael Mendonça França* - -* Remove deprecated `ActionDispatch::IntegrationTest#xml_http_request`. - - *Rafael Mendonça França* - -* Remove deprecated support for passing `:path` and route path as strings in `ActionDispatch::Routing::Mapper#match`. - - *Rafael Mendonça França* - -* Remove deprecated support for passing path as `nil` in `ActionDispatch::Routing::Mapper#match`. - - *Rafael Mendonça França* - -* Remove deprecated `cache_control` argument from `ActionDispatch::Static#initialize`. - - *Rafael Mendonça França* - -* Remove deprecated support to passing strings or symbols to the middleware stack. - - *Rafael Mendonça França* - -* Change HSTS subdomain to true. - - *Rafael Mendonça França* - -* Remove deprecated `host` and `port` ssl options. - - *Rafael Mendonça França* - -* Remove deprecated `const_error` argument in - `ActionDispatch::Session::SessionRestoreError#initialize`. - - *Rafael Mendonça França* - -* Remove deprecated `#original_exception` in `ActionDispatch::Session::SessionRestoreError`. - - *Rafael Mendonça França* - -* Deprecate `ActionDispatch::ParamsParser::ParseError` in favor of - `ActionDispatch::Http::Parameters::ParseError`. - - *Rafael Mendonça França* - -* Remove deprecated `ActionDispatch::ParamsParser`. - - *Rafael Mendonça França* - -* Remove deprecated `original_exception` and `message` arguments in - `ActionDispatch::ParamsParser::ParseError#initialize`. - - *Rafael Mendonça França* - -* Remove deprecated `#original_exception` in `ActionDispatch::ParamsParser::ParseError`. - - *Rafael Mendonça França* - -* Remove deprecated access to mime types through constants. - - *Rafael Mendonça França* - -* Remove deprecated support to non-keyword arguments in `ActionController::TestCase#process`, - `#get`, `#post`, `#patch`, `#put`, `#delete`, and `#head`. - - *Rafael Mendonça França* - -* Remove deprecated `xml_http_request` and `xhr` methods in `ActionController::TestCase`. - - *Rafael Mendonça França* - -* Remove deprecated methods in `ActionController::Parameters`. - - *Rafael Mendonça França* - -* Remove deprecated support to comparing a `ActionController::Parameters` - with a `Hash`. - - *Rafael Mendonça França* - -* Remove deprecated support to `:text` in `render`. - - *Rafael Mendonça França* - -* Remove deprecated support to `:nothing` in `render`. - - *Rafael Mendonça França* - -* Remove deprecated support to `:back` in `redirect_to`. - - *Rafael Mendonça França* - -* Remove deprecated support to passing status as option `head`. - - *Rafael Mendonça França* - -* Remove deprecated support to passing original exception to `ActionController::BadRequest` - and the `ActionController::BadRequest#original_exception` method. - - *Rafael Mendonça França* - -* Remove deprecated methods `skip_action_callback`, `skip_filter`, `before_filter`, - `prepend_before_filter`, `skip_before_filter`, `append_before_filter`, `around_filter` - `prepend_around_filter`, `skip_around_filter`, `append_around_filter`, `after_filter`, - `prepend_after_filter`, `skip_after_filter` and `append_after_filter`. - - *Rafael Mendonça França* - -* Show an "unmatched constraints" error when params fail to match constraints - on a matched route, rather than a "missing keys" error. - - Fixes #26470. - - *Chris Carter* - -* Fix adding implicitly rendered template digests to ETags. - - Fixes a case when modifying an implicitly rendered template for a - controller action using `fresh_when` or `stale?` would not result in a new - `ETag` value. - - *Javan Makhmali* - -* Make `fixture_file_upload` work in integration tests. - - *Yuji Yaginuma* - -* Add `to_param` to `ActionController::Parameters` deprecations. - - In the future `ActionController::Parameters` are discouraged from being used - in URLs without explicit whitelisting. Go through `to_h` to use `to_param`. - - *Kir Shatrov* - -* Fix nested multiple roots - - The PR #20940 enabled the use of multiple roots with different constraints - at the top level but unfortunately didn't work when those roots were inside - a namespace and also broke the use of root inside a namespace after a top - level root was defined because the check for the existence of the named route - used the global :root name and not the namespaced name. - - This is fixed by using the name_for_action method to expand the :root name to - the full namespaced name. We can pass nil for the second argument as we're not - dealing with resource definitions so don't need to handle the cases for edit - and new routes. - - Fixes #26148. - - *Ryo Hashimoto*, *Andrew White* - -* Include the content of the flash in the auto-generated etag. This solves the following problem: - - 1. POST /messages - 2. redirect_to messages_url, notice: 'Message was created' - 3. GET /messages/1 - 4. GET /messages - - Step 4 would before still include the flash message, even though it's no longer relevant, - because the etag cache was recorded with the flash in place and didn't change when it was gone. - - *DHH* - -* SSL: Changes redirect behavior for all non-GET and non-HEAD requests - (like POST/PUT/PATCH etc) to `http://` resources to redirect to `https://` - with a [307 status code](http://tools.ietf.org/html/rfc7231#section-6.4.7) instead of [301 status code](http://tools.ietf.org/html/rfc7231#section-6.4.2). - - 307 status code instructs the HTTP clients to preserve the original - request method while redirecting. It has been part of HTTP RFC since - 1999 and is implemented/recognized by most (if not all) user agents. - - # Before - POST http://example.com/articles (i.e. ArticlesContoller#create) - redirects to - GET https://example.com/articles (i.e. ArticlesContoller#index) - - # After - POST http://example.com/articles (i.e. ArticlesContoller#create) - redirects to - POST https://example.com/articles (i.e. ArticlesContoller#create) - - *Chirag Singhal* - -* Add `:as` option to `ActionController:TestCase#process` and related methods. - - Specifying `as: mime_type` allows the `CONTENT_TYPE` header to be specified - in controller tests without manually doing this through `@request.headers['CONTENT_TYPE']`. - - *Everest Stefan Munro-Zeisberger* - -* Show cache hits and misses when rendering partials. - - Partials using the `cache` helper will show whether a render hit or missed - the cache: - - ``` - Rendered messages/_message.html.erb in 1.2 ms [cache hit] - Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] - ``` - - This removes the need for the old fragment cache logging: - - ``` - Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms) - Rendered messages/_message.html.erb in 1.2 ms [cache hit] - Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms) - Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] - ``` - - Though that full output can be reenabled with - `config.action_controller.enable_fragment_cache_logging = true`. - - *Stan Lo* - -* Don't override the `Accept` header in integration tests when called with `xhr: true`. - - Fixes #25859. - - *David Chen* - -* Fix `defaults` option for root route. - - A regression from some refactoring for the 5.0 release, this change - fixes the use of `defaults` (default parameters) in the `root` routing method. - - *Chris Arcand* - -* Check `request.path_parameters` encoding at the point they're set. - - Check for any non-UTF8 characters in path parameters at the point they're - set in `env`. Previously they were checked for when used to get a controller - class, but this meant routes that went directly to a Rack app, or skipped - controller instantiation for some other reason, had to defend against - non-UTF8 characters themselves. - - *Grey Baker* - -* Don't raise `ActionController::UnknownHttpMethod` from `ActionDispatch::Static`. - - Pass `Rack::Request` objects to `ActionDispatch::FileHandler` to avoid it - raising `ActionController::UnknownHttpMethod`. If an unknown method is - passed, it should pass exception higher in the stack instead, once we've had a - chance to define exception handling behaviour. - - *Grey Baker* - -* Handle `Rack::QueryParser` errors in `ActionDispatch::ExceptionWrapper`. - - Updated `ActionDispatch::ExceptionWrapper` to handle the Rack 2.0 namespace - for `ParameterTypeError` and `InvalidParameterError` errors. - - *Grey Baker* - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actionpack/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/actionpack-5.1.7/MIT-LICENSE b/debian/gems-compat/actionpack-5.1.7/MIT-LICENSE deleted file mode 100644 index ac810e86d0..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2004-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/debian/gems-compat/actionpack-5.1.7/README.rdoc b/debian/gems-compat/actionpack-5.1.7/README.rdoc deleted file mode 100644 index 0720c66cb9..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/README.rdoc +++ /dev/null @@ -1,57 +0,0 @@ -= Action Pack -- From request to response - -Action Pack is a framework for handling and responding to web requests. It -provides mechanisms for *routing* (mapping request URLs to actions), defining -*controllers* that implement actions, and generating responses by rendering -*views*, which are templates of various formats. In short, Action Pack -provides the view and controller layers in the MVC paradigm. - -It consists of several modules: - -* Action Dispatch, which parses information about the web request, handles - routing as defined by the user, and does advanced processing related to HTTP - such as MIME-type negotiation, decoding parameters in POST, PATCH, or PUT bodies, - handling HTTP caching logic, cookies and sessions. - -* Action Controller, which provides a base controller class that can be - subclassed to implement filters and actions to handle requests. The result - of an action is typically content generated from views. - -With the Ruby on Rails framework, users only directly interface with the -Action Controller module. Necessary Action Dispatch functionality is activated -by default and Action View rendering is implicitly triggered by Action -Controller. However, these modules are designed to function on their own and -can be used outside of Rails. - - -== Download and installation - -The latest version of Action Pack can be installed with RubyGems: - - $ gem install actionpack - -Source code can be downloaded as part of the Rails project on GitHub - -* https://github.com/rails/rails/tree/master/actionpack - - -== License - -Action Pack is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -== Support - -API documentation is at - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/actionpack-5.1.7/actionpack.gemspec b/debian/gems-compat/actionpack-5.1.7/actionpack.gemspec deleted file mode 100644 index 67219bca6f..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/actionpack.gemspec +++ /dev/null @@ -1,55 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: actionpack 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "actionpack".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/actionpack/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/actionpack" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.".freeze - s.email = "david@loudthinking.com".freeze - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.rdoc".freeze, "lib/abstract_controller.rb".freeze, "lib/abstract_controller/asset_paths.rb".freeze, "lib/abstract_controller/base.rb".freeze, "lib/abstract_controller/caching.rb".freeze, "lib/abstract_controller/caching/fragments.rb".freeze, "lib/abstract_controller/callbacks.rb".freeze, "lib/abstract_controller/collector.rb".freeze, "lib/abstract_controller/error.rb".freeze, "lib/abstract_controller/helpers.rb".freeze, "lib/abstract_controller/logger.rb".freeze, "lib/abstract_controller/railties/routes_helpers.rb".freeze, "lib/abstract_controller/rendering.rb".freeze, "lib/abstract_controller/translation.rb".freeze, "lib/abstract_controller/url_for.rb".freeze, "lib/action_controller.rb".freeze, "lib/action_controller/api.rb".freeze, "lib/action_controller/api/api_rendering.rb".freeze, "lib/action_controller/base.rb".freeze, "lib/action_controller/caching.rb".freeze, "lib/action_controller/form_builder.rb".freeze, "lib/action_controller/log_subscriber.rb".freeze, "lib/action_controller/metal.rb".freeze, "lib/action_controller/metal/basic_implicit_render.rb".freeze, "lib/action_controller/metal/conditional_get.rb".freeze, "lib/action_controller/metal/cookies.rb".freeze, "lib/action_controller/metal/data_streaming.rb".freeze, "lib/action_controller/metal/etag_with_flash.rb".freeze, "lib/action_controller/metal/etag_with_template_digest.rb".freeze, "lib/action_controller/metal/exceptions.rb".freeze, "lib/action_controller/metal/flash.rb".freeze, "lib/action_controller/metal/force_ssl.rb".freeze, "lib/action_controller/metal/head.rb".freeze, "lib/action_controller/metal/helpers.rb".freeze, "lib/action_controller/metal/http_authentication.rb".freeze, "lib/action_controller/metal/implicit_render.rb".freeze, "lib/action_controller/metal/instrumentation.rb".freeze, "lib/action_controller/metal/live.rb".freeze, "lib/action_controller/metal/mime_responds.rb".freeze, "lib/action_controller/metal/parameter_encoding.rb".freeze, "lib/action_controller/metal/params_wrapper.rb".freeze, "lib/action_controller/metal/redirecting.rb".freeze, "lib/action_controller/metal/renderers.rb".freeze, "lib/action_controller/metal/rendering.rb".freeze, "lib/action_controller/metal/request_forgery_protection.rb".freeze, "lib/action_controller/metal/rescue.rb".freeze, "lib/action_controller/metal/streaming.rb".freeze, "lib/action_controller/metal/strong_parameters.rb".freeze, "lib/action_controller/metal/testing.rb".freeze, "lib/action_controller/metal/url_for.rb".freeze, "lib/action_controller/railtie.rb".freeze, "lib/action_controller/railties/helpers.rb".freeze, "lib/action_controller/renderer.rb".freeze, "lib/action_controller/template_assertions.rb".freeze, "lib/action_controller/test_case.rb".freeze, "lib/action_dispatch.rb".freeze, "lib/action_dispatch/http/cache.rb".freeze, "lib/action_dispatch/http/filter_parameters.rb".freeze, "lib/action_dispatch/http/filter_redirect.rb".freeze, "lib/action_dispatch/http/headers.rb".freeze, "lib/action_dispatch/http/mime_negotiation.rb".freeze, "lib/action_dispatch/http/mime_type.rb".freeze, "lib/action_dispatch/http/mime_types.rb".freeze, "lib/action_dispatch/http/parameter_filter.rb".freeze, "lib/action_dispatch/http/parameters.rb".freeze, "lib/action_dispatch/http/rack_cache.rb".freeze, "lib/action_dispatch/http/request.rb".freeze, "lib/action_dispatch/http/response.rb".freeze, "lib/action_dispatch/http/upload.rb".freeze, "lib/action_dispatch/http/url.rb".freeze, "lib/action_dispatch/journey.rb".freeze, "lib/action_dispatch/journey/formatter.rb".freeze, "lib/action_dispatch/journey/gtg/builder.rb".freeze, "lib/action_dispatch/journey/gtg/simulator.rb".freeze, "lib/action_dispatch/journey/gtg/transition_table.rb".freeze, "lib/action_dispatch/journey/nfa/builder.rb".freeze, "lib/action_dispatch/journey/nfa/dot.rb".freeze, "lib/action_dispatch/journey/nfa/simulator.rb".freeze, "lib/action_dispatch/journey/nfa/transition_table.rb".freeze, "lib/action_dispatch/journey/nodes/node.rb".freeze, "lib/action_dispatch/journey/parser.rb".freeze, "lib/action_dispatch/journey/parser.y".freeze, "lib/action_dispatch/journey/parser_extras.rb".freeze, "lib/action_dispatch/journey/path/pattern.rb".freeze, "lib/action_dispatch/journey/route.rb".freeze, "lib/action_dispatch/journey/router.rb".freeze, "lib/action_dispatch/journey/router/utils.rb".freeze, "lib/action_dispatch/journey/routes.rb".freeze, "lib/action_dispatch/journey/scanner.rb".freeze, "lib/action_dispatch/journey/visitors.rb".freeze, "lib/action_dispatch/journey/visualizer/fsm.css".freeze, "lib/action_dispatch/journey/visualizer/fsm.js".freeze, "lib/action_dispatch/journey/visualizer/index.html.erb".freeze, "lib/action_dispatch/middleware/callbacks.rb".freeze, "lib/action_dispatch/middleware/cookies.rb".freeze, "lib/action_dispatch/middleware/debug_exceptions.rb".freeze, "lib/action_dispatch/middleware/debug_locks.rb".freeze, "lib/action_dispatch/middleware/exception_wrapper.rb".freeze, "lib/action_dispatch/middleware/executor.rb".freeze, "lib/action_dispatch/middleware/flash.rb".freeze, "lib/action_dispatch/middleware/public_exceptions.rb".freeze, "lib/action_dispatch/middleware/reloader.rb".freeze, "lib/action_dispatch/middleware/remote_ip.rb".freeze, "lib/action_dispatch/middleware/request_id.rb".freeze, "lib/action_dispatch/middleware/session/abstract_store.rb".freeze, "lib/action_dispatch/middleware/session/cache_store.rb".freeze, "lib/action_dispatch/middleware/session/cookie_store.rb".freeze, "lib/action_dispatch/middleware/session/mem_cache_store.rb".freeze, "lib/action_dispatch/middleware/show_exceptions.rb".freeze, "lib/action_dispatch/middleware/ssl.rb".freeze, "lib/action_dispatch/middleware/stack.rb".freeze, "lib/action_dispatch/middleware/static.rb".freeze, "lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/_source.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/_source.text.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/_trace.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/_trace.text.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/layout.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/missing_template.text.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/template_error.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/template_error.text.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb".freeze, "lib/action_dispatch/middleware/templates/rescues/unknown_action.text.erb".freeze, "lib/action_dispatch/middleware/templates/routes/_route.html.erb".freeze, "lib/action_dispatch/middleware/templates/routes/_table.html.erb".freeze, "lib/action_dispatch/railtie.rb".freeze, "lib/action_dispatch/request/session.rb".freeze, "lib/action_dispatch/request/utils.rb".freeze, "lib/action_dispatch/routing.rb".freeze, "lib/action_dispatch/routing/endpoint.rb".freeze, "lib/action_dispatch/routing/inspector.rb".freeze, "lib/action_dispatch/routing/mapper.rb".freeze, "lib/action_dispatch/routing/polymorphic_routes.rb".freeze, "lib/action_dispatch/routing/redirection.rb".freeze, "lib/action_dispatch/routing/route_set.rb".freeze, "lib/action_dispatch/routing/routes_proxy.rb".freeze, "lib/action_dispatch/routing/url_for.rb".freeze, "lib/action_dispatch/system_test_case.rb".freeze, "lib/action_dispatch/system_testing/driver.rb".freeze, "lib/action_dispatch/system_testing/server.rb".freeze, "lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb".freeze, "lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb".freeze, "lib/action_dispatch/testing/assertion_response.rb".freeze, "lib/action_dispatch/testing/assertions.rb".freeze, "lib/action_dispatch/testing/assertions/response.rb".freeze, "lib/action_dispatch/testing/assertions/routing.rb".freeze, "lib/action_dispatch/testing/integration.rb".freeze, "lib/action_dispatch/testing/request_encoder.rb".freeze, "lib/action_dispatch/testing/test_process.rb".freeze, "lib/action_dispatch/testing/test_request.rb".freeze, "lib/action_dispatch/testing/test_response.rb".freeze, "lib/action_pack.rb".freeze, "lib/action_pack/gem_version.rb".freeze, "lib/action_pack/version.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.requirements = ["none".freeze] - s.rubygems_version = "2.7.6.2".freeze - s.summary = "Web-flow and rendering framework putting the VC in MVC (part of Rails).".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_development_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["~> 2.0"]) - s.add_runtime_dependency(%q.freeze, [">= 0.6.3"]) - s.add_runtime_dependency(%q.freeze, ["~> 2.0"]) - s.add_runtime_dependency(%q.freeze, [">= 1.0.2", "~> 1.0"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, [">= 0.6.3"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, [">= 1.0.2", "~> 1.0"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, [">= 0.6.3"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, [">= 1.0.2", "~> 1.0"]) - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller.rb deleted file mode 100644 index 8bd965b198..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller.rb +++ /dev/null @@ -1,24 +0,0 @@ -require "action_pack" -require "active_support/rails" -require "active_support/i18n" - -module AbstractController - extend ActiveSupport::Autoload - - autoload :Base - autoload :Caching - autoload :Callbacks - autoload :Collector - autoload :DoubleRenderError, "abstract_controller/rendering" - autoload :Helpers - autoload :Logger - autoload :Rendering - autoload :Translation - autoload :AssetPaths - autoload :UrlFor - - def self.eager_load! - super - AbstractController::Caching.eager_load! - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/asset_paths.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/asset_paths.rb deleted file mode 100644 index e6170228d9..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/asset_paths.rb +++ /dev/null @@ -1,10 +0,0 @@ -module AbstractController - module AssetPaths #:nodoc: - extend ActiveSupport::Concern - - included do - config_accessor :asset_host, :assets_dir, :javascripts_dir, - :stylesheets_dir, :default_asset_host_protocol, :relative_url_root - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/base.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/base.rb deleted file mode 100644 index e7cb6347a2..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/base.rb +++ /dev/null @@ -1,257 +0,0 @@ -require "abstract_controller/error" -require "active_support/configurable" -require "active_support/descendants_tracker" -require "active_support/core_ext/module/anonymous" -require "active_support/core_ext/module/attr_internal" - -module AbstractController - # Raised when a non-existing controller action is triggered. - class ActionNotFound < StandardError - end - - # AbstractController::Base is a low-level API. Nobody should be - # using it directly, and subclasses (like ActionController::Base) are - # expected to provide their own +render+ method, since rendering means - # different things depending on the context. - class Base - attr_internal :response_body - attr_internal :action_name - attr_internal :formats - - include ActiveSupport::Configurable - extend ActiveSupport::DescendantsTracker - - class << self - attr_reader :abstract - alias_method :abstract?, :abstract - - # Define a controller as abstract. See internal_methods for more - # details. - def abstract! - @abstract = true - end - - def inherited(klass) # :nodoc: - # Define the abstract ivar on subclasses so that we don't get - # uninitialized ivar warnings - unless klass.instance_variable_defined?(:@abstract) - klass.instance_variable_set(:@abstract, false) - end - super - end - - # A list of all internal methods for a controller. This finds the first - # abstract superclass of a controller, and gets a list of all public - # instance methods on that abstract class. Public instance methods of - # a controller would normally be considered action methods, so methods - # declared on abstract classes are being removed. - # (ActionController::Metal and ActionController::Base are defined as abstract) - def internal_methods - controller = self - - controller = controller.superclass until controller.abstract? - controller.public_instance_methods(true) - end - - # A list of method names that should be considered actions. This - # includes all public instance methods on a controller, less - # any internal methods (see internal_methods), adding back in - # any methods that are internal, but still exist on the class - # itself. - # - # ==== Returns - # * Set - A set of all methods that should be considered actions. - def action_methods - @action_methods ||= begin - # All public instance methods of this class, including ancestors - methods = (public_instance_methods(true) - - # Except for public instance methods of Base and its ancestors - internal_methods + - # Be sure to include shadowed public instance methods of this class - public_instance_methods(false)).uniq.map(&:to_s) - - methods.to_set - end - end - - # action_methods are cached and there is sometimes a need to refresh - # them. ::clear_action_methods! allows you to do that, so next time - # you run action_methods, they will be recalculated. - def clear_action_methods! - @action_methods = nil - end - - # Returns the full controller name, underscored, without the ending Controller. - # - # class MyApp::MyPostsController < AbstractController::Base - # - # end - # - # MyApp::MyPostsController.controller_path # => "my_app/my_posts" - # - # ==== Returns - # * String - def controller_path - @controller_path ||= name.sub(/Controller$/, "".freeze).underscore unless anonymous? - end - - # Refresh the cached action_methods when a new action_method is added. - def method_added(name) - super - clear_action_methods! - end - end - - abstract! - - # Calls the action going through the entire action dispatch stack. - # - # The actual method that is called is determined by calling - # #method_for_action. If no method can handle the action, then an - # AbstractController::ActionNotFound error is raised. - # - # ==== Returns - # * self - def process(action, *args) - @_action_name = action.to_s - - unless action_name = _find_action_name(@_action_name) - raise ActionNotFound, "The action '#{action}' could not be found for #{self.class.name}" - end - - @_response_body = nil - - process_action(action_name, *args) - end - - # Delegates to the class' ::controller_path - def controller_path - self.class.controller_path - end - - # Delegates to the class' ::action_methods - def action_methods - self.class.action_methods - end - - # Returns true if a method for the action is available and - # can be dispatched, false otherwise. - # - # Notice that action_methods.include?("foo") may return - # false and available_action?("foo") returns true because - # this method considers actions that are also available - # through other means, for example, implicit render ones. - # - # ==== Parameters - # * action_name - The name of an action to be tested - def available_action?(action_name) - _find_action_name(action_name) - end - - # Tests if a response body is set. Used to determine if the - # +process_action+ callback needs to be terminated in - # +AbstractController::Callbacks+. - def performed? - response_body - end - - # Returns true if the given controller is capable of rendering - # a path. A subclass of +AbstractController::Base+ - # may return false. An Email controller for example does not - # support paths, only full URLs. - def self.supports_path? - true - end - - private - - # Returns true if the name can be considered an action because - # it has a method defined in the controller. - # - # ==== Parameters - # * name - The name of an action to be tested - # - # :api: private - def action_method?(name) - self.class.action_methods.include?(name) - end - - # Call the action. Override this in a subclass to modify the - # behavior around processing an action. This, and not #process, - # is the intended way to override action dispatching. - # - # Notice that the first argument is the method to be dispatched - # which is *not* necessarily the same as the action name. - def process_action(method_name, *args) - send_action(method_name, *args) - end - - # Actually call the method associated with the action. Override - # this method if you wish to change how action methods are called, - # not to add additional behavior around it. For example, you would - # override #send_action if you want to inject arguments into the - # method. - alias send_action send - - # If the action name was not found, but a method called "action_missing" - # was found, #method_for_action will return "_handle_action_missing". - # This method calls #action_missing with the current action name. - def _handle_action_missing(*args) - action_missing(@_action_name, *args) - end - - # Takes an action name and returns the name of the method that will - # handle the action. - # - # It checks if the action name is valid and returns false otherwise. - # - # See method_for_action for more information. - # - # ==== Parameters - # * action_name - An action name to find a method name for - # - # ==== Returns - # * string - The name of the method that handles the action - # * false - No valid method name could be found. - # Raise +AbstractController::ActionNotFound+. - def _find_action_name(action_name) - _valid_action_name?(action_name) && method_for_action(action_name) - end - - # Takes an action name and returns the name of the method that will - # handle the action. In normal cases, this method returns the same - # name as it receives. By default, if #method_for_action receives - # a name that is not an action, it will look for an #action_missing - # method and return "_handle_action_missing" if one is found. - # - # Subclasses may override this method to add additional conditions - # that should be considered an action. For instance, an HTTP controller - # with a template matching the action name is considered to exist. - # - # If you override this method to handle additional cases, you may - # also provide a method (like +_handle_method_missing+) to handle - # the case. - # - # If none of these conditions are true, and +method_for_action+ - # returns +nil+, an +AbstractController::ActionNotFound+ exception will be raised. - # - # ==== Parameters - # * action_name - An action name to find a method name for - # - # ==== Returns - # * string - The name of the method that handles the action - # * nil - No method name could be found. - def method_for_action(action_name) - if action_method?(action_name) - action_name - elsif respond_to?(:action_missing, true) - "_handle_action_missing" - end - end - - # Checks if the action name is valid and returns false otherwise. - def _valid_action_name?(action_name) - !action_name.to_s.include? File::SEPARATOR - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/caching.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/caching.rb deleted file mode 100644 index 26e3f08bc1..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/caching.rb +++ /dev/null @@ -1,65 +0,0 @@ -module AbstractController - module Caching - extend ActiveSupport::Concern - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Fragments - end - - module ConfigMethods - def cache_store - config.cache_store - end - - def cache_store=(store) - config.cache_store = ActiveSupport::Cache.lookup_store(store) - end - - private - def cache_configured? - perform_caching && cache_store - end - end - - include ConfigMethods - include AbstractController::Caching::Fragments - - included do - extend ConfigMethods - - config_accessor :default_static_extension - self.default_static_extension ||= ".html" - - config_accessor :perform_caching - self.perform_caching = true if perform_caching.nil? - - config_accessor :enable_fragment_cache_logging - self.enable_fragment_cache_logging = false - - class_attribute :_view_cache_dependencies - self._view_cache_dependencies = [] - helper_method :view_cache_dependencies if respond_to?(:helper_method) - end - - module ClassMethods - def view_cache_dependency(&dependency) - self._view_cache_dependencies += [dependency] - end - end - - def view_cache_dependencies - self.class._view_cache_dependencies.map { |dep| instance_exec(&dep) }.compact - end - - private - # Convenience accessor. - def cache(key, options = {}, &block) # :doc: - if cache_configured? - cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block) - else - yield - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/caching/fragments.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/caching/fragments.rb deleted file mode 100644 index c85b4adba1..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/caching/fragments.rb +++ /dev/null @@ -1,143 +0,0 @@ -module AbstractController - module Caching - # Fragment caching is used for caching various blocks within - # views without caching the entire action as a whole. This is - # useful when certain elements of an action change frequently or - # depend on complicated state while other parts rarely change or - # can be shared amongst multiple parties. The caching is done using - # the +cache+ helper available in the Action View. See - # ActionView::Helpers::CacheHelper for more information. - # - # While it's strongly recommended that you use key-based cache - # expiration (see links in CacheHelper for more information), - # it is also possible to manually expire caches. For example: - # - # expire_fragment('name_of_cache') - module Fragments - extend ActiveSupport::Concern - - included do - if respond_to?(:class_attribute) - class_attribute :fragment_cache_keys - else - mattr_writer :fragment_cache_keys - end - - self.fragment_cache_keys = [] - - helper_method :fragment_cache_key if respond_to?(:helper_method) - end - - module ClassMethods - # Allows you to specify controller-wide key prefixes for - # cache fragments. Pass either a constant +value+, or a block - # which computes a value each time a cache key is generated. - # - # For example, you may want to prefix all fragment cache keys - # with a global version identifier, so you can easily - # invalidate all caches. - # - # class ApplicationController - # fragment_cache_key "v1" - # end - # - # When it's time to invalidate all fragments, simply change - # the string constant. Or, progressively roll out the cache - # invalidation using a computed value: - # - # class ApplicationController - # fragment_cache_key do - # @account.id.odd? ? "v1" : "v2" - # end - # end - def fragment_cache_key(value = nil, &key) - self.fragment_cache_keys += [key || -> { value }] - end - end - - # Given a key (as described in +expire_fragment+), returns - # a key suitable for use in reading, writing, or expiring a - # cached fragment. All keys begin with views/, - # followed by any controller-wide key prefix values, ending - # with the specified +key+ value. The key is expanded using - # ActiveSupport::Cache.expand_cache_key. - def fragment_cache_key(key) - head = self.class.fragment_cache_keys.map { |k| instance_exec(&k) } - tail = key.is_a?(Hash) ? url_for(key).split("://").last : key - ActiveSupport::Cache.expand_cache_key([*head, *tail], :views) - end - - # Writes +content+ to the location signified by - # +key+ (see +expire_fragment+ for acceptable formats). - def write_fragment(key, content, options = nil) - return content unless cache_configured? - - key = fragment_cache_key(key) - instrument_fragment_cache :write_fragment, key do - content = content.to_str - cache_store.write(key, content, options) - end - content - end - - # Reads a cached fragment from the location signified by +key+ - # (see +expire_fragment+ for acceptable formats). - def read_fragment(key, options = nil) - return unless cache_configured? - - key = fragment_cache_key(key) - instrument_fragment_cache :read_fragment, key do - result = cache_store.read(key, options) - result.respond_to?(:html_safe) ? result.html_safe : result - end - end - - # Check if a cached fragment from the location signified by - # +key+ exists (see +expire_fragment+ for acceptable formats). - def fragment_exist?(key, options = nil) - return unless cache_configured? - key = fragment_cache_key(key) - - instrument_fragment_cache :exist_fragment?, key do - cache_store.exist?(key, options) - end - end - - # Removes fragments from the cache. - # - # +key+ can take one of three forms: - # - # * String - This would normally take the form of a path, like - # pages/45/notes. - # * Hash - Treated as an implicit call to +url_for+, like - # { controller: 'pages', action: 'notes', id: 45} - # * Regexp - Will remove any fragment that matches, so - # %r{pages/\d*/notes} might remove all notes. Make sure you - # don't use anchors in the regex (^ or $) because - # the actual filename matched looks like - # ./cache/filename/path.cache. Note: Regexp expiration is - # only supported on caches that can iterate over all keys (unlike - # memcached). - # - # +options+ is passed through to the cache store's +delete+ - # method (or delete_matched, for Regexp keys). - def expire_fragment(key, options = nil) - return unless cache_configured? - key = fragment_cache_key(key) unless key.is_a?(Regexp) - - instrument_fragment_cache :expire_fragment, key do - if key.is_a?(Regexp) - cache_store.delete_matched(key, options) - else - cache_store.delete(key, options) - end - end - end - - def instrument_fragment_cache(name, key) # :nodoc: - payload = instrument_payload(key) - ActiveSupport::Notifications.instrument("#{name}.#{instrument_name}", payload) { yield } - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/callbacks.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/callbacks.rb deleted file mode 100644 index ce4ecf17cc..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/callbacks.rb +++ /dev/null @@ -1,190 +0,0 @@ -module AbstractController - module Callbacks - extend ActiveSupport::Concern - - # Uses ActiveSupport::Callbacks as the base functionality. For - # more details on the whole callback system, read the documentation - # for ActiveSupport::Callbacks. - include ActiveSupport::Callbacks - - included do - define_callbacks :process_action, - terminator: ->(controller, result_lambda) { result_lambda.call if result_lambda.is_a?(Proc); controller.performed? }, - skip_after_callbacks_if_terminated: true - end - - # Override AbstractController::Base's process_action to run the - # process_action callbacks around the normal behavior. - def process_action(*args) - run_callbacks(:process_action) do - super - end - end - - module ClassMethods - # If +:only+ or +:except+ are used, convert the options into the - # +:if+ and +:unless+ options of ActiveSupport::Callbacks. - # - # The basic idea is that :only => :index gets converted to - # :if => proc {|c| c.action_name == "index" }. - # - # Note that :only has priority over :if in case they - # are used together. - # - # only: :index, if: -> { true } # the :if option will be ignored. - # - # Note that :if has priority over :except in case they - # are used together. - # - # except: :index, if: -> { true } # the :except option will be ignored. - # - # ==== Options - # * only - The callback should be run only for this action. - # * except - The callback should be run for all actions except this action. - def _normalize_callback_options(options) - _normalize_callback_option(options, :only, :if) - _normalize_callback_option(options, :except, :unless) - end - - def _normalize_callback_option(options, from, to) # :nodoc: - if from = options[from] - _from = Array(from).map(&:to_s).to_set - from = proc { |c| _from.include? c.action_name } - options[to] = Array(options[to]).unshift(from) - end - end - - # Take callback names and an optional callback proc, normalize them, - # then call the block with each callback. This allows us to abstract - # the normalization across several methods that use it. - # - # ==== Parameters - # * callbacks - An array of callbacks, with an optional - # options hash as the last parameter. - # * block - A proc that should be added to the callbacks. - # - # ==== Block Parameters - # * name - The callback to be added. - # * options - A hash of options to be used when adding the callback. - def _insert_callbacks(callbacks, block = nil) - options = callbacks.extract_options! - _normalize_callback_options(options) - callbacks.push(block) if block - callbacks.each do |callback| - yield callback, options - end - end - - ## - # :method: before_action - # - # :call-seq: before_action(names, block) - # - # Append a callback before actions. See _insert_callbacks for parameter details. - - ## - # :method: prepend_before_action - # - # :call-seq: prepend_before_action(names, block) - # - # Prepend a callback before actions. See _insert_callbacks for parameter details. - - ## - # :method: skip_before_action - # - # :call-seq: skip_before_action(names) - # - # Skip a callback before actions. See _insert_callbacks for parameter details. - - ## - # :method: append_before_action - # - # :call-seq: append_before_action(names, block) - # - # Append a callback before actions. See _insert_callbacks for parameter details. - - ## - # :method: after_action - # - # :call-seq: after_action(names, block) - # - # Append a callback after actions. See _insert_callbacks for parameter details. - - ## - # :method: prepend_after_action - # - # :call-seq: prepend_after_action(names, block) - # - # Prepend a callback after actions. See _insert_callbacks for parameter details. - - ## - # :method: skip_after_action - # - # :call-seq: skip_after_action(names) - # - # Skip a callback after actions. See _insert_callbacks for parameter details. - - ## - # :method: append_after_action - # - # :call-seq: append_after_action(names, block) - # - # Append a callback after actions. See _insert_callbacks for parameter details. - - ## - # :method: around_action - # - # :call-seq: around_action(names, block) - # - # Append a callback around actions. See _insert_callbacks for parameter details. - - ## - # :method: prepend_around_action - # - # :call-seq: prepend_around_action(names, block) - # - # Prepend a callback around actions. See _insert_callbacks for parameter details. - - ## - # :method: skip_around_action - # - # :call-seq: skip_around_action(names) - # - # Skip a callback around actions. See _insert_callbacks for parameter details. - - ## - # :method: append_around_action - # - # :call-seq: append_around_action(names, block) - # - # Append a callback around actions. See _insert_callbacks for parameter details. - - # set up before_action, prepend_before_action, skip_before_action, etc. - # for each of before, after, and around. - [:before, :after, :around].each do |callback| - define_method "#{callback}_action" do |*names, &blk| - _insert_callbacks(names, blk) do |name, options| - set_callback(:process_action, callback, name, options) - end - end - - define_method "prepend_#{callback}_action" do |*names, &blk| - _insert_callbacks(names, blk) do |name, options| - set_callback(:process_action, callback, name, options.merge(prepend: true)) - end - end - - # Skip a before, after or around callback. See _insert_callbacks - # for details on the allowed parameters. - define_method "skip_#{callback}_action" do |*names| - _insert_callbacks(names) do |name, options| - skip_callback(:process_action, callback, name, options) - end - end - - # *_action is the same as append_*_action - alias_method :"append_#{callback}_action", :"#{callback}_action" - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/collector.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/collector.rb deleted file mode 100644 index 40ae5aa1ca..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/collector.rb +++ /dev/null @@ -1,41 +0,0 @@ -require "action_dispatch/http/mime_type" - -module AbstractController - module Collector - def self.generate_method_for_mime(mime) - sym = mime.is_a?(Symbol) ? mime : mime.to_sym - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{sym}(*args, &block) - custom(Mime[:#{sym}], *args, &block) - end - RUBY - end - - Mime::SET.each do |mime| - generate_method_for_mime(mime) - end - - Mime::Type.register_callback do |mime| - generate_method_for_mime(mime) unless instance_methods.include?(mime.to_sym) - end - - private - - def method_missing(symbol, &block) - unless mime_constant = Mime[symbol] - raise NoMethodError, "To respond to a custom format, register it as a MIME type first: " \ - "http://guides.rubyonrails.org/action_controller_overview.html#restful-downloads. " \ - "If you meant to respond to a variant like :tablet or :phone, not a custom format, " \ - "be sure to nest your variant response within a format response: " \ - "format.html { |html| html.tablet { ... } }" - end - - if Mime::SET.include?(mime_constant) - AbstractController::Collector.generate_method_for_mime(mime_constant) - send(symbol, &block) - else - super - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/error.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/error.rb deleted file mode 100644 index 7fafce4dd4..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/error.rb +++ /dev/null @@ -1,4 +0,0 @@ -module AbstractController - class Error < StandardError #:nodoc: - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/helpers.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/helpers.rb deleted file mode 100644 index ef3be7af83..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/helpers.rb +++ /dev/null @@ -1,195 +0,0 @@ -require "active_support/dependencies" - -module AbstractController - module Helpers - extend ActiveSupport::Concern - - included do - class_attribute :_helpers - self._helpers = Module.new - - class_attribute :_helper_methods - self._helper_methods = Array.new - end - - class MissingHelperError < LoadError - def initialize(error, path) - @error = error - @path = "helpers/#{path}.rb" - set_backtrace error.backtrace - - if error.path =~ /^#{path}(\.rb)?$/ - super("Missing helper file helpers/%s.rb" % path) - else - raise error - end - end - end - - module ClassMethods - # When a class is inherited, wrap its helper module in a new module. - # This ensures that the parent class's module can be changed - # independently of the child class's. - def inherited(klass) - helpers = _helpers - klass._helpers = Module.new { include helpers } - klass.class_eval { default_helper_module! } unless klass.anonymous? - super - end - - # Declare a controller method as a helper. For example, the following - # makes the +current_user+ and +logged_in?+ controller methods available - # to the view: - # class ApplicationController < ActionController::Base - # helper_method :current_user, :logged_in? - # - # def current_user - # @current_user ||= User.find_by(id: session[:user]) - # end - # - # def logged_in? - # current_user != nil - # end - # end - # - # In a view: - # <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%> - # - # ==== Parameters - # * method[, method] - A name or names of a method on the controller - # to be made available on the view. - def helper_method(*meths) - meths.flatten! - self._helper_methods += meths - - meths.each do |meth| - _helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1 - def #{meth}(*args, &blk) # def current_user(*args, &blk) - controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk) - end # end - ruby_eval - end - end - - # The +helper+ class method can take a series of helper module names, a block, or both. - # - # ==== Options - # * *args - Module, Symbol, String - # * block - A block defining helper methods - # - # When the argument is a module it will be included directly in the template class. - # helper FooHelper # => includes FooHelper - # - # When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file - # and include the module in the template class. The second form illustrates how to include custom helpers - # when working with namespaced controllers, or other cases where the file containing the helper definition is not - # in one of Rails' standard load paths: - # helper :foo # => requires 'foo_helper' and includes FooHelper - # helper 'resources/foo' # => requires 'resources/foo_helper' and includes Resources::FooHelper - # - # Additionally, the +helper+ class method can receive and evaluate a block, making the methods defined available - # to the template. - # - # # One line - # helper { def hello() "Hello, world!" end } - # - # # Multi-line - # helper do - # def foo(bar) - # "#{bar} is the very best" - # end - # end - # - # Finally, all the above styles can be mixed together, and the +helper+ method can be invoked with a mix of - # +symbols+, +strings+, +modules+ and blocks. - # - # helper(:three, BlindHelper) { def mice() 'mice' end } - # - def helper(*args, &block) - modules_for_helpers(args).each do |mod| - add_template_helper(mod) - end - - _helpers.module_eval(&block) if block_given? - end - - # Clears up all existing helpers in this class, only keeping the helper - # with the same name as this class. - def clear_helpers - inherited_helper_methods = _helper_methods - self._helpers = Module.new - self._helper_methods = Array.new - - inherited_helper_methods.each { |meth| helper_method meth } - default_helper_module! unless anonymous? - end - - # Returns a list of modules, normalized from the acceptable kinds of - # helpers with the following behavior: - # - # String or Symbol:: :FooBar or "FooBar" becomes "foo_bar_helper", - # and "foo_bar_helper.rb" is loaded using require_dependency. - # - # Module:: No further processing - # - # After loading the appropriate files, the corresponding modules - # are returned. - # - # ==== Parameters - # * args - An array of helpers - # - # ==== Returns - # * Array - A normalized list of modules for the list of - # helpers provided. - def modules_for_helpers(args) - args.flatten.map! do |arg| - case arg - when String, Symbol - file_name = "#{arg.to_s.underscore}_helper" - begin - require_dependency(file_name) - rescue LoadError => e - raise AbstractController::Helpers::MissingHelperError.new(e, file_name) - end - - mod_name = file_name.camelize - begin - mod_name.constantize - rescue LoadError - # dependencies.rb gives a similar error message but its wording is - # not as clear because it mentions autoloading. To the user all it - # matters is that a helper module couldn't be loaded, autoloading - # is an internal mechanism that should not leak. - raise NameError, "Couldn't find #{mod_name}, expected it to be defined in helpers/#{file_name}.rb" - end - when Module - arg - else - raise ArgumentError, "helper must be a String, Symbol, or Module" - end - end - end - - private - # Makes all the (instance) methods in the helper module available to templates - # rendered through this controller. - # - # ==== Parameters - # * module - The module to include into the current helper module - # for the class - def add_template_helper(mod) - _helpers.module_eval { include mod } - end - - def default_helper_module! - module_name = name.sub(/Controller$/, "".freeze) - module_path = module_name.underscore - helper module_path - rescue LoadError => e - raise e unless e.is_missing? "helpers/#{module_path}_helper" - rescue NameError => e - raise e unless e.missing_name? "#{module_name}Helper" - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/logger.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/logger.rb deleted file mode 100644 index c31ea6c5b5..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/logger.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "active_support/benchmarkable" - -module AbstractController - module Logger #:nodoc: - extend ActiveSupport::Concern - - included do - config_accessor :logger - include ActiveSupport::Benchmarkable - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/railties/routes_helpers.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/railties/routes_helpers.rb deleted file mode 100644 index 14b574e322..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/railties/routes_helpers.rb +++ /dev/null @@ -1,18 +0,0 @@ -module AbstractController - module Railties - module RoutesHelpers - def self.with(routes, include_path_helpers = true) - Module.new do - define_method(:inherited) do |klass| - super(klass) - if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_routes_url_helpers) } - klass.include(namespace.railtie_routes_url_helpers(include_path_helpers)) - else - klass.include(routes.url_helpers(include_path_helpers)) - end - end - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/rendering.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/rendering.rb deleted file mode 100644 index 54af938a93..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/rendering.rb +++ /dev/null @@ -1,134 +0,0 @@ -require "abstract_controller/error" -require "action_view" -require "action_view/view_paths" -require "set" - -module AbstractController - class DoubleRenderError < Error - DEFAULT_MESSAGE = "Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like \"redirect_to(...) and return\"." - - def initialize(message = nil) - super(message || DEFAULT_MESSAGE) - end - end - - module Rendering - extend ActiveSupport::Concern - include ActionView::ViewPaths - - # Normalizes arguments, options and then delegates render_to_body and - # sticks the result in self.response_body. - # :api: public - def render(*args, &block) - options = _normalize_render(*args, &block) - rendered_body = render_to_body(options) - if options[:html] - _set_html_content_type - else - _set_rendered_content_type rendered_format - end - self.response_body = rendered_body - end - - # Raw rendering of a template to a string. - # - # It is similar to render, except that it does not - # set the +response_body+ and it should be guaranteed - # to always return a string. - # - # If a component extends the semantics of +response_body+ - # (as ActionController extends it to be anything that - # responds to the method each), this method needs to be - # overridden in order to still return a string. - # :api: plugin - def render_to_string(*args, &block) - options = _normalize_render(*args, &block) - render_to_body(options) - end - - # Performs the actual template rendering. - # :api: public - def render_to_body(options = {}) - end - - # Returns Content-Type of rendered content - # :api: public - def rendered_format - Mime[:text] - end - - DEFAULT_PROTECTED_INSTANCE_VARIABLES = Set.new %i( - @_action_name @_response_body @_formats @_prefixes - ) - - # This method should return a hash with assigns. - # You can overwrite this configuration per controller. - # :api: public - def view_assigns - protected_vars = _protected_ivars - variables = instance_variables - - variables.reject! { |s| protected_vars.include? s } - variables.each_with_object({}) { |name, hash| - hash[name.slice(1, name.length)] = instance_variable_get(name) - } - end - - # Normalize args by converting render "foo" to - # render :action => "foo" and render "foo/bar" to - # render :file => "foo/bar". - # :api: plugin - def _normalize_args(action = nil, options = {}) - if action.respond_to?(:permitted?) - if action.permitted? - action - else - raise ArgumentError, "render parameters are not permitted" - end - elsif action.is_a?(Hash) - action - else - options - end - end - - # Normalize options. - # :api: plugin - def _normalize_options(options) - options - end - - # Process extra options. - # :api: plugin - def _process_options(options) - options - end - - # Process the rendered format. - # :api: private - def _process_format(format) - end - - def _process_variant(options) - end - - def _set_html_content_type # :nodoc: - end - - def _set_rendered_content_type(format) # :nodoc: - end - - # Normalize args and options. - # :api: private - def _normalize_render(*args, &block) - options = _normalize_args(*args, &block) - _process_variant(options) - _normalize_options(options) - options - end - - def _protected_ivars # :nodoc: - DEFAULT_PROTECTED_INSTANCE_VARIABLES - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/translation.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/translation.rb deleted file mode 100644 index e4ac95df50..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/translation.rb +++ /dev/null @@ -1,29 +0,0 @@ -module AbstractController - module Translation - # Delegates to I18n.translate. Also aliased as t. - # - # When the given key starts with a period, it will be scoped by the current - # controller and action. So if you call translate(".foo") from - # PeopleController#index, it will convert the call to - # I18n.translate("people.index.foo"). This makes it less repetitive - # to translate many keys within the same controller / action and gives you a - # simple framework for scoping them consistently. - def translate(key, options = {}) - if key.to_s.first == "." - path = controller_path.tr("/", ".") - defaults = [:"#{path}#{key}"] - defaults << options[:default] if options[:default] - options[:default] = defaults.flatten - key = "#{path}.#{action_name}#{key}" - end - I18n.translate(key, options) - end - alias :t :translate - - # Delegates to I18n.localize. Also aliased as l. - def localize(*args) - I18n.localize(*args) - end - alias :l :localize - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/url_for.rb b/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/url_for.rb deleted file mode 100644 index 72d07b0927..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/abstract_controller/url_for.rb +++ /dev/null @@ -1,33 +0,0 @@ -module AbstractController - # Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class - # has to provide a +RouteSet+ by implementing the _routes methods. Otherwise, an - # exception will be raised. - # - # Note that this module is completely decoupled from HTTP - the only requirement is a valid - # _routes implementation. - module UrlFor - extend ActiveSupport::Concern - include ActionDispatch::Routing::UrlFor - - def _routes - raise "In order to use #url_for, you must include routing helpers explicitly. " \ - "For instance, `include Rails.application.routes.url_helpers`." - end - - module ClassMethods - def _routes - nil - end - - def action_methods - @action_methods ||= begin - if _routes - super - _routes.named_routes.helper_names - else - super - end - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller.rb deleted file mode 100644 index 50f20aa789..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller.rb +++ /dev/null @@ -1,63 +0,0 @@ -require "active_support/rails" -require "abstract_controller" -require "action_dispatch" -require "action_controller/metal/live" -require "action_controller/metal/strong_parameters" - -module ActionController - extend ActiveSupport::Autoload - - autoload :API - autoload :Base - autoload :Metal - autoload :Middleware - autoload :Renderer - autoload :FormBuilder - - eager_autoload do - autoload :Caching - end - - autoload_under "metal" do - autoload :ConditionalGet - autoload :Cookies - autoload :DataStreaming - autoload :EtagWithTemplateDigest - autoload :EtagWithFlash - autoload :Flash - autoload :ForceSSL - autoload :Head - autoload :Helpers - autoload :HttpAuthentication - autoload :BasicImplicitRender - autoload :ImplicitRender - autoload :Instrumentation - autoload :MimeResponds - autoload :ParamsWrapper - autoload :Redirecting - autoload :Renderers - autoload :Rendering - autoload :RequestForgeryProtection - autoload :Rescue - autoload :Streaming - autoload :StrongParameters - autoload :ParameterEncoding - autoload :Testing - autoload :UrlFor - end - - autoload_under "api" do - autoload :ApiRendering - end - - autoload :TestCase, "action_controller/test_case" - autoload :TemplateAssertions, "action_controller/test_case" -end - -# Common Active Support usage in Action Controller -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/load_error" -require "active_support/core_ext/module/attr_internal" -require "active_support/core_ext/name_error" -require "active_support/core_ext/uri" -require "active_support/inflector" diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/api.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/api.rb deleted file mode 100644 index 94698df730..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/api.rb +++ /dev/null @@ -1,147 +0,0 @@ -require "action_view" -require "action_controller" -require "action_controller/log_subscriber" - -module ActionController - # API Controller is a lightweight version of ActionController::Base, - # created for applications that don't require all functionalities that a complete - # \Rails controller provides, allowing you to create controllers with just the - # features that you need for API only applications. - # - # An API Controller is different from a normal controller in the sense that - # by default it doesn't include a number of features that are usually required - # by browser access only: layouts and templates rendering, cookies, sessions, - # flash, assets, and so on. This makes the entire controller stack thinner, - # suitable for API applications. It doesn't mean you won't have such - # features if you need them: they're all available for you to include in - # your application, they're just not part of the default API controller stack. - # - # Normally, +ApplicationController+ is the only controller that inherits from - # ActionController::API. All other controllers in turn inherit from - # +ApplicationController+. - # - # A sample controller could look like this: - # - # class PostsController < ApplicationController - # def index - # posts = Post.all - # render json: posts - # end - # end - # - # Request, response, and parameters objects all work the exact same way as - # ActionController::Base. - # - # == Renders - # - # The default API Controller stack includes all renderers, which means you - # can use render :json and brothers freely in your controllers. Keep - # in mind that templates are not going to be rendered, so you need to ensure - # your controller is calling either render or redirect_to in - # all actions, otherwise it will return 204 No Content. - # - # def show - # post = Post.find(params[:id]) - # render json: post - # end - # - # == Redirects - # - # Redirects are used to move from one action to another. You can use the - # redirect_to method in your controllers in the same way as in - # ActionController::Base. For example: - # - # def create - # redirect_to root_url and return if not_authorized? - # # do stuff here - # end - # - # == Adding New Behavior - # - # In some scenarios you may want to add back some functionality provided by - # ActionController::Base that is not present by default in - # ActionController::API, for instance MimeResponds. This - # module gives you the respond_to method. Adding it is quite simple, - # you just need to include the module in a specific controller or in - # +ApplicationController+ in case you want it available in your entire - # application: - # - # class ApplicationController < ActionController::API - # include ActionController::MimeResponds - # end - # - # class PostsController < ApplicationController - # def index - # posts = Post.all - # - # respond_to do |format| - # format.json { render json: posts } - # format.xml { render xml: posts } - # end - # end - # end - # - # Make sure to check the modules included in ActionController::Base - # if you want to use any other functionality that is not provided - # by ActionController::API out of the box. - class API < Metal - abstract! - - # Shortcut helper that returns all the ActionController::API modules except - # the ones passed as arguments: - # - # class MyAPIBaseController < ActionController::Metal - # ActionController::API.without_modules(:ForceSSL, :UrlFor).each do |left| - # include left - # end - # end - # - # This gives better control over what you want to exclude and makes it easier - # to create an API controller class, instead of listing the modules required - # manually. - def self.without_modules(*modules) - modules = modules.map do |m| - m.is_a?(Symbol) ? ActionController.const_get(m) : m - end - - MODULES - modules - end - - MODULES = [ - AbstractController::Rendering, - - UrlFor, - Redirecting, - ApiRendering, - Renderers::All, - ConditionalGet, - BasicImplicitRender, - StrongParameters, - - ForceSSL, - DataStreaming, - - # Before callbacks should also be executed as early as possible, so - # also include them at the bottom. - AbstractController::Callbacks, - - # Append rescue at the bottom to wrap as much as possible. - Rescue, - - # Add instrumentations hooks at the bottom, to ensure they instrument - # all the methods properly. - Instrumentation, - - # Params wrapper should come before instrumentation so they are - # properly showed in logs - ParamsWrapper - ] - - MODULES.each do |mod| - include mod - end - - ActiveSupport.run_load_hooks(:action_controller_api, self) - ActiveSupport.run_load_hooks(:action_controller, self) - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/api/api_rendering.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/api/api_rendering.rb deleted file mode 100644 index 3a08d28c39..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/api/api_rendering.rb +++ /dev/null @@ -1,14 +0,0 @@ -module ActionController - module ApiRendering - extend ActiveSupport::Concern - - included do - include Rendering - end - - def render_to_body(options = {}) - _process_options(options) - super - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/base.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/base.rb deleted file mode 100644 index 8c2b111f89..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/base.rb +++ /dev/null @@ -1,273 +0,0 @@ -require "action_view" -require "action_controller/log_subscriber" -require "action_controller/metal/params_wrapper" - -module ActionController - # Action Controllers are the core of a web request in \Rails. They are made up of one or more actions that are executed - # on request and then either it renders a template or redirects to another action. An action is defined as a public method - # on the controller, which will automatically be made accessible to the web-server through \Rails Routes. - # - # By default, only the ApplicationController in a \Rails application inherits from ActionController::Base. All other - # controllers inherit from ApplicationController. This gives you one class to configure things such as - # request forgery protection and filtering of sensitive request parameters. - # - # A sample controller could look like this: - # - # class PostsController < ApplicationController - # def index - # @posts = Post.all - # end - # - # def create - # @post = Post.create params[:post] - # redirect_to posts_path - # end - # end - # - # Actions, by default, render a template in the app/views directory corresponding to the name of the controller and action - # after executing code in the action. For example, the +index+ action of the PostsController would render the - # template app/views/posts/index.html.erb by default after populating the @posts instance variable. - # - # Unlike index, the create action will not render a template. After performing its main purpose (creating a - # new post), it initiates a redirect instead. This redirect works by returning an external - # 302 Moved HTTP response that takes the user to the index action. - # - # These two methods represent the two basic action archetypes used in Action Controllers: Get-and-show and do-and-redirect. - # Most actions are variations on these themes. - # - # == Requests - # - # For every request, the router determines the value of the +controller+ and +action+ keys. These determine which controller - # and action are called. The remaining request parameters, the session (if one is available), and the full request with - # all the HTTP headers are made available to the action through accessor methods. Then the action is performed. - # - # The full request object is available via the request accessor and is primarily used to query for HTTP headers: - # - # def server_ip - # location = request.env["REMOTE_ADDR"] - # render plain: "This server hosted at #{location}" - # end - # - # == Parameters - # - # All request parameters, whether they come from a query string in the URL or form data submitted through a POST request are - # available through the params method which returns a hash. For example, an action that was performed through - # /posts?category=All&limit=5 will include { "category" => "All", "limit" => "5" } in params. - # - # It's also possible to construct multi-dimensional parameter hashes by specifying keys using brackets, such as: - # - # - # - # - # A request coming from a form holding these inputs will include { "post" => { "name" => "david", "address" => "hyacintvej" } }. - # If the address input had been named post[address][street], the params would have included - # { "post" => { "address" => { "street" => "hyacintvej" } } }. There's no limit to the depth of the nesting. - # - # == Sessions - # - # Sessions allow you to store objects in between requests. This is useful for objects that are not yet ready to be persisted, - # such as a Signup object constructed in a multi-paged process, or objects that don't change much and are needed all the time, such - # as a User object for a system that requires login. The session should not be used, however, as a cache for objects where it's likely - # they could be changed unknowingly. It's usually too much work to keep it all synchronized -- something databases already excel at. - # - # You can place objects in the session by using the session method, which accesses a hash: - # - # session[:person] = Person.authenticate(user_name, password) - # - # You can retrieve it again through the same hash: - # - # Hello #{session[:person]} - # - # For removing objects from the session, you can either assign a single key to +nil+: - # - # # removes :person from session - # session[:person] = nil - # - # or you can remove the entire session with +reset_session+. - # - # Sessions are stored by default in a browser cookie that's cryptographically signed, but unencrypted. - # This prevents the user from tampering with the session but also allows them to see its contents. - # - # Do not put secret information in cookie-based sessions! - # - # == Responses - # - # Each action results in a response, which holds the headers and document to be sent to the user's browser. The actual response - # object is generated automatically through the use of renders and redirects and requires no user intervention. - # - # == Renders - # - # Action Controller sends content to the user by using one of five rendering methods. The most versatile and common is the rendering - # of a template. Included in the Action Pack is the Action View, which enables rendering of ERB templates. It's automatically configured. - # The controller passes objects to the view by assigning instance variables: - # - # def show - # @post = Post.find(params[:id]) - # end - # - # Which are then automatically available to the view: - # - # Title: <%= @post.title %> - # - # You don't have to rely on the automated rendering. For example, actions that could result in the rendering of different templates - # will use the manual rendering methods: - # - # def search - # @results = Search.find(params[:query]) - # case @results.count - # when 0 then render action: "no_results" - # when 1 then render action: "show" - # when 2..10 then render action: "show_many" - # end - # end - # - # Read more about writing ERB and Builder templates in ActionView::Base. - # - # == Redirects - # - # Redirects are used to move from one action to another. For example, after a create action, which stores a blog entry to the - # database, we might like to show the user the new entry. Because we're following good DRY principles (Don't Repeat Yourself), we're - # going to reuse (and redirect to) a show action that we'll assume has already been created. The code might look like this: - # - # def create - # @entry = Entry.new(params[:entry]) - # if @entry.save - # # The entry was saved correctly, redirect to show - # redirect_to action: 'show', id: @entry.id - # else - # # things didn't go so well, do something else - # end - # end - # - # In this case, after saving our new entry to the database, the user is redirected to the show method, which is then executed. - # Note that this is an external HTTP-level redirection which will cause the browser to make a second request (a GET to the show action), - # and not some internal re-routing which calls both "create" and then "show" within one request. - # - # Learn more about redirect_to and what options you have in ActionController::Redirecting. - # - # == Calling multiple redirects or renders - # - # An action may contain only a single render or a single redirect. Attempting to try to do either again will result in a DoubleRenderError: - # - # def do_something - # redirect_to action: "elsewhere" - # render action: "overthere" # raises DoubleRenderError - # end - # - # If you need to redirect on the condition of something, then be sure to add "and return" to halt execution. - # - # def do_something - # redirect_to(action: "elsewhere") and return if monkeys.nil? - # render action: "overthere" # won't be called if monkeys is nil - # end - # - class Base < Metal - abstract! - - # We document the request and response methods here because albeit they are - # implemented in ActionController::Metal, the type of the returned objects - # is unknown at that level. - - ## - # :method: request - # - # Returns an ActionDispatch::Request instance that represents the - # current request. - - ## - # :method: response - # - # Returns an ActionDispatch::Response that represents the current - # response. - - # Shortcut helper that returns all the modules included in - # ActionController::Base except the ones passed as arguments: - # - # class MyBaseController < ActionController::Metal - # ActionController::Base.without_modules(:ParamsWrapper, :Streaming).each do |left| - # include left - # end - # end - # - # This gives better control over what you want to exclude and makes it - # easier to create a bare controller class, instead of listing the modules - # required manually. - def self.without_modules(*modules) - modules = modules.map do |m| - m.is_a?(Symbol) ? ActionController.const_get(m) : m - end - - MODULES - modules - end - - MODULES = [ - AbstractController::Rendering, - AbstractController::Translation, - AbstractController::AssetPaths, - - Helpers, - UrlFor, - Redirecting, - ActionView::Layouts, - Rendering, - Renderers::All, - ConditionalGet, - EtagWithTemplateDigest, - EtagWithFlash, - Caching, - MimeResponds, - ImplicitRender, - StrongParameters, - ParameterEncoding, - Cookies, - Flash, - FormBuilder, - RequestForgeryProtection, - ForceSSL, - Streaming, - DataStreaming, - HttpAuthentication::Basic::ControllerMethods, - HttpAuthentication::Digest::ControllerMethods, - HttpAuthentication::Token::ControllerMethods, - - # Before callbacks should also be executed as early as possible, so - # also include them at the bottom. - AbstractController::Callbacks, - - # Append rescue at the bottom to wrap as much as possible. - Rescue, - - # Add instrumentations hooks at the bottom, to ensure they instrument - # all the methods properly. - Instrumentation, - - # Params wrapper should come before instrumentation so they are - # properly showed in logs - ParamsWrapper - ] - - MODULES.each do |mod| - include mod - end - setup_renderer! - - # Define some internal variables that should not be propagated to the view. - PROTECTED_IVARS = AbstractController::Rendering::DEFAULT_PROTECTED_INSTANCE_VARIABLES + %i( - @_params @_response @_request @_config @_url_options @_action_has_layout @_view_context_class - @_view_renderer @_lookup_context @_routes @_view_runtime @_db_runtime @_helper_proxy - ) - - def _protected_ivars # :nodoc: - PROTECTED_IVARS - end - - def self.make_response!(request) - ActionDispatch::Response.create.tap do |res| - res.request = request - end - end - - ActiveSupport.run_load_hooks(:action_controller_base, self) - ActiveSupport.run_load_hooks(:action_controller, self) - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/caching.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/caching.rb deleted file mode 100644 index 954265ad97..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/caching.rb +++ /dev/null @@ -1,44 +0,0 @@ -module ActionController - # \Caching is a cheap way of speeding up slow applications by keeping the result of - # calculations, renderings, and database calls around for subsequent requests. - # - # You can read more about each approach by clicking the modules below. - # - # Note: To turn off all caching provided by Action Controller, set - # config.action_controller.perform_caching = false - # - # == \Caching stores - # - # All the caching stores from ActiveSupport::Cache are available to be used as backends - # for Action Controller caching. - # - # Configuration examples (FileStore is the default): - # - # config.action_controller.cache_store = :memory_store - # config.action_controller.cache_store = :file_store, '/path/to/cache/directory' - # config.action_controller.cache_store = :mem_cache_store, 'localhost' - # config.action_controller.cache_store = :mem_cache_store, Memcached::Rails.new('localhost:11211') - # config.action_controller.cache_store = MyOwnStore.new('parameter') - module Caching - extend ActiveSupport::Autoload - extend ActiveSupport::Concern - - included do - include AbstractController::Caching - end - - private - - def instrument_payload(key) - { - controller: controller_name, - action: action_name, - key: key - } - end - - def instrument_name - "action_controller".freeze - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/form_builder.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/form_builder.rb deleted file mode 100644 index f2656ca894..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/form_builder.rb +++ /dev/null @@ -1,48 +0,0 @@ -module ActionController - # Override the default form builder for all views rendered by this - # controller and any of its descendants. Accepts a subclass of - # +ActionView::Helpers::FormBuilder+. - # - # For example, given a form builder: - # - # class AdminFormBuilder < ActionView::Helpers::FormBuilder - # def special_field(name) - # end - # end - # - # The controller specifies a form builder as its default: - # - # class AdminAreaController < ApplicationController - # default_form_builder AdminFormBuilder - # end - # - # Then in the view any form using +form_for+ will be an instance of the - # specified form builder: - # - # <%= form_for(@instance) do |builder| %> - # <%= builder.special_field(:name) %> - # <% end %> - module FormBuilder - extend ActiveSupport::Concern - - included do - class_attribute :_default_form_builder, instance_accessor: false - end - - module ClassMethods - # Set the form builder to be used as the default for all forms - # in the views rendered by this controller and its subclasses. - # - # ==== Parameters - # * builder - Default form builder, an instance of +ActionView::Helpers::FormBuilder+ - def default_form_builder(builder) - self._default_form_builder = builder - end - end - - # Default form builder for the controller - def default_form_builder - self.class._default_form_builder - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/log_subscriber.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/log_subscriber.rb deleted file mode 100644 index d29a5fe68f..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/log_subscriber.rb +++ /dev/null @@ -1,76 +0,0 @@ -module ActionController - class LogSubscriber < ActiveSupport::LogSubscriber - INTERNAL_PARAMS = %w(controller action format _method only_path) - - def start_processing(event) - return unless logger.info? - - payload = event.payload - params = payload[:params].except(*INTERNAL_PARAMS) - format = payload[:format] - format = format.to_s.upcase if format.is_a?(Symbol) - - info "Processing by #{payload[:controller]}##{payload[:action]} as #{format}" - info " Parameters: #{params.inspect}" unless params.empty? - end - - def process_action(event) - info do - payload = event.payload - additions = ActionController::Base.log_process_action(payload) - - status = payload[:status] - if status.nil? && payload[:exception].present? - exception_class_name = payload[:exception].first - status = ActionDispatch::ExceptionWrapper.status_code_for_exception(exception_class_name) - end - message = "Completed #{status} #{Rack::Utils::HTTP_STATUS_CODES[status]} in #{event.duration.round}ms" - message << " (#{additions.join(" | ".freeze)})" unless additions.empty? - message << "\n\n" if defined?(Rails.env) && Rails.env.development? - - message - end - end - - def halted_callback(event) - info { "Filter chain halted as #{event.payload[:filter].inspect} rendered or redirected" } - end - - def send_file(event) - info { "Sent file #{event.payload[:path]} (#{event.duration.round(1)}ms)" } - end - - def redirect_to(event) - info { "Redirected to #{event.payload[:location]}" } - end - - def send_data(event) - info { "Sent data #{event.payload[:filename]} (#{event.duration.round(1)}ms)" } - end - - def unpermitted_parameters(event) - debug do - unpermitted_keys = event.payload[:keys] - "Unpermitted parameter#{'s' if unpermitted_keys.size > 1}: #{unpermitted_keys.map { |e| ":#{e}" }.join(", ")}" - end - end - - %w(write_fragment read_fragment exist_fragment? - expire_fragment expire_page write_page).each do |method| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{method}(event) - return unless logger.info? && ActionController::Base.enable_fragment_cache_logging - key_or_path = event.payload[:key] || event.payload[:path] - human_name = #{method.to_s.humanize.inspect} - info("\#{human_name} \#{key_or_path} (\#{event.duration.round(1)}ms)") - end - METHOD - end - - def logger - ActionController::Base.logger - end - end -end - -ActionController::LogSubscriber.attach_to :action_controller diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal.rb deleted file mode 100644 index 246644dcbd..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal.rb +++ /dev/null @@ -1,257 +0,0 @@ -require "active_support/core_ext/array/extract_options" -require "action_dispatch/middleware/stack" -require "action_dispatch/http/request" -require "action_dispatch/http/response" - -module ActionController - # Extend ActionDispatch middleware stack to make it aware of options - # allowing the following syntax in controllers: - # - # class PostsController < ApplicationController - # use AuthenticationMiddleware, except: [:index, :show] - # end - # - class MiddlewareStack < ActionDispatch::MiddlewareStack #:nodoc: - class Middleware < ActionDispatch::MiddlewareStack::Middleware #:nodoc: - def initialize(klass, args, actions, strategy, block) - @actions = actions - @strategy = strategy - super(klass, args, block) - end - - def valid?(action) - @strategy.call @actions, action - end - end - - def build(action, app = Proc.new) - action = action.to_s - - middlewares.reverse.inject(app) do |a, middleware| - middleware.valid?(action) ? middleware.build(a) : a - end - end - - private - - INCLUDE = ->(list, action) { list.include? action } - EXCLUDE = ->(list, action) { !list.include? action } - NULL = ->(list, action) { true } - - def build_middleware(klass, args, block) - options = args.extract_options! - only = Array(options.delete(:only)).map(&:to_s) - except = Array(options.delete(:except)).map(&:to_s) - args << options unless options.empty? - - strategy = NULL - list = nil - - if only.any? - strategy = INCLUDE - list = only - elsif except.any? - strategy = EXCLUDE - list = except - end - - Middleware.new(klass, args, list, strategy, block) - end - end - - # ActionController::Metal is the simplest possible controller, providing a - # valid Rack interface without the additional niceties provided by - # ActionController::Base. - # - # A sample metal controller might look like this: - # - # class HelloController < ActionController::Metal - # def index - # self.response_body = "Hello World!" - # end - # end - # - # And then to route requests to your metal controller, you would add - # something like this to config/routes.rb: - # - # get 'hello', to: HelloController.action(:index) - # - # The +action+ method returns a valid Rack application for the \Rails - # router to dispatch to. - # - # == Rendering Helpers - # - # ActionController::Metal by default provides no utilities for rendering - # views, partials, or other responses aside from explicitly calling of - # response_body=, content_type=, and status=. To - # add the render helpers you're used to having in a normal controller, you - # can do the following: - # - # class HelloController < ActionController::Metal - # include AbstractController::Rendering - # include ActionView::Layouts - # append_view_path "#{Rails.root}/app/views" - # - # def index - # render "hello/index" - # end - # end - # - # == Redirection Helpers - # - # To add redirection helpers to your metal controller, do the following: - # - # class HelloController < ActionController::Metal - # include ActionController::Redirecting - # include Rails.application.routes.url_helpers - # - # def index - # redirect_to root_url - # end - # end - # - # == Other Helpers - # - # You can refer to the modules included in ActionController::Base to see - # other features you can bring into your metal controller. - # - class Metal < AbstractController::Base - abstract! - - # Returns the last part of the controller's name, underscored, without the ending - # Controller. For instance, PostsController returns posts. - # Namespaces are left out, so Admin::PostsController returns posts as well. - # - # ==== Returns - # * string - def self.controller_name - @controller_name ||= name.demodulize.sub(/Controller$/, "").underscore - end - - def self.make_response!(request) - ActionDispatch::Response.new.tap do |res| - res.request = request - end - end - - def self.binary_params_for?(action) # :nodoc: - false - end - - # Delegates to the class' controller_name. - def controller_name - self.class.controller_name - end - - attr_internal :response, :request - delegate :session, to: "@_request" - delegate :headers, :status=, :location=, :content_type=, - :status, :location, :content_type, to: "@_response" - - def initialize - @_request = nil - @_response = nil - @_routes = nil - super - end - - def params - @_params ||= request.parameters - end - - def params=(val) - @_params = val - end - - alias :response_code :status # :nodoc: - - # Basic url_for that can be overridden for more robust functionality. - def url_for(string) - string - end - - def response_body=(body) - body = [body] unless body.nil? || body.respond_to?(:each) - response.reset_body! - return unless body - response.body = body - super - end - - # Tests if render or redirect has already happened. - def performed? - response_body || response.committed? - end - - def dispatch(name, request, response) #:nodoc: - set_request!(request) - set_response!(response) - process(name) - request.commit_flash - to_a - end - - def set_response!(response) # :nodoc: - @_response = response - end - - def set_request!(request) #:nodoc: - @_request = request - @_request.controller_instance = self - end - - def to_a #:nodoc: - response.to_a - end - - def reset_session - @_request.reset_session - end - - class_attribute :middleware_stack - self.middleware_stack = ActionController::MiddlewareStack.new - - def self.inherited(base) # :nodoc: - base.middleware_stack = middleware_stack.dup - super - end - - # Pushes the given Rack middleware and its arguments to the bottom of the - # middleware stack. - def self.use(*args, &block) - middleware_stack.use(*args, &block) - end - - # Alias for +middleware_stack+. - def self.middleware - middleware_stack - end - - # Returns a Rack endpoint for the given action name. - def self.action(name) - if middleware_stack.any? - middleware_stack.build(name) do |env| - req = ActionDispatch::Request.new(env) - res = make_response! req - new.dispatch(name, req, res) - end - else - lambda { |env| - req = ActionDispatch::Request.new(env) - res = make_response! req - new.dispatch(name, req, res) - } - end - end - - # Direct dispatch to the controller. Instantiates the controller, then - # executes the action named +name+. - def self.dispatch(name, req, res) - if middleware_stack.any? - middleware_stack.build(name) { |env| new.dispatch(name, req, res) }.call req.env - else - new.dispatch(name, req, res) - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/basic_implicit_render.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/basic_implicit_render.rb deleted file mode 100644 index cef65a362c..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/basic_implicit_render.rb +++ /dev/null @@ -1,11 +0,0 @@ -module ActionController - module BasicImplicitRender # :nodoc: - def send_action(method, *args) - super.tap { default_render unless performed? } - end - - def default_render(*args) - head :no_content - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/conditional_get.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/conditional_get.rb deleted file mode 100644 index eb636fa3f6..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/conditional_get.rb +++ /dev/null @@ -1,273 +0,0 @@ -require "active_support/core_ext/hash/keys" - -module ActionController - module ConditionalGet - extend ActiveSupport::Concern - - include Head - - included do - class_attribute :etaggers - self.etaggers = [] - end - - module ClassMethods - # Allows you to consider additional controller-wide information when generating an ETag. - # For example, if you serve pages tailored depending on who's logged in at the moment, you - # may want to add the current user id to be part of the ETag to prevent unauthorized displaying - # of cached pages. - # - # class InvoicesController < ApplicationController - # etag { current_user.try :id } - # - # def show - # # Etag will differ even for the same invoice when it's viewed by a different current_user - # @invoice = Invoice.find(params[:id]) - # fresh_when(@invoice) - # end - # end - def etag(&etagger) - self.etaggers += [etagger] - end - end - - # Sets the +etag+, +last_modified+, or both on the response and renders a - # 304 Not Modified response if the request is already fresh. - # - # === Parameters: - # - # * :etag Sets a "weak" ETag validator on the response. See the - # +:weak_etag+ option. - # * :weak_etag Sets a "weak" ETag validator on the response. - # Requests that set If-None-Match header may return a 304 Not Modified - # response if it matches the ETag exactly. A weak ETag indicates semantic - # equivalence, not byte-for-byte equality, so they're good for caching - # HTML pages in browser caches. They can't be used for responses that - # must be byte-identical, like serving Range requests within a PDF file. - # * :strong_etag Sets a "strong" ETag validator on the response. - # Requests that set If-None-Match header may return a 304 Not Modified - # response if it matches the ETag exactly. A strong ETag implies exact - # equality: the response must match byte for byte. This is necessary for - # doing Range requests within a large video or PDF file, for example, or - # for compatibility with some CDNs that don't support weak ETags. - # * :last_modified Sets a "weak" last-update validator on the - # response. Subsequent requests that set If-Modified-Since may return a - # 304 Not Modified response if last_modified <= If-Modified-Since. - # * :public By default the Cache-Control header is private, set this to - # +true+ if you want your application to be cacheable by other devices (proxy caches). - # * :template By default, the template digest for the current - # controller/action is included in ETags. If the action renders a - # different template, you can include its digest instead. If the action - # doesn't render a template at all, you can pass template: false - # to skip any attempt to check for a template digest. - # - # === Example: - # - # def show - # @article = Article.find(params[:id]) - # fresh_when(etag: @article, last_modified: @article.updated_at, public: true) - # end - # - # This will render the show template if the request isn't sending a matching ETag or - # If-Modified-Since header and just a 304 Not Modified response if there's a match. - # - # You can also just pass a record. In this case +last_modified+ will be set - # by calling +updated_at+ and +etag+ by passing the object itself. - # - # def show - # @article = Article.find(params[:id]) - # fresh_when(@article) - # end - # - # You can also pass an object that responds to +maximum+, such as a - # collection of active records. In this case +last_modified+ will be set by - # calling maximum(:updated_at) on the collection (the timestamp of the - # most recently updated record) and the +etag+ by passing the object itself. - # - # def index - # @articles = Article.all - # fresh_when(@articles) - # end - # - # When passing a record or a collection, you can still set the public header: - # - # def show - # @article = Article.find(params[:id]) - # fresh_when(@article, public: true) - # end - # - # When rendering a different template than the default controller/action - # style, you can indicate which digest to include in the ETag: - # - # before_action { fresh_when @article, template: 'widgets/show' } - # - def fresh_when(object = nil, etag: nil, weak_etag: nil, strong_etag: nil, last_modified: nil, public: false, template: nil) - weak_etag ||= etag || object unless strong_etag - last_modified ||= object.try(:updated_at) || object.try(:maximum, :updated_at) - - if strong_etag - response.strong_etag = combine_etags strong_etag, - last_modified: last_modified, public: public, template: template - elsif weak_etag || template - response.weak_etag = combine_etags weak_etag, - last_modified: last_modified, public: public, template: template - end - - response.last_modified = last_modified if last_modified - response.cache_control[:public] = true if public - - head :not_modified if request.fresh?(response) - end - - # Sets the +etag+ and/or +last_modified+ on the response and checks it against - # the client request. If the request doesn't match the options provided, the - # request is considered stale and should be generated from scratch. Otherwise, - # it's fresh and we don't need to generate anything and a reply of 304 Not Modified is sent. - # - # === Parameters: - # - # * :etag Sets a "weak" ETag validator on the response. See the - # +:weak_etag+ option. - # * :weak_etag Sets a "weak" ETag validator on the response. - # Requests that set If-None-Match header may return a 304 Not Modified - # response if it matches the ETag exactly. A weak ETag indicates semantic - # equivalence, not byte-for-byte equality, so they're good for caching - # HTML pages in browser caches. They can't be used for responses that - # must be byte-identical, like serving Range requests within a PDF file. - # * :strong_etag Sets a "strong" ETag validator on the response. - # Requests that set If-None-Match header may return a 304 Not Modified - # response if it matches the ETag exactly. A strong ETag implies exact - # equality: the response must match byte for byte. This is necessary for - # doing Range requests within a large video or PDF file, for example, or - # for compatibility with some CDNs that don't support weak ETags. - # * :last_modified Sets a "weak" last-update validator on the - # response. Subsequent requests that set If-Modified-Since may return a - # 304 Not Modified response if last_modified <= If-Modified-Since. - # * :public By default the Cache-Control header is private, set this to - # +true+ if you want your application to be cacheable by other devices (proxy caches). - # * :template By default, the template digest for the current - # controller/action is included in ETags. If the action renders a - # different template, you can include its digest instead. If the action - # doesn't render a template at all, you can pass template: false - # to skip any attempt to check for a template digest. - # - # === Example: - # - # def show - # @article = Article.find(params[:id]) - # - # if stale?(etag: @article, last_modified: @article.updated_at) - # @statistics = @article.really_expensive_call - # respond_to do |format| - # # all the supported formats - # end - # end - # end - # - # You can also just pass a record. In this case +last_modified+ will be set - # by calling +updated_at+ and +etag+ by passing the object itself. - # - # def show - # @article = Article.find(params[:id]) - # - # if stale?(@article) - # @statistics = @article.really_expensive_call - # respond_to do |format| - # # all the supported formats - # end - # end - # end - # - # You can also pass an object that responds to +maximum+, such as a - # collection of active records. In this case +last_modified+ will be set by - # calling +maximum(:updated_at)+ on the collection (the timestamp of the - # most recently updated record) and the +etag+ by passing the object itself. - # - # def index - # @articles = Article.all - # - # if stale?(@articles) - # @statistics = @articles.really_expensive_call - # respond_to do |format| - # # all the supported formats - # end - # end - # end - # - # When passing a record or a collection, you can still set the public header: - # - # def show - # @article = Article.find(params[:id]) - # - # if stale?(@article, public: true) - # @statistics = @article.really_expensive_call - # respond_to do |format| - # # all the supported formats - # end - # end - # end - # - # When rendering a different template than the default controller/action - # style, you can indicate which digest to include in the ETag: - # - # def show - # super if stale? @article, template: 'widgets/show' - # end - # - def stale?(object = nil, **freshness_kwargs) - fresh_when(object, **freshness_kwargs) - !request.fresh?(response) - end - - # Sets an HTTP 1.1 Cache-Control header. Defaults to issuing a +private+ - # instruction, so that intermediate caches must not cache the response. - # - # expires_in 20.minutes - # expires_in 3.hours, public: true - # expires_in 3.hours, public: true, must_revalidate: true - # - # This method will overwrite an existing Cache-Control header. - # See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities. - # - # The method will also ensure an HTTP Date header for client compatibility. - def expires_in(seconds, options = {}) - response.cache_control.merge!( - max_age: seconds, - public: options.delete(:public), - must_revalidate: options.delete(:must_revalidate) - ) - options.delete(:private) - - response.cache_control[:extras] = options.map { |k, v| "#{k}=#{v}" } - response.date = Time.now unless response.date? - end - - # Sets an HTTP 1.1 Cache-Control header of no-cache. This means the - # resource will be marked as stale, so clients must always revalidate. - # Intermediate/browser caches may still store the asset. - def expires_now - response.cache_control.replace(no_cache: true) - end - - # Cache or yield the block. The cache is supposed to never expire. - # - # You can use this method when you have an HTTP response that never changes, - # and the browser and proxies should cache it indefinitely. - # - # * +public+: By default, HTTP responses are private, cached only on the - # user's web browser. To allow proxies to cache the response, set +true+ to - # indicate that they can serve the cached response to all users. - def http_cache_forever(public: false) - expires_in 100.years, public: public - - yield if stale?(etag: request.fullpath, - last_modified: Time.new(2011, 1, 1).utc, - public: public) - end - - private - def combine_etags(validator, options) - [validator, *etaggers.map { |etagger| instance_exec(options, &etagger) }].compact - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/cookies.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/cookies.rb deleted file mode 100644 index 44925641a1..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/cookies.rb +++ /dev/null @@ -1,14 +0,0 @@ -module ActionController #:nodoc: - module Cookies - extend ActiveSupport::Concern - - included do - helper_method :cookies if defined?(helper_method) - end - - private - def cookies - request.cookie_jar - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/data_streaming.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/data_streaming.rb deleted file mode 100644 index 731e03e2fc..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/data_streaming.rb +++ /dev/null @@ -1,150 +0,0 @@ -require "action_controller/metal/exceptions" - -module ActionController #:nodoc: - # Methods for sending arbitrary data and for streaming files to the browser, - # instead of rendering. - module DataStreaming - extend ActiveSupport::Concern - - include ActionController::Rendering - - DEFAULT_SEND_FILE_TYPE = "application/octet-stream".freeze #:nodoc: - DEFAULT_SEND_FILE_DISPOSITION = "attachment".freeze #:nodoc: - - private - # Sends the file. This uses a server-appropriate method (such as X-Sendfile) - # via the Rack::Sendfile middleware. The header to use is set via - # +config.action_dispatch.x_sendfile_header+. - # Your server can also configure this for you by setting the X-Sendfile-Type header. - # - # Be careful to sanitize the path parameter if it is coming from a web - # page. send_file(params[:path]) allows a malicious user to - # download any file on your server. - # - # Options: - # * :filename - suggests a filename for the browser to use. - # Defaults to File.basename(path). - # * :type - specifies an HTTP content type. - # You can specify either a string or a symbol for a registered type with Mime::Type.register, for example :json. - # If omitted, the type will be inferred from the file extension specified in :filename. - # If no content type is registered for the extension, the default type 'application/octet-stream' will be used. - # * :disposition - specifies whether the file will be shown inline or downloaded. - # Valid values are 'inline' and 'attachment' (default). - # * :status - specifies the status code to send with the response. Defaults to 200. - # * :url_based_filename - set to +true+ if you want the browser to guess the filename from - # the URL, which is necessary for i18n filenames on certain browsers - # (setting :filename overrides this option). - # - # The default Content-Type and Content-Disposition headers are - # set to download arbitrary binary files in as many browsers as - # possible. IE versions 4, 5, 5.5, and 6 are all known to have - # a variety of quirks (especially when downloading over SSL). - # - # Simple download: - # - # send_file '/path/to.zip' - # - # Show a JPEG in the browser: - # - # send_file '/path/to.jpeg', type: 'image/jpeg', disposition: 'inline' - # - # Show a 404 page in the browser: - # - # send_file '/path/to/404.html', type: 'text/html; charset=utf-8', status: 404 - # - # Read about the other Content-* HTTP headers if you'd like to - # provide the user with more information (such as Content-Description) in - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11. - # - # Also be aware that the document may be cached by proxies and browsers. - # The Pragma and Cache-Control headers declare how the file may be cached - # by intermediaries. They default to require clients to validate with - # the server before releasing cached responses. See - # http://www.mnot.net/cache_docs/ for an overview of web caching and - # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9 - # for the Cache-Control header spec. - def send_file(path, options = {}) #:doc: - raise MissingFile, "Cannot read file #{path}" unless File.file?(path) && File.readable?(path) - - options[:filename] ||= File.basename(path) unless options[:url_based_filename] - send_file_headers! options - - self.status = options[:status] || 200 - self.content_type = options[:content_type] if options.key?(:content_type) - response.send_file path - end - - # Sends the given binary data to the browser. This method is similar to - # render plain: data, but also allows you to specify whether - # the browser should display the response as a file attachment (i.e. in a - # download dialog) or as inline data. You may also set the content type, - # the file name, and other things. - # - # Options: - # * :filename - suggests a filename for the browser to use. - # * :type - specifies an HTTP content type. Defaults to 'application/octet-stream'. - # You can specify either a string or a symbol for a registered type with Mime::Type.register, for example :json. - # If omitted, type will be inferred from the file extension specified in :filename. - # If no content type is registered for the extension, the default type 'application/octet-stream' will be used. - # * :disposition - specifies whether the file will be shown inline or downloaded. - # Valid values are 'inline' and 'attachment' (default). - # * :status - specifies the status code to send with the response. Defaults to 200. - # - # Generic data download: - # - # send_data buffer - # - # Download a dynamically-generated tarball: - # - # send_data generate_tgz('dir'), filename: 'dir.tgz' - # - # Display an image Active Record in the browser: - # - # send_data image.data, type: image.content_type, disposition: 'inline' - # - # See +send_file+ for more information on HTTP Content-* headers and caching. - def send_data(data, options = {}) #:doc: - send_file_headers! options - render options.slice(:status, :content_type).merge(body: data) - end - - def send_file_headers!(options) - type_provided = options.has_key?(:type) - - self.content_type = DEFAULT_SEND_FILE_TYPE - response.sending_file = true - - content_type = options.fetch(:type, DEFAULT_SEND_FILE_TYPE) - raise ArgumentError, ":type option required" if content_type.nil? - - if content_type.is_a?(Symbol) - extension = Mime[content_type] - raise ArgumentError, "Unknown MIME type #{options[:type]}" unless extension - self.content_type = extension - else - if !type_provided && options[:filename] - # If type wasn't provided, try guessing from file extension. - content_type = Mime::Type.lookup_by_extension(File.extname(options[:filename]).downcase.delete(".")) || content_type - end - self.content_type = content_type - end - - disposition = options.fetch(:disposition, DEFAULT_SEND_FILE_DISPOSITION) - unless disposition.nil? - disposition = disposition.to_s - disposition += %(; filename="#{options[:filename]}") if options[:filename] - headers["Content-Disposition"] = disposition - end - - headers["Content-Transfer-Encoding"] = "binary" - - # Fix a problem with IE 6.0 on opening downloaded files: - # If Cache-Control: no-cache is set (which Rails does by default), - # IE removes the file it just downloaded from its cache immediately - # after it displays the "open/save" dialog, which means that if you - # hit "open" the file isn't there anymore when the application that - # is called for handling the download is run, so let's workaround that - response.cache_control[:public] ||= false - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/etag_with_flash.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/etag_with_flash.rb deleted file mode 100644 index 7bd338bd7c..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/etag_with_flash.rb +++ /dev/null @@ -1,16 +0,0 @@ -module ActionController - # When you're using the flash, it's generally used as a conditional on the view. - # This means the content of the view depends on the flash. Which in turn means - # that the ETag for a response should be computed with the content of the flash - # in mind. This does that by including the content of the flash as a component - # in the ETag that's generated for a response. - module EtagWithFlash - extend ActiveSupport::Concern - - include ActionController::ConditionalGet - - included do - etag { flash unless flash.empty? } - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/etag_with_template_digest.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/etag_with_template_digest.rb deleted file mode 100644 index 798564db96..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/etag_with_template_digest.rb +++ /dev/null @@ -1,56 +0,0 @@ -module ActionController - # When our views change, they should bubble up into HTTP cache freshness - # and bust browser caches. So the template digest for the current action - # is automatically included in the ETag. - # - # Enabled by default for apps that use Action View. Disable by setting - # - # config.action_controller.etag_with_template_digest = false - # - # Override the template to digest by passing +:template+ to +fresh_when+ - # and +stale?+ calls. For example: - # - # # We're going to render widgets/show, not posts/show - # fresh_when @post, template: 'widgets/show' - # - # # We're not going to render a template, so omit it from the ETag. - # fresh_when @post, template: false - # - module EtagWithTemplateDigest - extend ActiveSupport::Concern - - include ActionController::ConditionalGet - - included do - class_attribute :etag_with_template_digest - self.etag_with_template_digest = true - - ActiveSupport.on_load :action_view, yield: true do - etag do |options| - determine_template_etag(options) if etag_with_template_digest - end - end - end - - private - def determine_template_etag(options) - if template = pick_template_for_etag(options) - lookup_and_digest_template(template) - end - end - - # Pick the template digest to include in the ETag. If the +:template+ option - # is present, use the named template. If +:template+ is +nil+ or absent, use - # the default controller/action template. If +:template+ is false, omit the - # template digest from the ETag. - def pick_template_for_etag(options) - unless options[:template] == false - options[:template] || "#{controller_path}/#{action_name}" - end - end - - def lookup_and_digest_template(template) - ActionView::Digestor.digest name: template, finder: lookup_context - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/exceptions.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/exceptions.rb deleted file mode 100644 index 175dd9eb9e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/exceptions.rb +++ /dev/null @@ -1,54 +0,0 @@ -module ActionController - class ActionControllerError < StandardError #:nodoc: - end - - class BadRequest < ActionControllerError #:nodoc: - def initialize(msg = nil) - super(msg) - set_backtrace $!.backtrace if $! - end - end - - class RenderError < ActionControllerError #:nodoc: - end - - class RoutingError < ActionControllerError #:nodoc: - attr_reader :failures - def initialize(message, failures = []) - super(message) - @failures = failures - end - end - - class ActionController::UrlGenerationError < ActionControllerError #:nodoc: - end - - class MethodNotAllowed < ActionControllerError #:nodoc: - def initialize(*allowed_methods) - super("Only #{allowed_methods.to_sentence(locale: :en)} requests are allowed.") - end - end - - class NotImplemented < MethodNotAllowed #:nodoc: - end - - class UnknownController < ActionControllerError #:nodoc: - end - - class MissingFile < ActionControllerError #:nodoc: - end - - class SessionOverflowError < ActionControllerError #:nodoc: - DEFAULT_MESSAGE = "Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data." - - def initialize(message = nil) - super(message || DEFAULT_MESSAGE) - end - end - - class UnknownHttpMethod < ActionControllerError #:nodoc: - end - - class UnknownFormat < ActionControllerError #:nodoc: - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/flash.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/flash.rb deleted file mode 100644 index 347fbf0e74..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/flash.rb +++ /dev/null @@ -1,60 +0,0 @@ -module ActionController #:nodoc: - module Flash - extend ActiveSupport::Concern - - included do - class_attribute :_flash_types, instance_accessor: false - self._flash_types = [] - - delegate :flash, to: :request - add_flash_types(:alert, :notice) - end - - module ClassMethods - # Creates new flash types. You can pass as many types as you want to create - # flash types other than the default alert and notice in - # your controllers and views. For instance: - # - # # in application_controller.rb - # class ApplicationController < ActionController::Base - # add_flash_types :warning - # end - # - # # in your controller - # redirect_to user_path(@user), warning: "Incomplete profile" - # - # # in your view - # <%= warning %> - # - # This method will automatically define a new method for each of the given - # names, and it will be available in your views. - def add_flash_types(*types) - types.each do |type| - next if _flash_types.include?(type) - - define_method(type) do - request.flash[type] - end - helper_method type - - self._flash_types += [type] - end - end - end - - private - def redirect_to(options = {}, response_status_and_flash = {}) #:doc: - self.class._flash_types.each do |flash_type| - if type = response_status_and_flash.delete(flash_type) - flash[flash_type] = type - end - end - - if other_flashes = response_status_and_flash.delete(:flash) - flash.update(other_flashes) - end - - super(options, response_status_and_flash) - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/force_ssl.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/force_ssl.rb deleted file mode 100644 index 73e67573ca..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/force_ssl.rb +++ /dev/null @@ -1,97 +0,0 @@ -require "active_support/core_ext/hash/except" -require "active_support/core_ext/hash/slice" - -module ActionController - # This module provides a method which will redirect the browser to use the secured HTTPS - # protocol. This will ensure that users' sensitive information will be - # transferred safely over the internet. You _should_ always force the browser - # to use HTTPS when you're transferring sensitive information such as - # user authentication, account information, or credit card information. - # - # Note that if you are really concerned about your application security, - # you might consider using +config.force_ssl+ in your config file instead. - # That will ensure all the data is transferred via HTTPS, and will - # prevent the user from getting their session hijacked when accessing the - # site over unsecured HTTP protocol. - module ForceSSL - extend ActiveSupport::Concern - include AbstractController::Callbacks - - ACTION_OPTIONS = [:only, :except, :if, :unless] - URL_OPTIONS = [:protocol, :host, :domain, :subdomain, :port, :path] - REDIRECT_OPTIONS = [:status, :flash, :alert, :notice] - - module ClassMethods - # Force the request to this particular controller or specified actions to be - # through the HTTPS protocol. - # - # If you need to disable this for any reason (e.g. development) then you can use - # an +:if+ or +:unless+ condition. - # - # class AccountsController < ApplicationController - # force_ssl if: :ssl_configured? - # - # def ssl_configured? - # !Rails.env.development? - # end - # end - # - # ==== URL Options - # You can pass any of the following options to affect the redirect url - # * host - Redirect to a different host name - # * subdomain - Redirect to a different subdomain - # * domain - Redirect to a different domain - # * port - Redirect to a non-standard port - # * path - Redirect to a different path - # - # ==== Redirect Options - # You can pass any of the following options to affect the redirect status and response - # * status - Redirect with a custom status (default is 301 Moved Permanently) - # * flash - Set a flash message when redirecting - # * alert - Set an alert message when redirecting - # * notice - Set a notice message when redirecting - # - # ==== Action Options - # You can pass any of the following options to affect the before_action callback - # * only - The callback should be run only for this action - # * except - The callback should be run for all actions except this action - # * if - A symbol naming an instance method or a proc; the - # callback will be called only when it returns a true value. - # * unless - A symbol naming an instance method or a proc; the - # callback will be called only when it returns a false value. - def force_ssl(options = {}) - action_options = options.slice(*ACTION_OPTIONS) - redirect_options = options.except(*ACTION_OPTIONS) - before_action(action_options) do - force_ssl_redirect(redirect_options) - end - end - end - - # Redirect the existing request to use the HTTPS protocol. - # - # ==== Parameters - # * host_or_options - Either a host name or any of the url and - # redirect options available to the force_ssl method. - def force_ssl_redirect(host_or_options = nil) - unless request.ssl? - options = { - protocol: "https://", - host: request.host, - path: request.fullpath, - status: :moved_permanently - } - - if host_or_options.is_a?(Hash) - options.merge!(host_or_options) - elsif host_or_options - options[:host] = host_or_options - end - - secure_url = ActionDispatch::Http::URL.url_for(options.slice(*URL_OPTIONS)) - flash.keep if respond_to?(:flash) && request.respond_to?(:flash) - redirect_to secure_url, options.slice(*REDIRECT_OPTIONS) - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/head.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/head.rb deleted file mode 100644 index 0c50894bce..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/head.rb +++ /dev/null @@ -1,58 +0,0 @@ -module ActionController - module Head - # Returns a response that has no content (merely headers). The options - # argument is interpreted to be a hash of header names and values. - # This allows you to easily return a response that consists only of - # significant headers: - # - # head :created, location: person_path(@person) - # - # head :created, location: @person - # - # It can also be used to return exceptional conditions: - # - # return head(:method_not_allowed) unless request.post? - # return head(:bad_request) unless valid_request? - # render - # - # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list of valid +status+ symbols. - def head(status, options = {}) - if status.is_a?(Hash) - raise ArgumentError, "#{status.inspect} is not a valid value for `status`." - end - - status ||= :ok - - location = options.delete(:location) - content_type = options.delete(:content_type) - - options.each do |key, value| - headers[key.to_s.dasherize.split("-").each { |v| v[0] = v[0].chr.upcase }.join("-")] = value.to_s - end - - self.status = status - self.location = url_for(location) if location - - self.response_body = "" - - if include_content?(response_code) - self.content_type = content_type || (Mime[formats.first] if formats) - response.charset = false - end - - true - end - - private - def include_content?(status) - case status - when 100..199 - false - when 204, 205, 304 - false - else - true - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/helpers.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/helpers.rb deleted file mode 100644 index 476d081239..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/helpers.rb +++ /dev/null @@ -1,122 +0,0 @@ -module ActionController - # The \Rails framework provides a large number of helpers for working with assets, dates, forms, - # numbers and model objects, to name a few. These helpers are available to all templates - # by default. - # - # In addition to using the standard template helpers provided, creating custom helpers to - # extract complicated logic or reusable functionality is strongly encouraged. By default, each controller - # will include all helpers. These helpers are only accessible on the controller through #helpers - # - # In previous versions of \Rails the controller will include a helper which - # matches the name of the controller, e.g., MyController will automatically - # include MyHelper. To return old behavior set +config.action_controller.include_all_helpers+ to +false+. - # - # Additional helpers can be specified using the +helper+ class method in ActionController::Base or any - # controller which inherits from it. - # - # The +to_s+ method from the \Time class can be wrapped in a helper method to display a custom message if - # a \Time object is blank: - # - # module FormattedTimeHelper - # def format_time(time, format=:long, blank_message=" ") - # time.blank? ? blank_message : time.to_s(format) - # end - # end - # - # FormattedTimeHelper can now be included in a controller, using the +helper+ class method: - # - # class EventsController < ActionController::Base - # helper FormattedTimeHelper - # def index - # @events = Event.all - # end - # end - # - # Then, in any view rendered by EventController, the format_time method can be called: - # - # <% @events.each do |event| -%> - #

- # <%= format_time(event.time, :short, "N/A") %> | <%= event.name %> - #

- # <% end -%> - # - # Finally, assuming we have two event instances, one which has a time and one which does not, - # the output might look like this: - # - # 23 Aug 11:30 | Carolina Railhawks Soccer Match - # N/A | Carolina Railhawks Training Workshop - # - module Helpers - extend ActiveSupport::Concern - - class << self; attr_accessor :helpers_path; end - include AbstractController::Helpers - - included do - class_attribute :helpers_path, :include_all_helpers - self.helpers_path ||= [] - self.include_all_helpers = true - end - - module ClassMethods - # Declares helper accessors for controller attributes. For example, the - # following adds new +name+ and name= instance methods to a - # controller and makes them available to the view: - # attr_accessor :name - # helper_attr :name - # - # ==== Parameters - # * attrs - Names of attributes to be converted into helpers. - def helper_attr(*attrs) - attrs.flatten.each { |attr| helper_method(attr, "#{attr}=") } - end - - # Provides a proxy to access helper methods from outside the view. - def helpers - @helper_proxy ||= begin - proxy = ActionView::Base.new - proxy.config = config.inheritable_copy - proxy.extend(_helpers) - end - end - - # Overwrite modules_for_helpers to accept :all as argument, which loads - # all helpers in helpers_path. - # - # ==== Parameters - # * args - A list of helpers - # - # ==== Returns - # * array - A normalized list of modules for the list of helpers provided. - def modules_for_helpers(args) - args += all_application_helpers if args.delete(:all) - super(args) - end - - # Returns a list of helper names in a given path. - # - # ActionController::Base.all_helpers_from_path 'app/helpers' - # # => ["application", "chart", "rubygems"] - def all_helpers_from_path(path) - helpers = Array(path).flat_map do |_path| - extract = /^#{Regexp.quote(_path.to_s)}\/?(.*)_helper.rb$/ - names = Dir["#{_path}/**/*_helper.rb"].map { |file| file.sub(extract, '\1'.freeze) } - names.sort! - end - helpers.uniq! - helpers - end - - private - # Extract helper names from files in app/helpers/**/*_helper.rb - def all_application_helpers - all_helpers_from_path(helpers_path) - end - end - - # Provides a proxy to access helper methods from outside the view. - def helpers - @_helper_proxy ||= view_context - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/http_authentication.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/http_authentication.rb deleted file mode 100644 index d8bc895265..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/http_authentication.rb +++ /dev/null @@ -1,520 +0,0 @@ -require "base64" -require "active_support/security_utils" - -module ActionController - # Makes it dead easy to do HTTP Basic, Digest and Token authentication. - module HttpAuthentication - # Makes it dead easy to do HTTP \Basic authentication. - # - # === Simple \Basic example - # - # class PostsController < ApplicationController - # http_basic_authenticate_with name: "dhh", password: "secret", except: :index - # - # def index - # render plain: "Everyone can see me!" - # end - # - # def edit - # render plain: "I'm only accessible if you know the password" - # end - # end - # - # === Advanced \Basic example - # - # Here is a more advanced \Basic example where only Atom feeds and the XML API is protected by HTTP authentication, - # the regular HTML interface is protected by a session approach: - # - # class ApplicationController < ActionController::Base - # before_action :set_account, :authenticate - # - # private - # def set_account - # @account = Account.find_by(url_name: request.subdomains.first) - # end - # - # def authenticate - # case request.format - # when Mime[:xml], Mime[:atom] - # if user = authenticate_with_http_basic { |u, p| @account.users.authenticate(u, p) } - # @current_user = user - # else - # request_http_basic_authentication - # end - # else - # if session_authenticated? - # @current_user = @account.users.find(session[:authenticated][:user_id]) - # else - # redirect_to(login_url) and return false - # end - # end - # end - # end - # - # In your integration tests, you can do something like this: - # - # def test_access_granted_from_xml - # @request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(users(:dhh).name, users(:dhh).password) - # get "/notes/1.xml" - # - # assert_equal 200, status - # end - module Basic - extend self - - module ControllerMethods - extend ActiveSupport::Concern - - module ClassMethods - def http_basic_authenticate_with(options = {}) - before_action(options.except(:name, :password, :realm)) do - authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password| - # This comparison uses & so that it doesn't short circuit and - # uses `variable_size_secure_compare` so that length information - # isn't leaked. - ActiveSupport::SecurityUtils.variable_size_secure_compare(name, options[:name]) & - ActiveSupport::SecurityUtils.variable_size_secure_compare(password, options[:password]) - end - end - end - end - - def authenticate_or_request_with_http_basic(realm = "Application", message = nil, &login_procedure) - authenticate_with_http_basic(&login_procedure) || request_http_basic_authentication(realm, message) - end - - def authenticate_with_http_basic(&login_procedure) - HttpAuthentication::Basic.authenticate(request, &login_procedure) - end - - def request_http_basic_authentication(realm = "Application", message = nil) - HttpAuthentication::Basic.authentication_request(self, realm, message) - end - end - - def authenticate(request, &login_procedure) - if has_basic_credentials?(request) - login_procedure.call(*user_name_and_password(request)) - end - end - - def has_basic_credentials?(request) - request.authorization.present? && (auth_scheme(request).downcase == "basic") - end - - def user_name_and_password(request) - decode_credentials(request).split(":", 2) - end - - def decode_credentials(request) - ::Base64.decode64(auth_param(request) || "") - end - - def auth_scheme(request) - request.authorization.to_s.split(" ", 2).first - end - - def auth_param(request) - request.authorization.to_s.split(" ", 2).second - end - - def encode_credentials(user_name, password) - "Basic #{::Base64.strict_encode64("#{user_name}:#{password}")}" - end - - def authentication_request(controller, realm, message) - message ||= "HTTP Basic: Access denied.\n" - controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.tr('"'.freeze, "".freeze)}") - controller.status = 401 - controller.response_body = message - end - end - - # Makes it dead easy to do HTTP \Digest authentication. - # - # === Simple \Digest example - # - # require 'digest/md5' - # class PostsController < ApplicationController - # REALM = "SuperSecret" - # USERS = {"dhh" => "secret", #plain text password - # "dap" => Digest::MD5.hexdigest(["dap",REALM,"secret"].join(":"))} #ha1 digest password - # - # before_action :authenticate, except: [:index] - # - # def index - # render plain: "Everyone can see me!" - # end - # - # def edit - # render plain: "I'm only accessible if you know the password" - # end - # - # private - # def authenticate - # authenticate_or_request_with_http_digest(REALM) do |username| - # USERS[username] - # end - # end - # end - # - # === Notes - # - # The +authenticate_or_request_with_http_digest+ block must return the user's password - # or the ha1 digest hash so the framework can appropriately hash to check the user's - # credentials. Returning +nil+ will cause authentication to fail. - # - # Storing the ha1 hash: MD5(username:realm:password), is better than storing a plain password. If - # the password file or database is compromised, the attacker would be able to use the ha1 hash to - # authenticate as the user at this +realm+, but would not have the user's password to try using at - # other sites. - # - # In rare instances, web servers or front proxies strip authorization headers before - # they reach your application. You can debug this situation by logging all environment - # variables, and check for HTTP_AUTHORIZATION, amongst others. - module Digest - extend self - - module ControllerMethods - def authenticate_or_request_with_http_digest(realm = "Application", message = nil, &password_procedure) - authenticate_with_http_digest(realm, &password_procedure) || request_http_digest_authentication(realm, message) - end - - # Authenticate with HTTP Digest, returns true or false - def authenticate_with_http_digest(realm = "Application", &password_procedure) - HttpAuthentication::Digest.authenticate(request, realm, &password_procedure) - end - - # Render output including the HTTP Digest authentication header - def request_http_digest_authentication(realm = "Application", message = nil) - HttpAuthentication::Digest.authentication_request(self, realm, message) - end - end - - # Returns false on a valid response, true otherwise - def authenticate(request, realm, &password_procedure) - request.authorization && validate_digest_response(request, realm, &password_procedure) - end - - # Returns false unless the request credentials response value matches the expected value. - # First try the password as a ha1 digest password. If this fails, then try it as a plain - # text password. - def validate_digest_response(request, realm, &password_procedure) - secret_key = secret_token(request) - credentials = decode_credentials_header(request) - valid_nonce = validate_nonce(secret_key, request, credentials[:nonce]) - - if valid_nonce && realm == credentials[:realm] && opaque(secret_key) == credentials[:opaque] - password = password_procedure.call(credentials[:username]) - return false unless password - - method = request.get_header("rack.methodoverride.original_method") || request.get_header("REQUEST_METHOD") - uri = credentials[:uri] - - [true, false].any? do |trailing_question_mark| - [true, false].any? do |password_is_ha1| - _uri = trailing_question_mark ? uri + "?" : uri - expected = expected_response(method, _uri, credentials, password, password_is_ha1) - expected == credentials[:response] - end - end - end - end - - # Returns the expected response for a request of +http_method+ to +uri+ with the decoded +credentials+ and the expected +password+ - # Optional parameter +password_is_ha1+ is set to +true+ by default, since best practice is to store ha1 digest instead - # of a plain-text password. - def expected_response(http_method, uri, credentials, password, password_is_ha1 = true) - ha1 = password_is_ha1 ? password : ha1(credentials, password) - ha2 = ::Digest::MD5.hexdigest([http_method.to_s.upcase, uri].join(":")) - ::Digest::MD5.hexdigest([ha1, credentials[:nonce], credentials[:nc], credentials[:cnonce], credentials[:qop], ha2].join(":")) - end - - def ha1(credentials, password) - ::Digest::MD5.hexdigest([credentials[:username], credentials[:realm], password].join(":")) - end - - def encode_credentials(http_method, credentials, password, password_is_ha1) - credentials[:response] = expected_response(http_method, credentials[:uri], credentials, password, password_is_ha1) - "Digest " + credentials.sort_by { |x| x[0].to_s }.map { |v| "#{v[0]}='#{v[1]}'" }.join(", ") - end - - def decode_credentials_header(request) - decode_credentials(request.authorization) - end - - def decode_credentials(header) - ActiveSupport::HashWithIndifferentAccess[header.to_s.gsub(/^Digest\s+/, "").split(",").map do |pair| - key, value = pair.split("=", 2) - [key.strip, value.to_s.gsub(/^"|"$/, "").delete('\'')] - end] - end - - def authentication_header(controller, realm) - secret_key = secret_token(controller.request) - nonce = self.nonce(secret_key) - opaque = opaque(secret_key) - controller.headers["WWW-Authenticate"] = %(Digest realm="#{realm}", qop="auth", algorithm=MD5, nonce="#{nonce}", opaque="#{opaque}") - end - - def authentication_request(controller, realm, message = nil) - message ||= "HTTP Digest: Access denied.\n" - authentication_header(controller, realm) - controller.status = 401 - controller.response_body = message - end - - def secret_token(request) - key_generator = request.key_generator - http_auth_salt = request.http_auth_salt - key_generator.generate_key(http_auth_salt) - end - - # Uses an MD5 digest based on time to generate a value to be used only once. - # - # A server-specified data string which should be uniquely generated each time a 401 response is made. - # It is recommended that this string be base64 or hexadecimal data. - # Specifically, since the string is passed in the header lines as a quoted string, the double-quote character is not allowed. - # - # The contents of the nonce are implementation dependent. - # The quality of the implementation depends on a good choice. - # A nonce might, for example, be constructed as the base 64 encoding of - # - # time-stamp H(time-stamp ":" ETag ":" private-key) - # - # where time-stamp is a server-generated time or other non-repeating value, - # ETag is the value of the HTTP ETag header associated with the requested entity, - # and private-key is data known only to the server. - # With a nonce of this form a server would recalculate the hash portion after receiving the client authentication header and - # reject the request if it did not match the nonce from that header or - # if the time-stamp value is not recent enough. In this way the server can limit the time of the nonce's validity. - # The inclusion of the ETag prevents a replay request for an updated version of the resource. - # (Note: including the IP address of the client in the nonce would appear to offer the server the ability - # to limit the reuse of the nonce to the same client that originally got it. - # However, that would break proxy farms, where requests from a single user often go through different proxies in the farm. - # Also, IP address spoofing is not that hard.) - # - # An implementation might choose not to accept a previously used nonce or a previously used digest, in order to - # protect against a replay attack. Or, an implementation might choose to use one-time nonces or digests for - # POST, PUT, or PATCH requests and a time-stamp for GET requests. For more details on the issues involved see Section 4 - # of this document. - # - # The nonce is opaque to the client. Composed of Time, and hash of Time with secret - # key from the Rails session secret generated upon creation of project. Ensures - # the time cannot be modified by client. - def nonce(secret_key, time = Time.now) - t = time.to_i - hashed = [t, secret_key] - digest = ::Digest::MD5.hexdigest(hashed.join(":")) - ::Base64.strict_encode64("#{t}:#{digest}") - end - - # Might want a shorter timeout depending on whether the request - # is a PATCH, PUT, or POST, and if the client is a browser or web service. - # Can be much shorter if the Stale directive is implemented. This would - # allow a user to use new nonce without prompting the user again for their - # username and password. - def validate_nonce(secret_key, request, value, seconds_to_timeout = 5 * 60) - return false if value.nil? - t = ::Base64.decode64(value).split(":").first.to_i - nonce(secret_key, t) == value && (t - Time.now.to_i).abs <= seconds_to_timeout - end - - # Opaque based on digest of secret key - def opaque(secret_key) - ::Digest::MD5.hexdigest(secret_key) - end - end - - # Makes it dead easy to do HTTP Token authentication. - # - # Simple Token example: - # - # class PostsController < ApplicationController - # TOKEN = "secret" - # - # before_action :authenticate, except: [ :index ] - # - # def index - # render plain: "Everyone can see me!" - # end - # - # def edit - # render plain: "I'm only accessible if you know the password" - # end - # - # private - # def authenticate - # authenticate_or_request_with_http_token do |token, options| - # # Compare the tokens in a time-constant manner, to mitigate - # # timing attacks. - # ActiveSupport::SecurityUtils.secure_compare( - # ::Digest::SHA256.hexdigest(token), - # ::Digest::SHA256.hexdigest(TOKEN) - # ) - # end - # end - # end - # - # - # Here is a more advanced Token example where only Atom feeds and the XML API is protected by HTTP token authentication, - # the regular HTML interface is protected by a session approach: - # - # class ApplicationController < ActionController::Base - # before_action :set_account, :authenticate - # - # private - # def set_account - # @account = Account.find_by(url_name: request.subdomains.first) - # end - # - # def authenticate - # case request.format - # when Mime[:xml], Mime[:atom] - # if user = authenticate_with_http_token { |t, o| @account.users.authenticate(t, o) } - # @current_user = user - # else - # request_http_token_authentication - # end - # else - # if session_authenticated? - # @current_user = @account.users.find(session[:authenticated][:user_id]) - # else - # redirect_to(login_url) and return false - # end - # end - # end - # end - # - # - # In your integration tests, you can do something like this: - # - # def test_access_granted_from_xml - # get( - # "/notes/1.xml", nil, - # 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token) - # ) - # - # assert_equal 200, status - # end - # - # - # On shared hosts, Apache sometimes doesn't pass authentication headers to - # FCGI instances. If your environment matches this description and you cannot - # authenticate, try this rule in your Apache setup: - # - # RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L] - module Token - TOKEN_KEY = "token=" - TOKEN_REGEX = /^(Token|Bearer)\s+/ - AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/ - extend self - - module ControllerMethods - def authenticate_or_request_with_http_token(realm = "Application", message = nil, &login_procedure) - authenticate_with_http_token(&login_procedure) || request_http_token_authentication(realm, message) - end - - def authenticate_with_http_token(&login_procedure) - Token.authenticate(self, &login_procedure) - end - - def request_http_token_authentication(realm = "Application", message = nil) - Token.authentication_request(self, realm, message) - end - end - - # If token Authorization header is present, call the login - # procedure with the present token and options. - # - # [controller] - # ActionController::Base instance for the current request. - # - # [login_procedure] - # Proc to call if a token is present. The Proc should take two arguments: - # - # authenticate(controller) { |token, options| ... } - # - # Returns the return value of login_procedure if a - # token is found. Returns nil if no token is found. - - def authenticate(controller, &login_procedure) - token, options = token_and_options(controller.request) - unless token.blank? - login_procedure.call(token, options) - end - end - - # Parses the token and options out of the token Authorization header. - # The value for the Authorization header is expected to have the prefix - # "Token" or "Bearer". If the header looks like this: - # Authorization: Token token="abc", nonce="def" - # Then the returned token is "abc", and the options are - # {nonce: "def"} - # - # request - ActionDispatch::Request instance with the current headers. - # - # Returns an +Array+ of [String, Hash] if a token is present. - # Returns +nil+ if no token is found. - def token_and_options(request) - authorization_request = request.authorization.to_s - if authorization_request[TOKEN_REGEX] - params = token_params_from authorization_request - [params.shift[1], Hash[params].with_indifferent_access] - end - end - - def token_params_from(auth) - rewrite_param_values params_array_from raw_params auth - end - - # Takes raw_params and turns it into an array of parameters - def params_array_from(raw_params) - raw_params.map { |param| param.split %r/=(.+)?/ } - end - - # This removes the " characters wrapping the value. - def rewrite_param_values(array_params) - array_params.each { |param| (param[1] || "").gsub! %r/^"|"$/, "" } - end - - # This method takes an authorization body and splits up the key-value - # pairs by the standardized :, ;, or \t - # delimiters defined in +AUTHN_PAIR_DELIMITERS+. - def raw_params(auth) - _raw_params = auth.sub(TOKEN_REGEX, "").split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/) - - if !(_raw_params.first =~ %r{\A#{TOKEN_KEY}}) - _raw_params[0] = "#{TOKEN_KEY}#{_raw_params.first}" - end - - _raw_params - end - - # Encodes the given token and options into an Authorization header value. - # - # token - String token. - # options - optional Hash of the options. - # - # Returns String. - def encode_credentials(token, options = {}) - values = ["#{TOKEN_KEY}#{token.to_s.inspect}"] + options.map do |key, value| - "#{key}=#{value.to_s.inspect}" - end - "Token #{values * ", "}" - end - - # Sets a WWW-Authenticate header to let the client know a token is desired. - # - # controller - ActionController::Base instance for the outgoing response. - # realm - String realm to use in the header. - # - # Returns nothing. - def authentication_request(controller, realm, message = nil) - message ||= "HTTP Token: Access denied.\n" - controller.headers["WWW-Authenticate"] = %(Token realm="#{realm.tr('"'.freeze, "".freeze)}") - controller.__send__ :render, plain: message, status: :unauthorized - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/implicit_render.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/implicit_render.rb deleted file mode 100644 index eeb27f99f4..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/implicit_render.rb +++ /dev/null @@ -1,71 +0,0 @@ -module ActionController - # Handles implicit rendering for a controller action that does not - # explicitly respond with +render+, +respond_to+, +redirect+, or +head+. - # - # For API controllers, the implicit response is always 204 No Content. - # - # For all other controllers, we use these heuristics to decide whether to - # render a template, raise an error for a missing template, or respond with - # 204 No Content: - # - # First, if we DO find a template, it's rendered. Template lookup accounts - # for the action name, locales, format, variant, template handlers, and more - # (see +render+ for details). - # - # Second, if we DON'T find a template but the controller action does have - # templates for other formats, variants, etc., then we trust that you meant - # to provide a template for this response, too, and we raise - # ActionController::UnknownFormat with an explanation. - # - # Third, if we DON'T find a template AND the request is a page load in a web - # browser (technically, a non-XHR GET request for an HTML response) where - # you reasonably expect to have rendered a template, then we raise - # ActionView::UnknownFormat with an explanation. - # - # Finally, if we DON'T find a template AND the request isn't a browser page - # load, then we implicitly respond with 204 No Content. - module ImplicitRender - # :stopdoc: - include BasicImplicitRender - - def default_render(*args) - if template_exists?(action_name.to_s, _prefixes, variants: request.variant) - render(*args) - elsif any_templates?(action_name.to_s, _prefixes) - message = "#{self.class.name}\##{action_name} is missing a template " \ - "for this request format and variant.\n" \ - "\nrequest.formats: #{request.formats.map(&:to_s).inspect}" \ - "\nrequest.variant: #{request.variant.inspect}" - - raise ActionController::UnknownFormat, message - elsif interactive_browser_request? - message = "#{self.class.name}\##{action_name} is missing a template " \ - "for this request format and variant.\n\n" \ - "request.formats: #{request.formats.map(&:to_s).inspect}\n" \ - "request.variant: #{request.variant.inspect}\n\n" \ - "NOTE! For XHR/Ajax or API requests, this action would normally " \ - "respond with 204 No Content: an empty white screen. Since you're " \ - "loading it in a web browser, we assume that you expected to " \ - "actually render a template, not nothing, so we're showing an " \ - "error to be extra-clear. If you expect 204 No Content, carry on. " \ - "That's what you'll get from an XHR or API request. Give it a shot." - - raise ActionController::UnknownFormat, message - else - logger.info "No template found for #{self.class.name}\##{action_name}, rendering head :no_content" if logger - super - end - end - - def method_for_action(action_name) - super || if template_exists?(action_name.to_s, _prefixes) - "default_render" - end - end - - private - def interactive_browser_request? - request.get? && request.format == Mime[:html] && !request.xhr? - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/instrumentation.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/instrumentation.rb deleted file mode 100644 index 2485d27cec..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/instrumentation.rb +++ /dev/null @@ -1,109 +0,0 @@ -require "benchmark" -require "abstract_controller/logger" - -module ActionController - # Adds instrumentation to several ends in ActionController::Base. It also provides - # some hooks related with process_action. This allows an ORM like Active Record - # and/or DataMapper to plug in ActionController and show related information. - # - # Check ActiveRecord::Railties::ControllerRuntime for an example. - module Instrumentation - extend ActiveSupport::Concern - - include AbstractController::Logger - - attr_internal :view_runtime - - def process_action(*args) - raw_payload = { - controller: self.class.name, - action: action_name, - params: request.filtered_parameters, - headers: request.headers, - format: request.format.ref, - method: request.request_method, - path: request.fullpath - } - - ActiveSupport::Notifications.instrument("start_processing.action_controller", raw_payload.dup) - - ActiveSupport::Notifications.instrument("process_action.action_controller", raw_payload) do |payload| - begin - result = super - payload[:status] = response.status - result - ensure - append_info_to_payload(payload) - end - end - end - - def render(*args) - render_output = nil - self.view_runtime = cleanup_view_runtime do - Benchmark.ms { render_output = super } - end - render_output - end - - def send_file(path, options = {}) - ActiveSupport::Notifications.instrument("send_file.action_controller", - options.merge(path: path)) do - super - end - end - - def send_data(data, options = {}) - ActiveSupport::Notifications.instrument("send_data.action_controller", options) do - super - end - end - - def redirect_to(*args) - ActiveSupport::Notifications.instrument("redirect_to.action_controller") do |payload| - result = super - payload[:status] = response.status - payload[:location] = response.filtered_location - result - end - end - - private - - # A hook invoked every time a before callback is halted. - def halted_callback_hook(filter) - ActiveSupport::Notifications.instrument("halted_callback.action_controller", filter: filter) - end - - # A hook which allows you to clean up any time, wrongly taken into account in - # views, like database querying time. - # - # def cleanup_view_runtime - # super - time_taken_in_something_expensive - # end - # - # :api: plugin - def cleanup_view_runtime - yield - end - - # Every time after an action is processed, this method is invoked - # with the payload, so you can add more information. - # :api: plugin - def append_info_to_payload(payload) - payload[:view_runtime] = view_runtime - end - - module ClassMethods - # A hook which allows other frameworks to log what happened during - # controller process action. This method should return an array - # with the messages to be added. - # :api: plugin - def log_process_action(payload) #:nodoc: - messages, view_runtime = [], payload[:view_runtime] - messages << ("Views: %.1fms" % view_runtime.to_f) if view_runtime - messages - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/live.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/live.rb deleted file mode 100644 index a607ee2309..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/live.rb +++ /dev/null @@ -1,310 +0,0 @@ -require "action_dispatch/http/response" -require "delegate" -require "active_support/json" - -module ActionController - # Mix this module into your controller, and all actions in that controller - # will be able to stream data to the client as it's written. - # - # class MyController < ActionController::Base - # include ActionController::Live - # - # def stream - # response.headers['Content-Type'] = 'text/event-stream' - # 100.times { - # response.stream.write "hello world\n" - # sleep 1 - # } - # ensure - # response.stream.close - # end - # end - # - # There are a few caveats with this module. You *cannot* write headers after the - # response has been committed (Response#committed? will return truthy). - # Calling +write+ or +close+ on the response stream will cause the response - # object to be committed. Make sure all headers are set before calling write - # or close on your stream. - # - # You *must* call close on your stream when you're finished, otherwise the - # socket may be left open forever. - # - # The final caveat is that your actions are executed in a separate thread than - # the main thread. Make sure your actions are thread safe, and this shouldn't - # be a problem (don't share state across threads, etc). - module Live - extend ActiveSupport::Concern - - module ClassMethods - def make_response!(request) - if request.get_header("HTTP_VERSION") == "HTTP/1.0" - super - else - Live::Response.new.tap do |res| - res.request = request - end - end - end - end - - # This class provides the ability to write an SSE (Server Sent Event) - # to an IO stream. The class is initialized with a stream and can be used - # to either write a JSON string or an object which can be converted to JSON. - # - # Writing an object will convert it into standard SSE format with whatever - # options you have configured. You may choose to set the following options: - # - # 1) Event. If specified, an event with this name will be dispatched on - # the browser. - # 2) Retry. The reconnection time in milliseconds used when attempting - # to send the event. - # 3) Id. If the connection dies while sending an SSE to the browser, then - # the server will receive a +Last-Event-ID+ header with value equal to +id+. - # - # After setting an option in the constructor of the SSE object, all future - # SSEs sent across the stream will use those options unless overridden. - # - # Example Usage: - # - # class MyController < ActionController::Base - # include ActionController::Live - # - # def index - # response.headers['Content-Type'] = 'text/event-stream' - # sse = SSE.new(response.stream, retry: 300, event: "event-name") - # sse.write({ name: 'John'}) - # sse.write({ name: 'John'}, id: 10) - # sse.write({ name: 'John'}, id: 10, event: "other-event") - # sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500) - # ensure - # sse.close - # end - # end - # - # Note: SSEs are not currently supported by IE. However, they are supported - # by Chrome, Firefox, Opera, and Safari. - class SSE - WHITELISTED_OPTIONS = %w( retry event id ) - - def initialize(stream, options = {}) - @stream = stream - @options = options - end - - def close - @stream.close - end - - def write(object, options = {}) - case object - when String - perform_write(object, options) - else - perform_write(ActiveSupport::JSON.encode(object), options) - end - end - - private - - def perform_write(json, options) - current_options = @options.merge(options).stringify_keys - - WHITELISTED_OPTIONS.each do |option_name| - if (option_value = current_options[option_name]) - @stream.write "#{option_name}: #{option_value}\n" - end - end - - message = json.gsub("\n".freeze, "\ndata: ".freeze) - @stream.write "data: #{message}\n\n" - end - end - - class ClientDisconnected < RuntimeError - end - - class Buffer < ActionDispatch::Response::Buffer #:nodoc: - include MonitorMixin - - # Ignore that the client has disconnected. - # - # If this value is `true`, calling `write` after the client - # disconnects will result in the written content being silently - # discarded. If this value is `false` (the default), a - # ClientDisconnected exception will be raised. - attr_accessor :ignore_disconnect - - def initialize(response) - @error_callback = lambda { true } - @cv = new_cond - @aborted = false - @ignore_disconnect = false - super(response, SizedQueue.new(10)) - end - - def write(string) - unless @response.committed? - @response.set_header "Cache-Control", "no-cache" - @response.delete_header "Content-Length" - end - - super - - unless connected? - @buf.clear - - unless @ignore_disconnect - # Raise ClientDisconnected, which is a RuntimeError (not an - # IOError), because that's more appropriate for something beyond - # the developer's control. - raise ClientDisconnected, "client disconnected" - end - end - end - - # Write a 'close' event to the buffer; the producer/writing thread - # uses this to notify us that it's finished supplying content. - # - # See also #abort. - def close - synchronize do - super - @buf.push nil - @cv.broadcast - end - end - - # Inform the producer/writing thread that the client has - # disconnected; the reading thread is no longer interested in - # anything that's being written. - # - # See also #close. - def abort - synchronize do - @aborted = true - @buf.clear - end - end - - # Is the client still connected and waiting for content? - # - # The result of calling `write` when this is `false` is determined - # by `ignore_disconnect`. - def connected? - !@aborted - end - - def on_error(&block) - @error_callback = block - end - - def call_on_error - @error_callback.call - end - - private - - def each_chunk(&block) - loop do - str = nil - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - str = @buf.pop - end - break unless str - yield str - end - end - end - - class Response < ActionDispatch::Response #:nodoc: all - private - - def before_committed - super - jar = request.cookie_jar - # The response can be committed multiple times - jar.write self unless committed? - end - - def build_buffer(response, body) - buf = Live::Buffer.new response - body.each { |part| buf.write part } - buf - end - end - - def process(name) - t1 = Thread.current - locals = t1.keys.map { |key| [key, t1[key]] } - - error = nil - # This processes the action in a child thread. It lets us return the - # response code and headers back up the Rack stack, and still process - # the body in parallel with sending data to the client. - new_controller_thread { - ActiveSupport::Dependencies.interlock.running do - t2 = Thread.current - - # Since we're processing the view in a different thread, copy the - # thread locals from the main thread to the child thread. :'( - locals.each { |k, v| t2[k] = v } - - begin - super(name) - rescue => e - if @_response.committed? - begin - @_response.stream.write(ActionView::Base.streaming_completion_on_exception) if request.format == :html - @_response.stream.call_on_error - rescue => exception - log_error(exception) - ensure - log_error(e) - @_response.stream.close - end - else - error = e - end - ensure - @_response.commit! - end - end - } - - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - @_response.await_commit - end - - raise error if error - end - - # Spawn a new thread to serve up the controller in. This is to get - # around the fact that Rack isn't based around IOs and we need to use - # a thread to stream data from the response bodies. Nobody should call - # this method except in Rails internals. Seriously! - def new_controller_thread # :nodoc: - Thread.new { - t2 = Thread.current - t2.abort_on_exception = true - yield - } - end - - def log_error(exception) - logger = ActionController::Base.logger - return unless logger - - logger.fatal do - message = "\n#{exception.class} (#{exception.message}):\n" - message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) - message << " " << exception.backtrace.join("\n ") - "#{message}\n\n" - end - end - - def response_body=(body) - super - response.close if response - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/mime_responds.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/mime_responds.rb deleted file mode 100644 index 7b4c7b923e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/mime_responds.rb +++ /dev/null @@ -1,311 +0,0 @@ -require "abstract_controller/collector" - -module ActionController #:nodoc: - module MimeResponds - # Without web-service support, an action which collects the data for displaying a list of people - # might look something like this: - # - # def index - # @people = Person.all - # end - # - # That action implicitly responds to all formats, but formats can also be whitelisted: - # - # def index - # @people = Person.all - # respond_to :html, :js - # end - # - # Here's the same action, with web-service support baked in: - # - # def index - # @people = Person.all - # - # respond_to do |format| - # format.html - # format.js - # format.xml { render xml: @people } - # end - # end - # - # What that says is, "if the client wants HTML or JS in response to this action, just respond as we - # would have before, but if the client wants XML, return them the list of people in XML format." - # (Rails determines the desired response format from the HTTP Accept header submitted by the client.) - # - # Supposing you have an action that adds a new person, optionally creating their company - # (by name) if it does not already exist, without web-services, it might look like this: - # - # def create - # @company = Company.find_or_create_by(name: params[:company][:name]) - # @person = @company.people.create(params[:person]) - # - # redirect_to(person_list_url) - # end - # - # Here's the same action, with web-service support baked in: - # - # def create - # company = params[:person].delete(:company) - # @company = Company.find_or_create_by(name: company[:name]) - # @person = @company.people.create(params[:person]) - # - # respond_to do |format| - # format.html { redirect_to(person_list_url) } - # format.js - # format.xml { render xml: @person.to_xml(include: @company) } - # end - # end - # - # If the client wants HTML, we just redirect them back to the person list. If they want JavaScript, - # then it is an Ajax request and we render the JavaScript template associated with this action. - # Lastly, if the client wants XML, we render the created person as XML, but with a twist: we also - # include the person's company in the rendered XML, so you get something like this: - # - # - # ... - # ... - # - # ... - # ... - # ... - # - # - # - # Note, however, the extra bit at the top of that action: - # - # company = params[:person].delete(:company) - # @company = Company.find_or_create_by(name: company[:name]) - # - # This is because the incoming XML document (if a web-service request is in process) can only contain a - # single root-node. So, we have to rearrange things so that the request looks like this (url-encoded): - # - # person[name]=...&person[company][name]=...&... - # - # And, like this (xml-encoded): - # - # - # ... - # - # ... - # - # - # - # In other words, we make the request so that it operates on a single entity's person. Then, in the action, - # we extract the company data from the request, find or create the company, and then create the new person - # with the remaining data. - # - # Note that you can define your own XML parameter parser which would allow you to describe multiple entities - # in a single request (i.e., by wrapping them all in a single root node), but if you just go with the flow - # and accept Rails' defaults, life will be much easier. - # - # If you need to use a MIME type which isn't supported by default, you can register your own handlers in - # +config/initializers/mime_types.rb+ as follows. - # - # Mime::Type.register "image/jpg", :jpg - # - # Respond to also allows you to specify a common block for different formats by using +any+: - # - # def index - # @people = Person.all - # - # respond_to do |format| - # format.html - # format.any(:xml, :json) { render request.format.to_sym => @people } - # end - # end - # - # In the example above, if the format is xml, it will render: - # - # render xml: @people - # - # Or if the format is json: - # - # render json: @people - # - # Formats can have different variants. - # - # The request variant is a specialization of the request format, like :tablet, - # :phone, or :desktop. - # - # We often want to render different html/json/xml templates for phones, - # tablets, and desktop browsers. Variants make it easy. - # - # You can set the variant in a +before_action+: - # - # request.variant = :tablet if request.user_agent =~ /iPad/ - # - # Respond to variants in the action just like you respond to formats: - # - # respond_to do |format| - # format.html do |variant| - # variant.tablet # renders app/views/projects/show.html+tablet.erb - # variant.phone { extra_setup; render ... } - # variant.none { special_setup } # executed only if there is no variant set - # end - # end - # - # Provide separate templates for each format and variant: - # - # app/views/projects/show.html.erb - # app/views/projects/show.html+tablet.erb - # app/views/projects/show.html+phone.erb - # - # When you're not sharing any code within the format, you can simplify defining variants - # using the inline syntax: - # - # respond_to do |format| - # format.js { render "trash" } - # format.html.phone { redirect_to progress_path } - # format.html.none { render "trash" } - # end - # - # Variants also support common +any+/+all+ block that formats have. - # - # It works for both inline: - # - # respond_to do |format| - # format.html.any { render html: "any" } - # format.html.phone { render html: "phone" } - # end - # - # and block syntax: - # - # respond_to do |format| - # format.html do |variant| - # variant.any(:tablet, :phablet){ render html: "any" } - # variant.phone { render html: "phone" } - # end - # end - # - # You can also set an array of variants: - # - # request.variant = [:tablet, :phone] - # - # This will work similarly to formats and MIME types negotiation. If there - # is no +:tablet+ variant declared, +:phone+ variant will be picked: - # - # respond_to do |format| - # format.html.none - # format.html.phone # this gets rendered - # end - def respond_to(*mimes) - raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given? - - collector = Collector.new(mimes, request.variant) - yield collector if block_given? - - if format = collector.negotiate_format(request) - _process_format(format) - _set_rendered_content_type format - response = collector.response - response.call if response - else - raise ActionController::UnknownFormat - end - end - - # A container for responses available from the current controller for - # requests for different mime-types sent to a particular action. - # - # The public controller methods +respond_to+ may be called with a block - # that is used to define responses to different mime-types, e.g. - # for +respond_to+ : - # - # respond_to do |format| - # format.html - # format.xml { render xml: @people } - # end - # - # In this usage, the argument passed to the block (+format+ above) is an - # instance of the ActionController::MimeResponds::Collector class. This - # object serves as a container in which available responses can be stored by - # calling any of the dynamically generated, mime-type-specific methods such - # as +html+, +xml+ etc on the Collector. Each response is represented by a - # corresponding block if present. - # - # A subsequent call to #negotiate_format(request) will enable the Collector - # to determine which specific mime-type it should respond with for the current - # request, with this response then being accessible by calling #response. - class Collector - include AbstractController::Collector - attr_accessor :format - - def initialize(mimes, variant = nil) - @responses = {} - @variant = variant - - mimes.each { |mime| @responses[Mime[mime]] = nil } - end - - def any(*args, &block) - if args.any? - args.each { |type| send(type, &block) } - else - custom(Mime::ALL, &block) - end - end - alias :all :any - - def custom(mime_type, &block) - mime_type = Mime::Type.lookup(mime_type.to_s) unless mime_type.is_a?(Mime::Type) - @responses[mime_type] ||= if block_given? - block - else - VariantCollector.new(@variant) - end - end - - def response - response = @responses.fetch(format, @responses[Mime::ALL]) - if response.is_a?(VariantCollector) # `format.html.phone` - variant inline syntax - response.variant - elsif response.nil? || response.arity == 0 # `format.html` - just a format, call its block - response - else # `format.html{ |variant| variant.phone }` - variant block syntax - variant_collector = VariantCollector.new(@variant) - response.call(variant_collector) # call format block with variants collector - variant_collector.variant - end - end - - def negotiate_format(request) - @format = request.negotiate_mime(@responses.keys) - end - - class VariantCollector #:nodoc: - def initialize(variant = nil) - @variant = variant - @variants = {} - end - - def any(*args, &block) - if block_given? - if args.any? && args.none? { |a| a == @variant } - args.each { |v| @variants[v] = block } - else - @variants[:any] = block - end - end - end - alias :all :any - - def method_missing(name, *args, &block) - @variants[name] = block if block_given? - end - - def variant - if @variant.empty? - @variants[:none] || @variants[:any] - else - @variants[variant_key] - end - end - - private - def variant_key - @variant.find { |variant| @variants.key?(variant) } || :any - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/parameter_encoding.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/parameter_encoding.rb deleted file mode 100644 index ecc691619e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/parameter_encoding.rb +++ /dev/null @@ -1,49 +0,0 @@ -module ActionController - # Specify binary encoding for parameters for a given action. - module ParameterEncoding - extend ActiveSupport::Concern - - module ClassMethods - def inherited(klass) # :nodoc: - super - klass.setup_param_encode - end - - def setup_param_encode # :nodoc: - @_parameter_encodings = {} - end - - def binary_params_for?(action) # :nodoc: - @_parameter_encodings[action.to_s] - end - - # Specify that a given action's parameters should all be encoded as - # ASCII-8BIT (it "skips" the encoding default of UTF-8). - # - # For example, a controller would use it like this: - # - # class RepositoryController < ActionController::Base - # skip_parameter_encoding :show - # - # def show - # @repo = Repository.find_by_filesystem_path params[:file_path] - # - # # `repo_name` is guaranteed to be UTF-8, but was ASCII-8BIT, so - # # tag it as such - # @repo_name = params[:repo_name].force_encoding 'UTF-8' - # end - # - # def index - # @repositories = Repository.all - # end - # end - # - # The show action in the above controller would have all parameter values - # encoded as ASCII-8BIT. This is useful in the case where an application - # must handle data but encoding of the data is unknown, like file system data. - def skip_parameter_encoding(action) - @_parameter_encodings[action.to_s] = true - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/params_wrapper.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/params_wrapper.rb deleted file mode 100644 index e8c69c98a9..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/params_wrapper.rb +++ /dev/null @@ -1,289 +0,0 @@ -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/hash/except" -require "active_support/core_ext/module/anonymous" -require "action_dispatch/http/mime_type" - -module ActionController - # Wraps the parameters hash into a nested hash. This will allow clients to - # submit requests without having to specify any root elements. - # - # This functionality is enabled in +config/initializers/wrap_parameters.rb+ - # and can be customized. - # - # You could also turn it on per controller by setting the format array to - # a non-empty array: - # - # class UsersController < ApplicationController - # wrap_parameters format: [:json, :xml, :url_encoded_form, :multipart_form] - # end - # - # If you enable +ParamsWrapper+ for +:json+ format, instead of having to - # send JSON parameters like this: - # - # {"user": {"name": "Konata"}} - # - # You can send parameters like this: - # - # {"name": "Konata"} - # - # And it will be wrapped into a nested hash with the key name matching the - # controller's name. For example, if you're posting to +UsersController+, - # your new +params+ hash will look like this: - # - # {"name" => "Konata", "user" => {"name" => "Konata"}} - # - # You can also specify the key in which the parameters should be wrapped to, - # and also the list of attributes it should wrap by using either +:include+ or - # +:exclude+ options like this: - # - # class UsersController < ApplicationController - # wrap_parameters :person, include: [:username, :password] - # end - # - # On Active Record models with no +:include+ or +:exclude+ option set, - # it will only wrap the parameters returned by the class method - # attribute_names. - # - # If you're going to pass the parameters to an +ActiveModel+ object (such as - # User.new(params[:user])), you might consider passing the model class to - # the method instead. The +ParamsWrapper+ will actually try to determine the - # list of attribute names from the model and only wrap those attributes: - # - # class UsersController < ApplicationController - # wrap_parameters Person - # end - # - # You still could pass +:include+ and +:exclude+ to set the list of attributes - # you want to wrap. - # - # By default, if you don't specify the key in which the parameters would be - # wrapped to, +ParamsWrapper+ will actually try to determine if there's - # a model related to it or not. This controller, for example: - # - # class Admin::UsersController < ApplicationController - # end - # - # will try to check if Admin::User or +User+ model exists, and use it to - # determine the wrapper key respectively. If both models don't exist, - # it will then fallback to use +user+ as the key. - module ParamsWrapper - extend ActiveSupport::Concern - - EXCLUDE_PARAMETERS = %w(authenticity_token _method utf8) - - require "mutex_m" - - class Options < Struct.new(:name, :format, :include, :exclude, :klass, :model) # :nodoc: - include Mutex_m - - def self.from_hash(hash) - name = hash[:name] - format = Array(hash[:format]) - include = hash[:include] && Array(hash[:include]).collect(&:to_s) - exclude = hash[:exclude] && Array(hash[:exclude]).collect(&:to_s) - new name, format, include, exclude, nil, nil - end - - def initialize(name, format, include, exclude, klass, model) # :nodoc: - super - @include_set = include - @name_set = name - end - - def model - super || synchronize { super || self.model = _default_wrap_model } - end - - def include - return super if @include_set - - m = model - synchronize do - return super if @include_set - - @include_set = true - - unless super || exclude - if m.respond_to?(:attribute_names) && m.attribute_names.any? - if m.respond_to?(:stored_attributes) && !m.stored_attributes.empty? - self.include = m.attribute_names + m.stored_attributes.values.flatten.map(&:to_s) - else - self.include = m.attribute_names - end - end - end - end - end - - def name - return super if @name_set - - m = model - synchronize do - return super if @name_set - - @name_set = true - - unless super || klass.anonymous? - self.name = m ? m.to_s.demodulize.underscore : - klass.controller_name.singularize - end - end - end - - private - # Determine the wrapper model from the controller's name. By convention, - # this could be done by trying to find the defined model that has the - # same singular name as the controller. For example, +UsersController+ - # will try to find if the +User+ model exists. - # - # This method also does namespace lookup. Foo::Bar::UsersController will - # try to find Foo::Bar::User, Foo::User and finally User. - def _default_wrap_model - return nil if klass.anonymous? - model_name = klass.name.sub(/Controller$/, "").classify - - begin - if model_klass = model_name.safe_constantize - model_klass - else - namespaces = model_name.split("::") - namespaces.delete_at(-2) - break if namespaces.last == model_name - model_name = namespaces.join("::") - end - end until model_klass - - model_klass - end - end - - included do - class_attribute :_wrapper_options - self._wrapper_options = Options.from_hash(format: []) - end - - module ClassMethods - def _set_wrapper_options(options) - self._wrapper_options = Options.from_hash(options) - end - - # Sets the name of the wrapper key, or the model which +ParamsWrapper+ - # would use to determine the attribute names from. - # - # ==== Examples - # wrap_parameters format: :xml - # # enables the parameter wrapper for XML format - # - # wrap_parameters :person - # # wraps parameters into +params[:person]+ hash - # - # wrap_parameters Person - # # wraps parameters by determining the wrapper key from Person class - # (+person+, in this case) and the list of attribute names - # - # wrap_parameters include: [:username, :title] - # # wraps only +:username+ and +:title+ attributes from parameters. - # - # wrap_parameters false - # # disables parameters wrapping for this controller altogether. - # - # ==== Options - # * :format - The list of formats in which the parameters wrapper - # will be enabled. - # * :include - The list of attribute names which parameters wrapper - # will wrap into a nested hash. - # * :exclude - The list of attribute names which parameters wrapper - # will exclude from a nested hash. - def wrap_parameters(name_or_model_or_options, options = {}) - model = nil - - case name_or_model_or_options - when Hash - options = name_or_model_or_options - when false - options = options.merge(format: []) - when Symbol, String - options = options.merge(name: name_or_model_or_options) - else - model = name_or_model_or_options - end - - opts = Options.from_hash _wrapper_options.to_h.slice(:format).merge(options) - opts.model = model - opts.klass = self - - self._wrapper_options = opts - end - - # Sets the default wrapper key or model which will be used to determine - # wrapper key and attribute names. Called automatically when the - # module is inherited. - def inherited(klass) - if klass._wrapper_options.format.any? - params = klass._wrapper_options.dup - params.klass = klass - klass._wrapper_options = params - end - super - end - end - - # Performs parameters wrapping upon the request. Called automatically - # by the metal call stack. - def process_action(*args) - if _wrapper_enabled? - if request.parameters[_wrapper_key].present? - wrapped_hash = _extract_parameters(request.parameters) - else - wrapped_hash = _wrap_parameters request.request_parameters - end - - wrapped_keys = request.request_parameters.keys - wrapped_filtered_hash = _wrap_parameters request.filtered_parameters.slice(*wrapped_keys) - - # This will make the wrapped hash accessible from controller and view. - request.parameters.merge! wrapped_hash - request.request_parameters.merge! wrapped_hash - - # This will display the wrapped hash in the log file. - request.filtered_parameters.merge! wrapped_filtered_hash - end - super - end - - private - - # Returns the wrapper key which will be used to store wrapped parameters. - def _wrapper_key - _wrapper_options.name - end - - # Returns the list of enabled formats. - def _wrapper_formats - _wrapper_options.format - end - - # Returns the list of parameters which will be selected for wrapped. - def _wrap_parameters(parameters) - { _wrapper_key => _extract_parameters(parameters) } - end - - def _extract_parameters(parameters) - if include_only = _wrapper_options.include - parameters.slice(*include_only) - else - exclude = _wrapper_options.exclude || [] - parameters.except(*(exclude + EXCLUDE_PARAMETERS)) - end - end - - # Checks if we should perform parameters wrapping. - def _wrapper_enabled? - return false unless request.has_content_type? - - ref = request.content_mime_type.ref - _wrapper_formats.include?(ref) && _wrapper_key && !request.request_parameters.key?(_wrapper_key) - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/redirecting.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/redirecting.rb deleted file mode 100644 index fdfe82f96b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/redirecting.rb +++ /dev/null @@ -1,122 +0,0 @@ -module ActionController - module Redirecting - extend ActiveSupport::Concern - - include AbstractController::Logger - include ActionController::UrlFor - - # Redirects the browser to the target specified in +options+. This parameter can be any one of: - # - # * Hash - The URL will be generated by calling url_for with the +options+. - # * Record - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record. - # * String starting with protocol:// (like http://) or a protocol relative reference (like //) - Is passed straight through as the target for redirection. - # * String not containing a protocol - The current protocol and host is prepended to the string. - # * Proc - A block that will be executed in the controller's context. Should return any option accepted by +redirect_to+. - # - # === Examples: - # - # redirect_to action: "show", id: 5 - # redirect_to @post - # redirect_to "http://www.rubyonrails.org" - # redirect_to "/images/screenshot.jpg" - # redirect_to posts_url - # redirect_to proc { edit_post_url(@post) } - # - # The redirection happens as a 302 Found header unless otherwise specified using the :status option: - # - # redirect_to post_url(@post), status: :found - # redirect_to action: 'atom', status: :moved_permanently - # redirect_to post_url(@post), status: 301 - # redirect_to action: 'atom', status: 302 - # - # The status code can either be a standard {HTTP Status code}[http://www.iana.org/assignments/http-status-codes] as an - # integer, or a symbol representing the downcased, underscored and symbolized description. - # Note that the status code must be a 3xx HTTP code, or redirection will not occur. - # - # If you are using XHR requests other than GET or POST and redirecting after the - # request then some browsers will follow the redirect using the original request - # method. This may lead to undesirable behavior such as a double DELETE. To work - # around this you can return a 303 See Other status code which will be - # followed using a GET request. - # - # redirect_to posts_url, status: :see_other - # redirect_to action: 'index', status: 303 - # - # It is also possible to assign a flash message as part of the redirection. There are two special accessors for the commonly used flash names - # +alert+ and +notice+ as well as a general purpose +flash+ bucket. - # - # redirect_to post_url(@post), alert: "Watch it, mister!" - # redirect_to post_url(@post), status: :found, notice: "Pay attention to the road" - # redirect_to post_url(@post), status: 301, flash: { updated_post_id: @post.id } - # redirect_to({ action: 'atom' }, alert: "Something serious happened") - # - # Statements after +redirect_to+ in our controller get executed, so +redirect_to+ doesn't stop the execution of the function. - # To terminate the execution of the function immediately after the +redirect_to+, use return. - # redirect_to post_url(@post) and return - def redirect_to(options = {}, response_status = {}) - raise ActionControllerError.new("Cannot redirect to nil!") unless options - raise AbstractController::DoubleRenderError if response_body - - self.status = _extract_redirect_to_status(options, response_status) - self.location = _compute_redirect_to_location(request, options) - self.response_body = "You are being redirected." - end - - # Redirects the browser to the page that issued the request (the referrer) - # if possible, otherwise redirects to the provided default fallback - # location. - # - # The referrer information is pulled from the HTTP `Referer` (sic) header on - # the request. This is an optional header and its presence on the request is - # subject to browser security settings and user preferences. If the request - # is missing this header, the fallback_location will be used. - # - # redirect_back fallback_location: { action: "show", id: 5 } - # redirect_back fallback_location: @post - # redirect_back fallback_location: "http://www.rubyonrails.org" - # redirect_back fallback_location: "/images/screenshot.jpg" - # redirect_back fallback_location: posts_url - # redirect_back fallback_location: proc { edit_post_url(@post) } - # - # All options that can be passed to redirect_to are accepted as - # options and the behavior is identical. - def redirect_back(fallback_location:, **args) - if referer = request.headers["Referer"] - redirect_to referer, **args - else - redirect_to fallback_location, **args - end - end - - def _compute_redirect_to_location(request, options) #:nodoc: - case options - # The scheme name consist of a letter followed by any combination of - # letters, digits, and the plus ("+"), period ("."), or hyphen ("-") - # characters; and is terminated by a colon (":"). - # See http://tools.ietf.org/html/rfc3986#section-3.1 - # The protocol relative scheme starts with a double slash "//". - when /\A([a-z][a-z\d\-+\.]*:|\/\/).*/i - options - when String - request.protocol + request.host_with_port + options - when Proc - _compute_redirect_to_location request, options.call - else - url_for(options) - end.delete("\0\r\n") - end - module_function :_compute_redirect_to_location - public :_compute_redirect_to_location - - private - def _extract_redirect_to_status(options, response_status) - if options.is_a?(Hash) && options.key?(:status) - Rack::Utils.status_code(options.delete(:status)) - elsif response_status.key?(:status) - Rack::Utils.status_code(response_status[:status]) - else - 302 - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/renderers.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/renderers.rb deleted file mode 100644 index 733aca195d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/renderers.rb +++ /dev/null @@ -1,180 +0,0 @@ -require "set" - -module ActionController - # See Renderers.add - def self.add_renderer(key, &block) - Renderers.add(key, &block) - end - - # See Renderers.remove - def self.remove_renderer(key) - Renderers.remove(key) - end - - # See Responder#api_behavior - class MissingRenderer < LoadError - def initialize(format) - super "No renderer defined for format: #{format}" - end - end - - module Renderers - extend ActiveSupport::Concern - - # A Set containing renderer names that correspond to available renderer procs. - # Default values are :json, :js, :xml. - RENDERERS = Set.new - - included do - class_attribute :_renderers - self._renderers = Set.new.freeze - end - - # Used in ActionController::Base - # and ActionController::API to include all - # renderers by default. - module All - extend ActiveSupport::Concern - include Renderers - - included do - self._renderers = RENDERERS - end - end - - # Adds a new renderer to call within controller actions. - # A renderer is invoked by passing its name as an option to - # AbstractController::Rendering#render. To create a renderer - # pass it a name and a block. The block takes two arguments, the first - # is the value paired with its key and the second is the remaining - # hash of options passed to +render+. - # - # Create a csv renderer: - # - # ActionController::Renderers.add :csv do |obj, options| - # filename = options[:filename] || 'data' - # str = obj.respond_to?(:to_csv) ? obj.to_csv : obj.to_s - # send_data str, type: Mime[:csv], - # disposition: "attachment; filename=#{filename}.csv" - # end - # - # Note that we used Mime[:csv] for the csv mime type as it comes with Rails. - # For a custom renderer, you'll need to register a mime type with - # Mime::Type.register. - # - # To use the csv renderer in a controller action: - # - # def show - # @csvable = Csvable.find(params[:id]) - # respond_to do |format| - # format.html - # format.csv { render csv: @csvable, filename: @csvable.name } - # end - # end - def self.add(key, &block) - define_method(_render_with_renderer_method_name(key), &block) - RENDERERS << key.to_sym - end - - # This method is the opposite of add method. - # - # To remove a csv renderer: - # - # ActionController::Renderers.remove(:csv) - def self.remove(key) - RENDERERS.delete(key.to_sym) - method_name = _render_with_renderer_method_name(key) - remove_method(method_name) if method_defined?(method_name) - end - - def self._render_with_renderer_method_name(key) - "_render_with_renderer_#{key}" - end - - module ClassMethods - # Adds, by name, a renderer or renderers to the +_renderers+ available - # to call within controller actions. - # - # It is useful when rendering from an ActionController::Metal controller or - # otherwise to add an available renderer proc to a specific controller. - # - # Both ActionController::Base and ActionController::API - # include ActionController::Renderers::All, making all renderers - # available in the controller. See Renderers::RENDERERS and Renderers.add. - # - # Since ActionController::Metal controllers cannot render, the controller - # must include AbstractController::Rendering, ActionController::Rendering, - # and ActionController::Renderers, and have at least one renderer. - # - # Rather than including ActionController::Renderers::All and including all renderers, - # you may specify which renderers to include by passing the renderer name or names to - # +use_renderers+. For example, a controller that includes only the :json renderer - # (+_render_with_renderer_json+) might look like: - # - # class MetalRenderingController < ActionController::Metal - # include AbstractController::Rendering - # include ActionController::Rendering - # include ActionController::Renderers - # - # use_renderers :json - # - # def show - # render json: record - # end - # end - # - # You must specify a +use_renderer+, else the +controller.renderer+ and - # +controller._renderers+ will be nil, and the action will fail. - def use_renderers(*args) - renderers = _renderers + args - self._renderers = renderers.freeze - end - alias use_renderer use_renderers - end - - # Called by +render+ in AbstractController::Rendering - # which sets the return value as the +response_body+. - # - # If no renderer is found, +super+ returns control to - # ActionView::Rendering.render_to_body, if present. - def render_to_body(options) - _render_to_body_with_renderer(options) || super - end - - def _render_to_body_with_renderer(options) - _renderers.each do |name| - if options.key?(name) - _process_options(options) - method_name = Renderers._render_with_renderer_method_name(name) - return send(method_name, options.delete(name), options) - end - end - nil - end - - add :json do |json, options| - json = json.to_json(options) unless json.kind_of?(String) - - if options[:callback].present? - if content_type.nil? || content_type == Mime[:json] - self.content_type = Mime[:js] - end - - "/**/#{options[:callback]}(#{json})" - else - self.content_type ||= Mime[:json] - json - end - end - - add :js do |js, options| - self.content_type ||= Mime[:js] - js.respond_to?(:to_js) ? js.to_js(options) : js - end - - add :xml do |xml, options| - self.content_type ||= Mime[:xml] - xml.respond_to?(:to_xml) ? xml.to_xml(options) : xml - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/rendering.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/rendering.rb deleted file mode 100644 index 67f207afc2..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/rendering.rb +++ /dev/null @@ -1,122 +0,0 @@ -require "active_support/core_ext/string/filters" - -module ActionController - module Rendering - extend ActiveSupport::Concern - - RENDER_FORMATS_IN_PRIORITY = [:body, :plain, :html] - - module ClassMethods - # Documentation at ActionController::Renderer#render - delegate :render, to: :renderer - - # Returns a renderer instance (inherited from ActionController::Renderer) - # for the controller. - attr_reader :renderer - - def setup_renderer! # :nodoc: - @renderer = Renderer.for(self) - end - - def inherited(klass) - klass.setup_renderer! - super - end - end - - # Before processing, set the request formats in current controller formats. - def process_action(*) #:nodoc: - self.formats = request.formats.map(&:ref).compact - super - end - - # Check for double render errors and set the content_type after rendering. - def render(*args) #:nodoc: - raise ::AbstractController::DoubleRenderError if response_body - super - end - - # Overwrite render_to_string because body can now be set to a Rack body. - def render_to_string(*) - result = super - if result.respond_to?(:each) - string = "" - result.each { |r| string << r } - string - else - result - end - end - - def render_to_body(options = {}) - super || _render_in_priorities(options) || " " - end - - private - - def _process_variant(options) - if defined?(request) && !request.nil? && request.variant.present? - options[:variant] = request.variant - end - end - - def _render_in_priorities(options) - RENDER_FORMATS_IN_PRIORITY.each do |format| - return options[format] if options.key?(format) - end - - nil - end - - def _set_html_content_type - self.content_type = Mime[:html].to_s - end - - def _set_rendered_content_type(format) - if format && !response.content_type - self.content_type = format.to_s - end - end - - # Normalize arguments by catching blocks and setting them on :update. - def _normalize_args(action = nil, options = {}, &blk) - options = super - options[:update] = blk if block_given? - options - end - - # Normalize both text and status options. - def _normalize_options(options) - _normalize_text(options) - - if options[:html] - options[:html] = ERB::Util.html_escape(options[:html]) - end - - if options[:status] - options[:status] = Rack::Utils.status_code(options[:status]) - end - - super - end - - def _normalize_text(options) - RENDER_FORMATS_IN_PRIORITY.each do |format| - if options.key?(format) && options[format].respond_to?(:to_text) - options[format] = options[format].to_text - end - end - end - - # Process controller specific options, as status, content-type and location. - def _process_options(options) - status, content_type, location = options.values_at(:status, :content_type, :location) - - self.status = status if status - self.content_type = content_type if content_type - headers["Location"] = url_for(location) if location - - super - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/request_forgery_protection.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/request_forgery_protection.rb deleted file mode 100644 index 5051c02a62..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/request_forgery_protection.rb +++ /dev/null @@ -1,418 +0,0 @@ -require "rack/session/abstract/id" -require "action_controller/metal/exceptions" -require "active_support/security_utils" - -module ActionController #:nodoc: - class InvalidAuthenticityToken < ActionControllerError #:nodoc: - end - - class InvalidCrossOriginRequest < ActionControllerError #:nodoc: - end - - # Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks - # by including a token in the rendered HTML for your application. This token is - # stored as a random string in the session, to which an attacker does not have - # access. When a request reaches your application, \Rails verifies the received - # token with the token in the session. All requests are checked except GET requests - # as these should be idempotent. Keep in mind that all session-oriented requests - # should be CSRF protected, including JavaScript and HTML requests. - # - # Since HTML and JavaScript requests are typically made from the browser, we - # need to ensure to verify request authenticity for the web browser. We can - # use session-oriented authentication for these types of requests, by using - # the `protect_from_forgery` method in our controllers. - # - # GET requests are not protected since they don't have side effects like writing - # to the database and don't leak sensitive information. JavaScript requests are - # an exception: a third-party site can use a - # - # The first two characters (">) are required in case the exception happens - # while rendering attributes for a given tag. You can check the real cause - # for the exception in your logger. - # - # == Web server support - # - # Not all web servers support streaming out-of-the-box. You need to check - # the instructions for each of them. - # - # ==== Unicorn - # - # Unicorn supports streaming but it needs to be configured. For this, you - # need to create a config file as follow: - # - # # unicorn.config.rb - # listen 3000, tcp_nopush: false - # - # And use it on initialization: - # - # unicorn_rails --config-file unicorn.config.rb - # - # You may also want to configure other parameters like :tcp_nodelay. - # Please check its documentation for more information: http://unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen - # - # If you are using Unicorn with NGINX, you may need to tweak NGINX. - # Streaming should work out of the box on Rainbows. - # - # ==== Passenger - # - # To be described. - # - module Streaming - extend ActiveSupport::Concern - - private - - # Set proper cache control and transfer encoding when streaming - def _process_options(options) - super - if options[:stream] - if request.version == "HTTP/1.0" - options.delete(:stream) - else - headers["Cache-Control"] ||= "no-cache" - headers["Transfer-Encoding"] = "chunked" - headers.delete("Content-Length") - end - end - end - - # Call render_body if we are streaming instead of usual +render+. - def _render_template(options) - if options.delete(:stream) - Rack::Chunked::Body.new view_renderer.render_body(view_context, options) - else - super - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/strong_parameters.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/strong_parameters.rb deleted file mode 100644 index 58d0669066..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/strong_parameters.rb +++ /dev/null @@ -1,1077 +0,0 @@ -require "active_support/core_ext/hash/indifferent_access" -require "active_support/core_ext/hash/transform_values" -require "active_support/core_ext/array/wrap" -require "active_support/core_ext/string/filters" -require "active_support/core_ext/object/to_query" -require "active_support/rescuable" -require "action_dispatch/http/upload" -require "rack/test" -require "stringio" -require "set" -require "yaml" - -module ActionController - # Raised when a required parameter is missing. - # - # params = ActionController::Parameters.new(a: {}) - # params.fetch(:b) - # # => ActionController::ParameterMissing: param is missing or the value is empty: b - # params.require(:a) - # # => ActionController::ParameterMissing: param is missing or the value is empty: a - class ParameterMissing < KeyError - attr_reader :param # :nodoc: - - def initialize(param) # :nodoc: - @param = param - super("param is missing or the value is empty: #{param}") - end - end - - # Raised when a supplied parameter is not expected and - # ActionController::Parameters.action_on_unpermitted_parameters - # is set to :raise. - # - # params = ActionController::Parameters.new(a: "123", b: "456") - # params.permit(:c) - # # => ActionController::UnpermittedParameters: found unpermitted parameters: :a, :b - class UnpermittedParameters < IndexError - attr_reader :params # :nodoc: - - def initialize(params) # :nodoc: - @params = params - super("found unpermitted parameter#{'s' if params.size > 1 }: #{params.map { |e| ":#{e}" }.join(", ")}") - end - end - - # Raised when a Parameters instance is not marked as permitted and - # an operation to transform it to hash is called. - # - # params = ActionController::Parameters.new(a: "123", b: "456") - # params.to_h - # # => ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash - class UnfilteredParameters < ArgumentError - def initialize # :nodoc: - super("unable to convert unpermitted parameters to hash") - end - end - - # == Action Controller \Parameters - # - # Allows you to choose which attributes should be whitelisted for mass updating - # and thus prevent accidentally exposing that which shouldn't be exposed. - # Provides two methods for this purpose: #require and #permit. The former is - # used to mark parameters as required. The latter is used to set the parameter - # as permitted and limit which attributes should be allowed for mass updating. - # - # params = ActionController::Parameters.new({ - # person: { - # name: "Francesco", - # age: 22, - # role: "admin" - # } - # }) - # - # permitted = params.require(:person).permit(:name, :age) - # permitted # => "Francesco", "age"=>22} permitted: true> - # permitted.permitted? # => true - # - # Person.first.update!(permitted) - # # => # - # - # It provides two options that controls the top-level behavior of new instances: - # - # * +permit_all_parameters+ - If it's +true+, all the parameters will be - # permitted by default. The default is +false+. - # * +action_on_unpermitted_parameters+ - Allow to control the behavior when parameters - # that are not explicitly permitted are found. The values can be +false+ to just filter them - # out, :log to additionally write a message on the logger, or :raise to raise - # ActionController::UnpermittedParameters exception. The default value is :log - # in test and development environments, +false+ otherwise. - # - # Examples: - # - # params = ActionController::Parameters.new - # params.permitted? # => false - # - # ActionController::Parameters.permit_all_parameters = true - # - # params = ActionController::Parameters.new - # params.permitted? # => true - # - # params = ActionController::Parameters.new(a: "123", b: "456") - # params.permit(:c) - # # => - # - # ActionController::Parameters.action_on_unpermitted_parameters = :raise - # - # params = ActionController::Parameters.new(a: "123", b: "456") - # params.permit(:c) - # # => ActionController::UnpermittedParameters: found unpermitted keys: a, b - # - # Please note that these options *are not thread-safe*. In a multi-threaded - # environment they should only be set once at boot-time and never mutated at - # runtime. - # - # You can fetch values of ActionController::Parameters using either - # :key or "key". - # - # params = ActionController::Parameters.new(key: "value") - # params[:key] # => "value" - # params["key"] # => "value" - class Parameters - cattr_accessor :permit_all_parameters, instance_accessor: false - self.permit_all_parameters = false - - cattr_accessor :action_on_unpermitted_parameters, instance_accessor: false - - ## - # :method: as_json - # - # :call-seq: - # as_json(options=nil) - # - # Returns a hash that can be used as the JSON representation for the parameters. - - ## - # :method: empty? - # - # :call-seq: - # empty?() - # - # Returns true if the parameters have no key/value pairs. - - ## - # :method: has_key? - # - # :call-seq: - # has_key?(key) - # - # Returns true if the given key is present in the parameters. - - ## - # :method: has_value? - # - # :call-seq: - # has_value?(value) - # - # Returns true if the given value is present for some key in the parameters. - - ## - # :method: include? - # - # :call-seq: - # include?(key) - # - # Returns true if the given key is present in the parameters. - - ## - # :method: key? - # - # :call-seq: - # key?(key) - # - # Returns true if the given key is present in the parameters. - - ## - # :method: keys - # - # :call-seq: - # keys() - # - # Returns a new array of the keys of the parameters. - - ## - # :method: to_s - # - # :call-seq: - # to_s() - # Returns the content of the parameters as a string. - - ## - # :method: value? - # - # :call-seq: - # value?(value) - # - # Returns true if the given value is present for some key in the parameters. - - ## - # :method: values - # - # :call-seq: - # values() - # - # Returns a new array of the values of the parameters. - delegate :keys, :key?, :has_key?, :values, :has_value?, :value?, :empty?, :include?, - :as_json, :to_s, to: :@parameters - - # By default, never raise an UnpermittedParameters exception if these - # params are present. The default includes both 'controller' and 'action' - # because they are added by Rails and should be of no concern. One way - # to change these is to specify `always_permitted_parameters` in your - # config. For instance: - # - # config.always_permitted_parameters = %w( controller action format ) - cattr_accessor :always_permitted_parameters - self.always_permitted_parameters = %w( controller action ) - - # Returns a new instance of ActionController::Parameters. - # Also, sets the +permitted+ attribute to the default value of - # ActionController::Parameters.permit_all_parameters. - # - # class Person < ActiveRecord::Base - # end - # - # params = ActionController::Parameters.new(name: "Francesco") - # params.permitted? # => false - # Person.new(params) # => ActiveModel::ForbiddenAttributesError - # - # ActionController::Parameters.permit_all_parameters = true - # - # params = ActionController::Parameters.new(name: "Francesco") - # params.permitted? # => true - # Person.new(params) # => # - def initialize(parameters = {}) - @parameters = parameters.with_indifferent_access - @permitted = self.class.permit_all_parameters - end - - # Returns true if another +Parameters+ object contains the same content and - # permitted flag. - def ==(other) - if other.respond_to?(:permitted?) - permitted? == other.permitted? && parameters == other.parameters - else - @parameters == other - end - end - - # Returns a safe ActiveSupport::HashWithIndifferentAccess - # representation of the parameters with all unpermitted keys removed. - # - # params = ActionController::Parameters.new({ - # name: "Senjougahara Hitagi", - # oddity: "Heavy stone crab" - # }) - # params.to_h - # # => ActionController::UnfilteredParameters: unable to convert unfiltered parameters to hash - # - # safe_params = params.permit(:name) - # safe_params.to_h # => {"name"=>"Senjougahara Hitagi"} - def to_h - if permitted? - convert_parameters_to_hashes(@parameters, :to_h) - else - raise UnfilteredParameters - end - end - - # Returns a safe Hash representation of the parameters - # with all unpermitted keys removed. - # - # params = ActionController::Parameters.new({ - # name: "Senjougahara Hitagi", - # oddity: "Heavy stone crab" - # }) - # params.to_hash - # # => ActionController::UnfilteredParameters: unable to convert unfiltered parameters to hash - # - # safe_params = params.permit(:name) - # safe_params.to_hash # => {"name"=>"Senjougahara Hitagi"} - def to_hash - to_h.to_hash - end - - # Returns a string representation of the receiver suitable for use as a URL - # query string: - # - # params = ActionController::Parameters.new({ - # name: "David", - # nationality: "Danish" - # }) - # params.to_query - # # => "name=David&nationality=Danish" - # - # An optional namespace can be passed to enclose key names: - # - # params = ActionController::Parameters.new({ - # name: "David", - # nationality: "Danish" - # }) - # params.to_query("user") - # # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" - # - # The string pairs "key=value" that conform the query string - # are sorted lexicographically in ascending order. - # - # This method is also aliased as +to_param+. - def to_query(*args) - to_h.to_query(*args) - end - alias_method :to_param, :to_query - - # Returns an unsafe, unfiltered - # ActiveSupport::HashWithIndifferentAccess representation of the - # parameters. - # - # params = ActionController::Parameters.new({ - # name: "Senjougahara Hitagi", - # oddity: "Heavy stone crab" - # }) - # params.to_unsafe_h - # # => {"name"=>"Senjougahara Hitagi", "oddity" => "Heavy stone crab"} - def to_unsafe_h - convert_parameters_to_hashes(@parameters, :to_unsafe_h) - end - alias_method :to_unsafe_hash, :to_unsafe_h - - # Convert all hashes in values into parameters, then yield each pair in - # the same way as Hash#each_pair. - def each_pair(&block) - @parameters.each_pair do |key, value| - yield key, convert_hashes_to_parameters(key, value) - end - end - alias_method :each, :each_pair - - # Attribute that keeps track of converted arrays, if any, to avoid double - # looping in the common use case permit + mass-assignment. Defined in a - # method to instantiate it only if needed. - # - # Testing membership still loops, but it's going to be faster than our own - # loop that converts values. Also, we are not going to build a new array - # object per fetch. - def converted_arrays - @converted_arrays ||= Set.new - end - - # Returns +true+ if the parameter is permitted, +false+ otherwise. - # - # params = ActionController::Parameters.new - # params.permitted? # => false - # params.permit! - # params.permitted? # => true - def permitted? - @permitted - end - - # Sets the +permitted+ attribute to +true+. This can be used to pass - # mass assignment. Returns +self+. - # - # class Person < ActiveRecord::Base - # end - # - # params = ActionController::Parameters.new(name: "Francesco") - # params.permitted? # => false - # Person.new(params) # => ActiveModel::ForbiddenAttributesError - # params.permit! - # params.permitted? # => true - # Person.new(params) # => # - def permit! - each_pair do |key, value| - Array.wrap(value).each do |v| - v.permit! if v.respond_to? :permit! - end - end - - @permitted = true - self - end - - # This method accepts both a single key and an array of keys. - # - # When passed a single key, if it exists and its associated value is - # either present or the singleton +false+, returns said value: - # - # ActionController::Parameters.new(person: { name: "Francesco" }).require(:person) - # # => "Francesco"} permitted: false> - # - # Otherwise raises ActionController::ParameterMissing: - # - # ActionController::Parameters.new.require(:person) - # # ActionController::ParameterMissing: param is missing or the value is empty: person - # - # ActionController::Parameters.new(person: nil).require(:person) - # # ActionController::ParameterMissing: param is missing or the value is empty: person - # - # ActionController::Parameters.new(person: "\t").require(:person) - # # ActionController::ParameterMissing: param is missing or the value is empty: person - # - # ActionController::Parameters.new(person: {}).require(:person) - # # ActionController::ParameterMissing: param is missing or the value is empty: person - # - # When given an array of keys, the method tries to require each one of them - # in order. If it succeeds, an array with the respective return values is - # returned: - # - # params = ActionController::Parameters.new(user: { ... }, profile: { ... }) - # user_params, profile_params = params.require([:user, :profile]) - # - # Otherwise, the method re-raises the first exception found: - # - # params = ActionController::Parameters.new(user: {}, profile: {}) - # user_params, profile_params = params.require([:user, :profile]) - # # ActionController::ParameterMissing: param is missing or the value is empty: user - # - # Technically this method can be used to fetch terminal values: - # - # # CAREFUL - # params = ActionController::Parameters.new(person: { name: "Finn" }) - # name = params.require(:person).require(:name) # CAREFUL - # - # but take into account that at some point those ones have to be permitted: - # - # def person_params - # params.require(:person).permit(:name).tap do |person_params| - # person_params.require(:name) # SAFER - # end - # end - # - # for example. - def require(key) - return key.map { |k| require(k) } if key.is_a?(Array) - value = self[key] - if value.present? || value == false - value - else - raise ParameterMissing.new(key) - end - end - - # Alias of #require. - alias :required :require - - # Returns a new ActionController::Parameters instance that - # includes only the given +filters+ and sets the +permitted+ attribute - # for the object to +true+. This is useful for limiting which attributes - # should be allowed for mass updating. - # - # params = ActionController::Parameters.new(user: { name: "Francesco", age: 22, role: "admin" }) - # permitted = params.require(:user).permit(:name, :age) - # permitted.permitted? # => true - # permitted.has_key?(:name) # => true - # permitted.has_key?(:age) # => true - # permitted.has_key?(:role) # => false - # - # Only permitted scalars pass the filter. For example, given - # - # params.permit(:name) - # - # +:name+ passes if it is a key of +params+ whose associated value is of type - # +String+, +Symbol+, +NilClass+, +Numeric+, +TrueClass+, +FalseClass+, - # +Date+, +Time+, +DateTime+, +StringIO+, +IO+, - # +ActionDispatch::Http::UploadedFile+ or +Rack::Test::UploadedFile+. - # Otherwise, the key +:name+ is filtered out. - # - # You may declare that the parameter should be an array of permitted scalars - # by mapping it to an empty array: - # - # params = ActionController::Parameters.new(tags: ["rails", "parameters"]) - # params.permit(tags: []) - # - # Sometimes it is not possible or convenient to declare the valid keys of - # a hash parameter or its internal structure. Just map to an empty hash: - # - # params.permit(preferences: {}) - # - # Be careful because this opens the door to arbitrary input. In this - # case, +permit+ ensures values in the returned structure are permitted - # scalars and filters out anything else. - # - # You can also use +permit+ on nested parameters, like: - # - # params = ActionController::Parameters.new({ - # person: { - # name: "Francesco", - # age: 22, - # pets: [{ - # name: "Purplish", - # category: "dogs" - # }] - # } - # }) - # - # permitted = params.permit(person: [ :name, { pets: :name } ]) - # permitted.permitted? # => true - # permitted[:person][:name] # => "Francesco" - # permitted[:person][:age] # => nil - # permitted[:person][:pets][0][:name] # => "Purplish" - # permitted[:person][:pets][0][:category] # => nil - # - # Note that if you use +permit+ in a key that points to a hash, - # it won't allow all the hash. You also need to specify which - # attributes inside the hash should be whitelisted. - # - # params = ActionController::Parameters.new({ - # person: { - # contact: { - # email: "none@test.com", - # phone: "555-1234" - # } - # } - # }) - # - # params.require(:person).permit(:contact) - # # => - # - # params.require(:person).permit(contact: :phone) - # # => "555-1234"} permitted: true>} permitted: true> - # - # params.require(:person).permit(contact: [ :email, :phone ]) - # # => "none@test.com", "phone"=>"555-1234"} permitted: true>} permitted: true> - def permit(*filters) - params = self.class.new - - filters.flatten.each do |filter| - case filter - when Symbol, String - permitted_scalar_filter(params, filter) - when Hash - hash_filter(params, filter) - end - end - - unpermitted_parameters!(params) if self.class.action_on_unpermitted_parameters - - params.permit! - end - - # Returns a parameter for the given +key+. If not found, - # returns +nil+. - # - # params = ActionController::Parameters.new(person: { name: "Francesco" }) - # params[:person] # => "Francesco"} permitted: false> - # params[:none] # => nil - def [](key) - convert_hashes_to_parameters(key, @parameters[key]) - end - - # Assigns a value to a given +key+. The given key may still get filtered out - # when +permit+ is called. - def []=(key, value) - @parameters[key] = value - end - - # Returns a parameter for the given +key+. If the +key+ - # can't be found, there are several options: With no other arguments, - # it will raise an ActionController::ParameterMissing error; - # if more arguments are given, then that will be returned; if a block - # is given, then that will be run and its result returned. - # - # params = ActionController::Parameters.new(person: { name: "Francesco" }) - # params.fetch(:person) # => "Francesco"} permitted: false> - # params.fetch(:none) # => ActionController::ParameterMissing: param is missing or the value is empty: none - # params.fetch(:none, "Francesco") # => "Francesco" - # params.fetch(:none) { "Francesco" } # => "Francesco" - def fetch(key, *args) - convert_value_to_parameters( - @parameters.fetch(key) { - if block_given? - yield - else - args.fetch(0) { raise ActionController::ParameterMissing.new(key) } - end - } - ) - end - - if Hash.method_defined?(:dig) - # Extracts the nested parameter from the given +keys+ by calling +dig+ - # at each step. Returns +nil+ if any intermediate step is +nil+. - # - # params = ActionController::Parameters.new(foo: { bar: { baz: 1 } }) - # params.dig(:foo, :bar, :baz) # => 1 - # params.dig(:foo, :zot, :xyz) # => nil - # - # params2 = ActionController::Parameters.new(foo: [10, 11, 12]) - # params2.dig(:foo, 1) # => 11 - def dig(*keys) - convert_value_to_parameters(@parameters.dig(*keys)) - end - end - - # Returns a new ActionController::Parameters instance that - # includes only the given +keys+. If the given +keys+ - # don't exist, returns an empty hash. - # - # params = ActionController::Parameters.new(a: 1, b: 2, c: 3) - # params.slice(:a, :b) # => 1, "b"=>2} permitted: false> - # params.slice(:d) # => - def slice(*keys) - new_instance_with_inherited_permitted_status(@parameters.slice(*keys)) - end - - # Returns current ActionController::Parameters instance which - # contains only the given +keys+. - def slice!(*keys) - @parameters.slice!(*keys) - self - end - - # Returns a new ActionController::Parameters instance that - # filters out the given +keys+. - # - # params = ActionController::Parameters.new(a: 1, b: 2, c: 3) - # params.except(:a, :b) # => 3} permitted: false> - # params.except(:d) # => 1, "b"=>2, "c"=>3} permitted: false> - def except(*keys) - new_instance_with_inherited_permitted_status(@parameters.except(*keys)) - end - - # Removes and returns the key/value pairs matching the given keys. - # - # params = ActionController::Parameters.new(a: 1, b: 2, c: 3) - # params.extract!(:a, :b) # => 1, "b"=>2} permitted: false> - # params # => 3} permitted: false> - def extract!(*keys) - new_instance_with_inherited_permitted_status(@parameters.extract!(*keys)) - end - - # Returns a new ActionController::Parameters with the results of - # running +block+ once for every value. The keys are unchanged. - # - # params = ActionController::Parameters.new(a: 1, b: 2, c: 3) - # params.transform_values { |x| x * 2 } - # # => 2, "b"=>4, "c"=>6} permitted: false> - def transform_values(&block) - if block - new_instance_with_inherited_permitted_status( - @parameters.transform_values(&block) - ) - else - @parameters.transform_values - end - end - - # Performs values transformation and returns the altered - # ActionController::Parameters instance. - def transform_values!(&block) - @parameters.transform_values!(&block) - self - end - - # Returns a new ActionController::Parameters instance with the - # results of running +block+ once for every key. The values are unchanged. - def transform_keys(&block) - if block - new_instance_with_inherited_permitted_status( - @parameters.transform_keys(&block) - ) - else - @parameters.transform_keys - end - end - - # Performs keys transformation and returns the altered - # ActionController::Parameters instance. - def transform_keys!(&block) - @parameters.transform_keys!(&block) - self - end - - # Deletes and returns a key-value pair from +Parameters+ whose key is equal - # to key. If the key is not found, returns the default value. If the - # optional code block is given and the key is not found, pass in the key - # and return the result of block. - def delete(key, &block) - convert_value_to_parameters(@parameters.delete(key, &block)) - end - - # Returns a new instance of ActionController::Parameters with only - # items that the block evaluates to true. - def select(&block) - new_instance_with_inherited_permitted_status(@parameters.select(&block)) - end - - # Equivalent to Hash#keep_if, but returns +nil+ if no changes were made. - def select!(&block) - @parameters.select!(&block) - self - end - alias_method :keep_if, :select! - - # Returns a new instance of ActionController::Parameters with items - # that the block evaluates to true removed. - def reject(&block) - new_instance_with_inherited_permitted_status(@parameters.reject(&block)) - end - - # Removes items that the block evaluates to true and returns self. - def reject!(&block) - @parameters.reject!(&block) - self - end - alias_method :delete_if, :reject! - - # Returns values that were assigned to the given +keys+. Note that all the - # +Hash+ objects will be converted to ActionController::Parameters. - def values_at(*keys) - convert_value_to_parameters(@parameters.values_at(*keys)) - end - - # Returns a new ActionController::Parameters with all keys from - # +other_hash+ merged into current hash. - def merge(other_hash) - new_instance_with_inherited_permitted_status( - @parameters.merge(other_hash.to_h) - ) - end - - # Returns current ActionController::Parameters instance with - # +other_hash+ merged into current hash. - def merge!(other_hash) - @parameters.merge!(other_hash.to_h) - self - end - - # Returns a new ActionController::Parameters with all keys from - # current hash merged into +other_hash+. - def reverse_merge(other_hash) - new_instance_with_inherited_permitted_status( - other_hash.to_h.merge(@parameters) - ) - end - - # Returns current ActionController::Parameters instance with - # current hash merged into +other_hash+. - def reverse_merge!(other_hash) - @parameters.merge!(other_hash.to_h) { |key, left, right| left } - self - end - - # This is required by ActiveModel attribute assignment, so that user can - # pass +Parameters+ to a mass assignment methods in a model. It should not - # matter as we are using +HashWithIndifferentAccess+ internally. - def stringify_keys # :nodoc: - dup - end - - def inspect - "<#{self.class} #{@parameters} permitted: #{@permitted}>" - end - - def self.hook_into_yaml_loading # :nodoc: - # Wire up YAML format compatibility with Rails 4.2 and Psych 2.0.8 and 2.0.9+. - # Makes the YAML parser call `init_with` when it encounters the keys below - # instead of trying its own parsing routines. - YAML.load_tags["!ruby/hash-with-ivars:ActionController::Parameters"] = name - YAML.load_tags["!ruby/hash:ActionController::Parameters"] = name - end - hook_into_yaml_loading - - def init_with(coder) # :nodoc: - case coder.tag - when "!ruby/hash:ActionController::Parameters" - # YAML 2.0.8's format where hash instance variables weren't stored. - @parameters = coder.map.with_indifferent_access - @permitted = false - when "!ruby/hash-with-ivars:ActionController::Parameters" - # YAML 2.0.9's Hash subclass format where keys and values - # were stored under an elements hash and `permitted` within an ivars hash. - @parameters = coder.map["elements"].with_indifferent_access - @permitted = coder.map["ivars"][:@permitted] - when "!ruby/object:ActionController::Parameters" - # YAML's Object format. Only needed because of the format - # backwardscompability above, otherwise equivalent to YAML's initialization. - @parameters, @permitted = coder.map["parameters"], coder.map["permitted"] - end - end - - # Returns duplicate of object including all parameters. - def deep_dup - self.class.new(@parameters.deep_dup).tap do |duplicate| - duplicate.permitted = @permitted - end - end - - protected - attr_reader :parameters - - def permitted=(new_permitted) - @permitted = new_permitted - end - - def fields_for_style? - @parameters.all? { |k, v| k =~ /\A-?\d+\z/ && (v.is_a?(Hash) || v.is_a?(Parameters)) } - end - - private - def new_instance_with_inherited_permitted_status(hash) - self.class.new(hash).tap do |new_instance| - new_instance.permitted = @permitted - end - end - - def convert_parameters_to_hashes(value, using) - case value - when Array - value.map { |v| convert_parameters_to_hashes(v, using) } - when Hash - value.transform_values do |v| - convert_parameters_to_hashes(v, using) - end.with_indifferent_access - when Parameters - value.send(using) - else - value - end - end - - def convert_hashes_to_parameters(key, value) - converted = convert_value_to_parameters(value) - @parameters[key] = converted unless converted.equal?(value) - converted - end - - def convert_value_to_parameters(value) - case value - when Array - return value if converted_arrays.member?(value) - converted = value.map { |_| convert_value_to_parameters(_) } - converted_arrays << converted - converted - when Hash - self.class.new(value) - else - value - end - end - - def each_element(object) - case object - when Array - object.grep(Parameters).map { |el| yield el }.compact - when Parameters - if object.fields_for_style? - hash = object.class.new - object.each { |k, v| hash[k] = yield v } - hash - else - yield object - end - end - end - - def unpermitted_parameters!(params) - unpermitted_keys = unpermitted_keys(params) - if unpermitted_keys.any? - case self.class.action_on_unpermitted_parameters - when :log - name = "unpermitted_parameters.action_controller" - ActiveSupport::Notifications.instrument(name, keys: unpermitted_keys) - when :raise - raise ActionController::UnpermittedParameters.new(unpermitted_keys) - end - end - end - - def unpermitted_keys(params) - keys - params.keys - always_permitted_parameters - end - - # - # --- Filtering ---------------------------------------------------------- - # - - # This is a white list of permitted scalar types that includes the ones - # supported in XML and JSON requests. - # - # This list is in particular used to filter ordinary requests, String goes - # as first element to quickly short-circuit the common case. - # - # If you modify this collection please update the API of +permit+ above. - PERMITTED_SCALAR_TYPES = [ - String, - Symbol, - NilClass, - Numeric, - TrueClass, - FalseClass, - Date, - Time, - # DateTimes are Dates, we document the type but avoid the redundant check. - StringIO, - IO, - ActionDispatch::Http::UploadedFile, - Rack::Test::UploadedFile, - ] - - def permitted_scalar?(value) - PERMITTED_SCALAR_TYPES.any? { |type| value.is_a?(type) } - end - - def permitted_scalar_filter(params, key) - if has_key?(key) && permitted_scalar?(self[key]) - params[key] = self[key] - end - - keys.grep(/\A#{Regexp.escape(key)}\(\d+[if]?\)\z/) do |k| - if permitted_scalar?(self[k]) - params[k] = self[k] - end - end - end - - def array_of_permitted_scalars?(value) - if value.is_a?(Array) && value.all? { |element| permitted_scalar?(element) } - yield value - end - end - - def non_scalar?(value) - value.is_a?(Array) || value.is_a?(Parameters) - end - - EMPTY_ARRAY = [] - EMPTY_HASH = {} - def hash_filter(params, filter) - filter = filter.with_indifferent_access - - # Slicing filters out non-declared keys. - slice(*filter.keys).each do |key, value| - next unless value - next unless has_key? key - - if filter[key] == EMPTY_ARRAY - # Declaration { comment_ids: [] }. - array_of_permitted_scalars?(self[key]) do |val| - params[key] = val - end - elsif filter[key] == EMPTY_HASH - # Declaration { preferences: {} }. - if value.is_a?(Parameters) - params[key] = permit_any_in_parameters(value) - end - elsif non_scalar?(value) - # Declaration { user: :name } or { user: [:name, :age, { address: ... }] }. - params[key] = each_element(value) do |element| - element.permit(*Array.wrap(filter[key])) - end - end - end - end - - def permit_any_in_parameters(params) - self.class.new.tap do |sanitized| - params.each do |key, value| - case value - when ->(v) { permitted_scalar?(v) } - sanitized[key] = value - when Array - sanitized[key] = permit_any_in_array(value) - when Parameters - sanitized[key] = permit_any_in_parameters(value) - else - # Filter this one out. - end - end - end - end - - def permit_any_in_array(array) - [].tap do |sanitized| - array.each do |element| - case element - when ->(e) { permitted_scalar?(e) } - sanitized << element - when Parameters - sanitized << permit_any_in_parameters(element) - else - # Filter this one out. - end - end - end - end - - def initialize_copy(source) - super - @parameters = @parameters.dup - end - end - - # == Strong \Parameters - # - # It provides an interface for protecting attributes from end-user - # assignment. This makes Action Controller parameters forbidden - # to be used in Active Model mass assignment until they have been - # whitelisted. - # - # In addition, parameters can be marked as required and flow through a - # predefined raise/rescue flow to end up as a 400 Bad Request with no - # effort. - # - # class PeopleController < ActionController::Base - # # Using "Person.create(params[:person])" would raise an - # # ActiveModel::ForbiddenAttributesError exception because it'd - # # be using mass assignment without an explicit permit step. - # # This is the recommended form: - # def create - # Person.create(person_params) - # end - # - # # This will pass with flying colors as long as there's a person key in the - # # parameters, otherwise it'll raise an ActionController::ParameterMissing - # # exception, which will get caught by ActionController::Base and turned - # # into a 400 Bad Request reply. - # def update - # redirect_to current_account.people.find(params[:id]).tap { |person| - # person.update!(person_params) - # } - # end - # - # private - # # Using a private method to encapsulate the permissible parameters is - # # a good pattern since you'll be able to reuse the same permit - # # list between create and update. Also, you can specialize this method - # # with per-user checking of permissible attributes. - # def person_params - # params.require(:person).permit(:name, :age) - # end - # end - # - # In order to use accepts_nested_attributes_for with Strong \Parameters, you - # will need to specify which nested attributes should be whitelisted. You might want - # to allow +:id+ and +:_destroy+, see ActiveRecord::NestedAttributes for more information. - # - # class Person - # has_many :pets - # accepts_nested_attributes_for :pets - # end - # - # class PeopleController < ActionController::Base - # def create - # Person.create(person_params) - # end - # - # ... - # - # private - # - # def person_params - # # It's mandatory to specify the nested attributes that should be whitelisted. - # # If you use `permit` with just the key that points to the nested attributes hash, - # # it will return an empty hash. - # params.require(:person).permit(:name, :age, pets_attributes: [ :id, :name, :category ]) - # end - # end - # - # See ActionController::Parameters.require and ActionController::Parameters.permit - # for more information. - module StrongParameters - extend ActiveSupport::Concern - include ActiveSupport::Rescuable - - # Returns a new ActionController::Parameters object that - # has been instantiated with the request.parameters. - def params - @_params ||= Parameters.new(request.parameters) - end - - # Assigns the given +value+ to the +params+ hash. If +value+ - # is a Hash, this will create an ActionController::Parameters - # object that has been instantiated with the given +value+ hash. - def params=(value) - @_params = value.is_a?(Hash) ? Parameters.new(value) : value - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/testing.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/testing.rb deleted file mode 100644 index 9bb416178a..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/testing.rb +++ /dev/null @@ -1,20 +0,0 @@ -module ActionController - module Testing - extend ActiveSupport::Concern - - # Behavior specific to functional tests - module Functional # :nodoc: - def recycle! - @_url_options = nil - self.formats = nil - self.params = nil - end - end - - module ClassMethods - def before_filters - _process_action_callbacks.find_all { |x| x.kind == :before }.map(&:name) - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/url_for.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/url_for.rb deleted file mode 100644 index 21ed5b4ec8..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/metal/url_for.rb +++ /dev/null @@ -1,56 +0,0 @@ -module ActionController - # Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing - # the _routes method. Otherwise, an exception will be raised. - # - # In addition to AbstractController::UrlFor, this module accesses the HTTP layer to define - # URL options like the +host+. In order to do so, this module requires the host class - # to implement +env+ which needs to be Rack-compatible and +request+ - # which is either an instance of +ActionDispatch::Request+ or an object - # that responds to the +host+, +optional_port+, +protocol+ and - # +symbolized_path_parameter+ methods. - # - # class RootUrl - # include ActionController::UrlFor - # include Rails.application.routes.url_helpers - # - # delegate :env, :request, to: :controller - # - # def initialize(controller) - # @controller = controller - # @url = root_path # named route from the application. - # end - # end - module UrlFor - extend ActiveSupport::Concern - - include AbstractController::UrlFor - - def url_options - @_url_options ||= { - host: request.host, - port: request.optional_port, - protocol: request.protocol, - _recall: request.path_parameters - }.merge!(super).freeze - - if (same_origin = _routes.equal?(request.routes)) || - (script_name = request.engine_script_name(_routes)) || - (original_script_name = request.original_script_name) - - options = @_url_options.dup - if original_script_name - options[:original_script_name] = original_script_name - else - if same_origin - options[:script_name] = request.script_name.empty? ? "".freeze : request.script_name.dup - else - options[:script_name] = script_name - end - end - options.freeze - else - @_url_options - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/railtie.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/railtie.rb deleted file mode 100644 index aa5b9506e6..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/railtie.rb +++ /dev/null @@ -1,77 +0,0 @@ -require "rails" -require "action_controller" -require "action_dispatch/railtie" -require "abstract_controller/railties/routes_helpers" -require "action_controller/railties/helpers" -require "action_view/railtie" - -module ActionController - class Railtie < Rails::Railtie #:nodoc: - config.action_controller = ActiveSupport::OrderedOptions.new - - config.eager_load_namespaces << ActionController - - initializer "action_controller.assets_config", group: :all do |app| - app.config.action_controller.assets_dir ||= app.config.paths["public"].first - end - - initializer "action_controller.set_helpers_path" do |app| - ActionController::Helpers.helpers_path = app.helpers_paths - end - - initializer "action_controller.parameters_config" do |app| - options = app.config.action_controller - - ActiveSupport.on_load(:action_controller, run_once: true) do - if options.delete(:raise_on_unfiltered_parameters) - ActiveSupport::Deprecation.warn("raise_on_unfiltered_parameters is deprecated and has no effect in Rails 5.1.") - end - - ActionController::Parameters.permit_all_parameters = options.delete(:permit_all_parameters) { false } - if app.config.action_controller[:always_permitted_parameters] - ActionController::Parameters.always_permitted_parameters = - app.config.action_controller.delete(:always_permitted_parameters) - end - ActionController::Parameters.action_on_unpermitted_parameters = options.delete(:action_on_unpermitted_parameters) do - (Rails.env.test? || Rails.env.development?) ? :log : false - end - end - end - - initializer "action_controller.set_configs" do |app| - paths = app.config.paths - options = app.config.action_controller - - options.logger ||= Rails.logger - options.cache_store ||= Rails.cache - - options.javascripts_dir ||= paths["public/javascripts"].first - options.stylesheets_dir ||= paths["public/stylesheets"].first - - # Ensure readers methods get compiled. - options.asset_host ||= app.config.asset_host - options.relative_url_root ||= app.config.relative_url_root - - ActiveSupport.on_load(:action_controller) do - include app.routes.mounted_helpers - extend ::AbstractController::Railties::RoutesHelpers.with(app.routes) - extend ::ActionController::Railties::Helpers - - options.each do |k, v| - k = "#{k}=" - if respond_to?(k) - send(k, v) - elsif !Base.respond_to?(k) - raise "Invalid option key: #{k}" - end - end - end - end - - initializer "action_controller.compile_config_methods" do - ActiveSupport.on_load(:action_controller) do - config.compile_methods! if config.respond_to?(:compile_methods!) - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/railties/helpers.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/railties/helpers.rb deleted file mode 100644 index 3985c6b273..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/railties/helpers.rb +++ /dev/null @@ -1,22 +0,0 @@ -module ActionController - module Railties - module Helpers - def inherited(klass) - super - return unless klass.respond_to?(:helpers_path=) - - if namespace = klass.parents.detect { |m| m.respond_to?(:railtie_helpers_paths) } - paths = namespace.railtie_helpers_paths - else - paths = ActionController::Helpers.helpers_path - end - - klass.helpers_path = paths - - if klass.superclass == ActionController::Base && ActionController::Base.include_all_helpers - klass.helper :all - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/renderer.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/renderer.rb deleted file mode 100644 index cbb719d8b2..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/renderer.rb +++ /dev/null @@ -1,115 +0,0 @@ -require "active_support/core_ext/hash/keys" - -module ActionController - # ActionController::Renderer allows you to render arbitrary templates - # without requirement of being in controller actions. - # - # You get a concrete renderer class by invoking ActionController::Base#renderer. - # For example: - # - # ApplicationController.renderer - # - # It allows you to call method #render directly. - # - # ApplicationController.renderer.render template: '...' - # - # You can use this shortcut in a controller, instead of the previous example: - # - # ApplicationController.render template: '...' - # - # #render allows you to use the same options that you can use when rendering in a controller. - # For example: - # - # FooController.render :action, locals: { ... }, assigns: { ... } - # - # The template will be rendered in a Rack environment which is accessible through - # ActionController::Renderer#env. You can set it up in two ways: - # - # * by changing renderer defaults, like - # - # ApplicationController.renderer.defaults # => hash with default Rack environment - # - # * by initializing an instance of renderer by passing it a custom environment. - # - # ApplicationController.renderer.new(method: 'post', https: true) - # - class Renderer - attr_reader :defaults, :controller - - DEFAULTS = { - http_host: "example.org", - https: false, - method: "get", - script_name: "", - input: "" - }.freeze - - # Create a new renderer instance for a specific controller class. - def self.for(controller, env = {}, defaults = DEFAULTS.dup) - new(controller, env, defaults) - end - - # Create a new renderer for the same controller but with a new env. - def new(env = {}) - self.class.new controller, env, defaults - end - - # Create a new renderer for the same controller but with new defaults. - def with_defaults(defaults) - self.class.new controller, @env, self.defaults.merge(defaults) - end - - # Accepts a custom Rack environment to render templates in. - # It will be merged with the default Rack environment defined by - # +ActionController::Renderer::DEFAULTS+. - def initialize(controller, env, defaults) - @controller = controller - @defaults = defaults - @env = normalize_keys defaults.merge(env) - end - - # Render templates with any options from ActionController::Base#render_to_string. - def render(*args) - raise "missing controller" unless controller - - request = ActionDispatch::Request.new @env - request.routes = controller._routes - - instance = controller.new - instance.set_request! request - instance.set_response! controller.make_response!(request) - instance.render_to_string(*args) - end - - private - def normalize_keys(env) - new_env = {} - env.each_pair { |k, v| new_env[rack_key_for(k)] = rack_value_for(k, v) } - new_env["rack.url_scheme"] = new_env["HTTPS"] == "on" ? "https" : "http" - new_env - end - - RACK_KEY_TRANSLATION = { - http_host: "HTTP_HOST", - https: "HTTPS", - method: "REQUEST_METHOD", - script_name: "SCRIPT_NAME", - input: "rack.input" - } - - IDENTITY = ->(_) { _ } - - RACK_VALUE_TRANSLATION = { - https: ->(v) { v ? "on" : "off" }, - method: ->(v) { v.upcase }, - } - - def rack_key_for(key) - RACK_KEY_TRANSLATION.fetch(key, key.to_s) - end - - def rack_value_for(key, value) - RACK_VALUE_TRANSLATION.fetch(key, IDENTITY).call value - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/template_assertions.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/template_assertions.rb deleted file mode 100644 index 0179f4afcd..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/template_assertions.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActionController - module TemplateAssertions - def assert_template(options = {}, message = nil) - raise NoMethodError, - "assert_template has been extracted to a gem. To continue using it, - add `gem 'rails-controller-testing'` to your Gemfile." - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/test_case.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_controller/test_case.rb deleted file mode 100644 index bc42d50205..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_controller/test_case.rb +++ /dev/null @@ -1,624 +0,0 @@ -require "rack/session/abstract/id" -require "active_support/core_ext/hash/conversions" -require "active_support/core_ext/object/to_query" -require "active_support/core_ext/module/anonymous" -require "active_support/core_ext/hash/keys" -require "active_support/testing/constant_lookup" -require "action_controller/template_assertions" -require "rails-dom-testing" - -module ActionController - class Metal - include Testing::Functional - end - - module Live - # Disable controller / rendering threads in tests. User tests can access - # the database on the main thread, so they could open a txn, then the - # controller thread will open a new connection and try to access data - # that's only visible to the main thread's txn. This is the problem in #23483. - remove_method :new_controller_thread - def new_controller_thread # :nodoc: - yield - end - end - - # ActionController::TestCase will be deprecated and moved to a gem in Rails 5.1. - # Please use ActionDispatch::IntegrationTest going forward. - class TestRequest < ActionDispatch::TestRequest #:nodoc: - DEFAULT_ENV = ActionDispatch::TestRequest::DEFAULT_ENV.dup - DEFAULT_ENV.delete "PATH_INFO" - - def self.new_session - TestSession.new - end - - attr_reader :controller_class - - # Create a new test request with default `env` values. - def self.create(controller_class) - env = {} - env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application - env["rack.request.cookie_hash"] = {}.with_indifferent_access - new(default_env.merge(env), new_session, controller_class) - end - - def self.default_env - DEFAULT_ENV - end - private_class_method :default_env - - def initialize(env, session, controller_class) - super(env) - - self.session = session - self.session_options = TestSession::DEFAULT_OPTIONS.dup - @controller_class = controller_class - @custom_param_parsers = { - xml: lambda { |raw_post| Hash.from_xml(raw_post)["hash"] } - } - end - - def query_string=(string) - set_header Rack::QUERY_STRING, string - end - - def content_type=(type) - set_header "CONTENT_TYPE", type - end - - def assign_parameters(routes, controller_path, action, parameters, generated_path, query_string_keys) - non_path_parameters = {} - path_parameters = {} - - parameters.each do |key, value| - if query_string_keys.include?(key) - non_path_parameters[key] = value - else - if value.is_a?(Array) - value = value.map(&:to_param) - else - value = value.to_param - end - - path_parameters[key] = value - end - end - - if get? - if query_string.blank? - self.query_string = non_path_parameters.to_query - end - else - if ENCODER.should_multipart?(non_path_parameters) - self.content_type = ENCODER.content_type - data = ENCODER.build_multipart non_path_parameters - else - fetch_header("CONTENT_TYPE") do |k| - set_header k, "application/x-www-form-urlencoded" - end - - case content_mime_type.to_sym - when nil - raise "Unknown Content-Type: #{content_type}" - when :json - data = ActiveSupport::JSON.encode(non_path_parameters) - when :xml - data = non_path_parameters.to_xml - when :url_encoded_form - data = non_path_parameters.to_query - else - @custom_param_parsers[content_mime_type.symbol] = ->(_) { non_path_parameters } - data = non_path_parameters.to_query - end - end - - data_stream = StringIO.new(data) - set_header "CONTENT_LENGTH", data_stream.length.to_s - set_header "rack.input", data_stream - end - - fetch_header("PATH_INFO") do |k| - set_header k, generated_path - end - path_parameters[:controller] = controller_path - path_parameters[:action] = action - - self.path_parameters = path_parameters - end - - ENCODER = Class.new do - include Rack::Test::Utils - - def should_multipart?(params) - # FIXME: lifted from Rack-Test. We should push this separation upstream. - multipart = false - query = lambda { |value| - case value - when Array - value.each(&query) - when Hash - value.values.each(&query) - when Rack::Test::UploadedFile - multipart = true - end - } - params.values.each(&query) - multipart - end - - public :build_multipart - - def content_type - "multipart/form-data; boundary=#{Rack::Test::MULTIPART_BOUNDARY}" - end - end.new - - private - - def params_parsers - super.merge @custom_param_parsers - end - end - - class LiveTestResponse < Live::Response - # Was the response successful? - alias_method :success?, :successful? - - # Was the URL not found? - alias_method :missing?, :not_found? - - # Was there a server-side error? - alias_method :error?, :server_error? - end - - # Methods #destroy and #load! are overridden to avoid calling methods on the - # @store object, which does not exist for the TestSession class. - class TestSession < Rack::Session::Abstract::SessionHash #:nodoc: - DEFAULT_OPTIONS = Rack::Session::Abstract::Persisted::DEFAULT_OPTIONS - - def initialize(session = {}) - super(nil, nil) - @id = SecureRandom.hex(16) - @data = stringify_keys(session) - @loaded = true - end - - def exists? - true - end - - def keys - @data.keys - end - - def values - @data.values - end - - def destroy - clear - end - - def fetch(key, *args, &block) - @data.fetch(key.to_s, *args, &block) - end - - private - - def load! - @id - end - end - - # Superclass for ActionController functional tests. Functional tests allow you to - # test a single controller action per test method. - # - # == Use integration style controller tests over functional style controller tests. - # - # Rails discourages the use of functional tests in favor of integration tests - # (use ActionDispatch::IntegrationTest). - # - # New Rails applications no longer generate functional style controller tests and they should - # only be used for backward compatibility. Integration style controller tests perform actual - # requests, whereas functional style controller tests merely simulate a request. Besides, - # integration tests are as fast as functional tests and provide lot of helpers such as +as+, - # +parsed_body+ for effective testing of controller actions including even API endpoints. - # - # == Basic example - # - # Functional tests are written as follows: - # 1. First, one uses the +get+, +post+, +patch+, +put+, +delete+ or +head+ method to simulate - # an HTTP request. - # 2. Then, one asserts whether the current state is as expected. "State" can be anything: - # the controller's HTTP response, the database contents, etc. - # - # For example: - # - # class BooksControllerTest < ActionController::TestCase - # def test_create - # # Simulate a POST response with the given HTTP parameters. - # post(:create, params: { book: { title: "Love Hina" }}) - # - # # Asserts that the controller tried to redirect us to - # # the created book's URI. - # assert_response :found - # - # # Asserts that the controller really put the book in the database. - # assert_not_nil Book.find_by(title: "Love Hina") - # end - # end - # - # You can also send a real document in the simulated HTTP request. - # - # def test_create - # json = {book: { title: "Love Hina" }}.to_json - # post :create, json - # end - # - # == Special instance variables - # - # ActionController::TestCase will also automatically provide the following instance - # variables for use in the tests: - # - # @controller:: - # The controller instance that will be tested. - # @request:: - # An ActionController::TestRequest, representing the current HTTP - # request. You can modify this object before sending the HTTP request. For example, - # you might want to set some session properties before sending a GET request. - # @response:: - # An ActionDispatch::TestResponse object, representing the response - # of the last HTTP response. In the above example, @response becomes valid - # after calling +post+. If the various assert methods are not sufficient, then you - # may use this object to inspect the HTTP response in detail. - # - # (Earlier versions of \Rails required each functional test to subclass - # Test::Unit::TestCase and define @controller, @request, @response in +setup+.) - # - # == Controller is automatically inferred - # - # ActionController::TestCase will automatically infer the controller under test - # from the test class name. If the controller cannot be inferred from the test - # class name, you can explicitly set it with +tests+. - # - # class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase - # tests WidgetController - # end - # - # == \Testing controller internals - # - # In addition to these specific assertions, you also have easy access to various collections that the regular test/unit assertions - # can be used against. These collections are: - # - # * session: Objects being saved in the session. - # * flash: The flash objects currently in the session. - # * cookies: \Cookies being sent to the user on this request. - # - # These collections can be used just like any other hash: - # - # assert_equal "Dave", cookies[:name] # makes sure that a cookie called :name was set as "Dave" - # assert flash.empty? # makes sure that there's nothing in the flash - # - # On top of the collections, you have the complete URL that a given action redirected to available in redirect_to_url. - # - # For redirects within the same controller, you can even call follow_redirect and the redirect will be followed, triggering another - # action call which can then be asserted against. - # - # == Manipulating session and cookie variables - # - # Sometimes you need to set up the session and cookie variables for a test. - # To do this just assign a value to the session or cookie collection: - # - # session[:key] = "value" - # cookies[:key] = "value" - # - # To clear the cookies for a test just clear the cookie collection: - # - # cookies.clear - # - # == \Testing named routes - # - # If you're using named routes, they can be easily tested using the original named routes' methods straight in the test case. - # - # assert_redirected_to page_url(title: 'foo') - class TestCase < ActiveSupport::TestCase - module Behavior - extend ActiveSupport::Concern - include ActionDispatch::TestProcess - include ActiveSupport::Testing::ConstantLookup - include Rails::Dom::Testing::Assertions - - attr_reader :response, :request - - module ClassMethods - # Sets the controller class name. Useful if the name can't be inferred from test class. - # Normalizes +controller_class+ before using. - # - # tests WidgetController - # tests :widget - # tests 'widget' - def tests(controller_class) - case controller_class - when String, Symbol - self.controller_class = "#{controller_class.to_s.camelize}Controller".constantize - when Class - self.controller_class = controller_class - else - raise ArgumentError, "controller class must be a String, Symbol, or Class" - end - end - - def controller_class=(new_class) - self._controller_class = new_class - end - - def controller_class - if current_controller_class = _controller_class - current_controller_class - else - self.controller_class = determine_default_controller_class(name) - end - end - - def determine_default_controller_class(name) - determine_constant_from_test_name(name) do |constant| - Class === constant && constant < ActionController::Metal - end - end - end - - # Simulate a GET request with the given parameters. - # - # - +action+: The controller action to call. - # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+. - # - +body+: The request body with a string that is appropriately encoded - # (application/x-www-form-urlencoded or multipart/form-data). - # - +session+: A hash of parameters to store in the session. This may be +nil+. - # - +flash+: A hash of parameters to store in the flash. This may be +nil+. - # - # You can also simulate POST, PATCH, PUT, DELETE, and HEAD requests with - # +post+, +patch+, +put+, +delete+, and +head+. - # Example sending parameters, session and setting a flash message: - # - # get :show, - # params: { id: 7 }, - # session: { user_id: 1 }, - # flash: { notice: 'This is flash message' } - # - # Note that the request method is not verified. The different methods are - # available to make the tests more expressive. - def get(action, **args) - res = process(action, method: "GET", **args) - cookies.update res.cookies - res - end - - # Simulate a POST request with the given parameters and set/volley the response. - # See +get+ for more details. - def post(action, **args) - process(action, method: "POST", **args) - end - - # Simulate a PATCH request with the given parameters and set/volley the response. - # See +get+ for more details. - def patch(action, **args) - process(action, method: "PATCH", **args) - end - - # Simulate a PUT request with the given parameters and set/volley the response. - # See +get+ for more details. - def put(action, **args) - process(action, method: "PUT", **args) - end - - # Simulate a DELETE request with the given parameters and set/volley the response. - # See +get+ for more details. - def delete(action, **args) - process(action, method: "DELETE", **args) - end - - # Simulate a HEAD request with the given parameters and set/volley the response. - # See +get+ for more details. - def head(action, **args) - process(action, method: "HEAD", **args) - end - - # Simulate an HTTP request to +action+ by specifying request method, - # parameters and set/volley the response. - # - # - +action+: The controller action to call. - # - +method+: Request method used to send the HTTP request. Possible values - # are +GET+, +POST+, +PATCH+, +PUT+, +DELETE+, +HEAD+. Defaults to +GET+. Can be a symbol. - # - +params+: The hash with HTTP parameters that you want to pass. This may be +nil+. - # - +body+: The request body with a string that is appropriately encoded - # (application/x-www-form-urlencoded or multipart/form-data). - # - +session+: A hash of parameters to store in the session. This may be +nil+. - # - +flash+: A hash of parameters to store in the flash. This may be +nil+. - # - +format+: Request format. Defaults to +nil+. Can be string or symbol. - # - +as+: Content type. Defaults to +nil+. Must be a symbol that corresponds - # to a mime type. - # - # Example calling +create+ action and sending two params: - # - # process :create, - # method: 'POST', - # params: { - # user: { name: 'Gaurish Sharma', email: 'user@example.com' } - # }, - # session: { user_id: 1 }, - # flash: { notice: 'This is flash message' } - # - # To simulate +GET+, +POST+, +PATCH+, +PUT+, +DELETE+ and +HEAD+ requests - # prefer using #get, #post, #patch, #put, #delete and #head methods - # respectively which will make tests more expressive. - # - # Note that the request method is not verified. - def process(action, method: "GET", params: {}, session: nil, body: nil, flash: {}, format: nil, xhr: false, as: nil) - check_required_ivars - - if body - @request.set_header "RAW_POST_DATA", body - end - - http_method = method.to_s.upcase - - @html_document = nil - - cookies.update(@request.cookies) - cookies.update_cookies_from_jar - @request.set_header "HTTP_COOKIE", cookies.to_header - @request.delete_header "action_dispatch.cookies" - - @request = TestRequest.new scrub_env!(@request.env), @request.session, @controller.class - @response = build_response @response_klass - @response.request = @request - @controller.recycle! - - @request.set_header "REQUEST_METHOD", http_method - - if as - @request.content_type = Mime[as].to_s - format ||= as - end - - parameters = params.symbolize_keys - - if format - parameters[:format] = format - end - - generated_extras = @routes.generate_extras(parameters.merge(controller: controller_class_name, action: action.to_s)) - generated_path = generated_path(generated_extras) - query_string_keys = query_parameter_names(generated_extras) - - @request.assign_parameters(@routes, controller_class_name, action.to_s, parameters, generated_path, query_string_keys) - - @request.session.update(session) if session - @request.flash.update(flash || {}) - - if xhr - @request.set_header "HTTP_X_REQUESTED_WITH", "XMLHttpRequest" - @request.fetch_header("HTTP_ACCEPT") do |k| - @request.set_header k, [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ") - end - end - - @request.fetch_header("SCRIPT_NAME") do |k| - @request.set_header k, @controller.config.relative_url_root - end - - begin - @controller.recycle! - @controller.dispatch(action, @request, @response) - ensure - @request = @controller.request - @response = @controller.response - - if @request.have_cookie_jar? - unless @request.cookie_jar.committed? - @request.cookie_jar.write(@response) - cookies.update(@request.cookie_jar.instance_variable_get(:@cookies)) - end - end - @response.prepare! - - if flash_value = @request.flash.to_session_value - @request.session["flash"] = flash_value - else - @request.session.delete("flash") - end - - if xhr - @request.delete_header "HTTP_X_REQUESTED_WITH" - @request.delete_header "HTTP_ACCEPT" - end - @request.query_string = "" - - @response.sent! - end - - @response - end - - def controller_class_name - @controller.class.anonymous? ? "anonymous" : @controller.class.controller_path - end - - def generated_path(generated_extras) - generated_extras[0] - end - - def query_parameter_names(generated_extras) - generated_extras[1] + [:controller, :action] - end - - def setup_controller_request_and_response - @controller = nil unless defined? @controller - - @response_klass = ActionDispatch::TestResponse - - if klass = self.class.controller_class - if klass < ActionController::Live - @response_klass = LiveTestResponse - end - unless @controller - begin - @controller = klass.new - rescue - warn "could not construct controller #{klass}" if $VERBOSE - end - end - end - - @request = TestRequest.create(@controller.class) - @response = build_response @response_klass - @response.request = @request - - if @controller - @controller.request = @request - @controller.params = {} - end - end - - def build_response(klass) - klass.create - end - - included do - include ActionController::TemplateAssertions - include ActionDispatch::Assertions - class_attribute :_controller_class - setup :setup_controller_request_and_response - ActiveSupport.run_load_hooks(:action_controller_test_case, self) - end - - private - - def scrub_env!(env) - env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ } - env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ } - env.delete "action_dispatch.request.query_parameters" - env.delete "action_dispatch.request.request_parameters" - env["rack.input"] = StringIO.new - env - end - - def document_root_element - html_document.root - end - - def check_required_ivars - # Sanity check for required instance variables so we can give an - # understandable error message. - [:@routes, :@controller, :@request, :@response].each do |iv_name| - if !instance_variable_defined?(iv_name) || instance_variable_get(iv_name).nil? - raise "#{iv_name} is nil: make sure you set it in your test's setup method." - end - end - end - end - - include Behavior - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch.rb deleted file mode 100644 index 303790e96d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch.rb +++ /dev/null @@ -1,109 +0,0 @@ -#-- -# Copyright (c) 2004-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "active_support" -require "active_support/rails" -require "active_support/core_ext/module/attribute_accessors" - -require "action_pack" -require "rack" - -module Rack - autoload :Test, "rack/test" -end - -module ActionDispatch - extend ActiveSupport::Autoload - - class IllegalStateError < StandardError - end - - eager_autoload do - autoload_under "http" do - autoload :Request - autoload :Response - end - end - - autoload_under "middleware" do - autoload :RequestId - autoload :Callbacks - autoload :Cookies - autoload :DebugExceptions - autoload :DebugLocks - autoload :ExceptionWrapper - autoload :Executor - autoload :Flash - autoload :PublicExceptions - autoload :Reloader - autoload :RemoteIp - autoload :ShowExceptions - autoload :SSL - autoload :Static - end - - autoload :Journey - autoload :MiddlewareStack, "action_dispatch/middleware/stack" - autoload :Routing - - module Http - extend ActiveSupport::Autoload - - autoload :Cache - autoload :Headers - autoload :MimeNegotiation - autoload :Parameters - autoload :ParameterFilter - autoload :Upload - autoload :UploadedFile, "action_dispatch/http/upload" - autoload :URL - end - - module Session - autoload :AbstractStore, "action_dispatch/middleware/session/abstract_store" - autoload :CookieStore, "action_dispatch/middleware/session/cookie_store" - autoload :MemCacheStore, "action_dispatch/middleware/session/mem_cache_store" - autoload :CacheStore, "action_dispatch/middleware/session/cache_store" - end - - mattr_accessor :test_app - - autoload_under "testing" do - autoload :Assertions - autoload :Integration - autoload :IntegrationTest, "action_dispatch/testing/integration" - autoload :TestProcess - autoload :TestRequest - autoload :TestResponse - autoload :AssertionResponse - end - - autoload :SystemTestCase, "action_dispatch/system_test_case" -end - -autoload :Mime, "action_dispatch/http/mime_type" - -ActiveSupport.on_load(:action_view) do - ActionView::Base.default_formats ||= Mime::SET.symbols - ActionView::Template::Types.delegate_to Mime -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/cache.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/cache.rb deleted file mode 100644 index 985e0fb972..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/cache.rb +++ /dev/null @@ -1,214 +0,0 @@ -module ActionDispatch - module Http - module Cache - module Request - HTTP_IF_MODIFIED_SINCE = "HTTP_IF_MODIFIED_SINCE".freeze - HTTP_IF_NONE_MATCH = "HTTP_IF_NONE_MATCH".freeze - - def if_modified_since - if since = get_header(HTTP_IF_MODIFIED_SINCE) - Time.rfc2822(since) rescue nil - end - end - - def if_none_match - get_header HTTP_IF_NONE_MATCH - end - - def if_none_match_etags - if_none_match ? if_none_match.split(/\s*,\s*/) : [] - end - - def not_modified?(modified_at) - if_modified_since && modified_at && if_modified_since >= modified_at - end - - def etag_matches?(etag) - if etag - validators = if_none_match_etags - validators.include?(etag) || validators.include?("*") - end - end - - # Check response freshness (Last-Modified and ETag) against request - # If-Modified-Since and If-None-Match conditions. If both headers are - # supplied, both must match, or the request is not considered fresh. - def fresh?(response) - last_modified = if_modified_since - etag = if_none_match - - return false unless last_modified || etag - - success = true - success &&= not_modified?(response.last_modified) if last_modified - success &&= etag_matches?(response.etag) if etag - success - end - end - - module Response - attr_reader :cache_control - - def last_modified - if last = get_header(LAST_MODIFIED) - Time.httpdate(last) - end - end - - def last_modified? - has_header? LAST_MODIFIED - end - - def last_modified=(utc_time) - set_header LAST_MODIFIED, utc_time.httpdate - end - - def date - if date_header = get_header(DATE) - Time.httpdate(date_header) - end - end - - def date? - has_header? DATE - end - - def date=(utc_time) - set_header DATE, utc_time.httpdate - end - - # This method sets a weak ETag validator on the response so browsers - # and proxies may cache the response, keyed on the ETag. On subsequent - # requests, the If-None-Match header is set to the cached ETag. If it - # matches the current ETag, we can return a 304 Not Modified response - # with no body, letting the browser or proxy know that their cache is - # current. Big savings in request time and network bandwidth. - # - # Weak ETags are considered to be semantically equivalent but not - # byte-for-byte identical. This is perfect for browser caching of HTML - # pages where we don't care about exact equality, just what the user - # is viewing. - # - # Strong ETags are considered byte-for-byte identical. They allow a - # browser or proxy cache to support Range requests, useful for paging - # through a PDF file or scrubbing through a video. Some CDNs only - # support strong ETags and will ignore weak ETags entirely. - # - # Weak ETags are what we almost always need, so they're the default. - # Check out `#strong_etag=` to provide a strong ETag validator. - def etag=(weak_validators) - self.weak_etag = weak_validators - end - - def weak_etag=(weak_validators) - set_header "ETag", generate_weak_etag(weak_validators) - end - - def strong_etag=(strong_validators) - set_header "ETag", generate_strong_etag(strong_validators) - end - - def etag?; etag; end - - # True if an ETag is set and it's a weak validator (preceded with W/) - def weak_etag? - etag? && etag.starts_with?('W/"') - end - - # True if an ETag is set and it isn't a weak validator (not preceded with W/) - def strong_etag? - etag? && !weak_etag? - end - - private - - DATE = "Date".freeze - LAST_MODIFIED = "Last-Modified".freeze - SPECIAL_KEYS = Set.new(%w[extras no-cache max-age public private must-revalidate]) - - def generate_weak_etag(validators) - "W/#{generate_strong_etag(validators)}" - end - - def generate_strong_etag(validators) - %("#{Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key(validators))}") - end - - def cache_control_segments - if cache_control = _cache_control - cache_control.delete(" ").split(",") - else - [] - end - end - - def cache_control_headers - cache_control = {} - - cache_control_segments.each do |segment| - directive, argument = segment.split("=", 2) - - if SPECIAL_KEYS.include? directive - key = directive.tr("-", "_") - cache_control[key.to_sym] = argument || true - else - cache_control[:extras] ||= [] - cache_control[:extras] << segment - end - end - - cache_control - end - - def prepare_cache_control! - @cache_control = cache_control_headers - end - - def handle_conditional_get! - if etag? || last_modified? || !@cache_control.empty? - set_conditional_cache_control!(@cache_control) - end - end - - DEFAULT_CACHE_CONTROL = "max-age=0, private, must-revalidate".freeze - NO_CACHE = "no-cache".freeze - PUBLIC = "public".freeze - PRIVATE = "private".freeze - MUST_REVALIDATE = "must-revalidate".freeze - - def set_conditional_cache_control!(cache_control) - control = {} - cc_headers = cache_control_headers - if extras = cc_headers.delete(:extras) - cache_control[:extras] ||= [] - cache_control[:extras] += extras - cache_control[:extras].uniq! - end - - control.merge! cc_headers - control.merge! cache_control - - if control.empty? - self._cache_control = DEFAULT_CACHE_CONTROL - elsif control[:no_cache] - self._cache_control = NO_CACHE - if control[:extras] - self._cache_control = _cache_control + ", #{control[:extras].join(', ')}" - end - else - extras = control[:extras] - max_age = control[:max_age] - - options = [] - options << "max-age=#{max_age.to_i}" if max_age - options << (control[:public] ? PUBLIC : PRIVATE) - options << MUST_REVALIDATE if control[:must_revalidate] - options.concat(extras) if extras - - self._cache_control = options.join(", ") - end - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/filter_parameters.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/filter_parameters.rb deleted file mode 100644 index 077ab2561f..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/filter_parameters.rb +++ /dev/null @@ -1,82 +0,0 @@ -require "action_dispatch/http/parameter_filter" - -module ActionDispatch - module Http - # Allows you to specify sensitive parameters which will be replaced from - # the request log by looking in the query string of the request and all - # sub-hashes of the params hash to filter. Filtering only certain sub-keys - # from a hash is possible by using the dot notation: 'credit_card.number'. - # If a block is given, each key and value of the params hash and all - # sub-hashes is passed to it, the value or key can be replaced using - # String#replace or similar method. - # - # env["action_dispatch.parameter_filter"] = [:password] - # => replaces the value to all keys matching /password/i with "[FILTERED]" - # - # env["action_dispatch.parameter_filter"] = [:foo, "bar"] - # => replaces the value to all keys matching /foo|bar/i with "[FILTERED]" - # - # env["action_dispatch.parameter_filter"] = [ "credit_card.code" ] - # => replaces { credit_card: {code: "xxxx"} } with "[FILTERED]", does not - # change { file: { code: "xxxx"} } - # - # env["action_dispatch.parameter_filter"] = -> (k, v) do - # v.reverse! if k =~ /secret/i - # end - # => reverses the value to all keys matching /secret/i - module FilterParameters - ENV_MATCH = [/RAW_POST_DATA/, "rack.request.form_vars"] # :nodoc: - NULL_PARAM_FILTER = ParameterFilter.new # :nodoc: - NULL_ENV_FILTER = ParameterFilter.new ENV_MATCH # :nodoc: - - def initialize - super - @filtered_parameters = nil - @filtered_env = nil - @filtered_path = nil - end - - # Returns a hash of parameters with all sensitive data replaced. - def filtered_parameters - @filtered_parameters ||= parameter_filter.filter(parameters) - end - - # Returns a hash of request.env with all sensitive data replaced. - def filtered_env - @filtered_env ||= env_filter.filter(@env) - end - - # Reconstructed a path with all sensitive GET parameters replaced. - def filtered_path - @filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}" - end - - private - - def parameter_filter # :doc: - parameter_filter_for fetch_header("action_dispatch.parameter_filter") { - return NULL_PARAM_FILTER - } - end - - def env_filter # :doc: - user_key = fetch_header("action_dispatch.parameter_filter") { - return NULL_ENV_FILTER - } - parameter_filter_for(Array(user_key) + ENV_MATCH) - end - - def parameter_filter_for(filters) # :doc: - ParameterFilter.new(filters) - end - - KV_RE = "[^&;=]+" - PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})} - def filtered_query_string # :doc: - query_string.gsub(PAIR_RE) do |_| - parameter_filter.filter($1 => $2).first.join("=") - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/filter_redirect.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/filter_redirect.rb deleted file mode 100644 index fc3c44582a..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/filter_redirect.rb +++ /dev/null @@ -1,35 +0,0 @@ -module ActionDispatch - module Http - module FilterRedirect - FILTERED = "[FILTERED]".freeze # :nodoc: - - def filtered_location # :nodoc: - if location_filter_match? - FILTERED - else - location - end - end - - private - - def location_filters - if request - request.get_header("action_dispatch.redirect_filter") || [] - else - [] - end - end - - def location_filter_match? - location_filters.any? do |filter| - if String === filter - location.include?(filter) - elsif Regexp === filter - location =~ filter - end - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/headers.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/headers.rb deleted file mode 100644 index 3c03976f03..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/headers.rb +++ /dev/null @@ -1,130 +0,0 @@ -module ActionDispatch - module Http - # Provides access to the request's HTTP headers from the environment. - # - # env = { "CONTENT_TYPE" => "text/plain", "HTTP_USER_AGENT" => "curl/7.43.0" } - # headers = ActionDispatch::Http::Headers.from_hash(env) - # headers["Content-Type"] # => "text/plain" - # headers["User-Agent"] # => "curl/7.43.0" - # - # Also note that when headers are mapped to CGI-like variables by the Rack - # server, both dashes and underscores are converted to underscores. This - # ambiguity cannot be resolved at this stage anymore. Both underscores and - # dashes have to be interpreted as if they were originally sent as dashes. - # - # # GET / HTTP/1.1 - # # ... - # # User-Agent: curl/7.43.0 - # # X_Custom_Header: token - # - # headers["X_Custom_Header"] # => nil - # headers["X-Custom-Header"] # => "token" - class Headers - CGI_VARIABLES = Set.new(%W[ - AUTH_TYPE - CONTENT_LENGTH - CONTENT_TYPE - GATEWAY_INTERFACE - HTTPS - PATH_INFO - PATH_TRANSLATED - QUERY_STRING - REMOTE_ADDR - REMOTE_HOST - REMOTE_IDENT - REMOTE_USER - REQUEST_METHOD - SCRIPT_NAME - SERVER_NAME - SERVER_PORT - SERVER_PROTOCOL - SERVER_SOFTWARE - ]).freeze - - HTTP_HEADER = /\A[A-Za-z0-9-]+\z/ - - include Enumerable - - def self.from_hash(hash) - new ActionDispatch::Request.new hash - end - - def initialize(request) # :nodoc: - @req = request - end - - # Returns the value for the given key mapped to @env. - def [](key) - @req.get_header env_name(key) - end - - # Sets the given value for the key mapped to @env. - def []=(key, value) - @req.set_header env_name(key), value - end - - # Add a value to a multivalued header like Vary or Accept-Encoding. - def add(key, value) - @req.add_header env_name(key), value - end - - def key?(key) - @req.has_header? env_name(key) - end - alias :include? :key? - - DEFAULT = Object.new # :nodoc: - - # Returns the value for the given key mapped to @env. - # - # If the key is not found and an optional code block is not provided, - # raises a KeyError exception. - # - # If the code block is provided, then it will be run and - # its result returned. - def fetch(key, default = DEFAULT) - @req.fetch_header(env_name(key)) do - return default unless default == DEFAULT - return yield if block_given? - raise KeyError, key - end - end - - def each(&block) - @req.each_header(&block) - end - - # Returns a new Http::Headers instance containing the contents of - # headers_or_env and the original instance. - def merge(headers_or_env) - headers = @req.dup.headers - headers.merge!(headers_or_env) - headers - end - - # Adds the contents of headers_or_env to original instance - # entries; duplicate keys are overwritten with the values from - # headers_or_env. - def merge!(headers_or_env) - headers_or_env.each do |key, value| - @req.set_header env_name(key), value - end - end - - def env; @req.env.dup; end - - private - - # Converts an HTTP header name to an environment variable name if it is - # not contained within the headers hash. - def env_name(key) - key = key.to_s - if key =~ HTTP_HEADER - key = key.upcase.tr("-", "_") - key = "HTTP_" + key unless CGI_VARIABLES.include?(key) - end - key - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_negotiation.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_negotiation.rb deleted file mode 100644 index 9a93a454bc..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_negotiation.rb +++ /dev/null @@ -1,179 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" - -module ActionDispatch - module Http - module MimeNegotiation - extend ActiveSupport::Concern - - included do - mattr_accessor :ignore_accept_header - self.ignore_accept_header = false - end - - # The MIME type of the HTTP request, such as Mime[:xml]. - # - # For backward compatibility, the post \format is extracted from the - # X-Post-Data-Format HTTP header if present. - def content_mime_type - fetch_header("action_dispatch.request.content_type") do |k| - v = if get_header("CONTENT_TYPE") =~ /^([^,\;]*)/ - Mime::Type.lookup($1.strip.downcase) - else - nil - end - set_header k, v - end - end - - def content_type - content_mime_type && content_mime_type.to_s - end - - def has_content_type? # :nodoc: - get_header "CONTENT_TYPE" - end - - # Returns the accepted MIME type for the request. - def accepts - fetch_header("action_dispatch.request.accepts") do |k| - header = get_header("HTTP_ACCEPT").to_s.strip - - v = if header.empty? - [content_mime_type] - else - Mime::Type.parse(header) - end - set_header k, v - end - end - - # Returns the MIME type for the \format used in the request. - # - # GET /posts/5.xml | request.format => Mime[:xml] - # GET /posts/5.xhtml | request.format => Mime[:html] - # GET /posts/5 | request.format => Mime[:html] or Mime[:js], or request.accepts.first - # - def format(view_path = []) - formats.first || Mime::NullType.instance - end - - def formats - fetch_header("action_dispatch.request.formats") do |k| - params_readable = begin - parameters[:format] - rescue ActionController::BadRequest - false - end - - v = if params_readable - Array(Mime[parameters[:format]]) - elsif use_accept_header && valid_accept_header - accepts - elsif extension_format = format_from_path_extension - [extension_format] - elsif xhr? - [Mime[:js]] - else - [Mime[:html]] - end - - v = v.select do |format| - format.symbol || format.ref == "*/*" - end - - set_header k, v - end - end - - # Sets the \variant for template. - def variant=(variant) - variant = Array(variant) - - if variant.all? { |v| v.is_a?(Symbol) } - @variant = ActiveSupport::ArrayInquirer.new(variant) - else - raise ArgumentError, "request.variant must be set to a Symbol or an Array of Symbols. " \ - "For security reasons, never directly set the variant to a user-provided value, " \ - "like params[:variant].to_sym. Check user-provided value against a whitelist first, " \ - "then set the variant: request.variant = :tablet if params[:variant] == 'tablet'" - end - end - - def variant - @variant ||= ActiveSupport::ArrayInquirer.new - end - - # Sets the \format by string extension, which can be used to force custom formats - # that are not controlled by the extension. - # - # class ApplicationController < ActionController::Base - # before_action :adjust_format_for_iphone - # - # private - # def adjust_format_for_iphone - # request.format = :iphone if request.env["HTTP_USER_AGENT"][/iPhone/] - # end - # end - def format=(extension) - parameters[:format] = extension.to_s - set_header "action_dispatch.request.formats", [Mime::Type.lookup_by_extension(parameters[:format])] - end - - # Sets the \formats by string extensions. This differs from #format= by allowing you - # to set multiple, ordered formats, which is useful when you want to have a fallback. - # - # In this example, the :iphone format will be used if it's available, otherwise it'll fallback - # to the :html format. - # - # class ApplicationController < ActionController::Base - # before_action :adjust_format_for_iphone_with_html_fallback - # - # private - # def adjust_format_for_iphone_with_html_fallback - # request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/] - # end - # end - def formats=(extensions) - parameters[:format] = extensions.first.to_s - set_header "action_dispatch.request.formats", extensions.collect { |extension| - Mime::Type.lookup_by_extension(extension) - } - end - - # Receives an array of mimes and return the first user sent mime that - # matches the order array. - # - def negotiate_mime(order) - formats.each do |priority| - if priority == Mime::ALL - return order.first - elsif order.include?(priority) - return priority - end - end - - order.include?(Mime::ALL) ? format : nil - end - - private - - BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/ - - def valid_accept_header # :doc: - (xhr? && (accept.present? || content_mime_type)) || - (accept.present? && accept !~ BROWSER_LIKE_ACCEPTS) - end - - def use_accept_header # :doc: - !self.class.ignore_accept_header - end - - def format_from_path_extension # :doc: - path = get_header("action_dispatch.original_path") || get_header("PATH_INFO") - if match = path && path.match(/\.(\w+)\z/) - Mime[match.captures.first] - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_type.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_type.rb deleted file mode 100644 index 1583a8f87f..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_type.rb +++ /dev/null @@ -1,340 +0,0 @@ -# -*- frozen-string-literal: true -*- - -require "singleton" -require "active_support/core_ext/string/starts_ends_with" - -module Mime - class Mimes - include Enumerable - - def initialize - @mimes = [] - @symbols = nil - end - - def each - @mimes.each { |x| yield x } - end - - def <<(type) - @mimes << type - @symbols = nil - end - - def delete_if - @mimes.delete_if { |x| yield x }.tap { @symbols = nil } - end - - def symbols - @symbols ||= map(&:to_sym) - end - end - - SET = Mimes.new - EXTENSION_LOOKUP = {} - LOOKUP = {} - - class << self - def [](type) - return type if type.is_a?(Type) - Type.lookup_by_extension(type) - end - - def fetch(type) - return type if type.is_a?(Type) - EXTENSION_LOOKUP.fetch(type.to_s) { |k| yield k } - end - end - - # Encapsulates the notion of a mime type. Can be used at render time, for example, with: - # - # class PostsController < ActionController::Base - # def show - # @post = Post.find(params[:id]) - # - # respond_to do |format| - # format.html - # format.ics { render body: @post.to_ics, mime_type: Mime::Type.lookup("text/calendar") } - # format.xml { render xml: @post } - # end - # end - # end - class Type - attr_reader :symbol - - @register_callbacks = [] - - # A simple helper class used in parsing the accept header - class AcceptItem #:nodoc: - attr_accessor :index, :name, :q - alias :to_s :name - - def initialize(index, name, q = nil) - @index = index - @name = name - q ||= 0.0 if @name == "*/*".freeze # default wildcard match to end of list - @q = ((q || 1.0).to_f * 100).to_i - end - - def <=>(item) - result = item.q <=> @q - result = @index <=> item.index if result == 0 - result - end - end - - class AcceptList #:nodoc: - def self.sort!(list) - list.sort! - - text_xml_idx = find_item_by_name list, "text/xml" - app_xml_idx = find_item_by_name list, Mime[:xml].to_s - - # Take care of the broken text/xml entry by renaming or deleting it - if text_xml_idx && app_xml_idx - app_xml = list[app_xml_idx] - text_xml = list[text_xml_idx] - - app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two - if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list - list[app_xml_idx], list[text_xml_idx] = text_xml, app_xml - app_xml_idx, text_xml_idx = text_xml_idx, app_xml_idx - end - list.delete_at(text_xml_idx) # delete text_xml from the list - elsif text_xml_idx - list[text_xml_idx].name = Mime[:xml].to_s - end - - # Look for more specific XML-based types and sort them ahead of app/xml - if app_xml_idx - app_xml = list[app_xml_idx] - idx = app_xml_idx - - while idx < list.length - type = list[idx] - break if type.q < app_xml.q - - if type.name.ends_with? "+xml" - list[app_xml_idx], list[idx] = list[idx], app_xml - app_xml_idx = idx - end - idx += 1 - end - end - - list.map! { |i| Mime::Type.lookup(i.name) }.uniq! - list - end - - def self.find_item_by_name(array, name) - array.index { |item| item.name == name } - end - end - - class << self - TRAILING_STAR_REGEXP = /^(text|application)\/\*/ - PARAMETER_SEPARATOR_REGEXP = /;\s*\w+="?\w+"?/ - - def register_callback(&block) - @register_callbacks << block - end - - def lookup(string) - LOOKUP[string] || Type.new(string) - end - - def lookup_by_extension(extension) - EXTENSION_LOOKUP[extension.to_s] - end - - # Registers an alias that's not used on mime type lookup, but can be referenced directly. Especially useful for - # rendering different HTML versions depending on the user agent, like an iPhone. - def register_alias(string, symbol, extension_synonyms = []) - register(string, symbol, [], extension_synonyms, true) - end - - def register(string, symbol, mime_type_synonyms = [], extension_synonyms = [], skip_lookup = false) - new_mime = Type.new(string, symbol, mime_type_synonyms) - - SET << new_mime - - ([string] + mime_type_synonyms).each { |str| LOOKUP[str] = new_mime } unless skip_lookup - ([symbol] + extension_synonyms).each { |ext| EXTENSION_LOOKUP[ext.to_s] = new_mime } - - @register_callbacks.each do |callback| - callback.call(new_mime) - end - new_mime - end - - def parse(accept_header) - if !accept_header.include?(",") - accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first - parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)].compact - else - list, index = [], 0 - accept_header.split(",").each do |header| - params, q = header.split(PARAMETER_SEPARATOR_REGEXP) - - next unless params - params.strip! - next if params.empty? - - params = parse_trailing_star(params) || [params] - - params.each do |m| - list << AcceptItem.new(index, m.to_s, q) - index += 1 - end - end - AcceptList.sort! list - end - end - - def parse_trailing_star(accept_header) - parse_data_with_trailing_star($1) if accept_header =~ TRAILING_STAR_REGEXP - end - - # For an input of 'text', returns [Mime[:json], Mime[:xml], Mime[:ics], - # Mime[:html], Mime[:css], Mime[:csv], Mime[:js], Mime[:yaml], Mime[:text]. - # - # For an input of 'application', returns [Mime[:html], Mime[:js], - # Mime[:xml], Mime[:yaml], Mime[:atom], Mime[:json], Mime[:rss], Mime[:url_encoded_form]. - def parse_data_with_trailing_star(type) - Mime::SET.select { |m| m =~ type } - end - - # This method is opposite of register method. - # - # To unregister a MIME type: - # - # Mime::Type.unregister(:mobile) - def unregister(symbol) - symbol = symbol.downcase - if mime = Mime[symbol] - SET.delete_if { |v| v.eql?(mime) } - LOOKUP.delete_if { |_, v| v.eql?(mime) } - EXTENSION_LOOKUP.delete_if { |_, v| v.eql?(mime) } - end - end - end - - attr_reader :hash - - def initialize(string, symbol = nil, synonyms = []) - @symbol, @synonyms = symbol, synonyms - @string = string - @hash = [@string, @synonyms, @symbol].hash - end - - def to_s - @string - end - - def to_str - to_s - end - - def to_sym - @symbol - end - - def ref - symbol || to_s - end - - def ===(list) - if list.is_a?(Array) - (@synonyms + [ self ]).any? { |synonym| list.include?(synonym) } - else - super - end - end - - def ==(mime_type) - return false unless mime_type - (@synonyms + [ self ]).any? do |synonym| - synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym - end - end - - def eql?(other) - super || (self.class == other.class && - @string == other.string && - @synonyms == other.synonyms && - @symbol == other.symbol) - end - - def =~(mime_type) - return false unless mime_type - regexp = Regexp.new(Regexp.quote(mime_type.to_s)) - @synonyms.any? { |synonym| synonym.to_s =~ regexp } || @string =~ regexp - end - - def html? - symbol == :html || @string =~ /html/ - end - - def all?; false; end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :string, :synonyms - - private - - def to_ary; end - def to_a; end - - def method_missing(method, *args) - if method.to_s.ends_with? "?" - method[0..-2].downcase.to_sym == to_sym - else - super - end - end - - def respond_to_missing?(method, include_private = false) - (method.to_s.ends_with? "?") || super - end - end - - class AllType < Type - include Singleton - - def initialize - super "*/*", :all - end - - def all?; true; end - def html?; true; end - end - - # ALL isn't a real MIME type, so we don't register it for lookup with the - # other concrete types. It's a wildcard match that we use for `respond_to` - # negotiation internals. - ALL = AllType.instance - - class NullType - include Singleton - - def nil? - true - end - - def ref; end - - def respond_to_missing?(method, include_private = false) - method.to_s.ends_with? "?" - end - - private - def method_missing(method, *args) - false if method.to_s.ends_with? "?" - end - end -end - -require "action_dispatch/http/mime_types" diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_types.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_types.rb deleted file mode 100644 index 8b04174f1f..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/mime_types.rb +++ /dev/null @@ -1,35 +0,0 @@ -# Build list of Mime types for HTTP responses -# http://www.iana.org/assignments/media-types/ - -Mime::Type.register "text/html", :html, %w( application/xhtml+xml ), %w( xhtml ) -Mime::Type.register "text/plain", :text, [], %w(txt) -Mime::Type.register "text/javascript", :js, %w( application/javascript application/x-javascript ) -Mime::Type.register "text/css", :css -Mime::Type.register "text/calendar", :ics -Mime::Type.register "text/csv", :csv -Mime::Type.register "text/vcard", :vcf - -Mime::Type.register "image/png", :png, [], %w(png) -Mime::Type.register "image/jpeg", :jpeg, [], %w(jpg jpeg jpe pjpeg) -Mime::Type.register "image/gif", :gif, [], %w(gif) -Mime::Type.register "image/bmp", :bmp, [], %w(bmp) -Mime::Type.register "image/tiff", :tiff, [], %w(tif tiff) -Mime::Type.register "image/svg+xml", :svg - -Mime::Type.register "video/mpeg", :mpeg, [], %w(mpg mpeg mpe) - -Mime::Type.register "application/xml", :xml, %w( text/xml application/x-xml ) -Mime::Type.register "application/rss+xml", :rss -Mime::Type.register "application/atom+xml", :atom -Mime::Type.register "application/x-yaml", :yaml, %w( text/yaml ), %w(yml yaml) - -Mime::Type.register "multipart/form-data", :multipart_form -Mime::Type.register "application/x-www-form-urlencoded", :url_encoded_form - -# http://www.ietf.org/rfc/rfc4627.txt -# http://www.json.org/JSONRequest.html -Mime::Type.register "application/json", :json, %w( text/x-json application/jsonrequest ) - -Mime::Type.register "application/pdf", :pdf, [], %w(pdf) -Mime::Type.register "application/zip", :zip, [], %w(zip) -Mime::Type.register "application/gzip", :gzip, %w(application/x-gzip), %w(gz) diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/parameter_filter.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/parameter_filter.rb deleted file mode 100644 index 1d2b4b902b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/parameter_filter.rb +++ /dev/null @@ -1,84 +0,0 @@ -require "active_support/core_ext/object/duplicable" - -module ActionDispatch - module Http - class ParameterFilter - FILTERED = "[FILTERED]".freeze # :nodoc: - - def initialize(filters = []) - @filters = filters - end - - def filter(params) - compiled_filter.call(params) - end - - private - - def compiled_filter - @compiled_filter ||= CompiledFilter.compile(@filters) - end - - class CompiledFilter # :nodoc: - def self.compile(filters) - return lambda { |params| params.dup } if filters.empty? - - strings, regexps, blocks = [], [], [] - - filters.each do |item| - case item - when Proc - blocks << item - when Regexp - regexps << item - else - strings << Regexp.escape(item.to_s) - end - end - - deep_regexps, regexps = regexps.partition { |r| r.to_s.include?("\\.".freeze) } - deep_strings, strings = strings.partition { |s| s.include?("\\.".freeze) } - - regexps << Regexp.new(strings.join("|".freeze), true) unless strings.empty? - deep_regexps << Regexp.new(deep_strings.join("|".freeze), true) unless deep_strings.empty? - - new regexps, deep_regexps, blocks - end - - attr_reader :regexps, :deep_regexps, :blocks - - def initialize(regexps, deep_regexps, blocks) - @regexps = regexps - @deep_regexps = deep_regexps.any? ? deep_regexps : nil - @blocks = blocks - end - - def call(original_params, parents = []) - filtered_params = original_params.class.new - - original_params.each do |key, value| - parents.push(key) if deep_regexps - if regexps.any? { |r| key =~ r } - value = FILTERED - elsif deep_regexps && (joined = parents.join(".")) && deep_regexps.any? { |r| joined =~ r } - value = FILTERED - elsif value.is_a?(Hash) - value = call(value, parents) - elsif value.is_a?(Array) - value = value.map { |v| v.is_a?(Hash) ? call(v, parents) : v } - elsif blocks.any? - key = key.dup if key.duplicable? - value = value.dup if value.duplicable? - blocks.each { |b| b.call(key, value) } - end - parents.pop if deep_regexps - - filtered_params[key] = value - end - - filtered_params - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/parameters.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/parameters.rb deleted file mode 100644 index fb639854c7..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/parameters.rb +++ /dev/null @@ -1,129 +0,0 @@ -module ActionDispatch - module Http - module Parameters - extend ActiveSupport::Concern - - PARAMETERS_KEY = "action_dispatch.request.path_parameters" - - DEFAULT_PARSERS = { - Mime[:json].symbol => -> (raw_post) { - data = ActiveSupport::JSON.decode(raw_post) - data.is_a?(Hash) ? data : { _json: data } - } - } - - # Raised when raw data from the request cannot be parsed by the parser - # defined for request's content mime type. - class ParseError < StandardError - def initialize - super($!.message) - end - end - - included do - class << self - # Returns the parameter parsers. - attr_reader :parameter_parsers - end - - self.parameter_parsers = DEFAULT_PARSERS - end - - module ClassMethods - # Configure the parameter parser for a given mime type. - # - # It accepts a hash where the key is the symbol of the mime type - # and the value is a proc. - # - # original_parsers = ActionDispatch::Request.parameter_parsers - # xml_parser = -> (raw_post) { Hash.from_xml(raw_post) || {} } - # new_parsers = original_parsers.merge(xml: xml_parser) - # ActionDispatch::Request.parameter_parsers = new_parsers - def parameter_parsers=(parsers) - @parameter_parsers = parsers.transform_keys { |key| key.respond_to?(:symbol) ? key.symbol : key } - end - end - - # Returns both GET and POST \parameters in a single hash. - def parameters - params = get_header("action_dispatch.request.parameters") - return params if params - - params = begin - request_parameters.merge(query_parameters) - rescue EOFError - query_parameters.dup - end - params.merge!(path_parameters) - params = set_binary_encoding(params, params[:controller], params[:action]) - set_header("action_dispatch.request.parameters", params) - params - end - alias :params :parameters - - def path_parameters=(parameters) #:nodoc: - delete_header("action_dispatch.request.parameters") - - parameters = set_binary_encoding(parameters, parameters[:controller], parameters[:action]) - # If any of the path parameters has an invalid encoding then - # raise since it's likely to trigger errors further on. - Request::Utils.check_param_encoding(parameters) - - set_header PARAMETERS_KEY, parameters - rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e - raise ActionController::BadRequest.new("Invalid path parameters: #{e.message}") - end - - # Returns a hash with the \parameters used to form the \path of the request. - # Returned hash keys are strings: - # - # {'action' => 'my_action', 'controller' => 'my_controller'} - def path_parameters - get_header(PARAMETERS_KEY) || set_header(PARAMETERS_KEY, {}) - end - - private - - def set_binary_encoding(params, controller, action) - return params unless controller && controller.valid_encoding? - - if binary_params_for?(controller, action) - ActionDispatch::Request::Utils.each_param_value(params) do |param| - param.force_encoding ::Encoding::ASCII_8BIT - end - end - params - end - - def binary_params_for?(controller, action) - controller_class_for(controller).binary_params_for?(action) - rescue NameError - false - end - - def parse_formatted_parameters(parsers) - return yield if content_length.zero? || content_mime_type.nil? - - strategy = parsers.fetch(content_mime_type.symbol) { return yield } - - begin - strategy.call(raw_post) - rescue # JSON or Ruby code block errors - my_logger = logger || ActiveSupport::Logger.new($stderr) - my_logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{raw_post}" - - raise ParseError - end - end - - def params_parsers - ActionDispatch::Request.parameter_parsers - end - end - end - - module ParamsParser - include ActiveSupport::Deprecation::DeprecatedConstantAccessor - deprecate_constant "ParseError", "ActionDispatch::Http::Parameters::ParseError" - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/rack_cache.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/rack_cache.rb deleted file mode 100644 index 003ae4029d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/rack_cache.rb +++ /dev/null @@ -1,61 +0,0 @@ -require "rack/cache" -require "rack/cache/context" -require "active_support/cache" - -module ActionDispatch - class RailsMetaStore < Rack::Cache::MetaStore - def self.resolve(uri) - new - end - - def initialize(store = Rails.cache) - @store = store - end - - def read(key) - if data = @store.read(key) - Marshal.load(data) - else - [] - end - end - - def write(key, value) - @store.write(key, Marshal.dump(value)) - end - - ::Rack::Cache::MetaStore::RAILS = self - end - - class RailsEntityStore < Rack::Cache::EntityStore - def self.resolve(uri) - new - end - - def initialize(store = Rails.cache) - @store = store - end - - def exist?(key) - @store.exist?(key) - end - - def open(key) - @store.read(key) - end - - def read(key) - body = open(key) - body.join if body - end - - def write(body) - buf = [] - key, size = slurp(body) { |part| buf << part } - @store.write(key, buf) - [key, size] - end - - ::Rack::Cache::EntityStore::RAILS = self - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/request.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/request.rb deleted file mode 100644 index 1f774dbfc5..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/request.rb +++ /dev/null @@ -1,410 +0,0 @@ -require "stringio" - -require "active_support/inflector" -require "action_dispatch/http/headers" -require "action_controller/metal/exceptions" -require "rack/request" -require "action_dispatch/http/cache" -require "action_dispatch/http/mime_negotiation" -require "action_dispatch/http/parameters" -require "action_dispatch/http/filter_parameters" -require "action_dispatch/http/upload" -require "action_dispatch/http/url" -require "active_support/core_ext/array/conversions" - -module ActionDispatch - class Request - include Rack::Request::Helpers - include ActionDispatch::Http::Cache::Request - include ActionDispatch::Http::MimeNegotiation - include ActionDispatch::Http::Parameters - include ActionDispatch::Http::FilterParameters - include ActionDispatch::Http::URL - include Rack::Request::Env - - autoload :Session, "action_dispatch/request/session" - autoload :Utils, "action_dispatch/request/utils" - - LOCALHOST = Regexp.union [/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/] - - ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE - PATH_TRANSLATED REMOTE_HOST - REMOTE_IDENT REMOTE_USER REMOTE_ADDR - SERVER_NAME SERVER_PROTOCOL - ORIGINAL_SCRIPT_NAME - - HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING - HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM - HTTP_NEGOTIATE HTTP_PRAGMA HTTP_CLIENT_IP - HTTP_X_FORWARDED_FOR HTTP_ORIGIN HTTP_VERSION - HTTP_X_CSRF_TOKEN HTTP_X_REQUEST_ID HTTP_X_FORWARDED_HOST - SERVER_ADDR - ].freeze - - ENV_METHODS.each do |env| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{env.sub(/^HTTP_/n, '').downcase} # def accept_charset - get_header "#{env}".freeze # get_header "HTTP_ACCEPT_CHARSET".freeze - end # end - METHOD - end - - def self.empty - new({}) - end - - def initialize(env) - super - @method = nil - @request_method = nil - @remote_ip = nil - @original_fullpath = nil - @fullpath = nil - @ip = nil - end - - def commit_cookie_jar! # :nodoc: - end - - PASS_NOT_FOUND = Class.new { # :nodoc: - def self.action(_); self; end - def self.call(_); [404, { "X-Cascade" => "pass" }, []]; end - def self.binary_params_for?(action); false; end - } - - def controller_class - params = path_parameters - params[:action] ||= "index" - controller_class_for(params[:controller]) - end - - def controller_class_for(name) - if name - controller_param = name.underscore - const_name = "#{controller_param.camelize}Controller" - ActiveSupport::Dependencies.constantize(const_name) - else - PASS_NOT_FOUND - end - end - - # Returns true if the request has a header matching the given key parameter. - # - # request.key? :ip_spoofing_check # => true - def key?(key) - has_header? key - end - - # List of HTTP request methods from the following RFCs: - # Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt) - # HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt) - # Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt) - # Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt) - # Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt) - # Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt) - # Calendar Extensions to WebDAV (http://www.ietf.org/rfc/rfc4791.txt) - # PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt) - RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT) - RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK) - RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY) - RFC3648 = %w(ORDERPATCH) - RFC3744 = %w(ACL) - RFC5323 = %w(SEARCH) - RFC4791 = %w(MKCALENDAR) - RFC5789 = %w(PATCH) - - HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC4791 + RFC5789 - - HTTP_METHOD_LOOKUP = {} - - # Populate the HTTP method lookup cache - HTTP_METHODS.each { |method| - HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym - } - - # Returns the HTTP \method that the application should see. - # In the case where the \method was overridden by a middleware - # (for instance, if a HEAD request was converted to a GET, - # or if a _method parameter was used to determine the \method - # the application should use), this \method returns the overridden - # value, not the original. - def request_method - @request_method ||= check_method(super) - end - - def routes # :nodoc: - get_header("action_dispatch.routes".freeze) - end - - def routes=(routes) # :nodoc: - set_header("action_dispatch.routes".freeze, routes) - end - - def engine_script_name(_routes) # :nodoc: - get_header(_routes.env_key) - end - - def engine_script_name=(name) # :nodoc: - set_header(routes.env_key, name.dup) - end - - def request_method=(request_method) #:nodoc: - if check_method(request_method) - @request_method = set_header("REQUEST_METHOD", request_method) - end - end - - def controller_instance # :nodoc: - get_header("action_controller.instance".freeze) - end - - def controller_instance=(controller) # :nodoc: - set_header("action_controller.instance".freeze, controller) - end - - def http_auth_salt - get_header "action_dispatch.http_auth_salt" - end - - def show_exceptions? # :nodoc: - # We're treating `nil` as "unset", and we want the default setting to be - # `true`. This logic should be extracted to `env_config` and calculated - # once. - !(get_header("action_dispatch.show_exceptions".freeze) == false) - end - - # Returns a symbol form of the #request_method - def request_method_symbol - HTTP_METHOD_LOOKUP[request_method] - end - - # Returns the original value of the environment's REQUEST_METHOD, - # even if it was overridden by middleware. See #request_method for - # more information. - def method - @method ||= check_method(get_header("rack.methodoverride.original_method") || get_header("REQUEST_METHOD")) - end - - # Returns a symbol form of the #method - def method_symbol - HTTP_METHOD_LOOKUP[method] - end - - # Provides access to the request's HTTP headers, for example: - # - # request.headers["Content-Type"] # => "text/plain" - def headers - @headers ||= Http::Headers.new(self) - end - - # Returns a +String+ with the last requested path including their params. - # - # # get '/foo' - # request.original_fullpath # => '/foo' - # - # # get '/foo?bar' - # request.original_fullpath # => '/foo?bar' - def original_fullpath - @original_fullpath ||= (get_header("ORIGINAL_FULLPATH") || fullpath) - end - - # Returns the +String+ full path including params of the last URL requested. - # - # # get "/articles" - # request.fullpath # => "/articles" - # - # # get "/articles?page=2" - # request.fullpath # => "/articles?page=2" - def fullpath - @fullpath ||= super - end - - # Returns the original request URL as a +String+. - # - # # get "/articles?page=2" - # request.original_url # => "http://www.example.com/articles?page=2" - def original_url - base_url + original_fullpath - end - - # The +String+ MIME type of the request. - # - # # get "/articles" - # request.media_type # => "application/x-www-form-urlencoded" - def media_type - content_mime_type.to_s - end - - # Returns the content length of the request as an integer. - def content_length - super.to_i - end - - # Returns true if the "X-Requested-With" header contains "XMLHttpRequest" - # (case-insensitive), which may need to be manually added depending on the - # choice of JavaScript libraries and frameworks. - def xml_http_request? - get_header("HTTP_X_REQUESTED_WITH") =~ /XMLHttpRequest/i - end - alias :xhr? :xml_http_request? - - # Returns the IP address of client as a +String+. - def ip - @ip ||= super - end - - # Returns the IP address of client as a +String+, - # usually set by the RemoteIp middleware. - def remote_ip - @remote_ip ||= (get_header("action_dispatch.remote_ip") || ip).to_s - end - - def remote_ip=(remote_ip) - set_header "action_dispatch.remote_ip".freeze, remote_ip - end - - ACTION_DISPATCH_REQUEST_ID = "action_dispatch.request_id".freeze # :nodoc: - - # Returns the unique request id, which is based on either the X-Request-Id header that can - # be generated by a firewall, load balancer, or web server or by the RequestId middleware - # (which sets the action_dispatch.request_id environment variable). - # - # This unique ID is useful for tracing a request from end-to-end as part of logging or debugging. - # This relies on the rack variable set by the ActionDispatch::RequestId middleware. - def request_id - get_header ACTION_DISPATCH_REQUEST_ID - end - - def request_id=(id) # :nodoc: - set_header ACTION_DISPATCH_REQUEST_ID, id - end - - alias_method :uuid, :request_id - - # Returns the lowercase name of the HTTP server software. - def server_software - (get_header("SERVER_SOFTWARE") && /^([a-zA-Z]+)/ =~ get_header("SERVER_SOFTWARE")) ? $1.downcase : nil - end - - # Read the request \body. This is useful for web services that need to - # work with raw requests directly. - def raw_post - unless has_header? "RAW_POST_DATA" - raw_post_body = body - set_header("RAW_POST_DATA", raw_post_body.read(content_length)) - raw_post_body.rewind if raw_post_body.respond_to?(:rewind) - end - get_header "RAW_POST_DATA" - end - - # The request body is an IO input stream. If the RAW_POST_DATA environment - # variable is already set, wrap it in a StringIO. - def body - if raw_post = get_header("RAW_POST_DATA") - raw_post.force_encoding(Encoding::BINARY) - StringIO.new(raw_post) - else - body_stream - end - end - - # Determine whether the request body contains form-data by checking - # the request Content-Type for one of the media-types: - # "application/x-www-form-urlencoded" or "multipart/form-data". The - # list of form-data media types can be modified through the - # +FORM_DATA_MEDIA_TYPES+ array. - # - # A request body is not assumed to contain form-data when no - # Content-Type header is provided and the request_method is POST. - def form_data? - FORM_DATA_MEDIA_TYPES.include?(media_type) - end - - def body_stream #:nodoc: - get_header("rack.input") - end - - # TODO This should be broken apart into AD::Request::Session and probably - # be included by the session middleware. - def reset_session - if session && session.respond_to?(:destroy) - session.destroy - else - self.session = {} - end - end - - def session=(session) #:nodoc: - Session.set self, session - end - - def session_options=(options) - Session::Options.set self, options - end - - # Override Rack's GET method to support indifferent access - def GET - fetch_header("action_dispatch.request.query_parameters") do |k| - rack_query_params = super || {} - # Check for non UTF-8 parameter values, which would cause errors later - Request::Utils.check_param_encoding(rack_query_params) - set_header k, Request::Utils.normalize_encode_params(rack_query_params) - end - rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e - raise ActionController::BadRequest.new("Invalid query parameters: #{e.message}") - end - alias :query_parameters :GET - - # Override Rack's POST method to support indifferent access - def POST - fetch_header("action_dispatch.request.request_parameters") do - pr = parse_formatted_parameters(params_parsers) do |params| - super || {} - end - self.request_parameters = Request::Utils.normalize_encode_params(pr) - end - rescue Http::Parameters::ParseError # one of the parse strategies blew up - self.request_parameters = Request::Utils.normalize_encode_params(super || {}) - raise - rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e - raise ActionController::BadRequest.new("Invalid request parameters: #{e.message}") - end - alias :request_parameters :POST - - # Returns the authorization header regardless of whether it was specified directly or through one of the - # proxy alternatives. - def authorization - get_header("HTTP_AUTHORIZATION") || - get_header("X-HTTP_AUTHORIZATION") || - get_header("X_HTTP_AUTHORIZATION") || - get_header("REDIRECT_X_HTTP_AUTHORIZATION") - end - - # True if the request came from localhost, 127.0.0.1, or ::1. - def local? - LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip - end - - def request_parameters=(params) - raise if params.nil? - set_header("action_dispatch.request.request_parameters".freeze, params) - end - - def logger - get_header("action_dispatch.logger".freeze) - end - - def commit_flash - end - - def ssl? - super || scheme == "wss".freeze - end - - private - def check_method(name) - HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS[0...-1].join(', ')}, and #{HTTP_METHODS[-1]}") - name - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/response.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/response.rb deleted file mode 100644 index dc159596c4..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/response.rb +++ /dev/null @@ -1,518 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" -require "action_dispatch/http/filter_redirect" -require "action_dispatch/http/cache" -require "monitor" - -module ActionDispatch # :nodoc: - # Represents an HTTP response generated by a controller action. Use it to - # retrieve the current state of the response, or customize the response. It can - # either represent a real HTTP response (i.e. one that is meant to be sent - # back to the web browser) or a TestResponse (i.e. one that is generated - # from integration tests). - # - # \Response is mostly a Ruby on \Rails framework implementation detail, and - # should never be used directly in controllers. Controllers should use the - # methods defined in ActionController::Base instead. For example, if you want - # to set the HTTP response's content MIME type, then use - # ActionControllerBase#headers instead of Response#headers. - # - # Nevertheless, integration tests may want to inspect controller responses in - # more detail, and that's when \Response can be useful for application - # developers. Integration test methods such as - # ActionDispatch::Integration::Session#get and - # ActionDispatch::Integration::Session#post return objects of type - # TestResponse (which are of course also of type \Response). - # - # For example, the following demo integration test prints the body of the - # controller response to the console: - # - # class DemoControllerTest < ActionDispatch::IntegrationTest - # def test_print_root_path_to_console - # get('/') - # puts response.body - # end - # end - class Response - class Header < DelegateClass(Hash) # :nodoc: - def initialize(response, header) - @response = response - super(header) - end - - def []=(k, v) - if @response.sending? || @response.sent? - raise ActionDispatch::IllegalStateError, "header already sent" - end - - super - end - - def merge(other) - self.class.new @response, __getobj__.merge(other) - end - - def to_hash - __getobj__.dup - end - end - - # The request that the response is responding to. - attr_accessor :request - - # The HTTP status code. - attr_reader :status - - # Get headers for this response. - attr_reader :header - - alias_method :headers, :header - - delegate :[], :[]=, to: :@header - - def each(&block) - sending! - x = @stream.each(&block) - sent! - x - end - - CONTENT_TYPE = "Content-Type".freeze - SET_COOKIE = "Set-Cookie".freeze - LOCATION = "Location".freeze - NO_CONTENT_CODES = [100, 101, 102, 204, 205, 304] - - cattr_accessor(:default_charset) { "utf-8" } - cattr_accessor(:default_headers) - - include Rack::Response::Helpers - # Aliasing these off because AD::Http::Cache::Response defines them - alias :_cache_control :cache_control - alias :_cache_control= :cache_control= - - include ActionDispatch::Http::FilterRedirect - include ActionDispatch::Http::Cache::Response - include MonitorMixin - - class Buffer # :nodoc: - def initialize(response, buf) - @response = response - @buf = buf - @closed = false - @str_body = nil - end - - def body - @str_body ||= begin - buf = "" - each { |chunk| buf << chunk } - buf - end - end - - def write(string) - raise IOError, "closed stream" if closed? - - @str_body = nil - @response.commit! - @buf.push string - end - - def each(&block) - if @str_body - return enum_for(:each) unless block_given? - - yield @str_body - else - each_chunk(&block) - end - end - - def abort - end - - def close - @response.commit! - @closed = true - end - - def closed? - @closed - end - - private - - def each_chunk(&block) - @buf.each(&block) # extract into own method - end - end - - def self.create(status = 200, header = {}, body = [], default_headers: self.default_headers) - header = merge_default_headers(header, default_headers) - new status, header, body - end - - def self.merge_default_headers(original, default) - default.respond_to?(:merge) ? default.merge(original) : original - end - - # The underlying body, as a streamable object. - attr_reader :stream - - def initialize(status = 200, header = {}, body = []) - super() - - @header = Header.new(self, header) - - self.body, self.status = body, status - - @cv = new_cond - @committed = false - @sending = false - @sent = false - - prepare_cache_control! - - yield self if block_given? - end - - def has_header?(key); headers.key? key; end - def get_header(key); headers[key]; end - def set_header(key, v); headers[key] = v; end - def delete_header(key); headers.delete key; end - - def await_commit - synchronize do - @cv.wait_until { @committed } - end - end - - def await_sent - synchronize { @cv.wait_until { @sent } } - end - - def commit! - synchronize do - before_committed - @committed = true - @cv.broadcast - end - end - - def sending! - synchronize do - before_sending - @sending = true - @cv.broadcast - end - end - - def sent! - synchronize do - @sent = true - @cv.broadcast - end - end - - def sending?; synchronize { @sending }; end - def committed?; synchronize { @committed }; end - def sent?; synchronize { @sent }; end - - # Sets the HTTP status code. - def status=(status) - @status = Rack::Utils.status_code(status) - end - - # Sets the HTTP content type. - def content_type=(content_type) - return unless content_type - new_header_info = parse_content_type(content_type.to_s) - prev_header_info = parsed_content_type_header - charset = new_header_info.charset || prev_header_info.charset - charset ||= self.class.default_charset unless prev_header_info.mime_type - set_content_type new_header_info.mime_type, charset - end - - # Sets the HTTP response's content MIME type. For example, in the controller - # you could write this: - # - # response.content_type = "text/plain" - # - # If a character set has been defined for this response (see charset=) then - # the character set information will also be included in the content type - # information. - - def content_type - parsed_content_type_header.mime_type - end - - def sending_file=(v) - if true == v - self.charset = false - end - end - - # Sets the HTTP character set. In case of +nil+ parameter - # it sets the charset to utf-8. - # - # response.charset = 'utf-16' # => 'utf-16' - # response.charset = nil # => 'utf-8' - def charset=(charset) - header_info = parsed_content_type_header - if false == charset - set_header CONTENT_TYPE, header_info.mime_type - else - content_type = header_info.mime_type - set_content_type content_type, charset || self.class.default_charset - end - end - - # The charset of the response. HTML wants to know the encoding of the - # content you're giving them, so we need to send that along. - def charset - header_info = parsed_content_type_header - header_info.charset || self.class.default_charset - end - - # The response code of the request. - def response_code - @status - end - - # Returns a string to ensure compatibility with Net::HTTPResponse. - def code - @status.to_s - end - - # Returns the corresponding message for the current HTTP status code: - # - # response.status = 200 - # response.message # => "OK" - # - # response.status = 404 - # response.message # => "Not Found" - # - def message - Rack::Utils::HTTP_STATUS_CODES[@status] - end - alias_method :status_message, :message - - # Returns the content of the response as a string. This contains the contents - # of any calls to render. - def body - @stream.body - end - - def write(string) - @stream.write string - end - - # Allows you to manually set or override the response body. - def body=(body) - if body.respond_to?(:to_path) - @stream = body - else - synchronize do - @stream = build_buffer self, munge_body_object(body) - end - end - end - - # Avoid having to pass an open file handle as the response body. - # Rack::Sendfile will usually intercept the response and uses - # the path directly, so there is no reason to open the file. - class FileBody #:nodoc: - attr_reader :to_path - - def initialize(path) - @to_path = path - end - - def body - File.binread(to_path) - end - - # Stream the file's contents if Rack::Sendfile isn't present. - def each - File.open(to_path, "rb") do |file| - while chunk = file.read(16384) - yield chunk - end - end - end - end - - # Send the file stored at +path+ as the response body. - def send_file(path) - commit! - @stream = FileBody.new(path) - end - - def reset_body! - @stream = build_buffer(self, []) - end - - def body_parts - parts = [] - @stream.each { |x| parts << x } - parts - end - - # The location header we'll be responding with. - alias_method :redirect_url, :location - - def close - stream.close if stream.respond_to?(:close) - end - - def abort - if stream.respond_to?(:abort) - stream.abort - elsif stream.respond_to?(:close) - # `stream.close` should really be reserved for a close from the - # other direction, but we must fall back to it for - # compatibility. - stream.close - end - end - - # Turns the Response into a Rack-compatible array of the status, headers, - # and body. Allows explicit splatting: - # - # status, headers, body = *response - def to_a - commit! - rack_response @status, @header.to_hash - end - alias prepare! to_a - - # Returns the response cookies, converted to a Hash of (name => value) pairs - # - # assert_equal 'AuthorOfNewPage', r.cookies['author'] - def cookies - cookies = {} - if header = get_header(SET_COOKIE) - header = header.split("\n") if header.respond_to?(:to_str) - header.each do |cookie| - if pair = cookie.split(";").first - key, value = pair.split("=").map { |v| Rack::Utils.unescape(v) } - cookies[key] = value - end - end - end - cookies - end - - private - - ContentTypeHeader = Struct.new :mime_type, :charset - NullContentTypeHeader = ContentTypeHeader.new nil, nil - - def parse_content_type(content_type) - if content_type - type, charset = content_type.split(/;\s*charset=/) - type = nil if type && type.empty? - ContentTypeHeader.new(type, charset) - else - NullContentTypeHeader - end - end - - # Small internal convenience method to get the parsed version of the current - # content type header. - def parsed_content_type_header - parse_content_type(get_header(CONTENT_TYPE)) - end - - def set_content_type(content_type, charset) - type = (content_type || "").dup - type << "; charset=#{charset.to_s.downcase}" if charset - set_header CONTENT_TYPE, type - end - - def before_committed - return if committed? - assign_default_content_type_and_charset! - handle_conditional_get! - handle_no_content! - end - - def before_sending - # Normally we've already committed by now, but it's possible - # (e.g., if the controller action tries to read back its own - # response) to get here before that. In that case, we must force - # an "early" commit: we're about to freeze the headers, so this is - # our last chance. - commit! unless committed? - - headers.freeze - request.commit_cookie_jar! unless committed? - end - - def build_buffer(response, body) - Buffer.new response, body - end - - def munge_body_object(body) - body.respond_to?(:each) ? body : [body] - end - - def assign_default_content_type_and_charset! - return if content_type - - ct = parsed_content_type_header - set_content_type(ct.mime_type || Mime[:html].to_s, - ct.charset || self.class.default_charset) - end - - class RackBody - def initialize(response) - @response = response - end - - def each(*args, &block) - @response.each(*args, &block) - end - - def close - # Rack "close" maps to Response#abort, and *not* Response#close - # (which is used when the controller's finished writing) - @response.abort - end - - def body - @response.body - end - - def respond_to?(method, include_private = false) - if method.to_s == "to_path" - @response.stream.respond_to?(method) - else - super - end - end - - def to_path - @response.stream.to_path - end - - def to_ary - nil - end - end - - def handle_no_content! - if NO_CONTENT_CODES.include?(@status) - @header.delete CONTENT_TYPE - @header.delete "Content-Length" - end - end - - def rack_response(status, header) - if NO_CONTENT_CODES.include?(status) - [status, header, []] - else - [status, header, RackBody.new(self)] - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/upload.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/upload.rb deleted file mode 100644 index 225272d66e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/upload.rb +++ /dev/null @@ -1,82 +0,0 @@ -module ActionDispatch - module Http - # Models uploaded files. - # - # The actual file is accessible via the +tempfile+ accessor, though some - # of its interface is available directly for convenience. - # - # Uploaded files are temporary files whose lifespan is one request. When - # the object is finalized Ruby unlinks the file, so there is no need to - # clean them with a separate maintenance task. - class UploadedFile - # The basename of the file in the client. - attr_accessor :original_filename - - # A string with the MIME type of the file. - attr_accessor :content_type - - # A +Tempfile+ object with the actual uploaded file. Note that some of - # its interface is available directly. - attr_accessor :tempfile - alias :to_io :tempfile - - # A string with the headers of the multipart request. - attr_accessor :headers - - def initialize(hash) # :nodoc: - @tempfile = hash[:tempfile] - raise(ArgumentError, ":tempfile is required") unless @tempfile - - if hash[:filename] - @original_filename = hash[:filename].dup - - begin - @original_filename.encode!(Encoding::UTF_8) - rescue EncodingError - @original_filename.force_encoding(Encoding::UTF_8) - end - else - @original_filename = nil - end - - @content_type = hash[:type] - @headers = hash[:head] - end - - # Shortcut for +tempfile.read+. - def read(length = nil, buffer = nil) - @tempfile.read(length, buffer) - end - - # Shortcut for +tempfile.open+. - def open - @tempfile.open - end - - # Shortcut for +tempfile.close+. - def close(unlink_now = false) - @tempfile.close(unlink_now) - end - - # Shortcut for +tempfile.path+. - def path - @tempfile.path - end - - # Shortcut for +tempfile.rewind+. - def rewind - @tempfile.rewind - end - - # Shortcut for +tempfile.size+. - def size - @tempfile.size - end - - # Shortcut for +tempfile.eof?+. - def eof? - @tempfile.eof? - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/url.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/url.rb deleted file mode 100644 index a6937d54ff..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/http/url.rb +++ /dev/null @@ -1,351 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" - -module ActionDispatch - module Http - module URL - IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ - HOST_REGEXP = /(^[^:]+:\/\/)?(\[[^\]]+\]|[^:]+)(?::(\d+$))?/ - PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/ - - mattr_accessor :tld_length - self.tld_length = 1 - - class << self - # Returns the domain part of a host given the domain level. - # - # # Top-level domain example - # extract_domain('www.example.com', 1) # => "example.com" - # # Second-level domain example - # extract_domain('dev.www.example.co.uk', 2) # => "example.co.uk" - def extract_domain(host, tld_length) - extract_domain_from(host, tld_length) if named_host?(host) - end - - # Returns the subdomains of a host as an Array given the domain level. - # - # # Top-level domain example - # extract_subdomains('www.example.com', 1) # => ["www"] - # # Second-level domain example - # extract_subdomains('dev.www.example.co.uk', 2) # => ["dev", "www"] - def extract_subdomains(host, tld_length) - if named_host?(host) - extract_subdomains_from(host, tld_length) - else - [] - end - end - - # Returns the subdomains of a host as a String given the domain level. - # - # # Top-level domain example - # extract_subdomain('www.example.com', 1) # => "www" - # # Second-level domain example - # extract_subdomain('dev.www.example.co.uk', 2) # => "dev.www" - def extract_subdomain(host, tld_length) - extract_subdomains(host, tld_length).join(".") - end - - def url_for(options) - if options[:only_path] - path_for options - else - full_url_for options - end - end - - def full_url_for(options) - host = options[:host] - protocol = options[:protocol] - port = options[:port] - - unless host - raise ArgumentError, "Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true" - end - - build_host_url(host, port, protocol, options, path_for(options)) - end - - def path_for(options) - path = options[:script_name].to_s.chomp("/".freeze) - path << options[:path] if options.key?(:path) - - add_trailing_slash(path) if options[:trailing_slash] - add_params(path, options[:params]) if options.key?(:params) - add_anchor(path, options[:anchor]) if options.key?(:anchor) - - path - end - - private - - def add_params(path, params) - params = { params: params } unless params.is_a?(Hash) - params.reject! { |_, v| v.to_param.nil? } - query = params.to_query - path << "?#{query}" unless query.empty? - end - - def add_anchor(path, anchor) - if anchor - path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param)}" - end - end - - def extract_domain_from(host, tld_length) - host.split(".").last(1 + tld_length).join(".") - end - - def extract_subdomains_from(host, tld_length) - parts = host.split(".") - parts[0..-(tld_length + 2)] - end - - def add_trailing_slash(path) - # includes querysting - if path.include?("?") - path.sub!(/\?/, '/\&') - # does not have a .format - elsif !path.include?(".") - path.sub!(/[^\/]\z|\A\z/, '\&/') - end - end - - def build_host_url(host, port, protocol, options, path) - if match = host.match(HOST_REGEXP) - protocol ||= match[1] unless protocol == false - host = match[2] - port = match[3] unless options.key? :port - end - - protocol = normalize_protocol protocol - host = normalize_host(host, options) - - result = protocol.dup - - if options[:user] && options[:password] - result << "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@" - end - - result << host - normalize_port(port, protocol) { |normalized_port| - result << ":#{normalized_port}" - } - - result.concat path - end - - def named_host?(host) - IP_HOST_REGEXP !~ host - end - - def normalize_protocol(protocol) - case protocol - when nil - "http://" - when false, "//" - "//" - when PROTOCOL_REGEXP - "#{$1}://" - else - raise ArgumentError, "Invalid :protocol option: #{protocol.inspect}" - end - end - - def normalize_host(_host, options) - return _host unless named_host?(_host) - - tld_length = options[:tld_length] || @@tld_length - subdomain = options.fetch :subdomain, true - domain = options[:domain] - - host = "" - if subdomain == true - return _host if domain.nil? - - host << extract_subdomains_from(_host, tld_length).join(".") - elsif subdomain - host << subdomain.to_param - end - host << "." unless host.empty? - host << (domain || extract_domain_from(_host, tld_length)) - host - end - - def normalize_port(port, protocol) - return unless port - - case protocol - when "//" then yield port - when "https://" - yield port unless port.to_i == 443 - else - yield port unless port.to_i == 80 - end - end - end - - def initialize - super - @protocol = nil - @port = nil - end - - # Returns the complete URL used for this request. - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com' - # req.url # => "http://example.com" - def url - protocol + host_with_port + fullpath - end - - # Returns 'https://' if this is an SSL request and 'http://' otherwise. - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com' - # req.protocol # => "http://" - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com', 'HTTPS' => 'on' - # req.protocol # => "https://" - def protocol - @protocol ||= ssl? ? "https://" : "http://" - end - - # Returns the \host and port for this request, such as "example.com:8080". - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com' - # req.raw_host_with_port # => "example.com" - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:80' - # req.raw_host_with_port # => "example.com:80" - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.raw_host_with_port # => "example.com:8080" - def raw_host_with_port - if forwarded = x_forwarded_host.presence - forwarded.split(/,\s?/).last - else - get_header("HTTP_HOST") || "#{server_name || server_addr}:#{get_header('SERVER_PORT')}" - end - end - - # Returns the host for this request, such as "example.com". - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.host # => "example.com" - def host - raw_host_with_port.sub(/:\d+$/, "".freeze) - end - - # Returns a \host:\port string for this request, such as "example.com" or - # "example.com:8080". Port is only included if it is not a default port - # (80 or 443) - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com' - # req.host_with_port # => "example.com" - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:80' - # req.host_with_port # => "example.com" - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.host_with_port # => "example.com:8080" - def host_with_port - "#{host}#{port_string}" - end - - # Returns the port number of this request as an integer. - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com' - # req.port # => 80 - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.port # => 8080 - def port - @port ||= begin - if raw_host_with_port =~ /:(\d+)$/ - $1.to_i - else - standard_port - end - end - end - - # Returns the standard \port number for this request's protocol. - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.standard_port # => 80 - def standard_port - case protocol - when "https://" then 443 - else 80 - end - end - - # Returns whether this request is using the standard port - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:80' - # req.standard_port? # => true - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.standard_port? # => false - def standard_port? - port == standard_port - end - - # Returns a number \port suffix like 8080 if the \port number of this request - # is not the default HTTP \port 80 or HTTPS \port 443. - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:80' - # req.optional_port # => nil - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.optional_port # => 8080 - def optional_port - standard_port? ? nil : port - end - - # Returns a string \port suffix, including colon, like ":8080" if the \port - # number of this request is not the default HTTP \port 80 or HTTPS \port 443. - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:80' - # req.port_string # => "" - # - # req = ActionDispatch::Request.new 'HTTP_HOST' => 'example.com:8080' - # req.port_string # => ":8080" - def port_string - standard_port? ? "" : ":#{port}" - end - - # Returns the requested port, such as 8080, based on SERVER_PORT - # - # req = ActionDispatch::Request.new 'SERVER_PORT' => '80' - # req.server_port # => 80 - # - # req = ActionDispatch::Request.new 'SERVER_PORT' => '8080' - # req.server_port # => 8080 - def server_port - get_header("SERVER_PORT").to_i - end - - # Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify - # a different tld_length, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk". - def domain(tld_length = @@tld_length) - ActionDispatch::Http::URL.extract_domain(host, tld_length) - end - - # Returns all the \subdomains as an array, so ["dev", "www"] would be - # returned for "dev.www.rubyonrails.org". You can specify a different tld_length, - # such as 2 to catch ["www"] instead of ["www", "rubyonrails"] - # in "www.rubyonrails.co.uk". - def subdomains(tld_length = @@tld_length) - ActionDispatch::Http::URL.extract_subdomains(host, tld_length) - end - - # Returns all the \subdomains as a string, so "dev.www" would be - # returned for "dev.www.rubyonrails.org". You can specify a different tld_length, - # such as 2 to catch "www" instead of "www.rubyonrails" - # in "www.rubyonrails.co.uk". - def subdomain(tld_length = @@tld_length) - ActionDispatch::Http::URL.extract_subdomain(host, tld_length) - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey.rb deleted file mode 100644 index d1cfc51f3e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "action_dispatch/journey/router" -require "action_dispatch/journey/gtg/builder" -require "action_dispatch/journey/gtg/simulator" -require "action_dispatch/journey/nfa/builder" -require "action_dispatch/journey/nfa/simulator" diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/formatter.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/formatter.rb deleted file mode 100644 index f3b8e82d32..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/formatter.rb +++ /dev/null @@ -1,187 +0,0 @@ -require "action_controller/metal/exceptions" - -module ActionDispatch - # :stopdoc: - module Journey - # The Formatter class is used for formatting URLs. For example, parameters - # passed to +url_for+ in Rails will eventually call Formatter#generate. - class Formatter - attr_reader :routes - - def initialize(routes) - @routes = routes - @cache = nil - end - - def generate(name, options, path_parameters, parameterize = nil) - constraints = path_parameters.merge(options) - missing_keys = nil # need for variable scope - - match_route(name, constraints) do |route| - parameterized_parts = extract_parameterized_parts(route, options, path_parameters, parameterize) - - # Skip this route unless a name has been provided or it is a - # standard Rails route since we can't determine whether an options - # hash passed to url_for matches a Rack application or a redirect. - next unless name || route.dispatcher? - - missing_keys = missing_keys(route, parameterized_parts) - next if missing_keys && !missing_keys.empty? - params = options.dup.delete_if do |key, _| - parameterized_parts.key?(key) || route.defaults.key?(key) - end - - defaults = route.defaults - required_parts = route.required_parts - - route.parts.reverse_each do |key| - break if defaults[key].nil? && parameterized_parts[key].present? - next if parameterized_parts[key].to_s != defaults[key].to_s - break if required_parts.include?(key) - - parameterized_parts.delete(key) - end - - return [route.format(parameterized_parts), params] - end - - unmatched_keys = (missing_keys || []) & constraints.keys - missing_keys = (missing_keys || []) - unmatched_keys - - message = "No route matches #{Hash[constraints.sort_by { |k, v| k.to_s }].inspect}" - message << ", missing required keys: #{missing_keys.sort.inspect}" if missing_keys && !missing_keys.empty? - message << ", possible unmatched constraints: #{unmatched_keys.sort.inspect}" if unmatched_keys && !unmatched_keys.empty? - - raise ActionController::UrlGenerationError, message - end - - def clear - @cache = nil - end - - private - - def extract_parameterized_parts(route, options, recall, parameterize = nil) - parameterized_parts = recall.merge(options) - - keys_to_keep = route.parts.reverse_each.drop_while { |part| - !options.key?(part) || (options[part] || recall[part]).nil? - } | route.required_parts - - parameterized_parts.delete_if do |bad_key, _| - !keys_to_keep.include?(bad_key) - end - - if parameterize - parameterized_parts.each do |k, v| - parameterized_parts[k] = parameterize.call(k, v) - end - end - - parameterized_parts.keep_if { |_, v| v } - parameterized_parts - end - - def named_routes - routes.named_routes - end - - def match_route(name, options) - if named_routes.key?(name) - yield named_routes[name] - else - routes = non_recursive(cache, options) - - supplied_keys = options.each_with_object({}) do |(k, v), h| - h[k.to_s] = true if v - end - - hash = routes.group_by { |_, r| r.score(supplied_keys) } - - hash.keys.sort.reverse_each do |score| - break if score < 0 - - hash[score].sort_by { |i, _| i }.each do |_, route| - yield route - end - end - end - end - - def non_recursive(cache, options) - routes = [] - queue = [cache] - - while queue.any? - c = queue.shift - routes.concat(c[:___routes]) if c.key?(:___routes) - - options.each do |pair| - queue << c[pair] if c.key?(pair) - end - end - - routes - end - - module RegexCaseComparator - DEFAULT_INPUT = /[-_.a-zA-Z0-9]+\/[-_.a-zA-Z0-9]+/ - DEFAULT_REGEX = /\A#{DEFAULT_INPUT}\Z/ - - def self.===(regex) - DEFAULT_INPUT == regex - end - end - - # Returns an array populated with missing keys if any are present. - def missing_keys(route, parts) - missing_keys = nil - tests = route.path.requirements - route.required_parts.each { |key| - case tests[key] - when nil - unless parts[key] - missing_keys ||= [] - missing_keys << key - end - when RegexCaseComparator - unless RegexCaseComparator::DEFAULT_REGEX === parts[key] - missing_keys ||= [] - missing_keys << key - end - else - unless /\A#{tests[key]}\Z/ === parts[key] - missing_keys ||= [] - missing_keys << key - end - end - } - missing_keys - end - - def possibles(cache, options, depth = 0) - cache.fetch(:___routes) { [] } + options.find_all { |pair| - cache.key?(pair) - }.flat_map { |pair| - possibles(cache[pair], options, depth + 1) - } - end - - def build_cache - root = { ___routes: [] } - routes.routes.each_with_index do |route, i| - leaf = route.required_defaults.inject(root) do |h, tuple| - h[tuple] ||= {} - end - (leaf[:___routes] ||= []) << [i, route] - end - root - end - - def cache - @cache ||= build_cache - end - end - end - # :startdoc: -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/builder.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/builder.rb deleted file mode 100644 index 0f8bed89bf..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/builder.rb +++ /dev/null @@ -1,162 +0,0 @@ -require "action_dispatch/journey/gtg/transition_table" - -module ActionDispatch - module Journey # :nodoc: - module GTG # :nodoc: - class Builder # :nodoc: - DUMMY = Nodes::Dummy.new - - attr_reader :root, :ast, :endpoints - - def initialize(root) - @root = root - @ast = Nodes::Cat.new root, DUMMY - @followpos = nil - end - - def transition_table - dtrans = TransitionTable.new - marked = {} - state_id = Hash.new { |h, k| h[k] = h.length } - - start = firstpos(root) - dstates = [start] - until dstates.empty? - s = dstates.shift - next if marked[s] - marked[s] = true # mark s - - s.group_by { |state| symbol(state) }.each do |sym, ps| - u = ps.flat_map { |l| followpos(l) } - next if u.empty? - - if u.uniq == [DUMMY] - from = state_id[s] - to = state_id[Object.new] - dtrans[from, to] = sym - - dtrans.add_accepting(to) - ps.each { |state| dtrans.add_memo(to, state.memo) } - else - dtrans[state_id[s], state_id[u]] = sym - - if u.include?(DUMMY) - to = state_id[u] - - accepting = ps.find_all { |l| followpos(l).include?(DUMMY) } - - accepting.each { |accepting_state| - dtrans.add_memo(to, accepting_state.memo) - } - - dtrans.add_accepting(state_id[u]) - end - end - - dstates << u - end - end - - dtrans - end - - def nullable?(node) - case node - when Nodes::Group - true - when Nodes::Star - true - when Nodes::Or - node.children.any? { |c| nullable?(c) } - when Nodes::Cat - nullable?(node.left) && nullable?(node.right) - when Nodes::Terminal - !node.left - when Nodes::Unary - nullable?(node.left) - else - raise ArgumentError, "unknown nullable: %s" % node.class.name - end - end - - def firstpos(node) - case node - when Nodes::Star - firstpos(node.left) - when Nodes::Cat - if nullable?(node.left) - firstpos(node.left) | firstpos(node.right) - else - firstpos(node.left) - end - when Nodes::Or - node.children.flat_map { |c| firstpos(c) }.uniq - when Nodes::Unary - firstpos(node.left) - when Nodes::Terminal - nullable?(node) ? [] : [node] - else - raise ArgumentError, "unknown firstpos: %s" % node.class.name - end - end - - def lastpos(node) - case node - when Nodes::Star - firstpos(node.left) - when Nodes::Or - node.children.flat_map { |c| lastpos(c) }.uniq - when Nodes::Cat - if nullable?(node.right) - lastpos(node.left) | lastpos(node.right) - else - lastpos(node.right) - end - when Nodes::Terminal - nullable?(node) ? [] : [node] - when Nodes::Unary - lastpos(node.left) - else - raise ArgumentError, "unknown lastpos: %s" % node.class.name - end - end - - def followpos(node) - followpos_table[node] - end - - private - - def followpos_table - @followpos ||= build_followpos - end - - def build_followpos - table = Hash.new { |h, k| h[k] = [] } - @ast.each do |n| - case n - when Nodes::Cat - lastpos(n.left).each do |i| - table[i] += firstpos(n.right) - end - when Nodes::Star - lastpos(n).each do |i| - table[i] += firstpos(n) - end - end - end - table - end - - def symbol(edge) - case edge - when Journey::Nodes::Symbol - edge.regexp - else - edge.left - end - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/simulator.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/simulator.rb deleted file mode 100644 index d692f6415c..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/simulator.rb +++ /dev/null @@ -1,47 +0,0 @@ -require "strscan" - -module ActionDispatch - module Journey # :nodoc: - module GTG # :nodoc: - class MatchData # :nodoc: - attr_reader :memos - - def initialize(memos) - @memos = memos - end - end - - class Simulator # :nodoc: - attr_reader :tt - - def initialize(transition_table) - @tt = transition_table - end - - def simulate(string) - ms = memos(string) { return } - MatchData.new(ms) - end - - alias :=~ :simulate - alias :match :simulate - - def memos(string) - input = StringScanner.new(string) - state = [0] - while sym = input.scan(%r([/.?]|[^/.?]+)) - state = tt.move(state, sym) - end - - acceptance_states = state.find_all { |s| - tt.accepting? s - } - - return yield if acceptance_states.empty? - - acceptance_states.flat_map { |x| tt.memo(x) }.compact - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/transition_table.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/transition_table.rb deleted file mode 100644 index beb9f1ef3b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/gtg/transition_table.rb +++ /dev/null @@ -1,157 +0,0 @@ -require "action_dispatch/journey/nfa/dot" - -module ActionDispatch - module Journey # :nodoc: - module GTG # :nodoc: - class TransitionTable # :nodoc: - include Journey::NFA::Dot - - attr_reader :memos - - def initialize - @regexp_states = {} - @string_states = {} - @accepting = {} - @memos = Hash.new { |h, k| h[k] = [] } - end - - def add_accepting(state) - @accepting[state] = true - end - - def accepting_states - @accepting.keys - end - - def accepting?(state) - @accepting[state] - end - - def add_memo(idx, memo) - @memos[idx] << memo - end - - def memo(idx) - @memos[idx] - end - - def eclosure(t) - Array(t) - end - - def move(t, a) - return [] if t.empty? - - regexps = [] - - t.map { |s| - if states = @regexp_states[s] - regexps.concat states.map { |re, v| re === a ? v : nil } - end - - if states = @string_states[s] - states[a] - end - }.compact.concat regexps - end - - def as_json(options = nil) - simple_regexp = Hash.new { |h, k| h[k] = {} } - - @regexp_states.each do |from, hash| - hash.each do |re, to| - simple_regexp[from][re.source] = to - end - end - - { - regexp_states: simple_regexp, - string_states: @string_states, - accepting: @accepting - } - end - - def to_svg - svg = IO.popen("dot -Tsvg", "w+") { |f| - f.write(to_dot) - f.close_write - f.readlines - } - 3.times { svg.shift } - svg.join.sub(/width="[^"]*"/, "").sub(/height="[^"]*"/, "") - end - - def visualizer(paths, title = "FSM") - viz_dir = File.join File.dirname(__FILE__), "..", "visualizer" - fsm_js = File.read File.join(viz_dir, "fsm.js") - fsm_css = File.read File.join(viz_dir, "fsm.css") - erb = File.read File.join(viz_dir, "index.html.erb") - states = "function tt() { return #{to_json}; }" - - fun_routes = paths.sample(3).map do |ast| - ast.map { |n| - case n - when Nodes::Symbol - case n.left - when ":id" then rand(100).to_s - when ":format" then %w{ xml json }.sample - else - "omg" - end - when Nodes::Terminal then n.symbol - else - nil - end - }.compact.join - end - - stylesheets = [fsm_css] - svg = to_svg - javascripts = [states, fsm_js] - - # Annoying hack warnings - fun_routes = fun_routes - stylesheets = stylesheets - svg = svg - javascripts = javascripts - - require "erb" - template = ERB.new erb - template.result(binding) - end - - def []=(from, to, sym) - to_mappings = states_hash_for(sym)[from] ||= {} - to_mappings[sym] = to - end - - def states - ss = @string_states.keys + @string_states.values.flat_map(&:values) - rs = @regexp_states.keys + @regexp_states.values.flat_map(&:values) - (ss + rs).uniq - end - - def transitions - @string_states.flat_map { |from, hash| - hash.map { |s, to| [from, s, to] } - } + @regexp_states.flat_map { |from, hash| - hash.map { |s, to| [from, s, to] } - } - end - - private - - def states_hash_for(sym) - case sym - when String - @string_states - when Regexp - @regexp_states - else - raise ArgumentError, "unknown symbol: %s" % sym.class - end - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/builder.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/builder.rb deleted file mode 100644 index 532f765094..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/builder.rb +++ /dev/null @@ -1,76 +0,0 @@ -require "action_dispatch/journey/nfa/transition_table" -require "action_dispatch/journey/gtg/transition_table" - -module ActionDispatch - module Journey # :nodoc: - module NFA # :nodoc: - class Visitor < Visitors::Visitor # :nodoc: - def initialize(tt) - @tt = tt - @i = -1 - end - - def visit_CAT(node) - left = visit(node.left) - right = visit(node.right) - - @tt.merge(left.last, right.first) - - [left.first, right.last] - end - - def visit_GROUP(node) - from = @i += 1 - left = visit(node.left) - to = @i += 1 - - @tt.accepting = to - - @tt[from, left.first] = nil - @tt[left.last, to] = nil - @tt[from, to] = nil - - [from, to] - end - - def visit_OR(node) - from = @i += 1 - children = node.children.map { |c| visit(c) } - to = @i += 1 - - children.each do |child| - @tt[from, child.first] = nil - @tt[child.last, to] = nil - end - - @tt.accepting = to - - [from, to] - end - - def terminal(node) - from_i = @i += 1 # new state - to_i = @i += 1 # new state - - @tt[from_i, to_i] = node - @tt.accepting = to_i - @tt.add_memo(to_i, node.memo) - - [from_i, to_i] - end - end - - class Builder # :nodoc: - def initialize(ast) - @ast = ast - end - - def transition_table - tt = TransitionTable.new - Visitor.new(tt).accept(@ast) - tt - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/dot.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/dot.rb deleted file mode 100644 index 8119e5d9da..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/dot.rb +++ /dev/null @@ -1,34 +0,0 @@ -module ActionDispatch - module Journey # :nodoc: - module NFA # :nodoc: - module Dot # :nodoc: - def to_dot - edges = transitions.map { |from, sym, to| - " #{from} -> #{to} [label=\"#{sym || 'ε'}\"];" - } - - #memo_nodes = memos.values.flatten.map { |n| - # label = n - # if Journey::Route === n - # label = "#{n.verb.source} #{n.path.spec}" - # end - # " #{n.object_id} [label=\"#{label}\", shape=box];" - #} - #memo_edges = memos.flat_map { |k, memos| - # (memos || []).map { |v| " #{k} -> #{v.object_id};" } - #}.uniq - - <<-eodot -digraph nfa { - rankdir=LR; - node [shape = doublecircle]; - #{accepting_states.join ' '}; - node [shape = circle]; -#{edges.join "\n"} -} - eodot - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/simulator.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/simulator.rb deleted file mode 100644 index 324d0eed15..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/simulator.rb +++ /dev/null @@ -1,47 +0,0 @@ -require "strscan" - -module ActionDispatch - module Journey # :nodoc: - module NFA # :nodoc: - class MatchData # :nodoc: - attr_reader :memos - - def initialize(memos) - @memos = memos - end - end - - class Simulator # :nodoc: - attr_reader :tt - - def initialize(transition_table) - @tt = transition_table - end - - def simulate(string) - input = StringScanner.new(string) - state = tt.eclosure(0) - until input.eos? - sym = input.scan(%r([/.?]|[^/.?]+)) - - # FIXME: tt.eclosure is not needed for the GTG - state = tt.eclosure(tt.move(state, sym)) - end - - acceptance_states = state.find_all { |s| - tt.accepting?(tt.eclosure(s).sort.last) - } - - return if acceptance_states.empty? - - memos = acceptance_states.flat_map { |x| tt.memo(x) }.compact - - MatchData.new(memos) - end - - alias :=~ :simulate - alias :match :simulate - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/transition_table.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/transition_table.rb deleted file mode 100644 index 543a670da0..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nfa/transition_table.rb +++ /dev/null @@ -1,118 +0,0 @@ -require "action_dispatch/journey/nfa/dot" - -module ActionDispatch - module Journey # :nodoc: - module NFA # :nodoc: - class TransitionTable # :nodoc: - include Journey::NFA::Dot - - attr_accessor :accepting - attr_reader :memos - - def initialize - @table = Hash.new { |h, f| h[f] = {} } - @memos = {} - @accepting = nil - @inverted = nil - end - - def accepting?(state) - accepting == state - end - - def accepting_states - [accepting] - end - - def add_memo(idx, memo) - @memos[idx] = memo - end - - def memo(idx) - @memos[idx] - end - - def []=(i, f, s) - @table[f][i] = s - end - - def merge(left, right) - @memos[right] = @memos.delete(left) - @table[right] = @table.delete(left) - end - - def states - (@table.keys + @table.values.flat_map(&:keys)).uniq - end - - # Returns set of NFA states to which there is a transition on ast symbol - # +a+ from some state +s+ in +t+. - def following_states(t, a) - Array(t).flat_map { |s| inverted[s][a] }.uniq - end - - # Returns set of NFA states to which there is a transition on ast symbol - # +a+ from some state +s+ in +t+. - def move(t, a) - Array(t).map { |s| - inverted[s].keys.compact.find_all { |sym| - sym === a - }.map { |sym| inverted[s][sym] } - }.flatten.uniq - end - - def alphabet - inverted.values.flat_map(&:keys).compact.uniq.sort_by(&:to_s) - end - - # Returns a set of NFA states reachable from some NFA state +s+ in set - # +t+ on nil-transitions alone. - def eclosure(t) - stack = Array(t) - seen = {} - children = [] - - until stack.empty? - s = stack.pop - next if seen[s] - - seen[s] = true - children << s - - stack.concat(inverted[s][nil]) - end - - children.uniq - end - - def transitions - @table.flat_map { |to, hash| - hash.map { |from, sym| [from, sym, to] } - } - end - - private - - def inverted - return @inverted if @inverted - - @inverted = Hash.new { |h, from| - h[from] = Hash.new { |j, s| j[s] = [] } - } - - @table.each { |to, hash| - hash.each { |from, sym| - if sym - sym = Nodes::Symbol === sym ? sym.regexp : sym.left - end - - @inverted[from][sym] << to - } - } - - @inverted - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nodes/node.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nodes/node.rb deleted file mode 100644 index 0d874a84c9..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/nodes/node.rb +++ /dev/null @@ -1,138 +0,0 @@ -require "action_dispatch/journey/visitors" - -module ActionDispatch - module Journey # :nodoc: - module Nodes # :nodoc: - class Node # :nodoc: - include Enumerable - - attr_accessor :left, :memo - - def initialize(left) - @left = left - @memo = nil - end - - def each(&block) - Visitors::Each::INSTANCE.accept(self, block) - end - - def to_s - Visitors::String::INSTANCE.accept(self, "") - end - - def to_dot - Visitors::Dot::INSTANCE.accept(self) - end - - def to_sym - name.to_sym - end - - def name - left.tr "*:".freeze, "".freeze - end - - def type - raise NotImplementedError - end - - def symbol?; false; end - def literal?; false; end - def terminal?; false; end - def star?; false; end - def cat?; false; end - def group?; false; end - end - - class Terminal < Node # :nodoc: - alias :symbol :left - def terminal?; true; end - end - - class Literal < Terminal # :nodoc: - def literal?; true; end - def type; :LITERAL; end - end - - class Dummy < Literal # :nodoc: - def initialize(x = Object.new) - super - end - - def literal?; false; end - end - - %w{ Symbol Slash Dot }.each do |t| - class_eval <<-eoruby, __FILE__, __LINE__ + 1 - class #{t} < Terminal; - def type; :#{t.upcase}; end - end - eoruby - end - - class Symbol < Terminal # :nodoc: - attr_accessor :regexp - alias :symbol :regexp - attr_reader :name - - DEFAULT_EXP = /[^\.\/\?]+/ - def initialize(left) - super - @regexp = DEFAULT_EXP - @name = left.tr "*:".freeze, "".freeze - end - - def default_regexp? - regexp == DEFAULT_EXP - end - - def symbol?; true; end - end - - class Unary < Node # :nodoc: - def children; [left] end - end - - class Group < Unary # :nodoc: - def type; :GROUP; end - def group?; true; end - end - - class Star < Unary # :nodoc: - def star?; true; end - def type; :STAR; end - - def name - left.name.tr "*:", "" - end - end - - class Binary < Node # :nodoc: - attr_accessor :right - - def initialize(left, right) - super(left) - @right = right - end - - def children; [left, right] end - end - - class Cat < Binary # :nodoc: - def cat?; true; end - def type; :CAT; end - end - - class Or < Node # :nodoc: - attr_reader :children - - def initialize(children) - @children = children - end - - def type; :OR; end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser.rb deleted file mode 100644 index e002755bcf..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser.rb +++ /dev/null @@ -1,199 +0,0 @@ -# -# DO NOT MODIFY!!!! -# This file is automatically generated by Racc 1.4.14 -# from Racc grammar file "". -# - -require 'racc/parser.rb' - -# :stopdoc: - -require "action_dispatch/journey/parser_extras" -module ActionDispatch - module Journey - class Parser < Racc::Parser -##### State transition tables begin ### - -racc_action_table = [ - 13, 15, 14, 7, 19, 16, 8, 19, 13, 15, - 14, 7, 17, 16, 8, 13, 15, 14, 7, 21, - 16, 8, 13, 15, 14, 7, 24, 16, 8 ] - -racc_action_check = [ - 2, 2, 2, 2, 22, 2, 2, 2, 19, 19, - 19, 19, 1, 19, 19, 7, 7, 7, 7, 17, - 7, 7, 0, 0, 0, 0, 20, 0, 0 ] - -racc_action_pointer = [ - 20, 12, -2, nil, nil, nil, nil, 13, nil, nil, - nil, nil, nil, nil, nil, nil, nil, 19, nil, 6, - 20, nil, -5, nil, nil ] - -racc_action_default = [ - -19, -19, -2, -3, -4, -5, -6, -19, -10, -11, - -12, -13, -14, -15, -16, -17, -18, -19, -1, -19, - -19, 25, -8, -9, -7 ] - -racc_goto_table = [ - 1, 22, 18, 23, nil, nil, nil, 20 ] - -racc_goto_check = [ - 1, 2, 1, 3, nil, nil, nil, 1 ] - -racc_goto_pointer = [ - nil, 0, -18, -16, nil, nil, nil, nil, nil, nil, - nil ] - -racc_goto_default = [ - nil, nil, 2, 3, 4, 5, 6, 9, 10, 11, - 12 ] - -racc_reduce_table = [ - 0, 0, :racc_error, - 2, 11, :_reduce_1, - 1, 11, :_reduce_2, - 1, 11, :_reduce_none, - 1, 12, :_reduce_none, - 1, 12, :_reduce_none, - 1, 12, :_reduce_none, - 3, 15, :_reduce_7, - 3, 13, :_reduce_8, - 3, 13, :_reduce_9, - 1, 16, :_reduce_10, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 19, :_reduce_15, - 1, 17, :_reduce_16, - 1, 18, :_reduce_17, - 1, 20, :_reduce_18 ] - -racc_reduce_n = 19 - -racc_shift_n = 25 - -racc_token_table = { - false => 0, - :error => 1, - :SLASH => 2, - :LITERAL => 3, - :SYMBOL => 4, - :LPAREN => 5, - :RPAREN => 6, - :DOT => 7, - :STAR => 8, - :OR => 9 } - -racc_nt_base = 10 - -racc_use_result_var = false - -Racc_arg = [ - racc_action_table, - racc_action_check, - racc_action_default, - racc_action_pointer, - racc_goto_table, - racc_goto_check, - racc_goto_default, - racc_goto_pointer, - racc_nt_base, - racc_reduce_table, - racc_token_table, - racc_shift_n, - racc_reduce_n, - racc_use_result_var ] - -Racc_token_to_s_table = [ - "$end", - "error", - "SLASH", - "LITERAL", - "SYMBOL", - "LPAREN", - "RPAREN", - "DOT", - "STAR", - "OR", - "$start", - "expressions", - "expression", - "or", - "terminal", - "group", - "star", - "symbol", - "literal", - "slash", - "dot" ] - -Racc_debug_parser = false - -##### State transition tables end ##### - -# reduce 0 omitted - -def _reduce_1(val, _values) - Cat.new(val.first, val.last) -end - -def _reduce_2(val, _values) - val.first -end - -# reduce 3 omitted - -# reduce 4 omitted - -# reduce 5 omitted - -# reduce 6 omitted - -def _reduce_7(val, _values) - Group.new(val[1]) -end - -def _reduce_8(val, _values) - Or.new([val.first, val.last]) -end - -def _reduce_9(val, _values) - Or.new([val.first, val.last]) -end - -def _reduce_10(val, _values) - Star.new(Symbol.new(val.last)) -end - -# reduce 11 omitted - -# reduce 12 omitted - -# reduce 13 omitted - -# reduce 14 omitted - -def _reduce_15(val, _values) - Slash.new(val.first) -end - -def _reduce_16(val, _values) - Symbol.new(val.first) -end - -def _reduce_17(val, _values) - Literal.new(val.first) -end - -def _reduce_18(val, _values) - Dot.new(val.first) -end - -def _reduce_none(val, _values) - val[0] -end - - end # class Parser - end # module Journey - end # module ActionDispatch diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser.y b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser.y deleted file mode 100644 index f9b1a7a958..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser.y +++ /dev/null @@ -1,50 +0,0 @@ -class ActionDispatch::Journey::Parser - options no_result_var -token SLASH LITERAL SYMBOL LPAREN RPAREN DOT STAR OR - -rule - expressions - : expression expressions { Cat.new(val.first, val.last) } - | expression { val.first } - | or - ; - expression - : terminal - | group - | star - ; - group - : LPAREN expressions RPAREN { Group.new(val[1]) } - ; - or - : expression OR expression { Or.new([val.first, val.last]) } - | expression OR or { Or.new([val.first, val.last]) } - ; - star - : STAR { Star.new(Symbol.new(val.last)) } - ; - terminal - : symbol - | literal - | slash - | dot - ; - slash - : SLASH { Slash.new(val.first) } - ; - symbol - : SYMBOL { Symbol.new(val.first) } - ; - literal - : LITERAL { Literal.new(val.first) } - ; - dot - : DOT { Dot.new(val.first) } - ; - -end - ----- header -# :stopdoc: - -require "action_dispatch/journey/parser_extras" diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser_extras.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser_extras.rb deleted file mode 100644 index 4c7e82d93c..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/parser_extras.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "action_dispatch/journey/scanner" -require "action_dispatch/journey/nodes/node" - -module ActionDispatch - # :stopdoc: - module Journey - class Parser < Racc::Parser - include Journey::Nodes - - def self.parse(string) - new.parse string - end - - def initialize - @scanner = Scanner.new - end - - def parse(string) - @scanner.scan_setup(string) - do_parse - end - - def next_token - @scanner.next_token - end - end - end - # :startdoc: -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/path/pattern.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/path/pattern.rb deleted file mode 100644 index cf0108ec32..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/path/pattern.rb +++ /dev/null @@ -1,196 +0,0 @@ -module ActionDispatch - module Journey # :nodoc: - module Path # :nodoc: - class Pattern # :nodoc: - attr_reader :spec, :requirements, :anchored - - def self.from_string(string) - build(string, {}, "/.?", true) - end - - def self.build(path, requirements, separators, anchored) - parser = Journey::Parser.new - ast = parser.parse path - new ast, requirements, separators, anchored - end - - def initialize(ast, requirements, separators, anchored) - @spec = ast - @requirements = requirements - @separators = separators - @anchored = anchored - - @names = nil - @optional_names = nil - @required_names = nil - @re = nil - @offsets = nil - end - - def build_formatter - Visitors::FormatBuilder.new.accept(spec) - end - - def eager_load! - required_names - offsets - to_regexp - nil - end - - def ast - @spec.find_all(&:symbol?).each do |node| - re = @requirements[node.to_sym] - node.regexp = re if re - end - - @spec.find_all(&:star?).each do |node| - node = node.left - node.regexp = @requirements[node.to_sym] || /(.+)/ - end - - @spec - end - - def names - @names ||= spec.find_all(&:symbol?).map(&:name) - end - - def required_names - @required_names ||= names - optional_names - end - - def optional_names - @optional_names ||= spec.find_all(&:group?).flat_map { |group| - group.find_all(&:symbol?) - }.map(&:name).uniq - end - - class AnchoredRegexp < Journey::Visitors::Visitor # :nodoc: - def initialize(separator, matchers) - @separator = separator - @matchers = matchers - @separator_re = "([^#{separator}]+)" - super() - end - - def accept(node) - %r{\A#{visit node}\Z} - end - - def visit_CAT(node) - [visit(node.left), visit(node.right)].join - end - - def visit_SYMBOL(node) - node = node.to_sym - - return @separator_re unless @matchers.key?(node) - - re = @matchers[node] - "(#{re})" - end - - def visit_GROUP(node) - "(?:#{visit node.left})?" - end - - def visit_LITERAL(node) - Regexp.escape(node.left) - end - alias :visit_DOT :visit_LITERAL - - def visit_SLASH(node) - node.left - end - - def visit_STAR(node) - re = @matchers[node.left.to_sym] || ".+" - "(#{re})" - end - - def visit_OR(node) - children = node.children.map { |n| visit n } - "(?:#{children.join(?|)})" - end - end - - class UnanchoredRegexp < AnchoredRegexp # :nodoc: - def accept(node) - %r{\A#{visit node}} - end - end - - class MatchData # :nodoc: - attr_reader :names - - def initialize(names, offsets, match) - @names = names - @offsets = offsets - @match = match - end - - def captures - Array.new(length - 1) { |i| self[i + 1] } - end - - def [](x) - idx = @offsets[x - 1] + x - @match[idx] - end - - def length - @offsets.length - end - - def post_match - @match.post_match - end - - def to_s - @match.to_s - end - end - - def match(other) - return unless match = to_regexp.match(other) - MatchData.new(names, offsets, match) - end - alias :=~ :match - - def source - to_regexp.source - end - - def to_regexp - @re ||= regexp_visitor.new(@separators, @requirements).accept spec - end - - private - - def regexp_visitor - @anchored ? AnchoredRegexp : UnanchoredRegexp - end - - def offsets - return @offsets if @offsets - - @offsets = [0] - - spec.find_all(&:symbol?).each do |node| - node = node.to_sym - - if @requirements.key?(node) - re = /#{@requirements[node]}|/ - @offsets.push((re.match("").length - 1) + @offsets.last) - else - @offsets << @offsets.last - end - end - - @offsets - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/route.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/route.rb deleted file mode 100644 index 927fd369c4..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/route.rb +++ /dev/null @@ -1,194 +0,0 @@ -module ActionDispatch - # :stopdoc: - module Journey - class Route - attr_reader :app, :path, :defaults, :name, :precedence - - attr_reader :constraints, :internal - alias :conditions :constraints - - module VerbMatchers - VERBS = %w{ DELETE GET HEAD OPTIONS LINK PATCH POST PUT TRACE UNLINK } - VERBS.each do |v| - class_eval <<-eoc - class #{v} - def self.verb; name.split("::").last; end - def self.call(req); req.#{v.downcase}?; end - end - eoc - end - - class Unknown - attr_reader :verb - - def initialize(verb) - @verb = verb - end - - def call(request); @verb === request.request_method; end - end - - class All - def self.call(_); true; end - def self.verb; ""; end - end - - VERB_TO_CLASS = VERBS.each_with_object(all: All) do |verb, hash| - klass = const_get verb - hash[verb] = klass - hash[verb.downcase] = klass - hash[verb.downcase.to_sym] = klass - end - end - - def self.verb_matcher(verb) - VerbMatchers::VERB_TO_CLASS.fetch(verb) do - VerbMatchers::Unknown.new verb.to_s.dasherize.upcase - end - end - - def self.build(name, app, path, constraints, required_defaults, defaults) - request_method_match = verb_matcher(constraints.delete(:request_method)) - new name, app, path, constraints, required_defaults, defaults, request_method_match, 0 - end - - ## - # +path+ is a path constraint. - # +constraints+ is a hash of constraints to be applied to this route. - def initialize(name, app, path, constraints, required_defaults, defaults, request_method_match, precedence, internal = false) - @name = name - @app = app - @path = path - - @request_method_match = request_method_match - @constraints = constraints - @defaults = defaults - @required_defaults = nil - @_required_defaults = required_defaults - @required_parts = nil - @parts = nil - @decorated_ast = nil - @precedence = precedence - @path_formatter = @path.build_formatter - @internal = internal - end - - def eager_load! - path.eager_load! - ast - parts - required_defaults - nil - end - - def ast - @decorated_ast ||= begin - decorated_ast = path.ast - decorated_ast.find_all(&:terminal?).each { |n| n.memo = self } - decorated_ast - end - end - - def requirements - # needed for rails `rails routes` - @defaults.merge(path.requirements).delete_if { |_, v| - /.+?/ == v - } - end - - def segments - path.names - end - - def required_keys - required_parts + required_defaults.keys - end - - def score(supplied_keys) - required_keys = path.required_names - - required_keys.each do |k| - return -1 unless supplied_keys.include?(k) - end - - score = 0 - path.names.each do |k| - score += 1 if supplied_keys.include?(k) - end - - score + (required_defaults.length * 2) - end - - def parts - @parts ||= segments.map(&:to_sym) - end - alias :segment_keys :parts - - def format(path_options) - @path_formatter.evaluate path_options - end - - def required_parts - @required_parts ||= path.required_names.map(&:to_sym) - end - - def required_default?(key) - @_required_defaults.include?(key) - end - - def required_defaults - @required_defaults ||= @defaults.dup.delete_if do |k, _| - parts.include?(k) || !required_default?(k) - end - end - - def glob? - !path.spec.grep(Nodes::Star).empty? - end - - def dispatcher? - @app.dispatcher? - end - - def matches?(request) - match_verb(request) && - constraints.all? { |method, value| - case value - when Regexp, String - value === request.send(method).to_s - when Array - value.include?(request.send(method)) - when TrueClass - request.send(method).present? - when FalseClass - request.send(method).blank? - else - value === request.send(method) - end - } - end - - def ip - constraints[:ip] || // - end - - def requires_matching_verb? - !@request_method_match.all? { |x| x == VerbMatchers::All } - end - - def verb - verbs.join("|") - end - - private - def verbs - @request_method_match.map(&:verb) - end - - def match_verb(request) - @request_method_match.any? { |m| m.call request } - end - end - end - # :startdoc: -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/router.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/router.rb deleted file mode 100644 index c1e7fcea5c..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/router.rb +++ /dev/null @@ -1,154 +0,0 @@ -require "action_dispatch/journey/router/utils" -require "action_dispatch/journey/routes" -require "action_dispatch/journey/formatter" - -before = $-w -$-w = false -require "action_dispatch/journey/parser" -$-w = before - -require "action_dispatch/journey/route" -require "action_dispatch/journey/path/pattern" - -module ActionDispatch - module Journey # :nodoc: - class Router # :nodoc: - class RoutingError < ::StandardError # :nodoc: - end - - attr_accessor :routes - - def initialize(routes) - @routes = routes - end - - def eager_load! - # Eagerly trigger the simulator's initialization so - # it doesn't happen during a request cycle. - simulator - nil - end - - def serve(req) - find_routes(req).each do |match, parameters, route| - set_params = req.path_parameters - path_info = req.path_info - script_name = req.script_name - - unless route.path.anchored - req.script_name = (script_name.to_s + match.to_s).chomp("/") - req.path_info = match.post_match - req.path_info = "/" + req.path_info unless req.path_info.start_with? "/" - end - - parameters = route.defaults.merge parameters.transform_values { |val| - val.dup.force_encoding(::Encoding::UTF_8) - } - - req.path_parameters = set_params.merge parameters - - status, headers, body = route.app.serve(req) - - if "pass" == headers["X-Cascade"] - req.script_name = script_name - req.path_info = path_info - req.path_parameters = set_params - next - end - - return [status, headers, body] - end - - return [404, { "X-Cascade" => "pass" }, ["Not Found"]] - end - - def recognize(rails_req) - find_routes(rails_req).each do |match, parameters, route| - unless route.path.anchored - rails_req.script_name = match.to_s - rails_req.path_info = match.post_match.sub(/^([^\/])/, '/\1') - end - - parameters = route.defaults.merge parameters - yield(route, parameters) - end - end - - def visualizer - tt = GTG::Builder.new(ast).transition_table - groups = partitioned_routes.first.map(&:ast).group_by(&:to_s) - asts = groups.values.map(&:first) - tt.visualizer(asts) - end - - private - - def partitioned_routes - routes.partition { |r| - r.path.anchored && r.ast.grep(Nodes::Symbol).all? { |n| n.default_regexp? } - } - end - - def ast - routes.ast - end - - def simulator - routes.simulator - end - - def custom_routes - routes.custom_routes - end - - def filter_routes(path) - return [] unless ast - simulator.memos(path) { [] } - end - - def find_routes(req) - routes = filter_routes(req.path_info).concat custom_routes.find_all { |r| - r.path.match(req.path_info) - } - - routes = - if req.head? - match_head_routes(routes, req) - else - match_routes(routes, req) - end - - routes.sort_by!(&:precedence) - - routes.map! { |r| - match_data = r.path.match(req.path_info) - path_parameters = {} - match_data.names.zip(match_data.captures) { |name, val| - path_parameters[name.to_sym] = Utils.unescape_uri(val) if val - } - [match_data, path_parameters, r] - } - end - - def match_head_routes(routes, req) - verb_specific_routes = routes.select(&:requires_matching_verb?) - head_routes = match_routes(verb_specific_routes, req) - - if head_routes.empty? - begin - req.request_method = "GET" - match_routes(routes, req) - ensure - req.request_method = "HEAD" - end - else - head_routes - end - end - - def match_routes(routes, req) - routes.select { |r| r.matches?(req) } - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/router/utils.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/router/utils.rb deleted file mode 100644 index f4a48ee62d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/router/utils.rb +++ /dev/null @@ -1,95 +0,0 @@ -module ActionDispatch - module Journey # :nodoc: - class Router # :nodoc: - class Utils # :nodoc: - # Normalizes URI path. - # - # Strips off trailing slash and ensures there is a leading slash. - # Also converts downcase url encoded string to uppercase. - # - # normalize_path("/foo") # => "/foo" - # normalize_path("/foo/") # => "/foo" - # normalize_path("foo") # => "/foo" - # normalize_path("") # => "/" - # normalize_path("/%ab") # => "/%AB" - def self.normalize_path(path) - encoding = path.encoding - path = "/#{path}" - path.squeeze!("/".freeze) - path.sub!(%r{/+\Z}, "".freeze) - path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase } - path = "/" if path == "".freeze - path.force_encoding(encoding) - path - end - - # URI path and fragment escaping - # http://tools.ietf.org/html/rfc3986 - class UriEncoder # :nodoc: - ENCODE = "%%%02X".freeze - US_ASCII = Encoding::US_ASCII - UTF_8 = Encoding::UTF_8 - EMPTY = "".force_encoding(US_ASCII).freeze - DEC2HEX = (0..255).to_a.map { |i| ENCODE % i }.map { |s| s.force_encoding(US_ASCII) } - - ALPHA = "a-zA-Z".freeze - DIGIT = "0-9".freeze - UNRESERVED = "#{ALPHA}#{DIGIT}\\-\\._~".freeze - SUB_DELIMS = "!\\$&'\\(\\)\\*\\+,;=".freeze - - ESCAPED = /%[a-zA-Z0-9]{2}/.freeze - - FRAGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/\?]/.freeze - SEGMENT = /[^#{UNRESERVED}#{SUB_DELIMS}:@]/.freeze - PATH = /[^#{UNRESERVED}#{SUB_DELIMS}:@\/]/.freeze - - def escape_fragment(fragment) - escape(fragment, FRAGMENT) - end - - def escape_path(path) - escape(path, PATH) - end - - def escape_segment(segment) - escape(segment, SEGMENT) - end - - def unescape_uri(uri) - encoding = uri.encoding == US_ASCII ? UTF_8 : uri.encoding - uri.gsub(ESCAPED) { |match| [match[1, 2].hex].pack("C") }.force_encoding(encoding) - end - - private - def escape(component, pattern) # :doc: - component.gsub(pattern) { |unsafe| percent_encode(unsafe) }.force_encoding(US_ASCII) - end - - def percent_encode(unsafe) # :doc: - safe = EMPTY.dup - unsafe.each_byte { |b| safe << DEC2HEX[b] } - safe - end - end - - ENCODER = UriEncoder.new - - def self.escape_path(path) - ENCODER.escape_path(path.to_s) - end - - def self.escape_segment(segment) - ENCODER.escape_segment(segment.to_s) - end - - def self.escape_fragment(fragment) - ENCODER.escape_fragment(fragment.to_s) - end - - def self.unescape_uri(uri) - ENCODER.unescape_uri(uri) - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/routes.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/routes.rb deleted file mode 100644 index 4329e2c818..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/routes.rb +++ /dev/null @@ -1,80 +0,0 @@ -module ActionDispatch - module Journey # :nodoc: - # The Routing table. Contains all routes for a system. Routes can be - # added to the table by calling Routes#add_route. - class Routes # :nodoc: - include Enumerable - - attr_reader :routes, :custom_routes, :anchored_routes - - def initialize - @routes = [] - @ast = nil - @anchored_routes = [] - @custom_routes = [] - @simulator = nil - end - - def empty? - routes.empty? - end - - def length - routes.length - end - alias :size :length - - def last - routes.last - end - - def each(&block) - routes.each(&block) - end - - def clear - routes.clear - anchored_routes.clear - custom_routes.clear - end - - def partition_route(route) - if route.path.anchored && route.ast.grep(Nodes::Symbol).all?(&:default_regexp?) - anchored_routes << route - else - custom_routes << route - end - end - - def ast - @ast ||= begin - asts = anchored_routes.map(&:ast) - Nodes::Or.new(asts) unless asts.empty? - end - end - - def simulator - return if ast.nil? - @simulator ||= begin - gtg = GTG::Builder.new(ast).transition_table - GTG::Simulator.new(gtg) - end - end - - def add_route(name, mapping) - route = mapping.make_route name, routes.length - routes << route - partition_route(route) - clear_cache! - route - end - - private - - def clear_cache! - @ast = nil - @simulator = nil - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/scanner.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/scanner.rb deleted file mode 100644 index 7dbb39b26d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/scanner.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true -require "strscan" - -module ActionDispatch - module Journey # :nodoc: - class Scanner # :nodoc: - def initialize - @ss = nil - end - - def scan_setup(str) - @ss = StringScanner.new(str) - end - - def eos? - @ss.eos? - end - - def pos - @ss.pos - end - - def pre_match - @ss.pre_match - end - - def next_token - return if @ss.eos? - - until token = scan || @ss.eos?; end - token - end - - private - - def scan - case - # / - when @ss.skip(/\//) - [:SLASH, "/"] - when @ss.skip(/\(/) - [:LPAREN, "("] - when @ss.skip(/\)/) - [:RPAREN, ")"] - when @ss.skip(/\|/) - [:OR, "|"] - when @ss.skip(/\./) - [:DOT, "."] - when text = @ss.scan(/:\w+/) - [:SYMBOL, text] - when text = @ss.scan(/\*\w+/) - [:STAR, text] - when text = @ss.scan(/(?:[\w%\-~!$&'*+,;=@]|\\[:()])+/) - text.tr! "\\", "" - [:LITERAL, text] - # any char - when text = @ss.scan(/./) - [:LITERAL, text] - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visitors.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visitors.rb deleted file mode 100644 index 1c50192867..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visitors.rb +++ /dev/null @@ -1,266 +0,0 @@ -module ActionDispatch - # :stopdoc: - module Journey - class Format - ESCAPE_PATH = ->(value) { Router::Utils.escape_path(value) } - ESCAPE_SEGMENT = ->(value) { Router::Utils.escape_segment(value) } - - Parameter = Struct.new(:name, :escaper) do - def escape(value); escaper.call value; end - end - - def self.required_path(symbol) - Parameter.new symbol, ESCAPE_PATH - end - - def self.required_segment(symbol) - Parameter.new symbol, ESCAPE_SEGMENT - end - - def initialize(parts) - @parts = parts - @children = [] - @parameters = [] - - parts.each_with_index do |object, i| - case object - when Journey::Format - @children << i - when Parameter - @parameters << i - end - end - end - - def evaluate(hash) - parts = @parts.dup - - @parameters.each do |index| - param = parts[index] - value = hash[param.name] - return "".freeze unless value - parts[index] = param.escape value - end - - @children.each { |index| parts[index] = parts[index].evaluate(hash) } - - parts.join - end - end - - module Visitors # :nodoc: - class Visitor # :nodoc: - DISPATCH_CACHE = {} - - def accept(node) - visit(node) - end - - private - - def visit(node) - send(DISPATCH_CACHE[node.type], node) - end - - def binary(node) - visit(node.left) - visit(node.right) - end - def visit_CAT(n); binary(n); end - - def nary(node) - node.children.each { |c| visit(c) } - end - def visit_OR(n); nary(n); end - - def unary(node) - visit(node.left) - end - def visit_GROUP(n); unary(n); end - def visit_STAR(n); unary(n); end - - def terminal(node); end - def visit_LITERAL(n); terminal(n); end - def visit_SYMBOL(n); terminal(n); end - def visit_SLASH(n); terminal(n); end - def visit_DOT(n); terminal(n); end - - private_instance_methods(false).each do |pim| - next unless pim =~ /^visit_(.*)$/ - DISPATCH_CACHE[$1.to_sym] = pim - end - end - - class FunctionalVisitor # :nodoc: - DISPATCH_CACHE = {} - - def accept(node, seed) - visit(node, seed) - end - - def visit(node, seed) - send(DISPATCH_CACHE[node.type], node, seed) - end - - def binary(node, seed) - visit(node.right, visit(node.left, seed)) - end - def visit_CAT(n, seed); binary(n, seed); end - - def nary(node, seed) - node.children.inject(seed) { |s, c| visit(c, s) } - end - def visit_OR(n, seed); nary(n, seed); end - - def unary(node, seed) - visit(node.left, seed) - end - def visit_GROUP(n, seed); unary(n, seed); end - def visit_STAR(n, seed); unary(n, seed); end - - def terminal(node, seed); seed; end - def visit_LITERAL(n, seed); terminal(n, seed); end - def visit_SYMBOL(n, seed); terminal(n, seed); end - def visit_SLASH(n, seed); terminal(n, seed); end - def visit_DOT(n, seed); terminal(n, seed); end - - instance_methods(false).each do |pim| - next unless pim =~ /^visit_(.*)$/ - DISPATCH_CACHE[$1.to_sym] = pim - end - end - - class FormatBuilder < Visitor # :nodoc: - def accept(node); Journey::Format.new(super); end - def terminal(node); [node.left]; end - - def binary(node) - visit(node.left) + visit(node.right) - end - - def visit_GROUP(n); [Journey::Format.new(unary(n))]; end - - def visit_STAR(n) - [Journey::Format.required_path(n.left.to_sym)] - end - - def visit_SYMBOL(n) - symbol = n.to_sym - if symbol == :controller - [Journey::Format.required_path(symbol)] - else - [Journey::Format.required_segment(symbol)] - end - end - end - - # Loop through the requirements AST - class Each < FunctionalVisitor # :nodoc: - def visit(node, block) - block.call(node) - super - end - - INSTANCE = new - end - - class String < FunctionalVisitor # :nodoc: - private - - def binary(node, seed) - visit(node.right, visit(node.left, seed)) - end - - def nary(node, seed) - last_child = node.children.last - node.children.inject(seed) { |s, c| - string = visit(c, s) - string << "|".freeze unless last_child == c - string - } - end - - def terminal(node, seed) - seed + node.left - end - - def visit_GROUP(node, seed) - visit(node.left, seed << "(".freeze) << ")".freeze - end - - INSTANCE = new - end - - class Dot < FunctionalVisitor # :nodoc: - def initialize - @nodes = [] - @edges = [] - end - - def accept(node, seed = [[], []]) - super - nodes, edges = seed - <<-eodot - digraph parse_tree { - size="8,5" - node [shape = none]; - edge [dir = none]; - #{nodes.join "\n"} - #{edges.join("\n")} - } - eodot - end - - private - - def binary(node, seed) - seed.last.concat node.children.map { |c| - "#{node.object_id} -> #{c.object_id};" - } - super - end - - def nary(node, seed) - seed.last.concat node.children.map { |c| - "#{node.object_id} -> #{c.object_id};" - } - super - end - - def unary(node, seed) - seed.last << "#{node.object_id} -> #{node.left.object_id};" - super - end - - def visit_GROUP(node, seed) - seed.first << "#{node.object_id} [label=\"()\"];" - super - end - - def visit_CAT(node, seed) - seed.first << "#{node.object_id} [label=\"○\"];" - super - end - - def visit_STAR(node, seed) - seed.first << "#{node.object_id} [label=\"*\"];" - super - end - - def visit_OR(node, seed) - seed.first << "#{node.object_id} [label=\"|\"];" - super - end - - def terminal(node, seed) - value = node.left - - seed.first << "#{node.object_id} [label=\"#{value}\"];" - seed - end - INSTANCE = new - end - end - end - # :startdoc: -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/fsm.css b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/fsm.css deleted file mode 100644 index 403e16a7bb..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/fsm.css +++ /dev/null @@ -1,30 +0,0 @@ -body { - font-family: "Helvetica Neue", Helvetica, Arial, Sans-Serif; - margin: 0; -} - -h1 { - font-size: 2.0em; font-weight: bold; text-align: center; - color: white; background-color: black; - padding: 5px 0; - margin: 0 0 20px; -} - -h2 { - text-align: center; - display: none; - font-size: 0.5em; -} - -.clearfix {display: inline-block; } -.input { overflow: show;} -.instruction { color: #666; padding: 0 30px 20px; font-size: 0.9em} -.instruction p { padding: 0 0 5px; } -.instruction li { padding: 0 10px 5px; } - -.form { background: #EEE; padding: 20px 30px; border-radius: 5px; margin-left: auto; margin-right: auto; width: 500px; margin-bottom: 20px} -.form p, .form form { text-align: center } -.form form {padding: 0 10px 5px; } -.form .fun_routes { font-size: 0.9em;} -.form .fun_routes a { margin: 0 5px 0 0; } - diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/fsm.js b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/fsm.js deleted file mode 100644 index d9bcaef928..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/fsm.js +++ /dev/null @@ -1,134 +0,0 @@ -function tokenize(input, callback) { - while(input.length > 0) { - callback(input.match(/^[\/\.\?]|[^\/\.\?]+/)[0]); - input = input.replace(/^[\/\.\?]|[^\/\.\?]+/, ''); - } -} - -var graph = d3.select("#chart-2 svg"); -var svg_edges = {}; -var svg_nodes = {}; - -graph.selectAll("g.edge").each(function() { - var node = d3.select(this); - var index = node.select("title").text().split("->"); - var left = parseInt(index[0]); - var right = parseInt(index[1]); - - if(!svg_edges[left]) { svg_edges[left] = {} } - svg_edges[left][right] = node; -}); - -graph.selectAll("g.node").each(function() { - var node = d3.select(this); - var index = parseInt(node.select("title").text()); - svg_nodes[index] = node; -}); - -function reset_graph() { - for(var key in svg_edges) { - for(var mkey in svg_edges[key]) { - var node = svg_edges[key][mkey]; - var path = node.select("path"); - var arrow = node.select("polygon"); - path.style("stroke", "black"); - arrow.style("stroke", "black").style("fill", "black"); - } - } - - for(var key in svg_nodes) { - var node = svg_nodes[key]; - node.select('ellipse').style("fill", "white"); - node.select('polygon').style("fill", "white"); - } - return false; -} - -function highlight_edge(from, to) { - var node = svg_edges[from][to]; - var path = node.select("path"); - var arrow = node.select("polygon"); - - path - .transition().duration(500) - .style("stroke", "green"); - - arrow - .transition().duration(500) - .style("stroke", "green").style("fill", "green"); -} - -function highlight_state(index, color) { - if(!color) { color = "green"; } - - svg_nodes[index].select('ellipse') - .style("fill", "white") - .transition().duration(500) - .style("fill", color); -} - -function highlight_finish(index) { - svg_nodes[index].select('polygon') - .style("fill", "while") - .transition().duration(500) - .style("fill", "blue"); -} - -function match(input) { - reset_graph(); - var table = tt(); - var states = [0]; - var regexp_states = table['regexp_states']; - var string_states = table['string_states']; - var accepting = table['accepting']; - - highlight_state(0); - - tokenize(input, function(token) { - var new_states = []; - for(var key in states) { - var state = states[key]; - - if(string_states[state] && string_states[state][token]) { - var new_state = string_states[state][token]; - highlight_edge(state, new_state); - highlight_state(new_state); - new_states.push(new_state); - } - - if(regexp_states[state]) { - for(var key in regexp_states[state]) { - var re = new RegExp("^" + key + "$"); - if(re.test(token)) { - var new_state = regexp_states[state][key]; - highlight_edge(state, new_state); - highlight_state(new_state); - new_states.push(new_state); - } - } - } - } - - if(new_states.length == 0) { - return; - } - states = new_states; - }); - - for(var key in states) { - var state = states[key]; - if(accepting[state]) { - for(var mkey in svg_edges[state]) { - if(!regexp_states[mkey] && !string_states[mkey]) { - highlight_edge(state, mkey); - highlight_finish(mkey); - } - } - } else { - highlight_state(state, "red"); - } - } - - return false; -} - diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/index.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/index.html.erb deleted file mode 100644 index 9b28a65200..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/journey/visualizer/index.html.erb +++ /dev/null @@ -1,52 +0,0 @@ - - - - <%= title %> - - - - - -
-

Routes FSM with NFA simulation

-
-

- Type a route in to the box and click "simulate". -

-
- - - -
-

- Some fun routes to try: - <% fun_routes.each do |path| %> - - <%= path %> - - <% end %> -

-
-
- <%= svg %> -
-
-

- This is a FSM for a system that has the following routes: -

-
    - <% paths.each do |route| %> -
  • <%= route %>
  • - <% end %> -
-
-
- <% javascripts.each do |js| %> - - <% end %> - - diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/callbacks.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/callbacks.rb deleted file mode 100644 index ff129cf96a..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/callbacks.rb +++ /dev/null @@ -1,34 +0,0 @@ -module ActionDispatch - # Provides callbacks to be executed before and after dispatching the request. - class Callbacks - include ActiveSupport::Callbacks - - define_callbacks :call - - class << self - def before(*args, &block) - set_callback(:call, :before, *args, &block) - end - - def after(*args, &block) - set_callback(:call, :after, *args, &block) - end - end - - def initialize(app) - @app = app - end - - def call(env) - error = nil - result = run_callbacks :call do - begin - @app.call(env) - rescue => error - end - end - raise error if error - result - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/cookies.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/cookies.rb deleted file mode 100644 index c61cb3fd68..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/cookies.rb +++ /dev/null @@ -1,628 +0,0 @@ -require "active_support/core_ext/hash/keys" -require "active_support/key_generator" -require "active_support/message_verifier" -require "active_support/json" -require "rack/utils" - -module ActionDispatch - class Request - def cookie_jar - fetch_header("action_dispatch.cookies".freeze) do - self.cookie_jar = Cookies::CookieJar.build(self, cookies) - end - end - - # :stopdoc: - prepend Module.new { - def commit_cookie_jar! - cookie_jar.commit! - end - } - - def have_cookie_jar? - has_header? "action_dispatch.cookies".freeze - end - - def cookie_jar=(jar) - set_header "action_dispatch.cookies".freeze, jar - end - - def key_generator - get_header Cookies::GENERATOR_KEY - end - - def signed_cookie_salt - get_header Cookies::SIGNED_COOKIE_SALT - end - - def encrypted_cookie_salt - get_header Cookies::ENCRYPTED_COOKIE_SALT - end - - def encrypted_signed_cookie_salt - get_header Cookies::ENCRYPTED_SIGNED_COOKIE_SALT - end - - def secret_token - get_header Cookies::SECRET_TOKEN - end - - def secret_key_base - get_header Cookies::SECRET_KEY_BASE - end - - def cookies_serializer - get_header Cookies::COOKIES_SERIALIZER - end - - def cookies_digest - get_header Cookies::COOKIES_DIGEST - end - # :startdoc: - end - - # \Cookies are read and written through ActionController#cookies. - # - # The cookies being read are the ones received along with the request, the cookies - # being written will be sent out with the response. Reading a cookie does not get - # the cookie object itself back, just the value it holds. - # - # Examples of writing: - # - # # Sets a simple session cookie. - # # This cookie will be deleted when the user's browser is closed. - # cookies[:user_name] = "david" - # - # # Cookie values are String based. Other data types need to be serialized. - # cookies[:lat_lon] = JSON.generate([47.68, -122.37]) - # - # # Sets a cookie that expires in 1 hour. - # cookies[:login] = { value: "XJ-122", expires: 1.hour.from_now } - # - # # Sets a signed cookie, which prevents users from tampering with its value. - # # The cookie is signed by your app's `secrets.secret_key_base` value. - # # It can be read using the signed method `cookies.signed[:name]` - # cookies.signed[:user_id] = current_user.id - # - # # Sets an encrypted cookie value before sending it to the client which - # # prevent users from reading and tampering with its value. - # # The cookie is signed by your app's `secrets.secret_key_base` value. - # # It can be read using the encrypted method `cookies.encrypted[:name]` - # cookies.encrypted[:discount] = 45 - # - # # Sets a "permanent" cookie (which expires in 20 years from now). - # cookies.permanent[:login] = "XJ-122" - # - # # You can also chain these methods: - # cookies.permanent.signed[:login] = "XJ-122" - # - # Examples of reading: - # - # cookies[:user_name] # => "david" - # cookies.size # => 2 - # JSON.parse(cookies[:lat_lon]) # => [47.68, -122.37] - # cookies.signed[:login] # => "XJ-122" - # cookies.encrypted[:discount] # => 45 - # - # Example for deleting: - # - # cookies.delete :user_name - # - # Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie: - # - # cookies[:name] = { - # value: 'a yummy cookie', - # expires: 1.year.from_now, - # domain: 'domain.com' - # } - # - # cookies.delete(:name, domain: 'domain.com') - # - # The option symbols for setting cookies are: - # - # * :value - The cookie's value. - # * :path - The path for which this cookie applies. Defaults to the root - # of the application. - # * :domain - The domain for which this cookie applies so you can - # restrict to the domain level. If you use a schema like www.example.com - # and want to share session with user.example.com set :domain - # to :all. Make sure to specify the :domain option with - # :all or Array again when deleting cookies. - # - # domain: nil # Does not set cookie domain. (default) - # domain: :all # Allow the cookie for the top most level - # # domain and subdomains. - # domain: %w(.example.com .example.org) # Allow the cookie - # # for concrete domain names. - # - # * :tld_length - When using :domain => :all, this option can be used to explicitly - # set the TLD length when using a short (<= 3 character) domain that is being interpreted as part of a TLD. - # For example, to share cookies between user1.lvh.me and user2.lvh.me, set :tld_length to 1. - # * :expires - The time at which this cookie expires, as a \Time object. - # * :secure - Whether this cookie is only transmitted to HTTPS servers. - # Default is +false+. - # * :httponly - Whether this cookie is accessible via scripting or - # only HTTP. Defaults to +false+. - class Cookies - HTTP_HEADER = "Set-Cookie".freeze - GENERATOR_KEY = "action_dispatch.key_generator".freeze - SIGNED_COOKIE_SALT = "action_dispatch.signed_cookie_salt".freeze - ENCRYPTED_COOKIE_SALT = "action_dispatch.encrypted_cookie_salt".freeze - ENCRYPTED_SIGNED_COOKIE_SALT = "action_dispatch.encrypted_signed_cookie_salt".freeze - SECRET_TOKEN = "action_dispatch.secret_token".freeze - SECRET_KEY_BASE = "action_dispatch.secret_key_base".freeze - COOKIES_SERIALIZER = "action_dispatch.cookies_serializer".freeze - COOKIES_DIGEST = "action_dispatch.cookies_digest".freeze - - # Cookies can typically store 4096 bytes. - MAX_COOKIE_SIZE = 4096 - - # Raised when storing more than 4K of session data. - CookieOverflow = Class.new StandardError - - # Include in a cookie jar to allow chaining, e.g. cookies.permanent.signed - module ChainedCookieJars - # Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example: - # - # cookies.permanent[:prefers_open_id] = true - # # => Set-Cookie: prefers_open_id=true; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT - # - # This jar is only meant for writing. You'll read permanent cookies through the regular accessor. - # - # This jar allows chaining with the signed jar as well, so you can set permanent, signed cookies. Examples: - # - # cookies.permanent.signed[:remember_me] = current_user.id - # # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT - def permanent - @permanent ||= PermanentCookieJar.new(self) - end - - # Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from - # the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed - # cookie was tampered with by the user (or a 3rd party), +nil+ will be returned. - # - # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set, - # legacy cookies signed with the old key generator will be transparently upgraded. - # - # This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+. - # - # Example: - # - # cookies.signed[:discount] = 45 - # # => Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/ - # - # cookies.signed[:discount] # => 45 - def signed - @signed ||= - if upgrade_legacy_signed_cookies? - UpgradeLegacySignedCookieJar.new(self) - else - SignedCookieJar.new(self) - end - end - - # Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read. - # If the cookie was tampered with by the user (or a 3rd party), +nil+ will be returned. - # - # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set, - # legacy cookies signed with the old key generator will be transparently upgraded. - # - # This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+. - # - # Example: - # - # cookies.encrypted[:discount] = 45 - # # => Set-Cookie: discount=ZS9ZZ1R4cG1pcUJ1bm80anhQang3dz09LS1mbDZDSU5scGdOT3ltQ2dTdlhSdWpRPT0%3D--ab54663c9f4e3bc340c790d6d2b71e92f5b60315; path=/ - # - # cookies.encrypted[:discount] # => 45 - def encrypted - @encrypted ||= - if upgrade_legacy_signed_cookies? - UpgradeLegacyEncryptedCookieJar.new(self) - else - EncryptedCookieJar.new(self) - end - end - - # Returns the +signed+ or +encrypted+ jar, preferring +encrypted+ if +secret_key_base+ is set. - # Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores. - def signed_or_encrypted - @signed_or_encrypted ||= - if request.secret_key_base.present? - encrypted - else - signed - end - end - - private - - def upgrade_legacy_signed_cookies? - request.secret_token.present? && request.secret_key_base.present? - end - end - - # Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream - # to the Message{Encryptor,Verifier} allows us to handle the - # (de)serialization step within the cookie jar, which gives us the - # opportunity to detect and migrate legacy cookies. - module VerifyAndUpgradeLegacySignedMessage # :nodoc: - def initialize(*args) - super - @legacy_verifier = ActiveSupport::MessageVerifier.new(request.secret_token, serializer: ActiveSupport::MessageEncryptor::NullSerializer) - end - - def verify_and_upgrade_legacy_signed_message(name, signed_message) - deserialize(name, @legacy_verifier.verify(signed_message)).tap do |value| - self[name] = { value: value } - end - rescue ActiveSupport::MessageVerifier::InvalidSignature - nil - end - - private - def parse(name, signed_message) - super || verify_and_upgrade_legacy_signed_message(name, signed_message) - end - end - - class CookieJar #:nodoc: - include Enumerable, ChainedCookieJars - - # This regular expression is used to split the levels of a domain. - # The top level domain can be any string without a period or - # **.**, ***.** style TLDs like co.uk or com.au - # - # www.example.co.uk gives: - # $& => example.co.uk - # - # example.com gives: - # $& => example.com - # - # lots.of.subdomains.example.local gives: - # $& => example.local - DOMAIN_REGEXP = /[^.]*\.([^.]*|..\...|...\...)$/ - - def self.build(req, cookies) - new(req).tap do |hash| - hash.update(cookies) - end - end - - attr_reader :request - - def initialize(request) - @set_cookies = {} - @delete_cookies = {} - @request = request - @cookies = {} - @committed = false - end - - def committed?; @committed; end - - def commit! - @committed = true - @set_cookies.freeze - @delete_cookies.freeze - end - - def each(&block) - @cookies.each(&block) - end - - # Returns the value of the cookie by +name+, or +nil+ if no such cookie exists. - def [](name) - @cookies[name.to_s] - end - - def fetch(name, *args, &block) - @cookies.fetch(name.to_s, *args, &block) - end - - def key?(name) - @cookies.key?(name.to_s) - end - alias :has_key? :key? - - def update(other_hash) - @cookies.update other_hash.stringify_keys - self - end - - def update_cookies_from_jar - request_jar = @request.cookie_jar.instance_variable_get(:@cookies) - set_cookies = request_jar.reject { |k, _| @delete_cookies.key?(k) } - - @cookies.update set_cookies if set_cookies - end - - def to_header - @cookies.map { |k, v| "#{escape(k)}=#{escape(v)}" }.join "; " - end - - def handle_options(options) #:nodoc: - options[:path] ||= "/" - - if options[:domain] == :all || options[:domain] == "all" - # if there is a provided tld length then we use it otherwise default domain regexp - domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP - - # if host is not ip and matches domain regexp - # (ip confirms to domain regexp so we explicitly check for ip) - options[:domain] = if (request.host !~ /^[\d.]+$/) && (request.host =~ domain_regexp) - ".#{$&}" - end - elsif options[:domain].is_a? Array - # if host matches one of the supplied domains without a dot in front of it - options[:domain] = options[:domain].find { |domain| request.host.include? domain.sub(/^\./, "") } - end - end - - # Sets the cookie named +name+. The second argument may be the cookie's - # value or a hash of options as documented above. - def []=(name, options) - if options.is_a?(Hash) - options.symbolize_keys! - value = options[:value] - else - value = options - options = { value: value } - end - - handle_options(options) - - if @cookies[name.to_s] != value || options[:expires] - @cookies[name.to_s] = value - @set_cookies[name.to_s] = options - @delete_cookies.delete(name.to_s) - end - - value - end - - # Removes the cookie on the client machine by setting the value to an empty string - # and the expiration date in the past. Like []=, you can pass in - # an options hash to delete cookies with extra data such as a :path. - def delete(name, options = {}) - return unless @cookies.has_key? name.to_s - - options.symbolize_keys! - handle_options(options) - - value = @cookies.delete(name.to_s) - @delete_cookies[name.to_s] = options - value - end - - # Whether the given cookie is to be deleted by this CookieJar. - # Like []=, you can pass in an options hash to test if a - # deletion applies to a specific :path, :domain etc. - def deleted?(name, options = {}) - options.symbolize_keys! - handle_options(options) - @delete_cookies[name.to_s] == options - end - - # Removes all cookies on the client machine by calling delete for each cookie - def clear(options = {}) - @cookies.each_key { |k| delete(k, options) } - end - - def write(headers) - if header = make_set_cookie_header(headers[HTTP_HEADER]) - headers[HTTP_HEADER] = header - end - end - - mattr_accessor :always_write_cookie - self.always_write_cookie = false - - private - - def escape(string) - ::Rack::Utils.escape(string) - end - - def make_set_cookie_header(header) - header = @set_cookies.inject(header) { |m, (k, v)| - if write_cookie?(v) - ::Rack::Utils.add_cookie_to_header(m, k, v) - else - m - end - } - @delete_cookies.inject(header) { |m, (k, v)| - ::Rack::Utils.add_remove_cookie_to_header(m, k, v) - } - end - - def write_cookie?(cookie) - request.ssl? || !cookie[:secure] || always_write_cookie - end - end - - class AbstractCookieJar # :nodoc: - include ChainedCookieJars - - def initialize(parent_jar) - @parent_jar = parent_jar - end - - def [](name) - if data = @parent_jar[name.to_s] - parse name, data - end - end - - def []=(name, options) - if options.is_a?(Hash) - options.symbolize_keys! - else - options = { value: options } - end - - commit(options) - @parent_jar[name] = options - end - - protected - def request; @parent_jar.request; end - - private - def parse(name, data); data; end - def commit(options); end - end - - class PermanentCookieJar < AbstractCookieJar # :nodoc: - private - def commit(options) - options[:expires] = 20.years.from_now - end - end - - class JsonSerializer # :nodoc: - def self.load(value) - ActiveSupport::JSON.decode(value) - end - - def self.dump(value) - ActiveSupport::JSON.encode(value) - end - end - - module SerializedCookieJars # :nodoc: - MARSHAL_SIGNATURE = "\x04\x08".freeze - - protected - def needs_migration?(value) - request.cookies_serializer == :hybrid && value.start_with?(MARSHAL_SIGNATURE) - end - - def serialize(value) - serializer.dump(value) - end - - def deserialize(name, value) - if value - if needs_migration?(value) - Marshal.load(value).tap do |v| - self[name] = { value: v } - end - else - serializer.load(value) - end - end - end - - def serializer - serializer = request.cookies_serializer || :marshal - case serializer - when :marshal - Marshal - when :json, :hybrid - JsonSerializer - else - serializer - end - end - - def digest - request.cookies_digest || "SHA1" - end - - def key_generator - request.key_generator - end - end - - class SignedCookieJar < AbstractCookieJar # :nodoc: - include SerializedCookieJars - - def initialize(parent_jar) - super - secret = key_generator.generate_key(request.signed_cookie_salt) - @verifier = ActiveSupport::MessageVerifier.new(secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer) - end - - private - def parse(name, signed_message) - deserialize name, @verifier.verified(signed_message) - end - - def commit(options) - options[:value] = @verifier.generate(serialize(options[:value])) - - raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE - end - end - - # UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if - # secrets.secret_token and secrets.secret_key_base are both set. It reads - # legacy cookies signed with the old dummy key generator and signs and - # re-saves them using the new key generator to provide a smooth upgrade path. - class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc: - include VerifyAndUpgradeLegacySignedMessage - end - - class EncryptedCookieJar < AbstractCookieJar # :nodoc: - include SerializedCookieJars - - def initialize(parent_jar) - super - - if ActiveSupport::LegacyKeyGenerator === key_generator - raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " \ - "Read the upgrade documentation to learn more about this new config option." - end - - secret = key_generator.generate_key(request.encrypted_cookie_salt || "")[0, ActiveSupport::MessageEncryptor.key_len] - sign_secret = key_generator.generate_key(request.encrypted_signed_cookie_salt || "") - @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer) - end - - private - def parse(name, encrypted_message) - deserialize name, @encryptor.decrypt_and_verify(encrypted_message) - rescue ActiveSupport::MessageVerifier::InvalidSignature, ActiveSupport::MessageEncryptor::InvalidMessage - nil - end - - def commit(options) - options[:value] = @encryptor.encrypt_and_sign(serialize(options[:value])) - - raise CookieOverflow if options[:value].bytesize > MAX_COOKIE_SIZE - end - end - - # UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore - # instead of EncryptedCookieJar if secrets.secret_token and secrets.secret_key_base - # are both set. It reads legacy cookies signed with the old dummy key generator and - # encrypts and re-saves them using the new key generator to provide a smooth upgrade path. - class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc: - include VerifyAndUpgradeLegacySignedMessage - end - - def initialize(app) - @app = app - end - - def call(env) - request = ActionDispatch::Request.new env - - status, headers, body = @app.call(env) - - if request.have_cookie_jar? - cookie_jar = request.cookie_jar - unless cookie_jar.committed? - cookie_jar.write(headers) - if headers[HTTP_HEADER].respond_to?(:join) - headers[HTTP_HEADER] = headers[HTTP_HEADER].join("\n") - end - end - end - - [status, headers, body] - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/debug_exceptions.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/debug_exceptions.rb deleted file mode 100644 index 1c720c5a8e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/debug_exceptions.rb +++ /dev/null @@ -1,203 +0,0 @@ -require "action_dispatch/http/request" -require "action_dispatch/middleware/exception_wrapper" -require "action_dispatch/routing/inspector" -require "action_view" -require "action_view/base" - -require "pp" - -module ActionDispatch - # This middleware is responsible for logging exceptions and - # showing a debugging page in case the request is local. - class DebugExceptions - RESCUES_TEMPLATE_PATH = File.expand_path("../templates", __FILE__) - - class DebugView < ActionView::Base - def debug_params(params) - clean_params = params.clone - clean_params.delete("action") - clean_params.delete("controller") - - if clean_params.empty? - "None" - else - PP.pp(clean_params, "", 200) - end - end - - def debug_headers(headers) - if headers.present? - headers.inspect.gsub(",", ",\n") - else - "None" - end - end - - def debug_hash(object) - object.to_hash.sort_by { |k, _| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n") - end - - def render(*) - logger = ActionView::Base.logger - - if logger && logger.respond_to?(:silence) - logger.silence { super } - else - super - end - end - end - - def initialize(app, routes_app = nil, response_format = :default) - @app = app - @routes_app = routes_app - @response_format = response_format - end - - def call(env) - request = ActionDispatch::Request.new env - _, headers, body = response = @app.call(env) - - if headers["X-Cascade"] == "pass" - body.close if body.respond_to?(:close) - raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}" - end - - response - rescue Exception => exception - raise exception unless request.show_exceptions? - render_exception(request, exception) - end - - private - - def render_exception(request, exception) - backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner") - wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) - log_error(request, wrapper) - - if request.get_header("action_dispatch.show_detailed_exceptions") - content_type = request.formats.first - - if api_request?(content_type) - render_for_api_request(content_type, wrapper) - else - render_for_browser_request(request, wrapper) - end - else - raise exception - end - end - - def render_for_browser_request(request, wrapper) - template = create_template(request, wrapper) - file = "rescues/#{wrapper.rescue_template}" - - if request.xhr? - body = template.render(template: file, layout: false, formats: [:text]) - format = "text/plain" - else - body = template.render(template: file, layout: "rescues/layout") - format = "text/html" - end - render(wrapper.status_code, body, format) - end - - def render_for_api_request(content_type, wrapper) - body = { - status: wrapper.status_code, - error: Rack::Utils::HTTP_STATUS_CODES.fetch( - wrapper.status_code, - Rack::Utils::HTTP_STATUS_CODES[500] - ), - exception: wrapper.exception.inspect, - traces: wrapper.traces - } - - to_format = "to_#{content_type.to_sym}" - - if content_type && body.respond_to?(to_format) - formatted_body = body.public_send(to_format) - format = content_type - else - formatted_body = body.to_json - format = Mime[:json] - end - - render(wrapper.status_code, formatted_body, format) - end - - def create_template(request, wrapper) - traces = wrapper.traces - - trace_to_show = "Application Trace" - if traces[trace_to_show].empty? && wrapper.rescue_template != "routing_error" - trace_to_show = "Full Trace" - end - - if source_to_show = traces[trace_to_show].first - source_to_show_id = source_to_show[:id] - end - - DebugView.new([RESCUES_TEMPLATE_PATH], - request: request, - exception: wrapper.exception, - traces: traces, - show_source_idx: source_to_show_id, - trace_to_show: trace_to_show, - routes_inspector: routes_inspector(wrapper.exception), - source_extracts: wrapper.source_extracts, - line_number: wrapper.line_number, - file: wrapper.file - ) - end - - def render(status, body, format) - [status, { "Content-Type" => "#{format}; charset=#{Response.default_charset}", "Content-Length" => body.bytesize.to_s }, [body]] - end - - def log_error(request, wrapper) - logger = logger(request) - return unless logger - - exception = wrapper.exception - - trace = wrapper.application_trace - trace = wrapper.framework_trace if trace.empty? - - ActiveSupport::Deprecation.silence do - logger.fatal " " - logger.fatal "#{exception.class} (#{exception.message}):" - log_array logger, exception.annoted_source_code if exception.respond_to?(:annoted_source_code) - logger.fatal " " - log_array logger, trace - end - end - - def log_array(logger, array) - if logger.formatter && logger.formatter.respond_to?(:tags_text) - logger.fatal array.join("\n#{logger.formatter.tags_text}") - else - logger.fatal array.join("\n") - end - end - - def logger(request) - request.logger || ActionView::Base.logger || stderr_logger - end - - def stderr_logger - @stderr_logger ||= ActiveSupport::Logger.new($stderr) - end - - def routes_inspector(exception) - if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error)) - ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes) - end - end - - def api_request?(content_type) - @response_format == :api && !content_type.html? - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/debug_locks.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/debug_locks.rb deleted file mode 100644 index 74b952528e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/debug_locks.rb +++ /dev/null @@ -1,122 +0,0 @@ -module ActionDispatch - # This middleware can be used to diagnose deadlocks in the autoload interlock. - # - # To use it, insert it near the top of the middleware stack, using - # config/application.rb: - # - # config.middleware.insert_before Rack::Sendfile, ActionDispatch::DebugLocks - # - # After restarting the application and re-triggering the deadlock condition, - # /rails/locks will show a summary of all threads currently known to - # the interlock, which lock level they are holding or awaiting, and their - # current backtrace. - # - # Generally a deadlock will be caused by the interlock conflicting with some - # other external lock or blocking I/O call. These cannot be automatically - # identified, but should be visible in the displayed backtraces. - # - # NOTE: The formatting and content of this middleware's output is intended for - # human consumption, and should be expected to change between releases. - # - # This middleware exposes operational details of the server, with no access - # control. It should only be enabled when in use, and removed thereafter. - class DebugLocks - def initialize(app, path = "/rails/locks") - @app = app - @path = path - end - - def call(env) - req = ActionDispatch::Request.new env - - if req.get? - path = req.path_info.chomp("/".freeze) - if path == @path - return render_details(req) - end - end - - @app.call(env) - end - - private - def render_details(req) - threads = ActiveSupport::Dependencies.interlock.raw_state do |threads| - # The Interlock itself comes to a complete halt as long as this block - # is executing. That gives us a more consistent picture of everything, - # but creates a pretty strong Observer Effect. - # - # Most directly, that means we need to do as little as possible in - # this block. More widely, it means this middleware should remain a - # strictly diagnostic tool (to be used when something has gone wrong), - # and not for any sort of general monitoring. - - threads.each.with_index do |(thread, info), idx| - info[:index] = idx - info[:backtrace] = thread.backtrace - end - - threads - end - - str = threads.map do |thread, info| - if info[:exclusive] - lock_state = "Exclusive" - elsif info[:sharing] > 0 - lock_state = "Sharing" - lock_state << " x#{info[:sharing]}" if info[:sharing] > 1 - else - lock_state = "No lock" - end - - if info[:waiting] - lock_state << " (yielded share)" - end - - msg = "Thread #{info[:index]} [0x#{thread.__id__.to_s(16)} #{thread.status || 'dead'}] #{lock_state}\n" - - if info[:sleeper] - msg << " Waiting in #{info[:sleeper]}" - msg << " to #{info[:purpose].to_s.inspect}" unless info[:purpose].nil? - msg << "\n" - - if info[:compatible] - compat = info[:compatible].map { |c| c == false ? "share" : c.to_s.inspect } - msg << " may be pre-empted for: #{compat.join(', ')}\n" - end - - blockers = threads.values.select { |binfo| blocked_by?(info, binfo, threads.values) } - msg << " blocked by: #{blockers.map { |i| i[:index] }.join(', ')}\n" if blockers.any? - end - - blockees = threads.values.select { |binfo| blocked_by?(binfo, info, threads.values) } - msg << " blocking: #{blockees.map { |i| i[:index] }.join(', ')}\n" if blockees.any? - - msg << "\n#{info[:backtrace].join("\n")}\n" if info[:backtrace] - end.join("\n\n---\n\n\n") - - [200, { "Content-Type" => "text/plain", "Content-Length" => str.size }, [str]] - end - - def blocked_by?(victim, blocker, all_threads) - return false if victim.equal?(blocker) - - case victim[:sleeper] - when :start_sharing - blocker[:exclusive] || - (!victim[:waiting] && blocker[:compatible] && !blocker[:compatible].include?(false)) - when :start_exclusive - blocker[:sharing] > 0 || - blocker[:exclusive] || - (blocker[:compatible] && !blocker[:compatible].include?(victim[:purpose])) - when :yield_shares - blocker[:exclusive] - when :stop_exclusive - blocker[:exclusive] || - victim[:compatible] && - victim[:compatible].include?(blocker[:purpose]) && - all_threads.all? { |other| !other[:compatible] || blocker.equal?(other) || other[:compatible].include?(blocker[:purpose]) } - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/exception_wrapper.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/exception_wrapper.rb deleted file mode 100644 index 397f0a8b92..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/exception_wrapper.rb +++ /dev/null @@ -1,148 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" -require "rack/utils" - -module ActionDispatch - class ExceptionWrapper - cattr_accessor :rescue_responses - @@rescue_responses = Hash.new(:internal_server_error) - @@rescue_responses.merge!( - "ActionController::RoutingError" => :not_found, - "AbstractController::ActionNotFound" => :not_found, - "ActionController::MethodNotAllowed" => :method_not_allowed, - "ActionController::UnknownHttpMethod" => :method_not_allowed, - "ActionController::NotImplemented" => :not_implemented, - "ActionController::UnknownFormat" => :not_acceptable, - "ActionController::InvalidAuthenticityToken" => :unprocessable_entity, - "ActionController::InvalidCrossOriginRequest" => :unprocessable_entity, - "ActionDispatch::Http::Parameters::ParseError" => :bad_request, - "ActionController::BadRequest" => :bad_request, - "ActionController::ParameterMissing" => :bad_request, - "Rack::QueryParser::ParameterTypeError" => :bad_request, - "Rack::QueryParser::InvalidParameterError" => :bad_request - ) - - cattr_accessor :rescue_templates - @@rescue_templates = Hash.new("diagnostics") - @@rescue_templates.merge!( - "ActionView::MissingTemplate" => "missing_template", - "ActionController::RoutingError" => "routing_error", - "AbstractController::ActionNotFound" => "unknown_action", - "ActionView::Template::Error" => "template_error" - ) - - attr_reader :backtrace_cleaner, :exception, :line_number, :file - - def initialize(backtrace_cleaner, exception) - @backtrace_cleaner = backtrace_cleaner - @exception = original_exception(exception) - - expand_backtrace if exception.is_a?(SyntaxError) || exception.cause.is_a?(SyntaxError) - end - - def rescue_template - @@rescue_templates[@exception.class.name] - end - - def status_code - self.class.status_code_for_exception(@exception.class.name) - end - - def application_trace - clean_backtrace(:silent) - end - - def framework_trace - clean_backtrace(:noise) - end - - def full_trace - clean_backtrace(:all) - end - - def traces - application_trace_with_ids = [] - framework_trace_with_ids = [] - full_trace_with_ids = [] - - full_trace.each_with_index do |trace, idx| - trace_with_id = { id: idx, trace: trace } - - if application_trace.include?(trace) - application_trace_with_ids << trace_with_id - else - framework_trace_with_ids << trace_with_id - end - - full_trace_with_ids << trace_with_id - end - - { - "Application Trace" => application_trace_with_ids, - "Framework Trace" => framework_trace_with_ids, - "Full Trace" => full_trace_with_ids - } - end - - def self.status_code_for_exception(class_name) - Rack::Utils.status_code(@@rescue_responses[class_name]) - end - - def source_extracts - backtrace.map do |trace| - file, line_number = extract_file_and_line_number(trace) - - { - code: source_fragment(file, line_number), - line_number: line_number - } - end - end - - private - - def backtrace - Array(@exception.backtrace) - end - - def original_exception(exception) - if @@rescue_responses.has_key?(exception.cause.class.name) - exception.cause - else - exception - end - end - - def clean_backtrace(*args) - if backtrace_cleaner - backtrace_cleaner.clean(backtrace, *args) - else - backtrace - end - end - - def source_fragment(path, line) - return unless Rails.respond_to?(:root) && Rails.root - full_path = Rails.root.join(path) - if File.exist?(full_path) - File.open(full_path, "r") do |file| - start = [line - 3, 0].max - lines = file.each_line.drop(start).take(6) - Hash[*(start + 1..(lines.count + start)).zip(lines).flatten] - end - end - end - - def extract_file_and_line_number(trace) - # Split by the first colon followed by some digits, which works for both - # Windows and Unix path styles. - file, line = trace.match(/^(.+?):(\d+).*$/, &:captures) || trace - [file, line.to_i] - end - - def expand_backtrace - @exception.backtrace.unshift( - @exception.to_s.split("\n") - ).flatten! - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/executor.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/executor.rb deleted file mode 100644 index 3d43f97a2b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/executor.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "rack/body_proxy" - -module ActionDispatch - class Executor - def initialize(app, executor) - @app, @executor = app, executor - end - - def call(env) - state = @executor.run! - begin - response = @app.call(env) - returned = response << ::Rack::BodyProxy.new(response.pop) { state.complete! } - ensure - state.complete! unless returned - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/flash.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/flash.rb deleted file mode 100644 index cbe2f4be4d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/flash.rb +++ /dev/null @@ -1,298 +0,0 @@ -require "active_support/core_ext/hash/keys" - -module ActionDispatch - # The flash provides a way to pass temporary primitive-types (String, Array, Hash) between actions. Anything you place in the flash will be exposed - # to the very next action and then cleared out. This is a great way of doing notices and alerts, such as a create - # action that sets flash[:notice] = "Post successfully created" before redirecting to a display action that can - # then expose the flash to its template. Actually, that exposure is automatically done. - # - # class PostsController < ActionController::Base - # def create - # # save post - # flash[:notice] = "Post successfully created" - # redirect_to @post - # end - # - # def show - # # doesn't need to assign the flash notice to the template, that's done automatically - # end - # end - # - # show.html.erb - # <% if flash[:notice] %> - #
<%= flash[:notice] %>
- # <% end %> - # - # Since the +notice+ and +alert+ keys are a common idiom, convenience accessors are available: - # - # flash.alert = "You must be logged in" - # flash.notice = "Post successfully created" - # - # This example places a string in the flash. And of course, you can put as many as you like at a time too. If you want to pass - # non-primitive types, you will have to handle that in your application. Example: To show messages with links, you will have to - # use sanitize helper. - # - # Just remember: They'll be gone by the time the next action has been performed. - # - # See docs on the FlashHash class for more details about the flash. - class Flash - KEY = "action_dispatch.request.flash_hash".freeze - - module RequestMethods - # Access the contents of the flash. Use flash["notice"] to - # read a notice you put there or flash["notice"] = "hello" - # to put a new one. - def flash - flash = flash_hash - return flash if flash - self.flash = Flash::FlashHash.from_session_value(session["flash"]) - end - - def flash=(flash) - set_header Flash::KEY, flash - end - - def flash_hash # :nodoc: - get_header Flash::KEY - end - - def commit_flash # :nodoc: - session = self.session || {} - flash_hash = self.flash_hash - - if flash_hash && (flash_hash.present? || session.key?("flash")) - session["flash"] = flash_hash.to_session_value - self.flash = flash_hash.dup - end - - if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?) - session.key?("flash") && session["flash"].nil? - session.delete("flash") - end - end - - def reset_session # :nodoc - super - self.flash = nil - end - end - - class FlashNow #:nodoc: - attr_accessor :flash - - def initialize(flash) - @flash = flash - end - - def []=(k, v) - k = k.to_s - @flash[k] = v - @flash.discard(k) - v - end - - def [](k) - @flash[k.to_s] - end - - # Convenience accessor for flash.now[:alert]=. - def alert=(message) - self[:alert] = message - end - - # Convenience accessor for flash.now[:notice]=. - def notice=(message) - self[:notice] = message - end - end - - class FlashHash - include Enumerable - - def self.from_session_value(value) #:nodoc: - case value - when FlashHash # Rails 3.1, 3.2 - flashes = value.instance_variable_get(:@flashes) - if discard = value.instance_variable_get(:@used) - flashes.except!(*discard) - end - new(flashes, flashes.keys) - when Hash # Rails 4.0 - flashes = value["flashes"] - if discard = value["discard"] - flashes.except!(*discard) - end - new(flashes, flashes.keys) - else - new - end - end - - # Builds a hash containing the flashes to keep for the next request. - # If there are none to keep, returns +nil+. - def to_session_value #:nodoc: - flashes_to_keep = @flashes.except(*@discard) - return nil if flashes_to_keep.empty? - { "discard" => [], "flashes" => flashes_to_keep } - end - - def initialize(flashes = {}, discard = []) #:nodoc: - @discard = Set.new(stringify_array(discard)) - @flashes = flashes.stringify_keys - @now = nil - end - - def initialize_copy(other) - if other.now_is_loaded? - @now = other.now.dup - @now.flash = self - end - super - end - - def []=(k, v) - k = k.to_s - @discard.delete k - @flashes[k] = v - end - - def [](k) - @flashes[k.to_s] - end - - def update(h) #:nodoc: - @discard.subtract stringify_array(h.keys) - @flashes.update h.stringify_keys - self - end - - def keys - @flashes.keys - end - - def key?(name) - @flashes.key? name.to_s - end - - def delete(key) - key = key.to_s - @discard.delete key - @flashes.delete key - self - end - - def to_hash - @flashes.dup - end - - def empty? - @flashes.empty? - end - - def clear - @discard.clear - @flashes.clear - end - - def each(&block) - @flashes.each(&block) - end - - alias :merge! :update - - def replace(h) #:nodoc: - @discard.clear - @flashes.replace h.stringify_keys - self - end - - # Sets a flash that will not be available to the next action, only to the current. - # - # flash.now[:message] = "Hello current action" - # - # This method enables you to use the flash as a central messaging system in your app. - # When you need to pass an object to the next action, you use the standard flash assign ([]=). - # When you need to pass an object to the current action, you use now, and your object will - # vanish when the current action is done. - # - # Entries set via now are accessed the same way as standard entries: flash['my-key']. - # - # Also, brings two convenience accessors: - # - # flash.now.alert = "Beware now!" - # # Equivalent to flash.now[:alert] = "Beware now!" - # - # flash.now.notice = "Good luck now!" - # # Equivalent to flash.now[:notice] = "Good luck now!" - def now - @now ||= FlashNow.new(self) - end - - # Keeps either the entire current flash or a specific flash entry available for the next action: - # - # flash.keep # keeps the entire flash - # flash.keep(:notice) # keeps only the "notice" entry, the rest of the flash is discarded - def keep(k = nil) - k = k.to_s if k - @discard.subtract Array(k || keys) - k ? self[k] : self - end - - # Marks the entire flash or a single flash entry to be discarded by the end of the current action: - # - # flash.discard # discard the entire flash at the end of the current action - # flash.discard(:warning) # discard only the "warning" entry at the end of the current action - def discard(k = nil) - k = k.to_s if k - @discard.merge Array(k || keys) - k ? self[k] : self - end - - # Mark for removal entries that were kept, and delete unkept ones. - # - # This method is called automatically by filters, so you generally don't need to care about it. - def sweep #:nodoc: - @discard.each { |k| @flashes.delete k } - @discard.replace @flashes.keys - end - - # Convenience accessor for flash[:alert]. - def alert - self[:alert] - end - - # Convenience accessor for flash[:alert]=. - def alert=(message) - self[:alert] = message - end - - # Convenience accessor for flash[:notice]. - def notice - self[:notice] - end - - # Convenience accessor for flash[:notice]=. - def notice=(message) - self[:notice] = message - end - - protected - def now_is_loaded? - @now - end - - private - def stringify_array(array) # :doc: - array.map do |item| - item.kind_of?(Symbol) ? item.to_s : item - end - end - end - - def self.new(app) app; end - end - - class Request - prepend Flash::RequestMethods - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/public_exceptions.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/public_exceptions.rb deleted file mode 100644 index 46f0f675b9..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/public_exceptions.rb +++ /dev/null @@ -1,55 +0,0 @@ -module ActionDispatch - # When called, this middleware renders an error page. By default if an HTML - # response is expected it will render static error pages from the `/public` - # directory. For example when this middleware receives a 500 response it will - # render the template found in `/public/500.html`. - # If an internationalized locale is set, this middleware will attempt to render - # the template in `/public/500..html`. If an internationalized template - # is not found it will fall back on `/public/500.html`. - # - # When a request with a content type other than HTML is made, this middleware - # will attempt to convert error information into the appropriate response type. - class PublicExceptions - attr_accessor :public_path - - def initialize(public_path) - @public_path = public_path - end - - def call(env) - request = ActionDispatch::Request.new(env) - status = request.path_info[1..-1].to_i - content_type = request.formats.first - body = { status: status, error: Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500]) } - - render(status, content_type, body) - end - - private - - def render(status, content_type, body) - format = "to_#{content_type.to_sym}" if content_type - if format && body.respond_to?(format) - render_format(status, content_type, body.public_send(format)) - else - render_html(status) - end - end - - def render_format(status, content_type, body) - [status, { "Content-Type" => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}", - "Content-Length" => body.bytesize.to_s }, [body]] - end - - def render_html(status) - path = "#{public_path}/#{status}.#{I18n.locale}.html" - path = "#{public_path}/#{status}.html" unless (found = File.exist?(path)) - - if found || File.exist?(path) - render_format(status, "text/html", File.read(path)) - else - [404, { "X-Cascade" => "pass" }, []] - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/reloader.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/reloader.rb deleted file mode 100644 index 6d64b1424b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/reloader.rb +++ /dev/null @@ -1,10 +0,0 @@ -module ActionDispatch - # ActionDispatch::Reloader wraps the request with callbacks provided by ActiveSupport::Reloader - # callbacks, intended to assist with code reloading during development. - # - # By default, ActionDispatch::Reloader is included in the middleware stack - # only in the development environment; specifically, when +config.cache_classes+ - # is false. - class Reloader < Executor - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/remote_ip.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/remote_ip.rb deleted file mode 100644 index 8bae5bfeff..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/remote_ip.rb +++ /dev/null @@ -1,181 +0,0 @@ -require "ipaddr" - -module ActionDispatch - # This middleware calculates the IP address of the remote client that is - # making the request. It does this by checking various headers that could - # contain the address, and then picking the last-set address that is not - # on the list of trusted IPs. This follows the precedent set by e.g. - # {the Tomcat server}[https://issues.apache.org/bugzilla/show_bug.cgi?id=50453], - # with {reasoning explained at length}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection] - # by @gingerlime. A more detailed explanation of the algorithm is given - # at GetIp#calculate_ip. - # - # Some Rack servers concatenate repeated headers, like {HTTP RFC 2616}[http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2] - # requires. Some Rack servers simply drop preceding headers, and only report - # the value that was {given in the last header}[http://andre.arko.net/2011/12/26/repeated-headers-and-ruby-web-servers]. - # If you are behind multiple proxy servers (like NGINX to HAProxy to Unicorn) - # then you should test your Rack server to make sure your data is good. - # - # IF YOU DON'T USE A PROXY, THIS MAKES YOU VULNERABLE TO IP SPOOFING. - # This middleware assumes that there is at least one proxy sitting around - # and setting headers with the client's remote IP address. If you don't use - # a proxy, because you are hosted on e.g. Heroku without SSL, any client can - # claim to have any IP address by setting the X-Forwarded-For header. If you - # care about that, then you need to explicitly drop or ignore those headers - # sometime before this middleware runs. - class RemoteIp - class IpSpoofAttackError < StandardError; end - - # The default trusted IPs list simply includes IP addresses that are - # guaranteed by the IP specification to be private addresses. Those will - # not be the ultimate client IP in production, and so are discarded. See - # http://en.wikipedia.org/wiki/Private_network for details. - TRUSTED_PROXIES = [ - "127.0.0.1", # localhost IPv4 - "::1", # localhost IPv6 - "fc00::/7", # private IPv6 range fc00::/7 - "10.0.0.0/8", # private IPv4 range 10.x.x.x - "172.16.0.0/12", # private IPv4 range 172.16.0.0 .. 172.31.255.255 - "192.168.0.0/16", # private IPv4 range 192.168.x.x - ].map { |proxy| IPAddr.new(proxy) } - - attr_reader :check_ip, :proxies - - # Create a new +RemoteIp+ middleware instance. - # - # The +ip_spoofing_check+ option is on by default. When on, an exception - # is raised if it looks like the client is trying to lie about its own IP - # address. It makes sense to turn off this check on sites aimed at non-IP - # clients (like WAP devices), or behind proxies that set headers in an - # incorrect or confusing way (like AWS ELB). - # - # The +custom_proxies+ argument can take an Array of string, IPAddr, or - # Regexp objects which will be used instead of +TRUSTED_PROXIES+. If a - # single string, IPAddr, or Regexp object is provided, it will be used in - # addition to +TRUSTED_PROXIES+. Any proxy setup will put the value you - # want in the middle (or at the beginning) of the X-Forwarded-For list, - # with your proxy servers after it. If your proxies aren't removed, pass - # them in via the +custom_proxies+ parameter. That way, the middleware will - # ignore those IP addresses, and return the one that you want. - def initialize(app, ip_spoofing_check = true, custom_proxies = nil) - @app = app - @check_ip = ip_spoofing_check - @proxies = if custom_proxies.blank? - TRUSTED_PROXIES - elsif custom_proxies.respond_to?(:any?) - custom_proxies - else - Array(custom_proxies) + TRUSTED_PROXIES - end - end - - # Since the IP address may not be needed, we store the object here - # without calculating the IP to keep from slowing down the majority of - # requests. For those requests that do need to know the IP, the - # GetIp#calculate_ip method will calculate the memoized client IP address. - def call(env) - req = ActionDispatch::Request.new env - req.remote_ip = GetIp.new(req, check_ip, proxies) - @app.call(req.env) - end - - # The GetIp class exists as a way to defer processing of the request data - # into an actual IP address. If the ActionDispatch::Request#remote_ip method - # is called, this class will calculate the value and then memoize it. - class GetIp - def initialize(req, check_ip, proxies) - @req = req - @check_ip = check_ip - @proxies = proxies - end - - # Sort through the various IP address headers, looking for the IP most - # likely to be the address of the actual remote client making this - # request. - # - # REMOTE_ADDR will be correct if the request is made directly against the - # Ruby process, on e.g. Heroku. When the request is proxied by another - # server like HAProxy or NGINX, the IP address that made the original - # request will be put in an X-Forwarded-For header. If there are multiple - # proxies, that header may contain a list of IPs. Other proxy services - # set the Client-Ip header instead, so we check that too. - # - # As discussed in {this post about Rails IP Spoofing}[http://blog.gingerlime.com/2012/rails-ip-spoofing-vulnerabilities-and-protection/], - # while the first IP in the list is likely to be the "originating" IP, - # it could also have been set by the client maliciously. - # - # In order to find the first address that is (probably) accurate, we - # take the list of IPs, remove known and trusted proxies, and then take - # the last address left, which was presumably set by one of those proxies. - def calculate_ip - # Set by the Rack web server, this is a single value. - remote_addr = ips_from(@req.remote_addr).last - - # Could be a CSV list and/or repeated headers that were concatenated. - client_ips = ips_from(@req.client_ip).reverse - forwarded_ips = ips_from(@req.x_forwarded_for).reverse - - # +Client-Ip+ and +X-Forwarded-For+ should not, generally, both be set. - # If they are both set, it means that either: - # - # 1) This request passed through two proxies with incompatible IP header - # conventions. - # 2) The client passed one of +Client-Ip+ or +X-Forwarded-For+ - # (whichever the proxy servers weren't using) themselves. - # - # Either way, there is no way for us to determine which header is the - # right one after the fact. Since we have no idea, if we are concerned - # about IP spoofing we need to give up and explode. (If you're not - # concerned about IP spoofing you can turn the +ip_spoofing_check+ - # option off.) - should_check_ip = @check_ip && client_ips.last && forwarded_ips.last - if should_check_ip && !forwarded_ips.include?(client_ips.last) - # We don't know which came from the proxy, and which from the user - raise IpSpoofAttackError, "IP spoofing attack?! " \ - "HTTP_CLIENT_IP=#{@req.client_ip.inspect} " \ - "HTTP_X_FORWARDED_FOR=#{@req.x_forwarded_for.inspect}" - end - - # We assume these things about the IP headers: - # - # - X-Forwarded-For will be a list of IPs, one per proxy, or blank - # - Client-Ip is propagated from the outermost proxy, or is blank - # - REMOTE_ADDR will be the IP that made the request to Rack - ips = [forwarded_ips, client_ips, remote_addr].flatten.compact - - # If every single IP option is in the trusted list, just return REMOTE_ADDR - filter_proxies(ips).first || remote_addr - end - - # Memoizes the value returned by #calculate_ip and returns it for - # ActionDispatch::Request to use. - def to_s - @ip ||= calculate_ip - end - - private - - def ips_from(header) # :doc: - return [] unless header - # Split the comma-separated list into an array of strings - ips = header.strip.split(/[,\s]+/) - ips.select do |ip| - begin - # Only return IPs that are valid according to the IPAddr#new method - range = IPAddr.new(ip).to_range - # we want to make sure nobody is sneaking a netmask in - range.begin == range.end - rescue ArgumentError - nil - end - end - end - - def filter_proxies(ips) # :doc: - ips.reject do |ip| - @proxies.any? { |proxy| proxy === ip } - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/request_id.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/request_id.rb deleted file mode 100644 index 1925ffd9dd..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/request_id.rb +++ /dev/null @@ -1,41 +0,0 @@ -require "securerandom" -require "active_support/core_ext/string/access" - -module ActionDispatch - # Makes a unique request id available to the +action_dispatch.request_id+ env variable (which is then accessible - # through ActionDispatch::Request#request_id or the alias ActionDispatch::Request#uuid) and sends - # the same id to the client via the X-Request-Id header. - # - # The unique request id is either based on the X-Request-Id header in the request, which would typically be generated - # by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the - # header is accepted from the outside world, we sanitize it to a max of 255 chars and alphanumeric and dashes only. - # - # The unique request id can be used to trace a request end-to-end and would typically end up being part of log files - # from multiple pieces of the stack. - class RequestId - X_REQUEST_ID = "X-Request-Id".freeze #:nodoc: - - def initialize(app) - @app = app - end - - def call(env) - req = ActionDispatch::Request.new env - req.request_id = make_request_id(req.x_request_id) - @app.call(env).tap { |_status, headers, _body| headers[X_REQUEST_ID] = req.request_id } - end - - private - def make_request_id(request_id) - if request_id.presence - request_id.gsub(/[^\w\-]/, "".freeze).first(255) - else - internal_request_id - end - end - - def internal_request_id - SecureRandom.uuid - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/abstract_store.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/abstract_store.rb deleted file mode 100644 index d9f018c8ac..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/abstract_store.rb +++ /dev/null @@ -1,90 +0,0 @@ -require "rack/utils" -require "rack/request" -require "rack/session/abstract/id" -require "action_dispatch/middleware/cookies" -require "action_dispatch/request/session" - -module ActionDispatch - module Session - class SessionRestoreError < StandardError #:nodoc: - def initialize - super("Session contains objects whose class definition isn't available.\n" \ - "Remember to require the classes for all objects kept in the session.\n" \ - "(Original exception: #{$!.message} [#{$!.class}])\n") - set_backtrace $!.backtrace - end - end - - module Compatibility - def initialize(app, options = {}) - options[:key] ||= "_session_id" - super - end - - def generate_sid - sid = SecureRandom.hex(16) - sid.encode!(Encoding::UTF_8) - sid - end - - private - - def initialize_sid # :doc: - @default_options.delete(:sidbits) - @default_options.delete(:secure_random) - end - - def make_request(env) - ActionDispatch::Request.new env - end - end - - module StaleSessionCheck - def load_session(env) - stale_session_check! { super } - end - - def extract_session_id(env) - stale_session_check! { super } - end - - def stale_session_check! - yield - rescue ArgumentError => argument_error - if argument_error.message =~ %r{undefined class/module ([\w:]*\w)} - begin - # Note that the regexp does not allow $1 to end with a ':' - $1.constantize - rescue LoadError, NameError - raise ActionDispatch::Session::SessionRestoreError - end - retry - else - raise - end - end - end - - module SessionObject # :nodoc: - def prepare_session(req) - Request::Session.create(self, req, @default_options) - end - - def loaded_session?(session) - !session.is_a?(Request::Session) || session.loaded? - end - end - - class AbstractStore < Rack::Session::Abstract::Persisted - include Compatibility - include StaleSessionCheck - include SessionObject - - private - - def set_cookie(request, session_id, cookie) - request.cookie_jar[key] = cookie - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/cache_store.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/cache_store.rb deleted file mode 100644 index 71274bc13a..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/cache_store.rb +++ /dev/null @@ -1,52 +0,0 @@ -require "action_dispatch/middleware/session/abstract_store" - -module ActionDispatch - module Session - # A session store that uses an ActiveSupport::Cache::Store to store the sessions. This store is most useful - # if you don't store critical data in your sessions and you don't need them to live for extended periods - # of time. - # - # ==== Options - # * cache - The cache to use. If it is not specified, Rails.cache will be used. - # * expire_after - The length of time a session will be stored before automatically expiring. - # By default, the :expires_in option of the cache is used. - class CacheStore < AbstractStore - def initialize(app, options = {}) - @cache = options[:cache] || Rails.cache - options[:expire_after] ||= @cache.options[:expires_in] - super - end - - # Get a session from the cache. - def find_session(env, sid) - unless sid && (session = @cache.read(cache_key(sid))) - sid, session = generate_sid, {} - end - [sid, session] - end - - # Set a session in the cache. - def write_session(env, sid, session, options) - key = cache_key(sid) - if session - @cache.write(key, session, expires_in: options[:expire_after]) - else - @cache.delete(key) - end - sid - end - - # Remove a session from the cache. - def delete_session(env, sid, options) - @cache.delete(cache_key(sid)) - generate_sid - end - - private - # Turn the session id into a cache key. - def cache_key(sid) - "_session_id:#{sid}" - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/cookie_store.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/cookie_store.rb deleted file mode 100644 index 57d325a9d8..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/cookie_store.rb +++ /dev/null @@ -1,129 +0,0 @@ -require "active_support/core_ext/hash/keys" -require "action_dispatch/middleware/session/abstract_store" -require "rack/session/cookie" - -module ActionDispatch - module Session - # This cookie-based session store is the Rails default. It is - # dramatically faster than the alternatives. - # - # Sessions typically contain at most a user_id and flash message; both fit - # within the 4K cookie size limit. A CookieOverflow exception is raised if - # you attempt to store more than 4K of data. - # - # The cookie jar used for storage is automatically configured to be the - # best possible option given your application's configuration. - # - # If you only have secret_token set, your cookies will be signed, but - # not encrypted. This means a user cannot alter their +user_id+ without - # knowing your app's secret key, but can easily read their +user_id+. This - # was the default for Rails 3 apps. - # - # If you have secret_key_base set, your cookies will be encrypted. This - # goes a step further than signed cookies in that encrypted cookies cannot - # be altered or read by users. This is the default starting in Rails 4. - # - # If you have both secret_token and secret_key_base set, your cookies will - # be encrypted, and signed cookies generated by Rails 3 will be - # transparently read and encrypted to provide a smooth upgrade path. - # - # Configure your session store in config/initializers/session_store.rb: - # - # Rails.application.config.session_store :cookie_store, key: '_your_app_session' - # - # Configure your secret key in config/secrets.yml: - # - # development: - # secret_key_base: 'secret key' - # - # To generate a secret key for an existing application, run `rails secret`. - # - # If you are upgrading an existing Rails 3 app, you should leave your - # existing secret_token in place and simply add the new secret_key_base. - # Note that you should wait to set secret_key_base until you have 100% of - # your userbase on Rails 4 and are reasonably sure you will not need to - # rollback to Rails 3. This is because cookies signed based on the new - # secret_key_base in Rails 4 are not backwards compatible with Rails 3. - # You are free to leave your existing secret_token in place, not set the - # new secret_key_base, and ignore the deprecation warnings until you are - # reasonably sure that your upgrade is otherwise complete. Additionally, - # you should take care to make sure you are not relying on the ability to - # decode signed cookies generated by your app in external applications or - # JavaScript before upgrading. - # - # Note that changing the secret key will invalidate all existing sessions! - # - # Because CookieStore extends Rack::Session::Abstract::Persisted, many of the - # options described there can be used to customize the session cookie that - # is generated. For example: - # - # Rails.application.config.session_store :cookie_store, expire_after: 14.days - # - # would set the session cookie to expire automatically 14 days after creation. - # Other useful options include :key, :secure and - # :httponly. - class CookieStore < AbstractStore - def initialize(app, options = {}) - super(app, options.merge!(cookie_only: true)) - end - - def delete_session(req, session_id, options) - new_sid = generate_sid unless options[:drop] - # Reset hash and Assign the new session id - req.set_header("action_dispatch.request.unsigned_session_cookie", new_sid ? { "session_id" => new_sid } : {}) - new_sid - end - - def load_session(req) - stale_session_check! do - data = unpacked_cookie_data(req) - data = persistent_session_id!(data) - [data["session_id"], data] - end - end - - private - - def extract_session_id(req) - stale_session_check! do - unpacked_cookie_data(req)["session_id"] - end - end - - def unpacked_cookie_data(req) - req.fetch_header("action_dispatch.request.unsigned_session_cookie") do |k| - v = stale_session_check! do - if data = get_cookie(req) - data.stringify_keys! - end - data || {} - end - req.set_header k, v - end - end - - def persistent_session_id!(data, sid = nil) - data ||= {} - data["session_id"] ||= sid || generate_sid - data - end - - def write_session(req, sid, session_data, options) - session_data["session_id"] = sid - session_data - end - - def set_cookie(request, session_id, cookie) - cookie_jar(request)[@key] = cookie - end - - def get_cookie(req) - cookie_jar(req)[@key] - end - - def cookie_jar(request) - request.cookie_jar.signed_or_encrypted - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/mem_cache_store.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/mem_cache_store.rb deleted file mode 100644 index ee2b1f26ad..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/session/mem_cache_store.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "action_dispatch/middleware/session/abstract_store" -begin - require "rack/session/dalli" -rescue LoadError => e - $stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install" - raise e -end - -module ActionDispatch - module Session - # A session store that uses MemCache to implement storage. - # - # ==== Options - # * expire_after - The length of time a session will be stored before automatically expiring. - class MemCacheStore < Rack::Session::Dalli - include Compatibility - include StaleSessionCheck - include SessionObject - - def initialize(app, options = {}) - options[:expire_after] ||= options[:expires] - super - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/show_exceptions.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/show_exceptions.rb deleted file mode 100644 index 90f26a1c33..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/show_exceptions.rb +++ /dev/null @@ -1,60 +0,0 @@ -require "action_dispatch/http/request" -require "action_dispatch/middleware/exception_wrapper" - -module ActionDispatch - # This middleware rescues any exception returned by the application - # and calls an exceptions app that will wrap it in a format for the end user. - # - # The exceptions app should be passed as parameter on initialization - # of ShowExceptions. Every time there is an exception, ShowExceptions will - # store the exception in env["action_dispatch.exception"], rewrite the - # PATH_INFO to the exception status code and call the rack app. - # - # If the application returns a "X-Cascade" pass response, this middleware - # will send an empty response as result with the correct status code. - # If any exception happens inside the exceptions app, this middleware - # catches the exceptions and returns a FAILSAFE_RESPONSE. - class ShowExceptions - FAILSAFE_RESPONSE = [500, { "Content-Type" => "text/plain" }, - ["500 Internal Server Error\n" \ - "If you are the administrator of this website, then please read this web " \ - "application's log file and/or the web server's log file to find out what " \ - "went wrong."]] - - def initialize(app, exceptions_app) - @app = app - @exceptions_app = exceptions_app - end - - def call(env) - request = ActionDispatch::Request.new env - @app.call(env) - rescue Exception => exception - if request.show_exceptions? - render_exception(request, exception) - else - raise exception - end - end - - private - - def render_exception(request, exception) - backtrace_cleaner = request.get_header "action_dispatch.backtrace_cleaner" - wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) - status = wrapper.status_code - request.set_header "action_dispatch.exception", wrapper.exception - request.set_header "action_dispatch.original_path", request.path_info - request.path_info = "/#{status}" - response = @exceptions_app.call(request.env) - response[1]["X-Cascade"] == "pass" ? pass_response(status) : response - rescue Exception => failsafe_error - $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}" - FAILSAFE_RESPONSE - end - - def pass_response(status) - [status, { "Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0" }, []] - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/ssl.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/ssl.rb deleted file mode 100644 index ffb2ae7dbd..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/ssl.rb +++ /dev/null @@ -1,144 +0,0 @@ -module ActionDispatch - # This middleware is added to the stack when `config.force_ssl = true`, and is passed - # the options set in `config.ssl_options`. It does three jobs to enforce secure HTTP - # requests: - # - # 1. TLS redirect: Permanently redirects http:// requests to https:// - # with the same URL host, path, etc. Enabled by default. Set `config.ssl_options` - # to modify the destination URL - # (e.g. `redirect: { host: "secure.widgets.com", port: 8080 }`), or set - # `redirect: false` to disable this feature. - # - # Cookies will not be flagged as secure for excluded requests. - # - # 2. Secure cookies: Sets the `secure` flag on cookies to tell browsers they - # mustn't be sent along with http:// requests. Enabled by default. Set - # `config.ssl_options` with `secure_cookies: false` to disable this feature. - # - # 3. HTTP Strict Transport Security (HSTS): Tells the browser to remember - # this site as TLS-only and automatically redirect non-TLS requests. - # Enabled by default. Configure `config.ssl_options` with `hsts: false` to disable. - # - # Set `config.ssl_options` with `hsts: { … }` to configure HSTS: - # * `expires`: How long, in seconds, these settings will stick. The minimum - # required to qualify for browser preload lists is `18.weeks`. Defaults to - # `180.days` (recommended). - # * `subdomains`: Set to `true` to tell the browser to apply these settings - # to all subdomains. This protects your cookies from interception by a - # vulnerable site on a subdomain. Defaults to `true`. - # * `preload`: Advertise that this site may be included in browsers' - # preloaded HSTS lists. HSTS protects your site on every visit *except the - # first visit* since it hasn't seen your HSTS header yet. To close this - # gap, browser vendors include a baked-in list of HSTS-enabled sites. - # Go to https://hstspreload.appspot.com to submit your site for inclusion. - # Defaults to `false`. - # - # To turn off HSTS, omitting the header is not enough. Browsers will remember the - # original HSTS directive until it expires. Instead, use the header to tell browsers to - # expire HSTS immediately. Setting `hsts: false` is a shortcut for - # `hsts: { expires: 0 }`. - # - # Requests can opt-out of redirection with `exclude`: - # - # config.ssl_options = { redirect: { exclude: -> request { request.path =~ /healthcheck/ } } } - class SSL - # Default to 180 days, the low end for https://www.ssllabs.com/ssltest/ - # and greater than the 18-week requirement for browser preload lists. - HSTS_EXPIRES_IN = 15552000 - - def self.default_hsts_options - { expires: HSTS_EXPIRES_IN, subdomains: true, preload: false } - end - - def initialize(app, redirect: {}, hsts: {}, secure_cookies: true) - @app = app - - @redirect = redirect - - @exclude = @redirect && @redirect[:exclude] || proc { !@redirect } - @secure_cookies = secure_cookies - - @hsts_header = build_hsts_header(normalize_hsts_options(hsts)) - end - - def call(env) - request = Request.new env - - if request.ssl? - @app.call(env).tap do |status, headers, body| - set_hsts_header! headers - flag_cookies_as_secure! headers if @secure_cookies && !@exclude.call(request) - end - else - return redirect_to_https request unless @exclude.call(request) - @app.call(env) - end - end - - private - def set_hsts_header!(headers) - headers["Strict-Transport-Security".freeze] ||= @hsts_header - end - - def normalize_hsts_options(options) - case options - # Explicitly disabling HSTS clears the existing setting from browsers - # by setting expiry to 0. - when false - self.class.default_hsts_options.merge(expires: 0) - # Default to enabled, with default options. - when nil, true - self.class.default_hsts_options - else - self.class.default_hsts_options.merge(options) - end - end - - # http://tools.ietf.org/html/rfc6797#section-6.1 - def build_hsts_header(hsts) - value = "max-age=#{hsts[:expires].to_i}" - value << "; includeSubDomains" if hsts[:subdomains] - value << "; preload" if hsts[:preload] - value - end - - def flag_cookies_as_secure!(headers) - if cookies = headers["Set-Cookie".freeze] - cookies = cookies.split("\n".freeze) - - headers["Set-Cookie".freeze] = cookies.map { |cookie| - if cookie !~ /;\s*secure\s*(;|$)/i - "#{cookie}; secure" - else - cookie - end - }.join("\n".freeze) - end - end - - def redirect_to_https(request) - [ @redirect.fetch(:status, redirection_status(request)), - { "Content-Type" => "text/html", - "Location" => https_location_for(request) }, - @redirect.fetch(:body, []) ] - end - - def redirection_status(request) - if request.get? || request.head? - 301 # Issue a permanent redirect via a GET request. - else - 307 # Issue a fresh request redirect to preserve the HTTP method. - end - end - - def https_location_for(request) - host = @redirect[:host] || request.host - port = @redirect[:port] || request.port - - location = "https://#{host}" - location << ":#{port}" if port != 80 && port != 443 - location << request.fullpath - location - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/stack.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/stack.rb deleted file mode 100644 index 6949b31e75..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/stack.rb +++ /dev/null @@ -1,114 +0,0 @@ -require "active_support/inflector/methods" -require "active_support/dependencies" - -module ActionDispatch - class MiddlewareStack - class Middleware - attr_reader :args, :block, :klass - - def initialize(klass, args, block) - @klass = klass - @args = args - @block = block - end - - def name; klass.name; end - - def ==(middleware) - case middleware - when Middleware - klass == middleware.klass - when Class - klass == middleware - end - end - - def inspect - if klass.is_a?(Class) - klass.to_s - else - klass.class.to_s - end - end - - def build(app) - klass.new(app, *args, &block) - end - end - - include Enumerable - - attr_accessor :middlewares - - def initialize(*args) - @middlewares = [] - yield(self) if block_given? - end - - def each - @middlewares.each { |x| yield x } - end - - def size - middlewares.size - end - - def last - middlewares.last - end - - def [](i) - middlewares[i] - end - - def unshift(klass, *args, &block) - middlewares.unshift(build_middleware(klass, args, block)) - end - - def initialize_copy(other) - self.middlewares = other.middlewares.dup - end - - def insert(index, klass, *args, &block) - index = assert_index(index, :before) - middlewares.insert(index, build_middleware(klass, args, block)) - end - - alias_method :insert_before, :insert - - def insert_after(index, *args, &block) - index = assert_index(index, :after) - insert(index + 1, *args, &block) - end - - def swap(target, *args, &block) - index = assert_index(target, :before) - insert(index, *args, &block) - middlewares.delete_at(index + 1) - end - - def delete(target) - middlewares.delete_if { |m| m.klass == target } - end - - def use(klass, *args, &block) - middlewares.push(build_middleware(klass, args, block)) - end - - def build(app = Proc.new) - middlewares.freeze.reverse.inject(app) { |a, e| e.build(a) } - end - - private - - def assert_index(index, where) - i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index } - raise "No such middleware to insert #{where}: #{index.inspect}" unless i - i - end - - def build_middleware(klass, args, block) - Middleware.new(klass, args, block) - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/static.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/static.rb deleted file mode 100644 index 5d10129d21..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/static.rb +++ /dev/null @@ -1,128 +0,0 @@ -require "rack/utils" -require "active_support/core_ext/uri" - -module ActionDispatch - # This middleware returns a file's contents from disk in the body response. - # When initialized, it can accept optional HTTP headers, which will be set - # when a response containing a file's contents is delivered. - # - # This middleware will render the file specified in `env["PATH_INFO"]` - # where the base path is in the +root+ directory. For example, if the +root+ - # is set to `public/`, then a request with `env["PATH_INFO"]` of - # `assets/application.js` will return a response with the contents of a file - # located at `public/assets/application.js` if the file exists. If the file - # does not exist, a 404 "File not Found" response will be returned. - class FileHandler - def initialize(root, index: "index", headers: {}) - @root = root.chomp("/") - @file_server = ::Rack::File.new(@root, headers) - @index = index - end - - # Takes a path to a file. If the file is found, has valid encoding, and has - # correct read permissions, the return value is a URI-escaped string - # representing the filename. Otherwise, false is returned. - # - # Used by the `Static` class to check the existence of a valid file - # in the server's `public/` directory (see Static#call). - def match?(path) - path = ::Rack::Utils.unescape_path path - return false unless ::Rack::Utils.valid_path? path - path = ::Rack::Utils.clean_path_info path - - paths = [path, "#{path}#{ext}", "#{path}/#{@index}#{ext}"] - - if match = paths.detect { |p| - path = File.join(@root, p.force_encoding(Encoding::UTF_8)) - begin - File.file?(path) && File.readable?(path) - rescue SystemCallError - false - end - - } - return ::Rack::Utils.escape_path(match) - end - end - - def call(env) - serve(Rack::Request.new(env)) - end - - def serve(request) - path = request.path_info - gzip_path = gzip_file_path(path) - - if gzip_path && gzip_encoding_accepted?(request) - request.path_info = gzip_path - status, headers, body = @file_server.call(request.env) - if status == 304 - return [status, headers, body] - end - headers["Content-Encoding"] = "gzip" - headers["Content-Type"] = content_type(path) - else - status, headers, body = @file_server.call(request.env) - end - - headers["Vary"] = "Accept-Encoding" if gzip_path - - return [status, headers, body] - ensure - request.path_info = path - end - - private - def ext - ::ActionController::Base.default_static_extension - end - - def content_type(path) - ::Rack::Mime.mime_type(::File.extname(path), "text/plain".freeze) - end - - def gzip_encoding_accepted?(request) - request.accept_encoding.any? { |enc, quality| enc =~ /\bgzip\b/i } - end - - def gzip_file_path(path) - can_gzip_mime = content_type(path) =~ /\A(?:text\/|application\/javascript)/ - gzip_path = "#{path}.gz" - if can_gzip_mime && File.exist?(File.join(@root, ::Rack::Utils.unescape_path(gzip_path))) - gzip_path - else - false - end - end - end - - # This middleware will attempt to return the contents of a file's body from - # disk in the response. If a file is not found on disk, the request will be - # delegated to the application stack. This middleware is commonly initialized - # to serve assets from a server's `public/` directory. - # - # This middleware verifies the path to ensure that only files - # living in the root directory can be rendered. A request cannot - # produce a directory traversal using this middleware. Only 'GET' and 'HEAD' - # requests will result in a file being returned. - class Static - def initialize(app, path, index: "index", headers: {}) - @app = app - @file_handler = FileHandler.new(path, index: index, headers: headers) - end - - def call(env) - req = Rack::Request.new env - - if req.get? || req.head? - path = req.path_info.chomp("/".freeze) - if match = @file_handler.match?(path) - req.path_info = match - return @file_handler.serve(req) - end - end - - @app.call(req.env) - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb deleted file mode 100644 index 49b1e83551..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb +++ /dev/null @@ -1,22 +0,0 @@ -<% unless @exception.blamed_files.blank? %> - <% if (hide = @exception.blamed_files.length > 8) %> - Toggle blamed files - <% end %> -
><%= @exception.describe_blame %>
-<% end %> - -

Request

-

Parameters:

<%= debug_params(@request.filtered_parameters) %>
- -
- - -
- -
- - -
- -

Response

-

Headers:

<%= debug_headers(defined?(@response) ? @response.headers : {}) %>
diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb deleted file mode 100644 index 396768ecee..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb +++ /dev/null @@ -1,23 +0,0 @@ -<% - clean_params = @request.filtered_parameters.clone - clean_params.delete("action") - clean_params.delete("controller") - - request_dump = clean_params.empty? ? 'None' : clean_params.inspect.gsub(',', ",\n") - - def debug_hash(object) - object.to_hash.sort_by { |k, _| k.to_s }.map { |k, v| "#{k}: #{v.inspect rescue $!.message}" }.join("\n") - end unless self.class.method_defined?(:debug_hash) -%> - -Request parameters -<%= request_dump %> - -Session dump -<%= debug_hash @request.session %> - -Env dump -<%= debug_hash @request.env.slice(*@request.class::ENV_METHODS) %> - -Response headers -<%= defined?(@response) ? @response.headers.inspect.gsub(',', ",\n") : 'None' %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_source.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_source.html.erb deleted file mode 100644 index e7b913bbe4..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_source.html.erb +++ /dev/null @@ -1,27 +0,0 @@ -<% @source_extracts.each_with_index do |source_extract, index| %> - <% if source_extract[:code] %> -
" id="frame-source-<%=index%>"> -
- Extracted source (around line #<%= source_extract[:line_number] %>): -
-
- - - - - -
-
-                <% source_extract[:code].each_key do |line_number| %>
-<%= line_number -%>
-                <% end %>
-              
-
-
-<% source_extract[:code].each do |line, source| -%>
"><%= source -%>
<% end -%> -
-
-
-
- <% end %> -<% end %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_source.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_source.text.erb deleted file mode 100644 index 23a9c7ba3f..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_source.text.erb +++ /dev/null @@ -1,8 +0,0 @@ -<% @source_extracts.first(3).each do |source_extract| %> -<% if source_extract[:code] %> -Extracted source (around line #<%= source_extract[:line_number] %>): - -<% source_extract[:code].each do |line, source| -%> -<%= line == source_extract[:line_number] ? "*#{line}" : "##{line}" -%> <%= source -%><% end -%> -<% end %> -<% end %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb deleted file mode 100644 index ab57b11c7d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +++ /dev/null @@ -1,52 +0,0 @@ -<% names = @traces.keys %> - -

Rails.root: <%= defined?(Rails) && Rails.respond_to?(:root) ? Rails.root : "unset" %>

- -
- <% names.each do |name| %> - <% - show = "show('#{name.gsub(/\s/, '-')}');" - hide = (names - [name]).collect {|hide_name| "hide('#{hide_name.gsub(/\s/, '-')}');"} - %> - <%= name %> <%= '|' unless names.last == name %> - <% end %> - - <% @traces.each do |name, trace| %> -
-
<% trace.each do |frame| %><%= frame[:trace] %>
<% end %>
-
- <% end %> - - -
diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb deleted file mode 100644 index c0b53068f7..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb +++ /dev/null @@ -1,9 +0,0 @@ -Rails.root: <%= defined?(Rails) && Rails.respond_to?(:root) ? Rails.root : "unset" %> - -<% @traces.each do |name, trace| %> -<% if trace.any? %> -<%= name %> -<%= trace.map { |t| t[:trace] }.join("\n") %> - -<% end %> -<% end %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb deleted file mode 100644 index f154021ae6..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb +++ /dev/null @@ -1,16 +0,0 @@ -
-

- <%= @exception.class.to_s %> - <% if @request.parameters['controller'] %> - in <%= @request.parameters['controller'].camelize %>Controller<% if @request.parameters['action'] %>#<%= @request.parameters['action'] %><% end %> - <% end %> -

-
- -
-

<%= h @exception.message %>

- - <%= render template: "rescues/_source" %> - <%= render template: "rescues/_trace" %> - <%= render template: "rescues/_request_and_response" %> -
diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb deleted file mode 100644 index 603de54b8b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb +++ /dev/null @@ -1,9 +0,0 @@ -<%= @exception.class.to_s %><% - if @request.parameters['controller'] -%> in <%= @request.parameters['controller'].camelize %>Controller<% if @request.parameters['action'] %>#<%= @request.parameters['action'] %><% end %> -<% end %> - -<%= @exception.message %> -<%= render template: "rescues/_source" %> -<%= render template: "rescues/_trace" %> -<%= render template: "rescues/_request_and_response" %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/layout.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/layout.erb deleted file mode 100644 index e0509f56f4..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/layout.erb +++ /dev/null @@ -1,160 +0,0 @@ - - - - - Action Controller: Exception caught - - - - - - -<%= yield %> - - - diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb deleted file mode 100644 index 2a65fd06ad..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +++ /dev/null @@ -1,11 +0,0 @@ -
-

Template is missing

-
- -
-

<%= h @exception.message %>

- - <%= render template: "rescues/_source" %> - <%= render template: "rescues/_trace" %> - <%= render template: "rescues/_request_and_response" %> -
diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/missing_template.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/missing_template.text.erb deleted file mode 100644 index ae62d9eb02..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/missing_template.text.erb +++ /dev/null @@ -1,3 +0,0 @@ -Template is missing - -<%= @exception.message %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb deleted file mode 100644 index 55dd5ddc7b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +++ /dev/null @@ -1,32 +0,0 @@ -
-

Routing Error

-
-
-

<%= h @exception.message %>

- <% unless @exception.failures.empty? %> -

-

Failure reasons:

-
    - <% @exception.failures.each do |route, reason| %> -
  1. <%= route.inspect.delete('\\') %> failed because <%= reason.downcase %>
  2. - <% end %> -
-

- <% end %> - - <%= render template: "rescues/_trace" %> - - <% if @routes_inspector %> -

- Routes -

- -

- Routes match in priority from top to bottom -

- - <%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %> - <% end %> - - <%= render template: "rescues/_request_and_response" %> -
diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb deleted file mode 100644 index f6e4dac1f3..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/routing_error.text.erb +++ /dev/null @@ -1,11 +0,0 @@ -Routing Error - -<%= @exception.message %> -<% unless @exception.failures.empty? %> -Failure reasons: -<% @exception.failures.each do |route, reason| %> - - <%= route.inspect.delete('\\') %> failed because <%= reason.downcase %> -<% end %> -<% end %> - -<%= render template: "rescues/_trace", format: :text %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb deleted file mode 100644 index 5060da9369..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/template_error.html.erb +++ /dev/null @@ -1,20 +0,0 @@ -
-

- <%= @exception.cause.class.to_s %> in - <%= @request.parameters["controller"].camelize if @request.parameters["controller"] %>#<%= @request.parameters["action"] %> -

-
- -
-

- Showing <%= @exception.file_name %> where line #<%= @exception.line_number %> raised: -

-
<%= h @exception.message %>
- - <%= render template: "rescues/_source" %> - -

<%= @exception.sub_template_message %>

- - <%= render template: "rescues/_trace" %> - <%= render template: "rescues/_request_and_response" %> -
diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb deleted file mode 100644 index 78d52acd96..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/template_error.text.erb +++ /dev/null @@ -1,7 +0,0 @@ -<%= @exception.cause.class.to_s %> in <%= @request.parameters["controller"].camelize if @request.parameters["controller"] %>#<%= @request.parameters["action"] %> - -Showing <%= @exception.file_name %> where line #<%= @exception.line_number %> raised: -<%= @exception.message %> -<%= @exception.sub_template_message %> -<%= render template: "rescues/_trace", format: :text %> -<%= render template: "rescues/_request_and_response", format: :text %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb deleted file mode 100644 index 259fb2bb3b..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/unknown_action.html.erb +++ /dev/null @@ -1,6 +0,0 @@ -
-

Unknown action

-
-
-

<%= h @exception.message %>

-
diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/unknown_action.text.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/unknown_action.text.erb deleted file mode 100644 index 83973addcb..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/rescues/unknown_action.text.erb +++ /dev/null @@ -1,3 +0,0 @@ -Unknown action - -<%= @exception.message %> diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/routes/_route.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/routes/_route.html.erb deleted file mode 100644 index 6e995c85c1..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/routes/_route.html.erb +++ /dev/null @@ -1,16 +0,0 @@ - - - <% if route[:name].present? %> - <%= route[:name] %>_path - <% end %> - - - <%= route[:verb] %> - - - <%= route[:path] %> - - - <%=simple_format route[:reqs] %> - - diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/routes/_table.html.erb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/routes/_table.html.erb deleted file mode 100644 index 429ea7057c..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/middleware/templates/routes/_table.html.erb +++ /dev/null @@ -1,196 +0,0 @@ -<% content_for :style do %> - #route_table { - margin: 0; - border-collapse: collapse; - } - - #route_table thead tr { - border-bottom: 2px solid #ddd; - } - - #route_table thead tr.bottom { - border-bottom: none; - } - - #route_table thead tr.bottom th { - padding: 10px 0; - line-height: 15px; - } - - #route_table tbody tr { - border-bottom: 1px solid #ddd; - } - - #route_table tbody tr:nth-child(odd) { - background: #f2f2f2; - } - - #route_table tbody.exact_matches, - #route_table tbody.fuzzy_matches { - background-color: LightGoldenRodYellow; - border-bottom: solid 2px SlateGrey; - } - - #route_table tbody.exact_matches tr, - #route_table tbody.fuzzy_matches tr { - background: none; - border-bottom: none; - } - - #route_table td { - padding: 4px 30px; - } - - #path_search { - width: 80%; - font-size: inherit; - } -<% end %> - - - - - - - - - - - - - - - - - - - - - - <%= yield %> - -
HelperHTTP VerbPathController#Action
<%# Helper %> - <%= link_to "Path", "#", 'data-route-helper' => '_path', - title: "Returns a relative path (without the http or domain)" %> / - <%= link_to "Url", "#", 'data-route-helper' => '_url', - title: "Returns an absolute url (with the http and domain)" %> - <%# HTTP Verb %> - <%# Path %> - <%= search_field(:path, nil, id: 'search', placeholder: "Path Match") %> - <%# Controller#action %> -
- - diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/railtie.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/railtie.rb deleted file mode 100644 index 16a18a7f25..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/railtie.rb +++ /dev/null @@ -1,45 +0,0 @@ -require "action_dispatch" - -module ActionDispatch - class Railtie < Rails::Railtie # :nodoc: - config.action_dispatch = ActiveSupport::OrderedOptions.new - config.action_dispatch.x_sendfile_header = nil - config.action_dispatch.ip_spoofing_check = true - config.action_dispatch.show_exceptions = true - config.action_dispatch.tld_length = 1 - config.action_dispatch.ignore_accept_header = false - config.action_dispatch.rescue_templates = {} - config.action_dispatch.rescue_responses = {} - config.action_dispatch.default_charset = nil - config.action_dispatch.rack_cache = false - config.action_dispatch.http_auth_salt = "http authentication" - config.action_dispatch.signed_cookie_salt = "signed cookie" - config.action_dispatch.encrypted_cookie_salt = "encrypted cookie" - config.action_dispatch.encrypted_signed_cookie_salt = "signed encrypted cookie" - config.action_dispatch.perform_deep_munge = true - - config.action_dispatch.default_headers = { - "X-Frame-Options" => "SAMEORIGIN", - "X-XSS-Protection" => "1; mode=block", - "X-Content-Type-Options" => "nosniff" - } - - config.eager_load_namespaces << ActionDispatch - - initializer "action_dispatch.configure" do |app| - ActionDispatch::Http::URL.tld_length = app.config.action_dispatch.tld_length - ActionDispatch::Request.ignore_accept_header = app.config.action_dispatch.ignore_accept_header - ActionDispatch::Request::Utils.perform_deep_munge = app.config.action_dispatch.perform_deep_munge - ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding - ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers - - ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses) - ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates) - - config.action_dispatch.always_write_cookie = Rails.env.development? if config.action_dispatch.always_write_cookie.nil? - ActionDispatch::Cookies::CookieJar.always_write_cookie = config.action_dispatch.always_write_cookie - - ActionDispatch.test_app = app - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/request/session.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/request/session.rb deleted file mode 100644 index a2a80f39fc..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/request/session.rb +++ /dev/null @@ -1,229 +0,0 @@ -require "rack/session/abstract/id" - -module ActionDispatch - class Request - # Session is responsible for lazily loading the session from store. - class Session # :nodoc: - ENV_SESSION_KEY = Rack::RACK_SESSION # :nodoc: - ENV_SESSION_OPTIONS_KEY = Rack::RACK_SESSION_OPTIONS # :nodoc: - - # Singleton object used to determine if an optional param wasn't specified - Unspecified = Object.new - - # Creates a session hash, merging the properties of the previous session if any - def self.create(store, req, default_options) - session_was = find req - session = Request::Session.new(store, req) - session.merge! session_was if session_was - - set(req, session) - Options.set(req, Request::Session::Options.new(store, default_options)) - session - end - - def self.find(req) - req.get_header ENV_SESSION_KEY - end - - def self.set(req, session) - req.set_header ENV_SESSION_KEY, session - end - - class Options #:nodoc: - def self.set(req, options) - req.set_header ENV_SESSION_OPTIONS_KEY, options - end - - def self.find(req) - req.get_header ENV_SESSION_OPTIONS_KEY - end - - def initialize(by, default_options) - @by = by - @delegate = default_options.dup - end - - def [](key) - @delegate[key] - end - - def id(req) - @delegate.fetch(:id) { - @by.send(:extract_session_id, req) - } - end - - def []=(k, v); @delegate[k] = v; end - def to_hash; @delegate.dup; end - def values_at(*args); @delegate.values_at(*args); end - end - - def initialize(by, req) - @by = by - @req = req - @delegate = {} - @loaded = false - @exists = nil # we haven't checked yet - end - - def id - options.id(@req) - end - - def options - Options.find @req - end - - def destroy - clear - options = self.options || {} - @by.send(:delete_session, @req, options.id(@req), options) - - # Load the new sid to be written with the response - @loaded = false - load_for_write! - end - - # Returns value of the key stored in the session or - # +nil+ if the given key is not found in the session. - def [](key) - load_for_read! - @delegate[key.to_s] - end - - # Returns true if the session has the given key or false. - def has_key?(key) - load_for_read! - @delegate.key?(key.to_s) - end - alias :key? :has_key? - alias :include? :has_key? - - # Returns keys of the session as Array. - def keys - @delegate.keys - end - - # Returns values of the session as Array. - def values - @delegate.values - end - - # Writes given value to given key of the session. - def []=(key, value) - load_for_write! - @delegate[key.to_s] = value - end - - # Clears the session. - def clear - load_for_write! - @delegate.clear - end - - # Returns the session as Hash. - def to_hash - load_for_read! - @delegate.dup.delete_if { |_, v| v.nil? } - end - - # Updates the session with given Hash. - # - # session.to_hash - # # => {"session_id"=>"e29b9ea315edf98aad94cc78c34cc9b2"} - # - # session.update({ "foo" => "bar" }) - # # => {"session_id"=>"e29b9ea315edf98aad94cc78c34cc9b2", "foo" => "bar"} - # - # session.to_hash - # # => {"session_id"=>"e29b9ea315edf98aad94cc78c34cc9b2", "foo" => "bar"} - def update(hash) - load_for_write! - @delegate.update stringify_keys(hash) - end - - # Deletes given key from the session. - def delete(key) - load_for_write! - @delegate.delete key.to_s - end - - # Returns value of the given key from the session, or raises +KeyError+ - # if can't find the given key and no default value is set. - # Returns default value if specified. - # - # session.fetch(:foo) - # # => KeyError: key not found: "foo" - # - # session.fetch(:foo, :bar) - # # => :bar - # - # session.fetch(:foo) do - # :bar - # end - # # => :bar - def fetch(key, default = Unspecified, &block) - load_for_read! - if default == Unspecified - @delegate.fetch(key.to_s, &block) - else - @delegate.fetch(key.to_s, default, &block) - end - end - - def inspect - if loaded? - super - else - "#<#{self.class}:0x#{(object_id << 1).to_s(16)} not yet loaded>" - end - end - - def exists? - return @exists unless @exists.nil? - @exists = @by.send(:session_exists?, @req) - end - - def loaded? - @loaded - end - - def empty? - load_for_read! - @delegate.empty? - end - - def merge!(other) - load_for_write! - @delegate.merge!(other) - end - - def each(&block) - to_hash.each(&block) - end - - private - - def load_for_read! - load! if !loaded? && exists? - end - - def load_for_write! - load! unless loaded? - end - - def load! - id, session = @by.load_session @req - options[:id] = id - @delegate.replace(stringify_keys(session)) - @loaded = true - end - - def stringify_keys(other) - other.each_with_object({}) { |(key, value), hash| - hash[key.to_s] = value - } - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/request/utils.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/request/utils.rb deleted file mode 100644 index a3c0e16fb3..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/request/utils.rb +++ /dev/null @@ -1,76 +0,0 @@ -module ActionDispatch - class Request - class Utils # :nodoc: - mattr_accessor :perform_deep_munge - self.perform_deep_munge = true - - def self.each_param_value(params, &block) - case params - when Array - params.each { |element| each_param_value(element, &block) } - when Hash - params.each_value { |value| each_param_value(value, &block) } - when String - block.call params - end - end - - def self.normalize_encode_params(params) - if perform_deep_munge - NoNilParamEncoder.normalize_encode_params params - else - ParamEncoder.normalize_encode_params params - end - end - - def self.check_param_encoding(params) - case params - when Array - params.each { |element| check_param_encoding(element) } - when Hash - params.each_value { |value| check_param_encoding(value) } - when String - unless params.valid_encoding? - # Raise Rack::Utils::InvalidParameterError for consistency with Rack. - # ActionDispatch::Request#GET will re-raise as a BadRequest error. - raise Rack::Utils::InvalidParameterError, "Invalid encoding for parameter: #{params.scrub}" - end - end - end - - class ParamEncoder # :nodoc: - # Convert nested Hash to HashWithIndifferentAccess. - # - def self.normalize_encode_params(params) - case params - when Array - handle_array params - when Hash - if params.has_key?(:tempfile) - ActionDispatch::Http::UploadedFile.new(params) - else - params.each_with_object({}) do |(key, val), new_hash| - new_hash[key] = normalize_encode_params(val) - end.with_indifferent_access - end - else - params - end - end - - def self.handle_array(params) - params.map! { |el| normalize_encode_params(el) } - end - end - - # Remove nils from the params hash - class NoNilParamEncoder < ParamEncoder # :nodoc: - def self.handle_array(params) - list = super - list.compact! - list - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing.rb deleted file mode 100644 index e022fe1a77..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing.rb +++ /dev/null @@ -1,258 +0,0 @@ -require "active_support/core_ext/string/filters" - -module ActionDispatch - # The routing module provides URL rewriting in native Ruby. It's a way to - # redirect incoming requests to controllers and actions. This replaces - # mod_rewrite rules. Best of all, Rails' \Routing works with any web server. - # Routes are defined in config/routes.rb. - # - # Think of creating routes as drawing a map for your requests. The map tells - # them where to go based on some predefined pattern: - # - # Rails.application.routes.draw do - # Pattern 1 tells some request to go to one place - # Pattern 2 tell them to go to another - # ... - # end - # - # The following symbols are special: - # - # :controller maps to your controller name - # :action maps to an action with your controllers - # - # Other names simply map to a parameter as in the case of :id. - # - # == Resources - # - # Resource routing allows you to quickly declare all of the common routes - # for a given resourceful controller. Instead of declaring separate routes - # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+ - # actions, a resourceful route declares them in a single line of code: - # - # resources :photos - # - # Sometimes, you have a resource that clients always look up without - # referencing an ID. A common example, /profile always shows the profile of - # the currently logged in user. In this case, you can use a singular resource - # to map /profile (rather than /profile/:id) to the show action. - # - # resource :profile - # - # It's common to have resources that are logically children of other - # resources: - # - # resources :magazines do - # resources :ads - # end - # - # You may wish to organize groups of controllers under a namespace. Most - # commonly, you might group a number of administrative controllers under - # an +admin+ namespace. You would place these controllers under the - # app/controllers/admin directory, and you can group them together - # in your router: - # - # namespace "admin" do - # resources :posts, :comments - # end - # - # Alternatively, you can add prefixes to your path without using a separate - # directory by using +scope+. +scope+ takes additional options which - # apply to all enclosed routes. - # - # scope path: "/cpanel", as: 'admin' do - # resources :posts, :comments - # end - # - # For more, see Routing::Mapper::Resources#resources, - # Routing::Mapper::Scoping#namespace, and - # Routing::Mapper::Scoping#scope. - # - # == Non-resourceful routes - # - # For routes that don't fit the resources mold, you can use the HTTP helper - # methods get, post, patch, put and delete. - # - # get 'post/:id' => 'posts#show' - # post 'post/:id' => 'posts#create_comment' - # - # Now, if you POST to /posts/:id, it will route to the create_comment action. A GET on the same - # URL will route to the show action. - # - # If your route needs to respond to more than one HTTP method (or all methods) then using the - # :via option on match is preferable. - # - # match 'post/:id' => 'posts#show', via: [:get, :post] - # - # == Named routes - # - # Routes can be named by passing an :as option, - # allowing for easy reference within your source as +name_of_route_url+ - # for the full URL and +name_of_route_path+ for the URI path. - # - # Example: - # - # # In config/routes.rb - # get '/login' => 'accounts#login', as: 'login' - # - # # With render, redirect_to, tests, etc. - # redirect_to login_url - # - # Arguments can be passed as well. - # - # redirect_to show_item_path(id: 25) - # - # Use root as a shorthand to name a route for the root path "/". - # - # # In config/routes.rb - # root to: 'blogs#index' - # - # # would recognize http://www.example.com/ as - # params = { controller: 'blogs', action: 'index' } - # - # # and provide these named routes - # root_url # => 'http://www.example.com/' - # root_path # => '/' - # - # Note: when using +controller+, the route is simply named after the - # method you call on the block parameter rather than map. - # - # # In config/routes.rb - # controller :blog do - # get 'blog/show' => :list - # get 'blog/delete' => :delete - # get 'blog/edit' => :edit - # end - # - # # provides named routes for show, delete, and edit - # link_to @article.title, blog_show_path(id: @article.id) - # - # == Pretty URLs - # - # Routes can generate pretty URLs. For example: - # - # get '/articles/:year/:month/:day' => 'articles#find_by_id', constraints: { - # year: /\d{4}/, - # month: /\d{1,2}/, - # day: /\d{1,2}/ - # } - # - # Using the route above, the URL "http://localhost:3000/articles/2005/11/06" - # maps to - # - # params = {year: '2005', month: '11', day: '06'} - # - # == Regular Expressions and parameters - # You can specify a regular expression to define a format for a parameter. - # - # controller 'geocode' do - # get 'geocode/:postalcode' => :show, constraints: { - # postalcode: /\d{5}(-\d{4})?/ - # } - # end - # - # Constraints can include the 'ignorecase' and 'extended syntax' regular - # expression modifiers: - # - # controller 'geocode' do - # get 'geocode/:postalcode' => :show, constraints: { - # postalcode: /hx\d\d\s\d[a-z]{2}/i - # } - # end - # - # controller 'geocode' do - # get 'geocode/:postalcode' => :show, constraints: { - # postalcode: /# Postalcode format - # \d{5} #Prefix - # (-\d{4})? #Suffix - # /x - # } - # end - # - # Using the multiline modifier will raise an +ArgumentError+. - # Encoding regular expression modifiers are silently ignored. The - # match will always use the default encoding or ASCII. - # - # == External redirects - # - # You can redirect any path to another path using the redirect helper in your router: - # - # get "/stories" => redirect("/posts") - # - # == Unicode character routes - # - # You can specify unicode character routes in your router: - # - # get "こんにちは" => "welcome#index" - # - # == Routing to Rack Applications - # - # Instead of a String, like posts#index, which corresponds to the - # index action in the PostsController, you can specify any Rack application - # as the endpoint for a matcher: - # - # get "/application.js" => Sprockets - # - # == Reloading routes - # - # You can reload routes if you feel you must: - # - # Rails.application.reload_routes! - # - # This will clear all named routes and reload config/routes.rb if the file has been modified from - # last load. To absolutely force reloading, use reload!. - # - # == Testing Routes - # - # The two main methods for testing your routes: - # - # === +assert_routing+ - # - # def test_movie_route_properly_splits - # opts = {controller: "plugin", action: "checkout", id: "2"} - # assert_routing "plugin/checkout/2", opts - # end - # - # +assert_routing+ lets you test whether or not the route properly resolves into options. - # - # === +assert_recognizes+ - # - # def test_route_has_options - # opts = {controller: "plugin", action: "show", id: "12"} - # assert_recognizes opts, "/plugins/show/12" - # end - # - # Note the subtle difference between the two: +assert_routing+ tests that - # a URL fits options while +assert_recognizes+ tests that a URL - # breaks into parameters properly. - # - # In tests you can simply pass the URL or named route to +get+ or +post+. - # - # def send_to_jail - # get '/jail' - # assert_response :success - # end - # - # def goes_to_login - # get login_url - # #... - # end - # - # == View a list of all your routes - # - # rails routes - # - # Target specific controllers by prefixing the command with -c option. - # - module Routing - extend ActiveSupport::Autoload - - autoload :Mapper - autoload :RouteSet - autoload :RoutesProxy - autoload :UrlFor - autoload :PolymorphicRoutes - - SEPARATORS = %w( / . ? ) #:nodoc: - HTTP_METHODS = [:get, :head, :post, :patch, :put, :delete, :options] #:nodoc: - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/endpoint.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/endpoint.rb deleted file mode 100644 index 88aa13c3e8..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/endpoint.rb +++ /dev/null @@ -1,10 +0,0 @@ -module ActionDispatch - module Routing - class Endpoint # :nodoc: - def dispatcher?; false; end - def redirect?; false; end - def matches?(req); true; end - def app; self; end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/inspector.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/inspector.rb deleted file mode 100644 index b91ffb8419..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/inspector.rb +++ /dev/null @@ -1,223 +0,0 @@ -require "delegate" -require "active_support/core_ext/string/strip" - -module ActionDispatch - module Routing - class RouteWrapper < SimpleDelegator - def endpoint - app.dispatcher? ? "#{controller}##{action}" : rack_app.inspect - end - - def constraints - requirements.except(:controller, :action) - end - - def rack_app - app.app - end - - def path - super.spec.to_s - end - - def name - super.to_s - end - - def reqs - @reqs ||= begin - reqs = endpoint - reqs += " #{constraints}" unless constraints.empty? - reqs - end - end - - def controller - parts.include?(:controller) ? ":controller" : requirements[:controller] - end - - def action - parts.include?(:action) ? ":action" : requirements[:action] - end - - def internal? - internal - end - - def engine? - rack_app.respond_to?(:routes) - end - end - - ## - # This class is just used for displaying route information when someone - # executes `rails routes` or looks at the RoutingError page. - # People should not use this class. - class RoutesInspector # :nodoc: - def initialize(routes) - @engines = {} - @routes = routes - end - - def format(formatter, filter = nil) - routes_to_display = filter_routes(normalize_filter(filter)) - routes = collect_routes(routes_to_display) - if routes.none? - formatter.no_routes(collect_routes(@routes)) - return formatter.result - end - - formatter.header routes - formatter.section routes - - @engines.each do |name, engine_routes| - formatter.section_title "Routes for #{name}" - formatter.section engine_routes - end - - formatter.result - end - - private - - def normalize_filter(filter) - if filter.is_a?(Hash) && filter[:controller] - { controller: /#{filter[:controller].downcase.sub(/_?controller\z/, '').sub('::', '/')}/ } - elsif filter - { controller: /#{filter}/, action: /#{filter}/, verb: /#{filter}/, name: /#{filter}/, path: /#{filter}/ } - end - end - - def filter_routes(filter) - if filter - @routes.select do |route| - route_wrapper = RouteWrapper.new(route) - filter.any? { |default, value| route_wrapper.send(default) =~ value } - end - else - @routes - end - end - - def collect_routes(routes) - routes.collect do |route| - RouteWrapper.new(route) - end.reject(&:internal?).collect do |route| - collect_engine_routes(route) - - { name: route.name, - verb: route.verb, - path: route.path, - reqs: route.reqs } - end - end - - def collect_engine_routes(route) - name = route.endpoint - return unless route.engine? - return if @engines[name] - - routes = route.rack_app.routes - if routes.is_a?(ActionDispatch::Routing::RouteSet) - @engines[name] = collect_routes(routes.routes) - end - end - end - - class ConsoleFormatter - def initialize - @buffer = [] - end - - def result - @buffer.join("\n") - end - - def section_title(title) - @buffer << "\n#{title}:" - end - - def section(routes) - @buffer << draw_section(routes) - end - - def header(routes) - @buffer << draw_header(routes) - end - - def no_routes(routes) - @buffer << - if routes.none? - <<-MESSAGE.strip_heredoc - You don't have any routes defined! - - Please add some routes in config/routes.rb. - MESSAGE - else - "No routes were found for this controller" - end - @buffer << "For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html." - end - - private - def draw_section(routes) - header_lengths = ["Prefix", "Verb", "URI Pattern"].map(&:length) - name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max) - - routes.map do |r| - "#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}" - end - end - - def draw_header(routes) - name_width, verb_width, path_width = widths(routes) - - "#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action" - end - - def widths(routes) - [routes.map { |r| r[:name].length }.max || 0, - routes.map { |r| r[:verb].length }.max || 0, - routes.map { |r| r[:path].length }.max || 0] - end - end - - class HtmlTableFormatter - def initialize(view) - @view = view - @buffer = [] - end - - def section_title(title) - @buffer << %(#{title}) - end - - def section(routes) - @buffer << @view.render(partial: "routes/route", collection: routes) - end - - # the header is part of the HTML page, so we don't construct it here. - def header(routes) - end - - def no_routes(*) - @buffer << <<-MESSAGE.strip_heredoc -

You don't have any routes defined!

- - MESSAGE - end - - def result - @view.raw @view.render(layout: "routes/table") { - @view.raw @buffer.join("\n") - } - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/mapper.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/mapper.rb deleted file mode 100644 index 9c157e69fd..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/mapper.rb +++ /dev/null @@ -1,2255 +0,0 @@ -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/enumerable" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/regexp" -require "action_dispatch/routing/redirection" -require "action_dispatch/routing/endpoint" - -module ActionDispatch - module Routing - class Mapper - URL_OPTIONS = [:protocol, :subdomain, :domain, :host, :port] - - class Constraints < Routing::Endpoint #:nodoc: - attr_reader :app, :constraints - - SERVE = ->(app, req) { app.serve req } - CALL = ->(app, req) { app.call req.env } - - def initialize(app, constraints, strategy) - # Unwrap Constraints objects. I don't actually think it's possible - # to pass a Constraints object to this constructor, but there were - # multiple places that kept testing children of this object. I - # *think* they were just being defensive, but I have no idea. - if app.is_a?(self.class) - constraints += app.constraints - app = app.app - end - - @strategy = strategy - - @app, @constraints, = app, constraints - end - - def dispatcher?; @strategy == SERVE; end - - def matches?(req) - @constraints.all? do |constraint| - (constraint.respond_to?(:matches?) && constraint.matches?(req)) || - (constraint.respond_to?(:call) && constraint.call(*constraint_args(constraint, req))) - end - end - - def serve(req) - return [ 404, { "X-Cascade" => "pass" }, [] ] unless matches?(req) - - @strategy.call @app, req - end - - private - def constraint_args(constraint, request) - constraint.arity == 1 ? [request] : [request.path_parameters, request] - end - end - - class Mapping #:nodoc: - ANCHOR_CHARACTERS_REGEX = %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} - OPTIONAL_FORMAT_REGEX = %r{(?:\(\.:format\)+|\.:format|/)\Z} - - attr_reader :requirements, :defaults - attr_reader :to, :default_controller, :default_action - attr_reader :required_defaults, :ast - - def self.build(scope, set, ast, controller, default_action, to, via, formatted, options_constraints, anchor, options) - options = scope[:options].merge(options) if scope[:options] - - defaults = (scope[:defaults] || {}).dup - scope_constraints = scope[:constraints] || {} - - new set, ast, defaults, controller, default_action, scope[:module], to, formatted, scope_constraints, scope[:blocks] || [], via, options_constraints, anchor, options - end - - def self.check_via(via) - if via.empty? - msg = "You should not use the `match` method in your router without specifying an HTTP method.\n" \ - "If you want to expose your action to both GET and POST, add `via: [:get, :post]` option.\n" \ - "If you want to expose your action to GET, use `get` in the router:\n" \ - " Instead of: match \"controller#action\"\n" \ - " Do: get \"controller#action\"" - raise ArgumentError, msg - end - via - end - - def self.normalize_path(path, format) - path = Mapper.normalize_path(path) - - if format == true - "#{path}.:format" - elsif optional_format?(path, format) - "#{path}(.:format)" - else - path - end - end - - def self.optional_format?(path, format) - format != false && path !~ OPTIONAL_FORMAT_REGEX - end - - def initialize(set, ast, defaults, controller, default_action, modyoule, to, formatted, scope_constraints, blocks, via, options_constraints, anchor, options) - @defaults = defaults - @set = set - - @to = to - @default_controller = controller - @default_action = default_action - @ast = ast - @anchor = anchor - @via = via - @internal = options.delete(:internal) - - path_params = ast.find_all(&:symbol?).map(&:to_sym) - - options = add_wildcard_options(options, formatted, ast) - - options = normalize_options!(options, path_params, modyoule) - - split_options = constraints(options, path_params) - - constraints = scope_constraints.merge Hash[split_options[:constraints] || []] - - if options_constraints.is_a?(Hash) - @defaults = Hash[options_constraints.find_all { |key, default| - URL_OPTIONS.include?(key) && (String === default || Integer === default) - }].merge @defaults - @blocks = blocks - constraints.merge! options_constraints - else - @blocks = blocks(options_constraints) - end - - requirements, conditions = split_constraints path_params, constraints - verify_regexp_requirements requirements.map(&:last).grep(Regexp) - - formats = normalize_format(formatted) - - @requirements = formats[:requirements].merge Hash[requirements] - @conditions = Hash[conditions] - @defaults = formats[:defaults].merge(@defaults).merge(normalize_defaults(options)) - - if path_params.include?(:action) && !@requirements.key?(:action) - @defaults[:action] ||= "index" - end - - @required_defaults = (split_options[:required_defaults] || []).map(&:first) - end - - def make_route(name, precedence) - route = Journey::Route.new(name, - application, - path, - conditions, - required_defaults, - defaults, - request_method, - precedence, - @internal) - - route - end - - def application - app(@blocks) - end - - def path - build_path @ast, requirements, @anchor - end - - def conditions - build_conditions @conditions, @set.request_class - end - - def build_conditions(current_conditions, request_class) - conditions = current_conditions.dup - - conditions.keep_if do |k, _| - request_class.public_method_defined?(k) - end - end - private :build_conditions - - def request_method - @via.map { |x| Journey::Route.verb_matcher(x) } - end - private :request_method - - JOINED_SEPARATORS = SEPARATORS.join # :nodoc: - - def build_path(ast, requirements, anchor) - pattern = Journey::Path::Pattern.new(ast, requirements, JOINED_SEPARATORS, anchor) - - # Find all the symbol nodes that are adjacent to literal nodes and alter - # the regexp so that Journey will partition them into custom routes. - ast.find_all { |node| - next unless node.cat? - - if node.left.literal? && node.right.symbol? - symbol = node.right - elsif node.left.literal? && node.right.cat? && node.right.left.symbol? - symbol = node.right.left - elsif node.left.symbol? && node.right.literal? - symbol = node.left - elsif node.left.symbol? && node.right.cat? && node.right.left.literal? - symbol = node.left - else - next - end - - if symbol - symbol.regexp = /(?:#{Regexp.union(symbol.regexp, '-')})+/ - end - } - - pattern - end - private :build_path - - private - def add_wildcard_options(options, formatted, path_ast) - # Add a constraint for wildcard route to make it non-greedy and match the - # optional format part of the route by default - if formatted != false - path_ast.grep(Journey::Nodes::Star).each_with_object({}) { |node, hash| - hash[node.name.to_sym] ||= /.+?/ - }.merge options - else - options - end - end - - def normalize_options!(options, path_params, modyoule) - if path_params.include?(:controller) - raise ArgumentError, ":controller segment is not allowed within a namespace block" if modyoule - - # Add a default constraint for :controller path segments that matches namespaced - # controllers with default routes like :controller/:action/:id(.:format), e.g: - # GET /admin/products/show/1 - # => { controller: 'admin/products', action: 'show', id: '1' } - options[:controller] ||= /.+?/ - end - - if to.respond_to?(:action) || to.respond_to?(:call) - options - else - to_endpoint = split_to to - controller = to_endpoint[0] || default_controller - action = to_endpoint[1] || default_action - - controller = add_controller_module(controller, modyoule) - - options.merge! check_controller_and_action(path_params, controller, action) - end - end - - def split_constraints(path_params, constraints) - constraints.partition do |key, requirement| - path_params.include?(key) || key == :controller - end - end - - def normalize_format(formatted) - case formatted - when true - { requirements: { format: /.+/ }, - defaults: {} } - when Regexp - { requirements: { format: formatted }, - defaults: { format: nil } } - when String - { requirements: { format: Regexp.compile(formatted) }, - defaults: { format: formatted } } - else - { requirements: {}, defaults: {} } - end - end - - def verify_regexp_requirements(requirements) - requirements.each do |requirement| - if requirement.source =~ ANCHOR_CHARACTERS_REGEX - raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" - end - - if requirement.multiline? - raise ArgumentError, "Regexp multiline option is not allowed in routing requirements: #{requirement.inspect}" - end - end - end - - def normalize_defaults(options) - Hash[options.reject { |_, default| Regexp === default }] - end - - def app(blocks) - if to.respond_to?(:action) - Routing::RouteSet::StaticDispatcher.new to - elsif to.respond_to?(:call) - Constraints.new(to, blocks, Constraints::CALL) - elsif blocks.any? - Constraints.new(dispatcher(defaults.key?(:controller)), blocks, Constraints::SERVE) - else - dispatcher(defaults.key?(:controller)) - end - end - - def check_controller_and_action(path_params, controller, action) - hash = check_part(:controller, controller, path_params, {}) do |part| - translate_controller(part) { - message = "'#{part}' is not a supported controller name. This can lead to potential routing problems." - message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use" - - raise ArgumentError, message - } - end - - check_part(:action, action, path_params, hash) { |part| - part.is_a?(Regexp) ? part : part.to_s - } - end - - def check_part(name, part, path_params, hash) - if part - hash[name] = yield(part) - else - unless path_params.include?(name) - message = "Missing :#{name} key on routes definition, please check your routes." - raise ArgumentError, message - end - end - hash - end - - def split_to(to) - if to =~ /#/ - to.split("#") - else - [] - end - end - - def add_controller_module(controller, modyoule) - if modyoule && !controller.is_a?(Regexp) - if controller =~ %r{\A/} - controller[1..-1] - else - [modyoule, controller].compact.join("/") - end - else - controller - end - end - - def translate_controller(controller) - return controller if Regexp === controller - return controller.to_s if controller =~ /\A[a-z_0-9][a-z_0-9\/]*\z/ - - yield - end - - def blocks(callable_constraint) - unless callable_constraint.respond_to?(:call) || callable_constraint.respond_to?(:matches?) - raise ArgumentError, "Invalid constraint: #{callable_constraint.inspect} must respond to :call or :matches?" - end - [callable_constraint] - end - - def constraints(options, path_params) - options.group_by do |key, option| - if Regexp === option - :constraints - else - if path_params.include?(key) - :path_params - else - :required_defaults - end - end - end - end - - def dispatcher(raise_on_name_error) - Routing::RouteSet::Dispatcher.new raise_on_name_error - end - end - - # Invokes Journey::Router::Utils.normalize_path and ensure that - # (:locale) becomes (/:locale) instead of /(:locale). Except - # for root cases, where the latter is the correct one. - def self.normalize_path(path) - path = Journey::Router::Utils.normalize_path(path) - path.gsub!(%r{/(\(+)/?}, '\1/') unless path =~ %r{^/\(+[^)]+\)$} - path - end - - def self.normalize_name(name) - normalize_path(name)[1..-1].tr("/", "_") - end - - module Base - # Matches a url pattern to one or more routes. - # - # You should not use the +match+ method in your router - # without specifying an HTTP method. - # - # If you want to expose your action to both GET and POST, use: - # - # # sets :controller, :action and :id in params - # match ':controller/:action/:id', via: [:get, :post] - # - # Note that +:controller+, +:action+ and +:id+ are interpreted as url - # query parameters and thus available through +params+ in an action. - # - # If you want to expose your action to GET, use +get+ in the router: - # - # Instead of: - # - # match ":controller/:action/:id" - # - # Do: - # - # get ":controller/:action/:id" - # - # Two of these symbols are special, +:controller+ maps to the controller - # and +:action+ to the controller's action. A pattern can also map - # wildcard segments (globs) to params: - # - # get 'songs/*category/:title', to: 'songs#show' - # - # # 'songs/rock/classic/stairway-to-heaven' sets - # # params[:category] = 'rock/classic' - # # params[:title] = 'stairway-to-heaven' - # - # To match a wildcard parameter, it must have a name assigned to it. - # Without a variable name to attach the glob parameter to, the route - # can't be parsed. - # - # When a pattern points to an internal route, the route's +:action+ and - # +:controller+ should be set in options or hash shorthand. Examples: - # - # match 'photos/:id' => 'photos#show', via: :get - # match 'photos/:id', to: 'photos#show', via: :get - # match 'photos/:id', controller: 'photos', action: 'show', via: :get - # - # A pattern can also point to a +Rack+ endpoint i.e. anything that - # responds to +call+: - # - # match 'photos/:id', to: -> (hash) { [200, {}, ["Coming soon"]] }, via: :get - # match 'photos/:id', to: PhotoRackApp, via: :get - # # Yes, controller actions are just rack endpoints - # match 'photos/:id', to: PhotosController.action(:show), via: :get - # - # Because requesting various HTTP verbs with a single action has security - # implications, you must either specify the actions in - # the via options or use one of the HttpHelpers[rdoc-ref:HttpHelpers] - # instead +match+ - # - # === Options - # - # Any options not seen here are passed on as params with the url. - # - # [:controller] - # The route's controller. - # - # [:action] - # The route's action. - # - # [:param] - # Overrides the default resource identifier +:id+ (name of the - # dynamic segment used to generate the routes). - # You can access that segment from your controller using - # params[<:param>]. - # In your router: - # - # resources :user, param: :name - # - # You can override ActiveRecord::Base#to_param of a related - # model to construct a URL: - # - # class User < ActiveRecord::Base - # def to_param - # name - # end - # end - # - # user = User.find_by(name: 'Phusion') - # user_path(user) # => "/users/Phusion" - # - # [:path] - # The path prefix for the routes. - # - # [:module] - # The namespace for :controller. - # - # match 'path', to: 'c#a', module: 'sekret', controller: 'posts', via: :get - # # => Sekret::PostsController - # - # See Scoping#namespace for its scope equivalent. - # - # [:as] - # The name used to generate routing helpers. - # - # [:via] - # Allowed HTTP verb(s) for route. - # - # match 'path', to: 'c#a', via: :get - # match 'path', to: 'c#a', via: [:get, :post] - # match 'path', to: 'c#a', via: :all - # - # [:to] - # Points to a +Rack+ endpoint. Can be an object that responds to - # +call+ or a string representing a controller's action. - # - # match 'path', to: 'controller#action', via: :get - # match 'path', to: -> (env) { [200, {}, ["Success!"]] }, via: :get - # match 'path', to: RackApp, via: :get - # - # [:on] - # Shorthand for wrapping routes in a specific RESTful context. Valid - # values are +:member+, +:collection+, and +:new+. Only use within - # resource(s) block. For example: - # - # resource :bar do - # match 'foo', to: 'c#a', on: :member, via: [:get, :post] - # end - # - # Is equivalent to: - # - # resource :bar do - # member do - # match 'foo', to: 'c#a', via: [:get, :post] - # end - # end - # - # [:constraints] - # Constrains parameters with a hash of regular expressions - # or an object that responds to matches?. In addition, constraints - # other than path can also be specified with any object - # that responds to === (eg. String, Array, Range, etc.). - # - # match 'path/:id', constraints: { id: /[A-Z]\d{5}/ }, via: :get - # - # match 'json_only', constraints: { format: 'json' }, via: :get - # - # class Whitelist - # def matches?(request) request.remote_ip == '1.2.3.4' end - # end - # match 'path', to: 'c#a', constraints: Whitelist.new, via: :get - # - # See Scoping#constraints for more examples with its scope - # equivalent. - # - # [:defaults] - # Sets defaults for parameters - # - # # Sets params[:format] to 'jpg' by default - # match 'path', to: 'c#a', defaults: { format: 'jpg' }, via: :get - # - # See Scoping#defaults for its scope equivalent. - # - # [:anchor] - # Boolean to anchor a match pattern. Default is true. When set to - # false, the pattern matches any request prefixed with the given path. - # - # # Matches any request starting with 'path' - # match 'path', to: 'c#a', anchor: false, via: :get - # - # [:format] - # Allows you to specify the default value for optional +format+ - # segment or disable it by supplying +false+. - def match(path, options = nil) - end - - # Mount a Rack-based application to be used within the application. - # - # mount SomeRackApp, at: "some_route" - # - # Alternatively: - # - # mount(SomeRackApp => "some_route") - # - # For options, see +match+, as +mount+ uses it internally. - # - # All mounted applications come with routing helpers to access them. - # These are named after the class specified, so for the above example - # the helper is either +some_rack_app_path+ or +some_rack_app_url+. - # To customize this helper's name, use the +:as+ option: - # - # mount(SomeRackApp => "some_route", as: "exciting") - # - # This will generate the +exciting_path+ and +exciting_url+ helpers - # which can be used to navigate to this mounted app. - def mount(app, options = nil) - if options - path = options.delete(:at) - elsif Hash === app - options = app - app, path = options.find { |k, _| k.respond_to?(:call) } - options.delete(app) if app - end - - raise ArgumentError, "A rack application must be specified" unless app.respond_to?(:call) - raise ArgumentError, <<-MSG.strip_heredoc unless path - Must be called with mount point - - mount SomeRackApp, at: "some_route" - or - mount(SomeRackApp => "some_route") - MSG - - rails_app = rails_app? app - options[:as] ||= app_name(app, rails_app) - - target_as = name_for_action(options[:as], path) - options[:via] ||= :all - - match(path, options.merge(to: app, anchor: false, format: false)) - - define_generate_prefix(app, target_as) if rails_app - self - end - - def default_url_options=(options) - @set.default_url_options = options - end - alias_method :default_url_options, :default_url_options= - - def with_default_scope(scope, &block) - scope(scope) do - instance_exec(&block) - end - end - - # Query if the following named route was already defined. - def has_named_route?(name) - @set.named_routes.key? name - end - - private - def rails_app?(app) - app.is_a?(Class) && app < Rails::Railtie - end - - def app_name(app, rails_app) - if rails_app - app.railtie_name - elsif app.is_a?(Class) - class_name = app.name - ActiveSupport::Inflector.underscore(class_name).tr("/", "_") - end - end - - def define_generate_prefix(app, name) - _route = @set.named_routes.get name - _routes = @set - _url_helpers = @set.url_helpers - - script_namer = ->(options) do - prefix_options = options.slice(*_route.segment_keys) - prefix_options[:relative_url_root] = "".freeze - - if options[:_recall] - prefix_options.reverse_merge!(options[:_recall].slice(*_route.segment_keys)) - end - - # We must actually delete prefix segment keys to avoid passing them to next url_for. - _route.segment_keys.each { |k| options.delete(k) } - _url_helpers.send("#{name}_path", prefix_options) - end - - app.routes.define_mounted_helper(name, script_namer) - - app.routes.extend Module.new { - def optimize_routes_generation?; false; end - - define_method :find_script_name do |options| - if options.key? :script_name - super(options) - else - script_namer.call(options) - end - end - } - end - end - - module HttpHelpers - # Define a route that only recognizes HTTP GET. - # For supported arguments, see match[rdoc-ref:Base#match] - # - # get 'bacon', to: 'food#bacon' - def get(*args, &block) - map_method(:get, args, &block) - end - - # Define a route that only recognizes HTTP POST. - # For supported arguments, see match[rdoc-ref:Base#match] - # - # post 'bacon', to: 'food#bacon' - def post(*args, &block) - map_method(:post, args, &block) - end - - # Define a route that only recognizes HTTP PATCH. - # For supported arguments, see match[rdoc-ref:Base#match] - # - # patch 'bacon', to: 'food#bacon' - def patch(*args, &block) - map_method(:patch, args, &block) - end - - # Define a route that only recognizes HTTP PUT. - # For supported arguments, see match[rdoc-ref:Base#match] - # - # put 'bacon', to: 'food#bacon' - def put(*args, &block) - map_method(:put, args, &block) - end - - # Define a route that only recognizes HTTP DELETE. - # For supported arguments, see match[rdoc-ref:Base#match] - # - # delete 'broccoli', to: 'food#broccoli' - def delete(*args, &block) - map_method(:delete, args, &block) - end - - private - def map_method(method, args, &block) - options = args.extract_options! - options[:via] = method - match(*args, options, &block) - self - end - end - - # You may wish to organize groups of controllers under a namespace. - # Most commonly, you might group a number of administrative controllers - # under an +admin+ namespace. You would place these controllers under - # the app/controllers/admin directory, and you can group them - # together in your router: - # - # namespace "admin" do - # resources :posts, :comments - # end - # - # This will create a number of routes for each of the posts and comments - # controller. For Admin::PostsController, Rails will create: - # - # GET /admin/posts - # GET /admin/posts/new - # POST /admin/posts - # GET /admin/posts/1 - # GET /admin/posts/1/edit - # PATCH/PUT /admin/posts/1 - # DELETE /admin/posts/1 - # - # If you want to route /posts (without the prefix /admin) to - # Admin::PostsController, you could use - # - # scope module: "admin" do - # resources :posts - # end - # - # or, for a single case - # - # resources :posts, module: "admin" - # - # If you want to route /admin/posts to +PostsController+ - # (without the Admin:: module prefix), you could use - # - # scope "/admin" do - # resources :posts - # end - # - # or, for a single case - # - # resources :posts, path: "/admin/posts" - # - # In each of these cases, the named routes remain the same as if you did - # not use scope. In the last case, the following paths map to - # +PostsController+: - # - # GET /admin/posts - # GET /admin/posts/new - # POST /admin/posts - # GET /admin/posts/1 - # GET /admin/posts/1/edit - # PATCH/PUT /admin/posts/1 - # DELETE /admin/posts/1 - module Scoping - # Scopes a set of routes to the given default options. - # - # Take the following route definition as an example: - # - # scope path: ":account_id", as: "account" do - # resources :projects - # end - # - # This generates helpers such as +account_projects_path+, just like +resources+ does. - # The difference here being that the routes generated are like /:account_id/projects, - # rather than /accounts/:account_id/projects. - # - # === Options - # - # Takes same options as Base#match and Resources#resources. - # - # # route /posts (without the prefix /admin) to Admin::PostsController - # scope module: "admin" do - # resources :posts - # end - # - # # prefix the posts resource's requests with '/admin' - # scope path: "/admin" do - # resources :posts - # end - # - # # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+ - # scope as: "sekret" do - # resources :posts - # end - def scope(*args) - options = args.extract_options!.dup - scope = {} - - options[:path] = args.flatten.join("/") if args.any? - options[:constraints] ||= {} - - unless nested_scope? - options[:shallow_path] ||= options[:path] if options.key?(:path) - options[:shallow_prefix] ||= options[:as] if options.key?(:as) - end - - if options[:constraints].is_a?(Hash) - defaults = options[:constraints].select do |k, v| - URL_OPTIONS.include?(k) && (v.is_a?(String) || v.is_a?(Integer)) - end - - options[:defaults] = defaults.merge(options[:defaults] || {}) - else - block, options[:constraints] = options[:constraints], {} - end - - if options.key?(:only) || options.key?(:except) - scope[:action_options] = { only: options.delete(:only), - except: options.delete(:except) } - end - - if options.key? :anchor - raise ArgumentError, "anchor is ignored unless passed to `match`" - end - - @scope.options.each do |option| - if option == :blocks - value = block - elsif option == :options - value = options - else - value = options.delete(option) { POISON } - end - - unless POISON == value - scope[option] = send("merge_#{option}_scope", @scope[option], value) - end - end - - @scope = @scope.new scope - yield - self - ensure - @scope = @scope.parent - end - - POISON = Object.new # :nodoc: - - # Scopes routes to a specific controller - # - # controller "food" do - # match "bacon", action: :bacon, via: :get - # end - def controller(controller) - @scope = @scope.new(controller: controller) - yield - ensure - @scope = @scope.parent - end - - # Scopes routes to a specific namespace. For example: - # - # namespace :admin do - # resources :posts - # end - # - # This generates the following routes: - # - # admin_posts GET /admin/posts(.:format) admin/posts#index - # admin_posts POST /admin/posts(.:format) admin/posts#create - # new_admin_post GET /admin/posts/new(.:format) admin/posts#new - # edit_admin_post GET /admin/posts/:id/edit(.:format) admin/posts#edit - # admin_post GET /admin/posts/:id(.:format) admin/posts#show - # admin_post PATCH/PUT /admin/posts/:id(.:format) admin/posts#update - # admin_post DELETE /admin/posts/:id(.:format) admin/posts#destroy - # - # === Options - # - # The +:path+, +:as+, +:module+, +:shallow_path+ and +:shallow_prefix+ - # options all default to the name of the namespace. - # - # For options, see Base#match. For +:shallow_path+ option, see - # Resources#resources. - # - # # accessible through /sekret/posts rather than /admin/posts - # namespace :admin, path: "sekret" do - # resources :posts - # end - # - # # maps to Sekret::PostsController rather than Admin::PostsController - # namespace :admin, module: "sekret" do - # resources :posts - # end - # - # # generates +sekret_posts_path+ rather than +admin_posts_path+ - # namespace :admin, as: "sekret" do - # resources :posts - # end - def namespace(path, options = {}) - path = path.to_s - - defaults = { - module: path, - as: options.fetch(:as, path), - shallow_path: options.fetch(:path, path), - shallow_prefix: options.fetch(:as, path) - } - - path_scope(options.delete(:path) { path }) do - scope(defaults.merge!(options)) { yield } - end - end - - # === Parameter Restriction - # Allows you to constrain the nested routes based on a set of rules. - # For instance, in order to change the routes to allow for a dot character in the +id+ parameter: - # - # constraints(id: /\d+\.\d+/) do - # resources :posts - # end - # - # Now routes such as +/posts/1+ will no longer be valid, but +/posts/1.1+ will be. - # The +id+ parameter must match the constraint passed in for this example. - # - # You may use this to also restrict other parameters: - # - # resources :posts do - # constraints(post_id: /\d+\.\d+/) do - # resources :comments - # end - # end - # - # === Restricting based on IP - # - # Routes can also be constrained to an IP or a certain range of IP addresses: - # - # constraints(ip: /192\.168\.\d+\.\d+/) do - # resources :posts - # end - # - # Any user connecting from the 192.168.* range will be able to see this resource, - # where as any user connecting outside of this range will be told there is no such route. - # - # === Dynamic request matching - # - # Requests to routes can be constrained based on specific criteria: - # - # constraints(-> (req) { req.env["HTTP_USER_AGENT"] =~ /iPhone/ }) do - # resources :iphones - # end - # - # You are able to move this logic out into a class if it is too complex for routes. - # This class must have a +matches?+ method defined on it which either returns +true+ - # if the user should be given access to that route, or +false+ if the user should not. - # - # class Iphone - # def self.matches?(request) - # request.env["HTTP_USER_AGENT"] =~ /iPhone/ - # end - # end - # - # An expected place for this code would be +lib/constraints+. - # - # This class is then used like this: - # - # constraints(Iphone) do - # resources :iphones - # end - def constraints(constraints = {}) - scope(constraints: constraints) { yield } - end - - # Allows you to set default parameters for a route, such as this: - # defaults id: 'home' do - # match 'scoped_pages/(:id)', to: 'pages#show' - # end - # Using this, the +:id+ parameter here will default to 'home'. - def defaults(defaults = {}) - @scope = @scope.new(defaults: merge_defaults_scope(@scope[:defaults], defaults)) - yield - ensure - @scope = @scope.parent - end - - private - def merge_path_scope(parent, child) - Mapper.normalize_path("#{parent}/#{child}") - end - - def merge_shallow_path_scope(parent, child) - Mapper.normalize_path("#{parent}/#{child}") - end - - def merge_as_scope(parent, child) - parent ? "#{parent}_#{child}" : child - end - - def merge_shallow_prefix_scope(parent, child) - parent ? "#{parent}_#{child}" : child - end - - def merge_module_scope(parent, child) - parent ? "#{parent}/#{child}" : child - end - - def merge_controller_scope(parent, child) - child - end - - def merge_action_scope(parent, child) - child - end - - def merge_via_scope(parent, child) - child - end - - def merge_format_scope(parent, child) - child - end - - def merge_path_names_scope(parent, child) - merge_options_scope(parent, child) - end - - def merge_constraints_scope(parent, child) - merge_options_scope(parent, child) - end - - def merge_defaults_scope(parent, child) - merge_options_scope(parent, child) - end - - def merge_blocks_scope(parent, child) - merged = parent ? parent.dup : [] - merged << child if child - merged - end - - def merge_options_scope(parent, child) - (parent || {}).merge(child) - end - - def merge_shallow_scope(parent, child) - child ? true : false - end - - def merge_to_scope(parent, child) - child - end - end - - # Resource routing allows you to quickly declare all of the common routes - # for a given resourceful controller. Instead of declaring separate routes - # for your +index+, +show+, +new+, +edit+, +create+, +update+ and +destroy+ - # actions, a resourceful route declares them in a single line of code: - # - # resources :photos - # - # Sometimes, you have a resource that clients always look up without - # referencing an ID. A common example, /profile always shows the profile of - # the currently logged in user. In this case, you can use a singular resource - # to map /profile (rather than /profile/:id) to the show action. - # - # resource :profile - # - # It's common to have resources that are logically children of other - # resources: - # - # resources :magazines do - # resources :ads - # end - # - # You may wish to organize groups of controllers under a namespace. Most - # commonly, you might group a number of administrative controllers under - # an +admin+ namespace. You would place these controllers under the - # app/controllers/admin directory, and you can group them together - # in your router: - # - # namespace "admin" do - # resources :posts, :comments - # end - # - # By default the +:id+ parameter doesn't accept dots. If you need to - # use dots as part of the +:id+ parameter add a constraint which - # overrides this restriction, e.g: - # - # resources :articles, id: /[^\/]+/ - # - # This allows any character other than a slash as part of your +:id+. - # - module Resources - # CANONICAL_ACTIONS holds all actions that does not need a prefix or - # a path appended since they fit properly in their scope level. - VALID_ON_OPTIONS = [:new, :collection, :member] - RESOURCE_OPTIONS = [:as, :controller, :path, :only, :except, :param, :concerns] - CANONICAL_ACTIONS = %w(index create new show update destroy) - - class Resource #:nodoc: - attr_reader :controller, :path, :param - - def initialize(entities, api_only, shallow, options = {}) - @name = entities.to_s - @path = (options[:path] || @name).to_s - @controller = (options[:controller] || @name).to_s - @as = options[:as] - @param = (options[:param] || :id).to_sym - @options = options - @shallow = shallow - @api_only = api_only - @only = options.delete :only - @except = options.delete :except - end - - def default_actions - if @api_only - [:index, :create, :show, :update, :destroy] - else - [:index, :create, :new, :show, :update, :destroy, :edit] - end - end - - def actions - if @only - Array(@only).map(&:to_sym) - elsif @except - default_actions - Array(@except).map(&:to_sym) - else - default_actions - end - end - - def name - @as || @name - end - - def plural - @plural ||= name.to_s - end - - def singular - @singular ||= name.to_s.singularize - end - - alias :member_name :singular - - # Checks for uncountable plurals, and appends "_index" if the plural - # and singular form are the same. - def collection_name - singular == plural ? "#{plural}_index" : plural - end - - def resource_scope - controller - end - - alias :collection_scope :path - - def member_scope - "#{path}/:#{param}" - end - - alias :shallow_scope :member_scope - - def new_scope(new_path) - "#{path}/#{new_path}" - end - - def nested_param - :"#{singular}_#{param}" - end - - def nested_scope - "#{path}/:#{nested_param}" - end - - def shallow? - @shallow - end - - def singleton?; false; end - end - - class SingletonResource < Resource #:nodoc: - def initialize(entities, api_only, shallow, options) - super - @as = nil - @controller = (options[:controller] || plural).to_s - @as = options[:as] - end - - def default_actions - if @api_only - [:show, :create, :update, :destroy] - else - [:show, :create, :update, :destroy, :new, :edit] - end - end - - def plural - @plural ||= name.to_s.pluralize - end - - def singular - @singular ||= name.to_s - end - - alias :member_name :singular - alias :collection_name :singular - - alias :member_scope :path - alias :nested_scope :path - - def singleton?; true; end - end - - def resources_path_names(options) - @scope[:path_names].merge!(options) - end - - # Sometimes, you have a resource that clients always look up without - # referencing an ID. A common example, /profile always shows the - # profile of the currently logged in user. In this case, you can use - # a singular resource to map /profile (rather than /profile/:id) to - # the show action: - # - # resource :profile - # - # creates six different routes in your application, all mapping to - # the +Profiles+ controller (note that the controller is named after - # the plural): - # - # GET /profile/new - # GET /profile - # GET /profile/edit - # PATCH/PUT /profile - # DELETE /profile - # POST /profile - # - # === Options - # Takes same options as +resources+. - def resource(*resources, &block) - options = resources.extract_options!.dup - - if apply_common_behavior_for(:resource, resources, options, &block) - return self - end - - with_scope_level(:resource) do - options = apply_action_options options - resource_scope(SingletonResource.new(resources.pop, api_only?, @scope[:shallow], options)) do - yield if block_given? - - concerns(options[:concerns]) if options[:concerns] - - new do - get :new - end if parent_resource.actions.include?(:new) - - set_member_mappings_for_resource - - collection do - post :create - end if parent_resource.actions.include?(:create) - end - end - - self - end - - # In Rails, a resourceful route provides a mapping between HTTP verbs - # and URLs and controller actions. By convention, each action also maps - # to particular CRUD operations in a database. A single entry in the - # routing file, such as - # - # resources :photos - # - # creates seven different routes in your application, all mapping to - # the +Photos+ controller: - # - # GET /photos - # GET /photos/new - # POST /photos - # GET /photos/:id - # GET /photos/:id/edit - # PATCH/PUT /photos/:id - # DELETE /photos/:id - # - # Resources can also be nested infinitely by using this block syntax: - # - # resources :photos do - # resources :comments - # end - # - # This generates the following comments routes: - # - # GET /photos/:photo_id/comments - # GET /photos/:photo_id/comments/new - # POST /photos/:photo_id/comments - # GET /photos/:photo_id/comments/:id - # GET /photos/:photo_id/comments/:id/edit - # PATCH/PUT /photos/:photo_id/comments/:id - # DELETE /photos/:photo_id/comments/:id - # - # === Options - # Takes same options as Base#match as well as: - # - # [:path_names] - # Allows you to change the segment component of the +edit+ and +new+ actions. - # Actions not specified are not changed. - # - # resources :posts, path_names: { new: "brand_new" } - # - # The above example will now change /posts/new to /posts/brand_new - # - # [:path] - # Allows you to change the path prefix for the resource. - # - # resources :posts, path: 'postings' - # - # The resource and all segments will now route to /postings instead of /posts - # - # [:only] - # Only generate routes for the given actions. - # - # resources :cows, only: :show - # resources :cows, only: [:show, :index] - # - # [:except] - # Generate all routes except for the given actions. - # - # resources :cows, except: :show - # resources :cows, except: [:show, :index] - # - # [:shallow] - # Generates shallow routes for nested resource(s). When placed on a parent resource, - # generates shallow routes for all nested resources. - # - # resources :posts, shallow: true do - # resources :comments - # end - # - # Is the same as: - # - # resources :posts do - # resources :comments, except: [:show, :edit, :update, :destroy] - # end - # resources :comments, only: [:show, :edit, :update, :destroy] - # - # This allows URLs for resources that otherwise would be deeply nested such - # as a comment on a blog post like /posts/a-long-permalink/comments/1234 - # to be shortened to just /comments/1234. - # - # [:shallow_path] - # Prefixes nested shallow routes with the specified path. - # - # scope shallow_path: "sekret" do - # resources :posts do - # resources :comments, shallow: true - # end - # end - # - # The +comments+ resource here will have the following routes generated for it: - # - # post_comments GET /posts/:post_id/comments(.:format) - # post_comments POST /posts/:post_id/comments(.:format) - # new_post_comment GET /posts/:post_id/comments/new(.:format) - # edit_comment GET /sekret/comments/:id/edit(.:format) - # comment GET /sekret/comments/:id(.:format) - # comment PATCH/PUT /sekret/comments/:id(.:format) - # comment DELETE /sekret/comments/:id(.:format) - # - # [:shallow_prefix] - # Prefixes nested shallow route names with specified prefix. - # - # scope shallow_prefix: "sekret" do - # resources :posts do - # resources :comments, shallow: true - # end - # end - # - # The +comments+ resource here will have the following routes generated for it: - # - # post_comments GET /posts/:post_id/comments(.:format) - # post_comments POST /posts/:post_id/comments(.:format) - # new_post_comment GET /posts/:post_id/comments/new(.:format) - # edit_sekret_comment GET /comments/:id/edit(.:format) - # sekret_comment GET /comments/:id(.:format) - # sekret_comment PATCH/PUT /comments/:id(.:format) - # sekret_comment DELETE /comments/:id(.:format) - # - # [:format] - # Allows you to specify the default value for optional +format+ - # segment or disable it by supplying +false+. - # - # === Examples - # - # # routes call Admin::PostsController - # resources :posts, module: "admin" - # - # # resource actions are at /admin/posts. - # resources :posts, path: "admin/posts" - def resources(*resources, &block) - options = resources.extract_options!.dup - - if apply_common_behavior_for(:resources, resources, options, &block) - return self - end - - with_scope_level(:resources) do - options = apply_action_options options - resource_scope(Resource.new(resources.pop, api_only?, @scope[:shallow], options)) do - yield if block_given? - - concerns(options[:concerns]) if options[:concerns] - - collection do - get :index if parent_resource.actions.include?(:index) - post :create if parent_resource.actions.include?(:create) - end - - new do - get :new - end if parent_resource.actions.include?(:new) - - set_member_mappings_for_resource - end - end - - self - end - - # To add a route to the collection: - # - # resources :photos do - # collection do - # get 'search' - # end - # end - # - # This will enable Rails to recognize paths such as /photos/search - # with GET, and route to the search action of +PhotosController+. It will also - # create the search_photos_url and search_photos_path - # route helpers. - def collection - unless resource_scope? - raise ArgumentError, "can't use collection outside resource(s) scope" - end - - with_scope_level(:collection) do - path_scope(parent_resource.collection_scope) do - yield - end - end - end - - # To add a member route, add a member block into the resource block: - # - # resources :photos do - # member do - # get 'preview' - # end - # end - # - # This will recognize /photos/1/preview with GET, and route to the - # preview action of +PhotosController+. It will also create the - # preview_photo_url and preview_photo_path helpers. - def member - unless resource_scope? - raise ArgumentError, "can't use member outside resource(s) scope" - end - - with_scope_level(:member) do - if shallow? - shallow_scope { - path_scope(parent_resource.member_scope) { yield } - } - else - path_scope(parent_resource.member_scope) { yield } - end - end - end - - def new - unless resource_scope? - raise ArgumentError, "can't use new outside resource(s) scope" - end - - with_scope_level(:new) do - path_scope(parent_resource.new_scope(action_path(:new))) do - yield - end - end - end - - def nested - unless resource_scope? - raise ArgumentError, "can't use nested outside resource(s) scope" - end - - with_scope_level(:nested) do - if shallow? && shallow_nesting_depth >= 1 - shallow_scope do - path_scope(parent_resource.nested_scope) do - scope(nested_options) { yield } - end - end - else - path_scope(parent_resource.nested_scope) do - scope(nested_options) { yield } - end - end - end - end - - # See ActionDispatch::Routing::Mapper::Scoping#namespace - def namespace(path, options = {}) - if resource_scope? - nested { super } - else - super - end - end - - def shallow - @scope = @scope.new(shallow: true) - yield - ensure - @scope = @scope.parent - end - - def shallow? - !parent_resource.singleton? && @scope[:shallow] - end - - # Matches a url pattern to one or more routes. - # For more information, see match[rdoc-ref:Base#match]. - # - # match 'path' => 'controller#action', via: patch - # match 'path', to: 'controller#action', via: :post - # match 'path', 'otherpath', on: :member, via: :get - def match(path, *rest, &block) - if rest.empty? && Hash === path - options = path - path, to = options.find { |name, _value| name.is_a?(String) } - - raise ArgumentError, "Route path not specified" if path.nil? - - case to - when Symbol - options[:action] = to - when String - if to =~ /#/ - options[:to] = to - else - options[:controller] = to - end - else - options[:to] = to - end - - options.delete(path) - paths = [path] - else - options = rest.pop || {} - paths = [path] + rest - end - - if options.key?(:defaults) - defaults(options.delete(:defaults)) { map_match(paths, options, &block) } - else - map_match(paths, options, &block) - end - end - - # You can specify what Rails should route "/" to with the root method: - # - # root to: 'pages#main' - # - # For options, see +match+, as +root+ uses it internally. - # - # You can also pass a string which will expand - # - # root 'pages#main' - # - # You should put the root route at the top of config/routes.rb, - # because this means it will be matched first. As this is the most popular route - # of most Rails applications, this is beneficial. - def root(path, options = {}) - if path.is_a?(String) - options[:to] = path - elsif path.is_a?(Hash) && options.empty? - options = path - else - raise ArgumentError, "must be called with a path and/or options" - end - - if @scope.resources? - with_scope_level(:root) do - path_scope(parent_resource.path) do - match_root_route(options) - end - end - else - match_root_route(options) - end - end - - private - - def parent_resource - @scope[:scope_level_resource] - end - - def apply_common_behavior_for(method, resources, options, &block) - if resources.length > 1 - resources.each { |r| send(method, r, options, &block) } - return true - end - - if options.delete(:shallow) - shallow do - send(method, resources.pop, options, &block) - end - return true - end - - if resource_scope? - nested { send(method, resources.pop, options, &block) } - return true - end - - options.keys.each do |k| - (options[:constraints] ||= {})[k] = options.delete(k) if options[k].is_a?(Regexp) - end - - scope_options = options.slice!(*RESOURCE_OPTIONS) - unless scope_options.empty? - scope(scope_options) do - send(method, resources.pop, options, &block) - end - return true - end - - false - end - - def apply_action_options(options) - return options if action_options? options - options.merge scope_action_options - end - - def action_options?(options) - options[:only] || options[:except] - end - - def scope_action_options - @scope[:action_options] || {} - end - - def resource_scope? - @scope.resource_scope? - end - - def resource_method_scope? - @scope.resource_method_scope? - end - - def nested_scope? - @scope.nested? - end - - def with_scope_level(kind) # :doc: - @scope = @scope.new_level(kind) - yield - ensure - @scope = @scope.parent - end - - def resource_scope(resource) - @scope = @scope.new(scope_level_resource: resource) - - controller(resource.resource_scope) { yield } - ensure - @scope = @scope.parent - end - - def nested_options - options = { as: parent_resource.member_name } - options[:constraints] = { - parent_resource.nested_param => param_constraint - } if param_constraint? - - options - end - - def shallow_nesting_depth - @scope.find_all { |node| - node.frame[:scope_level_resource] - }.count { |node| node.frame[:scope_level_resource].shallow? } - end - - def param_constraint? - @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp) - end - - def param_constraint - @scope[:constraints][parent_resource.param] - end - - def canonical_action?(action) - resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s) - end - - def shallow_scope - scope = { as: @scope[:shallow_prefix], - path: @scope[:shallow_path] } - @scope = @scope.new scope - - yield - ensure - @scope = @scope.parent - end - - def path_for_action(action, path) - return "#{@scope[:path]}/#{path}" if path - - if canonical_action?(action) - @scope[:path].to_s - else - "#{@scope[:path]}/#{action_path(action)}" - end - end - - def action_path(name) - @scope[:path_names][name.to_sym] || name - end - - def prefix_name_for_action(as, action) - if as - prefix = as - elsif !canonical_action?(action) - prefix = action - end - - if prefix && prefix != "/" && !prefix.empty? - Mapper.normalize_name prefix.to_s.tr("-", "_") - end - end - - def name_for_action(as, action) - prefix = prefix_name_for_action(as, action) - name_prefix = @scope[:as] - - if parent_resource - return nil unless as || action - - collection_name = parent_resource.collection_name - member_name = parent_resource.member_name - end - - action_name = @scope.action_name(name_prefix, prefix, collection_name, member_name) - candidate = action_name.select(&:present?).join("_") - - unless candidate.empty? - # If a name was not explicitly given, we check if it is valid - # and return nil in case it isn't. Otherwise, we pass the invalid name - # forward so the underlying router engine treats it and raises an exception. - if as.nil? - candidate unless candidate !~ /\A[_a-z]/i || has_named_route?(candidate) - else - candidate - end - end - end - - def set_member_mappings_for_resource # :doc: - member do - get :edit if parent_resource.actions.include?(:edit) - get :show if parent_resource.actions.include?(:show) - if parent_resource.actions.include?(:update) - patch :update - put :update - end - delete :destroy if parent_resource.actions.include?(:destroy) - end - end - - def api_only? # :doc: - @set.api_only? - end - - def path_scope(path) - @scope = @scope.new(path: merge_path_scope(@scope[:path], path)) - yield - ensure - @scope = @scope.parent - end - - def map_match(paths, options) - if options[:on] && !VALID_ON_OPTIONS.include?(options[:on]) - raise ArgumentError, "Unknown scope #{on.inspect} given to :on" - end - - if @scope[:to] - options[:to] ||= @scope[:to] - end - - if @scope[:controller] && @scope[:action] - options[:to] ||= "#{@scope[:controller]}##{@scope[:action]}" - end - - controller = options.delete(:controller) || @scope[:controller] - option_path = options.delete :path - to = options.delete :to - via = Mapping.check_via Array(options.delete(:via) { - @scope[:via] - }) - formatted = options.delete(:format) { @scope[:format] } - anchor = options.delete(:anchor) { true } - options_constraints = options.delete(:constraints) || {} - - path_types = paths.group_by(&:class) - path_types.fetch(String, []).each do |_path| - route_options = options.dup - if _path && option_path - raise ArgumentError, "Ambigous route definition. Both :path and the route path where specified as strings." - end - to = get_to_from_path(_path, to, route_options[:action]) - decomposed_match(_path, controller, route_options, _path, to, via, formatted, anchor, options_constraints) - end - - path_types.fetch(Symbol, []).each do |action| - route_options = options.dup - decomposed_match(action, controller, route_options, option_path, to, via, formatted, anchor, options_constraints) - end - - self - end - - def get_to_from_path(path, to, action) - return to if to || action - - path_without_format = path.sub(/\(\.:format\)$/, "") - if using_match_shorthand?(path_without_format) - path_without_format.gsub(%r{^/}, "").sub(%r{/([^/]*)$}, '#\1').tr("-", "_") - else - nil - end - end - - def using_match_shorthand?(path) - path =~ %r{^/?[-\w]+/[-\w/]+$} - end - - def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) - if on = options.delete(:on) - send(on) { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } - else - case @scope.scope_level - when :resources - nested { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } - when :resource - member { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } - else - add_route(path, controller, options, _path, to, via, formatted, anchor, options_constraints) - end - end - end - - def add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) - path = path_for_action(action, _path) - raise ArgumentError, "path is required" if path.blank? - - action = action.to_s - - default_action = options.delete(:action) || @scope[:action] - - if action =~ /^[\w\-\/]+$/ - default_action ||= action.tr("-", "_") unless action.include?("/") - else - action = nil - end - - as = if !options.fetch(:as, true) # if it's set to nil or false - options.delete(:as) - else - name_for_action(options.delete(:as), action) - end - - path = Mapping.normalize_path URI.parser.escape(path), formatted - ast = Journey::Parser.parse path - - mapping = Mapping.build(@scope, @set, ast, controller, default_action, to, via, formatted, options_constraints, anchor, options) - @set.add_route(mapping, as) - end - - def match_root_route(options) - name = has_named_route?(name_for_action(:root, nil)) ? nil : :root - args = ["/", { as: name, via: :get }.merge!(options)] - - match(*args) - end - end - - # Routing Concerns allow you to declare common routes that can be reused - # inside others resources and routes. - # - # concern :commentable do - # resources :comments - # end - # - # concern :image_attachable do - # resources :images, only: :index - # end - # - # These concerns are used in Resources routing: - # - # resources :messages, concerns: [:commentable, :image_attachable] - # - # or in a scope or namespace: - # - # namespace :posts do - # concerns :commentable - # end - module Concerns - # Define a routing concern using a name. - # - # Concerns may be defined inline, using a block, or handled by - # another object, by passing that object as the second parameter. - # - # The concern object, if supplied, should respond to call, - # which will receive two parameters: - # - # * The current mapper - # * A hash of options which the concern object may use - # - # Options may also be used by concerns defined in a block by accepting - # a block parameter. So, using a block, you might do something as - # simple as limit the actions available on certain resources, passing - # standard resource options through the concern: - # - # concern :commentable do |options| - # resources :comments, options - # end - # - # resources :posts, concerns: :commentable - # resources :archived_posts do - # # Don't allow comments on archived posts - # concerns :commentable, only: [:index, :show] - # end - # - # Or, using a callable object, you might implement something more - # specific to your application, which would be out of place in your - # routes file. - # - # # purchasable.rb - # class Purchasable - # def initialize(defaults = {}) - # @defaults = defaults - # end - # - # def call(mapper, options = {}) - # options = @defaults.merge(options) - # mapper.resources :purchases - # mapper.resources :receipts - # mapper.resources :returns if options[:returnable] - # end - # end - # - # # routes.rb - # concern :purchasable, Purchasable.new(returnable: true) - # - # resources :toys, concerns: :purchasable - # resources :electronics, concerns: :purchasable - # resources :pets do - # concerns :purchasable, returnable: false - # end - # - # Any routing helpers can be used inside a concern. If using a - # callable, they're accessible from the Mapper that's passed to - # call. - def concern(name, callable = nil, &block) - callable ||= lambda { |mapper, options| mapper.instance_exec(options, &block) } - @concerns[name] = callable - end - - # Use the named concerns - # - # resources :posts do - # concerns :commentable - # end - # - # concerns also work in any routes helper that you want to use: - # - # namespace :posts do - # concerns :commentable - # end - def concerns(*args) - options = args.extract_options! - args.flatten.each do |name| - if concern = @concerns[name] - concern.call(self, options) - else - raise ArgumentError, "No concern named #{name} was found!" - end - end - end - end - - module CustomUrls - # Define custom url helpers that will be added to the application's - # routes. This allows you to override and/or replace the default behavior - # of routing helpers, e.g: - # - # direct :homepage do - # "http://www.rubyonrails.org" - # end - # - # direct :commentable do |model| - # [ model, anchor: model.dom_id ] - # end - # - # direct :main do - # { controller: "pages", action: "index", subdomain: "www" } - # end - # - # The return value from the block passed to `direct` must be a valid set of - # arguments for `url_for` which will actually build the url string. This can - # be one of the following: - # - # * A string, which is treated as a generated url - # * A hash, e.g. { controller: "pages", action: "index" } - # * An array, which is passed to `polymorphic_url` - # * An Active Model instance - # * An Active Model class - # - # NOTE: Other url helpers can be called in the block but be careful not to invoke - # your custom url helper again otherwise it will result in a stack overflow error - # - # You can also specify default options that will be passed through to - # your url helper definition, e.g: - # - # direct :browse, page: 1, size: 10 do |options| - # [ :products, options.merge(params.permit(:page, :size).to_h.symbolize_keys) ] - # end - # - # In this instance the `params` object comes from the context in which the the - # block is executed, e.g. generating a url inside a controller action or a view. - # If the block is executed where there isn't a params object such as this: - # - # Rails.application.routes.url_helpers.browse_path - # - # then it will raise a `NameError`. Because of this you need to be aware of the - # context in which you will use your custom url helper when defining it. - # - # NOTE: The `direct` method can't be used inside of a scope block such as - # `namespace` or `scope` and will raise an error if it detects that it is. - def direct(name, options = {}, &block) - unless @scope.root? - raise RuntimeError, "The direct method can't be used inside a routes scope block" - end - - @set.add_url_helper(name, options, &block) - end - - # Define custom polymorphic mappings of models to urls. This alters the - # behavior of `polymorphic_url` and consequently the behavior of - # `link_to` and `form_for` when passed a model instance, e.g: - # - # resource :basket - # - # resolve "Basket" do - # [:basket] - # end - # - # This will now generate "/basket" when a `Basket` instance is passed to - # `link_to` or `form_for` instead of the standard "/baskets/:id". - # - # NOTE: This custom behavior only applies to simple polymorphic urls where - # a single model instance is passed and not more complicated forms, e.g: - # - # # config/routes.rb - # resource :profile - # namespace :admin do - # resources :users - # end - # - # resolve("User") { [:profile] } - # - # # app/views/application/_menu.html.erb - # link_to "Profile", @current_user - # link_to "Profile", [:admin, @current_user] - # - # The first `link_to` will generate "/profile" but the second will generate - # the standard polymorphic url of "/admin/users/1". - # - # You can pass options to a polymorphic mapping - the arity for the block - # needs to be two as the instance is passed as the first argument, e.g: - # - # resolve "Basket", anchor: "items" do |basket, options| - # [:basket, options] - # end - # - # This generates the url "/basket#items" because when the last item in an - # array passed to `polymorphic_url` is a hash then it's treated as options - # to the url helper that gets called. - # - # NOTE: The `resolve` method can't be used inside of a scope block such as - # `namespace` or `scope` and will raise an error if it detects that it is. - def resolve(*args, &block) - unless @scope.root? - raise RuntimeError, "The resolve method can't be used inside a routes scope block" - end - - options = args.extract_options! - args = args.flatten(1) - - args.each do |klass| - @set.add_polymorphic_mapping(klass, options, &block) - end - end - end - - class Scope # :nodoc: - OPTIONS = [:path, :shallow_path, :as, :shallow_prefix, :module, - :controller, :action, :path_names, :constraints, - :shallow, :blocks, :defaults, :via, :format, :options, :to] - - RESOURCE_SCOPES = [:resource, :resources] - RESOURCE_METHOD_SCOPES = [:collection, :member, :new] - - attr_reader :parent, :scope_level - - def initialize(hash, parent = NULL, scope_level = nil) - @hash = hash - @parent = parent - @scope_level = scope_level - end - - def nested? - scope_level == :nested - end - - def null? - @hash.nil? && @parent.nil? - end - - def root? - @parent.null? - end - - def resources? - scope_level == :resources - end - - def resource_method_scope? - RESOURCE_METHOD_SCOPES.include? scope_level - end - - def action_name(name_prefix, prefix, collection_name, member_name) - case scope_level - when :nested - [name_prefix, prefix] - when :collection - [prefix, name_prefix, collection_name] - when :new - [prefix, :new, name_prefix, member_name] - when :member - [prefix, name_prefix, member_name] - when :root - [name_prefix, collection_name, prefix] - else - [name_prefix, member_name, prefix] - end - end - - def resource_scope? - RESOURCE_SCOPES.include? scope_level - end - - def options - OPTIONS - end - - def new(hash) - self.class.new hash, self, scope_level - end - - def new_level(level) - self.class.new(frame, self, level) - end - - def [](key) - scope = find { |node| node.frame.key? key } - scope && scope.frame[key] - end - - include Enumerable - - def each - node = self - until node.equal? NULL - yield node - node = node.parent - end - end - - def frame; @hash; end - - NULL = Scope.new(nil, nil) - end - - def initialize(set) #:nodoc: - @set = set - @scope = Scope.new(path_names: @set.resources_path_names) - @concerns = {} - end - - include Base - include HttpHelpers - include Redirection - include Scoping - include Concerns - include Resources - include CustomUrls - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/polymorphic_routes.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/polymorphic_routes.rb deleted file mode 100644 index e89ea8b21d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/polymorphic_routes.rb +++ /dev/null @@ -1,350 +0,0 @@ -module ActionDispatch - module Routing - # Polymorphic URL helpers are methods for smart resolution to a named route call when - # given an Active Record model instance. They are to be used in combination with - # ActionController::Resources. - # - # These methods are useful when you want to generate the correct URL or path to a RESTful - # resource without having to know the exact type of the record in question. - # - # Nested resources and/or namespaces are also supported, as illustrated in the example: - # - # polymorphic_url([:admin, @article, @comment]) - # - # results in: - # - # admin_article_comment_url(@article, @comment) - # - # == Usage within the framework - # - # Polymorphic URL helpers are used in a number of places throughout the \Rails framework: - # - # * url_for, so you can use it with a record as the argument, e.g. - # url_for(@article); - # * ActionView::Helpers::FormHelper uses polymorphic_path, so you can write - # form_for(@article) without having to specify :url parameter for the form - # action; - # * redirect_to (which, in fact, uses url_for) so you can write - # redirect_to(post) in your controllers; - # * ActionView::Helpers::AtomFeedHelper, so you don't have to explicitly specify URLs - # for feed entries. - # - # == Prefixed polymorphic helpers - # - # In addition to polymorphic_url and polymorphic_path methods, a - # number of prefixed helpers are available as a shorthand to action: "..." - # in options. Those are: - # - # * edit_polymorphic_url, edit_polymorphic_path - # * new_polymorphic_url, new_polymorphic_path - # - # Example usage: - # - # edit_polymorphic_path(@post) # => "/posts/1/edit" - # polymorphic_path(@post, format: :pdf) # => "/posts/1.pdf" - # - # == Usage with mounted engines - # - # If you are using a mounted engine and you need to use a polymorphic_url - # pointing at the engine's routes, pass in the engine's route proxy as the first - # argument to the method. For example: - # - # polymorphic_url([blog, @post]) # calls blog.post_path(@post) - # form_for([blog, @post]) # => "/blog/posts/1" - # - module PolymorphicRoutes - # Constructs a call to a named RESTful route for the given record and returns the - # resulting URL string. For example: - # - # # calls post_url(post) - # polymorphic_url(post) # => "http://example.com/posts/1" - # polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1" - # polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1" - # polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1" - # polymorphic_url(Comment) # => "http://example.com/comments" - # - # ==== Options - # - # * :action - Specifies the action prefix for the named route: - # :new or :edit. Default is no prefix. - # * :routing_type - Allowed values are :path or :url. - # Default is :url. - # - # Also includes all the options from url_for. These include such - # things as :anchor or :trailing_slash. Example usage - # is given below: - # - # polymorphic_url([blog, post], anchor: 'my_anchor') - # # => "http://example.com/blogs/1/posts/1#my_anchor" - # polymorphic_url([blog, post], anchor: 'my_anchor', script_name: "/my_app") - # # => "http://example.com/my_app/blogs/1/posts/1#my_anchor" - # - # For all of these options, see the documentation for {url_for}[rdoc-ref:ActionDispatch::Routing::UrlFor]. - # - # ==== Functionality - # - # # an Article record - # polymorphic_url(record) # same as article_url(record) - # - # # a Comment record - # polymorphic_url(record) # same as comment_url(record) - # - # # it recognizes new records and maps to the collection - # record = Comment.new - # polymorphic_url(record) # same as comments_url() - # - # # the class of a record will also map to the collection - # polymorphic_url(Comment) # same as comments_url() - # - def polymorphic_url(record_or_hash_or_array, options = {}) - if Hash === record_or_hash_or_array - options = record_or_hash_or_array.merge(options) - record = options.delete :id - return polymorphic_url record, options - end - - if mapping = polymorphic_mapping(record_or_hash_or_array) - return mapping.call(self, [record_or_hash_or_array, options], false) - end - - opts = options.dup - action = opts.delete :action - type = opts.delete(:routing_type) || :url - - HelperMethodBuilder.polymorphic_method self, - record_or_hash_or_array, - action, - type, - opts - end - - # Returns the path component of a URL for the given record. It uses - # polymorphic_url with routing_type: :path. - def polymorphic_path(record_or_hash_or_array, options = {}) - if Hash === record_or_hash_or_array - options = record_or_hash_or_array.merge(options) - record = options.delete :id - return polymorphic_path record, options - end - - if mapping = polymorphic_mapping(record_or_hash_or_array) - return mapping.call(self, [record_or_hash_or_array, options], true) - end - - opts = options.dup - action = opts.delete :action - type = :path - - HelperMethodBuilder.polymorphic_method self, - record_or_hash_or_array, - action, - type, - opts - end - - %w(edit new).each do |action| - module_eval <<-EOT, __FILE__, __LINE__ + 1 - def #{action}_polymorphic_url(record_or_hash, options = {}) - polymorphic_url_for_action("#{action}", record_or_hash, options) - end - - def #{action}_polymorphic_path(record_or_hash, options = {}) - polymorphic_path_for_action("#{action}", record_or_hash, options) - end - EOT - end - - private - - def polymorphic_url_for_action(action, record_or_hash, options) - polymorphic_url(record_or_hash, options.merge(action: action)) - end - - def polymorphic_path_for_action(action, record_or_hash, options) - polymorphic_path(record_or_hash, options.merge(action: action)) - end - - def polymorphic_mapping(record) - if record.respond_to?(:to_model) - _routes.polymorphic_mappings[record.to_model.model_name.name] - else - _routes.polymorphic_mappings[record.class.name] - end - end - - class HelperMethodBuilder # :nodoc: - CACHE = { "path" => {}, "url" => {} } - - def self.get(action, type) - type = type.to_s - CACHE[type].fetch(action) { build action, type } - end - - def self.url; CACHE["url".freeze][nil]; end - def self.path; CACHE["path".freeze][nil]; end - - def self.build(action, type) - prefix = action ? "#{action}_" : "" - suffix = type - if action.to_s == "new" - HelperMethodBuilder.singular prefix, suffix - else - HelperMethodBuilder.plural prefix, suffix - end - end - - def self.singular(prefix, suffix) - new(->(name) { name.singular_route_key }, prefix, suffix) - end - - def self.plural(prefix, suffix) - new(->(name) { name.route_key }, prefix, suffix) - end - - def self.polymorphic_method(recipient, record_or_hash_or_array, action, type, options) - builder = get action, type - - case record_or_hash_or_array - when Array - record_or_hash_or_array = record_or_hash_or_array.compact - if record_or_hash_or_array.empty? - raise ArgumentError, "Nil location provided. Can't build URI." - end - if record_or_hash_or_array.first.is_a?(ActionDispatch::Routing::RoutesProxy) - recipient = record_or_hash_or_array.shift - end - - method, args = builder.handle_list record_or_hash_or_array - when String, Symbol - method, args = builder.handle_string record_or_hash_or_array - when Class - method, args = builder.handle_class record_or_hash_or_array - - when nil - raise ArgumentError, "Nil location provided. Can't build URI." - else - method, args = builder.handle_model record_or_hash_or_array - end - - if options.empty? - recipient.send(method, *args) - else - recipient.send(method, *args, options) - end - end - - attr_reader :suffix, :prefix - - def initialize(key_strategy, prefix, suffix) - @key_strategy = key_strategy - @prefix = prefix - @suffix = suffix - end - - def handle_string(record) - [get_method_for_string(record), []] - end - - def handle_string_call(target, str) - target.send get_method_for_string str - end - - def handle_class(klass) - [get_method_for_class(klass), []] - end - - def handle_class_call(target, klass) - target.send get_method_for_class klass - end - - def handle_model(record) - args = [] - - model = record.to_model - named_route = if model.persisted? - args << model - get_method_for_string model.model_name.singular_route_key - else - get_method_for_class model - end - - [named_route, args] - end - - def handle_model_call(target, record) - if mapping = polymorphic_mapping(target, record) - mapping.call(target, [record], suffix == "path") - else - method, args = handle_model(record) - target.send(method, *args) - end - end - - def handle_list(list) - record_list = list.dup - record = record_list.pop - - args = [] - - route = record_list.map { |parent| - case parent - when Symbol, String - parent.to_s - when Class - args << parent - parent.model_name.singular_route_key - else - args << parent.to_model - parent.to_model.model_name.singular_route_key - end - } - - route << - case record - when Symbol, String - record.to_s - when Class - @key_strategy.call record.model_name - else - model = record.to_model - if model.persisted? - args << model - model.model_name.singular_route_key - else - @key_strategy.call model.model_name - end - end - - route << suffix - - named_route = prefix + route.join("_") - [named_route, args] - end - - private - - def polymorphic_mapping(target, record) - if record.respond_to?(:to_model) - target._routes.polymorphic_mappings[record.to_model.model_name.name] - else - target._routes.polymorphic_mappings[record.class.name] - end - end - - def get_method_for_class(klass) - name = @key_strategy.call klass.model_name - get_method_for_string name - end - - def get_method_for_string(str) - "#{prefix}#{str}_#{suffix}" - end - - [nil, "new", "edit"].each do |action| - CACHE["url"][action] = build action, "url" - CACHE["path"][action] = build action, "path" - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/redirection.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/redirection.rb deleted file mode 100644 index e8f47b8640..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/redirection.rb +++ /dev/null @@ -1,199 +0,0 @@ -require "action_dispatch/http/request" -require "active_support/core_ext/uri" -require "active_support/core_ext/array/extract_options" -require "rack/utils" -require "action_controller/metal/exceptions" -require "action_dispatch/routing/endpoint" - -module ActionDispatch - module Routing - class Redirect < Endpoint # :nodoc: - attr_reader :status, :block - - def initialize(status, block) - @status = status - @block = block - end - - def redirect?; true; end - - def call(env) - serve Request.new env - end - - def serve(req) - uri = URI.parse(path(req.path_parameters, req)) - - unless uri.host - if relative_path?(uri.path) - uri.path = "#{req.script_name}/#{uri.path}" - elsif uri.path.empty? - uri.path = req.script_name.empty? ? "/" : req.script_name - end - end - - uri.scheme ||= req.scheme - uri.host ||= req.host - uri.port ||= req.port unless req.standard_port? - - req.commit_flash - - body = %(You are being redirected.) - - headers = { - "Location" => uri.to_s, - "Content-Type" => "text/html", - "Content-Length" => body.length.to_s - } - - [ status, headers, [body] ] - end - - def path(params, request) - block.call params, request - end - - def inspect - "redirect(#{status})" - end - - private - def relative_path?(path) - path && !path.empty? && path[0] != "/" - end - - def escape(params) - Hash[params.map { |k, v| [k, Rack::Utils.escape(v)] }] - end - - def escape_fragment(params) - Hash[params.map { |k, v| [k, Journey::Router::Utils.escape_fragment(v)] }] - end - - def escape_path(params) - Hash[params.map { |k, v| [k, Journey::Router::Utils.escape_path(v)] }] - end - end - - class PathRedirect < Redirect - URL_PARTS = /\A([^?]+)?(\?[^#]+)?(#.+)?\z/ - - def path(params, request) - if block.match(URL_PARTS) - path = interpolation_required?($1, params) ? $1 % escape_path(params) : $1 - query = interpolation_required?($2, params) ? $2 % escape(params) : $2 - fragment = interpolation_required?($3, params) ? $3 % escape_fragment(params) : $3 - - "#{path}#{query}#{fragment}" - else - interpolation_required?(block, params) ? block % escape(params) : block - end - end - - def inspect - "redirect(#{status}, #{block})" - end - - private - def interpolation_required?(string, params) - !params.empty? && string && string.match(/%\{\w*\}/) - end - end - - class OptionRedirect < Redirect # :nodoc: - alias :options :block - - def path(params, request) - url_options = { - protocol: request.protocol, - host: request.host, - port: request.optional_port, - path: request.path, - params: request.query_parameters - }.merge! options - - if !params.empty? && url_options[:path].match(/%\{\w*\}/) - url_options[:path] = (url_options[:path] % escape_path(params)) - end - - unless options[:host] || options[:domain] - if relative_path?(url_options[:path]) - url_options[:path] = "/#{url_options[:path]}" - url_options[:script_name] = request.script_name - elsif url_options[:path].empty? - url_options[:path] = request.script_name.empty? ? "/" : "" - url_options[:script_name] = request.script_name - end - end - - ActionDispatch::Http::URL.url_for url_options - end - - def inspect - "redirect(#{status}, #{options.map { |k, v| "#{k}: #{v}" }.join(', ')})" - end - end - - module Redirection - # Redirect any path to another path: - # - # get "/stories" => redirect("/posts") - # - # This will redirect the user, while ignoring certain parts of the request, including query string, etc. - # `/stories`, `/stories?foo=bar`, etc all redirect to `/posts`. - # - # You can also use interpolation in the supplied redirect argument: - # - # get 'docs/:article', to: redirect('/wiki/%{article}') - # - # Note that if you return a path without a leading slash then the url is prefixed with the - # current SCRIPT_NAME environment variable. This is typically '/' but may be different in - # a mounted engine or where the application is deployed to a subdirectory of a website. - # - # Alternatively you can use one of the other syntaxes: - # - # The block version of redirect allows for the easy encapsulation of any logic associated with - # the redirect in question. Either the params and request are supplied as arguments, or just - # params, depending of how many arguments your block accepts. A string is required as a - # return value. - # - # get 'jokes/:number', to: redirect { |params, request| - # path = (params[:number].to_i.even? ? "wheres-the-beef" : "i-love-lamp") - # "http://#{request.host_with_port}/#{path}" - # } - # - # Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass - # the block to +get+ instead of +redirect+. Use { ... } instead. - # - # The options version of redirect allows you to supply only the parts of the url which need - # to change, it also supports interpolation of the path similar to the first example. - # - # get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}') - # get 'stores/:name(*all)', to: redirect(subdomain: 'stores', path: '/%{name}%{all}') - # get '/stories', to: redirect(path: '/posts') - # - # This will redirect the user, while changing only the specified parts of the request, - # for example the `path` option in the last example. - # `/stories`, `/stories?foo=bar`, redirect to `/posts` and `/posts?foo=bar` respectively. - # - # Finally, an object which responds to call can be supplied to redirect, allowing you to reuse - # common redirect routes. The call method must accept two arguments, params and request, and return - # a string. - # - # get 'accounts/:name' => redirect(SubdomainRedirector.new('api')) - # - def redirect(*args, &block) - options = args.extract_options! - status = options.delete(:status) || 301 - path = args.shift - - return OptionRedirect.new(status, options) if options.any? - return PathRedirect.new(status, path) if String === path - - block = path if path.respond_to? :call - raise ArgumentError, "redirection argument not supported" unless block - Redirect.new status, block - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/route_set.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/route_set.rb deleted file mode 100644 index 0cb25d6d43..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/route_set.rb +++ /dev/null @@ -1,885 +0,0 @@ -require "action_dispatch/journey" -require "active_support/core_ext/object/to_query" -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/module/remove_method" -require "active_support/core_ext/array/extract_options" -require "action_controller/metal/exceptions" -require "action_dispatch/http/request" -require "action_dispatch/routing/endpoint" - -module ActionDispatch - module Routing - # :stopdoc: - class RouteSet - # Since the router holds references to many parts of the system - # like engines, controllers and the application itself, inspecting - # the route set can actually be really slow, therefore we default - # alias inspect to to_s. - alias inspect to_s - - class Dispatcher < Routing::Endpoint - def initialize(raise_on_name_error) - @raise_on_name_error = raise_on_name_error - end - - def dispatcher?; true; end - - def serve(req) - params = req.path_parameters - controller = controller req - res = controller.make_response! req - dispatch(controller, params[:action], req, res) - rescue ActionController::RoutingError - if @raise_on_name_error - raise - else - return [404, { "X-Cascade" => "pass" }, []] - end - end - - private - - def controller(req) - req.controller_class - rescue NameError => e - raise ActionController::RoutingError, e.message, e.backtrace - end - - def dispatch(controller, action, req, res) - controller.dispatch(action, req, res) - end - end - - class StaticDispatcher < Dispatcher - def initialize(controller_class) - super(false) - @controller_class = controller_class - end - - private - - def controller(_); @controller_class; end - end - - # A NamedRouteCollection instance is a collection of named routes, and also - # maintains an anonymous module that can be used to install helpers for the - # named routes. - class NamedRouteCollection - include Enumerable - attr_reader :routes, :url_helpers_module, :path_helpers_module - private :routes - - def initialize - @routes = {} - @path_helpers = Set.new - @url_helpers = Set.new - @custom_helpers = Set.new - @url_helpers_module = Module.new - @path_helpers_module = Module.new - end - - def route_defined?(name) - key = name.to_sym - @path_helpers.include?(key) || @url_helpers.include?(key) - end - - def helper_names - @path_helpers.map(&:to_s) + @url_helpers.map(&:to_s) - end - - def clear! - @path_helpers.each do |helper| - @path_helpers_module.send :remove_method, helper - end - - @url_helpers.each do |helper| - @url_helpers_module.send :remove_method, helper - end - - @custom_helpers.each do |helper| - path_name = :"#{helper}_path" - url_name = :"#{helper}_url" - - if @path_helpers_module.method_defined?(path_name) - @path_helpers_module.send :remove_method, path_name - end - - if @url_helpers_module.method_defined?(url_name) - @url_helpers_module.send :remove_method, url_name - end - end - - @routes.clear - @path_helpers.clear - @url_helpers.clear - @custom_helpers.clear - end - - def add(name, route) - key = name.to_sym - path_name = :"#{name}_path" - url_name = :"#{name}_url" - - if routes.key? key - @path_helpers_module.send :undef_method, path_name - @url_helpers_module.send :undef_method, url_name - end - routes[key] = route - define_url_helper @path_helpers_module, route, path_name, route.defaults, name, PATH - define_url_helper @url_helpers_module, route, url_name, route.defaults, name, UNKNOWN - - @path_helpers << path_name - @url_helpers << url_name - end - - def get(name) - routes[name.to_sym] - end - - def key?(name) - return unless name - routes.key? name.to_sym - end - - alias []= add - alias [] get - alias clear clear! - - def each - routes.each { |name, route| yield name, route } - self - end - - def names - routes.keys - end - - def length - routes.length - end - - def add_url_helper(name, defaults, &block) - @custom_helpers << name - helper = CustomUrlHelper.new(name, defaults, &block) - - @path_helpers_module.module_eval do - define_method(:"#{name}_path") do |*args| - helper.call(self, args, true) - end - end - - @url_helpers_module.module_eval do - define_method(:"#{name}_url") do |*args| - helper.call(self, args, false) - end - end - end - - class UrlHelper - def self.create(route, options, route_name, url_strategy) - if optimize_helper?(route) - OptimizedUrlHelper.new(route, options, route_name, url_strategy) - else - new route, options, route_name, url_strategy - end - end - - def self.optimize_helper?(route) - !route.glob? && route.path.requirements.empty? - end - - attr_reader :url_strategy, :route_name - - class OptimizedUrlHelper < UrlHelper - attr_reader :arg_size - - def initialize(route, options, route_name, url_strategy) - super - @required_parts = @route.required_parts - @arg_size = @required_parts.size - end - - def call(t, args, inner_options) - if args.size == arg_size && !inner_options && optimize_routes_generation?(t) - options = t.url_options.merge @options - options[:path] = optimized_helper(args) - - original_script_name = options.delete(:original_script_name) - script_name = t._routes.find_script_name(options) - - if original_script_name - script_name = original_script_name + script_name - end - - options[:script_name] = script_name - - url_strategy.call options - else - super - end - end - - private - - def optimized_helper(args) - params = parameterize_args(args) do - raise_generation_error(args) - end - - @route.format params - end - - def optimize_routes_generation?(t) - t.send(:optimize_routes_generation?) - end - - def parameterize_args(args) - params = {} - @arg_size.times { |i| - key = @required_parts[i] - value = args[i].to_param - yield key if value.nil? || value.empty? - params[key] = value - } - params - end - - def raise_generation_error(args) - missing_keys = [] - params = parameterize_args(args) { |missing_key| - missing_keys << missing_key - } - constraints = Hash[@route.requirements.merge(params).sort_by { |k, v| k.to_s }] - message = "No route matches #{constraints.inspect}" - message << ", missing required keys: #{missing_keys.sort.inspect}" - - raise ActionController::UrlGenerationError, message - end - end - - def initialize(route, options, route_name, url_strategy) - @options = options - @segment_keys = route.segment_keys.uniq - @route = route - @url_strategy = url_strategy - @route_name = route_name - end - - def call(t, args, inner_options) - controller_options = t.url_options - options = controller_options.merge @options - hash = handle_positional_args(controller_options, - inner_options || {}, - args, - options, - @segment_keys) - - t._routes.url_for(hash, route_name, url_strategy) - end - - def handle_positional_args(controller_options, inner_options, args, result, path_params) - if args.size > 0 - # take format into account - if path_params.include?(:format) - path_params_size = path_params.size - 1 - else - path_params_size = path_params.size - end - - if args.size < path_params_size - path_params -= controller_options.keys - path_params -= result.keys - else - path_params = path_params.dup - end - inner_options.each_key do |key| - path_params.delete(key) - end - - args.each_with_index do |arg, index| - param = path_params[index] - result[param] = arg if param - end - end - - result.merge!(inner_options) - end - end - - private - # Create a url helper allowing ordered parameters to be associated - # with corresponding dynamic segments, so you can do: - # - # foo_url(bar, baz, bang) - # - # Instead of: - # - # foo_url(bar: bar, baz: baz, bang: bang) - # - # Also allow options hash, so you can do: - # - # foo_url(bar, baz, bang, sort_by: 'baz') - # - def define_url_helper(mod, route, name, opts, route_key, url_strategy) - helper = UrlHelper.create(route, opts, route_key, url_strategy) - mod.module_eval do - define_method(name) do |*args| - last = args.last - options = \ - case last - when Hash - args.pop - when ActionController::Parameters - args.pop.to_h - end - helper.call self, args, options - end - end - end - end - - # strategy for building urls to send to the client - PATH = ->(options) { ActionDispatch::Http::URL.path_for(options) } - UNKNOWN = ->(options) { ActionDispatch::Http::URL.url_for(options) } - - attr_accessor :formatter, :set, :named_routes, :default_scope, :router - attr_accessor :disable_clear_and_finalize, :resources_path_names - attr_accessor :default_url_options - attr_reader :env_key, :polymorphic_mappings - - alias :routes :set - - def self.default_resources_path_names - { new: "new", edit: "edit" } - end - - def self.new_with_config(config) - route_set_config = DEFAULT_CONFIG - - # engines apparently don't have this set - if config.respond_to? :relative_url_root - route_set_config.relative_url_root = config.relative_url_root - end - - if config.respond_to? :api_only - route_set_config.api_only = config.api_only - end - - new route_set_config - end - - Config = Struct.new :relative_url_root, :api_only - - DEFAULT_CONFIG = Config.new(nil, false) - - def initialize(config = DEFAULT_CONFIG) - self.named_routes = NamedRouteCollection.new - self.resources_path_names = self.class.default_resources_path_names - self.default_url_options = {} - - @config = config - @append = [] - @prepend = [] - @disable_clear_and_finalize = false - @finalized = false - @env_key = "ROUTES_#{object_id}_SCRIPT_NAME".freeze - - @set = Journey::Routes.new - @router = Journey::Router.new @set - @formatter = Journey::Formatter.new self - @polymorphic_mappings = {} - end - - def eager_load! - router.eager_load! - routes.each(&:eager_load!) - nil - end - - def relative_url_root - @config.relative_url_root - end - - def api_only? - @config.api_only - end - - def request_class - ActionDispatch::Request - end - - def make_request(env) - request_class.new env - end - private :make_request - - def draw(&block) - clear! unless @disable_clear_and_finalize - eval_block(block) - finalize! unless @disable_clear_and_finalize - nil - end - - def append(&block) - @append << block - end - - def prepend(&block) - @prepend << block - end - - def eval_block(block) - mapper = Mapper.new(self) - if default_scope - mapper.with_default_scope(default_scope, &block) - else - mapper.instance_exec(&block) - end - end - private :eval_block - - def finalize! - return if @finalized - @append.each { |blk| eval_block(blk) } - @finalized = true - end - - def clear! - @finalized = false - named_routes.clear - set.clear - formatter.clear - @polymorphic_mappings.clear - @prepend.each { |blk| eval_block(blk) } - end - - module MountedHelpers - extend ActiveSupport::Concern - include UrlFor - end - - # Contains all the mounted helpers across different - # engines and the `main_app` helper for the application. - # You can include this in your classes if you want to - # access routes for other engines. - def mounted_helpers - MountedHelpers - end - - def define_mounted_helper(name, script_namer = nil) - return if MountedHelpers.method_defined?(name) - - routes = self - helpers = routes.url_helpers - - MountedHelpers.class_eval do - define_method "_#{name}" do - RoutesProxy.new(routes, _routes_context, helpers, script_namer) - end - end - - MountedHelpers.class_eval(<<-RUBY, __FILE__, __LINE__ + 1) - def #{name} - @_#{name} ||= _#{name} - end - RUBY - end - - def url_helpers(supports_path = true) - routes = self - - Module.new do - extend ActiveSupport::Concern - include UrlFor - - # Define url_for in the singleton level so one can do: - # Rails.application.routes.url_helpers.url_for(args) - proxy_class = Class.new do - include UrlFor - include routes.named_routes.path_helpers_module - include routes.named_routes.url_helpers_module - - attr_reader :_routes - - def initialize(routes) - @_routes = routes - end - - def optimize_routes_generation? - @_routes.optimize_routes_generation? - end - end - - @_proxy = proxy_class.new(routes) - - class << self - def url_for(options) - @_proxy.url_for(options) - end - - def full_url_for(options) - @_proxy.full_url_for(options) - end - - def route_for(name, *args) - @_proxy.route_for(name, *args) - end - - def optimize_routes_generation? - @_proxy.optimize_routes_generation? - end - - def polymorphic_url(record_or_hash_or_array, options = {}) - @_proxy.polymorphic_url(record_or_hash_or_array, options) - end - - def polymorphic_path(record_or_hash_or_array, options = {}) - @_proxy.polymorphic_path(record_or_hash_or_array, options) - end - - def _routes; @_proxy._routes; end - def url_options; {}; end - end - - url_helpers = routes.named_routes.url_helpers_module - - # Make named_routes available in the module singleton - # as well, so one can do: - # Rails.application.routes.url_helpers.posts_path - extend url_helpers - - # Any class that includes this module will get all - # named routes... - include url_helpers - - if supports_path - path_helpers = routes.named_routes.path_helpers_module - - include path_helpers - extend path_helpers - end - - # plus a singleton class method called _routes ... - included do - singleton_class.send(:redefine_method, :_routes) { routes } - end - - # And an instance method _routes. Note that - # UrlFor (included in this module) add extra - # conveniences for working with @_routes. - define_method(:_routes) { @_routes || routes } - - define_method(:_generate_paths_by_default) do - supports_path - end - - private :_generate_paths_by_default - end - end - - def empty? - routes.empty? - end - - def add_route(mapping, name) - raise ArgumentError, "Invalid route name: '#{name}'" unless name.blank? || name.to_s.match(/^[_a-z]\w*$/i) - - if name && named_routes[name] - raise ArgumentError, "Invalid route name, already in use: '#{name}' \n" \ - "You may have defined two routes with the same name using the `:as` option, or " \ - "you may be overriding a route already defined by a resource with the same naming. " \ - "For the latter, you can restrict the routes created with `resources` as explained here: \n" \ - "http://guides.rubyonrails.org/routing.html#restricting-the-routes-created" - end - - route = @set.add_route(name, mapping) - named_routes[name] = route if name - - if route.segment_keys.include?(:controller) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Using a dynamic :controller segment in a route is deprecated and - will be removed in Rails 5.2. - MSG - end - - if route.segment_keys.include?(:action) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Using a dynamic :action segment in a route is deprecated and - will be removed in Rails 5.2. - MSG - end - - route - end - - def add_polymorphic_mapping(klass, options, &block) - @polymorphic_mappings[klass] = CustomUrlHelper.new(klass, options, &block) - end - - def add_url_helper(name, options, &block) - named_routes.add_url_helper(name, options, &block) - end - - class CustomUrlHelper - attr_reader :name, :defaults, :block - - def initialize(name, defaults, &block) - @name = name - @defaults = defaults - @block = block - end - - def call(t, args, only_path = false) - options = args.extract_options! - url = t.full_url_for(eval_block(t, args, options)) - - if only_path - "/" + url.partition(%r{(? e - raise ActionController::RoutingError, e.message - end - - req = make_request(env) - @router.recognize(req) do |route, params| - params.merge!(extras) - params.each do |key, value| - if value.is_a?(String) - value = value.dup.force_encoding(Encoding::BINARY) - params[key] = URI.parser.unescape(value) - end - end - req.path_parameters = params - app = route.app - if app.matches?(req) && app.dispatcher? - begin - req.controller_class - rescue NameError - raise ActionController::RoutingError, "A route matches #{path.inspect}, but references missing controller: #{params[:controller].camelize}Controller" - end - - return req.path_parameters - end - end - - raise ActionController::RoutingError, "No route matches #{path.inspect}" - end - end - # :startdoc: - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/routes_proxy.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/routes_proxy.rb deleted file mode 100644 index 7143b7b9ab..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/routes_proxy.rb +++ /dev/null @@ -1,66 +0,0 @@ -require "active_support/core_ext/array/extract_options" - -module ActionDispatch - module Routing - class RoutesProxy #:nodoc: - include ActionDispatch::Routing::UrlFor - - attr_accessor :scope, :routes - alias :_routes :routes - - def initialize(routes, scope, helpers, script_namer = nil) - @routes, @scope = routes, scope - @helpers = helpers - @script_namer = script_namer - end - - def url_options - scope.send(:_with_routes, routes) do - scope.url_options - end - end - - def respond_to_missing?(method, include_private = false) - super || @helpers.respond_to?(method) - end - - def method_missing(method, *args) - if @helpers.respond_to?(method) - self.class.class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{method}(*args) - options = args.extract_options! - options = url_options.merge((options || {}).symbolize_keys) - - if @script_namer - options[:script_name] = merge_script_names( - options[:script_name], - @script_namer.call(options) - ) - end - - args << options - @helpers.#{method}(*args) - end - RUBY - send(method, *args) - else - super - end - end - - # Keeps the part of the script name provided by the global - # context via ENV["SCRIPT_NAME"], which `mount` doesn't know - # about since it depends on the specific request, but use our - # script name resolver for the mount point dependent part. - def merge_script_names(previous_script_name, new_script_name) - return new_script_name unless previous_script_name - - resolved_parts = new_script_name.count("/") - previous_parts = previous_script_name.count("/") - context_parts = previous_parts - resolved_parts + 1 - - (previous_script_name.split("/").slice(0, context_parts).join("/")) + new_script_name - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/url_for.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/url_for.rb deleted file mode 100644 index f8b9f64399..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/routing/url_for.rb +++ /dev/null @@ -1,216 +0,0 @@ -module ActionDispatch - module Routing - # In config/routes.rb you define URL-to-controller mappings, but the reverse - # is also possible: a URL can be generated from one of your routing definitions. - # URL generation functionality is centralized in this module. - # - # See ActionDispatch::Routing for general information about routing and routes.rb. - # - # Tip: If you need to generate URLs from your models or some other place, - # then ActionController::UrlFor is what you're looking for. Read on for - # an introduction. In general, this module should not be included on its own, - # as it is usually included by url_helpers (as in Rails.application.routes.url_helpers). - # - # == URL generation from parameters - # - # As you may know, some functions, such as ActionController::Base#url_for - # and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set - # of parameters. For example, you've probably had the chance to write code - # like this in one of your views: - # - # <%= link_to('Click here', controller: 'users', - # action: 'new', message: 'Welcome!') %> - # # => Click here - # - # link_to, and all other functions that require URL generation functionality, - # actually use ActionController::UrlFor under the hood. And in particular, - # they use the ActionController::UrlFor#url_for method. One can generate - # the same path as the above example by using the following code: - # - # include UrlFor - # url_for(controller: 'users', - # action: 'new', - # message: 'Welcome!', - # only_path: true) - # # => "/users/new?message=Welcome%21" - # - # Notice the only_path: true part. This is because UrlFor has no - # information about the website hostname that your Rails app is serving. So if you - # want to include the hostname as well, then you must also pass the :host - # argument: - # - # include UrlFor - # url_for(controller: 'users', - # action: 'new', - # message: 'Welcome!', - # host: 'www.example.com') - # # => "http://www.example.com/users/new?message=Welcome%21" - # - # By default, all controllers and views have access to a special version of url_for, - # that already knows what the current hostname is. So if you use url_for in your - # controllers or your views, then you don't need to explicitly pass the :host - # argument. - # - # For convenience reasons, mailers provide a shortcut for ActionController::UrlFor#url_for. - # So within mailers, you only have to type +url_for+ instead of 'ActionController::UrlFor#url_for' - # in full. However, mailers don't have hostname information, and you still have to provide - # the +:host+ argument or set the default host that will be used in all mailers using the - # configuration option +config.action_mailer.default_url_options+. For more information on - # url_for in mailers read the ActionMailer#Base documentation. - # - # - # == URL generation for named routes - # - # UrlFor also allows one to access methods that have been auto-generated from - # named routes. For example, suppose that you have a 'users' resource in your - # config/routes.rb: - # - # resources :users - # - # This generates, among other things, the method users_path. By default, - # this method is accessible from your controllers, views and mailers. If you need - # to access this auto-generated method from other places (such as a model), then - # you can do that by including Rails.application.routes.url_helpers in your class: - # - # class User < ActiveRecord::Base - # include Rails.application.routes.url_helpers - # - # def base_uri - # user_path(self) - # end - # end - # - # User.find(1).base_uri # => "/users/1" - # - module UrlFor - extend ActiveSupport::Concern - include PolymorphicRoutes - - included do - unless method_defined?(:default_url_options) - # Including in a class uses an inheritable hash. Modules get a plain hash. - if respond_to?(:class_attribute) - class_attribute :default_url_options - else - mattr_writer :default_url_options - end - - self.default_url_options = {} - end - - include(*_url_for_modules) if respond_to?(:_url_for_modules) - end - - def initialize(*) - @_routes = nil - super - end - - # Hook overridden in controller to add request information - # with `default_url_options`. Application logic should not - # go into url_options. - def url_options - default_url_options - end - - # Generate a url based on the options provided, default_url_options and the - # routes defined in routes.rb. The following options are supported: - # - # * :only_path - If true, the relative url is returned. Defaults to +false+. - # * :protocol - The protocol to connect to. Defaults to 'http'. - # * :host - Specifies the host the link should be targeted at. - # If :only_path is false, this option must be - # provided either explicitly, or via +default_url_options+. - # * :subdomain - Specifies the subdomain of the link, using the +tld_length+ - # to split the subdomain from the host. - # If false, removes all subdomains from the host part of the link. - # * :domain - Specifies the domain of the link, using the +tld_length+ - # to split the domain from the host. - # * :tld_length - Number of labels the TLD id composed of, only used if - # :subdomain or :domain are supplied. Defaults to - # ActionDispatch::Http::URL.tld_length, which in turn defaults to 1. - # * :port - Optionally specify the port to connect to. - # * :anchor - An anchor name to be appended to the path. - # * :trailing_slash - If true, adds a trailing slash, as in "/archive/2009/" - # * :script_name - Specifies application path relative to domain root. If provided, prepends application path. - # - # Any other key (:controller, :action, etc.) given to - # +url_for+ is forwarded to the Routes module. - # - # url_for controller: 'tasks', action: 'testing', host: 'somehost.org', port: '8080' - # # => 'http://somehost.org:8080/tasks/testing' - # url_for controller: 'tasks', action: 'testing', host: 'somehost.org', anchor: 'ok', only_path: true - # # => '/tasks/testing#ok' - # url_for controller: 'tasks', action: 'testing', trailing_slash: true - # # => 'http://somehost.org/tasks/testing/' - # url_for controller: 'tasks', action: 'testing', host: 'somehost.org', number: '33' - # # => 'http://somehost.org/tasks/testing?number=33' - # url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp" - # # => 'http://somehost.org/myapp/tasks/testing' - # url_for controller: 'tasks', action: 'testing', host: 'somehost.org', script_name: "/myapp", only_path: true - # # => '/myapp/tasks/testing' - # - # Missing routes keys may be filled in from the current request's parameters - # (e.g. +:controller+, +:action+, +:id+ and any other parameters that are - # placed in the path). Given that the current action has been reached - # through `GET /users/1`: - # - # url_for(only_path: true) # => '/users/1' - # url_for(only_path: true, action: 'edit') # => '/users/1/edit' - # url_for(only_path: true, action: 'edit', id: 2) # => '/users/2/edit' - # - # Notice that no +:id+ parameter was provided to the first +url_for+ call - # and the helper used the one from the route's path. Any path parameter - # implicitly used by +url_for+ can always be overwritten like shown on the - # last +url_for+ calls. - def url_for(options = nil) - full_url_for(options) - end - - def full_url_for(options = nil) # :nodoc: - case options - when nil - _routes.url_for(url_options.symbolize_keys) - when Hash, ActionController::Parameters - route_name = options.delete :use_route - merged_url_options = options.to_h.symbolize_keys.reverse_merge!(url_options) - _routes.url_for(merged_url_options, route_name) - when String - options - when Symbol - HelperMethodBuilder.url.handle_string_call self, options - when Array - components = options.dup - polymorphic_url(components, components.extract_options!) - when Class - HelperMethodBuilder.url.handle_class_call self, options - else - HelperMethodBuilder.url.handle_model_call self, options - end - end - - def route_for(name, *args) # :nodoc: - public_send(:"#{name}_url", *args) - end - - protected - - def optimize_routes_generation? - _routes.optimize_routes_generation? && default_url_options.empty? - end - - private - - def _with_routes(routes) # :doc: - old_routes, @_routes = @_routes, routes - yield - ensure - @_routes = old_routes - end - - def _routes_context # :doc: - self - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_test_case.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_test_case.rb deleted file mode 100644 index 891847d1c5..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_test_case.rb +++ /dev/null @@ -1,131 +0,0 @@ -gem "capybara", ">= 2.15" - -require "capybara/dsl" -require "capybara/minitest" -require "action_controller" -require "action_dispatch/system_testing/driver" -require "action_dispatch/system_testing/server" -require "action_dispatch/system_testing/test_helpers/screenshot_helper" -require "action_dispatch/system_testing/test_helpers/setup_and_teardown" - -module ActionDispatch - # = System Testing - # - # System tests let you test applications in the browser. Because system - # tests use a real browser experience, you can test all of your JavaScript - # easily from your test suite. - # - # To create a system test in your application, extend your test class - # from ApplicationSystemTestCase. System tests use Capybara as a - # base and allow you to configure the settings through your - # application_system_test_case.rb file that is generated with a new - # application or scaffold. - # - # Here is an example system test: - # - # require 'application_system_test_case' - # - # class Users::CreateTest < ApplicationSystemTestCase - # test "adding a new user" do - # visit users_path - # click_on 'New User' - # - # fill_in 'Name', with: 'Arya' - # click_on 'Create User' - # - # assert_text 'Arya' - # end - # end - # - # When generating an application or scaffold, an +application_system_test_case.rb+ - # file will also be generated containing the base class for system testing. - # This is where you can change the driver, add Capybara settings, and other - # configuration for your system tests. - # - # require "test_helper" - # - # class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - # driven_by :selenium, using: :chrome, screen_size: [1400, 1400] - # end - # - # By default, ActionDispatch::SystemTestCase is driven by the - # Selenium driver, with the Chrome browser, and a browser size of 1400x1400. - # - # Changing the driver configuration options are easy. Let's say you want to use - # the Firefox browser instead of Chrome. In your +application_system_test_case.rb+ - # file add the following: - # - # require "test_helper" - # - # class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - # driven_by :selenium, using: :firefox - # end - # - # +driven_by+ has a required argument for the driver name. The keyword - # arguments are +:using+ for the browser and +:screen_size+ to change the - # size of the browser screen. These two options are not applicable for - # headless drivers and will be silently ignored if passed. - # - # To use a headless driver, like Poltergeist, update your Gemfile to use - # Poltergeist instead of Selenium and then declare the driver name in the - # +application_system_test_case.rb+ file. In this case you would leave out the +:using+ - # option because the driver is headless, but you can still use - # +:screen_size+ to change the size of the browser screen, also you can use - # +:options+ to pass options supported by the driver. Please refeer to your - # driver documentation to learn about supported options. - # - # require "test_helper" - # require "capybara/poltergeist" - # - # class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - # driven_by :poltergeist, screen_size: [1400, 1400], options: - # { js_errors: true } - # end - # - # Because ActionDispatch::SystemTestCase is a shim between Capybara - # and Rails, any driver that is supported by Capybara is supported by system - # tests as long as you include the required gems and files. - class SystemTestCase < IntegrationTest - include Capybara::DSL - include Capybara::Minitest::Assertions - include SystemTesting::TestHelpers::SetupAndTeardown - include SystemTesting::TestHelpers::ScreenshotHelper - - def initialize(*) # :nodoc: - super - self.class.driver.use - end - - def self.start_application # :nodoc: - Capybara.app = Rack::Builder.new do - map "/" do - run Rails.application - end - end - - SystemTesting::Server.new.run - end - - class_attribute :driver, instance_accessor: false - - # System Test configuration options - # - # The default settings are Selenium, using Chrome, with a screen size - # of 1400x1400. - # - # Examples: - # - # driven_by :poltergeist - # - # driven_by :selenium, using: :firefox - # - # driven_by :selenium, screen_size: [800, 800] - def self.driven_by(driver, using: :chrome, screen_size: [1400, 1400], options: {}) - self.driver = SystemTesting::Driver.new(driver, using: using, screen_size: screen_size, options: options) - end - - driven_by :selenium - end - - SystemTestCase.start_application -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/driver.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/driver.rb deleted file mode 100644 index 81e6f0fc80..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/driver.rb +++ /dev/null @@ -1,53 +0,0 @@ -module ActionDispatch - module SystemTesting - class Driver # :nodoc: - def initialize(name, **options) - @name = name - @browser = options[:using] - @screen_size = options[:screen_size] - @options = options[:options] - end - - def use - register if registerable? - - setup - end - - private - def registerable? - [:selenium, :poltergeist, :webkit].include?(@name) - end - - def register - Capybara.register_driver @name do |app| - case @name - when :selenium then register_selenium(app) - when :poltergeist then register_poltergeist(app) - when :webkit then register_webkit(app) - end - end - end - - def register_selenium(app) - Capybara::Selenium::Driver.new(app, { browser: @browser }.merge(@options)).tap do |driver| - driver.browser.manage.window.size = Selenium::WebDriver::Dimension.new(*@screen_size) - end - end - - def register_poltergeist(app) - Capybara::Poltergeist::Driver.new(app, @options.merge(window_size: @screen_size)) - end - - def register_webkit(app) - Capybara::Webkit::Driver.new(app, Capybara::Webkit::Configuration.to_hash.merge(@options)).tap do |driver| - driver.resize_window(*@screen_size) - end - end - - def setup - Capybara.current_driver = @name - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/server.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/server.rb deleted file mode 100644 index 5a7c2f0cb3..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/server.rb +++ /dev/null @@ -1,45 +0,0 @@ -require "rack/handler/puma" - -module ActionDispatch - module SystemTesting - class Server # :nodoc: - class << self - attr_accessor :silence_puma - end - - self.silence_puma = false - - def run - register - setup - end - - private - def register - Capybara.register_server :rails_puma do |app, port, host| - Rack::Handler::Puma.run( - app, - Port: port, - Threads: "0:1", - workers: 0, - daemon: false, - Silent: self.class.silence_puma - ) - end - end - - def setup - set_server - set_port - end - - def set_server - Capybara.server = :rails_puma - end - - def set_port - Capybara.always_include_port = true - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb deleted file mode 100644 index 7abd08952a..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb +++ /dev/null @@ -1,98 +0,0 @@ -module ActionDispatch - module SystemTesting - module TestHelpers - # Screenshot helper for system testing - module ScreenshotHelper - # Takes a screenshot of the current page in the browser. - # - # +take_screenshot+ can be used at any point in your system tests to take - # a screenshot of the current state. This can be useful for debugging or - # automating visual testing. - # - # The screenshot will be displayed in your console, if supported. - # - # You can set the +RAILS_SYSTEM_TESTING_SCREENSHOT+ environment variable to - # control the output. Possible values are: - # * [+inline+ (default)] display the screenshot in the terminal using the - # iTerm image protocol (http://iterm2.com/documentation-images.html). - # * [+simple+] only display the screenshot path. - # This is the default value if the +CI+ environment variables - # is defined. - # * [+artifact+] display the screenshot in the terminal, using the terminal - # artifact format (http://buildkite.github.io/terminal/inline-images/). - def take_screenshot - save_image - puts display_image - end - - # Takes a screenshot of the current page in the browser if the test - # failed. - # - # +take_failed_screenshot+ is included in application_system_test_case.rb - # that is generated with the application. To take screenshots when a test - # fails add +take_failed_screenshot+ to the teardown block before clearing - # sessions. - def take_failed_screenshot - take_screenshot if failed? && supports_screenshot? - end - - private - def image_name - failed? ? "failures_#{method_name}" : method_name - end - - def image_path - @image_path ||= absolute_image_path.relative_path_from(Pathname.pwd).to_s - end - - def absolute_image_path - Rails.root.join("tmp/screenshots/#{image_name}.png") - end - - def save_image - page.save_screenshot(absolute_image_path) - end - - def output_type - # Environment variables have priority - output_type = ENV["RAILS_SYSTEM_TESTING_SCREENSHOT"] || ENV["CAPYBARA_INLINE_SCREENSHOT"] - - # If running in a CI environment, default to simple - output_type ||= "simple" if ENV["CI"] - - # Default - output_type ||= "inline" - - output_type - end - - def display_image - message = "[Screenshot]: #{image_path}\n" - - case output_type - when "artifact" - message << "\e]1338;url=artifact://#{absolute_image_path}\a\n" - when "inline" - name = inline_base64(File.basename(absolute_image_path)) - image = inline_base64(File.read(absolute_image_path)) - message << "\e]1337;File=name=#{name};height=400px;inline=1:#{image}\a\n" - end - - message - end - - def inline_base64(path) - Base64.encode64(path).gsub("\n", "") - end - - def failed? - !passed? && !skipped? - end - - def supports_screenshot? - Capybara.current_driver != :rack_test - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb deleted file mode 100644 index f03f0d4299..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActionDispatch - module SystemTesting - module TestHelpers - module SetupAndTeardown # :nodoc: - DEFAULT_HOST = "http://127.0.0.1" - - def host!(host) - super - Capybara.app_host = host - end - - def before_setup - host! DEFAULT_HOST - super - end - - def after_teardown - take_failed_screenshot - Capybara.reset_sessions! - super - end - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertion_response.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertion_response.rb deleted file mode 100644 index c37726957e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertion_response.rb +++ /dev/null @@ -1,45 +0,0 @@ -module ActionDispatch - # This is a class that abstracts away an asserted response. It purposely - # does not inherit from Response because it doesn't need it. That means it - # does not have headers or a body. - class AssertionResponse - attr_reader :code, :name - - GENERIC_RESPONSE_CODES = { # :nodoc: - success: "2XX", - missing: "404", - redirect: "3XX", - error: "5XX" - } - - # Accepts a specific response status code as an Integer (404) or String - # ('404') or a response status range as a Symbol pseudo-code (:success, - # indicating any 200-299 status code). - def initialize(code_or_name) - if code_or_name.is_a?(Symbol) - @name = code_or_name - @code = code_from_name(code_or_name) - else - @name = name_from_code(code_or_name) - @code = code_or_name - end - - raise ArgumentError, "Invalid response name: #{name}" if @code.nil? - raise ArgumentError, "Invalid response code: #{code}" if @name.nil? - end - - def code_and_name - "#{code}: #{name}" - end - - private - - def code_from_name(name) - GENERIC_RESPONSE_CODES[name] || Rack::Utils::SYMBOL_TO_STATUS_CODE[name] - end - - def name_from_code(code) - GENERIC_RESPONSE_CODES.invert[code] || Rack::Utils::HTTP_STATUS_CODES[code] - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions.rb deleted file mode 100644 index 4ea18d671d..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "rails-dom-testing" - -module ActionDispatch - module Assertions - autoload :ResponseAssertions, "action_dispatch/testing/assertions/response" - autoload :RoutingAssertions, "action_dispatch/testing/assertions/routing" - - extend ActiveSupport::Concern - - include ResponseAssertions - include RoutingAssertions - include Rails::Dom::Testing::Assertions - - def html_document - @html_document ||= if @response.content_type.to_s.end_with?("xml") - Nokogiri::XML::Document.parse(@response.body) - else - Nokogiri::HTML::Document.parse(@response.body) - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions/response.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions/response.rb deleted file mode 100644 index 817737341c..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions/response.rb +++ /dev/null @@ -1,105 +0,0 @@ -module ActionDispatch - module Assertions - # A small suite of assertions that test responses from \Rails applications. - module ResponseAssertions - RESPONSE_PREDICATES = { # :nodoc: - success: :successful?, - missing: :not_found?, - redirect: :redirection?, - error: :server_error?, - } - - # Asserts that the response is one of the following types: - # - # * :success - Status code was in the 200-299 range - # * :redirect - Status code was in the 300-399 range - # * :missing - Status code was 404 - # * :error - Status code was in the 500-599 range - # - # You can also pass an explicit status number like assert_response(501) - # or its symbolic equivalent assert_response(:not_implemented). - # See Rack::Utils::SYMBOL_TO_STATUS_CODE for a full list. - # - # # Asserts that the response was a redirection - # assert_response :redirect - # - # # Asserts that the response code was status code 401 (unauthorized) - # assert_response 401 - def assert_response(type, message = nil) - message ||= generate_response_message(type) - - if RESPONSE_PREDICATES.keys.include?(type) - assert @response.send(RESPONSE_PREDICATES[type]), message - else - assert_equal AssertionResponse.new(type).code, @response.response_code, message - end - end - - # Asserts that the redirection options passed in match those of the redirect called in the latest action. - # This match can be partial, such that assert_redirected_to(controller: "weblog") will also - # match the redirection of redirect_to(controller: "weblog", action: "show") and so on. - # - # # Asserts that the redirection was to the "index" action on the WeblogController - # assert_redirected_to controller: "weblog", action: "index" - # - # # Asserts that the redirection was to the named route login_url - # assert_redirected_to login_url - # - # # Asserts that the redirection was to the url for @customer - # assert_redirected_to @customer - # - # # Asserts that the redirection matches the regular expression - # assert_redirected_to %r(\Ahttp://example.org) - def assert_redirected_to(options = {}, message = nil) - assert_response(:redirect, message) - return true if options === @response.location - - redirect_is = normalize_argument_to_redirection(@response.location) - redirect_expected = normalize_argument_to_redirection(options) - - message ||= "Expected response to be a redirect to <#{redirect_expected}> but was a redirect to <#{redirect_is}>" - assert_operator redirect_expected, :===, redirect_is, message - end - - private - # Proxy to to_param if the object will respond to it. - def parameterize(value) - value.respond_to?(:to_param) ? value.to_param : value - end - - def normalize_argument_to_redirection(fragment) - if Regexp === fragment - fragment - else - handle = @controller || ActionController::Redirecting - handle._compute_redirect_to_location(@request, fragment) - end - end - - def generate_response_message(expected, actual = @response.response_code) - "Expected response to be a <#{code_with_name(expected)}>,"\ - " but was a <#{code_with_name(actual)}>" - .concat(location_if_redirected).concat(response_body_if_short) - end - - def response_body_if_short - return "" if @response.body.size > 500 - "\nResponse body: #{@response.body}" - end - - def location_if_redirected - return "" unless @response.redirection? && @response.location.present? - location = normalize_argument_to_redirection(@response.location) - " redirect to <#{location}>" - end - - def code_with_name(code_or_name) - if RESPONSE_PREDICATES.values.include?("#{code_or_name}?".to_sym) - code_or_name = RESPONSE_PREDICATES.invert["#{code_or_name}?".to_sym] - end - - AssertionResponse.new(code_or_name).code_and_name - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions/routing.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions/routing.rb deleted file mode 100644 index 37c1ca02b6..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/assertions/routing.rb +++ /dev/null @@ -1,222 +0,0 @@ -require "uri" -require "active_support/core_ext/hash/indifferent_access" -require "active_support/core_ext/string/access" -require "action_controller/metal/exceptions" - -module ActionDispatch - module Assertions - # Suite of assertions to test routes generated by \Rails and the handling of requests made to them. - module RoutingAssertions - # Asserts that the routing of the given +path+ was handled correctly and that the parsed options (given in the +expected_options+ hash) - # match +path+. Basically, it asserts that \Rails recognizes the route given by +expected_options+. - # - # Pass a hash in the second argument (+path+) to specify the request method. This is useful for routes - # requiring a specific HTTP method. The hash should contain a :path with the incoming request path - # and a :method containing the required HTTP verb. - # - # # Asserts that POSTing to /items will call the create action on ItemsController - # assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post}) - # - # You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used - # to assert that values in the query string will end up in the params hash correctly. To test query strings you must use the - # extras argument, appending the query string on the path directly will not work. For example: - # - # # Asserts that a path of '/items/list/1?view=print' returns the correct options - # assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" }) - # - # The +message+ parameter allows you to pass in an error message that is displayed upon failure. - # - # # Check the default route (i.e., the index action) - # assert_recognizes({controller: 'items', action: 'index'}, 'items') - # - # # Test a specific action - # assert_recognizes({controller: 'items', action: 'list'}, 'items/list') - # - # # Test an action with a parameter - # assert_recognizes({controller: 'items', action: 'destroy', id: '1'}, 'items/destroy/1') - # - # # Test a custom route - # assert_recognizes({controller: 'items', action: 'show', id: '1'}, 'view/item1') - def assert_recognizes(expected_options, path, extras = {}, msg = nil) - if path.is_a?(Hash) && path[:method].to_s == "all" - [:get, :post, :put, :delete].each do |method| - assert_recognizes(expected_options, path.merge(method: method), extras, msg) - end - else - request = recognized_request_for(path, extras, msg) - - expected_options = expected_options.clone - - expected_options.stringify_keys! - - msg = message(msg, "") { - sprintf("The recognized options <%s> did not match <%s>, difference:", - request.path_parameters, expected_options) - } - - assert_equal(expected_options, request.path_parameters, msg) - end - end - - # Asserts that the provided options can be used to generate the provided path. This is the inverse of +assert_recognizes+. - # The +extras+ parameter is used to tell the request the names and values of additional request parameters that would be in - # a query string. The +message+ parameter allows you to specify a custom error message for assertion failures. - # - # The +defaults+ parameter is unused. - # - # # Asserts that the default action is generated for a route with no action - # assert_generates "/items", controller: "items", action: "index" - # - # # Tests that the list action is properly routed - # assert_generates "/items/list", controller: "items", action: "list" - # - # # Tests the generation of a route with a parameter - # assert_generates "/items/list/1", { controller: "items", action: "list", id: "1" } - # - # # Asserts that the generated route gives us our custom route - # assert_generates "changesets/12", { controller: 'scm', action: 'show_diff', revision: "12" } - def assert_generates(expected_path, options, defaults = {}, extras = {}, message = nil) - if expected_path =~ %r{://} - fail_on(URI::InvalidURIError, message) do - uri = URI.parse(expected_path) - expected_path = uri.path.to_s.empty? ? "/" : uri.path - end - else - expected_path = "/#{expected_path}" unless expected_path.first == "/" - end - # Load routes.rb if it hasn't been loaded. - - options = options.clone - generated_path, query_string_keys = @routes.generate_extras(options, defaults) - found_extras = options.reject { |k, _| ! query_string_keys.include? k } - - msg = message || sprintf("found extras <%s>, not <%s>", found_extras, extras) - assert_equal(extras, found_extras, msg) - - msg = message || sprintf("The generated path <%s> did not match <%s>", generated_path, - expected_path) - assert_equal(expected_path, generated_path, msg) - end - - # Asserts that path and options match both ways; in other words, it verifies that path generates - # options and then that options generates path. This essentially combines +assert_recognizes+ - # and +assert_generates+ into one step. - # - # The +extras+ hash allows you to specify options that would normally be provided as a query string to the action. The - # +message+ parameter allows you to specify a custom error message to display upon failure. - # - # # Asserts a basic route: a controller with the default action (index) - # assert_routing '/home', controller: 'home', action: 'index' - # - # # Test a route generated with a specific controller, action, and parameter (id) - # assert_routing '/entries/show/23', controller: 'entries', action: 'show', id: 23 - # - # # Asserts a basic route (controller + default action), with an error message if it fails - # assert_routing '/store', { controller: 'store', action: 'index' }, {}, {}, 'Route for store index not generated properly' - # - # # Tests a route, providing a defaults hash - # assert_routing 'controller/action/9', {id: "9", item: "square"}, {controller: "controller", action: "action"}, {}, {item: "square"} - # - # # Tests a route with an HTTP method - # assert_routing({ method: 'put', path: '/product/321' }, { controller: "product", action: "update", id: "321" }) - def assert_routing(path, options, defaults = {}, extras = {}, message = nil) - assert_recognizes(options, path, extras, message) - - controller, default_controller = options[:controller], defaults[:controller] - if controller && controller.include?(?/) && default_controller && default_controller.include?(?/) - options[:controller] = "/#{controller}" - end - - generate_options = options.dup.delete_if { |k, _| defaults.key?(k) } - assert_generates(path.is_a?(Hash) ? path[:path] : path, generate_options, defaults, extras, message) - end - - # A helper to make it easier to test different route configurations. - # This method temporarily replaces @routes - # with a new RouteSet instance. - # - # The new instance is yielded to the passed block. Typically the block - # will create some routes using set.draw { match ... }: - # - # with_routing do |set| - # set.draw do - # resources :users - # end - # assert_equal "/users", users_path - # end - # - def with_routing - old_routes, @routes = @routes, ActionDispatch::Routing::RouteSet.new - if defined?(@controller) && @controller - old_controller, @controller = @controller, @controller.clone - _routes = @routes - - @controller.singleton_class.include(_routes.url_helpers) - - if @controller.respond_to? :view_context_class - @controller.view_context_class = Class.new(@controller.view_context_class) do - include _routes.url_helpers - end - end - end - yield @routes - ensure - @routes = old_routes - if defined?(@controller) && @controller - @controller = old_controller - end - end - - # ROUTES TODO: These assertions should really work in an integration context - def method_missing(selector, *args, &block) - if defined?(@controller) && @controller && defined?(@routes) && @routes && @routes.named_routes.route_defined?(selector) - @controller.send(selector, *args, &block) - else - super - end - end - - private - # Recognizes the route for a given path. - def recognized_request_for(path, extras = {}, msg) - if path.is_a?(Hash) - method = path[:method] - path = path[:path] - else - method = :get - end - - # Assume given controller - request = ActionController::TestRequest.create @controller.class - - if path =~ %r{://} - fail_on(URI::InvalidURIError, msg) do - uri = URI.parse(path) - request.env["rack.url_scheme"] = uri.scheme || "http" - request.host = uri.host if uri.host - request.port = uri.port if uri.port - request.path = uri.path.to_s.empty? ? "/" : uri.path - end - else - path = "/#{path}" unless path.first == "/" - request.path = path - end - - request.request_method = method if method - - params = fail_on(ActionController::RoutingError, msg) do - @routes.recognize_path(path, method: method, extras: extras) - end - request.path_parameters = params.with_indifferent_access - - request - end - - def fail_on(exception_class, message) - yield - rescue exception_class => e - raise Minitest::Assertion, message || e.message - end - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/integration.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/integration.rb deleted file mode 100644 index 00ca50c535..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/integration.rb +++ /dev/null @@ -1,649 +0,0 @@ -require "stringio" -require "uri" -require "active_support/core_ext/kernel/singleton_class" -require "active_support/core_ext/object/try" -require "rack/test" -require "minitest" - -require "action_dispatch/testing/request_encoder" - -module ActionDispatch - module Integration #:nodoc: - module RequestHelpers - # Performs a GET request with the given parameters. See +#process+ for more - # details. - def get(path, **args) - process(:get, path, **args) - end - - # Performs a POST request with the given parameters. See +#process+ for more - # details. - def post(path, **args) - process(:post, path, **args) - end - - # Performs a PATCH request with the given parameters. See +#process+ for more - # details. - def patch(path, **args) - process(:patch, path, **args) - end - - # Performs a PUT request with the given parameters. See +#process+ for more - # details. - def put(path, **args) - process(:put, path, **args) - end - - # Performs a DELETE request with the given parameters. See +#process+ for - # more details. - def delete(path, **args) - process(:delete, path, **args) - end - - # Performs a HEAD request with the given parameters. See +#process+ for more - # details. - def head(path, *args) - process(:head, path, *args) - end - - # Follow a single redirect response. If the last response was not a - # redirect, an exception will be raised. Otherwise, the redirect is - # performed on the location header. - def follow_redirect! - raise "not a redirect! #{status} #{status_message}" unless redirect? - get(response.location) - status - end - end - - # An instance of this class represents a set of requests and responses - # performed sequentially by a test process. Because you can instantiate - # multiple sessions and run them side-by-side, you can also mimic (to some - # limited extent) multiple simultaneous users interacting with your system. - # - # Typically, you will instantiate a new session using - # IntegrationTest#open_session, rather than instantiating - # Integration::Session directly. - class Session - DEFAULT_HOST = "www.example.com" - - include Minitest::Assertions - include TestProcess, RequestHelpers, Assertions - - %w( status status_message headers body redirect? ).each do |method| - delegate method, to: :response, allow_nil: true - end - - %w( path ).each do |method| - delegate method, to: :request, allow_nil: true - end - - # The hostname used in the last request. - def host - @host || DEFAULT_HOST - end - attr_writer :host - - # The remote_addr used in the last request. - attr_accessor :remote_addr - - # The Accept header to send. - attr_accessor :accept - - # A map of the cookies returned by the last response, and which will be - # sent with the next request. - def cookies - _mock_session.cookie_jar - end - - # A reference to the controller instance used by the last request. - attr_reader :controller - - # A reference to the request instance used by the last request. - attr_reader :request - - # A reference to the response instance used by the last request. - attr_reader :response - - # A running counter of the number of requests processed. - attr_accessor :request_count - - include ActionDispatch::Routing::UrlFor - - # Create and initialize a new Session instance. - def initialize(app) - super() - @app = app - - reset! - end - - def url_options - @url_options ||= default_url_options.dup.tap do |url_options| - url_options.reverse_merge!(controller.url_options) if controller - - if @app.respond_to?(:routes) - url_options.reverse_merge!(@app.routes.default_url_options) - end - - url_options.reverse_merge!(host: host, protocol: https? ? "https" : "http") - end - end - - # Resets the instance. This can be used to reset the state information - # in an existing session instance, so it can be used from a clean-slate - # condition. - # - # session.reset! - def reset! - @https = false - @controller = @request = @response = nil - @_mock_session = nil - @request_count = 0 - @url_options = nil - - self.host = DEFAULT_HOST - self.remote_addr = "127.0.0.1" - self.accept = "text/xml,application/xml,application/xhtml+xml," \ - "text/html;q=0.9,text/plain;q=0.8,image/png," \ - "*/*;q=0.5" - - unless defined? @named_routes_configured - # the helpers are made protected by default--we make them public for - # easier access during testing and troubleshooting. - @named_routes_configured = true - end - end - - # Specify whether or not the session should mimic a secure HTTPS request. - # - # session.https! - # session.https!(false) - def https!(flag = true) - @https = flag - end - - # Returns +true+ if the session is mimicking a secure HTTPS request. - # - # if session.https? - # ... - # end - def https? - @https - end - - # Performs the actual request. - # - # - +method+: The HTTP method (GET, POST, PATCH, PUT, DELETE, HEAD, OPTIONS) - # as a symbol. - # - +path+: The URI (as a String) on which you want to perform the - # request. - # - +params+: The HTTP parameters that you want to pass. This may - # be +nil+, - # a Hash, or a String that is appropriately encoded - # (application/x-www-form-urlencoded or - # multipart/form-data). - # - +headers+: Additional headers to pass, as a Hash. The headers will be - # merged into the Rack env hash. - # - +env+: Additional env to pass, as a Hash. The headers will be - # merged into the Rack env hash. - # - # This method is rarely used directly. Use +#get+, +#post+, or other standard - # HTTP methods in integration tests. +#process+ is only required when using a - # request method that doesn't have a method defined in the integration tests. - # - # This method returns the response status, after performing the request. - # Furthermore, if this method was called from an ActionDispatch::IntegrationTest object, - # then that object's @response instance variable will point to a Response object - # which one can use to inspect the details of the response. - # - # Example: - # process :get, '/author', params: { since: 201501011400 } - def process(method, path, params: nil, headers: nil, env: nil, xhr: false, as: nil) - request_encoder = RequestEncoder.encoder(as) - headers ||= {} - - if method == :get && as == :json && params - headers["X-Http-Method-Override"] = "GET" - method = :post - end - - if path =~ %r{://} - path = build_expanded_path(path) do |location| - https! URI::HTTPS === location if location.scheme - - if url_host = location.host - default = Rack::Request::DEFAULT_PORTS[location.scheme] - url_host += ":#{location.port}" if default != location.port - host! url_host - end - end - end - - hostname, port = host.split(":") - - request_env = { - :method => method, - :params => request_encoder.encode_params(params), - - "SERVER_NAME" => hostname, - "SERVER_PORT" => port || (https? ? "443" : "80"), - "HTTPS" => https? ? "on" : "off", - "rack.url_scheme" => https? ? "https" : "http", - - "REQUEST_URI" => path, - "HTTP_HOST" => host, - "REMOTE_ADDR" => remote_addr, - "CONTENT_TYPE" => request_encoder.content_type, - "HTTP_ACCEPT" => request_encoder.accept_header || accept - } - - wrapped_headers = Http::Headers.from_hash({}) - wrapped_headers.merge!(headers) if headers - - if xhr - wrapped_headers["HTTP_X_REQUESTED_WITH"] = "XMLHttpRequest" - wrapped_headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ") - end - - # this modifies the passed request_env directly - if wrapped_headers.present? - Http::Headers.from_hash(request_env).merge!(wrapped_headers) - end - if env.present? - Http::Headers.from_hash(request_env).merge!(env) - end - - session = Rack::Test::Session.new(_mock_session) - - # NOTE: rack-test v0.5 doesn't build a default uri correctly - # Make sure requested path is always a full uri - session.request(build_full_uri(path, request_env), request_env) - - @request_count += 1 - @request = ActionDispatch::Request.new(session.last_request.env) - response = _mock_session.last_response - @response = ActionDispatch::TestResponse.from_response(response) - @response.request = @request - @html_document = nil - @url_options = nil - - @controller = @request.controller_instance - - response.status - end - - # Set the host name to use in the next request. - # - # session.host! "www.example.com" - alias :host! :host= - - private - def _mock_session - @_mock_session ||= Rack::MockSession.new(@app, host) - end - - def build_full_uri(path, env) - "#{env['rack.url_scheme']}://#{env['SERVER_NAME']}:#{env['SERVER_PORT']}#{path}" - end - - def build_expanded_path(path) - location = URI.parse(path) - yield location if block_given? - path = location.path - location.query ? "#{path}?#{location.query}" : path - end - end - - module Runner - include ActionDispatch::Assertions - - APP_SESSIONS = {} - - attr_reader :app - - def initialize(*args, &blk) - super(*args, &blk) - @integration_session = nil - end - - def before_setup # :nodoc: - @app = nil - super - end - - def integration_session - @integration_session ||= create_session(app) - end - - # Reset the current session. This is useful for testing multiple sessions - # in a single test case. - def reset! - @integration_session = create_session(app) - end - - def create_session(app) - klass = APP_SESSIONS[app] ||= Class.new(Integration::Session) { - # If the app is a Rails app, make url_helpers available on the session - # This makes app.url_for and app.foo_path available in the console - if app.respond_to?(:routes) - include app.routes.url_helpers - include app.routes.mounted_helpers - end - } - klass.new(app) - end - - def remove! # :nodoc: - @integration_session = nil - end - - %w(get post patch put head delete cookies assigns follow_redirect!).each do |method| - define_method(method) do |*args| - # reset the html_document variable, except for cookies/assigns calls - unless method == "cookies" || method == "assigns" - @html_document = nil - end - - integration_session.__send__(method, *args).tap do - copy_session_variables! - end - end - end - - # Open a new session instance. If a block is given, the new session is - # yielded to the block before being returned. - # - # session = open_session do |sess| - # sess.extend(CustomAssertions) - # end - # - # By default, a single session is automatically created for you, but you - # can use this method to open multiple sessions that ought to be tested - # simultaneously. - def open_session - dup.tap do |session| - session.reset! - yield session if block_given? - end - end - - # Copy the instance variables from the current session instance into the - # test instance. - def copy_session_variables! #:nodoc: - @controller = @integration_session.controller - @response = @integration_session.response - @request = @integration_session.request - end - - def default_url_options - integration_session.default_url_options - end - - def default_url_options=(options) - integration_session.default_url_options = options - end - - def respond_to_missing?(method, include_private = false) - integration_session.respond_to?(method, include_private) || super - end - - # Delegate unhandled messages to the current session instance. - def method_missing(sym, *args, &block) - if integration_session.respond_to?(sym) - integration_session.__send__(sym, *args, &block).tap do - copy_session_variables! - end - else - super - end - end - end - end - - # An integration test spans multiple controllers and actions, - # tying them all together to ensure they work together as expected. It tests - # more completely than either unit or functional tests do, exercising the - # entire stack, from the dispatcher to the database. - # - # At its simplest, you simply extend IntegrationTest and write your tests - # using the get/post methods: - # - # require "test_helper" - # - # class ExampleTest < ActionDispatch::IntegrationTest - # fixtures :people - # - # def test_login - # # get the login page - # get "/login" - # assert_equal 200, status - # - # # post the login and follow through to the home page - # post "/login", params: { username: people(:jamis).username, - # password: people(:jamis).password } - # follow_redirect! - # assert_equal 200, status - # assert_equal "/home", path - # end - # end - # - # However, you can also have multiple session instances open per test, and - # even extend those instances with assertions and methods to create a very - # powerful testing DSL that is specific for your application. You can even - # reference any named routes you happen to have defined. - # - # require "test_helper" - # - # class AdvancedTest < ActionDispatch::IntegrationTest - # fixtures :people, :rooms - # - # def test_login_and_speak - # jamis, david = login(:jamis), login(:david) - # room = rooms(:office) - # - # jamis.enter(room) - # jamis.speak(room, "anybody home?") - # - # david.enter(room) - # david.speak(room, "hello!") - # end - # - # private - # - # module CustomAssertions - # def enter(room) - # # reference a named route, for maximum internal consistency! - # get(room_url(id: room.id)) - # assert(...) - # ... - # end - # - # def speak(room, message) - # post "/say/#{room.id}", xhr: true, params: { message: message } - # assert(...) - # ... - # end - # end - # - # def login(who) - # open_session do |sess| - # sess.extend(CustomAssertions) - # who = people(who) - # sess.post "/login", params: { username: who.username, - # password: who.password } - # assert(...) - # end - # end - # end - # - # Another longer example would be: - # - # A simple integration test that exercises multiple controllers: - # - # require 'test_helper' - # - # class UserFlowsTest < ActionDispatch::IntegrationTest - # test "login and browse site" do - # # login via https - # https! - # get "/login" - # assert_response :success - # - # post "/login", params: { username: users(:david).username, password: users(:david).password } - # follow_redirect! - # assert_equal '/welcome', path - # assert_equal 'Welcome david!', flash[:notice] - # - # https!(false) - # get "/articles/all" - # assert_response :success - # assert_select 'h1', 'Articles' - # end - # end - # - # As you can see the integration test involves multiple controllers and - # exercises the entire stack from database to dispatcher. In addition you can - # have multiple session instances open simultaneously in a test and extend - # those instances with assertion methods to create a very powerful testing - # DSL (domain-specific language) just for your application. - # - # Here's an example of multiple sessions and custom DSL in an integration test - # - # require 'test_helper' - # - # class UserFlowsTest < ActionDispatch::IntegrationTest - # test "login and browse site" do - # # User david logs in - # david = login(:david) - # # User guest logs in - # guest = login(:guest) - # - # # Both are now available in different sessions - # assert_equal 'Welcome david!', david.flash[:notice] - # assert_equal 'Welcome guest!', guest.flash[:notice] - # - # # User david can browse site - # david.browses_site - # # User guest can browse site as well - # guest.browses_site - # - # # Continue with other assertions - # end - # - # private - # - # module CustomDsl - # def browses_site - # get "/products/all" - # assert_response :success - # assert_select 'h1', 'Products' - # end - # end - # - # def login(user) - # open_session do |sess| - # sess.extend(CustomDsl) - # u = users(user) - # sess.https! - # sess.post "/login", params: { username: u.username, password: u.password } - # assert_equal '/welcome', sess.path - # sess.https!(false) - # end - # end - # end - # - # See the {request helpers documentation}[rdoc-ref:ActionDispatch::Integration::RequestHelpers] for help on how to - # use +get+, etc. - # - # === Changing the request encoding - # - # You can also test your JSON API easily by setting what the request should - # be encoded as: - # - # require "test_helper" - # - # class ApiTest < ActionDispatch::IntegrationTest - # test "creates articles" do - # assert_difference -> { Article.count } do - # post articles_path, params: { article: { title: "Ahoy!" } }, as: :json - # end - # - # assert_response :success - # assert_equal({ id: Article.last.id, title: "Ahoy!" }, response.parsed_body) - # end - # end - # - # The +as+ option passes an "application/json" Accept header (thereby setting - # the request format to JSON unless overridden), sets the content type to - # "application/json" and encodes the parameters as JSON. - # - # Calling +parsed_body+ on the response parses the response body based on the - # last response MIME type. - # - # Out of the box, only :json is supported. But for any custom MIME - # types you've registered, you can add your own encoders with: - # - # ActionDispatch::IntegrationTest.register_encoder :wibble, - # param_encoder: -> params { params.to_wibble }, - # response_parser: -> body { body } - # - # Where +param_encoder+ defines how the params should be encoded and - # +response_parser+ defines how the response body should be parsed through - # +parsed_body+. - # - # Consult the Rails Testing Guide for more. - - class IntegrationTest < ActiveSupport::TestCase - include TestProcess::FixtureFile - - module UrlOptions - extend ActiveSupport::Concern - def url_options - integration_session.url_options - end - end - - module Behavior - extend ActiveSupport::Concern - - include Integration::Runner - include ActionController::TemplateAssertions - - included do - include ActionDispatch::Routing::UrlFor - include UrlOptions # don't let UrlFor override the url_options method - ActiveSupport.run_load_hooks(:action_dispatch_integration_test, self) - @@app = nil - end - - module ClassMethods - def app - if defined?(@@app) && @@app - @@app - else - ActionDispatch.test_app - end - end - - def app=(app) - @@app = app - end - - def register_encoder(*args) - RequestEncoder.register_encoder(*args) - end - end - - def app - super || self.class.app - end - - def document_root_element - html_document.root - end - end - - include Behavior - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/request_encoder.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/request_encoder.rb deleted file mode 100644 index 8c27e9ecb7..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/request_encoder.rb +++ /dev/null @@ -1,53 +0,0 @@ -module ActionDispatch - class RequestEncoder # :nodoc: - class IdentityEncoder - def content_type; end - def accept_header; end - def encode_params(params); params; end - def response_parser; -> body { body }; end - end - - @encoders = { identity: IdentityEncoder.new } - - attr_reader :response_parser - - def initialize(mime_name, param_encoder, response_parser) - @mime = Mime[mime_name] - - unless @mime - raise ArgumentError, "Can't register a request encoder for " \ - "unregistered MIME Type: #{mime_name}. See `Mime::Type.register`." - end - - @response_parser = response_parser || -> body { body } - @param_encoder = param_encoder || :"to_#{@mime.symbol}".to_proc - end - - def content_type - @mime.to_s - end - - def accept_header - @mime.to_s - end - - def encode_params(params) - @param_encoder.call(params) - end - - def self.parser(content_type) - mime = Mime::Type.lookup(content_type) - encoder(mime ? mime.ref : nil).response_parser - end - - def self.encoder(name) - @encoders[name] || @encoders[:identity] - end - - def self.register_encoder(mime_name, param_encoder: nil, response_parser: nil) - @encoders[mime_name] = new(mime_name, param_encoder, response_parser) - end - - register_encoder :json, response_parser: -> body { JSON.parse(body) } - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_process.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_process.rb deleted file mode 100644 index 0282eb15c3..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_process.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "action_dispatch/middleware/cookies" -require "action_dispatch/middleware/flash" - -module ActionDispatch - module TestProcess - module FixtureFile - # Shortcut for Rack::Test::UploadedFile.new(File.join(ActionDispatch::IntegrationTest.fixture_path, path), type): - # - # post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png') - # - # To upload binary files on Windows, pass :binary as the last parameter. - # This will not affect other platforms: - # - # post :change_avatar, avatar: fixture_file_upload('files/spongebob.png', 'image/png', :binary) - def fixture_file_upload(path, mime_type = nil, binary = false) - if self.class.respond_to?(:fixture_path) && self.class.fixture_path && - !File.exist?(path) - path = File.join(self.class.fixture_path, path) - end - Rack::Test::UploadedFile.new(path, mime_type, binary) - end - end - - include FixtureFile - - def assigns(key = nil) - raise NoMethodError, - "assigns has been extracted to a gem. To continue using it, - add `gem 'rails-controller-testing'` to your Gemfile." - end - - def session - @request.session - end - - def flash - @request.flash - end - - def cookies - @cookie_jar ||= Cookies::CookieJar.build(@request, @request.cookies) - end - - def redirect_to_url - @response.redirect_url - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_request.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_request.rb deleted file mode 100644 index 91b25ec155..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_request.rb +++ /dev/null @@ -1,69 +0,0 @@ -require "active_support/core_ext/hash/indifferent_access" -require "rack/utils" - -module ActionDispatch - class TestRequest < Request - DEFAULT_ENV = Rack::MockRequest.env_for("/", - "HTTP_HOST" => "test.host", - "REMOTE_ADDR" => "0.0.0.0", - "HTTP_USER_AGENT" => "Rails Testing", - ) - - # Create a new test request with default `env` values - def self.create(env = {}) - env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application - env["rack.request.cookie_hash"] ||= {}.with_indifferent_access - new(default_env.merge(env)) - end - - def self.default_env - DEFAULT_ENV - end - private_class_method :default_env - - def request_method=(method) - super(method.to_s.upcase) - end - - def host=(host) - set_header("HTTP_HOST", host) - end - - def port=(number) - set_header("SERVER_PORT", number.to_i) - end - - def request_uri=(uri) - set_header("REQUEST_URI", uri) - end - - def path=(path) - set_header("PATH_INFO", path) - end - - def action=(action_name) - path_parameters[:action] = action_name.to_s - end - - def if_modified_since=(last_modified) - set_header("HTTP_IF_MODIFIED_SINCE", last_modified) - end - - def if_none_match=(etag) - set_header("HTTP_IF_NONE_MATCH", etag) - end - - def remote_addr=(addr) - set_header("REMOTE_ADDR", addr) - end - - def user_agent=(user_agent) - set_header("HTTP_USER_AGENT", user_agent) - end - - def accept=(mime_types) - delete_header("action_dispatch.request.accepts") - set_header("HTTP_ACCEPT", Array(mime_types).collect(&:to_s).join(",")) - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_response.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_response.rb deleted file mode 100644 index 5c89f9c75e..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_dispatch/testing/test_response.rb +++ /dev/null @@ -1,33 +0,0 @@ -require "action_dispatch/testing/request_encoder" - -module ActionDispatch - # Integration test methods such as ActionDispatch::Integration::Session#get - # and ActionDispatch::Integration::Session#post return objects of class - # TestResponse, which represent the HTTP response results of the requested - # controller actions. - # - # See Response for more information on controller response objects. - class TestResponse < Response - def self.from_response(response) - new response.status, response.headers, response.body - end - - def initialize(*) # :nodoc: - super - @response_parser = RequestEncoder.parser(content_type) - end - - # Was the response successful? - alias_method :success?, :successful? - - # Was the URL not found? - alias_method :missing?, :not_found? - - # Was there a server-side error? - alias_method :error?, :server_error? - - def parsed_body - @parsed_body ||= @response_parser.call(body) - end - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_pack.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_pack.rb deleted file mode 100644 index eec622e085..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_pack.rb +++ /dev/null @@ -1,24 +0,0 @@ -#-- -# Copyright (c) 2004-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "action_pack/version" diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_pack/gem_version.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_pack/gem_version.rb deleted file mode 100644 index 11747e9c02..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_pack/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActionPack - # Returns the version of the currently loaded Action Pack as a Gem::Version - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/actionpack-5.1.7/lib/action_pack/version.rb b/debian/gems-compat/actionpack-5.1.7/lib/action_pack/version.rb deleted file mode 100644 index 3d96158431..0000000000 --- a/debian/gems-compat/actionpack-5.1.7/lib/action_pack/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module ActionPack - # Returns the version of the currently loaded ActionPack as a Gem::Version - def self.version - gem_version - end -end diff --git a/debian/gems-compat/actionview-5.1.7/CHANGELOG.md b/debian/gems-compat/actionview-5.1.7/CHANGELOG.md deleted file mode 100644 index 82d08ce57b..0000000000 --- a/debian/gems-compat/actionview-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,306 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* Fix issue with `button_to`'s `to_form_params` - - `button_to` was throwing exception when invoked with `params` hash that - contains symbol and string keys. The reason for the exception was that - `to_form_params` was comparing the given symbol and string keys. - - The issue is fixed by turning all keys to strings inside - `to_form_params` before comparing them. - - *Georgi Georgiev* - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* No changes. - - -## Rails 5.1.5 (February 14, 2018) ## - -* No changes. - - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* No changes. - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* No changes. - - -## Rails 5.1.2 (June 26, 2017) ## - -* Fix issues with scopes and engine on `current_page?` method. - - Fixes #29401. - - *Nikita Savrov* - -* Generate field ids in `collection_check_boxes` and `collection_radio_buttons`. - - This makes sure that the labels are linked up with the fields. - - Fixes #29014. - - *Yuji Yaginuma* - -* Update distance_of_time_in_words helper to display better error messages - for bad input. - - *Jay Hayes* - - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* Remove the option `encode_special_chars` misnomer from `strip_tags` - - As of rails-html-sanitizer v1.0.3, the sanitizer will ignore the - `encode_special_chars` option. - - Fixes #28060. - - *Andrew Hood* - -* Change the ERB handler from Erubis to Erubi. - - Erubi is an Erubis fork that's svelte, simple, and currently maintained. - Plus it supports `--enable-frozen-string-literal` in Ruby 2.3+. - - Compatibility: Drops support for `<%===` tags for debug output. - These were an unused, undocumented side effect of the Erubis - implementation. - - Deprecation: The Erubis handler will be removed in Rails 5.2, for the - handful of folks using it directly. - - *Jeremy Evans* - -* Allow render locals to be assigned to instance variables in a view. - - Fixes #27480. - - *Andrew White* - -* Add `check_parameters` option to `current_page?` which makes it more strict. - - *Maksym Pugach* - -* Return correct object name in form helper method after `fields_for`. - - Fixes #26931. - - *Yuji Yaginuma* - -* Use `ActionView::Resolver.caching?` (`config.action_view.cache_template_loading`) - to enable template recompilation. - - Before it was enabled by `consider_all_requests_local`, which caused - recompilation in tests. - - *Max Melentiev* - -* Add `form_with` to unify `form_tag` and `form_for` usage. - - Used like `form_tag` (where just the open tag is output): - - ```erb - <%= form_with scope: :post, url: super_special_posts_path %> - ``` - - Used like `form_for`: - - ```erb - <%= form_with model: @post do |form| %> - <%= form.text_field :title %> - <% end %> - ``` - - *Kasper Timm Hansen*, *Marek Kirejczyk* - -* Add `fields` form helper method. - - ```erb - <%= fields :comment, model: @comment do |fields| %> - <%= fields.text_field :title %> - <% end %> - ``` - - Can also be used within form helpers such as `form_with`. - - *Kasper Timm Hansen* - -* Removed deprecated `#original_exception` in `ActionView::Template::Error`. - - *Rafael Mendonça França* - -* Render now accepts any keys for locals, including reserved keywords. - - Only locals with valid variable names get set directly. Others - will still be available in `local_assigns`. - - Example of render with reserved keywords: - - ```erb - <%= render "example", class: "text-center", message: "Hello world!" %> - - - <%= tag.div class: local_assigns[:class] do %> -

<%= message %>

- <% end %> - ``` - - *Peter Schilling*, *Matthew Draper* - -* Add `:skip_pipeline` option to several asset tag helpers - - `javascript_include_tag`, `stylesheet_link_tag`, `favicon_link_tag`, - `image_tag` and `audio_tag` now accept a `:skip_pipeline` option which can - be set to true to bypass the asset pipeline and serve the assets from the - public folder. - - *Richard Schneeman* - -* Add `:poster_skip_pipeline` option to the `video_tag` helper - - `video_tag` now accepts a `:poster_skip_pipeline` option which can be used - in combination with the `:poster` option to bypass the asset pipeline and - serve the poster image for the video from the public folder. - - *Richard Schneeman* - -* Show cache hits and misses when rendering partials. - - Partials using the `cache` helper will show whether a render hit or missed - the cache: - - ``` - Rendered messages/_message.html.erb in 1.2 ms [cache hit] - Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] - ``` - - This removes the need for the old fragment cache logging: - - ``` - Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms) - Rendered messages/_message.html.erb in 1.2 ms [cache hit] - Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms) - Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss] - ``` - - Though that full output can be reenabled with - `config.action_controller.enable_fragment_cache_logging = true`. - - *Stan Lo* - -* Changed partial rendering with a collection to allow collections which - implement `to_a`. - - Extracting the collection option had an optimization to avoid unnecessary - queries of ActiveRecord Relations by calling `#to_ary` on the given - collection. Instances of `Enumerator` or `Enumerable` are valid - collections, but they do not implement `#to_ary`. By changing this to - `#to_a`, they will now be extracted and rendered as expected. - - *Steven Harman* - -* New syntax for tag helpers. Avoid positional parameters and support HTML5 by default. - Example usage of tag helpers before: - - ```ruby - tag(:br, nil, true) - content_tag(:div, content_tag(:p, "Hello world!"), class: "strong") - - <%= content_tag :div, class: "strong" do -%> - Hello world! - <% end -%> - ``` - - Example usage of tag helpers after: - - ```ruby - tag.br - tag.div tag.p("Hello world!"), class: "strong" - - <%= tag.div class: "strong" do %> - Hello world! - <% end %> - ``` - - *Marek Kirejczyk*, *Kasper Timm Hansen* - -* Change `datetime_field` and `datetime_field_tag` to generate `datetime-local` fields. - - As a new specification of the HTML 5 the text field type `datetime` will no longer exist - and it is recommended to use `datetime-local`. - Ref: https://html.spec.whatwg.org/multipage/forms.html#local-date-and-time-state-(type=datetime-local) - - *Herminio Torres* - -* Raw template handler (which is also the default template handler in Rails 5) now outputs - HTML-safe strings. - - In Rails 5 the default template handler was changed to the raw template handler. Because - the ERB template handler escaped strings by default this broke some applications that - expected plain JS or HTML files to be rendered unescaped. This fixes the issue caused - by changing the default handler by changing the Raw template handler to output HTML-safe - strings. - - *Eileen M. Uchitelle* - -* `select_tag`'s `include_blank` option for generation for blank option tag, now adds an empty space label, - when the value as well as content for option tag are empty, so that we conform with html specification. - Ref: https://www.w3.org/TR/html5/forms.html#the-option-element. - - Generation of option before: - - ```html - - ``` - - Generation of option after: - - ```html - - ``` - - *Vipul A M* - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actionview/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/actionview-5.1.7/MIT-LICENSE b/debian/gems-compat/actionview-5.1.7/MIT-LICENSE deleted file mode 100644 index ac810e86d0..0000000000 --- a/debian/gems-compat/actionview-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2004-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/debian/gems-compat/actionview-5.1.7/README.rdoc b/debian/gems-compat/actionview-5.1.7/README.rdoc deleted file mode 100644 index 7a3e5e31d0..0000000000 --- a/debian/gems-compat/actionview-5.1.7/README.rdoc +++ /dev/null @@ -1,38 +0,0 @@ -= Action View - -Action View is a framework for handling view template lookup and rendering, and provides -view helpers that assist when building HTML forms, Atom feeds and more. -Template formats that Action View handles are ERB (embedded Ruby, typically -used to inline short Ruby snippets inside HTML), and XML Builder. - -== Download and installation - -The latest version of Action View can be installed with RubyGems: - - $ gem install actionview - -Source code can be downloaded as part of the Rails project on GitHub - -* https://github.com/rails/rails/tree/master/actionview - - -== License - -Action View is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -== Support - -API documentation is at - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/actionview-5.1.7/actionview.gemspec b/debian/gems-compat/actionview-5.1.7/actionview.gemspec deleted file mode 100644 index 7e1fe030d9..0000000000 --- a/debian/gems-compat/actionview-5.1.7/actionview.gemspec +++ /dev/null @@ -1,55 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: actionview 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "actionview".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/actionview/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/actionview" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "Simple, battle-tested conventions and helpers for building web pages.".freeze - s.email = "david@loudthinking.com".freeze - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.rdoc".freeze, "lib/action_view.rb".freeze, "lib/action_view/base.rb".freeze, "lib/action_view/buffers.rb".freeze, "lib/action_view/context.rb".freeze, "lib/action_view/dependency_tracker.rb".freeze, "lib/action_view/digestor.rb".freeze, "lib/action_view/flows.rb".freeze, "lib/action_view/gem_version.rb".freeze, "lib/action_view/helpers.rb".freeze, "lib/action_view/helpers/active_model_helper.rb".freeze, "lib/action_view/helpers/asset_tag_helper.rb".freeze, "lib/action_view/helpers/asset_url_helper.rb".freeze, "lib/action_view/helpers/atom_feed_helper.rb".freeze, "lib/action_view/helpers/cache_helper.rb".freeze, "lib/action_view/helpers/capture_helper.rb".freeze, "lib/action_view/helpers/controller_helper.rb".freeze, "lib/action_view/helpers/csrf_helper.rb".freeze, "lib/action_view/helpers/date_helper.rb".freeze, "lib/action_view/helpers/debug_helper.rb".freeze, "lib/action_view/helpers/form_helper.rb".freeze, "lib/action_view/helpers/form_options_helper.rb".freeze, "lib/action_view/helpers/form_tag_helper.rb".freeze, "lib/action_view/helpers/javascript_helper.rb".freeze, "lib/action_view/helpers/number_helper.rb".freeze, "lib/action_view/helpers/output_safety_helper.rb".freeze, "lib/action_view/helpers/record_tag_helper.rb".freeze, "lib/action_view/helpers/rendering_helper.rb".freeze, "lib/action_view/helpers/sanitize_helper.rb".freeze, "lib/action_view/helpers/tag_helper.rb".freeze, "lib/action_view/helpers/tags.rb".freeze, "lib/action_view/helpers/tags/base.rb".freeze, "lib/action_view/helpers/tags/check_box.rb".freeze, "lib/action_view/helpers/tags/checkable.rb".freeze, "lib/action_view/helpers/tags/collection_check_boxes.rb".freeze, "lib/action_view/helpers/tags/collection_helpers.rb".freeze, "lib/action_view/helpers/tags/collection_radio_buttons.rb".freeze, "lib/action_view/helpers/tags/collection_select.rb".freeze, "lib/action_view/helpers/tags/color_field.rb".freeze, "lib/action_view/helpers/tags/date_field.rb".freeze, "lib/action_view/helpers/tags/date_select.rb".freeze, "lib/action_view/helpers/tags/datetime_field.rb".freeze, "lib/action_view/helpers/tags/datetime_local_field.rb".freeze, "lib/action_view/helpers/tags/datetime_select.rb".freeze, "lib/action_view/helpers/tags/email_field.rb".freeze, "lib/action_view/helpers/tags/file_field.rb".freeze, "lib/action_view/helpers/tags/grouped_collection_select.rb".freeze, "lib/action_view/helpers/tags/hidden_field.rb".freeze, "lib/action_view/helpers/tags/label.rb".freeze, "lib/action_view/helpers/tags/month_field.rb".freeze, "lib/action_view/helpers/tags/number_field.rb".freeze, "lib/action_view/helpers/tags/password_field.rb".freeze, "lib/action_view/helpers/tags/placeholderable.rb".freeze, "lib/action_view/helpers/tags/radio_button.rb".freeze, "lib/action_view/helpers/tags/range_field.rb".freeze, "lib/action_view/helpers/tags/search_field.rb".freeze, "lib/action_view/helpers/tags/select.rb".freeze, "lib/action_view/helpers/tags/tel_field.rb".freeze, "lib/action_view/helpers/tags/text_area.rb".freeze, "lib/action_view/helpers/tags/text_field.rb".freeze, "lib/action_view/helpers/tags/time_field.rb".freeze, "lib/action_view/helpers/tags/time_select.rb".freeze, "lib/action_view/helpers/tags/time_zone_select.rb".freeze, "lib/action_view/helpers/tags/translator.rb".freeze, "lib/action_view/helpers/tags/url_field.rb".freeze, "lib/action_view/helpers/tags/week_field.rb".freeze, "lib/action_view/helpers/text_helper.rb".freeze, "lib/action_view/helpers/translation_helper.rb".freeze, "lib/action_view/helpers/url_helper.rb".freeze, "lib/action_view/layouts.rb".freeze, "lib/action_view/locale/en.yml".freeze, "lib/action_view/log_subscriber.rb".freeze, "lib/action_view/lookup_context.rb".freeze, "lib/action_view/model_naming.rb".freeze, "lib/action_view/path_set.rb".freeze, "lib/action_view/railtie.rb".freeze, "lib/action_view/record_identifier.rb".freeze, "lib/action_view/renderer/abstract_renderer.rb".freeze, "lib/action_view/renderer/partial_renderer.rb".freeze, "lib/action_view/renderer/partial_renderer/collection_caching.rb".freeze, "lib/action_view/renderer/renderer.rb".freeze, "lib/action_view/renderer/streaming_template_renderer.rb".freeze, "lib/action_view/renderer/template_renderer.rb".freeze, "lib/action_view/rendering.rb".freeze, "lib/action_view/routing_url_for.rb".freeze, "lib/action_view/tasks/cache_digests.rake".freeze, "lib/action_view/template.rb".freeze, "lib/action_view/template/error.rb".freeze, "lib/action_view/template/handlers.rb".freeze, "lib/action_view/template/handlers/builder.rb".freeze, "lib/action_view/template/handlers/erb.rb".freeze, "lib/action_view/template/handlers/erb/deprecated_erubis.rb".freeze, "lib/action_view/template/handlers/erb/erubi.rb".freeze, "lib/action_view/template/handlers/erb/erubis.rb".freeze, "lib/action_view/template/handlers/html.rb".freeze, "lib/action_view/template/handlers/raw.rb".freeze, "lib/action_view/template/html.rb".freeze, "lib/action_view/template/resolver.rb".freeze, "lib/action_view/template/text.rb".freeze, "lib/action_view/template/types.rb".freeze, "lib/action_view/test_case.rb".freeze, "lib/action_view/testing/resolvers.rb".freeze, "lib/action_view/version.rb".freeze, "lib/action_view/view_paths.rb".freeze, "lib/assets/compiled/rails-ujs.js".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.requirements = ["none".freeze] - s.rubygems_version = "2.7.6.2".freeze - s.summary = "Rendering framework putting the V in MVC (part of Rails).".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q.freeze, ["= 5.1.7"]) - s.add_development_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["~> 3.1"]) - s.add_runtime_dependency(%q.freeze, ["~> 1.4"]) - s.add_runtime_dependency(%q.freeze, ["~> 2.0"]) - s.add_runtime_dependency(%q.freeze, [">= 1.0.3", "~> 1.0"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 3.1"]) - s.add_dependency(%q.freeze, ["~> 1.4"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, [">= 1.0.3", "~> 1.0"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 3.1"]) - s.add_dependency(%q.freeze, ["~> 1.4"]) - s.add_dependency(%q.freeze, ["~> 2.0"]) - s.add_dependency(%q.freeze, [">= 1.0.3", "~> 1.0"]) - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view.rb deleted file mode 100644 index ca586f1d52..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view.rb +++ /dev/null @@ -1,96 +0,0 @@ -#-- -# Copyright (c) 2004-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "active_support" -require "active_support/rails" -require "action_view/version" - -module ActionView - extend ActiveSupport::Autoload - - ENCODING_FLAG = '#.*coding[:=]\s*(\S+)[ \t]*' - - eager_autoload do - autoload :Base - autoload :Context - autoload :CompiledTemplates, "action_view/context" - autoload :Digestor - autoload :Helpers - autoload :LookupContext - autoload :Layouts - autoload :PathSet - autoload :RecordIdentifier - autoload :Rendering - autoload :RoutingUrlFor - autoload :Template - autoload :ViewPaths - - autoload_under "renderer" do - autoload :Renderer - autoload :AbstractRenderer - autoload :PartialRenderer - autoload :TemplateRenderer - autoload :StreamingTemplateRenderer - end - - autoload_at "action_view/template/resolver" do - autoload :Resolver - autoload :PathResolver - autoload :OptimizedFileSystemResolver - autoload :FallbackFileSystemResolver - end - - autoload_at "action_view/buffers" do - autoload :OutputBuffer - autoload :StreamingBuffer - end - - autoload_at "action_view/flows" do - autoload :OutputFlow - autoload :StreamingFlow - end - - autoload_at "action_view/template/error" do - autoload :MissingTemplate - autoload :ActionViewError - autoload :EncodingError - autoload :MissingRequestError - autoload :TemplateError - autoload :WrongEncodingError - end - end - - autoload :TestCase - - def self.eager_load! - super - ActionView::Helpers.eager_load! - ActionView::Template.eager_load! - end -end - -require "active_support/core_ext/string/output_safety" - -ActiveSupport.on_load(:i18n) do - I18n.load_path << "#{File.dirname(__FILE__)}/action_view/locale/en.yml" -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/base.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/base.rb deleted file mode 100644 index 5387174467..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/base.rb +++ /dev/null @@ -1,217 +0,0 @@ -require "active_support/core_ext/module/attr_internal" -require "active_support/core_ext/module/attribute_accessors" -require "active_support/ordered_options" -require "action_view/log_subscriber" -require "action_view/helpers" -require "action_view/context" -require "action_view/template" -require "action_view/lookup_context" - -module ActionView #:nodoc: - # = Action View Base - # - # Action View templates can be written in several ways. - # If the template file has a .erb extension, then it uses the erubi[https://rubygems.org/gems/erubi] - # template system which can embed Ruby into an HTML document. - # If the template file has a .builder extension, then Jim Weirich's Builder::XmlMarkup library is used. - # - # == ERB - # - # You trigger ERB by using embeddings such as <% %>, <% -%>, and <%= %>. The <%= %> tag set is used when you want output. Consider the - # following loop for names: - # - # Names of all the people - # <% @people.each do |person| %> - # Name: <%= person.name %>
- # <% end %> - # - # The loop is setup in regular embedding tags <% %>, and the name is written using the output embedding tag <%= %>. Note that this - # is not just a usage suggestion. Regular output functions like print or puts won't work with ERB templates. So this would be wrong: - # - # <%# WRONG %> - # Hi, Mr. <% puts "Frodo" %> - # - # If you absolutely must write from within a function use +concat+. - # - # When on a line that only contains whitespaces except for the tag, <% %> suppresses leading and trailing whitespace, - # including the trailing newline. <% %> and <%- -%> are the same. - # Note however that <%= %> and <%= -%> are different: only the latter removes trailing whitespaces. - # - # === Using sub templates - # - # Using sub templates allows you to sidestep tedious replication and extract common display structures in shared templates. The - # classic example is the use of a header and footer (even though the Action Pack-way would be to use Layouts): - # - # <%= render "shared/header" %> - # Something really specific and terrific - # <%= render "shared/footer" %> - # - # As you see, we use the output embeddings for the render methods. The render call itself will just return a string holding the - # result of the rendering. The output embedding writes it to the current template. - # - # But you don't have to restrict yourself to static includes. Templates can share variables amongst themselves by using instance - # variables defined using the regular embedding tags. Like this: - # - # <% @page_title = "A Wonderful Hello" %> - # <%= render "shared/header" %> - # - # Now the header can pick up on the @page_title variable and use it for outputting a title tag: - # - # <%= @page_title %> - # - # === Passing local variables to sub templates - # - # You can pass local variables to sub templates by using a hash with the variable names as keys and the objects as values: - # - # <%= render "shared/header", { headline: "Welcome", person: person } %> - # - # These can now be accessed in shared/header with: - # - # Headline: <%= headline %> - # First name: <%= person.first_name %> - # - # The local variables passed to sub templates can be accessed as a hash using the local_assigns hash. This lets you access the - # variables as: - # - # Headline: <%= local_assigns[:headline] %> - # - # This is useful in cases where you aren't sure if the local variable has been assigned. Alternatively, you could also use - # defined? headline to first check if the variable has been assigned before using it. - # - # === Template caching - # - # By default, Rails will compile each template to a method in order to render it. When you alter a template, - # Rails will check the file's modification time and recompile it in development mode. - # - # == Builder - # - # Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object - # named +xml+ is automatically made available to templates with a .builder extension. - # - # Here are some basic examples: - # - # xml.em("emphasized") # => emphasized - # xml.em { xml.b("emph & bold") } # => emph & bold - # xml.a("A Link", "href" => "http://onestepback.org") # => A Link - # xml.target("name" => "compile", "option" => "fast") # => - # # NOTE: order of attributes is not specified. - # - # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following: - # - # xml.div do - # xml.h1(@person.name) - # xml.p(@person.bio) - # end - # - # would produce something like: - # - #
- #

David Heinemeier Hansson

- #

A product of Danish Design during the Winter of '79...

- #
- # - # Here is a full-length RSS example actually used on Basecamp: - # - # xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do - # xml.channel do - # xml.title(@feed_title) - # xml.link(@url) - # xml.description "Basecamp: Recent items" - # xml.language "en-us" - # xml.ttl "40" - # - # @recent_items.each do |item| - # xml.item do - # xml.title(item_title(item)) - # xml.description(item_description(item)) if item_description(item) - # xml.pubDate(item_pubDate(item)) - # xml.guid(@person.firm.account.url + @recent_items.url(item)) - # xml.link(@person.firm.account.url + @recent_items.url(item)) - # - # xml.tag!("dc:creator", item.author_name) if item_has_creator?(item) - # end - # end - # end - # end - # - # For more information on Builder please consult the {source - # code}[https://github.com/jimweirich/builder]. - class Base - include Helpers, ::ERB::Util, Context - - # Specify the proc used to decorate input tags that refer to attributes with errors. - cattr_accessor :field_error_proc - @@field_error_proc = Proc.new { |html_tag, instance| "
#{html_tag}
".html_safe } - - # How to complete the streaming when an exception occurs. - # This is our best guess: first try to close the attribute, then the tag. - cattr_accessor :streaming_completion_on_exception - @@streaming_completion_on_exception = %(">) - - # Specify whether rendering within namespaced controllers should prefix - # the partial paths for ActiveModel objects with the namespace. - # (e.g., an Admin::PostsController would render @post using /admin/posts/_post.erb) - cattr_accessor :prefix_partial_path_with_controller_namespace - @@prefix_partial_path_with_controller_namespace = true - - # Specify default_formats that can be rendered. - cattr_accessor :default_formats - - # Specify whether an error should be raised for missing translations - cattr_accessor :raise_on_missing_translations - @@raise_on_missing_translations = false - - # Specify whether submit_tag should automatically disable on click - cattr_accessor :automatically_disable_submit_tag - @@automatically_disable_submit_tag = true - - class_attribute :_routes - class_attribute :logger - - class << self - delegate :erb_trim_mode=, to: "ActionView::Template::Handlers::ERB" - - def cache_template_loading - ActionView::Resolver.caching? - end - - def cache_template_loading=(value) - ActionView::Resolver.caching = value - end - - def xss_safe? #:nodoc: - true - end - end - - attr_accessor :view_renderer - attr_internal :config, :assigns - - delegate :lookup_context, to: :view_renderer - delegate :formats, :formats=, :locale, :locale=, :view_paths, :view_paths=, to: :lookup_context - - def assign(new_assigns) # :nodoc: - @_assigns = new_assigns.each { |key, value| instance_variable_set("@#{key}", value) } - end - - def initialize(context = nil, assigns = {}, controller = nil, formats = nil) #:nodoc: - @_config = ActiveSupport::InheritableOptions.new - - if context.is_a?(ActionView::Renderer) - @view_renderer = context - else - lookup_context = context.is_a?(ActionView::LookupContext) ? - context : ActionView::LookupContext.new(context) - lookup_context.formats = formats if formats - lookup_context.prefixes = controller._prefixes if controller - @view_renderer = ActionView::Renderer.new(lookup_context) - end - - assign(assigns) - assign_controller(controller) - _prepare_context - end - - ActiveSupport.run_load_hooks(:action_view, self) - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/buffers.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/buffers.rb deleted file mode 100644 index 089daa6d60..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/buffers.rb +++ /dev/null @@ -1,50 +0,0 @@ -require "active_support/core_ext/string/output_safety" - -module ActionView - class OutputBuffer < ActiveSupport::SafeBuffer #:nodoc: - def initialize(*) - super - encode! - end - - def <<(value) - return self if value.nil? - super(value.to_s) - end - alias :append= :<< - - def safe_expr_append=(val) - return self if val.nil? - safe_concat val.to_s - end - - alias :safe_append= :safe_concat - end - - class StreamingBuffer #:nodoc: - def initialize(block) - @block = block - end - - def <<(value) - value = value.to_s - value = ERB::Util.h(value) unless value.html_safe? - @block.call(value) - end - alias :concat :<< - alias :append= :<< - - def safe_concat(value) - @block.call(value.to_s) - end - alias :safe_append= :safe_concat - - def html_safe? - true - end - - def html_safe - self - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/context.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/context.rb deleted file mode 100644 index 31aa73a0cf..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/context.rb +++ /dev/null @@ -1,36 +0,0 @@ -module ActionView - module CompiledTemplates #:nodoc: - # holds compiled template code - end - - # = Action View Context - # - # Action View contexts are supplied to Action Controller to render a template. - # The default Action View context is ActionView::Base. - # - # In order to work with ActionController, a Context must just include this module. - # The initialization of the variables used by the context (@output_buffer, @view_flow, - # and @virtual_path) is responsibility of the object that includes this module - # (although you can call _prepare_context defined below). - module Context - include CompiledTemplates - attr_accessor :output_buffer, :view_flow - - # Prepares the context by setting the appropriate instance variables. - # :api: plugin - def _prepare_context - @view_flow = OutputFlow.new - @output_buffer = nil - @virtual_path = nil - end - - # Encapsulates the interaction with the view flow so it - # returns the correct buffer on +yield+. This is usually - # overwritten by helpers to add more behavior. - # :api: plugin - def _layout_for(name = nil) - name ||= :layout - view_flow.get(name).html_safe - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/dependency_tracker.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/dependency_tracker.rb deleted file mode 100644 index 451eeec9d6..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/dependency_tracker.rb +++ /dev/null @@ -1,173 +0,0 @@ -require "concurrent/map" -require "action_view/path_set" - -module ActionView - class DependencyTracker # :nodoc: - @trackers = Concurrent::Map.new - - def self.find_dependencies(name, template, view_paths = nil) - tracker = @trackers[template.handler] - return [] unless tracker - - tracker.call(name, template, view_paths) - end - - def self.register_tracker(extension, tracker) - handler = Template.handler_for_extension(extension) - if tracker.respond_to?(:supports_view_paths?) - @trackers[handler] = tracker - else - @trackers[handler] = lambda { |name, template, _| - tracker.call(name, template) - } - end - end - - def self.remove_tracker(handler) - @trackers.delete(handler) - end - - class ERBTracker # :nodoc: - EXPLICIT_DEPENDENCY = /# Template Dependency: (\S+)/ - - # A valid ruby identifier - suitable for class, method and specially variable names - IDENTIFIER = / - [[:alpha:]_] # at least one uppercase letter, lowercase letter or underscore - [[:word:]]* # followed by optional letters, numbers or underscores - /x - - # Any kind of variable name. e.g. @instance, @@class, $global or local. - # Possibly following a method call chain - VARIABLE_OR_METHOD_CHAIN = / - (?:\$|@{1,2})? # optional global, instance or class variable indicator - (?:#{IDENTIFIER}\.)* # followed by an optional chain of zero-argument method calls - (?#{IDENTIFIER}) # and a final valid identifier, captured as DYNAMIC - /x - - # A simple string literal. e.g. "School's out!" - STRING = / - (?['"]) # an opening quote - (?.*?) # with anything inside, captured as STATIC - \k # and a matching closing quote - /x - - # Part of any hash containing the :partial key - PARTIAL_HASH_KEY = / - (?:\bpartial:|:partial\s*=>) # partial key in either old or new style hash syntax - \s* # followed by optional spaces - /x - - # Part of any hash containing the :layout key - LAYOUT_HASH_KEY = / - (?:\blayout:|:layout\s*=>) # layout key in either old or new style hash syntax - \s* # followed by optional spaces - /x - - # Matches: - # partial: "comments/comment", collection: @all_comments => "comments/comment" - # (object: @single_comment, partial: "comments/comment") => "comments/comment" - # - # "comments/comments" - # 'comments/comments' - # ('comments/comments') - # - # (@topic) => "topics/topic" - # topics => "topics/topic" - # (message.topics) => "topics/topic" - RENDER_ARGUMENTS = /\A - (?:\s*\(?\s*) # optional opening paren surrounded by spaces - (?:.*?#{PARTIAL_HASH_KEY}|#{LAYOUT_HASH_KEY})? # optional hash, up to the partial or layout key declaration - (?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest - /xm - - LAYOUT_DEPENDENCY = /\A - (?:\s*\(?\s*) # optional opening paren surrounded by spaces - (?:.*?#{LAYOUT_HASH_KEY}) # check if the line has layout key declaration - (?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest - /xm - - def self.supports_view_paths? # :nodoc: - true - end - - def self.call(name, template, view_paths = nil) - new(name, template, view_paths).dependencies - end - - def initialize(name, template, view_paths = nil) - @name, @template, @view_paths = name, template, view_paths - end - - def dependencies - render_dependencies + explicit_dependencies - end - - attr_reader :name, :template - private :name, :template - - private - def source - template.source - end - - def directory - name.split("/")[0..-2].join("/") - end - - def render_dependencies - render_dependencies = [] - render_calls = source.split(/\brender\b/).drop(1) - - render_calls.each do |arguments| - add_dependencies(render_dependencies, arguments, LAYOUT_DEPENDENCY) - add_dependencies(render_dependencies, arguments, RENDER_ARGUMENTS) - end - - render_dependencies.uniq - end - - def add_dependencies(render_dependencies, arguments, pattern) - arguments.scan(pattern) do - add_dynamic_dependency(render_dependencies, Regexp.last_match[:dynamic]) - add_static_dependency(render_dependencies, Regexp.last_match[:static]) - end - end - - def add_dynamic_dependency(dependencies, dependency) - if dependency - dependencies << "#{dependency.pluralize}/#{dependency.singularize}" - end - end - - def add_static_dependency(dependencies, dependency) - if dependency - if dependency.include?("/") - dependencies << dependency - else - dependencies << "#{directory}/#{dependency}" - end - end - end - - def resolve_directories(wildcard_dependencies) - return [] unless @view_paths - - wildcard_dependencies.flat_map { |query, templates| - @view_paths.find_all_with_query(query).map do |template| - "#{File.dirname(query)}/#{File.basename(template).split('.').first}" - end - }.sort - end - - def explicit_dependencies - dependencies = source.scan(EXPLICIT_DEPENDENCY).flatten.uniq - - wildcards, explicits = dependencies.partition { |dependency| dependency[-1] == "*" } - - (explicits + resolve_directories(wildcards)).uniq - end - end - - register_tracker :erb, ERBTracker - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/digestor.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/digestor.rb deleted file mode 100644 index aa0b0f4c9f..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/digestor.rb +++ /dev/null @@ -1,134 +0,0 @@ -require "concurrent/map" -require "action_view/dependency_tracker" -require "monitor" - -module ActionView - class Digestor - @@digest_mutex = Mutex.new - - module PerExecutionDigestCacheExpiry - def self.before(target) - ActionView::LookupContext::DetailsKey.clear - end - end - - class << self - # Supported options: - # - # * name - Template name - # * finder - An instance of ActionView::LookupContext - # * dependencies - An array of dependent views - def digest(name:, finder:, dependencies: []) - dependencies ||= [] - cache_key = [ name, finder.rendered_format, dependencies ].flatten.compact.join(".") - - # this is a correctly done double-checked locking idiom - # (Concurrent::Map's lookups have volatile semantics) - finder.digest_cache[cache_key] || @@digest_mutex.synchronize do - finder.digest_cache.fetch(cache_key) do # re-check under lock - partial = name.include?("/_") - root = tree(name, finder, partial) - dependencies.each do |injected_dep| - root.children << Injected.new(injected_dep, nil, nil) - end - finder.digest_cache[cache_key] = root.digest(finder) - end - end - end - - def logger - ActionView::Base.logger || NullLogger - end - - # Create a dependency tree for template named +name+. - def tree(name, finder, partial = false, seen = {}) - logical_name = name.gsub(%r|/_|, "/") - - if template = find_template(finder, logical_name, [], partial, []) - finder.rendered_format ||= template.formats.first - - if node = seen[template.identifier] # handle cycles in the tree - node - else - node = seen[template.identifier] = Node.create(name, logical_name, template, partial) - - deps = DependencyTracker.find_dependencies(name, template, finder.view_paths) - deps.uniq { |n| n.gsub(%r|/_|, "/") }.each do |dep_file| - node.children << tree(dep_file, finder, true, seen) - end - node - end - else - unless name.include?("#") # Dynamic template partial names can never be tracked - logger.error " Couldn't find template for digesting: #{name}" - end - - seen[name] ||= Missing.new(name, logical_name, nil) - end - end - - private - def find_template(finder, *args) - finder.disable_cache do - if format = finder.rendered_format - finder.find_all(*args, formats: [format]).first || finder.find_all(*args).first - else - finder.find_all(*args).first - end - end - end - end - - class Node - attr_reader :name, :logical_name, :template, :children - - def self.create(name, logical_name, template, partial) - klass = partial ? Partial : Node - klass.new(name, logical_name, template, []) - end - - def initialize(name, logical_name, template, children = []) - @name = name - @logical_name = logical_name - @template = template - @children = children - end - - def digest(finder, stack = []) - Digest::MD5.hexdigest("#{template.source}-#{dependency_digest(finder, stack)}") - end - - def dependency_digest(finder, stack) - children.map do |node| - if stack.include?(node) - false - else - finder.digest_cache[node.name] ||= begin - stack.push node - node.digest(finder, stack).tap { stack.pop } - end - end - end.join("-") - end - - def to_dep_map - children.any? ? { name => children.map(&:to_dep_map) } : name - end - end - - class Partial < Node; end - - class Missing < Node - def digest(finder, _ = []) "" end - end - - class Injected < Node - def digest(finder, _ = []) name end - end - - class NullLogger - def self.debug(_); end - def self.error(_); end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/flows.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/flows.rb deleted file mode 100644 index 6d5f57a570..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/flows.rb +++ /dev/null @@ -1,74 +0,0 @@ -require "active_support/core_ext/string/output_safety" - -module ActionView - class OutputFlow #:nodoc: - attr_reader :content - - def initialize - @content = Hash.new { |h, k| h[k] = ActiveSupport::SafeBuffer.new } - end - - # Called by _layout_for to read stored values. - def get(key) - @content[key] - end - - # Called by each renderer object to set the layout contents. - def set(key, value) - @content[key] = ActiveSupport::SafeBuffer.new(value) - end - - # Called by content_for - def append(key, value) - @content[key] << value - end - alias_method :append!, :append - end - - class StreamingFlow < OutputFlow #:nodoc: - def initialize(view, fiber) - @view = view - @parent = nil - @child = view.output_buffer - @content = view.view_flow.content - @fiber = fiber - @root = Fiber.current.object_id - end - - # Try to get stored content. If the content - # is not available and we're inside the layout fiber, - # then it will begin waiting for the given key and yield. - def get(key) - return super if @content.key?(key) - - if inside_fiber? - view = @view - - begin - @waiting_for = key - view.output_buffer, @parent = @child, view.output_buffer - Fiber.yield - ensure - @waiting_for = nil - view.output_buffer, @child = @parent, view.output_buffer - end - end - - super - end - - # Appends the contents for the given key. This is called - # by providing and resuming back to the fiber, - # if that's the key it's waiting for. - def append!(key, value) - super - @fiber.resume if @waiting_for == key - end - - private - - def inside_fiber? - Fiber.current.object_id != @root - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/gem_version.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/gem_version.rb deleted file mode 100644 index 26f7db9c49..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActionView - # Returns the version of the currently loaded Action View as a Gem::Version - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers.rb deleted file mode 100644 index c1b4b4f84b..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers.rb +++ /dev/null @@ -1,64 +0,0 @@ -require "active_support/benchmarkable" - -module ActionView #:nodoc: - module Helpers #:nodoc: - extend ActiveSupport::Autoload - - autoload :ActiveModelHelper - autoload :AssetTagHelper - autoload :AssetUrlHelper - autoload :AtomFeedHelper - autoload :CacheHelper - autoload :CaptureHelper - autoload :ControllerHelper - autoload :CsrfHelper - autoload :DateHelper - autoload :DebugHelper - autoload :FormHelper - autoload :FormOptionsHelper - autoload :FormTagHelper - autoload :JavaScriptHelper, "action_view/helpers/javascript_helper" - autoload :NumberHelper - autoload :OutputSafetyHelper - autoload :RecordTagHelper - autoload :RenderingHelper - autoload :SanitizeHelper - autoload :TagHelper - autoload :TextHelper - autoload :TranslationHelper - autoload :UrlHelper - autoload :Tags - - def self.eager_load! - super - Tags.eager_load! - end - - extend ActiveSupport::Concern - - include ActiveSupport::Benchmarkable - include ActiveModelHelper - include AssetTagHelper - include AssetUrlHelper - include AtomFeedHelper - include CacheHelper - include CaptureHelper - include ControllerHelper - include CsrfHelper - include DateHelper - include DebugHelper - include FormHelper - include FormOptionsHelper - include FormTagHelper - include JavaScriptHelper - include NumberHelper - include OutputSafetyHelper - include RecordTagHelper - include RenderingHelper - include SanitizeHelper - include TagHelper - include TextHelper - include TranslationHelper - include UrlHelper - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/active_model_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/active_model_helper.rb deleted file mode 100644 index 4bb5788a16..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/active_model_helper.rb +++ /dev/null @@ -1,49 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/enumerable" - -module ActionView - # = Active Model Helpers - module Helpers - module ActiveModelHelper - end - - module ActiveModelInstanceTag - def object - @active_model_object ||= begin - object = super - object.respond_to?(:to_model) ? object.to_model : object - end - end - - def content_tag(*) - error_wrapping(super) - end - - def tag(type, options, *) - tag_generate_errors?(options) ? error_wrapping(super) : super - end - - def error_wrapping(html_tag) - if object_has_errors? - Base.field_error_proc.call(html_tag, self) - else - html_tag - end - end - - def error_message - object.errors[@method_name] - end - - private - - def object_has_errors? - object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present? - end - - def tag_generate_errors?(options) - options["type"] != "hidden" - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/asset_tag_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/asset_tag_helper.rb deleted file mode 100644 index 750f96f29e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/asset_tag_helper.rb +++ /dev/null @@ -1,365 +0,0 @@ -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/hash/keys" -require "action_view/helpers/asset_url_helper" -require "action_view/helpers/tag_helper" - -module ActionView - # = Action View Asset Tag Helpers - module Helpers #:nodoc: - # This module provides methods for generating HTML that links views to assets such - # as images, JavaScripts, stylesheets, and feeds. These methods do not verify - # the assets exist before linking to them: - # - # image_tag("rails.png") - # # => Rails - # stylesheet_link_tag("application") - # # => - module AssetTagHelper - extend ActiveSupport::Concern - - include AssetUrlHelper - include TagHelper - - # Returns an HTML script tag for each of the +sources+ provided. - # - # Sources may be paths to JavaScript files. Relative paths are assumed to be relative - # to assets/javascripts, full paths are assumed to be relative to the document - # root. Relative paths are idiomatic, use absolute paths only when needed. - # - # When passing paths, the ".js" extension is optional. If you do not want ".js" - # appended to the path extname: false can be set on the options. - # - # You can modify the HTML attributes of the script tag by passing a hash as the - # last argument. - # - # When the Asset Pipeline is enabled, you can pass the name of your manifest as - # source, and include other JavaScript or CoffeeScript files inside the manifest. - # - # ==== Options - # - # When the last parameter is a hash you can add HTML attributes using that - # parameter. The following options are supported: - # - # * :extname - Append an extension to the generated url unless the extension - # already exists. This only applies for relative urls. - # * :protocol - Sets the protocol of the generated url, this option only - # applies when a relative url and +host+ options are provided. - # * :host - When a relative url is provided the host is added to the - # that path. - # * :skip_pipeline - This option is used to bypass the asset pipeline - # when it is set to true. - # - # ==== Examples - # - # javascript_include_tag "xmlhr" - # # => - # - # javascript_include_tag "xmlhr", host: "localhost", protocol: "https" - # # => - # - # javascript_include_tag "template.jst", extname: false - # # => - # - # javascript_include_tag "xmlhr.js" - # # => - # - # javascript_include_tag "common.javascript", "/elsewhere/cools" - # # => - # # - # - # javascript_include_tag "http://www.example.com/xmlhr" - # # => - # - # javascript_include_tag "http://www.example.com/xmlhr.js" - # # => - def javascript_include_tag(*sources) - options = sources.extract_options!.stringify_keys - path_options = options.extract!("protocol", "extname", "host", "skip_pipeline").symbolize_keys - sources.uniq.map { |source| - tag_options = { - "src" => path_to_javascript(source, path_options) - }.merge!(options) - content_tag("script".freeze, "", tag_options) - }.join("\n").html_safe - end - - # Returns a stylesheet link tag for the sources specified as arguments. If - # you don't specify an extension, .css will be appended automatically. - # You can modify the link attributes by passing a hash as the last argument. - # For historical reasons, the 'media' attribute will always be present and defaults - # to "screen", so you must explicitly set it to "all" for the stylesheet(s) to - # apply to all media types. - # - # stylesheet_link_tag "style" - # # => - # - # stylesheet_link_tag "style.css" - # # => - # - # stylesheet_link_tag "http://www.example.com/style.css" - # # => - # - # stylesheet_link_tag "style", media: "all" - # # => - # - # stylesheet_link_tag "style", media: "print" - # # => - # - # stylesheet_link_tag "random.styles", "/css/stylish" - # # => - # # - def stylesheet_link_tag(*sources) - options = sources.extract_options!.stringify_keys - path_options = options.extract!("protocol", "host", "skip_pipeline").symbolize_keys - sources.uniq.map { |source| - tag_options = { - "rel" => "stylesheet", - "media" => "screen", - "href" => path_to_stylesheet(source, path_options) - }.merge!(options) - tag(:link, tag_options) - }.join("\n").html_safe - end - - # Returns a link tag that browsers and feed readers can use to auto-detect - # an RSS or Atom feed. The +type+ can either be :rss (default) or - # :atom. Control the link options in url_for format using the - # +url_options+. You can modify the LINK tag itself in +tag_options+. - # - # ==== Options - # - # * :rel - Specify the relation of this link, defaults to "alternate" - # * :type - Override the auto-generated mime type - # * :title - Specify the title of the link, defaults to the +type+ - # - # ==== Examples - # - # auto_discovery_link_tag - # # => - # auto_discovery_link_tag(:atom) - # # => - # auto_discovery_link_tag(:rss, {action: "feed"}) - # # => - # auto_discovery_link_tag(:rss, {action: "feed"}, {title: "My RSS"}) - # # => - # auto_discovery_link_tag(:rss, {controller: "news", action: "feed"}) - # # => - # auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "Example RSS"}) - # # => - def auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {}) - if !(type == :rss || type == :atom) && tag_options[:type].blank? - raise ArgumentError.new("You should pass :type tag_option key explicitly, because you have passed #{type} type other than :rss or :atom.") - end - - tag( - "link", - "rel" => tag_options[:rel] || "alternate", - "type" => tag_options[:type] || Template::Types[type].to_s, - "title" => tag_options[:title] || type.to_s.upcase, - "href" => url_options.is_a?(Hash) ? url_for(url_options.merge(only_path: false)) : url_options - ) - end - - # Returns a link tag for a favicon managed by the asset pipeline. - # - # If a page has no link like the one generated by this helper, browsers - # ask for /favicon.ico automatically, and cache the file if the - # request succeeds. If the favicon changes it is hard to get it updated. - # - # To have better control applications may let the asset pipeline manage - # their favicon storing the file under app/assets/images, and - # using this helper to generate its corresponding link tag. - # - # The helper gets the name of the favicon file as first argument, which - # defaults to "favicon.ico", and also supports +:rel+ and +:type+ options - # to override their defaults, "shortcut icon" and "image/x-icon" - # respectively: - # - # favicon_link_tag - # # => - # - # favicon_link_tag 'myicon.ico' - # # => - # - # Mobile Safari looks for a different link tag, pointing to an image that - # will be used if you add the page to the home screen of an iOS device. - # The following call would generate such a tag: - # - # favicon_link_tag 'mb-icon.png', rel: 'apple-touch-icon', type: 'image/png' - # # => - def favicon_link_tag(source = "favicon.ico", options = {}) - tag("link", { - rel: "shortcut icon", - type: "image/x-icon", - href: path_to_image(source, skip_pipeline: options.delete(:skip_pipeline)) - }.merge!(options.symbolize_keys)) - end - - # Returns an HTML image tag for the +source+. The +source+ can be a full - # path or a file. - # - # ==== Options - # - # You can add HTML attributes using the +options+. The +options+ supports - # two additional keys for convenience and conformance: - # - # * :alt - If no alt text is given, the file name part of the - # +source+ is used (capitalized and without the extension) - # * :size - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes - # width="30" and height="45", and "50" becomes width="50" and height="50". - # :size will be ignored if the value is not in the correct format. - # - # ==== Examples - # - # image_tag("icon") - # # => Icon - # image_tag("icon.png") - # # => Icon - # image_tag("icon.png", size: "16x10", alt: "Edit Entry") - # # => Edit Entry - # image_tag("/icons/icon.gif", size: "16") - # # => Icon - # image_tag("/icons/icon.gif", height: '32', width: '32') - # # => Icon - # image_tag("/icons/icon.gif", class: "menu_icon") - # # => Icon - # image_tag("/icons/icon.gif", data: { title: 'Rails Application' }) - # # => - def image_tag(source, options = {}) - options = options.symbolize_keys - check_for_image_tag_errors(options) - - src = options[:src] = path_to_image(source, skip_pipeline: options.delete(:skip_pipeline)) - - unless src.start_with?("cid:") || src.start_with?("data:") || src.blank? - options[:alt] = options.fetch(:alt) { image_alt(src) } - end - - options[:width], options[:height] = extract_dimensions(options.delete(:size)) if options[:size] - tag("img", options) - end - - # Returns a string suitable for an HTML image tag alt attribute. - # The +src+ argument is meant to be an image file path. - # The method removes the basename of the file path and the digest, - # if any. It also removes hyphens and underscores from file names and - # replaces them with spaces, returning a space-separated, titleized - # string. - # - # ==== Examples - # - # image_alt('rails.png') - # # => Rails - # - # image_alt('hyphenated-file-name.png') - # # => Hyphenated file name - # - # image_alt('underscored_file_name.png') - # # => Underscored file name - def image_alt(src) - File.basename(src, ".*".freeze).sub(/-[[:xdigit:]]{32,64}\z/, "".freeze).tr("-_".freeze, " ".freeze).capitalize - end - - # Returns an HTML video tag for the +sources+. If +sources+ is a string, - # a single video tag will be returned. If +sources+ is an array, a video - # tag with nested source tags for each source will be returned. The - # +sources+ can be full paths or files that exists in your public videos - # directory. - # - # ==== Options - # You can add HTML attributes using the +options+. The +options+ supports - # two additional keys for convenience and conformance: - # - # * :poster - Set an image (like a screenshot) to be shown - # before the video loads. The path is calculated like the +src+ of +image_tag+. - # * :size - Supplied as "{Width}x{Height}" or "{Number}", so "30x45" becomes - # width="30" and height="45", and "50" becomes width="50" and height="50". - # :size will be ignored if the value is not in the correct format. - # * :poster_skip_pipeline will bypass the asset pipeline when using - # the :poster option instead using an asset in the public folder. - # - # ==== Examples - # - # video_tag("trailer") - # # => - # video_tag("trailer.ogg") - # # => - # video_tag("trailer.ogg", controls: true, preload: 'none') - # # => - # video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png") - # # => - # video_tag("trailer.m4v", size: "16x10", poster: "screenshot.png", poster_skip_pipeline: true) - # # => - # video_tag("/trailers/hd.avi", size: "16x16") - # # => - # video_tag("/trailers/hd.avi", size: "16") - # # => - # video_tag("/trailers/hd.avi", height: '32', width: '32') - # # => - # video_tag("trailer.ogg", "trailer.flv") - # # => - # video_tag(["trailer.ogg", "trailer.flv"]) - # # => - # video_tag(["trailer.ogg", "trailer.flv"], size: "160x120") - # # => - def video_tag(*sources) - options = sources.extract_options!.symbolize_keys - public_poster_folder = options.delete(:poster_skip_pipeline) - sources << options - multiple_sources_tag_builder("video", sources) do |tag_options| - tag_options[:poster] = path_to_image(tag_options[:poster], skip_pipeline: public_poster_folder) if tag_options[:poster] - tag_options[:width], tag_options[:height] = extract_dimensions(tag_options.delete(:size)) if tag_options[:size] - end - end - - # Returns an HTML audio tag for the +source+. - # The +source+ can be full path or file that exists in - # your public audios directory. - # - # audio_tag("sound") - # # => - # audio_tag("sound.wav") - # # => - # audio_tag("sound.wav", autoplay: true, controls: true) - # # => - # audio_tag("sound.wav", "sound.mid") - # # => - def audio_tag(*sources) - multiple_sources_tag_builder("audio", sources) - end - - private - def multiple_sources_tag_builder(type, sources) - options = sources.extract_options!.symbolize_keys - skip_pipeline = options.delete(:skip_pipeline) - sources.flatten! - - yield options if block_given? - - if sources.size > 1 - content_tag(type, options) do - safe_join sources.map { |source| tag("source", src: send("path_to_#{type}", source, skip_pipeline: skip_pipeline)) } - end - else - options[:src] = send("path_to_#{type}", sources.first, skip_pipeline: skip_pipeline) - content_tag(type, nil, options) - end - end - - def extract_dimensions(size) - size = size.to_s - if /\A\d+x\d+\z/.match?(size) - size.split("x") - elsif /\A\d+\z/.match?(size) - [size, size] - end - end - - def check_for_image_tag_errors(options) - if options[:size] && (options[:height] || options[:width]) - raise ArgumentError, "Cannot pass a :size option with a :height or :width option" - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/asset_url_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/asset_url_helper.rb deleted file mode 100644 index 03bd1eb008..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/asset_url_helper.rb +++ /dev/null @@ -1,467 +0,0 @@ -require "zlib" - -module ActionView - # = Action View Asset URL Helpers - module Helpers - # This module provides methods for generating asset paths and - # urls. - # - # image_path("rails.png") - # # => "/assets/rails.png" - # - # image_url("rails.png") - # # => "http://www.example.com/assets/rails.png" - # - # === Using asset hosts - # - # By default, Rails links to these assets on the current host in the public - # folder, but you can direct Rails to link to assets from a dedicated asset - # server by setting ActionController::Base.asset_host in the application - # configuration, typically in config/environments/production.rb. - # For example, you'd define assets.example.com to be your asset - # host this way, inside the configure block of your environment-specific - # configuration files or config/application.rb: - # - # config.action_controller.asset_host = "assets.example.com" - # - # Helpers take that into account: - # - # image_tag("rails.png") - # # => Rails - # stylesheet_link_tag("application") - # # => - # - # Browsers open a limited number of simultaneous connections to a single - # host. The exact number varies by browser and version. This limit may cause - # some asset downloads to wait for previous assets to finish before they can - # begin. You can use the %d wildcard in the +asset_host+ to - # distribute the requests over four hosts. For example, - # assets%d.example.com will spread the asset requests over - # "assets0.example.com", ..., "assets3.example.com". - # - # image_tag("rails.png") - # # => Rails - # stylesheet_link_tag("application") - # # => - # - # This may improve the asset loading performance of your application. - # It is also possible the combination of additional connection overhead - # (DNS, SSL) and the overall browser connection limits may result in this - # solution being slower. You should be sure to measure your actual - # performance across targeted browsers both before and after this change. - # - # To implement the corresponding hosts you can either setup four actual - # hosts or use wildcard DNS to CNAME the wildcard to a single asset host. - # You can read more about setting up your DNS CNAME records from your ISP. - # - # Note: This is purely a browser performance optimization and is not meant - # for server load balancing. See http://www.die.net/musings/page_load_time/ - # for background and http://www.browserscope.org/?category=network for - # connection limit data. - # - # Alternatively, you can exert more control over the asset host by setting - # +asset_host+ to a proc like this: - # - # ActionController::Base.asset_host = Proc.new { |source| - # "http://assets#{Digest::MD5.hexdigest(source).to_i(16) % 2 + 1}.example.com" - # } - # image_tag("rails.png") - # # => Rails - # stylesheet_link_tag("application") - # # => - # - # The example above generates "http://assets1.example.com" and - # "http://assets2.example.com". This option is useful for example if - # you need fewer/more than four hosts, custom host names, etc. - # - # As you see the proc takes a +source+ parameter. That's a string with the - # absolute path of the asset, for example "/assets/rails.png". - # - # ActionController::Base.asset_host = Proc.new { |source| - # if source.ends_with?('.css') - # "http://stylesheets.example.com" - # else - # "http://assets.example.com" - # end - # } - # image_tag("rails.png") - # # => Rails - # stylesheet_link_tag("application") - # # => - # - # Alternatively you may ask for a second parameter +request+. That one is - # particularly useful for serving assets from an SSL-protected page. The - # example proc below disables asset hosting for HTTPS connections, while - # still sending assets for plain HTTP requests from asset hosts. If you don't - # have SSL certificates for each of the asset hosts this technique allows you - # to avoid warnings in the client about mixed media. - # Note that the request parameter might not be supplied, e.g. when the assets - # are precompiled via a Rake task. Make sure to use a +Proc+ instead of a lambda, - # since a +Proc+ allows missing parameters and sets them to +nil+. - # - # config.action_controller.asset_host = Proc.new { |source, request| - # if request && request.ssl? - # "#{request.protocol}#{request.host_with_port}" - # else - # "#{request.protocol}assets.example.com" - # end - # } - # - # You can also implement a custom asset host object that responds to +call+ - # and takes either one or two parameters just like the proc. - # - # config.action_controller.asset_host = AssetHostingWithMinimumSsl.new( - # "http://asset%d.example.com", "https://asset1.example.com" - # ) - # - module AssetUrlHelper - URI_REGEXP = %r{^[-a-z]+://|^(?:cid|data):|^//}i - - # This is the entry point for all assets. - # When using the asset pipeline (i.e. sprockets and sprockets-rails), the - # behavior is "enhanced". You can bypass the asset pipeline by passing in - # skip_pipeline: true to the options. - # - # All other asset *_path helpers delegate through this method. - # - # === With the asset pipeline - # - # All options passed to +asset_path+ will be passed to +compute_asset_path+ - # which is implemented by sprockets-rails. - # - # asset_path("application.js") # => "/assets/application-60aa4fdc5cea14baf5400fba1abf4f2a46a5166bad4772b1effe341570f07de9.js" - # - # === Without the asset pipeline (skip_pipeline: true) - # - # Accepts a type option that can specify the asset's extension. No error - # checking is done to verify the source passed into +asset_path+ is valid - # and that the file exists on disk. - # - # asset_path("application.js", skip_pipeline: true) # => "application.js" - # asset_path("filedoesnotexist.png", skip_pipeline: true) # => "filedoesnotexist.png" - # asset_path("application", type: :javascript, skip_pipeline: true) # => "/javascripts/application.js" - # asset_path("application", type: :stylesheet, skip_pipeline: true) # => "/stylesheets/application.css" - # - # === Options applying to all assets - # - # Below lists scenarios that apply to +asset_path+ whether or not you're - # using the asset pipeline. - # - # - All fully qualified urls are returned immediately. This bypasses the - # asset pipeline and all other behavior described. - # - # asset_path("http://www.example.com/js/xmlhr.js") # => "http://www.example.com/js/xmlhr.js" - # - # - All assets that begin with a forward slash are assumed to be full - # urls and will not be expanded. This will bypass the asset pipeline. - # - # asset_path("/foo.png") # => "/foo.png" - # - # - All blank strings will be returned immediately. This bypasses the - # asset pipeline and all other behavior described. - # - # asset_path("") # => "" - # - # - If config.relative_url_root is specified, all assets will have that - # root prepended. - # - # Rails.application.config.relative_url_root = "bar" - # asset_path("foo.js", skip_pipeline: true) # => "bar/foo.js" - # - # - A different asset host can be specified via config.action_controller.asset_host - # this is commonly used in conjunction with a CDN. - # - # Rails.application.config.action_controller.asset_host = "assets.example.com" - # asset_path("foo.js", skip_pipeline: true) # => "http://assets.example.com/foo.js" - # - # - An extension name can be specified manually with extname. - # - # asset_path("foo", skip_pipeline: true, extname: ".js") # => "/foo.js" - # asset_path("foo.css", skip_pipeline: true, extname: ".js") # => "/foo.css.js" - def asset_path(source, options = {}) - raise ArgumentError, "nil is not a valid asset source" if source.nil? - - source = source.to_s - return "" if source.blank? - return source if URI_REGEXP.match?(source) - - tail, source = source[/([\?#].+)$/], source.sub(/([\?#].+)$/, "".freeze) - - if extname = compute_asset_extname(source, options) - source = "#{source}#{extname}" - end - - if source[0] != ?/ - if options[:skip_pipeline] - source = public_compute_asset_path(source, options) - else - source = compute_asset_path(source, options) - end - end - - relative_url_root = defined?(config.relative_url_root) && config.relative_url_root - if relative_url_root - source = File.join(relative_url_root, source) unless source.starts_with?("#{relative_url_root}/") - end - - if host = compute_asset_host(source, options) - source = File.join(host, source) - end - - "#{source}#{tail}" - end - alias_method :path_to_asset, :asset_path # aliased to avoid conflicts with an asset_path named route - - # Computes the full URL to an asset in the public directory. This - # will use +asset_path+ internally, so most of their behaviors - # will be the same. If :host options is set, it overwrites global - # +config.action_controller.asset_host+ setting. - # - # All other options provided are forwarded to +asset_path+ call. - # - # asset_url "application.js" # => http://example.com/assets/application.js - # asset_url "application.js", host: "http://cdn.example.com" # => http://cdn.example.com/assets/application.js - # - def asset_url(source, options = {}) - path_to_asset(source, options.merge(protocol: :request)) - end - alias_method :url_to_asset, :asset_url # aliased to avoid conflicts with an asset_url named route - - ASSET_EXTENSIONS = { - javascript: ".js", - stylesheet: ".css" - } - - # Compute extname to append to asset path. Returns +nil+ if - # nothing should be added. - def compute_asset_extname(source, options = {}) - return if options[:extname] == false - extname = options[:extname] || ASSET_EXTENSIONS[options[:type]] - if extname && File.extname(source) != extname - extname - else - nil - end - end - - # Maps asset types to public directory. - ASSET_PUBLIC_DIRECTORIES = { - audio: "/audios", - font: "/fonts", - image: "/images", - javascript: "/javascripts", - stylesheet: "/stylesheets", - video: "/videos" - } - - # Computes asset path to public directory. Plugins and - # extensions can override this method to point to custom assets - # or generate digested paths or query strings. - def compute_asset_path(source, options = {}) - dir = ASSET_PUBLIC_DIRECTORIES[options[:type]] || "" - File.join(dir, source) - end - alias :public_compute_asset_path :compute_asset_path - - # Pick an asset host for this source. Returns +nil+ if no host is set, - # the host if no wildcard is set, the host interpolated with the - # numbers 0-3 if it contains %d (the number is the source hash mod 4), - # or the value returned from invoking call on an object responding to call - # (proc or otherwise). - def compute_asset_host(source = "", options = {}) - request = self.request if respond_to?(:request) - host = options[:host] - host ||= config.asset_host if defined? config.asset_host - - if host - if host.respond_to?(:call) - arity = host.respond_to?(:arity) ? host.arity : host.method(:call).arity - args = [source] - args << request if request && (arity > 1 || arity < 0) - host = host.call(*args) - elsif host.include?("%d") - host = host % (Zlib.crc32(source) % 4) - end - end - - host ||= request.base_url if request && options[:protocol] == :request - return unless host - - if URI_REGEXP.match?(host) - host - else - protocol = options[:protocol] || config.default_asset_host_protocol || (request ? :request : :relative) - case protocol - when :relative - "//#{host}" - when :request - "#{request.protocol}#{host}" - else - "#{protocol}://#{host}" - end - end - end - - # Computes the path to a JavaScript asset in the public javascripts directory. - # If the +source+ filename has no extension, .js will be appended (except for explicit URIs) - # Full paths from the document root will be passed through. - # Used internally by +javascript_include_tag+ to build the script path. - # - # javascript_path "xmlhr" # => /assets/xmlhr.js - # javascript_path "dir/xmlhr.js" # => /assets/dir/xmlhr.js - # javascript_path "/dir/xmlhr" # => /dir/xmlhr.js - # javascript_path "http://www.example.com/js/xmlhr" # => http://www.example.com/js/xmlhr - # javascript_path "http://www.example.com/js/xmlhr.js" # => http://www.example.com/js/xmlhr.js - def javascript_path(source, options = {}) - path_to_asset(source, { type: :javascript }.merge!(options)) - end - alias_method :path_to_javascript, :javascript_path # aliased to avoid conflicts with a javascript_path named route - - # Computes the full URL to a JavaScript asset in the public javascripts directory. - # This will use +javascript_path+ internally, so most of their behaviors will be the same. - # Since +javascript_url+ is based on +asset_url+ method you can set :host options. If :host - # options is set, it overwrites global +config.action_controller.asset_host+ setting. - # - # javascript_url "js/xmlhr.js", host: "http://stage.example.com" # => http://stage.example.com/assets/dir/xmlhr.js - # - def javascript_url(source, options = {}) - url_to_asset(source, { type: :javascript }.merge!(options)) - end - alias_method :url_to_javascript, :javascript_url # aliased to avoid conflicts with a javascript_url named route - - # Computes the path to a stylesheet asset in the public stylesheets directory. - # If the +source+ filename has no extension, .css will be appended (except for explicit URIs). - # Full paths from the document root will be passed through. - # Used internally by +stylesheet_link_tag+ to build the stylesheet path. - # - # stylesheet_path "style" # => /assets/style.css - # stylesheet_path "dir/style.css" # => /assets/dir/style.css - # stylesheet_path "/dir/style.css" # => /dir/style.css - # stylesheet_path "http://www.example.com/css/style" # => http://www.example.com/css/style - # stylesheet_path "http://www.example.com/css/style.css" # => http://www.example.com/css/style.css - def stylesheet_path(source, options = {}) - path_to_asset(source, { type: :stylesheet }.merge!(options)) - end - alias_method :path_to_stylesheet, :stylesheet_path # aliased to avoid conflicts with a stylesheet_path named route - - # Computes the full URL to a stylesheet asset in the public stylesheets directory. - # This will use +stylesheet_path+ internally, so most of their behaviors will be the same. - # Since +stylesheet_url+ is based on +asset_url+ method you can set :host options. If :host - # options is set, it overwrites global +config.action_controller.asset_host+ setting. - # - # stylesheet_url "css/style.css", host: "http://stage.example.com" # => http://stage.example.com/css/style.css - # - def stylesheet_url(source, options = {}) - url_to_asset(source, { type: :stylesheet }.merge!(options)) - end - alias_method :url_to_stylesheet, :stylesheet_url # aliased to avoid conflicts with a stylesheet_url named route - - # Computes the path to an image asset. - # Full paths from the document root will be passed through. - # Used internally by +image_tag+ to build the image path: - # - # image_path("edit") # => "/assets/edit" - # image_path("edit.png") # => "/assets/edit.png" - # image_path("icons/edit.png") # => "/assets/icons/edit.png" - # image_path("/icons/edit.png") # => "/icons/edit.png" - # image_path("http://www.example.com/img/edit.png") # => "http://www.example.com/img/edit.png" - # - # If you have images as application resources this method may conflict with their named routes. - # The alias +path_to_image+ is provided to avoid that. Rails uses the alias internally, and - # plugin authors are encouraged to do so. - def image_path(source, options = {}) - path_to_asset(source, { type: :image }.merge!(options)) - end - alias_method :path_to_image, :image_path # aliased to avoid conflicts with an image_path named route - - # Computes the full URL to an image asset. - # This will use +image_path+ internally, so most of their behaviors will be the same. - # Since +image_url+ is based on +asset_url+ method you can set :host options. If :host - # options is set, it overwrites global +config.action_controller.asset_host+ setting. - # - # image_url "edit.png", host: "http://stage.example.com" # => http://stage.example.com/edit.png - # - def image_url(source, options = {}) - url_to_asset(source, { type: :image }.merge!(options)) - end - alias_method :url_to_image, :image_url # aliased to avoid conflicts with an image_url named route - - # Computes the path to a video asset in the public videos directory. - # Full paths from the document root will be passed through. - # Used internally by +video_tag+ to build the video path. - # - # video_path("hd") # => /videos/hd - # video_path("hd.avi") # => /videos/hd.avi - # video_path("trailers/hd.avi") # => /videos/trailers/hd.avi - # video_path("/trailers/hd.avi") # => /trailers/hd.avi - # video_path("http://www.example.com/vid/hd.avi") # => http://www.example.com/vid/hd.avi - def video_path(source, options = {}) - path_to_asset(source, { type: :video }.merge!(options)) - end - alias_method :path_to_video, :video_path # aliased to avoid conflicts with a video_path named route - - # Computes the full URL to a video asset in the public videos directory. - # This will use +video_path+ internally, so most of their behaviors will be the same. - # Since +video_url+ is based on +asset_url+ method you can set :host options. If :host - # options is set, it overwrites global +config.action_controller.asset_host+ setting. - # - # video_url "hd.avi", host: "http://stage.example.com" # => http://stage.example.com/hd.avi - # - def video_url(source, options = {}) - url_to_asset(source, { type: :video }.merge!(options)) - end - alias_method :url_to_video, :video_url # aliased to avoid conflicts with a video_url named route - - # Computes the path to an audio asset in the public audios directory. - # Full paths from the document root will be passed through. - # Used internally by +audio_tag+ to build the audio path. - # - # audio_path("horse") # => /audios/horse - # audio_path("horse.wav") # => /audios/horse.wav - # audio_path("sounds/horse.wav") # => /audios/sounds/horse.wav - # audio_path("/sounds/horse.wav") # => /sounds/horse.wav - # audio_path("http://www.example.com/sounds/horse.wav") # => http://www.example.com/sounds/horse.wav - def audio_path(source, options = {}) - path_to_asset(source, { type: :audio }.merge!(options)) - end - alias_method :path_to_audio, :audio_path # aliased to avoid conflicts with an audio_path named route - - # Computes the full URL to an audio asset in the public audios directory. - # This will use +audio_path+ internally, so most of their behaviors will be the same. - # Since +audio_url+ is based on +asset_url+ method you can set :host options. If :host - # options is set, it overwrites global +config.action_controller.asset_host+ setting. - # - # audio_url "horse.wav", host: "http://stage.example.com" # => http://stage.example.com/horse.wav - # - def audio_url(source, options = {}) - url_to_asset(source, { type: :audio }.merge!(options)) - end - alias_method :url_to_audio, :audio_url # aliased to avoid conflicts with an audio_url named route - - # Computes the path to a font asset. - # Full paths from the document root will be passed through. - # - # font_path("font") # => /fonts/font - # font_path("font.ttf") # => /fonts/font.ttf - # font_path("dir/font.ttf") # => /fonts/dir/font.ttf - # font_path("/dir/font.ttf") # => /dir/font.ttf - # font_path("http://www.example.com/dir/font.ttf") # => http://www.example.com/dir/font.ttf - def font_path(source, options = {}) - path_to_asset(source, { type: :font }.merge!(options)) - end - alias_method :path_to_font, :font_path # aliased to avoid conflicts with a font_path named route - - # Computes the full URL to a font asset. - # This will use +font_path+ internally, so most of their behaviors will be the same. - # Since +font_url+ is based on +asset_url+ method you can set :host options. If :host - # options is set, it overwrites global +config.action_controller.asset_host+ setting. - # - # font_url "font.ttf", host: "http://stage.example.com" # => http://stage.example.com/font.ttf - # - def font_url(source, options = {}) - url_to_asset(source, { type: :font }.merge!(options)) - end - alias_method :url_to_font, :font_url # aliased to avoid conflicts with a font_url named route - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/atom_feed_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/atom_feed_helper.rb deleted file mode 100644 index 3538515aee..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/atom_feed_helper.rb +++ /dev/null @@ -1,203 +0,0 @@ -require "set" - -module ActionView - # = Action View Atom Feed Helpers - module Helpers - module AtomFeedHelper - # Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERB or any other - # template languages). - # - # Full usage example: - # - # config/routes.rb: - # Rails.application.routes.draw do - # resources :posts - # root to: "posts#index" - # end - # - # app/controllers/posts_controller.rb: - # class PostsController < ApplicationController - # # GET /posts.html - # # GET /posts.atom - # def index - # @posts = Post.all - # - # respond_to do |format| - # format.html - # format.atom - # end - # end - # end - # - # app/views/posts/index.atom.builder: - # atom_feed do |feed| - # feed.title("My great blog!") - # feed.updated(@posts[0].created_at) if @posts.length > 0 - # - # @posts.each do |post| - # feed.entry(post) do |entry| - # entry.title(post.title) - # entry.content(post.body, type: 'html') - # - # entry.author do |author| - # author.name("DHH") - # end - # end - # end - # end - # - # The options for atom_feed are: - # - # * :language: Defaults to "en-US". - # * :root_url: The HTML alternative that this feed is doubling for. Defaults to / on the current host. - # * :url: The URL for this feed. Defaults to the current URL. - # * :id: The id for this feed. Defaults to "tag:localhost,2005:/posts", in this case. - # * :schema_date: The date at which the tag scheme for the feed was first used. A good default is the year you - # created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified, - # 2005 is used (as an "I don't care" value). - # * :instruct: Hash of XML processing instructions in the form {target => {attribute => value, }} or {target => [{attribute => value, }, ]} - # - # Other namespaces can be added to the root element: - # - # app/views/posts/index.atom.builder: - # atom_feed({'xmlns:app' => 'http://www.w3.org/2007/app', - # 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'}) do |feed| - # feed.title("My great blog!") - # feed.updated((@posts.first.created_at)) - # feed.tag!('openSearch:totalResults', 10) - # - # @posts.each do |post| - # feed.entry(post) do |entry| - # entry.title(post.title) - # entry.content(post.body, type: 'html') - # entry.tag!('app:edited', Time.now) - # - # entry.author do |author| - # author.name("DHH") - # end - # end - # end - # end - # - # The Atom spec defines five elements (content rights title subtitle - # summary) which may directly contain xhtml content if type: 'xhtml' - # is specified as an attribute. If so, this helper will take care of - # the enclosing div and xhtml namespace declaration. Example usage: - # - # entry.summary type: 'xhtml' do |xhtml| - # xhtml.p pluralize(order.line_items.count, "line item") - # xhtml.p "Shipped to #{order.address}" - # xhtml.p "Paid by #{order.pay_type}" - # end - # - # - # atom_feed yields an +AtomFeedBuilder+ instance. Nested elements yield - # an +AtomBuilder+ instance. - def atom_feed(options = {}, &block) - if options[:schema_date] - options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime) - else - options[:schema_date] = "2005" # The Atom spec copyright date - end - - xml = options.delete(:xml) || eval("xml", block.binding) - xml.instruct! - if options[:instruct] - options[:instruct].each do |target, attrs| - if attrs.respond_to?(:keys) - xml.instruct!(target, attrs) - elsif attrs.respond_to?(:each) - attrs.each { |attr_group| xml.instruct!(target, attr_group) } - end - end - end - - feed_opts = { "xml:lang" => options[:language] || "en-US", "xmlns" => "http://www.w3.org/2005/Atom" } - feed_opts.merge!(options).reject! { |k, v| !k.to_s.match(/^xml/) } - - xml.feed(feed_opts) do - xml.id(options[:id] || "tag:#{request.host},#{options[:schema_date]}:#{request.fullpath.split(".")[0]}") - xml.link(rel: "alternate", type: "text/html", href: options[:root_url] || (request.protocol + request.host_with_port)) - xml.link(rel: "self", type: "application/atom+xml", href: options[:url] || request.url) - - yield AtomFeedBuilder.new(xml, self, options) - end - end - - class AtomBuilder #:nodoc: - XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set - - def initialize(xml) - @xml = xml - end - - private - # Delegate to xml builder, first wrapping the element in an xhtml - # namespaced div element if the method and arguments indicate - # that an xhtml_block? is desired. - def method_missing(method, *arguments, &block) - if xhtml_block?(method, arguments) - @xml.__send__(method, *arguments) do - @xml.div(xmlns: "http://www.w3.org/1999/xhtml") do |xhtml| - block.call(xhtml) - end - end - else - @xml.__send__(method, *arguments, &block) - end - end - - # True if the method name matches one of the five elements defined - # in the Atom spec as potentially containing XHTML content and - # if type: 'xhtml' is, in fact, specified. - def xhtml_block?(method, arguments) - if XHTML_TAG_NAMES.include?(method.to_s) - last = arguments.last - last.is_a?(Hash) && last[:type].to_s == "xhtml" - end - end - end - - class AtomFeedBuilder < AtomBuilder #:nodoc: - def initialize(xml, view, feed_options = {}) - @xml, @view, @feed_options = xml, view, feed_options - end - - # Accepts a Date or Time object and inserts it in the proper format. If +nil+ is passed, current time in UTC is used. - def updated(date_or_time = nil) - @xml.updated((date_or_time || Time.now.utc).xmlschema) - end - - # Creates an entry tag for a specific record and prefills the id using class and id. - # - # Options: - # - # * :published: Time first published. Defaults to the created_at attribute on the record if one such exists. - # * :updated: Time of update. Defaults to the updated_at attribute on the record if one such exists. - # * :url: The URL for this entry or +false+ or +nil+ for not having a link tag. Defaults to the +polymorphic_url+ for the record. - # * :id: The ID for this entry. Defaults to "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}" - # * :type: The TYPE for this entry. Defaults to "text/html". - def entry(record, options = {}) - @xml.entry do - @xml.id(options[:id] || "tag:#{@view.request.host},#{@feed_options[:schema_date]}:#{record.class}/#{record.id}") - - if options[:published] || (record.respond_to?(:created_at) && record.created_at) - @xml.published((options[:published] || record.created_at).xmlschema) - end - - if options[:updated] || (record.respond_to?(:updated_at) && record.updated_at) - @xml.updated((options[:updated] || record.updated_at).xmlschema) - end - - type = options.fetch(:type, "text/html") - - url = options.fetch(:url) { @view.polymorphic_url(record) } - @xml.link(rel: "alternate", type: type, href: url) if url - - yield AtomBuilder.new(@xml) - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/cache_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/cache_helper.rb deleted file mode 100644 index 8c22bf6719..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/cache_helper.rb +++ /dev/null @@ -1,253 +0,0 @@ -module ActionView - # = Action View Cache Helper - module Helpers - module CacheHelper - # This helper exposes a method for caching fragments of a view - # rather than an entire action or page. This technique is useful - # caching pieces like menus, lists of new topics, static HTML - # fragments, and so on. This method takes a block that contains - # the content you wish to cache. - # - # The best way to use this is by doing key-based cache expiration - # on top of a cache store like Memcached that'll automatically - # kick out old entries. For more on key-based expiration, see: - # http://signalvnoise.com/posts/3113-how-key-based-cache-expiration-works - # - # When using this method, you list the cache dependency as the name of the cache, like so: - # - # <% cache project do %> - # All the topics on this project - # <%= render project.topics %> - # <% end %> - # - # This approach will assume that when a new topic is added, you'll touch - # the project. The cache key generated from this call will be something like: - # - # views/projects/123-20120806214154/7a1156131a6928cb0026877f8b749ac9 - # ^class ^id ^updated_at ^template tree digest - # - # The cache is thus automatically bumped whenever the project updated_at is touched. - # - # If your template cache depends on multiple sources (try to avoid this to keep things simple), - # you can name all these dependencies as part of an array: - # - # <% cache [ project, current_user ] do %> - # All the topics on this project - # <%= render project.topics %> - # <% end %> - # - # This will include both records as part of the cache key and updating either of them will - # expire the cache. - # - # ==== \Template digest - # - # The template digest that's added to the cache key is computed by taking an MD5 of the - # contents of the entire template file. This ensures that your caches will automatically - # expire when you change the template file. - # - # Note that the MD5 is taken of the entire template file, not just what's within the - # cache do/end call. So it's possible that changing something outside of that call will - # still expire the cache. - # - # Additionally, the digestor will automatically look through your template file for - # explicit and implicit dependencies, and include those as part of the digest. - # - # The digestor can be bypassed by passing skip_digest: true as an option to the cache call: - # - # <% cache project, skip_digest: true do %> - # All the topics on this project - # <%= render project.topics %> - # <% end %> - # - # ==== Implicit dependencies - # - # Most template dependencies can be derived from calls to render in the template itself. - # Here are some examples of render calls that Cache Digests knows how to decode: - # - # render partial: "comments/comment", collection: commentable.comments - # render "comments/comments" - # render 'comments/comments' - # render('comments/comments') - # - # render "header" translates to render("comments/header") - # - # render(@topic) translates to render("topics/topic") - # render(topics) translates to render("topics/topic") - # render(message.topics) translates to render("topics/topic") - # - # It's not possible to derive all render calls like that, though. - # Here are a few examples of things that can't be derived: - # - # render group_of_attachments - # render @project.documents.where(published: true).order('created_at') - # - # You will have to rewrite those to the explicit form: - # - # render partial: 'attachments/attachment', collection: group_of_attachments - # render partial: 'documents/document', collection: @project.documents.where(published: true).order('created_at') - # - # === Explicit dependencies - # - # Sometimes you'll have template dependencies that can't be derived at all. This is typically - # the case when you have template rendering that happens in helpers. Here's an example: - # - # <%= render_sortable_todolists @project.todolists %> - # - # You'll need to use a special comment format to call those out: - # - # <%# Template Dependency: todolists/todolist %> - # <%= render_sortable_todolists @project.todolists %> - # - # In some cases, like a single table inheritance setup, you might have - # a bunch of explicit dependencies. Instead of writing every template out, - # you can use a wildcard to match any template in a directory: - # - # <%# Template Dependency: events/* %> - # <%= render_categorizable_events @person.events %> - # - # This marks every template in the directory as a dependency. To find those - # templates, the wildcard path must be absolutely defined from app/views or paths - # otherwise added with +prepend_view_path+ or +append_view_path+. - # This way the wildcard for `app/views/recordings/events` would be `recordings/events/*` etc. - # - # The pattern used to match explicit dependencies is /# Template Dependency: (\S+)/, - # so it's important that you type it out just so. - # You can only declare one template dependency per line. - # - # === External dependencies - # - # If you use a helper method, for example, inside a cached block and - # you then update that helper, you'll have to bump the cache as well. - # It doesn't really matter how you do it, but the MD5 of the template file - # must change. One recommendation is to simply be explicit in a comment, like: - # - # <%# Helper Dependency Updated: May 6, 2012 at 6pm %> - # <%= some_helper_method(person) %> - # - # Now all you have to do is change that timestamp when the helper method changes. - # - # === Collection Caching - # - # When rendering a collection of objects that each use the same partial, a `cached` - # option can be passed. - # - # For collections rendered such: - # - # <%= render partial: 'projects/project', collection: @projects, cached: true %> - # - # The `cached: true` will make Action View's rendering read several templates - # from cache at once instead of one call per template. - # - # Templates in the collection not already cached are written to cache. - # - # Works great alongside individual template fragment caching. - # For instance if the template the collection renders is cached like: - # - # # projects/_project.html.erb - # <% cache project do %> - # <%# ... %> - # <% end %> - # - # Any collection renders will find those cached templates when attempting - # to read multiple templates at once. - # - # If your collection cache depends on multiple sources (try to avoid this to keep things simple), - # you can name all these dependencies as part of a block that returns an array: - # - # <%= render partial: 'projects/project', collection: @projects, cached: -> project { [ project, current_user ] } %> - # - # This will include both records as part of the cache key and updating either of them will - # expire the cache. - def cache(name = {}, options = {}, &block) - if controller.respond_to?(:perform_caching) && controller.perform_caching - name_options = options.slice(:skip_digest, :virtual_path) - safe_concat(fragment_for(cache_fragment_name(name, name_options), options, &block)) - else - yield - end - - nil - end - - # Cache fragments of a view if +condition+ is true - # - # <% cache_if admin?, project do %> - # All the topics on this project - # <%= render project.topics %> - # <% end %> - def cache_if(condition, name = {}, options = {}, &block) - if condition - cache(name, options, &block) - else - yield - end - - nil - end - - # Cache fragments of a view unless +condition+ is true - # - # <% cache_unless admin?, project do %> - # All the topics on this project - # <%= render project.topics %> - # <% end %> - def cache_unless(condition, name = {}, options = {}, &block) - cache_if !condition, name, options, &block - end - - # This helper returns the name of a cache key for a given fragment cache - # call. By supplying +skip_digest:+ true to cache, the digestion of cache - # fragments can be manually bypassed. This is useful when cache fragments - # cannot be manually expired unless you know the exact key which is the - # case when using memcached. - # - # The digest will be generated using +virtual_path:+ if it is provided. - # - def cache_fragment_name(name = {}, skip_digest: nil, virtual_path: nil) - if skip_digest - name - else - fragment_name_with_digest(name, virtual_path) - end - end - - private - - def fragment_name_with_digest(name, virtual_path) - virtual_path ||= @virtual_path - if virtual_path - name = controller.url_for(name).split("://").last if name.is_a?(Hash) - digest = Digestor.digest name: virtual_path, finder: lookup_context, dependencies: view_cache_dependencies - [ name, digest ] - else - name - end - end - - def fragment_for(name = {}, options = nil, &block) - if content = read_fragment_for(name, options) - @view_renderer.cache_hits[@virtual_path] = :hit if defined?(@view_renderer) - content - else - @view_renderer.cache_hits[@virtual_path] = :miss if defined?(@view_renderer) - write_fragment_for(name, options, &block) - end - end - - def read_fragment_for(name, options) - controller.read_fragment(name, options) - end - - def write_fragment_for(name, options) - pos = output_buffer.length - yield - output_safe = output_buffer.html_safe? - fragment = output_buffer.slice!(pos..-1) - if output_safe - self.output_buffer = output_buffer.class.new(output_buffer) - end - controller.write_fragment(name, fragment, options) - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/capture_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/capture_helper.rb deleted file mode 100644 index 719592b5c5..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/capture_helper.rb +++ /dev/null @@ -1,210 +0,0 @@ -require "active_support/core_ext/string/output_safety" - -module ActionView - # = Action View Capture Helper - module Helpers - # CaptureHelper exposes methods to let you extract generated markup which - # can be used in other parts of a template or layout file. - # - # It provides a method to capture blocks into variables through capture and - # a way to capture a block of markup for use in a layout through content_for. - module CaptureHelper - # The capture method extracts part of a template as a String object. - # You can then use this object anywhere in your templates, layout, or helpers. - # - # The capture method can be used in ERB templates... - # - # <% @greeting = capture do %> - # Welcome to my shiny new web page! The date and time is - # <%= Time.now %> - # <% end %> - # - # ...and Builder (RXML) templates. - # - # @timestamp = capture do - # "The current timestamp is #{Time.now}." - # end - # - # You can then use that variable anywhere else. For example: - # - # - # <%= @greeting %> - # - # <%= @greeting %> - # - # - # - def capture(*args) - value = nil - buffer = with_output_buffer { value = yield(*args) } - if (string = buffer.presence || value) && string.is_a?(String) - ERB::Util.html_escape string - end - end - - # Calling content_for stores a block of markup in an identifier for later use. - # In order to access this stored content in other templates, helper modules - # or the layout, you would pass the identifier as an argument to content_for. - # - # Note: yield can still be used to retrieve the stored content, but calling - # yield doesn't work in helper modules, while content_for does. - # - # <% content_for :not_authorized do %> - # alert('You are not authorized to do that!') - # <% end %> - # - # You can then use content_for :not_authorized anywhere in your templates. - # - # <%= content_for :not_authorized if current_user.nil? %> - # - # This is equivalent to: - # - # <%= yield :not_authorized if current_user.nil? %> - # - # content_for, however, can also be used in helper modules. - # - # module StorageHelper - # def stored_content - # content_for(:storage) || "Your storage is empty" - # end - # end - # - # This helper works just like normal helpers. - # - # <%= stored_content %> - # - # You can also use the yield syntax alongside an existing call to - # yield in a layout. For example: - # - # <%# This is the layout %> - # - # - # My Website - # <%= yield :script %> - # - # - # <%= yield %> - # - # - # - # And now, we'll create a view that has a content_for call that - # creates the script identifier. - # - # <%# This is our view %> - # Please login! - # - # <% content_for :script do %> - # - # <% end %> - # - # Then, in another view, you could to do something like this: - # - # <%= link_to 'Logout', action: 'logout', remote: true %> - # - # <% content_for :script do %> - # <%= javascript_include_tag :defaults %> - # <% end %> - # - # That will place +script+ tags for your default set of JavaScript files on the page; - # this technique is useful if you'll only be using these scripts in a few views. - # - # Note that content_for concatenates (default) the blocks it is given for a particular - # identifier in order. For example: - # - # <% content_for :navigation do %> - #
  • <%= link_to 'Home', action: 'index' %>
  • - # <% end %> - # - # And in another place: - # - # <% content_for :navigation do %> - #
  • <%= link_to 'Login', action: 'login' %>
  • - # <% end %> - # - # Then, in another template or layout, this code would render both links in order: - # - #
      <%= content_for :navigation %>
    - # - # If the flush parameter is true content_for replaces the blocks it is given. For example: - # - # <% content_for :navigation do %> - #
  • <%= link_to 'Home', action: 'index' %>
  • - # <% end %> - # - # <%# Add some other content, or use a different template: %> - # - # <% content_for :navigation, flush: true do %> - #
  • <%= link_to 'Login', action: 'login' %>
  • - # <% end %> - # - # Then, in another template or layout, this code would render only the last link: - # - #
      <%= content_for :navigation %>
    - # - # Lastly, simple content can be passed as a parameter: - # - # <% content_for :script, javascript_include_tag(:defaults) %> - # - # WARNING: content_for is ignored in caches. So you shouldn't use it for elements that will be fragment cached. - def content_for(name, content = nil, options = {}, &block) - if content || block_given? - if block_given? - options = content if content - content = capture(&block) - end - if content - options[:flush] ? @view_flow.set(name, content) : @view_flow.append(name, content) - end - nil - else - @view_flow.get(name).presence - end - end - - # The same as +content_for+ but when used with streaming flushes - # straight back to the layout. In other words, if you want to - # concatenate several times to the same buffer when rendering a given - # template, you should use +content_for+, if not, use +provide+ to tell - # the layout to stop looking for more contents. - def provide(name, content = nil, &block) - content = capture(&block) if block_given? - result = @view_flow.append!(name, content) if content - result unless content - end - - # content_for? checks whether any content has been captured yet using `content_for`. - # Useful to render parts of your layout differently based on what is in your views. - # - # <%# This is the layout %> - # - # - # My Website - # <%= yield :script %> - # - # - # <%= yield %> - # <%= yield :right_col %> - # - # - def content_for?(name) - @view_flow.get(name).present? - end - - # Use an alternate output buffer for the duration of the block. - # Defaults to a new empty string. - def with_output_buffer(buf = nil) #:nodoc: - unless buf - buf = ActionView::OutputBuffer.new - if output_buffer && output_buffer.respond_to?(:encoding) - buf.force_encoding(output_buffer.encoding) - end - end - self.output_buffer, old_buffer = buf, output_buffer - yield - output_buffer - ensure - self.output_buffer = old_buffer - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/controller_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/controller_helper.rb deleted file mode 100644 index 902c5a47ea..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/controller_helper.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "active_support/core_ext/module/attr_internal" - -module ActionView - module Helpers - # This module keeps all methods and behavior in ActionView - # that simply delegates to the controller. - module ControllerHelper #:nodoc: - attr_internal :controller, :request - - CONTROLLER_DELEGATES = [:request_forgery_protection_token, :params, - :session, :cookies, :response, :headers, :flash, :action_name, - :controller_name, :controller_path] - - delegate(*CONTROLLER_DELEGATES, to: :controller) - - def assign_controller(controller) - if @_controller = controller - @_request = controller.request if controller.respond_to?(:request) - @_config = controller.config.inheritable_copy if controller.respond_to?(:config) - @_default_form_builder = controller.default_form_builder if controller.respond_to?(:default_form_builder) - end - end - - def logger - controller.logger if controller.respond_to?(:logger) - end - - def respond_to?(method_name, include_private = false) - return controller.respond_to?(method_name) if CONTROLLER_DELEGATES.include?(method_name.to_sym) - super - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/csrf_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/csrf_helper.rb deleted file mode 100644 index 2a15d2aa5a..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/csrf_helper.rb +++ /dev/null @@ -1,33 +0,0 @@ -module ActionView - # = Action View CSRF Helper - module Helpers - module CsrfHelper - # Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site - # request forgery protection parameter and token, respectively. - # - # - # <%= csrf_meta_tags %> - # - # - # These are used to generate the dynamic forms that implement non-remote links with - # :method. - # - # You don't need to use these tags for regular forms as they generate their own hidden fields. - # - # For AJAX requests other than GETs, extract the "csrf-token" from the meta-tag and send as the - # "X-CSRF-Token" HTTP header. If you are using jQuery with jquery-rails this happens automatically. - # - def csrf_meta_tags - if protect_against_forgery? - [ - tag("meta", name: "csrf-param", content: request_forgery_protection_token), - tag("meta", name: "csrf-token", content: form_authenticity_token) - ].join("\n").html_safe - end - end - - # For backwards compatibility. - alias csrf_meta_tag csrf_meta_tags - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/date_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/date_helper.rb deleted file mode 100644 index 3f43465aa4..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/date_helper.rb +++ /dev/null @@ -1,1154 +0,0 @@ -require "date" -require "action_view/helpers/tag_helper" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/date/conversions" -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/object/acts_like" -require "active_support/core_ext/object/with_options" - -module ActionView - module Helpers - # = Action View Date Helpers - # - # The Date Helper primarily creates select/option tags for different kinds of dates and times or date and time - # elements. All of the select-type methods share a number of common options that are as follows: - # - # * :prefix - overwrites the default prefix of "date" used for the select names. So specifying "birthday" - # would give \birthday[month] instead of \date[month] if passed to the select_month method. - # * :include_blank - set to true if it should be possible to set an empty date. - # * :discard_type - set to true if you want to discard the type part of the select name. If set to true, - # the select_month method would use simply "date" (which can be overwritten using :prefix) instead - # of \date[month]. - module DateHelper - MINUTES_IN_YEAR = 525600 - MINUTES_IN_QUARTER_YEAR = 131400 - MINUTES_IN_THREE_QUARTERS_YEAR = 394200 - - # Reports the approximate distance in time between two Time, Date or DateTime objects or integers as seconds. - # Pass include_seconds: true if you want more detailed approximations when distance < 1 min, 29 secs. - # Distances are reported based on the following table: - # - # 0 <-> 29 secs # => less than a minute - # 30 secs <-> 1 min, 29 secs # => 1 minute - # 1 min, 30 secs <-> 44 mins, 29 secs # => [2..44] minutes - # 44 mins, 30 secs <-> 89 mins, 29 secs # => about 1 hour - # 89 mins, 30 secs <-> 23 hrs, 59 mins, 29 secs # => about [2..24] hours - # 23 hrs, 59 mins, 30 secs <-> 41 hrs, 59 mins, 29 secs # => 1 day - # 41 hrs, 59 mins, 30 secs <-> 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days - # 29 days, 23 hrs, 59 mins, 30 secs <-> 44 days, 23 hrs, 59 mins, 29 secs # => about 1 month - # 44 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs # => about 2 months - # 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec # => [2..12] months - # 1 yr <-> 1 yr, 3 months # => about 1 year - # 1 yr, 3 months <-> 1 yr, 9 months # => over 1 year - # 1 yr, 9 months <-> 2 yr minus 1 sec # => almost 2 years - # 2 yrs <-> max time or date # => (same rules as 1 yr) - # - # With include_seconds: true and the difference < 1 minute 29 seconds: - # 0-4 secs # => less than 5 seconds - # 5-9 secs # => less than 10 seconds - # 10-19 secs # => less than 20 seconds - # 20-39 secs # => half a minute - # 40-59 secs # => less than a minute - # 60-89 secs # => 1 minute - # - # from_time = Time.now - # distance_of_time_in_words(from_time, from_time + 50.minutes) # => about 1 hour - # distance_of_time_in_words(from_time, 50.minutes.from_now) # => about 1 hour - # distance_of_time_in_words(from_time, from_time + 15.seconds) # => less than a minute - # distance_of_time_in_words(from_time, from_time + 15.seconds, include_seconds: true) # => less than 20 seconds - # distance_of_time_in_words(from_time, 3.years.from_now) # => about 3 years - # distance_of_time_in_words(from_time, from_time + 60.hours) # => 3 days - # distance_of_time_in_words(from_time, from_time + 45.seconds, include_seconds: true) # => less than a minute - # distance_of_time_in_words(from_time, from_time - 45.seconds, include_seconds: true) # => less than a minute - # distance_of_time_in_words(from_time, 76.seconds.from_now) # => 1 minute - # distance_of_time_in_words(from_time, from_time + 1.year + 3.days) # => about 1 year - # distance_of_time_in_words(from_time, from_time + 3.years + 6.months) # => over 3 years - # distance_of_time_in_words(from_time, from_time + 4.years + 9.days + 30.minutes + 5.seconds) # => about 4 years - # - # to_time = Time.now + 6.years + 19.days - # distance_of_time_in_words(from_time, to_time, include_seconds: true) # => about 6 years - # distance_of_time_in_words(to_time, from_time, include_seconds: true) # => about 6 years - # distance_of_time_in_words(Time.now, Time.now) # => less than a minute - # - # With the scope option, you can define a custom scope for Rails - # to look up the translation. - # - # For example you can define the following in your locale (e.g. en.yml). - # - # datetime: - # distance_in_words: - # short: - # about_x_hours: - # one: 'an hour' - # other: '%{count} hours' - # - # See https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/en.yml - # for more examples. - # - # Which will then result in the following: - # - # from_time = Time.now - # distance_of_time_in_words(from_time, from_time + 50.minutes, scope: 'datetime.distance_in_words.short') # => "an hour" - # distance_of_time_in_words(from_time, from_time + 3.hours, scope: 'datetime.distance_in_words.short') # => "3 hours" - def distance_of_time_in_words(from_time, to_time = 0, options = {}) - options = { - scope: :'datetime.distance_in_words' - }.merge!(options) - - from_time = normalize_distance_of_time_argument_to_time(from_time) - to_time = normalize_distance_of_time_argument_to_time(to_time) - from_time, to_time = to_time, from_time if from_time > to_time - distance_in_minutes = ((to_time - from_time) / 60.0).round - distance_in_seconds = (to_time - from_time).round - - I18n.with_options locale: options[:locale], scope: options[:scope] do |locale| - case distance_in_minutes - when 0..1 - return distance_in_minutes == 0 ? - locale.t(:less_than_x_minutes, count: 1) : - locale.t(:x_minutes, count: distance_in_minutes) unless options[:include_seconds] - - case distance_in_seconds - when 0..4 then locale.t :less_than_x_seconds, count: 5 - when 5..9 then locale.t :less_than_x_seconds, count: 10 - when 10..19 then locale.t :less_than_x_seconds, count: 20 - when 20..39 then locale.t :half_a_minute - when 40..59 then locale.t :less_than_x_minutes, count: 1 - else locale.t :x_minutes, count: 1 - end - - when 2...45 then locale.t :x_minutes, count: distance_in_minutes - when 45...90 then locale.t :about_x_hours, count: 1 - # 90 mins up to 24 hours - when 90...1440 then locale.t :about_x_hours, count: (distance_in_minutes.to_f / 60.0).round - # 24 hours up to 42 hours - when 1440...2520 then locale.t :x_days, count: 1 - # 42 hours up to 30 days - when 2520...43200 then locale.t :x_days, count: (distance_in_minutes.to_f / 1440.0).round - # 30 days up to 60 days - when 43200...86400 then locale.t :about_x_months, count: (distance_in_minutes.to_f / 43200.0).round - # 60 days up to 365 days - when 86400...525600 then locale.t :x_months, count: (distance_in_minutes.to_f / 43200.0).round - else - from_year = from_time.year - from_year += 1 if from_time.month >= 3 - to_year = to_time.year - to_year -= 1 if to_time.month < 3 - leap_years = (from_year > to_year) ? 0 : (from_year..to_year).count { |x| Date.leap?(x) } - minute_offset_for_leap_year = leap_years * 1440 - # Discount the leap year days when calculating year distance. - # e.g. if there are 20 leap year days between 2 dates having the same day - # and month then the based on 365 days calculation - # the distance in years will come out to over 80 years when in written - # English it would read better as about 80 years. - minutes_with_offset = distance_in_minutes - minute_offset_for_leap_year - remainder = (minutes_with_offset % MINUTES_IN_YEAR) - distance_in_years = (minutes_with_offset.div MINUTES_IN_YEAR) - if remainder < MINUTES_IN_QUARTER_YEAR - locale.t(:about_x_years, count: distance_in_years) - elsif remainder < MINUTES_IN_THREE_QUARTERS_YEAR - locale.t(:over_x_years, count: distance_in_years) - else - locale.t(:almost_x_years, count: distance_in_years + 1) - end - end - end - end - - # Like distance_of_time_in_words, but where to_time is fixed to Time.now. - # - # time_ago_in_words(3.minutes.from_now) # => 3 minutes - # time_ago_in_words(3.minutes.ago) # => 3 minutes - # time_ago_in_words(Time.now - 15.hours) # => about 15 hours - # time_ago_in_words(Time.now) # => less than a minute - # time_ago_in_words(Time.now, include_seconds: true) # => less than 5 seconds - # - # from_time = Time.now - 3.days - 14.minutes - 25.seconds - # time_ago_in_words(from_time) # => 3 days - # - # from_time = (3.days + 14.minutes + 25.seconds).ago - # time_ago_in_words(from_time) # => 3 days - # - # Note that you cannot pass a Numeric value to time_ago_in_words. - # - def time_ago_in_words(from_time, options = {}) - distance_of_time_in_words(from_time, Time.now, options) - end - - alias_method :distance_of_time_in_words_to_now, :time_ago_in_words - - # Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based - # attribute (identified by +method+) on an object assigned to the template (identified by +object+). - # - # ==== Options - # * :use_month_numbers - Set to true if you want to use month numbers rather than month names (e.g. - # "2" instead of "February"). - # * :use_two_digit_numbers - Set to true if you want to display two digit month and day numbers (e.g. - # "02" instead of "February" and "08" instead of "8"). - # * :use_short_month - Set to true if you want to use abbreviated month names instead of full - # month names (e.g. "Feb" instead of "February"). - # * :add_month_numbers - Set to true if you want to use both month numbers and month names (e.g. - # "2 - February" instead of "February"). - # * :use_month_names - Set to an array with 12 month names if you want to customize month names. - # Note: You can also use Rails' i18n functionality for this. - # * :month_format_string - Set to a format string. The string gets passed keys +:number+ (integer) - # and +:name+ (string). A format string would be something like "%{name} (%02d)" for example. - # See Kernel.sprintf for documentation on format sequences. - # * :date_separator - Specifies a string to separate the date fields. Default is "" (i.e. nothing). - # * :time_separator - Specifies a string to separate the time fields. Default is "" (i.e. nothing). - # * :datetime_separator- Specifies a string to separate the date and time fields. Default is "" (i.e. nothing). - # * :start_year - Set the start year for the year select. Default is Date.today.year - 5 if - # you are creating new record. While editing existing record, :start_year defaults to - # the current selected year minus 5. - # * :end_year - Set the end year for the year select. Default is Date.today.year + 5 if - # you are creating new record. While editing existing record, :end_year defaults to - # the current selected year plus 5. - # * :discard_day - Set to true if you don't want to show a day select. This includes the day - # as a hidden field instead of showing a select field. Also note that this implicitly sets the day to be the - # first of the given month in order to not create invalid dates like 31 February. - # * :discard_month - Set to true if you don't want to show a month select. This includes the month - # as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true. - # * :discard_year - Set to true if you don't want to show a year select. This includes the year - # as a hidden field instead of showing a select field. - # * :order - Set to an array containing :day, :month and :year to - # customize the order in which the select fields are shown. If you leave out any of the symbols, the respective - # select will not be shown (like when you set discard_xxx: true. Defaults to the order defined in - # the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails). - # * :include_blank - Include a blank option in every select field so it's possible to set empty - # dates. - # * :default - Set a default date if the affected date isn't set or is +nil+. - # * :selected - Set a date that overrides the actual value. - # * :disabled - Set to true if you want show the select fields as disabled. - # * :prompt - Set to true (for a generic prompt), a prompt string or a hash of prompt strings - # for :year, :month, :day, :hour, :minute and :second. - # Setting this option prepends a select option with a generic prompt (Day, Month, Year, Hour, Minute, Seconds) - # or the given prompt string. - # * :with_css_classes - Set to true or a hash of strings. Use true if you want to assign generic styles for - # select tags. This automatically set classes 'year', 'month', 'day', 'hour', 'minute' and 'second'. A hash of - # strings for :year, :month, :day, :hour, :minute, :second - # will extend the select type with the given value. Use +html_options+ to modify every select tag in the set. - # * :use_hidden - Set to true if you only want to generate hidden input tags. - # - # If anything is passed in the +html_options+ hash it will be applied to every select tag in the set. - # - # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. - # - # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute. - # date_select("article", "written_on") - # - # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute, - # # with the year in the year drop down box starting at 1995. - # date_select("article", "written_on", start_year: 1995) - # - # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute, - # # with the year in the year drop down box starting at 1995, numbers used for months instead of words, - # # and without a day select box. - # date_select("article", "written_on", start_year: 1995, use_month_numbers: true, - # discard_day: true, include_blank: true) - # - # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute, - # # with two digit numbers used for months and days. - # date_select("article", "written_on", use_two_digit_numbers: true) - # - # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute - # # with the fields ordered as day, month, year rather than month, day, year. - # date_select("article", "written_on", order: [:day, :month, :year]) - # - # # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute - # # lacking a year field. - # date_select("user", "birthday", order: [:month, :day]) - # - # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute - # # which is initially set to the date 3 days from the current date - # date_select("article", "written_on", default: 3.days.from_now) - # - # # Generates a date select that when POSTed is stored in the article variable, in the written_on attribute - # # which is set in the form with today's date, regardless of the value in the Active Record object. - # date_select("article", "written_on", selected: Date.today) - # - # # Generates a date select that when POSTed is stored in the credit_card variable, in the bill_due attribute - # # that will have a default day of 20. - # date_select("credit_card", "bill_due", default: { day: 20 }) - # - # # Generates a date select with custom prompts. - # date_select("article", "written_on", prompt: { day: 'Select day', month: 'Select month', year: 'Select year' }) - # - # The selects are prepared for multi-parameter assignment to an Active Record object. - # - # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that - # all month choices are valid. - def date_select(object_name, method, options = {}, html_options = {}) - Tags::DateSelect.new(object_name, method, self, options, html_options).render - end - - # Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a - # specified time-based attribute (identified by +method+) on an object assigned to the template (identified by - # +object+). You can include the seconds with :include_seconds. You can get hours in the AM/PM format - # with :ampm option. - # - # This method will also generate 3 input hidden tags, for the actual year, month and day unless the option - # :ignore_date is set to +true+. If you set the :ignore_date to +true+, you must have a - # +date_select+ on the same method within the form otherwise an exception will be raised. - # - # If anything is passed in the html_options hash it will be applied to every select tag in the set. - # - # # Creates a time select tag that, when POSTed, will be stored in the article variable in the sunrise attribute. - # time_select("article", "sunrise") - # - # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the article variables in - # # the sunrise attribute. - # time_select("article", "start_time", include_seconds: true) - # - # # You can set the :minute_step to 15 which will give you: 00, 15, 30, and 45. - # time_select 'game', 'game_time', {minute_step: 15} - # - # # Creates a time select tag with a custom prompt. Use prompt: true for generic prompts. - # time_select("article", "written_on", prompt: {hour: 'Choose hour', minute: 'Choose minute', second: 'Choose seconds'}) - # time_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours - # time_select("article", "written_on", prompt: true) # generic prompts for all - # - # # You can set :ampm option to true which will show the hours as: 12 PM, 01 AM .. 11 PM. - # time_select 'game', 'game_time', {ampm: true} - # - # The selects are prepared for multi-parameter assignment to an Active Record object. - # - # Note: If the day is not included as an option but the month is, the day will be set to the 1st to ensure that - # all month choices are valid. - def time_select(object_name, method, options = {}, html_options = {}) - Tags::TimeSelect.new(object_name, method, self, options, html_options).render - end - - # Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a - # specified datetime-based attribute (identified by +method+) on an object assigned to the template (identified - # by +object+). - # - # If anything is passed in the html_options hash it will be applied to every select tag in the set. - # - # # Generates a datetime select that, when POSTed, will be stored in the article variable in the written_on - # # attribute. - # datetime_select("article", "written_on") - # - # # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the - # # article variable in the written_on attribute. - # datetime_select("article", "written_on", start_year: 1995) - # - # # Generates a datetime select with a default value of 3 days from the current time that, when POSTed, will - # # be stored in the trip variable in the departing attribute. - # datetime_select("trip", "departing", default: 3.days.from_now) - # - # # Generate a datetime select with hours in the AM/PM format - # datetime_select("article", "written_on", ampm: true) - # - # # Generates a datetime select that discards the type that, when POSTed, will be stored in the article variable - # # as the written_on attribute. - # datetime_select("article", "written_on", discard_type: true) - # - # # Generates a datetime select with a custom prompt. Use prompt: true for generic prompts. - # datetime_select("article", "written_on", prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'}) - # datetime_select("article", "written_on", prompt: {hour: true}) # generic prompt for hours - # datetime_select("article", "written_on", prompt: true) # generic prompts for all - # - # The selects are prepared for multi-parameter assignment to an Active Record object. - def datetime_select(object_name, method, options = {}, html_options = {}) - Tags::DatetimeSelect.new(object_name, method, self, options, html_options).render - end - - # Returns a set of HTML select-tags (one for year, month, day, hour, minute, and second) pre-selected with the - # +datetime+. It's also possible to explicitly set the order of the tags using the :order option with - # an array of symbols :year, :month and :day in the desired order. If you do not - # supply a Symbol, it will be appended onto the :order passed in. You can also add - # :date_separator, :datetime_separator and :time_separator keys to the +options+ to - # control visual display of the elements. - # - # If anything is passed in the html_options hash it will be applied to every select tag in the set. - # - # my_date_time = Time.now + 4.days - # - # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today). - # select_datetime(my_date_time) - # - # # Generates a datetime select that defaults to today (no specified datetime) - # select_datetime() - # - # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) - # # with the fields ordered year, month, day rather than month, day, year. - # select_datetime(my_date_time, order: [:year, :month, :day]) - # - # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) - # # with a '/' between each date field. - # select_datetime(my_date_time, date_separator: '/') - # - # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) - # # with a date fields separated by '/', time fields separated by '' and the date and time fields - # # separated by a comma (','). - # select_datetime(my_date_time, date_separator: '/', time_separator: '', datetime_separator: ',') - # - # # Generates a datetime select that discards the type of the field and defaults to the datetime in - # # my_date_time (four days after today) - # select_datetime(my_date_time, discard_type: true) - # - # # Generate a datetime field with hours in the AM/PM format - # select_datetime(my_date_time, ampm: true) - # - # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) - # # prefixed with 'payday' rather than 'date' - # select_datetime(my_date_time, prefix: 'payday') - # - # # Generates a datetime select with a custom prompt. Use prompt: true for generic prompts. - # select_datetime(my_date_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'}) - # select_datetime(my_date_time, prompt: {hour: true}) # generic prompt for hours - # select_datetime(my_date_time, prompt: true) # generic prompts for all - def select_datetime(datetime = Time.current, options = {}, html_options = {}) - DateTimeSelector.new(datetime, options, html_options).select_datetime - end - - # Returns a set of HTML select-tags (one for year, month, and day) pre-selected with the +date+. - # It's possible to explicitly set the order of the tags using the :order option with an array of - # symbols :year, :month and :day in the desired order. - # If the array passed to the :order option does not contain all the three symbols, all tags will be hidden. - # - # If anything is passed in the html_options hash it will be applied to every select tag in the set. - # - # my_date = Time.now + 6.days - # - # # Generates a date select that defaults to the date in my_date (six days after today). - # select_date(my_date) - # - # # Generates a date select that defaults to today (no specified date). - # select_date() - # - # # Generates a date select that defaults to the date in my_date (six days after today) - # # with the fields ordered year, month, day rather than month, day, year. - # select_date(my_date, order: [:year, :month, :day]) - # - # # Generates a date select that discards the type of the field and defaults to the date in - # # my_date (six days after today). - # select_date(my_date, discard_type: true) - # - # # Generates a date select that defaults to the date in my_date, - # # which has fields separated by '/'. - # select_date(my_date, date_separator: '/') - # - # # Generates a date select that defaults to the datetime in my_date (six days after today) - # # prefixed with 'payday' rather than 'date'. - # select_date(my_date, prefix: 'payday') - # - # # Generates a date select with a custom prompt. Use prompt: true for generic prompts. - # select_date(my_date, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'}) - # select_date(my_date, prompt: {hour: true}) # generic prompt for hours - # select_date(my_date, prompt: true) # generic prompts for all - def select_date(date = Date.current, options = {}, html_options = {}) - DateTimeSelector.new(date, options, html_options).select_date - end - - # Returns a set of HTML select-tags (one for hour and minute). - # You can set :time_separator key to format the output, and - # the :include_seconds option to include an input for seconds. - # - # If anything is passed in the html_options hash it will be applied to every select tag in the set. - # - # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds - # - # # Generates a time select that defaults to the time in my_time. - # select_time(my_time) - # - # # Generates a time select that defaults to the current time (no specified time). - # select_time() - # - # # Generates a time select that defaults to the time in my_time, - # # which has fields separated by ':'. - # select_time(my_time, time_separator: ':') - # - # # Generates a time select that defaults to the time in my_time, - # # that also includes an input for seconds. - # select_time(my_time, include_seconds: true) - # - # # Generates a time select that defaults to the time in my_time, that has fields - # # separated by ':' and includes an input for seconds. - # select_time(my_time, time_separator: ':', include_seconds: true) - # - # # Generate a time select field with hours in the AM/PM format - # select_time(my_time, ampm: true) - # - # # Generates a time select field with hours that range from 2 to 14 - # select_time(my_time, start_hour: 2, end_hour: 14) - # - # # Generates a time select with a custom prompt. Use :prompt to true for generic prompts. - # select_time(my_time, prompt: {day: 'Choose day', month: 'Choose month', year: 'Choose year'}) - # select_time(my_time, prompt: {hour: true}) # generic prompt for hours - # select_time(my_time, prompt: true) # generic prompts for all - def select_time(datetime = Time.current, options = {}, html_options = {}) - DateTimeSelector.new(datetime, options, html_options).select_time - end - - # Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. - # The datetime can be either a +Time+ or +DateTime+ object or an integer. - # Override the field name using the :field_name option, 'second' by default. - # - # my_time = Time.now + 16.seconds - # - # # Generates a select field for seconds that defaults to the seconds for the time in my_time. - # select_second(my_time) - # - # # Generates a select field for seconds that defaults to the number given. - # select_second(33) - # - # # Generates a select field for seconds that defaults to the seconds for the time in my_time - # # that is named 'interval' rather than 'second'. - # select_second(my_time, field_name: 'interval') - # - # # Generates a select field for seconds with a custom prompt. Use prompt: true for a - # # generic prompt. - # select_second(14, prompt: 'Choose seconds') - def select_second(datetime, options = {}, html_options = {}) - DateTimeSelector.new(datetime, options, html_options).select_second - end - - # Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. - # Also can return a select tag with options by minute_step from 0 through 59 with the 00 minute - # selected. The datetime can be either a +Time+ or +DateTime+ object or an integer. - # Override the field name using the :field_name option, 'minute' by default. - # - # my_time = Time.now + 10.minutes - # - # # Generates a select field for minutes that defaults to the minutes for the time in my_time. - # select_minute(my_time) - # - # # Generates a select field for minutes that defaults to the number given. - # select_minute(14) - # - # # Generates a select field for minutes that defaults to the minutes for the time in my_time - # # that is named 'moment' rather than 'minute'. - # select_minute(my_time, field_name: 'moment') - # - # # Generates a select field for minutes with a custom prompt. Use prompt: true for a - # # generic prompt. - # select_minute(14, prompt: 'Choose minutes') - def select_minute(datetime, options = {}, html_options = {}) - DateTimeSelector.new(datetime, options, html_options).select_minute - end - - # Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. - # The datetime can be either a +Time+ or +DateTime+ object or an integer. - # Override the field name using the :field_name option, 'hour' by default. - # - # my_time = Time.now + 6.hours - # - # # Generates a select field for hours that defaults to the hour for the time in my_time. - # select_hour(my_time) - # - # # Generates a select field for hours that defaults to the number given. - # select_hour(13) - # - # # Generates a select field for hours that defaults to the hour for the time in my_time - # # that is named 'stride' rather than 'hour'. - # select_hour(my_time, field_name: 'stride') - # - # # Generates a select field for hours with a custom prompt. Use prompt: true for a - # # generic prompt. - # select_hour(13, prompt: 'Choose hour') - # - # # Generate a select field for hours in the AM/PM format - # select_hour(my_time, ampm: true) - # - # # Generates a select field that includes options for hours from 2 to 14. - # select_hour(my_time, start_hour: 2, end_hour: 14) - def select_hour(datetime, options = {}, html_options = {}) - DateTimeSelector.new(datetime, options, html_options).select_hour - end - - # Returns a select tag with options for each of the days 1 through 31 with the current day selected. - # The date can also be substituted for a day number. - # If you want to display days with a leading zero set the :use_two_digit_numbers key in +options+ to true. - # Override the field name using the :field_name option, 'day' by default. - # - # my_date = Time.now + 2.days - # - # # Generates a select field for days that defaults to the day for the date in my_date. - # select_day(my_date) - # - # # Generates a select field for days that defaults to the number given. - # select_day(5) - # - # # Generates a select field for days that defaults to the number given, but displays it with two digits. - # select_day(5, use_two_digit_numbers: true) - # - # # Generates a select field for days that defaults to the day for the date in my_date - # # that is named 'due' rather than 'day'. - # select_day(my_date, field_name: 'due') - # - # # Generates a select field for days with a custom prompt. Use prompt: true for a - # # generic prompt. - # select_day(5, prompt: 'Choose day') - def select_day(date, options = {}, html_options = {}) - DateTimeSelector.new(date, options, html_options).select_day - end - - # Returns a select tag with options for each of the months January through December with the current month - # selected. The month names are presented as keys (what's shown to the user) and the month numbers (1-12) are - # used as values (what's submitted to the server). It's also possible to use month numbers for the presentation - # instead of names -- set the :use_month_numbers key in +options+ to true for this to happen. If you - # want both numbers and names, set the :add_month_numbers key in +options+ to true. If you would prefer - # to show month names as abbreviations, set the :use_short_month key in +options+ to true. If you want - # to use your own month names, set the :use_month_names key in +options+ to an array of 12 month names. - # If you want to display months with a leading zero set the :use_two_digit_numbers key in +options+ to true. - # Override the field name using the :field_name option, 'month' by default. - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "January", "March". - # select_month(Date.today) - # - # # Generates a select field for months that defaults to the current month that - # # is named "start" rather than "month". - # select_month(Date.today, field_name: 'start') - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "1", "3". - # select_month(Date.today, use_month_numbers: true) - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "1 - January", "3 - March". - # select_month(Date.today, add_month_numbers: true) - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "Jan", "Mar". - # select_month(Date.today, use_short_month: true) - # - # # Generates a select field for months that defaults to the current month that - # # will use keys like "Januar", "Marts." - # select_month(Date.today, use_month_names: %w(Januar Februar Marts ...)) - # - # # Generates a select field for months that defaults to the current month that - # # will use keys with two digit numbers like "01", "03". - # select_month(Date.today, use_two_digit_numbers: true) - # - # # Generates a select field for months with a custom prompt. Use prompt: true for a - # # generic prompt. - # select_month(14, prompt: 'Choose month') - def select_month(date, options = {}, html_options = {}) - DateTimeSelector.new(date, options, html_options).select_month - end - - # Returns a select tag with options for each of the five years on each side of the current, which is selected. - # The five year radius can be changed using the :start_year and :end_year keys in the - # +options+. Both ascending and descending year lists are supported by making :start_year less than or - # greater than :end_year. The date can also be substituted for a year given as a number. - # Override the field name using the :field_name option, 'year' by default. - # - # # Generates a select field for years that defaults to the current year that - # # has ascending year values. - # select_year(Date.today, start_year: 1992, end_year: 2007) - # - # # Generates a select field for years that defaults to the current year that - # # is named 'birth' rather than 'year'. - # select_year(Date.today, field_name: 'birth') - # - # # Generates a select field for years that defaults to the current year that - # # has descending year values. - # select_year(Date.today, start_year: 2005, end_year: 1900) - # - # # Generates a select field for years that defaults to the year 2006 that - # # has ascending year values. - # select_year(2006, start_year: 2000, end_year: 2010) - # - # # Generates a select field for years with a custom prompt. Use prompt: true for a - # # generic prompt. - # select_year(14, prompt: 'Choose year') - def select_year(date, options = {}, html_options = {}) - DateTimeSelector.new(date, options, html_options).select_year - end - - # Returns an HTML time tag for the given date or time. - # - # time_tag Date.today # => - # - # time_tag Time.now # => - # - # time_tag Date.yesterday, 'Yesterday' # => - # - # time_tag Date.today, pubdate: true # => - # - # time_tag Date.today, datetime: Date.today.strftime('%G-W%V') # => - # - # - # <%= time_tag Time.now do %> - # Right now - # <% end %> - # # => - def time_tag(date_or_time, *args, &block) - options = args.extract_options! - format = options.delete(:format) || :long - content = args.first || I18n.l(date_or_time, format: format) - datetime = date_or_time.acts_like?(:time) ? date_or_time.xmlschema : date_or_time.iso8601 - - content_tag("time".freeze, content, options.reverse_merge(datetime: datetime), &block) - end - - private - - def normalize_distance_of_time_argument_to_time(value) - if value.is_a?(Numeric) - Time.at(value) - elsif value.respond_to?(:to_time) - value.to_time - else - raise ArgumentError, "#{value.inspect} can't be converted to a Time value" - end - end - end - - class DateTimeSelector #:nodoc: - include ActionView::Helpers::TagHelper - - DEFAULT_PREFIX = "date".freeze - POSITION = { - year: 1, month: 2, day: 3, hour: 4, minute: 5, second: 6 - }.freeze - - AMPM_TRANSLATION = Hash[ - [[0, "12 AM"], [1, "01 AM"], [2, "02 AM"], [3, "03 AM"], - [4, "04 AM"], [5, "05 AM"], [6, "06 AM"], [7, "07 AM"], - [8, "08 AM"], [9, "09 AM"], [10, "10 AM"], [11, "11 AM"], - [12, "12 PM"], [13, "01 PM"], [14, "02 PM"], [15, "03 PM"], - [16, "04 PM"], [17, "05 PM"], [18, "06 PM"], [19, "07 PM"], - [20, "08 PM"], [21, "09 PM"], [22, "10 PM"], [23, "11 PM"]] - ].freeze - - def initialize(datetime, options = {}, html_options = {}) - @options = options.dup - @html_options = html_options.dup - @datetime = datetime - @options[:datetime_separator] ||= " — " - @options[:time_separator] ||= " : " - end - - def select_datetime - order = date_order.dup - order -= [:hour, :minute, :second] - @options[:discard_year] ||= true unless order.include?(:year) - @options[:discard_month] ||= true unless order.include?(:month) - @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day) - @options[:discard_minute] ||= true if @options[:discard_hour] - @options[:discard_second] ||= true unless @options[:include_seconds] && !@options[:discard_minute] - - set_day_if_discarded - - if @options[:tag] && @options[:ignore_date] - select_time - else - [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) } - order += [:hour, :minute, :second] unless @options[:discard_hour] - - build_selects_from_types(order) - end - end - - def select_date - order = date_order.dup - - @options[:discard_hour] = true - @options[:discard_minute] = true - @options[:discard_second] = true - - @options[:discard_year] ||= true unless order.include?(:year) - @options[:discard_month] ||= true unless order.include?(:month) - @options[:discard_day] ||= true if @options[:discard_month] || !order.include?(:day) - - set_day_if_discarded - - [:day, :month, :year].each { |o| order.unshift(o) unless order.include?(o) } - - build_selects_from_types(order) - end - - def select_time - order = [] - - @options[:discard_month] = true - @options[:discard_year] = true - @options[:discard_day] = true - @options[:discard_second] ||= true unless @options[:include_seconds] - - order += [:year, :month, :day] unless @options[:ignore_date] - - order += [:hour, :minute] - order << :second if @options[:include_seconds] - - build_selects_from_types(order) - end - - def select_second - if @options[:use_hidden] || @options[:discard_second] - build_hidden(:second, sec) if @options[:include_seconds] - else - build_options_and_select(:second, sec) - end - end - - def select_minute - if @options[:use_hidden] || @options[:discard_minute] - build_hidden(:minute, min) - else - build_options_and_select(:minute, min, step: @options[:minute_step]) - end - end - - def select_hour - if @options[:use_hidden] || @options[:discard_hour] - build_hidden(:hour, hour) - else - options = {} - options[:ampm] = @options[:ampm] || false - options[:start] = @options[:start_hour] || 0 - options[:end] = @options[:end_hour] || 23 - build_options_and_select(:hour, hour, options) - end - end - - def select_day - if @options[:use_hidden] || @options[:discard_day] - build_hidden(:day, day || 1) - else - build_options_and_select(:day, day, start: 1, end: 31, leading_zeros: false, use_two_digit_numbers: @options[:use_two_digit_numbers]) - end - end - - def select_month - if @options[:use_hidden] || @options[:discard_month] - build_hidden(:month, month || 1) - else - month_options = [] - 1.upto(12) do |month_number| - options = { value: month_number } - options[:selected] = "selected" if month == month_number - month_options << content_tag("option".freeze, month_name(month_number), options) + "\n" - end - build_select(:month, month_options.join) - end - end - - def select_year - if !@datetime || @datetime == 0 - val = "1" - middle_year = Date.today.year - else - val = middle_year = year - end - - if @options[:use_hidden] || @options[:discard_year] - build_hidden(:year, val) - else - options = {} - options[:start] = @options[:start_year] || middle_year - 5 - options[:end] = @options[:end_year] || middle_year + 5 - options[:step] = options[:start] < options[:end] ? 1 : -1 - options[:leading_zeros] = false - options[:max_years_allowed] = @options[:max_years_allowed] || 1000 - - if (options[:end] - options[:start]).abs > options[:max_years_allowed] - raise ArgumentError, "There are too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter." - end - - build_options_and_select(:year, val, options) - end - end - - private - %w( sec min hour day month year ).each do |method| - define_method(method) do - case @datetime - when Hash then @datetime[method.to_sym] - when Numeric then @datetime - when nil then nil - else @datetime.send(method) - end - end - end - - # If the day is hidden, the day should be set to the 1st so all month and year choices are - # valid. Otherwise, February 31st or February 29th, 2011 can be selected, which are invalid. - def set_day_if_discarded - if @datetime && @options[:discard_day] - @datetime = @datetime.change(day: 1) - end - end - - # Returns translated month names, but also ensures that a custom month - # name array has a leading +nil+ element. - def month_names - @month_names ||= begin - month_names = @options[:use_month_names] || translated_month_names - month_names.unshift(nil) if month_names.size < 13 - month_names - end - end - - # Returns translated month names. - # => [nil, "January", "February", "March", - # "April", "May", "June", "July", - # "August", "September", "October", - # "November", "December"] - # - # If :use_short_month option is set - # => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", - # "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - def translated_month_names - key = @options[:use_short_month] ? :'date.abbr_month_names' : :'date.month_names' - I18n.translate(key, locale: @options[:locale]) - end - - # Looks up month names by number (1-based): - # - # month_name(1) # => "January" - # - # If the :use_month_numbers option is passed: - # - # month_name(1) # => 1 - # - # If the :use_two_month_numbers option is passed: - # - # month_name(1) # => '01' - # - # If the :add_month_numbers option is passed: - # - # month_name(1) # => "1 - January" - # - # If the :month_format_string option is passed: - # - # month_name(1) # => "January (01)" - # - # depending on the format string. - def month_name(number) - if @options[:use_month_numbers] - number - elsif @options[:use_two_digit_numbers] - "%02d" % number - elsif @options[:add_month_numbers] - "#{number} - #{month_names[number]}" - elsif format_string = @options[:month_format_string] - format_string % { number: number, name: month_names[number] } - else - month_names[number] - end - end - - def date_order - @date_order ||= @options[:order] || translated_date_order - end - - def translated_date_order - date_order = I18n.translate(:'date.order', locale: @options[:locale], default: []) - date_order = date_order.map(&:to_sym) - - forbidden_elements = date_order - [:year, :month, :day] - if forbidden_elements.any? - raise StandardError, - "#{@options[:locale]}.date.order only accepts :year, :month and :day" - end - - date_order - end - - # Build full select tag from date type and options. - def build_options_and_select(type, selected, options = {}) - build_select(type, build_options(selected, options)) - end - - # Build select option HTML from date value and options. - # build_options(15, start: 1, end: 31) - # => " - # - # ..." - # - # If use_two_digit_numbers: true option is passed - # build_options(15, start: 1, end: 31, use_two_digit_numbers: true) - # => " - # - # ..." - # - # If :step options is passed - # build_options(15, start: 1, end: 31, step: 2) - # => " - # - # ..." - def build_options(selected, options = {}) - options = { - leading_zeros: true, ampm: false, use_two_digit_numbers: false - }.merge!(options) - - start = options.delete(:start) || 0 - stop = options.delete(:end) || 59 - step = options.delete(:step) || 1 - leading_zeros = options.delete(:leading_zeros) - - select_options = [] - start.step(stop, step) do |i| - value = leading_zeros ? sprintf("%02d", i) : i - tag_options = { value: value } - tag_options[:selected] = "selected" if selected == i - text = options[:use_two_digit_numbers] ? sprintf("%02d", i) : value - text = options[:ampm] ? AMPM_TRANSLATION[i] : text - select_options << content_tag("option".freeze, text, tag_options) - end - - (select_options.join("\n") + "\n").html_safe - end - - # Builds select tag from date type and HTML select options. - # build_select(:month, "...") - # => "" - def build_select(type, select_options_as_html) - select_options = { - id: input_id_from_type(type), - name: input_name_from_type(type) - }.merge!(@html_options) - select_options[:disabled] = "disabled" if @options[:disabled] - select_options[:class] = css_class_attribute(type, select_options[:class], @options[:with_css_classes]) if @options[:with_css_classes] - - select_html = "\n" - select_html << content_tag("option".freeze, "", value: "") + "\n" if @options[:include_blank] - select_html << prompt_option_tag(type, @options[:prompt]) + "\n" if @options[:prompt] - select_html << select_options_as_html - - (content_tag("select".freeze, select_html.html_safe, select_options) + "\n").html_safe - end - - # Builds the css class value for the select element - # css_class_attribute(:year, 'date optional', { year: 'my-year' }) - # => "date optional my-year" - def css_class_attribute(type, html_options_class, options) # :nodoc: - css_class = \ - case options - when Hash - options[type.to_sym] - else - type - end - - [html_options_class, css_class].compact.join(" ") - end - - # Builds a prompt option tag with supplied options or from default options. - # prompt_option_tag(:month, prompt: 'Select month') - # => "" - def prompt_option_tag(type, options) - prompt = \ - case options - when Hash - default_options = { year: false, month: false, day: false, hour: false, minute: false, second: false } - default_options.merge!(options)[type.to_sym] - when String - options - else - I18n.translate(:"datetime.prompts.#{type}", locale: @options[:locale]) - end - - prompt ? content_tag("option".freeze, prompt, value: "") : "" - end - - # Builds hidden input tag for date part and value. - # build_hidden(:year, 2008) - # => "" - def build_hidden(type, value) - select_options = { - type: "hidden", - id: input_id_from_type(type), - name: input_name_from_type(type), - value: value - }.merge!(@html_options.slice(:disabled)) - select_options[:disabled] = "disabled" if @options[:disabled] - - tag(:input, select_options) + "\n".html_safe - end - - # Returns the name attribute for the input tag. - # => post[written_on(1i)] - def input_name_from_type(type) - prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX - prefix += "[#{@options[:index]}]" if @options.has_key?(:index) - - field_name = @options[:field_name] || type.to_s - if @options[:include_position] - field_name += "(#{ActionView::Helpers::DateTimeSelector::POSITION[type]}i)" - end - - @options[:discard_type] ? prefix : "#{prefix}[#{field_name}]" - end - - # Returns the id attribute for the input tag. - # => "post_written_on_1i" - def input_id_from_type(type) - id = input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, "_").gsub(/[\]\)]/, "") - id = @options[:namespace] + "_" + id if @options[:namespace] - - id - end - - # Given an ordering of datetime components, create the selection HTML - # and join them with their appropriate separators. - def build_selects_from_types(order) - select = "" - first_visible = order.find { |type| !@options[:"discard_#{type}"] } - order.reverse_each do |type| - separator = separator(type) unless type == first_visible # don't add before first visible field - select.insert(0, separator.to_s + send("select_#{type}").to_s) - end - select.html_safe - end - - # Returns the separator for a given datetime component. - def separator(type) - return "" if @options[:use_hidden] - - case type - when :year, :month, :day - @options[:"discard_#{type}"] ? "" : @options[:date_separator] - when :hour - (@options[:discard_year] && @options[:discard_day]) ? "" : @options[:datetime_separator] - when :minute, :second - @options[:"discard_#{type}"] ? "" : @options[:time_separator] - end - end - end - - class FormBuilder - # Wraps ActionView::Helpers::DateHelper#date_select for form builders: - # - # <%= form_for @person do |f| %> - # <%= f.date_select :birth_date %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def date_select(method, options = {}, html_options = {}) - @template.date_select(@object_name, method, objectify_options(options), html_options) - end - - # Wraps ActionView::Helpers::DateHelper#time_select for form builders: - # - # <%= form_for @race do |f| %> - # <%= f.time_select :average_lap %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def time_select(method, options = {}, html_options = {}) - @template.time_select(@object_name, method, objectify_options(options), html_options) - end - - # Wraps ActionView::Helpers::DateHelper#datetime_select for form builders: - # - # <%= form_for @person do |f| %> - # <%= f.datetime_select :last_request_at %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def datetime_select(method, options = {}, html_options = {}) - @template.datetime_select(@object_name, method, objectify_options(options), html_options) - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/debug_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/debug_helper.rb deleted file mode 100644 index f61ca2c9c2..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/debug_helper.rb +++ /dev/null @@ -1,34 +0,0 @@ -module ActionView - # = Action View Debug Helper - # - # Provides a set of methods for making it easier to debug Rails objects. - module Helpers - module DebugHelper - include TagHelper - - # Returns a YAML representation of +object+ wrapped with
     and 
    . - # If the object cannot be converted to YAML using +to_yaml+, +inspect+ will be called instead. - # Useful for inspecting an object at the time of rendering. - # - # @user = User.new({ username: 'testing', password: 'xyz', age: 42}) - # debug(@user) - # # => - #
    --- !ruby/object:User
    -      #   attributes:
    -      #     updated_at:
    -      #     username: testing
    -      #     age: 42
    -      #     password: xyz
    -      #     created_at:
    -      #   
    - def debug(object) - Marshal::dump(object) - object = ERB::Util.html_escape(object.to_yaml) - content_tag(:pre, object, class: "debug_dump") - rescue # errors from Marshal or YAML - # Object couldn't be dumped, perhaps because of singleton methods -- this is the fallback - content_tag(:code, object.inspect, class: "debug_dump") - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_helper.rb deleted file mode 100644 index edf8581bda..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_helper.rb +++ /dev/null @@ -1,2354 +0,0 @@ -require "cgi" -require "action_view/helpers/date_helper" -require "action_view/helpers/tag_helper" -require "action_view/helpers/form_tag_helper" -require "action_view/helpers/active_model_helper" -require "action_view/model_naming" -require "action_view/record_identifier" -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/string/output_safety" -require "active_support/core_ext/string/inflections" - -module ActionView - # = Action View Form Helpers - module Helpers - # Form helpers are designed to make working with resources much easier - # compared to using vanilla HTML. - # - # Typically, a form designed to create or update a resource reflects the - # identity of the resource in several ways: (i) the url that the form is - # sent to (the form element's +action+ attribute) should result in a request - # being routed to the appropriate controller action (with the appropriate :id - # parameter in the case of an existing resource), (ii) input fields should - # be named in such a way that in the controller their values appear in the - # appropriate places within the +params+ hash, and (iii) for an existing record, - # when the form is initially displayed, input fields corresponding to attributes - # of the resource should show the current values of those attributes. - # - # In Rails, this is usually achieved by creating the form using +form_for+ and - # a number of related helper methods. +form_for+ generates an appropriate form - # tag and yields a form builder object that knows the model the form is about. - # Input fields are created by calling methods defined on the form builder, which - # means they are able to generate the appropriate names and default values - # corresponding to the model attributes, as well as convenient IDs, etc. - # Conventions in the generated field names allow controllers to receive form data - # nicely structured in +params+ with no effort on your side. - # - # For example, to create a new person you typically set up a new instance of - # +Person+ in the PeopleController#new action, @person, and - # in the view template pass that object to +form_for+: - # - # <%= form_for @person do |f| %> - # <%= f.label :first_name %>: - # <%= f.text_field :first_name %>
    - # - # <%= f.label :last_name %>: - # <%= f.text_field :last_name %>
    - # - # <%= f.submit %> - # <% end %> - # - # The HTML generated for this would be (modulus formatting): - # - #
    - # - # : - #
    - # - # : - #
    - # - # - #
    - # - # As you see, the HTML reflects knowledge about the resource in several spots, - # like the path the form should be submitted to, or the names of the input fields. - # - # In particular, thanks to the conventions followed in the generated field names, the - # controller gets a nested hash params[:person] with the person attributes - # set in the form. That hash is ready to be passed to Person.new: - # - # @person = Person.new(params[:person]) - # if @person.save - # # success - # else - # # error handling - # end - # - # Interestingly, the exact same view code in the previous example can be used to edit - # a person. If @person is an existing record with name "John Smith" and ID 256, - # the code above as is would yield instead: - # - #
    - # - # - # : - #
    - # - # : - #
    - # - # - #
    - # - # Note that the endpoint, default values, and submit button label are tailored for @person. - # That works that way because the involved helpers know whether the resource is a new record or not, - # and generate HTML accordingly. - # - # The controller would receive the form data again in params[:person], ready to be - # passed to Person#update: - # - # if @person.update(params[:person]) - # # success - # else - # # error handling - # end - # - # That's how you typically work with resources. - module FormHelper - extend ActiveSupport::Concern - - include FormTagHelper - include UrlHelper - include ModelNaming - include RecordIdentifier - - attr_internal :default_form_builder - - # Creates a form that allows the user to create or update the attributes - # of a specific model object. - # - # The method can be used in several slightly different ways, depending on - # how much you wish to rely on Rails to infer automatically from the model - # how the form should be constructed. For a generic model object, a form - # can be created by passing +form_for+ a string or symbol representing - # the object we are concerned with: - # - # <%= form_for :person do |f| %> - # First name: <%= f.text_field :first_name %>
    - # Last name : <%= f.text_field :last_name %>
    - # Biography : <%= f.text_area :biography %>
    - # Admin? : <%= f.check_box :admin %>
    - # <%= f.submit %> - # <% end %> - # - # The variable +f+ yielded to the block is a FormBuilder object that - # incorporates the knowledge about the model object represented by - # :person passed to +form_for+. Methods defined on the FormBuilder - # are used to generate fields bound to this model. Thus, for example, - # - # <%= f.text_field :first_name %> - # - # will get expanded to - # - # <%= text_field :person, :first_name %> - # - # which results in an HTML tag whose +name+ attribute is - # person[first_name]. This means that when the form is submitted, - # the value entered by the user will be available in the controller as - # params[:person][:first_name]. - # - # For fields generated in this way using the FormBuilder, - # if :person also happens to be the name of an instance variable - # @person, the default value of the field shown when the form is - # initially displayed (e.g. in the situation where you are editing an - # existing record) will be the value of the corresponding attribute of - # @person. - # - # The rightmost argument to +form_for+ is an - # optional hash of options - - # - # * :url - The URL the form is to be submitted to. This may be - # represented in the same way as values passed to +url_for+ or +link_to+. - # So for example you may use a named route directly. When the model is - # represented by a string or symbol, as in the example above, if the - # :url option is not specified, by default the form will be - # sent back to the current url (We will describe below an alternative - # resource-oriented usage of +form_for+ in which the URL does not need - # to be specified explicitly). - # * :namespace - A namespace for your form to ensure uniqueness of - # id attributes on form elements. The namespace attribute will be prefixed - # with underscore on the generated HTML id. - # * :method - The method to use when submitting the form, usually - # either "get" or "post". If "patch", "put", "delete", or another verb - # is used, a hidden input with name _method is added to - # simulate the verb over post. - # * :authenticity_token - Authenticity token to use in the form. - # Use only if you need to pass custom authenticity token string, or to - # not add authenticity_token field at all (by passing false). - # Remote forms may omit the embedded authenticity token by setting - # config.action_view.embed_authenticity_token_in_remote_forms = false. - # This is helpful when you're fragment-caching the form. Remote forms - # get the authenticity token from the meta tag, so embedding is - # unnecessary unless you support browsers without JavaScript. - # * :remote - If set to true, will allow the Unobtrusive - # JavaScript drivers to control the submit behavior. By default this - # behavior is an ajax submit. - # * :enforce_utf8 - If set to false, a hidden input with name - # utf8 is not output. - # * :html - Optional HTML attributes for the form tag. - # - # Also note that +form_for+ doesn't create an exclusive scope. It's still - # possible to use both the stand-alone FormHelper methods and methods - # from FormTagHelper. For example: - # - # <%= form_for :person do |f| %> - # First name: <%= f.text_field :first_name %> - # Last name : <%= f.text_field :last_name %> - # Biography : <%= text_area :person, :biography %> - # Admin? : <%= check_box_tag "person[admin]", "1", @person.company.admin? %> - # <%= f.submit %> - # <% end %> - # - # This also works for the methods in FormOptionHelper and DateHelper that - # are designed to work with an object as base, like - # FormOptionHelper#collection_select and DateHelper#datetime_select. - # - # === #form_for with a model object - # - # In the examples above, the object to be created or edited was - # represented by a symbol passed to +form_for+, and we noted that - # a string can also be used equivalently. It is also possible, however, - # to pass a model object itself to +form_for+. For example, if @post - # is an existing record you wish to edit, you can create the form using - # - # <%= form_for @post do |f| %> - # ... - # <% end %> - # - # This behaves in almost the same way as outlined previously, with a - # couple of small exceptions. First, the prefix used to name the input - # elements within the form (hence the key that denotes them in the +params+ - # hash) is actually derived from the object's _class_, e.g. params[:post] - # if the object's class is +Post+. However, this can be overwritten using - # the :as option, e.g. - - # - # <%= form_for(@person, as: :client) do |f| %> - # ... - # <% end %> - # - # would result in params[:client]. - # - # Secondly, the field values shown when the form is initially displayed - # are taken from the attributes of the object passed to +form_for+, - # regardless of whether the object is an instance - # variable. So, for example, if we had a _local_ variable +post+ - # representing an existing record, - # - # <%= form_for post do |f| %> - # ... - # <% end %> - # - # would produce a form with fields whose initial state reflect the current - # values of the attributes of +post+. - # - # === Resource-oriented style - # - # In the examples just shown, although not indicated explicitly, we still - # need to use the :url option in order to specify where the - # form is going to be sent. However, further simplification is possible - # if the record passed to +form_for+ is a _resource_, i.e. it corresponds - # to a set of RESTful routes, e.g. defined using the +resources+ method - # in config/routes.rb. In this case Rails will simply infer the - # appropriate URL from the record itself. For example, - # - # <%= form_for @post do |f| %> - # ... - # <% end %> - # - # is then equivalent to something like: - # - # <%= form_for @post, as: :post, url: post_path(@post), method: :patch, html: { class: "edit_post", id: "edit_post_45" } do |f| %> - # ... - # <% end %> - # - # And for a new record - # - # <%= form_for(Post.new) do |f| %> - # ... - # <% end %> - # - # is equivalent to something like: - # - # <%= form_for @post, as: :post, url: posts_path, html: { class: "new_post", id: "new_post" } do |f| %> - # ... - # <% end %> - # - # However you can still overwrite individual conventions, such as: - # - # <%= form_for(@post, url: super_posts_path) do |f| %> - # ... - # <% end %> - # - # You can also set the answer format, like this: - # - # <%= form_for(@post, format: :json) do |f| %> - # ... - # <% end %> - # - # For namespaced routes, like +admin_post_url+: - # - # <%= form_for([:admin, @post]) do |f| %> - # ... - # <% end %> - # - # If your resource has associations defined, for example, you want to add comments - # to the document given that the routes are set correctly: - # - # <%= form_for([@document, @comment]) do |f| %> - # ... - # <% end %> - # - # Where @document = Document.find(params[:id]) and - # @comment = Comment.new. - # - # === Setting the method - # - # You can force the form to use the full array of HTTP verbs by setting - # - # method: (:get|:post|:patch|:put|:delete) - # - # in the options hash. If the verb is not GET or POST, which are natively - # supported by HTML forms, the form will be set to POST and a hidden input - # called _method will carry the intended verb for the server to interpret. - # - # === Unobtrusive JavaScript - # - # Specifying: - # - # remote: true - # - # in the options hash creates a form that will allow the unobtrusive JavaScript drivers to modify its - # behavior. The expected default behavior is an XMLHttpRequest in the background instead of the regular - # POST arrangement, but ultimately the behavior is the choice of the JavaScript driver implementor. - # Even though it's using JavaScript to serialize the form elements, the form submission will work just like - # a regular submission as viewed by the receiving side (all elements available in params). - # - # Example: - # - # <%= form_for(@post, remote: true) do |f| %> - # ... - # <% end %> - # - # The HTML generated for this would be: - # - #
    - # - # ... - #
    - # - # === Setting HTML options - # - # You can set data attributes directly by passing in a data hash, but all other HTML options must be wrapped in - # the HTML key. Example: - # - # <%= form_for(@post, data: { behavior: "autosave" }, html: { name: "go" }) do |f| %> - # ... - # <% end %> - # - # The HTML generated for this would be: - # - #
    - # - # ... - #
    - # - # === Removing hidden model id's - # - # The form_for method automatically includes the model id as a hidden field in the form. - # This is used to maintain the correlation between the form data and its associated model. - # Some ORM systems do not use IDs on nested models so in this case you want to be able - # to disable the hidden id. - # - # In the following example the Post model has many Comments stored within it in a NoSQL database, - # thus there is no primary key for comments. - # - # Example: - # - # <%= form_for(@post) do |f| %> - # <%= f.fields_for(:comments, include_id: false) do |cf| %> - # ... - # <% end %> - # <% end %> - # - # === Customized form builders - # - # You can also build forms using a customized FormBuilder class. Subclass - # FormBuilder and override or define some more helpers, then use your - # custom builder. For example, let's say you made a helper to - # automatically add labels to form inputs. - # - # <%= form_for @person, url: { action: "create" }, builder: LabellingFormBuilder do |f| %> - # <%= f.text_field :first_name %> - # <%= f.text_field :last_name %> - # <%= f.text_area :biography %> - # <%= f.check_box :admin %> - # <%= f.submit %> - # <% end %> - # - # In this case, if you use this: - # - # <%= render f %> - # - # The rendered template is people/_labelling_form and the local - # variable referencing the form builder is called - # labelling_form. - # - # The custom FormBuilder class is automatically merged with the options - # of a nested fields_for call, unless it's explicitly set. - # - # In many cases you will want to wrap the above in another helper, so you - # could do something like the following: - # - # def labelled_form_for(record_or_name_or_array, *args, &block) - # options = args.extract_options! - # form_for(record_or_name_or_array, *(args << options.merge(builder: LabellingFormBuilder)), &block) - # end - # - # If you don't need to attach a form to a model instance, then check out - # FormTagHelper#form_tag. - # - # === Form to external resources - # - # When you build forms to external resources sometimes you need to set an authenticity token or just render a form - # without it, for example when you submit data to a payment gateway number and types of fields could be limited. - # - # To set an authenticity token you need to pass an :authenticity_token parameter - # - # <%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f| - # ... - # <% end %> - # - # If you don't want to an authenticity token field be rendered at all just pass false: - # - # <%= form_for @invoice, url: external_url, authenticity_token: false do |f| - # ... - # <% end %> - def form_for(record, options = {}, &block) - raise ArgumentError, "Missing block" unless block_given? - html_options = options[:html] ||= {} - - case record - when String, Symbol - object_name = record - object = nil - else - object = record.is_a?(Array) ? record.last : record - raise ArgumentError, "First argument in form cannot contain nil or be empty" unless object - object_name = options[:as] || model_name_from_record_or_class(object).param_key - apply_form_for_options!(record, object, options) - end - - html_options[:data] = options.delete(:data) if options.has_key?(:data) - html_options[:remote] = options.delete(:remote) if options.has_key?(:remote) - html_options[:method] = options.delete(:method) if options.has_key?(:method) - html_options[:enforce_utf8] = options.delete(:enforce_utf8) if options.has_key?(:enforce_utf8) - html_options[:authenticity_token] = options.delete(:authenticity_token) - - builder = instantiate_builder(object_name, object, options) - output = capture(builder, &block) - html_options[:multipart] ||= builder.multipart? - - html_options = html_options_for_form(options[:url] || {}, html_options) - form_tag_with_body(html_options, output) - end - - def apply_form_for_options!(record, object, options) #:nodoc: - object = convert_to_model(object) - - as = options[:as] - namespace = options[:namespace] - action, method = object.respond_to?(:persisted?) && object.persisted? ? [:edit, :patch] : [:new, :post] - options[:html].reverse_merge!( - class: as ? "#{action}_#{as}" : dom_class(object, action), - id: (as ? [namespace, action, as] : [namespace, dom_id(object, action)]).compact.join("_").presence, - method: method - ) - - options[:url] ||= if options.key?(:format) - polymorphic_path(record, format: options.delete(:format)) - else - polymorphic_path(record, {}) - end - end - private :apply_form_for_options! - - mattr_accessor(:form_with_generates_remote_forms) { true } - - # Creates a form tag based on mixing URLs, scopes, or models. - # - # # Using just a URL: - # <%= form_with url: posts_path do |form| %> - # <%= form.text_field :title %> - # <% end %> - # # => - #
    - # - #
    - # - # # Adding a scope prefixes the input field names: - # <%= form_with scope: :post, url: posts_path do |form| %> - # <%= form.text_field :title %> - # <% end %> - # # => - #
    - # - #
    - # - # # Using a model infers both the URL and scope: - # <%= form_with model: Post.new do |form| %> - # <%= form.text_field :title %> - # <% end %> - # # => - #
    - # - #
    - # - # # An existing model makes an update form and fills out field values: - # <%= form_with model: Post.first do |form| %> - # <%= form.text_field :title %> - # <% end %> - # # => - #
    - # - # - #
    - # - # # Though the fields don't have to correspond to model attributes: - # <%= form_with model: Cat.new do |form| %> - # <%= form.text_field :cats_dont_have_gills %> - # <%= form.text_field :but_in_forms_they_can %> - # <% end %> - # # => - #
    - # - # - #
    - # - # The parameters in the forms are accessible in controllers according to - # their name nesting. So inputs named +title+ and post[title] are - # accessible as params[:title] and params[:post][:title] - # respectively. - # - # By default +form_with+ attaches the data-remote attribute - # submitting the form via an XMLHTTPRequest in the background if an - # Unobtrusive JavaScript driver, like rails-ujs, is used. See the - # :local option for more. - # - # For ease of comparison the examples above left out the submit button, - # as well as the auto generated hidden fields that enable UTF-8 support - # and adds an authenticity token needed for cross site request forgery - # protection. - # - # === Resource-oriented style - # - # In many of the examples just shown, the +:model+ passed to +form_with+ - # is a _resource_. It corresponds to a set of RESTful routes, most likely - # defined via +resources+ in config/routes.rb. - # - # So when passing such a model record, Rails infers the URL and method. - # - # <%= form_with model: @post do |form| %> - # ... - # <% end %> - # - # is then equivalent to something like: - # - # <%= form_with scope: :post, url: post_path(@post), method: :patch do |form| %> - # ... - # <% end %> - # - # And for a new record - # - # <%= form_with model: Post.new do |form| %> - # ... - # <% end %> - # - # is equivalent to something like: - # - # <%= form_with scope: :post, url: posts_path do |form| %> - # ... - # <% end %> - # - # ==== +form_with+ options - # - # * :url - The URL the form submits to. Akin to values passed to - # +url_for+ or +link_to+. For example, you may use a named route - # directly. When a :scope is passed without a :url the - # form just submits to the current URL. - # * :method - The method to use when submitting the form, usually - # either "get" or "post". If "patch", "put", "delete", or another verb - # is used, a hidden input named _method is added to - # simulate the verb over post. - # * :format - The format of the route the form submits to. - # Useful when submitting to another resource type, like :json. - # Skipped if a :url is passed. - # * :scope - The scope to prefix input field names with and - # thereby how the submitted parameters are grouped in controllers. - # * :model - A model object to infer the :url and - # :scope by, plus fill out input field values. - # So if a +title+ attribute is set to "Ahoy!" then a +title+ input - # field's value would be "Ahoy!". - # If the model is a new record a create form is generated, if an - # existing record, however, an update form is generated. - # Pass :scope or :url to override the defaults. - # E.g. turn params[:post] into params[:article]. - # * :authenticity_token - Authenticity token to use in the form. - # Override with a custom authenticity token or pass false to - # skip the authenticity token field altogether. - # Useful when submitting to an external resource like a payment gateway - # that might limit the valid fields. - # Remote forms may omit the embedded authenticity token by setting - # config.action_view.embed_authenticity_token_in_remote_forms = false. - # This is helpful when fragment-caching the form. Remote forms - # get the authenticity token from the meta tag, so embedding is - # unnecessary unless you support browsers without JavaScript. - # * :local - By default form submits are remote and unobstrusive XHRs. - # Disable remote submits with local: true. - # * :skip_enforcing_utf8 - By default a hidden field named +utf8+ - # is output to enforce UTF-8 submits. Set to true to skip the field. - # * :builder - Override the object used to build the form. - # * :id - Optional HTML id attribute. - # * :class - Optional HTML class attribute. - # * :data - Optional HTML data attributes. - # * :html - Other optional HTML attributes for the form tag. - # - # === Examples - # - # When not passing a block, +form_with+ just generates an opening form tag. - # - # <%= form_with(model: @post, url: super_posts_path) %> - # <%= form_with(model: @post, scope: :article) %> - # <%= form_with(model: @post, format: :json) %> - # <%= form_with(model: @post, authenticity_token: false) %> # Disables the token. - # - # For namespaced routes, like +admin_post_url+: - # - # <%= form_with(model: [ :admin, @post ]) do |form| %> - # ... - # <% end %> - # - # If your resource has associations defined, for example, you want to add comments - # to the document given that the routes are set correctly: - # - # <%= form_with(model: [ @document, Comment.new ]) do |form| %> - # ... - # <% end %> - # - # Where @document = Document.find(params[:id]). - # - # When using labels +form_with+ requires setting the id on the field being - # labelled: - # - # <%= form_with(model: @post) do |form| %> - # <%= form.label :title %> - # <%= form.text_field :title, id: :post_title %> - # <% end %> - # - # See +label+ for more on how the +for+ attribute is derived. - # - # === Mixing with other form helpers - # - # While +form_with+ uses a FormBuilder object it's possible to mix and - # match the stand-alone FormHelper methods and methods - # from FormTagHelper: - # - # <%= form_with scope: :person do |form| %> - # <%= form.text_field :first_name %> - # <%= form.text_field :last_name %> - # - # <%= text_area :person, :biography %> - # <%= check_box_tag "person[admin]", "1", @person.company.admin? %> - # - # <%= form.submit %> - # <% end %> - # - # Same goes for the methods in FormOptionHelper and DateHelper designed - # to work with an object as a base, like - # FormOptionHelper#collection_select and DateHelper#datetime_select. - # - # === Setting the method - # - # You can force the form to use the full array of HTTP verbs by setting - # - # method: (:get|:post|:patch|:put|:delete) - # - # in the options hash. If the verb is not GET or POST, which are natively - # supported by HTML forms, the form will be set to POST and a hidden input - # called _method will carry the intended verb for the server to interpret. - # - # === Setting HTML options - # - # You can set data attributes directly in a data hash, but HTML options - # besides id and class must be wrapped in an HTML key: - # - # <%= form_with(model: @post, data: { behavior: "autosave" }, html: { name: "go" }) do |form| %> - # ... - # <% end %> - # - # generates - # - #
    - # - # ... - #
    - # - # === Removing hidden model id's - # - # The +form_with+ method automatically includes the model id as a hidden field in the form. - # This is used to maintain the correlation between the form data and its associated model. - # Some ORM systems do not use IDs on nested models so in this case you want to be able - # to disable the hidden id. - # - # In the following example the Post model has many Comments stored within it in a NoSQL database, - # thus there is no primary key for comments. - # - # <%= form_with(model: @post) do |form| %> - # <%= form.fields(:comments, skip_id: true) do |fields| %> - # ... - # <% end %> - # <% end %> - # - # === Customized form builders - # - # You can also build forms using a customized FormBuilder class. Subclass - # FormBuilder and override or define some more helpers, then use your - # custom builder. For example, let's say you made a helper to - # automatically add labels to form inputs. - # - # <%= form_with model: @person, url: { action: "create" }, builder: LabellingFormBuilder do |form| %> - # <%= form.text_field :first_name %> - # <%= form.text_field :last_name %> - # <%= form.text_area :biography %> - # <%= form.check_box :admin %> - # <%= form.submit %> - # <% end %> - # - # In this case, if you use: - # - # <%= render form %> - # - # The rendered template is people/_labelling_form and the local - # variable referencing the form builder is called - # labelling_form. - # - # The custom FormBuilder class is automatically merged with the options - # of a nested +fields+ call, unless it's explicitly set. - # - # In many cases you will want to wrap the above in another helper, so you - # could do something like the following: - # - # def labelled_form_with(**options, &block) - # form_with(**options.merge(builder: LabellingFormBuilder), &block) - # end - def form_with(model: nil, scope: nil, url: nil, format: nil, **options) - options[:allow_method_names_outside_object] = true - options[:skip_default_ids] = true - - if model - url ||= polymorphic_path(model, format: format) - - model = model.last if model.is_a?(Array) - scope ||= model_name_from_record_or_class(model).param_key - end - - if block_given? - builder = instantiate_builder(scope, model, options) - output = capture(builder, &Proc.new) - options[:multipart] ||= builder.multipart? - - html_options = html_options_for_form_with(url, model, options) - form_tag_with_body(html_options, output) - else - html_options = html_options_for_form_with(url, model, options) - form_tag_html(html_options) - end - end - - # Creates a scope around a specific model object like form_for, but - # doesn't create the form tags themselves. This makes fields_for suitable - # for specifying additional model objects in the same form. - # - # Although the usage and purpose of +fields_for+ is similar to +form_for+'s, - # its method signature is slightly different. Like +form_for+, it yields - # a FormBuilder object associated with a particular model object to a block, - # and within the block allows methods to be called on the builder to - # generate fields associated with the model object. Fields may reflect - # a model object in two ways - how they are named (hence how submitted - # values appear within the +params+ hash in the controller) and what - # default values are shown when the form the fields appear in is first - # displayed. In order for both of these features to be specified independently, - # both an object name (represented by either a symbol or string) and the - # object itself can be passed to the method separately - - # - # <%= form_for @person do |person_form| %> - # First name: <%= person_form.text_field :first_name %> - # Last name : <%= person_form.text_field :last_name %> - # - # <%= fields_for :permission, @person.permission do |permission_fields| %> - # Admin? : <%= permission_fields.check_box :admin %> - # <% end %> - # - # <%= person_form.submit %> - # <% end %> - # - # In this case, the checkbox field will be represented by an HTML +input+ - # tag with the +name+ attribute permission[admin], and the submitted - # value will appear in the controller as params[:permission][:admin]. - # If @person.permission is an existing record with an attribute - # +admin+, the initial state of the checkbox when first displayed will - # reflect the value of @person.permission.admin. - # - # Often this can be simplified by passing just the name of the model - # object to +fields_for+ - - # - # <%= fields_for :permission do |permission_fields| %> - # Admin?: <%= permission_fields.check_box :admin %> - # <% end %> - # - # ...in which case, if :permission also happens to be the name of an - # instance variable @permission, the initial state of the input - # field will reflect the value of that variable's attribute @permission.admin. - # - # Alternatively, you can pass just the model object itself (if the first - # argument isn't a string or symbol +fields_for+ will realize that the - # name has been omitted) - - # - # <%= fields_for @person.permission do |permission_fields| %> - # Admin?: <%= permission_fields.check_box :admin %> - # <% end %> - # - # and +fields_for+ will derive the required name of the field from the - # _class_ of the model object, e.g. if @person.permission, is - # of class +Permission+, the field will still be named permission[admin]. - # - # Note: This also works for the methods in FormOptionHelper and - # DateHelper that are designed to work with an object as base, like - # FormOptionHelper#collection_select and DateHelper#datetime_select. - # - # === Nested Attributes Examples - # - # When the object belonging to the current scope has a nested attribute - # writer for a certain attribute, fields_for will yield a new scope - # for that attribute. This allows you to create forms that set or change - # the attributes of a parent object and its associations in one go. - # - # Nested attribute writers are normal setter methods named after an - # association. The most common way of defining these writers is either - # with +accepts_nested_attributes_for+ in a model definition or by - # defining a method with the proper name. For example: the attribute - # writer for the association :address is called - # address_attributes=. - # - # Whether a one-to-one or one-to-many style form builder will be yielded - # depends on whether the normal reader method returns a _single_ object - # or an _array_ of objects. - # - # ==== One-to-one - # - # Consider a Person class which returns a _single_ Address from the - # address reader method and responds to the - # address_attributes= writer method: - # - # class Person - # def address - # @address - # end - # - # def address_attributes=(attributes) - # # Process the attributes hash - # end - # end - # - # This model can now be used with a nested fields_for, like so: - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :address do |address_fields| %> - # Street : <%= address_fields.text_field :street %> - # Zip code: <%= address_fields.text_field :zip_code %> - # <% end %> - # ... - # <% end %> - # - # When address is already an association on a Person you can use - # +accepts_nested_attributes_for+ to define the writer method for you: - # - # class Person < ActiveRecord::Base - # has_one :address - # accepts_nested_attributes_for :address - # end - # - # If you want to destroy the associated model through the form, you have - # to enable it first using the :allow_destroy option for - # +accepts_nested_attributes_for+: - # - # class Person < ActiveRecord::Base - # has_one :address - # accepts_nested_attributes_for :address, allow_destroy: true - # end - # - # Now, when you use a form element with the _destroy parameter, - # with a value that evaluates to +true+, you will destroy the associated - # model (eg. 1, '1', true, or 'true'): - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :address do |address_fields| %> - # ... - # Delete: <%= address_fields.check_box :_destroy %> - # <% end %> - # ... - # <% end %> - # - # ==== One-to-many - # - # Consider a Person class which returns an _array_ of Project instances - # from the projects reader method and responds to the - # projects_attributes= writer method: - # - # class Person - # def projects - # [@project1, @project2] - # end - # - # def projects_attributes=(attributes) - # # Process the attributes hash - # end - # end - # - # Note that the projects_attributes= writer method is in fact - # required for fields_for to correctly identify :projects as a - # collection, and the correct indices to be set in the form markup. - # - # When projects is already an association on Person you can use - # +accepts_nested_attributes_for+ to define the writer method for you: - # - # class Person < ActiveRecord::Base - # has_many :projects - # accepts_nested_attributes_for :projects - # end - # - # This model can now be used with a nested fields_for. The block given to - # the nested fields_for call will be repeated for each instance in the - # collection: - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects do |project_fields| %> - # <% if project_fields.object.active? %> - # Name: <%= project_fields.text_field :name %> - # <% end %> - # <% end %> - # ... - # <% end %> - # - # It's also possible to specify the instance to be used: - # - # <%= form_for @person do |person_form| %> - # ... - # <% @person.projects.each do |project| %> - # <% if project.active? %> - # <%= person_form.fields_for :projects, project do |project_fields| %> - # Name: <%= project_fields.text_field :name %> - # <% end %> - # <% end %> - # <% end %> - # ... - # <% end %> - # - # Or a collection to be used: - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects, @active_projects do |project_fields| %> - # Name: <%= project_fields.text_field :name %> - # <% end %> - # ... - # <% end %> - # - # If you want to destroy any of the associated models through the - # form, you have to enable it first using the :allow_destroy - # option for +accepts_nested_attributes_for+: - # - # class Person < ActiveRecord::Base - # has_many :projects - # accepts_nested_attributes_for :projects, allow_destroy: true - # end - # - # This will allow you to specify which models to destroy in the - # attributes hash by adding a form element for the _destroy - # parameter with a value that evaluates to +true+ - # (eg. 1, '1', true, or 'true'): - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects do |project_fields| %> - # Delete: <%= project_fields.check_box :_destroy %> - # <% end %> - # ... - # <% end %> - # - # When a collection is used you might want to know the index of each - # object into the array. For this purpose, the index method - # is available in the FormBuilder object. - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects do |project_fields| %> - # Project #<%= project_fields.index %> - # ... - # <% end %> - # ... - # <% end %> - # - # Note that fields_for will automatically generate a hidden field - # to store the ID of the record. There are circumstances where this - # hidden field is not needed and you can pass include_id: false - # to prevent fields_for from rendering it automatically. - def fields_for(record_name, record_object = nil, options = {}, &block) - builder = instantiate_builder(record_name, record_object, options) - capture(builder, &block) - end - - # Scopes input fields with either an explicit scope or model. - # Like +form_with+ does with :scope or :model, - # except it doesn't output the form tags. - # - # # Using a scope prefixes the input field names: - # <%= fields :comment do |fields| %> - # <%= fields.text_field :body %> - # <% end %> - # # => - # <% end %> - # # => - # - # - # # Using +fields+ with +form_with+: - # <%= form_with model: @post do |form| %> - # <%= form.text_field :title %> - # - # <%= form.fields :comment do |fields| %> - # <%= fields.text_field :body %> - # <% end %> - # <% end %> - # - # Much like +form_with+ a FormBuilder instance associated with the scope - # or model is yielded, so any generated field names are prefixed with - # either the passed scope or the scope inferred from the :model. - # - # When using labels +fields+ requires setting the id on the field being - # labelled: - # - # <%= fields :comment do |fields| %> - # <%= fields.label :body %> - # <%= fields.text_field :body, id: :comment_body %> - # <% end %> - # - # See +label+ for more on how the +for+ attribute is derived. - # - # === Mixing with other form helpers - # - # While +form_with+ uses a FormBuilder object it's possible to mix and - # match the stand-alone FormHelper methods and methods - # from FormTagHelper: - # - # <%= fields model: @comment do |fields| %> - # <%= fields.text_field :body %> - # - # <%= text_area :commenter, :biography %> - # <%= check_box_tag "comment[all_caps]", "1", @comment.commenter.hulk_mode? %> - # <% end %> - # - # Same goes for the methods in FormOptionHelper and DateHelper designed - # to work with an object as a base, like - # FormOptionHelper#collection_select and DateHelper#datetime_select. - def fields(scope = nil, model: nil, **options, &block) - options[:allow_method_names_outside_object] = true - options[:skip_default_ids] = true - - if model - scope ||= model_name_from_record_or_class(model).param_key - end - - builder = instantiate_builder(scope, model, options) - capture(builder, &block) - end - - # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation - # is found in the current I18n locale (through helpers.label..) or you specify it explicitly. - # Additional options on the label tag can be passed as a hash with +options+. These options will be tagged - # onto the HTML as an HTML element attribute as in the example shown, except for the :value option, which is designed to - # target labels for radio_button tags (where the value is used in the ID of the input tag). - # - # ==== Examples - # label(:post, :title) - # # => - # - # You can localize your labels based on model and attribute names. - # For example you can define the following in your locale (e.g. en.yml) - # - # helpers: - # label: - # post: - # body: "Write your entire text here" - # - # Which then will result in - # - # label(:post, :body) - # # => - # - # Localization can also be based purely on the translation of the attribute-name - # (if you are using ActiveRecord): - # - # activerecord: - # attributes: - # post: - # cost: "Total cost" - # - # label(:post, :cost) - # # => - # - # label(:post, :title, "A short title") - # # => - # - # label(:post, :title, "A short title", class: "title_label") - # # => - # - # label(:post, :privacy, "Public Post", value: "public") - # # => - # - # label(:post, :terms) do - # raw('Accept Terms.') - # end - # # => - def label(object_name, method, content_or_options = nil, options = nil, &block) - Tags::Label.new(object_name, method, self, content_or_options, options).render(&block) - end - - # Returns an input tag of the "text" type tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a - # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example - # shown. - # - # ==== Examples - # text_field(:post, :title, size: 20) - # # => - # - # text_field(:post, :title, class: "create_input") - # # => - # - # text_field(:session, :user, onchange: "if ($('#session_user').val() === 'admin') { alert('Your login cannot be admin!'); }") - # # => - # - # text_field(:snippet, :code, size: 20, class: 'code_input') - # # => - def text_field(object_name, method, options = {}) - Tags::TextField.new(object_name, method, self, options).render - end - - # Returns an input tag of the "password" type tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a - # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example - # shown. For security reasons this field is blank by default; pass in a value via +options+ if this is not desired. - # - # ==== Examples - # password_field(:login, :pass, size: 20) - # # => - # - # password_field(:account, :secret, class: "form_input", value: @account.secret) - # # => - # - # password_field(:user, :password, onchange: "if ($('#user_password').val().length > 30) { alert('Your password needs to be shorter!'); }") - # # => - # - # password_field(:account, :pin, size: 20, class: 'form_input') - # # => - def password_field(object_name, method, options = {}) - Tags::PasswordField.new(object_name, method, self, options).render - end - - # Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a - # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example - # shown. - # - # ==== Examples - # hidden_field(:signup, :pass_confirm) - # # => - # - # hidden_field(:post, :tag_list) - # # => - # - # hidden_field(:user, :token) - # # => - def hidden_field(object_name, method, options = {}) - Tags::HiddenField.new(object_name, method, self, options).render - end - - # Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a - # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example - # shown. - # - # Using this method inside a +form_for+ block will set the enclosing form's encoding to multipart/form-data. - # - # ==== Options - # * Creates standard HTML attributes for the tag. - # * :disabled - If set to true, the user will not be able to use this input. - # * :multiple - If set to true, *in most updated browsers* the user will be allowed to select multiple files. - # * :accept - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations. - # - # ==== Examples - # file_field(:user, :avatar) - # # => - # - # file_field(:post, :image, multiple: true) - # # => - # - # file_field(:post, :attached, accept: 'text/html') - # # => - # - # file_field(:post, :image, accept: 'image/png,image/gif,image/jpeg') - # # => - # - # file_field(:attachment, :file, class: 'file_input') - # # => - def file_field(object_name, method, options = {}) - Tags::FileField.new(object_name, method, self, options).render - end - - # Returns a textarea opening and closing tag set tailored for accessing a specified attribute (identified by +method+) - # on an object assigned to the template (identified by +object+). Additional options on the input tag can be passed as a - # hash with +options+. - # - # ==== Examples - # text_area(:post, :body, cols: 20, rows: 40) - # # => - # - # text_area(:comment, :text, size: "20x30") - # # => - # - # text_area(:application, :notes, cols: 40, rows: 15, class: 'app_input') - # # => - # - # text_area(:entry, :body, size: "20x20", disabled: 'disabled') - # # => - def text_area(object_name, method, options = {}) - Tags::TextArea.new(object_name, method, self, options).render - end - - # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object. - # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked. - # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1 - # while the default +unchecked_value+ is set to 0 which is convenient for boolean values. - # - # ==== Gotcha - # - # The HTML specification says unchecked check boxes are not successful, and - # thus web browsers do not send them. Unfortunately this introduces a gotcha: - # if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid - # invoice the user unchecks its check box, no +paid+ parameter is sent. So, - # any mass-assignment idiom like - # - # @invoice.update(params[:invoice]) - # - # wouldn't update the flag. - # - # To prevent this the helper generates an auxiliary hidden field before - # the very check box. The hidden field has the same name and its - # attributes mimic an unchecked check box. - # - # This way, the client either sends only the hidden field (representing - # the check box is unchecked), or both fields. Since the HTML specification - # says key/value pairs have to be sent in the same order they appear in the - # form, and parameters extraction gets the last occurrence of any repeated - # key in the query string, that works for ordinary forms. - # - # Unfortunately that workaround does not work when the check box goes - # within an array-like parameter, as in - # - # <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %> - # <%= form.check_box :paid %> - # ... - # <% end %> - # - # because parameter name repetition is precisely what Rails seeks to distinguish - # the elements of the array. For each item with a checked check box you - # get an extra ghost item with only that attribute, assigned to "0". - # - # In that case it is preferable to either use +check_box_tag+ or to use - # hashes instead of arrays. - # - # # Let's say that @post.validated? is 1: - # check_box("post", "validated") - # # => - # # - # - # # Let's say that @puppy.gooddog is "no": - # check_box("puppy", "gooddog", {}, "yes", "no") - # # => - # # - # - # check_box("eula", "accepted", { class: 'eula_check' }, "yes", "no") - # # => - # # - def check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0") - Tags::CheckBox.new(object_name, method, self, checked_value, unchecked_value, options).render - end - - # Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the - # radio button will be checked. - # - # To force the radio button to be checked pass checked: true in the - # +options+ hash. You may pass HTML options there as well. - # - # # Let's say that @post.category returns "rails": - # radio_button("post", "category", "rails") - # radio_button("post", "category", "java") - # # => - # # - # - # # Let's say that @user.receive_newsletter returns "no": - # radio_button("user", "receive_newsletter", "yes") - # radio_button("user", "receive_newsletter", "no") - # # => - # # - def radio_button(object_name, method, tag_value, options = {}) - Tags::RadioButton.new(object_name, method, self, tag_value, options).render - end - - # Returns a text_field of type "color". - # - # color_field("car", "color") - # # => - def color_field(object_name, method, options = {}) - Tags::ColorField.new(object_name, method, self, options).render - end - - # Returns an input of type "search" for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object_name+). Inputs of type "search" may be styled differently by - # some browsers. - # - # search_field(:user, :name) - # # => - # search_field(:user, :name, autosave: false) - # # => - # search_field(:user, :name, results: 3) - # # => - # # Assume request.host returns "www.example.com" - # search_field(:user, :name, autosave: true) - # # => - # search_field(:user, :name, onsearch: true) - # # => - # search_field(:user, :name, autosave: false, onsearch: true) - # # => - # search_field(:user, :name, autosave: true, onsearch: true) - # # => - def search_field(object_name, method, options = {}) - Tags::SearchField.new(object_name, method, self, options).render - end - - # Returns a text_field of type "tel". - # - # telephone_field("user", "phone") - # # => - # - def telephone_field(object_name, method, options = {}) - Tags::TelField.new(object_name, method, self, options).render - end - # aliases telephone_field - alias phone_field telephone_field - - # Returns a text_field of type "date". - # - # date_field("user", "born_on") - # # => - # - # The default value is generated by trying to call +strftime+ with "%Y-%m-%d" - # on the object's value, which makes it behave as expected for instances - # of DateTime and ActiveSupport::TimeWithZone. You can still override that - # by passing the "value" option explicitly, e.g. - # - # @user.born_on = Date.new(1984, 1, 27) - # date_field("user", "born_on", value: "1984-05-12") - # # => - # - # You can create values for the "min" and "max" attributes by passing - # instances of Date or Time to the options hash. - # - # date_field("user", "born_on", min: Date.today) - # # => - # - # Alternatively, you can pass a String formatted as an ISO8601 date as the - # values for "min" and "max." - # - # date_field("user", "born_on", min: "2014-05-20") - # # => - # - def date_field(object_name, method, options = {}) - Tags::DateField.new(object_name, method, self, options).render - end - - # Returns a text_field of type "time". - # - # The default value is generated by trying to call +strftime+ with "%T.%L" - # on the object's value. It is still possible to override that - # by passing the "value" option. - # - # === Options - # * Accepts same options as time_field_tag - # - # === Example - # time_field("task", "started_at") - # # => - # - # You can create values for the "min" and "max" attributes by passing - # instances of Date or Time to the options hash. - # - # time_field("task", "started_at", min: Time.now) - # # => - # - # Alternatively, you can pass a String formatted as an ISO8601 time as the - # values for "min" and "max." - # - # time_field("task", "started_at", min: "01:00:00") - # # => - # - def time_field(object_name, method, options = {}) - Tags::TimeField.new(object_name, method, self, options).render - end - - # Returns a text_field of type "datetime-local". - # - # datetime_field("user", "born_on") - # # => - # - # The default value is generated by trying to call +strftime+ with "%Y-%m-%dT%T" - # on the object's value, which makes it behave as expected for instances - # of DateTime and ActiveSupport::TimeWithZone. - # - # @user.born_on = Date.new(1984, 1, 12) - # datetime_field("user", "born_on") - # # => - # - # You can create values for the "min" and "max" attributes by passing - # instances of Date or Time to the options hash. - # - # datetime_field("user", "born_on", min: Date.today) - # # => - # - # Alternatively, you can pass a String formatted as an ISO8601 datetime as - # the values for "min" and "max." - # - # datetime_field("user", "born_on", min: "2014-05-20T00:00:00") - # # => - # - def datetime_field(object_name, method, options = {}) - Tags::DatetimeLocalField.new(object_name, method, self, options).render - end - - alias datetime_local_field datetime_field - - # Returns a text_field of type "month". - # - # month_field("user", "born_on") - # # => - # - # The default value is generated by trying to call +strftime+ with "%Y-%m" - # on the object's value, which makes it behave as expected for instances - # of DateTime and ActiveSupport::TimeWithZone. - # - # @user.born_on = Date.new(1984, 1, 27) - # month_field("user", "born_on") - # # => - # - def month_field(object_name, method, options = {}) - Tags::MonthField.new(object_name, method, self, options).render - end - - # Returns a text_field of type "week". - # - # week_field("user", "born_on") - # # => - # - # The default value is generated by trying to call +strftime+ with "%Y-W%W" - # on the object's value, which makes it behave as expected for instances - # of DateTime and ActiveSupport::TimeWithZone. - # - # @user.born_on = Date.new(1984, 5, 12) - # week_field("user", "born_on") - # # => - # - def week_field(object_name, method, options = {}) - Tags::WeekField.new(object_name, method, self, options).render - end - - # Returns a text_field of type "url". - # - # url_field("user", "homepage") - # # => - # - def url_field(object_name, method, options = {}) - Tags::UrlField.new(object_name, method, self, options).render - end - - # Returns a text_field of type "email". - # - # email_field("user", "address") - # # => - # - def email_field(object_name, method, options = {}) - Tags::EmailField.new(object_name, method, self, options).render - end - - # Returns an input tag of type "number". - # - # ==== Options - # * Accepts same options as number_field_tag - def number_field(object_name, method, options = {}) - Tags::NumberField.new(object_name, method, self, options).render - end - - # Returns an input tag of type "range". - # - # ==== Options - # * Accepts same options as range_field_tag - def range_field(object_name, method, options = {}) - Tags::RangeField.new(object_name, method, self, options).render - end - - private - def html_options_for_form_with(url_for_options = nil, model = nil, html: {}, local: !form_with_generates_remote_forms, - skip_enforcing_utf8: false, **options) - html_options = options.slice(:id, :class, :multipart, :method, :data).merge(html) - html_options[:method] ||= :patch if model.respond_to?(:persisted?) && model.persisted? - html_options[:enforce_utf8] = !skip_enforcing_utf8 - - html_options[:enctype] = "multipart/form-data" if html_options.delete(:multipart) - - # The following URL is unescaped, this is just a hash of options, and it is the - # responsibility of the caller to escape all the values. - html_options[:action] = url_for(url_for_options || {}) - html_options[:"accept-charset"] = "UTF-8" - html_options[:"data-remote"] = true unless local - - html_options[:authenticity_token] = options.delete(:authenticity_token) - - if !local && html_options[:authenticity_token].blank? - html_options[:authenticity_token] = embed_authenticity_token_in_remote_forms - end - - if html_options[:authenticity_token] == true - # Include the default authenticity_token, which is only generated when it's set to nil, - # but we needed the true value to override the default of no authenticity_token on data-remote. - html_options[:authenticity_token] = nil - end - - html_options.stringify_keys! - end - - def instantiate_builder(record_name, record_object, options) - case record_name - when String, Symbol - object = record_object - object_name = record_name - else - object = record_name - object_name = model_name_from_record_or_class(object).param_key if object - end - - builder = options[:builder] || default_form_builder_class - builder.new(object_name, object, self, options) - end - - def default_form_builder_class - builder = default_form_builder || ActionView::Base.default_form_builder - builder.respond_to?(:constantize) ? builder.constantize : builder - end - end - - # A +FormBuilder+ object is associated with a particular model object and - # allows you to generate fields associated with the model object. The - # +FormBuilder+ object is yielded when using +form_for+ or +fields_for+. - # For example: - # - # <%= form_for @person do |person_form| %> - # Name: <%= person_form.text_field :name %> - # Admin: <%= person_form.check_box :admin %> - # <% end %> - # - # In the above block, a +FormBuilder+ object is yielded as the - # +person_form+ variable. This allows you to generate the +text_field+ - # and +check_box+ fields by specifying their eponymous methods, which - # modify the underlying template and associates the +@person+ model object - # with the form. - # - # The +FormBuilder+ object can be thought of as serving as a proxy for the - # methods in the +FormHelper+ module. This class, however, allows you to - # call methods with the model object you are building the form for. - # - # You can create your own custom FormBuilder templates by subclassing this - # class. For example: - # - # class MyFormBuilder < ActionView::Helpers::FormBuilder - # def div_radio_button(method, tag_value, options = {}) - # @template.content_tag(:div, - # @template.radio_button( - # @object_name, method, tag_value, objectify_options(options) - # ) - # ) - # end - # end - # - # The above code creates a new method +div_radio_button+ which wraps a div - # around the new radio button. Note that when options are passed in, you - # must call +objectify_options+ in order for the model object to get - # correctly passed to the method. If +objectify_options+ is not called, - # then the newly created helper will not be linked back to the model. - # - # The +div_radio_button+ code from above can now be used as follows: - # - # <%= form_for @person, :builder => MyFormBuilder do |f| %> - # I am a child: <%= f.div_radio_button(:admin, "child") %> - # I am an adult: <%= f.div_radio_button(:admin, "adult") %> - # <% end -%> - # - # The standard set of helper methods for form building are located in the - # +field_helpers+ class attribute. - class FormBuilder - include ModelNaming - - # The methods which wrap a form helper call. - class_attribute :field_helpers - self.field_helpers = [:fields_for, :fields, :label, :text_field, :password_field, - :hidden_field, :file_field, :text_area, :check_box, - :radio_button, :color_field, :search_field, - :telephone_field, :phone_field, :date_field, - :time_field, :datetime_field, :datetime_local_field, - :month_field, :week_field, :url_field, :email_field, - :number_field, :range_field] - - attr_accessor :object_name, :object, :options - - attr_reader :multipart, :index - alias :multipart? :multipart - - def multipart=(multipart) - @multipart = multipart - - if parent_builder = @options[:parent_builder] - parent_builder.multipart = multipart - end - end - - def self._to_partial_path - @_to_partial_path ||= name.demodulize.underscore.sub!(/_builder$/, "") - end - - def to_partial_path - self.class._to_partial_path - end - - def to_model - self - end - - def initialize(object_name, object, template, options) - @nested_child_index = {} - @object_name, @object, @template, @options = object_name, object, template, options - @default_options = @options ? @options.slice(:index, :namespace, :skip_default_ids, :allow_method_names_outside_object) : {} - - convert_to_legacy_options(@options) - - if @object_name.to_s.match(/\[\]$/) - if (object ||= @template.instance_variable_get("@#{Regexp.last_match.pre_match}")) && object.respond_to?(:to_param) - @auto_index = object.to_param - else - raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}" - end - end - - @multipart = nil - @index = options[:index] || options[:child_index] - end - - (field_helpers - [:label, :check_box, :radio_button, :fields_for, :fields, :hidden_field, :file_field]).each do |selector| - class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 - def #{selector}(method, options = {}) # def text_field(method, options = {}) - @template.send( # @template.send( - #{selector.inspect}, # "text_field", - @object_name, # @object_name, - method, # method, - objectify_options(options)) # objectify_options(options)) - end # end - RUBY_EVAL - end - - # Creates a scope around a specific model object like form_for, but - # doesn't create the form tags themselves. This makes fields_for suitable - # for specifying additional model objects in the same form. - # - # Although the usage and purpose of +fields_for+ is similar to +form_for+'s, - # its method signature is slightly different. Like +form_for+, it yields - # a FormBuilder object associated with a particular model object to a block, - # and within the block allows methods to be called on the builder to - # generate fields associated with the model object. Fields may reflect - # a model object in two ways - how they are named (hence how submitted - # values appear within the +params+ hash in the controller) and what - # default values are shown when the form the fields appear in is first - # displayed. In order for both of these features to be specified independently, - # both an object name (represented by either a symbol or string) and the - # object itself can be passed to the method separately - - # - # <%= form_for @person do |person_form| %> - # First name: <%= person_form.text_field :first_name %> - # Last name : <%= person_form.text_field :last_name %> - # - # <%= fields_for :permission, @person.permission do |permission_fields| %> - # Admin? : <%= permission_fields.check_box :admin %> - # <% end %> - # - # <%= person_form.submit %> - # <% end %> - # - # In this case, the checkbox field will be represented by an HTML +input+ - # tag with the +name+ attribute permission[admin], and the submitted - # value will appear in the controller as params[:permission][:admin]. - # If @person.permission is an existing record with an attribute - # +admin+, the initial state of the checkbox when first displayed will - # reflect the value of @person.permission.admin. - # - # Often this can be simplified by passing just the name of the model - # object to +fields_for+ - - # - # <%= fields_for :permission do |permission_fields| %> - # Admin?: <%= permission_fields.check_box :admin %> - # <% end %> - # - # ...in which case, if :permission also happens to be the name of an - # instance variable @permission, the initial state of the input - # field will reflect the value of that variable's attribute @permission.admin. - # - # Alternatively, you can pass just the model object itself (if the first - # argument isn't a string or symbol +fields_for+ will realize that the - # name has been omitted) - - # - # <%= fields_for @person.permission do |permission_fields| %> - # Admin?: <%= permission_fields.check_box :admin %> - # <% end %> - # - # and +fields_for+ will derive the required name of the field from the - # _class_ of the model object, e.g. if @person.permission, is - # of class +Permission+, the field will still be named permission[admin]. - # - # Note: This also works for the methods in FormOptionHelper and - # DateHelper that are designed to work with an object as base, like - # FormOptionHelper#collection_select and DateHelper#datetime_select. - # - # === Nested Attributes Examples - # - # When the object belonging to the current scope has a nested attribute - # writer for a certain attribute, fields_for will yield a new scope - # for that attribute. This allows you to create forms that set or change - # the attributes of a parent object and its associations in one go. - # - # Nested attribute writers are normal setter methods named after an - # association. The most common way of defining these writers is either - # with +accepts_nested_attributes_for+ in a model definition or by - # defining a method with the proper name. For example: the attribute - # writer for the association :address is called - # address_attributes=. - # - # Whether a one-to-one or one-to-many style form builder will be yielded - # depends on whether the normal reader method returns a _single_ object - # or an _array_ of objects. - # - # ==== One-to-one - # - # Consider a Person class which returns a _single_ Address from the - # address reader method and responds to the - # address_attributes= writer method: - # - # class Person - # def address - # @address - # end - # - # def address_attributes=(attributes) - # # Process the attributes hash - # end - # end - # - # This model can now be used with a nested fields_for, like so: - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :address do |address_fields| %> - # Street : <%= address_fields.text_field :street %> - # Zip code: <%= address_fields.text_field :zip_code %> - # <% end %> - # ... - # <% end %> - # - # When address is already an association on a Person you can use - # +accepts_nested_attributes_for+ to define the writer method for you: - # - # class Person < ActiveRecord::Base - # has_one :address - # accepts_nested_attributes_for :address - # end - # - # If you want to destroy the associated model through the form, you have - # to enable it first using the :allow_destroy option for - # +accepts_nested_attributes_for+: - # - # class Person < ActiveRecord::Base - # has_one :address - # accepts_nested_attributes_for :address, allow_destroy: true - # end - # - # Now, when you use a form element with the _destroy parameter, - # with a value that evaluates to +true+, you will destroy the associated - # model (eg. 1, '1', true, or 'true'): - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :address do |address_fields| %> - # ... - # Delete: <%= address_fields.check_box :_destroy %> - # <% end %> - # ... - # <% end %> - # - # ==== One-to-many - # - # Consider a Person class which returns an _array_ of Project instances - # from the projects reader method and responds to the - # projects_attributes= writer method: - # - # class Person - # def projects - # [@project1, @project2] - # end - # - # def projects_attributes=(attributes) - # # Process the attributes hash - # end - # end - # - # Note that the projects_attributes= writer method is in fact - # required for fields_for to correctly identify :projects as a - # collection, and the correct indices to be set in the form markup. - # - # When projects is already an association on Person you can use - # +accepts_nested_attributes_for+ to define the writer method for you: - # - # class Person < ActiveRecord::Base - # has_many :projects - # accepts_nested_attributes_for :projects - # end - # - # This model can now be used with a nested fields_for. The block given to - # the nested fields_for call will be repeated for each instance in the - # collection: - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects do |project_fields| %> - # <% if project_fields.object.active? %> - # Name: <%= project_fields.text_field :name %> - # <% end %> - # <% end %> - # ... - # <% end %> - # - # It's also possible to specify the instance to be used: - # - # <%= form_for @person do |person_form| %> - # ... - # <% @person.projects.each do |project| %> - # <% if project.active? %> - # <%= person_form.fields_for :projects, project do |project_fields| %> - # Name: <%= project_fields.text_field :name %> - # <% end %> - # <% end %> - # <% end %> - # ... - # <% end %> - # - # Or a collection to be used: - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects, @active_projects do |project_fields| %> - # Name: <%= project_fields.text_field :name %> - # <% end %> - # ... - # <% end %> - # - # If you want to destroy any of the associated models through the - # form, you have to enable it first using the :allow_destroy - # option for +accepts_nested_attributes_for+: - # - # class Person < ActiveRecord::Base - # has_many :projects - # accepts_nested_attributes_for :projects, allow_destroy: true - # end - # - # This will allow you to specify which models to destroy in the - # attributes hash by adding a form element for the _destroy - # parameter with a value that evaluates to +true+ - # (eg. 1, '1', true, or 'true'): - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects do |project_fields| %> - # Delete: <%= project_fields.check_box :_destroy %> - # <% end %> - # ... - # <% end %> - # - # When a collection is used you might want to know the index of each - # object into the array. For this purpose, the index method - # is available in the FormBuilder object. - # - # <%= form_for @person do |person_form| %> - # ... - # <%= person_form.fields_for :projects do |project_fields| %> - # Project #<%= project_fields.index %> - # ... - # <% end %> - # ... - # <% end %> - # - # Note that fields_for will automatically generate a hidden field - # to store the ID of the record. There are circumstances where this - # hidden field is not needed and you can pass include_id: false - # to prevent fields_for from rendering it automatically. - def fields_for(record_name, record_object = nil, fields_options = {}, &block) - fields_options, record_object = record_object, nil if record_object.is_a?(Hash) && record_object.extractable_options? - fields_options[:builder] ||= options[:builder] - fields_options[:namespace] = options[:namespace] - fields_options[:parent_builder] = self - - case record_name - when String, Symbol - if nested_attributes_association?(record_name) - return fields_for_with_nested_attributes(record_name, record_object, fields_options, block) - end - else - record_object = record_name.is_a?(Array) ? record_name.last : record_name - record_name = model_name_from_record_or_class(record_object).param_key - end - - object_name = @object_name - index = if options.has_key?(:index) - options[:index] - elsif defined?(@auto_index) - object_name = object_name.to_s.sub(/\[\]$/, "") - @auto_index - end - - record_name = if index - "#{object_name}[#{index}][#{record_name}]" - elsif record_name.to_s.end_with?("[]") - record_name = record_name.to_s.sub(/(.*)\[\]$/, "[\\1][#{record_object.id}]") - "#{object_name}#{record_name}" - else - "#{object_name}[#{record_name}]" - end - fields_options[:child_index] = index - - @template.fields_for(record_name, record_object, fields_options, &block) - end - - # See the docs for the ActionView::FormHelper.fields helper method. - def fields(scope = nil, model: nil, **options, &block) - options[:allow_method_names_outside_object] = true - options[:skip_default_ids] = true - - convert_to_legacy_options(options) - - fields_for(scope || model, model, **options, &block) - end - - # Returns a label tag tailored for labelling an input field for a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). The text of label will default to the attribute name unless a translation - # is found in the current I18n locale (through helpers.label..) or you specify it explicitly. - # Additional options on the label tag can be passed as a hash with +options+. These options will be tagged - # onto the HTML as an HTML element attribute as in the example shown, except for the :value option, which is designed to - # target labels for radio_button tags (where the value is used in the ID of the input tag). - # - # ==== Examples - # label(:title) - # # => - # - # You can localize your labels based on model and attribute names. - # For example you can define the following in your locale (e.g. en.yml) - # - # helpers: - # label: - # post: - # body: "Write your entire text here" - # - # Which then will result in - # - # label(:body) - # # => - # - # Localization can also be based purely on the translation of the attribute-name - # (if you are using ActiveRecord): - # - # activerecord: - # attributes: - # post: - # cost: "Total cost" - # - # label(:cost) - # # => - # - # label(:title, "A short title") - # # => - # - # label(:title, "A short title", class: "title_label") - # # => - # - # label(:privacy, "Public Post", value: "public") - # # => - # - # label(:terms) do - # raw('Accept Terms.') - # end - # # => - def label(method, text = nil, options = {}, &block) - @template.label(@object_name, method, text, objectify_options(options), &block) - end - - # Returns a checkbox tag tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). This object must be an instance object (@object) and not a local object. - # It's intended that +method+ returns an integer and if that integer is above zero, then the checkbox is checked. - # Additional options on the input tag can be passed as a hash with +options+. The +checked_value+ defaults to 1 - # while the default +unchecked_value+ is set to 0 which is convenient for boolean values. - # - # ==== Gotcha - # - # The HTML specification says unchecked check boxes are not successful, and - # thus web browsers do not send them. Unfortunately this introduces a gotcha: - # if an +Invoice+ model has a +paid+ flag, and in the form that edits a paid - # invoice the user unchecks its check box, no +paid+ parameter is sent. So, - # any mass-assignment idiom like - # - # @invoice.update(params[:invoice]) - # - # wouldn't update the flag. - # - # To prevent this the helper generates an auxiliary hidden field before - # the very check box. The hidden field has the same name and its - # attributes mimic an unchecked check box. - # - # This way, the client either sends only the hidden field (representing - # the check box is unchecked), or both fields. Since the HTML specification - # says key/value pairs have to be sent in the same order they appear in the - # form, and parameters extraction gets the last occurrence of any repeated - # key in the query string, that works for ordinary forms. - # - # Unfortunately that workaround does not work when the check box goes - # within an array-like parameter, as in - # - # <%= fields_for "project[invoice_attributes][]", invoice, index: nil do |form| %> - # <%= form.check_box :paid %> - # ... - # <% end %> - # - # because parameter name repetition is precisely what Rails seeks to distinguish - # the elements of the array. For each item with a checked check box you - # get an extra ghost item with only that attribute, assigned to "0". - # - # In that case it is preferable to either use +check_box_tag+ or to use - # hashes instead of arrays. - # - # # Let's say that @post.validated? is 1: - # check_box("validated") - # # => - # # - # - # # Let's say that @puppy.gooddog is "no": - # check_box("gooddog", {}, "yes", "no") - # # => - # # - # - # # Let's say that @eula.accepted is "no": - # check_box("accepted", { class: 'eula_check' }, "yes", "no") - # # => - # # - def check_box(method, options = {}, checked_value = "1", unchecked_value = "0") - @template.check_box(@object_name, method, objectify_options(options), checked_value, unchecked_value) - end - - # Returns a radio button tag for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). If the current value of +method+ is +tag_value+ the - # radio button will be checked. - # - # To force the radio button to be checked pass checked: true in the - # +options+ hash. You may pass HTML options there as well. - # - # # Let's say that @post.category returns "rails": - # radio_button("category", "rails") - # radio_button("category", "java") - # # => - # # - # - # # Let's say that @user.receive_newsletter returns "no": - # radio_button("receive_newsletter", "yes") - # radio_button("receive_newsletter", "no") - # # => - # # - def radio_button(method, tag_value, options = {}) - @template.radio_button(@object_name, method, tag_value, objectify_options(options)) - end - - # Returns a hidden input tag tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a - # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example - # shown. - # - # ==== Examples - # # Let's say that @signup.pass_confirm returns true: - # hidden_field(:pass_confirm) - # # => - # - # # Let's say that @post.tag_list returns "blog, ruby": - # hidden_field(:tag_list) - # # => - # - # # Let's say that @user.token returns "abcde": - # hidden_field(:token) - # # => - # - def hidden_field(method, options = {}) - @emitted_hidden_id = true if method == :id - @template.hidden_field(@object_name, method, objectify_options(options)) - end - - # Returns a file upload input tag tailored for accessing a specified attribute (identified by +method+) on an object - # assigned to the template (identified by +object+). Additional options on the input tag can be passed as a - # hash with +options+. These options will be tagged onto the HTML as an HTML element attribute as in the example - # shown. - # - # Using this method inside a +form_for+ block will set the enclosing form's encoding to multipart/form-data. - # - # ==== Options - # * Creates standard HTML attributes for the tag. - # * :disabled - If set to true, the user will not be able to use this input. - # * :multiple - If set to true, *in most updated browsers* the user will be allowed to select multiple files. - # * :accept - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations. - # - # ==== Examples - # # Let's say that @user has avatar: - # file_field(:avatar) - # # => - # - # # Let's say that @post has image: - # file_field(:image, :multiple => true) - # # => - # - # # Let's say that @post has attached: - # file_field(:attached, accept: 'text/html') - # # => - # - # # Let's say that @post has image: - # file_field(:image, accept: 'image/png,image/gif,image/jpeg') - # # => - # - # # Let's say that @attachment has file: - # file_field(:file, class: 'file_input') - # # => - def file_field(method, options = {}) - self.multipart = true - @template.file_field(@object_name, method, objectify_options(options)) - end - - # Add the submit button for the given form. When no value is given, it checks - # if the object is a new resource or not to create the proper label: - # - # <%= form_for @post do |f| %> - # <%= f.submit %> - # <% end %> - # - # In the example above, if @post is a new record, it will use "Create Post" as - # submit button label, otherwise, it uses "Update Post". - # - # Those labels can be customized using I18n, under the helpers.submit key and accept - # the %{model} as translation interpolation: - # - # en: - # helpers: - # submit: - # create: "Create a %{model}" - # update: "Confirm changes to %{model}" - # - # It also searches for a key specific for the given object: - # - # en: - # helpers: - # submit: - # post: - # create: "Add %{model}" - # - def submit(value = nil, options = {}) - value, options = nil, value if value.is_a?(Hash) - value ||= submit_default_value - @template.submit_tag(value, options) - end - - # Add the submit button for the given form. When no value is given, it checks - # if the object is a new resource or not to create the proper label: - # - # <%= form_for @post do |f| %> - # <%= f.button %> - # <% end %> - # - # In the example above, if @post is a new record, it will use "Create Post" as - # button label, otherwise, it uses "Update Post". - # - # Those labels can be customized using I18n, under the helpers.submit key - # (the same as submit helper) and accept the %{model} as translation interpolation: - # - # en: - # helpers: - # submit: - # create: "Create a %{model}" - # update: "Confirm changes to %{model}" - # - # It also searches for a key specific for the given object: - # - # en: - # helpers: - # submit: - # post: - # create: "Add %{model}" - # - # ==== Examples - # button("Create post") - # # => - # - # button do - # content_tag(:strong, 'Ask me!') - # end - # # => - # - def button(value = nil, options = {}, &block) - value, options = nil, value if value.is_a?(Hash) - value ||= submit_default_value - @template.button_tag(value, options, &block) - end - - def emitted_hidden_id? - @emitted_hidden_id ||= nil - end - - private - def objectify_options(options) - @default_options.merge(options.merge(object: @object)) - end - - def submit_default_value - object = convert_to_model(@object) - key = object ? (object.persisted? ? :update : :create) : :submit - - model = if object.respond_to?(:model_name) - object.model_name.human - else - @object_name.to_s.humanize - end - - defaults = [] - defaults << :"helpers.submit.#{object_name}.#{key}" - defaults << :"helpers.submit.#{key}" - defaults << "#{key.to_s.humanize} #{model}" - - I18n.t(defaults.shift, model: model, default: defaults) - end - - def nested_attributes_association?(association_name) - @object.respond_to?("#{association_name}_attributes=") - end - - def fields_for_with_nested_attributes(association_name, association, options, block) - name = "#{object_name}[#{association_name}_attributes]" - association = convert_to_model(association) - - if association.respond_to?(:persisted?) - association = [association] if @object.send(association_name).respond_to?(:to_ary) - elsif !association.respond_to?(:to_ary) - association = @object.send(association_name) - end - - if association.respond_to?(:to_ary) - explicit_child_index = options[:child_index] - output = ActiveSupport::SafeBuffer.new - association.each do |child| - if explicit_child_index - options[:child_index] = explicit_child_index.call if explicit_child_index.respond_to?(:call) - else - options[:child_index] = nested_child_index(name) - end - output << fields_for_nested_model("#{name}[#{options[:child_index]}]", child, options, block) - end - output - elsif association - fields_for_nested_model(name, association, options, block) - end - end - - def fields_for_nested_model(name, object, fields_options, block) - object = convert_to_model(object) - emit_hidden_id = object.persisted? && fields_options.fetch(:include_id) { - options.fetch(:include_id, true) - } - - @template.fields_for(name, object, fields_options) do |f| - output = @template.capture(f, &block) - output.concat f.hidden_field(:id) if output && emit_hidden_id && !f.emitted_hidden_id? - output - end - end - - def nested_child_index(name) - @nested_child_index[name] ||= -1 - @nested_child_index[name] += 1 - end - - def convert_to_legacy_options(options) - if options.key?(:skip_id) - options[:include_id] = !options.delete(:skip_id) - end - end - end - end - - ActiveSupport.on_load(:action_view) do - cattr_accessor(:default_form_builder, instance_writer: false, instance_reader: false) do - ::ActionView::Helpers::FormBuilder - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_options_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_options_helper.rb deleted file mode 100644 index 07d4310a4e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_options_helper.rb +++ /dev/null @@ -1,881 +0,0 @@ -require "cgi" -require "erb" -require "action_view/helpers/form_helper" -require "active_support/core_ext/string/output_safety" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/array/wrap" - -module ActionView - # = Action View Form Option Helpers - module Helpers - # Provides a number of methods for turning different kinds of containers into a set of option tags. - # - # The collection_select, select and time_zone_select methods take an options parameter, a hash: - # - # * :include_blank - set to true or a prompt string if the first option element of the select element is a blank. Useful if there is not a default value required for the select element. - # - # select("post", "category", Post::CATEGORIES, {include_blank: true}) - # - # could become: - # - # - # - # Another common case is a select tag for a belongs_to-associated object. - # - # Example with @post.person_id => 2: - # - # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: 'None'}) - # - # could become: - # - # - # - # * :prompt - set to true or a prompt string. When the select element doesn't have a value yet, this prepends an option with a generic prompt -- "Please select" -- or the given prompt string. - # - # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {prompt: 'Select Person'}) - # - # could become: - # - # - # - # * :index - like the other form helpers, +select+ can accept an :index option to manually set the ID used in the resulting output. Unlike other helpers, +select+ expects this - # option to be in the +html_options+ parameter. - # - # select("album[]", "genre", %w[rap rock country], {}, { index: nil }) - # - # becomes: - # - # - # - # * :disabled - can be a single value or an array of values that will be disabled options in the final output. - # - # select("post", "category", Post::CATEGORIES, {disabled: 'restricted'}) - # - # could become: - # - # - # - # When used with the collection_select helper, :disabled can also be a Proc that identifies those options that should be disabled. - # - # collection_select(:post, :category_id, Category.all, :id, :name, {disabled: -> (category) { category.archived? }}) - # - # If the categories "2008 stuff" and "Christmas" return true when the method archived? is called, this would return: - # - # - module FormOptionsHelper - # ERB::Util can mask some helpers like textilize. Make sure to include them. - include TextHelper - - # Create a select tag and a series of contained option tags for the provided object and method. - # The option currently held by the object will be selected, provided that the object is available. - # - # There are two possible formats for the +choices+ parameter, corresponding to other helpers' output: - # - # * A flat collection (see +options_for_select+). - # - # * A nested collection (see +grouped_options_for_select+). - # - # For example: - # - # select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true }) - # - # would become: - # - # - # - # assuming the associated person has ID 1. - # - # This can be used to provide a default set of options in the standard way: before rendering the create form, a - # new model instance is assigned the default options and bound to @model_name. Usually this model is not saved - # to the database. Instead, a second model object is created when the create request is received. - # This allows the user to submit a form page more than once with the expected results of creating multiple records. - # In addition, this allows a single partial to be used to generate form inputs for both edit and create forms. - # - # By default, post.person_id is the selected option. Specify selected: value to use a different selection - # or selected: nil to leave all options unselected. Similarly, you can specify values to be disabled in the option - # tags by specifying the :disabled option. This can either be a single value or an array of values to be disabled. - # - # A block can be passed to +select+ to customize how the options tags will be rendered. This - # is useful when the options tag has complex attributes. - # - # select(report, "campaign_ids") do - # available_campaigns.each do |c| - # content_tag(:option, c.name, value: c.id, data: { tags: c.tags.to_json }) - # end - # end - # - # ==== Gotcha - # - # The HTML specification says when +multiple+ parameter passed to select and all options got deselected - # web browsers do not send any value to server. Unfortunately this introduces a gotcha: - # if an +User+ model has many +roles+ and have +role_ids+ accessor, and in the form that edits roles of the user - # the user deselects all roles from +role_ids+ multiple select box, no +role_ids+ parameter is sent. So, - # any mass-assignment idiom like - # - # @user.update(params[:user]) - # - # wouldn't update roles. - # - # To prevent this the helper generates an auxiliary hidden field before - # every multiple select. The hidden field has the same name as multiple select and blank value. - # - # Note: The client either sends only the hidden field (representing - # the deselected multiple select box), or both fields. This means that the resulting array - # always contains a blank string. - # - # In case if you don't want the helper to generate this hidden field you can specify - # include_hidden: false option. - # - def select(object, method, choices = nil, options = {}, html_options = {}, &block) - Tags::Select.new(object, method, self, choices, options, html_options, &block).render - end - - # Returns - # - # - # - # - # - def collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) - Tags::CollectionSelect.new(object, method, self, collection, value_method, text_method, options, html_options).render - end - - # Returns - # - # - # - # - # - # - # - # - # - # - def grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) - Tags::GroupedCollectionSelect.new(object, method, self, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options).render - end - - # Returns select and option tags for the given object and method, using - # #time_zone_options_for_select to generate the list of option tags. - # - # In addition to the :include_blank option documented above, - # this method also supports a :model option, which defaults - # to ActiveSupport::TimeZone. This may be used by users to specify a - # different time zone model object. (See +time_zone_options_for_select+ - # for more information.) - # - # You can also supply an array of ActiveSupport::TimeZone objects - # as +priority_zones+ so that they will be listed above the rest of the - # (long) list. You can use ActiveSupport::TimeZone.us_zones for a list - # of US time zones, ActiveSupport::TimeZone.country_zones(country_code) - # for another country's time zones, or a Regexp to select the zones of - # your choice. - # - # Finally, this method supports a :default option, which selects - # a default ActiveSupport::TimeZone if the object's time zone is +nil+. - # - # time_zone_select( "user", "time_zone", nil, include_blank: true) - # - # time_zone_select( "user", "time_zone", nil, default: "Pacific Time (US & Canada)" ) - # - # time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, default: "Pacific Time (US & Canada)") - # - # time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ]) - # - # time_zone_select( "user", 'time_zone', /Australia/) - # - # time_zone_select( "user", "time_zone", ActiveSupport::TimeZone.all.sort, model: ActiveSupport::TimeZone) - def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {}) - Tags::TimeZoneSelect.new(object, method, self, priority_zones, options, html_options).render - end - - # Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Given a container - # where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and - # the "firsts" as option text. Hashes are turned into this form automatically, so the keys become "firsts" and values - # become lasts. If +selected+ is specified, the matching "last" or element will get the selected option-tag. +selected+ - # may also be an array of values to be selected when using a multiple select. - # - # options_for_select([["Dollar", "$"], ["Kroner", "DKK"]]) - # # => - # # => - # - # options_for_select([ "VISA", "MasterCard" ], "MasterCard") - # # => - # # => - # - # options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40") - # # => - # # => - # - # options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"]) - # # => - # # => - # # => - # - # You can optionally provide HTML attributes as the last element of the array. - # - # options_for_select([ "Denmark", ["USA", {class: 'bold'}], "Sweden" ], ["USA", "Sweden"]) - # # => - # # => - # # => - # - # options_for_select([["Dollar", "$", {class: "bold"}], ["Kroner", "DKK", {onclick: "alert('HI');"}]]) - # # => - # # => - # - # If you wish to specify disabled option tags, set +selected+ to be a hash, with :disabled being either a value - # or array of values to be disabled. In this case, you can use :selected to specify selected option tags. - # - # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: "Super Platinum") - # # => - # # => - # # => - # # => - # - # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], disabled: ["Advanced", "Super Platinum"]) - # # => - # # => - # # => - # # => - # - # options_for_select(["Free", "Basic", "Advanced", "Super Platinum"], selected: "Free", disabled: "Super Platinum") - # # => - # # => - # # => - # # => - # - # NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. - def options_for_select(container, selected = nil) - return container if String === container - - selected, disabled = extract_selected_and_disabled(selected).map do |r| - Array(r).map(&:to_s) - end - - container.map do |element| - html_attributes = option_html_attributes(element) - text, value = option_text_and_value(element).map(&:to_s) - - html_attributes[:selected] ||= option_value_selected?(value, selected) - html_attributes[:disabled] ||= disabled && option_value_selected?(value, disabled) - html_attributes[:value] = value - - tag_builder.content_tag_string(:option, text, html_attributes) - end.join("\n").html_safe - end - - # Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning - # the result of a call to the +value_method+ as the option value and the +text_method+ as the option text. - # - # options_from_collection_for_select(@people, 'id', 'name') - # # => - # - # This is more often than not used inside a #select_tag like this example: - # - # select_tag 'person', options_from_collection_for_select(@people, 'id', 'name') - # - # If +selected+ is specified as a value or array of values, the element(s) returning a match on +value_method+ - # will be selected option tag(s). - # - # If +selected+ is specified as a Proc, those members of the collection that return true for the anonymous - # function are the selected values. - # - # +selected+ can also be a hash, specifying both :selected and/or :disabled values as required. - # - # Be sure to specify the same class as the +value_method+ when specifying selected or disabled options. - # Failure to do this will produce undesired results. Example: - # options_from_collection_for_select(@people, 'id', 'name', '1') - # Will not select a person with the id of 1 because 1 (an Integer) is not the same as '1' (a string) - # options_from_collection_for_select(@people, 'id', 'name', 1) - # should produce the desired results. - def options_from_collection_for_select(collection, value_method, text_method, selected = nil) - options = collection.map do |element| - [value_for_collection(element, text_method), value_for_collection(element, value_method), option_html_attributes(element)] - end - selected, disabled = extract_selected_and_disabled(selected) - select_deselect = { - selected: extract_values_from_collection(collection, value_method, selected), - disabled: extract_values_from_collection(collection, value_method, disabled) - } - - options_for_select(options, select_deselect) - end - - # Returns a string of tags, like options_from_collection_for_select, but - # groups them by tags based on the object relationships of the arguments. - # - # Parameters: - # * +collection+ - An array of objects representing the tags. - # * +group_method+ - The name of a method which, when called on a member of +collection+, returns an - # array of child objects representing the tags. - # * +group_label_method+ - The name of a method which, when called on a member of +collection+, returns a - # string to be used as the +label+ attribute for its tag. - # * +option_key_method+ - The name of a method which, when called on a child object of a member of - # +collection+, returns a value to be used as the +value+ attribute for its tag. - # * +option_value_method+ - The name of a method which, when called on a child object of a member of - # +collection+, returns a value to be used as the contents of its tag. - # * +selected_key+ - A value equal to the +value+ attribute for one of the tags, - # which will have the +selected+ attribute set. Corresponds to the return value of one of the calls - # to +option_key_method+. If +nil+, no selection is made. Can also be a hash if disabled values are - # to be specified. - # - # Example object structure for use with this method: - # - # class Continent < ActiveRecord::Base - # has_many :countries - # # attribs: id, name - # end - # - # class Country < ActiveRecord::Base - # belongs_to :continent - # # attribs: id, name, continent_id - # end - # - # Sample usage: - # option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3) - # - # Possible output: - # - # - # - # ... - # - # - # - # - # - # ... - # - # - # Note: Only the and tags are returned, so you still have to - # wrap the output in an appropriate tag. - def grouped_options_for_select(grouped_options, selected_key = nil, options = {}) - prompt = options[:prompt] - divider = options[:divider] - - body = "".html_safe - - if prompt - body.safe_concat content_tag("option".freeze, prompt_text(prompt), value: "") - end - - grouped_options.each do |container| - html_attributes = option_html_attributes(container) - - if divider - label = divider - else - label, container = container - end - - html_attributes = { label: label }.merge!(html_attributes) - body.safe_concat content_tag("optgroup".freeze, options_for_select(container, selected_key), html_attributes) - end - - body - end - - # Returns a string of option tags for pretty much any time zone in the - # world. Supply an ActiveSupport::TimeZone name as +selected+ to have it - # marked as the selected option tag. You can also supply an array of - # ActiveSupport::TimeZone objects as +priority_zones+, so that they will - # be listed above the rest of the (long) list. (You can use - # ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list - # of the US time zones, or a Regexp to select the zones of your choice) - # - # The +selected+ parameter must be either +nil+, or a string that names - # an ActiveSupport::TimeZone. - # - # By default, +model+ is the ActiveSupport::TimeZone constant (which can - # be obtained in Active Record as a value object). The only requirement - # is that the +model+ parameter be an object that responds to +all+, and - # returns an array of objects that represent time zones. - # - # NOTE: Only the option tags are returned, you have to wrap this call in - # a regular HTML select tag. - def time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone) - zone_options = "".html_safe - - zones = model.all - convert_zones = lambda { |list| list.map { |z| [ z.to_s, z.name ] } } - - if priority_zones - if priority_zones.is_a?(Regexp) - priority_zones = zones.select { |z| z =~ priority_zones } - end - - zone_options.safe_concat options_for_select(convert_zones[priority_zones], selected) - zone_options.safe_concat content_tag("option".freeze, "-------------", value: "", disabled: true) - zone_options.safe_concat "\n" - - zones = zones - priority_zones - end - - zone_options.safe_concat options_for_select(convert_zones[zones], selected) - end - - # Returns radio button tags for the collection of existing return values - # of +method+ for +object+'s class. The value returned from calling - # +method+ on the instance +object+ will be selected. If calling +method+ - # returns +nil+, no selection is made. - # - # The :value_method and :text_method parameters are - # methods to be called on each member of +collection+. The return values - # are used as the +value+ attribute and contents of each radio button tag, - # respectively. They can also be any object that responds to +call+, such - # as a +proc+, that will be called for each member of the +collection+ to - # retrieve the value/text. - # - # Example object structure for use with this method: - # class Post < ActiveRecord::Base - # belongs_to :author - # end - # class Author < ActiveRecord::Base - # has_many :posts - # def name_with_initial - # "#{first_name.first}. #{last_name}" - # end - # end - # - # Sample usage (selecting the associated Author for an instance of Post, @post): - # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) - # - # If @post.author_id is already 1, this would return: - # - # - # - # - # - # - # - # It is also possible to customize the way the elements will be shown by - # giving a block to the method: - # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b| - # b.label { b.radio_button } - # end - # - # The argument passed to the block is a special kind of builder for this - # collection, which has the ability to generate the label and radio button - # for the current item in the collection, with proper text and value. - # Using it, you can change the label and radio button display order or - # even use the label as wrapper, as in the example above. - # - # The builder methods label and radio_button also accept - # extra HTML options: - # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b| - # b.label(class: "radio_button") { b.radio_button(class: "radio_button") } - # end - # - # There are also three special methods available: object, text and - # value, which are the current item being rendered, its text and value methods, - # respectively. You can use them like this: - # collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial) do |b| - # b.label(:"data-value" => b.value) { b.radio_button + b.text } - # end - # - # ==== Gotcha - # - # The HTML specification says when nothing is select on a collection of radio buttons - # web browsers do not send any value to server. - # Unfortunately this introduces a gotcha: - # if a +User+ model has a +category_id+ field and in the form no category is selected, no +category_id+ parameter is sent. So, - # any strong parameters idiom like: - # - # params.require(:user).permit(...) - # - # will raise an error since no {user: ...} will be present. - # - # To prevent this the helper generates an auxiliary hidden field before - # every collection of radio buttons. The hidden field has the same name as collection radio button and blank value. - # - # In case if you don't want the helper to generate this hidden field you can specify - # include_hidden: false option. - def collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block) - Tags::CollectionRadioButtons.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block) - end - - # Returns check box tags for the collection of existing return values of - # +method+ for +object+'s class. The value returned from calling +method+ - # on the instance +object+ will be selected. If calling +method+ returns - # +nil+, no selection is made. - # - # The :value_method and :text_method parameters are - # methods to be called on each member of +collection+. The return values - # are used as the +value+ attribute and contents of each check box tag, - # respectively. They can also be any object that responds to +call+, such - # as a +proc+, that will be called for each member of the +collection+ to - # retrieve the value/text. - # - # Example object structure for use with this method: - # class Post < ActiveRecord::Base - # has_and_belongs_to_many :authors - # end - # class Author < ActiveRecord::Base - # has_and_belongs_to_many :posts - # def name_with_initial - # "#{first_name.first}. #{last_name}" - # end - # end - # - # Sample usage (selecting the associated Author for an instance of Post, @post): - # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) - # - # If @post.author_ids is already [1], this would return: - # - # - # - # - # - # - # - # - # It is also possible to customize the way the elements will be shown by - # giving a block to the method: - # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b| - # b.label { b.check_box } - # end - # - # The argument passed to the block is a special kind of builder for this - # collection, which has the ability to generate the label and check box - # for the current item in the collection, with proper text and value. - # Using it, you can change the label and check box display order or even - # use the label as wrapper, as in the example above. - # - # The builder methods label and check_box also accept - # extra HTML options: - # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b| - # b.label(class: "check_box") { b.check_box(class: "check_box") } - # end - # - # There are also three special methods available: object, text and - # value, which are the current item being rendered, its text and value methods, - # respectively. You can use them like this: - # collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) do |b| - # b.label(:"data-value" => b.value) { b.check_box + b.text } - # end - # - # ==== Gotcha - # - # When no selection is made for a collection of checkboxes most - # web browsers will not send any value. - # - # For example, if we have a +User+ model with +category_ids+ field and we - # have the following code in our update action: - # - # @user.update(params[:user]) - # - # If no +category_ids+ are selected then we can safely assume this field - # will not be updated. - # - # This is possible thanks to a hidden field generated by the helper method - # for every collection of checkboxes. - # This hidden field is given the same field name as the checkboxes with a - # blank value. - # - # In the rare case you don't want this hidden field, you can pass the - # include_hidden: false option to the helper method. - def collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block) - Tags::CollectionCheckBoxes.new(object, method, self, collection, value_method, text_method, options, html_options).render(&block) - end - - private - def option_html_attributes(element) - if Array === element - element.select { |e| Hash === e }.reduce({}, :merge!) - else - {} - end - end - - def option_text_and_value(option) - # Options are [text, value] pairs or strings used for both. - if !option.is_a?(String) && option.respond_to?(:first) && option.respond_to?(:last) - option = option.reject { |e| Hash === e } if Array === option - [option.first, option.last] - else - [option, option] - end - end - - def option_value_selected?(value, selected) - Array(selected).include? value - end - - def extract_selected_and_disabled(selected) - if selected.is_a?(Proc) - [selected, nil] - else - selected = Array.wrap(selected) - options = selected.extract_options!.symbolize_keys - selected_items = options.fetch(:selected, selected) - [selected_items, options[:disabled]] - end - end - - def extract_values_from_collection(collection, value_method, selected) - if selected.is_a?(Proc) - collection.map do |element| - element.send(value_method) if selected.call(element) - end.compact - else - selected - end - end - - def value_for_collection(item, value) - value.respond_to?(:call) ? value.call(item) : item.send(value) - end - - def prompt_text(prompt) - prompt.kind_of?(String) ? prompt : I18n.translate("helpers.select.prompt", default: "Please select") - end - end - - class FormBuilder - # Wraps ActionView::Helpers::FormOptionsHelper#select for form builders: - # - # <%= form_for @post do |f| %> - # <%= f.select :person_id, Person.all.collect { |p| [ p.name, p.id ] }, include_blank: true %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def select(method, choices = nil, options = {}, html_options = {}, &block) - @template.select(@object_name, method, choices, objectify_options(options), @default_options.merge(html_options), &block) - end - - # Wraps ActionView::Helpers::FormOptionsHelper#collection_select for form builders: - # - # <%= form_for @post do |f| %> - # <%= f.collection_select :person_id, Author.all, :id, :name_with_initial, prompt: true %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def collection_select(method, collection, value_method, text_method, options = {}, html_options = {}) - @template.collection_select(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options)) - end - - # Wraps ActionView::Helpers::FormOptionsHelper#grouped_collection_select for form builders: - # - # <%= form_for @city do |f| %> - # <%= f.grouped_collection_select :country_id, @continents, :countries, :name, :id, :name %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {}) - @template.grouped_collection_select(@object_name, method, collection, group_method, group_label_method, option_key_method, option_value_method, objectify_options(options), @default_options.merge(html_options)) - end - - # Wraps ActionView::Helpers::FormOptionsHelper#time_zone_select for form builders: - # - # <%= form_for @user do |f| %> - # <%= f.time_zone_select :time_zone, nil, include_blank: true %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def time_zone_select(method, priority_zones = nil, options = {}, html_options = {}) - @template.time_zone_select(@object_name, method, priority_zones, objectify_options(options), @default_options.merge(html_options)) - end - - # Wraps ActionView::Helpers::FormOptionsHelper#collection_check_boxes for form builders: - # - # <%= form_for @post do |f| %> - # <%= f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def collection_check_boxes(method, collection, value_method, text_method, options = {}, html_options = {}, &block) - @template.collection_check_boxes(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block) - end - - # Wraps ActionView::Helpers::FormOptionsHelper#collection_radio_buttons for form builders: - # - # <%= form_for @post do |f| %> - # <%= f.collection_radio_buttons :author_id, Author.all, :id, :name_with_initial %> - # <%= f.submit %> - # <% end %> - # - # Please refer to the documentation of the base helper for details. - def collection_radio_buttons(method, collection, value_method, text_method, options = {}, html_options = {}, &block) - @template.collection_radio_buttons(@object_name, method, collection, value_method, text_method, objectify_options(options), @default_options.merge(html_options), &block) - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_tag_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_tag_helper.rb deleted file mode 100644 index 9fc08b3837..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/form_tag_helper.rb +++ /dev/null @@ -1,907 +0,0 @@ -require "cgi" -require "action_view/helpers/tag_helper" -require "active_support/core_ext/string/output_safety" -require "active_support/core_ext/module/attribute_accessors" - -module ActionView - # = Action View Form Tag Helpers - module Helpers - # Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like - # FormHelper does. Instead, you provide the names and values manually. - # - # NOTE: The HTML options disabled, readonly, and multiple can all be treated as booleans. So specifying - # disabled: true will give disabled="disabled". - module FormTagHelper - extend ActiveSupport::Concern - - include UrlHelper - include TextHelper - - mattr_accessor :embed_authenticity_token_in_remote_forms - self.embed_authenticity_token_in_remote_forms = nil - - # Starts a form tag that points the action to a url configured with url_for_options just like - # ActionController::Base#url_for. The method for the form defaults to POST. - # - # ==== Options - # * :multipart - If set to true, the enctype is set to "multipart/form-data". - # * :method - The method to use when submitting the form, usually either "get" or "post". - # If "patch", "put", "delete", or another verb is used, a hidden input with name _method - # is added to simulate the verb over post. - # * :authenticity_token - Authenticity token to use in the form. Use only if you need to - # pass custom authenticity token string, or to not add authenticity_token field at all - # (by passing false). Remote forms may omit the embedded authenticity token - # by setting config.action_view.embed_authenticity_token_in_remote_forms = false. - # This is helpful when you're fragment-caching the form. Remote forms get the - # authenticity token from the meta tag, so embedding is unnecessary unless you - # support browsers without JavaScript. - # * :remote - If set to true, will allow the Unobtrusive JavaScript drivers to control the - # submit behavior. By default this behavior is an ajax submit. - # * :enforce_utf8 - If set to false, a hidden input with name utf8 is not output. - # * Any other key creates standard HTML attributes for the tag. - # - # ==== Examples - # form_tag('/posts') - # # =>
    - # - # form_tag('/posts/1', method: :put) - # # => ... ... - # - # form_tag('/upload', multipart: true) - # # => - # - # <%= form_tag('/posts') do -%> - #
    <%= submit_tag 'Save' %>
    - # <% end -%> - # # =>
    - # - # <%= form_tag('/posts', remote: true) %> - # # =>
    - # - # form_tag('http://far.away.com/form', authenticity_token: false) - # # form without authenticity token - # - # form_tag('http://far.away.com/form', authenticity_token: "cf50faa3fe97702ca1ae") - # # form with custom authenticity token - # - def form_tag(url_for_options = {}, options = {}, &block) - html_options = html_options_for_form(url_for_options, options) - if block_given? - form_tag_with_body(html_options, capture(&block)) - else - form_tag_html(html_options) - end - end - - # Creates a dropdown selection box, or if the :multiple option is set to true, a multiple - # choice selection box. - # - # Helpers::FormOptions can be used to create common select boxes such as countries, time zones, or - # associated records. option_tags is a string containing the option tags for the select box. - # - # ==== Options - # * :multiple - If set to true, the selection will allow multiple choices. - # * :disabled - If set to true, the user will not be able to use this input. - # * :include_blank - If set to true, an empty option will be created. If set to a string, the string will be used as the option's content and the value will be empty. - # * :prompt - Create a prompt option with blank value and the text asking user to select something. - # * Any other key creates standard HTML attributes for the tag. - # - # ==== Examples - # select_tag "people", options_from_collection_for_select(@people, "id", "name") - # # - # - # select_tag "people", options_from_collection_for_select(@people, "id", "name", "1") - # # - # - # select_tag "people", raw("") - # # => - # - # select_tag "count", raw("") - # # => - # - # select_tag "colors", raw(""), multiple: true - # # => - # - # select_tag "locations", raw("") - # # => - # - # select_tag "access", raw(""), multiple: true, class: 'form_input', id: 'unique_id' - # # => - # - # select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: true - # # => - # - # select_tag "people", options_from_collection_for_select(@people, "id", "name"), include_blank: "All" - # # => - # - # select_tag "people", options_from_collection_for_select(@people, "id", "name"), prompt: "Select something" - # # => - # - # select_tag "destination", raw(""), disabled: true - # # => - # - # select_tag "credit_card", options_for_select([ "VISA", "MasterCard" ], "MasterCard") - # # => - def select_tag(name, option_tags = nil, options = {}) - option_tags ||= "" - html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name - - if options.include?(:include_blank) - include_blank = options.delete(:include_blank) - options_for_blank_options_tag = { value: "" } - - if include_blank == true - include_blank = "" - options_for_blank_options_tag[:label] = " " - end - - if include_blank - option_tags = content_tag("option".freeze, include_blank, options_for_blank_options_tag).safe_concat(option_tags) - end - end - - if prompt = options.delete(:prompt) - option_tags = content_tag("option".freeze, prompt, value: "").safe_concat(option_tags) - end - - content_tag "select".freeze, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys) - end - - # Creates a standard text field; use these text fields to input smaller chunks of text like a username - # or a search query. - # - # ==== Options - # * :disabled - If set to true, the user will not be able to use this input. - # * :size - The number of visible characters that will fit in the input. - # * :maxlength - The maximum number of characters that the browser will allow the user to enter. - # * :placeholder - The text contained in the field by default which is removed when the field receives focus. - # * Any other key creates standard HTML attributes for the tag. - # - # ==== Examples - # text_field_tag 'name' - # # => - # - # text_field_tag 'query', 'Enter your search query here' - # # => - # - # text_field_tag 'search', nil, placeholder: 'Enter search term...' - # # => - # - # text_field_tag 'request', nil, class: 'special_input' - # # => - # - # text_field_tag 'address', '', size: 75 - # # => - # - # text_field_tag 'zip', nil, maxlength: 5 - # # => - # - # text_field_tag 'payment_amount', '$0.00', disabled: true - # # => - # - # text_field_tag 'ip', '0.0.0.0', maxlength: 15, size: 20, class: "ip-input" - # # => - def text_field_tag(name, value = nil, options = {}) - tag :input, { "type" => "text", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys) - end - - # Creates a label element. Accepts a block. - # - # ==== Options - # * Creates standard HTML attributes for the tag. - # - # ==== Examples - # label_tag 'name' - # # => - # - # label_tag 'name', 'Your name' - # # => - # - # label_tag 'name', nil, class: 'small_label' - # # => - def label_tag(name = nil, content_or_options = nil, options = nil, &block) - if block_given? && content_or_options.is_a?(Hash) - options = content_or_options = content_or_options.stringify_keys - else - options ||= {} - options = options.stringify_keys - end - options["for"] = sanitize_to_id(name) unless name.blank? || options.has_key?("for") - content_tag :label, content_or_options || name.to_s.humanize, options, &block - end - - # Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or - # data that should be hidden from the user. - # - # ==== Options - # * Creates standard HTML attributes for the tag. - # - # ==== Examples - # hidden_field_tag 'tags_list' - # # => - # - # hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@' - # # => - # - # hidden_field_tag 'collected_input', '', onchange: "alert('Input collected!')" - # # => - def hidden_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :hidden)) - end - - # Creates a file upload field. If you are using file uploads then you will also need - # to set the multipart option for the form tag: - # - # <%= form_tag '/upload', multipart: true do %> - # <%= file_field_tag "file" %> - # <%= submit_tag %> - # <% end %> - # - # The specified URL will then be passed a File object containing the selected file, or if the field - # was left blank, a StringIO object. - # - # ==== Options - # * Creates standard HTML attributes for the tag. - # * :disabled - If set to true, the user will not be able to use this input. - # * :multiple - If set to true, *in most updated browsers* the user will be allowed to select multiple files. - # * :accept - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations. - # - # ==== Examples - # file_field_tag 'attachment' - # # => - # - # file_field_tag 'avatar', class: 'profile_input' - # # => - # - # file_field_tag 'picture', disabled: true - # # => - # - # file_field_tag 'resume', value: '~/resume.doc' - # # => - # - # file_field_tag 'user_pic', accept: 'image/png,image/gif,image/jpeg' - # # => - # - # file_field_tag 'file', accept: 'text/html', class: 'upload', value: 'index.html' - # # => - def file_field_tag(name, options = {}) - text_field_tag(name, nil, options.merge(type: :file)) - end - - # Creates a password field, a masked text field that will hide the users input behind a mask character. - # - # ==== Options - # * :disabled - If set to true, the user will not be able to use this input. - # * :size - The number of visible characters that will fit in the input. - # * :maxlength - The maximum number of characters that the browser will allow the user to enter. - # * Any other key creates standard HTML attributes for the tag. - # - # ==== Examples - # password_field_tag 'pass' - # # => - # - # password_field_tag 'secret', 'Your secret here' - # # => - # - # password_field_tag 'masked', nil, class: 'masked_input_field' - # # => - # - # password_field_tag 'token', '', size: 15 - # # => - # - # password_field_tag 'key', nil, maxlength: 16 - # # => - # - # password_field_tag 'confirm_pass', nil, disabled: true - # # => - # - # password_field_tag 'pin', '1234', maxlength: 4, size: 6, class: "pin_input" - # # => - def password_field_tag(name = "password", value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :password)) - end - - # Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. - # - # ==== Options - # * :size - A string specifying the dimensions (columns by rows) of the textarea (e.g., "25x10"). - # * :rows - Specify the number of rows in the textarea - # * :cols - Specify the number of columns in the textarea - # * :disabled - If set to true, the user will not be able to use this input. - # * :escape - By default, the contents of the text input are HTML escaped. - # If you need unescaped contents, set this to false. - # * Any other key creates standard HTML attributes for the tag. - # - # ==== Examples - # text_area_tag 'post' - # # => - # - # text_area_tag 'bio', @user.bio - # # => - # - # text_area_tag 'body', nil, rows: 10, cols: 25 - # # => - # - # text_area_tag 'body', nil, size: "25x10" - # # => - # - # text_area_tag 'description', "Description goes here.", disabled: true - # # => - # - # text_area_tag 'comment', nil, class: 'comment_input' - # # => - def text_area_tag(name, content = nil, options = {}) - options = options.stringify_keys - - if size = options.delete("size") - options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split) - end - - escape = options.delete("escape") { true } - content = ERB::Util.html_escape(content) if escape - - content_tag :textarea, content.to_s.html_safe, { "name" => name, "id" => sanitize_to_id(name) }.update(options) - end - - # Creates a check box form input tag. - # - # ==== Options - # * :disabled - If set to true, the user will not be able to use this input. - # * Any other key creates standard HTML options for the tag. - # - # ==== Examples - # check_box_tag 'accept' - # # => - # - # check_box_tag 'rock', 'rock music' - # # => - # - # check_box_tag 'receive_email', 'yes', true - # # => - # - # check_box_tag 'tos', 'yes', false, class: 'accept_tos' - # # => - # - # check_box_tag 'eula', 'accepted', false, disabled: true - # # => - def check_box_tag(name, value = "1", checked = false, options = {}) - html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys) - html_options["checked"] = "checked" if checked - tag :input, html_options - end - - # Creates a radio button; use groups of radio buttons named the same to allow users to - # select from a group of options. - # - # ==== Options - # * :disabled - If set to true, the user will not be able to use this input. - # * Any other key creates standard HTML options for the tag. - # - # ==== Examples - # radio_button_tag 'gender', 'male' - # # => - # - # radio_button_tag 'receive_updates', 'no', true - # # => - # - # radio_button_tag 'time_slot', "3:00 p.m.", false, disabled: true - # # => - # - # radio_button_tag 'color', "green", true, class: "color_input" - # # => - def radio_button_tag(name, value, checked = false, options = {}) - html_options = { "type" => "radio", "name" => name, "id" => "#{sanitize_to_id(name)}_#{sanitize_to_id(value)}", "value" => value }.update(options.stringify_keys) - html_options["checked"] = "checked" if checked - tag :input, html_options - end - - # Creates a submit button with the text value as the caption. - # - # ==== Options - # * :data - This option can be used to add custom data attributes. - # * :disabled - If true, the user will not be able to use this input. - # * Any other key creates standard HTML options for the tag. - # - # ==== Data attributes - # - # * confirm: 'question?' - If present the unobtrusive JavaScript - # drivers will provide a prompt with the question specified. If the user accepts, - # the form is processed normally, otherwise no action is taken. - # * :disable_with - Value of this parameter will be used as the value for a - # disabled version of the submit button when the form is submitted. This feature is - # provided by the unobtrusive JavaScript driver. To disable this feature for a single submit tag - # pass :data => { disable_with: false } Defaults to value attribute. - # - # ==== Examples - # submit_tag - # # => - # - # submit_tag "Edit this article" - # # => - # - # submit_tag "Save edits", disabled: true - # # => - # - # submit_tag "Complete sale", data: { disable_with: "Submitting..." } - # # => - # - # submit_tag nil, class: "form_submit" - # # => - # - # submit_tag "Edit", class: "edit_button" - # # => - # - # submit_tag "Save", data: { confirm: "Are you sure?" } - # # => - # - def submit_tag(value = "Save changes", options = {}) - options = options.deep_stringify_keys - tag_options = { "type" => "submit", "name" => "commit", "value" => value }.update(options) - set_default_disable_with value, tag_options - tag :input, tag_options - end - - # Creates a button element that defines a submit button, - # reset button or a generic button which can be used in - # JavaScript, for example. You can use the button tag as a regular - # submit tag but it isn't supported in legacy browsers. However, - # the button tag does allow for richer labels such as images and emphasis, - # so this helper will also accept a block. By default, it will create - # a button tag with type `submit`, if type is not given. - # - # ==== Options - # * :data - This option can be used to add custom data attributes. - # * :disabled - If true, the user will not be able to - # use this input. - # * Any other key creates standard HTML options for the tag. - # - # ==== Data attributes - # - # * confirm: 'question?' - If present, the - # unobtrusive JavaScript drivers will provide a prompt with - # the question specified. If the user accepts, the form is - # processed normally, otherwise no action is taken. - # * :disable_with - Value of this parameter will be - # used as the value for a disabled version of the submit - # button when the form is submitted. This feature is provided - # by the unobtrusive JavaScript driver. - # - # ==== Examples - # button_tag - # # => - # - # button_tag 'Reset', type: 'reset' - # # => - # - # button_tag 'Button', type: 'button' - # # => - # - # button_tag 'Reset', type: 'reset', disabled: true - # # => - # - # button_tag(type: 'button') do - # content_tag(:strong, 'Ask me!') - # end - # # => - # - # button_tag "Save", data: { confirm: "Are you sure?" } - # # => - # - # button_tag "Checkout", data: { disable_with: "Please wait..." } - # # => - # - def button_tag(content_or_options = nil, options = nil, &block) - if content_or_options.is_a? Hash - options = content_or_options - else - options ||= {} - end - - options = { "name" => "button", "type" => "submit" }.merge!(options.stringify_keys) - - if block_given? - content_tag :button, options, &block - else - content_tag :button, content_or_options || "Button", options - end - end - - # Displays an image which when clicked will submit the form. - # - # source is passed to AssetTagHelper#path_to_image - # - # ==== Options - # * :data - This option can be used to add custom data attributes. - # * :disabled - If set to true, the user will not be able to use this input. - # * Any other key creates standard HTML options for the tag. - # - # ==== Data attributes - # - # * confirm: 'question?' - This will add a JavaScript confirm - # prompt with the question specified. If the user accepts, the form is - # processed normally, otherwise no action is taken. - # - # ==== Examples - # image_submit_tag("login.png") - # # => - # - # image_submit_tag("purchase.png", disabled: true) - # # => - # - # image_submit_tag("search.png", class: 'search_button', alt: 'Find') - # # => - # - # image_submit_tag("agree.png", disabled: true, class: "agree_disagree_button") - # # => - # - # image_submit_tag("save.png", data: { confirm: "Are you sure?" }) - # # => - def image_submit_tag(source, options = {}) - options = options.stringify_keys - tag :input, { "alt" => image_alt(source), "type" => "image", "src" => path_to_image(source) }.update(options) - end - - # Creates a field set for grouping HTML form elements. - # - # legend will become the fieldset's title (optional as per W3C). - # options accept the same values as tag. - # - # ==== Examples - # <%= field_set_tag do %> - #

    <%= text_field_tag 'name' %>

    - # <% end %> - # # =>

    - # - # <%= field_set_tag 'Your details' do %> - #

    <%= text_field_tag 'name' %>

    - # <% end %> - # # =>
    Your details

    - # - # <%= field_set_tag nil, class: 'format' do %> - #

    <%= text_field_tag 'name' %>

    - # <% end %> - # # =>

    - def field_set_tag(legend = nil, options = nil, &block) - output = tag(:fieldset, options, true) - output.safe_concat(content_tag("legend".freeze, legend)) unless legend.blank? - output.concat(capture(&block)) if block_given? - output.safe_concat("") - end - - # Creates a text field of type "color". - # - # ==== Options - # * Accepts the same options as text_field_tag. - # - # ==== Examples - # color_field_tag 'name' - # # => - # - # color_field_tag 'color', '#DEF726' - # # => - # - # color_field_tag 'color', nil, class: 'special_input' - # # => - # - # color_field_tag 'color', '#DEF726', class: 'special_input', disabled: true - # # => - def color_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :color)) - end - - # Creates a text field of type "search". - # - # ==== Options - # * Accepts the same options as text_field_tag. - # - # ==== Examples - # search_field_tag 'name' - # # => - # - # search_field_tag 'search', 'Enter your search query here' - # # => - # - # search_field_tag 'search', nil, class: 'special_input' - # # => - # - # search_field_tag 'search', 'Enter your search query here', class: 'special_input', disabled: true - # # => - def search_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :search)) - end - - # Creates a text field of type "tel". - # - # ==== Options - # * Accepts the same options as text_field_tag. - # - # ==== Examples - # telephone_field_tag 'name' - # # => - # - # telephone_field_tag 'tel', '0123456789' - # # => - # - # telephone_field_tag 'tel', nil, class: 'special_input' - # # => - # - # telephone_field_tag 'tel', '0123456789', class: 'special_input', disabled: true - # # => - def telephone_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :tel)) - end - alias phone_field_tag telephone_field_tag - - # Creates a text field of type "date". - # - # ==== Options - # * Accepts the same options as text_field_tag. - # - # ==== Examples - # date_field_tag 'name' - # # => - # - # date_field_tag 'date', '01/01/2014' - # # => - # - # date_field_tag 'date', nil, class: 'special_input' - # # => - # - # date_field_tag 'date', '01/01/2014', class: 'special_input', disabled: true - # # => - def date_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :date)) - end - - # Creates a text field of type "time". - # - # === Options - # * :min - The minimum acceptable value. - # * :max - The maximum acceptable value. - # * :step - The acceptable value granularity. - # * Otherwise accepts the same options as text_field_tag. - def time_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :time)) - end - - # Creates a text field of type "datetime-local". - # - # === Options - # * :min - The minimum acceptable value. - # * :max - The maximum acceptable value. - # * :step - The acceptable value granularity. - # * Otherwise accepts the same options as text_field_tag. - def datetime_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: "datetime-local")) - end - - alias datetime_local_field_tag datetime_field_tag - - # Creates a text field of type "month". - # - # === Options - # * :min - The minimum acceptable value. - # * :max - The maximum acceptable value. - # * :step - The acceptable value granularity. - # * Otherwise accepts the same options as text_field_tag. - def month_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :month)) - end - - # Creates a text field of type "week". - # - # === Options - # * :min - The minimum acceptable value. - # * :max - The maximum acceptable value. - # * :step - The acceptable value granularity. - # * Otherwise accepts the same options as text_field_tag. - def week_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :week)) - end - - # Creates a text field of type "url". - # - # ==== Options - # * Accepts the same options as text_field_tag. - # - # ==== Examples - # url_field_tag 'name' - # # => - # - # url_field_tag 'url', 'http://rubyonrails.org' - # # => - # - # url_field_tag 'url', nil, class: 'special_input' - # # => - # - # url_field_tag 'url', 'http://rubyonrails.org', class: 'special_input', disabled: true - # # => - def url_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :url)) - end - - # Creates a text field of type "email". - # - # ==== Options - # * Accepts the same options as text_field_tag. - # - # ==== Examples - # email_field_tag 'name' - # # => - # - # email_field_tag 'email', 'email@example.com' - # # => - # - # email_field_tag 'email', nil, class: 'special_input' - # # => - # - # email_field_tag 'email', 'email@example.com', class: 'special_input', disabled: true - # # => - def email_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.merge(type: :email)) - end - - # Creates a number field. - # - # ==== Options - # * :min - The minimum acceptable value. - # * :max - The maximum acceptable value. - # * :in - A range specifying the :min and - # :max values. - # * :within - Same as :in. - # * :step - The acceptable value granularity. - # * Otherwise accepts the same options as text_field_tag. - # - # ==== Examples - # number_field_tag 'quantity' - # # => - # - # number_field_tag 'quantity', '1' - # # => - # - # number_field_tag 'quantity', nil, class: 'special_input' - # # => - # - # number_field_tag 'quantity', nil, min: 1 - # # => - # - # number_field_tag 'quantity', nil, max: 9 - # # => - # - # number_field_tag 'quantity', nil, in: 1...10 - # # => - # - # number_field_tag 'quantity', nil, within: 1...10 - # # => - # - # number_field_tag 'quantity', nil, min: 1, max: 10 - # # => - # - # number_field_tag 'quantity', nil, min: 1, max: 10, step: 2 - # # => - # - # number_field_tag 'quantity', '1', class: 'special_input', disabled: true - # # => - def number_field_tag(name, value = nil, options = {}) - options = options.stringify_keys - options["type"] ||= "number" - if range = options.delete("in") || options.delete("within") - options.update("min" => range.min, "max" => range.max) - end - text_field_tag(name, value, options) - end - - # Creates a range form element. - # - # ==== Options - # * Accepts the same options as number_field_tag. - def range_field_tag(name, value = nil, options = {}) - number_field_tag(name, value, options.merge(type: :range)) - end - - # Creates the hidden UTF8 enforcer tag. Override this method in a helper - # to customize the tag. - def utf8_enforcer_tag - # Use raw HTML to ensure the value is written as an HTML entity; it - # needs to be the right character regardless of which encoding the - # browser infers. - ''.html_safe - end - - private - def html_options_for_form(url_for_options, options) - options.stringify_keys.tap do |html_options| - html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart") - # The following URL is unescaped, this is just a hash of options, and it is the - # responsibility of the caller to escape all the values. - html_options["action"] = url_for(url_for_options) - html_options["accept-charset"] = "UTF-8" - - html_options["data-remote"] = true if html_options.delete("remote") - - if html_options["data-remote"] && - !embed_authenticity_token_in_remote_forms && - html_options["authenticity_token"].blank? - # The authenticity token is taken from the meta tag in this case - html_options["authenticity_token"] = false - elsif html_options["authenticity_token"] == true - # Include the default authenticity_token, which is only generated when its set to nil, - # but we needed the true value to override the default of no authenticity_token on data-remote. - html_options["authenticity_token"] = nil - end - end - end - - def extra_tags_for_form(html_options) - authenticity_token = html_options.delete("authenticity_token") - method = html_options.delete("method").to_s.downcase - - method_tag = \ - case method - when "get" - html_options["method"] = "get" - "" - when "post", "" - html_options["method"] = "post" - token_tag(authenticity_token, form_options: { - action: html_options["action"], - method: "post" - }) - else - html_options["method"] = "post" - method_tag(method) + token_tag(authenticity_token, form_options: { - action: html_options["action"], - method: method - }) - end - - if html_options.delete("enforce_utf8") { true } - utf8_enforcer_tag + method_tag - else - method_tag - end - end - - def form_tag_html(html_options) - extra_tags = extra_tags_for_form(html_options) - tag(:form, html_options, true) + extra_tags - end - - def form_tag_with_body(html_options, content) - output = form_tag_html(html_options) - output << content - output.safe_concat("
    ") - end - - # see http://www.w3.org/TR/html4/types.html#type-name - def sanitize_to_id(name) - name.to_s.delete("]").tr("^-a-zA-Z0-9:.", "_") - end - - def set_default_disable_with(value, tag_options) - return unless ActionView::Base.automatically_disable_submit_tag - data = tag_options["data"] - - unless tag_options["data-disable-with"] == false || (data && data["disable_with"] == false) - disable_with_text = tag_options["data-disable-with"] - disable_with_text ||= data["disable_with"] if data - disable_with_text ||= value.to_s.clone - tag_options.deep_merge!("data" => { "disable_with" => disable_with_text }) - else - data.delete("disable_with") if data - end - - tag_options.delete("data-disable-with") - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/javascript_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/javascript_helper.rb deleted file mode 100644 index 22e1e74ad6..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/javascript_helper.rb +++ /dev/null @@ -1,81 +0,0 @@ -require "action_view/helpers/tag_helper" - -module ActionView - module Helpers - module JavaScriptHelper - JS_ESCAPE_MAP = { - '\\' => '\\\\', - " '<\/', - "\r\n" => '\n', - "\n" => '\n', - "\r" => '\n', - '"' => '\\"', - "'" => "\\'" - } - - JS_ESCAPE_MAP["\342\200\250".force_encoding(Encoding::UTF_8).encode!] = "
" - JS_ESCAPE_MAP["\342\200\251".force_encoding(Encoding::UTF_8).encode!] = "
" - - # Escapes carriage returns and single and double quotes for JavaScript segments. - # - # Also available through the alias j(). This is particularly helpful in JavaScript - # responses, like: - # - # $('some_element').replaceWith('<%= j render 'some/element_template' %>'); - def escape_javascript(javascript) - if javascript - result = javascript.gsub(/(\\|<\/|\r\n|\342\200\250|\342\200\251|[\n\r"'])/u) { |match| JS_ESCAPE_MAP[match] } - javascript.html_safe? ? result.html_safe : result - else - "" - end - end - - alias_method :j, :escape_javascript - - # Returns a JavaScript tag with the +content+ inside. Example: - # javascript_tag "alert('All is good')" - # - # Returns: - # - # - # +html_options+ may be a hash of attributes for the \ - # - # Instead of passing the content as an argument, you can also use a block - # in which case, you pass your +html_options+ as the first parameter. - # - # <%= javascript_tag defer: 'defer' do -%> - # alert('All is good') - # <% end -%> - def javascript_tag(content_or_options_with_block = nil, html_options = {}, &block) - content = - if block_given? - html_options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash) - capture(&block) - else - content_or_options_with_block - end - - content_tag("script".freeze, javascript_cdata_section(content), html_options) - end - - def javascript_cdata_section(content) #:nodoc: - "\n//#{cdata_section("\n#{content}\n//")}\n".html_safe - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/number_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/number_helper.rb deleted file mode 100644 index b6bc5f4f6f..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/number_helper.rb +++ /dev/null @@ -1,449 +0,0 @@ -require "active_support/core_ext/hash/keys" -require "active_support/core_ext/string/output_safety" -require "active_support/number_helper" - -module ActionView - # = Action View Number Helpers - module Helpers #:nodoc: - # Provides methods for converting numbers into formatted strings. - # Methods are provided for phone numbers, currency, percentage, - # precision, positional notation, file size and pretty printing. - # - # Most methods expect a +number+ argument, and will return it - # unchanged if can't be converted into a valid number. - module NumberHelper - # Raised when argument +number+ param given to the helpers is invalid and - # the option :raise is set to +true+. - class InvalidNumberError < StandardError - attr_accessor :number - def initialize(number) - @number = number - end - end - - # Formats a +number+ into a phone number (US by default e.g., (555) - # 123-9876). You can customize the format in the +options+ hash. - # - # ==== Options - # - # * :area_code - Adds parentheses around the area code. - # * :delimiter - Specifies the delimiter to use - # (defaults to "-"). - # * :extension - Specifies an extension to add to the - # end of the generated number. - # * :country_code - Sets the country code for the phone - # number. - # * :pattern - Specifies how the number is divided into three - # groups with the custom regexp to override the default format. - # * :raise - If true, raises +InvalidNumberError+ when - # the argument is invalid. - # - # ==== Examples - # - # number_to_phone(5551234) # => 555-1234 - # number_to_phone("5551234") # => 555-1234 - # number_to_phone(1235551234) # => 123-555-1234 - # number_to_phone(1235551234, area_code: true) # => (123) 555-1234 - # number_to_phone(1235551234, delimiter: " ") # => 123 555 1234 - # number_to_phone(1235551234, area_code: true, extension: 555) # => (123) 555-1234 x 555 - # number_to_phone(1235551234, country_code: 1) # => +1-123-555-1234 - # number_to_phone("123a456") # => 123a456 - # number_to_phone("1234a567", raise: true) # => InvalidNumberError - # - # number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: ".") - # # => +1.123.555.1234 x 1343 - # - # number_to_phone(75561234567, pattern: /(\d{1,4})(\d{4})(\d{4})$/, area_code: true) - # # => "(755) 6123-4567" - # number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/)) - # # => "133-1234-5678" - def number_to_phone(number, options = {}) - return unless number - options = options.symbolize_keys - - parse_float(number, true) if options.delete(:raise) - ERB::Util.html_escape(ActiveSupport::NumberHelper.number_to_phone(number, options)) - end - - # Formats a +number+ into a currency string (e.g., $13.65). You - # can customize the format in the +options+ hash. - # - # The currency unit and number formatting of the current locale will be used - # unless otherwise specified in the provided options. No currency conversion - # is performed. If the user is given a way to change their locale, they will - # also be able to change the relative value of the currency displayed with - # this helper. If your application will ever support multiple locales, you - # may want to specify a constant :locale option or consider - # using a library capable of currency conversion. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the level of precision (defaults - # to 2). - # * :unit - Sets the denomination of the currency - # (defaults to "$"). - # * :separator - Sets the separator between the units - # (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ","). - # * :format - Sets the format for non-negative numbers - # (defaults to "%u%n"). Fields are %u for the - # currency, and %n for the number. - # * :negative_format - Sets the format for negative - # numbers (defaults to prepending a hyphen to the formatted - # number given by :format). Accepts the same fields - # than :format, except %n is here the - # absolute value of the number. - # * :raise - If true, raises +InvalidNumberError+ when - # the argument is invalid. - # - # ==== Examples - # - # number_to_currency(1234567890.50) # => $1,234,567,890.50 - # number_to_currency(1234567890.506) # => $1,234,567,890.51 - # number_to_currency(1234567890.506, precision: 3) # => $1,234,567,890.506 - # number_to_currency(1234567890.506, locale: :fr) # => 1 234 567 890,51 € - # number_to_currency("123a456") # => $123a456 - # - # number_to_currency("123a456", raise: true) # => InvalidNumberError - # - # number_to_currency(-1234567890.50, negative_format: "(%u%n)") - # # => ($1,234,567,890.50) - # number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "") - # # => R$1234567890,50 - # number_to_currency(1234567890.50, unit: "R$", separator: ",", delimiter: "", format: "%n %u") - # # => 1234567890,50 R$ - def number_to_currency(number, options = {}) - delegate_number_helper_method(:number_to_currency, number, options) - end - - # Formats a +number+ as a percentage string (e.g., 65%). You can - # customize the format in the +options+ hash. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +false+). - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +false+). - # * :format - Specifies the format of the percentage - # string The number field is %n (defaults to "%n%"). - # * :raise - If true, raises +InvalidNumberError+ when - # the argument is invalid. - # - # ==== Examples - # - # number_to_percentage(100) # => 100.000% - # number_to_percentage("98") # => 98.000% - # number_to_percentage(100, precision: 0) # => 100% - # number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000% - # number_to_percentage(302.24398923423, precision: 5) # => 302.24399% - # number_to_percentage(1000, locale: :fr) # => 1 000,000% - # number_to_percentage("98a") # => 98a% - # number_to_percentage(100, format: "%n %") # => 100.000 % - # - # number_to_percentage("98a", raise: true) # => InvalidNumberError - def number_to_percentage(number, options = {}) - delegate_number_helper_method(:number_to_percentage, number, options) - end - - # Formats a +number+ with grouped thousands using +delimiter+ - # (e.g., 12,324). You can customize the format in the +options+ - # hash. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :delimiter - Sets the thousands delimiter (defaults - # to ","). - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter_pattern - Sets a custom regular expression used for - # deriving the placement of delimiter. Helpful when using currency formats - # like INR. - # * :raise - If true, raises +InvalidNumberError+ when - # the argument is invalid. - # - # ==== Examples - # - # number_with_delimiter(12345678) # => 12,345,678 - # number_with_delimiter("123456") # => 123,456 - # number_with_delimiter(12345678.05) # => 12,345,678.05 - # number_with_delimiter(12345678, delimiter: ".") # => 12.345.678 - # number_with_delimiter(12345678, delimiter: ",") # => 12,345,678 - # number_with_delimiter(12345678.05, separator: " ") # => 12,345,678 05 - # number_with_delimiter(12345678.05, locale: :fr) # => 12 345 678,05 - # number_with_delimiter("112a") # => 112a - # number_with_delimiter(98765432.98, delimiter: " ", separator: ",") - # # => 98 765 432,98 - # - # number_with_delimiter("123456.78", - # delimiter_pattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/) # => "1,23,456.78" - # - # number_with_delimiter("112a", raise: true) # => raise InvalidNumberError - def number_with_delimiter(number, options = {}) - delegate_number_helper_method(:number_to_delimited, number, options) - end - - # Formats a +number+ with the specified level of - # :precision (e.g., 112.32 has a precision of 2 if - # +:significant+ is +false+, and 5 if +:significant+ is +true+). - # You can customize the format in the +options+ hash. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +false+). - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +false+). - # * :raise - If true, raises +InvalidNumberError+ when - # the argument is invalid. - # - # ==== Examples - # - # number_with_precision(111.2345) # => 111.235 - # number_with_precision(111.2345, precision: 2) # => 111.23 - # number_with_precision(13, precision: 5) # => 13.00000 - # number_with_precision(389.32314, precision: 0) # => 389 - # number_with_precision(111.2345, significant: true) # => 111 - # number_with_precision(111.2345, precision: 1, significant: true) # => 100 - # number_with_precision(13, precision: 5, significant: true) # => 13.000 - # number_with_precision(111.234, locale: :fr) # => 111,234 - # - # number_with_precision(13, precision: 5, significant: true, strip_insignificant_zeros: true) - # # => 13 - # - # number_with_precision(389.32314, precision: 4, significant: true) # => 389.3 - # number_with_precision(1111.2345, precision: 2, separator: ',', delimiter: '.') - # # => 1.111,23 - def number_with_precision(number, options = {}) - delegate_number_helper_method(:number_to_rounded, number, options) - end - - # Formats the bytes in +number+ into a more understandable - # representation (e.g., giving it 1500 yields 1.5 KB). This - # method is useful for reporting file sizes to users. You can - # customize the format in the +options+ hash. - # - # See number_to_human if you want to pretty-print a - # generic number. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +true+) - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +true+) - # * :raise - If true, raises +InvalidNumberError+ when - # the argument is invalid. - # - # ==== Examples - # - # number_to_human_size(123) # => 123 Bytes - # number_to_human_size(1234) # => 1.21 KB - # number_to_human_size(12345) # => 12.1 KB - # number_to_human_size(1234567) # => 1.18 MB - # number_to_human_size(1234567890) # => 1.15 GB - # number_to_human_size(1234567890123) # => 1.12 TB - # number_to_human_size(1234567890123456) # => 1.1 PB - # number_to_human_size(1234567890123456789) # => 1.07 EB - # number_to_human_size(1234567, precision: 2) # => 1.2 MB - # number_to_human_size(483989, precision: 2) # => 470 KB - # number_to_human_size(1234567, precision: 2, separator: ',') # => 1,2 MB - # number_to_human_size(1234567890123, precision: 5) # => "1.1228 TB" - # number_to_human_size(524288000, precision: 5) # => "500 MB" - def number_to_human_size(number, options = {}) - delegate_number_helper_method(:number_to_human_size, number, options) - end - - # Pretty prints (formats and approximates) a number in a way it - # is more readable by humans (eg.: 1200000000 becomes "1.2 - # Billion"). This is useful for numbers that can get very large - # (and too hard to read). - # - # See number_to_human_size if you want to print a file - # size. - # - # You can also define your own unit-quantifier names if you want - # to use other decimal units (eg.: 1500 becomes "1.5 - # kilometers", 0.150 becomes "150 milliliters", etc). You may - # define a wide range of unit quantifiers, even fractional ones - # (centi, deci, mili, etc). - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +true+) - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +true+) - # * :units - A Hash of unit quantifier names. Or a - # string containing an i18n scope where to find this hash. It - # might have the following keys: - # * *integers*: :unit, :ten, - # :hundred, :thousand, :million, - # :billion, :trillion, - # :quadrillion - # * *fractionals*: :deci, :centi, - # :mili, :micro, :nano, - # :pico, :femto - # * :format - Sets the format of the output string - # (defaults to "%n %u"). The field types are: - # * %u - The quantifier (ex.: 'thousand') - # * %n - The number - # * :raise - If true, raises +InvalidNumberError+ when - # the argument is invalid. - # - # ==== Examples - # - # number_to_human(123) # => "123" - # number_to_human(1234) # => "1.23 Thousand" - # number_to_human(12345) # => "12.3 Thousand" - # number_to_human(1234567) # => "1.23 Million" - # number_to_human(1234567890) # => "1.23 Billion" - # number_to_human(1234567890123) # => "1.23 Trillion" - # number_to_human(1234567890123456) # => "1.23 Quadrillion" - # number_to_human(1234567890123456789) # => "1230 Quadrillion" - # number_to_human(489939, precision: 2) # => "490 Thousand" - # number_to_human(489939, precision: 4) # => "489.9 Thousand" - # number_to_human(1234567, precision: 4, - # significant: false) # => "1.2346 Million" - # number_to_human(1234567, precision: 1, - # separator: ',', - # significant: false) # => "1,2 Million" - # - # number_to_human(500000000, precision: 5) # => "500 Million" - # number_to_human(12345012345, significant: false) # => "12.345 Billion" - # - # Non-significant zeros after the decimal separator are stripped - # out by default (set :strip_insignificant_zeros to - # +false+ to change that): - # - # number_to_human(12.00001) # => "12" - # number_to_human(12.00001, strip_insignificant_zeros: false) # => "12.0" - # - # ==== Custom Unit Quantifiers - # - # You can also use your own custom unit quantifiers: - # number_to_human(500000, units: {unit: "ml", thousand: "lt"}) # => "500 lt" - # - # If in your I18n locale you have: - # distance: - # centi: - # one: "centimeter" - # other: "centimeters" - # unit: - # one: "meter" - # other: "meters" - # thousand: - # one: "kilometer" - # other: "kilometers" - # billion: "gazillion-distance" - # - # Then you could do: - # - # number_to_human(543934, units: :distance) # => "544 kilometers" - # number_to_human(54393498, units: :distance) # => "54400 kilometers" - # number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance" - # number_to_human(343, units: :distance, precision: 1) # => "300 meters" - # number_to_human(1, units: :distance) # => "1 meter" - # number_to_human(0.34, units: :distance) # => "34 centimeters" - # - def number_to_human(number, options = {}) - delegate_number_helper_method(:number_to_human, number, options) - end - - private - - def delegate_number_helper_method(method, number, options) - return unless number - options = escape_unsafe_options(options.symbolize_keys) - - wrap_with_output_safety_handling(number, options.delete(:raise)) { - ActiveSupport::NumberHelper.public_send(method, number, options) - } - end - - def escape_unsafe_options(options) - options[:format] = ERB::Util.html_escape(options[:format]) if options[:format] - options[:negative_format] = ERB::Util.html_escape(options[:negative_format]) if options[:negative_format] - options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] - options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] - options[:unit] = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe? - options[:units] = escape_units(options[:units]) if options[:units] && Hash === options[:units] - options - end - - def escape_units(units) - Hash[units.map do |k, v| - [k, ERB::Util.html_escape(v)] - end] - end - - def wrap_with_output_safety_handling(number, raise_on_invalid, &block) - valid_float = valid_float?(number) - raise InvalidNumberError, number if raise_on_invalid && !valid_float - - formatted_number = yield - - if valid_float || number.html_safe? - formatted_number.html_safe - else - formatted_number - end - end - - def valid_float?(number) - !parse_float(number, false).nil? - end - - def parse_float(number, raise_error) - Float(number) - rescue ArgumentError, TypeError - raise InvalidNumberError, number if raise_error - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/output_safety_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/output_safety_helper.rb deleted file mode 100644 index 25defd1276..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/output_safety_helper.rb +++ /dev/null @@ -1,68 +0,0 @@ -require "active_support/core_ext/string/output_safety" - -module ActionView #:nodoc: - # = Action View Raw Output Helper - module Helpers #:nodoc: - module OutputSafetyHelper - # This method outputs without escaping a string. Since escaping tags is - # now default, this can be used when you don't want Rails to automatically - # escape tags. This is not recommended if the data is coming from the user's - # input. - # - # For example: - # - # raw @user.name - # # => 'Jimmy Tables' - def raw(stringish) - stringish.to_s.html_safe - end - - # This method returns an HTML safe string similar to what Array#join - # would return. The array is flattened, and all items, including - # the supplied separator, are HTML escaped unless they are HTML - # safe, and the returned string is marked as HTML safe. - # - # safe_join([raw("

    foo

    "), "

    bar

    "], "
    ") - # # => "

    foo

    <br /><p>bar</p>" - # - # safe_join([raw("

    foo

    "), raw("

    bar

    ")], raw("
    ")) - # # => "

    foo


    bar

    " - # - def safe_join(array, sep = $,) - sep = ERB::Util.unwrapped_html_escape(sep) - - array.flatten.map! { |i| ERB::Util.unwrapped_html_escape(i) }.join(sep).html_safe - end - - # Converts the array to a comma-separated sentence where the last element is - # joined by the connector word. This is the html_safe-aware version of - # ActiveSupport's {Array#to_sentence}[http://api.rubyonrails.org/classes/Array.html#method-i-to_sentence]. - # - def to_sentence(array, options = {}) - options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) - - default_connectors = { - words_connector: ", ", - two_words_connector: " and ", - last_word_connector: ", and " - } - if defined?(I18n) - i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {}) - default_connectors.merge!(i18n_connectors) - end - options = default_connectors.merge!(options) - - case array.length - when 0 - "".html_safe - when 1 - ERB::Util.html_escape(array[0]) - when 2 - safe_join([array[0], array[1]], options[:two_words_connector]) - else - safe_join([safe_join(array[0...-1], options[:words_connector]), options[:last_word_connector], array[-1]], nil) - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/record_tag_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/record_tag_helper.rb deleted file mode 100644 index ad59006386..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/record_tag_helper.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActionView - module Helpers - module RecordTagHelper - def div_for(*) # :nodoc: - raise NoMethodError, "The `div_for` method has been removed from " \ - "Rails. To continue using it, add the `record_tag_helper` gem to " \ - "your Gemfile:\n" \ - " gem 'record_tag_helper', '~> 1.0'\n" \ - "Consult the Rails upgrade guide for details." - end - - def content_tag_for(*) # :nodoc: - raise NoMethodError, "The `content_tag_for` method has been removed from " \ - "Rails. To continue using it, add the `record_tag_helper` gem to " \ - "your Gemfile:\n" \ - " gem 'record_tag_helper', '~> 1.0'\n" \ - "Consult the Rails upgrade guide for details." - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/rendering_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/rendering_helper.rb deleted file mode 100644 index 8a4a8348b0..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/rendering_helper.rb +++ /dev/null @@ -1,97 +0,0 @@ -module ActionView - module Helpers - # = Action View Rendering - # - # Implements methods that allow rendering from a view context. - # In order to use this module, all you need is to implement - # view_renderer that returns an ActionView::Renderer object. - module RenderingHelper - # Returns the result of a render that's dictated by the options hash. The primary options are: - # - # * :partial - See ActionView::PartialRenderer. - # * :file - Renders an explicit template file (this used to be the old default), add :locals to pass in those. - # * :inline - Renders an inline template similar to how it's done in the controller. - # * :plain - Renders the text passed in out. Setting the content - # type as text/plain. - # * :html - Renders the HTML safe string passed in out, otherwise - # performs HTML escape on the string first. Setting the content type as - # text/html. - # * :body - Renders the text passed in, and inherits the content - # type of text/plain from ActionDispatch::Response - # object. - # - # If no options hash is passed or :update specified, the default is to render a partial and use the second parameter - # as the locals hash. - def render(options = {}, locals = {}, &block) - case options - when Hash - if block_given? - view_renderer.render_partial(self, options.merge(partial: options[:layout]), &block) - else - view_renderer.render(self, options) - end - else - view_renderer.render_partial(self, partial: options, locals: locals, &block) - end - end - - # Overwrites _layout_for in the context object so it supports the case a block is - # passed to a partial. Returns the contents that are yielded to a layout, given a - # name or a block. - # - # You can think of a layout as a method that is called with a block. If the user calls - # yield :some_name, the block, by default, returns content_for(:some_name). - # If the user calls simply +yield+, the default block returns content_for(:layout). - # - # The user can override this default by passing a block to the layout: - # - # # The template - # <%= render layout: "my_layout" do %> - # Content - # <% end %> - # - # # The layout - # - # <%= yield %> - # - # - # In this case, instead of the default block, which would return content_for(:layout), - # this method returns the block that was passed in to render :layout, and the response - # would be - # - # - # Content - # - # - # Finally, the block can take block arguments, which can be passed in by +yield+: - # - # # The template - # <%= render layout: "my_layout" do |customer| %> - # Hello <%= customer.name %> - # <% end %> - # - # # The layout - # - # <%= yield Struct.new(:name).new("David") %> - # - # - # In this case, the layout would receive the block passed into render :layout, - # and the struct specified would be passed into the block as an argument. The result - # would be - # - # - # Hello David - # - # - def _layout_for(*args, &block) - name = args.first - - if block && !name.is_a?(Symbol) - capture(*args, &block) - else - super - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/sanitize_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/sanitize_helper.rb deleted file mode 100644 index 0abd5bc5dc..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/sanitize_helper.rb +++ /dev/null @@ -1,175 +0,0 @@ -require "active_support/core_ext/object/try" -require "rails-html-sanitizer" - -module ActionView - # = Action View Sanitize Helpers - module Helpers - # The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements. - # These helper methods extend Action View making them callable within your template files. - module SanitizeHelper - extend ActiveSupport::Concern - # Sanitizes HTML input, stripping all tags and attributes that aren't whitelisted. - # - # It also strips href/src attributes with unsafe protocols like - # javascript:, while also protecting against attempts to use Unicode, - # ASCII, and hex character references to work around these protocol filters. - # All special characters will be escaped. - # - # The default sanitizer is Rails::Html::WhiteListSanitizer. See {Rails HTML - # Sanitizers}[https://github.com/rails/rails-html-sanitizer] for more information. - # - # Custom sanitization rules can also be provided. - # - # Please note that sanitizing user-provided text does not guarantee that the - # resulting markup is valid or even well-formed. - # - # ==== Options - # - # * :tags - An array of allowed tags. - # * :attributes - An array of allowed attributes. - # * :scrubber - A {Rails::Html scrubber}[https://github.com/rails/rails-html-sanitizer] - # or {Loofah::Scrubber}[https://github.com/flavorjones/loofah] object that - # defines custom sanitization rules. A custom scrubber takes precedence over - # custom tags and attributes. - # - # ==== Examples - # - # Normal use: - # - # <%= sanitize @comment.body %> - # - # Providing custom whitelisted tags and attributes: - # - # <%= sanitize @comment.body, tags: %w(strong em a), attributes: %w(href) %> - # - # Providing a custom Rails::Html scrubber: - # - # class CommentScrubber < Rails::Html::PermitScrubber - # def initialize - # super - # self.tags = %w( form script comment blockquote ) - # self.attributes = %w( style ) - # end - # - # def skip_node?(node) - # node.text? - # end - # end - # - # <%= sanitize @comment.body, scrubber: CommentScrubber.new %> - # - # See {Rails HTML Sanitizer}[https://github.com/rails/rails-html-sanitizer] for - # documentation about Rails::Html scrubbers. - # - # Providing a custom Loofah::Scrubber: - # - # scrubber = Loofah::Scrubber.new do |node| - # node.remove if node.name == 'script' - # end - # - # <%= sanitize @comment.body, scrubber: scrubber %> - # - # See {Loofah's documentation}[https://github.com/flavorjones/loofah] for more - # information about defining custom Loofah::Scrubber objects. - # - # To set the default allowed tags or attributes across your application: - # - # # In config/application.rb - # config.action_view.sanitized_allowed_tags = ['strong', 'em', 'a'] - # config.action_view.sanitized_allowed_attributes = ['href', 'title'] - def sanitize(html, options = {}) - self.class.white_list_sanitizer.sanitize(html, options).try(:html_safe) - end - - # Sanitizes a block of CSS code. Used by +sanitize+ when it comes across a style attribute. - def sanitize_css(style) - self.class.white_list_sanitizer.sanitize_css(style) - end - - # Strips all HTML tags from +html+, including comments and special characters. - # - # strip_tags("Strip these tags!") - # # => Strip these tags! - # - # strip_tags("Bold no more! See more here...") - # # => Bold no more! See more here... - # - # strip_tags("
    Welcome to my website!
    ") - # # => Welcome to my website! - # - # strip_tags("> A quote from Smith & Wesson") - # # => > A quote from Smith & Wesson - def strip_tags(html) - self.class.full_sanitizer.sanitize(html) - end - - # Strips all link tags from +html+ leaving just the link text. - # - # strip_links('Ruby on Rails') - # # => Ruby on Rails - # - # strip_links('Please e-mail me at me@email.com.') - # # => Please e-mail me at me@email.com. - # - # strip_links('Blog: Visit.') - # # => Blog: Visit. - # - # strip_links('<malformed & link') - # # => <malformed & link - def strip_links(html) - self.class.link_sanitizer.sanitize(html) - end - - module ClassMethods #:nodoc: - attr_writer :full_sanitizer, :link_sanitizer, :white_list_sanitizer - - # Vendors the full, link and white list sanitizers. - # Provided strictly for compatibility and can be removed in Rails 5.1. - def sanitizer_vendor - Rails::Html::Sanitizer - end - - def sanitized_allowed_tags - sanitizer_vendor.white_list_sanitizer.allowed_tags - end - - def sanitized_allowed_attributes - sanitizer_vendor.white_list_sanitizer.allowed_attributes - end - - # Gets the Rails::Html::FullSanitizer instance used by +strip_tags+. Replace with - # any object that responds to +sanitize+. - # - # class Application < Rails::Application - # config.action_view.full_sanitizer = MySpecialSanitizer.new - # end - # - def full_sanitizer - @full_sanitizer ||= sanitizer_vendor.full_sanitizer.new - end - - # Gets the Rails::Html::LinkSanitizer instance used by +strip_links+. - # Replace with any object that responds to +sanitize+. - # - # class Application < Rails::Application - # config.action_view.link_sanitizer = MySpecialSanitizer.new - # end - # - def link_sanitizer - @link_sanitizer ||= sanitizer_vendor.link_sanitizer.new - end - - # Gets the Rails::Html::WhiteListSanitizer instance used by sanitize and +sanitize_css+. - # Replace with any object that responds to +sanitize+. - # - # class Application < Rails::Application - # config.action_view.white_list_sanitizer = MySpecialSanitizer.new - # end - # - def white_list_sanitizer - @white_list_sanitizer ||= sanitizer_vendor.white_list_sanitizer.new - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tag_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tag_helper.rb deleted file mode 100644 index 306b71c85e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tag_helper.rb +++ /dev/null @@ -1,313 +0,0 @@ -# frozen-string-literal: true - -require "active_support/core_ext/string/output_safety" -require "set" - -module ActionView - # = Action View Tag Helpers - module Helpers #:nodoc: - # Provides methods to generate HTML tags programmatically both as a modern - # HTML5 compliant builder style and legacy XHTML compliant tags. - module TagHelper - extend ActiveSupport::Concern - include CaptureHelper - include OutputSafetyHelper - - BOOLEAN_ATTRIBUTES = %w(allowfullscreen async autofocus autoplay checked - compact controls declare default defaultchecked - defaultmuted defaultselected defer disabled - enabled formnovalidate hidden indeterminate inert - ismap itemscope loop multiple muted nohref - noresize noshade novalidate nowrap open - pauseonexit readonly required reversed scoped - seamless selected sortable truespeed typemustmatch - visible).to_set - - BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym)) - - TAG_PREFIXES = ["aria", "data", :aria, :data].to_set - - PRE_CONTENT_STRINGS = Hash.new { "" } - PRE_CONTENT_STRINGS[:textarea] = "\n" - PRE_CONTENT_STRINGS["textarea"] = "\n" - - class TagBuilder #:nodoc: - include CaptureHelper - include OutputSafetyHelper - - VOID_ELEMENTS = %i(area base br col embed hr img input keygen link meta param source track wbr).to_set - - def initialize(view_context) - @view_context = view_context - end - - def tag_string(name, content = nil, escape_attributes: true, **options, &block) - content = @view_context.capture(self, &block) if block_given? - if VOID_ELEMENTS.include?(name) && content.nil? - "<#{name.to_s.dasherize}#{tag_options(options, escape_attributes)}>".html_safe - else - content_tag_string(name.to_s.dasherize, content || "", options, escape_attributes) - end - end - - def content_tag_string(name, content, options, escape = true) - tag_options = tag_options(options, escape) if options - content = ERB::Util.unwrapped_html_escape(content) if escape - "<#{name}#{tag_options}>#{PRE_CONTENT_STRINGS[name]}#{content}".html_safe - end - - def tag_options(options, escape = true) - return if options.blank? - output = "".dup - sep = " " - options.each_pair do |key, value| - if TAG_PREFIXES.include?(key) && value.is_a?(Hash) - value.each_pair do |k, v| - next if v.nil? - output << sep - output << prefix_tag_option(key, k, v, escape) - end - elsif BOOLEAN_ATTRIBUTES.include?(key) - if value - output << sep - output << boolean_tag_option(key) - end - elsif !value.nil? - output << sep - output << tag_option(key, value, escape) - end - end - output unless output.empty? - end - - def boolean_tag_option(key) - %(#{key}="#{key}") - end - - def tag_option(key, value, escape) - if value.is_a?(Array) - value = escape ? safe_join(value, " ".freeze) : value.join(" ".freeze) - else - value = escape ? ERB::Util.unwrapped_html_escape(value) : value.to_s - end - %(#{key}="#{value.gsub('"'.freeze, '"'.freeze)}") - end - - private - def prefix_tag_option(prefix, key, value, escape) - key = "#{prefix}-#{key.to_s.dasherize}" - unless value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(BigDecimal) - value = value.to_json - end - tag_option(key, value, escape) - end - - def respond_to_missing?(*args) - true - end - - def method_missing(called, *args, &block) - tag_string(called, *args, &block) - end - end - - # Returns an HTML tag. - # - # === Building HTML tags - # - # Builds HTML5 compliant tags with a tag proxy. Every tag can be built with: - # - # tag.(optional content, options) - # - # where tag name can be e.g. br, div, section, article, or any tag really. - # - # ==== Passing content - # - # Tags can pass content to embed within it: - # - # tag.h1 'All titles fit to print' # =>

    All titles fit to print

    - # - # tag.div tag.p('Hello world!') # =>

    Hello world!

    - # - # Content can also be captured with a block, which is useful in templates: - # - # <%= tag.p do %> - # The next great American novel starts here. - # <% end %> - # # =>

    The next great American novel starts here.

    - # - # ==== Options - # - # Use symbol keyed options to add attributes to the generated tag. - # - # tag.section class: %w( kitties puppies ) - # # =>
    - # - # tag.section id: dom_id(@post) - # # =>
    - # - # Pass +true+ for any attributes that can render with no values, like +disabled+ and +readonly+. - # - # tag.input type: 'text', disabled: true - # # => - # - # HTML5 data-* attributes can be set with a single +data+ key - # pointing to a hash of sub-attributes. - # - # To play nicely with JavaScript conventions, sub-attributes are dasherized. - # - # tag.article data: { user_id: 123 } - # # =>
    - # - # Thus data-user-id can be accessed as dataset.userId. - # - # Data attribute values are encoded to JSON, with the exception of strings, symbols and - # BigDecimals. - # This may come in handy when using jQuery's HTML5-aware .data() - # from 1.4.3. - # - # tag.div data: { city_state: %w( Chigaco IL ) } - # # =>
    - # - # The generated attributes are escaped by default. This can be disabled using - # +escape_attributes+. - # - # tag.img src: 'open & shut.png' - # # => - # - # tag.img src: 'open & shut.png', escape_attributes: false - # # => - # - # The tag builder respects - # {HTML5 void elements}[https://www.w3.org/TR/html5/syntax.html#void-elements] - # if no content is passed, and omits closing tags for those elements. - # - # # A standard element: - # tag.div # =>
    - # - # # A void element: - # tag.br # =>
    - # - # === Legacy syntax - # - # The following format is for legacy syntax support. It will be deprecated in future versions of Rails. - # - # tag(name, options = nil, open = false, escape = true) - # - # It returns an empty HTML tag of type +name+ which by default is XHTML - # compliant. Set +open+ to true to create an open tag compatible - # with HTML 4.0 and below. Add HTML attributes by passing an attributes - # hash to +options+. Set +escape+ to false to disable attribute value - # escaping. - # - # ==== Options - # - # You can use symbols or strings for the attribute names. - # - # Use +true+ with boolean attributes that can render with no value, like - # +disabled+ and +readonly+. - # - # HTML5 data-* attributes can be set with a single +data+ key - # pointing to a hash of sub-attributes. - # - # ==== Examples - # - # tag("br") - # # =>
    - # - # tag("br", nil, true) - # # =>
    - # - # tag("input", type: 'text', disabled: true) - # # => - # - # tag("input", type: 'text', class: ["strong", "highlight"]) - # # => - # - # tag("img", src: "open & shut.png") - # # => - # - # tag("img", {src: "open & shut.png"}, false, false) - # # => - # - # tag("div", data: {name: 'Stephen', city_state: %w(Chicago IL)}) - # # =>
    - def tag(name = nil, options = nil, open = false, escape = true) - if name.nil? - tag_builder - else - "<#{name}#{tag_builder.tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe - end - end - - # Returns an HTML block tag of type +name+ surrounding the +content+. Add - # HTML attributes by passing an attributes hash to +options+. - # Instead of passing the content as an argument, you can also use a block - # in which case, you pass your +options+ as the second parameter. - # Set escape to false to disable attribute value escaping. - # Note: this is legacy syntax, see +tag+ method description for details. - # - # ==== Options - # The +options+ hash can be used with attributes with no value like (disabled and - # readonly), which you can give a value of true in the +options+ hash. You can use - # symbols or strings for the attribute names. - # - # ==== Examples - # content_tag(:p, "Hello world!") - # # =>

    Hello world!

    - # content_tag(:div, content_tag(:p, "Hello world!"), class: "strong") - # # =>

    Hello world!

    - # content_tag(:div, "Hello world!", class: ["strong", "highlight"]) - # # =>
    Hello world!
    - # content_tag("select", options, multiple: true) - # # => - # - # <%= content_tag :div, class: "strong" do -%> - # Hello world! - # <% end -%> - # # =>
    Hello world!
    - def content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block) - if block_given? - options = content_or_options_with_block if content_or_options_with_block.is_a?(Hash) - tag_builder.content_tag_string(name, capture(&block), options, escape) - else - tag_builder.content_tag_string(name, content_or_options_with_block, options, escape) - end - end - - # Returns a CDATA section with the given +content+. CDATA sections - # are used to escape blocks of text containing characters which would - # otherwise be recognized as markup. CDATA sections begin with the string - # and end with (and may not contain) the string ]]>. - # - # cdata_section("") - # # => ]]> - # - # cdata_section(File.read("hello_world.txt")) - # # => - # - # cdata_section("hello]]>world") - # # => world]]> - def cdata_section(content) - splitted = content.to_s.gsub(/\]\]\>/, "]]]]>") - "".html_safe - end - - # Returns an escaped version of +html+ without affecting existing escaped entities. - # - # escape_once("1 < 2 & 3") - # # => "1 < 2 & 3" - # - # escape_once("<< Accept & Checkout") - # # => "<< Accept & Checkout" - def escape_once(html) - ERB::Util.html_escape_once(html) - end - - private - def tag_builder - @tag_builder ||= TagBuilder.new(self) - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags.rb deleted file mode 100644 index a4f6eb0150..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags.rb +++ /dev/null @@ -1,42 +0,0 @@ -module ActionView - module Helpers - module Tags #:nodoc: - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Base - autoload :Translator - autoload :CheckBox - autoload :CollectionCheckBoxes - autoload :CollectionRadioButtons - autoload :CollectionSelect - autoload :ColorField - autoload :DateField - autoload :DateSelect - autoload :DatetimeField - autoload :DatetimeLocalField - autoload :DatetimeSelect - autoload :EmailField - autoload :FileField - autoload :GroupedCollectionSelect - autoload :HiddenField - autoload :Label - autoload :MonthField - autoload :NumberField - autoload :PasswordField - autoload :RadioButton - autoload :RangeField - autoload :SearchField - autoload :Select - autoload :TelField - autoload :TextArea - autoload :TextField - autoload :TimeField - autoload :TimeSelect - autoload :TimeZoneSelect - autoload :UrlField - autoload :WeekField - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/base.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/base.rb deleted file mode 100644 index 910347891b..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/base.rb +++ /dev/null @@ -1,190 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class Base # :nodoc: - include Helpers::ActiveModelInstanceTag, Helpers::TagHelper, Helpers::FormTagHelper - include FormOptionsHelper - - attr_reader :object - - def initialize(object_name, method_name, template_object, options = {}) - @object_name, @method_name = object_name.to_s.dup, method_name.to_s.dup - @template_object = template_object - - @object_name.sub!(/\[\]$/, "") || @object_name.sub!(/\[\]\]$/, "]") - @object = retrieve_object(options.delete(:object)) - @skip_default_ids = options.delete(:skip_default_ids) - @allow_method_names_outside_object = options.delete(:allow_method_names_outside_object) - @options = options - - if Regexp.last_match - @generate_indexed_names = true - @auto_index = retrieve_autoindex(Regexp.last_match.pre_match) - else - @generate_indexed_names = false - @auto_index = nil - end - end - - # This is what child classes implement. - def render - raise NotImplementedError, "Subclasses must implement a render method" - end - - private - - def value(object) - if @allow_method_names_outside_object - object.public_send @method_name if object && object.respond_to?(@method_name) - else - object.public_send @method_name if object - end - end - - def value_before_type_cast(object) - unless object.nil? - method_before_type_cast = @method_name + "_before_type_cast" - - if value_came_from_user?(object) && object.respond_to?(method_before_type_cast) - object.public_send(method_before_type_cast) - else - value(object) - end - end - end - - def value_came_from_user?(object) - method_name = "#{@method_name}_came_from_user?" - !object.respond_to?(method_name) || object.public_send(method_name) - end - - def retrieve_object(object) - if object - object - elsif @template_object.instance_variable_defined?("@#{@object_name}") - @template_object.instance_variable_get("@#{@object_name}") - end - rescue NameError - # As @object_name may contain the nested syntax (item[subobject]) we need to fallback to nil. - nil - end - - def retrieve_autoindex(pre_match) - object = self.object || @template_object.instance_variable_get("@#{pre_match}") - if object && object.respond_to?(:to_param) - object.to_param - else - raise ArgumentError, "object[] naming but object param and @object var don't exist or don't respond to to_param: #{object.inspect}" - end - end - - def add_default_name_and_id_for_value(tag_value, options) - if tag_value.nil? - add_default_name_and_id(options) - else - specified_id = options["id"] - add_default_name_and_id(options) - - if specified_id.blank? && options["id"].present? - options["id"] += "_#{sanitized_value(tag_value)}" - end - end - end - - def add_default_name_and_id(options) - index = name_and_id_index(options) - options["name"] = options.fetch("name") { tag_name(options["multiple"], index) } - - unless skip_default_ids? - options["id"] = options.fetch("id") { tag_id(index) } - if namespace = options.delete("namespace") - options["id"] = options["id"] ? "#{namespace}_#{options['id']}" : namespace - end - end - end - - def tag_name(multiple = false, index = nil) - # a little duplication to construct less strings - case - when @object_name.empty? - "#{sanitized_method_name}#{"[]" if multiple}" - when index - "#{@object_name}[#{index}][#{sanitized_method_name}]#{"[]" if multiple}" - else - "#{@object_name}[#{sanitized_method_name}]#{"[]" if multiple}" - end - end - - def tag_id(index = nil) - # a little duplication to construct less strings - case - when @object_name.empty? - sanitized_method_name.dup - when index - "#{sanitized_object_name}_#{index}_#{sanitized_method_name}" - else - "#{sanitized_object_name}_#{sanitized_method_name}" - end - end - - def sanitized_object_name - @sanitized_object_name ||= @object_name.gsub(/\]\[|[^-a-zA-Z0-9:.]/, "_").sub(/_$/, "") - end - - def sanitized_method_name - @sanitized_method_name ||= @method_name.sub(/\?$/, "") - end - - def sanitized_value(value) - value.to_s.gsub(/\s/, "_").gsub(/[^-[[:word:]]]/, "").mb_chars.downcase.to_s - end - - def select_content_tag(option_tags, options, html_options) - html_options = html_options.stringify_keys - add_default_name_and_id(html_options) - - if placeholder_required?(html_options) - raise ArgumentError, "include_blank cannot be false for a required field." if options[:include_blank] == false - options[:include_blank] ||= true unless options[:prompt] - end - - value = options.fetch(:selected) { value(object) } - select = content_tag("select", add_options(option_tags, options, value), html_options.except!("skip_default_ids", "allow_method_names_outside_object")) - - if html_options["multiple"] && options.fetch(:include_hidden, true) - tag("input", disabled: html_options["disabled"], name: html_options["name"], type: "hidden", value: "") + select - else - select - end - end - - def placeholder_required?(html_options) - # See https://html.spec.whatwg.org/multipage/forms.html#attr-select-required - html_options["required"] && !html_options["multiple"] && html_options.fetch("size", 1).to_i == 1 - end - - def add_options(option_tags, options, value = nil) - if options[:include_blank] - option_tags = tag_builder.content_tag_string("option", options[:include_blank].kind_of?(String) ? options[:include_blank] : nil, value: "") + "\n" + option_tags - end - if value.blank? && options[:prompt] - option_tags = tag_builder.content_tag_string("option", prompt_text(options[:prompt]), value: "") + "\n" + option_tags - end - option_tags - end - - def name_and_id_index(options) - if options.key?("index") - options.delete("index") || "" - elsif @generate_indexed_names - @auto_index || "" - end - end - - def skip_default_ids? - @skip_default_ids - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/check_box.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/check_box.rb deleted file mode 100644 index 02f87fc89f..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/check_box.rb +++ /dev/null @@ -1,64 +0,0 @@ -require "action_view/helpers/tags/checkable" - -module ActionView - module Helpers - module Tags # :nodoc: - class CheckBox < Base #:nodoc: - include Checkable - - def initialize(object_name, method_name, template_object, checked_value, unchecked_value, options) - @checked_value = checked_value - @unchecked_value = unchecked_value - super(object_name, method_name, template_object, options) - end - - def render - options = @options.stringify_keys - options["type"] = "checkbox" - options["value"] = @checked_value - options["checked"] = "checked" if input_checked?(object, options) - - if options["multiple"] - add_default_name_and_id_for_value(@checked_value, options) - options.delete("multiple") - else - add_default_name_and_id(options) - end - - include_hidden = options.delete("include_hidden") { true } - checkbox = tag("input", options) - - if include_hidden - hidden = hidden_field_for_checkbox(options) - hidden + checkbox - else - checkbox - end - end - - private - - def checked?(value) - case value - when TrueClass, FalseClass - value == !!@checked_value - when NilClass - false - when String - value == @checked_value - else - if value.respond_to?(:include?) - value.include?(@checked_value) - else - value.to_i == @checked_value.to_i - end - end - end - - def hidden_field_for_checkbox(options) - @unchecked_value ? tag("input", options.slice("name", "disabled", "form").merge!("type" => "hidden", "value" => @unchecked_value)) : "".html_safe - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/checkable.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/checkable.rb deleted file mode 100644 index 052e9df662..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/checkable.rb +++ /dev/null @@ -1,16 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - module Checkable # :nodoc: - def input_checked?(object, options) - if options.has_key?("checked") - checked = options.delete "checked" - checked == true || checked == "checked" - else - checked?(value(object)) - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_check_boxes.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_check_boxes.rb deleted file mode 100644 index e02b7bdb2e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_check_boxes.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "action_view/helpers/tags/collection_helpers" - -module ActionView - module Helpers - module Tags # :nodoc: - class CollectionCheckBoxes < Base # :nodoc: - include CollectionHelpers - - class CheckBoxBuilder < Builder # :nodoc: - def check_box(extra_html_options = {}) - html_options = extra_html_options.merge(@input_html_options) - html_options[:multiple] = true - html_options[:skip_default_ids] = false - @template_object.check_box(@object_name, @method_name, html_options, @value, nil) - end - end - - def render(&block) - render_collection_for(CheckBoxBuilder, &block) - end - - private - - def render_component(builder) - builder.check_box + builder.label - end - - def hidden_field_name - "#{super}[]" - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_helpers.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_helpers.rb deleted file mode 100644 index 75d237eb35..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_helpers.rb +++ /dev/null @@ -1,117 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - module CollectionHelpers # :nodoc: - class Builder # :nodoc: - attr_reader :object, :text, :value - - def initialize(template_object, object_name, method_name, object, - sanitized_attribute_name, text, value, input_html_options) - @template_object = template_object - @object_name = object_name - @method_name = method_name - @object = object - @sanitized_attribute_name = sanitized_attribute_name - @text = text - @value = value - @input_html_options = input_html_options - end - - def label(label_html_options = {}, &block) - html_options = @input_html_options.slice(:index, :namespace).merge(label_html_options) - html_options[:for] ||= @input_html_options[:id] if @input_html_options[:id] - - @template_object.label(@object_name, @sanitized_attribute_name, @text, html_options, &block) - end - end - - def initialize(object_name, method_name, template_object, collection, value_method, text_method, options, html_options) - @collection = collection - @value_method = value_method - @text_method = text_method - @html_options = html_options - - super(object_name, method_name, template_object, options) - end - - private - - def instantiate_builder(builder_class, item, value, text, html_options) - builder_class.new(@template_object, @object_name, @method_name, item, - sanitize_attribute_name(value), text, value, html_options) - end - - # Generate default options for collection helpers, such as :checked and - # :disabled. - def default_html_options_for_collection(item, value) - html_options = @html_options.dup - - [:checked, :selected, :disabled, :readonly].each do |option| - current_value = @options[option] - next if current_value.nil? - - accept = if current_value.respond_to?(:call) - current_value.call(item) - else - Array(current_value).map(&:to_s).include?(value.to_s) - end - - if accept - html_options[option] = true - elsif option == :checked - html_options[option] = false - end - end - - html_options[:object] = @object - html_options - end - - def sanitize_attribute_name(value) - "#{sanitized_method_name}_#{sanitized_value(value)}" - end - - def render_collection - @collection.map do |item| - value = value_for_collection(item, @value_method) - text = value_for_collection(item, @text_method) - default_html_options = default_html_options_for_collection(item, value) - additional_html_options = option_html_attributes(item) - - yield item, value, text, default_html_options.merge(additional_html_options) - end.join.html_safe - end - - def render_collection_for(builder_class, &block) - options = @options.stringify_keys - rendered_collection = render_collection do |item, value, text, default_html_options| - builder = instantiate_builder(builder_class, item, value, text, default_html_options) - - if block_given? - @template_object.capture(builder, &block) - else - render_component(builder) - end - end - - # Prepend a hidden field to make sure something will be sent back to the - # server if all radio buttons are unchecked. - if options.fetch("include_hidden", true) - hidden_field + rendered_collection - else - rendered_collection - end - end - - def hidden_field - hidden_name = @html_options[:name] || hidden_field_name - @template_object.hidden_field_tag(hidden_name, "", id: nil) - end - - def hidden_field_name - "#{tag_name(false, @options[:index])}" - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_radio_buttons.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_radio_buttons.rb deleted file mode 100644 index f085a5fb73..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_radio_buttons.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "action_view/helpers/tags/collection_helpers" - -module ActionView - module Helpers - module Tags # :nodoc: - class CollectionRadioButtons < Base # :nodoc: - include CollectionHelpers - - class RadioButtonBuilder < Builder # :nodoc: - def radio_button(extra_html_options = {}) - html_options = extra_html_options.merge(@input_html_options) - html_options[:skip_default_ids] = false - @template_object.radio_button(@object_name, @method_name, @value, html_options) - end - end - - def render(&block) - render_collection_for(RadioButtonBuilder, &block) - end - - private - - def render_component(builder) - builder.radio_button + builder.label - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_select.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_select.rb deleted file mode 100644 index 4365c714eb..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/collection_select.rb +++ /dev/null @@ -1,28 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class CollectionSelect < Base #:nodoc: - def initialize(object_name, method_name, template_object, collection, value_method, text_method, options, html_options) - @collection = collection - @value_method = value_method - @text_method = text_method - @html_options = html_options - - super(object_name, method_name, template_object, options) - end - - def render - option_tags_options = { - selected: @options.fetch(:selected) { value(@object) }, - disabled: @options[:disabled] - } - - select_content_tag( - options_from_collection_for_select(@collection, @value_method, @text_method, option_tags_options), - @options, @html_options - ) - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/color_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/color_field.rb deleted file mode 100644 index b4bbe92746..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/color_field.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class ColorField < TextField # :nodoc: - def render - options = @options.stringify_keys - options["value"] ||= validate_color_string(value(object)) - @options = options - super - end - - private - - def validate_color_string(string) - regex = /#[0-9a-fA-F]{6}/ - if regex.match(string) - string.downcase - else - "#000000" - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/date_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/date_field.rb deleted file mode 100644 index c22be0db29..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/date_field.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class DateField < DatetimeField # :nodoc: - private - - def format_date(value) - value.try(:strftime, "%Y-%m-%d") - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/date_select.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/date_select.rb deleted file mode 100644 index 638c134deb..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/date_select.rb +++ /dev/null @@ -1,72 +0,0 @@ -require "active_support/core_ext/time/calculations" - -module ActionView - module Helpers - module Tags # :nodoc: - class DateSelect < Base # :nodoc: - def initialize(object_name, method_name, template_object, options, html_options) - @html_options = html_options - - super(object_name, method_name, template_object, options) - end - - def render - error_wrapping(datetime_selector(@options, @html_options).send("select_#{select_type}").html_safe) - end - - class << self - def select_type - @select_type ||= name.split("::").last.sub("Select", "").downcase - end - end - - private - - def select_type - self.class.select_type - end - - def datetime_selector(options, html_options) - datetime = options.fetch(:selected) { value(object) || default_datetime(options) } - @auto_index ||= nil - - options = options.dup - options[:field_name] = @method_name - options[:include_position] = true - options[:prefix] ||= @object_name - options[:index] = @auto_index if @auto_index && !options.has_key?(:index) - - DateTimeSelector.new(datetime, options, html_options) - end - - def default_datetime(options) - return if options[:include_blank] || options[:prompt] - - case options[:default] - when nil - Time.current - when Date, Time - options[:default] - else - default = options[:default].dup - - # Rename :minute and :second to :min and :sec - default[:min] ||= default[:minute] - default[:sec] ||= default[:second] - - time = Time.current - - [:year, :month, :day, :hour, :min, :sec].each do |key| - default[key] ||= time.send(key) - end - - Time.utc( - default[:year], default[:month], default[:day], - default[:hour], default[:min], default[:sec] - ) - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_field.rb deleted file mode 100644 index b3940c7e44..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_field.rb +++ /dev/null @@ -1,30 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class DatetimeField < TextField # :nodoc: - def render - options = @options.stringify_keys - options["value"] ||= format_date(value(object)) - options["min"] = format_date(datetime_value(options["min"])) - options["max"] = format_date(datetime_value(options["max"])) - @options = options - super - end - - private - - def format_date(value) - raise NotImplementedError - end - - def datetime_value(value) - if value.is_a? String - DateTime.parse(value) rescue nil - else - value - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_local_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_local_field.rb deleted file mode 100644 index b4a74185d1..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_local_field.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class DatetimeLocalField < DatetimeField # :nodoc: - class << self - def field_type - @field_type ||= "datetime-local" - end - end - - private - - def format_date(value) - value.try(:strftime, "%Y-%m-%dT%T") - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_select.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_select.rb deleted file mode 100644 index 563de1840e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/datetime_select.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class DatetimeSelect < DateSelect # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/email_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/email_field.rb deleted file mode 100644 index 7ce3ccb9bf..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/email_field.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class EmailField < TextField # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/file_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/file_field.rb deleted file mode 100644 index 476b820d84..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/file_field.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class FileField < TextField # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/grouped_collection_select.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/grouped_collection_select.rb deleted file mode 100644 index 20e312dd0f..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/grouped_collection_select.rb +++ /dev/null @@ -1,29 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class GroupedCollectionSelect < Base # :nodoc: - def initialize(object_name, method_name, template_object, collection, group_method, group_label_method, option_key_method, option_value_method, options, html_options) - @collection = collection - @group_method = group_method - @group_label_method = group_label_method - @option_key_method = option_key_method - @option_value_method = option_value_method - @html_options = html_options - - super(object_name, method_name, template_object, options) - end - - def render - option_tags_options = { - selected: @options.fetch(:selected) { value(@object) }, - disabled: @options[:disabled] - } - - select_content_tag( - option_groups_from_collection_for_select(@collection, @group_method, @group_label_method, @option_key_method, @option_value_method, option_tags_options), @options, @html_options - ) - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/hidden_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/hidden_field.rb deleted file mode 100644 index c3757c2461..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/hidden_field.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class HiddenField < TextField # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/label.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/label.rb deleted file mode 100644 index cab15ae201..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/label.rb +++ /dev/null @@ -1,83 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class Label < Base # :nodoc: - class LabelBuilder # :nodoc: - attr_reader :object - - def initialize(template_object, object_name, method_name, object, tag_value) - @template_object = template_object - @object_name = object_name - @method_name = method_name - @object = object - @tag_value = tag_value - end - - def translation - method_and_value = @tag_value.present? ? "#{@method_name}.#{@tag_value}" : @method_name - - content ||= Translator - .new(object, @object_name, method_and_value, scope: "helpers.label") - .translate - content ||= @method_name.humanize - - content - end - end - - def initialize(object_name, method_name, template_object, content_or_options = nil, options = nil) - options ||= {} - - content_is_options = content_or_options.is_a?(Hash) - if content_is_options - options.merge! content_or_options - @content = nil - else - @content = content_or_options - end - - super(object_name, method_name, template_object, options) - end - - def render(&block) - options = @options.stringify_keys - tag_value = options.delete("value") - name_and_id = options.dup - - if name_and_id["for"] - name_and_id["id"] = name_and_id["for"] - else - name_and_id.delete("id") - end - - add_default_name_and_id_for_value(tag_value, name_and_id) - options.delete("index") - options.delete("namespace") - options["for"] = name_and_id["id"] unless options.key?("for") - - builder = LabelBuilder.new(@template_object, @object_name, @method_name, @object, tag_value) - - content = if block_given? - @template_object.capture(builder, &block) - elsif @content.present? - @content.to_s - else - render_component(builder) - end - - label_tag(name_and_id["id"], content, options) - end - - private - - def render_component(builder) - builder.translation - end - - def skip_default_ids? - false # The id is used as the `for` attribute. - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/month_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/month_field.rb deleted file mode 100644 index 4c0fb846ee..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/month_field.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class MonthField < DatetimeField # :nodoc: - private - - def format_date(value) - value.try(:strftime, "%Y-%m") - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/number_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/number_field.rb deleted file mode 100644 index 4f95b1b4de..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/number_field.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class NumberField < TextField # :nodoc: - def render - options = @options.stringify_keys - - if range = options.delete("in") || options.delete("within") - options.update("min" => range.min, "max" => range.max) - end - - @options = options - super - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/password_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/password_field.rb deleted file mode 100644 index 444ef65074..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/password_field.rb +++ /dev/null @@ -1,12 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class PasswordField < TextField # :nodoc: - def render - @options = { value: nil }.merge!(@options) - super - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/placeholderable.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/placeholderable.rb deleted file mode 100644 index cf7b117614..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/placeholderable.rb +++ /dev/null @@ -1,22 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - module Placeholderable # :nodoc: - def initialize(*) - super - - if tag_value = @options[:placeholder] - placeholder = tag_value if tag_value.is_a?(String) - method_and_value = tag_value.is_a?(TrueClass) ? @method_name : "#{@method_name}.#{tag_value}" - - placeholder ||= Tags::Translator - .new(object, @object_name, method_and_value, scope: "helpers.placeholder") - .translate - placeholder ||= @method_name.humanize - @options[:placeholder] = placeholder - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/radio_button.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/radio_button.rb deleted file mode 100644 index 43dbd32083..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/radio_button.rb +++ /dev/null @@ -1,31 +0,0 @@ -require "action_view/helpers/tags/checkable" - -module ActionView - module Helpers - module Tags # :nodoc: - class RadioButton < Base # :nodoc: - include Checkable - - def initialize(object_name, method_name, template_object, tag_value, options) - @tag_value = tag_value - super(object_name, method_name, template_object, options) - end - - def render - options = @options.stringify_keys - options["type"] = "radio" - options["value"] = @tag_value - options["checked"] = "checked" if input_checked?(object, options) - add_default_name_and_id_for_value(@tag_value, options) - tag("input", options) - end - - private - - def checked?(value) - value.to_s == @tag_value.to_s - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/range_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/range_field.rb deleted file mode 100644 index f98ae88043..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/range_field.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class RangeField < NumberField # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/search_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/search_field.rb deleted file mode 100644 index a848aeabfa..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/search_field.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class SearchField < TextField # :nodoc: - def render - options = @options.stringify_keys - - if options["autosave"] - if options["autosave"] == true - options["autosave"] = request.host.split(".").reverse.join(".") - end - options["results"] ||= 10 - end - - if options["onsearch"] - options["incremental"] = true unless options.has_key?("incremental") - end - - @options = options - super - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/select.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/select.rb deleted file mode 100644 index 667c7e945a..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/select.rb +++ /dev/null @@ -1,41 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class Select < Base # :nodoc: - def initialize(object_name, method_name, template_object, choices, options, html_options) - @choices = block_given? ? template_object.capture { yield || "" } : choices - @choices = @choices.to_a if @choices.is_a?(Range) - - @html_options = html_options - - super(object_name, method_name, template_object, options) - end - - def render - option_tags_options = { - selected: @options.fetch(:selected) { value(@object) }, - disabled: @options[:disabled] - } - - option_tags = if grouped_choices? - grouped_options_for_select(@choices, option_tags_options) - else - options_for_select(@choices, option_tags_options) - end - - select_content_tag(option_tags, @options, @html_options) - end - - private - - # Grouped choices look like this: - # - # [nil, []] - # { nil => [] } - def grouped_choices? - !@choices.empty? && @choices.first.respond_to?(:last) && Array === @choices.first.last - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/tel_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/tel_field.rb deleted file mode 100644 index 987bb9e67a..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/tel_field.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class TelField < TextField # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/text_area.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/text_area.rb deleted file mode 100644 index 31e3a9e9b1..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/text_area.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "action_view/helpers/tags/placeholderable" - -module ActionView - module Helpers - module Tags # :nodoc: - class TextArea < Base # :nodoc: - include Placeholderable - - def render - options = @options.stringify_keys - add_default_name_and_id(options) - - if size = options.delete("size") - options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split) - end - - content_tag("textarea", options.delete("value") { value_before_type_cast(object) }, options) - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/text_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/text_field.rb deleted file mode 100644 index 613cade7b3..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/text_field.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "action_view/helpers/tags/placeholderable" - -module ActionView - module Helpers - module Tags # :nodoc: - class TextField < Base # :nodoc: - include Placeholderable - - def render - options = @options.stringify_keys - options["size"] = options["maxlength"] unless options.key?("size") - options["type"] ||= field_type - options["value"] = options.fetch("value") { value_before_type_cast(object) } unless field_type == "file" - add_default_name_and_id(options) - tag("input", options) - end - - class << self - def field_type - @field_type ||= name.split("::").last.sub("Field", "").downcase - end - end - - private - - def field_type - self.class.field_type - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_field.rb deleted file mode 100644 index 0e90a3aed7..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_field.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class TimeField < DatetimeField # :nodoc: - private - - def format_date(value) - value.try(:strftime, "%T.%L") - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_select.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_select.rb deleted file mode 100644 index 0b06311d25..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_select.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class TimeSelect < DateSelect # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_zone_select.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_zone_select.rb deleted file mode 100644 index 80d165ec7e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/time_zone_select.rb +++ /dev/null @@ -1,20 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class TimeZoneSelect < Base # :nodoc: - def initialize(object_name, method_name, template_object, priority_zones, options, html_options) - @priority_zones = priority_zones - @html_options = html_options - - super(object_name, method_name, template_object, options) - end - - def render - select_content_tag( - time_zone_options_for_select(value(@object) || @options[:default], @priority_zones, @options[:model] || ActiveSupport::TimeZone), @options, @html_options - ) - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/translator.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/translator.rb deleted file mode 100644 index ced835eaa8..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/translator.rb +++ /dev/null @@ -1,42 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class Translator # :nodoc: - def initialize(object, object_name, method_and_value, scope:) - @object_name = object_name.gsub(/\[(.*)_attributes\]\[\d+\]/, '.\1') - @method_and_value = method_and_value - @scope = scope - @model = object.respond_to?(:to_model) ? object.to_model : nil - end - - def translate - translated_attribute = I18n.t("#{object_name}.#{method_and_value}", default: i18n_default, scope: scope).presence - translated_attribute || human_attribute_name - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :object_name, :method_and_value, :scope, :model - - private - - def i18n_default - if model - key = model.model_name.i18n_key - ["#{key}.#{method_and_value}".to_sym, ""] - else - "" - end - end - - def human_attribute_name - if model && model.class.respond_to?(:human_attribute_name) - model.class.human_attribute_name(method_and_value) - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/url_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/url_field.rb deleted file mode 100644 index d76340178d..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/url_field.rb +++ /dev/null @@ -1,8 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class UrlField < TextField # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/week_field.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/week_field.rb deleted file mode 100644 index 835d1667d7..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/tags/week_field.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActionView - module Helpers - module Tags # :nodoc: - class WeekField < DatetimeField # :nodoc: - private - - def format_date(value) - value.try(:strftime, "%Y-W%V") - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/text_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/text_helper.rb deleted file mode 100644 index bc922f9ce8..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/text_helper.rb +++ /dev/null @@ -1,484 +0,0 @@ -require "active_support/core_ext/string/filters" -require "active_support/core_ext/array/extract_options" - -module ActionView - # = Action View Text Helpers - module Helpers #:nodoc: - # The TextHelper module provides a set of methods for filtering, formatting - # and transforming strings, which can reduce the amount of inline Ruby code in - # your views. These helper methods extend Action View making them callable - # within your template files. - # - # ==== Sanitization - # - # Most text helpers by default sanitize the given content, but do not escape it. - # This means HTML tags will appear in the page but all malicious code will be removed. - # Let's look at some examples using the +simple_format+ method: - # - # simple_format('Example') - # # => "

    Example

    " - # - # simple_format('Example') - # # => "

    Example

    " - # - # If you want to escape all content, you should invoke the +h+ method before - # calling the text helper. - # - # simple_format h('Example') - # # => "

    <a href=\"http://example.com/\">Example</a>

    " - module TextHelper - extend ActiveSupport::Concern - - include SanitizeHelper - include TagHelper - include OutputSafetyHelper - - # The preferred method of outputting text in your views is to use the - # <%= "text" %> eRuby syntax. The regular _puts_ and _print_ methods - # do not operate as expected in an eRuby code block. If you absolutely must - # output text within a non-output code block (i.e., <% %>), you can use the concat method. - # - # <% - # concat "hello" - # # is the equivalent of <%= "hello" %> - # - # if logged_in - # concat "Logged in!" - # else - # concat link_to('login', action: :login) - # end - # # will either display "Logged in!" or a login link - # %> - def concat(string) - output_buffer << string - end - - def safe_concat(string) - output_buffer.respond_to?(:safe_concat) ? output_buffer.safe_concat(string) : concat(string) - end - - # Truncates a given +text+ after a given :length if +text+ is longer than :length - # (defaults to 30). The last characters will be replaced with the :omission (defaults to "...") - # for a total length not exceeding :length. - # - # Pass a :separator to truncate +text+ at a natural break. - # - # Pass a block if you want to show extra content when the text is truncated. - # - # The result is marked as HTML-safe, but it is escaped by default, unless :escape is - # +false+. Care should be taken if +text+ contains HTML tags or entities, because truncation - # may produce invalid HTML (such as unbalanced or incomplete tags). - # - # truncate("Once upon a time in a world far far away") - # # => "Once upon a time in a world..." - # - # truncate("Once upon a time in a world far far away", length: 17) - # # => "Once upon a ti..." - # - # truncate("Once upon a time in a world far far away", length: 17, separator: ' ') - # # => "Once upon a..." - # - # truncate("And they found that many people were sleeping better.", length: 25, omission: '... (continued)') - # # => "And they f... (continued)" - # - # truncate("

    Once upon a time in a world far far away

    ") - # # => "<p>Once upon a time in a wo..." - # - # truncate("

    Once upon a time in a world far far away

    ", escape: false) - # # => "

    Once upon a time in a wo..." - # - # truncate("Once upon a time in a world far far away") { link_to "Continue", "#" } - # # => "Once upon a time in a wo...Continue" - def truncate(text, options = {}, &block) - if text - length = options.fetch(:length, 30) - - content = text.truncate(length, options) - content = options[:escape] == false ? content.html_safe : ERB::Util.html_escape(content) - content << capture(&block) if block_given? && text.length > length - content - end - end - - # Highlights one or more +phrases+ everywhere in +text+ by inserting it into - # a :highlighter string. The highlighter can be specialized by passing :highlighter - # as a single-quoted string with \1 where the phrase is to be inserted (defaults to - # '\1') or passing a block that receives each matched term. By default +text+ - # is sanitized to prevent possible XSS attacks. If the input is trustworthy, passing false - # for :sanitize will turn sanitizing off. - # - # highlight('You searched for: rails', 'rails') - # # => You searched for: rails - # - # highlight('You searched for: rails', /for|rails/) - # # => You searched for: rails - # - # highlight('You searched for: ruby, rails, dhh', 'actionpack') - # # => You searched for: ruby, rails, dhh - # - # highlight('You searched for: rails', ['for', 'rails'], highlighter: '\1') - # # => You searched for: rails - # - # highlight('You searched for: rails', 'rails', highlighter: '\1') - # # => You searched for: rails - # - # highlight('You searched for: rails', 'rails') { |match| link_to(search_path(q: match, match)) } - # # => You searched for: rails - # - # highlight('ruby on rails', 'rails', sanitize: false) - # # => "ruby on rails" - def highlight(text, phrases, options = {}) - text = sanitize(text) if options.fetch(:sanitize, true) - - if text.blank? || phrases.blank? - text || "" - else - match = Array(phrases).map do |p| - Regexp === p ? p.to_s : Regexp.escape(p) - end.join("|") - - if block_given? - text.gsub(/(#{match})(?![^<]*?>)/i) { |found| yield found } - else - highlighter = options.fetch(:highlighter, '\1') - text.gsub(/(#{match})(?![^<]*?>)/i, highlighter) - end - end.html_safe - end - - # Extracts an excerpt from +text+ that matches the first instance of +phrase+. - # The :radius option expands the excerpt on each side of the first occurrence of +phrase+ by the number of characters - # defined in :radius (which defaults to 100). If the excerpt radius overflows the beginning or end of the +text+, - # then the :omission option (which defaults to "...") will be prepended/appended accordingly. Use the - # :separator option to choose the delimitation. The resulting string will be stripped in any case. If the +phrase+ - # isn't found, +nil+ is returned. - # - # excerpt('This is an example', 'an', radius: 5) - # # => ...s is an exam... - # - # excerpt('This is an example', 'is', radius: 5) - # # => This is a... - # - # excerpt('This is an example', 'is') - # # => This is an example - # - # excerpt('This next thing is an example', 'ex', radius: 2) - # # => ...next... - # - # excerpt('This is also an example', 'an', radius: 8, omission: ' ') - # # => is also an example - # - # excerpt('This is a very beautiful morning', 'very', separator: ' ', radius: 1) - # # => ...a very beautiful... - def excerpt(text, phrase, options = {}) - return unless text && phrase - - separator = options.fetch(:separator, nil) || "" - case phrase - when Regexp - regex = phrase - else - regex = /#{Regexp.escape(phrase)}/i - end - - return unless matches = text.match(regex) - phrase = matches[0] - - unless separator.empty? - text.split(separator).each do |value| - if value.match(regex) - phrase = value - break - end - end - end - - first_part, second_part = text.split(phrase, 2) - - prefix, first_part = cut_excerpt_part(:first, first_part, separator, options) - postfix, second_part = cut_excerpt_part(:second, second_part, separator, options) - - affix = [first_part, separator, phrase, separator, second_part].join.strip - [prefix, affix, postfix].join - end - - # Attempts to pluralize the +singular+ word unless +count+ is 1. If - # +plural+ is supplied, it will use that when count is > 1, otherwise - # it will use the Inflector to determine the plural form for the given locale, - # which defaults to I18n.locale - # - # The word will be pluralized using rules defined for the locale - # (you must define your own inflection rules for languages other than English). - # See ActiveSupport::Inflector.pluralize - # - # pluralize(1, 'person') - # # => 1 person - # - # pluralize(2, 'person') - # # => 2 people - # - # pluralize(3, 'person', plural: 'users') - # # => 3 users - # - # pluralize(0, 'person') - # # => 0 people - # - # pluralize(2, 'Person', locale: :de) - # # => 2 Personen - def pluralize(count, singular, plural_arg = nil, plural: plural_arg, locale: I18n.locale) - word = if (count == 1 || count =~ /^1(\.0+)?$/) - singular - else - plural || singular.pluralize(locale) - end - - "#{count || 0} #{word}" - end - - # Wraps the +text+ into lines no longer than +line_width+ width. This method - # breaks on the first whitespace character that does not exceed +line_width+ - # (which is 80 by default). - # - # word_wrap('Once upon a time') - # # => Once upon a time - # - # word_wrap('Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding a successor to the throne turned out to be more trouble than anyone could have imagined...') - # # => Once upon a time, in a kingdom called Far Far Away, a king fell ill, and finding\na successor to the throne turned out to be more trouble than anyone could have\nimagined... - # - # word_wrap('Once upon a time', line_width: 8) - # # => Once\nupon a\ntime - # - # word_wrap('Once upon a time', line_width: 1) - # # => Once\nupon\na\ntime - # - # You can also specify a custom +break_sequence+ ("\n" by default) - # - # word_wrap('Once upon a time', line_width: 1, break_sequence: "\r\n") - # # => Once\r\nupon\r\na\r\ntime - def word_wrap(text, line_width: 80, break_sequence: "\n") - text.split("\n").collect! do |line| - line.length > line_width ? line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\\1#{break_sequence}").strip : line - end * break_sequence - end - - # Returns +text+ transformed into HTML using simple formatting rules. - # Two or more consecutive newlines(\n\n or \r\n\r\n) are - # considered a paragraph and wrapped in

    tags. One newline - # (\n or \r\n) is considered a linebreak and a - #
    tag is appended. This method does not remove the - # newlines from the +text+. - # - # You can pass any HTML attributes into html_options. These - # will be added to all created paragraphs. - # - # ==== Options - # * :sanitize - If +false+, does not sanitize +text+. - # * :wrapper_tag - String representing the wrapper tag, defaults to "p" - # - # ==== Examples - # my_text = "Here is some basic text...\n...with a line break." - # - # simple_format(my_text) - # # => "

    Here is some basic text...\n
    ...with a line break.

    " - # - # simple_format(my_text, {}, wrapper_tag: "div") - # # => "
    Here is some basic text...\n
    ...with a line break.
    " - # - # more_text = "We want to put a paragraph...\n\n...right there." - # - # simple_format(more_text) - # # => "

    We want to put a paragraph...

    \n\n

    ...right there.

    " - # - # simple_format("Look ma! A class!", class: 'description') - # # => "

    Look ma! A class!

    " - # - # simple_format("Unblinkable.") - # # => "

    Unblinkable.

    " - # - # simple_format("Blinkable! It's true.", {}, sanitize: false) - # # => "

    Blinkable! It's true.

    " - def simple_format(text, html_options = {}, options = {}) - wrapper_tag = options.fetch(:wrapper_tag, :p) - - text = sanitize(text) if options.fetch(:sanitize, true) - paragraphs = split_paragraphs(text) - - if paragraphs.empty? - content_tag(wrapper_tag, nil, html_options) - else - paragraphs.map! { |paragraph| - content_tag(wrapper_tag, raw(paragraph), html_options) - }.join("\n\n").html_safe - end - end - - # Creates a Cycle object whose _to_s_ method cycles through elements of an - # array every time it is called. This can be used for example, to alternate - # classes for table rows. You can use named cycles to allow nesting in loops. - # Passing a Hash as the last parameter with a :name key will create a - # named cycle. The default name for a cycle without a +:name+ key is - # "default". You can manually reset a cycle by calling reset_cycle - # and passing the name of the cycle. The current cycle string can be obtained - # anytime using the current_cycle method. - # - # # Alternate CSS classes for even and odd numbers... - # @items = [1,2,3,4] - # - # <% @items.each do |item| %> - # "> - # - # - # <% end %> - #
    <%= item %>
    - # - # - # # Cycle CSS classes for rows, and text colors for values within each row - # @items = x = [{first: 'Robert', middle: 'Daniel', last: 'James'}, - # {first: 'Emily', middle: 'Shannon', maiden: 'Pike', last: 'Hicks'}, - # {first: 'June', middle: 'Dae', last: 'Jones'}] - # <% @items.each do |item| %> - # "> - # - # <% item.values.each do |value| %> - # <%# Create a named cycle "colors" %> - # "> - # <%= value %> - # - # <% end %> - # <% reset_cycle("colors") %> - # - # - # <% end %> - def cycle(first_value, *values) - options = values.extract_options! - name = options.fetch(:name, "default") - - values.unshift(*first_value) - - cycle = get_cycle(name) - unless cycle && cycle.values == values - cycle = set_cycle(name, Cycle.new(*values)) - end - cycle.to_s - end - - # Returns the current cycle string after a cycle has been started. Useful - # for complex table highlighting or any other design need which requires - # the current cycle string in more than one place. - # - # # Alternate background colors - # @items = [1,2,3,4] - # <% @items.each do |item| %> - #
    "> - # <%= item %> - #
    - # <% end %> - def current_cycle(name = "default") - cycle = get_cycle(name) - cycle.current_value if cycle - end - - # Resets a cycle so that it starts from the first element the next time - # it is called. Pass in +name+ to reset a named cycle. - # - # # Alternate CSS classes for even and odd numbers... - # @items = [[1,2,3,4], [5,6,3], [3,4,5,6,7,4]] - # - # <% @items.each do |item| %> - # "> - # <% item.each do |value| %> - # "> - # <%= value %> - # - # <% end %> - # - # <% reset_cycle("colors") %> - # - # <% end %> - #
    - def reset_cycle(name = "default") - cycle = get_cycle(name) - cycle.reset if cycle - end - - class Cycle #:nodoc: - attr_reader :values - - def initialize(first_value, *values) - @values = values.unshift(first_value) - reset - end - - def reset - @index = 0 - end - - def current_value - @values[previous_index].to_s - end - - def to_s - value = @values[@index].to_s - @index = next_index - return value - end - - private - - def next_index - step_index(1) - end - - def previous_index - step_index(-1) - end - - def step_index(n) - (@index + n) % @values.size - end - end - - private - # The cycle helpers need to store the cycles in a place that is - # guaranteed to be reset every time a page is rendered, so it - # uses an instance variable of ActionView::Base. - def get_cycle(name) - @_cycles = Hash.new unless defined?(@_cycles) - return @_cycles[name] - end - - def set_cycle(name, cycle_object) - @_cycles = Hash.new unless defined?(@_cycles) - @_cycles[name] = cycle_object - end - - def split_paragraphs(text) - return [] if text.blank? - - text.to_str.gsub(/\r\n?/, "\n").split(/\n\n+/).map! do |t| - t.gsub!(/([^\n]\n)(?=[^\n])/, '\1
    ') || t - end - end - - def cut_excerpt_part(part_position, part, separator, options) - return "", "" unless part - - radius = options.fetch(:radius, 100) - omission = options.fetch(:omission, "...") - - part = part.split(separator) - part.delete("") - affix = part.size > radius ? omission : "" - - part = if part_position == :first - drop_index = [part.length - radius, 0].max - part.drop(drop_index) - else - part.first(radius) - end - - return affix, part.join(separator) - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/translation_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/translation_helper.rb deleted file mode 100644 index 47ed41a129..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/translation_helper.rb +++ /dev/null @@ -1,140 +0,0 @@ -require "action_view/helpers/tag_helper" -require "active_support/core_ext/string/access" -require "i18n/exceptions" - -module ActionView - # = Action View Translation Helpers - module Helpers - module TranslationHelper - extend ActiveSupport::Concern - - include TagHelper - - included do - mattr_accessor :debug_missing_translation - self.debug_missing_translation = true - end - - # Delegates to I18n#translate but also performs three additional - # functions. - # - # First, it will ensure that any thrown +MissingTranslation+ messages will - # be rendered as inline spans that: - # - # * Have a translation-missing class applied - # * Contain the missing key as the value of the +title+ attribute - # * Have a titleized version of the last key segment as text - # - # For example, the value returned for the missing translation key - # "blog.post.title" will be: - # - # Title - # - # This allows for views to display rather reasonable strings while still - # giving developers a way to find missing translations. - # - # If you would prefer missing translations to raise an error, you can - # opt out of span-wrapping behavior globally by setting - # ActionView::Base.raise_on_missing_translations = true or - # individually by passing raise: true as an option to - # translate. - # - # Second, if the key starts with a period translate will scope - # the key by the current partial. Calling translate(".foo") from - # the people/index.html.erb template is equivalent to calling - # translate("people.index.foo"). This makes it less - # repetitive to translate many keys within the same partial and provides - # a convention to scope keys consistently. - # - # Third, the translation will be marked as html_safe if the key - # has the suffix "_html" or the last element of the key is "html". Calling - # translate("footer_html") or translate("footer.html") - # will return an HTML safe string that won't be escaped by other HTML - # helper methods. This naming convention helps to identify translations - # that include HTML tags so that you know what kind of output to expect - # when you call translate in a template and translators know which keys - # they can provide HTML values for. - def translate(key, options = {}) - options = options.dup - has_default = options.has_key?(:default) - remaining_defaults = Array(options.delete(:default)).compact - - if has_default && !remaining_defaults.first.kind_of?(Symbol) - options[:default] = remaining_defaults - end - - # If the user has explicitly decided to NOT raise errors, pass that option to I18n. - # Otherwise, tell I18n to raise an exception, which we rescue further in this method. - # Note: `raise_error` refers to us re-raising the error in this method. I18n is forced to raise by default. - if options[:raise] == false - raise_error = false - i18n_raise = false - else - raise_error = options[:raise] || ActionView::Base.raise_on_missing_translations - i18n_raise = true - end - - if html_safe_translation_key?(key) - html_safe_options = options.dup - options.except(*I18n::RESERVED_KEYS).each do |name, value| - unless name == :count && value.is_a?(Numeric) - html_safe_options[name] = ERB::Util.html_escape(value.to_s) - end - end - translation = I18n.translate(scope_key_by_partial(key), html_safe_options.merge(raise: i18n_raise)) - - translation.respond_to?(:html_safe) ? translation.html_safe : translation - else - I18n.translate(scope_key_by_partial(key), options.merge(raise: i18n_raise)) - end - rescue I18n::MissingTranslationData => e - if remaining_defaults.present? - translate remaining_defaults.shift, options.merge(default: remaining_defaults) - else - raise e if raise_error - - keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope]) - title = "translation missing: #{keys.join('.')}" - - interpolations = options.except(:default, :scope) - if interpolations.any? - title << ", " << interpolations.map { |k, v| "#{k}: #{ERB::Util.html_escape(v)}" }.join(", ") - end - - return title unless ActionView::Base.debug_missing_translation - - content_tag("span", keys.last.to_s.titleize, class: "translation_missing", title: title) - end - end - alias :t :translate - - # Delegates to I18n.localize with no additional functionality. - # - # See http://rubydoc.info/github/svenfuchs/i18n/master/I18n/Backend/Base:localize - # for more information. - def localize(*args) - I18n.localize(*args) - end - alias :l :localize - - private - def scope_key_by_partial(key) - if key.to_s.first == "." - if @virtual_path - @virtual_path.gsub(%r{/_?}, ".") + key.to_s - else - raise "Cannot use t(#{key.inspect}) shortcut because path is not available" - end - else - key - end - end - - def html_safe_translation_key?(key) - /(\b|_|\.)html$/.match?(key.to_s) - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/url_helper.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/url_helper.rb deleted file mode 100644 index 775d3fe234..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/helpers/url_helper.rb +++ /dev/null @@ -1,652 +0,0 @@ -require "action_view/helpers/javascript_helper" -require "active_support/core_ext/array/access" -require "active_support/core_ext/hash/keys" -require "active_support/core_ext/string/output_safety" - -module ActionView - # = Action View URL Helpers - module Helpers #:nodoc: - # Provides a set of methods for making links and getting URLs that - # depend on the routing subsystem (see ActionDispatch::Routing). - # This allows you to use the same format for links in views - # and controllers. - module UrlHelper - # This helper may be included in any class that includes the - # URL helpers of a routes (routes.url_helpers). Some methods - # provided here will only work in the context of a request - # (link_to_unless_current, for instance), which must be provided - # as a method called #request on the context. - BUTTON_TAG_METHOD_VERBS = %w{patch put delete} - extend ActiveSupport::Concern - - include TagHelper - - module ClassMethods - def _url_for_modules - ActionView::RoutingUrlFor - end - end - - # Basic implementation of url_for to allow use helpers without routes existence - def url_for(options = nil) # :nodoc: - case options - when String - options - when :back - _back_url - else - raise ArgumentError, "arguments passed to url_for can't be handled. Please require " \ - "routes or provide your own implementation" - end - end - - def _back_url # :nodoc: - _filtered_referrer || "javascript:history.back()" - end - protected :_back_url - - def _filtered_referrer # :nodoc: - if controller.respond_to?(:request) - referrer = controller.request.env["HTTP_REFERER"] - if referrer && URI(referrer).scheme != "javascript" - referrer - end - end - rescue URI::InvalidURIError - end - protected :_filtered_referrer - - # Creates an anchor element of the given +name+ using a URL created by the set of +options+. - # See the valid options in the documentation for +url_for+. It's also possible to - # pass a String instead of an options hash, which generates an anchor element that uses the - # value of the String as the href for the link. Using a :back Symbol instead - # of an options hash will generate a link to the referrer (a JavaScript back link - # will be used in place of a referrer if none exists). If +nil+ is passed as the name - # the value of the link itself will become the name. - # - # ==== Signatures - # - # link_to(body, url, html_options = {}) - # # url is a String; you can use URL helpers like - # # posts_path - # - # link_to(body, url_options = {}, html_options = {}) - # # url_options, except :method, is passed to url_for - # - # link_to(options = {}, html_options = {}) do - # # name - # end - # - # link_to(url, html_options = {}) do - # # name - # end - # - # ==== Options - # * :data - This option can be used to add custom data attributes. - # * method: symbol of HTTP verb - This modifier will dynamically - # create an HTML form and immediately submit the form for processing using - # the HTTP verb specified. Useful for having links perform a POST operation - # in dangerous actions like deleting a record (which search bots can follow - # while spidering your site). Supported verbs are :post, :delete, :patch, and :put. - # Note that if the user has JavaScript disabled, the request will fall back - # to using GET. If href: '#' is used and the user has JavaScript - # disabled clicking the link will have no effect. If you are relying on the - # POST behavior, you should check for it in your controller's action by using - # the request object's methods for post?, delete?, patch?, or put?. - # * remote: true - This will allow the unobtrusive JavaScript - # driver to make an Ajax request to the URL in question instead of following - # the link. The drivers each provide mechanisms for listening for the - # completion of the Ajax request and performing JavaScript operations once - # they're complete - # - # ==== Data attributes - # - # * confirm: 'question?' - This will allow the unobtrusive JavaScript - # driver to prompt with the question specified (in this case, the - # resulting text would be question?. If the user accepts, the - # link is processed normally, otherwise no action is taken. - # * :disable_with - Value of this parameter will be used as the - # name for a disabled version of the link. This feature is provided by - # the unobtrusive JavaScript driver. - # - # ==== Examples - # Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments - # and newer RESTful routes. Current Rails style favors RESTful routes whenever possible, so base - # your application on resources and use - # - # link_to "Profile", profile_path(@profile) - # # => Profile - # - # or the even pithier - # - # link_to "Profile", @profile - # # => Profile - # - # in place of the older more verbose, non-resource-oriented - # - # link_to "Profile", controller: "profiles", action: "show", id: @profile - # # => Profile - # - # Similarly, - # - # link_to "Profiles", profiles_path - # # => Profiles - # - # is better than - # - # link_to "Profiles", controller: "profiles" - # # => Profiles - # - # You can use a block as well if your link target is hard to fit into the name parameter. ERB example: - # - # <%= link_to(@profile) do %> - # <%= @profile.name %> -- Check it out! - # <% end %> - # # => - # David -- Check it out! - # - # - # Classes and ids for CSS are easy to produce: - # - # link_to "Articles", articles_path, id: "news", class: "article" - # # => Articles - # - # Be careful when using the older argument style, as an extra literal hash is needed: - # - # link_to "Articles", { controller: "articles" }, id: "news", class: "article" - # # => Articles - # - # Leaving the hash off gives the wrong link: - # - # link_to "WRONG!", controller: "articles", id: "news", class: "article" - # # => WRONG! - # - # +link_to+ can also produce links with anchors or query strings: - # - # link_to "Comment wall", profile_path(@profile, anchor: "wall") - # # => Comment wall - # - # link_to "Ruby on Rails search", controller: "searches", query: "ruby on rails" - # # => Ruby on Rails search - # - # link_to "Nonsense search", searches_path(foo: "bar", baz: "quux") - # # => Nonsense search - # - # The only option specific to +link_to+ (:method) is used as follows: - # - # link_to("Destroy", "http://www.example.com", method: :delete) - # # => Destroy - # - # You can also use custom data attributes using the :data option: - # - # link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" } - # # => Visit Other Site - # - # Also you can set any link attributes such as target, rel, type: - # - # link_to "External link", "http://www.rubyonrails.org/", target: "_blank", rel: "nofollow" - # # => External link - def link_to(name = nil, options = nil, html_options = nil, &block) - html_options, options, name = options, name, block if block_given? - options ||= {} - - html_options = convert_options_to_data_attributes(options, html_options) - - url = url_for(options) - html_options["href".freeze] ||= url - - content_tag("a".freeze, name || url, html_options, &block) - end - - # Generates a form containing a single button that submits to the URL created - # by the set of +options+. This is the safest method to ensure links that - # cause changes to your data are not triggered by search bots or accelerators. - # If the HTML button does not work with your layout, you can also consider - # using the +link_to+ method with the :method modifier as described in - # the +link_to+ documentation. - # - # By default, the generated form element has a class name of button_to - # to allow styling of the form itself and its children. This can be changed - # using the :form_class modifier within +html_options+. You can control - # the form submission and input element behavior using +html_options+. - # This method accepts the :method modifier described in the +link_to+ documentation. - # If no :method modifier is given, it will default to performing a POST operation. - # You can also disable the button by passing disabled: true in +html_options+. - # If you are using RESTful routes, you can pass the :method - # to change the HTTP verb used to submit the form. - # - # ==== Options - # The +options+ hash accepts the same options as +url_for+. - # - # There are a few special +html_options+: - # * :method - Symbol of HTTP verb. Supported verbs are :post, :get, - # :delete, :patch, and :put. By default it will be :post. - # * :disabled - If set to true, it will generate a disabled button. - # * :data - This option can be used to add custom data attributes. - # * :remote - If set to true, will allow the Unobtrusive JavaScript drivers to control the - # submit behavior. By default this behavior is an ajax submit. - # * :form - This hash will be form attributes - # * :form_class - This controls the class of the form within which the submit button will - # be placed - # * :params - Hash of parameters to be rendered as hidden fields within the form. - # - # ==== Data attributes - # - # * :confirm - This will use the unobtrusive JavaScript driver to - # prompt with the question specified. If the user accepts, the link is - # processed normally, otherwise no action is taken. - # * :disable_with - Value of this parameter will be - # used as the value for a disabled version of the submit - # button when the form is submitted. This feature is provided - # by the unobtrusive JavaScript driver. - # - # ==== Examples - # <%= button_to "New", action: "new" %> - # # => "
    - # # - # #
    " - # - # <%= button_to "New", new_articles_path %> - # # => "
    - # # - # #
    " - # - # <%= button_to [:make_happy, @user] do %> - # Make happy <%= @user.name %> - # <% end %> - # # => "
    - # # - # #
    " - # - # <%= button_to "New", { action: "new" }, form_class: "new-thing" %> - # # => "
    - # # - # #
    " - # - # - # <%= button_to "Create", { action: "create" }, remote: true, form: { "data-type" => "json" } %> - # # => "
    - # # - # # - # #
    " - # - # - # <%= button_to "Delete Image", { action: "delete", id: @image.id }, - # method: :delete, data: { confirm: "Are you sure?" } %> - # # => "
    - # # - # # - # # - # #
    " - # - # - # <%= button_to('Destroy', 'http://www.example.com', - # method: "delete", remote: true, data: { confirm: 'Are you sure?', disable_with: 'loading...' }) %> - # # => "
    - # # - # # - # # - # #
    " - # # - def button_to(name = nil, options = nil, html_options = nil, &block) - html_options, options = options, name if block_given? - options ||= {} - html_options ||= {} - html_options = html_options.stringify_keys - - url = options.is_a?(String) ? options : url_for(options) - remote = html_options.delete("remote") - params = html_options.delete("params") - - method = html_options.delete("method").to_s - method_tag = BUTTON_TAG_METHOD_VERBS.include?(method) ? method_tag(method) : "".freeze.html_safe - - form_method = method == "get" ? "get" : "post" - form_options = html_options.delete("form") || {} - form_options[:class] ||= html_options.delete("form_class") || "button_to" - form_options[:method] = form_method - form_options[:action] = url - form_options[:'data-remote'] = true if remote - - request_token_tag = if form_method == "post" - request_method = method.empty? ? "post" : method - token_tag(nil, form_options: { action: url, method: request_method }) - else - "".freeze - end - - html_options = convert_options_to_data_attributes(options, html_options) - html_options["type"] = "submit" - - button = if block_given? - content_tag("button", html_options, &block) - else - html_options["value"] = name || url - tag("input", html_options) - end - - inner_tags = method_tag.safe_concat(button).safe_concat(request_token_tag) - if params - to_form_params(params).each do |param| - inner_tags.safe_concat tag(:input, type: "hidden", name: param[:name], value: param[:value]) - end - end - content_tag("form", inner_tags, form_options) - end - - # Creates a link tag of the given +name+ using a URL created by the set of - # +options+ unless the current request URI is the same as the links, in - # which case only the name is returned (or the given block is yielded, if - # one exists). You can give +link_to_unless_current+ a block which will - # specialize the default behavior (e.g., show a "Start Here" link rather - # than the link's text). - # - # ==== Examples - # Let's say you have a navigation menu... - # - # - # - # If in the "about" action, it will render... - # - # - # - # ...but if in the "index" action, it will render: - # - # - # - # The implicit block given to +link_to_unless_current+ is evaluated if the current - # action is the action given. So, if we had a comments page and wanted to render a - # "Go Back" link instead of a link to the comments page, we could do something like this... - # - # <%= - # link_to_unless_current("Comment", { controller: "comments", action: "new" }) do - # link_to("Go back", { controller: "posts", action: "index" }) - # end - # %> - def link_to_unless_current(name, options = {}, html_options = {}, &block) - link_to_unless current_page?(options), name, options, html_options, &block - end - - # Creates a link tag of the given +name+ using a URL created by the set of - # +options+ unless +condition+ is true, in which case only the name is - # returned. To specialize the default behavior (i.e., show a login link rather - # than just the plaintext link text), you can pass a block that - # accepts the name or the full argument list for +link_to_unless+. - # - # ==== Examples - # <%= link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) %> - # # If the user is logged in... - # # => Reply - # - # <%= - # link_to_unless(@current_user.nil?, "Reply", { action: "reply" }) do |name| - # link_to(name, { controller: "accounts", action: "signup" }) - # end - # %> - # # If the user is logged in... - # # => Reply - # # If not... - # # => Reply - def link_to_unless(condition, name, options = {}, html_options = {}, &block) - link_to_if !condition, name, options, html_options, &block - end - - # Creates a link tag of the given +name+ using a URL created by the set of - # +options+ if +condition+ is true, otherwise only the name is - # returned. To specialize the default behavior, you can pass a block that - # accepts the name or the full argument list for +link_to_unless+ (see the examples - # in +link_to_unless+). - # - # ==== Examples - # <%= link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) %> - # # If the user isn't logged in... - # # => Login - # - # <%= - # link_to_if(@current_user.nil?, "Login", { controller: "sessions", action: "new" }) do - # link_to(@current_user.login, { controller: "accounts", action: "show", id: @current_user }) - # end - # %> - # # If the user isn't logged in... - # # => Login - # # If they are logged in... - # # => my_username - def link_to_if(condition, name, options = {}, html_options = {}, &block) - if condition - link_to(name, options, html_options) - else - if block_given? - block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block) - else - ERB::Util.html_escape(name) - end - end - end - - # Creates a mailto link tag to the specified +email_address+, which is - # also used as the name of the link unless +name+ is specified. Additional - # HTML attributes for the link can be passed in +html_options+. - # - # +mail_to+ has several methods for customizing the email itself by - # passing special keys to +html_options+. - # - # ==== Options - # * :subject - Preset the subject line of the email. - # * :body - Preset the body of the email. - # * :cc - Carbon Copy additional recipients on the email. - # * :bcc - Blind Carbon Copy additional recipients on the email. - # * :reply_to - Preset the Reply-To field of the email. - # - # ==== Obfuscation - # Prior to Rails 4.0, +mail_to+ provided options for encoding the address - # in order to hinder email harvesters. To take advantage of these options, - # install the +actionview-encoded_mail_to+ gem. - # - # ==== Examples - # mail_to "me@domain.com" - # # => me@domain.com - # - # mail_to "me@domain.com", "My email" - # # => My email - # - # mail_to "me@domain.com", "My email", cc: "ccaddress@domain.com", - # subject: "This is an example email" - # # => My email - # - # You can use a block as well if your link target is hard to fit into the name parameter. ERB example: - # - # <%= mail_to "me@domain.com" do %> - # Email me: me@domain.com - # <% end %> - # # => - # Email me: me@domain.com - # - def mail_to(email_address, name = nil, html_options = {}, &block) - html_options, name = name, nil if block_given? - html_options = (html_options || {}).stringify_keys - - extras = %w{ cc bcc body subject reply_to }.map! { |item| - option = html_options.delete(item).presence || next - "#{item.dasherize}=#{ERB::Util.url_encode(option)}" - }.compact - extras = extras.empty? ? "".freeze : "?" + extras.join("&") - - encoded_email_address = ERB::Util.url_encode(email_address).gsub("%40", "@") - html_options["href"] = "mailto:#{encoded_email_address}#{extras}" - - content_tag("a".freeze, name || email_address, html_options, &block) - end - - # True if the current request URI was generated by the given +options+. - # - # ==== Examples - # Let's say we're in the http://www.example.com/shop/checkout?order=desc&page=1 action. - # - # current_page?(action: 'process') - # # => false - # - # current_page?(action: 'checkout') - # # => true - # - # current_page?(controller: 'library', action: 'checkout') - # # => false - # - # current_page?(controller: 'shop', action: 'checkout') - # # => true - # - # current_page?(controller: 'shop', action: 'checkout', order: 'asc') - # # => false - # - # current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '1') - # # => true - # - # current_page?(controller: 'shop', action: 'checkout', order: 'desc', page: '2') - # # => false - # - # current_page?('http://www.example.com/shop/checkout') - # # => true - # - # current_page?('http://www.example.com/shop/checkout', check_parameters: true) - # # => false - # - # current_page?('/shop/checkout') - # # => true - # - # current_page?('http://www.example.com/shop/checkout?order=desc&page=1') - # # => true - # - # Let's say we're in the http://www.example.com/products action with method POST in case of invalid product. - # - # current_page?(controller: 'product', action: 'index') - # # => false - # - # We can also pass in the symbol arguments instead of strings. - # - def current_page?(options, check_parameters: false) - unless request - raise "You cannot use helpers that need to determine the current " \ - "page unless your view context provides a Request object " \ - "in a #request method" - end - - return false unless request.get? || request.head? - - check_parameters ||= options.is_a?(Hash) && options.delete(:check_parameters) - url_string = URI.parser.unescape(url_for(options)).force_encoding(Encoding::BINARY) - - # We ignore any extra parameters in the request_uri if the - # submitted url doesn't have any either. This lets the function - # work with things like ?order=asc - # the behaviour can be disabled with check_parameters: true - request_uri = url_string.index("?") || check_parameters ? request.fullpath : request.path - request_uri = URI.parser.unescape(request_uri).force_encoding(Encoding::BINARY) - - if url_string.start_with?("/") && url_string != "/" - url_string.chomp!("/") - request_uri.chomp!("/") - end - - if %r{^\w+://}.match?(url_string) - url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}" - else - url_string == request_uri - end - end - - private - def convert_options_to_data_attributes(options, html_options) - if html_options - html_options = html_options.stringify_keys - html_options["data-remote"] = "true".freeze if link_to_remote_options?(options) || link_to_remote_options?(html_options) - - method = html_options.delete("method".freeze) - - add_method_to_attributes!(html_options, method) if method - - html_options - else - link_to_remote_options?(options) ? { "data-remote" => "true".freeze } : {} - end - end - - def link_to_remote_options?(options) - if options.is_a?(Hash) - options.delete("remote".freeze) || options.delete(:remote) - end - end - - def add_method_to_attributes!(html_options, method) - if method && method.to_s.downcase != "get".freeze && html_options["rel".freeze] !~ /nofollow/ - html_options["rel".freeze] = "#{html_options["rel".freeze]} nofollow".lstrip - end - html_options["data-method".freeze] = method - end - - def token_tag(token = nil, form_options: {}) - if token != false && protect_against_forgery? - token ||= form_authenticity_token(form_options: form_options) - tag(:input, type: "hidden", name: request_forgery_protection_token.to_s, value: token) - else - "".freeze - end - end - - def method_tag(method) - tag("input", type: "hidden", name: "_method", value: method.to_s) - end - - # Returns an array of hashes each containing :name and :value keys - # suitable for use as the names and values of form input fields: - # - # to_form_params(name: 'David', nationality: 'Danish') - # # => [{name: 'name', value: 'David'}, {name: 'nationality', value: 'Danish'}] - # - # to_form_params(country: {name: 'Denmark'}) - # # => [{name: 'country[name]', value: 'Denmark'}] - # - # to_form_params(countries: ['Denmark', 'Sweden']}) - # # => [{name: 'countries[]', value: 'Denmark'}, {name: 'countries[]', value: 'Sweden'}] - # - # An optional namespace can be passed to enclose key names: - # - # to_form_params({ name: 'Denmark' }, 'country') - # # => [{name: 'country[name]', value: 'Denmark'}] - def to_form_params(attribute, namespace = nil) - attribute = if attribute.respond_to?(:permitted?) - attribute.to_h - else - attribute - end - - params = [] - case attribute - when Hash - attribute.each do |key, value| - prefix = namespace ? "#{namespace}[#{key}]" : key - params.push(*to_form_params(value, prefix)) - end - when Array - array_prefix = "#{namespace}[]" - attribute.each do |value| - params.push(*to_form_params(value, array_prefix)) - end - else - params << { name: namespace.to_s, value: attribute.to_param } - end - - params.sort_by { |pair| pair[:name] } - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/layouts.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/layouts.rb deleted file mode 100644 index 81feb90486..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/layouts.rb +++ /dev/null @@ -1,431 +0,0 @@ -require "action_view/rendering" -require "active_support/core_ext/module/remove_method" - -module ActionView - # Layouts reverse the common pattern of including shared headers and footers in many templates to isolate changes in - # repeated setups. The inclusion pattern has pages that look like this: - # - # <%= render "shared/header" %> - # Hello World - # <%= render "shared/footer" %> - # - # This approach is a decent way of keeping common structures isolated from the changing content, but it's verbose - # and if you ever want to change the structure of these two includes, you'll have to change all the templates. - # - # With layouts, you can flip it around and have the common structure know where to insert changing content. This means - # that the header and footer are only mentioned in one place, like this: - # - # // The header part of this layout - # <%= yield %> - # // The footer part of this layout - # - # And then you have content pages that look like this: - # - # hello world - # - # At rendering time, the content page is computed and then inserted in the layout, like this: - # - # // The header part of this layout - # hello world - # // The footer part of this layout - # - # == Accessing shared variables - # - # Layouts have access to variables specified in the content pages and vice versa. This allows you to have layouts with - # references that won't materialize before rendering time: - # - #

    <%= @page_title %>

    - # <%= yield %> - # - # ...and content pages that fulfill these references _at_ rendering time: - # - # <% @page_title = "Welcome" %> - # Off-world colonies offers you a chance to start a new life - # - # The result after rendering is: - # - #

    Welcome

    - # Off-world colonies offers you a chance to start a new life - # - # == Layout assignment - # - # You can either specify a layout declaratively (using the #layout class method) or give - # it the same name as your controller, and place it in app/views/layouts. - # If a subclass does not have a layout specified, it inherits its layout using normal Ruby inheritance. - # - # For instance, if you have PostsController and a template named app/views/layouts/posts.html.erb, - # that template will be used for all actions in PostsController and controllers inheriting - # from PostsController. - # - # If you use a module, for instance Weblog::PostsController, you will need a template named - # app/views/layouts/weblog/posts.html.erb. - # - # Since all your controllers inherit from ApplicationController, they will use - # app/views/layouts/application.html.erb if no other layout is specified - # or provided. - # - # == Inheritance Examples - # - # class BankController < ActionController::Base - # # bank.html.erb exists - # - # class ExchangeController < BankController - # # exchange.html.erb exists - # - # class CurrencyController < BankController - # - # class InformationController < BankController - # layout "information" - # - # class TellerController < InformationController - # # teller.html.erb exists - # - # class EmployeeController < InformationController - # # employee.html.erb exists - # layout nil - # - # class VaultController < BankController - # layout :access_level_layout - # - # class TillController < BankController - # layout false - # - # In these examples, we have three implicit lookup scenarios: - # * The +BankController+ uses the "bank" layout. - # * The +ExchangeController+ uses the "exchange" layout. - # * The +CurrencyController+ inherits the layout from BankController. - # - # However, when a layout is explicitly set, the explicitly set layout wins: - # * The +InformationController+ uses the "information" layout, explicitly set. - # * The +TellerController+ also uses the "information" layout, because the parent explicitly set it. - # * The +EmployeeController+ uses the "employee" layout, because it set the layout to +nil+, resetting the parent configuration. - # * The +VaultController+ chooses a layout dynamically by calling the access_level_layout method. - # * The +TillController+ does not use a layout at all. - # - # == Types of layouts - # - # Layouts are basically just regular templates, but the name of this template needs not be specified statically. Sometimes - # you want to alternate layouts depending on runtime information, such as whether someone is logged in or not. This can - # be done either by specifying a method reference as a symbol or using an inline method (as a proc). - # - # The method reference is the preferred approach to variable layouts and is used like this: - # - # class WeblogController < ActionController::Base - # layout :writers_and_readers - # - # def index - # # fetching posts - # end - # - # private - # def writers_and_readers - # logged_in? ? "writer_layout" : "reader_layout" - # end - # end - # - # Now when a new request for the index action is processed, the layout will vary depending on whether the person accessing - # is logged in or not. - # - # If you want to use an inline method, such as a proc, do something like this: - # - # class WeblogController < ActionController::Base - # layout proc { |controller| controller.logged_in? ? "writer_layout" : "reader_layout" } - # end - # - # If an argument isn't given to the proc, it's evaluated in the context of - # the current controller anyway. - # - # class WeblogController < ActionController::Base - # layout proc { logged_in? ? "writer_layout" : "reader_layout" } - # end - # - # Of course, the most common way of specifying a layout is still just as a plain template name: - # - # class WeblogController < ActionController::Base - # layout "weblog_standard" - # end - # - # The template will be looked always in app/views/layouts/ folder. But you can point - # layouts folder direct also. layout "layouts/demo" is the same as layout "demo". - # - # Setting the layout to +nil+ forces it to be looked up in the filesystem and fallbacks to the parent behavior if none exists. - # Setting it to +nil+ is useful to re-enable template lookup overriding a previous configuration set in the parent: - # - # class ApplicationController < ActionController::Base - # layout "application" - # end - # - # class PostsController < ApplicationController - # # Will use "application" layout - # end - # - # class CommentsController < ApplicationController - # # Will search for "comments" layout and fallback "application" layout - # layout nil - # end - # - # == Conditional layouts - # - # If you have a layout that by default is applied to all the actions of a controller, you still have the option of rendering - # a given action or set of actions without a layout, or restricting a layout to only a single action or a set of actions. The - # :only and :except options can be passed to the layout call. For example: - # - # class WeblogController < ActionController::Base - # layout "weblog_standard", except: :rss - # - # # ... - # - # end - # - # This will assign "weblog_standard" as the WeblogController's layout for all actions except for the +rss+ action, which will - # be rendered directly, without wrapping a layout around the rendered view. - # - # Both the :only and :except condition can accept an arbitrary number of method references, so - # #except: [ :rss, :text_only ] is valid, as is except: :rss. - # - # == Using a different layout in the action render call - # - # If most of your actions use the same layout, it makes perfect sense to define a controller-wide layout as described above. - # Sometimes you'll have exceptions where one action wants to use a different layout than the rest of the controller. - # You can do this by passing a :layout option to the render call. For example: - # - # class WeblogController < ActionController::Base - # layout "weblog_standard" - # - # def help - # render action: "help", layout: "help" - # end - # end - # - # This will override the controller-wide "weblog_standard" layout, and will render the help action with the "help" layout instead. - module Layouts - extend ActiveSupport::Concern - - include ActionView::Rendering - - included do - class_attribute :_layout, :_layout_conditions, instance_accessor: false - self._layout = nil - self._layout_conditions = {} - _write_layout_method - end - - delegate :_layout_conditions, to: :class - - module ClassMethods - def inherited(klass) # :nodoc: - super - klass._write_layout_method - end - - # This module is mixed in if layout conditions are provided. This means - # that if no layout conditions are used, this method is not used - module LayoutConditions # :nodoc: - private - - # Determines whether the current action has a layout definition by - # checking the action name against the :only and :except conditions - # set by the layout method. - # - # ==== Returns - # * Boolean - True if the action has a layout definition, false otherwise. - def _conditional_layout? - return unless super - - conditions = _layout_conditions - - if only = conditions[:only] - only.include?(action_name) - elsif except = conditions[:except] - !except.include?(action_name) - else - true - end - end - end - - # Specify the layout to use for this class. - # - # If the specified layout is a: - # String:: the String is the template name - # Symbol:: call the method specified by the symbol - # Proc:: call the passed Proc - # false:: There is no layout - # true:: raise an ArgumentError - # nil:: Force default layout behavior with inheritance - # - # Return value of +Proc+ and +Symbol+ arguments should be +String+, +false+, +true+ or +nil+ - # with the same meaning as described above. - # ==== Parameters - # * layout - The layout to use. - # - # ==== Options (conditions) - # * :only - A list of actions to apply this layout to. - # * :except - Apply this layout to all actions but this one. - def layout(layout, conditions = {}) - include LayoutConditions unless conditions.empty? - - conditions.each { |k, v| conditions[k] = Array(v).map(&:to_s) } - self._layout_conditions = conditions - - self._layout = layout - _write_layout_method - end - - # Creates a _layout method to be called by _default_layout . - # - # If a layout is not explicitly mentioned then look for a layout with the controller's name. - # if nothing is found then try same procedure to find super class's layout. - def _write_layout_method # :nodoc: - remove_possible_method(:_layout) - - prefixes = /\blayouts/.match?(_implied_layout_name) ? [] : ["layouts"] - default_behavior = "lookup_context.find_all('#{_implied_layout_name}', #{prefixes.inspect}, false, [], { formats: formats }).first || super" - name_clause = if name - default_behavior - else - <<-RUBY - super - RUBY - end - - layout_definition = \ - case _layout - when String - _layout.inspect - when Symbol - <<-RUBY - #{_layout}.tap do |layout| - return #{default_behavior} if layout.nil? - unless layout.is_a?(String) || !layout - raise ArgumentError, "Your layout method :#{_layout} returned \#{layout}. It " \ - "should have returned a String, false, or nil" - end - end - RUBY - when Proc - define_method :_layout_from_proc, &_layout - protected :_layout_from_proc - <<-RUBY - result = _layout_from_proc(#{_layout.arity == 0 ? '' : 'self'}) - return #{default_behavior} if result.nil? - result - RUBY - when false - nil - when true - raise ArgumentError, "Layouts must be specified as a String, Symbol, Proc, false, or nil" - when nil - name_clause - end - - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def _layout(formats) - if _conditional_layout? - #{layout_definition} - else - #{name_clause} - end - end - private :_layout - RUBY - end - - private - - # If no layout is supplied, look for a template named the return - # value of this method. - # - # ==== Returns - # * String - A template name - def _implied_layout_name - controller_path - end - end - - def _normalize_options(options) # :nodoc: - super - - if _include_layout?(options) - layout = options.delete(:layout) { :default } - options[:layout] = _layout_for_option(layout) - end - end - - attr_internal_writer :action_has_layout - - def initialize(*) # :nodoc: - @_action_has_layout = true - super - end - - # Controls whether an action should be rendered using a layout. - # If you want to disable any layout settings for the - # current action so that it is rendered without a layout then - # either override this method in your controller to return false - # for that action or set the action_has_layout attribute - # to false before rendering. - def action_has_layout? - @_action_has_layout - end - - private - - def _conditional_layout? - true - end - - # This will be overwritten by _write_layout_method - def _layout(*); end - - # Determine the layout for a given name, taking into account the name type. - # - # ==== Parameters - # * name - The name of the template - def _layout_for_option(name) - case name - when String then _normalize_layout(name) - when Proc then name - when true then Proc.new { |formats| _default_layout(formats, true) } - when :default then Proc.new { |formats| _default_layout(formats, false) } - when false, nil then nil - else - raise ArgumentError, - "String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}" - end - end - - def _normalize_layout(value) - value.is_a?(String) && value !~ /\blayouts/ ? "layouts/#{value}" : value - end - - # Returns the default layout for this controller. - # Optionally raises an exception if the layout could not be found. - # - # ==== Parameters - # * formats - The formats accepted to this layout - # * require_layout - If set to +true+ and layout is not found, - # an +ArgumentError+ exception is raised (defaults to +false+) - # - # ==== Returns - # * template - The template object for the default layout (or +nil+) - def _default_layout(formats, require_layout = false) - begin - value = _layout(formats) if action_has_layout? - rescue NameError => e - raise e, "Could not render layout: #{e.message}" - end - - if require_layout && action_has_layout? && !value - raise ArgumentError, - "There was no default layout for #{self.class} in #{view_paths.inspect}" - end - - _normalize_layout(value) - end - - def _include_layout?(options) - (options.keys & [:body, :plain, :html, :inline, :partial]).empty? || options.key?(:layout) - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/locale/en.yml b/debian/gems-compat/actionview-5.1.7/lib/action_view/locale/en.yml deleted file mode 100644 index 8a56f147b8..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/locale/en.yml +++ /dev/null @@ -1,56 +0,0 @@ -"en": - # Used in distance_of_time_in_words(), distance_of_time_in_words_to_now(), time_ago_in_words() - datetime: - distance_in_words: - half_a_minute: "half a minute" - less_than_x_seconds: - one: "less than 1 second" - other: "less than %{count} seconds" - x_seconds: - one: "1 second" - other: "%{count} seconds" - less_than_x_minutes: - one: "less than a minute" - other: "less than %{count} minutes" - x_minutes: - one: "1 minute" - other: "%{count} minutes" - about_x_hours: - one: "about 1 hour" - other: "about %{count} hours" - x_days: - one: "1 day" - other: "%{count} days" - about_x_months: - one: "about 1 month" - other: "about %{count} months" - x_months: - one: "1 month" - other: "%{count} months" - about_x_years: - one: "about 1 year" - other: "about %{count} years" - over_x_years: - one: "over 1 year" - other: "over %{count} years" - almost_x_years: - one: "almost 1 year" - other: "almost %{count} years" - prompts: - year: "Year" - month: "Month" - day: "Day" - hour: "Hour" - minute: "Minute" - second: "Seconds" - - helpers: - select: - # Default value for :prompt => true in FormOptionsHelper - prompt: "Please select" - - # Default translation keys for submit and button FormHelper - submit: - create: 'Create %{model}' - update: 'Update %{model}' - submit: 'Save %{model}' diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/log_subscriber.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/log_subscriber.rb deleted file mode 100644 index ab8ec0aa42..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/log_subscriber.rb +++ /dev/null @@ -1,94 +0,0 @@ -require "active_support/log_subscriber" - -module ActionView - # = Action View Log Subscriber - # - # Provides functionality so that Rails can output logs from Action View. - class LogSubscriber < ActiveSupport::LogSubscriber - VIEWS_PATTERN = /^app\/views\// - - def initialize - @root = nil - super - end - - def render_template(event) - info do - message = " Rendered #{from_rails_root(event.payload[:identifier])}" - message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout] - message << " (#{event.duration.round(1)}ms)" - end - end - - def render_partial(event) - info do - message = " Rendered #{from_rails_root(event.payload[:identifier])}" - message << " within #{from_rails_root(event.payload[:layout])}" if event.payload[:layout] - message << " (#{event.duration.round(1)}ms)" - message << " #{cache_message(event.payload)}" unless event.payload[:cache_hit].nil? - message - end - end - - def render_collection(event) - identifier = event.payload[:identifier] || "templates" - - info do - " Rendered collection of #{from_rails_root(identifier)}" \ - " #{render_count(event.payload)} (#{event.duration.round(1)}ms)" - end - end - - def start(name, id, payload) - if name == "render_template.action_view" - log_rendering_start(payload) - end - - super - end - - def logger - ActionView::Base.logger - end - - private - - EMPTY = "" - def from_rails_root(string) # :doc: - string = string.sub(rails_root, EMPTY) - string.sub!(VIEWS_PATTERN, EMPTY) - string - end - - def rails_root # :doc: - @root ||= "#{Rails.root}/" - end - - def render_count(payload) # :doc: - if payload[:cache_hits] - "[#{payload[:cache_hits]} / #{payload[:count]} cache hits]" - else - "[#{payload[:count]} times]" - end - end - - def cache_message(payload) # :doc: - case payload[:cache_hit] - when :hit - "[cache hit]" - when :miss - "[cache miss]" - end - end - - def log_rendering_start(payload) - info do - message = " Rendering #{from_rails_root(payload[:identifier])}" - message << " within #{from_rails_root(payload[:layout])}" if payload[:layout] - message - end - end - end -end - -ActionView::LogSubscriber.attach_to :action_view diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/lookup_context.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/lookup_context.rb deleted file mode 100644 index f385a7cd04..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/lookup_context.rb +++ /dev/null @@ -1,274 +0,0 @@ -require "concurrent/map" -require "active_support/core_ext/module/remove_method" -require "active_support/core_ext/module/attribute_accessors" -require "action_view/template/resolver" - -module ActionView - # = Action View Lookup Context - # - # LookupContext is the object responsible for holding all information - # required for looking up templates, i.e. view paths and details. - # LookupContext is also responsible for generating a key, given to - # view paths, used in the resolver cache lookup. Since this key is generated - # only once during the request, it speeds up all cache accesses. - class LookupContext #:nodoc: - attr_accessor :prefixes, :rendered_format - - mattr_accessor :fallbacks - @@fallbacks = FallbackFileSystemResolver.instances - - mattr_accessor :registered_details - self.registered_details = [] - - def self.register_detail(name, &block) - registered_details << name - Accessors::DEFAULT_PROCS[name] = block - - Accessors.send :define_method, :"default_#{name}", &block - Accessors.module_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{name} - @details.fetch(:#{name}, []) - end - - def #{name}=(value) - value = value.present? ? Array(value) : default_#{name} - _set_detail(:#{name}, value) if value != @details[:#{name}] - end - METHOD - end - - # Holds accessors for the registered details. - module Accessors #:nodoc: - DEFAULT_PROCS = {} - end - - register_detail(:locale) do - locales = [I18n.locale] - locales.concat(I18n.fallbacks[I18n.locale]) if I18n.respond_to? :fallbacks - locales << I18n.default_locale - locales.uniq! - locales - end - register_detail(:formats) { ActionView::Base.default_formats || [:html, :text, :js, :css, :xml, :json] } - register_detail(:variants) { [] } - register_detail(:handlers) { Template::Handlers.extensions } - - class DetailsKey #:nodoc: - alias :eql? :equal? - - @details_keys = Concurrent::Map.new - - def self.get(details) - if details[:formats] - details = details.dup - details[:formats] &= Template::Types.symbols - end - @details_keys[details] ||= Concurrent::Map.new - end - - def self.clear - @details_keys.clear - end - - def self.digest_caches - @details_keys.values - end - end - - # Add caching behavior on top of Details. - module DetailsCache - attr_accessor :cache - - # Calculate the details key. Remove the handlers from calculation to improve performance - # since the user cannot modify it explicitly. - def details_key #:nodoc: - @details_key ||= DetailsKey.get(@details) if @cache - end - - # Temporary skip passing the details_key forward. - def disable_cache - old_value, @cache = @cache, false - yield - ensure - @cache = old_value - end - - private - - def _set_detail(key, value) # :doc: - @details = @details.dup if @details_key - @details_key = nil - @details[key] = value - end - end - - # Helpers related to template lookup using the lookup context information. - module ViewPaths - attr_reader :view_paths, :html_fallback_for_js - - # Whenever setting view paths, makes a copy so that we can manipulate them in - # instance objects as we wish. - def view_paths=(paths) - @view_paths = ActionView::PathSet.new(Array(paths)) - end - - def find(name, prefixes = [], partial = false, keys = [], options = {}) - @view_paths.find(*args_for_lookup(name, prefixes, partial, keys, options)) - end - alias :find_template :find - - def find_file(name, prefixes = [], partial = false, keys = [], options = {}) - @view_paths.find_file(*args_for_lookup(name, prefixes, partial, keys, options)) - end - - def find_all(name, prefixes = [], partial = false, keys = [], options = {}) - @view_paths.find_all(*args_for_lookup(name, prefixes, partial, keys, options)) - end - - def exists?(name, prefixes = [], partial = false, keys = [], **options) - @view_paths.exists?(*args_for_lookup(name, prefixes, partial, keys, options)) - end - alias :template_exists? :exists? - - def any?(name, prefixes = [], partial = false) - @view_paths.exists?(*args_for_any(name, prefixes, partial)) - end - alias :any_templates? :any? - - # Adds fallbacks to the view paths. Useful in cases when you are rendering - # a :file. - def with_fallbacks - added_resolvers = 0 - self.class.fallbacks.each do |resolver| - next if view_paths.include?(resolver) - view_paths.push(resolver) - added_resolvers += 1 - end - yield - ensure - added_resolvers.times { view_paths.pop } - end - - private - - def args_for_lookup(name, prefixes, partial, keys, details_options) - name, prefixes = normalize_name(name, prefixes) - details, details_key = detail_args_for(details_options) - [name, prefixes, partial || false, details, details_key, keys] - end - - # Compute details hash and key according to user options (e.g. passed from #render). - def detail_args_for(options) # :doc: - return @details, details_key if options.empty? # most common path. - user_details = @details.merge(options) - - if @cache - details_key = DetailsKey.get(user_details) - else - details_key = nil - end - - [user_details, details_key] - end - - def args_for_any(name, prefixes, partial) - name, prefixes = normalize_name(name, prefixes) - details, details_key = detail_args_for_any - [name, prefixes, partial || false, details, details_key] - end - - def detail_args_for_any - @detail_args_for_any ||= begin - details = {} - - registered_details.each do |k| - if k == :variants - details[k] = :any - else - details[k] = Accessors::DEFAULT_PROCS[k].call - end - end - - if @cache - [details, DetailsKey.get(details)] - else - [details, nil] - end - end - end - - # Support legacy foo.erb names even though we now ignore .erb - # as well as incorrectly putting part of the path in the template - # name instead of the prefix. - def normalize_name(name, prefixes) - prefixes = prefixes.presence - parts = name.to_s.split("/".freeze) - parts.shift if parts.first.empty? - name = parts.pop - - return name, prefixes || [""] if parts.empty? - - parts = parts.join("/".freeze) - prefixes = prefixes ? prefixes.map { |p| "#{p}/#{parts}" } : [parts] - - return name, prefixes - end - end - - include Accessors - include DetailsCache - include ViewPaths - - def initialize(view_paths, details = {}, prefixes = []) - @details_key = nil - @cache = true - @prefixes = prefixes - @rendered_format = nil - - @details = initialize_details({}, details) - self.view_paths = view_paths - end - - def digest_cache - details_key - end - - def initialize_details(target, details) - registered_details.each do |k| - target[k] = details[k] || Accessors::DEFAULT_PROCS[k].call - end - target - end - private :initialize_details - - # Override formats= to expand ["*/*"] values and automatically - # add :html as fallback to :js. - def formats=(values) - if values - values.concat(default_formats) if values.delete "*/*".freeze - if values == [:js] - values << :html - @html_fallback_for_js = true - end - end - super(values) - end - - # Override locale to return a symbol instead of array. - def locale - @details[:locale].first - end - - # Overload locale= to also set the I18n.locale. If the current I18n.config object responds - # to original_config, it means that it has a copy of the original I18n configuration and it's - # acting as proxy, which we need to skip. - def locale=(value) - if value - config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config - config.locale = value - end - - super(default_locale) - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/model_naming.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/model_naming.rb deleted file mode 100644 index b6ed13424e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/model_naming.rb +++ /dev/null @@ -1,12 +0,0 @@ -module ActionView - module ModelNaming #:nodoc: - # Converts the given object to an ActiveModel compliant one. - def convert_to_model(object) - object.respond_to?(:to_model) ? object.to_model : object - end - - def model_name_from_record_or_class(record_or_class) - convert_to_model(record_or_class).model_name - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/path_set.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/path_set.rb deleted file mode 100644 index 6688519ffd..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/path_set.rb +++ /dev/null @@ -1,98 +0,0 @@ -module ActionView #:nodoc: - # = Action View PathSet - # - # This class is used to store and access paths in Action View. A number of - # operations are defined so that you can search among the paths in this - # set and also perform operations on other +PathSet+ objects. - # - # A +LookupContext+ will use a +PathSet+ to store the paths in its context. - class PathSet #:nodoc: - include Enumerable - - attr_reader :paths - - delegate :[], :include?, :pop, :size, :each, to: :paths - - def initialize(paths = []) - @paths = typecast paths - end - - def initialize_copy(other) - @paths = other.paths.dup - self - end - - def to_ary - paths.dup - end - - def compact - PathSet.new paths.compact - end - - def +(array) - PathSet.new(paths + array) - end - - %w(<< concat push insert unshift).each do |method| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{method}(*args) - paths.#{method}(*typecast(args)) - end - METHOD - end - - def find(*args) - find_all(*args).first || raise(MissingTemplate.new(self, *args)) - end - - def find_file(path, prefixes = [], *args) - _find_all(path, prefixes, args, true).first || raise(MissingTemplate.new(self, path, prefixes, *args)) - end - - def find_all(path, prefixes = [], *args) - _find_all path, prefixes, args, false - end - - def exists?(path, prefixes, *args) - find_all(path, prefixes, *args).any? - end - - def find_all_with_query(query) # :nodoc: - paths.each do |resolver| - templates = resolver.find_all_with_query(query) - return templates unless templates.empty? - end - - [] - end - - private - - def _find_all(path, prefixes, args, outside_app) - prefixes = [prefixes] if String === prefixes - prefixes.each do |prefix| - paths.each do |resolver| - if outside_app - templates = resolver.find_all_anywhere(path, prefix, *args) - else - templates = resolver.find_all(path, prefix, *args) - end - return templates unless templates.empty? - end - end - [] - end - - def typecast(paths) - paths.map do |path| - case path - when Pathname, String - OptimizedFileSystemResolver.new path.to_s - else - path - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/railtie.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/railtie.rb deleted file mode 100644 index 61678933e9..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/railtie.rb +++ /dev/null @@ -1,73 +0,0 @@ -require "action_view" -require "rails" - -module ActionView - # = Action View Railtie - class Railtie < Rails::Engine # :nodoc: - config.action_view = ActiveSupport::OrderedOptions.new - config.action_view.embed_authenticity_token_in_remote_forms = nil - config.action_view.debug_missing_translation = true - - config.eager_load_namespaces << ActionView - - initializer "action_view.embed_authenticity_token_in_remote_forms" do |app| - ActiveSupport.on_load(:action_view) do - ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = - app.config.action_view.delete(:embed_authenticity_token_in_remote_forms) - end - end - - initializer "action_view.form_with_generates_remote_forms" do |app| - ActiveSupport.on_load(:action_view) do - form_with_generates_remote_forms = app.config.action_view.delete(:form_with_generates_remote_forms) - unless form_with_generates_remote_forms.nil? - ActionView::Helpers::FormHelper.form_with_generates_remote_forms = form_with_generates_remote_forms - end - end - end - - initializer "action_view.logger" do - ActiveSupport.on_load(:action_view) { self.logger ||= Rails.logger } - end - - initializer "action_view.set_configs" do |app| - ActiveSupport.on_load(:action_view) do - app.config.action_view.each do |k, v| - send "#{k}=", v - end - end - end - - initializer "action_view.caching" do |app| - ActiveSupport.on_load(:action_view) do - if app.config.action_view.cache_template_loading.nil? - ActionView::Resolver.caching = app.config.cache_classes - end - end - end - - initializer "action_view.per_request_digest_cache" do |app| - ActiveSupport.on_load(:action_view) do - unless ActionView::Resolver.caching? - app.executor.to_run ActionView::Digestor::PerExecutionDigestCacheExpiry - end - end - end - - initializer "action_view.setup_action_pack" do |app| - ActiveSupport.on_load(:action_controller) do - ActionView::RoutingUrlFor.include(ActionDispatch::Routing::UrlFor) - end - end - - initializer "action_view.collection_caching", after: "action_controller.set_configs" do |app| - PartialRenderer.collection_cache = app.config.action_controller.cache_store - end - - rake_tasks do |app| - unless app.config.api_only - load "action_view/tasks/cache_digests.rake" - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/record_identifier.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/record_identifier.rb deleted file mode 100644 index 48bea315a9..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/record_identifier.rb +++ /dev/null @@ -1,110 +0,0 @@ -require "active_support/core_ext/module" -require "action_view/model_naming" - -module ActionView - # RecordIdentifier encapsulates methods used by various ActionView helpers - # to associate records with DOM elements. - # - # Consider for example the following code that form of post: - # - # <%= form_for(post) do |f| %> - # <%= f.text_field :body %> - # <% end %> - # - # When +post+ is a new, unsaved ActiveRecord::Base instance, the resulting HTML - # is: - # - #
    - # - #
    - # - # When +post+ is a persisted ActiveRecord::Base instance, the resulting HTML - # is: - # - #
    - # - #
    - # - # In both cases, the +id+ and +class+ of the wrapping DOM element are - # automatically generated, following naming conventions encapsulated by the - # RecordIdentifier methods #dom_id and #dom_class: - # - # dom_id(Post.new) # => "new_post" - # dom_class(Post.new) # => "post" - # dom_id(Post.find 42) # => "post_42" - # dom_class(Post.find 42) # => "post" - # - # Note that these methods do not strictly require +Post+ to be a subclass of - # ActiveRecord::Base. - # Any +Post+ class will work as long as its instances respond to +to_key+ - # and +model_name+, given that +model_name+ responds to +param_key+. - # For instance: - # - # class Post - # attr_accessor :to_key - # - # def model_name - # OpenStruct.new param_key: 'post' - # end - # - # def self.find(id) - # new.tap { |post| post.to_key = [id] } - # end - # end - module RecordIdentifier - extend self - extend ModelNaming - - include ModelNaming - - JOIN = "_".freeze - NEW = "new".freeze - - # The DOM class convention is to use the singular form of an object or class. - # - # dom_class(post) # => "post" - # dom_class(Person) # => "person" - # - # If you need to address multiple instances of the same class in the same view, you can prefix the dom_class: - # - # dom_class(post, :edit) # => "edit_post" - # dom_class(Person, :edit) # => "edit_person" - def dom_class(record_or_class, prefix = nil) - singular = model_name_from_record_or_class(record_or_class).param_key - prefix ? "#{prefix}#{JOIN}#{singular}" : singular - end - - # The DOM id convention is to use the singular form of an object or class with the id following an underscore. - # If no id is found, prefix with "new_" instead. - # - # dom_id(Post.find(45)) # => "post_45" - # dom_id(Post.new) # => "new_post" - # - # If you need to address multiple instances of the same class in the same view, you can prefix the dom_id: - # - # dom_id(Post.find(45), :edit) # => "edit_post_45" - # dom_id(Post.new, :custom) # => "custom_post" - def dom_id(record, prefix = nil) - if record_id = record_key_for_dom_id(record) - "#{dom_class(record, prefix)}#{JOIN}#{record_id}" - else - dom_class(record, prefix || NEW) - end - end - - private - - # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id. - # This can be overwritten to customize the default generated string representation if desired. - # If you need to read back a key from a dom_id in order to query for the underlying database record, - # you should write a helper like 'person_record_from_dom_id' that will extract the key either based - # on the default implementation (which just joins all key attributes with '_') or on your own - # overwritten version of the method. By default, this implementation passes the key string through a - # method that replaces all characters that are invalid inside DOM ids, with valid ones. You need to - # make sure yourself that your dom ids are valid, in case you overwrite this method. - def record_key_for_dom_id(record) # :doc: - key = convert_to_model(record).to_key - key ? key.join(JOIN) : key - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/abstract_renderer.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/abstract_renderer.rb deleted file mode 100644 index 0b315eb569..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/abstract_renderer.rb +++ /dev/null @@ -1,53 +0,0 @@ -module ActionView - # This class defines the interface for a renderer. Each class that - # subclasses +AbstractRenderer+ is used by the base +Renderer+ class to - # render a specific type of object. - # - # The base +Renderer+ class uses its +render+ method to delegate to the - # renderers. These currently consist of - # - # PartialRenderer - Used for rendering partials - # TemplateRenderer - Used for rendering other types of templates - # StreamingTemplateRenderer - Used for streaming - # - # Whenever the +render+ method is called on the base +Renderer+ class, a new - # renderer object of the correct type is created, and the +render+ method on - # that new object is called in turn. This abstracts the setup and rendering - # into a separate classes for partials and templates. - class AbstractRenderer #:nodoc: - delegate :find_template, :find_file, :template_exists?, :any_templates?, :with_fallbacks, :with_layout_format, :formats, to: :@lookup_context - - def initialize(lookup_context) - @lookup_context = lookup_context - end - - def render - raise NotImplementedError - end - - private - - def extract_details(options) # :doc: - @lookup_context.registered_details.each_with_object({}) do |key, details| - value = options[key] - - details[key] = Array(value) if value - end - end - - def instrument(name, **options) # :doc: - options[:identifier] ||= (@template && @template.identifier) || @path - - ActiveSupport::Notifications.instrument("render_#{name}.action_view", options) do |payload| - yield payload - end - end - - def prepend_formats(formats) # :doc: - formats = Array(formats) - return if formats.empty? || @lookup_context.html_fallback_for_js - - @lookup_context.formats = formats | @lookup_context.formats - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/partial_renderer.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/partial_renderer.rb deleted file mode 100644 index 1f8f997a2d..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/partial_renderer.rb +++ /dev/null @@ -1,550 +0,0 @@ -require "concurrent/map" -require "action_view/renderer/partial_renderer/collection_caching" - -module ActionView - class PartialIteration - # The number of iterations that will be done by the partial. - attr_reader :size - - # The current iteration of the partial. - attr_reader :index - - def initialize(size) - @size = size - @index = 0 - end - - # Check if this is the first iteration of the partial. - def first? - index == 0 - end - - # Check if this is the last iteration of the partial. - def last? - index == size - 1 - end - - def iterate! # :nodoc: - @index += 1 - end - end - - # = Action View Partials - # - # There's also a convenience method for rendering sub templates within the current controller that depends on a - # single object (we call this kind of sub templates for partials). It relies on the fact that partials should - # follow the naming convention of being prefixed with an underscore -- as to separate them from regular - # templates that could be rendered on their own. - # - # In a template for Advertiser#account: - # - # <%= render partial: "account" %> - # - # This would render "advertiser/_account.html.erb". - # - # In another template for Advertiser#buy, we could have: - # - # <%= render partial: "account", locals: { account: @buyer } %> - # - # <% @advertisements.each do |ad| %> - # <%= render partial: "ad", locals: { ad: ad } %> - # <% end %> - # - # This would first render "advertiser/_account.html.erb" with @buyer passed in as the local variable +account+, then - # render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. - # - # == The :as and :object options - # - # By default ActionView::PartialRenderer doesn't have any local variables. - # The :object option can be used to pass an object to the partial. For instance: - # - # <%= render partial: "account", object: @buyer %> - # - # would provide the @buyer object to the partial, available under the local variable +account+ and is - # equivalent to: - # - # <%= render partial: "account", locals: { account: @buyer } %> - # - # With the :as option we can specify a different name for said local variable. For example, if we - # wanted it to be +user+ instead of +account+ we'd do: - # - # <%= render partial: "account", object: @buyer, as: 'user' %> - # - # This is equivalent to - # - # <%= render partial: "account", locals: { user: @buyer } %> - # - # == \Rendering a collection of partials - # - # The example of partial use describes a familiar pattern where a template needs to iterate over an array and - # render a sub template for each of the elements. This pattern has been implemented as a single method that - # accepts an array and renders a partial by the same name as the elements contained within. So the three-lined - # example in "Using partials" can be rewritten with a single line: - # - # <%= render partial: "ad", collection: @advertisements %> - # - # This will render "advertiser/_ad.html.erb" and pass the local variable +ad+ to the template for display. An - # iteration object will automatically be made available to the template with a name of the form - # +partial_name_iteration+. The iteration object has knowledge about which index the current object has in - # the collection and the total size of the collection. The iteration object also has two convenience methods, - # +first?+ and +last?+. In the case of the example above, the template would be fed +ad_iteration+. - # For backwards compatibility the +partial_name_counter+ is still present and is mapped to the iteration's - # +index+ method. - # - # The :as option may be used when rendering partials. - # - # You can specify a partial to be rendered between elements via the :spacer_template option. - # The following example will render advertiser/_ad_divider.html.erb between each ad partial: - # - # <%= render partial: "ad", collection: @advertisements, spacer_template: "ad_divider" %> - # - # If the given :collection is +nil+ or empty, render will return nil. This will allow you - # to specify a text which will be displayed instead by using this form: - # - # <%= render(partial: "ad", collection: @advertisements) || "There's no ad to be displayed" %> - # - # NOTE: Due to backwards compatibility concerns, the collection can't be one of hashes. Normally you'd also - # just keep domain objects, like Active Records, in there. - # - # == \Rendering shared partials - # - # Two controllers can share a set of partials and render them like this: - # - # <%= render partial: "advertisement/ad", locals: { ad: @advertisement } %> - # - # This will render the partial "advertisement/_ad.html.erb" regardless of which controller this is being called from. - # - # == \Rendering objects that respond to `to_partial_path` - # - # Instead of explicitly naming the location of a partial, you can also let PartialRenderer do the work - # and pick the proper path by checking `to_partial_path` method. - # - # # @account.to_partial_path returns 'accounts/account', so it can be used to replace: - # # <%= render partial: "accounts/account", locals: { account: @account} %> - # <%= render partial: @account %> - # - # # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`, - # # that's why we can replace: - # # <%= render partial: "posts/post", collection: @posts %> - # <%= render partial: @posts %> - # - # == \Rendering the default case - # - # If you're not going to be using any of the options like collections or layouts, you can also use the short-hand - # defaults of render to render partials. Examples: - # - # # Instead of <%= render partial: "account" %> - # <%= render "account" %> - # - # # Instead of <%= render partial: "account", locals: { account: @buyer } %> - # <%= render "account", account: @buyer %> - # - # # @account.to_partial_path returns 'accounts/account', so it can be used to replace: - # # <%= render partial: "accounts/account", locals: { account: @account} %> - # <%= render @account %> - # - # # @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`, - # # that's why we can replace: - # # <%= render partial: "posts/post", collection: @posts %> - # <%= render @posts %> - # - # == \Rendering partials with layouts - # - # Partials can have their own layouts applied to them. These layouts are different than the ones that are - # specified globally for the entire action, but they work in a similar fashion. Imagine a list with two types - # of users: - # - # <%# app/views/users/index.html.erb %> - # Here's the administrator: - # <%= render partial: "user", layout: "administrator", locals: { user: administrator } %> - # - # Here's the editor: - # <%= render partial: "user", layout: "editor", locals: { user: editor } %> - # - # <%# app/views/users/_user.html.erb %> - # Name: <%= user.name %> - # - # <%# app/views/users/_administrator.html.erb %> - #
    - # Budget: $<%= user.budget %> - # <%= yield %> - #
    - # - # <%# app/views/users/_editor.html.erb %> - #
    - # Deadline: <%= user.deadline %> - # <%= yield %> - #
    - # - # ...this will return: - # - # Here's the administrator: - #
    - # Budget: $<%= user.budget %> - # Name: <%= user.name %> - #
    - # - # Here's the editor: - #
    - # Deadline: <%= user.deadline %> - # Name: <%= user.name %> - #
    - # - # If a collection is given, the layout will be rendered once for each item in - # the collection. For example, these two snippets have the same output: - # - # <%# app/views/users/_user.html.erb %> - # Name: <%= user.name %> - # - # <%# app/views/users/index.html.erb %> - # <%# This does not use layouts %> - #
      - # <% users.each do |user| -%> - #
    • - # <%= render partial: "user", locals: { user: user } %> - #
    • - # <% end -%> - #
    - # - # <%# app/views/users/_li_layout.html.erb %> - #
  • - # <%= yield %> - #
  • - # - # <%# app/views/users/index.html.erb %> - #
      - # <%= render partial: "user", layout: "li_layout", collection: users %> - #
    - # - # Given two users whose names are Alice and Bob, these snippets return: - # - #
      - #
    • - # Name: Alice - #
    • - #
    • - # Name: Bob - #
    • - #
    - # - # The current object being rendered, as well as the object_counter, will be - # available as local variables inside the layout template under the same names - # as available in the partial. - # - # You can also apply a layout to a block within any template: - # - # <%# app/views/users/_chief.html.erb %> - # <%= render(layout: "administrator", locals: { user: chief }) do %> - # Title: <%= chief.title %> - # <% end %> - # - # ...this will return: - # - #
    - # Budget: $<%= user.budget %> - # Title: <%= chief.name %> - #
    - # - # As you can see, the :locals hash is shared between both the partial and its layout. - # - # If you pass arguments to "yield" then this will be passed to the block. One way to use this is to pass - # an array to layout and treat it as an enumerable. - # - # <%# app/views/users/_user.html.erb %> - #
    - # Budget: $<%= user.budget %> - # <%= yield user %> - #
    - # - # <%# app/views/users/index.html.erb %> - # <%= render layout: @users do |user| %> - # Title: <%= user.title %> - # <% end %> - # - # This will render the layout for each user and yield to the block, passing the user, each time. - # - # You can also yield multiple times in one layout and use block arguments to differentiate the sections. - # - # <%# app/views/users/_user.html.erb %> - #
    - # <%= yield user, :header %> - # Budget: $<%= user.budget %> - # <%= yield user, :footer %> - #
    - # - # <%# app/views/users/index.html.erb %> - # <%= render layout: @users do |user, section| %> - # <%- case section when :header -%> - # Title: <%= user.title %> - # <%- when :footer -%> - # Deadline: <%= user.deadline %> - # <%- end -%> - # <% end %> - class PartialRenderer < AbstractRenderer - include CollectionCaching - - PREFIXED_PARTIAL_NAMES = Concurrent::Map.new do |h, k| - h[k] = Concurrent::Map.new - end - - def initialize(*) - super - @context_prefix = @lookup_context.prefixes.first - end - - def render(context, options, block) - setup(context, options, block) - @template = find_partial - - @lookup_context.rendered_format ||= begin - if @template && @template.formats.present? - @template.formats.first - else - formats.first - end - end - - if @collection - render_collection - else - render_partial - end - end - - private - - def render_collection - instrument(:collection, count: @collection.size) do |payload| - return nil if @collection.blank? - - if @options.key?(:spacer_template) - spacer = find_template(@options[:spacer_template], @locals.keys).render(@view, @locals) - end - - cache_collection_render(payload) do - @template ? collection_with_template : collection_without_template - end.join(spacer).html_safe - end - end - - def render_partial - instrument(:partial) do |payload| - view, locals, block = @view, @locals, @block - object, as = @object, @variable - - if !block && (layout = @options[:layout]) - layout = find_template(layout.to_s, @template_keys) - end - - object = locals[as] if object.nil? # Respect object when object is false - locals[as] = object if @has_object - - content = @template.render(view, locals) do |*name| - view._layout_for(*name, &block) - end - - content = layout.render(view, locals) { content } if layout - payload[:cache_hit] = view.view_renderer.cache_hits[@template.virtual_path] - content - end - end - - # Sets up instance variables needed for rendering a partial. This method - # finds the options and details and extracts them. The method also contains - # logic that handles the type of object passed in as the partial. - # - # If +options[:partial]+ is a string, then the +@path+ instance variable is - # set to that string. Otherwise, the +options[:partial]+ object must - # respond to +to_partial_path+ in order to setup the path. - def setup(context, options, block) - @view = context - @options = options - @block = block - - @locals = options[:locals] || {} - @details = extract_details(options) - - prepend_formats(options[:formats]) - - partial = options[:partial] - - if String === partial - @has_object = options.key?(:object) - @object = options[:object] - @collection = collection_from_options - @path = partial - else - @has_object = true - @object = partial - @collection = collection_from_object || collection_from_options - - if @collection - paths = @collection_data = @collection.map { |o| partial_path(o) } - @path = paths.uniq.one? ? paths.first : nil - else - @path = partial_path - end - end - - if as = options[:as] - raise_invalid_option_as(as) unless /\A[a-z_]\w*\z/.match?(as.to_s) - as = as.to_sym - end - - if @path - @variable, @variable_counter, @variable_iteration = retrieve_variable(@path, as) - @template_keys = retrieve_template_keys - else - paths.map! { |path| retrieve_variable(path, as).unshift(path) } - end - - self - end - - def collection_from_options - if @options.key?(:collection) - collection = @options[:collection] - collection ? collection.to_a : [] - end - end - - def collection_from_object - @object.to_ary if @object.respond_to?(:to_ary) - end - - def find_partial - find_template(@path, @template_keys) if @path - end - - def find_template(path, locals) - prefixes = path.include?(?/) ? [] : @lookup_context.prefixes - @lookup_context.find_template(path, prefixes, true, locals, @details) - end - - def collection_with_template - view, locals, template = @view, @locals, @template - as, counter, iteration = @variable, @variable_counter, @variable_iteration - - if layout = @options[:layout] - layout = find_template(layout, @template_keys) - end - - partial_iteration = PartialIteration.new(@collection.size) - locals[iteration] = partial_iteration - - @collection.map do |object| - locals[as] = object - locals[counter] = partial_iteration.index - - content = template.render(view, locals) - content = layout.render(view, locals) { content } if layout - partial_iteration.iterate! - content - end - end - - def collection_without_template - view, locals, collection_data = @view, @locals, @collection_data - cache = {} - keys = @locals.keys - - partial_iteration = PartialIteration.new(@collection.size) - - @collection.map do |object| - index = partial_iteration.index - path, as, counter, iteration = collection_data[index] - - locals[as] = object - locals[counter] = index - locals[iteration] = partial_iteration - - template = (cache[path] ||= find_template(path, keys + [as, counter, iteration])) - content = template.render(view, locals) - partial_iteration.iterate! - content - end - end - - # Obtains the path to where the object's partial is located. If the object - # responds to +to_partial_path+, then +to_partial_path+ will be called and - # will provide the path. If the object does not respond to +to_partial_path+, - # then an +ArgumentError+ is raised. - # - # If +prefix_partial_path_with_controller_namespace+ is true, then this - # method will prefix the partial paths with a namespace. - def partial_path(object = @object) - object = object.to_model if object.respond_to?(:to_model) - - path = if object.respond_to?(:to_partial_path) - object.to_partial_path - else - raise ArgumentError.new("'#{object.inspect}' is not an ActiveModel-compatible object. It must implement :to_partial_path.") - end - - if @view.prefix_partial_path_with_controller_namespace - prefixed_partial_names[path] ||= merge_prefix_into_object_path(@context_prefix, path.dup) - else - path - end - end - - def prefixed_partial_names - @prefixed_partial_names ||= PREFIXED_PARTIAL_NAMES[@context_prefix] - end - - def merge_prefix_into_object_path(prefix, object_path) - if prefix.include?(?/) && object_path.include?(?/) - prefixes = [] - prefix_array = File.dirname(prefix).split("/") - object_path_array = object_path.split("/")[0..-3] # skip model dir & partial - - prefix_array.each_with_index do |dir, index| - break if dir == object_path_array[index] - prefixes << dir - end - - (prefixes << object_path).join("/") - else - object_path - end - end - - def retrieve_template_keys - keys = @locals.keys - keys << @variable if @has_object || @collection - if @collection - keys << @variable_counter - keys << @variable_iteration - end - keys - end - - def retrieve_variable(path, as) - variable = as || begin - base = path[-1] == "/".freeze ? "".freeze : File.basename(path) - raise_invalid_identifier(path) unless base =~ /\A_?(.*?)(?:\.\w+)*\z/ - $1.to_sym - end - if @collection - variable_counter = :"#{variable}_counter" - variable_iteration = :"#{variable}_iteration" - end - [variable, variable_counter, variable_iteration] - end - - IDENTIFIER_ERROR_MESSAGE = "The partial name (%s) is not a valid Ruby identifier; " \ - "make sure your partial name starts with underscore." - - OPTION_AS_ERROR_MESSAGE = "The value (%s) of the option `as` is not a valid Ruby identifier; " \ - "make sure it starts with lowercase letter, " \ - "and is followed by any combination of letters, numbers and underscores." - - def raise_invalid_identifier(path) - raise ArgumentError.new(IDENTIFIER_ERROR_MESSAGE % (path)) - end - - def raise_invalid_option_as(as) - raise ArgumentError.new(OPTION_AS_ERROR_MESSAGE % (as)) - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/partial_renderer/collection_caching.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/partial_renderer/collection_caching.rb deleted file mode 100644 index 1fbe209200..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/partial_renderer/collection_caching.rb +++ /dev/null @@ -1,55 +0,0 @@ -module ActionView - module CollectionCaching # :nodoc: - extend ActiveSupport::Concern - - included do - # Fallback cache store if Action View is used without Rails. - # Otherwise overridden in Railtie to use Rails.cache. - mattr_accessor(:collection_cache) { ActiveSupport::Cache::MemoryStore.new } - end - - private - def cache_collection_render(instrumentation_payload) - return yield unless @options[:cached] - - keyed_collection = collection_by_cache_keys - cached_partials = collection_cache.read_multi(*keyed_collection.keys) - instrumentation_payload[:cache_hits] = cached_partials.size - - @collection = keyed_collection.reject { |key, _| cached_partials.key?(key) }.values - rendered_partials = @collection.empty? ? [] : yield - - index = 0 - fetch_or_cache_partial(cached_partials, order_by: keyed_collection.each_key) do - rendered_partials[index].tap { index += 1 } - end - end - - def callable_cache_key? - @options[:cached].respond_to?(:call) - end - - def collection_by_cache_keys - seed = callable_cache_key? ? @options[:cached] : ->(i) { i } - - @collection.each_with_object({}) do |item, hash| - hash[expanded_cache_key(seed.call(item))] = item - end - end - - def expanded_cache_key(key) - key = @view.fragment_cache_key(@view.cache_fragment_name(key, virtual_path: @template.virtual_path)) - key.frozen? ? key.dup : key # #read_multi & #write may require mutability, Dalli 2.6.0. - end - - def fetch_or_cache_partial(cached_partials, order_by:) - order_by.map do |cache_key| - cached_partials.fetch(cache_key) do - yield.tap do |rendered_partial| - collection_cache.write(cache_key, rendered_partial) - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/renderer.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/renderer.rb deleted file mode 100644 index bcdeb85d30..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/renderer.rb +++ /dev/null @@ -1,54 +0,0 @@ -module ActionView - # This is the main entry point for rendering. It basically delegates - # to other objects like TemplateRenderer and PartialRenderer which - # actually renders the template. - # - # The Renderer will parse the options from the +render+ or +render_body+ - # method and render a partial or a template based on the options. The - # +TemplateRenderer+ and +PartialRenderer+ objects are wrappers which do all - # the setup and logic necessary to render a view and a new object is created - # each time +render+ is called. - class Renderer - attr_accessor :lookup_context - - def initialize(lookup_context) - @lookup_context = lookup_context - end - - # Main render entry point shared by Action View and Action Controller. - def render(context, options) - if options.key?(:partial) - render_partial(context, options) - else - render_template(context, options) - end - end - - # Render but returns a valid Rack body. If fibers are defined, we return - # a streaming body that renders the template piece by piece. - # - # Note that partials are not supported to be rendered with streaming, - # so in such cases, we just wrap them in an array. - def render_body(context, options) - if options.key?(:partial) - [render_partial(context, options)] - else - StreamingTemplateRenderer.new(@lookup_context).render(context, options) - end - end - - # Direct access to template rendering. - def render_template(context, options) #:nodoc: - TemplateRenderer.new(@lookup_context).render(context, options) - end - - # Direct access to partial rendering. - def render_partial(context, options, &block) #:nodoc: - PartialRenderer.new(@lookup_context).render(context, options, block) - end - - def cache_hits # :nodoc: - @cache_hits ||= {} - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/streaming_template_renderer.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/streaming_template_renderer.rb deleted file mode 100644 index 62ce985243..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/streaming_template_renderer.rb +++ /dev/null @@ -1,101 +0,0 @@ -require "fiber" - -module ActionView - # == TODO - # - # * Support streaming from child templates, partials and so on. - # * Rack::Cache needs to support streaming bodies - class StreamingTemplateRenderer < TemplateRenderer #:nodoc: - # A valid Rack::Body (i.e. it responds to each). - # It is initialized with a block that, when called, starts - # rendering the template. - class Body #:nodoc: - def initialize(&start) - @start = start - end - - def each(&block) - begin - @start.call(block) - rescue Exception => exception - log_error(exception) - block.call ActionView::Base.streaming_completion_on_exception - end - self - end - - private - - # This is the same logging logic as in ShowExceptions middleware. - def log_error(exception) - logger = ActionView::Base.logger - return unless logger - - message = "\n#{exception.class} (#{exception.message}):\n" - message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code) - message << " " << exception.backtrace.join("\n ") - logger.fatal("#{message}\n\n") - end - end - - # For streaming, instead of rendering a given a template, we return a Body - # object that responds to each. This object is initialized with a block - # that knows how to render the template. - def render_template(template, layout_name = nil, locals = {}) #:nodoc: - return [super] unless layout_name && template.supports_streaming? - - locals ||= {} - layout = layout_name && find_layout(layout_name, locals.keys, [formats.first]) - - Body.new do |buffer| - delayed_render(buffer, template, layout, @view, locals) - end - end - - private - - def delayed_render(buffer, template, layout, view, locals) - # Wrap the given buffer in the StreamingBuffer and pass it to the - # underlying template handler. Now, every time something is concatenated - # to the buffer, it is not appended to an array, but streamed straight - # to the client. - output = ActionView::StreamingBuffer.new(buffer) - yielder = lambda { |*name| view._layout_for(*name) } - - instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do - fiber = Fiber.new do - if layout - layout.render(view, locals, output, &yielder) - else - # If you don't have a layout, just render the thing - # and concatenate the final result. This is the same - # as a layout with just <%= yield %> - output.safe_concat view._layout_for - end - end - - # Set the view flow to support streaming. It will be aware - # when to stop rendering the layout because it needs to search - # something in the template and vice-versa. - view.view_flow = StreamingFlow.new(view, fiber) - - # Yo! Start the fiber! - fiber.resume - - # If the fiber is still alive, it means we need something - # from the template, so start rendering it. If not, it means - # the layout exited without requiring anything from the template. - if fiber.alive? - content = template.render(view, locals, &yielder) - - # Once rendering the template is done, sets its content in the :layout key. - view.view_flow.set(:layout, content) - - # In case the layout continues yielding, we need to resume - # the fiber until all yields are handled. - fiber.resume while fiber.alive? - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/template_renderer.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/template_renderer.rb deleted file mode 100644 index 54317199de..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/renderer/template_renderer.rb +++ /dev/null @@ -1,100 +0,0 @@ -require "active_support/core_ext/object/try" - -module ActionView - class TemplateRenderer < AbstractRenderer #:nodoc: - def render(context, options) - @view = context - @details = extract_details(options) - template = determine_template(options) - - prepend_formats(template.formats) - - @lookup_context.rendered_format ||= (template.formats.first || formats.first) - - render_template(template, options[:layout], options[:locals]) - end - - private - - # Determine the template to be rendered using the given options. - def determine_template(options) - keys = options.has_key?(:locals) ? options[:locals].keys : [] - - if options.key?(:body) - Template::Text.new(options[:body]) - elsif options.key?(:plain) - Template::Text.new(options[:plain]) - elsif options.key?(:html) - Template::HTML.new(options[:html], formats.first) - elsif options.key?(:file) - with_fallbacks { find_file(options[:file], nil, false, keys, @details) } - elsif options.key?(:inline) - handler = Template.handler_for_extension(options[:type] || "erb") - Template.new(options[:inline], "inline template", handler, locals: keys) - elsif options.key?(:template) - if options[:template].respond_to?(:render) - options[:template] - else - find_template(options[:template], options[:prefixes], false, keys, @details) - end - else - raise ArgumentError, "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :html or :body option." - end - end - - # Renders the given template. A string representing the layout can be - # supplied as well. - def render_template(template, layout_name = nil, locals = nil) - view, locals = @view, locals || {} - - render_with_layout(layout_name, locals) do |layout| - instrument(:template, identifier: template.identifier, layout: layout.try(:virtual_path)) do - template.render(view, locals) { |*name| view._layout_for(*name) } - end - end - end - - def render_with_layout(path, locals) - layout = path && find_layout(path, locals.keys, [formats.first]) - content = yield(layout) - - if layout - view = @view - view.view_flow.set(:layout, content) - layout.render(view, locals) { |*name| view._layout_for(*name) } - else - content - end - end - - # This is the method which actually finds the layout using details in the lookup - # context object. If no layout is found, it checks if at least a layout with - # the given name exists across all details before raising the error. - def find_layout(layout, keys, formats) - resolve_layout(layout, keys, formats) - end - - def resolve_layout(layout, keys, formats) - details = @details.dup - details[:formats] = formats - - case layout - when String - begin - if layout.start_with?("/") - with_fallbacks { find_template(layout, nil, false, [], details) } - else - find_template(layout, nil, false, [], details) - end - rescue ActionView::MissingTemplate - all_details = @details.merge(formats: @lookup_context.default_formats) - raise unless template_exists?(layout, nil, false, [], all_details) - end - when Proc - resolve_layout(layout.call(formats), keys, formats) - else - layout - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/rendering.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/rendering.rb deleted file mode 100644 index cf18562c45..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/rendering.rb +++ /dev/null @@ -1,153 +0,0 @@ -require "action_view/view_paths" - -module ActionView - # This is a class to fix I18n global state. Whenever you provide I18n.locale during a request, - # it will trigger the lookup_context and consequently expire the cache. - class I18nProxy < ::I18n::Config #:nodoc: - attr_reader :original_config, :lookup_context - - def initialize(original_config, lookup_context) - original_config = original_config.original_config if original_config.respond_to?(:original_config) - @original_config, @lookup_context = original_config, lookup_context - end - - def locale - @original_config.locale - end - - def locale=(value) - @lookup_context.locale = value - end - end - - module Rendering - extend ActiveSupport::Concern - include ActionView::ViewPaths - - # Overwrite process to setup I18n proxy. - def process(*) #:nodoc: - old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context) - super - ensure - I18n.config = old_config - end - - module ClassMethods - def view_context_class - @view_context_class ||= begin - supports_path = supports_path? - routes = respond_to?(:_routes) && _routes - helpers = respond_to?(:_helpers) && _helpers - - Class.new(ActionView::Base) do - if routes - include routes.url_helpers(supports_path) - include routes.mounted_helpers - end - - if helpers - include helpers - end - end - end - end - end - - attr_internal_writer :view_context_class - - def view_context_class - @_view_context_class ||= self.class.view_context_class - end - - # An instance of a view class. The default view class is ActionView::Base. - # - # The view class must have the following methods: - # View.new[lookup_context, assigns, controller] - # Create a new ActionView instance for a controller and we can also pass the arguments. - # View#render(option) - # Returns String with the rendered template - # - # Override this method in a module to change the default behavior. - def view_context - view_context_class.new(view_renderer, view_assigns, self) - end - - # Returns an object that is able to render templates. - # :api: private - def view_renderer - @_view_renderer ||= ActionView::Renderer.new(lookup_context) - end - - def render_to_body(options = {}) - _process_options(options) - _render_template(options) - end - - def rendered_format - Template::Types[lookup_context.rendered_format] - end - - private - - # Find and render a template based on the options given. - # :api: private - def _render_template(options) - variant = options.delete(:variant) - assigns = options.delete(:assigns) - context = view_context - - context.assign assigns if assigns - lookup_context.rendered_format = nil if options[:formats] - lookup_context.variants = variant if variant - - view_renderer.render(context, options) - end - - # Assign the rendered format to look up context. - def _process_format(format) - super - lookup_context.formats = [format.to_sym] - lookup_context.rendered_format = lookup_context.formats.first - end - - # Normalize args by converting render "foo" to render :action => "foo" and - # render "foo/bar" to render :template => "foo/bar". - # :api: private - def _normalize_args(action = nil, options = {}) - options = super(action, options) - case action - when NilClass - when Hash - options = action - when String, Symbol - action = action.to_s - key = action.include?(?/) ? :template : :action - options[key] = action - else - if action.respond_to?(:permitted?) && action.permitted? - options = action - else - options[:partial] = action - end - end - - options - end - - # Normalize options. - # :api: private - def _normalize_options(options) - options = super(options) - if options[:partial] == true - options[:partial] = action_name - end - - if (options.keys & [:partial, :file, :template]).empty? - options[:prefixes] ||= _prefixes - end - - options[:template] ||= (options[:action] || action_name).to_s - options - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/routing_url_for.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/routing_url_for.rb deleted file mode 100644 index 687ba7c1b4..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/routing_url_for.rb +++ /dev/null @@ -1,143 +0,0 @@ -require "action_dispatch/routing/polymorphic_routes" - -module ActionView - module RoutingUrlFor - # Returns the URL for the set of +options+ provided. This takes the - # same options as +url_for+ in Action Controller (see the - # documentation for ActionController::Base#url_for). Note that by default - # :only_path is true so you'll get the relative "/controller/action" - # instead of the fully qualified URL like "http://example.com/controller/action". - # - # ==== Options - # * :anchor - Specifies the anchor name to be appended to the path. - # * :only_path - If true, returns the relative URL (omitting the protocol, host name, and port) (true by default unless :host is specified). - # * :trailing_slash - If true, adds a trailing slash, as in "/archive/2005/". Note that this - # is currently not recommended since it breaks caching. - # * :host - Overrides the default (current) host if provided. - # * :protocol - Overrides the default (current) protocol if provided. - # * :user - Inline HTTP authentication (only plucked out if :password is also present). - # * :password - Inline HTTP authentication (only plucked out if :user is also present). - # - # ==== Relying on named routes - # - # Passing a record (like an Active Record) instead of a hash as the options parameter will - # trigger the named route for that record. The lookup will happen on the name of the class. So passing a - # Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as - # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route). - # - # ==== Implicit Controller Namespacing - # - # Controllers passed in using the +:controller+ option will retain their namespace unless it is an absolute one. - # - # ==== Examples - # <%= url_for(action: 'index') %> - # # => /blogs/ - # - # <%= url_for(action: 'find', controller: 'books') %> - # # => /books/find - # - # <%= url_for(action: 'login', controller: 'members', only_path: false, protocol: 'https') %> - # # => https://www.example.com/members/login/ - # - # <%= url_for(action: 'play', anchor: 'player') %> - # # => /messages/play/#player - # - # <%= url_for(action: 'jump', anchor: 'tax&ship') %> - # # => /testing/jump/#tax&ship - # - # <%= url_for(Workshop.new) %> - # # relies on Workshop answering a persisted? call (and in this case returning false) - # # => /workshops - # - # <%= url_for(@workshop) %> - # # calls @workshop.to_param which by default returns the id - # # => /workshops/5 - # - # # to_param can be re-defined in a model to provide different URL names: - # # => /workshops/1-workshop-name - # - # <%= url_for("http://www.example.com") %> - # # => http://www.example.com - # - # <%= url_for(:back) %> - # # if request.env["HTTP_REFERER"] is set to "http://www.example.com" - # # => http://www.example.com - # - # <%= url_for(:back) %> - # # if request.env["HTTP_REFERER"] is not set or is blank - # # => javascript:history.back() - # - # <%= url_for(action: 'index', controller: 'users') %> - # # Assuming an "admin" namespace - # # => /admin/users - # - # <%= url_for(action: 'index', controller: '/users') %> - # # Specify absolute path with beginning slash - # # => /users - def url_for(options = nil) - case options - when String - options - when nil - super(only_path: _generate_paths_by_default) - when Hash - options = options.symbolize_keys - unless options.key?(:only_path) - options[:only_path] = only_path?(options[:host]) - end - - super(options) - when ActionController::Parameters - unless options.key?(:only_path) - options[:only_path] = only_path?(options[:host]) - end - - super(options) - when :back - _back_url - when Array - components = options.dup - if _generate_paths_by_default - polymorphic_path(components, components.extract_options!) - else - polymorphic_url(components, components.extract_options!) - end - else - method = _generate_paths_by_default ? :path : :url - builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(method) - - case options - when Symbol - builder.handle_string_call(self, options) - when Class - builder.handle_class_call(self, options) - else - builder.handle_model_call(self, options) - end - end - end - - def url_options #:nodoc: - return super unless controller.respond_to?(:url_options) - controller.url_options - end - - private - def _routes_context - controller - end - - def optimize_routes_generation? - controller.respond_to?(:optimize_routes_generation?, true) ? - controller.optimize_routes_generation? : super - end - - def _generate_paths_by_default - true - end - - def only_path?(host) - _generate_paths_by_default unless host - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/tasks/cache_digests.rake b/debian/gems-compat/actionview-5.1.7/lib/action_view/tasks/cache_digests.rake deleted file mode 100644 index d30b3f7797..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/tasks/cache_digests.rake +++ /dev/null @@ -1,23 +0,0 @@ -namespace :cache_digests do - desc "Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)" - task nested_dependencies: :environment do - abort "You must provide TEMPLATE for the task to run" unless ENV["TEMPLATE"].present? - puts JSON.pretty_generate ActionView::Digestor.tree(CacheDigests.template_name, CacheDigests.finder).children.map(&:to_dep_map) - end - - desc "Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_comment.html)" - task dependencies: :environment do - abort "You must provide TEMPLATE for the task to run" unless ENV["TEMPLATE"].present? - puts JSON.pretty_generate ActionView::Digestor.tree(CacheDigests.template_name, CacheDigests.finder).children.map(&:name) - end - - class CacheDigests - def self.template_name - ENV["TEMPLATE"].split(".", 2).first - end - - def self.finder - ApplicationController.new.lookup_context - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template.rb deleted file mode 100644 index b0e2f1e54e..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template.rb +++ /dev/null @@ -1,359 +0,0 @@ -require "active_support/core_ext/object/try" -require "active_support/core_ext/kernel/singleton_class" -require "thread" - -module ActionView - # = Action View Template - class Template - extend ActiveSupport::Autoload - - # === Encodings in ActionView::Template - # - # ActionView::Template is one of a few sources of potential - # encoding issues in Rails. This is because the source for - # templates are usually read from disk, and Ruby (like most - # encoding-aware programming languages) assumes that the - # String retrieved through File IO is encoded in the - # default_external encoding. In Rails, the default - # default_external encoding is UTF-8. - # - # As a result, if a user saves their template as ISO-8859-1 - # (for instance, using a non-Unicode-aware text editor), - # and uses characters outside of the ASCII range, their - # users will see diamonds with question marks in them in - # the browser. - # - # For the rest of this documentation, when we say "UTF-8", - # we mean "UTF-8 or whatever the default_internal encoding - # is set to". By default, it will be UTF-8. - # - # To mitigate this problem, we use a few strategies: - # 1. If the source is not valid UTF-8, we raise an exception - # when the template is compiled to alert the user - # to the problem. - # 2. The user can specify the encoding using Ruby-style - # encoding comments in any template engine. If such - # a comment is supplied, Rails will apply that encoding - # to the resulting compiled source returned by the - # template handler. - # 3. In all cases, we transcode the resulting String to - # the UTF-8. - # - # This means that other parts of Rails can always assume - # that templates are encoded in UTF-8, even if the original - # source of the template was not UTF-8. - # - # From a user's perspective, the easiest thing to do is - # to save your templates as UTF-8. If you do this, you - # do not need to do anything else for things to "just work". - # - # === Instructions for template handlers - # - # The easiest thing for you to do is to simply ignore - # encodings. Rails will hand you the template source - # as the default_internal (generally UTF-8), raising - # an exception for the user before sending the template - # to you if it could not determine the original encoding. - # - # For the greatest simplicity, you can support only - # UTF-8 as the default_internal. This means - # that from the perspective of your handler, the - # entire pipeline is just UTF-8. - # - # === Advanced: Handlers with alternate metadata sources - # - # If you want to provide an alternate mechanism for - # specifying encodings (like ERB does via <%# encoding: ... %>), - # you may indicate that you will handle encodings yourself - # by implementing handles_encoding? on your handler. - # - # If you do, Rails will not try to encode the String - # into the default_internal, passing you the unaltered - # bytes tagged with the assumed encoding (from - # default_external). - # - # In this case, make sure you return a String from - # your handler encoded in the default_internal. Since - # you are handling out-of-band metadata, you are - # also responsible for alerting the user to any - # problems with converting the user's data to - # the default_internal. - # - # To do so, simply raise +WrongEncodingError+ as follows: - # - # raise WrongEncodingError.new( - # problematic_string, - # expected_encoding - # ) - - ## - # :method: local_assigns - # - # Returns a hash with the defined local variables. - # - # Given this sub template rendering: - # - # <%= render "shared/header", { headline: "Welcome", person: person } %> - # - # You can use +local_assigns+ in the sub templates to access the local variables: - # - # local_assigns[:headline] # => "Welcome" - - eager_autoload do - autoload :Error - autoload :Handlers - autoload :HTML - autoload :Text - autoload :Types - end - - extend Template::Handlers - - attr_accessor :locals, :formats, :variants, :virtual_path - - attr_reader :source, :identifier, :handler, :original_encoding, :updated_at - - # This finalizer is needed (and exactly with a proc inside another proc) - # otherwise templates leak in development. - Finalizer = proc do |method_name, mod| # :nodoc: - proc do - mod.module_eval do - remove_possible_method method_name - end - end - end - - def initialize(source, identifier, handler, details) - format = details[:format] || (handler.default_format if handler.respond_to?(:default_format)) - - @source = source - @identifier = identifier - @handler = handler - @compiled = false - @original_encoding = nil - @locals = details[:locals] || [] - @virtual_path = details[:virtual_path] - @updated_at = details[:updated_at] || Time.now - @formats = Array(format).map { |f| f.respond_to?(:ref) ? f.ref : f } - @variants = [details[:variant]] - @compile_mutex = Mutex.new - end - - # Returns whether the underlying handler supports streaming. If so, - # a streaming buffer *may* be passed when it starts rendering. - def supports_streaming? - handler.respond_to?(:supports_streaming?) && handler.supports_streaming? - end - - # Render a template. If the template was not compiled yet, it is done - # exactly before rendering. - # - # This method is instrumented as "!render_template.action_view". Notice that - # we use a bang in this instrumentation because you don't want to - # consume this in production. This is only slow if it's being listened to. - def render(view, locals, buffer = nil, &block) - instrument_render_template do - compile!(view) - view.send(method_name, locals, buffer, &block) - end - rescue => e - handle_render_error(view, e) - end - - def type - @type ||= Types[@formats.first] if @formats.first - end - - # Receives a view object and return a template similar to self by using @virtual_path. - # - # This method is useful if you have a template object but it does not contain its source - # anymore since it was already compiled. In such cases, all you need to do is to call - # refresh passing in the view object. - # - # Notice this method raises an error if the template to be refreshed does not have a - # virtual path set (true just for inline templates). - def refresh(view) - raise "A template needs to have a virtual path in order to be refreshed" unless @virtual_path - lookup = view.lookup_context - pieces = @virtual_path.split("/") - name = pieces.pop - partial = !!name.sub!(/^_/, "") - lookup.disable_cache do - lookup.find_template(name, [ pieces.join("/") ], partial, @locals) - end - end - - def inspect - @inspect ||= defined?(Rails.root) ? identifier.sub("#{Rails.root}/", "".freeze) : identifier - end - - # This method is responsible for properly setting the encoding of the - # source. Until this point, we assume that the source is BINARY data. - # If no additional information is supplied, we assume the encoding is - # the same as Encoding.default_external. - # - # The user can also specify the encoding via a comment on the first - # line of the template (# encoding: NAME-OF-ENCODING). This will work - # with any template engine, as we process out the encoding comment - # before passing the source on to the template engine, leaving a - # blank line in its stead. - def encode! - return unless source.encoding == Encoding::BINARY - - # Look for # encoding: *. If we find one, we'll encode the - # String in that encoding, otherwise, we'll use the - # default external encoding. - if source.sub!(/\A#{ENCODING_FLAG}/, "") - encoding = magic_encoding = $1 - else - encoding = Encoding.default_external - end - - # Tag the source with the default external encoding - # or the encoding specified in the file - source.force_encoding(encoding) - - # If the user didn't specify an encoding, and the handler - # handles encodings, we simply pass the String as is to - # the handler (with the default_external tag) - if !magic_encoding && @handler.respond_to?(:handles_encoding?) && @handler.handles_encoding? - source - # Otherwise, if the String is valid in the encoding, - # encode immediately to default_internal. This means - # that if a handler doesn't handle encodings, it will - # always get Strings in the default_internal - elsif source.valid_encoding? - source.encode! - # Otherwise, since the String is invalid in the encoding - # specified, raise an exception - else - raise WrongEncodingError.new(source, encoding) - end - end - - private - - # Compile a template. This method ensures a template is compiled - # just once and removes the source after it is compiled. - def compile!(view) - return if @compiled - - # Templates can be used concurrently in threaded environments - # so compilation and any instance variable modification must - # be synchronized - @compile_mutex.synchronize do - # Any thread holding this lock will be compiling the template needed - # by the threads waiting. So re-check the @compiled flag to avoid - # re-compilation - return if @compiled - - if view.is_a?(ActionView::CompiledTemplates) - mod = ActionView::CompiledTemplates - else - mod = view.singleton_class - end - - instrument("!compile_template") do - compile(mod) - end - - # Just discard the source if we have a virtual path. This - # means we can get the template back. - @source = nil if @virtual_path - @compiled = true - end - end - - # Among other things, this method is responsible for properly setting - # the encoding of the compiled template. - # - # If the template engine handles encodings, we send the encoded - # String to the engine without further processing. This allows - # the template engine to support additional mechanisms for - # specifying the encoding. For instance, ERB supports <%# encoding: %> - # - # Otherwise, after we figure out the correct encoding, we then - # encode the source into Encoding.default_internal. - # In general, this means that templates will be UTF-8 inside of Rails, - # regardless of the original source encoding. - def compile(mod) - encode! - code = @handler.call(self) - - # Make sure that the resulting String to be eval'd is in the - # encoding of the code - source = <<-end_src - def #{method_name}(local_assigns, output_buffer) - _old_virtual_path, @virtual_path = @virtual_path, #{@virtual_path.inspect};_old_output_buffer = @output_buffer;#{locals_code};#{code} - ensure - @virtual_path, @output_buffer = _old_virtual_path, _old_output_buffer - end - end_src - - # Make sure the source is in the encoding of the returned code - source.force_encoding(code.encoding) - - # In case we get back a String from a handler that is not in - # BINARY or the default_internal, encode it to the default_internal - source.encode! - - # Now, validate that the source we got back from the template - # handler is valid in the default_internal. This is for handlers - # that handle encoding but screw up - unless source.valid_encoding? - raise WrongEncodingError.new(@source, Encoding.default_internal) - end - - mod.module_eval(source, identifier, 0) - ObjectSpace.define_finalizer(self, Finalizer[method_name, mod]) - end - - def handle_render_error(view, e) - if e.is_a?(Template::Error) - e.sub_template_of(self) - raise e - else - template = self - unless template.source - template = refresh(view) - template.encode! - end - raise Template::Error.new(template) - end - end - - def locals_code - # Only locals with valid variable names get set directly. Others will - # still be available in local_assigns. - locals = @locals - Module::RUBY_RESERVED_KEYWORDS - locals = locals.grep(/\A@?(?![A-Z0-9])(?:[[:alnum:]_]|[^\0-\177])+\z/) - - # Double assign to suppress the dreaded 'assigned but unused variable' warning - locals.each_with_object("") { |key, code| code << "#{key} = #{key} = local_assigns[:#{key}];" } - end - - def method_name - @method_name ||= begin - m = "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}" - m.tr!("-".freeze, "_".freeze) - m - end - end - - def identifier_method_name - inspect.tr("^a-z_".freeze, "_".freeze) - end - - def instrument(action, &block) # :doc: - ActiveSupport::Notifications.instrument("#{action}.action_view", instrument_payload, &block) - end - - def instrument_render_template(&block) - ActiveSupport::Notifications.instrument("!render_template.action_view".freeze, instrument_payload, &block) - end - - def instrument_payload - { virtual_path: @virtual_path, identifier: @identifier } - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/error.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/error.rb deleted file mode 100644 index cc90477190..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/error.rb +++ /dev/null @@ -1,142 +0,0 @@ -require "active_support/core_ext/enumerable" - -module ActionView - # = Action View Errors - class ActionViewError < StandardError #:nodoc: - end - - class EncodingError < StandardError #:nodoc: - end - - class MissingRequestError < StandardError #:nodoc: - end - - class WrongEncodingError < EncodingError #:nodoc: - def initialize(string, encoding) - @string, @encoding = string, encoding - end - - def message - @string.force_encoding(Encoding::ASCII_8BIT) - "Your template was not saved as valid #{@encoding}. Please " \ - "either specify #{@encoding} as the encoding for your template " \ - "in your text editor, or mark the template with its " \ - "encoding by inserting the following as the first line " \ - "of the template:\n\n# encoding: .\n\n" \ - "The source of your template was:\n\n#{@string}" - end - end - - class MissingTemplate < ActionViewError #:nodoc: - attr_reader :path - - def initialize(paths, path, prefixes, partial, details, *) - @path = path - prefixes = Array(prefixes) - template_type = if partial - "partial" - elsif /layouts/i.match?(path) - "layout" - else - "template" - end - - if partial && path.present? - path = path.sub(%r{([^/]+)$}, "_\\1") - end - searched_paths = prefixes.map { |prefix| [prefix, path].join("/") } - - out = "Missing #{template_type} #{searched_paths.join(", ")} with #{details.inspect}. Searched in:\n" - out += paths.compact.map { |p| " * #{p.to_s.inspect}\n" }.join - super out - end - end - - class Template - # The Template::Error exception is raised when the compilation or rendering of the template - # fails. This exception then gathers a bunch of intimate details and uses it to report a - # precise exception message. - class Error < ActionViewError #:nodoc: - SOURCE_CODE_RADIUS = 3 - - # Override to prevent #cause resetting during re-raise. - attr_reader :cause - - def initialize(template) - super($!.message) - set_backtrace($!.backtrace) - @cause = $! - @template, @sub_templates = template, nil - end - - def file_name - @template.identifier - end - - def sub_template_message - if @sub_templates - "Trace of template inclusion: " + - @sub_templates.collect(&:inspect).join(", ") - else - "" - end - end - - def source_extract(indentation = 0, output = :console) - return unless num = line_number - num = num.to_i - - source_code = @template.source.split("\n") - - start_on_line = [ num - SOURCE_CODE_RADIUS - 1, 0 ].max - end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min - - indent = end_on_line.to_s.size + indentation - return unless source_code = source_code[start_on_line..end_on_line] - - formatted_code_for(source_code, start_on_line, indent, output) - end - - def sub_template_of(template_path) - @sub_templates ||= [] - @sub_templates << template_path - end - - def line_number - @line_number ||= - if file_name - regexp = /#{Regexp.escape File.basename(file_name)}:(\d+)/ - $1 if message =~ regexp || backtrace.find { |line| line =~ regexp } - end - end - - def annoted_source_code - source_extract(4) - end - - private - - def source_location - if line_number - "on line ##{line_number} of " - else - "in " - end + file_name - end - - def formatted_code_for(source_code, line_counter, indent, output) - start_value = (output == :html) ? {} : [] - source_code.inject(start_value) do |result, line| - line_counter += 1 - if output == :html - result.update(line_counter.to_s => "%#{indent}s %s\n" % ["", line]) - else - result << "%#{indent}s: %s" % [line_counter, line] - end - end - end - end - end - - TemplateError = Template::Error -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers.rb deleted file mode 100644 index f4301f6f07..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers.rb +++ /dev/null @@ -1,64 +0,0 @@ -module ActionView #:nodoc: - # = Action View Template Handlers - class Template - module Handlers #:nodoc: - autoload :Raw, "action_view/template/handlers/raw" - autoload :ERB, "action_view/template/handlers/erb" - autoload :Html, "action_view/template/handlers/html" - autoload :Builder, "action_view/template/handlers/builder" - - def self.extended(base) - base.register_default_template_handler :raw, Raw.new - base.register_template_handler :erb, ERB.new - base.register_template_handler :html, Html.new - base.register_template_handler :builder, Builder.new - base.register_template_handler :ruby, :source.to_proc - end - - @@template_handlers = {} - @@default_template_handlers = nil - - def self.extensions - @@template_extensions ||= @@template_handlers.keys - end - - # Register an object that knows how to handle template files with the given - # extensions. This can be used to implement new template types. - # The handler must respond to +:call+, which will be passed the template - # and should return the rendered template as a String. - def register_template_handler(*extensions, handler) - raise(ArgumentError, "Extension is required") if extensions.empty? - extensions.each do |extension| - @@template_handlers[extension.to_sym] = handler - end - @@template_extensions = nil - end - - # Opposite to register_template_handler. - def unregister_template_handler(*extensions) - extensions.each do |extension| - handler = @@template_handlers.delete extension.to_sym - @@default_template_handlers = nil if @@default_template_handlers == handler - end - @@template_extensions = nil - end - - def template_handler_extensions - @@template_handlers.keys.map(&:to_s).sort - end - - def registered_template_handler(extension) - extension && @@template_handlers[extension.to_sym] - end - - def register_default_template_handler(extension, klass) - register_template_handler(extension, klass) - @@default_template_handlers = klass - end - - def handler_for_extension(extension) - registered_template_handler(extension) || @@default_template_handlers - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/builder.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/builder.rb deleted file mode 100644 index e99b921cb7..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/builder.rb +++ /dev/null @@ -1,26 +0,0 @@ -module ActionView - module Template::Handlers - class Builder - # Default format used by Builder. - class_attribute :default_format - self.default_format = :xml - - def call(template) - require_engine - "xml = ::Builder::XmlMarkup.new(:indent => 2);" \ - "self.output_buffer = xml.target!;" + - template.source + - ";xml.target!;" - end - - private - - def require_engine # :doc: - @required ||= begin - require "builder" - true - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb.rb deleted file mode 100644 index 58c7fd1a88..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb.rb +++ /dev/null @@ -1,78 +0,0 @@ -module ActionView - class Template - module Handlers - autoload :Erubis, "action_view/template/handlers/erb/deprecated_erubis" - - class ERB - autoload :Erubi, "action_view/template/handlers/erb/erubi" - autoload :Erubis, "action_view/template/handlers/erb/erubis" - - # Specify trim mode for the ERB compiler. Defaults to '-'. - # See ERB documentation for suitable values. - class_attribute :erb_trim_mode - self.erb_trim_mode = "-" - - # Default implementation used. - class_attribute :erb_implementation - self.erb_implementation = Erubi - - # Do not escape templates of these mime types. - class_attribute :escape_whitelist - self.escape_whitelist = ["text/plain"] - - ENCODING_TAG = Regexp.new("\\A(<%#{ENCODING_FLAG}-?%>)[ \\t]*") - - def self.call(template) - new.call(template) - end - - def supports_streaming? - true - end - - def handles_encoding? - true - end - - def call(template) - # First, convert to BINARY, so in case the encoding is - # wrong, we can still find an encoding tag - # (<%# encoding %>) inside the String using a regular - # expression - template_source = template.source.dup.force_encoding(Encoding::ASCII_8BIT) - - erb = template_source.gsub(ENCODING_TAG, "") - encoding = $2 - - erb.force_encoding valid_encoding(template.source.dup, encoding) - - # Always make sure we return a String in the default_internal - erb.encode! - - self.class.erb_implementation.new( - erb, - escape: (self.class.escape_whitelist.include? template.type), - trim: (self.class.erb_trim_mode == "-") - ).src - end - - private - - def valid_encoding(string, encoding) - # If a magic encoding comment was found, tag the - # String with this encoding. This is for a case - # where the original String was assumed to be, - # for instance, UTF-8, but a magic comment - # proved otherwise - string.force_encoding(encoding) if encoding - - # If the String is valid, return the encoding we found - return string.encoding if string.valid_encoding? - - # Otherwise, raise an exception - raise WrongEncodingError.new(string, string.encoding) - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/deprecated_erubis.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/deprecated_erubis.rb deleted file mode 100644 index 427ea20064..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/deprecated_erubis.rb +++ /dev/null @@ -1,9 +0,0 @@ -::ActiveSupport::Deprecation.warn("ActionView::Template::Handlers::Erubis is deprecated and will be removed from Rails 5.2. Switch to ActionView::Template::Handlers::ERB::Erubi instead.") - -module ActionView - class Template - module Handlers - Erubis = ERB::Erubis - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/erubi.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/erubi.rb deleted file mode 100644 index 755cc84015..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/erubi.rb +++ /dev/null @@ -1,81 +0,0 @@ -require "erubi" - -module ActionView - class Template - module Handlers - class ERB - class Erubi < ::Erubi::Engine - # :nodoc: all - def initialize(input, properties = {}) - @newline_pending = 0 - - # Dup properties so that we don't modify argument - properties = Hash[properties] - properties[:preamble] = "@output_buffer = output_buffer || ActionView::OutputBuffer.new;" - properties[:postamble] = "@output_buffer.to_s" - properties[:bufvar] = "@output_buffer" - properties[:escapefunc] = "" - - super - end - - def evaluate(action_view_erb_handler_context) - pr = eval("proc { #{@src} }", binding, @filename || "(erubi)") - action_view_erb_handler_context.instance_eval(&pr) - end - - private - def add_text(text) - return if text.empty? - - if text == "\n" - @newline_pending += 1 - else - src << "@output_buffer.safe_append='" - src << "\n" * @newline_pending if @newline_pending > 0 - src << text.gsub(/['\\]/, '\\\\\&') - src << "'.freeze;" - - @newline_pending = 0 - end - end - - BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/ - - def add_expression(indicator, code) - flush_newline_if_pending(src) - - if (indicator == "==") || @escape - src << "@output_buffer.safe_expr_append=" - else - src << "@output_buffer.append=" - end - - if BLOCK_EXPR.match?(code) - src << " " << code - else - src << "(" << code << ");" - end - end - - def add_code(code) - flush_newline_if_pending(src) - super - end - - def add_postamble(_) - flush_newline_if_pending(src) - super - end - - def flush_newline_if_pending(src) - if @newline_pending > 0 - src << "@output_buffer.safe_append='#{"\n" * @newline_pending}'.freeze;" - @newline_pending = 0 - end - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/erubis.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/erubis.rb deleted file mode 100644 index f3c35e1aec..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/erb/erubis.rb +++ /dev/null @@ -1,81 +0,0 @@ -gem "erubis" -require "erubis" - -module ActionView - class Template - module Handlers - class ERB - class Erubis < ::Erubis::Eruby - # :nodoc: all - def add_preamble(src) - @newline_pending = 0 - src << "@output_buffer = output_buffer || ActionView::OutputBuffer.new;" - end - - def add_text(src, text) - return if text.empty? - - if text == "\n" - @newline_pending += 1 - else - src << "@output_buffer.safe_append='" - src << "\n" * @newline_pending if @newline_pending > 0 - src << escape_text(text) - src << "'.freeze;" - - @newline_pending = 0 - end - end - - # Erubis toggles <%= and <%== behavior when escaping is enabled. - # We override to always treat <%== as escaped. - def add_expr(src, code, indicator) - case indicator - when "==" - add_expr_escaped(src, code) - else - super - end - end - - BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/ - - def add_expr_literal(src, code) - flush_newline_if_pending(src) - if BLOCK_EXPR.match?(code) - src << "@output_buffer.append= " << code - else - src << "@output_buffer.append=(" << code << ");" - end - end - - def add_expr_escaped(src, code) - flush_newline_if_pending(src) - if BLOCK_EXPR.match?(code) - src << "@output_buffer.safe_expr_append= " << code - else - src << "@output_buffer.safe_expr_append=(" << code << ");" - end - end - - def add_stmt(src, code) - flush_newline_if_pending(src) - super - end - - def add_postamble(src) - flush_newline_if_pending(src) - src << "@output_buffer.to_s" - end - - def flush_newline_if_pending(src) - if @newline_pending > 0 - src << "@output_buffer.safe_append='#{"\n" * @newline_pending}'.freeze;" - @newline_pending = 0 - end - end - end - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/html.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/html.rb deleted file mode 100644 index ccaa8d1469..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/html.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActionView - module Template::Handlers - class Html < Raw - def call(template) - "ActionView::OutputBuffer.new #{super}" - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/raw.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/raw.rb deleted file mode 100644 index e7519e94f9..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/handlers/raw.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActionView - module Template::Handlers - class Raw - def call(template) - "#{template.source.inspect}.html_safe;" - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/html.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/html.rb deleted file mode 100644 index 0ffae10432..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/html.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActionView #:nodoc: - # = Action View HTML Template - class Template - class HTML #:nodoc: - attr_accessor :type - - def initialize(string, type = nil) - @string = string.to_s - @type = Types[type] || type if type - @type ||= Types[:html] - end - - def identifier - "html template" - end - - alias_method :inspect, :identifier - - def to_str - ERB::Util.h(@string) - end - - def render(*args) - to_str - end - - def formats - [@type.respond_to?(:ref) ? @type.ref : @type.to_s] - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/resolver.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/resolver.rb deleted file mode 100644 index d3905b5f23..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/resolver.rb +++ /dev/null @@ -1,390 +0,0 @@ -require "pathname" -require "active_support/core_ext/class" -require "active_support/core_ext/module/attribute_accessors" -require "action_view/template" -require "thread" -require "concurrent/map" - -module ActionView - # = Action View Resolver - class Resolver - # Keeps all information about view path and builds virtual path. - class Path - attr_reader :name, :prefix, :partial, :virtual - alias_method :partial?, :partial - - def self.build(name, prefix, partial) - virtual = "" - virtual << "#{prefix}/" unless prefix.empty? - virtual << (partial ? "_#{name}" : name) - new name, prefix, partial, virtual - end - - def initialize(name, prefix, partial, virtual) - @name = name - @prefix = prefix - @partial = partial - @virtual = virtual - end - - def to_str - @virtual - end - alias :to_s :to_str - end - - # Threadsafe template cache - class Cache #:nodoc: - class SmallCache < Concurrent::Map - def initialize(options = {}) - super(options.merge(initial_capacity: 2)) - end - end - - # preallocate all the default blocks for performance/memory consumption reasons - PARTIAL_BLOCK = lambda { |cache, partial| cache[partial] = SmallCache.new } - PREFIX_BLOCK = lambda { |cache, prefix| cache[prefix] = SmallCache.new(&PARTIAL_BLOCK) } - NAME_BLOCK = lambda { |cache, name| cache[name] = SmallCache.new(&PREFIX_BLOCK) } - KEY_BLOCK = lambda { |cache, key| cache[key] = SmallCache.new(&NAME_BLOCK) } - - # usually a majority of template look ups return nothing, use this canonical preallocated array to save memory - NO_TEMPLATES = [].freeze - - def initialize - @data = SmallCache.new(&KEY_BLOCK) - @query_cache = SmallCache.new - end - - def inspect - "#<#{self.class.name}:0x#{(object_id << 1).to_s(16)} keys=#{@data.size} queries=#{@query_cache.size}>" - end - - # Cache the templates returned by the block - def cache(key, name, prefix, partial, locals) - if Resolver.caching? - @data[key][name][prefix][partial][locals] ||= canonical_no_templates(yield) - else - fresh_templates = yield - cached_templates = @data[key][name][prefix][partial][locals] - - if templates_have_changed?(cached_templates, fresh_templates) - @data[key][name][prefix][partial][locals] = canonical_no_templates(fresh_templates) - else - cached_templates || NO_TEMPLATES - end - end - end - - def cache_query(query) # :nodoc: - if Resolver.caching? - @query_cache[query] ||= canonical_no_templates(yield) - else - yield - end - end - - def clear - @data.clear - @query_cache.clear - end - - # Get the cache size. Do not call this - # method. This method is not guaranteed to be here ever. - def size # :nodoc: - size = 0 - @data.each_value do |v1| - v1.each_value do |v2| - v2.each_value do |v3| - v3.each_value do |v4| - size += v4.size - end - end - end - end - - size + @query_cache.size - end - - private - - def canonical_no_templates(templates) - templates.empty? ? NO_TEMPLATES : templates - end - - def templates_have_changed?(cached_templates, fresh_templates) - # if either the old or new template list is empty, we don't need to (and can't) - # compare modification times, and instead just check whether the lists are different - if cached_templates.blank? || fresh_templates.blank? - return fresh_templates.blank? != cached_templates.blank? - end - - cached_templates_max_updated_at = cached_templates.map(&:updated_at).max - - # if a template has changed, it will be now be newer than all the cached templates - fresh_templates.any? { |t| t.updated_at > cached_templates_max_updated_at } - end - end - - cattr_accessor :caching - self.caching = true - - class << self - alias :caching? :caching - end - - def initialize - @cache = Cache.new - end - - def clear_cache - @cache.clear - end - - # Normalizes the arguments and passes it on to find_templates. - def find_all(name, prefix = nil, partial = false, details = {}, key = nil, locals = []) - cached(key, [name, prefix, partial], details, locals) do - find_templates(name, prefix, partial, details) - end - end - - def find_all_anywhere(name, prefix, partial = false, details = {}, key = nil, locals = []) - cached(key, [name, prefix, partial], details, locals) do - find_templates(name, prefix, partial, details, true) - end - end - - def find_all_with_query(query) # :nodoc: - @cache.cache_query(query) { find_template_paths(File.join(@path, query)) } - end - - private - - delegate :caching?, to: :class - - # This is what child classes implement. No defaults are needed - # because Resolver guarantees that the arguments are present and - # normalized. - def find_templates(name, prefix, partial, details, outside_app_allowed = false) - raise NotImplementedError, "Subclasses must implement a find_templates(name, prefix, partial, details, outside_app_allowed = false) method" - end - - # Helpers that builds a path. Useful for building virtual paths. - def build_path(name, prefix, partial) - Path.build(name, prefix, partial) - end - - # Handles templates caching. If a key is given and caching is on - # always check the cache before hitting the resolver. Otherwise, - # it always hits the resolver but if the key is present, check if the - # resolver is fresher before returning it. - def cached(key, path_info, details, locals) - name, prefix, partial = path_info - locals = locals.map(&:to_s).sort! - - if key - @cache.cache(key, name, prefix, partial, locals) do - decorate(yield, path_info, details, locals) - end - else - decorate(yield, path_info, details, locals) - end - end - - # Ensures all the resolver information is set in the template. - def decorate(templates, path_info, details, locals) - cached = nil - templates.each do |t| - t.locals = locals - t.formats = details[:formats] || [:html] if t.formats.empty? - t.variants = details[:variants] || [] if t.variants.empty? - t.virtual_path ||= (cached ||= build_path(*path_info)) - end - end - end - - # An abstract class that implements a Resolver with path semantics. - class PathResolver < Resolver #:nodoc: - EXTENSIONS = { locale: ".", formats: ".", variants: "+", handlers: "." } - DEFAULT_PATTERN = ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}" - - def initialize(pattern = nil) - @pattern = pattern || DEFAULT_PATTERN - super() - end - - private - - def find_templates(name, prefix, partial, details, outside_app_allowed = false) - path = Path.build(name, prefix, partial) - query(path, details, details[:formats], outside_app_allowed) - end - - def query(path, details, formats, outside_app_allowed) - query = build_query(path, details) - - template_paths = find_template_paths(query) - template_paths = reject_files_external_to_app(template_paths) unless outside_app_allowed - - template_paths.map do |template| - handler, format, variant = extract_handler_and_format_and_variant(template) - contents = File.binread(template) - - Template.new(contents, File.expand_path(template), handler, - virtual_path: path.virtual, - format: format, - variant: variant, - updated_at: mtime(template) - ) - end - end - - def reject_files_external_to_app(files) - files.reject { |filename| !inside_path?(@path, filename) } - end - - def find_template_paths(query) - Dir[query].uniq.reject do |filename| - File.directory?(filename) || - # deals with case-insensitive file systems. - !File.fnmatch(query, filename, File::FNM_EXTGLOB) - end - end - - def inside_path?(path, filename) - filename = File.expand_path(filename) - path = File.join(path, "") - filename.start_with?(path) - end - - # Helper for building query glob string based on resolver's pattern. - def build_query(path, details) - query = @pattern.dup - - prefix = path.prefix.empty? ? "" : "#{escape_entry(path.prefix)}\\1" - query.gsub!(/:prefix(\/)?/, prefix) - - partial = escape_entry(path.partial? ? "_#{path.name}" : path.name) - query.gsub!(/:action/, partial) - - details.each do |ext, candidates| - if ext == :variants && candidates == :any - query.gsub!(/:#{ext}/, "*") - else - query.gsub!(/:#{ext}/, "{#{candidates.compact.uniq.join(',')}}") - end - end - - File.expand_path(query, @path) - end - - def escape_entry(entry) - entry.gsub(/[*?{}\[\]]/, '\\\\\\&'.freeze) - end - - # Returns the file mtime from the filesystem. - def mtime(p) - File.mtime(p) - end - - # Extract handler, formats and variant from path. If a format cannot be found neither - # from the path, or the handler, we should return the array of formats given - # to the resolver. - def extract_handler_and_format_and_variant(path) - pieces = File.basename(path).split(".".freeze) - pieces.shift - - extension = pieces.pop - - handler = Template.handler_for_extension(extension) - format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last - format &&= Template::Types[format] - - [handler, format, variant] - end - end - - # A resolver that loads files from the filesystem. It allows setting your own - # resolving pattern. Such pattern can be a glob string supported by some variables. - # - # ==== Examples - # - # Default pattern, loads views the same way as previous versions of rails, eg. when you're - # looking for `users/new` it will produce query glob: `users/new{.{en},}{.{html,js},}{.{erb,haml},}` - # - # FileSystemResolver.new("/path/to/views", ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}") - # - # This one allows you to keep files with different formats in separate subdirectories, - # eg. `users/new.html` will be loaded from `users/html/new.erb` or `users/new.html.erb`, - # `users/new.js` from `users/js/new.erb` or `users/new.js.erb`, etc. - # - # FileSystemResolver.new("/path/to/views", ":prefix/{:formats/,}:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}") - # - # If you don't specify a pattern then the default will be used. - # - # In order to use any of the customized resolvers above in a Rails application, you just need - # to configure ActionController::Base.view_paths in an initializer, for example: - # - # ActionController::Base.view_paths = FileSystemResolver.new( - # Rails.root.join("app/views"), - # ":prefix/:action{.:locale,}{.:formats,}{+:variants,}{.:handlers,}", - # ) - # - # ==== Pattern format and variables - # - # Pattern has to be a valid glob string, and it allows you to use the - # following variables: - # - # * :prefix - usually the controller path - # * :action - name of the action - # * :locale - possible locale versions - # * :formats - possible request formats (for example html, json, xml...) - # * :variants - possible request variants (for example phone, tablet...) - # * :handlers - possible handlers (for example erb, haml, builder...) - # - class FileSystemResolver < PathResolver - def initialize(path, pattern = nil) - raise ArgumentError, "path already is a Resolver class" if path.is_a?(Resolver) - super(pattern) - @path = File.expand_path(path) - end - - def to_s - @path.to_s - end - alias :to_path :to_s - - def eql?(resolver) - self.class.equal?(resolver.class) && to_path == resolver.to_path - end - alias :== :eql? - end - - # An Optimized resolver for Rails' most common case. - class OptimizedFileSystemResolver < FileSystemResolver #:nodoc: - def build_query(path, details) - query = escape_entry(File.join(@path, path)) - - exts = EXTENSIONS.map do |ext, prefix| - if ext == :variants && details[ext] == :any - "{#{prefix}*,}" - else - "{#{details[ext].compact.uniq.map { |e| "#{prefix}#{e}," }.join}}" - end - end.join - - query + exts - end - end - - # The same as FileSystemResolver but does not allow templates to store - # a virtual path since it is invalid for such resolvers. - class FallbackFileSystemResolver < FileSystemResolver #:nodoc: - def self.instances - [new(""), new("/")] - end - - def decorate(*) - super.each { |t| t.virtual_path = nil } - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/text.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/text.rb deleted file mode 100644 index 380528d6ef..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/text.rb +++ /dev/null @@ -1,31 +0,0 @@ -module ActionView #:nodoc: - # = Action View Text Template - class Template - class Text #:nodoc: - attr_accessor :type - - def initialize(string) - @string = string.to_s - @type = Types[:text] - end - - def identifier - "text template" - end - - alias_method :inspect, :identifier - - def to_str - @string - end - - def render(*args) - to_str - end - - def formats - [@type.ref] - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/types.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/template/types.rb deleted file mode 100644 index 21959a3798..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/template/types.rb +++ /dev/null @@ -1,55 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" - -module ActionView - class Template - class Types - class Type - SET = Struct.new(:symbols).new([ :html, :text, :js, :css, :xml, :json ]) - - def self.[](type) - if type.is_a?(self) - type - else - new(type) - end - end - - attr_reader :symbol - - def initialize(symbol) - @symbol = symbol.to_sym - end - - def to_s - @symbol.to_s - end - alias to_str to_s - - def ref - @symbol - end - alias to_sym ref - - def ==(type) - @symbol == type.to_sym unless type.blank? - end - end - - cattr_accessor :type_klass - - def self.delegate_to(klass) - self.type_klass = klass - end - - delegate_to Type - - def self.[](type) - type_klass[type] - end - - def self.symbols - type_klass::SET.symbols - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/test_case.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/test_case.rb deleted file mode 100644 index ae4fec4337..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/test_case.rb +++ /dev/null @@ -1,284 +0,0 @@ -require "active_support/core_ext/module/remove_method" -require "action_controller" -require "action_controller/test_case" -require "action_view" - -require "rails-dom-testing" - -module ActionView - # = Action View Test Case - class TestCase < ActiveSupport::TestCase - class TestController < ActionController::Base - include ActionDispatch::TestProcess - - attr_accessor :request, :response, :params - - class << self - attr_writer :controller_path - end - - def controller_path=(path) - self.class.controller_path = (path) - end - - def initialize - super - self.class.controller_path = "" - @request = ActionController::TestRequest.create(self.class) - @response = ActionDispatch::TestResponse.new - - @request.env.delete("PATH_INFO") - @params = ActionController::Parameters.new - end - end - - module Behavior - extend ActiveSupport::Concern - - include ActionDispatch::Assertions, ActionDispatch::TestProcess - include Rails::Dom::Testing::Assertions - include ActionController::TemplateAssertions - include ActionView::Context - - include ActionDispatch::Routing::PolymorphicRoutes - - include AbstractController::Helpers - include ActionView::Helpers - include ActionView::RecordIdentifier - include ActionView::RoutingUrlFor - - include ActiveSupport::Testing::ConstantLookup - - delegate :lookup_context, to: :controller - attr_accessor :controller, :output_buffer, :rendered - - module ClassMethods - def tests(helper_class) - case helper_class - when String, Symbol - self.helper_class = "#{helper_class.to_s.underscore}_helper".camelize.safe_constantize - when Module - self.helper_class = helper_class - end - end - - def determine_default_helper_class(name) - determine_constant_from_test_name(name) do |constant| - Module === constant && !(Class === constant) - end - end - - def helper_method(*methods) - # Almost a duplicate from ActionController::Helpers - methods.flatten.each do |method| - _helpers.module_eval <<-end_eval - def #{method}(*args, &block) # def current_user(*args, &block) - _test_case.send(%(#{method}), *args, &block) # _test_case.send(%(current_user), *args, &block) - end # end - end_eval - end - end - - attr_writer :helper_class - - def helper_class - @helper_class ||= determine_default_helper_class(name) - end - - def new(*) - include_helper_modules! - super - end - - private - - def include_helper_modules! - helper(helper_class) if helper_class - include _helpers - end - end - - def setup_with_controller - @controller = ActionView::TestCase::TestController.new - @request = @controller.request - # empty string ensures buffer has UTF-8 encoding as - # new without arguments returns ASCII-8BIT encoded buffer like String#new - @output_buffer = ActiveSupport::SafeBuffer.new "" - @rendered = "" - - make_test_case_available_to_view! - say_no_to_protect_against_forgery! - end - - def config - @controller.config if @controller.respond_to?(:config) - end - - def render(options = {}, local_assigns = {}, &block) - view.assign(view_assigns) - @rendered << output = view.render(options, local_assigns, &block) - output - end - - def rendered_views - @_rendered_views ||= RenderedViewsCollection.new - end - - def _routes - @controller._routes if @controller.respond_to?(:_routes) - end - - # Need to experiment if this priority is the best one: rendered => output_buffer - class RenderedViewsCollection - def initialize - @rendered_views ||= Hash.new { |hash, key| hash[key] = [] } - end - - def add(view, locals) - @rendered_views[view] ||= [] - @rendered_views[view] << locals - end - - def locals_for(view) - @rendered_views[view] - end - - def rendered_views - @rendered_views.keys - end - - def view_rendered?(view, expected_locals) - locals_for(view).any? do |actual_locals| - expected_locals.all? { |key, value| value == actual_locals[key] } - end - end - end - - included do - setup :setup_with_controller - ActiveSupport.run_load_hooks(:action_view_test_case, self) - end - - private - - # Need to experiment if this priority is the best one: rendered => output_buffer - def document_root_element - Nokogiri::HTML::Document.parse(@rendered.blank? ? @output_buffer : @rendered).root - end - - def say_no_to_protect_against_forgery! - _helpers.module_eval do - remove_possible_method :protect_against_forgery? - def protect_against_forgery? - false - end - end - end - - def make_test_case_available_to_view! - test_case_instance = self - _helpers.module_eval do - unless private_method_defined?(:_test_case) - define_method(:_test_case) { test_case_instance } - private :_test_case - end - end - end - - module Locals - attr_accessor :rendered_views - - def render(options = {}, local_assigns = {}) - case options - when Hash - if block_given? - rendered_views.add options[:layout], options[:locals] - elsif options.key?(:partial) - rendered_views.add options[:partial], options[:locals] - end - else - rendered_views.add options, local_assigns - end - - super - end - end - - # The instance of ActionView::Base that is used by +render+. - def view - @view ||= begin - view = @controller.view_context - view.singleton_class.include(_helpers) - view.extend(Locals) - view.rendered_views = rendered_views - view.output_buffer = output_buffer - view - end - end - - alias_method :_view, :view - - INTERNAL_IVARS = [ - :@NAME, - :@failures, - :@assertions, - :@__io__, - :@_assertion_wrapped, - :@_assertions, - :@_result, - :@_routes, - :@controller, - :@_layouts, - :@_files, - :@_rendered_views, - :@method_name, - :@output_buffer, - :@_partials, - :@passed, - :@rendered, - :@request, - :@routes, - :@tagged_logger, - :@_templates, - :@options, - :@test_passed, - :@view, - :@view_context_class, - :@_subscribers, - :@html_document - ] - - def _user_defined_ivars - instance_variables - INTERNAL_IVARS - end - - # Returns a Hash of instance variables and their values, as defined by - # the user in the test case, which are then assigned to the view being - # rendered. This is generally intended for internal use and extension - # frameworks. - def view_assigns - Hash[_user_defined_ivars.map do |ivar| - [ivar[1..-1].to_sym, instance_variable_get(ivar)] - end] - end - - def method_missing(selector, *args) - begin - routes = @controller.respond_to?(:_routes) && @controller._routes - rescue - # Dont call routes, if there is an error on _routes call - end - - if routes && - (routes.named_routes.route_defined?(selector) || - routes.mounted_helpers.method_defined?(selector)) - @controller.__send__(selector, *args) - else - super - end - end - end - - include Behavior - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/testing/resolvers.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/testing/resolvers.rb deleted file mode 100644 index 3188526b63..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/testing/resolvers.rb +++ /dev/null @@ -1,52 +0,0 @@ -require "action_view/template/resolver" - -module ActionView #:nodoc: - # Use FixtureResolver in your tests to simulate the presence of files on the - # file system. This is used internally by Rails' own test suite, and is - # useful for testing extensions that have no way of knowing what the file - # system will look like at runtime. - class FixtureResolver < PathResolver - attr_reader :hash - - def initialize(hash = {}, pattern = nil) - super(pattern) - @hash = hash - end - - def to_s - @hash.keys.join(", ") - end - - private - - def query(path, exts, _, _) - query = "" - EXTENSIONS.each_key do |ext| - query << "(" << exts[ext].map { |e| e && Regexp.escape(".#{e}") }.join("|") << "|)" - end - query = /^(#{Regexp.escape(path)})#{query}$/ - - templates = [] - @hash.each do |_path, array| - source, updated_at = array - next unless query.match?(_path) - handler, format, variant = extract_handler_and_format_and_variant(_path) - templates << Template.new(source, _path, handler, - virtual_path: path.virtual, - format: format, - variant: variant, - updated_at: updated_at - ) - end - - templates.sort_by { |t| -t.identifier.match(/^#{query}$/).captures.reject(&:blank?).size } - end - end - - class NullResolver < PathResolver - def query(path, exts, _, _) - handler, format, variant = extract_handler_and_format_and_variant(path) - [ActionView::Template.new("Template generated by Null Resolver", path.virtual, handler, virtual_path: path.virtual, format: format, variant: variant)] - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/version.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/version.rb deleted file mode 100644 index 315404864d..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module ActionView - # Returns the version of the currently loaded ActionView as a Gem::Version - def self.version - gem_version - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/action_view/view_paths.rb b/debian/gems-compat/actionview-5.1.7/lib/action_view/view_paths.rb deleted file mode 100644 index f0fe6831fa..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/action_view/view_paths.rb +++ /dev/null @@ -1,105 +0,0 @@ -module ActionView - module ViewPaths - extend ActiveSupport::Concern - - included do - class_attribute :_view_paths - self._view_paths = ActionView::PathSet.new - _view_paths.freeze - end - - delegate :template_exists?, :any_templates?, :view_paths, :formats, :formats=, - :locale, :locale=, to: :lookup_context - - module ClassMethods - def _prefixes # :nodoc: - @_prefixes ||= begin - return local_prefixes if superclass.abstract? - - local_prefixes + superclass._prefixes - end - end - - private - - # Override this method in your controller if you want to change paths prefixes for finding views. - # Prefixes defined here will still be added to parents' ._prefixes. - def local_prefixes - [controller_path] - end - end - - # The prefixes used in render "foo" shortcuts. - def _prefixes # :nodoc: - self.class._prefixes - end - - # LookupContext is the object responsible for holding all - # information required for looking up templates, i.e. view paths and - # details. Check ActionView::LookupContext for more information. - def lookup_context - @_lookup_context ||= - ActionView::LookupContext.new(self.class._view_paths, details_for_lookup, _prefixes) - end - - def details_for_lookup - {} - end - - # Append a path to the list of view paths for the current LookupContext. - # - # ==== Parameters - # * path - If a String is provided, it gets converted into - # the default view path. You may also provide a custom view path - # (see ActionView::PathSet for more information) - def append_view_path(path) - lookup_context.view_paths.push(*path) - end - - # Prepend a path to the list of view paths for the current LookupContext. - # - # ==== Parameters - # * path - If a String is provided, it gets converted into - # the default view path. You may also provide a custom view path - # (see ActionView::PathSet for more information) - def prepend_view_path(path) - lookup_context.view_paths.unshift(*path) - end - - module ClassMethods - # Append a path to the list of view paths for this controller. - # - # ==== Parameters - # * path - If a String is provided, it gets converted into - # the default view path. You may also provide a custom view path - # (see ActionView::PathSet for more information) - def append_view_path(path) - self._view_paths = view_paths + Array(path) - end - - # Prepend a path to the list of view paths for this controller. - # - # ==== Parameters - # * path - If a String is provided, it gets converted into - # the default view path. You may also provide a custom view path - # (see ActionView::PathSet for more information) - def prepend_view_path(path) - self._view_paths = ActionView::PathSet.new(Array(path) + view_paths) - end - - # A list of all of the default view paths for this controller. - def view_paths - _view_paths - end - - # Set the view paths. - # - # ==== Parameters - # * paths - If a PathSet is provided, use that; - # otherwise, process the parameter into a PathSet. - def view_paths=(paths) - self._view_paths = ActionView::PathSet.new(Array(paths)) - end - end - end -end diff --git a/debian/gems-compat/actionview-5.1.7/lib/assets/compiled/rails-ujs.js b/debian/gems-compat/actionview-5.1.7/lib/assets/compiled/rails-ujs.js deleted file mode 100644 index 7b5a6d3e5c..0000000000 --- a/debian/gems-compat/actionview-5.1.7/lib/assets/compiled/rails-ujs.js +++ /dev/null @@ -1,683 +0,0 @@ -/* -Unobtrusive JavaScript -https://github.com/rails/rails/blob/master/actionview/app/assets/javascripts -Released under the MIT license - */ - -(function() { - var context = this; - - (function() { - (function() { - this.Rails = { - linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]', - buttonClickSelector: { - selector: 'button[data-remote]:not([form]), button[data-confirm]:not([form])', - exclude: 'form button' - }, - inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]', - formSubmitSelector: 'form', - formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])', - formDisableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled', - formEnableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled', - fileInputSelector: 'input[name][type=file]:not([disabled])', - linkDisableSelector: 'a[data-disable-with], a[data-disable]', - buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]' - }; - - }).call(this); - }).call(context); - - var Rails = context.Rails; - - (function() { - (function() { - var expando, m; - - m = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector; - - Rails.matches = function(element, selector) { - if (selector.exclude != null) { - return m.call(element, selector.selector) && !m.call(element, selector.exclude); - } else { - return m.call(element, selector); - } - }; - - expando = '_ujsData'; - - Rails.getData = function(element, key) { - var ref; - return (ref = element[expando]) != null ? ref[key] : void 0; - }; - - Rails.setData = function(element, key, value) { - if (element[expando] == null) { - element[expando] = {}; - } - return element[expando][key] = value; - }; - - Rails.$ = function(selector) { - return Array.prototype.slice.call(document.querySelectorAll(selector)); - }; - - }).call(this); - (function() { - var $, csrfParam, csrfToken; - - $ = Rails.$; - - csrfToken = Rails.csrfToken = function() { - var meta; - meta = document.querySelector('meta[name=csrf-token]'); - return meta && meta.content; - }; - - csrfParam = Rails.csrfParam = function() { - var meta; - meta = document.querySelector('meta[name=csrf-param]'); - return meta && meta.content; - }; - - Rails.CSRFProtection = function(xhr) { - var token; - token = csrfToken(); - if (token != null) { - return xhr.setRequestHeader('X-CSRF-Token', token); - } - }; - - Rails.refreshCSRFTokens = function() { - var param, token; - token = csrfToken(); - param = csrfParam(); - if ((token != null) && (param != null)) { - return $('form input[name="' + param + '"]').forEach(function(input) { - return input.value = token; - }); - } - }; - - }).call(this); - (function() { - var CustomEvent, fire, matches; - - matches = Rails.matches; - - CustomEvent = window.CustomEvent; - - if (typeof CustomEvent !== 'function') { - CustomEvent = function(event, params) { - var evt; - evt = document.createEvent('CustomEvent'); - evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); - return evt; - }; - CustomEvent.prototype = window.Event.prototype; - } - - fire = Rails.fire = function(obj, name, data) { - var event; - event = new CustomEvent(name, { - bubbles: true, - cancelable: true, - detail: data - }); - obj.dispatchEvent(event); - return !event.defaultPrevented; - }; - - Rails.stopEverything = function(e) { - fire(e.target, 'ujs:everythingStopped'); - e.preventDefault(); - e.stopPropagation(); - return e.stopImmediatePropagation(); - }; - - Rails.delegate = function(element, selector, eventType, handler) { - return element.addEventListener(eventType, function(e) { - var target; - target = e.target; - while (!(!(target instanceof Element) || matches(target, selector))) { - target = target.parentNode; - } - if (target instanceof Element && handler.call(target, e) === false) { - e.preventDefault(); - return e.stopPropagation(); - } - }); - }; - - }).call(this); - (function() { - var AcceptHeaders, CSRFProtection, createXHR, fire, prepareOptions, processResponse; - - CSRFProtection = Rails.CSRFProtection, fire = Rails.fire; - - AcceptHeaders = { - '*': '*/*', - text: 'text/plain', - html: 'text/html', - xml: 'application/xml, text/xml', - json: 'application/json, text/javascript', - script: 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript' - }; - - Rails.ajax = function(options) { - var xhr; - options = prepareOptions(options); - xhr = createXHR(options, function() { - var response; - response = processResponse(xhr.response, xhr.getResponseHeader('Content-Type')); - if (Math.floor(xhr.status / 100) === 2) { - if (typeof options.success === "function") { - options.success(response, xhr.statusText, xhr); - } - } else { - if (typeof options.error === "function") { - options.error(response, xhr.statusText, xhr); - } - } - return typeof options.complete === "function" ? options.complete(xhr, xhr.statusText) : void 0; - }); - if (!(typeof options.beforeSend === "function" ? options.beforeSend(xhr, options) : void 0)) { - return false; - } - if (xhr.readyState === XMLHttpRequest.OPENED) { - return xhr.send(options.data); - } - }; - - prepareOptions = function(options) { - options.url = options.url || location.href; - options.type = options.type.toUpperCase(); - if (options.type === 'GET' && options.data) { - if (options.url.indexOf('?') < 0) { - options.url += '?' + options.data; - } else { - options.url += '&' + options.data; - } - } - if (AcceptHeaders[options.dataType] == null) { - options.dataType = '*'; - } - options.accept = AcceptHeaders[options.dataType]; - if (options.dataType !== '*') { - options.accept += ', */*; q=0.01'; - } - return options; - }; - - createXHR = function(options, done) { - var xhr; - xhr = new XMLHttpRequest(); - xhr.open(options.type, options.url, true); - xhr.setRequestHeader('Accept', options.accept); - if (typeof options.data === 'string') { - xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); - } - if (!options.crossDomain) { - xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); - } - CSRFProtection(xhr); - xhr.withCredentials = !!options.withCredentials; - xhr.onreadystatechange = function() { - if (xhr.readyState === XMLHttpRequest.DONE) { - return done(xhr); - } - }; - return xhr; - }; - - processResponse = function(response, type) { - var parser, script; - if (typeof response === 'string' && typeof type === 'string') { - if (type.match(/\bjson\b/)) { - try { - response = JSON.parse(response); - } catch (error) {} - } else if (type.match(/\b(?:java|ecma)script\b/)) { - script = document.createElement('script'); - script.text = response; - document.head.appendChild(script).parentNode.removeChild(script); - } else if (type.match(/\b(xml|html|svg)\b/)) { - parser = new DOMParser(); - type = type.replace(/;.+/, ''); - try { - response = parser.parseFromString(response, type); - } catch (error) {} - } - } - return response; - }; - - Rails.href = function(element) { - return element.href; - }; - - Rails.isCrossDomain = function(url) { - var e, originAnchor, urlAnchor; - originAnchor = document.createElement('a'); - originAnchor.href = location.href; - urlAnchor = document.createElement('a'); - try { - urlAnchor.href = url; - return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) || (originAnchor.protocol + '//' + originAnchor.host === urlAnchor.protocol + '//' + urlAnchor.host)); - } catch (error) { - e = error; - return true; - } - }; - - }).call(this); - (function() { - var matches, toArray; - - matches = Rails.matches; - - toArray = function(e) { - return Array.prototype.slice.call(e); - }; - - Rails.serializeElement = function(element, additionalParam) { - var inputs, params; - inputs = [element]; - if (matches(element, 'form')) { - inputs = toArray(element.elements); - } - params = []; - inputs.forEach(function(input) { - if (!input.name || input.disabled) { - return; - } - if (matches(input, 'select')) { - return toArray(input.options).forEach(function(option) { - if (option.selected) { - return params.push({ - name: input.name, - value: option.value - }); - } - }); - } else if (input.checked || ['radio', 'checkbox', 'submit'].indexOf(input.type) === -1) { - return params.push({ - name: input.name, - value: input.value - }); - } - }); - if (additionalParam) { - params.push(additionalParam); - } - return params.map(function(param) { - if (param.name != null) { - return (encodeURIComponent(param.name)) + "=" + (encodeURIComponent(param.value)); - } else { - return param; - } - }).join('&'); - }; - - Rails.formElements = function(form, selector) { - if (matches(form, 'form')) { - return toArray(form.elements).filter(function(el) { - return matches(el, selector); - }); - } else { - return toArray(form.querySelectorAll(selector)); - } - }; - - }).call(this); - (function() { - var allowAction, fire, stopEverything; - - fire = Rails.fire, stopEverything = Rails.stopEverything; - - Rails.handleConfirm = function(e) { - if (!allowAction(this)) { - return stopEverything(e); - } - }; - - allowAction = function(element) { - var answer, callback, message; - message = element.getAttribute('data-confirm'); - if (!message) { - return true; - } - answer = false; - if (fire(element, 'confirm')) { - try { - answer = confirm(message); - } catch (error) {} - callback = fire(element, 'confirm:complete', [answer]); - } - return answer && callback; - }; - - }).call(this); - (function() { - var disableFormElement, disableFormElements, disableLinkElement, enableFormElement, enableFormElements, enableLinkElement, formElements, getData, matches, setData, stopEverything; - - matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, stopEverything = Rails.stopEverything, formElements = Rails.formElements; - - Rails.handleDisabledElement = function(e) { - var element; - element = this; - if (element.disabled) { - return stopEverything(e); - } - }; - - Rails.enableElement = function(e) { - var element; - element = e instanceof Event ? e.target : e; - if (matches(element, Rails.linkDisableSelector)) { - return enableLinkElement(element); - } else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formEnableSelector)) { - return enableFormElement(element); - } else if (matches(element, Rails.formSubmitSelector)) { - return enableFormElements(element); - } - }; - - Rails.disableElement = function(e) { - var element; - element = e instanceof Event ? e.target : e; - if (matches(element, Rails.linkDisableSelector)) { - return disableLinkElement(element); - } else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formDisableSelector)) { - return disableFormElement(element); - } else if (matches(element, Rails.formSubmitSelector)) { - return disableFormElements(element); - } - }; - - disableLinkElement = function(element) { - var replacement; - replacement = element.getAttribute('data-disable-with'); - if (replacement != null) { - setData(element, 'ujs:enable-with', element.innerHTML); - element.innerHTML = replacement; - } - element.addEventListener('click', stopEverything); - return setData(element, 'ujs:disabled', true); - }; - - enableLinkElement = function(element) { - var originalText; - originalText = getData(element, 'ujs:enable-with'); - if (originalText != null) { - element.innerHTML = originalText; - setData(element, 'ujs:enable-with', null); - } - element.removeEventListener('click', stopEverything); - return setData(element, 'ujs:disabled', null); - }; - - disableFormElements = function(form) { - return formElements(form, Rails.formDisableSelector).forEach(disableFormElement); - }; - - disableFormElement = function(element) { - var replacement; - replacement = element.getAttribute('data-disable-with'); - if (replacement != null) { - if (matches(element, 'button')) { - setData(element, 'ujs:enable-with', element.innerHTML); - element.innerHTML = replacement; - } else { - setData(element, 'ujs:enable-with', element.value); - element.value = replacement; - } - } - element.disabled = true; - return setData(element, 'ujs:disabled', true); - }; - - enableFormElements = function(form) { - return formElements(form, Rails.formEnableSelector).forEach(enableFormElement); - }; - - enableFormElement = function(element) { - var originalText; - originalText = getData(element, 'ujs:enable-with'); - if (originalText != null) { - if (matches(element, 'button')) { - element.innerHTML = originalText; - } else { - element.value = originalText; - } - setData(element, 'ujs:enable-with', null); - } - element.disabled = false; - return setData(element, 'ujs:disabled', null); - }; - - }).call(this); - (function() { - var stopEverything; - - stopEverything = Rails.stopEverything; - - Rails.handleMethod = function(e) { - var csrfParam, csrfToken, form, formContent, href, link, method; - link = this; - method = link.getAttribute('data-method'); - if (!method) { - return; - } - href = Rails.href(link); - csrfToken = Rails.csrfToken(); - csrfParam = Rails.csrfParam(); - form = document.createElement('form'); - formContent = ""; - if ((csrfParam != null) && (csrfToken != null) && !Rails.isCrossDomain(href)) { - formContent += ""; - } - formContent += ''; - form.method = 'post'; - form.action = href; - form.target = link.target; - form.innerHTML = formContent; - form.style.display = 'none'; - document.body.appendChild(form); - form.querySelector('[type="submit"]').click(); - return stopEverything(e); - }; - - }).call(this); - (function() { - var ajax, fire, getData, isCrossDomain, isRemote, matches, serializeElement, setData, stopEverything, - slice = [].slice; - - matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, fire = Rails.fire, stopEverything = Rails.stopEverything, ajax = Rails.ajax, isCrossDomain = Rails.isCrossDomain, serializeElement = Rails.serializeElement; - - isRemote = function(element) { - var value; - value = element.getAttribute('data-remote'); - return (value != null) && value !== 'false'; - }; - - Rails.handleRemote = function(e) { - var button, data, dataType, element, method, url, withCredentials; - element = this; - if (!isRemote(element)) { - return true; - } - if (!fire(element, 'ajax:before')) { - fire(element, 'ajax:stopped'); - return false; - } - withCredentials = element.getAttribute('data-with-credentials'); - dataType = element.getAttribute('data-type') || 'script'; - if (matches(element, Rails.formSubmitSelector)) { - button = getData(element, 'ujs:submit-button'); - method = getData(element, 'ujs:submit-button-formmethod') || element.method; - url = getData(element, 'ujs:submit-button-formaction') || element.getAttribute('action') || location.href; - if (method.toUpperCase() === 'GET') { - url = url.replace(/\?.*$/, ''); - } - if (element.enctype === 'multipart/form-data') { - data = new FormData(element); - if (button != null) { - data.append(button.name, button.value); - } - } else { - data = serializeElement(element, button); - } - setData(element, 'ujs:submit-button', null); - setData(element, 'ujs:submit-button-formmethod', null); - setData(element, 'ujs:submit-button-formaction', null); - } else if (matches(element, Rails.buttonClickSelector) || matches(element, Rails.inputChangeSelector)) { - method = element.getAttribute('data-method'); - url = element.getAttribute('data-url'); - data = serializeElement(element, element.getAttribute('data-params')); - } else { - method = element.getAttribute('data-method'); - url = Rails.href(element); - data = element.getAttribute('data-params'); - } - ajax({ - type: method || 'GET', - url: url, - data: data, - dataType: dataType, - beforeSend: function(xhr, options) { - if (fire(element, 'ajax:beforeSend', [xhr, options])) { - return fire(element, 'ajax:send', [xhr]); - } else { - fire(element, 'ajax:stopped'); - return false; - } - }, - success: function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return fire(element, 'ajax:success', args); - }, - error: function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return fire(element, 'ajax:error', args); - }, - complete: function() { - var args; - args = 1 <= arguments.length ? slice.call(arguments, 0) : []; - return fire(element, 'ajax:complete', args); - }, - crossDomain: isCrossDomain(url), - withCredentials: (withCredentials != null) && withCredentials !== 'false' - }); - return stopEverything(e); - }; - - Rails.formSubmitButtonClick = function(e) { - var button, form; - button = this; - form = button.form; - if (!form) { - return; - } - if (button.name) { - setData(form, 'ujs:submit-button', { - name: button.name, - value: button.value - }); - } - setData(form, 'ujs:formnovalidate-button', button.formNoValidate); - setData(form, 'ujs:submit-button-formaction', button.getAttribute('formaction')); - return setData(form, 'ujs:submit-button-formmethod', button.getAttribute('formmethod')); - }; - - Rails.handleMetaClick = function(e) { - var data, link, metaClick, method; - link = this; - method = (link.getAttribute('data-method') || 'GET').toUpperCase(); - data = link.getAttribute('data-params'); - metaClick = e.metaKey || e.ctrlKey; - if (metaClick && method === 'GET' && !data) { - return e.stopImmediatePropagation(); - } - }; - - }).call(this); - (function() { - var $, CSRFProtection, delegate, disableElement, enableElement, fire, formSubmitButtonClick, getData, handleConfirm, handleDisabledElement, handleMetaClick, handleMethod, handleRemote, refreshCSRFTokens; - - fire = Rails.fire, delegate = Rails.delegate, getData = Rails.getData, $ = Rails.$, refreshCSRFTokens = Rails.refreshCSRFTokens, CSRFProtection = Rails.CSRFProtection, enableElement = Rails.enableElement, disableElement = Rails.disableElement, handleDisabledElement = Rails.handleDisabledElement, handleConfirm = Rails.handleConfirm, handleRemote = Rails.handleRemote, formSubmitButtonClick = Rails.formSubmitButtonClick, handleMetaClick = Rails.handleMetaClick, handleMethod = Rails.handleMethod; - - if ((typeof jQuery !== "undefined" && jQuery !== null) && (jQuery.ajax != null) && !jQuery.rails) { - jQuery.rails = Rails; - jQuery.ajaxPrefilter(function(options, originalOptions, xhr) { - if (!options.crossDomain) { - return CSRFProtection(xhr); - } - }); - } - - Rails.start = function() { - if (window._rails_loaded) { - throw new Error('rails-ujs has already been loaded!'); - } - window.addEventListener('pageshow', function() { - $(Rails.formEnableSelector).forEach(function(el) { - if (getData(el, 'ujs:disabled')) { - return enableElement(el); - } - }); - return $(Rails.linkDisableSelector).forEach(function(el) { - if (getData(el, 'ujs:disabled')) { - return enableElement(el); - } - }); - }); - delegate(document, Rails.linkDisableSelector, 'ajax:complete', enableElement); - delegate(document, Rails.linkDisableSelector, 'ajax:stopped', enableElement); - delegate(document, Rails.buttonDisableSelector, 'ajax:complete', enableElement); - delegate(document, Rails.buttonDisableSelector, 'ajax:stopped', enableElement); - delegate(document, Rails.linkClickSelector, 'click', handleDisabledElement); - delegate(document, Rails.linkClickSelector, 'click', handleConfirm); - delegate(document, Rails.linkClickSelector, 'click', handleMetaClick); - delegate(document, Rails.linkClickSelector, 'click', disableElement); - delegate(document, Rails.linkClickSelector, 'click', handleRemote); - delegate(document, Rails.linkClickSelector, 'click', handleMethod); - delegate(document, Rails.buttonClickSelector, 'click', handleDisabledElement); - delegate(document, Rails.buttonClickSelector, 'click', handleConfirm); - delegate(document, Rails.buttonClickSelector, 'click', disableElement); - delegate(document, Rails.buttonClickSelector, 'click', handleRemote); - delegate(document, Rails.inputChangeSelector, 'change', handleDisabledElement); - delegate(document, Rails.inputChangeSelector, 'change', handleConfirm); - delegate(document, Rails.inputChangeSelector, 'change', handleRemote); - delegate(document, Rails.formSubmitSelector, 'submit', handleDisabledElement); - delegate(document, Rails.formSubmitSelector, 'submit', handleConfirm); - delegate(document, Rails.formSubmitSelector, 'submit', handleRemote); - delegate(document, Rails.formSubmitSelector, 'submit', function(e) { - return setTimeout((function() { - return disableElement(e); - }), 13); - }); - delegate(document, Rails.formSubmitSelector, 'ajax:send', disableElement); - delegate(document, Rails.formSubmitSelector, 'ajax:complete', enableElement); - delegate(document, Rails.formInputClickSelector, 'click', handleDisabledElement); - delegate(document, Rails.formInputClickSelector, 'click', handleConfirm); - delegate(document, Rails.formInputClickSelector, 'click', formSubmitButtonClick); - document.addEventListener('DOMContentLoaded', refreshCSRFTokens); - return window._rails_loaded = true; - }; - - if (window.Rails === Rails && fire(document, 'rails:attachBindings')) { - Rails.start(); - } - - }).call(this); - }).call(this); - - if (typeof module === "object" && module.exports) { - module.exports = Rails; - } else if (typeof define === "function" && define.amd) { - define(Rails); - } -}).call(this); diff --git a/debian/gems-compat/activejob-5.1.7/CHANGELOG.md b/debian/gems-compat/activejob-5.1.7/CHANGELOG.md deleted file mode 100644 index 395e5c2ea8..0000000000 --- a/debian/gems-compat/activejob-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,129 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* No changes. - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* Do not deserialize GlobalID objects that were not generated by Active Job. - - Trusting any GlobaID object when deserializing jobs can allow attackers to access - information that should not be accessible to them. - - Fix CVE-2018-16476. - - *Rafael Mendonça França* - - -## Rails 5.1.6 (March 29, 2018) ## - -* No changes. - - -## Rails 5.1.5 (February 14, 2018) ## - -* Support redis-rb 4.0. - - *Jeremy Daer* - - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* No changes. - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* No changes. - - -## Rails 5.1.2 (June 26, 2017) ## - -* No changes. - - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* Change logging instrumentation to log errors when a job raises an exception. - - Fixes #26848. - - *Steven Bull* - -* Correctly set test adapter when configure the queue adapter on a per job. - - Fixes #26360. - - *Yuji Yaginuma* - -* Removed deprecated support to passing the adapter class to `.queue_adapter`. - - *Rafael Mendonça França* - -* Removed deprecated `#original_exception` in `ActiveJob::DeserializationError`. - - *Rafael Mendonça França* - -* Added instance variable `@queue` to JobWrapper. - - This will fix issues in [resque-scheduler](https://github.com/resque/resque-scheduler) `#job_to_hash` method, - so we can use `#enqueue_delayed_selection`, `#remove_delayed` method in resque-scheduler smoothly. - - *mu29* - -* Yield the job instance so you have access to things like `job.arguments` on the custom logic after retries fail. - - *DHH* - -* Added declarative exception handling via `ActiveJob::Base.retry_on` and `ActiveJob::Base.discard_on`. - - Examples: - - class RemoteServiceJob < ActiveJob::Base - retry_on CustomAppException # defaults to 3s wait, 5 attempts - retry_on AnotherCustomAppException, wait: ->(executions) { executions * 2 } - retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3 - retry_on Net::OpenTimeout, wait: :exponentially_longer, attempts: 10 - discard_on ActiveJob::DeserializationError - - def perform(*args) - # Might raise CustomAppException or AnotherCustomAppException for something domain specific - # Might raise ActiveRecord::Deadlocked when a local db deadlock is detected - # Might raise Net::OpenTimeout when the remote service is down - end - end - - *DHH* - - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activejob/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/activejob-5.1.7/MIT-LICENSE b/debian/gems-compat/activejob-5.1.7/MIT-LICENSE deleted file mode 100644 index daa726b9f0..0000000000 --- a/debian/gems-compat/activejob-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2014-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/debian/gems-compat/activejob-5.1.7/README.md b/debian/gems-compat/activejob-5.1.7/README.md deleted file mode 100644 index 8becac7753..0000000000 --- a/debian/gems-compat/activejob-5.1.7/README.md +++ /dev/null @@ -1,126 +0,0 @@ -# Active Job -- Make work happen later - -Active Job is a framework for declaring jobs and making them run on a variety -of queueing backends. These jobs can be everything from regularly scheduled -clean-ups, to billing charges, to mailings. Anything that can be chopped up into -small units of work and run in parallel, really. - -It also serves as the backend for Action Mailer's #deliver_later functionality -that makes it easy to turn any mailing into a job for running later. That's -one of the most common jobs in a modern web application: sending emails outside -of the request-response cycle, so the user doesn't have to wait on it. - -The main point is to ensure that all Rails apps will have a job infrastructure -in place, even if it's in the form of an "immediate runner". We can then have -framework features and other gems build on top of that, without having to worry -about API differences between Delayed Job and Resque. Picking your queuing -backend becomes more of an operational concern, then. And you'll be able to -switch between them without having to rewrite your jobs. - - -## Usage - -To learn how to use your preferred queueing backend see its adapter -documentation at -[ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html). - -Declare a job like so: - -```ruby -class MyJob < ActiveJob::Base - queue_as :my_jobs - - def perform(record) - record.do_work - end -end -``` - -Enqueue a job like so: - -```ruby -MyJob.perform_later record # Enqueue a job to be performed as soon as the queueing system is free. -``` - -```ruby -MyJob.set(wait_until: Date.tomorrow.noon).perform_later(record) # Enqueue a job to be performed tomorrow at noon. -``` - -```ruby -MyJob.set(wait: 1.week).perform_later(record) # Enqueue a job to be performed 1 week from now. -``` - -That's it! - - -## GlobalID support - -Active Job supports [GlobalID serialization](https://github.com/rails/globalid/) for parameters. This makes it possible -to pass live Active Record objects to your job instead of class/id pairs, which -you then have to manually deserialize. Before, jobs would look like this: - -```ruby -class TrashableCleanupJob - def perform(trashable_class, trashable_id, depth) - trashable = trashable_class.constantize.find(trashable_id) - trashable.cleanup(depth) - end -end -``` - -Now you can simply do: - -```ruby -class TrashableCleanupJob - def perform(trashable, depth) - trashable.cleanup(depth) - end -end -``` - -This works with any class that mixes in GlobalID::Identification, which -by default has been mixed into Active Record classes. - - -## Supported queueing systems - -Active Job has built-in adapters for multiple queueing backends (Sidekiq, -Resque, Delayed Job and others). To get an up-to-date list of the adapters -see the API Documentation for [ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html). - -## Auxiliary gems - -* [activejob-stats](https://github.com/seuros/activejob-stats) - -## Download and installation - -The latest version of Active Job can be installed with RubyGems: - -``` - $ gem install activejob -``` - -Source code can be downloaded as part of the Rails project on GitHub - -* https://github.com/rails/rails/tree/master/activejob - -## License - -Active Job is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -## Support - -API documentation is at: - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/activejob-5.1.7/activejob.gemspec b/debian/gems-compat/activejob-5.1.7/activejob.gemspec deleted file mode 100644 index 83b2fb9d6d..0000000000 --- a/debian/gems-compat/activejob-5.1.7/activejob.gemspec +++ /dev/null @@ -1,39 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: activejob 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "activejob".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/activejob/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/activejob" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "Declare job classes that can be run by a variety of queueing backends.".freeze - s.email = "david@loudthinking.com".freeze - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.md".freeze, "lib/active_job.rb".freeze, "lib/active_job/arguments.rb".freeze, "lib/active_job/base.rb".freeze, "lib/active_job/callbacks.rb".freeze, "lib/active_job/configured_job.rb".freeze, "lib/active_job/core.rb".freeze, "lib/active_job/enqueuing.rb".freeze, "lib/active_job/exceptions.rb".freeze, "lib/active_job/execution.rb".freeze, "lib/active_job/gem_version.rb".freeze, "lib/active_job/logging.rb".freeze, "lib/active_job/queue_adapter.rb".freeze, "lib/active_job/queue_adapters.rb".freeze, "lib/active_job/queue_adapters/async_adapter.rb".freeze, "lib/active_job/queue_adapters/backburner_adapter.rb".freeze, "lib/active_job/queue_adapters/delayed_job_adapter.rb".freeze, "lib/active_job/queue_adapters/inline_adapter.rb".freeze, "lib/active_job/queue_adapters/qu_adapter.rb".freeze, "lib/active_job/queue_adapters/que_adapter.rb".freeze, "lib/active_job/queue_adapters/queue_classic_adapter.rb".freeze, "lib/active_job/queue_adapters/resque_adapter.rb".freeze, "lib/active_job/queue_adapters/sidekiq_adapter.rb".freeze, "lib/active_job/queue_adapters/sneakers_adapter.rb".freeze, "lib/active_job/queue_adapters/sucker_punch_adapter.rb".freeze, "lib/active_job/queue_adapters/test_adapter.rb".freeze, "lib/active_job/queue_name.rb".freeze, "lib/active_job/queue_priority.rb".freeze, "lib/active_job/railtie.rb".freeze, "lib/active_job/test_case.rb".freeze, "lib/active_job/test_helper.rb".freeze, "lib/active_job/translation.rb".freeze, "lib/active_job/version.rb".freeze, "lib/rails/generators/job/job_generator.rb".freeze, "lib/rails/generators/job/templates/application_job.rb".freeze, "lib/rails/generators/job/templates/job.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.rubygems_version = "2.7.6.2".freeze - s.summary = "Job framework with pluggable queues.".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, [">= 0.3.6"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 0.3.6"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 0.3.6"]) - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job.rb deleted file mode 100644 index 8b7aef65a2..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job.rb +++ /dev/null @@ -1,37 +0,0 @@ -#-- -# Copyright (c) 2014-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "active_support" -require "active_support/rails" -require "active_job/version" -require "global_id" - -module ActiveJob - extend ActiveSupport::Autoload - - autoload :Base - autoload :QueueAdapters - autoload :ConfiguredJob - autoload :TestCase - autoload :TestHelper -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/arguments.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/arguments.rb deleted file mode 100644 index d936b369ca..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/arguments.rb +++ /dev/null @@ -1,154 +0,0 @@ -require "active_support/core_ext/hash" - -module ActiveJob - # Raised when an exception is raised during job arguments deserialization. - # - # Wraps the original exception raised as +cause+. - class DeserializationError < StandardError - def initialize #:nodoc: - super("Error while trying to deserialize arguments: #{$!.message}") - set_backtrace $!.backtrace - end - end - - # Raised when an unsupported argument type is set as a job argument. We - # currently support NilClass, Integer, Fixnum, Float, String, TrueClass, FalseClass, - # Bignum, BigDecimal, and objects that can be represented as GlobalIDs (ex: Active Record). - # Raised if you set the key for a Hash something else than a string or - # a symbol. Also raised when trying to serialize an object which can't be - # identified with a Global ID - such as an unpersisted Active Record model. - class SerializationError < ArgumentError; end - - module Arguments - extend self - # :nodoc: - TYPE_WHITELIST = [ NilClass, String, Integer, Float, BigDecimal, TrueClass, FalseClass ] - TYPE_WHITELIST.push(Fixnum, Bignum) unless 1.class == Integer - - # Serializes a set of arguments. Whitelisted types are returned - # as-is. Arrays/Hashes are serialized element by element. - # All other types are serialized using GlobalID. - def serialize(arguments) - arguments.map { |argument| serialize_argument(argument) } - end - - # Deserializes a set of arguments. Whitelisted types are returned - # as-is. Arrays/Hashes are deserialized element by element. - # All other types are deserialized using GlobalID. - def deserialize(arguments) - arguments.map { |argument| deserialize_argument(argument) } - rescue - raise DeserializationError - end - - private - # :nodoc: - GLOBALID_KEY = "_aj_globalid".freeze - # :nodoc: - SYMBOL_KEYS_KEY = "_aj_symbol_keys".freeze - # :nodoc: - WITH_INDIFFERENT_ACCESS_KEY = "_aj_hash_with_indifferent_access".freeze - private_constant :GLOBALID_KEY, :SYMBOL_KEYS_KEY, :WITH_INDIFFERENT_ACCESS_KEY - - def serialize_argument(argument) - case argument - when *TYPE_WHITELIST - argument - when GlobalID::Identification - convert_to_global_id_hash(argument) - when Array - argument.map { |arg| serialize_argument(arg) } - when ActiveSupport::HashWithIndifferentAccess - result = serialize_hash(argument) - result[WITH_INDIFFERENT_ACCESS_KEY] = serialize_argument(true) - result - when Hash - symbol_keys = argument.each_key.grep(Symbol).map(&:to_s) - result = serialize_hash(argument) - result[SYMBOL_KEYS_KEY] = symbol_keys - result - else - raise SerializationError.new("Unsupported argument type: #{argument.class.name}") - end - end - - def deserialize_argument(argument) - case argument - when String - argument - when *TYPE_WHITELIST - argument - when Array - argument.map { |arg| deserialize_argument(arg) } - when Hash - if serialized_global_id?(argument) - deserialize_global_id argument - else - deserialize_hash(argument) - end - else - raise ArgumentError, "Can only deserialize primitive arguments: #{argument.inspect}" - end - end - - def serialized_global_id?(hash) - hash.size == 1 && hash.include?(GLOBALID_KEY) - end - - def deserialize_global_id(hash) - GlobalID::Locator.locate hash[GLOBALID_KEY] - end - - def serialize_hash(argument) - argument.each_with_object({}) do |(key, value), hash| - hash[serialize_hash_key(key)] = serialize_argument(value) - end - end - - def deserialize_hash(serialized_hash) - result = serialized_hash.transform_values { |v| deserialize_argument(v) } - if result.delete(WITH_INDIFFERENT_ACCESS_KEY) - result = result.with_indifferent_access - elsif symbol_keys = result.delete(SYMBOL_KEYS_KEY) - result = transform_symbol_keys(result, symbol_keys) - end - result - end - - # :nodoc: - RESERVED_KEYS = [ - GLOBALID_KEY, GLOBALID_KEY.to_sym, - SYMBOL_KEYS_KEY, SYMBOL_KEYS_KEY.to_sym, - WITH_INDIFFERENT_ACCESS_KEY, WITH_INDIFFERENT_ACCESS_KEY.to_sym, - ] - private_constant :RESERVED_KEYS - - def serialize_hash_key(key) - case key - when *RESERVED_KEYS - raise SerializationError.new("Can't serialize a Hash with reserved key #{key.inspect}") - when String, Symbol - key.to_s - else - raise SerializationError.new("Only string and symbol hash keys may be serialized as job arguments, but #{key.inspect} is a #{key.class}") - end - end - - def transform_symbol_keys(hash, symbol_keys) - hash.transform_keys do |key| - if symbol_keys.include?(key) - key.to_sym - else - key - end - end - end - - def convert_to_global_id_hash(argument) - { GLOBALID_KEY => argument.to_global_id.to_s } - rescue URI::GID::MissingModelIdError - raise SerializationError, "Unable to serialize #{argument.class} " \ - "without an id. (Maybe you forgot to call save?)" - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/base.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/base.rb deleted file mode 100644 index 18e8641e50..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/base.rb +++ /dev/null @@ -1,72 +0,0 @@ -require "active_job/core" -require "active_job/queue_adapter" -require "active_job/queue_name" -require "active_job/queue_priority" -require "active_job/enqueuing" -require "active_job/execution" -require "active_job/callbacks" -require "active_job/exceptions" -require "active_job/logging" -require "active_job/translation" - -module ActiveJob #:nodoc: - # = Active Job - # - # Active Job objects can be configured to work with different backend - # queuing frameworks. To specify a queue adapter to use: - # - # ActiveJob::Base.queue_adapter = :inline - # - # A list of supported adapters can be found in QueueAdapters. - # - # Active Job objects can be defined by creating a class that inherits - # from the ActiveJob::Base class. The only necessary method to - # implement is the "perform" method. - # - # To define an Active Job object: - # - # class ProcessPhotoJob < ActiveJob::Base - # def perform(photo) - # photo.watermark!('Rails') - # photo.rotate!(90.degrees) - # photo.resize_to_fit!(300, 300) - # photo.upload! - # end - # end - # - # Records that are passed in are serialized/deserialized using Global - # ID. More information can be found in Arguments. - # - # To enqueue a job to be performed as soon as the queueing system is free: - # - # ProcessPhotoJob.perform_later(photo) - # - # To enqueue a job to be processed at some point in the future: - # - # ProcessPhotoJob.set(wait_until: Date.tomorrow.noon).perform_later(photo) - # - # More information can be found in ActiveJob::Core::ClassMethods#set - # - # A job can also be processed immediately without sending to the queue: - # - # ProcessPhotoJob.perform_now(photo) - # - # == Exceptions - # - # * DeserializationError - Error class for deserialization errors. - # * SerializationError - Error class for serialization errors. - class Base - include Core - include QueueAdapter - include QueueName - include QueuePriority - include Enqueuing - include Execution - include Callbacks - include Exceptions - include Logging - include Translation - - ActiveSupport.run_load_hooks(:active_job, self) - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/callbacks.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/callbacks.rb deleted file mode 100644 index d5b17de8b5..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/callbacks.rb +++ /dev/null @@ -1,151 +0,0 @@ -require "active_support/callbacks" - -module ActiveJob - # = Active Job Callbacks - # - # Active Job provides hooks during the life cycle of a job. Callbacks allow you - # to trigger logic during the life cycle of a job. Available callbacks are: - # - # * before_enqueue - # * around_enqueue - # * after_enqueue - # * before_perform - # * around_perform - # * after_perform - # - module Callbacks - extend ActiveSupport::Concern - include ActiveSupport::Callbacks - - class << self - include ActiveSupport::Callbacks - define_callbacks :execute - end - - included do - define_callbacks :perform - define_callbacks :enqueue - end - - # These methods will be included into any Active Job object, adding - # callbacks for +perform+ and +enqueue+ methods. - module ClassMethods - # Defines a callback that will get called right before the - # job's perform method is executed. - # - # class VideoProcessJob < ActiveJob::Base - # queue_as :default - # - # before_perform do |job| - # UserMailer.notify_video_started_processing(job.arguments.first) - # end - # - # def perform(video_id) - # Video.find(video_id).process - # end - # end - # - def before_perform(*filters, &blk) - set_callback(:perform, :before, *filters, &blk) - end - - # Defines a callback that will get called right after the - # job's perform method has finished. - # - # class VideoProcessJob < ActiveJob::Base - # queue_as :default - # - # after_perform do |job| - # UserMailer.notify_video_processed(job.arguments.first) - # end - # - # def perform(video_id) - # Video.find(video_id).process - # end - # end - # - def after_perform(*filters, &blk) - set_callback(:perform, :after, *filters, &blk) - end - - # Defines a callback that will get called around the job's perform method. - # - # class VideoProcessJob < ActiveJob::Base - # queue_as :default - # - # around_perform do |job, block| - # UserMailer.notify_video_started_processing(job.arguments.first) - # block.call - # UserMailer.notify_video_processed(job.arguments.first) - # end - # - # def perform(video_id) - # Video.find(video_id).process - # end - # end - # - def around_perform(*filters, &blk) - set_callback(:perform, :around, *filters, &blk) - end - - # Defines a callback that will get called right before the - # job is enqueued. - # - # class VideoProcessJob < ActiveJob::Base - # queue_as :default - # - # before_enqueue do |job| - # $statsd.increment "enqueue-video-job.try" - # end - # - # def perform(video_id) - # Video.find(video_id).process - # end - # end - # - def before_enqueue(*filters, &blk) - set_callback(:enqueue, :before, *filters, &blk) - end - - # Defines a callback that will get called right after the - # job is enqueued. - # - # class VideoProcessJob < ActiveJob::Base - # queue_as :default - # - # after_enqueue do |job| - # $statsd.increment "enqueue-video-job.success" - # end - # - # def perform(video_id) - # Video.find(video_id).process - # end - # end - # - def after_enqueue(*filters, &blk) - set_callback(:enqueue, :after, *filters, &blk) - end - - # Defines a callback that will get called around the enqueueing - # of the job. - # - # class VideoProcessJob < ActiveJob::Base - # queue_as :default - # - # around_enqueue do |job, block| - # $statsd.time "video-job.process" do - # block.call - # end - # end - # - # def perform(video_id) - # Video.find(video_id).process - # end - # end - # - def around_enqueue(*filters, &blk) - set_callback(:enqueue, :around, *filters, &blk) - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/configured_job.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/configured_job.rb deleted file mode 100644 index 2ff31f2dae..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/configured_job.rb +++ /dev/null @@ -1,16 +0,0 @@ -module ActiveJob - class ConfiguredJob #:nodoc: - def initialize(job_class, options = {}) - @options = options - @job_class = job_class - end - - def perform_now(*args) - @job_class.new(*args).perform_now - end - - def perform_later(*args) - @job_class.new(*args).enqueue @options - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/core.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/core.rb deleted file mode 100644 index e3e63f227e..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/core.rb +++ /dev/null @@ -1,138 +0,0 @@ -module ActiveJob - # Provides general behavior that will be included into every Active Job - # object that inherits from ActiveJob::Base. - module Core - extend ActiveSupport::Concern - - included do - # Job arguments - attr_accessor :arguments - attr_writer :serialized_arguments - - # Timestamp when the job should be performed - attr_accessor :scheduled_at - - # Job Identifier - attr_accessor :job_id - - # Queue in which the job will reside. - attr_writer :queue_name - - # Priority that the job will have (lower is more priority). - attr_writer :priority - - # ID optionally provided by adapter - attr_accessor :provider_job_id - - # Number of times this job has been executed (which increments on every retry, like after an exception). - attr_accessor :executions - - # I18n.locale to be used during the job. - attr_accessor :locale - end - - # These methods will be included into any Active Job object, adding - # helpers for de/serialization and creation of job instances. - module ClassMethods - # Creates a new job instance from a hash created with +serialize+ - def deserialize(job_data) - job = job_data["job_class"].constantize.new - job.deserialize(job_data) - job - end - - # Creates a job preconfigured with the given options. You can call - # perform_later with the job arguments to enqueue the job with the - # preconfigured options - # - # ==== Options - # * :wait - Enqueues the job with the specified delay - # * :wait_until - Enqueues the job at the time specified - # * :queue - Enqueues the job on the specified queue - # * :priority - Enqueues the job with the specified priority - # - # ==== Examples - # - # VideoJob.set(queue: :some_queue).perform_later(Video.last) - # VideoJob.set(wait: 5.minutes).perform_later(Video.last) - # VideoJob.set(wait_until: Time.now.tomorrow).perform_later(Video.last) - # VideoJob.set(queue: :some_queue, wait: 5.minutes).perform_later(Video.last) - # VideoJob.set(queue: :some_queue, wait_until: Time.now.tomorrow).perform_later(Video.last) - # VideoJob.set(queue: :some_queue, wait: 5.minutes, priority: 10).perform_later(Video.last) - def set(options = {}) - ConfiguredJob.new(self, options) - end - end - - # Creates a new job instance. Takes the arguments that will be - # passed to the perform method. - def initialize(*arguments) - @arguments = arguments - @job_id = SecureRandom.uuid - @queue_name = self.class.queue_name - @priority = self.class.priority - @executions = 0 - end - - # Returns a hash with the job data that can safely be passed to the - # queueing adapter. - def serialize - { - "job_class" => self.class.name, - "job_id" => job_id, - "provider_job_id" => provider_job_id, - "queue_name" => queue_name, - "priority" => priority, - "arguments" => serialize_arguments(arguments), - "executions" => executions, - "locale" => I18n.locale.to_s - } - end - - # Attaches the stored job data to the current instance. Receives a hash - # returned from +serialize+ - # - # ==== Examples - # - # class DeliverWebhookJob < ActiveJob::Base - # def serialize - # super.merge('attempt_number' => (@attempt_number || 0) + 1) - # end - # - # def deserialize(job_data) - # super - # @attempt_number = job_data['attempt_number'] - # end - # - # rescue_from(TimeoutError) do |exception| - # raise exception if @attempt_number > 5 - # retry_job(wait: 10) - # end - # end - def deserialize(job_data) - self.job_id = job_data["job_id"] - self.provider_job_id = job_data["provider_job_id"] - self.queue_name = job_data["queue_name"] - self.priority = job_data["priority"] - self.serialized_arguments = job_data["arguments"] - self.executions = job_data["executions"] - self.locale = job_data["locale"] || I18n.locale.to_s - end - - private - def deserialize_arguments_if_needed - if defined?(@serialized_arguments) && @serialized_arguments.present? - @arguments = deserialize_arguments(@serialized_arguments) - @serialized_arguments = nil - end - end - - def serialize_arguments(serialized_args) - Arguments.serialize(serialized_args) - end - - def deserialize_arguments(serialized_args) - Arguments.deserialize(serialized_args) - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/enqueuing.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/enqueuing.rb deleted file mode 100644 index c73117e7f3..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/enqueuing.rb +++ /dev/null @@ -1,57 +0,0 @@ -require "active_job/arguments" - -module ActiveJob - # Provides behavior for enqueuing jobs. - module Enqueuing - extend ActiveSupport::Concern - - # Includes the +perform_later+ method for job initialization. - module ClassMethods - # Push a job onto the queue. The arguments must be legal JSON types - # (string, int, float, nil, true, false, hash or array) or - # GlobalID::Identification instances. Arbitrary Ruby objects - # are not supported. - # - # Returns an instance of the job class queued with arguments available in - # Job#arguments. - def perform_later(*args) - job_or_instantiate(*args).enqueue - end - - private - def job_or_instantiate(*args) # :doc: - args.first.is_a?(self) ? args.first : new(*args) - end - end - - # Enqueues the job to be performed by the queue adapter. - # - # ==== Options - # * :wait - Enqueues the job with the specified delay - # * :wait_until - Enqueues the job at the time specified - # * :queue - Enqueues the job on the specified queue - # * :priority - Enqueues the job with the specified priority - # - # ==== Examples - # - # my_job_instance.enqueue - # my_job_instance.enqueue wait: 5.minutes - # my_job_instance.enqueue queue: :important - # my_job_instance.enqueue wait_until: Date.tomorrow.midnight - # my_job_instance.enqueue priority: 10 - def enqueue(options = {}) - self.scheduled_at = options[:wait].seconds.from_now.to_f if options[:wait] - self.scheduled_at = options[:wait_until].to_f if options[:wait_until] - self.queue_name = self.class.queue_name_from_part(options[:queue]) if options[:queue] - self.priority = options[:priority].to_i if options[:priority] - run_callbacks :enqueue do - if scheduled_at - self.class.queue_adapter.enqueue_at self, scheduled_at - else - self.class.queue_adapter.enqueue self - end - end - self - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/exceptions.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/exceptions.rb deleted file mode 100644 index c1b5d35313..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/exceptions.rb +++ /dev/null @@ -1,122 +0,0 @@ -require "active_support/core_ext/numeric/time" - -module ActiveJob - # Provides behavior for retrying and discarding jobs on exceptions. - module Exceptions - extend ActiveSupport::Concern - - module ClassMethods - # Catch the exception and reschedule job for re-execution after so many seconds, for a specific number of attempts. - # If the exception keeps getting raised beyond the specified number of attempts, the exception is allowed to - # bubble up to the underlying queuing system, which may have its own retry mechanism or place it in a - # holding queue for inspection. - # - # You can also pass a block that'll be invoked if the retry attempts fail for custom logic rather than letting - # the exception bubble up. This block is yielded with the job instance as the first and the error instance as the second parameter. - # - # ==== Options - # * :wait - Re-enqueues the job with a delay specified either in seconds (default: 3 seconds), - # as a computing proc that the number of executions so far as an argument, or as a symbol reference of - # :exponentially_longer, which applies the wait algorithm of (executions ** 4) + 2 - # (first wait 3s, then 18s, then 83s, etc) - # * :attempts - Re-enqueues the job the specified number of times (default: 5 attempts) - # * :queue - Re-enqueues the job on a different queue - # * :priority - Re-enqueues the job with a different priority - # - # ==== Examples - # - # class RemoteServiceJob < ActiveJob::Base - # retry_on CustomAppException # defaults to 3s wait, 5 attempts - # retry_on AnotherCustomAppException, wait: ->(executions) { executions * 2 } - # retry_on(YetAnotherCustomAppException) do |job, exception| - # ExceptionNotifier.caught(exception) - # end - # retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3 - # retry_on Net::OpenTimeout, wait: :exponentially_longer, attempts: 10 - # - # def perform(*args) - # # Might raise CustomAppException, AnotherCustomAppException, or YetAnotherCustomAppException for something domain specific - # # Might raise ActiveRecord::Deadlocked when a local db deadlock is detected - # # Might raise Net::OpenTimeout when the remote service is down - # end - # end - def retry_on(exception, wait: 3.seconds, attempts: 5, queue: nil, priority: nil) - rescue_from exception do |error| - if executions < attempts - logger.error "Retrying #{self.class} in #{wait} seconds, due to a #{exception}. The original exception was #{error.cause.inspect}." - retry_job wait: determine_delay(wait), queue: queue, priority: priority - else - if block_given? - yield self, exception - else - logger.error "Stopped retrying #{self.class} due to a #{exception}, which reoccurred on #{executions} attempts. The original exception was #{error.cause.inspect}." - raise error - end - end - end - end - - # Discard the job with no attempts to retry, if the exception is raised. This is useful when the subject of the job, - # like an Active Record, is no longer available, and the job is thus no longer relevant. - # - # ==== Example - # - # class SearchIndexingJob < ActiveJob::Base - # discard_on ActiveJob::DeserializationError - # - # def perform(record) - # # Will raise ActiveJob::DeserializationError if the record can't be deserialized - # end - # end - def discard_on(exception) - rescue_from exception do |error| - logger.error "Discarded #{self.class} due to a #{exception}. The original exception was #{error.cause.inspect}." - end - end - end - - # Reschedules the job to be re-executed. This is useful in combination - # with the +rescue_from+ option. When you rescue an exception from your job - # you can ask Active Job to retry performing your job. - # - # ==== Options - # * :wait - Enqueues the job with the specified delay in seconds - # * :wait_until - Enqueues the job at the time specified - # * :queue - Enqueues the job on the specified queue - # * :priority - Enqueues the job with the specified priority - # - # ==== Examples - # - # class SiteScraperJob < ActiveJob::Base - # rescue_from(ErrorLoadingSite) do - # retry_job queue: :low_priority - # end - # - # def perform(*args) - # # raise ErrorLoadingSite if cannot scrape - # end - # end - def retry_job(options = {}) - enqueue options - end - - private - def determine_delay(seconds_or_duration_or_algorithm) - case seconds_or_duration_or_algorithm - when :exponentially_longer - (executions**4) + 2 - when ActiveSupport::Duration - duration = seconds_or_duration_or_algorithm - duration.to_i - when Integer - seconds = seconds_or_duration_or_algorithm - seconds - when Proc - algorithm = seconds_or_duration_or_algorithm - algorithm.call(executions) - else - raise "Couldn't determine a delay based on #{seconds_or_duration_or_algorithm.inspect}" - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/execution.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/execution.rb deleted file mode 100644 index 94d30c8eaf..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/execution.rb +++ /dev/null @@ -1,47 +0,0 @@ -require "active_support/rescuable" -require "active_job/arguments" - -module ActiveJob - module Execution - extend ActiveSupport::Concern - include ActiveSupport::Rescuable - - # Includes methods for executing and performing jobs instantly. - module ClassMethods - # Performs the job immediately. - # - # MyJob.perform_now("mike") - # - def perform_now(*args) - job_or_instantiate(*args).perform_now - end - - def execute(job_data) #:nodoc: - ActiveJob::Callbacks.run_callbacks(:execute) do - job = deserialize(job_data) - job.perform_now - end - end - end - - # Performs the job immediately. The job is not sent to the queueing adapter - # but directly executed by blocking the execution of others until it's finished. - # - # MyJob.new(*args).perform_now - def perform_now - deserialize_arguments_if_needed - run_callbacks :perform do - # Guard against jobs that were persisted before we started counting executions by zeroing out nil counters - self.executions = (executions || 0) + 1 - - perform(*arguments) - end - rescue => exception - rescue_with_handler(exception) || raise - end - - def perform(*) - fail NotImplementedError - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/gem_version.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/gem_version.rb deleted file mode 100644 index 37f3e9c36b..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveJob - # Returns the version of the currently loaded Active Job as a Gem::Version - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/logging.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/logging.rb deleted file mode 100644 index f46d5c68a8..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/logging.rb +++ /dev/null @@ -1,128 +0,0 @@ -require "active_support/core_ext/hash/transform_values" -require "active_support/core_ext/string/filters" -require "active_support/tagged_logging" -require "active_support/logger" - -module ActiveJob - module Logging #:nodoc: - extend ActiveSupport::Concern - - included do - cattr_accessor(:logger) { ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDOUT)) } - - around_enqueue do |_, block, _| - tag_logger do - block.call - end - end - - around_perform do |job, block, _| - tag_logger(job.class.name, job.job_id) do - payload = { adapter: job.class.queue_adapter, job: job } - ActiveSupport::Notifications.instrument("perform_start.active_job", payload.dup) - ActiveSupport::Notifications.instrument("perform.active_job", payload) do - block.call - end - end - end - - after_enqueue do |job| - if job.scheduled_at - ActiveSupport::Notifications.instrument "enqueue_at.active_job", - adapter: job.class.queue_adapter, job: job - else - ActiveSupport::Notifications.instrument "enqueue.active_job", - adapter: job.class.queue_adapter, job: job - end - end - end - - private - def tag_logger(*tags) - if logger.respond_to?(:tagged) - tags.unshift "ActiveJob" unless logger_tagged_by_active_job? - logger.tagged(*tags) { yield } - else - yield - end - end - - def logger_tagged_by_active_job? - logger.formatter.current_tags.include?("ActiveJob") - end - - class LogSubscriber < ActiveSupport::LogSubscriber #:nodoc: - def enqueue(event) - info do - job = event.payload[:job] - "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)}" + args_info(job) - end - end - - def enqueue_at(event) - info do - job = event.payload[:job] - "Enqueued #{job.class.name} (Job ID: #{job.job_id}) to #{queue_name(event)} at #{scheduled_at(event)}" + args_info(job) - end - end - - def perform_start(event) - info do - job = event.payload[:job] - "Performing #{job.class.name} (Job ID: #{job.job_id}) from #{queue_name(event)}" + args_info(job) - end - end - - def perform(event) - job = event.payload[:job] - ex = event.payload[:exception_object] - if ex - error do - "Error performing #{job.class.name} (Job ID: #{job.job_id}) from #{queue_name(event)} in #{event.duration.round(2)}ms: #{ex.class} (#{ex.message}):\n" + Array(ex.backtrace).join("\n") - end - else - info do - "Performed #{job.class.name} (Job ID: #{job.job_id}) from #{queue_name(event)} in #{event.duration.round(2)}ms" - end - end - end - - private - def queue_name(event) - event.payload[:adapter].class.name.demodulize.remove("Adapter") + "(#{event.payload[:job].queue_name})" - end - - def args_info(job) - if job.arguments.any? - " with arguments: " + - job.arguments.map { |arg| format(arg).inspect }.join(", ") - else - "" - end - end - - def format(arg) - case arg - when Hash - arg.transform_values { |value| format(value) } - when Array - arg.map { |value| format(value) } - when GlobalID::Identification - arg.to_global_id rescue arg - else - arg - end - end - - def scheduled_at(event) - Time.at(event.payload[:job].scheduled_at).utc - end - - def logger - ActiveJob::Base.logger - end - end - end -end - -ActiveJob::Logging::LogSubscriber.attach_to :active_job diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapter.rb deleted file mode 100644 index 9dae80ffc2..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapter.rb +++ /dev/null @@ -1,51 +0,0 @@ -require "active_support/core_ext/string/inflections" - -module ActiveJob - # The ActiveJob::QueueAdapter module is used to load the - # correct adapter. The default queue adapter is the +:async+ queue. - module QueueAdapter #:nodoc: - extend ActiveSupport::Concern - - included do - class_attribute :_queue_adapter, instance_accessor: false, instance_predicate: false - self.queue_adapter = :async - end - - # Includes the setter method for changing the active queue adapter. - module ClassMethods - # Returns the backend queue provider. The default queue adapter - # is the +:async+ queue. See QueueAdapters for more information. - def queue_adapter - _queue_adapter - end - - # Specify the backend queue provider. The default queue adapter - # is the +:async+ queue. See QueueAdapters for more - # information. - def queue_adapter=(name_or_adapter_or_class) - self._queue_adapter = interpret_adapter(name_or_adapter_or_class) - end - - private - - def interpret_adapter(name_or_adapter_or_class) - case name_or_adapter_or_class - when Symbol, String - ActiveJob::QueueAdapters.lookup(name_or_adapter_or_class).new - else - if queue_adapter?(name_or_adapter_or_class) - name_or_adapter_or_class - else - raise ArgumentError - end - end - end - - QUEUE_ADAPTER_METHODS = [:enqueue, :enqueue_at].freeze - - def queue_adapter?(object) - QUEUE_ADAPTER_METHODS.all? { |meth| object.respond_to?(meth) } - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters.rb deleted file mode 100644 index c8eedb6156..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters.rb +++ /dev/null @@ -1,137 +0,0 @@ -module ActiveJob - # == Active Job adapters - # - # Active Job has adapters for the following queueing backends: - # - # * {Backburner}[https://github.com/nesquena/backburner] - # * {Delayed Job}[https://github.com/collectiveidea/delayed_job] - # * {Qu}[https://github.com/bkeepers/qu] - # * {Que}[https://github.com/chanks/que] - # * {queue_classic}[https://github.com/QueueClassic/queue_classic] - # * {Resque}[https://github.com/resque/resque] - # * {Sidekiq}[http://sidekiq.org] - # * {Sneakers}[https://github.com/jondot/sneakers] - # * {Sucker Punch}[https://github.com/brandonhilkert/sucker_punch] - # * {Active Job Async Job}[http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/AsyncAdapter.html] - # * {Active Job Inline}[http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters/InlineAdapter.html] - # - # === Backends Features - # - # | | Async | Queues | Delayed | Priorities | Timeout | Retries | - # |-------------------|-------|--------|------------|------------|---------|---------| - # | Backburner | Yes | Yes | Yes | Yes | Job | Global | - # | Delayed Job | Yes | Yes | Yes | Job | Global | Global | - # | Qu | Yes | Yes | No | No | No | Global | - # | Que | Yes | Yes | Yes | Job | No | Job | - # | queue_classic | Yes | Yes | Yes* | No | No | No | - # | Resque | Yes | Yes | Yes (Gem) | Queue | Global | Yes | - # | Sidekiq | Yes | Yes | Yes | Queue | No | Job | - # | Sneakers | Yes | Yes | No | Queue | Queue | No | - # | Sucker Punch | Yes | Yes | Yes | No | No | No | - # | Active Job Async | Yes | Yes | Yes | No | No | No | - # | Active Job Inline | No | Yes | N/A | N/A | N/A | N/A | - # - # ==== Async - # - # Yes: The Queue Adapter has the ability to run the job in a non-blocking manner. - # It either runs on a separate or forked process, or on a different thread. - # - # No: The job is run in the same process. - # - # ==== Queues - # - # Yes: Jobs may set which queue they are run in with queue_as or by using the set - # method. - # - # ==== Delayed - # - # Yes: The adapter will run the job in the future through perform_later. - # - # (Gem): An additional gem is required to use perform_later with this adapter. - # - # No: The adapter will run jobs at the next opportunity and cannot use perform_later. - # - # N/A: The adapter does not support queueing. - # - # NOTE: - # queue_classic supports job scheduling since version 3.1. - # For older versions you can use the queue_classic-later gem. - # - # ==== Priorities - # - # The order in which jobs are processed can be configured differently depending - # on the adapter. - # - # Job: Any class inheriting from the adapter may set the priority on the job - # object relative to other jobs. - # - # Queue: The adapter can set the priority for job queues, when setting a queue - # with Active Job this will be respected. - # - # Yes: Allows the priority to be set on the job object, at the queue level or - # as default configuration option. - # - # No: Does not allow the priority of jobs to be configured. - # - # N/A: The adapter does not support queueing, and therefore sorting them. - # - # ==== Timeout - # - # When a job will stop after the allotted time. - # - # Job: The timeout can be set for each instance of the job class. - # - # Queue: The timeout is set for all jobs on the queue. - # - # Global: The adapter is configured that all jobs have a maximum run time. - # - # N/A: This adapter does not run in a separate process, and therefore timeout - # is unsupported. - # - # ==== Retries - # - # Job: The number of retries can be set per instance of the job class. - # - # Yes: The Number of retries can be configured globally, for each instance or - # on the queue. This adapter may also present failed instances of the job class - # that can be restarted. - # - # Global: The adapter has a global number of retries. - # - # N/A: The adapter does not run in a separate process, and therefore doesn't - # support retries. - # - # === Async and Inline Queue Adapters - # - # Active Job has two built-in queue adapters intended for development and - # testing: +:async+ and +:inline+. - module QueueAdapters - extend ActiveSupport::Autoload - - autoload :AsyncAdapter - autoload :InlineAdapter - autoload :BackburnerAdapter - autoload :DelayedJobAdapter - autoload :QuAdapter - autoload :QueAdapter - autoload :QueueClassicAdapter - autoload :ResqueAdapter - autoload :SidekiqAdapter - autoload :SneakersAdapter - autoload :SuckerPunchAdapter - autoload :TestAdapter - - ADAPTER = "Adapter".freeze - private_constant :ADAPTER - - class << self - # Returns adapter for specified name. - # - # ActiveJob::QueueAdapters.lookup(:sidekiq) - # # => ActiveJob::QueueAdapters::SidekiqAdapter - def lookup(name) - const_get(name.to_s.camelize << ADAPTER) - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/async_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/async_adapter.rb deleted file mode 100644 index e2bff9e646..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/async_adapter.rb +++ /dev/null @@ -1,114 +0,0 @@ -require "securerandom" -require "concurrent/scheduled_task" -require "concurrent/executor/thread_pool_executor" -require "concurrent/utility/processor_counter" - -module ActiveJob - module QueueAdapters - # == Active Job Async adapter - # - # The Async adapter runs jobs with an in-process thread pool. - # - # This is the default queue adapter. It's well-suited for dev/test since - # it doesn't need an external infrastructure, but it's a poor fit for - # production since it drops pending jobs on restart. - # - # To use this adapter, set queue adapter to +:async+: - # - # config.active_job.queue_adapter = :async - # - # To configure the adapter's thread pool, instantiate the adapter and - # pass your own config: - # - # config.active_job.queue_adapter = ActiveJob::QueueAdapters::AsyncAdapter.new \ - # min_threads: 1, - # max_threads: 2 * Concurrent.processor_count, - # idletime: 600.seconds - # - # The adapter uses a {Concurrent Ruby}[https://github.com/ruby-concurrency/concurrent-ruby] thread pool to schedule and execute - # jobs. Since jobs share a single thread pool, long-running jobs will block - # short-lived jobs. Fine for dev/test; bad for production. - class AsyncAdapter - # See {Concurrent::ThreadPoolExecutor}[http://ruby-concurrency.github.io/concurrent-ruby/Concurrent/ThreadPoolExecutor.html] for executor options. - def initialize(**executor_options) - @scheduler = Scheduler.new(**executor_options) - end - - def enqueue(job) #:nodoc: - @scheduler.enqueue JobWrapper.new(job), queue_name: job.queue_name - end - - def enqueue_at(job, timestamp) #:nodoc: - @scheduler.enqueue_at JobWrapper.new(job), timestamp, queue_name: job.queue_name - end - - # Gracefully stop processing jobs. Finishes in-progress work and handles - # any new jobs following the executor's fallback policy (`caller_runs`). - # Waits for termination by default. Pass `wait: false` to continue. - def shutdown(wait: true) #:nodoc: - @scheduler.shutdown wait: wait - end - - # Used for our test suite. - def immediate=(immediate) #:nodoc: - @scheduler.immediate = immediate - end - - # Note that we don't actually need to serialize the jobs since we're - # performing them in-process, but we do so anyway for parity with other - # adapters and deployment environments. Otherwise, serialization bugs - # may creep in undetected. - class JobWrapper #:nodoc: - def initialize(job) - job.provider_job_id = SecureRandom.uuid - @job_data = job.serialize - end - - def perform - Base.execute @job_data - end - end - - class Scheduler #:nodoc: - DEFAULT_EXECUTOR_OPTIONS = { - min_threads: 0, - max_threads: Concurrent.processor_count, - auto_terminate: true, - idletime: 60, # 1 minute - max_queue: 0, # unlimited - fallback_policy: :caller_runs # shouldn't matter -- 0 max queue - }.freeze - - attr_accessor :immediate - - def initialize(**options) - self.immediate = false - @immediate_executor = Concurrent::ImmediateExecutor.new - @async_executor = Concurrent::ThreadPoolExecutor.new(DEFAULT_EXECUTOR_OPTIONS.merge(options)) - end - - def enqueue(job, queue_name:) - executor.post(job, &:perform) - end - - def enqueue_at(job, timestamp, queue_name:) - delay = timestamp - Time.current.to_f - if delay > 0 - Concurrent::ScheduledTask.execute(delay, args: [job], executor: executor, &:perform) - else - enqueue(job, queue_name: queue_name) - end - end - - def shutdown(wait: true) - @async_executor.shutdown - @async_executor.wait_for_termination if wait - end - - def executor - immediate ? @immediate_executor : @async_executor - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/backburner_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/backburner_adapter.rb deleted file mode 100644 index e3eccce62b..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/backburner_adapter.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "backburner" - -module ActiveJob - module QueueAdapters - # == Backburner adapter for Active Job - # - # Backburner is a beanstalkd-powered job queue that can handle a very - # high volume of jobs. You create background jobs and place them on - # multiple work queues to be processed later. Read more about - # Backburner {here}[https://github.com/nesquena/backburner]. - # - # To use Backburner set the queue_adapter config to +:backburner+. - # - # Rails.application.config.active_job.queue_adapter = :backburner - class BackburnerAdapter - def enqueue(job) #:nodoc: - Backburner::Worker.enqueue JobWrapper, [ job.serialize ], queue: job.queue_name - end - - def enqueue_at(job, timestamp) #:nodoc: - delay = timestamp - Time.current.to_f - Backburner::Worker.enqueue JobWrapper, [ job.serialize ], queue: job.queue_name, delay: delay - end - - class JobWrapper #:nodoc: - class << self - def perform(job_data) - Base.execute job_data - end - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/delayed_job_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/delayed_job_adapter.rb deleted file mode 100644 index 83ad2e767d..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/delayed_job_adapter.rb +++ /dev/null @@ -1,41 +0,0 @@ -require "delayed_job" - -module ActiveJob - module QueueAdapters - # == Delayed Job adapter for Active Job - # - # Delayed::Job (or DJ) encapsulates the common pattern of asynchronously - # executing longer tasks in the background. Although DJ can have many - # storage backends, one of the most used is based on Active Record. - # Read more about Delayed Job {here}[https://github.com/collectiveidea/delayed_job]. - # - # To use Delayed Job, set the queue_adapter config to +:delayed_job+. - # - # Rails.application.config.active_job.queue_adapter = :delayed_job - class DelayedJobAdapter - def enqueue(job) #:nodoc: - delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, priority: job.priority) - job.provider_job_id = delayed_job.id - delayed_job - end - - def enqueue_at(job, timestamp) #:nodoc: - delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, priority: job.priority, run_at: Time.at(timestamp)) - job.provider_job_id = delayed_job.id - delayed_job - end - - class JobWrapper #:nodoc: - attr_accessor :job_data - - def initialize(job_data) - @job_data = job_data - end - - def perform - Base.execute(job_data) - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/inline_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/inline_adapter.rb deleted file mode 100644 index 0496f8449e..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/inline_adapter.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActiveJob - module QueueAdapters - # == Active Job Inline adapter - # - # When enqueuing jobs with the Inline adapter the job will be executed - # immediately. - # - # To use the Inline set the queue_adapter config to +:inline+. - # - # Rails.application.config.active_job.queue_adapter = :inline - class InlineAdapter - def enqueue(job) #:nodoc: - Base.execute(job.serialize) - end - - def enqueue_at(*) #:nodoc: - raise NotImplementedError, "Use a queueing backend to enqueue jobs in the future. Read more at http://guides.rubyonrails.org/active_job_basics.html" - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/qu_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/qu_adapter.rb deleted file mode 100644 index e8994533e4..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/qu_adapter.rb +++ /dev/null @@ -1,44 +0,0 @@ -require "qu" - -module ActiveJob - module QueueAdapters - # == Qu adapter for Active Job - # - # Qu is a Ruby library for queuing and processing background jobs. It is - # heavily inspired by delayed_job and Resque. Qu was created to overcome - # some shortcomings in the existing queuing libraries. - # The advantages of Qu are: Multiple backends (redis, mongo), jobs are - # requeued when worker is killed, resque-like API. - # - # Read more about Qu {here}[https://github.com/bkeepers/qu]. - # - # To use Qu set the queue_adapter config to +:qu+. - # - # Rails.application.config.active_job.queue_adapter = :qu - class QuAdapter - def enqueue(job, *args) #:nodoc: - qu_job = Qu::Payload.new(klass: JobWrapper, args: [job.serialize]).tap do |payload| - payload.instance_variable_set(:@queue, job.queue_name) - end.push - - # qu_job can be nil depending on the configured backend - job.provider_job_id = qu_job.id unless qu_job.nil? - qu_job - end - - def enqueue_at(job, timestamp, *args) #:nodoc: - raise NotImplementedError, "This queueing backend does not support scheduling jobs. To see what features are supported go to http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html" - end - - class JobWrapper < Qu::Job #:nodoc: - def initialize(job_data) - @job_data = job_data - end - - def perform - Base.execute @job_data - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/que_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/que_adapter.rb deleted file mode 100644 index 0e698f0d79..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/que_adapter.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "que" - -module ActiveJob - module QueueAdapters - # == Que adapter for Active Job - # - # Que is a high-performance alternative to DelayedJob or QueueClassic that - # improves the reliability of your application by protecting your jobs with - # the same ACID guarantees as the rest of your data. Que is a queue for - # Ruby and PostgreSQL that manages jobs using advisory locks. - # - # Read more about Que {here}[https://github.com/chanks/que]. - # - # To use Que set the queue_adapter config to +:que+. - # - # Rails.application.config.active_job.queue_adapter = :que - class QueAdapter - def enqueue(job) #:nodoc: - que_job = JobWrapper.enqueue job.serialize, priority: job.priority - job.provider_job_id = que_job.attrs["job_id"] - que_job - end - - def enqueue_at(job, timestamp) #:nodoc: - que_job = JobWrapper.enqueue job.serialize, priority: job.priority, run_at: Time.at(timestamp) - job.provider_job_id = que_job.attrs["job_id"] - que_job - end - - class JobWrapper < Que::Job #:nodoc: - def run(job_data) - Base.execute job_data - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/queue_classic_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/queue_classic_adapter.rb deleted file mode 100644 index 1115eb88ae..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/queue_classic_adapter.rb +++ /dev/null @@ -1,56 +0,0 @@ -require "queue_classic" - -module ActiveJob - module QueueAdapters - # == queue_classic adapter for Active Job - # - # queue_classic provides a simple interface to a PostgreSQL-backed message - # queue. queue_classic specializes in concurrent locking and minimizing - # database load while providing a simple, intuitive developer experience. - # queue_classic assumes that you are already using PostgreSQL in your - # production environment and that adding another dependency (e.g. redis, - # beanstalkd, 0mq) is undesirable. - # - # Read more about queue_classic {here}[https://github.com/QueueClassic/queue_classic]. - # - # To use queue_classic set the queue_adapter config to +:queue_classic+. - # - # Rails.application.config.active_job.queue_adapter = :queue_classic - class QueueClassicAdapter - def enqueue(job) #:nodoc: - qc_job = build_queue(job.queue_name).enqueue("#{JobWrapper.name}.perform", job.serialize) - job.provider_job_id = qc_job["id"] if qc_job.is_a?(Hash) - qc_job - end - - def enqueue_at(job, timestamp) #:nodoc: - queue = build_queue(job.queue_name) - unless queue.respond_to?(:enqueue_at) - raise NotImplementedError, "To be able to schedule jobs with queue_classic " \ - "the QC::Queue needs to respond to `enqueue_at(timestamp, method, *args)`. " \ - "You can implement this yourself or you can use the queue_classic-later gem." - end - qc_job = queue.enqueue_at(timestamp, "#{JobWrapper.name}.perform", job.serialize) - job.provider_job_id = qc_job["id"] if qc_job.is_a?(Hash) - qc_job - end - - # Builds a QC::Queue object to schedule jobs on. - # - # If you have a custom QC::Queue subclass you'll need to subclass - # ActiveJob::QueueAdapters::QueueClassicAdapter and override the - # build_queue method. - def build_queue(queue_name) - QC::Queue.new(queue_name) - end - - class JobWrapper #:nodoc: - class << self - def perform(job_data) - Base.execute job_data - end - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/resque_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/resque_adapter.rb deleted file mode 100644 index 2df157ef89..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/resque_adapter.rb +++ /dev/null @@ -1,51 +0,0 @@ -require "resque" -require "active_support/core_ext/enumerable" -require "active_support/core_ext/array/access" - -begin - require "resque-scheduler" -rescue LoadError - begin - require "resque_scheduler" - rescue LoadError - false - end -end - -module ActiveJob - module QueueAdapters - # == Resque adapter for Active Job - # - # Resque (pronounced like "rescue") is a Redis-backed library for creating - # background jobs, placing those jobs on multiple queues, and processing - # them later. - # - # Read more about Resque {here}[https://github.com/resque/resque]. - # - # To use Resque set the queue_adapter config to +:resque+. - # - # Rails.application.config.active_job.queue_adapter = :resque - class ResqueAdapter - def enqueue(job) #:nodoc: - JobWrapper.instance_variable_set(:@queue, job.queue_name) - Resque.enqueue_to job.queue_name, JobWrapper, job.serialize - end - - def enqueue_at(job, timestamp) #:nodoc: - unless Resque.respond_to?(:enqueue_at_with_queue) - raise NotImplementedError, "To be able to schedule jobs with Resque you need the " \ - "resque-scheduler gem. Please add it to your Gemfile and run bundle install" - end - Resque.enqueue_at_with_queue job.queue_name, timestamp, JobWrapper, job.serialize - end - - class JobWrapper #:nodoc: - class << self - def perform(job_data) - Base.execute job_data - end - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sidekiq_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sidekiq_adapter.rb deleted file mode 100644 index 895cc1f981..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sidekiq_adapter.rb +++ /dev/null @@ -1,45 +0,0 @@ -require "sidekiq" - -module ActiveJob - module QueueAdapters - # == Sidekiq adapter for Active Job - # - # Simple, efficient background processing for Ruby. Sidekiq uses threads to - # handle many jobs at the same time in the same process. It does not - # require Rails but will integrate tightly with it to make background - # processing dead simple. - # - # Read more about Sidekiq {here}[http://sidekiq.org]. - # - # To use Sidekiq set the queue_adapter config to +:sidekiq+. - # - # Rails.application.config.active_job.queue_adapter = :sidekiq - class SidekiqAdapter - def enqueue(job) #:nodoc: - #Sidekiq::Client does not support symbols as keys - job.provider_job_id = Sidekiq::Client.push \ - "class" => JobWrapper, - "wrapped" => job.class.to_s, - "queue" => job.queue_name, - "args" => [ job.serialize ] - end - - def enqueue_at(job, timestamp) #:nodoc: - job.provider_job_id = Sidekiq::Client.push \ - "class" => JobWrapper, - "wrapped" => job.class.to_s, - "queue" => job.queue_name, - "args" => [ job.serialize ], - "at" => timestamp - end - - class JobWrapper #:nodoc: - include Sidekiq::Worker - - def perform(job_data) - Base.execute job_data.merge("provider_job_id" => jid) - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sneakers_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sneakers_adapter.rb deleted file mode 100644 index f00acfc04a..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sneakers_adapter.rb +++ /dev/null @@ -1,46 +0,0 @@ -require "sneakers" -require "monitor" - -module ActiveJob - module QueueAdapters - # == Sneakers adapter for Active Job - # - # A high-performance RabbitMQ background processing framework for Ruby. - # Sneakers is being used in production for both I/O and CPU intensive - # workloads, and have achieved the goals of high-performance and - # 0-maintenance, as designed. - # - # Read more about Sneakers {here}[https://github.com/jondot/sneakers]. - # - # To use Sneakers set the queue_adapter config to +:sneakers+. - # - # Rails.application.config.active_job.queue_adapter = :sneakers - class SneakersAdapter - def initialize - @monitor = Monitor.new - end - - def enqueue(job) #:nodoc: - @monitor.synchronize do - JobWrapper.from_queue job.queue_name - JobWrapper.enqueue ActiveSupport::JSON.encode(job.serialize) - end - end - - def enqueue_at(job, timestamp) #:nodoc: - raise NotImplementedError, "This queueing backend does not support scheduling jobs. To see what features are supported go to http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html" - end - - class JobWrapper #:nodoc: - include Sneakers::Worker - from_queue "default" - - def work(msg) - job_data = ActiveSupport::JSON.decode(msg) - Base.execute job_data - ack! - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sucker_punch_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sucker_punch_adapter.rb deleted file mode 100644 index dd59a79813..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/sucker_punch_adapter.rb +++ /dev/null @@ -1,47 +0,0 @@ -require "sucker_punch" - -module ActiveJob - module QueueAdapters - # == Sucker Punch adapter for Active Job - # - # Sucker Punch is a single-process Ruby asynchronous processing library. - # This reduces the cost of hosting on a service like Heroku along - # with the memory footprint of having to maintain additional jobs if - # hosting on a dedicated server. All queues can run within a - # single application (eg. Rails, Sinatra, etc.) process. - # - # Read more about Sucker Punch {here}[https://github.com/brandonhilkert/sucker_punch]. - # - # To use Sucker Punch set the queue_adapter config to +:sucker_punch+. - # - # Rails.application.config.active_job.queue_adapter = :sucker_punch - class SuckerPunchAdapter - def enqueue(job) #:nodoc: - if JobWrapper.respond_to?(:perform_async) - # sucker_punch 2.0 API - JobWrapper.perform_async job.serialize - else - # sucker_punch 1.0 API - JobWrapper.new.async.perform job.serialize - end - end - - def enqueue_at(job, timestamp) #:nodoc: - if JobWrapper.respond_to?(:perform_in) - delay = timestamp - Time.current.to_f - JobWrapper.perform_in delay, job.serialize - else - raise NotImplementedError, "sucker_punch 1.0 does not support `enqueued_at`. Please upgrade to version ~> 2.0.0 to enable this behavior." - end - end - - class JobWrapper #:nodoc: - include SuckerPunch::Job - - def perform(job_data) - Base.execute job_data - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/test_adapter.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/test_adapter.rb deleted file mode 100644 index 1b633b210e..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_adapters/test_adapter.rb +++ /dev/null @@ -1,59 +0,0 @@ -module ActiveJob - module QueueAdapters - # == Test adapter for Active Job - # - # The test adapter should be used only in testing. Along with - # ActiveJob::TestCase and ActiveJob::TestHelper - # it makes a great tool to test your Rails application. - # - # To use the test adapter set queue_adapter config to +:test+. - # - # Rails.application.config.active_job.queue_adapter = :test - class TestAdapter - attr_accessor(:perform_enqueued_jobs, :perform_enqueued_at_jobs, :filter) - attr_writer(:enqueued_jobs, :performed_jobs) - - # Provides a store of all the enqueued jobs with the TestAdapter so you can check them. - def enqueued_jobs - @enqueued_jobs ||= [] - end - - # Provides a store of all the performed jobs with the TestAdapter so you can check them. - def performed_jobs - @performed_jobs ||= [] - end - - def enqueue(job) #:nodoc: - return if filtered?(job) - - job_data = job_to_hash(job) - enqueue_or_perform(perform_enqueued_jobs, job, job_data) - end - - def enqueue_at(job, timestamp) #:nodoc: - return if filtered?(job) - - job_data = job_to_hash(job, at: timestamp) - enqueue_or_perform(perform_enqueued_at_jobs, job, job_data) - end - - private - def job_to_hash(job, extras = {}) - { job: job.class, args: job.serialize.fetch("arguments"), queue: job.queue_name }.merge!(extras) - end - - def enqueue_or_perform(perform, job, job_data) - if perform - performed_jobs << job_data - Base.execute job.serialize - else - enqueued_jobs << job_data - end - end - - def filtered?(job) - filter && !Array(filter).include?(job.class) - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_name.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_name.rb deleted file mode 100644 index 352cf62424..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_name.rb +++ /dev/null @@ -1,50 +0,0 @@ -module ActiveJob - module QueueName - extend ActiveSupport::Concern - - # Includes the ability to override the default queue name and prefix. - module ClassMethods - mattr_accessor(:queue_name_prefix) - mattr_accessor(:default_queue_name) { "default" } - - # Specifies the name of the queue to process the job on. - # - # class PublishToFeedJob < ActiveJob::Base - # queue_as :feeds - # - # def perform(post) - # post.to_feed! - # end - # end - def queue_as(part_name = nil, &block) - if block_given? - self.queue_name = block - else - self.queue_name = queue_name_from_part(part_name) - end - end - - def queue_name_from_part(part_name) #:nodoc: - queue_name = part_name || default_queue_name - name_parts = [queue_name_prefix.presence, queue_name] - name_parts.compact.join(queue_name_delimiter) - end - end - - included do - class_attribute :queue_name, instance_accessor: false - class_attribute :queue_name_delimiter, instance_accessor: false - - self.queue_name = default_queue_name - self.queue_name_delimiter = "_" # set default delimiter to '_' - end - - # Returns the name of the queue the job will be run on. - def queue_name - if @queue_name.is_a?(Proc) - @queue_name = self.class.queue_name_from_part(instance_exec(&@queue_name)) - end - @queue_name - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_priority.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_priority.rb deleted file mode 100644 index b02202fcc8..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/queue_priority.rb +++ /dev/null @@ -1,43 +0,0 @@ -module ActiveJob - module QueuePriority - extend ActiveSupport::Concern - - # Includes the ability to override the default queue priority. - module ClassMethods - mattr_accessor(:default_priority) - - # Specifies the priority of the queue to create the job with. - # - # class PublishToFeedJob < ActiveJob::Base - # queue_with_priority 50 - # - # def perform(post) - # post.to_feed! - # end - # end - # - # Specify either an argument or a block. - def queue_with_priority(priority = nil, &block) - if block_given? - self.priority = block - else - self.priority = priority - end - end - end - - included do - class_attribute :priority, instance_accessor: false - - self.priority = default_priority - end - - # Returns the priority that the job will be created with - def priority - if @priority.is_a?(Proc) - @priority = instance_exec(&@priority) - end - @priority - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/railtie.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/railtie.rb deleted file mode 100644 index 4a8bf04d70..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/railtie.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "global_id/railtie" -require "active_job" - -module ActiveJob - # = Active Job Railtie - class Railtie < Rails::Railtie # :nodoc: - config.active_job = ActiveSupport::OrderedOptions.new - - initializer "active_job.logger" do - ActiveSupport.on_load(:active_job) { self.logger = ::Rails.logger } - end - - initializer "active_job.set_configs" do |app| - options = app.config.active_job - options.queue_adapter ||= :async - - ActiveSupport.on_load(:active_job) do - options.each { |k, v| send("#{k}=", v) } - end - end - - initializer "active_job.set_reloader_hook" do |app| - ActiveSupport.on_load(:active_job) do - ActiveJob::Callbacks.singleton_class.set_callback(:execute, :around, prepend: true) do |_, inner| - app.reloader.wrap do - inner.call - end - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/test_case.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/test_case.rb deleted file mode 100644 index a5ec45e4a7..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/test_case.rb +++ /dev/null @@ -1,9 +0,0 @@ -require "active_support/test_case" - -module ActiveJob - class TestCase < ActiveSupport::TestCase - include ActiveJob::TestHelper - - ActiveSupport.run_load_hooks(:active_job_test_case, self) - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/test_helper.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/test_helper.rb deleted file mode 100644 index a61e4f59a5..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/test_helper.rb +++ /dev/null @@ -1,387 +0,0 @@ -require "active_support/core_ext/class/subclasses" -require "active_support/core_ext/hash/keys" - -module ActiveJob - # Provides helper methods for testing Active Job - module TestHelper - delegate :enqueued_jobs, :enqueued_jobs=, - :performed_jobs, :performed_jobs=, - to: :queue_adapter - - module TestQueueAdapter - extend ActiveSupport::Concern - - included do - class_attribute :_test_adapter, instance_accessor: false, instance_predicate: false - end - - module ClassMethods - def queue_adapter - self._test_adapter.nil? ? super : self._test_adapter - end - - def disable_test_adapter - self._test_adapter = nil - end - - def enable_test_adapter(test_adapter) - self._test_adapter = test_adapter - end - end - end - - ActiveJob::Base.include(TestQueueAdapter) - - def before_setup # :nodoc: - test_adapter = queue_adapter_for_test - - queue_adapter_changed_jobs.each do |klass| - klass.enable_test_adapter(test_adapter) - end - - clear_enqueued_jobs - clear_performed_jobs - super - end - - def after_teardown # :nodoc: - super - - queue_adapter_changed_jobs.each { |klass| klass.disable_test_adapter } - end - - # Specifies the queue adapter to use with all active job test helpers. - # - # Returns an instance of the queue adapter and defaults to - # ActiveJob::QueueAdapters::TestAdapter. - # - # Note: The adapter provided by this method must provide some additional - # methods from those expected of a standard ActiveJob::QueueAdapter - # in order to be used with the active job test helpers. Refer to - # ActiveJob::QueueAdapters::TestAdapter. - def queue_adapter_for_test - ActiveJob::QueueAdapters::TestAdapter.new - end - - # Asserts that the number of enqueued jobs matches the given number. - # - # def test_jobs - # assert_enqueued_jobs 0 - # HelloJob.perform_later('david') - # assert_enqueued_jobs 1 - # HelloJob.perform_later('abdelkader') - # assert_enqueued_jobs 2 - # end - # - # If a block is passed, that block will cause the specified number of - # jobs to be enqueued. - # - # def test_jobs_again - # assert_enqueued_jobs 1 do - # HelloJob.perform_later('cristian') - # end - # - # assert_enqueued_jobs 2 do - # HelloJob.perform_later('aaron') - # HelloJob.perform_later('rafael') - # end - # end - # - # The number of times a specific job is enqueued can be asserted. - # - # def test_logging_job - # assert_enqueued_jobs 1, only: LoggingJob do - # LoggingJob.perform_later - # HelloJob.perform_later('jeremy') - # end - # end - # - # The number of times a job is enqueued to a specific queue can also be asserted. - # - # def test_logging_job - # assert_enqueued_jobs 2, queue: 'default' do - # LoggingJob.perform_later - # HelloJob.perform_later('elfassy') - # end - # end - def assert_enqueued_jobs(number, only: nil, queue: nil) - if block_given? - original_count = enqueued_jobs_size(only: only, queue: queue) - yield - new_count = enqueued_jobs_size(only: only, queue: queue) - assert_equal number, new_count - original_count, "#{number} jobs expected, but #{new_count - original_count} were enqueued" - else - actual_count = enqueued_jobs_size(only: only, queue: queue) - assert_equal number, actual_count, "#{number} jobs expected, but #{actual_count} were enqueued" - end - end - - # Asserts that no jobs have been enqueued. - # - # def test_jobs - # assert_no_enqueued_jobs - # HelloJob.perform_later('jeremy') - # assert_enqueued_jobs 1 - # end - # - # If a block is passed, that block should not cause any job to be enqueued. - # - # def test_jobs_again - # assert_no_enqueued_jobs do - # # No job should be enqueued from this block - # end - # end - # - # It can be asserted that no jobs of a specific kind are enqueued: - # - # def test_no_logging - # assert_no_enqueued_jobs only: LoggingJob do - # HelloJob.perform_later('jeremy') - # end - # end - # - # Note: This assertion is simply a shortcut for: - # - # assert_enqueued_jobs 0, &block - def assert_no_enqueued_jobs(only: nil, &block) - assert_enqueued_jobs 0, only: only, &block - end - - # Asserts that the number of performed jobs matches the given number. - # If no block is passed, perform_enqueued_jobs - # must be called around the job call. - # - # def test_jobs - # assert_performed_jobs 0 - # - # perform_enqueued_jobs do - # HelloJob.perform_later('xavier') - # end - # assert_performed_jobs 1 - # - # perform_enqueued_jobs do - # HelloJob.perform_later('yves') - # assert_performed_jobs 2 - # end - # end - # - # If a block is passed, that block should cause the specified number of - # jobs to be performed. - # - # def test_jobs_again - # assert_performed_jobs 1 do - # HelloJob.perform_later('robin') - # end - # - # assert_performed_jobs 2 do - # HelloJob.perform_later('carlos') - # HelloJob.perform_later('sean') - # end - # end - # - # The block form supports filtering. If the :only option is specified, - # then only the listed job(s) will be performed. - # - # def test_hello_job - # assert_performed_jobs 1, only: HelloJob do - # HelloJob.perform_later('jeremy') - # LoggingJob.perform_later - # end - # end - # - # An array may also be specified, to support testing multiple jobs. - # - # def test_hello_and_logging_jobs - # assert_nothing_raised do - # assert_performed_jobs 2, only: [HelloJob, LoggingJob] do - # HelloJob.perform_later('jeremy') - # LoggingJob.perform_later('stewie') - # RescueJob.perform_later('david') - # end - # end - # end - def assert_performed_jobs(number, only: nil) - if block_given? - original_count = performed_jobs.size - perform_enqueued_jobs(only: only) { yield } - new_count = performed_jobs.size - assert_equal number, new_count - original_count, - "#{number} jobs expected, but #{new_count - original_count} were performed" - else - performed_jobs_size = performed_jobs.size - assert_equal number, performed_jobs_size, "#{number} jobs expected, but #{performed_jobs_size} were performed" - end - end - - # Asserts that no jobs have been performed. - # - # def test_jobs - # assert_no_performed_jobs - # - # perform_enqueued_jobs do - # HelloJob.perform_later('matthew') - # assert_performed_jobs 1 - # end - # end - # - # If a block is passed, that block should not cause any job to be performed. - # - # def test_jobs_again - # assert_no_performed_jobs do - # # No job should be performed from this block - # end - # end - # - # The block form supports filtering. If the :only option is specified, - # then only the listed job(s) will not be performed. - # - # def test_no_logging - # assert_no_performed_jobs only: LoggingJob do - # HelloJob.perform_later('jeremy') - # end - # end - # - # Note: This assertion is simply a shortcut for: - # - # assert_performed_jobs 0, &block - def assert_no_performed_jobs(only: nil, &block) - assert_performed_jobs 0, only: only, &block - end - - # Asserts that the job passed in the block has been enqueued with the given arguments. - # - # def test_assert_enqueued_with - # assert_enqueued_with(job: MyJob, args: [1,2,3], queue: 'low') do - # MyJob.perform_later(1,2,3) - # end - # - # assert_enqueued_with(job: MyJob, at: Date.tomorrow.noon) do - # MyJob.set(wait_until: Date.tomorrow.noon).perform_later - # end - # end - def assert_enqueued_with(job: nil, args: nil, at: nil, queue: nil) - original_enqueued_jobs_count = enqueued_jobs.count - expected = { job: job, args: args, at: at, queue: queue }.compact - serialized_args = serialize_args_for_assertion(expected) - yield - in_block_jobs = enqueued_jobs.drop(original_enqueued_jobs_count) - matching_job = in_block_jobs.find do |in_block_job| - serialized_args.all? { |key, value| value == in_block_job[key] } - end - assert matching_job, "No enqueued job found with #{expected}" - instantiate_job(matching_job) - end - - # Asserts that the job passed in the block has been performed with the given arguments. - # - # def test_assert_performed_with - # assert_performed_with(job: MyJob, args: [1,2,3], queue: 'high') do - # MyJob.perform_later(1,2,3) - # end - # - # assert_performed_with(job: MyJob, at: Date.tomorrow.noon) do - # MyJob.set(wait_until: Date.tomorrow.noon).perform_later - # end - # end - def assert_performed_with(job: nil, args: nil, at: nil, queue: nil) - original_performed_jobs_count = performed_jobs.count - expected = { job: job, args: args, at: at, queue: queue }.compact - serialized_args = serialize_args_for_assertion(expected) - perform_enqueued_jobs { yield } - in_block_jobs = performed_jobs.drop(original_performed_jobs_count) - matching_job = in_block_jobs.find do |in_block_job| - serialized_args.all? { |key, value| value == in_block_job[key] } - end - assert matching_job, "No performed job found with #{expected}" - instantiate_job(matching_job) - end - - # Performs all enqueued jobs in the duration of the block. - # - # def test_perform_enqueued_jobs - # perform_enqueued_jobs do - # MyJob.perform_later(1, 2, 3) - # end - # assert_performed_jobs 1 - # end - # - # This method also supports filtering. If the +:only+ option is specified, - # then only the listed job(s) will be performed. - # - # def test_perform_enqueued_jobs_with_only - # perform_enqueued_jobs(only: MyJob) do - # MyJob.perform_later(1, 2, 3) # will be performed - # HelloJob.perform_later(1, 2, 3) # will not be performed - # end - # assert_performed_jobs 1 - # end - def perform_enqueued_jobs(only: nil) - old_perform_enqueued_jobs = queue_adapter.perform_enqueued_jobs - old_perform_enqueued_at_jobs = queue_adapter.perform_enqueued_at_jobs - old_filter = queue_adapter.filter - - begin - queue_adapter.perform_enqueued_jobs = true - queue_adapter.perform_enqueued_at_jobs = true - queue_adapter.filter = only - yield - ensure - queue_adapter.perform_enqueued_jobs = old_perform_enqueued_jobs - queue_adapter.perform_enqueued_at_jobs = old_perform_enqueued_at_jobs - queue_adapter.filter = old_filter - end - end - - # Accesses the queue_adapter set by ActiveJob::Base. - # - # def test_assert_job_has_custom_queue_adapter_set - # assert_instance_of CustomQueueAdapter, HelloJob.queue_adapter - # end - def queue_adapter - ActiveJob::Base.queue_adapter - end - - private - def clear_enqueued_jobs - enqueued_jobs.clear - end - - def clear_performed_jobs - performed_jobs.clear - end - - def enqueued_jobs_size(only: nil, queue: nil) - enqueued_jobs.count do |job| - job_class = job.fetch(:job) - if only - next false unless Array(only).include?(job_class) - end - if queue - next false unless queue.to_s == job.fetch(:queue, job_class.queue_name) - end - true - end - end - - def serialize_args_for_assertion(args) - args.dup.tap do |serialized_args| - serialized_args[:args] = ActiveJob::Arguments.serialize(serialized_args[:args]) if serialized_args[:args] - serialized_args[:at] = serialized_args[:at].to_f if serialized_args[:at] - end - end - - def instantiate_job(payload) - job = payload[:job].new(*payload[:args]) - job.scheduled_at = Time.at(payload[:at]) if payload.key?(:at) - job.queue_name = payload[:queue] - job - end - - def queue_adapter_changed_jobs - (ActiveJob::Base.descendants << ActiveJob::Base).select do |klass| - # only override explicitly set adapters, a quirk of `class_attribute` - klass.singleton_class.public_instance_methods(false).include?(:_queue_adapter) - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/translation.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/translation.rb deleted file mode 100644 index 67e4cf4ab9..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/translation.rb +++ /dev/null @@ -1,11 +0,0 @@ -module ActiveJob - module Translation #:nodoc: - extend ActiveSupport::Concern - - included do - around_perform do |job, block, _| - I18n.with_locale(job.locale, &block) - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/active_job/version.rb b/debian/gems-compat/activejob-5.1.7/lib/active_job/version.rb deleted file mode 100644 index 60b463817f..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/active_job/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module ActiveJob - # Returns the version of the currently loaded Active Job as a Gem::Version - def self.version - gem_version - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/job_generator.rb b/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/job_generator.rb deleted file mode 100644 index 50476a2e50..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/job_generator.rb +++ /dev/null @@ -1,38 +0,0 @@ -require "rails/generators/named_base" - -module Rails # :nodoc: - module Generators # :nodoc: - class JobGenerator < Rails::Generators::NamedBase # :nodoc: - desc "This generator creates an active job file at app/jobs" - - class_option :queue, type: :string, default: "default", desc: "The queue name for the generated job" - - check_class_collision suffix: "Job" - - hook_for :test_framework - - def self.default_generator_root - File.dirname(__FILE__) - end - - def create_job_file - template "job.rb", File.join("app/jobs", class_path, "#{file_name}_job.rb") - - in_root do - if behavior == :invoke && !File.exist?(application_job_file_name) - template "application_job.rb", application_job_file_name - end - end - end - - private - def application_job_file_name - @application_job_file_name ||= if mountable_engine? - "app/jobs/#{namespaced_path}/application_job.rb" - else - "app/jobs/application_job.rb" - end - end - end - end -end diff --git a/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/templates/application_job.rb b/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/templates/application_job.rb deleted file mode 100644 index f93745a31a..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/templates/application_job.rb +++ /dev/null @@ -1,9 +0,0 @@ -<% module_namespacing do -%> -class ApplicationJob < ActiveJob::Base - # Automatically retry jobs that encountered a deadlock - # retry_on ActiveRecord::Deadlocked - - # Most jobs are safe to ignore if the underlying records are no longer available - # discard_on ActiveJob::DeserializationError -end -<% end -%> diff --git a/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/templates/job.rb b/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/templates/job.rb deleted file mode 100644 index 4ad2914a45..0000000000 --- a/debian/gems-compat/activejob-5.1.7/lib/rails/generators/job/templates/job.rb +++ /dev/null @@ -1,9 +0,0 @@ -<% module_namespacing do -%> -class <%= class_name %>Job < ApplicationJob - queue_as :<%= options[:queue] %> - - def perform(*args) - # Do something later - end -end -<% end -%> diff --git a/debian/gems-compat/activemodel-5.1.7/CHANGELOG.md b/debian/gems-compat/activemodel-5.1.7/CHANGELOG.md deleted file mode 100644 index 4cd4646cdb..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,112 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* No changes. - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* No changes. - - -## Rails 5.1.5 (February 14, 2018) ## - -* Fix to working before/after validation callbacks on multiple contexts. - - *Yoshiyuki Hirano* - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* No changes. - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* No changes. - - -## Rails 5.1.2 (June 26, 2017) ## - -* Fix regression in numericality validator when comparing Decimal and Float input - values with more scale than the schema. - - *Bradley Priest* - - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* The original string assigned to a model attribute is no longer incorrectly - frozen. - - Fixes #24185, #28718. - - *Matthew Draper* - -* Avoid converting integer as a string into float. - - *namusyaka* - -* Remove deprecated behavior that halts callbacks when the return is false. - - *Rafael Mendonça França* - -* Remove unused `ActiveModel::TestCase` class. - - *Yuji Yaginuma* - -* Moved DecimalWithoutScale, Text, and UnsignedInteger from Active Model to Active Record - - *Iain Beeston* - -* Allow indifferent access in `ActiveModel::Errors`. - - `#include?`, `#has_key?`, `#key?`, `#delete` and `#full_messages_for`. - - *Kenichi Kamiya* - -* Removed deprecated `:tokenizer` in the length validator. - - *Rafael Mendonça França* - -* Removed deprecated methods in `ActiveModel::Errors`. - - `#get`, `#set`, `[]=`, `add_on_empty` and `add_on_blank`. - - *Rafael Mendonça França* - - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activemodel/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/activemodel-5.1.7/MIT-LICENSE b/debian/gems-compat/activemodel-5.1.7/MIT-LICENSE deleted file mode 100644 index ac810e86d0..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2004-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/debian/gems-compat/activemodel-5.1.7/README.rdoc b/debian/gems-compat/activemodel-5.1.7/README.rdoc deleted file mode 100644 index 77f5761993..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/README.rdoc +++ /dev/null @@ -1,264 +0,0 @@ -= Active Model -- model interfaces for Rails - -Active Model provides a known set of interfaces for usage in model classes. -They allow for Action Pack helpers to interact with non-Active Record models, -for example. Active Model also helps with building custom ORMs for use outside of -the Rails framework. - -Prior to Rails 3.0, if a plugin or gem developer wanted to have an object -interact with Action Pack helpers, it was required to either copy chunks of -code from Rails, or monkey patch entire helpers to make them handle objects -that did not exactly conform to the Active Record interface. This would result -in code duplication and fragile applications that broke on upgrades. Active -Model solves this by defining an explicit API. You can read more about the -API in ActiveModel::Lint::Tests. - -Active Model provides a default module that implements the basic API required -to integrate with Action Pack out of the box: ActiveModel::Model. - - class Person - include ActiveModel::Model - - attr_accessor :name, :age - validates_presence_of :name - end - - person = Person.new(name: 'bob', age: '18') - person.name # => 'bob' - person.age # => '18' - person.valid? # => true - -It includes model name introspections, conversions, translations and -validations, resulting in a class suitable to be used with Action Pack. -See ActiveModel::Model for more examples. - -Active Model also provides the following functionality to have ORM-like -behavior out of the box: - -* Add attribute magic to objects - - class Person - include ActiveModel::AttributeMethods - - attribute_method_prefix 'clear_' - define_attribute_methods :name, :age - - attr_accessor :name, :age - - def clear_attribute(attr) - send("#{attr}=", nil) - end - end - - person = Person.new - person.clear_name - person.clear_age - - {Learn more}[link:classes/ActiveModel/AttributeMethods.html] - -* Callbacks for certain operations - - class Person - extend ActiveModel::Callbacks - define_model_callbacks :create - - def create - run_callbacks :create do - # Your create action methods here - end - end - end - - This generates +before_create+, +around_create+ and +after_create+ - class methods that wrap your create method. - - {Learn more}[link:classes/ActiveModel/Callbacks.html] - -* Tracking value changes - - class Person - include ActiveModel::Dirty - - define_attribute_methods :name - - def name - @name - end - - def name=(val) - name_will_change! unless val == @name - @name = val - end - - def save - # do persistence work - changes_applied - end - end - - person = Person.new - person.name # => nil - person.changed? # => false - person.name = 'bob' - person.changed? # => true - person.changed # => ['name'] - person.changes # => { 'name' => [nil, 'bob'] } - person.save - person.name = 'robert' - person.save - person.previous_changes # => {'name' => ['bob, 'robert']} - - {Learn more}[link:classes/ActiveModel/Dirty.html] - -* Adding +errors+ interface to objects - - Exposing error messages allows objects to interact with Action Pack - helpers seamlessly. - - class Person - - def initialize - @errors = ActiveModel::Errors.new(self) - end - - attr_accessor :name - attr_reader :errors - - def validate! - errors.add(:name, "cannot be nil") if name.nil? - end - - def self.human_attribute_name(attr, options = {}) - "Name" - end - end - - person = Person.new - person.name = nil - person.validate! - person.errors.full_messages - # => ["Name cannot be nil"] - - {Learn more}[link:classes/ActiveModel/Errors.html] - -* Model name introspection - - class NamedPerson - extend ActiveModel::Naming - end - - NamedPerson.model_name.name # => "NamedPerson" - NamedPerson.model_name.human # => "Named person" - - {Learn more}[link:classes/ActiveModel/Naming.html] - -* Making objects serializable - - ActiveModel::Serialization provides a standard interface for your object - to provide +to_json+ serialization. - - class SerialPerson - include ActiveModel::Serialization - - attr_accessor :name - - def attributes - {'name' => name} - end - end - - s = SerialPerson.new - s.serializable_hash # => {"name"=>nil} - - class SerialPerson - include ActiveModel::Serializers::JSON - end - - s = SerialPerson.new - s.to_json # => "{\"name\":null}" - - {Learn more}[link:classes/ActiveModel/Serialization.html] - -* Internationalization (i18n) support - - class Person - extend ActiveModel::Translation - end - - Person.human_attribute_name('my_attribute') - # => "My attribute" - - {Learn more}[link:classes/ActiveModel/Translation.html] - -* Validation support - - class Person - include ActiveModel::Validations - - attr_accessor :first_name, :last_name - - validates_each :first_name, :last_name do |record, attr, value| - record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z - end - end - - person = Person.new - person.first_name = 'zoolander' - person.valid? # => false - - {Learn more}[link:classes/ActiveModel/Validations.html] - -* Custom validators - - class HasNameValidator < ActiveModel::Validator - def validate(record) - record.errors.add(:name, "must exist") if record.name.blank? - end - end - - class ValidatorPerson - include ActiveModel::Validations - validates_with HasNameValidator - attr_accessor :name - end - - p = ValidatorPerson.new - p.valid? # => false - p.errors.full_messages # => ["Name must exist"] - p.name = "Bob" - p.valid? # => true - - {Learn more}[link:classes/ActiveModel/Validator.html] - - -== Download and installation - -The latest version of Active Model can be installed with RubyGems: - - $ gem install activemodel - -Source code can be downloaded as part of the Rails project on GitHub - -* https://github.com/rails/rails/tree/master/activemodel - - -== License - -Active Model is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -== Support - -API documentation is at - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/activemodel-5.1.7/activemodel.gemspec b/debian/gems-compat/activemodel-5.1.7/activemodel.gemspec deleted file mode 100644 index acb62e02a4..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/activemodel.gemspec +++ /dev/null @@ -1,36 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: activemodel 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "activemodel".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/activemodel/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/activemodel" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "A toolkit for building modeling frameworks like Active Record. Rich support for attributes, callbacks, validations, serialization, internationalization, and testing.".freeze - s.email = "david@loudthinking.com".freeze - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.rdoc".freeze, "lib/active_model.rb".freeze, "lib/active_model/attribute_assignment.rb".freeze, "lib/active_model/attribute_methods.rb".freeze, "lib/active_model/callbacks.rb".freeze, "lib/active_model/conversion.rb".freeze, "lib/active_model/dirty.rb".freeze, "lib/active_model/errors.rb".freeze, "lib/active_model/forbidden_attributes_protection.rb".freeze, "lib/active_model/gem_version.rb".freeze, "lib/active_model/lint.rb".freeze, "lib/active_model/locale/en.yml".freeze, "lib/active_model/model.rb".freeze, "lib/active_model/naming.rb".freeze, "lib/active_model/railtie.rb".freeze, "lib/active_model/secure_password.rb".freeze, "lib/active_model/serialization.rb".freeze, "lib/active_model/serializers/json.rb".freeze, "lib/active_model/translation.rb".freeze, "lib/active_model/type.rb".freeze, "lib/active_model/type/big_integer.rb".freeze, "lib/active_model/type/binary.rb".freeze, "lib/active_model/type/boolean.rb".freeze, "lib/active_model/type/date.rb".freeze, "lib/active_model/type/date_time.rb".freeze, "lib/active_model/type/decimal.rb".freeze, "lib/active_model/type/float.rb".freeze, "lib/active_model/type/helpers.rb".freeze, "lib/active_model/type/helpers/accepts_multiparameter_time.rb".freeze, "lib/active_model/type/helpers/mutable.rb".freeze, "lib/active_model/type/helpers/numeric.rb".freeze, "lib/active_model/type/helpers/time_value.rb".freeze, "lib/active_model/type/immutable_string.rb".freeze, "lib/active_model/type/integer.rb".freeze, "lib/active_model/type/registry.rb".freeze, "lib/active_model/type/string.rb".freeze, "lib/active_model/type/time.rb".freeze, "lib/active_model/type/value.rb".freeze, "lib/active_model/validations.rb".freeze, "lib/active_model/validations/absence.rb".freeze, "lib/active_model/validations/acceptance.rb".freeze, "lib/active_model/validations/callbacks.rb".freeze, "lib/active_model/validations/clusivity.rb".freeze, "lib/active_model/validations/confirmation.rb".freeze, "lib/active_model/validations/exclusion.rb".freeze, "lib/active_model/validations/format.rb".freeze, "lib/active_model/validations/helper_methods.rb".freeze, "lib/active_model/validations/inclusion.rb".freeze, "lib/active_model/validations/length.rb".freeze, "lib/active_model/validations/numericality.rb".freeze, "lib/active_model/validations/presence.rb".freeze, "lib/active_model/validations/validates.rb".freeze, "lib/active_model/validations/with.rb".freeze, "lib/active_model/validator.rb".freeze, "lib/active_model/version.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.rubygems_version = "2.7.6.2".freeze - s.summary = "A toolkit for building modeling frameworks (part of Rails).".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model.rb deleted file mode 100644 index 2389c858d5..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model.rb +++ /dev/null @@ -1,72 +0,0 @@ -#-- -# Copyright (c) 2004-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "active_support" -require "active_support/rails" -require "active_model/version" - -module ActiveModel - extend ActiveSupport::Autoload - - autoload :AttributeAssignment - autoload :AttributeMethods - autoload :BlockValidator, "active_model/validator" - autoload :Callbacks - autoload :Conversion - autoload :Dirty - autoload :EachValidator, "active_model/validator" - autoload :ForbiddenAttributesProtection - autoload :Lint - autoload :Model - autoload :Name, "active_model/naming" - autoload :Naming - autoload :SecurePassword - autoload :Serialization - autoload :Translation - autoload :Validations - autoload :Validator - - eager_autoload do - autoload :Errors - autoload :RangeError, "active_model/errors" - autoload :StrictValidationFailed, "active_model/errors" - autoload :UnknownAttributeError, "active_model/errors" - end - - module Serializers - extend ActiveSupport::Autoload - - eager_autoload do - autoload :JSON - end - end - - def self.eager_load! - super - ActiveModel::Serializers.eager_load! - end -end - -ActiveSupport.on_load(:i18n) do - I18n.load_path << File.dirname(__FILE__) + "/active_model/locale/en.yml" -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/attribute_assignment.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/attribute_assignment.rb deleted file mode 100644 index 7dad3b6dff..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/attribute_assignment.rb +++ /dev/null @@ -1,52 +0,0 @@ -require "active_support/core_ext/hash/keys" - -module ActiveModel - module AttributeAssignment - include ActiveModel::ForbiddenAttributesProtection - - # Allows you to set all the attributes by passing in a hash of attributes with - # keys matching the attribute names. - # - # If the passed hash responds to permitted? method and the return value - # of this method is +false+ an ActiveModel::ForbiddenAttributesError - # exception is raised. - # - # class Cat - # include ActiveModel::AttributeAssignment - # attr_accessor :name, :status - # end - # - # cat = Cat.new - # cat.assign_attributes(name: "Gorby", status: "yawning") - # cat.name # => 'Gorby' - # cat.status => 'yawning' - # cat.assign_attributes(status: "sleeping") - # cat.name # => 'Gorby' - # cat.status => 'sleeping' - def assign_attributes(new_attributes) - if !new_attributes.respond_to?(:stringify_keys) - raise ArgumentError, "When assigning attributes, you must pass a hash as an argument." - end - return if new_attributes.nil? || new_attributes.empty? - - attributes = new_attributes.stringify_keys - _assign_attributes(sanitize_for_mass_assignment(attributes)) - end - - private - - def _assign_attributes(attributes) - attributes.each do |k, v| - _assign_attribute(k, v) - end - end - - def _assign_attribute(k, v) - if respond_to?("#{k}=") - public_send("#{k}=", v) - else - raise UnknownAttributeError.new(self, k) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/attribute_methods.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/attribute_methods.rb deleted file mode 100644 index 166c6ac21f..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/attribute_methods.rb +++ /dev/null @@ -1,476 +0,0 @@ -require "concurrent/map" -require "mutex_m" - -module ActiveModel - # Raised when an attribute is not defined. - # - # class User < ActiveRecord::Base - # has_many :pets - # end - # - # user = User.first - # user.pets.select(:id).first.user_id - # # => ActiveModel::MissingAttributeError: missing attribute: user_id - class MissingAttributeError < NoMethodError - end - - # == Active \Model \Attribute \Methods - # - # Provides a way to add prefixes and suffixes to your methods as - # well as handling the creation of ActiveRecord::Base-like - # class methods such as +table_name+. - # - # The requirements to implement ActiveModel::AttributeMethods are to: - # - # * include ActiveModel::AttributeMethods in your class. - # * Call each of its methods you want to add, such as +attribute_method_suffix+ - # or +attribute_method_prefix+. - # * Call +define_attribute_methods+ after the other methods are called. - # * Define the various generic +_attribute+ methods that you have declared. - # * Define an +attributes+ method which returns a hash with each - # attribute name in your model as hash key and the attribute value as hash value. - # Hash keys must be strings. - # - # A minimal implementation could be: - # - # class Person - # include ActiveModel::AttributeMethods - # - # attribute_method_affix prefix: 'reset_', suffix: '_to_default!' - # attribute_method_suffix '_contrived?' - # attribute_method_prefix 'clear_' - # define_attribute_methods :name - # - # attr_accessor :name - # - # def attributes - # { 'name' => @name } - # end - # - # private - # - # def attribute_contrived?(attr) - # true - # end - # - # def clear_attribute(attr) - # send("#{attr}=", nil) - # end - # - # def reset_attribute_to_default!(attr) - # send("#{attr}=", 'Default Name') - # end - # end - module AttributeMethods - extend ActiveSupport::Concern - - NAME_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?=]?\z/ - CALL_COMPILABLE_REGEXP = /\A[a-zA-Z_]\w*[!?]?\z/ - - included do - class_attribute :attribute_aliases, :attribute_method_matchers, instance_writer: false - self.attribute_aliases = {} - self.attribute_method_matchers = [ClassMethods::AttributeMethodMatcher.new] - end - - module ClassMethods - # Declares a method available for all attributes with the given prefix. - # Uses +method_missing+ and respond_to? to rewrite the method. - # - # #{prefix}#{attr}(*args, &block) - # - # to - # - # #{prefix}attribute(#{attr}, *args, &block) - # - # An instance method #{prefix}attribute must exist and accept - # at least the +attr+ argument. - # - # class Person - # include ActiveModel::AttributeMethods - # - # attr_accessor :name - # attribute_method_prefix 'clear_' - # define_attribute_methods :name - # - # private - # - # def clear_attribute(attr) - # send("#{attr}=", nil) - # end - # end - # - # person = Person.new - # person.name = 'Bob' - # person.name # => "Bob" - # person.clear_name - # person.name # => nil - def attribute_method_prefix(*prefixes) - self.attribute_method_matchers += prefixes.map! { |prefix| AttributeMethodMatcher.new prefix: prefix } - undefine_attribute_methods - end - - # Declares a method available for all attributes with the given suffix. - # Uses +method_missing+ and respond_to? to rewrite the method. - # - # #{attr}#{suffix}(*args, &block) - # - # to - # - # attribute#{suffix}(#{attr}, *args, &block) - # - # An attribute#{suffix} instance method must exist and accept at - # least the +attr+ argument. - # - # class Person - # include ActiveModel::AttributeMethods - # - # attr_accessor :name - # attribute_method_suffix '_short?' - # define_attribute_methods :name - # - # private - # - # def attribute_short?(attr) - # send(attr).length < 5 - # end - # end - # - # person = Person.new - # person.name = 'Bob' - # person.name # => "Bob" - # person.name_short? # => true - def attribute_method_suffix(*suffixes) - self.attribute_method_matchers += suffixes.map! { |suffix| AttributeMethodMatcher.new suffix: suffix } - undefine_attribute_methods - end - - # Declares a method available for all attributes with the given prefix - # and suffix. Uses +method_missing+ and respond_to? to rewrite - # the method. - # - # #{prefix}#{attr}#{suffix}(*args, &block) - # - # to - # - # #{prefix}attribute#{suffix}(#{attr}, *args, &block) - # - # An #{prefix}attribute#{suffix} instance method must exist and - # accept at least the +attr+ argument. - # - # class Person - # include ActiveModel::AttributeMethods - # - # attr_accessor :name - # attribute_method_affix prefix: 'reset_', suffix: '_to_default!' - # define_attribute_methods :name - # - # private - # - # def reset_attribute_to_default!(attr) - # send("#{attr}=", 'Default Name') - # end - # end - # - # person = Person.new - # person.name # => 'Gem' - # person.reset_name_to_default! - # person.name # => 'Default Name' - def attribute_method_affix(*affixes) - self.attribute_method_matchers += affixes.map! { |affix| AttributeMethodMatcher.new prefix: affix[:prefix], suffix: affix[:suffix] } - undefine_attribute_methods - end - - # Allows you to make aliases for attributes. - # - # class Person - # include ActiveModel::AttributeMethods - # - # attr_accessor :name - # attribute_method_suffix '_short?' - # define_attribute_methods :name - # - # alias_attribute :nickname, :name - # - # private - # - # def attribute_short?(attr) - # send(attr).length < 5 - # end - # end - # - # person = Person.new - # person.name = 'Bob' - # person.name # => "Bob" - # person.nickname # => "Bob" - # person.name_short? # => true - # person.nickname_short? # => true - def alias_attribute(new_name, old_name) - self.attribute_aliases = attribute_aliases.merge(new_name.to_s => old_name.to_s) - attribute_method_matchers.each do |matcher| - matcher_new = matcher.method_name(new_name).to_s - matcher_old = matcher.method_name(old_name).to_s - define_proxy_call false, self, matcher_new, matcher_old - end - end - - # Is +new_name+ an alias? - def attribute_alias?(new_name) - attribute_aliases.key? new_name.to_s - end - - # Returns the original name for the alias +name+ - def attribute_alias(name) - attribute_aliases[name.to_s] - end - - # Declares the attributes that should be prefixed and suffixed by - # ActiveModel::AttributeMethods. - # - # To use, pass attribute names (as strings or symbols). Be sure to declare - # +define_attribute_methods+ after you define any prefix, suffix or affix - # methods, or they will not hook in. - # - # class Person - # include ActiveModel::AttributeMethods - # - # attr_accessor :name, :age, :address - # attribute_method_prefix 'clear_' - # - # # Call to define_attribute_methods must appear after the - # # attribute_method_prefix, attribute_method_suffix or - # # attribute_method_affix declarations. - # define_attribute_methods :name, :age, :address - # - # private - # - # def clear_attribute(attr) - # send("#{attr}=", nil) - # end - # end - def define_attribute_methods(*attr_names) - attr_names.flatten.each { |attr_name| define_attribute_method(attr_name) } - end - - # Declares an attribute that should be prefixed and suffixed by - # ActiveModel::AttributeMethods. - # - # To use, pass an attribute name (as string or symbol). Be sure to declare - # +define_attribute_method+ after you define any prefix, suffix or affix - # method, or they will not hook in. - # - # class Person - # include ActiveModel::AttributeMethods - # - # attr_accessor :name - # attribute_method_suffix '_short?' - # - # # Call to define_attribute_method must appear after the - # # attribute_method_prefix, attribute_method_suffix or - # # attribute_method_affix declarations. - # define_attribute_method :name - # - # private - # - # def attribute_short?(attr) - # send(attr).length < 5 - # end - # end - # - # person = Person.new - # person.name = 'Bob' - # person.name # => "Bob" - # person.name_short? # => true - def define_attribute_method(attr_name) - attribute_method_matchers.each do |matcher| - method_name = matcher.method_name(attr_name) - - unless instance_method_already_implemented?(method_name) - generate_method = "define_method_#{matcher.method_missing_target}" - - if respond_to?(generate_method, true) - send(generate_method, attr_name.to_s) - else - define_proxy_call true, generated_attribute_methods, method_name, matcher.method_missing_target, attr_name.to_s - end - end - end - attribute_method_matchers_cache.clear - end - - # Removes all the previously dynamically defined methods from the class. - # - # class Person - # include ActiveModel::AttributeMethods - # - # attr_accessor :name - # attribute_method_suffix '_short?' - # define_attribute_method :name - # - # private - # - # def attribute_short?(attr) - # send(attr).length < 5 - # end - # end - # - # person = Person.new - # person.name = 'Bob' - # person.name_short? # => true - # - # Person.undefine_attribute_methods - # - # person.name_short? # => NoMethodError - def undefine_attribute_methods - generated_attribute_methods.module_eval do - instance_methods.each { |m| undef_method(m) } - end - attribute_method_matchers_cache.clear - end - - def generated_attribute_methods #:nodoc: - @generated_attribute_methods ||= Module.new { - extend Mutex_m - }.tap { |mod| include mod } - end - - private - def instance_method_already_implemented?(method_name) - generated_attribute_methods.method_defined?(method_name) - end - - # The methods +method_missing+ and +respond_to?+ of this module are - # invoked often in a typical rails, both of which invoke the method - # +matched_attribute_method+. The latter method iterates through an - # array doing regular expression matches, which results in a lot of - # object creations. Most of the time it returns a +nil+ match. As the - # match result is always the same given a +method_name+, this cache is - # used to alleviate the GC, which ultimately also speeds up the app - # significantly (in our case our test suite finishes 10% faster with - # this cache). - def attribute_method_matchers_cache - @attribute_method_matchers_cache ||= Concurrent::Map.new(initial_capacity: 4) - end - - def attribute_method_matchers_matching(method_name) - attribute_method_matchers_cache.compute_if_absent(method_name) do - # Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix - # will match every time. - matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1) - matchers.map { |method| method.match(method_name) }.compact - end - end - - # Define a method `name` in `mod` that dispatches to `send` - # using the given `extra` args. This falls back on `define_method` - # and `send` if the given names cannot be compiled. - def define_proxy_call(include_private, mod, name, send, *extra) - defn = if NAME_COMPILABLE_REGEXP.match?(name) - "def #{name}(*args)" - else - "define_method(:'#{name}') do |*args|" - end - - extra = (extra.map!(&:inspect) << "*args").join(", ".freeze) - - target = if CALL_COMPILABLE_REGEXP.match?(send) - "#{"self." unless include_private}#{send}(#{extra})" - else - "send(:'#{send}', #{extra})" - end - - mod.module_eval <<-RUBY, __FILE__, __LINE__ + 1 - #{defn} - #{target} - end - RUBY - end - - class AttributeMethodMatcher #:nodoc: - attr_reader :prefix, :suffix, :method_missing_target - - AttributeMethodMatch = Struct.new(:target, :attr_name, :method_name) - - def initialize(options = {}) - @prefix, @suffix = options.fetch(:prefix, ""), options.fetch(:suffix, "") - @regex = /^(?:#{Regexp.escape(@prefix)})(.*)(?:#{Regexp.escape(@suffix)})$/ - @method_missing_target = "#{@prefix}attribute#{@suffix}" - @method_name = "#{prefix}%s#{suffix}" - end - - def match(method_name) - if @regex =~ method_name - AttributeMethodMatch.new(method_missing_target, $1, method_name) - end - end - - def method_name(attr_name) - @method_name % attr_name - end - - def plain? - prefix.empty? && suffix.empty? - end - end - end - - # Allows access to the object attributes, which are held in the hash - # returned by attributes, as though they were first-class - # methods. So a +Person+ class with a +name+ attribute can for example use - # Person#name and Person#name= and never directly use - # the attributes hash -- except for multiple assignments with - # ActiveRecord::Base#attributes=. - # - # It's also possible to instantiate related objects, so a Client - # class belonging to the +clients+ table with a +master_id+ foreign key - # can instantiate master through Client#master. - def method_missing(method, *args, &block) - if respond_to_without_attributes?(method, true) - super - else - match = matched_attribute_method(method.to_s) - match ? attribute_missing(match, *args, &block) : super - end - end - - # +attribute_missing+ is like +method_missing+, but for attributes. When - # +method_missing+ is called we check to see if there is a matching - # attribute method. If so, we tell +attribute_missing+ to dispatch the - # attribute. This method can be overloaded to customize the behavior. - def attribute_missing(match, *args, &block) - __send__(match.target, match.attr_name, *args, &block) - end - - # A +Person+ instance with a +name+ attribute can ask - # person.respond_to?(:name), person.respond_to?(:name=), - # and person.respond_to?(:name?) which will all return +true+. - alias :respond_to_without_attributes? :respond_to? - def respond_to?(method, include_private_methods = false) - if super - true - elsif !include_private_methods && super(method, true) - # If we're here then we haven't found among non-private methods - # but found among all methods. Which means that the given method is private. - false - else - !matched_attribute_method(method.to_s).nil? - end - end - - private - def attribute_method?(attr_name) - respond_to_without_attributes?(:attributes) && attributes.include?(attr_name) - end - - # Returns a struct representing the matching attribute method. - # The struct's attributes are prefix, base and suffix. - def matched_attribute_method(method_name) - matches = self.class.send(:attribute_method_matchers_matching, method_name) - matches.detect { |match| attribute_method?(match.attr_name) } - end - - def missing_attribute(attr_name, stack) - raise ActiveModel::MissingAttributeError, "missing attribute: #{attr_name}", stack - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/callbacks.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/callbacks.rb deleted file mode 100644 index eac2761433..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/callbacks.rb +++ /dev/null @@ -1,148 +0,0 @@ -require "active_support/core_ext/array/extract_options" - -module ActiveModel - # == Active \Model \Callbacks - # - # Provides an interface for any class to have Active Record like callbacks. - # - # Like the Active Record methods, the callback chain is aborted as soon as - # one of the methods throws +:abort+. - # - # First, extend ActiveModel::Callbacks from the class you are creating: - # - # class MyModel - # extend ActiveModel::Callbacks - # end - # - # Then define a list of methods that you want callbacks attached to: - # - # define_model_callbacks :create, :update - # - # This will provide all three standard callbacks (before, around and after) - # for both the :create and :update methods. To implement, - # you need to wrap the methods you want callbacks on in a block so that the - # callbacks get a chance to fire: - # - # def create - # run_callbacks :create do - # # Your create action methods here - # end - # end - # - # Then in your class, you can use the +before_create+, +after_create+ and - # +around_create+ methods, just as you would in an Active Record model. - # - # before_create :action_before_create - # - # def action_before_create - # # Your code here - # end - # - # When defining an around callback remember to yield to the block, otherwise - # it won't be executed: - # - # around_create :log_status - # - # def log_status - # puts 'going to call the block...' - # yield - # puts 'block successfully called.' - # end - # - # You can choose to have only specific callbacks by passing a hash to the - # +define_model_callbacks+ method. - # - # define_model_callbacks :create, only: [:after, :before] - # - # Would only create the +after_create+ and +before_create+ callback methods in - # your class. - module Callbacks - def self.extended(base) #:nodoc: - base.class_eval do - include ActiveSupport::Callbacks - end - end - - # define_model_callbacks accepts the same options +define_callbacks+ does, - # in case you want to overwrite a default. Besides that, it also accepts an - # :only option, where you can choose if you want all types (before, - # around or after) or just some. - # - # define_model_callbacks :initializer, only: :after - # - # Note, the only: hash will apply to all callbacks defined - # on that method call. To get around this you can call the define_model_callbacks - # method as many times as you need. - # - # define_model_callbacks :create, only: :after - # define_model_callbacks :update, only: :before - # define_model_callbacks :destroy, only: :around - # - # Would create +after_create+, +before_update+ and +around_destroy+ methods - # only. - # - # You can pass in a class to before_, after_ and around_, - # in which case the callback will call that class's _ method - # passing the object that the callback is being called on. - # - # class MyModel - # extend ActiveModel::Callbacks - # define_model_callbacks :create - # - # before_create AnotherClass - # end - # - # class AnotherClass - # def self.before_create( obj ) - # # obj is the MyModel instance that the callback is being called on - # end - # end - # - # NOTE: +method_name+ passed to `define_model_callbacks` must not end with - # `!`, `?` or `=`. - def define_model_callbacks(*callbacks) - options = callbacks.extract_options! - options = { - skip_after_callbacks_if_terminated: true, - scope: [:kind, :name], - only: [:before, :around, :after] - }.merge!(options) - - types = Array(options.delete(:only)) - - callbacks.each do |callback| - define_callbacks(callback, options) - - types.each do |type| - send("_define_#{type}_model_callback", self, callback) - end - end - end - - private - - def _define_before_model_callback(klass, callback) - klass.define_singleton_method("before_#{callback}") do |*args, &block| - set_callback(:"#{callback}", :before, *args, &block) - end - end - - def _define_around_model_callback(klass, callback) - klass.define_singleton_method("around_#{callback}") do |*args, &block| - set_callback(:"#{callback}", :around, *args, &block) - end - end - - def _define_after_model_callback(klass, callback) - klass.define_singleton_method("after_#{callback}") do |*args, &block| - options = args.extract_options! - options[:prepend] = true - conditional = ActiveSupport::Callbacks::Conditionals::Value.new { |v| - v != false - } - options[:if] = Array(options[:if]) << conditional - set_callback(:"#{callback}", :after, *(args << options), &block) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/conversion.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/conversion.rb deleted file mode 100644 index 12687c70d3..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/conversion.rb +++ /dev/null @@ -1,109 +0,0 @@ -module ActiveModel - # == Active \Model \Conversion - # - # Handles default conversions: to_model, to_key, to_param, and to_partial_path. - # - # Let's take for example this non-persisted object. - # - # class ContactMessage - # include ActiveModel::Conversion - # - # # ContactMessage are never persisted in the DB - # def persisted? - # false - # end - # end - # - # cm = ContactMessage.new - # cm.to_model == cm # => true - # cm.to_key # => nil - # cm.to_param # => nil - # cm.to_partial_path # => "contact_messages/contact_message" - module Conversion - extend ActiveSupport::Concern - - # If your object is already designed to implement all of the \Active \Model - # you can use the default :to_model implementation, which simply - # returns +self+. - # - # class Person - # include ActiveModel::Conversion - # end - # - # person = Person.new - # person.to_model == person # => true - # - # If your model does not act like an \Active \Model object, then you should - # define :to_model yourself returning a proxy object that wraps - # your object with \Active \Model compliant methods. - def to_model - self - end - - # Returns an Array of all key attributes if any of the attributes is set, whether or not - # the object is persisted. Returns +nil+ if there are no key attributes. - # - # class Person - # include ActiveModel::Conversion - # attr_accessor :id - # - # def initialize(id) - # @id = id - # end - # end - # - # person = Person.new(1) - # person.to_key # => [1] - def to_key - key = respond_to?(:id) && id - key ? [key] : nil - end - - # Returns a +string+ representing the object's key suitable for use in URLs, - # or +nil+ if persisted? is +false+. - # - # class Person - # include ActiveModel::Conversion - # attr_accessor :id - # - # def initialize(id) - # @id = id - # end - # - # def persisted? - # true - # end - # end - # - # person = Person.new(1) - # person.to_param # => "1" - def to_param - (persisted? && key = to_key) ? key.join("-") : nil - end - - # Returns a +string+ identifying the path associated with the object. - # ActionPack uses this to find a suitable partial to represent the object. - # - # class Person - # include ActiveModel::Conversion - # end - # - # person = Person.new - # person.to_partial_path # => "people/person" - def to_partial_path - self.class._to_partial_path - end - - module ClassMethods #:nodoc: - # Provide a class level cache for #to_partial_path. This is an - # internal method and should not be accessed directly. - def _to_partial_path #:nodoc: - @_to_partial_path ||= begin - element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(name)) - collection = ActiveSupport::Inflector.tableize(name) - "#{collection}/#{element}".freeze - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/dirty.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/dirty.rb deleted file mode 100644 index 6e0af99ad7..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/dirty.rb +++ /dev/null @@ -1,272 +0,0 @@ -require "active_support/hash_with_indifferent_access" -require "active_support/core_ext/object/duplicable" - -module ActiveModel - # == Active \Model \Dirty - # - # Provides a way to track changes in your object in the same way as - # Active Record does. - # - # The requirements for implementing ActiveModel::Dirty are: - # - # * include ActiveModel::Dirty in your object. - # * Call define_attribute_methods passing each method you want to - # track. - # * Call [attr_name]_will_change! before each change to the tracked - # attribute. - # * Call changes_applied after the changes are persisted. - # * Call clear_changes_information when you want to reset the changes - # information. - # * Call restore_attributes when you want to restore previous data. - # - # A minimal implementation could be: - # - # class Person - # include ActiveModel::Dirty - # - # define_attribute_methods :name - # - # def initialize - # @name = nil - # end - # - # def name - # @name - # end - # - # def name=(val) - # name_will_change! unless val == @name - # @name = val - # end - # - # def save - # # do persistence work - # - # changes_applied - # end - # - # def reload! - # # get the values from the persistence layer - # - # clear_changes_information - # end - # - # def rollback! - # restore_attributes - # end - # end - # - # A newly instantiated +Person+ object is unchanged: - # - # person = Person.new - # person.changed? # => false - # - # Change the name: - # - # person.name = 'Bob' - # person.changed? # => true - # person.name_changed? # => true - # person.name_changed?(from: nil, to: "Bob") # => true - # person.name_was # => nil - # person.name_change # => [nil, "Bob"] - # person.name = 'Bill' - # person.name_change # => [nil, "Bill"] - # - # Save the changes: - # - # person.save - # person.changed? # => false - # person.name_changed? # => false - # - # Reset the changes: - # - # person.previous_changes # => {"name" => [nil, "Bill"]} - # person.name_previously_changed? # => true - # person.name_previous_change # => [nil, "Bill"] - # person.reload! - # person.previous_changes # => {} - # - # Rollback the changes: - # - # person.name = "Uncle Bob" - # person.rollback! - # person.name # => "Bill" - # person.name_changed? # => false - # - # Assigning the same value leaves the attribute unchanged: - # - # person.name = 'Bill' - # person.name_changed? # => false - # person.name_change # => nil - # - # Which attributes have changed? - # - # person.name = 'Bob' - # person.changed # => ["name"] - # person.changes # => {"name" => ["Bill", "Bob"]} - # - # If an attribute is modified in-place then make use of - # [attribute_name]_will_change! to mark that the attribute is changing. - # Otherwise \Active \Model can't track changes to in-place attributes. Note - # that Active Record can detect in-place modifications automatically. You do - # not need to call [attribute_name]_will_change! on Active Record models. - # - # person.name_will_change! - # person.name_change # => ["Bill", "Bill"] - # person.name << 'y' - # person.name_change # => ["Bill", "Billy"] - module Dirty - extend ActiveSupport::Concern - include ActiveModel::AttributeMethods - - OPTION_NOT_GIVEN = Object.new # :nodoc: - private_constant :OPTION_NOT_GIVEN - - included do - attribute_method_suffix "_changed?", "_change", "_will_change!", "_was" - attribute_method_suffix "_previously_changed?", "_previous_change" - attribute_method_affix prefix: "restore_", suffix: "!" - end - - # Returns +true+ if any of the attributes have unsaved changes, +false+ otherwise. - # - # person.changed? # => false - # person.name = 'bob' - # person.changed? # => true - def changed? - changed_attributes.present? - end - - # Returns an array with the name of the attributes with unsaved changes. - # - # person.changed # => [] - # person.name = 'bob' - # person.changed # => ["name"] - def changed - changed_attributes.keys - end - - # Returns a hash of changed attributes indicating their original - # and new values like attr => [original value, new value]. - # - # person.changes # => {} - # person.name = 'bob' - # person.changes # => { "name" => ["bill", "bob"] } - def changes - ActiveSupport::HashWithIndifferentAccess[changed.map { |attr| [attr, attribute_change(attr)] }] - end - - # Returns a hash of attributes that were changed before the model was saved. - # - # person.name # => "bob" - # person.name = 'robert' - # person.save - # person.previous_changes # => {"name" => ["bob", "robert"]} - def previous_changes - @previously_changed ||= ActiveSupport::HashWithIndifferentAccess.new - end - - # Returns a hash of the attributes with unsaved changes indicating their original - # values like attr => original value. - # - # person.name # => "bob" - # person.name = 'robert' - # person.changed_attributes # => {"name" => "bob"} - def changed_attributes - @changed_attributes ||= ActiveSupport::HashWithIndifferentAccess.new - end - - # Handles *_changed? for +method_missing+. - def attribute_changed?(attr, from: OPTION_NOT_GIVEN, to: OPTION_NOT_GIVEN) # :nodoc: - !!changes_include?(attr) && - (to == OPTION_NOT_GIVEN || to == __send__(attr)) && - (from == OPTION_NOT_GIVEN || from == changed_attributes[attr]) - end - - # Handles *_was for +method_missing+. - def attribute_was(attr) # :nodoc: - attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr) - end - - # Handles *_previously_changed? for +method_missing+. - def attribute_previously_changed?(attr) #:nodoc: - previous_changes_include?(attr) - end - - # Restore all previous data of the provided attributes. - def restore_attributes(attributes = changed) - attributes.each { |attr| restore_attribute! attr } - end - - private - - # Returns +true+ if attr_name is changed, +false+ otherwise. - def changes_include?(attr_name) - attributes_changed_by_setter.include?(attr_name) - end - alias attribute_changed_by_setter? changes_include? - - # Returns +true+ if attr_name were changed before the model was saved, - # +false+ otherwise. - def previous_changes_include?(attr_name) - previous_changes.include?(attr_name) - end - - # Removes current changes and makes them accessible through +previous_changes+. - def changes_applied # :doc: - @previously_changed = changes - @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new - end - - # Clears all dirty data: current changes and previous changes. - def clear_changes_information # :doc: - @previously_changed = ActiveSupport::HashWithIndifferentAccess.new - @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new - end - - # Handles *_change for +method_missing+. - def attribute_change(attr) - [changed_attributes[attr], __send__(attr)] if attribute_changed?(attr) - end - - # Handles *_previous_change for +method_missing+. - def attribute_previous_change(attr) - previous_changes[attr] if attribute_previously_changed?(attr) - end - - # Handles *_will_change! for +method_missing+. - def attribute_will_change!(attr) - return if attribute_changed?(attr) - - begin - value = __send__(attr) - value = value.duplicable? ? value.clone : value - rescue TypeError, NoMethodError - end - - set_attribute_was(attr, value) - end - - # Handles restore_*! for +method_missing+. - def restore_attribute!(attr) - if attribute_changed?(attr) - __send__("#{attr}=", changed_attributes[attr]) - clear_attribute_changes([attr]) - end - end - - # This is necessary because `changed_attributes` might be overridden in - # other implementations (e.g. in `ActiveRecord`) - alias_method :attributes_changed_by_setter, :changed_attributes # :nodoc: - - # Force an attribute to have a particular "before" value - def set_attribute_was(attr, old_value) - attributes_changed_by_setter[attr] = old_value - end - - # Remove changes information for the provided attributes. - def clear_attribute_changes(attributes) # :doc: - attributes_changed_by_setter.except!(*attributes) - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/errors.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/errors.rb deleted file mode 100644 index 9df4ca51fe..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/errors.rb +++ /dev/null @@ -1,506 +0,0 @@ -require "active_support/core_ext/array/conversions" -require "active_support/core_ext/string/inflections" -require "active_support/core_ext/object/deep_dup" -require "active_support/core_ext/string/filters" - -module ActiveModel - # == Active \Model \Errors - # - # Provides a modified +Hash+ that you can include in your object - # for handling error messages and interacting with Action View helpers. - # - # A minimal implementation could be: - # - # class Person - # # Required dependency for ActiveModel::Errors - # extend ActiveModel::Naming - # - # def initialize - # @errors = ActiveModel::Errors.new(self) - # end - # - # attr_accessor :name - # attr_reader :errors - # - # def validate! - # errors.add(:name, :blank, message: "cannot be nil") if name.nil? - # end - # - # # The following methods are needed to be minimally implemented - # - # def read_attribute_for_validation(attr) - # send(attr) - # end - # - # def self.human_attribute_name(attr, options = {}) - # attr - # end - # - # def self.lookup_ancestors - # [self] - # end - # end - # - # The last three methods are required in your object for +Errors+ to be - # able to generate error messages correctly and also handle multiple - # languages. Of course, if you extend your object with ActiveModel::Translation - # you will not need to implement the last two. Likewise, using - # ActiveModel::Validations will handle the validation related methods - # for you. - # - # The above allows you to do: - # - # person = Person.new - # person.validate! # => ["cannot be nil"] - # person.errors.full_messages # => ["name cannot be nil"] - # # etc.. - class Errors - include Enumerable - - CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict] - MESSAGE_OPTIONS = [:message] - - attr_reader :messages, :details - - # Pass in the instance of the object that is using the errors object. - # - # class Person - # def initialize - # @errors = ActiveModel::Errors.new(self) - # end - # end - def initialize(base) - @base = base - @messages = apply_default_array({}) - @details = apply_default_array({}) - end - - def initialize_dup(other) # :nodoc: - @messages = other.messages.dup - @details = other.details.deep_dup - super - end - - # Copies the errors from other. - # - # other - The ActiveModel::Errors instance. - # - # Examples - # - # person.errors.copy!(other) - def copy!(other) # :nodoc: - @messages = other.messages.dup - @details = other.details.dup - end - - # Clear the error messages. - # - # person.errors.full_messages # => ["name cannot be nil"] - # person.errors.clear - # person.errors.full_messages # => [] - def clear - messages.clear - details.clear - end - - # Returns +true+ if the error messages include an error for the given key - # +attribute+, +false+ otherwise. - # - # person.errors.messages # => {:name=>["cannot be nil"]} - # person.errors.include?(:name) # => true - # person.errors.include?(:age) # => false - def include?(attribute) - attribute = attribute.to_sym - messages.key?(attribute) && messages[attribute].present? - end - alias :has_key? :include? - alias :key? :include? - - # Delete messages for +key+. Returns the deleted messages. - # - # person.errors[:name] # => ["cannot be nil"] - # person.errors.delete(:name) # => ["cannot be nil"] - # person.errors[:name] # => [] - def delete(key) - attribute = key.to_sym - details.delete(attribute) - messages.delete(attribute) - end - - # When passed a symbol or a name of a method, returns an array of errors - # for the method. - # - # person.errors[:name] # => ["cannot be nil"] - # person.errors['name'] # => ["cannot be nil"] - # - # Note that, if you try to get errors of an attribute which has - # no errors associated with it, this method will instantiate - # an empty error list for it and +keys+ will return an array - # of error keys which includes this attribute. - # - # person.errors.keys # => [] - # person.errors[:name] # => [] - # person.errors.keys # => [:name] - def [](attribute) - messages[attribute.to_sym] - end - - # Iterates through each error key, value pair in the error messages hash. - # Yields the attribute and the error for that attribute. If the attribute - # has more than one error message, yields once for each error message. - # - # person.errors.add(:name, :blank, message: "can't be blank") - # person.errors.each do |attribute, error| - # # Will yield :name and "can't be blank" - # end - # - # person.errors.add(:name, :not_specified, message: "must be specified") - # person.errors.each do |attribute, error| - # # Will yield :name and "can't be blank" - # # then yield :name and "must be specified" - # end - def each - messages.each_key do |attribute| - messages[attribute].each { |error| yield attribute, error } - end - end - - # Returns the number of error messages. - # - # person.errors.add(:name, :blank, message: "can't be blank") - # person.errors.size # => 1 - # person.errors.add(:name, :not_specified, message: "must be specified") - # person.errors.size # => 2 - def size - values.flatten.size - end - alias :count :size - - # Returns all message values. - # - # person.errors.messages # => {:name=>["cannot be nil", "must be specified"]} - # person.errors.values # => [["cannot be nil", "must be specified"]] - def values - messages.values - end - - # Returns all message keys. - # - # person.errors.messages # => {:name=>["cannot be nil", "must be specified"]} - # person.errors.keys # => [:name] - def keys - messages.keys - end - - # Returns +true+ if no errors are found, +false+ otherwise. - # If the error message is a string it can be empty. - # - # person.errors.full_messages # => ["name cannot be nil"] - # person.errors.empty? # => false - def empty? - size.zero? - end - alias :blank? :empty? - - # Returns an xml formatted representation of the Errors hash. - # - # person.errors.add(:name, :blank, message: "can't be blank") - # person.errors.add(:name, :not_specified, message: "must be specified") - # person.errors.to_xml - # # => - # # - # # - # # name can't be blank - # # name must be specified - # # - def to_xml(options = {}) - to_a.to_xml({ root: "errors", skip_types: true }.merge!(options)) - end - - # Returns a Hash that can be used as the JSON representation for this - # object. You can pass the :full_messages option. This determines - # if the json object should contain full messages or not (false by default). - # - # person.errors.as_json # => {:name=>["cannot be nil"]} - # person.errors.as_json(full_messages: true) # => {:name=>["name cannot be nil"]} - def as_json(options = nil) - to_hash(options && options[:full_messages]) - end - - # Returns a Hash of attributes with their error messages. If +full_messages+ - # is +true+, it will contain full messages (see +full_message+). - # - # person.errors.to_hash # => {:name=>["cannot be nil"]} - # person.errors.to_hash(true) # => {:name=>["name cannot be nil"]} - def to_hash(full_messages = false) - if full_messages - messages.each_with_object({}) do |(attribute, array), messages| - messages[attribute] = array.map { |message| full_message(attribute, message) } - end - else - without_default_proc(messages) - end - end - - # Adds +message+ to the error messages and used validator type to +details+ on +attribute+. - # More than one error can be added to the same +attribute+. - # If no +message+ is supplied, :invalid is assumed. - # - # person.errors.add(:name) - # # => ["is invalid"] - # person.errors.add(:name, :not_implemented, message: "must be implemented") - # # => ["is invalid", "must be implemented"] - # - # person.errors.messages - # # => {:name=>["is invalid", "must be implemented"]} - # - # person.errors.details - # # => {:name=>[{error: :not_implemented}, {error: :invalid}]} - # - # If +message+ is a symbol, it will be translated using the appropriate - # scope (see +generate_message+). - # - # If +message+ is a proc, it will be called, allowing for things like - # Time.now to be used within an error. - # - # If the :strict option is set to +true+, it will raise - # ActiveModel::StrictValidationFailed instead of adding the error. - # :strict option can also be set to any other exception. - # - # person.errors.add(:name, :invalid, strict: true) - # # => ActiveModel::StrictValidationFailed: Name is invalid - # person.errors.add(:name, :invalid, strict: NameIsInvalid) - # # => NameIsInvalid: Name is invalid - # - # person.errors.messages # => {} - # - # +attribute+ should be set to :base if the error is not - # directly associated with a single attribute. - # - # person.errors.add(:base, :name_or_email_blank, - # message: "either name or email must be present") - # person.errors.messages - # # => {:base=>["either name or email must be present"]} - # person.errors.details - # # => {:base=>[{error: :name_or_email_blank}]} - def add(attribute, message = :invalid, options = {}) - message = message.call if message.respond_to?(:call) - detail = normalize_detail(message, options) - message = normalize_message(attribute, message, options) - if exception = options[:strict] - exception = ActiveModel::StrictValidationFailed if exception == true - raise exception, full_message(attribute, message) - end - - details[attribute.to_sym] << detail - messages[attribute.to_sym] << message - end - - # Returns +true+ if an error on the attribute with the given message is - # present, or +false+ otherwise. +message+ is treated the same as for +add+. - # - # person.errors.add :name, :blank - # person.errors.added? :name, :blank # => true - # person.errors.added? :name, "can't be blank" # => true - # - # If the error message requires an option, then it returns +true+ with - # the correct option, or +false+ with an incorrect or missing option. - # - # person.errors.add :name, :too_long, { count: 25 } - # person.errors.added? :name, :too_long, count: 25 # => true - # person.errors.added? :name, "is too long (maximum is 25 characters)" # => true - # person.errors.added? :name, :too_long, count: 24 # => false - # person.errors.added? :name, :too_long # => false - # person.errors.added? :name, "is too long" # => false - def added?(attribute, message = :invalid, options = {}) - message = message.call if message.respond_to?(:call) - message = normalize_message(attribute, message, options) - self[attribute].include? message - end - - # Returns all the full error messages in an array. - # - # class Person - # validates_presence_of :name, :address, :email - # validates_length_of :name, in: 5..30 - # end - # - # person = Person.create(address: '123 First St.') - # person.errors.full_messages - # # => ["Name is too short (minimum is 5 characters)", "Name can't be blank", "Email can't be blank"] - def full_messages - map { |attribute, message| full_message(attribute, message) } - end - alias :to_a :full_messages - - # Returns all the full error messages for a given attribute in an array. - # - # class Person - # validates_presence_of :name, :email - # validates_length_of :name, in: 5..30 - # end - # - # person = Person.create() - # person.errors.full_messages_for(:name) - # # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"] - def full_messages_for(attribute) - attribute = attribute.to_sym - messages[attribute].map { |message| full_message(attribute, message) } - end - - # Returns a full message for a given attribute. - # - # person.errors.full_message(:name, 'is invalid') # => "Name is invalid" - def full_message(attribute, message) - return message if attribute == :base - attr_name = attribute.to_s.tr(".", "_").humanize - attr_name = @base.class.human_attribute_name(attribute, default: attr_name) - I18n.t(:"errors.format", - default: "%{attribute} %{message}", - attribute: attr_name, - message: message) - end - - # Translates an error message in its default scope - # (activemodel.errors.messages). - # - # Error messages are first looked up in activemodel.errors.models.MODEL.attributes.ATTRIBUTE.MESSAGE, - # if it's not there, it's looked up in activemodel.errors.models.MODEL.MESSAGE and if - # that is not there also, it returns the translation of the default message - # (e.g. activemodel.errors.messages.MESSAGE). The translated model - # name, translated attribute name and the value are available for - # interpolation. - # - # When using inheritance in your models, it will check all the inherited - # models too, but only if the model itself hasn't been found. Say you have - # class Admin < User; end and you wanted the translation for - # the :blank error message for the title attribute, - # it looks for these translations: - # - # * activemodel.errors.models.admin.attributes.title.blank - # * activemodel.errors.models.admin.blank - # * activemodel.errors.models.user.attributes.title.blank - # * activemodel.errors.models.user.blank - # * any default you provided through the +options+ hash (in the activemodel.errors scope) - # * activemodel.errors.messages.blank - # * errors.attributes.title.blank - # * errors.messages.blank - def generate_message(attribute, type = :invalid, options = {}) - type = options.delete(:message) if options[:message].is_a?(Symbol) - - if @base.class.respond_to?(:i18n_scope) - defaults = @base.class.lookup_ancestors.map do |klass| - [ :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}", - :"#{@base.class.i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ] - end - else - defaults = [] - end - - defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope) - defaults << :"errors.attributes.#{attribute}.#{type}" - defaults << :"errors.messages.#{type}" - - defaults.compact! - defaults.flatten! - - key = defaults.shift - defaults = options.delete(:message) if options[:message] - value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil) - - options = { - default: defaults, - model: @base.model_name.human, - attribute: @base.class.human_attribute_name(attribute), - value: value, - object: @base - }.merge!(options) - - I18n.translate(key, options) - end - - def marshal_dump # :nodoc: - [@base, without_default_proc(@messages), without_default_proc(@details)] - end - - def marshal_load(array) # :nodoc: - @base, @messages, @details = array - apply_default_array(@messages) - apply_default_array(@details) - end - - def init_with(coder) # :nodoc: - coder.map.each { |k, v| instance_variable_set(:"@#{k}", v) } - @details ||= {} - apply_default_array(@messages) - apply_default_array(@details) - end - - private - def normalize_message(attribute, message, options) - case message - when Symbol - generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS)) - else - message - end - end - - def normalize_detail(message, options) - { error: message }.merge(options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS)) - end - - def without_default_proc(hash) - hash.dup.tap do |new_h| - new_h.default_proc = nil - end - end - - def apply_default_array(hash) - hash.default_proc = proc { |h, key| h[key] = [] } - hash - end - end - - # Raised when a validation cannot be corrected by end users and are considered - # exceptional. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # - # validates_presence_of :name, strict: true - # end - # - # person = Person.new - # person.name = nil - # person.valid? - # # => ActiveModel::StrictValidationFailed: Name can't be blank - class StrictValidationFailed < StandardError - end - - # Raised when attribute values are out of range. - class RangeError < ::RangeError - end - - # Raised when unknown attributes are supplied via mass assignment. - # - # class Person - # include ActiveModel::AttributeAssignment - # include ActiveModel::Validations - # end - # - # person = Person.new - # person.assign_attributes(name: 'Gorby') - # # => ActiveModel::UnknownAttributeError: unknown attribute 'name' for Person. - class UnknownAttributeError < NoMethodError - attr_reader :record, :attribute - - def initialize(record, attribute) - @record = record - @attribute = attribute - super("unknown attribute '#{attribute}' for #{@record.class}.") - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/forbidden_attributes_protection.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/forbidden_attributes_protection.rb deleted file mode 100644 index 45ab8a2ca1..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/forbidden_attributes_protection.rb +++ /dev/null @@ -1,29 +0,0 @@ -module ActiveModel - # Raised when forbidden attributes are used for mass assignment. - # - # class Person < ActiveRecord::Base - # end - # - # params = ActionController::Parameters.new(name: 'Bob') - # Person.new(params) - # # => ActiveModel::ForbiddenAttributesError - # - # params.permit! - # Person.new(params) - # # => # - class ForbiddenAttributesError < StandardError - end - - module ForbiddenAttributesProtection # :nodoc: - private - def sanitize_for_mass_assignment(attributes) - if attributes.respond_to?(:permitted?) - raise ActiveModel::ForbiddenAttributesError if !attributes.permitted? - attributes.to_h - else - attributes - end - end - alias :sanitize_forbidden_attributes :sanitize_for_mass_assignment - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/gem_version.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/gem_version.rb deleted file mode 100644 index c1ea11ed5e..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveModel - # Returns the version of the currently loaded \Active \Model as a Gem::Version - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/lint.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/lint.rb deleted file mode 100644 index 291a545528..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/lint.rb +++ /dev/null @@ -1,116 +0,0 @@ -module ActiveModel - module Lint - # == Active \Model \Lint \Tests - # - # You can test whether an object is compliant with the Active \Model API by - # including ActiveModel::Lint::Tests in your TestCase. It will - # include tests that tell you whether your object is fully compliant, - # or if not, which aspects of the API are not implemented. - # - # Note an object is not required to implement all APIs in order to work - # with Action Pack. This module only intends to provide guidance in case - # you want all features out of the box. - # - # These tests do not attempt to determine the semantic correctness of the - # returned values. For instance, you could implement valid? to - # always return +true+, and the tests would pass. It is up to you to ensure - # that the values are semantically meaningful. - # - # Objects you pass in are expected to return a compliant object from a call - # to to_model. It is perfectly fine for to_model to return - # +self+. - module Tests - # Passes if the object's model responds to to_key and if calling - # this method returns +nil+ when the object is not persisted. - # Fails otherwise. - # - # to_key returns an Enumerable of all (primary) key attributes - # of the model, and is used to a generate unique DOM id for the object. - def test_to_key - assert model.respond_to?(:to_key), "The model should respond to to_key" - def model.persisted?() false end - assert model.to_key.nil?, "to_key should return nil when `persisted?` returns false" - end - - # Passes if the object's model responds to to_param and if - # calling this method returns +nil+ when the object is not persisted. - # Fails otherwise. - # - # to_param is used to represent the object's key in URLs. - # Implementers can decide to either raise an exception or provide a - # default in case the record uses a composite primary key. There are no - # tests for this behavior in lint because it doesn't make sense to force - # any of the possible implementation strategies on the implementer. - def test_to_param - assert model.respond_to?(:to_param), "The model should respond to to_param" - def model.to_key() [1] end - def model.persisted?() false end - assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false" - end - - # Passes if the object's model responds to to_partial_path and if - # calling this method returns a string. Fails otherwise. - # - # to_partial_path is used for looking up partials. For example, - # a BlogPost model might return "blog_posts/blog_post". - def test_to_partial_path - assert model.respond_to?(:to_partial_path), "The model should respond to to_partial_path" - assert_kind_of String, model.to_partial_path - end - - # Passes if the object's model responds to persisted? and if - # calling this method returns either +true+ or +false+. Fails otherwise. - # - # persisted? is used when calculating the URL for an object. - # If the object is not persisted, a form for that object, for instance, - # will route to the create action. If it is persisted, a form for the - # object will route to the update action. - def test_persisted? - assert model.respond_to?(:persisted?), "The model should respond to persisted?" - assert_boolean model.persisted?, "persisted?" - end - - # Passes if the object's model responds to model_name both as - # an instance method and as a class method, and if calling this method - # returns a string with some convenience methods: :human, - # :singular and :plural. - # - # Check ActiveModel::Naming for more information. - def test_model_naming - assert model.class.respond_to?(:model_name), "The model class should respond to model_name" - model_name = model.class.model_name - assert model_name.respond_to?(:to_str) - assert model_name.human.respond_to?(:to_str) - assert model_name.singular.respond_to?(:to_str) - assert model_name.plural.respond_to?(:to_str) - - assert model.respond_to?(:model_name), "The model instance should respond to model_name" - assert_equal model.model_name, model.class.model_name - end - - # Passes if the object's model responds to errors and if calling - # [](attribute) on the result of this method returns an array. - # Fails otherwise. - # - # errors[attribute] is used to retrieve the errors of a model - # for a given attribute. If errors are present, the method should return - # an array of strings that are the errors for the attribute in question. - # If localization is used, the strings should be localized for the current - # locale. If no error is present, the method should return an empty array. - def test_errors_aref - assert model.respond_to?(:errors), "The model should respond to errors" - assert model.errors[:hello].is_a?(Array), "errors#[] should return an Array" - end - - private - def model - assert @model.respond_to?(:to_model), "The object should respond to to_model" - @model.to_model - end - - def assert_boolean(result, name) - assert result == true || result == false, "#{name} should be a boolean" - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/locale/en.yml b/debian/gems-compat/activemodel-5.1.7/lib/active_model/locale/en.yml deleted file mode 100644 index 061e35dd1e..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/locale/en.yml +++ /dev/null @@ -1,36 +0,0 @@ -en: - errors: - # The default format to use in full error messages. - format: "%{attribute} %{message}" - - # The values :model, :attribute and :value are always available for interpolation - # The value :count is available when applicable. Can be used for pluralization. - messages: - model_invalid: "Validation failed: %{errors}" - inclusion: "is not included in the list" - exclusion: "is reserved" - invalid: "is invalid" - confirmation: "doesn't match %{attribute}" - accepted: "must be accepted" - empty: "can't be empty" - blank: "can't be blank" - present: "must be blank" - too_long: - one: "is too long (maximum is 1 character)" - other: "is too long (maximum is %{count} characters)" - too_short: - one: "is too short (minimum is 1 character)" - other: "is too short (minimum is %{count} characters)" - wrong_length: - one: "is the wrong length (should be 1 character)" - other: "is the wrong length (should be %{count} characters)" - not_a_number: "is not a number" - not_an_integer: "must be an integer" - greater_than: "must be greater than %{count}" - greater_than_or_equal_to: "must be greater than or equal to %{count}" - equal_to: "must be equal to %{count}" - less_than: "must be less than %{count}" - less_than_or_equal_to: "must be less than or equal to %{count}" - other_than: "must be other than %{count}" - odd: "must be odd" - even: "must be even" diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/model.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/model.rb deleted file mode 100644 index 945a5402a3..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/model.rb +++ /dev/null @@ -1,97 +0,0 @@ -module ActiveModel - # == Active \Model \Basic \Model - # - # Includes the required interface for an object to interact with - # Action Pack and Action View, using different Active Model modules. - # It includes model name introspections, conversions, translations and - # validations. Besides that, it allows you to initialize the object with a - # hash of attributes, pretty much like Active Record does. - # - # A minimal implementation could be: - # - # class Person - # include ActiveModel::Model - # attr_accessor :name, :age - # end - # - # person = Person.new(name: 'bob', age: '18') - # person.name # => "bob" - # person.age # => "18" - # - # Note that, by default, ActiveModel::Model implements persisted? - # to return +false+, which is the most common case. You may want to override - # it in your class to simulate a different scenario: - # - # class Person - # include ActiveModel::Model - # attr_accessor :id, :name - # - # def persisted? - # self.id == 1 - # end - # end - # - # person = Person.new(id: 1, name: 'bob') - # person.persisted? # => true - # - # Also, if for some reason you need to run code on initialize, make - # sure you call +super+ if you want the attributes hash initialization to - # happen. - # - # class Person - # include ActiveModel::Model - # attr_accessor :id, :name, :omg - # - # def initialize(attributes={}) - # super - # @omg ||= true - # end - # end - # - # person = Person.new(id: 1, name: 'bob') - # person.omg # => true - # - # For more detailed information on other functionalities available, please - # refer to the specific modules included in ActiveModel::Model - # (see below). - module Model - extend ActiveSupport::Concern - include ActiveModel::AttributeAssignment - include ActiveModel::Validations - include ActiveModel::Conversion - - included do - extend ActiveModel::Naming - extend ActiveModel::Translation - end - - # Initializes a new model with the given +params+. - # - # class Person - # include ActiveModel::Model - # attr_accessor :name, :age - # end - # - # person = Person.new(name: 'bob', age: '18') - # person.name # => "bob" - # person.age # => "18" - def initialize(attributes = {}) - assign_attributes(attributes) if attributes - - super() - end - - # Indicates if the model is persisted. Default is +false+. - # - # class Person - # include ActiveModel::Model - # attr_accessor :id, :name - # end - # - # person = Person.new(id: 1, name: 'bob') - # person.persisted? # => false - def persisted? - false - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/naming.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/naming.rb deleted file mode 100644 index 9853cf38fe..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/naming.rb +++ /dev/null @@ -1,316 +0,0 @@ -require "active_support/core_ext/hash/except" -require "active_support/core_ext/module/introspection" -require "active_support/core_ext/module/remove_method" - -module ActiveModel - class Name - include Comparable - - attr_reader :singular, :plural, :element, :collection, - :singular_route_key, :route_key, :param_key, :i18n_key, - :name - - alias_method :cache_key, :collection - - ## - # :method: == - # - # :call-seq: - # ==(other) - # - # Equivalent to String#==. Returns +true+ if the class name and - # +other+ are equal, otherwise +false+. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name == 'BlogPost' # => true - # BlogPost.model_name == 'Blog Post' # => false - - ## - # :method: === - # - # :call-seq: - # ===(other) - # - # Equivalent to #==. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name === 'BlogPost' # => true - # BlogPost.model_name === 'Blog Post' # => false - - ## - # :method: <=> - # - # :call-seq: - # ==(other) - # - # Equivalent to String#<=>. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name <=> 'BlogPost' # => 0 - # BlogPost.model_name <=> 'Blog' # => 1 - # BlogPost.model_name <=> 'BlogPosts' # => -1 - - ## - # :method: =~ - # - # :call-seq: - # =~(regexp) - # - # Equivalent to String#=~. Match the class name against the given - # regexp. Returns the position where the match starts or +nil+ if there is - # no match. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name =~ /Post/ # => 4 - # BlogPost.model_name =~ /\d/ # => nil - - ## - # :method: !~ - # - # :call-seq: - # !~(regexp) - # - # Equivalent to String#!~. Match the class name against the given - # regexp. Returns +true+ if there is no match, otherwise +false+. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name !~ /Post/ # => false - # BlogPost.model_name !~ /\d/ # => true - - ## - # :method: eql? - # - # :call-seq: - # eql?(other) - # - # Equivalent to String#eql?. Returns +true+ if the class name and - # +other+ have the same length and content, otherwise +false+. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name.eql?('BlogPost') # => true - # BlogPost.model_name.eql?('Blog Post') # => false - - ## - # :method: to_s - # - # :call-seq: - # to_s() - # - # Returns the class name. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name.to_s # => "BlogPost" - - ## - # :method: to_str - # - # :call-seq: - # to_str() - # - # Equivalent to +to_s+. - delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s, - :to_str, :as_json, to: :name - - # Returns a new ActiveModel::Name instance. By default, the +namespace+ - # and +name+ option will take the namespace and name of the given class - # respectively. - # - # module Foo - # class Bar - # end - # end - # - # ActiveModel::Name.new(Foo::Bar).to_s - # # => "Foo::Bar" - def initialize(klass, namespace = nil, name = nil) - @name = name || klass.name - - raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank? - - @unnamespaced = @name.sub(/^#{namespace.name}::/, "") if namespace - @klass = klass - @singular = _singularize(@name) - @plural = ActiveSupport::Inflector.pluralize(@singular) - @element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name)) - @human = ActiveSupport::Inflector.humanize(@element) - @collection = ActiveSupport::Inflector.tableize(@name) - @param_key = (namespace ? _singularize(@unnamespaced) : @singular) - @i18n_key = @name.underscore.to_sym - - @route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key) : @plural.dup) - @singular_route_key = ActiveSupport::Inflector.singularize(@route_key) - @route_key << "_index" if @plural == @singular - end - - # Transform the model name into a more human format, using I18n. By default, - # it will underscore then humanize the class name. - # - # class BlogPost - # extend ActiveModel::Naming - # end - # - # BlogPost.model_name.human # => "Blog post" - # - # Specify +options+ with additional translating options. - def human(options = {}) - return @human unless @klass.respond_to?(:lookup_ancestors) && - @klass.respond_to?(:i18n_scope) - - defaults = @klass.lookup_ancestors.map do |klass| - klass.model_name.i18n_key - end - - defaults << options[:default] if options[:default] - defaults << @human - - options = { scope: [@klass.i18n_scope, :models], count: 1, default: defaults }.merge!(options.except(:default)) - I18n.translate(defaults.shift, options) - end - - private - - def _singularize(string) - ActiveSupport::Inflector.underscore(string).tr("/".freeze, "_".freeze) - end - end - - # == Active \Model \Naming - # - # Creates a +model_name+ method on your object. - # - # To implement, just extend ActiveModel::Naming in your object: - # - # class BookCover - # extend ActiveModel::Naming - # end - # - # BookCover.model_name.name # => "BookCover" - # BookCover.model_name.human # => "Book cover" - # - # BookCover.model_name.i18n_key # => :book_cover - # BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover" - # - # Providing the functionality that ActiveModel::Naming provides in your object - # is required to pass the \Active \Model Lint test. So either extending the - # provided method below, or rolling your own is required. - module Naming - def self.extended(base) #:nodoc: - base.remove_possible_method :model_name - base.delegate :model_name, to: :class - end - - # Returns an ActiveModel::Name object for module. It can be - # used to retrieve all kinds of naming-related information - # (See ActiveModel::Name for more information). - # - # class Person - # extend ActiveModel::Naming - # end - # - # Person.model_name.name # => "Person" - # Person.model_name.class # => ActiveModel::Name - # Person.model_name.singular # => "person" - # Person.model_name.plural # => "people" - def model_name - @_model_name ||= begin - namespace = parents.detect do |n| - n.respond_to?(:use_relative_model_naming?) && n.use_relative_model_naming? - end - ActiveModel::Name.new(self, namespace) - end - end - - # Returns the plural class name of a record or class. - # - # ActiveModel::Naming.plural(post) # => "posts" - # ActiveModel::Naming.plural(Highrise::Person) # => "highrise_people" - def self.plural(record_or_class) - model_name_from_record_or_class(record_or_class).plural - end - - # Returns the singular class name of a record or class. - # - # ActiveModel::Naming.singular(post) # => "post" - # ActiveModel::Naming.singular(Highrise::Person) # => "highrise_person" - def self.singular(record_or_class) - model_name_from_record_or_class(record_or_class).singular - end - - # Identifies whether the class name of a record or class is uncountable. - # - # ActiveModel::Naming.uncountable?(Sheep) # => true - # ActiveModel::Naming.uncountable?(Post) # => false - def self.uncountable?(record_or_class) - plural(record_or_class) == singular(record_or_class) - end - - # Returns string to use while generating route names. It differs for - # namespaced models regarding whether it's inside isolated engine. - # - # # For isolated engine: - # ActiveModel::Naming.singular_route_key(Blog::Post) # => "post" - # - # # For shared engine: - # ActiveModel::Naming.singular_route_key(Blog::Post) # => "blog_post" - def self.singular_route_key(record_or_class) - model_name_from_record_or_class(record_or_class).singular_route_key - end - - # Returns string to use while generating route names. It differs for - # namespaced models regarding whether it's inside isolated engine. - # - # # For isolated engine: - # ActiveModel::Naming.route_key(Blog::Post) # => "posts" - # - # # For shared engine: - # ActiveModel::Naming.route_key(Blog::Post) # => "blog_posts" - # - # The route key also considers if the noun is uncountable and, in - # such cases, automatically appends _index. - def self.route_key(record_or_class) - model_name_from_record_or_class(record_or_class).route_key - end - - # Returns string to use for params names. It differs for - # namespaced models regarding whether it's inside isolated engine. - # - # # For isolated engine: - # ActiveModel::Naming.param_key(Blog::Post) # => "post" - # - # # For shared engine: - # ActiveModel::Naming.param_key(Blog::Post) # => "blog_post" - def self.param_key(record_or_class) - model_name_from_record_or_class(record_or_class).param_key - end - - def self.model_name_from_record_or_class(record_or_class) #:nodoc: - if record_or_class.respond_to?(:to_model) - record_or_class.to_model.model_name - else - record_or_class.model_name - end - end - private_class_method :model_name_from_record_or_class - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/railtie.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/railtie.rb deleted file mode 100644 index 1671eb7bd4..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/railtie.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "active_model" -require "rails" - -module ActiveModel - class Railtie < Rails::Railtie # :nodoc: - config.eager_load_namespaces << ActiveModel - - initializer "active_model.secure_password" do - ActiveModel::SecurePassword.min_cost = Rails.env.test? - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/secure_password.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/secure_password.rb deleted file mode 100644 index 1c0fe92bc0..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/secure_password.rb +++ /dev/null @@ -1,127 +0,0 @@ -module ActiveModel - module SecurePassword - extend ActiveSupport::Concern - - # BCrypt hash function can handle maximum 72 characters, and if we pass - # password of length more than 72 characters it ignores extra characters. - # Hence need to put a restriction on password length. - MAX_PASSWORD_LENGTH_ALLOWED = 72 - - class << self - attr_accessor :min_cost # :nodoc: - end - self.min_cost = false - - module ClassMethods - # Adds methods to set and authenticate against a BCrypt password. - # This mechanism requires you to have a +password_digest+ attribute. - # - # The following validations are added automatically: - # * Password must be present on creation - # * Password length should be less than or equal to 72 characters - # * Confirmation of password (using a +password_confirmation+ attribute) - # - # If password confirmation validation is not needed, simply leave out the - # value for +password_confirmation+ (i.e. don't provide a form field for - # it). When this attribute has a +nil+ value, the validation will not be - # triggered. - # - # For further customizability, it is possible to suppress the default - # validations by passing validations: false as an argument. - # - # Add bcrypt (~> 3.1.7) to Gemfile to use #has_secure_password: - # - # gem 'bcrypt', '~> 3.1.7' - # - # Example using Active Record (which automatically includes ActiveModel::SecurePassword): - # - # # Schema: User(name:string, password_digest:string) - # class User < ActiveRecord::Base - # has_secure_password - # end - # - # user = User.new(name: 'david', password: '', password_confirmation: 'nomatch') - # user.save # => false, password required - # user.password = 'mUc3m00RsqyRe' - # user.save # => false, confirmation doesn't match - # user.password_confirmation = 'mUc3m00RsqyRe' - # user.save # => true - # user.authenticate('notright') # => false - # user.authenticate('mUc3m00RsqyRe') # => user - # User.find_by(name: 'david').try(:authenticate, 'notright') # => false - # User.find_by(name: 'david').try(:authenticate, 'mUc3m00RsqyRe') # => user - def has_secure_password(options = {}) - # Load bcrypt gem only when has_secure_password is used. - # This is to avoid ActiveModel (and by extension the entire framework) - # being dependent on a binary library. - begin - require "bcrypt" - rescue LoadError - $stderr.puts "You don't have bcrypt installed in your application. Please add it to your Gemfile and run bundle install" - raise - end - - include InstanceMethodsOnActivation - - if options.fetch(:validations, true) - include ActiveModel::Validations - - # This ensures the model has a password by checking whether the password_digest - # is present, so that this works with both new and existing records. However, - # when there is an error, the message is added to the password attribute instead - # so that the error message will make sense to the end-user. - validate do |record| - record.errors.add(:password, :blank) unless record.password_digest.present? - end - - validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED - validates_confirmation_of :password, allow_blank: true - end - end - end - - module InstanceMethodsOnActivation - # Returns +self+ if the password is correct, otherwise +false+. - # - # class User < ActiveRecord::Base - # has_secure_password validations: false - # end - # - # user = User.new(name: 'david', password: 'mUc3m00RsqyRe') - # user.save - # user.authenticate('notright') # => false - # user.authenticate('mUc3m00RsqyRe') # => user - def authenticate(unencrypted_password) - BCrypt::Password.new(password_digest).is_password?(unencrypted_password) && self - end - - attr_reader :password - - # Encrypts the password into the +password_digest+ attribute, only if the - # new password is not empty. - # - # class User < ActiveRecord::Base - # has_secure_password validations: false - # end - # - # user = User.new - # user.password = nil - # user.password_digest # => nil - # user.password = 'mUc3m00RsqyRe' - # user.password_digest # => "$2a$10$4LEA7r4YmNHtvlAvHhsYAeZmk/xeUVtMTYqwIvYY76EW5GUqDiP4." - def password=(unencrypted_password) - if unencrypted_password.nil? - self.password_digest = nil - elsif !unencrypted_password.empty? - @password = unencrypted_password - cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost - self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost) - end - end - - def password_confirmation=(unencrypted_password) - @password_confirmation = unencrypted_password - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/serialization.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/serialization.rb deleted file mode 100644 index 77834f26fc..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/serialization.rb +++ /dev/null @@ -1,190 +0,0 @@ -require "active_support/core_ext/hash/except" -require "active_support/core_ext/hash/slice" - -module ActiveModel - # == Active \Model \Serialization - # - # Provides a basic serialization to a serializable_hash for your objects. - # - # A minimal implementation could be: - # - # class Person - # include ActiveModel::Serialization - # - # attr_accessor :name - # - # def attributes - # {'name' => nil} - # end - # end - # - # Which would provide you with: - # - # person = Person.new - # person.serializable_hash # => {"name"=>nil} - # person.name = "Bob" - # person.serializable_hash # => {"name"=>"Bob"} - # - # An +attributes+ hash must be defined and should contain any attributes you - # need to be serialized. Attributes must be strings, not symbols. - # When called, serializable hash will use instance methods that match the name - # of the attributes hash's keys. In order to override this behavior, take a look - # at the private method +read_attribute_for_serialization+. - # - # ActiveModel::Serializers::JSON module automatically includes - # the ActiveModel::Serialization module, so there is no need to - # explicitly include ActiveModel::Serialization. - # - # A minimal implementation including JSON would be: - # - # class Person - # include ActiveModel::Serializers::JSON - # - # attr_accessor :name - # - # def attributes - # {'name' => nil} - # end - # end - # - # Which would provide you with: - # - # person = Person.new - # person.serializable_hash # => {"name"=>nil} - # person.as_json # => {"name"=>nil} - # person.to_json # => "{\"name\":null}" - # - # person.name = "Bob" - # person.serializable_hash # => {"name"=>"Bob"} - # person.as_json # => {"name"=>"Bob"} - # person.to_json # => "{\"name\":\"Bob\"}" - # - # Valid options are :only, :except, :methods and - # :include. The following are all valid examples: - # - # person.serializable_hash(only: 'name') - # person.serializable_hash(include: :address) - # person.serializable_hash(include: { address: { only: 'city' }}) - module Serialization - # Returns a serialized hash of your object. - # - # class Person - # include ActiveModel::Serialization - # - # attr_accessor :name, :age - # - # def attributes - # {'name' => nil, 'age' => nil} - # end - # - # def capitalized_name - # name.capitalize - # end - # end - # - # person = Person.new - # person.name = 'bob' - # person.age = 22 - # person.serializable_hash # => {"name"=>"bob", "age"=>22} - # person.serializable_hash(only: :name) # => {"name"=>"bob"} - # person.serializable_hash(except: :name) # => {"age"=>22} - # person.serializable_hash(methods: :capitalized_name) - # # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"} - # - # Example with :include option - # - # class User - # include ActiveModel::Serializers::JSON - # attr_accessor :name, :notes # Emulate has_many :notes - # def attributes - # {'name' => nil} - # end - # end - # - # class Note - # include ActiveModel::Serializers::JSON - # attr_accessor :title, :text - # def attributes - # {'title' => nil, 'text' => nil} - # end - # end - # - # note = Note.new - # note.title = 'Battle of Austerlitz' - # note.text = 'Some text here' - # - # user = User.new - # user.name = 'Napoleon' - # user.notes = [note] - # - # user.serializable_hash - # # => {"name" => "Napoleon"} - # user.serializable_hash(include: { notes: { only: 'title' }}) - # # => {"name" => "Napoleon", "notes" => [{"title"=>"Battle of Austerlitz"}]} - def serializable_hash(options = nil) - options ||= {} - - attribute_names = attributes.keys - if only = options[:only] - attribute_names &= Array(only).map(&:to_s) - elsif except = options[:except] - attribute_names -= Array(except).map(&:to_s) - end - - hash = {} - attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) } - - Array(options[:methods]).each { |m| hash[m.to_s] = send(m) } - - serializable_add_includes(options) do |association, records, opts| - hash[association.to_s] = if records.respond_to?(:to_ary) - records.to_ary.map { |a| a.serializable_hash(opts) } - else - records.serializable_hash(opts) - end - end - - hash - end - - private - - # Hook method defining how an attribute value should be retrieved for - # serialization. By default this is assumed to be an instance named after - # the attribute. Override this method in subclasses should you need to - # retrieve the value for a given attribute differently: - # - # class MyClass - # include ActiveModel::Serialization - # - # def initialize(data = {}) - # @data = data - # end - # - # def read_attribute_for_serialization(key) - # @data[key] - # end - # end - alias :read_attribute_for_serialization :send - - # Add associations specified via the :include option. - # - # Expects a block that takes as arguments: - # +association+ - name of the association - # +records+ - the association record(s) to be serialized - # +opts+ - options for the association records - def serializable_add_includes(options = {}) #:nodoc: - return unless includes = options[:include] - - unless includes.is_a?(Hash) - includes = Hash[Array(includes).map { |n| n.is_a?(Hash) ? n.to_a.first : [n, {}] }] - end - - includes.each do |association, opts| - if records = send(association) - yield association, records, opts - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/serializers/json.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/serializers/json.rb deleted file mode 100644 index a9d92eb92a..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/serializers/json.rb +++ /dev/null @@ -1,145 +0,0 @@ -require "active_support/json" - -module ActiveModel - module Serializers - # == Active \Model \JSON \Serializer - module JSON - extend ActiveSupport::Concern - include ActiveModel::Serialization - - included do - extend ActiveModel::Naming - - class_attribute :include_root_in_json, instance_writer: false - self.include_root_in_json = false - end - - # Returns a hash representing the model. Some configuration can be - # passed through +options+. - # - # The option include_root_in_json controls the top-level behavior - # of +as_json+. If +true+, +as_json+ will emit a single root node named - # after the object's type. The default value for include_root_in_json - # option is +false+. - # - # user = User.find(1) - # user.as_json - # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, - # # "created_at" => "2006/08/01", "awesome" => true} - # - # ActiveRecord::Base.include_root_in_json = true - # - # user.as_json - # # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16, - # # "created_at" => "2006/08/01", "awesome" => true } } - # - # This behavior can also be achieved by setting the :root option - # to +true+ as in: - # - # user = User.find(1) - # user.as_json(root: true) - # # => { "user" => { "id" => 1, "name" => "Konata Izumi", "age" => 16, - # # "created_at" => "2006/08/01", "awesome" => true } } - # - # Without any +options+, the returned Hash will include all the model's - # attributes. - # - # user = User.find(1) - # user.as_json - # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, - # # "created_at" => "2006/08/01", "awesome" => true} - # - # The :only and :except options can be used to limit - # the attributes included, and work similar to the +attributes+ method. - # - # user.as_json(only: [:id, :name]) - # # => { "id" => 1, "name" => "Konata Izumi" } - # - # user.as_json(except: [:id, :created_at, :age]) - # # => { "name" => "Konata Izumi", "awesome" => true } - # - # To include the result of some method calls on the model use :methods: - # - # user.as_json(methods: :permalink) - # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, - # # "created_at" => "2006/08/01", "awesome" => true, - # # "permalink" => "1-konata-izumi" } - # - # To include associations use :include: - # - # user.as_json(include: :posts) - # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, - # # "created_at" => "2006/08/01", "awesome" => true, - # # "posts" => [ { "id" => 1, "author_id" => 1, "title" => "Welcome to the weblog" }, - # # { "id" => 2, "author_id" => 1, "title" => "So I was thinking" } ] } - # - # Second level and higher order associations work as well: - # - # user.as_json(include: { posts: { - # include: { comments: { - # only: :body } }, - # only: :title } }) - # # => { "id" => 1, "name" => "Konata Izumi", "age" => 16, - # # "created_at" => "2006/08/01", "awesome" => true, - # # "posts" => [ { "comments" => [ { "body" => "1st post!" }, { "body" => "Second!" } ], - # # "title" => "Welcome to the weblog" }, - # # { "comments" => [ { "body" => "Don't think too hard" } ], - # # "title" => "So I was thinking" } ] } - def as_json(options = nil) - root = if options && options.key?(:root) - options[:root] - else - include_root_in_json - end - - if root - root = model_name.element if root == true - { root => serializable_hash(options) } - else - serializable_hash(options) - end - end - - # Sets the model +attributes+ from a JSON string. Returns +self+. - # - # class Person - # include ActiveModel::Serializers::JSON - # - # attr_accessor :name, :age, :awesome - # - # def attributes=(hash) - # hash.each do |key, value| - # send("#{key}=", value) - # end - # end - # - # def attributes - # instance_values - # end - # end - # - # json = { name: 'bob', age: 22, awesome:true }.to_json - # person = Person.new - # person.from_json(json) # => # - # person.name # => "bob" - # person.age # => 22 - # person.awesome # => true - # - # The default value for +include_root+ is +false+. You can change it to - # +true+ if the given JSON string includes a single root node. - # - # json = { person: { name: 'bob', age: 22, awesome:true } }.to_json - # person = Person.new - # person.from_json(json, true) # => # - # person.name # => "bob" - # person.age # => 22 - # person.awesome # => true - def from_json(json, include_root = include_root_in_json) - hash = ActiveSupport::JSON.decode(json) - hash = hash.values.first if include_root - self.attributes = hash - self - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/translation.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/translation.rb deleted file mode 100644 index 35fc7cf743..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/translation.rb +++ /dev/null @@ -1,68 +0,0 @@ -module ActiveModel - # == Active \Model \Translation - # - # Provides integration between your object and the Rails internationalization - # (i18n) framework. - # - # A minimal implementation could be: - # - # class TranslatedPerson - # extend ActiveModel::Translation - # end - # - # TranslatedPerson.human_attribute_name('my_attribute') - # # => "My attribute" - # - # This also provides the required class methods for hooking into the - # Rails internationalization API, including being able to define a - # class based +i18n_scope+ and +lookup_ancestors+ to find translations in - # parent classes. - module Translation - include ActiveModel::Naming - - # Returns the +i18n_scope+ for the class. Overwrite if you want custom lookup. - def i18n_scope - :activemodel - end - - # When localizing a string, it goes through the lookup returned by this - # method, which is used in ActiveModel::Name#human, - # ActiveModel::Errors#full_messages and - # ActiveModel::Translation#human_attribute_name. - def lookup_ancestors - ancestors.select { |x| x.respond_to?(:model_name) } - end - - # Transforms attribute names into a more human format, such as "First name" - # instead of "first_name". - # - # Person.human_attribute_name("first_name") # => "First name" - # - # Specify +options+ with additional translating options. - def human_attribute_name(attribute, options = {}) - options = { count: 1 }.merge!(options) - parts = attribute.to_s.split(".") - attribute = parts.pop - namespace = parts.join("/") unless parts.empty? - attributes_scope = "#{i18n_scope}.attributes" - - if namespace - defaults = lookup_ancestors.map do |klass| - :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}" - end - defaults << :"#{attributes_scope}.#{namespace}.#{attribute}" - else - defaults = lookup_ancestors.map do |klass| - :"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}" - end - end - - defaults << :"attributes.#{attribute}" - defaults << options.delete(:default) if options[:default] - defaults << attribute.humanize - - options[:default] = defaults - I18n.translate(defaults.shift, options) - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type.rb deleted file mode 100644 index 095801d8f0..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type.rb +++ /dev/null @@ -1,47 +0,0 @@ -require "active_model/type/helpers" -require "active_model/type/value" - -require "active_model/type/big_integer" -require "active_model/type/binary" -require "active_model/type/boolean" -require "active_model/type/date" -require "active_model/type/date_time" -require "active_model/type/decimal" -require "active_model/type/float" -require "active_model/type/immutable_string" -require "active_model/type/integer" -require "active_model/type/string" -require "active_model/type/time" - -require "active_model/type/registry" - -module ActiveModel - module Type - @registry = Registry.new - - class << self - attr_accessor :registry # :nodoc: - - # Add a new type to the registry, allowing it to be get through ActiveModel::Type#lookup - def register(type_name, klass = nil, **options, &block) - registry.register(type_name, klass, **options, &block) - end - - def lookup(*args, **kwargs) # :nodoc: - registry.lookup(*args, **kwargs) - end - end - - register(:big_integer, Type::BigInteger) - register(:binary, Type::Binary) - register(:boolean, Type::Boolean) - register(:date, Type::Date) - register(:datetime, Type::DateTime) - register(:decimal, Type::Decimal) - register(:float, Type::Float) - register(:immutable_string, Type::ImmutableString) - register(:integer, Type::Integer) - register(:string, Type::String) - register(:time, Type::Time) - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/big_integer.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/big_integer.rb deleted file mode 100644 index 3b629682fe..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/big_integer.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "active_model/type/integer" - -module ActiveModel - module Type - class BigInteger < Integer # :nodoc: - private - - def max_value - ::Float::INFINITY - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/binary.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/binary.rb deleted file mode 100644 index 819e4e4a96..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/binary.rb +++ /dev/null @@ -1,50 +0,0 @@ -module ActiveModel - module Type - class Binary < Value # :nodoc: - def type - :binary - end - - def binary? - true - end - - def cast(value) - if value.is_a?(Data) - value.to_s - else - super - end - end - - def serialize(value) - return if value.nil? - Data.new(super) - end - - def changed_in_place?(raw_old_value, value) - old_value = deserialize(raw_old_value) - old_value != value - end - - class Data # :nodoc: - def initialize(value) - @value = value.to_s - end - - def to_s - @value - end - alias_method :to_str, :to_s - - def hex - @value.unpack("H*")[0] - end - - def ==(other) - other == to_s || super - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/boolean.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/boolean.rb deleted file mode 100644 index f2a47370a3..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/boolean.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveModel - module Type - # == Active \Model \Type \Boolean - # - # A class that behaves like a boolean type, including rules for coercion of user input. - # - # === Coercion - # Values set from user input will first be coerced into the appropriate ruby type. - # Coercion behavior is roughly mapped to Ruby's boolean semantics. - # - # - "false", "f" , "0", +0+ or any other value in +FALSE_VALUES+ will be coerced to +false+ - # - Empty strings are coerced to +nil+ - # - All other values will be coerced to +true+ - class Boolean < Value - FALSE_VALUES = [false, 0, "0", "f", "F", "false", "FALSE", "off", "OFF"].to_set - - def type # :nodoc: - :boolean - end - - private - - def cast_value(value) - if value == "" - nil - else - !FALSE_VALUES.include?(value) - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/date.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/date.rb deleted file mode 100644 index eefd080351..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/date.rb +++ /dev/null @@ -1,54 +0,0 @@ -module ActiveModel - module Type - class Date < Value # :nodoc: - include Helpers::AcceptsMultiparameterTime.new - - def type - :date - end - - def serialize(value) - cast(value) - end - - def type_cast_for_schema(value) - value.to_s(:db).inspect - end - - private - - def cast_value(value) - if value.is_a?(::String) - return if value.empty? - fast_string_to_date(value) || fallback_string_to_date(value) - elsif value.respond_to?(:to_date) - value.to_date - else - value - end - end - - ISO_DATE = /\A(\d{4})-(\d\d)-(\d\d)\z/ - def fast_string_to_date(string) - if string =~ ISO_DATE - new_date $1.to_i, $2.to_i, $3.to_i - end - end - - def fallback_string_to_date(string) - new_date(*::Date._parse(string, false).values_at(:year, :mon, :mday)) - end - - def new_date(year, mon, mday) - if year && year != 0 - ::Date.new(year, mon, mday) rescue nil - end - end - - def value_from_multiparameter_assignment(*) - time = super - time && time.to_date - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/date_time.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/date_time.rb deleted file mode 100644 index 5cb0077e45..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/date_time.rb +++ /dev/null @@ -1,44 +0,0 @@ -module ActiveModel - module Type - class DateTime < Value # :nodoc: - include Helpers::TimeValue - include Helpers::AcceptsMultiparameterTime.new( - defaults: { 4 => 0, 5 => 0 } - ) - - def type - :datetime - end - - private - - def cast_value(value) - return apply_seconds_precision(value) unless value.is_a?(::String) - return if value.empty? - - fast_string_to_time(value) || fallback_string_to_time(value) - end - - # '0.123456' -> 123456 - # '1.123456' -> 123456 - def microseconds(time) - time[:sec_fraction] ? (time[:sec_fraction] * 1_000_000).to_i : 0 - end - - def fallback_string_to_time(string) - time_hash = ::Date._parse(string) - time_hash[:sec_fraction] = microseconds(time_hash) - - new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset)) - end - - def value_from_multiparameter_assignment(values_hash) - missing_parameter = (1..3).detect { |key| !values_hash.key?(key) } - if missing_parameter - raise ArgumentError, missing_parameter - end - super - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/decimal.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/decimal.rb deleted file mode 100644 index e6805c5f6b..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/decimal.rb +++ /dev/null @@ -1,68 +0,0 @@ -require "bigdecimal/util" - -module ActiveModel - module Type - class Decimal < Value # :nodoc: - include Helpers::Numeric - BIGDECIMAL_PRECISION = 18 - - def type - :decimal - end - - def type_cast_for_schema(value) - value.to_s.inspect - end - - private - - def cast_value(value) - casted_value = \ - case value - when ::Float - convert_float_to_big_decimal(value) - when ::Numeric - BigDecimal(value, precision || BIGDECIMAL_PRECISION) - when ::String - begin - value.to_d - rescue ArgumentError - BigDecimal(0) - end - else - if value.respond_to?(:to_d) - value.to_d - else - cast_value(value.to_s) - end - end - - apply_scale(casted_value) - end - - def convert_float_to_big_decimal(value) - if precision - BigDecimal(apply_scale(value), float_precision) - else - value.to_d - end - end - - def float_precision - if precision.to_i > ::Float::DIG + 1 - ::Float::DIG + 1 - else - precision.to_i - end - end - - def apply_scale(value) - if scale - value.round(scale) - else - value - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/float.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/float.rb deleted file mode 100644 index 4d0d2771a0..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/float.rb +++ /dev/null @@ -1,34 +0,0 @@ -module ActiveModel - module Type - class Float < Value # :nodoc: - include Helpers::Numeric - - def type - :float - end - - def type_cast_for_schema(value) - return "::Float::NAN" if value.try(:nan?) - case value - when ::Float::INFINITY then "::Float::INFINITY" - when -::Float::INFINITY then "-::Float::INFINITY" - else super - end - end - - alias serialize cast - - private - - def cast_value(value) - case value - when ::Float then value - when "Infinity" then ::Float::INFINITY - when "-Infinity" then -::Float::INFINITY - when "NaN" then ::Float::NAN - else value.to_f - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers.rb deleted file mode 100644 index 82cd9ebe98..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers.rb +++ /dev/null @@ -1,4 +0,0 @@ -require "active_model/type/helpers/accepts_multiparameter_time" -require "active_model/type/helpers/numeric" -require "active_model/type/helpers/mutable" -require "active_model/type/helpers/time_value" diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/accepts_multiparameter_time.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/accepts_multiparameter_time.rb deleted file mode 100644 index f783d286c5..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/accepts_multiparameter_time.rb +++ /dev/null @@ -1,35 +0,0 @@ -module ActiveModel - module Type - module Helpers # :nodoc: all - class AcceptsMultiparameterTime < Module - def initialize(defaults: {}) - define_method(:cast) do |value| - if value.is_a?(Hash) - value_from_multiparameter_assignment(value) - else - super(value) - end - end - - define_method(:assert_valid_value) do |value| - if value.is_a?(Hash) - value_from_multiparameter_assignment(value) - else - super(value) - end - end - - define_method(:value_from_multiparameter_assignment) do |values_hash| - defaults.each do |k, v| - values_hash[k] ||= v - end - return unless values_hash[1] && values_hash[2] && values_hash[3] - values = values_hash.sort.map(&:last) - ::Time.send(default_timezone, *values) - end - private :value_from_multiparameter_assignment - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/mutable.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/mutable.rb deleted file mode 100644 index f3a17a1698..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/mutable.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActiveModel - module Type - module Helpers # :nodoc: all - module Mutable - def cast(value) - deserialize(serialize(value)) - end - - # +raw_old_value+ will be the `_before_type_cast` version of the - # value (likely a string). +new_value+ will be the current, type - # cast value. - def changed_in_place?(raw_old_value, new_value) - raw_old_value != serialize(new_value) - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/numeric.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/numeric.rb deleted file mode 100644 index 275822b738..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/numeric.rb +++ /dev/null @@ -1,35 +0,0 @@ -module ActiveModel - module Type - module Helpers # :nodoc: all - module Numeric - def cast(value) - value = \ - case value - when true then 1 - when false then 0 - when ::String then value.presence - else value - end - super(value) - end - - def changed?(old_value, _new_value, new_value_before_type_cast) # :nodoc: - super || number_to_non_number?(old_value, new_value_before_type_cast) - end - - private - - def number_to_non_number?(old_value, new_value_before_type_cast) - old_value != nil && non_numeric_string?(new_value_before_type_cast) - end - - def non_numeric_string?(value) - # 'wibble'.to_i will give zero, we want to make sure - # that we aren't marking int zero to string zero as - # changed. - value.to_s !~ /\A-?\d+\.?\d*\z/ - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/time_value.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/time_value.rb deleted file mode 100644 index f78f1ddcd7..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/helpers/time_value.rb +++ /dev/null @@ -1,78 +0,0 @@ -require "active_support/core_ext/string/zones" -require "active_support/core_ext/time/zones" - -module ActiveModel - module Type - module Helpers # :nodoc: all - module TimeValue - def serialize(value) - value = apply_seconds_precision(value) - - if value.acts_like?(:time) - zone_conversion_method = is_utc? ? :getutc : :getlocal - - if value.respond_to?(zone_conversion_method) - value = value.send(zone_conversion_method) - end - end - - value - end - - def is_utc? - ::Time.zone_default.nil? || ::Time.zone_default =~ "UTC" - end - - def default_timezone - if is_utc? - :utc - else - :local - end - end - - def apply_seconds_precision(value) - return value unless precision && value.respond_to?(:usec) - number_of_insignificant_digits = 6 - precision - round_power = 10**number_of_insignificant_digits - value.change(usec: value.usec - value.usec % round_power) - end - - def type_cast_for_schema(value) - value.to_s(:db).inspect - end - - def user_input_in_time_zone(value) - value.in_time_zone - end - - private - - def new_time(year, mon, mday, hour, min, sec, microsec, offset = nil) - # Treat 0000-00-00 00:00:00 as nil. - return if year.nil? || (year == 0 && mon == 0 && mday == 0) - - if offset - time = ::Time.utc(year, mon, mday, hour, min, sec, microsec) rescue nil - return unless time - - time -= offset - is_utc? ? time : time.getlocal - else - ::Time.public_send(default_timezone, year, mon, mday, hour, min, sec, microsec) rescue nil - end - end - - ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/ - - # Doesn't handle time zones. - def fast_string_to_time(string) - if string =~ ISO_DATETIME - microsec = ($7.to_r * 1_000_000).to_i - new_time $1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, microsec - end - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/immutable_string.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/immutable_string.rb deleted file mode 100644 index 58268540e5..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/immutable_string.rb +++ /dev/null @@ -1,30 +0,0 @@ -module ActiveModel - module Type - class ImmutableString < Value # :nodoc: - def type - :string - end - - def serialize(value) - case value - when ::Numeric, ActiveSupport::Duration then value.to_s - when true then "t" - when false then "f" - else super - end - end - - private - - def cast_value(value) - result = \ - case value - when true then "t" - when false then "f" - else value.to_s - end - result.freeze - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/integer.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/integer.rb deleted file mode 100644 index 106b5d966c..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/integer.rb +++ /dev/null @@ -1,68 +0,0 @@ -module ActiveModel - module Type - class Integer < Value # :nodoc: - include Helpers::Numeric - - # Column storage size in bytes. - # 4 bytes means a MySQL int or Postgres integer as opposed to smallint etc. - DEFAULT_LIMIT = 4 - - def initialize(*) - super - @range = min_value...max_value - end - - def type - :integer - end - - def deserialize(value) - return if value.nil? - value.to_i - end - - def serialize(value) - result = cast(value) - if result - ensure_in_range(result) - end - result - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :range - - private - - def cast_value(value) - case value - when true then 1 - when false then 0 - else - value.to_i rescue nil - end - end - - def ensure_in_range(value) - unless range.cover?(value) - raise ActiveModel::RangeError, "#{value} is out of range for #{self.class} with limit #{_limit} bytes" - end - end - - def max_value - 1 << (_limit * 8 - 1) # 8 bits per byte with one bit for sign - end - - def min_value - -max_value - end - - def _limit - limit || DEFAULT_LIMIT - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/registry.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/registry.rb deleted file mode 100644 index 2d5dd366eb..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/registry.rb +++ /dev/null @@ -1,68 +0,0 @@ -module ActiveModel - # :stopdoc: - module Type - class Registry - def initialize - @registrations = [] - end - - def register(type_name, klass = nil, **options, &block) - block ||= proc { |_, *args| klass.new(*args) } - registrations << registration_klass.new(type_name, block, **options) - end - - def lookup(symbol, *args) - registration = find_registration(symbol, *args) - - if registration - registration.call(self, symbol, *args) - else - raise ArgumentError, "Unknown type #{symbol.inspect}" - end - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :registrations - - private - - def registration_klass - Registration - end - - def find_registration(symbol, *args) - registrations.find { |r| r.matches?(symbol, *args) } - end - end - - class Registration - # Options must be taken because of https://bugs.ruby-lang.org/issues/10856 - def initialize(name, block, **) - @name = name - @block = block - end - - def call(_registry, *args, **kwargs) - if kwargs.any? # https://bugs.ruby-lang.org/issues/10856 - block.call(*args, **kwargs) - else - block.call(*args) - end - end - - def matches?(type_name, *args, **kwargs) - type_name == name - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :name, :block - end - end - # :startdoc: -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/string.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/string.rb deleted file mode 100644 index 850cab962b..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/string.rb +++ /dev/null @@ -1,24 +0,0 @@ -require "active_model/type/immutable_string" - -module ActiveModel - module Type - class String < ImmutableString # :nodoc: - def changed_in_place?(raw_old_value, new_value) - if new_value.is_a?(::String) - raw_old_value != new_value - end - end - - private - - def cast_value(value) - case value - when ::String then ::String.new(value) - when true then "t".freeze - when false then "f".freeze - else value.to_s - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/time.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/time.rb deleted file mode 100644 index fdc7240735..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/time.rb +++ /dev/null @@ -1,44 +0,0 @@ -module ActiveModel - module Type - class Time < Value # :nodoc: - include Helpers::TimeValue - include Helpers::AcceptsMultiparameterTime.new( - defaults: { 1 => 1970, 2 => 1, 3 => 1, 4 => 0, 5 => 0 } - ) - - def type - :time - end - - def user_input_in_time_zone(value) - return unless value.present? - - case value - when ::String - value = "2000-01-01 #{value}" - time_hash = ::Date._parse(value) - return if time_hash[:hour].nil? - when ::Time - value = value.change(year: 2000, day: 1, month: 1) - end - - super(value) - end - - private - - def cast_value(value) - return apply_seconds_precision(value) unless value.is_a?(::String) - return if value.empty? - - dummy_time_value = value.sub(/\A(\d\d\d\d-\d\d-\d\d |)/, "2000-01-01 ") - - fast_string_to_time(dummy_time_value) || begin - time_hash = ::Date._parse(dummy_time_value) - return if time_hash[:hour].nil? - new_time(*time_hash.values_at(:year, :mon, :mday, :hour, :min, :sec, :sec_fraction, :offset)) - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/value.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/value.rb deleted file mode 100644 index 3b2e0ced50..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/type/value.rb +++ /dev/null @@ -1,120 +0,0 @@ -module ActiveModel - module Type - class Value - attr_reader :precision, :scale, :limit - - def initialize(precision: nil, limit: nil, scale: nil) - @precision = precision - @scale = scale - @limit = limit - end - - def type # :nodoc: - end - - # Converts a value from database input to the appropriate ruby type. The - # return value of this method will be returned from - # ActiveRecord::AttributeMethods::Read#read_attribute. The default - # implementation just calls Value#cast. - # - # +value+ The raw input, as provided from the database. - def deserialize(value) - cast(value) - end - - # Type casts a value from user input (e.g. from a setter). This value may - # be a string from the form builder, or a ruby object passed to a setter. - # There is currently no way to differentiate between which source it came - # from. - # - # The return value of this method will be returned from - # ActiveRecord::AttributeMethods::Read#read_attribute. See also: - # Value#cast_value. - # - # +value+ The raw input, as provided to the attribute setter. - def cast(value) - cast_value(value) unless value.nil? - end - - # Casts a value from the ruby type to a type that the database knows how - # to understand. The returned value from this method should be a - # +String+, +Numeric+, +Date+, +Time+, +Symbol+, +true+, +false+, or - # +nil+. - def serialize(value) - value - end - - # Type casts a value for schema dumping. This method is private, as we are - # hoping to remove it entirely. - def type_cast_for_schema(value) # :nodoc: - value.inspect - end - - # These predicates are not documented, as I need to look further into - # their use, and see if they can be removed entirely. - def binary? # :nodoc: - false - end - - # Determines whether a value has changed for dirty checking. +old_value+ - # and +new_value+ will always be type-cast. Types should not need to - # override this method. - def changed?(old_value, new_value, _new_value_before_type_cast) - old_value != new_value - end - - # Determines whether the mutable value has been modified since it was - # read. Returns +false+ by default. If your type returns an object - # which could be mutated, you should override this method. You will need - # to either: - # - # - pass +new_value+ to Value#serialize and compare it to - # +raw_old_value+ - # - # or - # - # - pass +raw_old_value+ to Value#deserialize and compare it to - # +new_value+ - # - # +raw_old_value+ The original value, before being passed to - # +deserialize+. - # - # +new_value+ The current value, after type casting. - def changed_in_place?(raw_old_value, new_value) - false - end - - def force_equality?(_value) # :nodoc: - false - end - - def map(value) # :nodoc: - yield value - end - - def ==(other) - self.class == other.class && - precision == other.precision && - scale == other.scale && - limit == other.limit - end - alias eql? == - - def hash - [self.class, precision, scale, limit].hash - end - - def assert_valid_value(*) - end - - private - - # Convenience method for types which do not need separate type casting - # behavior for user and database inputs. Called by Value#cast for - # values except +nil+. - def cast_value(value) # :doc: - value - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations.rb deleted file mode 100644 index d460068830..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations.rb +++ /dev/null @@ -1,435 +0,0 @@ -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/hash/keys" -require "active_support/core_ext/hash/except" - -module ActiveModel - # == Active \Model \Validations - # - # Provides a full validation framework to your objects. - # - # A minimal implementation could be: - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :first_name, :last_name - # - # validates_each :first_name, :last_name do |record, attr, value| - # record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z - # end - # end - # - # Which provides you with the full standard validation stack that you - # know from Active Record: - # - # person = Person.new - # person.valid? # => true - # person.invalid? # => false - # - # person.first_name = 'zoolander' - # person.valid? # => false - # person.invalid? # => true - # person.errors.messages # => {first_name:["starts with z."]} - # - # Note that ActiveModel::Validations automatically adds an +errors+ - # method to your instances initialized with a new ActiveModel::Errors - # object, so there is no need for you to do this manually. - module Validations - extend ActiveSupport::Concern - - included do - extend ActiveModel::Naming - extend ActiveModel::Callbacks - extend ActiveModel::Translation - - extend HelperMethods - include HelperMethods - - attr_accessor :validation_context - private :validation_context= - define_callbacks :validate, scope: :name - - class_attribute :_validators, instance_writer: false - self._validators = Hash.new { |h, k| h[k] = [] } - end - - module ClassMethods - # Validates each attribute against a block. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :first_name, :last_name - # - # validates_each :first_name, :last_name, allow_blank: true do |record, attr, value| - # record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z - # end - # end - # - # Options: - # * :on - Specifies the contexts where this validation is active. - # Runs in all validation contexts by default +nil+. You can pass a symbol - # or an array of symbols. (e.g. on: :create or - # on: :custom_validation_context or - # on: [:create, :custom_validation_context]) - # * :allow_nil - Skip validation if attribute is +nil+. - # * :allow_blank - Skip validation if attribute is blank. - # * :if - Specifies a method, proc or string to call to determine - # if the validation should occur (e.g. if: :allow_validation, - # or if: Proc.new { |user| user.signup_step > 2 }). The method, - # proc or string should return or evaluate to a +true+ or +false+ value. - # * :unless - Specifies a method, proc or string to call to - # determine if the validation should not occur (e.g. unless: :skip_validation, - # or unless: Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a +true+ or +false+ - # value. - def validates_each(*attr_names, &block) - validates_with BlockValidator, _merge_attributes(attr_names), &block - end - - VALID_OPTIONS_FOR_VALIDATE = [:on, :if, :unless, :prepend].freeze # :nodoc: - - # Adds a validation method or block to the class. This is useful when - # overriding the +validate+ instance method becomes too unwieldy and - # you're looking for more descriptive declaration of your validations. - # - # This can be done with a symbol pointing to a method: - # - # class Comment - # include ActiveModel::Validations - # - # validate :must_be_friends - # - # def must_be_friends - # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee) - # end - # end - # - # With a block which is passed with the current record to be validated: - # - # class Comment - # include ActiveModel::Validations - # - # validate do |comment| - # comment.must_be_friends - # end - # - # def must_be_friends - # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee) - # end - # end - # - # Or with a block where self points to the current record to be validated: - # - # class Comment - # include ActiveModel::Validations - # - # validate do - # errors.add(:base, 'Must be friends to leave a comment') unless commenter.friend_of?(commentee) - # end - # end - # - # Note that the return value of validation methods is not relevant. - # It's not possible to halt the validate callback chain. - # - # Options: - # * :on - Specifies the contexts where this validation is active. - # Runs in all validation contexts by default +nil+. You can pass a symbol - # or an array of symbols. (e.g. on: :create or - # on: :custom_validation_context or - # on: [:create, :custom_validation_context]) - # * :if - Specifies a method, proc or string to call to determine - # if the validation should occur (e.g. if: :allow_validation, - # or if: Proc.new { |user| user.signup_step > 2 }). The method, - # proc or string should return or evaluate to a +true+ or +false+ value. - # * :unless - Specifies a method, proc or string to call to - # determine if the validation should not occur (e.g. unless: :skip_validation, - # or unless: Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a +true+ or +false+ - # value. - def validate(*args, &block) - options = args.extract_options! - - if args.all? { |arg| arg.is_a?(Symbol) } - options.each_key do |k| - unless VALID_OPTIONS_FOR_VALIDATE.include?(k) - raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{VALID_OPTIONS_FOR_VALIDATE.map(&:inspect).join(', ')}. Perhaps you meant to call `validates` instead of `validate`?") - end - end - end - - if options.key?(:on) - options = options.dup - options[:if] = Array(options[:if]) - options[:if].unshift ->(o) { - !(Array(options[:on]) & Array(o.validation_context)).empty? - } - end - - args << options - set_callback(:validate, *args, &block) - end - - # List all validators that are being used to validate the model using - # +validates_with+ method. - # - # class Person - # include ActiveModel::Validations - # - # validates_with MyValidator - # validates_with OtherValidator, on: :create - # validates_with StrictValidator, strict: true - # end - # - # Person.validators - # # => [ - # # #, - # # #, - # # # - # # ] - def validators - _validators.values.flatten.uniq - end - - # Clears all of the validators and validations. - # - # Note that this will clear anything that is being used to validate - # the model for both the +validates_with+ and +validate+ methods. - # It clears the validators that are created with an invocation of - # +validates_with+ and the callbacks that are set by an invocation - # of +validate+. - # - # class Person - # include ActiveModel::Validations - # - # validates_with MyValidator - # validates_with OtherValidator, on: :create - # validates_with StrictValidator, strict: true - # validate :cannot_be_robot - # - # def cannot_be_robot - # errors.add(:base, 'A person cannot be a robot') if person_is_robot - # end - # end - # - # Person.validators - # # => [ - # # #, - # # #, - # # # - # # ] - # - # If one runs Person.clear_validators! and then checks to see what - # validators this class has, you would obtain: - # - # Person.validators # => [] - # - # Also, the callback set by validate :cannot_be_robot will be erased - # so that: - # - # Person._validate_callbacks.empty? # => true - # - def clear_validators! - reset_callbacks(:validate) - _validators.clear - end - - # List all validators that are being used to validate a specific attribute. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name , :age - # - # validates_presence_of :name - # validates_inclusion_of :age, in: 0..99 - # end - # - # Person.validators_on(:name) - # # => [ - # # #, - # # ] - def validators_on(*attributes) - attributes.flat_map do |attribute| - _validators[attribute.to_sym] - end - end - - # Returns +true+ if +attribute+ is an attribute method, +false+ otherwise. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # end - # - # User.attribute_method?(:name) # => true - # User.attribute_method?(:age) # => false - def attribute_method?(attribute) - method_defined?(attribute) - end - - # Copy validators on inheritance. - def inherited(base) #:nodoc: - dup = _validators.dup - base._validators = dup.each { |k, v| dup[k] = v.dup } - super - end - end - - # Clean the +Errors+ object if instance is duped. - def initialize_dup(other) #:nodoc: - @errors = nil - super - end - - # Returns the +Errors+ object that holds all information about attribute - # error messages. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # validates_presence_of :name - # end - # - # person = Person.new - # person.valid? # => false - # person.errors # => # - def errors - @errors ||= Errors.new(self) - end - - # Runs all the specified validations and returns +true+ if no errors were - # added otherwise +false+. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # validates_presence_of :name - # end - # - # person = Person.new - # person.name = '' - # person.valid? # => false - # person.name = 'david' - # person.valid? # => true - # - # Context can optionally be supplied to define which callbacks to test - # against (the context is defined on the validations using :on). - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # validates_presence_of :name, on: :new - # end - # - # person = Person.new - # person.valid? # => true - # person.valid?(:new) # => false - def valid?(context = nil) - current_context, self.validation_context = validation_context, context - errors.clear - run_validations! - ensure - self.validation_context = current_context - end - - alias_method :validate, :valid? - - # Performs the opposite of valid?. Returns +true+ if errors were - # added, +false+ otherwise. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # validates_presence_of :name - # end - # - # person = Person.new - # person.name = '' - # person.invalid? # => true - # person.name = 'david' - # person.invalid? # => false - # - # Context can optionally be supplied to define which callbacks to test - # against (the context is defined on the validations using :on). - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # validates_presence_of :name, on: :new - # end - # - # person = Person.new - # person.invalid? # => false - # person.invalid?(:new) # => true - def invalid?(context = nil) - !valid?(context) - end - - # Runs all the validations within the specified context. Returns +true+ if - # no errors are found, raises +ValidationError+ otherwise. - # - # Validations with no :on option will run no matter the context. Validations with - # some :on option will only run in the specified context. - def validate!(context = nil) - valid?(context) || raise_validation_error - end - - # Hook method defining how an attribute value should be retrieved. By default - # this is assumed to be an instance named after the attribute. Override this - # method in subclasses should you need to retrieve the value for a given - # attribute differently: - # - # class MyClass - # include ActiveModel::Validations - # - # def initialize(data = {}) - # @data = data - # end - # - # def read_attribute_for_validation(key) - # @data[key] - # end - # end - alias :read_attribute_for_validation :send - - private - - def run_validations! - _run_validate_callbacks - errors.empty? - end - - def raise_validation_error # :doc: - raise(ValidationError.new(self)) - end - end - - # = Active Model ValidationError - # - # Raised by validate! when the model is invalid. Use the - # +model+ method to retrieve the record which did not validate. - # - # begin - # complex_operation_that_internally_calls_validate! - # rescue ActiveModel::ValidationError => invalid - # puts invalid.model.errors - # end - class ValidationError < StandardError - attr_reader :model - - def initialize(model) - @model = model - errors = @model.errors.full_messages.join(", ") - super(I18n.t(:"#{@model.class.i18n_scope}.errors.messages.model_invalid", errors: errors, default: :"errors.messages.model_invalid")) - end - end -end - -Dir[File.dirname(__FILE__) + "/validations/*.rb"].each { |file| require file } diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/absence.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/absence.rb deleted file mode 100644 index 4618f46e30..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/absence.rb +++ /dev/null @@ -1,31 +0,0 @@ -module ActiveModel - module Validations - # == \Active \Model Absence Validator - class AbsenceValidator < EachValidator #:nodoc: - def validate_each(record, attr_name, value) - record.errors.add(attr_name, :present, options) if value.present? - end - end - - module HelperMethods - # Validates that the specified attributes are blank (as defined by - # Object#blank?). Happens by default on save. - # - # class Person < ActiveRecord::Base - # validates_absence_of :first_name - # end - # - # The first_name attribute must be in the object and it must be blank. - # - # Configuration options: - # * :message - A custom error message (default is: "must be blank"). - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. - # See ActiveModel::Validations#validates for more information - def validates_absence_of(*attr_names) - validates_with AbsenceValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/acceptance.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/acceptance.rb deleted file mode 100644 index a26c37daa5..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/acceptance.rb +++ /dev/null @@ -1,104 +0,0 @@ -module ActiveModel - module Validations - class AcceptanceValidator < EachValidator # :nodoc: - def initialize(options) - super({ allow_nil: true, accept: ["1", true] }.merge!(options)) - setup!(options[:class]) - end - - def validate_each(record, attribute, value) - unless acceptable_option?(value) - record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil)) - end - end - - private - - def setup!(klass) - klass.include(LazilyDefineAttributes.new(AttributeDefinition.new(attributes))) - end - - def acceptable_option?(value) - Array(options[:accept]).include?(value) - end - - class LazilyDefineAttributes < Module - def initialize(attribute_definition) - define_method(:respond_to_missing?) do |method_name, include_private = false| - super(method_name, include_private) || attribute_definition.matches?(method_name) - end - - define_method(:method_missing) do |method_name, *args, &block| - if attribute_definition.matches?(method_name) - attribute_definition.define_on(self.class) - send(method_name, *args, &block) - else - super(method_name, *args, &block) - end - end - end - end - - class AttributeDefinition - def initialize(attributes) - @attributes = attributes.map(&:to_s) - end - - def matches?(method_name) - attr_name = convert_to_reader_name(method_name) - attributes.include?(attr_name) - end - - def define_on(klass) - attr_readers = attributes.reject { |name| klass.attribute_method?(name) } - attr_writers = attributes.reject { |name| klass.attribute_method?("#{name}=") } - klass.send(:attr_reader, *attr_readers) - klass.send(:attr_writer, *attr_writers) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :attributes - - private - - def convert_to_reader_name(method_name) - method_name.to_s.chomp("=") - end - end - end - - module HelperMethods - # Encapsulates the pattern of wanting to validate the acceptance of a - # terms of service check box (or similar agreement). - # - # class Person < ActiveRecord::Base - # validates_acceptance_of :terms_of_service - # validates_acceptance_of :eula, message: 'must be abided' - # end - # - # If the database column does not exist, the +terms_of_service+ attribute - # is entirely virtual. This check is performed only if +terms_of_service+ - # is not +nil+ and by default on save. - # - # Configuration options: - # * :message - A custom error message (default is: "must be - # accepted"). - # * :accept - Specifies a value that is considered accepted. - # Also accepts an array of possible values. The default value is - # an array ["1", true], which makes it easy to relate to an HTML - # checkbox. This should be set to, or include, +true+ if you are validating - # a database column, since the attribute is typecast from "1" to +true+ - # before validation. - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. - # See ActiveModel::Validations#validates for more information. - def validates_acceptance_of(*attr_names) - validates_with AcceptanceValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/callbacks.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/callbacks.rb deleted file mode 100644 index 5e3a8b81c7..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/callbacks.rb +++ /dev/null @@ -1,118 +0,0 @@ -module ActiveModel - module Validations - # == Active \Model \Validation \Callbacks - # - # Provides an interface for any class to have +before_validation+ and - # +after_validation+ callbacks. - # - # First, include ActiveModel::Validations::Callbacks from the class you are - # creating: - # - # class MyModel - # include ActiveModel::Validations::Callbacks - # - # before_validation :do_stuff_before_validation - # after_validation :do_stuff_after_validation - # end - # - # Like other before_* callbacks if +before_validation+ throws - # +:abort+ then valid? will not be called. - module Callbacks - extend ActiveSupport::Concern - - included do - include ActiveSupport::Callbacks - define_callbacks :validation, - skip_after_callbacks_if_terminated: true, - scope: [:kind, :name] - end - - module ClassMethods - # Defines a callback that will get called right before validation. - # - # class Person - # include ActiveModel::Validations - # include ActiveModel::Validations::Callbacks - # - # attr_accessor :name - # - # validates_length_of :name, maximum: 6 - # - # before_validation :remove_whitespaces - # - # private - # - # def remove_whitespaces - # name.strip! - # end - # end - # - # person = Person.new - # person.name = ' bob ' - # person.valid? # => true - # person.name # => "bob" - def before_validation(*args, &block) - options = args.extract_options! - options[:if] = Array(options[:if]) - - if options.key?(:on) - options[:if].unshift ->(o) { - !(Array(options[:on]) & Array(o.validation_context)).empty? - } - end - - args << options - set_callback(:validation, :before, *args, &block) - end - - # Defines a callback that will get called right after validation. - # - # class Person - # include ActiveModel::Validations - # include ActiveModel::Validations::Callbacks - # - # attr_accessor :name, :status - # - # validates_presence_of :name - # - # after_validation :set_status - # - # private - # - # def set_status - # self.status = errors.empty? - # end - # end - # - # person = Person.new - # person.name = '' - # person.valid? # => false - # person.status # => false - # person.name = 'bob' - # person.valid? # => true - # person.status # => true - def after_validation(*args, &block) - options = args.extract_options! - options[:prepend] = true - options[:if] = Array(options[:if]) - - if options.key?(:on) - options[:if].unshift ->(o) { - !(Array(options[:on]) & Array(o.validation_context)).empty? - } - end - - args << options - set_callback(:validation, :after, *args, &block) - end - end - - private - - # Overwrite run validations to include callbacks. - def run_validations! - _run_validation_callbacks { super } - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/clusivity.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/clusivity.rb deleted file mode 100644 index 18f1056e2b..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/clusivity.rb +++ /dev/null @@ -1,52 +0,0 @@ -require "active_support/core_ext/range" - -module ActiveModel - module Validations - module Clusivity #:nodoc: - ERROR_MESSAGE = "An object with the method #include? or a proc, lambda or symbol is required, " \ - "and must be supplied as the :in (or :within) option of the configuration hash" - - def check_validity! - unless delimiter.respond_to?(:include?) || delimiter.respond_to?(:call) || delimiter.respond_to?(:to_sym) - raise ArgumentError, ERROR_MESSAGE - end - end - - private - - def include?(record, value) - members = if delimiter.respond_to?(:call) - delimiter.call(record) - elsif delimiter.respond_to?(:to_sym) - record.send(delimiter) - else - delimiter - end - - members.send(inclusion_method(members), value) - end - - def delimiter - @delimiter ||= options[:in] || options[:within] - end - - # In Ruby 2.2 Range#include? on non-number-or-time-ish ranges checks all - # possible values in the range for equality, which is slower but more accurate. - # Range#cover? uses the previous logic of comparing a value with the range - # endpoints, which is fast but is only accurate on Numeric, Time, Date, - # or DateTime ranges. - def inclusion_method(enumerable) - if enumerable.is_a? Range - case enumerable.first - when Numeric, Time, DateTime, Date - :cover? - else - :include? - end - else - :include? - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/confirmation.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/confirmation.rb deleted file mode 100644 index 03585bf5e1..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/confirmation.rb +++ /dev/null @@ -1,78 +0,0 @@ -module ActiveModel - module Validations - class ConfirmationValidator < EachValidator # :nodoc: - def initialize(options) - super({ case_sensitive: true }.merge!(options)) - setup!(options[:class]) - end - - def validate_each(record, attribute, value) - if (confirmed = record.send("#{attribute}_confirmation")) - unless confirmation_value_equal?(record, attribute, value, confirmed) - human_attribute_name = record.class.human_attribute_name(attribute) - record.errors.add(:"#{attribute}_confirmation", :confirmation, options.except(:case_sensitive).merge!(attribute: human_attribute_name)) - end - end - end - - private - def setup!(klass) - klass.send(:attr_reader, *attributes.map do |attribute| - :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation") - end.compact) - - klass.send(:attr_writer, *attributes.map do |attribute| - :"#{attribute}_confirmation" unless klass.method_defined?(:"#{attribute}_confirmation=") - end.compact) - end - - def confirmation_value_equal?(record, attribute, value, confirmed) - if !options[:case_sensitive] && value.is_a?(String) - value.casecmp(confirmed) == 0 - else - value == confirmed - end - end - end - - module HelperMethods - # Encapsulates the pattern of wanting to validate a password or email - # address field with a confirmation. - # - # Model: - # class Person < ActiveRecord::Base - # validates_confirmation_of :user_name, :password - # validates_confirmation_of :email_address, - # message: 'should match confirmation' - # end - # - # View: - # <%= password_field "person", "password" %> - # <%= password_field "person", "password_confirmation" %> - # - # The added +password_confirmation+ attribute is virtual; it exists only - # as an in-memory attribute for validating the password. To achieve this, - # the validation adds accessors to the model for the confirmation - # attribute. - # - # NOTE: This check is performed only if +password_confirmation+ is not - # +nil+. To require confirmation, make sure to add a presence check for - # the confirmation attribute: - # - # validates_presence_of :password_confirmation, if: :password_changed? - # - # Configuration options: - # * :message - A custom error message (default is: "doesn't match - # %{translated_attribute_name}"). - # * :case_sensitive - Looks for an exact match. Ignored by - # non-text columns (+true+ by default). - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. - # See ActiveModel::Validations#validates for more information - def validates_confirmation_of(*attr_names) - validates_with ConfirmationValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/exclusion.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/exclusion.rb deleted file mode 100644 index b7156ba802..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/exclusion.rb +++ /dev/null @@ -1,47 +0,0 @@ -require "active_model/validations/clusivity" - -module ActiveModel - module Validations - class ExclusionValidator < EachValidator # :nodoc: - include Clusivity - - def validate_each(record, attribute, value) - if include?(record, value) - record.errors.add(attribute, :exclusion, options.except(:in, :within).merge!(value: value)) - end - end - end - - module HelperMethods - # Validates that the value of the specified attribute is not in a - # particular enumerable object. - # - # class Person < ActiveRecord::Base - # validates_exclusion_of :username, in: %w( admin superuser ), message: "You don't belong here" - # validates_exclusion_of :age, in: 30..60, message: 'This site is only for under 30 and over 60' - # validates_exclusion_of :format, in: %w( mov avi ), message: "extension %{value} is not allowed" - # validates_exclusion_of :password, in: ->(person) { [person.username, person.first_name] }, - # message: 'should not be the same as your username or first name' - # validates_exclusion_of :karma, in: :reserved_karmas - # end - # - # Configuration options: - # * :in - An enumerable object of items that the value shouldn't - # be part of. This can be supplied as a proc, lambda or symbol which returns an - # enumerable. If the enumerable is a numerical, time or datetime range the test - # is performed with Range#cover?, otherwise with include?. When - # using a proc or lambda the instance under validation is passed as an argument. - # * :within - A synonym(or alias) for :in - # Range#cover?, otherwise with include?. - # * :message - Specifies a custom error message (default is: "is - # reserved"). - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. - # See ActiveModel::Validations#validates for more information - def validates_exclusion_of(*attr_names) - validates_with ExclusionValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/format.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/format.rb deleted file mode 100644 index b4b8d9f33c..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/format.rb +++ /dev/null @@ -1,113 +0,0 @@ - -module ActiveModel - module Validations - class FormatValidator < EachValidator # :nodoc: - def validate_each(record, attribute, value) - if options[:with] - regexp = option_call(record, :with) - record_error(record, attribute, :with, value) if value.to_s !~ regexp - elsif options[:without] - regexp = option_call(record, :without) - record_error(record, attribute, :without, value) if regexp.match?(value.to_s) - end - end - - def check_validity! - unless options.include?(:with) ^ options.include?(:without) # ^ == xor, or "exclusive or" - raise ArgumentError, "Either :with or :without must be supplied (but not both)" - end - - check_options_validity :with - check_options_validity :without - end - - private - - def option_call(record, name) - option = options[name] - option.respond_to?(:call) ? option.call(record) : option - end - - def record_error(record, attribute, name, value) - record.errors.add(attribute, :invalid, options.except(name).merge!(value: value)) - end - - def check_options_validity(name) - if option = options[name] - if option.is_a?(Regexp) - if options[:multiline] != true && regexp_using_multiline_anchors?(option) - raise ArgumentError, "The provided regular expression is using multiline anchors (^ or $), " \ - "which may present a security risk. Did you mean to use \\A and \\z, or forgot to add the " \ - ":multiline => true option?" - end - elsif !option.respond_to?(:call) - raise ArgumentError, "A regular expression or a proc or lambda must be supplied as :#{name}" - end - end - end - - def regexp_using_multiline_anchors?(regexp) - source = regexp.source - source.start_with?("^") || (source.end_with?("$") && !source.end_with?("\\$")) - end - end - - module HelperMethods - # Validates whether the value of the specified attribute is of the correct - # form, going by the regular expression provided. You can require that the - # attribute matches the regular expression: - # - # class Person < ActiveRecord::Base - # validates_format_of :email, with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create - # end - # - # Alternatively, you can require that the specified attribute does _not_ - # match the regular expression: - # - # class Person < ActiveRecord::Base - # validates_format_of :email, without: /NOSPAM/ - # end - # - # You can also provide a proc or lambda which will determine the regular - # expression that will be used to validate the attribute. - # - # class Person < ActiveRecord::Base - # # Admin can have number as a first letter in their screen name - # validates_format_of :screen_name, - # with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i } - # end - # - # Note: use \A and \z to match the start and end of the - # string, ^ and $ match the start/end of a line. - # - # Due to frequent misuse of ^ and $, you need to pass - # the multiline: true option in case you use any of these two - # anchors in the provided regular expression. In most cases, you should be - # using \A and \z. - # - # You must pass either :with or :without as an option. - # In addition, both must be a regular expression or a proc or lambda, or - # else an exception will be raised. - # - # Configuration options: - # * :message - A custom error message (default is: "is invalid"). - # * :with - Regular expression that if the attribute matches will - # result in a successful validation. This can be provided as a proc or - # lambda returning regular expression which will be called at runtime. - # * :without - Regular expression that if the attribute does not - # match will result in a successful validation. This can be provided as - # a proc or lambda returning regular expression which will be called at - # runtime. - # * :multiline - Set to true if your regular expression contains - # anchors that match the beginning or end of lines as opposed to the - # beginning or end of the string. These anchors are ^ and $. - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. - # See ActiveModel::Validations#validates for more information - def validates_format_of(*attr_names) - validates_with FormatValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/helper_methods.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/helper_methods.rb deleted file mode 100644 index 2176115334..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/helper_methods.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveModel - module Validations - module HelperMethods # :nodoc: - private - def _merge_attributes(attr_names) - options = attr_names.extract_options!.symbolize_keys - attr_names.flatten! - options[:attributes] = attr_names - options - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/inclusion.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/inclusion.rb deleted file mode 100644 index c6c5bae649..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/inclusion.rb +++ /dev/null @@ -1,45 +0,0 @@ -require "active_model/validations/clusivity" - -module ActiveModel - module Validations - class InclusionValidator < EachValidator # :nodoc: - include Clusivity - - def validate_each(record, attribute, value) - unless include?(record, value) - record.errors.add(attribute, :inclusion, options.except(:in, :within).merge!(value: value)) - end - end - end - - module HelperMethods - # Validates whether the value of the specified attribute is available in a - # particular enumerable object. - # - # class Person < ActiveRecord::Base - # validates_inclusion_of :gender, in: %w( m f ) - # validates_inclusion_of :age, in: 0..99 - # validates_inclusion_of :format, in: %w( jpg gif png ), message: "extension %{value} is not included in the list" - # validates_inclusion_of :states, in: ->(person) { STATES[person.country] } - # validates_inclusion_of :karma, in: :available_karmas - # end - # - # Configuration options: - # * :in - An enumerable object of available items. This can be - # supplied as a proc, lambda or symbol which returns an enumerable. If the - # enumerable is a numerical, time or datetime range the test is performed - # with Range#cover?, otherwise with include?. When using - # a proc or lambda the instance under validation is passed as an argument. - # * :within - A synonym(or alias) for :in - # * :message - Specifies a custom error message (default is: "is - # not included in the list"). - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. - # See ActiveModel::Validations#validates for more information - def validates_inclusion_of(*attr_names) - validates_with InclusionValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/length.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/length.rb deleted file mode 100644 index 940c58f3a7..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/length.rb +++ /dev/null @@ -1,121 +0,0 @@ -module ActiveModel - module Validations - class LengthValidator < EachValidator # :nodoc: - MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze - CHECKS = { is: :==, minimum: :>=, maximum: :<= }.freeze - - RESERVED_OPTIONS = [:minimum, :maximum, :within, :is, :too_short, :too_long] - - def initialize(options) - if range = (options.delete(:in) || options.delete(:within)) - raise ArgumentError, ":in and :within must be a Range" unless range.is_a?(Range) - options[:minimum], options[:maximum] = range.min, range.max - end - - if options[:allow_blank] == false && options[:minimum].nil? && options[:is].nil? - options[:minimum] = 1 - end - - super - end - - def check_validity! - keys = CHECKS.keys & options.keys - - if keys.empty? - raise ArgumentError, "Range unspecified. Specify the :in, :within, :maximum, :minimum, or :is option." - end - - keys.each do |key| - value = options[key] - - unless (value.is_a?(Integer) && value >= 0) || value == Float::INFINITY - raise ArgumentError, ":#{key} must be a nonnegative Integer or Infinity" - end - end - end - - def validate_each(record, attribute, value) - value_length = value.respond_to?(:length) ? value.length : value.to_s.length - errors_options = options.except(*RESERVED_OPTIONS) - - CHECKS.each do |key, validity_check| - next unless check_value = options[key] - - if !value.nil? || skip_nil_check?(key) - next if value_length.send(validity_check, check_value) - end - - errors_options[:count] = check_value - - default_message = options[MESSAGES[key]] - errors_options[:message] ||= default_message if default_message - - record.errors.add(attribute, MESSAGES[key], errors_options) - end - end - - private - def skip_nil_check?(key) - key == :maximum && options[:allow_nil].nil? && options[:allow_blank].nil? - end - end - - module HelperMethods - # Validates that the specified attributes match the length restrictions - # supplied. Only one constraint option can be used at a time apart from - # +:minimum+ and +:maximum+ that can be combined together: - # - # class Person < ActiveRecord::Base - # validates_length_of :first_name, maximum: 30 - # validates_length_of :last_name, maximum: 30, message: "less than 30 if you don't mind" - # validates_length_of :fax, in: 7..32, allow_nil: true - # validates_length_of :phone, in: 7..32, allow_blank: true - # validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name' - # validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters' - # validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me." - # validates_length_of :words_in_essay, minimum: 100, too_short: 'Your essay must be at least 100 words.' - # - # private - # - # def words_in_essay - # essay.scan(/\w+/) - # end - # end - # - # Constraint options: - # - # * :minimum - The minimum size of the attribute. - # * :maximum - The maximum size of the attribute. Allows +nil+ by - # default if not used with +:minimum+. - # * :is - The exact size of the attribute. - # * :within - A range specifying the minimum and maximum size of - # the attribute. - # * :in - A synonym (or alias) for :within. - # - # Other options: - # - # * :allow_nil - Attribute may be +nil+; skip validation. - # * :allow_blank - Attribute may be blank; skip validation. - # * :too_long - The error message if the attribute goes over the - # maximum (default is: "is too long (maximum is %{count} characters)"). - # * :too_short - The error message if the attribute goes under the - # minimum (default is: "is too short (minimum is %{count} characters)"). - # * :wrong_length - The error message if using the :is - # method and the attribute is the wrong size (default is: "is the wrong - # length (should be %{count} characters)"). - # * :message - The error message to use for a :minimum, - # :maximum, or :is violation. An alias of the appropriate - # too_long/too_short/wrong_length message. - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+ and +:strict+. - # See ActiveModel::Validations#validates for more information - def validates_length_of(*attr_names) - validates_with LengthValidator, _merge_attributes(attr_names) - end - - alias_method :validates_size_of, :validates_length_of - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/numericality.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/numericality.rb deleted file mode 100644 index 2ef584f8df..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/numericality.rb +++ /dev/null @@ -1,163 +0,0 @@ -module ActiveModel - module Validations - class NumericalityValidator < EachValidator # :nodoc: - CHECKS = { greater_than: :>, greater_than_or_equal_to: :>=, - equal_to: :==, less_than: :<, less_than_or_equal_to: :<=, - odd: :odd?, even: :even?, other_than: :!= }.freeze - - RESERVED_OPTIONS = CHECKS.keys + [:only_integer] - - def check_validity! - keys = CHECKS.keys - [:odd, :even] - options.slice(*keys).each do |option, value| - unless value.is_a?(Numeric) || value.is_a?(Proc) || value.is_a?(Symbol) - raise ArgumentError, ":#{option} must be a number, a symbol or a proc" - end - end - end - - def validate_each(record, attr_name, value) - before_type_cast = :"#{attr_name}_before_type_cast" - - raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast) && record.send(before_type_cast) != value - raw_value ||= value - - if record_attribute_changed_in_place?(record, attr_name) - raw_value = value - end - - unless is_number?(raw_value) - record.errors.add(attr_name, :not_a_number, filtered_options(raw_value)) - return - end - - if allow_only_integer?(record) && !is_integer?(raw_value) - record.errors.add(attr_name, :not_an_integer, filtered_options(raw_value)) - return - end - - if raw_value.is_a?(Numeric) - value = raw_value - else - value = parse_raw_value_as_a_number(raw_value) - end - - options.slice(*CHECKS.keys).each do |option, option_value| - case option - when :odd, :even - unless value.to_i.send(CHECKS[option]) - record.errors.add(attr_name, option, filtered_options(value)) - end - else - case option_value - when Proc - option_value = option_value.call(record) - when Symbol - option_value = record.send(option_value) - end - - unless value.send(CHECKS[option], option_value) - record.errors.add(attr_name, option, filtered_options(value).merge!(count: option_value)) - end - end - end - end - - private - - def is_number?(raw_value) - !parse_raw_value_as_a_number(raw_value).nil? - rescue ArgumentError, TypeError - false - end - - def parse_raw_value_as_a_number(raw_value) - return raw_value.to_i if is_integer?(raw_value) - Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/ - end - - def is_integer?(raw_value) - /\A[+-]?\d+\z/ === raw_value.to_s - end - - def filtered_options(value) - filtered = options.except(*RESERVED_OPTIONS) - filtered[:value] = value - filtered - end - - def allow_only_integer?(record) - case options[:only_integer] - when Symbol - record.send(options[:only_integer]) - when Proc - options[:only_integer].call(record) - else - options[:only_integer] - end - end - - def record_attribute_changed_in_place?(record, attr_name) - record.respond_to?(:attribute_changed_in_place?) && - record.attribute_changed_in_place?(attr_name.to_s) - end - end - - module HelperMethods - # Validates whether the value of the specified attribute is numeric by - # trying to convert it to a float with Kernel.Float (if only_integer - # is +false+) or applying it to the regular expression /\A[\+\-]?\d+\Z/ - # (if only_integer is set to +true+). - # - # class Person < ActiveRecord::Base - # validates_numericality_of :value, on: :create - # end - # - # Configuration options: - # * :message - A custom error message (default is: "is not a number"). - # * :only_integer - Specifies whether the value has to be an - # integer, e.g. an integral value (default is +false+). - # * :allow_nil - Skip validation if attribute is +nil+ (default is - # +false+). Notice that for Integer and Float columns empty strings are - # converted to +nil+. - # * :greater_than - Specifies the value must be greater than the - # supplied value. - # * :greater_than_or_equal_to - Specifies the value must be - # greater than or equal the supplied value. - # * :equal_to - Specifies the value must be equal to the supplied - # value. - # * :less_than - Specifies the value must be less than the - # supplied value. - # * :less_than_or_equal_to - Specifies the value must be less - # than or equal the supplied value. - # * :other_than - Specifies the value must be other than the - # supplied value. - # * :odd - Specifies the value must be an odd number. - # * :even - Specifies the value must be an even number. - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+ . - # See ActiveModel::Validations#validates for more information - # - # The following checks can also be supplied with a proc or a symbol which - # corresponds to a method: - # - # * :greater_than - # * :greater_than_or_equal_to - # * :equal_to - # * :less_than - # * :less_than_or_equal_to - # * :only_integer - # - # For example: - # - # class Person < ActiveRecord::Base - # validates_numericality_of :width, less_than: ->(person) { person.height } - # validates_numericality_of :width, greater_than: :minimum_weight - # end - def validates_numericality_of(*attr_names) - validates_with NumericalityValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/presence.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/presence.rb deleted file mode 100644 index 6e8a434bbe..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/presence.rb +++ /dev/null @@ -1,38 +0,0 @@ - -module ActiveModel - module Validations - class PresenceValidator < EachValidator # :nodoc: - def validate_each(record, attr_name, value) - record.errors.add(attr_name, :blank, options) if value.blank? - end - end - - module HelperMethods - # Validates that the specified attributes are not blank (as defined by - # Object#blank?). Happens by default on save. - # - # class Person < ActiveRecord::Base - # validates_presence_of :first_name - # end - # - # The first_name attribute must be in the object and it cannot be blank. - # - # If you want to validate the presence of a boolean field (where the real - # values are +true+ and +false+), you will want to use - # validates_inclusion_of :field_name, in: [true, false]. - # - # This is due to the way Object#blank? handles boolean values: - # false.blank? # => true. - # - # Configuration options: - # * :message - A custom error message (default is: "can't be blank"). - # - # There is also a list of default options supported by every validator: - # +:if+, +:unless+, +:on+, +:allow_nil+, +:allow_blank+, and +:strict+. - # See ActiveModel::Validations#validates for more information - def validates_presence_of(*attr_names) - validates_with PresenceValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/validates.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/validates.rb deleted file mode 100644 index 0ce5935f3a..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/validates.rb +++ /dev/null @@ -1,173 +0,0 @@ -require "active_support/core_ext/hash/slice" - -module ActiveModel - module Validations - module ClassMethods - # This method is a shortcut to all default validators and any custom - # validator classes ending in 'Validator'. Note that Rails default - # validators can be overridden inside specific classes by creating - # custom validator classes in their place such as PresenceValidator. - # - # Examples of using the default rails validators: - # - # validates :terms, acceptance: true - # validates :password, confirmation: true - # validates :username, exclusion: { in: %w(admin superuser) } - # validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create } - # validates :age, inclusion: { in: 0..9 } - # validates :first_name, length: { maximum: 30 } - # validates :age, numericality: true - # validates :username, presence: true - # validates :username, uniqueness: true - # - # The power of the +validates+ method comes when using custom validators - # and default validators in one call for a given attribute. - # - # class EmailValidator < ActiveModel::EachValidator - # def validate_each(record, attribute, value) - # record.errors.add attribute, (options[:message] || "is not an email") unless - # value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i - # end - # end - # - # class Person - # include ActiveModel::Validations - # attr_accessor :name, :email - # - # validates :name, presence: true, uniqueness: true, length: { maximum: 100 } - # validates :email, presence: true, email: true - # end - # - # Validator classes may also exist within the class being validated - # allowing custom modules of validators to be included as needed. - # - # class Film - # include ActiveModel::Validations - # - # class TitleValidator < ActiveModel::EachValidator - # def validate_each(record, attribute, value) - # record.errors.add attribute, "must start with 'the'" unless value =~ /\Athe/i - # end - # end - # - # validates :name, title: true - # end - # - # Additionally validator classes may be in another namespace and still - # used within any class. - # - # validates :name, :'film/title' => true - # - # The validators hash can also handle regular expressions, ranges, arrays - # and strings in shortcut form. - # - # validates :email, format: /@/ - # validates :gender, inclusion: %w(male female) - # validates :password, length: 6..20 - # - # When using shortcut form, ranges and arrays are passed to your - # validator's initializer as options[:in] while other types - # including regular expressions and strings are passed as options[:with]. - # - # There is also a list of options that could be used along with validators: - # - # * :on - Specifies the contexts where this validation is active. - # Runs in all validation contexts by default +nil+. You can pass a symbol - # or an array of symbols. (e.g. on: :create or - # on: :custom_validation_context or - # on: [:create, :custom_validation_context]) - # * :if - Specifies a method, proc or string to call to determine - # if the validation should occur (e.g. if: :allow_validation, - # or if: Proc.new { |user| user.signup_step > 2 }). The method, - # proc or string should return or evaluate to a +true+ or +false+ value. - # * :unless - Specifies a method, proc or string to call to determine - # if the validation should not occur (e.g. unless: :skip_validation, - # or unless: Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a +true+ or - # +false+ value. - # * :allow_nil - Skip validation if the attribute is +nil+. - # * :allow_blank - Skip validation if the attribute is blank. - # * :strict - If the :strict option is set to true - # will raise ActiveModel::StrictValidationFailed instead of adding the error. - # :strict option can also be set to any other exception. - # - # Example: - # - # validates :password, presence: true, confirmation: true, if: :password_required? - # validates :token, uniqueness: true, strict: TokenGenerationException - # - # - # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+, +:strict+ - # and +:message+ can be given to one specific validator, as a hash: - # - # validates :password, presence: { if: :password_required?, message: 'is forgotten.' }, confirmation: true - def validates(*attributes) - defaults = attributes.extract_options!.dup - validations = defaults.slice!(*_validates_default_keys) - - raise ArgumentError, "You need to supply at least one attribute" if attributes.empty? - raise ArgumentError, "You need to supply at least one validation" if validations.empty? - - defaults[:attributes] = attributes - - validations.each do |key, options| - next unless options - key = "#{key.to_s.camelize}Validator" - - begin - validator = key.include?("::".freeze) ? key.constantize : const_get(key) - rescue NameError - raise ArgumentError, "Unknown validator: '#{key}'" - end - - validates_with(validator, defaults.merge(_parse_validates_options(options))) - end - end - - # This method is used to define validations that cannot be corrected by end - # users and are considered exceptional. So each validator defined with bang - # or :strict option set to true will always raise - # ActiveModel::StrictValidationFailed instead of adding error - # when validation fails. See validates for more information about - # the validation itself. - # - # class Person - # include ActiveModel::Validations - # - # attr_accessor :name - # validates! :name, presence: true - # end - # - # person = Person.new - # person.name = '' - # person.valid? - # # => ActiveModel::StrictValidationFailed: Name can't be blank - def validates!(*attributes) - options = attributes.extract_options! - options[:strict] = true - validates(*(attributes << options)) - end - - private - - # When creating custom validators, it might be useful to be able to specify - # additional default keys. This can be done by overwriting this method. - def _validates_default_keys - [:if, :unless, :on, :allow_blank, :allow_nil , :strict] - end - - def _parse_validates_options(options) - case options - when TrueClass - {} - when Hash - options - when Range, Array - { in: options } - else - { with: options } - end - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/with.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/with.rb deleted file mode 100644 index 9227dd06ff..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validations/with.rb +++ /dev/null @@ -1,145 +0,0 @@ -require "active_support/core_ext/array/extract_options" - -module ActiveModel - module Validations - class WithValidator < EachValidator # :nodoc: - def validate_each(record, attr, val) - method_name = options[:with] - - if record.method(method_name).arity == 0 - record.send method_name - else - record.send method_name, attr - end - end - end - - module ClassMethods - # Passes the record off to the class or classes specified and allows them - # to add errors based on more complex conditions. - # - # class Person - # include ActiveModel::Validations - # validates_with MyValidator - # end - # - # class MyValidator < ActiveModel::Validator - # def validate(record) - # if some_complex_logic - # record.errors.add :base, 'This record is invalid' - # end - # end - # - # private - # def some_complex_logic - # # ... - # end - # end - # - # You may also pass it multiple classes, like so: - # - # class Person - # include ActiveModel::Validations - # validates_with MyValidator, MyOtherValidator, on: :create - # end - # - # Configuration options: - # * :on - Specifies the contexts where this validation is active. - # Runs in all validation contexts by default +nil+. You can pass a symbol - # or an array of symbols. (e.g. on: :create or - # on: :custom_validation_context or - # on: [:create, :custom_validation_context]) - # * :if - Specifies a method, proc or string to call to determine - # if the validation should occur (e.g. if: :allow_validation, - # or if: Proc.new { |user| user.signup_step > 2 }). - # The method, proc or string should return or evaluate to a +true+ or - # +false+ value. - # * :unless - Specifies a method, proc or string to call to - # determine if the validation should not occur - # (e.g. unless: :skip_validation, or - # unless: Proc.new { |user| user.signup_step <= 2 }). - # The method, proc or string should return or evaluate to a +true+ or - # +false+ value. - # * :strict - Specifies whether validation should be strict. - # See ActiveModel::Validations#validates! for more information. - # - # If you pass any additional configuration options, they will be passed - # to the class and available as +options+: - # - # class Person - # include ActiveModel::Validations - # validates_with MyValidator, my_custom_key: 'my custom value' - # end - # - # class MyValidator < ActiveModel::Validator - # def validate(record) - # options[:my_custom_key] # => "my custom value" - # end - # end - def validates_with(*args, &block) - options = args.extract_options! - options[:class] = self - - args.each do |klass| - validator = klass.new(options, &block) - - if validator.respond_to?(:attributes) && !validator.attributes.empty? - validator.attributes.each do |attribute| - _validators[attribute.to_sym] << validator - end - else - _validators[nil] << validator - end - - validate(validator, options) - end - end - end - - # Passes the record off to the class or classes specified and allows them - # to add errors based on more complex conditions. - # - # class Person - # include ActiveModel::Validations - # - # validate :instance_validations - # - # def instance_validations - # validates_with MyValidator - # end - # end - # - # Please consult the class method documentation for more information on - # creating your own validator. - # - # You may also pass it multiple classes, like so: - # - # class Person - # include ActiveModel::Validations - # - # validate :instance_validations, on: :create - # - # def instance_validations - # validates_with MyValidator, MyOtherValidator - # end - # end - # - # Standard configuration options (:on, :if and - # :unless), which are available on the class version of - # +validates_with+, should instead be placed on the +validates+ method - # as these are applied and tested in the callback. - # - # If you pass any additional configuration options, they will be passed - # to the class and available as +options+, please refer to the - # class version of this method for more information. - def validates_with(*args, &block) - options = args.extract_options! - options[:class] = self.class - - args.each do |klass| - validator = klass.new(options, &block) - validator.validate(self) - end - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validator.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/validator.rb deleted file mode 100644 index 98234e9b6b..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/validator.rb +++ /dev/null @@ -1,181 +0,0 @@ -require "active_support/core_ext/module/anonymous" - -module ActiveModel - # == Active \Model \Validator - # - # A simple base class that can be used along with - # ActiveModel::Validations::ClassMethods.validates_with - # - # class Person - # include ActiveModel::Validations - # validates_with MyValidator - # end - # - # class MyValidator < ActiveModel::Validator - # def validate(record) - # if some_complex_logic - # record.errors.add(:base, "This record is invalid") - # end - # end - # - # private - # def some_complex_logic - # # ... - # end - # end - # - # Any class that inherits from ActiveModel::Validator must implement a method - # called +validate+ which accepts a +record+. - # - # class Person - # include ActiveModel::Validations - # validates_with MyValidator - # end - # - # class MyValidator < ActiveModel::Validator - # def validate(record) - # record # => The person instance being validated - # options # => Any non-standard options passed to validates_with - # end - # end - # - # To cause a validation error, you must add to the +record+'s errors directly - # from within the validators message. - # - # class MyValidator < ActiveModel::Validator - # def validate(record) - # record.errors.add :base, "This is some custom error message" - # record.errors.add :first_name, "This is some complex validation" - # # etc... - # end - # end - # - # To add behavior to the initialize method, use the following signature: - # - # class MyValidator < ActiveModel::Validator - # def initialize(options) - # super - # @my_custom_field = options[:field_name] || :first_name - # end - # end - # - # Note that the validator is initialized only once for the whole application - # life cycle, and not on each validation run. - # - # The easiest way to add custom validators for validating individual attributes - # is with the convenient ActiveModel::EachValidator. - # - # class TitleValidator < ActiveModel::EachValidator - # def validate_each(record, attribute, value) - # record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value) - # end - # end - # - # This can now be used in combination with the +validates+ method - # (see ActiveModel::Validations::ClassMethods.validates for more on this). - # - # class Person - # include ActiveModel::Validations - # attr_accessor :title - # - # validates :title, presence: true, title: true - # end - # - # It can be useful to access the class that is using that validator when there are prerequisites such - # as an +attr_accessor+ being present. This class is accessible via +options[:class]+ in the constructor. - # To setup your validator override the constructor. - # - # class MyValidator < ActiveModel::Validator - # def initialize(options={}) - # super - # options[:class].send :attr_accessor, :custom_attribute - # end - # end - class Validator - attr_reader :options - - # Returns the kind of the validator. - # - # PresenceValidator.kind # => :presence - # UniquenessValidator.kind # => :uniqueness - def self.kind - @kind ||= name.split("::").last.underscore.chomp("_validator").to_sym unless anonymous? - end - - # Accepts options that will be made available through the +options+ reader. - def initialize(options = {}) - @options = options.except(:class).freeze - end - - # Returns the kind for this validator. - # - # PresenceValidator.new.kind # => :presence - # UniquenessValidator.new.kind # => :uniqueness - def kind - self.class.kind - end - - # Override this method in subclasses with validation logic, adding errors - # to the records +errors+ array where necessary. - def validate(record) - raise NotImplementedError, "Subclasses must implement a validate(record) method." - end - end - - # +EachValidator+ is a validator which iterates through the attributes given - # in the options hash invoking the validate_each method passing in the - # record, attribute and value. - # - # All \Active \Model validations are built on top of this validator. - class EachValidator < Validator #:nodoc: - attr_reader :attributes - - # Returns a new validator instance. All options will be available via the - # +options+ reader, however the :attributes option will be removed - # and instead be made available through the +attributes+ reader. - def initialize(options) - @attributes = Array(options.delete(:attributes)) - raise ArgumentError, ":attributes cannot be blank" if @attributes.empty? - super - check_validity! - end - - # Performs validation on the supplied record. By default this will call - # +validate_each+ to determine validity therefore subclasses should - # override +validate_each+ with validation logic. - def validate(record) - attributes.each do |attribute| - value = record.read_attribute_for_validation(attribute) - next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank]) - validate_each(record, attribute, value) - end - end - - # Override this method in subclasses with the validation logic, adding - # errors to the records +errors+ array where necessary. - def validate_each(record, attribute, value) - raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method" - end - - # Hook method that gets called by the initializer allowing verification - # that the arguments supplied are valid. You could for example raise an - # +ArgumentError+ when invalid options are supplied. - def check_validity! - end - end - - # +BlockValidator+ is a special +EachValidator+ which receives a block on initialization - # and call this block for each attribute being validated. +validates_each+ uses this validator. - class BlockValidator < EachValidator #:nodoc: - def initialize(options, &block) - @block = block - super - end - - private - - def validate_each(record, attribute, value) - @block.call(record, attribute, value) - end - end -end diff --git a/debian/gems-compat/activemodel-5.1.7/lib/active_model/version.rb b/debian/gems-compat/activemodel-5.1.7/lib/active_model/version.rb deleted file mode 100644 index 6e7fd227fd..0000000000 --- a/debian/gems-compat/activemodel-5.1.7/lib/active_model/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module ActiveModel - # Returns the version of the currently loaded \Active \Model as a Gem::Version - def self.version - gem_version - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/CHANGELOG.md b/debian/gems-compat/activerecord-5.1.7/CHANGELOG.md deleted file mode 100644 index 4980614b0a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,1116 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* Fix `touch` option to behave consistently with `Persistence#touch` method. - - *Ryuta Kamizono* - -* Back port Rails 5.2 `reverse_order` Arel SQL literal fix. - - *Matt Jones*, *Brooke Kuhlmann* - -* `becomes` should clear the mutation tracker which is created in `after_initialize`. - - Fixes #32867. - - *Ryuta Kamizono* - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* MySQL: Support mysql2 0.5.x. - - *Aaron Stone* - -* Apply time column precision on assignment. - - PR #20317 changed the behavior of datetime columns so that when they - have a specified precision then on assignment the value is rounded to - that precision. This behavior is now applied to time columns as well. - - Fixes #30301. - - *Andrew White* - -* Normalize time column values for SQLite database. - - For legacy reasons, time columns in SQLite are stored as full datetimes - because until #24542 the quoting for time columns didn't remove the date - component. To ensure that values are consistent we now normalize the - date component to 2001-01-01 on reading and writing. - - *Andrew White* - -* Ensure that the date component is removed when quoting times. - - PR #24542 altered the quoting for time columns so that the date component - was removed however it only removed it when it was 2001-01-01. Now the - date component is removed irrespective of what the date is. - - *Andrew White* - -* Fix that after commit callbacks on update does not triggered when optimistic locking is enabled. - - *Ryuta Kamizono* - -* `ActiveRecord::Persistence#touch` does not work well when optimistic locking enabled and - `locking_column`, without default value, is null in the database. - - *bogdanvlviv* - -* Fix destroying existing object does not work well when optimistic locking enabled and - `locking column` is null in the database. - - *bogdanvlviv* - - -## Rails 5.1.5 (February 14, 2018) ## - -* PostgreSQL: Allow pg-1.0 gem to be used with Active Record. - - *Lars Kanis* - -* Fix `count(:all)` with eager loading and having an order other than the driving table. - - Fixes #31783. - - *Ryuta Kamizono* - -* Use `count(:all)` in `HasManyAssociation#count_records` to prevent invalid - SQL queries for association counting. - - *Klas Eskilson* - -* Fix to invoke callbacks when using `update_attribute`. - - *Mike Busch* - -* Fix `count(:all)` to correctly work `distinct` with custom SELECT list. - - *Ryuta Kamizono* - -* Fix conflicts `counter_cache` with `touch: true` by optimistic locking. - - ``` - # create_table :posts do |t| - # t.integer :comments_count, default: 0 - # t.integer :lock_version - # t.timestamps - # end - class Post < ApplicationRecord - end - - # create_table :comments do |t| - # t.belongs_to :post - # end - class Comment < ApplicationRecord - belongs_to :post, touch: true, counter_cache: true - end - ``` - - Before: - ``` - post = Post.create! - # => begin transaction - INSERT INTO "posts" ("created_at", "updated_at", "lock_version") - VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0) - commit transaction - - comment = Comment.create!(post: post) - # => begin transaction - INSERT INTO "comments" ("post_id") VALUES (1) - - UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1, - "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1 - - UPDATE "posts" SET "updated_at" = '2017-12-11 21:27:11.398330', - "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0 - rollback transaction - # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post. - - Comment.take.destroy! - # => begin transaction - DELETE FROM "comments" WHERE "comments"."id" = 1 - - UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1, - "lock_version" = COALESCE("lock_version", 0) + 1 WHERE "posts"."id" = 1 - - UPDATE "posts" SET "updated_at" = '2017-12-11 21:42:47.785901', - "lock_version" = 1 WHERE "posts"."id" = 1 AND "posts"."lock_version" = 0 - rollback transaction - # => ActiveRecord::StaleObjectError: Attempted to touch a stale object: Post. - ``` - - After: - ``` - post = Post.create! - # => begin transaction - INSERT INTO "posts" ("created_at", "updated_at", "lock_version") - VALUES ("2017-12-11 21:27:11.387397", "2017-12-11 21:27:11.387397", 0) - commit transaction - - comment = Comment.create!(post: post) - # => begin transaction - INSERT INTO "comments" ("post_id") VALUES (1) - - UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) + 1, - "lock_version" = COALESCE("lock_version", 0) + 1, - "updated_at" = '2017-12-11 21:37:09.802642' WHERE "posts"."id" = 1 - commit transaction - - comment.destroy! - # => begin transaction - DELETE FROM "comments" WHERE "comments"."id" = 1 - - UPDATE "posts" SET "comments_count" = COALESCE("comments_count", 0) - 1, - "lock_version" = COALESCE("lock_version", 0) + 1, - "updated_at" = '2017-12-11 21:39:02.685520' WHERE "posts"."id" = 1 - commit transaction - ``` - - Fixes #31199. - - *bogdanvlviv* - -* Query cache was unavailable when entering the `ActiveRecord::Base.cache` block - without being connected. - - *Tsukasa Oishi* - -* Fix `bin/rails db:setup` and `bin/rails db:test:prepare` create wrong - ar_internal_metadata's data for a test database. - - Before: - ``` - $ RAILS_ENV=test rails dbconsole - > SELECT * FROM ar_internal_metadata; - key|value|created_at|updated_at - environment|development|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679 - ``` - - After: - ``` - $ RAILS_ENV=test rails dbconsole - > SELECT * FROM ar_internal_metadata; - key|value|created_at|updated_at - environment|test|2017-09-11 23:14:10.815679|2017-09-11 23:14:10.815679 - ``` - - Fixes #26731. - - *bogdanvlviv* - -* Fix longer sequence name detection for serial columns. - - Fixes #28332. - - *Ryuta Kamizono* - -* MySQL: Don't lose `auto_increment: true` in the `db/schema.rb`. - - Fixes #30894. - - *Ryuta Kamizono* - -* Fix `COUNT(DISTINCT ...)` for `GROUP BY` with `ORDER BY` and `LIMIT`. - - Fixes #30886. - - *Ryuta Kamizono* - - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* Ensure `sum` honors `distinct` on `has_many :through` associations - - Fixes #16791 - - *Aaron Wortham - -* Fix `COUNT(DISTINCT ...)` with `ORDER BY` and `LIMIT` to keep the existing select list. - - *Ryuta Kamizono* - -* Fix `unscoped(where: [columns])` removing the wrong bind values - - When the `where` is called on a relation after a `or`, unscoping the column of that later `where`, it removed - bind values used by the `or` instead. - - ``` - Post.where(id: 1).or(Post.where(id: 2)).where(foo: 3).unscope(where: :foo).to_sql - # Currently: - # SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 2 OR "posts"."id" = 3) - # With fix: - # SELECT "posts".* FROM "posts" WHERE ("posts"."id" = 1 OR "posts"."id" = 2) - ``` - - *Maxime Handfield Lapointe* - -* When a `has_one` association is destroyed by `dependent: destroy`, - `destroyed_by_association` will now be set to the reflection, matching the - behaviour of `has_many` associations. - - *Lisa Ugray* - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* `Relation#joins` is no longer affected by the target model's - `current_scope`, with the exception of `unscoped`. - - Fixes #29338. - - *Sean Griffin* - -* Previously, when building records using a `has_many :through` association, - if the child records were deleted before the parent was saved, they would - still be persisted. Now, if child records are deleted before the parent is saved - on a `has_many :through` association, the child records will not be persisted. - - *Tobias Kraze* - - -## Rails 5.1.2 (June 26, 2017) ## - -* Restore previous behavior of collection proxies: their values can have - methods stubbed, and they respect extension modules applied by a default - scope. - - *Ryuta Kamizono* - -* Loading model schema from database is now thread-safe. - - Fixes #28589. - - *Vikrant Chaudhary*, *David Abdemoulaie* - - -## Rails 5.1.1 (May 12, 2017) ## - -* Add type caster to `RuntimeReflection#alias_name` - - Fixes #28959. - - *Jon Moss* - - -## Rails 5.1.0 (April 27, 2017) ## - -* Quote database name in db:create grant statement (when database_user does not have access to create the database). - - *Rune Philosof* - -* When multiple threads are sharing a database connection inside a test using - transactional fixtures, a nested transaction will temporarily lock the - connection to the current thread, forcing others to wait. - - Fixes #28197. - - *Matthew Draper* - -* Load only needed records on `ActiveRecord::Relation#inspect`. - - Instead of loading all records and returning only a subset of those, just - load the records as needed. - - Fixes #25537. - - *Hendy Tanata* - -* Remove comments from structure.sql when using postgresql adapter to avoid - version-specific parts of the file. - - Fixes #28153. - - *Ari Pollak* - -* Add `:default` option to `belongs_to`. - - Use it to specify that an association should be initialized with a particular - record before validation. For example: - - # Before - belongs_to :account - before_validation -> { self.account ||= Current.account } - - # After - belongs_to :account, default: -> { Current.account } - - *George Claghorn* - -* Deprecate `Migrator.schema_migrations_table_name`. - - *Ryuta Kamizono* - -* Fix select with block doesn't return newly built records in has_many association. - - Fixes #28348. - - *Ryuta Kamizono* - -* Check whether `Rails.application` defined before calling it - - In #27674 we changed the migration generator to generate migrations at the - path defined in `Rails.application.config.paths` however the code checked - for the presence of the `Rails` constant but not the `Rails.application` - method which caused problems when using Active Record and generators outside - of the context of a Rails application. - - Fixes #28325. - - *Andrew White* - -* Fix `deserialize` with JSON array. - - Fixes #28285. - - *Ryuta Kamizono* - -* Fix `rake db:schema:load` with subdirectories. - - *Ryuta Kamizono* - -* Fix `rake db:migrate:status` with subdirectories. - - *Ryuta Kamizono* - -* Don't share options between reference id and type columns - - When using a polymorphic reference column in a migration, sharing options - between the two columns doesn't make sense since they are different types. - The `reference_id` column is usually an integer and the `reference_type` - column a string so options like `unsigned: true` will result in an invalid - table definition. - - *Ryuta Kamizono* - -* Use `max_identifier_length` for `index_name_length` in PostgreSQL adapter. - - *Ryuta Kamizono* - -* Deprecate `supports_migrations?` on connection adapters. - - *Ryuta Kamizono* - -* Fix regression of #1969 with SELECT aliases in HAVING clause. - - *Eugene Kenny* - -* Deprecate using `#quoted_id` in quoting. - - *Ryuta Kamizono* - -* Fix `wait_timeout` to configurable for mysql2 adapter. - - Fixes #26556. - - *Ryuta Kamizono* - -* Correctly dump native timestamp types for MySQL. - - The native timestamp type in MySQL is different from datetime type. - Internal representation of the timestamp type is UNIX time, This means - that timestamp columns are affected by time zone. - - > SET time_zone = '+00:00'; - Query OK, 0 rows affected (0.00 sec) - - > INSERT INTO time_with_zone(ts,dt) VALUES (NOW(),NOW()); - Query OK, 1 row affected (0.02 sec) - - > SELECT * FROM time_with_zone; - +---------------------+---------------------+ - | ts | dt | - +---------------------+---------------------+ - | 2016-02-07 22:11:44 | 2016-02-07 22:11:44 | - +---------------------+---------------------+ - 1 row in set (0.00 sec) - - > SET time_zone = '-08:00'; - Query OK, 0 rows affected (0.00 sec) - - > SELECT * FROM time_with_zone; - +---------------------+---------------------+ - | ts | dt | - +---------------------+---------------------+ - | 2016-02-07 14:11:44 | 2016-02-07 22:11:44 | - +---------------------+---------------------+ - 1 row in set (0.00 sec) - - *Ryuta Kamizono* - -* All integer-like PKs are autoincrement unless they have an explicit default. - - *Matthew Draper* - -* Omit redundant `using: :btree` for schema dumping. - - *Ryuta Kamizono* - -* Deprecate passing `default` to `index_name_exists?`. - - *Ryuta Kamizono* - -* PostgreSQL: schema dumping support for interval and OID columns. - - *Ryuta Kamizono* - -* Deprecate `supports_primary_key?` on connection adapters since it's - been long unused and unsupported. - - *Ryuta Kamizono* - -* Make `table_name=` reset current statement cache, - so queries are not run against the previous table name. - - *namusyaka* - -* Allow `ActiveRecord::Base#as_json` to be passed a frozen Hash. - - *Isaac Betesh* - -* Fix inspection behavior when the :id column is not primary key. - - *namusyaka* - -* Deprecate locking records with unpersisted changes. - - *Marc Schütz* - -* Remove deprecated behavior that halts callbacks when the return is false. - - *Rafael Mendonça França* - -* Deprecate `ColumnDumper#migration_keys`. - - *Ryuta Kamizono* - -* Fix `association_primary_key_type` for reflections with symbol primary key. - - Fixes #27864. - - *Daniel Colson* - -* Virtual/generated column support for MySQL 5.7.5+ and MariaDB 5.2.0+. - - MySQL generated columns: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html - MariaDB virtual columns: https://mariadb.com/kb/en/mariadb/virtual-computed-columns/ - - Declare virtual columns with `t.virtual name, type: …, as: "expression"`. - Pass `stored: true` to persist the generated value (false by default). - - Example: - - create_table :generated_columns do |t| - t.string :name - t.virtual :upper_name, type: :string, as: "UPPER(name)" - t.virtual :name_length, type: :integer, as: "LENGTH(name)", stored: true - t.index :name_length # May be indexed, too! - end - - *Ryuta Kamizono* - -* Deprecate `initialize_schema_migrations_table` and `initialize_internal_metadata_table`. - - *Ryuta Kamizono* - -* Support foreign key creation for SQLite3. - - *Ryuta Kamizono* - -* Place generated migrations into the path set by `config.paths["db/migrate"]`. - - *Kevin Glowacz* - -* Raise `ActiveRecord::InvalidForeignKey` when a foreign key constraint fails on SQLite3. - - *Ryuta Kamizono* - -* Add the touch option to `#increment!` and `#decrement!`. - - *Hiroaki Izu* - -* Deprecate passing a class to the `class_name` because it eagerloads more classes than - necessary and potentially creates circular dependencies. - - *Kir Shatrov* - -* Raise error when has_many through is defined before through association. - - Fixes #26834. - - *Chris Holmes* - -* Deprecate passing `name` to `indexes`. - - *Ryuta Kamizono* - -* Remove deprecated tasks: `db:test:clone`, `db:test:clone_schema`, `db:test:clone_structure`. - - *Rafel Mendonça França* - -* Compare deserialized values for `PostgreSQL::OID::Hstore` types when - calling `ActiveRecord::Dirty#changed_in_place?`. - - Fixes #27502. - - *Jon Moss* - -* Raise `ArgumentError` when passing an `ActiveRecord::Base` instance to `.find`, - `.exists?` and `.update`. - - *Rafael Mendonça França* - -* Respect precision option for arrays of timestamps. - - Fixes #27514. - - *Sean Griffin* - -* Optimize slow model instantiation when using STI and `store_full_sti_class = false` option. - - *Konstantin Lazarev* - -* Add `touch` option to counter cache modifying methods. - - Works when updating, resetting, incrementing and decrementing counters: - - # Touches `updated_at`/`updated_on`. - Topic.increment_counter(:messages_count, 1, touch: true) - Topic.decrement_counter(:messages_count, 1, touch: true) - - # Touches `last_discussed_at`. - Topic.reset_counters(18, :messages, touch: :last_discussed_at) - - # Touches `updated_at` and `last_discussed_at`. - Topic.update_counters(18, messages_count: 5, touch: %i( updated_at last_discussed_at )) - - Fixes #26724. - - *Jarred Trost* - -* Remove deprecated `#uniq`, `#uniq!`, and `#uniq_value`. - - *Ryuta Kamizono* - -* Remove deprecated `#insert_sql`, `#update_sql`, and `#delete_sql`. - - *Ryuta Kamizono* - -* Remove deprecated `#use_transactional_fixtures` configuration. - - *Rafael Mendonça França* - -* Remove deprecated `#raise_in_transactional_callbacks` configuration. - - *Rafael Mendonça França* - -* Remove deprecated `#load_schema_for`. - - *Rafael Mendonça França* - -* Remove deprecated conditions parameter from `#destroy_all` and `#delete_all`. - - *Rafael Mendonça França* - -* Remove deprecated support to passing arguments to `#select` when a block is provided. - - *Rafael Mendonça França* - -* Remove deprecated support to query using commas on LIMIT. - - *Rafael Mendonça França* - -* Remove deprecated support to passing a class as a value in a query. - - *Rafael Mendonça França* - -* Raise `ActiveRecord::IrreversibleOrderError` when using `last` with an irreversible - order. - - *Rafael Mendonça França* - -* Raise when a `has_many :through` association has an ambiguous reflection name. - - *Rafael Mendonça França* - -* Raise when `ActiveRecord::Migration` is inherited from directly. - - *Rafael Mendonça França* - -* Remove deprecated `original_exception` argument in `ActiveRecord::StatementInvalid#initialize` - and `ActiveRecord::StatementInvalid#original_exception`. - - *Rafael Mendonça França* - -* `#tables` and `#table_exists?` return only tables and not views. - - All the deprecations on those methods were removed. - - *Rafael Mendonça França* - -* Remove deprecated `name` argument from `#tables`. - - *Rafael Mendonça França* - -* Remove deprecated support to passing a column to `#quote`. - - *Rafael Mendonça França* - -* Set `:time` as a timezone aware type and remove deprecation when - `config.active_record.time_zone_aware_types` is not explicitly set. - - *Rafael Mendonça França* - -* Remove deprecated force reload argument in singular and collection association readers. - - *Rafael Mendonça França* - -* Remove deprecated `activerecord.errors.messages.restrict_dependent_destroy.one` and - `activerecord.errors.messages.restrict_dependent_destroy.many` i18n scopes. - - *Rafael Mendonça França* - -* Allow passing extra flags to `db:structure:load` and `db:structure:dump` - - Introduces `ActiveRecord::Tasks::DatabaseTasks.structure_(load|dump)_flags` to customize the - eventual commands run against the database, e.g. mysqldump/pg_dump. - - *Kir Shatrov* - -* Notifications see frozen SQL string. - - Fixes #23774. - - *Richard Monette* - -* RuntimeErrors are no longer translated to `ActiveRecord::StatementInvalid`. - - *Richard Monette* - -* Change the schema cache format to use YAML instead of Marshal. - - *Kir Shatrov* - -* Support index length and order options using both string and symbol - column names. - - Fixes #27243. - - *Ryuta Kamizono* - -* Raise `ActiveRecord::RangeError` when values that executed are out of range. - - *Ryuta Kamizono* - -* Raise `ActiveRecord::NotNullViolation` when a record cannot be inserted - or updated because it would violate a not null constraint. - - *Ryuta Kamizono* - -* Emulate db trigger behaviour for after_commit :destroy, :update. - - Race conditions can occur when an ActiveRecord is destroyed - twice or destroyed and updated. The callbacks should only be - triggered once, similar to a SQL database trigger. - - *Stefan Budeanu* - -* Moved `DecimalWithoutScale`, `Text`, and `UnsignedInteger` from Active Model to Active Record. - - *Iain Beeston* - -* Fix `write_attribute` method to check whether an attribute is aliased or not, and - use the aliased attribute name if needed. - - *Prathamesh Sonpatki* - -* Fix `read_attribute` method to check whether an attribute is aliased or not, and - use the aliased attribute name if needed. - - Fixes #26417. - - *Prathamesh Sonpatki* - -* PostgreSQL & MySQL: Use big integer as primary key type for new tables. - - *Jon McCartie*, *Pavel Pravosud* - -* Change the type argument of `ActiveRecord::Base#attribute` to be optional. - The default is now `ActiveRecord::Type::Value.new`, which provides no type - casting behavior. - - *Sean Griffin* - -* Don't treat unsigned integers with zerofill as signed. - - Fixes #27125. - - *Ryuta Kamizono* - -* Fix the uniqueness validation scope with a polymorphic association. - - *Sergey Alekseev* - -* Raise `ActiveRecord::RecordNotFound` from collection `*_ids` setters - for unknown IDs with a better error message. - - Changes the collection `*_ids` setters to cast provided IDs the data - type of the primary key set in the association, not the model - primary key. - - *Dominic Cleal* - -* For PostgreSQL >= 9.4 use `pgcrypto`'s `gen_random_uuid()` instead of - `uuid-ossp`'s UUID generation function. - - *Yuji Yaginuma*, *Yaw Boakye* - -* Introduce `Model#reload_` to bring back the behavior - of `Article.category(true)` where `category` is a singular - association. - - The force reloading of the association reader was deprecated - in #20888. Unfortunately the suggested alternative of - `article.reload.category` does not expose the same behavior. - - This patch adds a reader method with the prefix `reload_` for - singular associations. This method has the same semantics as - passing true to the association reader used to have. - - *Yves Senn* - -* Make sure eager loading `ActiveRecord::Associations` also loads - constants defined in `ActiveRecord::Associations::Preloader`. - - *Yves Senn* - -* Allow `ActionController::Parameters`-like objects to be passed as - values for Postgres HStore columns. - - Fixes #26904. - - *Jon Moss* - -* Added `stat` method to `ActiveRecord::ConnectionAdapters::ConnectionPool`. - - Example: - - ActiveRecord::Base.connection_pool.stat # => - { size: 15, connections: 1, busy: 1, dead: 0, idle: 0, waiting: 0, checkout_timeout: 5 } - - *Pavel Evstigneev* - -* Avoid `unscope(:order)` when `limit_value` is presented for `count` - and `exists?`. - - If `limit_value` is presented, records fetching order is very important - for performance. We should not unscope the order in the case. - - *Ryuta Kamizono* - -* Fix an Active Record `DateTime` field `NoMethodError` caused by incomplete - datetime. - - Fixes #24195. - - *Sen Zhang* - -* Allow `slice` to take an array of methods(without the need for splatting). - - *Cohen Carlisle* - -* Improved partial writes with HABTM and has many through associations - to fire database query only if relation has been changed. - - Fixes #19663. - - *Mehmet Emin İNAÇ* - -* Deprecate passing arguments and block at the same time to - `ActiveRecord::QueryMethods#select`. - - *Prathamesh Sonpatki* - -* Fixed: Optimistic locking does not work well with `null` in the database. - - Fixes #26024. - - *bogdanvlviv* - -* Fixed support for case insensitive comparisons of `text` columns in - PostgreSQL. - - *Edho Arief* - -* Serialize JSON attribute value `nil` as SQL `NULL`, not JSON `null`. - - *Trung Duc Tran* - -* Return `true` from `update_attribute` when the value of the attribute - to be updated is unchanged. - - Fixes #26593. - - *Prathamesh Sonpatki* - -* Always store errors details information with symbols. - - When the association is autosaved we were storing the details with - string keys. This was creating inconsistency with other details that are - added using the `Errors#add` method. It was also inconsistent with the - `Errors#messages` storage. - - To fix this inconsistency we are always storing with symbols. This will - cause a small breaking change because in those cases the details could - be accessed as strings keys but now it can not. - - Fix #26499. - - *Rafael Mendonça França*, *Marcus Vieira* - -* Calling `touch` on a model using optimistic locking will now leave the model - in a non-dirty state with no attribute changes. - - Fixes #26496. - - *Jakob Skjerning* - -* Using a mysql2 connection after it fails to reconnect will now have an error message - saying the connection is closed rather than an undefined method error message. - - *Dylan Thacker-Smith* - -* PostgreSQL array columns will now respect the encoding of strings contained - in the array. - - Fixes #26326. - - *Sean Griffin* - -* Inverse association instances will now be set before `after_find` or - `after_initialize` callbacks are run. - - Fixes #26320. - - *Sean Griffin* - -* Remove unnecessarily association load when a `belongs_to` association has already been - loaded then the foreign key is changed directly and the record saved. - - *James Coleman* - -* Remove standardized column types/arguments spaces in schema dump. - - *Tim Petricola* - -* Avoid loading records from database when they are already loaded using - the `pluck` method on a collection. - - Fixes #25921. - - *Ryuta Kamizono* - -* Remove text default treated as an empty string in non-strict mode for - consistency with other types. - - Strict mode controls how MySQL handles invalid or missing values in - data-change statements such as INSERT or UPDATE. If strict mode is not - in effect, MySQL inserts adjusted values for invalid or missing values - and produces warnings. - - def test_mysql_not_null_defaults_non_strict - using_strict(false) do - with_mysql_not_null_table do |klass| - record = klass.new - assert_nil record.non_null_integer - assert_nil record.non_null_string - assert_nil record.non_null_text - assert_nil record.non_null_blob - - record.save! - record.reload - - assert_equal 0, record.non_null_integer - assert_equal "", record.non_null_string - assert_equal "", record.non_null_text - assert_equal "", record.non_null_blob - end - end - end - - https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict - - *Ryuta Kamizono* - -* SQLite3 migrations to add a column to an existing table can now be - successfully rolled back when the column was given and invalid column - type. - - Fixes #26087. - - *Travis O'Neill* - -* Deprecate `sanitize_conditions`. Use `sanitize_sql` instead. - - *Ryuta Kamizono* - -* Doing count on relations that contain LEFT OUTER JOIN Arel node no longer - force a DISTINCT. This solves issues when using count after a left_joins. - - *Maxime Handfield Lapointe* - -* RecordNotFound raised by association.find exposes `id`, `primary_key` and - `model` methods to be consistent with RecordNotFound raised by Record.find. - - *Michel Pigassou* - -* Hashes can once again be passed to setters of `composed_of`, if all of the - mapping methods are methods implemented on `Hash`. - - Fixes #25978. - - *Sean Griffin* - -* Fix the SELECT statement in `#table_comment` for MySQL. - - *Takeshi Akima* - -* Virtual attributes will no longer raise when read on models loaded from the - database. - - *Sean Griffin* - -* Support calling the method `merge` in `scope`'s lambda. - - *Yasuhiro Sugino* - -* Fixes multi-parameter attributes conversion with invalid params. - - *Hiroyuki Ishii* - -* Add newline between each migration in `structure.sql`. - - Keeps schema migration inserts as a single commit, but allows for easier - git diffing. - - Fixes #25504. - - *Grey Baker*, *Norberto Lopes* - -* The flag `error_on_ignored_order_or_limit` has been deprecated in favor of - the current `error_on_ignored_order`. - - *Xavier Noria* - -* Batch processing methods support `limit`: - - Post.limit(10_000).find_each do |post| - # ... - end - - It also works in `find_in_batches` and `in_batches`. - - *Xavier Noria* - -* Using `group` with an attribute that has a custom type will properly cast - the hash keys after calling a calculation method like `count`. - - Fixes #25595. - - *Sean Griffin* - -* Fix the generated `#to_param` method to use `omission: ''` so that - the resulting output is actually up to 20 characters, not - effectively 17 to leave room for the default "...". - Also call `#parameterize` before `#truncate` and make the - `separator: /-/` to maximize the information included in the - output. - - Fixes #23635. - - *Rob Biedenharn* - -* Ensure concurrent invocations of the connection reaper cannot allocate the - same connection to two threads. - - Fixes #25585. - - *Matthew Draper* - -* Inspecting an object with an associated array of over 10 elements no longer - truncates the array, preventing `inspect` from looping infinitely in some - cases. - - *Kevin McPhillips* - -* Removed the unused methods `ActiveRecord::Base.connection_id` and - `ActiveRecord::Base.connection_id=`. - - *Sean Griffin* - -* Ensure hashes can be assigned to attributes created using `composed_of`. - - Fixes #25210. - - *Sean Griffin* - -* Fix logging edge case where if an attribute was of the binary type and - was provided as a Hash. - - *Jon Moss* - -* Handle JSON deserialization correctly if the column default from database - adapter returns `''` instead of `nil`. - - *Johannes Opper* - -* Introduce new Active Record transaction error classes for catching - transaction serialization failures or deadlocks. - - *Erol Fornoles* - -* PostgreSQL: Fix `db:structure:load` silent failure on SQL error. - - The command line flag `-v ON_ERROR_STOP=1` should be used - when invoking `psql` to make sure errors are not suppressed. - - Example: - - psql -v ON_ERROR_STOP=1 -q -f awesome-file.sql my-app-db - - Fixes #23818. - - *Ralin Chimev* - - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activerecord/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/activerecord-5.1.7/MIT-LICENSE b/debian/gems-compat/activerecord-5.1.7/MIT-LICENSE deleted file mode 100644 index f9e4444f07..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2004-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/activerecord-5.1.7/README.rdoc b/debian/gems-compat/activerecord-5.1.7/README.rdoc deleted file mode 100644 index cfbee4d6f7..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/README.rdoc +++ /dev/null @@ -1,217 +0,0 @@ -= Active Record -- Object-relational mapping in Rails - -Active Record connects classes to relational database tables to establish an -almost zero-configuration persistence layer for applications. The library -provides a base class that, when subclassed, sets up a mapping between the new -class and an existing table in the database. In the context of an application, -these classes are commonly referred to as *models*. Models can also be -connected to other models; this is done by defining *associations*. - -Active Record relies heavily on naming in that it uses class and association -names to establish mappings between respective database tables and foreign key -columns. Although these mappings can be defined explicitly, it's recommended -to follow naming conventions, especially when getting started with the -library. - -A short rundown of some of the major features: - -* Automated mapping between classes and tables, attributes and columns. - - class Product < ActiveRecord::Base - end - - {Learn more}[link:classes/ActiveRecord/Base.html] - -The Product class is automatically mapped to the table named "products", -which might look like this: - - CREATE TABLE products ( - id int NOT NULL auto_increment, - name varchar(255), - PRIMARY KEY (id) - ); - -This would also define the following accessors: Product#name and -Product#name=(new_name). - - -* Associations between objects defined by simple class methods. - - class Firm < ActiveRecord::Base - has_many :clients - has_one :account - belongs_to :conglomerate - end - - {Learn more}[link:classes/ActiveRecord/Associations/ClassMethods.html] - - -* Aggregations of value objects. - - class Account < ActiveRecord::Base - composed_of :balance, class_name: 'Money', - mapping: %w(balance amount) - composed_of :address, - mapping: [%w(address_street street), %w(address_city city)] - end - - {Learn more}[link:classes/ActiveRecord/Aggregations/ClassMethods.html] - - -* Validation rules that can differ for new or existing objects. - - class Account < ActiveRecord::Base - validates :subdomain, :name, :email_address, :password, presence: true - validates :subdomain, uniqueness: true - validates :terms_of_service, acceptance: true, on: :create - validates :password, :email_address, confirmation: true, on: :create - end - - {Learn more}[link:classes/ActiveRecord/Validations.html] - - -* Callbacks available for the entire life cycle (instantiation, saving, destroying, validating, etc.). - - class Person < ActiveRecord::Base - before_destroy :invalidate_payment_plan - # the `invalidate_payment_plan` method gets called just before Person#destroy - end - - {Learn more}[link:classes/ActiveRecord/Callbacks.html] - - -* Inheritance hierarchies. - - class Company < ActiveRecord::Base; end - class Firm < Company; end - class Client < Company; end - class PriorityClient < Client; end - - {Learn more}[link:classes/ActiveRecord/Base.html] - - -* Transactions. - - # Database transaction - Account.transaction do - david.withdrawal(100) - mary.deposit(100) - end - - {Learn more}[link:classes/ActiveRecord/Transactions/ClassMethods.html] - - -* Reflections on columns, associations, and aggregations. - - reflection = Firm.reflect_on_association(:clients) - reflection.klass # => Client (class) - Firm.columns # Returns an array of column descriptors for the firms table - - {Learn more}[link:classes/ActiveRecord/Reflection/ClassMethods.html] - - -* Database abstraction through simple adapters. - - # connect to SQLite3 - ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'dbfile.sqlite3') - - # connect to MySQL with authentication - ActiveRecord::Base.establish_connection( - adapter: 'mysql2', - host: 'localhost', - username: 'me', - password: 'secret', - database: 'activerecord' - ) - - {Learn more}[link:classes/ActiveRecord/Base.html] and read about the built-in support for - MySQL[link:classes/ActiveRecord/ConnectionAdapters/Mysql2Adapter.html], - PostgreSQL[link:classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html], and - SQLite3[link:classes/ActiveRecord/ConnectionAdapters/SQLite3Adapter.html]. - - -* Logging support for Log4r[https://github.com/colbygk/log4r] and Logger[http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc]. - - ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT) - ActiveRecord::Base.logger = Log4r::Logger.new('Application Log') - - -* Database agnostic schema management with Migrations. - - class AddSystemSettings < ActiveRecord::Migration[5.0] - def up - create_table :system_settings do |t| - t.string :name - t.string :label - t.text :value - t.string :type - t.integer :position - end - - SystemSetting.create name: 'notice', label: 'Use notice?', value: 1 - end - - def down - drop_table :system_settings - end - end - - {Learn more}[link:classes/ActiveRecord/Migration.html] - - -== Philosophy - -Active Record is an implementation of the object-relational mapping (ORM) -pattern[http://www.martinfowler.com/eaaCatalog/activeRecord.html] by the same -name described by Martin Fowler: - - "An object that wraps a row in a database table or view, - encapsulates the database access, and adds domain logic on that data." - -Active Record attempts to provide a coherent wrapper as a solution for the inconvenience that is -object-relational mapping. The prime directive for this mapping has been to minimize -the amount of code needed to build a real-world domain model. This is made possible -by relying on a number of conventions that make it easy for Active Record to infer -complex relations and structures from a minimal amount of explicit direction. - -Convention over Configuration: -* No XML files! -* Lots of reflection and run-time extension -* Magic is not inherently a bad word - -Admit the Database: -* Lets you drop down to SQL for odd cases and performance -* Doesn't attempt to duplicate or replace data definitions - - -== Download and installation - -The latest version of Active Record can be installed with RubyGems: - - $ gem install activerecord - -Source code can be downloaded as part of the Rails project on GitHub: - -* https://github.com/rails/rails/tree/master/activerecord - - -== License - -Active Record is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -== Support - -API documentation is at: - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/activerecord-5.1.7/activerecord.gemspec b/debian/gems-compat/activerecord-5.1.7/activerecord.gemspec deleted file mode 100644 index 06c7a0d2e3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/activerecord.gemspec +++ /dev/null @@ -1,44 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: activerecord 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "activerecord".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/activerecord/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/activerecord" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.".freeze - s.email = "david@loudthinking.com".freeze - s.extra_rdoc_files = ["README.rdoc".freeze] - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.rdoc".freeze, "examples/performance.rb".freeze, "examples/simple.rb".freeze, "lib/active_record.rb".freeze, "lib/active_record/aggregations.rb".freeze, "lib/active_record/association_relation.rb".freeze, "lib/active_record/associations.rb".freeze, "lib/active_record/associations/alias_tracker.rb".freeze, "lib/active_record/associations/association.rb".freeze, "lib/active_record/associations/association_scope.rb".freeze, "lib/active_record/associations/belongs_to_association.rb".freeze, "lib/active_record/associations/belongs_to_polymorphic_association.rb".freeze, "lib/active_record/associations/builder/association.rb".freeze, "lib/active_record/associations/builder/belongs_to.rb".freeze, "lib/active_record/associations/builder/collection_association.rb".freeze, "lib/active_record/associations/builder/has_and_belongs_to_many.rb".freeze, "lib/active_record/associations/builder/has_many.rb".freeze, "lib/active_record/associations/builder/has_one.rb".freeze, "lib/active_record/associations/builder/singular_association.rb".freeze, "lib/active_record/associations/collection_association.rb".freeze, "lib/active_record/associations/collection_proxy.rb".freeze, "lib/active_record/associations/foreign_association.rb".freeze, "lib/active_record/associations/has_many_association.rb".freeze, "lib/active_record/associations/has_many_through_association.rb".freeze, "lib/active_record/associations/has_one_association.rb".freeze, "lib/active_record/associations/has_one_through_association.rb".freeze, "lib/active_record/associations/join_dependency.rb".freeze, "lib/active_record/associations/join_dependency/join_association.rb".freeze, "lib/active_record/associations/join_dependency/join_base.rb".freeze, "lib/active_record/associations/join_dependency/join_part.rb".freeze, "lib/active_record/associations/preloader.rb".freeze, "lib/active_record/associations/preloader/association.rb".freeze, "lib/active_record/associations/preloader/belongs_to.rb".freeze, "lib/active_record/associations/preloader/collection_association.rb".freeze, "lib/active_record/associations/preloader/has_many.rb".freeze, "lib/active_record/associations/preloader/has_many_through.rb".freeze, "lib/active_record/associations/preloader/has_one.rb".freeze, "lib/active_record/associations/preloader/has_one_through.rb".freeze, "lib/active_record/associations/preloader/singular_association.rb".freeze, "lib/active_record/associations/preloader/through_association.rb".freeze, "lib/active_record/associations/singular_association.rb".freeze, "lib/active_record/associations/through_association.rb".freeze, "lib/active_record/attribute.rb".freeze, "lib/active_record/attribute/user_provided_default.rb".freeze, "lib/active_record/attribute_assignment.rb".freeze, "lib/active_record/attribute_decorators.rb".freeze, "lib/active_record/attribute_methods.rb".freeze, "lib/active_record/attribute_methods/before_type_cast.rb".freeze, "lib/active_record/attribute_methods/dirty.rb".freeze, "lib/active_record/attribute_methods/primary_key.rb".freeze, "lib/active_record/attribute_methods/query.rb".freeze, "lib/active_record/attribute_methods/read.rb".freeze, "lib/active_record/attribute_methods/serialization.rb".freeze, "lib/active_record/attribute_methods/time_zone_conversion.rb".freeze, "lib/active_record/attribute_methods/write.rb".freeze, "lib/active_record/attribute_mutation_tracker.rb".freeze, "lib/active_record/attribute_set.rb".freeze, "lib/active_record/attribute_set/builder.rb".freeze, "lib/active_record/attribute_set/yaml_encoder.rb".freeze, "lib/active_record/attributes.rb".freeze, "lib/active_record/autosave_association.rb".freeze, "lib/active_record/base.rb".freeze, "lib/active_record/callbacks.rb".freeze, "lib/active_record/coders/json.rb".freeze, "lib/active_record/coders/yaml_column.rb".freeze, "lib/active_record/collection_cache_key.rb".freeze, "lib/active_record/connection_adapters/abstract/connection_pool.rb".freeze, "lib/active_record/connection_adapters/abstract/database_limits.rb".freeze, "lib/active_record/connection_adapters/abstract/database_statements.rb".freeze, "lib/active_record/connection_adapters/abstract/query_cache.rb".freeze, "lib/active_record/connection_adapters/abstract/quoting.rb".freeze, "lib/active_record/connection_adapters/abstract/savepoints.rb".freeze, "lib/active_record/connection_adapters/abstract/schema_creation.rb".freeze, "lib/active_record/connection_adapters/abstract/schema_definitions.rb".freeze, "lib/active_record/connection_adapters/abstract/schema_dumper.rb".freeze, "lib/active_record/connection_adapters/abstract/schema_statements.rb".freeze, "lib/active_record/connection_adapters/abstract/transaction.rb".freeze, "lib/active_record/connection_adapters/abstract_adapter.rb".freeze, "lib/active_record/connection_adapters/abstract_mysql_adapter.rb".freeze, "lib/active_record/connection_adapters/column.rb".freeze, "lib/active_record/connection_adapters/connection_specification.rb".freeze, "lib/active_record/connection_adapters/determine_if_preparable_visitor.rb".freeze, "lib/active_record/connection_adapters/mysql/column.rb".freeze, "lib/active_record/connection_adapters/mysql/database_statements.rb".freeze, "lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb".freeze, "lib/active_record/connection_adapters/mysql/quoting.rb".freeze, "lib/active_record/connection_adapters/mysql/schema_creation.rb".freeze, "lib/active_record/connection_adapters/mysql/schema_definitions.rb".freeze, "lib/active_record/connection_adapters/mysql/schema_dumper.rb".freeze, "lib/active_record/connection_adapters/mysql/schema_statements.rb".freeze, "lib/active_record/connection_adapters/mysql/type_metadata.rb".freeze, "lib/active_record/connection_adapters/mysql2_adapter.rb".freeze, "lib/active_record/connection_adapters/postgresql/column.rb".freeze, "lib/active_record/connection_adapters/postgresql/database_statements.rb".freeze, "lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/array.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/bit.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/bytea.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/cidr.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/date_time.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/decimal.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/enum.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/hstore.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/inet.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/json.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/jsonb.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/money.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/oid.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/point.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/range.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/uuid.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/vector.rb".freeze, "lib/active_record/connection_adapters/postgresql/oid/xml.rb".freeze, "lib/active_record/connection_adapters/postgresql/quoting.rb".freeze, "lib/active_record/connection_adapters/postgresql/referential_integrity.rb".freeze, "lib/active_record/connection_adapters/postgresql/schema_creation.rb".freeze, "lib/active_record/connection_adapters/postgresql/schema_definitions.rb".freeze, "lib/active_record/connection_adapters/postgresql/schema_dumper.rb".freeze, "lib/active_record/connection_adapters/postgresql/schema_statements.rb".freeze, "lib/active_record/connection_adapters/postgresql/type_metadata.rb".freeze, "lib/active_record/connection_adapters/postgresql/utils.rb".freeze, "lib/active_record/connection_adapters/postgresql_adapter.rb".freeze, "lib/active_record/connection_adapters/schema_cache.rb".freeze, "lib/active_record/connection_adapters/sql_type_metadata.rb".freeze, "lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb".freeze, "lib/active_record/connection_adapters/sqlite3/quoting.rb".freeze, "lib/active_record/connection_adapters/sqlite3/schema_creation.rb".freeze, "lib/active_record/connection_adapters/sqlite3/schema_definitions.rb".freeze, "lib/active_record/connection_adapters/sqlite3/schema_dumper.rb".freeze, "lib/active_record/connection_adapters/sqlite3/schema_statements.rb".freeze, "lib/active_record/connection_adapters/sqlite3_adapter.rb".freeze, "lib/active_record/connection_adapters/statement_pool.rb".freeze, "lib/active_record/connection_handling.rb".freeze, "lib/active_record/core.rb".freeze, "lib/active_record/counter_cache.rb".freeze, "lib/active_record/define_callbacks.rb".freeze, "lib/active_record/dynamic_matchers.rb".freeze, "lib/active_record/enum.rb".freeze, "lib/active_record/errors.rb".freeze, "lib/active_record/explain.rb".freeze, "lib/active_record/explain_registry.rb".freeze, "lib/active_record/explain_subscriber.rb".freeze, "lib/active_record/fixture_set/file.rb".freeze, "lib/active_record/fixtures.rb".freeze, "lib/active_record/gem_version.rb".freeze, "lib/active_record/inheritance.rb".freeze, "lib/active_record/integration.rb".freeze, "lib/active_record/internal_metadata.rb".freeze, "lib/active_record/legacy_yaml_adapter.rb".freeze, "lib/active_record/locale/en.yml".freeze, "lib/active_record/locking/optimistic.rb".freeze, "lib/active_record/locking/pessimistic.rb".freeze, "lib/active_record/log_subscriber.rb".freeze, "lib/active_record/migration.rb".freeze, "lib/active_record/migration/command_recorder.rb".freeze, "lib/active_record/migration/compatibility.rb".freeze, "lib/active_record/migration/join_table.rb".freeze, "lib/active_record/model_schema.rb".freeze, "lib/active_record/nested_attributes.rb".freeze, "lib/active_record/no_touching.rb".freeze, "lib/active_record/null_relation.rb".freeze, "lib/active_record/persistence.rb".freeze, "lib/active_record/query_cache.rb".freeze, "lib/active_record/querying.rb".freeze, "lib/active_record/railtie.rb".freeze, "lib/active_record/railties/console_sandbox.rb".freeze, "lib/active_record/railties/controller_runtime.rb".freeze, "lib/active_record/railties/databases.rake".freeze, "lib/active_record/railties/jdbcmysql_error.rb".freeze, "lib/active_record/readonly_attributes.rb".freeze, "lib/active_record/reflection.rb".freeze, "lib/active_record/relation.rb".freeze, "lib/active_record/relation/batches.rb".freeze, "lib/active_record/relation/batches/batch_enumerator.rb".freeze, "lib/active_record/relation/calculations.rb".freeze, "lib/active_record/relation/delegation.rb".freeze, "lib/active_record/relation/finder_methods.rb".freeze, "lib/active_record/relation/from_clause.rb".freeze, "lib/active_record/relation/merger.rb".freeze, "lib/active_record/relation/predicate_builder.rb".freeze, "lib/active_record/relation/predicate_builder/array_handler.rb".freeze, "lib/active_record/relation/predicate_builder/association_query_handler.rb".freeze, "lib/active_record/relation/predicate_builder/base_handler.rb".freeze, "lib/active_record/relation/predicate_builder/basic_object_handler.rb".freeze, "lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb".freeze, "lib/active_record/relation/predicate_builder/range_handler.rb".freeze, "lib/active_record/relation/predicate_builder/relation_handler.rb".freeze, "lib/active_record/relation/query_attribute.rb".freeze, "lib/active_record/relation/query_methods.rb".freeze, "lib/active_record/relation/record_fetch_warning.rb".freeze, "lib/active_record/relation/spawn_methods.rb".freeze, "lib/active_record/relation/where_clause.rb".freeze, "lib/active_record/relation/where_clause_factory.rb".freeze, "lib/active_record/result.rb".freeze, "lib/active_record/runtime_registry.rb".freeze, "lib/active_record/sanitization.rb".freeze, "lib/active_record/schema.rb".freeze, "lib/active_record/schema_dumper.rb".freeze, "lib/active_record/schema_migration.rb".freeze, "lib/active_record/scoping.rb".freeze, "lib/active_record/scoping/default.rb".freeze, "lib/active_record/scoping/named.rb".freeze, "lib/active_record/secure_token.rb".freeze, "lib/active_record/serialization.rb".freeze, "lib/active_record/statement_cache.rb".freeze, "lib/active_record/store.rb".freeze, "lib/active_record/suppressor.rb".freeze, "lib/active_record/table_metadata.rb".freeze, "lib/active_record/tasks/database_tasks.rb".freeze, "lib/active_record/tasks/mysql_database_tasks.rb".freeze, "lib/active_record/tasks/postgresql_database_tasks.rb".freeze, "lib/active_record/tasks/sqlite_database_tasks.rb".freeze, "lib/active_record/timestamp.rb".freeze, "lib/active_record/touch_later.rb".freeze, "lib/active_record/transactions.rb".freeze, "lib/active_record/translation.rb".freeze, "lib/active_record/type.rb".freeze, "lib/active_record/type/adapter_specific_registry.rb".freeze, "lib/active_record/type/date.rb".freeze, "lib/active_record/type/date_time.rb".freeze, "lib/active_record/type/decimal_without_scale.rb".freeze, "lib/active_record/type/hash_lookup_type_map.rb".freeze, "lib/active_record/type/internal/abstract_json.rb".freeze, "lib/active_record/type/internal/timezone.rb".freeze, "lib/active_record/type/serialized.rb".freeze, "lib/active_record/type/text.rb".freeze, "lib/active_record/type/time.rb".freeze, "lib/active_record/type/type_map.rb".freeze, "lib/active_record/type/unsigned_integer.rb".freeze, "lib/active_record/type_caster.rb".freeze, "lib/active_record/type_caster/connection.rb".freeze, "lib/active_record/type_caster/map.rb".freeze, "lib/active_record/validations.rb".freeze, "lib/active_record/validations/absence.rb".freeze, "lib/active_record/validations/associated.rb".freeze, "lib/active_record/validations/length.rb".freeze, "lib/active_record/validations/presence.rb".freeze, "lib/active_record/validations/uniqueness.rb".freeze, "lib/active_record/version.rb".freeze, "lib/rails/generators/active_record.rb".freeze, "lib/rails/generators/active_record/migration.rb".freeze, "lib/rails/generators/active_record/migration/migration_generator.rb".freeze, "lib/rails/generators/active_record/migration/templates/create_table_migration.rb".freeze, "lib/rails/generators/active_record/migration/templates/migration.rb".freeze, "lib/rails/generators/active_record/model/model_generator.rb".freeze, "lib/rails/generators/active_record/model/templates/application_record.rb".freeze, "lib/rails/generators/active_record/model/templates/model.rb".freeze, "lib/rails/generators/active_record/model/templates/module.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.rdoc_options = ["--main".freeze, "README.rdoc".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.rubygems_version = "2.7.6.2".freeze - s.summary = "Object-relational mapper framework (part of Rails).".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["~> 8.0"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 8.0"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["~> 8.0"]) - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/examples/performance.rb b/debian/gems-compat/activerecord-5.1.7/examples/performance.rb deleted file mode 100644 index 3257dd4ad7..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/examples/performance.rb +++ /dev/null @@ -1,183 +0,0 @@ -require "active_record" -require "benchmark/ips" - -TIME = (ENV["BENCHMARK_TIME"] || 20).to_i -RECORDS = (ENV["BENCHMARK_RECORDS"] || TIME * 1000).to_i - -conn = { adapter: "sqlite3", database: ":memory:" } - -ActiveRecord::Base.establish_connection(conn) - -class User < ActiveRecord::Base - connection.create_table :users, force: true do |t| - t.string :name, :email - t.timestamps - end - - has_many :exhibits -end - -class Exhibit < ActiveRecord::Base - connection.create_table :exhibits, force: true do |t| - t.belongs_to :user - t.string :name - t.text :notes - t.timestamps - end - - belongs_to :user - - def look; attributes end - def feel; look; user.name end - - def self.with_name - where("name IS NOT NULL") - end - - def self.with_notes - where("notes IS NOT NULL") - end - - def self.look(exhibits) exhibits.each(&:look) end - def self.feel(exhibits) exhibits.each(&:feel) end -end - -def progress_bar(int); print "." if (int % 100).zero? ; end - -puts "Generating data..." - -module ActiveRecord - class Faker - LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse non aliquet diam. Curabitur vel urna metus, quis malesuada elit. - Integer consequat tincidunt felis. Etiam non erat dolor. Vivamus imperdiet nibh sit amet diam eleifend id posuere diam malesuada. Mauris at accumsan sem. - Donec id lorem neque. Fusce erat lorem, ornare eu congue vitae, malesuada quis neque. Maecenas vel urna a velit pretium fermentum. Donec tortor enim, - tempor venenatis egestas a, tempor sed ipsum. Ut arcu justo, faucibus non imperdiet ac, interdum at diam. Pellentesque ipsum enim, venenatis ut iaculis vitae, - varius vitae sem. Sed rutrum quam ac elit euismod bibendum. Donec ultricies ultricies magna, at lacinia libero mollis aliquam. Sed ac arcu in tortor elementum - tincidunt vel interdum sem. Curabitur eget erat arcu. Praesent eget eros leo. Nam magna enim, sollicitudin vehicula scelerisque in, vulputate ut libero. - Praesent varius tincidunt commodo".split - - def self.name - LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join " " - end - - def self.email - LOREM.grep(/^\w*$/).sort_by { rand }.first(2).join("@") + ".com" - end - end -end - -# pre-compute the insert statements and fake data compilation, -# so the benchmarks below show the actual runtime for the execute -# method, minus the setup steps - -# Using the same paragraph for all exhibits because it is very slow -# to generate unique paragraphs for all exhibits. -notes = ActiveRecord::Faker::LOREM.join " " -today = Date.today - -puts "Inserting #{RECORDS} users and exhibits..." -RECORDS.times do |record| - user = User.create( - created_at: today, - name: ActiveRecord::Faker.name, - email: ActiveRecord::Faker.email - ) - - Exhibit.create( - created_at: today, - name: ActiveRecord::Faker.name, - user: user, - notes: notes - ) - progress_bar(record) -end -puts "Done!\n" - -Benchmark.ips(TIME) do |x| - ar_obj = Exhibit.find(1) - attrs = { name: "sam" } - attrs_first = { name: "sam" } - attrs_second = { name: "tom" } - exhibit = { - name: ActiveRecord::Faker.name, - notes: notes, - created_at: Date.today - } - - x.report("Model#id") do - ar_obj.id - end - - x.report "Model.new (instantiation)" do - Exhibit.new - end - - x.report "Model.new (setting attributes)" do - Exhibit.new(attrs) - end - - x.report "Model.first" do - Exhibit.first.look - end - - x.report "Model.take" do - Exhibit.take - end - - x.report("Model.all limit(100)") do - Exhibit.look Exhibit.limit(100) - end - - x.report("Model.all take(100)") do - Exhibit.look Exhibit.take(100) - end - - x.report "Model.all limit(100) with relationship" do - Exhibit.feel Exhibit.limit(100).includes(:user) - end - - x.report "Model.all limit(10,000)" do - Exhibit.look Exhibit.limit(10000) - end - - x.report "Model.named_scope" do - Exhibit.limit(10).with_name.with_notes - end - - x.report "Model.create" do - Exhibit.create(exhibit) - end - - x.report "Resource#attributes=" do - e = Exhibit.new(attrs_first) - e.attributes = attrs_second - end - - x.report "Resource#update" do - Exhibit.first.update(name: "bob") - end - - x.report "Resource#destroy" do - Exhibit.first.destroy - end - - x.report "Model.transaction" do - Exhibit.transaction { Exhibit.new } - end - - x.report "Model.find(id)" do - User.find(1) - end - - x.report "Model.find_by_sql" do - Exhibit.find_by_sql("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}").first - end - - x.report "Model.log" do - Exhibit.connection.send(:log, "hello", "world") {} - end - - x.report "AR.execute(query)" do - ActiveRecord::Base.connection.execute("SELECT * FROM exhibits WHERE id = #{(rand * 1000 + 1).to_i}") - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/examples/simple.rb b/debian/gems-compat/activerecord-5.1.7/examples/simple.rb deleted file mode 100644 index c3648fee48..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/examples/simple.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "active_record" - -class Person < ActiveRecord::Base - establish_connection adapter: "sqlite3", database: "foobar.db" - connection.create_table table_name, force: true do |t| - t.string :name - end -end - -bob = Person.create!(name: "bob") -puts Person.all.inspect -bob.destroy -puts Person.all.inspect diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record.rb deleted file mode 100644 index 96b8545dfc..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record.rb +++ /dev/null @@ -1,181 +0,0 @@ -#-- -# Copyright (c) 2004-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "active_support" -require "active_support/rails" -require "active_model" -require "arel" - -require "active_record/version" -require "active_record/attribute_set" - -module ActiveRecord - extend ActiveSupport::Autoload - - autoload :Attribute - autoload :Base - autoload :Callbacks - autoload :Core - autoload :ConnectionHandling - autoload :CounterCache - autoload :DynamicMatchers - autoload :Enum - autoload :InternalMetadata - autoload :Explain - autoload :Inheritance - autoload :Integration - autoload :Migration - autoload :Migrator, "active_record/migration" - autoload :ModelSchema - autoload :NestedAttributes - autoload :NoTouching - autoload :TouchLater - autoload :Persistence - autoload :QueryCache - autoload :Querying - autoload :CollectionCacheKey - autoload :ReadonlyAttributes - autoload :RecordInvalid, "active_record/validations" - autoload :Reflection - autoload :RuntimeRegistry - autoload :Sanitization - autoload :Schema - autoload :SchemaDumper - autoload :SchemaMigration - autoload :Scoping - autoload :Serialization - autoload :StatementCache - autoload :Store - autoload :Suppressor - autoload :Timestamp - autoload :Transactions - autoload :Translation - autoload :Validations - autoload :SecureToken - - eager_autoload do - autoload :ActiveRecordError, "active_record/errors" - autoload :ConnectionNotEstablished, "active_record/errors" - autoload :ConnectionAdapters, "active_record/connection_adapters/abstract_adapter" - - autoload :Aggregations - autoload :Associations - autoload :AttributeAssignment - autoload :AttributeMethods - autoload :AutosaveAssociation - - autoload :LegacyYamlAdapter - - autoload :Relation - autoload :AssociationRelation - autoload :NullRelation - - autoload_under "relation" do - autoload :QueryMethods - autoload :FinderMethods - autoload :Calculations - autoload :PredicateBuilder - autoload :SpawnMethods - autoload :Batches - autoload :Delegation - end - - autoload :Result - autoload :TableMetadata - end - - module Coders - autoload :YAMLColumn, "active_record/coders/yaml_column" - autoload :JSON, "active_record/coders/json" - end - - module AttributeMethods - extend ActiveSupport::Autoload - - eager_autoload do - autoload :BeforeTypeCast - autoload :Dirty - autoload :PrimaryKey - autoload :Query - autoload :Read - autoload :TimeZoneConversion - autoload :Write - autoload :Serialization - end - end - - module Locking - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Optimistic - autoload :Pessimistic - end - end - - module ConnectionAdapters - extend ActiveSupport::Autoload - - eager_autoload do - autoload :AbstractAdapter - end - end - - module Scoping - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Named - autoload :Default - end - end - - module Tasks - extend ActiveSupport::Autoload - - autoload :DatabaseTasks - autoload :SQLiteDatabaseTasks, "active_record/tasks/sqlite_database_tasks" - autoload :MySQLDatabaseTasks, "active_record/tasks/mysql_database_tasks" - autoload :PostgreSQLDatabaseTasks, - "active_record/tasks/postgresql_database_tasks" - end - - autoload :TestFixtures, "active_record/fixtures" - - def self.eager_load! - super - ActiveRecord::Locking.eager_load! - ActiveRecord::Scoping.eager_load! - ActiveRecord::Associations.eager_load! - ActiveRecord::AttributeMethods.eager_load! - ActiveRecord::ConnectionAdapters.eager_load! - end -end - -ActiveSupport.on_load(:active_record) do - Arel::Table.engine = self -end - -ActiveSupport.on_load(:i18n) do - I18n.load_path << File.dirname(__FILE__) + "/active_record/locale/en.yml" -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/aggregations.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/aggregations.rb deleted file mode 100644 index 10cbd5429c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/aggregations.rb +++ /dev/null @@ -1,282 +0,0 @@ -module ActiveRecord - # See ActiveRecord::Aggregations::ClassMethods for documentation - module Aggregations - extend ActiveSupport::Concern - - def initialize_dup(*) # :nodoc: - @aggregation_cache = {} - super - end - - def reload(*) # :nodoc: - clear_aggregation_cache - super - end - - private - - def clear_aggregation_cache - @aggregation_cache.clear if persisted? - end - - def init_internals - @aggregation_cache = {} - super - end - - # Active Record implements aggregation through a macro-like class method called #composed_of - # for representing attributes as value objects. It expresses relationships like "Account [is] - # composed of Money [among other things]" or "Person [is] composed of [an] address". Each call - # to the macro adds a description of how the value objects are created from the attributes of - # the entity object (when the entity is initialized either as a new object or from finding an - # existing object) and how it can be turned back into attributes (when the entity is saved to - # the database). - # - # class Customer < ActiveRecord::Base - # composed_of :balance, class_name: "Money", mapping: %w(amount currency) - # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ] - # end - # - # The customer class now has the following methods to manipulate the value objects: - # * Customer#balance, Customer#balance=(money) - # * Customer#address, Customer#address=(address) - # - # These methods will operate with value objects like the ones described below: - # - # class Money - # include Comparable - # attr_reader :amount, :currency - # EXCHANGE_RATES = { "USD_TO_DKK" => 6 } - # - # def initialize(amount, currency = "USD") - # @amount, @currency = amount, currency - # end - # - # def exchange_to(other_currency) - # exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor - # Money.new(exchanged_amount, other_currency) - # end - # - # def ==(other_money) - # amount == other_money.amount && currency == other_money.currency - # end - # - # def <=>(other_money) - # if currency == other_money.currency - # amount <=> other_money.amount - # else - # amount <=> other_money.exchange_to(currency).amount - # end - # end - # end - # - # class Address - # attr_reader :street, :city - # def initialize(street, city) - # @street, @city = street, city - # end - # - # def close_to?(other_address) - # city == other_address.city - # end - # - # def ==(other_address) - # city == other_address.city && street == other_address.street - # end - # end - # - # Now it's possible to access attributes from the database through the value objects instead. If - # you choose to name the composition the same as the attribute's name, it will be the only way to - # access that attribute. That's the case with our +balance+ attribute. You interact with the value - # objects just like you would with any other attribute: - # - # customer.balance = Money.new(20) # sets the Money value object and the attribute - # customer.balance # => Money value object - # customer.balance.exchange_to("DKK") # => Money.new(120, "DKK") - # customer.balance > Money.new(10) # => true - # customer.balance == Money.new(20) # => true - # customer.balance < Money.new(5) # => false - # - # Value objects can also be composed of multiple attributes, such as the case of Address. The order - # of the mappings will determine the order of the parameters. - # - # customer.address_street = "Hyancintvej" - # customer.address_city = "Copenhagen" - # customer.address # => Address.new("Hyancintvej", "Copenhagen") - # - # customer.address = Address.new("May Street", "Chicago") - # customer.address_street # => "May Street" - # customer.address_city # => "Chicago" - # - # == Writing value objects - # - # Value objects are immutable and interchangeable objects that represent a given value, such as - # a Money object representing $5. Two Money objects both representing $5 should be equal (through - # methods such as == and <=> from Comparable if ranking makes sense). This is - # unlike entity objects where equality is determined by identity. An entity class such as Customer can - # easily have two different objects that both have an address on Hyancintvej. Entity identity is - # determined by object or relational unique identifiers (such as primary keys). Normal - # ActiveRecord::Base classes are entity objects. - # - # It's also important to treat the value objects as immutable. Don't allow the Money object to have - # its amount changed after creation. Create a new Money object with the new value instead. The - # Money#exchange_to method is an example of this. It returns a new value object instead of changing - # its own values. Active Record won't persist value objects that have been changed through means - # other than the writer method. - # - # The immutable requirement is enforced by Active Record by freezing any object assigned as a value - # object. Attempting to change it afterwards will result in a +RuntimeError+. - # - # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not - # keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable - # - # == Custom constructors and converters - # - # By default value objects are initialized by calling the new constructor of the value - # class passing each of the mapped attributes, in the order specified by the :mapping - # option, as arguments. If the value class doesn't support this convention then #composed_of allows - # a custom constructor to be specified. - # - # When a new value is assigned to the value object, the default assumption is that the new value - # is an instance of the value class. Specifying a custom converter allows the new value to be automatically - # converted to an instance of value class if necessary. - # - # For example, the +NetworkResource+ model has +network_address+ and +cidr_range+ attributes that should be - # aggregated using the +NetAddr::CIDR+ value class (http://www.rubydoc.info/gems/netaddr/1.5.0/NetAddr/CIDR). - # The constructor for the value class is called +create+ and it expects a CIDR address string as a parameter. - # New values can be assigned to the value object using either another +NetAddr::CIDR+ object, a string - # or an array. The :constructor and :converter options can be used to meet - # these requirements: - # - # class NetworkResource < ActiveRecord::Base - # composed_of :cidr, - # class_name: 'NetAddr::CIDR', - # mapping: [ %w(network_address network), %w(cidr_range bits) ], - # allow_nil: true, - # constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") }, - # converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) } - # end - # - # # This calls the :constructor - # network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24) - # - # # These assignments will both use the :converter - # network_resource.cidr = [ '192.168.2.1', 8 ] - # network_resource.cidr = '192.168.0.1/24' - # - # # This assignment won't use the :converter as the value is already an instance of the value class - # network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8') - # - # # Saving and then reloading will use the :constructor on reload - # network_resource.save - # network_resource.reload - # - # == Finding records by a value object - # - # Once a #composed_of relationship is specified for a model, records can be loaded from the database - # by specifying an instance of the value object in the conditions hash. The following example - # finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD": - # - # Customer.where(balance: Money.new(20, "USD")) - # - module ClassMethods - # Adds reader and writer methods for manipulating a value object: - # composed_of :address adds address and address=(new_address) methods. - # - # Options are: - # * :class_name - Specifies the class name of the association. Use it only if that name - # can't be inferred from the part id. So composed_of :address will by default be linked - # to the Address class, but if the real class name is +CompanyAddress+, you'll have to specify it - # with this option. - # * :mapping - Specifies the mapping of entity attributes to attributes of the value - # object. Each mapping is represented as an array where the first item is the name of the - # entity attribute and the second item is the name of the attribute in the value object. The - # order in which mappings are defined determines the order in which attributes are sent to the - # value class constructor. - # * :allow_nil - Specifies that the value object will not be instantiated when all mapped - # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all - # mapped attributes. - # This defaults to +false+. - # * :constructor - A symbol specifying the name of the constructor method or a Proc that - # is called to initialize the value object. The constructor is passed all of the mapped attributes, - # in the order that they are defined in the :mapping option, as arguments and uses them - # to instantiate a :class_name object. - # The default is :new. - # * :converter - A symbol specifying the name of a class method of :class_name - # or a Proc that is called when a new value is assigned to the value object. The converter is - # passed the single value that is used in the assignment and is only called if the new value is - # not an instance of :class_name. If :allow_nil is set to true, the converter - # can return +nil+ to skip the assignment. - # - # Option examples: - # composed_of :temperature, mapping: %w(reading celsius) - # composed_of :balance, class_name: "Money", mapping: %w(balance amount), - # converter: Proc.new { |balance| balance.to_money } - # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ] - # composed_of :gps_location - # composed_of :gps_location, allow_nil: true - # composed_of :ip_address, - # class_name: 'IPAddr', - # mapping: %w(ip to_i), - # constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) }, - # converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) } - # - def composed_of(part_id, options = {}) - options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter) - - name = part_id.id2name - class_name = options[:class_name] || name.camelize - mapping = options[:mapping] || [ name, name ] - mapping = [ mapping ] unless mapping.first.is_a?(Array) - allow_nil = options[:allow_nil] || false - constructor = options[:constructor] || :new - converter = options[:converter] - - reader_method(name, class_name, mapping, allow_nil, constructor) - writer_method(name, class_name, mapping, allow_nil, converter) - - reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self) - Reflection.add_aggregate_reflection self, part_id, reflection - end - - private - def reader_method(name, class_name, mapping, allow_nil, constructor) - define_method(name) do - if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? { |key, _| !_read_attribute(key).nil? }) - attrs = mapping.collect { |key, _| _read_attribute(key) } - object = constructor.respond_to?(:call) ? - constructor.call(*attrs) : - class_name.constantize.send(constructor, *attrs) - @aggregation_cache[name] = object - end - @aggregation_cache[name] - end - end - - def writer_method(name, class_name, mapping, allow_nil, converter) - define_method("#{name}=") do |part| - klass = class_name.constantize - - unless part.is_a?(klass) || converter.nil? || part.nil? - part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part) - end - - hash_from_multiparameter_assignment = part.is_a?(Hash) && - part.each_key.all? { |k| k.is_a?(Integer) } - if hash_from_multiparameter_assignment - raise ArgumentError unless part.size == part.each_key.max - part = klass.new(*part.sort.map(&:last)) - end - - if part.nil? && allow_nil - mapping.each { |key, _| self[key] = nil } - @aggregation_cache[name] = nil - else - mapping.each { |key, value| self[key] = part.send(value) } - @aggregation_cache[name] = part.freeze - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/association_relation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/association_relation.rb deleted file mode 100644 index de2d03cd0b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/association_relation.rb +++ /dev/null @@ -1,38 +0,0 @@ -module ActiveRecord - class AssociationRelation < Relation - def initialize(klass, table, predicate_builder, association) - super(klass, table, predicate_builder) - @association = association - end - - def proxy_association - @association - end - - def ==(other) - other == records - end - - def build(*args, &block) - scoping { @association.build(*args, &block) } - end - alias new build - - def create(*args, &block) - scoping { @association.create(*args, &block) } - end - - def create!(*args, &block) - scoping { @association.create!(*args, &block) } - end - - private - - def exec_queries - super do |r| - @association.set_inverse_instance r - yield r if block_given? - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations.rb deleted file mode 100644 index 682c0c1deb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations.rb +++ /dev/null @@ -1,1883 +0,0 @@ -require "active_support/core_ext/enumerable" -require "active_support/core_ext/string/conversions" -require "active_support/core_ext/module/remove_method" -require "active_record/errors" - -module ActiveRecord - class AssociationNotFoundError < ConfigurationError #:nodoc: - def initialize(record = nil, association_name = nil) - if record && association_name - super("Association named '#{association_name}' was not found on #{record.class.name}; perhaps you misspelled it?") - else - super("Association was not found.") - end - end - end - - class InverseOfAssociationNotFoundError < ActiveRecordError #:nodoc: - def initialize(reflection = nil, associated_class = nil) - if reflection - super("Could not find the inverse association for #{reflection.name} (#{reflection.options[:inverse_of].inspect} in #{associated_class.nil? ? reflection.class_name : associated_class.name})") - else - super("Could not find the inverse association.") - end - end - end - - class HasManyThroughAssociationNotFoundError < ActiveRecordError #:nodoc: - def initialize(owner_class_name = nil, reflection = nil) - if owner_class_name && reflection - super("Could not find the association #{reflection.options[:through].inspect} in model #{owner_class_name}") - else - super("Could not find the association.") - end - end - end - - class HasManyThroughAssociationPolymorphicSourceError < ActiveRecordError #:nodoc: - def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil) - if owner_class_name && reflection && source_reflection - super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' on the polymorphic object '#{source_reflection.class_name}##{source_reflection.name}' without 'source_type'. Try adding 'source_type: \"#{reflection.name.to_s.classify}\"' to 'has_many :through' definition.") - else - super("Cannot have a has_many :through association.") - end - end - end - - class HasManyThroughAssociationPolymorphicThroughError < ActiveRecordError #:nodoc: - def initialize(owner_class_name = nil, reflection = nil) - if owner_class_name && reflection - super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.") - else - super("Cannot have a has_many :through association.") - end - end - end - - class HasManyThroughAssociationPointlessSourceTypeError < ActiveRecordError #:nodoc: - def initialize(owner_class_name = nil, reflection = nil, source_reflection = nil) - if owner_class_name && reflection && source_reflection - super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' with a :source_type option if the '#{reflection.through_reflection.class_name}##{source_reflection.name}' is not polymorphic. Try removing :source_type on your association.") - else - super("Cannot have a has_many :through association.") - end - end - end - - class HasOneThroughCantAssociateThroughCollection < ActiveRecordError #:nodoc: - def initialize(owner_class_name = nil, reflection = nil, through_reflection = nil) - if owner_class_name && reflection && through_reflection - super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' where the :through association '#{owner_class_name}##{through_reflection.name}' is a collection. Specify a has_one or belongs_to association in the :through option instead.") - else - super("Cannot have a has_one :through association.") - end - end - end - - class HasOneAssociationPolymorphicThroughError < ActiveRecordError #:nodoc: - def initialize(owner_class_name = nil, reflection = nil) - if owner_class_name && reflection - super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.") - else - super("Cannot have a has_one :through association.") - end - end - end - - class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc: - def initialize(reflection = nil) - if reflection - through_reflection = reflection.through_reflection - source_reflection_names = reflection.source_reflection_names - source_associations = reflection.through_reflection.klass._reflections.keys - super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => '. Is it one of #{source_associations.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ', locale: :en)}?") - else - super("Could not find the source association(s).") - end - end - end - - class HasManyThroughOrderError < ActiveRecordError #:nodoc: - def initialize(owner_class_name = nil, reflection = nil, through_reflection = nil) - if owner_class_name && reflection && through_reflection - super("Cannot have a has_many :through association '#{owner_class_name}##{reflection.name}' which goes through '#{owner_class_name}##{through_reflection.name}' before the through association is defined.") - else - super("Cannot have a has_many :through association before the through association is defined.") - end - end - end - - class ThroughCantAssociateThroughHasOneOrManyReflection < ActiveRecordError #:nodoc: - def initialize(owner = nil, reflection = nil) - if owner && reflection - super("Cannot modify association '#{owner.class.name}##{reflection.name}' because the source reflection class '#{reflection.source_reflection.class_name}' is associated to '#{reflection.through_reflection.class_name}' via :#{reflection.source_reflection.macro}.") - else - super("Cannot modify association.") - end - end - end - - class AmbiguousSourceReflectionForThroughAssociation < ActiveRecordError # :nodoc: - def initialize(klass, macro, association_name, options, possible_sources) - example_options = options.dup - example_options[:source] = possible_sources.first - - super("Ambiguous source reflection for through association. Please " \ - "specify a :source directive on your declaration like:\n" \ - "\n" \ - " class #{klass} < ActiveRecord::Base\n" \ - " #{macro} :#{association_name}, #{example_options}\n" \ - " end" - ) - end - end - - class HasManyThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc: - end - - class HasOneThroughCantAssociateThroughHasOneOrManyReflection < ThroughCantAssociateThroughHasOneOrManyReflection #:nodoc: - end - - class HasManyThroughCantAssociateNewRecords < ActiveRecordError #:nodoc: - def initialize(owner = nil, reflection = nil) - if owner && reflection - super("Cannot associate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to create the has_many :through record associating them.") - else - super("Cannot associate new records.") - end - end - end - - class HasManyThroughCantDissociateNewRecords < ActiveRecordError #:nodoc: - def initialize(owner = nil, reflection = nil) - if owner && reflection - super("Cannot dissociate new records through '#{owner.class.name}##{reflection.name}' on '#{reflection.source_reflection.class_name rescue nil}##{reflection.source_reflection.name rescue nil}'. Both records must have an id in order to delete the has_many :through record associating them.") - else - super("Cannot dissociate new records.") - end - end - end - - class ThroughNestedAssociationsAreReadonly < ActiveRecordError #:nodoc: - def initialize(owner = nil, reflection = nil) - if owner && reflection - super("Cannot modify association '#{owner.class.name}##{reflection.name}' because it goes through more than one other association.") - else - super("Through nested associations are read-only.") - end - end - end - - class HasManyThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc: - end - - class HasOneThroughNestedAssociationsAreReadonly < ThroughNestedAssociationsAreReadonly #:nodoc: - end - - # This error is raised when trying to eager load a polymorphic association using a JOIN. - # Eager loading polymorphic associations is only possible with - # {ActiveRecord::Relation#preload}[rdoc-ref:QueryMethods#preload]. - class EagerLoadPolymorphicError < ActiveRecordError - def initialize(reflection = nil) - if reflection - super("Cannot eagerly load the polymorphic association #{reflection.name.inspect}") - else - super("Eager load polymorphic error.") - end - end - end - - class ReadOnlyAssociation < ActiveRecordError #:nodoc: - def initialize(reflection = nil) - if reflection - super("Cannot add to a has_many :through association. Try adding to #{reflection.through_reflection.name.inspect}.") - else - super("Read-only reflection error.") - end - end - end - - # This error is raised when trying to destroy a parent instance in N:1 or 1:1 associations - # (has_many, has_one) when there is at least 1 child associated instance. - # ex: if @project.tasks.size > 0, DeleteRestrictionError will be raised when trying to destroy @project - class DeleteRestrictionError < ActiveRecordError #:nodoc: - def initialize(name = nil) - if name - super("Cannot delete record because of dependent #{name}") - else - super("Delete restriction error.") - end - end - end - - # See ActiveRecord::Associations::ClassMethods for documentation. - module Associations # :nodoc: - extend ActiveSupport::Autoload - extend ActiveSupport::Concern - - # These classes will be loaded when associations are created. - # So there is no need to eager load them. - autoload :Association - autoload :SingularAssociation - autoload :CollectionAssociation - autoload :ForeignAssociation - autoload :CollectionProxy - autoload :ThroughAssociation - - module Builder #:nodoc: - autoload :Association, "active_record/associations/builder/association" - autoload :SingularAssociation, "active_record/associations/builder/singular_association" - autoload :CollectionAssociation, "active_record/associations/builder/collection_association" - - autoload :BelongsTo, "active_record/associations/builder/belongs_to" - autoload :HasOne, "active_record/associations/builder/has_one" - autoload :HasMany, "active_record/associations/builder/has_many" - autoload :HasAndBelongsToMany, "active_record/associations/builder/has_and_belongs_to_many" - end - - eager_autoload do - autoload :BelongsToAssociation - autoload :BelongsToPolymorphicAssociation - autoload :HasManyAssociation - autoload :HasManyThroughAssociation - autoload :HasOneAssociation - autoload :HasOneThroughAssociation - - autoload :Preloader - autoload :JoinDependency - autoload :AssociationScope - autoload :AliasTracker - end - - def self.eager_load! - super - Preloader.eager_load! - end - - # Returns the association instance for the given name, instantiating it if it doesn't already exist - def association(name) #:nodoc: - association = association_instance_get(name) - - if association.nil? - unless reflection = self.class._reflect_on_association(name) - raise AssociationNotFoundError.new(self, name) - end - association = reflection.association_class.new(self, reflection) - association_instance_set(name, association) - end - - association - end - - def association_cached?(name) # :nodoc - @association_cache.key?(name) - end - - def initialize_dup(*) # :nodoc: - @association_cache = {} - super - end - - def reload(*) # :nodoc: - clear_association_cache - super - end - - private - # Clears out the association cache. - def clear_association_cache - @association_cache.clear if persisted? - end - - def init_internals - @association_cache = {} - super - end - - # Returns the specified association instance if it exists, +nil+ otherwise. - def association_instance_get(name) - @association_cache[name] - end - - # Set the specified association instance. - def association_instance_set(name, association) - @association_cache[name] = association - end - - # \Associations are a set of macro-like class methods for tying objects together through - # foreign keys. They express relationships like "Project has one Project Manager" - # or "Project belongs to a Portfolio". Each macro adds a number of methods to the - # class which are specialized according to the collection or association symbol and the - # options hash. It works much the same way as Ruby's own attr* - # methods. - # - # class Project < ActiveRecord::Base - # belongs_to :portfolio - # has_one :project_manager - # has_many :milestones - # has_and_belongs_to_many :categories - # end - # - # The project class now has the following methods (and more) to ease the traversal and - # manipulation of its relationships: - # * Project#portfolio, Project#portfolio=(portfolio), Project#portfolio.nil? - # * Project#project_manager, Project#project_manager=(project_manager), Project#project_manager.nil?, - # * Project#milestones.empty?, Project#milestones.size, Project#milestones, Project#milestones<<(milestone), - # Project#milestones.delete(milestone), Project#milestones.destroy(milestone), Project#milestones.find(milestone_id), - # Project#milestones.build, Project#milestones.create - # * Project#categories.empty?, Project#categories.size, Project#categories, Project#categories<<(category1), - # Project#categories.delete(category1), Project#categories.destroy(category1) - # - # === A word of warning - # - # Don't create associations that have the same name as {instance methods}[rdoc-ref:ActiveRecord::Core] of - # ActiveRecord::Base. Since the association adds a method with that name to - # its model, using an association with the same name as one provided by ActiveRecord::Base will override the method inherited through ActiveRecord::Base and will break things. - # For instance, +attributes+ and +connection+ would be bad choices for association names, because those names already exist in the list of ActiveRecord::Base instance methods. - # - # == Auto-generated methods - # See also Instance Public methods below for more details. - # - # === Singular associations (one-to-one) - # | | belongs_to | - # generated methods | belongs_to | :polymorphic | has_one - # ----------------------------------+------------+--------------+--------- - # other | X | X | X - # other=(other) | X | X | X - # build_other(attributes={}) | X | | X - # create_other(attributes={}) | X | | X - # create_other!(attributes={}) | X | | X - # reload_other | X | X | X - # - # === Collection associations (one-to-many / many-to-many) - # | | | has_many - # generated methods | habtm | has_many | :through - # ----------------------------------+-------+----------+---------- - # others | X | X | X - # others=(other,other,...) | X | X | X - # other_ids | X | X | X - # other_ids=(id,id,...) | X | X | X - # others<< | X | X | X - # others.push | X | X | X - # others.concat | X | X | X - # others.build(attributes={}) | X | X | X - # others.create(attributes={}) | X | X | X - # others.create!(attributes={}) | X | X | X - # others.size | X | X | X - # others.length | X | X | X - # others.count | X | X | X - # others.sum(*args) | X | X | X - # others.empty? | X | X | X - # others.clear | X | X | X - # others.delete(other,other,...) | X | X | X - # others.delete_all | X | X | X - # others.destroy(other,other,...) | X | X | X - # others.destroy_all | X | X | X - # others.find(*args) | X | X | X - # others.exists? | X | X | X - # others.distinct | X | X | X - # others.reset | X | X | X - # others.reload | X | X | X - # - # === Overriding generated methods - # - # Association methods are generated in a module included into the model - # class, making overrides easy. The original generated method can thus be - # called with +super+: - # - # class Car < ActiveRecord::Base - # belongs_to :owner - # belongs_to :old_owner - # - # def owner=(new_owner) - # self.old_owner = self.owner - # super - # end - # end - # - # The association methods module is included immediately after the - # generated attributes methods module, meaning an association will - # override the methods for an attribute with the same name. - # - # == Cardinality and associations - # - # Active Record associations can be used to describe one-to-one, one-to-many and many-to-many - # relationships between models. Each model uses an association to describe its role in - # the relation. The #belongs_to association is always used in the model that has - # the foreign key. - # - # === One-to-one - # - # Use #has_one in the base, and #belongs_to in the associated model. - # - # class Employee < ActiveRecord::Base - # has_one :office - # end - # class Office < ActiveRecord::Base - # belongs_to :employee # foreign key - employee_id - # end - # - # === One-to-many - # - # Use #has_many in the base, and #belongs_to in the associated model. - # - # class Manager < ActiveRecord::Base - # has_many :employees - # end - # class Employee < ActiveRecord::Base - # belongs_to :manager # foreign key - manager_id - # end - # - # === Many-to-many - # - # There are two ways to build a many-to-many relationship. - # - # The first way uses a #has_many association with the :through option and a join model, so - # there are two stages of associations. - # - # class Assignment < ActiveRecord::Base - # belongs_to :programmer # foreign key - programmer_id - # belongs_to :project # foreign key - project_id - # end - # class Programmer < ActiveRecord::Base - # has_many :assignments - # has_many :projects, through: :assignments - # end - # class Project < ActiveRecord::Base - # has_many :assignments - # has_many :programmers, through: :assignments - # end - # - # For the second way, use #has_and_belongs_to_many in both models. This requires a join table - # that has no corresponding model or primary key. - # - # class Programmer < ActiveRecord::Base - # has_and_belongs_to_many :projects # foreign keys in the join table - # end - # class Project < ActiveRecord::Base - # has_and_belongs_to_many :programmers # foreign keys in the join table - # end - # - # Choosing which way to build a many-to-many relationship is not always simple. - # If you need to work with the relationship model as its own entity, - # use #has_many :through. Use #has_and_belongs_to_many when working with legacy schemas or when - # you never work directly with the relationship itself. - # - # == Is it a #belongs_to or #has_one association? - # - # Both express a 1-1 relationship. The difference is mostly where to place the foreign - # key, which goes on the table for the class declaring the #belongs_to relationship. - # - # class User < ActiveRecord::Base - # # I reference an account. - # belongs_to :account - # end - # - # class Account < ActiveRecord::Base - # # One user references me. - # has_one :user - # end - # - # The tables for these classes could look something like: - # - # CREATE TABLE users ( - # id int NOT NULL auto_increment, - # account_id int default NULL, - # name varchar default NULL, - # PRIMARY KEY (id) - # ) - # - # CREATE TABLE accounts ( - # id int NOT NULL auto_increment, - # name varchar default NULL, - # PRIMARY KEY (id) - # ) - # - # == Unsaved objects and associations - # - # You can manipulate objects and associations before they are saved to the database, but - # there is some special behavior you should be aware of, mostly involving the saving of - # associated objects. - # - # You can set the :autosave option on a #has_one, #belongs_to, - # #has_many, or #has_and_belongs_to_many association. Setting it - # to +true+ will _always_ save the members, whereas setting it to +false+ will - # _never_ save the members. More details about :autosave option is available at - # AutosaveAssociation. - # - # === One-to-one associations - # - # * Assigning an object to a #has_one association automatically saves that object and - # the object being replaced (if there is one), in order to update their foreign - # keys - except if the parent object is unsaved (new_record? == true). - # * If either of these saves fail (due to one of the objects being invalid), an - # ActiveRecord::RecordNotSaved exception is raised and the assignment is - # cancelled. - # * If you wish to assign an object to a #has_one association without saving it, - # use the #build_association method (documented below). The object being - # replaced will still be saved to update its foreign key. - # * Assigning an object to a #belongs_to association does not save the object, since - # the foreign key field belongs on the parent. It does not save the parent either. - # - # === Collections - # - # * Adding an object to a collection (#has_many or #has_and_belongs_to_many) automatically - # saves that object, except if the parent object (the owner of the collection) is not yet - # stored in the database. - # * If saving any of the objects being added to a collection (via push or similar) - # fails, then push returns +false+. - # * If saving fails while replacing the collection (via association=), an - # ActiveRecord::RecordNotSaved exception is raised and the assignment is - # cancelled. - # * You can add an object to a collection without automatically saving it by using the - # collection.build method (documented below). - # * All unsaved (new_record? == true) members of the collection are automatically - # saved when the parent is saved. - # - # == Customizing the query - # - # \Associations are built from Relation objects, and you can use the Relation syntax - # to customize them. For example, to add a condition: - # - # class Blog < ActiveRecord::Base - # has_many :published_posts, -> { where(published: true) }, class_name: 'Post' - # end - # - # Inside the -> { ... } block you can use all of the usual Relation methods. - # - # === Accessing the owner object - # - # Sometimes it is useful to have access to the owner object when building the query. The owner - # is passed as a parameter to the block. For example, the following association would find all - # events that occur on the user's birthday: - # - # class User < ActiveRecord::Base - # has_many :birthday_events, ->(user) { where(starts_on: user.birthday) }, class_name: 'Event' - # end - # - # Note: Joining, eager loading and preloading of these associations is not fully possible. - # These operations happen before instance creation and the scope will be called with a +nil+ argument. - # This can lead to unexpected behavior and is deprecated. - # - # == Association callbacks - # - # Similar to the normal callbacks that hook into the life cycle of an Active Record object, - # you can also define callbacks that get triggered when you add an object to or remove an - # object from an association collection. - # - # class Project - # has_and_belongs_to_many :developers, after_add: :evaluate_velocity - # - # def evaluate_velocity(developer) - # ... - # end - # end - # - # It's possible to stack callbacks by passing them as an array. Example: - # - # class Project - # has_and_belongs_to_many :developers, - # after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}] - # end - # - # Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+. - # - # If any of the +before_add+ callbacks throw an exception, the object will not be - # added to the collection. - # - # Similarly, if any of the +before_remove+ callbacks throw an exception, the object - # will not be removed from the collection. - # - # == Association extensions - # - # The proxy objects that control the access to associations can be extended through anonymous - # modules. This is especially beneficial for adding new finders, creators, and other - # factory-type methods that are only used as part of this association. - # - # class Account < ActiveRecord::Base - # has_many :people do - # def find_or_create_by_name(name) - # first_name, last_name = name.split(" ", 2) - # find_or_create_by(first_name: first_name, last_name: last_name) - # end - # end - # end - # - # person = Account.first.people.find_or_create_by_name("David Heinemeier Hansson") - # person.first_name # => "David" - # person.last_name # => "Heinemeier Hansson" - # - # If you need to share the same extensions between many associations, you can use a named - # extension module. - # - # module FindOrCreateByNameExtension - # def find_or_create_by_name(name) - # first_name, last_name = name.split(" ", 2) - # find_or_create_by(first_name: first_name, last_name: last_name) - # end - # end - # - # class Account < ActiveRecord::Base - # has_many :people, -> { extending FindOrCreateByNameExtension } - # end - # - # class Company < ActiveRecord::Base - # has_many :people, -> { extending FindOrCreateByNameExtension } - # end - # - # Some extensions can only be made to work with knowledge of the association's internals. - # Extensions can access relevant state using the following methods (where +items+ is the - # name of the association): - # - # * record.association(:items).owner - Returns the object the association is part of. - # * record.association(:items).reflection - Returns the reflection object that describes the association. - # * record.association(:items).target - Returns the associated object for #belongs_to and #has_one, or - # the collection of associated objects for #has_many and #has_and_belongs_to_many. - # - # However, inside the actual extension code, you will not have access to the record as - # above. In this case, you can access proxy_association. For example, - # record.association(:items) and record.items.proxy_association will return - # the same object, allowing you to make calls like proxy_association.owner inside - # association extensions. - # - # == Association Join Models - # - # Has Many associations can be configured with the :through option to use an - # explicit join model to retrieve the data. This operates similarly to a - # #has_and_belongs_to_many association. The advantage is that you're able to add validations, - # callbacks, and extra attributes on the join model. Consider the following schema: - # - # class Author < ActiveRecord::Base - # has_many :authorships - # has_many :books, through: :authorships - # end - # - # class Authorship < ActiveRecord::Base - # belongs_to :author - # belongs_to :book - # end - # - # @author = Author.first - # @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to - # @author.books # selects all books by using the Authorship join model - # - # You can also go through a #has_many association on the join model: - # - # class Firm < ActiveRecord::Base - # has_many :clients - # has_many :invoices, through: :clients - # end - # - # class Client < ActiveRecord::Base - # belongs_to :firm - # has_many :invoices - # end - # - # class Invoice < ActiveRecord::Base - # belongs_to :client - # end - # - # @firm = Firm.first - # @firm.clients.flat_map { |c| c.invoices } # select all invoices for all clients of the firm - # @firm.invoices # selects all invoices by going through the Client join model - # - # Similarly you can go through a #has_one association on the join model: - # - # class Group < ActiveRecord::Base - # has_many :users - # has_many :avatars, through: :users - # end - # - # class User < ActiveRecord::Base - # belongs_to :group - # has_one :avatar - # end - # - # class Avatar < ActiveRecord::Base - # belongs_to :user - # end - # - # @group = Group.first - # @group.users.collect { |u| u.avatar }.compact # select all avatars for all users in the group - # @group.avatars # selects all avatars by going through the User join model. - # - # An important caveat with going through #has_one or #has_many associations on the - # join model is that these associations are *read-only*. For example, the following - # would not work following the previous example: - # - # @group.avatars << Avatar.new # this would work if User belonged_to Avatar rather than the other way around - # @group.avatars.delete(@group.avatars.last) # so would this - # - # == Setting Inverses - # - # If you are using a #belongs_to on the join model, it is a good idea to set the - # :inverse_of option on the #belongs_to, which will mean that the following example - # works correctly (where tags is a #has_many :through association): - # - # @post = Post.first - # @tag = @post.tags.build name: "ruby" - # @tag.save - # - # The last line ought to save the through record (a Tagging). This will only work if the - # :inverse_of is set: - # - # class Tagging < ActiveRecord::Base - # belongs_to :post - # belongs_to :tag, inverse_of: :taggings - # end - # - # If you do not set the :inverse_of record, the association will - # do its best to match itself up with the correct inverse. Automatic - # inverse detection only works on #has_many, #has_one, and - # #belongs_to associations. - # - # Extra options on the associations, as defined in the - # AssociationReflection::INVALID_AUTOMATIC_INVERSE_OPTIONS constant, will - # also prevent the association's inverse from being found automatically. - # - # The automatic guessing of the inverse association uses a heuristic based - # on the name of the class, so it may not work for all associations, - # especially the ones with non-standard names. - # - # You can turn off the automatic detection of inverse associations by setting - # the :inverse_of option to false like so: - # - # class Tagging < ActiveRecord::Base - # belongs_to :tag, inverse_of: false - # end - # - # == Nested \Associations - # - # You can actually specify *any* association with the :through option, including an - # association which has a :through option itself. For example: - # - # class Author < ActiveRecord::Base - # has_many :posts - # has_many :comments, through: :posts - # has_many :commenters, through: :comments - # end - # - # class Post < ActiveRecord::Base - # has_many :comments - # end - # - # class Comment < ActiveRecord::Base - # belongs_to :commenter - # end - # - # @author = Author.first - # @author.commenters # => People who commented on posts written by the author - # - # An equivalent way of setting up this association this would be: - # - # class Author < ActiveRecord::Base - # has_many :posts - # has_many :commenters, through: :posts - # end - # - # class Post < ActiveRecord::Base - # has_many :comments - # has_many :commenters, through: :comments - # end - # - # class Comment < ActiveRecord::Base - # belongs_to :commenter - # end - # - # When using a nested association, you will not be able to modify the association because there - # is not enough information to know what modification to make. For example, if you tried to - # add a Commenter in the example above, there would be no way to tell how to set up the - # intermediate Post and Comment objects. - # - # == Polymorphic \Associations - # - # Polymorphic associations on models are not restricted on what types of models they - # can be associated with. Rather, they specify an interface that a #has_many association - # must adhere to. - # - # class Asset < ActiveRecord::Base - # belongs_to :attachable, polymorphic: true - # end - # - # class Post < ActiveRecord::Base - # has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use. - # end - # - # @asset.attachable = @post - # - # This works by using a type column in addition to a foreign key to specify the associated - # record. In the Asset example, you'd need an +attachable_id+ integer column and an - # +attachable_type+ string column. - # - # Using polymorphic associations in combination with single table inheritance (STI) is - # a little tricky. In order for the associations to work as expected, ensure that you - # store the base model for the STI models in the type column of the polymorphic - # association. To continue with the asset example above, suppose there are guest posts - # and member posts that use the posts table for STI. In this case, there must be a +type+ - # column in the posts table. - # - # Note: The attachable_type= method is being called when assigning an +attachable+. - # The +class_name+ of the +attachable+ is passed as a String. - # - # class Asset < ActiveRecord::Base - # belongs_to :attachable, polymorphic: true - # - # def attachable_type=(class_name) - # super(class_name.constantize.base_class.to_s) - # end - # end - # - # class Post < ActiveRecord::Base - # # because we store "Post" in attachable_type now dependent: :destroy will work - # has_many :assets, as: :attachable, dependent: :destroy - # end - # - # class GuestPost < Post - # end - # - # class MemberPost < Post - # end - # - # == Caching - # - # All of the methods are built on a simple caching principle that will keep the result - # of the last query around unless specifically instructed not to. The cache is even - # shared across methods to make it even cheaper to use the macro-added methods without - # worrying too much about performance at the first go. - # - # project.milestones # fetches milestones from the database - # project.milestones.size # uses the milestone cache - # project.milestones.empty? # uses the milestone cache - # project.milestones(true).size # fetches milestones from the database - # project.milestones # uses the milestone cache - # - # == Eager loading of associations - # - # Eager loading is a way to find objects of a certain class and a number of named associations. - # It is one of the easiest ways to prevent the dreaded N+1 problem in which fetching 100 - # posts that each need to display their author triggers 101 database queries. Through the - # use of eager loading, the number of queries will be reduced from 101 to 2. - # - # class Post < ActiveRecord::Base - # belongs_to :author - # has_many :comments - # end - # - # Consider the following loop using the class above: - # - # Post.all.each do |post| - # puts "Post: " + post.title - # puts "Written by: " + post.author.name - # puts "Last comment on: " + post.comments.first.created_on - # end - # - # To iterate over these one hundred posts, we'll generate 201 database queries. Let's - # first just optimize it for retrieving the author: - # - # Post.includes(:author).each do |post| - # - # This references the name of the #belongs_to association that also used the :author - # symbol. After loading the posts, +find+ will collect the +author_id+ from each one and load - # all of the referenced authors with one query. Doing so will cut down the number of queries - # from 201 to 102. - # - # We can improve upon the situation further by referencing both associations in the finder with: - # - # Post.includes(:author, :comments).each do |post| - # - # This will load all comments with a single query. This reduces the total number of queries - # to 3. In general, the number of queries will be 1 plus the number of associations - # named (except if some of the associations are polymorphic #belongs_to - see below). - # - # To include a deep hierarchy of associations, use a hash: - # - # Post.includes(:author, { comments: { author: :gravatar } }).each do |post| - # - # The above code will load all the comments and all of their associated - # authors and gravatars. You can mix and match any combination of symbols, - # arrays, and hashes to retrieve the associations you want to load. - # - # All of this power shouldn't fool you into thinking that you can pull out huge amounts - # of data with no performance penalty just because you've reduced the number of queries. - # The database still needs to send all the data to Active Record and it still needs to - # be processed. So it's no catch-all for performance problems, but it's a great way to - # cut down on the number of queries in a situation as the one described above. - # - # Since only one table is loaded at a time, conditions or orders cannot reference tables - # other than the main one. If this is the case, Active Record falls back to the previously - # used LEFT OUTER JOIN based strategy. For example: - # - # Post.includes([:author, :comments]).where(['comments.approved = ?', true]) - # - # This will result in a single SQL query with joins along the lines of: - # LEFT OUTER JOIN comments ON comments.post_id = posts.id and - # LEFT OUTER JOIN authors ON authors.id = posts.author_id. Note that using conditions - # like this can have unintended consequences. - # In the above example, posts with no approved comments are not returned at all because - # the conditions apply to the SQL statement as a whole and not just to the association. - # - # You must disambiguate column references for this fallback to happen, for example - # order: "author.name DESC" will work but order: "name DESC" will not. - # - # If you want to load all posts (including posts with no approved comments), then write - # your own LEFT OUTER JOIN query using ON: - # - # Post.joins("LEFT OUTER JOIN comments ON comments.post_id = posts.id AND comments.approved = '1'") - # - # In this case, it is usually more natural to include an association which has conditions defined on it: - # - # class Post < ActiveRecord::Base - # has_many :approved_comments, -> { where(approved: true) }, class_name: 'Comment' - # end - # - # Post.includes(:approved_comments) - # - # This will load posts and eager load the +approved_comments+ association, which contains - # only those comments that have been approved. - # - # If you eager load an association with a specified :limit option, it will be ignored, - # returning all the associated objects: - # - # class Picture < ActiveRecord::Base - # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment' - # end - # - # Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments. - # - # Eager loading is supported with polymorphic associations. - # - # class Address < ActiveRecord::Base - # belongs_to :addressable, polymorphic: true - # end - # - # A call that tries to eager load the addressable model - # - # Address.includes(:addressable) - # - # This will execute one query to load the addresses and load the addressables with one - # query per addressable type. - # For example, if all the addressables are either of class Person or Company, then a total - # of 3 queries will be executed. The list of addressable types to load is determined on - # the back of the addresses loaded. This is not supported if Active Record has to fallback - # to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError. - # The reason is that the parent model's type is a column value so its corresponding table - # name cannot be put in the +FROM+/+JOIN+ clauses of that query. - # - # == Table Aliasing - # - # Active Record uses table aliasing in the case that a table is referenced multiple times - # in a join. If a table is referenced only once, the standard table name is used. The - # second time, the table is aliased as #{reflection_name}_#{parent_table_name}. - # Indexes are appended for any more successive uses of the table name. - # - # Post.joins(:comments) - # # => SELECT ... FROM posts INNER JOIN comments ON ... - # Post.joins(:special_comments) # STI - # # => SELECT ... FROM posts INNER JOIN comments ON ... AND comments.type = 'SpecialComment' - # Post.joins(:comments, :special_comments) # special_comments is the reflection name, posts is the parent table name - # # => SELECT ... FROM posts INNER JOIN comments ON ... INNER JOIN comments special_comments_posts - # - # Acts as tree example: - # - # TreeMixin.joins(:children) - # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... - # TreeMixin.joins(children: :parent) - # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... - # INNER JOIN parents_mixins ... - # TreeMixin.joins(children: {parent: :children}) - # # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ... - # INNER JOIN parents_mixins ... - # INNER JOIN mixins childrens_mixins_2 - # - # Has and Belongs to Many join tables use the same idea, but add a _join suffix: - # - # Post.joins(:categories) - # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... - # Post.joins(categories: :posts) - # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... - # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories - # Post.joins(categories: {posts: :categories}) - # # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ... - # INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories - # INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2 - # - # If you wish to specify your own custom joins using ActiveRecord::QueryMethods#joins method, those table - # names will take precedence over the eager associations: - # - # Post.joins(:comments).joins("inner join comments ...") - # # => SELECT ... FROM posts INNER JOIN comments_posts ON ... INNER JOIN comments ... - # Post.joins(:comments, :special_comments).joins("inner join comments ...") - # # => SELECT ... FROM posts INNER JOIN comments comments_posts ON ... - # INNER JOIN comments special_comments_posts ... - # INNER JOIN comments ... - # - # Table aliases are automatically truncated according to the maximum length of table identifiers - # according to the specific database. - # - # == Modules - # - # By default, associations will look for objects within the current module scope. Consider: - # - # module MyApplication - # module Business - # class Firm < ActiveRecord::Base - # has_many :clients - # end - # - # class Client < ActiveRecord::Base; end - # end - # end - # - # When Firm#clients is called, it will in turn call - # MyApplication::Business::Client.find_all_by_firm_id(firm.id). - # If you want to associate with a class in another module scope, this can be done by - # specifying the complete class name. - # - # module MyApplication - # module Business - # class Firm < ActiveRecord::Base; end - # end - # - # module Billing - # class Account < ActiveRecord::Base - # belongs_to :firm, class_name: "MyApplication::Business::Firm" - # end - # end - # end - # - # == Bi-directional associations - # - # When you specify an association, there is usually an association on the associated model - # that specifies the same relationship in reverse. For example, with the following models: - # - # class Dungeon < ActiveRecord::Base - # has_many :traps - # has_one :evil_wizard - # end - # - # class Trap < ActiveRecord::Base - # belongs_to :dungeon - # end - # - # class EvilWizard < ActiveRecord::Base - # belongs_to :dungeon - # end - # - # The +traps+ association on +Dungeon+ and the +dungeon+ association on +Trap+ are - # the inverse of each other, and the inverse of the +dungeon+ association on +EvilWizard+ - # is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default, - # Active Record can guess the inverse of the association based on the name - # of the class. The result is the following: - # - # d = Dungeon.first - # t = d.traps.first - # d.object_id == t.dungeon.object_id # => true - # - # The +Dungeon+ instances +d+ and t.dungeon in the above example refer to - # the same in-memory instance since the association matches the name of the class. - # The result would be the same if we added +:inverse_of+ to our model definitions: - # - # class Dungeon < ActiveRecord::Base - # has_many :traps, inverse_of: :dungeon - # has_one :evil_wizard, inverse_of: :dungeon - # end - # - # class Trap < ActiveRecord::Base - # belongs_to :dungeon, inverse_of: :traps - # end - # - # class EvilWizard < ActiveRecord::Base - # belongs_to :dungeon, inverse_of: :evil_wizard - # end - # - # There are limitations to :inverse_of support: - # - # * does not work with :through associations. - # * does not work with :polymorphic associations. - # * inverse associations for #belongs_to associations #has_many are ignored. - # - # For more information, see the documentation for the +:inverse_of+ option. - # - # == Deleting from associations - # - # === Dependent associations - # - # #has_many, #has_one, and #belongs_to associations support the :dependent option. - # This allows you to specify that associated records should be deleted when the owner is - # deleted. - # - # For example: - # - # class Author - # has_many :posts, dependent: :destroy - # end - # Author.find(1).destroy # => Will destroy all of the author's posts, too - # - # The :dependent option can have different values which specify how the deletion - # is done. For more information, see the documentation for this option on the different - # specific association types. When no option is given, the behavior is to do nothing - # with the associated records when destroying a record. - # - # Note that :dependent is implemented using Rails' callback - # system, which works by processing callbacks in order. Therefore, other - # callbacks declared either before or after the :dependent option - # can affect what it does. - # - # Note that :dependent option is ignored for #has_one :through associations. - # - # === Delete or destroy? - # - # #has_many and #has_and_belongs_to_many associations have the methods destroy, - # delete, destroy_all and delete_all. - # - # For #has_and_belongs_to_many, delete and destroy are the same: they - # cause the records in the join table to be removed. - # - # For #has_many, destroy and destroy_all will always call the destroy method of the - # record(s) being removed so that callbacks are run. However delete and delete_all will either - # do the deletion according to the strategy specified by the :dependent option, or - # if no :dependent option is given, then it will follow the default strategy. - # The default strategy is to do nothing (leave the foreign keys with the parent ids set), except for - # #has_many :through, where the default strategy is delete_all (delete - # the join records, without running their callbacks). - # - # There is also a clear method which is the same as delete_all, except that - # it returns the association rather than the records which have been deleted. - # - # === What gets deleted? - # - # There is a potential pitfall here: #has_and_belongs_to_many and #has_many :through - # associations have records in join tables, as well as the associated records. So when we - # call one of these deletion methods, what exactly should be deleted? - # - # The answer is that it is assumed that deletion on an association is about removing the - # link between the owner and the associated object(s), rather than necessarily the - # associated objects themselves. So with #has_and_belongs_to_many and #has_many - # :through, the join records will be deleted, but the associated records won't. - # - # This makes sense if you think about it: if you were to call post.tags.delete(Tag.find_by(name: 'food')) - # you would want the 'food' tag to be unlinked from the post, rather than for the tag itself - # to be removed from the database. - # - # However, there are examples where this strategy doesn't make sense. For example, suppose - # a person has many projects, and each project has many tasks. If we deleted one of a person's - # tasks, we would probably not want the project to be deleted. In this scenario, the delete method - # won't actually work: it can only be used if the association on the join model is a - # #belongs_to. In other situations you are expected to perform operations directly on - # either the associated records or the :through association. - # - # With a regular #has_many there is no distinction between the "associated records" - # and the "link", so there is only one choice for what gets deleted. - # - # With #has_and_belongs_to_many and #has_many :through, if you want to delete the - # associated records themselves, you can always do something along the lines of - # person.tasks.each(&:destroy). - # - # == Type safety with ActiveRecord::AssociationTypeMismatch - # - # If you attempt to assign an object to an association that doesn't match the inferred - # or specified :class_name, you'll get an ActiveRecord::AssociationTypeMismatch. - # - # == Options - # - # All of the association macros can be specialized through options. This makes cases - # more complex than the simple and guessable ones possible. - module ClassMethods - # Specifies a one-to-many association. The following methods for retrieval and query of - # collections of associated objects will be added: - # - # +collection+ is a placeholder for the symbol passed as the +name+ argument, so - # has_many :clients would add among others clients.empty?. - # - # [collection(force_reload = false)] - # Returns a Relation of all the associated objects. - # An empty Relation is returned if none are found. - # [collection<<(object, ...)] - # Adds one or more objects to the collection by setting their foreign keys to the collection's primary key. - # Note that this operation instantly fires update SQL without waiting for the save or update call on the - # parent object, unless the parent object is a new record. - # This will also run validations and callbacks of associated object(s). - # [collection.delete(object, ...)] - # Removes one or more objects from the collection by setting their foreign keys to +NULL+. - # Objects will be in addition destroyed if they're associated with dependent: :destroy, - # and deleted if they're associated with dependent: :delete_all. - # - # If the :through option is used, then the join records are deleted (rather than - # nullified) by default, but you can specify dependent: :destroy or - # dependent: :nullify to override this. - # [collection.destroy(object, ...)] - # Removes one or more objects from the collection by running destroy on - # each record, regardless of any dependent option, ensuring callbacks are run. - # - # If the :through option is used, then the join records are destroyed - # instead, not the objects themselves. - # [collection=objects] - # Replaces the collections content by deleting and adding objects as appropriate. If the :through - # option is true callbacks in the join models are triggered except destroy callbacks, since deletion is - # direct by default. You can specify dependent: :destroy or - # dependent: :nullify to override this. - # [collection_singular_ids] - # Returns an array of the associated objects' ids - # [collection_singular_ids=ids] - # Replace the collection with the objects identified by the primary keys in +ids+. This - # method loads the models and calls collection=. See above. - # [collection.clear] - # Removes every object from the collection. This destroys the associated objects if they - # are associated with dependent: :destroy, deletes them directly from the - # database if dependent: :delete_all, otherwise sets their foreign keys to +NULL+. - # If the :through option is true no destroy callbacks are invoked on the join models. - # Join models are directly deleted. - # [collection.empty?] - # Returns +true+ if there are no associated objects. - # [collection.size] - # Returns the number of associated objects. - # [collection.find(...)] - # Finds an associated object according to the same rules as ActiveRecord::FinderMethods#find. - # [collection.exists?(...)] - # Checks whether an associated object with the given conditions exists. - # Uses the same rules as ActiveRecord::FinderMethods#exists?. - # [collection.build(attributes = {}, ...)] - # Returns one or more new objects of the collection type that have been instantiated - # with +attributes+ and linked to this object through a foreign key, but have not yet - # been saved. - # [collection.create(attributes = {})] - # Returns a new object of the collection type that has been instantiated - # with +attributes+, linked to this object through a foreign key, and that has already - # been saved (if it passed the validation). *Note*: This only works if the base model - # already exists in the DB, not if it is a new (unsaved) record! - # [collection.create!(attributes = {})] - # Does the same as collection.create, but raises ActiveRecord::RecordInvalid - # if the record is invalid. - # [collection.reload] - # Returns a Relation of all of the associated objects, forcing a database read. - # An empty Relation is returned if none are found. - # - # === Example - # - # A Firm class declares has_many :clients, which will add: - # * Firm#clients (similar to Client.where(firm_id: id)) - # * Firm#clients<< - # * Firm#clients.delete - # * Firm#clients.destroy - # * Firm#clients= - # * Firm#client_ids - # * Firm#client_ids= - # * Firm#clients.clear - # * Firm#clients.empty? (similar to firm.clients.size == 0) - # * Firm#clients.size (similar to Client.count "firm_id = #{id}") - # * Firm#clients.find (similar to Client.where(firm_id: id).find(id)) - # * Firm#clients.exists?(name: 'ACME') (similar to Client.exists?(name: 'ACME', firm_id: firm.id)) - # * Firm#clients.build (similar to Client.new("firm_id" => id)) - # * Firm#clients.create (similar to c = Client.new("firm_id" => id); c.save; c) - # * Firm#clients.create! (similar to c = Client.new("firm_id" => id); c.save!) - # * Firm#clients.reload - # The declaration can also include an +options+ hash to specialize the behavior of the association. - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific set of records or customize the generated - # query when you access the associated collection. - # - # Scope examples: - # has_many :comments, -> { where(author_id: 1) } - # has_many :employees, -> { joins(:address) } - # has_many :posts, ->(blog) { where("max_post_length > ?", blog.max_post_length) } - # - # === Extensions - # - # The +extension+ argument allows you to pass a block into a has_many - # association. This is useful for adding new finders, creators and other - # factory-type methods to be used as part of the association. - # - # Extension examples: - # has_many :employees do - # def find_or_create_by_name(name) - # first_name, last_name = name.split(" ", 2) - # find_or_create_by(first_name: first_name, last_name: last_name) - # end - # end - # - # === Options - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So has_many :products will by default be linked - # to the +Product+ class, but if the real class name is +SpecialProduct+, you'll have to - # specify it with this option. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_many - # association will use "person_id" as the default :foreign_key. - # [:foreign_type] - # Specify the column used to store the associated object's type, if this is a polymorphic - # association. By default this is guessed to be the name of the polymorphic association - # specified on "as" option with a "_type" suffix. So a class that defines a - # has_many :tags, as: :taggable association will use "taggable_type" as the - # default :foreign_type. - # [:primary_key] - # Specify the name of the column to use as the primary key for the association. By default this is +id+. - # [:dependent] - # Controls what happens to the associated objects when - # their owner is destroyed. Note that these are implemented as - # callbacks, and Rails executes callbacks in order. Therefore, other - # similar callbacks may affect the :dependent behavior, and the - # :dependent behavior may affect other callbacks. - # - # * :destroy causes all the associated objects to also be destroyed. - # * :delete_all causes all the associated objects to be deleted directly from the database (so callbacks will not be executed). - # * :nullify causes the foreign keys to be set to +NULL+. Callbacks are not executed. - # * :restrict_with_exception causes an exception to be raised if there are any associated records. - # * :restrict_with_error causes an error to be added to the owner if there are any associated objects. - # - # If using with the :through option, the association on the join model must be - # a #belongs_to, and the records which get deleted are the join records, rather than - # the associated records. - # - # If using dependent: :destroy on a scoped association, only the scoped objects are destroyed. - # For example, if a Post model defines - # has_many :comments, -> { where published: true }, dependent: :destroy and destroy is - # called on a post, only published comments are destroyed. This means that any unpublished comments in the - # database would still contain a foreign key pointing to the now deleted post. - # [:counter_cache] - # This option can be used to configure a custom named :counter_cache. You only need this option, - # when you customized the name of your :counter_cache on the #belongs_to association. - # [:as] - # Specifies a polymorphic interface (See #belongs_to). - # [:through] - # Specifies an association through which to perform the query. This can be any other type - # of association, including other :through associations. Options for :class_name, - # :primary_key and :foreign_key are ignored, as the association uses the - # source reflection. - # - # If the association on the join model is a #belongs_to, the collection can be modified - # and the records on the :through model will be automatically created and removed - # as appropriate. Otherwise, the collection is read-only, so you should manipulate the - # :through association directly. - # - # If you are going to modify the association (rather than just read from it), then it is - # a good idea to set the :inverse_of option on the source association on the - # join model. This allows associated records to be built which will automatically create - # the appropriate join model records when they are saved. (See the 'Association Join Models' - # section above.) - # [:source] - # Specifies the source association name used by #has_many :through queries. - # Only use it if the name cannot be inferred from the association. - # has_many :subscribers, through: :subscriptions will look for either :subscribers or - # :subscriber on Subscription, unless a :source is given. - # [:source_type] - # Specifies type of the source association used by #has_many :through queries where the source - # association is a polymorphic #belongs_to. - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated objects or destroy them if marked for destruction, - # when saving the parent object. If false, never save or destroy the associated objects. - # By default, only save associated objects that are new records. This option is implemented as a - # +before_save+ callback. Because callbacks are run in the order they are defined, associated objects - # may need to be explicitly saved in any user-defined +before_save+ callbacks. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets - # :autosave to true. - # [:inverse_of] - # Specifies the name of the #belongs_to association on the associated object - # that is the inverse of this #has_many association. Does not work in combination - # with :through or :as options. - # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. - # [:extend] - # Specifies a module or array of modules that will be extended into the association object returned. - # Useful for defining methods on associations, especially when they should be shared between multiple - # association objects. - # - # Option examples: - # has_many :comments, -> { order("posted_on") } - # has_many :comments, -> { includes(:author) } - # has_many :people, -> { where(deleted: false).order("name") }, class_name: "Person" - # has_many :tracks, -> { order("position") }, dependent: :destroy - # has_many :comments, dependent: :nullify - # has_many :tags, as: :taggable - # has_many :reports, -> { readonly } - # has_many :subscribers, through: :subscriptions, source: :user - def has_many(name, scope = nil, options = {}, &extension) - reflection = Builder::HasMany.build(self, name, scope, options, &extension) - Reflection.add_reflection self, name, reflection - end - - # Specifies a one-to-one association with another class. This method should only be used - # if the other class contains the foreign key. If the current class contains the foreign key, - # then you should use #belongs_to instead. See also ActiveRecord::Associations::ClassMethods's overview - # on when to use #has_one and when to use #belongs_to. - # - # The following methods for retrieval and query of a single associated object will be added: - # - # +association+ is a placeholder for the symbol passed as the +name+ argument, so - # has_one :manager would add among others manager.nil?. - # - # [association] - # Returns the associated object. +nil+ is returned if none is found. - # [association=(associate)] - # Assigns the associate object, extracts the primary key, sets it as the foreign key, - # and saves the associate object. To avoid database inconsistencies, permanently deletes an existing - # associated object when assigning a new one, even if the new one isn't saved to database. - # [build_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+ and linked to this object through a foreign key, but has not - # yet been saved. - # [create_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+, linked to this object through a foreign key, and that - # has already been saved (if it passed the validation). - # [create_association!(attributes = {})] - # Does the same as create_association, but raises ActiveRecord::RecordInvalid - # if the record is invalid. - # [reload_association] - # Returns the associated object, forcing a database read. - # - # === Example - # - # An Account class declares has_one :beneficiary, which will add: - # * Account#beneficiary (similar to Beneficiary.where(account_id: id).first) - # * Account#beneficiary=(beneficiary) (similar to beneficiary.account_id = account.id; beneficiary.save) - # * Account#build_beneficiary (similar to Beneficiary.new("account_id" => id)) - # * Account#create_beneficiary (similar to b = Beneficiary.new("account_id" => id); b.save; b) - # * Account#create_beneficiary! (similar to b = Beneficiary.new("account_id" => id); b.save!; b) - # * Account#reload_beneficiary - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific record or customize the generated query - # when you access the associated object. - # - # Scope examples: - # has_one :author, -> { where(comment_id: 1) } - # has_one :employer, -> { joins(:company) } - # has_one :latest_post, ->(blog) { where("created_at > ?", blog.enabled_at) } - # - # === Options - # - # The declaration can also include an +options+ hash to specialize the behavior of the association. - # - # Options are: - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So has_one :manager will by default be linked to the Manager class, but - # if the real class name is Person, you'll have to specify it with this option. - # [:dependent] - # Controls what happens to the associated object when - # its owner is destroyed: - # - # * :destroy causes the associated object to also be destroyed - # * :delete causes the associated object to be deleted directly from the database (so callbacks will not execute) - # * :nullify causes the foreign key to be set to +NULL+. Callbacks are not executed. - # * :restrict_with_exception causes an exception to be raised if there is an associated record - # * :restrict_with_error causes an error to be added to the owner if there is an associated object - # - # Note that :dependent option is ignored when using :through option. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of this class in lower-case and "_id" suffixed. So a Person class that makes a #has_one association - # will use "person_id" as the default :foreign_key. - # [:foreign_type] - # Specify the column used to store the associated object's type, if this is a polymorphic - # association. By default this is guessed to be the name of the polymorphic association - # specified on "as" option with a "_type" suffix. So a class that defines a - # has_one :tag, as: :taggable association will use "taggable_type" as the - # default :foreign_type. - # [:primary_key] - # Specify the method that returns the primary key used for the association. By default this is +id+. - # [:as] - # Specifies a polymorphic interface (See #belongs_to). - # [:through] - # Specifies a Join Model through which to perform the query. Options for :class_name, - # :primary_key, and :foreign_key are ignored, as the association uses the - # source reflection. You can only use a :through query through a #has_one - # or #belongs_to association on the join model. - # [:source] - # Specifies the source association name used by #has_one :through queries. - # Only use it if the name cannot be inferred from the association. - # has_one :favorite, through: :favorites will look for a - # :favorite on Favorite, unless a :source is given. - # [:source_type] - # Specifies type of the source association used by #has_one :through queries where the source - # association is a polymorphic #belongs_to. - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated object or destroy it if marked for destruction, - # when saving the parent object. If false, never save or destroy the associated object. - # By default, only save the associated object if it's a new record. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets - # :autosave to true. - # [:inverse_of] - # Specifies the name of the #belongs_to association on the associated object - # that is the inverse of this #has_one association. Does not work in combination - # with :through or :as options. - # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. - # [:required] - # When set to +true+, the association will also have its presence validated. - # This will validate the association itself, not the id. You can use - # +:inverse_of+ to avoid an extra query during validation. - # - # Option examples: - # has_one :credit_card, dependent: :destroy # destroys the associated credit card - # has_one :credit_card, dependent: :nullify # updates the associated records foreign - # # key value to NULL rather than destroying it - # has_one :last_comment, -> { order('posted_on') }, class_name: "Comment" - # has_one :project_manager, -> { where(role: 'project_manager') }, class_name: "Person" - # has_one :attachment, as: :attachable - # has_one :boss, -> { readonly } - # has_one :club, through: :membership - # has_one :primary_address, -> { where(primary: true) }, through: :addressables, source: :addressable - # has_one :credit_card, required: true - def has_one(name, scope = nil, options = {}) - reflection = Builder::HasOne.build(self, name, scope, options) - Reflection.add_reflection self, name, reflection - end - - # Specifies a one-to-one association with another class. This method should only be used - # if this class contains the foreign key. If the other class contains the foreign key, - # then you should use #has_one instead. See also ActiveRecord::Associations::ClassMethods's overview - # on when to use #has_one and when to use #belongs_to. - # - # Methods will be added for retrieval and query for a single associated object, for which - # this object holds an id: - # - # +association+ is a placeholder for the symbol passed as the +name+ argument, so - # belongs_to :author would add among others author.nil?. - # - # [association] - # Returns the associated object. +nil+ is returned if none is found. - # [association=(associate)] - # Assigns the associate object, extracts the primary key, and sets it as the foreign key. - # [build_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+ and linked to this object through a foreign key, but has not yet been saved. - # [create_association(attributes = {})] - # Returns a new object of the associated type that has been instantiated - # with +attributes+, linked to this object through a foreign key, and that - # has already been saved (if it passed the validation). - # [create_association!(attributes = {})] - # Does the same as create_association, but raises ActiveRecord::RecordInvalid - # if the record is invalid. - # [reload_association] - # Returns the associated object, forcing a database read. - # - # === Example - # - # A Post class declares belongs_to :author, which will add: - # * Post#author (similar to Author.find(author_id)) - # * Post#author=(author) (similar to post.author_id = author.id) - # * Post#build_author (similar to post.author = Author.new) - # * Post#create_author (similar to post.author = Author.new; post.author.save; post.author) - # * Post#create_author! (similar to post.author = Author.new; post.author.save!; post.author) - # * Post#reload_author - # The declaration can also include an +options+ hash to specialize the behavior of the association. - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific record or customize the generated query - # when you access the associated object. - # - # Scope examples: - # belongs_to :firm, -> { where(id: 2) } - # belongs_to :user, -> { joins(:friends) } - # belongs_to :level, ->(game) { where("game_level > ?", game.current_level) } - # - # === Options - # - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So belongs_to :author will by default be linked to the Author class, but - # if the real class name is Person, you'll have to specify it with this option. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of the association with an "_id" suffix. So a class that defines a belongs_to :person - # association will use "person_id" as the default :foreign_key. Similarly, - # belongs_to :favorite_person, class_name: "Person" will use a foreign key - # of "favorite_person_id". - # [:foreign_type] - # Specify the column used to store the associated object's type, if this is a polymorphic - # association. By default this is guessed to be the name of the association with a "_type" - # suffix. So a class that defines a belongs_to :taggable, polymorphic: true - # association will use "taggable_type" as the default :foreign_type. - # [:primary_key] - # Specify the method that returns the primary key of associated object used for the association. - # By default this is id. - # [:dependent] - # If set to :destroy, the associated object is destroyed when this object is. If set to - # :delete, the associated object is deleted *without* calling its destroy method. - # This option should not be specified when #belongs_to is used in conjunction with - # a #has_many relationship on another class because of the potential to leave - # orphaned records behind. - # [:counter_cache] - # Caches the number of belonging objects on the associate class through the use of CounterCache::ClassMethods#increment_counter - # and CounterCache::ClassMethods#decrement_counter. The counter cache is incremented when an object of this - # class is created and decremented when it's destroyed. This requires that a column - # named #{table_name}_count (such as +comments_count+ for a belonging Comment class) - # is used on the associate class (such as a Post class) - that is the migration for - # #{table_name}_count is created on the associate class (such that Post.comments_count will - # return the count cached, see note below). You can also specify a custom counter - # cache column by providing a column name instead of a +true+/+false+ value to this - # option (e.g., counter_cache: :my_custom_counter.) - # Note: Specifying a counter cache will add it to that model's list of readonly attributes - # using +attr_readonly+. - # [:polymorphic] - # Specify this association is a polymorphic association by passing +true+. - # Note: If you've enabled the counter cache, then you may want to add the counter cache attribute - # to the +attr_readonly+ list in the associated classes (e.g. class Post; attr_readonly :comments_count; end). - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +false+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated object or destroy it if marked for destruction, when - # saving the parent object. - # If false, never save or destroy the associated object. - # By default, only save the associated object if it's a new record. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for - # sets :autosave to true. - # [:touch] - # If true, the associated object will be touched (the updated_at/on attributes set to current time) - # when this record is either saved or destroyed. If you specify a symbol, that attribute - # will be updated with the current time in addition to the updated_at/on attribute. - # Please note that with touching no validation is performed and only the +after_touch+, - # +after_commit+ and +after_rollback+ callbacks are executed. - # [:inverse_of] - # Specifies the name of the #has_one or #has_many association on the associated - # object that is the inverse of this #belongs_to association. Does not work in - # combination with the :polymorphic options. - # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail. - # [:optional] - # When set to +true+, the association will not have its presence validated. - # [:required] - # When set to +true+, the association will also have its presence validated. - # This will validate the association itself, not the id. You can use - # +:inverse_of+ to avoid an extra query during validation. - # NOTE: required is set to true by default and is deprecated. If - # you don't want to have association presence validated, use optional: true. - # [:default] - # Provide a callable (i.e. proc or lambda) to specify that the association should - # be initialized with a particular record before validation. - # - # Option examples: - # belongs_to :firm, foreign_key: "client_of" - # belongs_to :person, primary_key: "name", foreign_key: "person_name" - # belongs_to :author, class_name: "Person", foreign_key: "author_id" - # belongs_to :valid_coupon, ->(o) { where "discounts > ?", o.payments_count }, - # class_name: "Coupon", foreign_key: "coupon_id" - # belongs_to :attachable, polymorphic: true - # belongs_to :project, -> { readonly } - # belongs_to :post, counter_cache: true - # belongs_to :comment, touch: true - # belongs_to :company, touch: :employees_last_updated_at - # belongs_to :user, optional: true - # belongs_to :account, default: -> { company.account } - def belongs_to(name, scope = nil, options = {}) - reflection = Builder::BelongsTo.build(self, name, scope, options) - Reflection.add_reflection self, name, reflection - end - - # Specifies a many-to-many relationship with another class. This associates two classes via an - # intermediate join table. Unless the join table is explicitly specified as an option, it is - # guessed using the lexical order of the class names. So a join between Developer and Project - # will give the default join table name of "developers_projects" because "D" precedes "P" alphabetically. - # Note that this precedence is calculated using the < operator for String. This - # means that if the strings are of different lengths, and the strings are equal when compared - # up to the shortest length, then the longer string is considered of higher - # lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" - # to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", - # but it in fact generates a join table name of "paper_boxes_papers". Be aware of this caveat, and use the - # custom :join_table option if you need to. - # If your tables share a common prefix, it will only appear once at the beginning. For example, - # the tables "catalog_categories" and "catalog_products" generate a join table name of "catalog_categories_products". - # - # The join table should not have a primary key or a model associated with it. You must manually generate the - # join table with a migration such as this: - # - # class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration[5.0] - # def change - # create_join_table :developers, :projects - # end - # end - # - # It's also a good idea to add indexes to each of those columns to speed up the joins process. - # However, in MySQL it is advised to add a compound index for both of the columns as MySQL only - # uses one index per table during the lookup. - # - # Adds the following methods for retrieval and query: - # - # +collection+ is a placeholder for the symbol passed as the +name+ argument, so - # has_and_belongs_to_many :categories would add among others categories.empty?. - # - # [collection] - # Returns a Relation of all the associated objects. - # An empty Relation is returned if none are found. - # [collection<<(object, ...)] - # Adds one or more objects to the collection by creating associations in the join table - # (collection.push and collection.concat are aliases to this method). - # Note that this operation instantly fires update SQL without waiting for the save or update call on the - # parent object, unless the parent object is a new record. - # [collection.delete(object, ...)] - # Removes one or more objects from the collection by removing their associations from the join table. - # This does not destroy the objects. - # [collection.destroy(object, ...)] - # Removes one or more objects from the collection by running destroy on each association in the join table, overriding any dependent option. - # This does not destroy the objects. - # [collection=objects] - # Replaces the collection's content by deleting and adding objects as appropriate. - # [collection_singular_ids] - # Returns an array of the associated objects' ids. - # [collection_singular_ids=ids] - # Replace the collection by the objects identified by the primary keys in +ids+. - # [collection.clear] - # Removes every object from the collection. This does not destroy the objects. - # [collection.empty?] - # Returns +true+ if there are no associated objects. - # [collection.size] - # Returns the number of associated objects. - # [collection.find(id)] - # Finds an associated object responding to the +id+ and that - # meets the condition that it has to be associated with this object. - # Uses the same rules as ActiveRecord::FinderMethods#find. - # [collection.exists?(...)] - # Checks whether an associated object with the given conditions exists. - # Uses the same rules as ActiveRecord::FinderMethods#exists?. - # [collection.build(attributes = {})] - # Returns a new object of the collection type that has been instantiated - # with +attributes+ and linked to this object through the join table, but has not yet been saved. - # [collection.create(attributes = {})] - # Returns a new object of the collection type that has been instantiated - # with +attributes+, linked to this object through the join table, and that has already been - # saved (if it passed the validation). - # [collection.reload] - # Returns a Relation of all of the associated objects, forcing a database read. - # An empty Relation is returned if none are found. - # - # === Example - # - # A Developer class declares has_and_belongs_to_many :projects, which will add: - # * Developer#projects - # * Developer#projects<< - # * Developer#projects.delete - # * Developer#projects.destroy - # * Developer#projects= - # * Developer#project_ids - # * Developer#project_ids= - # * Developer#projects.clear - # * Developer#projects.empty? - # * Developer#projects.size - # * Developer#projects.find(id) - # * Developer#projects.exists?(...) - # * Developer#projects.build (similar to Project.new("developer_id" => id)) - # * Developer#projects.create (similar to c = Project.new("developer_id" => id); c.save; c) - # * Developer#projects.reload - # The declaration may include an +options+ hash to specialize the behavior of the association. - # - # === Scopes - # - # You can pass a second argument +scope+ as a callable (i.e. proc or - # lambda) to retrieve a specific set of records or customize the generated - # query when you access the associated collection. - # - # Scope examples: - # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } - # has_and_belongs_to_many :categories, ->(post) { - # where("default_category = ?", post.default_category) - # - # === Extensions - # - # The +extension+ argument allows you to pass a block into a - # has_and_belongs_to_many association. This is useful for adding new - # finders, creators and other factory-type methods to be used as part of - # the association. - # - # Extension examples: - # has_and_belongs_to_many :contractors do - # def find_or_create_by_name(name) - # first_name, last_name = name.split(" ", 2) - # find_or_create_by(first_name: first_name, last_name: last_name) - # end - # end - # - # === Options - # - # [:class_name] - # Specify the class name of the association. Use it only if that name can't be inferred - # from the association name. So has_and_belongs_to_many :projects will by default be linked to the - # Project class, but if the real class name is SuperProject, you'll have to specify it with this option. - # [:join_table] - # Specify the name of the join table if the default based on lexical order isn't what you want. - # WARNING: If you're overwriting the table name of either class, the +table_name+ method - # MUST be declared underneath any #has_and_belongs_to_many declaration in order to work. - # [:foreign_key] - # Specify the foreign key used for the association. By default this is guessed to be the name - # of this class in lower-case and "_id" suffixed. So a Person class that makes - # a #has_and_belongs_to_many association to Project will use "person_id" as the - # default :foreign_key. - # [:association_foreign_key] - # Specify the foreign key used for the association on the receiving side of the association. - # By default this is guessed to be the name of the associated class in lower-case and "_id" suffixed. - # So if a Person class makes a #has_and_belongs_to_many association to Project, - # the association will use "project_id" as the default :association_foreign_key. - # [:validate] - # When set to +true+, validates new objects added to association when saving the parent object. +true+ by default. - # If you want to ensure associated objects are revalidated on every update, use +validates_associated+. - # [:autosave] - # If true, always save the associated objects or destroy them if marked for destruction, when - # saving the parent object. - # If false, never save or destroy the associated objects. - # By default, only save associated objects that are new records. - # - # Note that NestedAttributes::ClassMethods#accepts_nested_attributes_for sets - # :autosave to true. - # - # Option examples: - # has_and_belongs_to_many :projects - # has_and_belongs_to_many :projects, -> { includes(:milestones, :manager) } - # has_and_belongs_to_many :nations, class_name: "Country" - # has_and_belongs_to_many :categories, join_table: "prods_cats" - # has_and_belongs_to_many :categories, -> { readonly } - def has_and_belongs_to_many(name, scope = nil, **options, &extension) - habtm_reflection = ActiveRecord::Reflection::HasAndBelongsToManyReflection.new(name, scope, options, self) - - builder = Builder::HasAndBelongsToMany.new name, self, options - - join_model = ActiveSupport::Deprecation.silence { builder.through_model } - - const_set join_model.name, join_model - private_constant join_model.name - - middle_reflection = builder.middle_reflection join_model - - Builder::HasMany.define_callbacks self, middle_reflection - Reflection.add_reflection self, middle_reflection.name, middle_reflection - middle_reflection.parent_reflection = habtm_reflection - - include Module.new { - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def destroy_associations - association(:#{middle_reflection.name}).delete_all(:delete_all) - association(:#{name}).reset - super - end - RUBY - } - - hm_options = {} - hm_options[:through] = middle_reflection.name - hm_options[:source] = join_model.right_reflection.name - - [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name, :extend].each do |k| - hm_options[k] = options[k] if options.key? k - end - - ActiveSupport::Deprecation.silence { has_many name, scope, hm_options, &extension } - _reflections[name.to_s].parent_reflection = habtm_reflection - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/alias_tracker.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/alias_tracker.rb deleted file mode 100644 index be92712c43..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/alias_tracker.rb +++ /dev/null @@ -1,89 +0,0 @@ -require "active_support/core_ext/string/conversions" - -module ActiveRecord - module Associations - # Keeps track of table aliases for ActiveRecord::Associations::JoinDependency - class AliasTracker # :nodoc: - attr_reader :aliases - - def self.create(connection, initial_table) - aliases = Hash.new(0) - aliases[initial_table] = 1 - new(connection, aliases) - end - - def self.create_with_joins(connection, initial_table, joins) - if joins.empty? - create(connection, initial_table) - else - aliases = Hash.new { |h, k| - h[k] = initial_count_for(connection, k, joins) - } - aliases[initial_table] = 1 - new(connection, aliases) - end - end - - def self.initial_count_for(connection, name, table_joins) - # quoted_name should be downcased as some database adapters (Oracle) return quoted name in uppercase - quoted_name = connection.quote_table_name(name).downcase - - counts = table_joins.map do |join| - if join.is_a?(Arel::Nodes::StringJoin) - # Table names + table aliases - join.left.downcase.scan( - /join(?:\s+\w+)?\s+(\S+\s+)?#{quoted_name}\son/ - ).size - elsif join.respond_to? :left - join.left.table_name == name ? 1 : 0 - else - # this branch is reached by two tests: - # - # activerecord/test/cases/associations/cascaded_eager_loading_test.rb:37 - # with :posts - # - # activerecord/test/cases/associations/eager_test.rb:1133 - # with :comments - # - 0 - end - end - - counts.sum - end - - # table_joins is an array of arel joins which might conflict with the aliases we assign here - def initialize(connection, aliases) - @aliases = aliases - @connection = connection - end - - def aliased_table_for(table_name, aliased_name, type_caster) - if aliases[table_name].zero? - # If it's zero, we can have our table_name - aliases[table_name] = 1 - Arel::Table.new(table_name, type_caster: type_caster) - else - # Otherwise, we need to use an alias - aliased_name = @connection.table_alias_for(aliased_name) - - # Update the count - aliases[aliased_name] += 1 - - table_alias = if aliases[aliased_name] > 1 - "#{truncate(aliased_name)}_#{aliases[aliased_name]}" - else - aliased_name - end - Arel::Table.new(table_name, type_caster: type_caster).alias(table_alias) - end - end - - private - - def truncate(name) - name.slice(0, @connection.table_alias_length - 2) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/association.rb deleted file mode 100644 index 0f330af2f6..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/association.rb +++ /dev/null @@ -1,295 +0,0 @@ -require "active_support/core_ext/array/wrap" - -module ActiveRecord - module Associations - # = Active Record Associations - # - # This is the root class of all associations ('+ Foo' signifies an included module Foo): - # - # Association - # SingularAssociation - # HasOneAssociation + ForeignAssociation - # HasOneThroughAssociation + ThroughAssociation - # BelongsToAssociation - # BelongsToPolymorphicAssociation - # CollectionAssociation - # HasManyAssociation + ForeignAssociation - # HasManyThroughAssociation + ThroughAssociation - class Association #:nodoc: - attr_reader :owner, :target, :reflection - attr_accessor :inversed - - delegate :options, to: :reflection - - def initialize(owner, reflection) - reflection.check_validity! - - @owner, @reflection = owner, reflection - - reset - reset_scope - end - - # Returns the name of the table of the associated class: - # - # post.comments.aliased_table_name # => "comments" - # - def aliased_table_name - klass.table_name - end - - # Resets the \loaded flag to +false+ and sets the \target to +nil+. - def reset - @loaded = false - @target = nil - @stale_state = nil - @inversed = false - end - - # Reloads the \target and returns +self+ on success. - def reload - reset - reset_scope - load_target - self unless target.nil? - end - - # Has the \target been already \loaded? - def loaded? - @loaded - end - - # Asserts the \target has been loaded setting the \loaded flag to +true+. - def loaded! - @loaded = true - @stale_state = stale_state - @inversed = false - end - - # The target is stale if the target no longer points to the record(s) that the - # relevant foreign_key(s) refers to. If stale, the association accessor method - # on the owner will reload the target. It's up to subclasses to implement the - # stale_state method if relevant. - # - # Note that if the target has not been loaded, it is not considered stale. - def stale_target? - !inversed && loaded? && @stale_state != stale_state - end - - # Sets the target of this association to \target, and the \loaded flag to +true+. - def target=(target) - @target = target - loaded! - end - - def scope - target_scope.merge!(association_scope) - end - - # The scope for this association. - # - # Note that the association_scope is merged into the target_scope only when the - # scope method is called. This is because at that point the call may be surrounded - # by scope.scoping { ... } or with_scope { ... } etc, which affects the scope which - # actually gets built. - def association_scope - if klass - @association_scope ||= AssociationScope.scope(self, klass.connection) - end - end - - def reset_scope - @association_scope = nil - end - - # Set the inverse association, if possible - def set_inverse_instance(record) - if invertible_for?(record) - inverse = record.association(inverse_reflection_for(record).name) - inverse.target = owner - inverse.inversed = true - end - record - end - - # Remove the inverse association, if possible - def remove_inverse_instance(record) - if invertible_for?(record) - inverse = record.association(inverse_reflection_for(record).name) - inverse.target = nil - inverse.inversed = false - end - end - - # Returns the class of the target. belongs_to polymorphic overrides this to look at the - # polymorphic_type field on the owner. - def klass - reflection.klass - end - - # Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the - # through association's scope) - def target_scope - AssociationRelation.create(klass, klass.arel_table, klass.predicate_builder, self).merge!(klass.all) - end - - def extensions - extensions = klass.default_extensions | reflection.extensions - - if scope = reflection.scope - extensions |= klass.unscoped.instance_exec(owner, &scope).extensions - end - - extensions - end - - # Loads the \target if needed and returns it. - # - # This method is abstract in the sense that it relies on +find_target+, - # which is expected to be provided by descendants. - # - # If the \target is already \loaded it is just returned. Thus, you can call - # +load_target+ unconditionally to get the \target. - # - # ActiveRecord::RecordNotFound is rescued within the method, and it is - # not reraised. The proxy is \reset and +nil+ is the return value. - def load_target - @target = find_target if (@stale_state && stale_target?) || find_target? - - loaded! unless loaded? - target - rescue ActiveRecord::RecordNotFound - reset - end - - def interpolate(sql, record = nil) - if sql.respond_to?(:to_proc) - owner.instance_exec(record, &sql) - else - sql - end - end - - # We can't dump @reflection since it contains the scope proc - def marshal_dump - ivars = (instance_variables - [:@reflection]).map { |name| [name, instance_variable_get(name)] } - [@reflection.name, ivars] - end - - def marshal_load(data) - reflection_name, ivars = data - ivars.each { |name, val| instance_variable_set(name, val) } - @reflection = @owner.class._reflect_on_association(reflection_name) - end - - def initialize_attributes(record, except_from_scope_attributes = nil) #:nodoc: - except_from_scope_attributes ||= {} - skip_assign = [reflection.foreign_key, reflection.type].compact - assigned_keys = record.changed_attribute_names_to_save - assigned_keys += except_from_scope_attributes.keys.map(&:to_s) - attributes = create_scope.except(*(assigned_keys - skip_assign)) - record.assign_attributes(attributes) - set_inverse_instance(record) - end - - def create(attributes = {}, &block) - _create_record(attributes, &block) - end - - def create!(attributes = {}, &block) - _create_record(attributes, true, &block) - end - - private - - def find_target? - !loaded? && (!owner.new_record? || foreign_key_present?) && klass - end - - def creation_attributes - attributes = {} - - if (reflection.has_one? || reflection.collection?) && !options[:through] - attributes[reflection.foreign_key] = owner[reflection.active_record_primary_key] - - if reflection.options[:as] - attributes[reflection.type] = owner.class.base_class.name - end - end - - attributes - end - - # Sets the owner attributes on the given record - def set_owner_attributes(record) - creation_attributes.each { |key, value| record[key] = value } - end - - # Returns true if there is a foreign key present on the owner which - # references the target. This is used to determine whether we can load - # the target if the owner is currently a new record (and therefore - # without a key). If the owner is a new record then foreign_key must - # be present in order to load target. - # - # Currently implemented by belongs_to (vanilla and polymorphic) and - # has_one/has_many :through associations which go through a belongs_to. - def foreign_key_present? - false - end - - # Raises ActiveRecord::AssociationTypeMismatch unless +record+ is of - # the kind of the class of the associated objects. Meant to be used as - # a sanity check when you are about to assign an associated record. - def raise_on_type_mismatch!(record) - unless record.is_a?(reflection.klass) - fresh_class = reflection.class_name.safe_constantize - unless fresh_class && record.is_a?(fresh_class) - message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, "\ - "got #{record.inspect} which is an instance of #{record.class}(##{record.class.object_id})" - raise ActiveRecord::AssociationTypeMismatch, message - end - end - end - - # Can be redefined by subclasses, notably polymorphic belongs_to - # The record parameter is necessary to support polymorphic inverses as we must check for - # the association in the specific class of the record. - def inverse_reflection_for(record) - reflection.inverse_of - end - - # Returns true if inverse association on the given record needs to be set. - # This method is redefined by subclasses. - def invertible_for?(record) - foreign_key_for?(record) && inverse_reflection_for(record) - end - - # Returns true if record contains the foreign_key - def foreign_key_for?(record) - record.has_attribute?(reflection.foreign_key) - end - - # This should be implemented to return the values of the relevant key(s) on the owner, - # so that when stale_state is different from the value stored on the last find_target, - # the target is stale. - # - # This is only relevant to certain associations, which is why it returns +nil+ by default. - def stale_state - end - - def build_record(attributes) - reflection.build_association(attributes) do |record| - initialize_attributes(record, attributes) - end - end - - # Returns true if statement cache should be skipped on the association reader. - def skip_statement_cache? - reflection.has_scope? || - scope.eager_loading? || - klass.scope_attributes? || - reflection.source_reflection.active_record.default_scopes.any? - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/association_scope.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/association_scope.rb deleted file mode 100644 index 9ca3a20fef..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/association_scope.rb +++ /dev/null @@ -1,180 +0,0 @@ -module ActiveRecord - module Associations - class AssociationScope #:nodoc: - def self.scope(association, connection) - INSTANCE.scope(association, connection) - end - - def self.create(&block) - block ||= lambda { |val| val } - new(block) - end - - def initialize(value_transformation) - @value_transformation = value_transformation - end - - INSTANCE = create - - def scope(association, connection) - klass = association.klass - reflection = association.reflection - scope = klass.unscoped - owner = association.owner - alias_tracker = AliasTracker.create connection, association.klass.table_name - chain_head, chain_tail = get_chain(reflection, association, alias_tracker) - - scope.extending! reflection.extensions - add_constraints(scope, owner, reflection, chain_head, chain_tail) - end - - def join_type - Arel::Nodes::InnerJoin - end - - def self.get_bind_values(owner, chain) - binds = [] - last_reflection = chain.last - - binds << last_reflection.join_id_for(owner) - if last_reflection.type - binds << owner.class.base_class.name - end - - chain.each_cons(2).each do |reflection, next_reflection| - if reflection.type - binds << next_reflection.klass.base_class.name - end - end - binds - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :value_transformation - - private - def join(table, constraint) - table.create_join(table, table.create_on(constraint), join_type) - end - - def last_chain_scope(scope, table, reflection, owner) - join_keys = reflection.join_keys - key = join_keys.key - foreign_key = join_keys.foreign_key - - value = transform_value(owner[foreign_key]) - scope = apply_scope(scope, table, key, value) - - if reflection.type - polymorphic_type = transform_value(owner.class.base_class.name) - scope = apply_scope(scope, table, reflection.type, polymorphic_type) - end - - scope - end - - def transform_value(value) - value_transformation.call(value) - end - - def next_chain_scope(scope, table, reflection, foreign_table, next_reflection) - join_keys = reflection.join_keys - key = join_keys.key - foreign_key = join_keys.foreign_key - - constraint = table[key].eq(foreign_table[foreign_key]) - - if reflection.type - value = transform_value(next_reflection.klass.base_class.name) - scope = apply_scope(scope, table, reflection.type, value) - end - - scope.joins!(join(foreign_table, constraint)) - end - - class ReflectionProxy < SimpleDelegator # :nodoc: - attr_accessor :next - attr_reader :alias_name - - def initialize(reflection, alias_name) - super(reflection) - @alias_name = alias_name - end - - def all_includes; nil; end - end - - def get_chain(reflection, association, tracker) - name = reflection.name - runtime_reflection = Reflection::RuntimeReflection.new(reflection, association) - previous_reflection = runtime_reflection - reflection.chain.drop(1).each do |refl| - alias_name = tracker.aliased_table_for( - refl.table_name, - refl.alias_candidate(name), - refl.klass.type_caster - ) - proxy = ReflectionProxy.new(refl, alias_name) - previous_reflection.next = proxy - previous_reflection = proxy - end - [runtime_reflection, previous_reflection] - end - - def add_constraints(scope, owner, refl, chain_head, chain_tail) - owner_reflection = chain_tail - table = owner_reflection.alias_name - scope = last_chain_scope(scope, table, owner_reflection, owner) - - reflection = chain_head - while reflection - table = reflection.alias_name - next_reflection = reflection.next - - unless reflection == chain_tail - foreign_table = next_reflection.alias_name - scope = next_chain_scope(scope, table, reflection, foreign_table, next_reflection) - end - - # Exclude the scope of the association itself, because that - # was already merged in the #scope method. - reflection.constraints.each do |scope_chain_item| - item = eval_scope(reflection.klass, table, scope_chain_item, owner) - - if scope_chain_item == refl.scope - scope.merge! item.except(:where, :includes) - end - - reflection.all_includes do - scope.includes! item.includes_values - end - - scope.unscope!(*item.unscope_values) - scope.where_clause += item.where_clause - scope.order_values |= item.order_values - end - - reflection = next_reflection - end - - scope - end - - def apply_scope(scope, table, key, value) - if scope.table == table - scope.where!(key => value) - else - scope.where!(table.name => { key => value }) - end - end - - def eval_scope(klass, table, scope, owner) - predicate_builder = PredicateBuilder.new(TableMetadata.new(klass, table)) - ActiveRecord::Relation.create(klass, table, predicate_builder).instance_exec(owner, &scope) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/belongs_to_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/belongs_to_association.rb deleted file mode 100644 index 9a32da6a18..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/belongs_to_association.rb +++ /dev/null @@ -1,111 +0,0 @@ -module ActiveRecord - # = Active Record Belongs To Association - module Associations - class BelongsToAssociation < SingularAssociation #:nodoc: - def handle_dependency - target.send(options[:dependent]) if load_target - end - - def replace(record) - if record - raise_on_type_mismatch!(record) - update_counters_on_replace(record) - replace_keys(record) - set_inverse_instance(record) - @updated = true - else - decrement_counters - remove_keys - end - - self.target = record - end - - def default(&block) - writer(owner.instance_exec(&block)) if reader.nil? - end - - def reset - super - @updated = false - end - - def updated? - @updated - end - - def decrement_counters # :nodoc: - update_counters(-1) - end - - def increment_counters # :nodoc: - update_counters(1) - end - - private - - def update_counters(by) - if require_counter_update? && foreign_key_present? - if target && !stale_target? - target.increment!(reflection.counter_cache_column, by, touch: reflection.options[:touch]) - else - klass.update_counters(target_id, reflection.counter_cache_column => by, touch: reflection.options[:touch]) - end - end - end - - def find_target? - !loaded? && foreign_key_present? && klass - end - - def require_counter_update? - reflection.counter_cache_column && owner.persisted? - end - - def update_counters_on_replace(record) - if require_counter_update? && different_target?(record) - owner.instance_variable_set :@_after_replace_counter_called, true - record.increment!(reflection.counter_cache_column, touch: reflection.options[:touch]) - decrement_counters - end - end - - # Checks whether record is different to the current target, without loading it - def different_target?(record) - record.id != owner._read_attribute(reflection.foreign_key) - end - - def replace_keys(record) - owner[reflection.foreign_key] = record._read_attribute(reflection.association_primary_key(record.class)) - end - - def remove_keys - owner[reflection.foreign_key] = nil - end - - def foreign_key_present? - owner._read_attribute(reflection.foreign_key) - end - - # NOTE - for now, we're only supporting inverse setting from belongs_to back onto - # has_one associations. - def invertible_for?(record) - inverse = inverse_reflection_for(record) - inverse && inverse.has_one? - end - - def target_id - if options[:primary_key] - owner.send(reflection.name).try(:id) - else - owner._read_attribute(reflection.foreign_key) - end - end - - def stale_state - result = owner._read_attribute(reflection.foreign_key) { |n| owner.send(:missing_attribute, n, caller) } - result && result.to_s - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/belongs_to_polymorphic_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/belongs_to_polymorphic_association.rb deleted file mode 100644 index b710cf6bdb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/belongs_to_polymorphic_association.rb +++ /dev/null @@ -1,40 +0,0 @@ -module ActiveRecord - # = Active Record Belongs To Polymorphic Association - module Associations - class BelongsToPolymorphicAssociation < BelongsToAssociation #:nodoc: - def klass - type = owner[reflection.foreign_type] - type.presence && type.constantize - end - - private - - def replace_keys(record) - super - owner[reflection.foreign_type] = record.class.base_class.name - end - - def remove_keys - super - owner[reflection.foreign_type] = nil - end - - def different_target?(record) - super || record.class != klass - end - - def inverse_reflection_for(record) - reflection.polymorphic_inverse_of(record.class) - end - - def raise_on_type_mismatch!(record) - # A polymorphic association cannot have a type mismatch, by definition - end - - def stale_state - foreign_key = super - foreign_key && [foreign_key.to_s, owner[reflection.foreign_type].to_s] - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/association.rb deleted file mode 100644 index d0534056d9..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/association.rb +++ /dev/null @@ -1,143 +0,0 @@ -# This is the parent Association class which defines the variables -# used by all associations. -# -# The hierarchy is defined as follows: -# Association -# - SingularAssociation -# - BelongsToAssociation -# - HasOneAssociation -# - CollectionAssociation -# - HasManyAssociation - -module ActiveRecord::Associations::Builder # :nodoc: - class Association #:nodoc: - class << self - attr_accessor :extensions - end - self.extensions = [] - - VALID_OPTIONS = [:class_name, :anonymous_class, :foreign_key, :validate] # :nodoc: - - def self.build(model, name, scope, options, &block) - if model.dangerous_attribute_method?(name) - raise ArgumentError, "You tried to define an association named #{name} on the model #{model.name}, but " \ - "this will conflict with a method #{name} already defined by Active Record. " \ - "Please choose a different association name." - end - - extension = define_extensions model, name, &block - reflection = create_reflection model, name, scope, options, extension - define_accessors model, reflection - define_callbacks model, reflection - define_validations model, reflection - reflection - end - - def self.create_reflection(model, name, scope, options, extension = nil) - raise ArgumentError, "association names must be a Symbol" unless name.kind_of?(Symbol) - - if scope.is_a?(Hash) - options = scope - scope = nil - end - - validate_options(options) - - scope = build_scope(scope, extension) - - ActiveRecord::Reflection.create(macro, name, scope, options, model) - end - - def self.build_scope(scope, extension) - new_scope = scope - - if scope && scope.arity == 0 - new_scope = proc { instance_exec(&scope) } - end - - if extension - new_scope = wrap_scope new_scope, extension - end - - new_scope - end - - def self.wrap_scope(scope, extension) - scope - end - - def self.macro - raise NotImplementedError - end - - def self.valid_options(options) - VALID_OPTIONS + Association.extensions.flat_map(&:valid_options) - end - - def self.validate_options(options) - options.assert_valid_keys(valid_options(options)) - end - - def self.define_extensions(model, name) - end - - def self.define_callbacks(model, reflection) - if dependent = reflection.options[:dependent] - check_dependent_options(dependent) - add_destroy_callbacks(model, reflection) - end - - Association.extensions.each do |extension| - extension.build model, reflection - end - end - - # Defines the setter and getter methods for the association - # class Post < ActiveRecord::Base - # has_many :comments - # end - # - # Post.first.comments and Post.first.comments= methods are defined by this method... - def self.define_accessors(model, reflection) - mixin = model.generated_association_methods - name = reflection.name - define_readers(mixin, name) - define_writers(mixin, name) - end - - def self.define_readers(mixin, name) - mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{name}(*args) - association(:#{name}).reader(*args) - end - CODE - end - - def self.define_writers(mixin, name) - mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{name}=(value) - association(:#{name}).writer(value) - end - CODE - end - - def self.define_validations(model, reflection) - # noop - end - - def self.valid_dependent_options - raise NotImplementedError - end - - def self.check_dependent_options(dependent) - unless valid_dependent_options.include? dependent - raise ArgumentError, "The :dependent option must be one of #{valid_dependent_options}, but is :#{dependent}" - end - end - - def self.add_destroy_callbacks(model, reflection) - name = reflection.name - model.before_destroy lambda { |o| o.association(name).handle_dependency } - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/belongs_to.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/belongs_to.rb deleted file mode 100644 index d3105dc5e4..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/belongs_to.rb +++ /dev/null @@ -1,155 +0,0 @@ -module ActiveRecord::Associations::Builder # :nodoc: - class BelongsTo < SingularAssociation #:nodoc: - def self.macro - :belongs_to - end - - def self.valid_options(options) - super + [:polymorphic, :touch, :counter_cache, :optional, :default] - end - - def self.valid_dependent_options - [:destroy, :delete] - end - - def self.define_callbacks(model, reflection) - super - add_counter_cache_callbacks(model, reflection) if reflection.options[:counter_cache] - add_touch_callbacks(model, reflection) if reflection.options[:touch] - add_default_callbacks(model, reflection) if reflection.options[:default] - end - - def self.define_accessors(mixin, reflection) - super - add_counter_cache_methods mixin - end - - def self.add_counter_cache_methods(mixin) - return if mixin.method_defined? :belongs_to_counter_cache_after_update - - mixin.class_eval do - def belongs_to_counter_cache_after_update(reflection) - foreign_key = reflection.foreign_key - cache_column = reflection.counter_cache_column - - if (@_after_create_counter_called ||= false) - @_after_create_counter_called = false - elsif (@_after_replace_counter_called ||= false) - @_after_replace_counter_called = false - elsif saved_change_to_attribute?(foreign_key) && !new_record? - if reflection.polymorphic? - model = attribute_in_database(reflection.foreign_type).try(:constantize) - model_was = attribute_before_last_save(reflection.foreign_type).try(:constantize) - else - model = reflection.klass - model_was = reflection.klass - end - - foreign_key_was = attribute_before_last_save foreign_key - foreign_key = attribute_in_database foreign_key - - if foreign_key && model.respond_to?(:increment_counter) - model.increment_counter(cache_column, foreign_key) - end - - if foreign_key_was && model_was.respond_to?(:decrement_counter) - model_was.decrement_counter(cache_column, foreign_key_was) - end - end - end - end - end - - def self.add_counter_cache_callbacks(model, reflection) - cache_column = reflection.counter_cache_column - - model.after_update lambda { |record| - record.belongs_to_counter_cache_after_update(reflection) - } - - klass = reflection.class_name.safe_constantize - klass.attr_readonly cache_column if klass && klass.respond_to?(:attr_readonly) - end - - def self.touch_record(o, changes, foreign_key, name, touch, touch_method) # :nodoc: - old_foreign_id = changes[foreign_key] && changes[foreign_key].first - - if old_foreign_id - association = o.association(name) - reflection = association.reflection - if reflection.polymorphic? - foreign_type = reflection.foreign_type - klass = changes[foreign_type] && changes[foreign_type].first || o.public_send(foreign_type) - klass = klass.constantize - else - klass = association.klass - end - primary_key = reflection.association_primary_key(klass) - old_record = klass.find_by(primary_key => old_foreign_id) - - if old_record - if touch != true - old_record.send(touch_method, touch) - else - old_record.send(touch_method) - end - end - end - - record = o.send name - if record && record.persisted? - if touch != true - record.send(touch_method, touch) - else - record.send(touch_method) - end - end - end - - def self.add_touch_callbacks(model, reflection) - foreign_key = reflection.foreign_key - n = reflection.name - touch = reflection.options[:touch] - - callback = lambda { |changes_method| lambda { |record| - BelongsTo.touch_record(record, record.send(changes_method), foreign_key, n, touch, belongs_to_touch_method) - }} - - unless reflection.counter_cache_column - model.after_create callback.(:saved_changes), if: :saved_changes? - model.after_destroy callback.(:changes_to_save) - end - - model.after_update callback.(:saved_changes), if: :saved_changes? - model.after_touch callback.(:changes_to_save) - end - - def self.add_default_callbacks(model, reflection) - model.before_validation lambda { |o| - o.association(reflection.name).default(&reflection.options[:default]) - } - end - - def self.add_destroy_callbacks(model, reflection) - model.after_destroy lambda { |o| o.association(reflection.name).handle_dependency } - end - - def self.define_validations(model, reflection) - if reflection.options.key?(:required) - reflection.options[:optional] = !reflection.options.delete(:required) - end - - if reflection.options[:optional].nil? - required = model.belongs_to_required_by_default - else - required = !reflection.options[:optional] - end - - super - - if required - model.validates_presence_of reflection.name, message: :required - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/collection_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/collection_association.rb deleted file mode 100644 index edeb6491bd..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/collection_association.rb +++ /dev/null @@ -1,82 +0,0 @@ -# This class is inherited by the has_many and has_many_and_belongs_to_many association classes - -require "active_record/associations" - -module ActiveRecord::Associations::Builder # :nodoc: - class CollectionAssociation < Association #:nodoc: - CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove] - - def self.valid_options(options) - super + [:table_name, :before_add, - :after_add, :before_remove, :after_remove, :extend] - end - - def self.define_callbacks(model, reflection) - super - name = reflection.name - options = reflection.options - CALLBACKS.each { |callback_name| - define_callback(model, callback_name, name, options) - } - end - - def self.define_extensions(model, name) - if block_given? - extension_module_name = "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension" - extension = Module.new(&Proc.new) - model.parent.const_set(extension_module_name, extension) - end - end - - def self.define_callback(model, callback_name, name, options) - full_callback_name = "#{callback_name}_for_#{name}" - - # TODO : why do i need method_defined? I think its because of the inheritance chain - model.class_attribute full_callback_name unless model.method_defined?(full_callback_name) - callbacks = Array(options[callback_name.to_sym]).map do |callback| - case callback - when Symbol - ->(method, owner, record) { owner.send(callback, record) } - when Proc - ->(method, owner, record) { callback.call(owner, record) } - else - ->(method, owner, record) { callback.send(method, owner, record) } - end - end - model.send "#{full_callback_name}=", callbacks - end - - # Defines the setter and getter methods for the collection_singular_ids. - def self.define_readers(mixin, name) - super - - mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{name.to_s.singularize}_ids - association(:#{name}).ids_reader - end - CODE - end - - def self.define_writers(mixin, name) - super - - mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{name.to_s.singularize}_ids=(ids) - association(:#{name}).ids_writer(ids) - end - CODE - end - - def self.wrap_scope(scope, mod) - if scope - if scope.arity > 0 - proc { |owner| instance_exec(owner, &scope).extending(mod) } - else - proc { instance_exec(&scope).extending(mod) } - end - else - proc { extending(mod) } - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_and_belongs_to_many.rb deleted file mode 100644 index 6b71826431..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ /dev/null @@ -1,133 +0,0 @@ -module ActiveRecord::Associations::Builder # :nodoc: - class HasAndBelongsToMany # :nodoc: - class JoinTableResolver # :nodoc: - KnownTable = Struct.new :join_table - - class KnownClass # :nodoc: - def initialize(lhs_class, rhs_class_name) - @lhs_class = lhs_class - @rhs_class_name = rhs_class_name - @join_table = nil - end - - def join_table - @join_table ||= [@lhs_class.table_name, klass.table_name].sort.join("\0").gsub(/^(.*[._])(.+)\0\1(.+)/, '\1\2_\3').tr("\0", "_") - end - - private - - def klass - @lhs_class.send(:compute_type, @rhs_class_name) - end - end - - def self.build(lhs_class, name, options) - if options[:join_table] - KnownTable.new options[:join_table].to_s - else - class_name = options.fetch(:class_name) { - name.to_s.camelize.singularize - } - KnownClass.new lhs_class, class_name.to_s - end - end - end - - attr_reader :lhs_model, :association_name, :options - - def initialize(association_name, lhs_model, options) - @association_name = association_name - @lhs_model = lhs_model - @options = options - end - - def through_model - habtm = JoinTableResolver.build lhs_model, association_name, options - - join_model = Class.new(ActiveRecord::Base) { - class << self; - attr_accessor :left_model - attr_accessor :name - attr_accessor :table_name_resolver - attr_accessor :left_reflection - attr_accessor :right_reflection - end - - def self.table_name - table_name_resolver.join_table - end - - def self.compute_type(class_name) - left_model.compute_type class_name - end - - def self.add_left_association(name, options) - belongs_to name, required: false, **options - self.left_reflection = _reflect_on_association(name) - end - - def self.add_right_association(name, options) - rhs_name = name.to_s.singularize.to_sym - belongs_to rhs_name, required: false, **options - self.right_reflection = _reflect_on_association(rhs_name) - end - - def self.retrieve_connection - left_model.retrieve_connection - end - - private - - def self.suppress_composite_primary_key(pk) - pk unless pk.is_a?(Array) - end - } - - join_model.name = "HABTM_#{association_name.to_s.camelize}" - join_model.table_name_resolver = habtm - join_model.left_model = lhs_model - - join_model.add_left_association :left_side, anonymous_class: lhs_model - join_model.add_right_association association_name, belongs_to_options(options) - join_model - end - - def middle_reflection(join_model) - middle_name = [lhs_model.name.downcase.pluralize, - association_name].join("_".freeze).gsub("::".freeze, "_".freeze).to_sym - middle_options = middle_options join_model - - HasMany.create_reflection(lhs_model, - middle_name, - nil, - middle_options) - end - - private - - def middle_options(join_model) - middle_options = {} - middle_options[:class_name] = "#{lhs_model.name}::#{join_model.name}" - middle_options[:source] = join_model.left_reflection.name - if options.key? :foreign_key - middle_options[:foreign_key] = options[:foreign_key] - end - middle_options - end - - def belongs_to_options(options) - rhs_options = {} - - if options.key? :class_name - rhs_options[:foreign_key] = options[:class_name].to_s.foreign_key - rhs_options[:class_name] = options[:class_name] - end - - if options.key? :association_foreign_key - rhs_options[:foreign_key] = options[:association_foreign_key] - end - - rhs_options - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_many.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_many.rb deleted file mode 100644 index 7864d4c536..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_many.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord::Associations::Builder # :nodoc: - class HasMany < CollectionAssociation #:nodoc: - def self.macro - :has_many - end - - def self.valid_options(options) - super + [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of, :counter_cache, :join_table, :foreign_type, :index_errors] - end - - def self.valid_dependent_options - [:destroy, :delete_all, :nullify, :restrict_with_error, :restrict_with_exception] - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_one.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_one.rb deleted file mode 100644 index 4de846d12b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/has_one.rb +++ /dev/null @@ -1,28 +0,0 @@ -module ActiveRecord::Associations::Builder # :nodoc: - class HasOne < SingularAssociation #:nodoc: - def self.macro - :has_one - end - - def self.valid_options(options) - valid = super + [:as] - valid += [:through, :source, :source_type] if options[:through] - valid - end - - def self.valid_dependent_options - [:destroy, :delete, :nullify, :restrict_with_error, :restrict_with_exception] - end - - def self.add_destroy_callbacks(model, reflection) - super unless reflection.options[:through] - end - - def self.define_validations(model, reflection) - super - if reflection.options[:required] - model.validates_presence_of reflection.name, message: :required - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/singular_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/singular_association.rb deleted file mode 100644 index 7732b63af6..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/builder/singular_association.rb +++ /dev/null @@ -1,40 +0,0 @@ -# This class is inherited by the has_one and belongs_to association classes - -module ActiveRecord::Associations::Builder # :nodoc: - class SingularAssociation < Association #:nodoc: - def self.valid_options(options) - super + [:foreign_type, :dependent, :primary_key, :inverse_of, :required] - end - - def self.define_accessors(model, reflection) - super - mixin = model.generated_association_methods - name = reflection.name - - define_constructors(mixin, name) if reflection.constructable? - - mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 - def reload_#{name} - association(:#{name}).force_reload_reader - end - CODE - end - - # Defines the (build|create)_association methods for belongs_to or has_one association - def self.define_constructors(mixin, name) - mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1 - def build_#{name}(*args, &block) - association(:#{name}).build(*args, &block) - end - - def create_#{name}(*args, &block) - association(:#{name}).create(*args, &block) - end - - def create_#{name}!(*args, &block) - association(:#{name}).create!(*args, &block) - end - CODE - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/collection_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/collection_association.rb deleted file mode 100644 index 42b65eab37..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/collection_association.rb +++ /dev/null @@ -1,501 +0,0 @@ -module ActiveRecord - module Associations - # = Active Record Association Collection - # - # CollectionAssociation is an abstract class that provides common stuff to - # ease the implementation of association proxies that represent - # collections. See the class hierarchy in Association. - # - # CollectionAssociation: - # HasManyAssociation => has_many - # HasManyThroughAssociation + ThroughAssociation => has_many :through - # - # The CollectionAssociation class provides common methods to the collections - # defined by +has_and_belongs_to_many+, +has_many+ or +has_many+ with - # the +:through association+ option. - # - # You need to be careful with assumptions regarding the target: The proxy - # does not fetch records from the database until it needs them, but new - # ones created with +build+ are added to the target. So, the target may be - # non-empty and still lack children waiting to be read from the database. - # If you look directly to the database you cannot assume that's the entire - # collection because new records may have been added to the target, etc. - # - # If you need to work on all current children, new and existing records, - # +load_target+ and the +loaded+ flag are your friends. - class CollectionAssociation < Association #:nodoc: - # Implements the reader method, e.g. foo.items for Foo.has_many :items - def reader - if stale_target? - reload - end - - @proxy ||= CollectionProxy.create(klass, self) - @proxy.reset_scope - end - - # Implements the writer method, e.g. foo.items= for Foo.has_many :items - def writer(records) - replace(records) - end - - # Implements the ids reader method, e.g. foo.item_ids for Foo.has_many :items - def ids_reader - if loaded? - target.pluck(reflection.association_primary_key) - else - @association_ids ||= scope.pluck(reflection.association_primary_key) - end - end - - # Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items - def ids_writer(ids) - pk_type = reflection.association_primary_key_type - ids = Array(ids).reject(&:blank?) - ids.map! { |i| pk_type.cast(i) } - - primary_key = reflection.association_primary_key - records = klass.where(primary_key => ids).index_by do |r| - r.public_send(primary_key) - end.values_at(*ids).compact - - if records.size != ids.size - klass.all.raise_record_not_found_exception!(ids, records.size, ids.size, primary_key) - else - replace(records) - end - end - - def reset - super - @target = [] - end - - def find(*args) - if block_given? - load_target.find(*args) { |*block_args| yield(*block_args) } - else - if options[:inverse_of] && loaded? - args_flatten = args.flatten - raise RecordNotFound, "Couldn't find #{scope.klass.name} without an ID" if args_flatten.blank? - result = find_by_scan(*args) - - result_size = Array(result).size - if !result || result_size != args_flatten.size - scope.raise_record_not_found_exception!(args_flatten, result_size, args_flatten.size) - else - result - end - else - scope.find(*args) - end - end - end - - def build(attributes = {}, &block) - if attributes.is_a?(Array) - attributes.collect { |attr| build(attr, &block) } - else - add_to_target(build_record(attributes)) do |record| - yield(record) if block_given? - end - end - end - - # Add +records+ to this association. Returns +self+ so method calls may - # be chained. Since << flattens its argument list and inserts each record, - # +push+ and +concat+ behave identically. - def concat(*records) - records = records.flatten - if owner.new_record? - load_target - concat_records(records) - else - transaction { concat_records(records) } - end - end - - # Starts a transaction in the association class's database connection. - # - # class Author < ActiveRecord::Base - # has_many :books - # end - # - # Author.first.books.transaction do - # # same effect as calling Book.transaction - # end - def transaction(*args) - reflection.klass.transaction(*args) do - yield - end - end - - # Removes all records from the association without calling callbacks - # on the associated records. It honors the +:dependent+ option. However - # if the +:dependent+ value is +:destroy+ then in that case the +:delete_all+ - # deletion strategy for the association is applied. - # - # You can force a particular deletion strategy by passing a parameter. - # - # Example: - # - # @author.books.delete_all(:nullify) - # @author.books.delete_all(:delete_all) - # - # See delete for more info. - def delete_all(dependent = nil) - if dependent && ![:nullify, :delete_all].include?(dependent) - raise ArgumentError, "Valid values are :nullify or :delete_all" - end - - dependent = if dependent - dependent - elsif options[:dependent] == :destroy - :delete_all - else - options[:dependent] - end - - delete_or_nullify_all_records(dependent).tap do - reset - loaded! - end - end - - # Destroy all the records from this association. - # - # See destroy for more info. - def destroy_all - destroy(load_target).tap do - reset - loaded! - end - end - - # Removes +records+ from this association calling +before_remove+ and - # +after_remove+ callbacks. - # - # This method is abstract in the sense that +delete_records+ has to be - # provided by descendants. Note this method does not imply the records - # are actually removed from the database, that depends precisely on - # +delete_records+. They are in any case removed from the collection. - def delete(*records) - return if records.empty? - records = find(records) if records.any? { |record| record.kind_of?(Integer) || record.kind_of?(String) } - delete_or_destroy(records, options[:dependent]) - end - - # Deletes the +records+ and removes them from this association calling - # +before_remove+ , +after_remove+ , +before_destroy+ and +after_destroy+ callbacks. - # - # Note that this method removes records from the database ignoring the - # +:dependent+ option. - def destroy(*records) - return if records.empty? - records = find(records) if records.any? { |record| record.kind_of?(Integer) || record.kind_of?(String) } - delete_or_destroy(records, :destroy) - end - - # Returns the size of the collection by executing a SELECT COUNT(*) - # query if the collection hasn't been loaded, and calling - # collection.size if it has. - # - # If the collection has been already loaded +size+ and +length+ are - # equivalent. If not and you are going to need the records anyway - # +length+ will take one less query. Otherwise +size+ is more efficient. - # - # This method is abstract in the sense that it relies on - # +count_records+, which is a method descendants have to provide. - def size - if !find_target? || loaded? - target.size - elsif !association_scope.group_values.empty? - load_target.size - elsif !association_scope.distinct_value && target.is_a?(Array) - unsaved_records = target.select(&:new_record?) - unsaved_records.size + count_records - else - count_records - end - end - - # Returns true if the collection is empty. - # - # If the collection has been loaded - # it is equivalent to collection.size.zero?. If the - # collection has not been loaded, it is equivalent to - # collection.exists?. If the collection has not already been - # loaded and you are going to fetch the records anyway it is better to - # check collection.length.zero?. - def empty? - if loaded? - size.zero? - else - @target.blank? && !scope.exists? - end - end - - # Replace this collection with +other_array+. This will perform a diff - # and delete/add only records that have changed. - def replace(other_array) - other_array.each { |val| raise_on_type_mismatch!(val) } - original_target = load_target.dup - - if owner.new_record? - replace_records(other_array, original_target) - else - replace_common_records_in_memory(other_array, original_target) - if other_array != original_target - transaction { replace_records(other_array, original_target) } - else - other_array - end - end - end - - def include?(record) - if record.is_a?(reflection.klass) - if record.new_record? - include_in_memory?(record) - else - loaded? ? target.include?(record) : scope.exists?(record.id) - end - else - false - end - end - - def load_target - if find_target? - @target = merge_target_lists(find_target, target) - end - - loaded! - target - end - - def add_to_target(record, skip_callbacks = false, &block) - if association_scope.distinct_value - index = @target.index(record) - end - replace_on_target(record, index, skip_callbacks, &block) - end - - def scope - scope = super - scope.none! if null_scope? - scope - end - - def null_scope? - owner.new_record? && !foreign_key_present? - end - - def find_from_target? - loaded? || - owner.new_record? || - target.any? { |record| record.new_record? || record.changed? } - end - - private - - def find_target - return scope.to_a if skip_statement_cache? - - conn = klass.connection - sc = reflection.association_scope_cache(conn, owner) do - StatementCache.create(conn) { |params| - as = AssociationScope.create { params.bind } - target_scope.merge as.scope(self, conn) - } - end - - binds = AssociationScope.get_bind_values(owner, reflection.chain) - sc.execute(binds, klass, conn) do |record| - set_inverse_instance(record) - end - end - - # We have some records loaded from the database (persisted) and some that are - # in-memory (memory). The same record may be represented in the persisted array - # and in the memory array. - # - # So the task of this method is to merge them according to the following rules: - # - # * The final array must not have duplicates - # * The order of the persisted array is to be preserved - # * Any changes made to attributes on objects in the memory array are to be preserved - # * Otherwise, attributes should have the value found in the database - def merge_target_lists(persisted, memory) - return persisted if memory.empty? - return memory if persisted.empty? - - persisted.map! do |record| - if mem_record = memory.delete(record) - - ((record.attribute_names & mem_record.attribute_names) - mem_record.changed_attribute_names_to_save).each do |name| - mem_record[name] = record[name] - end - - mem_record - else - record - end - end - - persisted + memory - end - - def _create_record(attributes, raise = false, &block) - unless owner.persisted? - raise ActiveRecord::RecordNotSaved, "You cannot call create unless the parent is saved" - end - - if attributes.is_a?(Array) - attributes.collect { |attr| _create_record(attr, raise, &block) } - else - transaction do - add_to_target(build_record(attributes)) do |record| - yield(record) if block_given? - insert_record(record, true, raise) { @_was_loaded = loaded? } - end - end - end - end - - # Do the relevant stuff to insert the given record into the association collection. - def insert_record(record, validate = true, raise = false, &block) - if raise - record.save!(validate: validate, &block) - else - record.save(validate: validate, &block) - end - end - - def create_scope - scope.scope_for_create.stringify_keys - end - - def delete_or_destroy(records, method) - records = records.flatten - records.each { |record| raise_on_type_mismatch!(record) } - existing_records = records.reject(&:new_record?) - - if existing_records.empty? - remove_records(existing_records, records, method) - else - transaction { remove_records(existing_records, records, method) } - end - end - - def remove_records(existing_records, records, method) - records.each { |record| callback(:before_remove, record) } - - delete_records(existing_records, method) if existing_records.any? - records.each { |record| target.delete(record) } - - records.each { |record| callback(:after_remove, record) } - end - - # Delete the given records from the association, - # using one of the methods +:destroy+, +:delete_all+ - # or +:nullify+ (or +nil+, in which case a default is used). - def delete_records(records, method) - raise NotImplementedError - end - - def replace_records(new_target, original_target) - delete(target - new_target) - - unless concat(new_target - target) - @target = original_target - raise RecordNotSaved, "Failed to replace #{reflection.name} because one or more of the " \ - "new records could not be saved." - end - - target - end - - def replace_common_records_in_memory(new_target, original_target) - common_records = new_target & original_target - common_records.each do |record| - skip_callbacks = true - replace_on_target(record, @target.index(record), skip_callbacks) - end - end - - def concat_records(records, raise = false) - result = true - - records.each do |record| - raise_on_type_mismatch!(record) - add_to_target(record) do - result &&= insert_record(record, true, raise) { @_was_loaded = loaded? } unless owner.new_record? - end - end - - result && records - end - - def replace_on_target(record, index, skip_callbacks) - callback(:before_add, record) unless skip_callbacks - - set_inverse_instance(record) - - @_was_loaded = true - - yield(record) if block_given? - - if index - target[index] = record - elsif @_was_loaded || !loaded? - target << record - end - - callback(:after_add, record) unless skip_callbacks - - record - ensure - @_was_loaded = nil - end - - def callback(method, record) - callbacks_for(method).each do |callback| - callback.call(method, owner, record) - end - end - - def callbacks_for(callback_name) - full_callback_name = "#{callback_name}_for_#{reflection.name}" - owner.class.send(full_callback_name) - end - - def include_in_memory?(record) - if reflection.is_a?(ActiveRecord::Reflection::ThroughReflection) - assoc = owner.association(reflection.through_reflection.name) - assoc.reader.any? { |source| - target_reflection = source.send(reflection.source_reflection.name) - target_reflection.respond_to?(:include?) ? target_reflection.include?(record) : target_reflection == record - } || target.include?(record) - else - target.include?(record) - end - end - - # If the :inverse_of option has been - # specified, then #find scans the entire collection. - def find_by_scan(*args) - expects_array = args.first.kind_of?(Array) - ids = args.flatten.compact.map(&:to_s).uniq - - if ids.size == 1 - id = ids.first - record = load_target.detect { |r| id == r.id.to_s } - expects_array ? [ record ] : record - else - load_target.select { |r| ids.include?(r.id.to_s) } - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/collection_proxy.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/collection_proxy.rb deleted file mode 100644 index 0a5c42b178..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/collection_proxy.rb +++ /dev/null @@ -1,1160 +0,0 @@ -module ActiveRecord - module Associations - # Association proxies in Active Record are middlemen between the object that - # holds the association, known as the @owner, and the actual associated - # object, known as the @target. The kind of association any proxy is - # about is available in @reflection. That's an instance of the class - # ActiveRecord::Reflection::AssociationReflection. - # - # For example, given - # - # class Blog < ActiveRecord::Base - # has_many :posts - # end - # - # blog = Blog.first - # - # the association proxy in blog.posts has the object in +blog+ as - # @owner, the collection of its posts as @target, and - # the @reflection object represents a :has_many macro. - # - # This class delegates unknown methods to @target via - # method_missing. - # - # The @target object is not \loaded until needed. For example, - # - # blog.posts.count - # - # is computed directly through SQL and does not trigger by itself the - # instantiation of the actual post records. - class CollectionProxy < Relation - def initialize(klass, association) #:nodoc: - @association = association - super klass, klass.arel_table, klass.predicate_builder - - extensions = association.extensions - extend(*extensions) if extensions.any? - end - - def target - @association.target - end - - def load_target - @association.load_target - end - - # Returns +true+ if the association has been loaded, otherwise +false+. - # - # person.pets.loaded? # => false - # person.pets - # person.pets.loaded? # => true - def loaded? - @association.loaded? - end - - ## - # :method: select - # - # :call-seq: - # select(*fields, &block) - # - # Works in two ways. - # - # *First:* Specify a subset of fields to be selected from the result set. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.select(:name) - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.select(:id, :name) - # # => [ - # # #, - # # #, - # # # - # # ] - # - # Be careful because this also means you're initializing a model - # object with only the fields that you've selected. If you attempt - # to access a field except +id+ that is not in the initialized record you'll - # receive: - # - # person.pets.select(:name).first.person_id - # # => ActiveModel::MissingAttributeError: missing attribute: person_id - # - # *Second:* You can pass a block so it can be used just like Array#select. - # This builds an array of objects from the database for the scope, - # converting them into an array and iterating through them using - # Array#select. - # - # person.pets.select { |pet| pet.name =~ /oo/ } - # # => [ - # # #, - # # # - # # ] - - # Finds an object in the collection responding to the +id+. Uses the same - # rules as ActiveRecord::Base.find. Returns ActiveRecord::RecordNotFound - # error if the object cannot be found. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.find(1) # => # - # person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with 'id'=4 - # - # person.pets.find(2) { |pet| pet.name.downcase! } - # # => # - # - # person.pets.find(2, 3) - # # => [ - # # #, - # # # - # # ] - def find(*args, &block) - @association.find(*args, &block) - end - - ## - # :method: first - # - # :call-seq: - # first(limit = nil) - # - # Returns the first record, or the first +n+ records, from the collection. - # If the collection is empty, the first form returns +nil+, and the second - # form returns an empty array. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.first # => # - # - # person.pets.first(2) - # # => [ - # # #, - # # # - # # ] - # - # another_person_without.pets # => [] - # another_person_without.pets.first # => nil - # another_person_without.pets.first(3) # => [] - - ## - # :method: second - # - # :call-seq: - # second() - # - # Same as #first except returns only the second record. - - ## - # :method: third - # - # :call-seq: - # third() - # - # Same as #first except returns only the third record. - - ## - # :method: fourth - # - # :call-seq: - # fourth() - # - # Same as #first except returns only the fourth record. - - ## - # :method: fifth - # - # :call-seq: - # fifth() - # - # Same as #first except returns only the fifth record. - - ## - # :method: forty_two - # - # :call-seq: - # forty_two() - # - # Same as #first except returns only the forty second record. - # Also known as accessing "the reddit". - - ## - # :method: third_to_last - # - # :call-seq: - # third_to_last() - # - # Same as #first except returns only the third-to-last record. - - ## - # :method: second_to_last - # - # :call-seq: - # second_to_last() - # - # Same as #first except returns only the second-to-last record. - - # Returns the last record, or the last +n+ records, from the collection. - # If the collection is empty, the first form returns +nil+, and the second - # form returns an empty array. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.last # => # - # - # person.pets.last(2) - # # => [ - # # #, - # # # - # # ] - # - # another_person_without.pets # => [] - # another_person_without.pets.last # => nil - # another_person_without.pets.last(3) # => [] - def last(limit = nil) - load_target if find_from_target? - super - end - - # Gives a record (or N records if a parameter is supplied) from the collection - # using the same rules as ActiveRecord::Base.take. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.take # => # - # - # person.pets.take(2) - # # => [ - # # #, - # # # - # # ] - # - # another_person_without.pets # => [] - # another_person_without.pets.take # => nil - # another_person_without.pets.take(2) # => [] - def take(limit = nil) - load_target if find_from_target? - super - end - - # Returns a new object of the collection type that has been instantiated - # with +attributes+ and linked to this object, but have not yet been saved. - # You can pass an array of attributes hashes, this will return an array - # with the new objects. - # - # class Person - # has_many :pets - # end - # - # person.pets.build - # # => # - # - # person.pets.build(name: 'Fancy-Fancy') - # # => # - # - # person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}]) - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.size # => 5 # size of the collection - # person.pets.count # => 0 # count from database - def build(attributes = {}, &block) - @association.build(attributes, &block) - end - alias_method :new, :build - - # Returns a new object of the collection type that has been instantiated with - # attributes, linked to this object and that has already been saved (if it - # passes the validations). - # - # class Person - # has_many :pets - # end - # - # person.pets.create(name: 'Fancy-Fancy') - # # => # - # - # person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}]) - # # => [ - # # #, - # # # - # # ] - # - # person.pets.size # => 3 - # person.pets.count # => 3 - # - # person.pets.find(1, 2, 3) - # # => [ - # # #, - # # #, - # # # - # # ] - def create(attributes = {}, &block) - @association.create(attributes, &block) - end - - # Like #create, except that if the record is invalid, raises an exception. - # - # class Person - # has_many :pets - # end - # - # class Pet - # validates :name, presence: true - # end - # - # person.pets.create!(name: nil) - # # => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank - def create!(attributes = {}, &block) - @association.create!(attributes, &block) - end - - # Add one or more records to the collection by setting their foreign keys - # to the association's primary key. Since #<< flattens its argument list and - # inserts each record, +push+ and #concat behave identically. Returns +self+ - # so method calls may be chained. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.size # => 0 - # person.pets.concat(Pet.new(name: 'Fancy-Fancy')) - # person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')) - # person.pets.size # => 3 - # - # person.id # => 1 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')]) - # person.pets.size # => 5 - def concat(*records) - @association.concat(*records) - end - - # Replaces this collection with +other_array+. This will perform a diff - # and delete/add only records that have changed. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [#] - # - # other_pets = [Pet.new(name: 'Puff', group: 'celebrities'] - # - # person.pets.replace(other_pets) - # - # person.pets - # # => [#] - # - # If the supplied array has an incorrect association type, it raises - # an ActiveRecord::AssociationTypeMismatch error: - # - # person.pets.replace(["doo", "ggie", "gaga"]) - # # => ActiveRecord::AssociationTypeMismatch: Pet expected, got String - def replace(other_array) - @association.replace(other_array) - end - - # Deletes all the records from the collection according to the strategy - # specified by the +:dependent+ option. If no +:dependent+ option is given, - # then it will follow the default strategy. - # - # For has_many :through associations, the default deletion strategy is - # +:delete_all+. - # - # For +has_many+ associations, the default deletion strategy is +:nullify+. - # This sets the foreign keys to +NULL+. - # - # class Person < ActiveRecord::Base - # has_many :pets # dependent: :nullify option by default - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.delete_all - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.size # => 0 - # person.pets # => [] - # - # Pet.find(1, 2, 3) - # # => [ - # # #, - # # #, - # # # - # # ] - # - # Both +has_many+ and has_many :through dependencies default to the - # +:delete_all+ strategy if the +:dependent+ option is set to +:destroy+. - # Records are not instantiated and callbacks will not be fired. - # - # class Person < ActiveRecord::Base - # has_many :pets, dependent: :destroy - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.delete_all - # - # Pet.find(1, 2, 3) - # # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 2, 3) - # - # If it is set to :delete_all, all the objects are deleted - # *without* calling their +destroy+ method. - # - # class Person < ActiveRecord::Base - # has_many :pets, dependent: :delete_all - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.delete_all - # - # Pet.find(1, 2, 3) - # # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 2, 3) - def delete_all(dependent = nil) - @association.delete_all(dependent) - end - - # Deletes the records of the collection directly from the database - # ignoring the +:dependent+ option. Records are instantiated and it - # invokes +before_remove+, +after_remove+ , +before_destroy+ and - # +after_destroy+ callbacks. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.destroy_all - # - # person.pets.size # => 0 - # person.pets # => [] - # - # Pet.find(1) # => Couldn't find Pet with id=1 - def destroy_all - @association.destroy_all - end - - # Deletes the +records+ supplied from the collection according to the strategy - # specified by the +:dependent+ option. If no +:dependent+ option is given, - # then it will follow the default strategy. Returns an array with the - # deleted records. - # - # For has_many :through associations, the default deletion strategy is - # +:delete_all+. - # - # For +has_many+ associations, the default deletion strategy is +:nullify+. - # This sets the foreign keys to +NULL+. - # - # class Person < ActiveRecord::Base - # has_many :pets # dependent: :nullify option by default - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.delete(Pet.find(1)) - # # => [#] - # - # person.pets.size # => 2 - # person.pets - # # => [ - # # #, - # # # - # # ] - # - # Pet.find(1) - # # => # - # - # If it is set to :destroy all the +records+ are removed by calling - # their +destroy+ method. See +destroy+ for more information. - # - # class Person < ActiveRecord::Base - # has_many :pets, dependent: :destroy - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.delete(Pet.find(1), Pet.find(3)) - # # => [ - # # #, - # # # - # # ] - # - # person.pets.size # => 1 - # person.pets - # # => [#] - # - # Pet.find(1, 3) - # # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 3) - # - # If it is set to :delete_all, all the +records+ are deleted - # *without* calling their +destroy+ method. - # - # class Person < ActiveRecord::Base - # has_many :pets, dependent: :delete_all - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.delete(Pet.find(1)) - # # => [#] - # - # person.pets.size # => 2 - # person.pets - # # => [ - # # #, - # # # - # # ] - # - # Pet.find(1) - # # => ActiveRecord::RecordNotFound: Couldn't find Pet with 'id'=1 - # - # You can pass +Integer+ or +String+ values, it finds the records - # responding to the +id+ and executes delete on them. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.delete("1") - # # => [#] - # - # person.pets.delete(2, 3) - # # => [ - # # #, - # # # - # # ] - def delete(*records) - @association.delete(*records) - end - - # Destroys the +records+ supplied and removes them from the collection. - # This method will _always_ remove record from the database ignoring - # the +:dependent+ option. Returns an array with the removed records. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.destroy(Pet.find(1)) - # # => [#] - # - # person.pets.size # => 2 - # person.pets - # # => [ - # # #, - # # # - # # ] - # - # person.pets.destroy(Pet.find(2), Pet.find(3)) - # # => [ - # # #, - # # # - # # ] - # - # person.pets.size # => 0 - # person.pets # => [] - # - # Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (1, 2, 3) - # - # You can pass +Integer+ or +String+ values, it finds the records - # responding to the +id+ and then deletes them from the database. - # - # person.pets.size # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.destroy("4") - # # => # - # - # person.pets.size # => 2 - # person.pets - # # => [ - # # #, - # # # - # # ] - # - # person.pets.destroy(5, 6) - # # => [ - # # #, - # # # - # # ] - # - # person.pets.size # => 0 - # person.pets # => [] - # - # Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with 'id': (4, 5, 6) - def destroy(*records) - @association.destroy(*records) - end - - ## - # :method: distinct - # - # :call-seq: - # distinct(value = true) - # - # Specifies whether the records should be unique or not. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.select(:name) - # # => [ - # # #, - # # # - # # ] - # - # person.pets.select(:name).distinct - # # => [#] - # - # person.pets.select(:name).distinct.distinct(false) - # # => [ - # # #, - # # # - # # ] - - #-- - def uniq - load_target.uniq - end - - def calculate(operation, column_name) - null_scope? ? scope.calculate(operation, column_name) : super - end - - def pluck(*column_names) - null_scope? ? scope.pluck(*column_names) : super - end - - ## - # :method: count - # - # :call-seq: - # count(column_name = nil, &block) - # - # Count all records. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # # This will perform the count using SQL. - # person.pets.count # => 3 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # Passing a block will select all of a person's pets in SQL and then - # perform the count using Ruby. - # - # person.pets.count { |pet| pet.name.include?('-') } # => 2 - - # Returns the size of the collection. If the collection hasn't been loaded, - # it executes a SELECT COUNT(*) query. Else it calls collection.size. - # - # If the collection has been already loaded +size+ and +length+ are - # equivalent. If not and you are going to need the records anyway - # +length+ will take one less query. Otherwise +size+ is more efficient. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.size # => 3 - # # executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1 - # - # person.pets # This will execute a SELECT * FROM query - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.size # => 3 - # # Because the collection is already loaded, this will behave like - # # collection.size and no SQL count query is executed. - def size - @association.size - end - - ## - # :method: length - # - # :call-seq: - # length() - # - # Returns the size of the collection calling +size+ on the target. - # If the collection has been already loaded, +length+ and +size+ are - # equivalent. If not and you are going to need the records anyway this - # method will take one less query. Otherwise +size+ is more efficient. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.length # => 3 - # # executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1 - # - # # Because the collection is loaded, you can - # # call the collection with no additional queries: - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - - # Returns +true+ if the collection is empty. If the collection has been - # loaded it is equivalent - # to collection.size.zero?. If the collection has not been loaded, - # it is equivalent to !collection.exists?. If the collection has - # not already been loaded and you are going to fetch the records anyway it - # is better to check collection.length.zero?. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.count # => 1 - # person.pets.empty? # => false - # - # person.pets.delete_all - # - # person.pets.count # => 0 - # person.pets.empty? # => true - def empty? - @association.empty? - end - - ## - # :method: any? - # - # :call-seq: - # any?() - # - # Returns +true+ if the collection is not empty. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.count # => 0 - # person.pets.any? # => false - # - # person.pets << Pet.new(name: 'Snoop') - # person.pets.count # => 1 - # person.pets.any? # => true - # - # You can also pass a +block+ to define criteria. The behavior - # is the same, it returns true if the collection based on the - # criteria is not empty. - # - # person.pets - # # => [#] - # - # person.pets.any? do |pet| - # pet.group == 'cats' - # end - # # => false - # - # person.pets.any? do |pet| - # pet.group == 'dogs' - # end - # # => true - - ## - # :method: many? - # - # :call-seq: - # many?() - # - # Returns true if the collection has more than one record. - # Equivalent to collection.size > 1. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.count # => 1 - # person.pets.many? # => false - # - # person.pets << Pet.new(name: 'Snoopy') - # person.pets.count # => 2 - # person.pets.many? # => true - # - # You can also pass a +block+ to define criteria. The - # behavior is the same, it returns true if the collection - # based on the criteria has more than one record. - # - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # person.pets.many? do |pet| - # pet.group == 'dogs' - # end - # # => false - # - # person.pets.many? do |pet| - # pet.group == 'cats' - # end - # # => true - - # Returns +true+ if the given +record+ is present in the collection. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets # => [#] - # - # person.pets.include?(Pet.find(20)) # => true - # person.pets.include?(Pet.find(21)) # => false - def include?(record) - !!@association.include?(record) - end - - def proxy_association - @association - end - - # Returns a Relation object for the records in this association - def scope - @scope ||= @association.scope - end - - # Equivalent to Array#==. Returns +true+ if the two arrays - # contain the same number of elements and if each element is equal - # to the corresponding element in the +other+ array, otherwise returns - # +false+. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [ - # # #, - # # # - # # ] - # - # other = person.pets.to_ary - # - # person.pets == other - # # => true - # - # other = [Pet.new(id: 1), Pet.new(id: 2)] - # - # person.pets == other - # # => false - def ==(other) - load_target == other - end - - # Returns a new array of objects from the collection. If the collection - # hasn't been loaded, it fetches the records from the database. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - # - # other_pets = person.pets.to_ary - # # => [ - # # #, - # # #, - # # # - # # ] - # - # other_pets.replace([Pet.new(name: 'BooGoo')]) - # - # other_pets - # # => [#] - # - # person.pets - # # This is not affected by replace - # # => [ - # # #, - # # #, - # # # - # # ] - def to_ary - load_target.dup - end - alias_method :to_a, :to_ary - - def records # :nodoc: - load_target - end - - # Adds one or more +records+ to the collection by setting their foreign keys - # to the association's primary key. Returns +self+, so several appends may be - # chained together. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets.size # => 0 - # person.pets << Pet.new(name: 'Fancy-Fancy') - # person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')] - # person.pets.size # => 3 - # - # person.id # => 1 - # person.pets - # # => [ - # # #, - # # #, - # # # - # # ] - def <<(*records) - proxy_association.concat(records) && self - end - alias_method :push, :<< - alias_method :append, :<< - - def prepend(*args) - raise NoMethodError, "prepend on association is not defined. Please use <<, push or append" - end - - # Equivalent to +delete_all+. The difference is that returns +self+, instead - # of an array with the deleted objects, so methods can be chained. See - # +delete_all+ for more information. - # Note that because +delete_all+ removes records by directly - # running an SQL query into the database, the +updated_at+ column of - # the object is not changed. - def clear - delete_all - self - end - - # Reloads the collection from the database. Returns +self+. - # Equivalent to collection(true). - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets # fetches pets from the database - # # => [#] - # - # person.pets # uses the pets cache - # # => [#] - # - # person.pets.reload # fetches pets from the database - # # => [#] - # - # person.pets(true) # fetches pets from the database - # # => [#] - def reload - proxy_association.reload - reset_scope - end - - # Unloads the association. Returns +self+. - # - # class Person < ActiveRecord::Base - # has_many :pets - # end - # - # person.pets # fetches pets from the database - # # => [#] - # - # person.pets # uses the pets cache - # # => [#] - # - # person.pets.reset # clears the pets cache - # - # person.pets # fetches pets from the database - # # => [#] - def reset - proxy_association.reset - proxy_association.reset_scope - reset_scope - end - - def reset_scope # :nodoc: - @offsets = {} - @scope = nil - self - end - - delegate_methods = [ - QueryMethods, - SpawnMethods, - ].flat_map { |klass| - klass.public_instance_methods(false) - } - self.public_instance_methods(false) - [:select] + [:scoping] - - delegate(*delegate_methods, to: :scope) - - private - - def find_nth_with_limit(index, limit) - load_target if find_from_target? - super - end - - def find_nth_from_last(index) - load_target if find_from_target? - super - end - - def null_scope? - @association.null_scope? - end - - def find_from_target? - @association.find_from_target? - end - - def exec_queries - load_target - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/foreign_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/foreign_association.rb deleted file mode 100644 index 3ceec0ee46..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/foreign_association.rb +++ /dev/null @@ -1,11 +0,0 @@ -module ActiveRecord::Associations - module ForeignAssociation # :nodoc: - def foreign_key_present? - if reflection.klass.primary_key - owner.attribute_present?(reflection.active_record_primary_key) - else - false - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_many_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_many_association.rb deleted file mode 100644 index 820c611058..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_many_association.rb +++ /dev/null @@ -1,133 +0,0 @@ -module ActiveRecord - # = Active Record Has Many Association - module Associations - # This is the proxy that handles a has many association. - # - # If the association has a :through option further specialization - # is provided by its child HasManyThroughAssociation. - class HasManyAssociation < CollectionAssociation #:nodoc: - include ForeignAssociation - - def handle_dependency - case options[:dependent] - when :restrict_with_exception - raise ActiveRecord::DeleteRestrictionError.new(reflection.name) unless empty? - - when :restrict_with_error - unless empty? - record = owner.class.human_attribute_name(reflection.name).downcase - owner.errors.add(:base, :'restrict_dependent_destroy.has_many', record: record) - throw(:abort) - end - - when :destroy - # No point in executing the counter update since we're going to destroy the parent anyway - load_target.each { |t| t.destroyed_by_association = reflection } - destroy_all - else - delete_all - end - end - - def insert_record(record, validate = true, raise = false) - set_owner_attributes(record) - super - end - - def empty? - if reflection.has_cached_counter? - size.zero? - else - super - end - end - - private - - # Returns the number of records in this collection. - # - # If the association has a counter cache it gets that value. Otherwise - # it will attempt to do a count via SQL, bounded to :limit if - # there's one. Some configuration options like :group make it impossible - # to do an SQL count, in those cases the array count will be used. - # - # That does not depend on whether the collection has already been loaded - # or not. The +size+ method is the one that takes the loaded flag into - # account and delegates to +count_records+ if needed. - # - # If the collection is empty the target is set to an empty array and - # the loaded flag is set to true as well. - def count_records - count = if reflection.has_cached_counter? - owner._read_attribute(reflection.counter_cache_column).to_i - else - scope.count(:all) - end - - # If there's nothing in the database and @target has no new records - # we are certain the current target is an empty array. This is a - # documented side-effect of the method that may avoid an extra SELECT. - (@target ||= []) && loaded! if count == 0 - - [association_scope.limit_value, count].compact.min - end - - def update_counter(difference, reflection = reflection()) - if reflection.has_cached_counter? - owner.increment!(reflection.counter_cache_column, difference) - end - end - - def update_counter_in_memory(difference, reflection = reflection()) - if reflection.counter_must_be_updated_by_has_many? - counter = reflection.counter_cache_column - owner.increment(counter, difference) - owner.send(:clear_attribute_change, counter) # eww - end - end - - def delete_count(method, scope) - if method == :delete_all - scope.delete_all - else - scope.update_all(reflection.foreign_key => nil) - end - end - - def delete_or_nullify_all_records(method) - count = delete_count(method, scope) - update_counter(-count) - end - - # Deletes the records according to the :dependent option. - def delete_records(records, method) - if method == :destroy - records.each(&:destroy!) - update_counter(-records.length) unless reflection.inverse_updates_counter_cache? - else - scope = self.scope.where(reflection.klass.primary_key => records) - update_counter(-delete_count(method, scope)) - end - end - - def concat_records(records, *) - update_counter_if_success(super, records.length) - end - - def _create_record(attributes, *) - if attributes.is_a?(Array) - super - else - update_counter_if_success(super, 1) - end - end - - def update_counter_if_success(saved_successfully, difference) - if saved_successfully - update_counter_in_memory(difference) - end - saved_successfully - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_many_through_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_many_through_association.rb deleted file mode 100644 index 2fd20b4368..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_many_through_association.rb +++ /dev/null @@ -1,214 +0,0 @@ -module ActiveRecord - # = Active Record Has Many Through Association - module Associations - class HasManyThroughAssociation < HasManyAssociation #:nodoc: - include ThroughAssociation - - def initialize(owner, reflection) - super - - @through_records = {} - @through_association = nil - end - - def concat(*records) - unless owner.new_record? - records.flatten.each do |record| - raise_on_type_mismatch!(record) - end - end - - super - end - - def concat_records(records) - ensure_not_nested - - records = super(records, true) - - if owner.new_record? && records - records.flatten.each do |record| - build_through_record(record) - end - end - - records - end - - def insert_record(record, validate = true, raise = false) - ensure_not_nested - - if record.new_record? || record.has_changes_to_save? - return unless super - end - - save_through_record(record) - - record - end - - private - - def through_association - @through_association ||= owner.association(through_reflection.name) - end - - # The through record (built with build_record) is temporarily cached - # so that it may be reused if insert_record is subsequently called. - # - # However, after insert_record has been called, the cache is cleared in - # order to allow multiple instances of the same record in an association. - def build_through_record(record) - @through_records[record.object_id] ||= begin - ensure_mutable - - through_record = through_association.build(*options_for_through_record) - through_record.send("#{source_reflection.name}=", record) - - if options[:source_type] - through_record.send("#{source_reflection.foreign_type}=", options[:source_type]) - end - - through_record - end - end - - def options_for_through_record - [through_scope_attributes] - end - - def through_scope_attributes - scope.where_values_hash(through_association.reflection.name.to_s). - except!(through_association.reflection.foreign_key, - through_association.reflection.klass.inheritance_column) - end - - def save_through_record(record) - association = build_through_record(record) - if association.changed? - association.save! - end - ensure - @through_records.delete(record.object_id) - end - - def build_record(attributes) - ensure_not_nested - - record = super(attributes) - - inverse = source_reflection.inverse_of - if inverse - if inverse.collection? - record.send(inverse.name) << build_through_record(record) - elsif inverse.has_one? - record.send("#{inverse.name}=", build_through_record(record)) - end - end - - record - end - - def remove_records(existing_records, records, method) - super - delete_through_records(records) - end - - def target_reflection_has_associated_record? - !(through_reflection.belongs_to? && owner[through_reflection.foreign_key].blank?) - end - - def update_through_counter?(method) - case method - when :destroy - !through_reflection.inverse_updates_counter_cache? - when :nullify - false - else - true - end - end - - def delete_or_nullify_all_records(method) - delete_records(load_target, method) - end - - def delete_records(records, method) - ensure_not_nested - - scope = through_association.scope - scope.where! construct_join_attributes(*records) - - case method - when :destroy - if scope.klass.primary_key - count = scope.destroy_all.length - else - scope.each(&:_run_destroy_callbacks) - - arel = scope.arel - - stmt = Arel::DeleteManager.new - stmt.from scope.klass.arel_table - stmt.wheres = arel.constraints - - count = scope.klass.connection.delete(stmt, "SQL", scope.bound_attributes) - end - when :nullify - count = scope.update_all(source_reflection.foreign_key => nil) - else - count = scope.delete_all - end - - delete_through_records(records) - - if source_reflection.options[:counter_cache] && method != :destroy - counter = source_reflection.counter_cache_column - klass.decrement_counter counter, records.map(&:id) - end - - if through_reflection.collection? && update_through_counter?(method) - update_counter(-count, through_reflection) - else - update_counter(-count) - end - end - - def through_records_for(record) - attributes = construct_join_attributes(record) - candidates = Array.wrap(through_association.target) - candidates.find_all do |c| - attributes.all? do |key, value| - c.public_send(key) == value - end - end - end - - def delete_through_records(records) - records.each do |record| - through_records = through_records_for(record) - - if through_reflection.collection? - through_records.each { |r| through_association.target.delete(r) } - else - if through_records.include?(through_association.target) - through_association.target = nil - end - end - - @through_records.delete(record.object_id) - end - end - - def find_target - return [] unless target_reflection_has_associated_record? - super - end - - # NOTE - not sure that we can actually cope with inverses here - def invertible_for?(record) - false - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_one_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_one_association.rb deleted file mode 100644 index d2e5efed74..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_one_association.rb +++ /dev/null @@ -1,109 +0,0 @@ -module ActiveRecord - # = Active Record Has One Association - module Associations - class HasOneAssociation < SingularAssociation #:nodoc: - include ForeignAssociation - - def handle_dependency - case options[:dependent] - when :restrict_with_exception - raise ActiveRecord::DeleteRestrictionError.new(reflection.name) if load_target - - when :restrict_with_error - if load_target - record = owner.class.human_attribute_name(reflection.name).downcase - owner.errors.add(:base, :'restrict_dependent_destroy.has_one', record: record) - throw(:abort) - end - - else - delete - end - end - - def replace(record, save = true) - raise_on_type_mismatch!(record) if record - load_target - - return target unless target || record - - assigning_another_record = target != record - if assigning_another_record || record.has_changes_to_save? - save &&= owner.persisted? - - transaction_if(save) do - remove_target!(options[:dependent]) if target && !target.destroyed? && assigning_another_record - - if record - set_owner_attributes(record) - set_inverse_instance(record) - - if save && !record.save - nullify_owner_attributes(record) - set_owner_attributes(target) if target - raise RecordNotSaved, "Failed to save the new associated #{reflection.name}." - end - end - end - end - - self.target = record - end - - def delete(method = options[:dependent]) - if load_target - case method - when :delete - target.delete - when :destroy - target.destroyed_by_association = reflection - target.destroy - when :nullify - target.update_columns(reflection.foreign_key => nil) if target.persisted? - end - end - end - - private - - # The reason that the save param for replace is false, if for create (not just build), - # is because the setting of the foreign keys is actually handled by the scoping when - # the record is instantiated, and so they are set straight away and do not need to be - # updated within replace. - def set_new_record(record) - replace(record, false) - end - - def remove_target!(method) - case method - when :delete - target.delete - when :destroy - target.destroyed_by_association = reflection - target.destroy - else - nullify_owner_attributes(target) - remove_inverse_instance(target) - - if target.persisted? && owner.persisted? && !target.save - set_owner_attributes(target) - raise RecordNotSaved, "Failed to remove the existing associated #{reflection.name}. " \ - "The record failed to save after its foreign key was set to nil." - end - end - end - - def nullify_owner_attributes(record) - record[reflection.foreign_key] = nil - end - - def transaction_if(value) - if value - reflection.klass.transaction { yield } - else - yield - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_one_through_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_one_through_association.rb deleted file mode 100644 index 1183bdf6f4..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/has_one_through_association.rb +++ /dev/null @@ -1,40 +0,0 @@ -module ActiveRecord - # = Active Record Has One Through Association - module Associations - class HasOneThroughAssociation < HasOneAssociation #:nodoc: - include ThroughAssociation - - def replace(record) - create_through_record(record) - self.target = record - end - - private - - def create_through_record(record) - ensure_not_nested - - through_proxy = owner.association(through_reflection.name) - through_record = through_proxy.load_target - - if through_record && !record - through_record.destroy - elsif record - attributes = construct_join_attributes(record) - - if through_record && through_record.destroyed? - through_record = through_proxy.tap(&:reload).target - end - - if through_record - through_record.update(attributes) - elsif owner.new_record? - through_proxy.build(attributes) - else - through_proxy.create(attributes) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency.rb deleted file mode 100644 index 4f5047320a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency.rb +++ /dev/null @@ -1,307 +0,0 @@ -module ActiveRecord - module Associations - class JoinDependency # :nodoc: - autoload :JoinBase, "active_record/associations/join_dependency/join_base" - autoload :JoinAssociation, "active_record/associations/join_dependency/join_association" - - class Aliases # :nodoc: - def initialize(tables) - @tables = tables - @alias_cache = tables.each_with_object({}) { |table, h| - h[table.node] = table.columns.each_with_object({}) { |column, i| - i[column.name] = column.alias - } - } - @name_and_alias_cache = tables.each_with_object({}) { |table, h| - h[table.node] = table.columns.map { |column| - [column.name, column.alias] - } - } - end - - def columns - @tables.flat_map(&:column_aliases) - end - - # An array of [column_name, alias] pairs for the table - def column_aliases(node) - @name_and_alias_cache[node] - end - - def column_alias(node, column) - @alias_cache[node][column] - end - - Table = Struct.new(:node, :columns) do # :nodoc: - def table - Arel::Nodes::TableAlias.new node.table, node.aliased_table_name - end - - def column_aliases - t = table - columns.map { |column| t[column.name].as Arel.sql column.alias } - end - end - Column = Struct.new(:name, :alias) - end - - attr_reader :alias_tracker, :base_klass, :join_root - - def self.make_tree(associations) - hash = {} - walk_tree associations, hash - hash - end - - def self.walk_tree(associations, hash) - case associations - when Symbol, String - hash[associations.to_sym] ||= {} - when Array - associations.each do |assoc| - walk_tree assoc, hash - end - when Hash - associations.each do |k, v| - cache = hash[k] ||= {} - walk_tree v, cache - end - else - raise ConfigurationError, associations.inspect - end - end - - # base is the base class on which operation is taking place. - # associations is the list of associations which are joined using hash, symbol or array. - # joins is the list of all string join commands and arel nodes. - # - # Example : - # - # class Physician < ActiveRecord::Base - # has_many :appointments - # has_many :patients, through: :appointments - # end - # - # If I execute `@physician.patients.to_a` then - # base # => Physician - # associations # => [] - # joins # => [# Physician - # associations # => [:appointments] - # joins # => [] - # - def initialize(base, associations, joins, eager_loading: true) - @alias_tracker = AliasTracker.create_with_joins(base.connection, base.table_name, joins) - @eager_loading = eager_loading - tree = self.class.make_tree associations - @join_root = JoinBase.new base, build(tree, base) - @join_root.children.each { |child| construct_tables! @join_root, child } - end - - def reflections - join_root.drop(1).map!(&:reflection) - end - - def join_constraints(outer_joins, join_type) - joins = join_root.children.flat_map { |child| - - if join_type == Arel::Nodes::OuterJoin - make_left_outer_joins join_root, child - else - make_inner_joins join_root, child - end - } - - joins.concat outer_joins.flat_map { |oj| - if join_root.match? oj.join_root - walk join_root, oj.join_root - else - oj.join_root.children.flat_map { |child| - make_outer_joins oj.join_root, child - } - end - } - end - - def aliases - @aliases ||= Aliases.new join_root.each_with_index.map { |join_part, i| - columns = join_part.column_names.each_with_index.map { |column_name, j| - Aliases::Column.new column_name, "t#{i}_r#{j}" - } - Aliases::Table.new(join_part, columns) - } - end - - def instantiate(result_set, &block) - primary_key = aliases.column_alias(join_root, join_root.primary_key) - - seen = Hash.new { |i, object_id| - i[object_id] = Hash.new { |j, child_class| - j[child_class] = {} - } - } - - model_cache = Hash.new { |h, klass| h[klass] = {} } - parents = model_cache[join_root] - column_aliases = aliases.column_aliases join_root - - message_bus = ActiveSupport::Notifications.instrumenter - - payload = { - record_count: result_set.length, - class_name: join_root.base_klass.name - } - - message_bus.instrument("instantiation.active_record", payload) do - result_set.each { |row_hash| - parent_key = primary_key ? row_hash[primary_key] : row_hash - parent = parents[parent_key] ||= join_root.instantiate(row_hash, column_aliases, &block) - construct(parent, join_root, row_hash, result_set, seen, model_cache, aliases) - } - end - - parents.values - end - - private - - def make_constraints(parent, child, tables, join_type) - chain = child.reflection.chain - foreign_table = parent.table - foreign_klass = parent.base_klass - child.join_constraints(foreign_table, foreign_klass, join_type, tables, chain) - end - - def make_outer_joins(parent, child) - tables = table_aliases_for(parent, child) - join_type = Arel::Nodes::OuterJoin - info = make_constraints parent, child, tables, join_type - - [info] + child.children.flat_map { |c| make_outer_joins(child, c) } - end - - def make_left_outer_joins(parent, child) - tables = child.tables - join_type = Arel::Nodes::OuterJoin - info = make_constraints parent, child, tables, join_type - - [info] + child.children.flat_map { |c| make_left_outer_joins(child, c) } - end - - def make_inner_joins(parent, child) - tables = child.tables - join_type = Arel::Nodes::InnerJoin - info = make_constraints parent, child, tables, join_type - - [info] + child.children.flat_map { |c| make_inner_joins(child, c) } - end - - def table_aliases_for(parent, node) - node.reflection.chain.map { |reflection| - alias_tracker.aliased_table_for( - reflection.table_name, - table_alias_for(reflection, parent, reflection != node.reflection), - reflection.klass.type_caster - ) - } - end - - def construct_tables!(parent, node) - node.tables = table_aliases_for(parent, node) - node.children.each { |child| construct_tables! node, child } - end - - def table_alias_for(reflection, parent, join) - name = "#{reflection.plural_name}_#{parent.table_name}" - name << "_join" if join - name - end - - def walk(left, right) - intersection, missing = right.children.map { |node1| - [left.children.find { |node2| node1.match? node2 }, node1] - }.partition(&:first) - - ojs = missing.flat_map { |_, n| make_outer_joins left, n } - intersection.flat_map { |l, r| walk l, r }.concat ojs - end - - def find_reflection(klass, name) - klass._reflect_on_association(name) || - raise(ConfigurationError, "Can't join '#{klass.name}' to association named '#{name}'; perhaps you misspelled it?") - end - - def build(associations, base_klass) - associations.map do |name, right| - reflection = find_reflection base_klass, name - reflection.check_validity! - reflection.check_eager_loadable! - - if reflection.polymorphic? - next unless @eager_loading - raise EagerLoadPolymorphicError.new(reflection) - end - - JoinAssociation.new reflection, build(right, reflection.klass) - end.compact - end - - def construct(ar_parent, parent, row, rs, seen, model_cache, aliases) - return if ar_parent.nil? - - parent.children.each do |node| - if node.reflection.collection? - other = ar_parent.association(node.reflection.name) - other.loaded! - elsif ar_parent.association_cached?(node.reflection.name) - model = ar_parent.association(node.reflection.name).target - construct(model, node, row, rs, seen, model_cache, aliases) - next - end - - key = aliases.column_alias(node, node.primary_key) - id = row[key] - if id.nil? - nil_association = ar_parent.association(node.reflection.name) - nil_association.loaded! - next - end - - model = seen[ar_parent.object_id][node.base_klass][id] - - if model - construct(model, node, row, rs, seen, model_cache, aliases) - else - model = construct_model(ar_parent, node, row, model_cache, id, aliases) - - if node.reflection.scope_for(node.base_klass).readonly_value - model.readonly! - end - - seen[ar_parent.object_id][node.base_klass][id] = model - construct(model, node, row, rs, seen, model_cache, aliases) - end - end - end - - def construct_model(record, node, row, model_cache, id, aliases) - other = record.association(node.reflection.name) - - model = model_cache[node][id] ||= - node.instantiate(row, aliases.column_aliases(node)) do |m| - other.set_inverse_instance(m) - end - - if node.reflection.collection? - other.target.push(model) - else - other.target = model - end - - model - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_association.rb deleted file mode 100644 index 95f16c622e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_association.rb +++ /dev/null @@ -1,105 +0,0 @@ -require "active_record/associations/join_dependency/join_part" - -module ActiveRecord - module Associations - class JoinDependency # :nodoc: - class JoinAssociation < JoinPart # :nodoc: - # The reflection of the association represented - attr_reader :reflection - - attr_accessor :tables - - def initialize(reflection, children) - super(reflection.klass, children) - - @reflection = reflection - @tables = nil - end - - def match?(other) - return true if self == other - super && reflection == other.reflection - end - - JoinInformation = Struct.new :joins, :binds - - def join_constraints(foreign_table, foreign_klass, join_type, tables, chain) - joins = [] - binds = [] - tables = tables.reverse - - # The chain starts with the target table, but we want to end with it here (makes - # more sense in this context), so we reverse - chain.reverse_each do |reflection| - table = tables.shift - klass = reflection.klass - - join_keys = reflection.join_keys - key = join_keys.key - foreign_key = join_keys.foreign_key - - constraint = build_constraint(klass, table, key, foreign_table, foreign_key) - - rel = reflection.join_scope(table) - - if rel && !rel.arel.constraints.empty? - binds += rel.bound_attributes - constraint = constraint.and rel.arel.constraints - end - - if reflection.type - value = foreign_klass.base_class.name - column = klass.columns_hash[reflection.type.to_s] - - binds << Relation::QueryAttribute.new(column.name, value, klass.type_for_attribute(column.name)) - constraint = constraint.and klass.arel_attribute(reflection.type, table).eq(Arel::Nodes::BindParam.new) - end - - joins << table.create_join(table, table.create_on(constraint), join_type) - - # The current table in this iteration becomes the foreign table in the next - foreign_table, foreign_klass = table, klass - end - - JoinInformation.new joins, binds - end - - # Builds equality condition. - # - # Example: - # - # class Physician < ActiveRecord::Base - # has_many :appointments - # end - # - # If I execute `Physician.joins(:appointments).to_a` then - # klass # => Physician - # table # => # - # key # => physician_id - # foreign_table # => # - # foreign_key # => id - # - def build_constraint(klass, table, key, foreign_table, foreign_key) - constraint = table[key].eq(foreign_table[foreign_key]) - - if klass.finder_needs_type_condition? - constraint = table.create_and([ - constraint, - klass.send(:type_condition, table) - ]) - end - - constraint - end - - def table - tables.first - end - - def aliased_table_name - table.table_alias || table.name - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_base.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_base.rb deleted file mode 100644 index fca20514d1..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_base.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "active_record/associations/join_dependency/join_part" - -module ActiveRecord - module Associations - class JoinDependency # :nodoc: - class JoinBase < JoinPart # :nodoc: - def match?(other) - return true if self == other - super && base_klass == other.base_klass - end - - def table - base_klass.arel_table - end - - def aliased_table_name - base_klass.table_name - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_part.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_part.rb deleted file mode 100644 index 61cec5403a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/join_dependency/join_part.rb +++ /dev/null @@ -1,71 +0,0 @@ -module ActiveRecord - module Associations - class JoinDependency # :nodoc: - # A JoinPart represents a part of a JoinDependency. It is inherited - # by JoinBase and JoinAssociation. A JoinBase represents the Active Record which - # everything else is being joined onto. A JoinAssociation represents an association which - # is joining to the base. A JoinAssociation may result in more than one actual join - # operations (for example a has_and_belongs_to_many JoinAssociation would result in - # two; one for the join table and one for the target table). - class JoinPart # :nodoc: - include Enumerable - - # The Active Record class which this join part is associated 'about'; for a JoinBase - # this is the actual base model, for a JoinAssociation this is the target model of the - # association. - attr_reader :base_klass, :children - - delegate :table_name, :column_names, :primary_key, to: :base_klass - - def initialize(base_klass, children) - @base_klass = base_klass - @children = children - end - - def name - reflection.name - end - - def match?(other) - self.class == other.class - end - - def each(&block) - yield self - children.each { |child| child.each(&block) } - end - - # An Arel::Table for the active_record - def table - raise NotImplementedError - end - - # The alias for the active_record's table - def aliased_table_name - raise NotImplementedError - end - - def extract_record(row, column_names_with_alias) - # This code is performance critical as it is called per row. - # see: https://github.com/rails/rails/pull/12185 - hash = {} - - index = 0 - length = column_names_with_alias.length - - while index < length - column_name, alias_name = column_names_with_alias[index] - hash[column_name] = row[alias_name] - index += 1 - end - - hash - end - - def instantiate(row, aliases, &block) - base_klass.instantiate(extract_record(row, aliases), &block) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader.rb deleted file mode 100644 index 9f77f38b35..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader.rb +++ /dev/null @@ -1,213 +0,0 @@ -module ActiveRecord - module Associations - # Implements the details of eager loading of Active Record associations. - # - # Suppose that you have the following two Active Record models: - # - # class Author < ActiveRecord::Base - # # columns: name, age - # has_many :books - # end - # - # class Book < ActiveRecord::Base - # # columns: title, sales, author_id - # end - # - # When you load an author with all associated books Active Record will make - # multiple queries like this: - # - # Author.includes(:books).where(name: ['bell hooks', 'Homer']).to_a - # - # => SELECT `authors`.* FROM `authors` WHERE `name` IN ('bell hooks', 'Homer') - # => SELECT `books`.* FROM `books` WHERE `author_id` IN (2, 5) - # - # Active Record saves the ids of the records from the first query to use in - # the second. Depending on the number of associations involved there can be - # arbitrarily many SQL queries made. - # - # However, if there is a WHERE clause that spans across tables Active - # Record will fall back to a slightly more resource-intensive single query: - # - # Author.includes(:books).where(books: {title: 'Illiad'}).to_a - # => SELECT `authors`.`id` AS t0_r0, `authors`.`name` AS t0_r1, `authors`.`age` AS t0_r2, - # `books`.`id` AS t1_r0, `books`.`title` AS t1_r1, `books`.`sales` AS t1_r2 - # FROM `authors` - # LEFT OUTER JOIN `books` ON `authors`.`id` = `books`.`author_id` - # WHERE `books`.`title` = 'Illiad' - # - # This could result in many rows that contain redundant data and it performs poorly at scale - # and is therefore only used when necessary. - # - class Preloader #:nodoc: - extend ActiveSupport::Autoload - - eager_autoload do - autoload :Association, "active_record/associations/preloader/association" - autoload :SingularAssociation, "active_record/associations/preloader/singular_association" - autoload :CollectionAssociation, "active_record/associations/preloader/collection_association" - autoload :ThroughAssociation, "active_record/associations/preloader/through_association" - - autoload :HasMany, "active_record/associations/preloader/has_many" - autoload :HasManyThrough, "active_record/associations/preloader/has_many_through" - autoload :HasOne, "active_record/associations/preloader/has_one" - autoload :HasOneThrough, "active_record/associations/preloader/has_one_through" - autoload :BelongsTo, "active_record/associations/preloader/belongs_to" - end - - NULL_RELATION = Struct.new(:values, :where_clause, :joins_values).new({}, Relation::WhereClause.empty, []) - - # Eager loads the named associations for the given Active Record record(s). - # - # In this description, 'association name' shall refer to the name passed - # to an association creation method. For example, a model that specifies - # belongs_to :author, has_many :buyers has association - # names +:author+ and +:buyers+. - # - # == Parameters - # +records+ is an array of ActiveRecord::Base. This array needs not be flat, - # i.e. +records+ itself may also contain arrays of records. In any case, - # +preload_associations+ will preload the all associations records by - # flattening +records+. - # - # +associations+ specifies one or more associations that you want to - # preload. It may be: - # - a Symbol or a String which specifies a single association name. For - # example, specifying +:books+ allows this method to preload all books - # for an Author. - # - an Array which specifies multiple association names. This array - # is processed recursively. For example, specifying [:avatar, :books] - # allows this method to preload an author's avatar as well as all of his - # books. - # - a Hash which specifies multiple association names, as well as - # association names for the to-be-preloaded association objects. For - # example, specifying { author: :avatar } will preload a - # book's author, as well as that author's avatar. - # - # +:associations+ has the same format as the +:include+ option for - # ActiveRecord::Base.find. So +associations+ could look like this: - # - # :books - # [ :books, :author ] - # { author: :avatar } - # [ :books, { author: :avatar } ] - def preload(records, associations, preload_scope = nil) - records = Array.wrap(records).compact.uniq - associations = Array.wrap(associations) - preload_scope = preload_scope || NULL_RELATION - - if records.empty? - [] - else - associations.flat_map { |association| - preloaders_on association, records, preload_scope - } - end - end - - private - - # Loads all the given data into +records+ for the +association+. - def preloaders_on(association, records, scope) - case association - when Hash - preloaders_for_hash(association, records, scope) - when Symbol - preloaders_for_one(association, records, scope) - when String - preloaders_for_one(association.to_sym, records, scope) - else - raise ArgumentError, "#{association.inspect} was not recognized for preload" - end - end - - def preloaders_for_hash(association, records, scope) - association.flat_map { |parent, child| - loaders = preloaders_for_one parent, records, scope - - recs = loaders.flat_map(&:preloaded_records).uniq - loaders.concat Array.wrap(child).flat_map { |assoc| - preloaders_on assoc, recs, scope - } - loaders - } - end - - # Loads all the given data into +records+ for a singular +association+. - # - # Functions by instantiating a preloader class such as Preloader::HasManyThrough and - # call the +run+ method for each passed in class in the +records+ argument. - # - # Not all records have the same class, so group then preload group on the reflection - # itself so that if various subclass share the same association then we do not split - # them unnecessarily - # - # Additionally, polymorphic belongs_to associations can have multiple associated - # classes, depending on the polymorphic_type field. So we group by the classes as - # well. - def preloaders_for_one(association, records, scope) - grouped_records(association, records).flat_map do |reflection, klasses| - klasses.map do |rhs_klass, rs| - loader = preloader_for(reflection, rs, rhs_klass).new(rhs_klass, rs, reflection, scope) - loader.run self - loader - end - end - end - - def grouped_records(association, records) - h = {} - records.each do |record| - next unless record - assoc = record.association(association) - klasses = h[assoc.reflection] ||= {} - (klasses[assoc.klass] ||= []) << record - end - h - end - - class AlreadyLoaded # :nodoc: - attr_reader :owners, :reflection - - def initialize(klass, owners, reflection, preload_scope) - @owners = owners - @reflection = reflection - end - - def run(preloader); end - - def preloaded_records - owners.flat_map { |owner| owner.association(reflection.name).target } - end - end - - class NullPreloader # :nodoc: - def self.new(klass, owners, reflection, preload_scope); self; end - def self.run(preloader); end - def self.preloaded_records; []; end - def self.owners; []; end - end - - # Returns a class containing the logic needed to load preload the data - # and attach it to a relation. For example +Preloader::Association+ or - # +Preloader::HasManyThrough+. The class returned implements a `run` method - # that accepts a preloader. - def preloader_for(reflection, owners, rhs_klass) - return NullPreloader unless rhs_klass - - if owners.first.association(reflection.name).loaded? - return AlreadyLoaded - end - reflection.check_preloadable! - - case reflection.macro - when :has_many - reflection.options[:through] ? HasManyThrough : HasMany - when :has_one - reflection.options[:through] ? HasOneThrough : HasOne - when :belongs_to - BelongsTo - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/association.rb deleted file mode 100644 index b70c2bcc6d..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/association.rb +++ /dev/null @@ -1,147 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class Association #:nodoc: - attr_reader :owners, :reflection, :preload_scope, :model, :klass - attr_reader :preloaded_records - - def initialize(klass, owners, reflection, preload_scope) - @klass = klass - @owners = owners - @reflection = reflection - @preload_scope = preload_scope - @model = owners.first && owners.first.class - @scope = nil - @preloaded_records = [] - end - - def run(preloader) - preload(preloader) - end - - def preload(preloader) - raise NotImplementedError - end - - def scope - @scope ||= build_scope - end - - def records_for(ids) - scope.where(association_key_name => ids) - end - - def table - klass.arel_table - end - - # The name of the key on the associated records - def association_key_name - raise NotImplementedError - end - - # This is overridden by HABTM as the condition should be on the foreign_key column in - # the join table - def association_key - klass.arel_attribute(association_key_name, table) - end - - # The name of the key on the model which declares the association - def owner_key_name - raise NotImplementedError - end - - def options - reflection.options - end - - private - - def associated_records_by_owner(preloader) - records = load_records do |record| - owner = owners_by_key[convert_key(record[association_key_name])] - association = owner.association(reflection.name) - association.set_inverse_instance(record) - end - - owners.each_with_object({}) do |owner, result| - result[owner] = records[convert_key(owner[owner_key_name])] || [] - end - end - - def owner_keys - unless defined?(@owner_keys) - @owner_keys = owners.map do |owner| - owner[owner_key_name] - end - @owner_keys.uniq! - @owner_keys.compact! - end - @owner_keys - end - - def owners_by_key - unless defined?(@owners_by_key) - @owners_by_key = owners.each_with_object({}) do |owner, h| - h[convert_key(owner[owner_key_name])] = owner - end - end - @owners_by_key - end - - def key_conversion_required? - unless defined?(@key_conversion_required) - @key_conversion_required = (association_key_type != owner_key_type) - end - - @key_conversion_required - end - - def convert_key(key) - if key_conversion_required? - key.to_s - else - key - end - end - - def association_key_type - @klass.type_for_attribute(association_key_name.to_s).type - end - - def owner_key_type - @model.type_for_attribute(owner_key_name.to_s).type - end - - def load_records(&block) - return {} if owner_keys.empty? - # Some databases impose a limit on the number of ids in a list (in Oracle it's 1000) - # Make several smaller queries if necessary or make one query if the adapter supports it - slices = owner_keys.each_slice(klass.connection.in_clause_length || owner_keys.size) - @preloaded_records = slices.flat_map do |slice| - records_for(slice).load(&block) - end - @preloaded_records.group_by do |record| - convert_key(record[association_key_name]) - end - end - - def reflection_scope - @reflection_scope ||= reflection.scope_for(klass) - end - - def build_scope - scope = klass.scope_for_association - - if reflection.type - scope.where!(reflection.type => model.base_class.sti_name) - end - - scope.merge!(reflection_scope) - scope.merge!(preload_scope) if preload_scope != NULL_RELATION - scope - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/belongs_to.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/belongs_to.rb deleted file mode 100644 index 38e231826c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/belongs_to.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class BelongsTo < SingularAssociation #:nodoc: - def association_key_name - reflection.options[:primary_key] || klass && klass.primary_key - end - - def owner_key_name - reflection.foreign_key - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/collection_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/collection_association.rb deleted file mode 100644 index 26690bf16d..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/collection_association.rb +++ /dev/null @@ -1,17 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class CollectionAssociation < Association #:nodoc: - private - - def preload(preloader) - associated_records_by_owner(preloader).each do |owner, records| - association = owner.association(reflection.name) - association.loaded! - association.target.concat(records) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_many.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_many.rb deleted file mode 100644 index 20df1cc19a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_many.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class HasMany < CollectionAssociation #:nodoc: - def association_key_name - reflection.foreign_key - end - - def owner_key_name - reflection.active_record_primary_key - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_many_through.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_many_through.rb deleted file mode 100644 index 2029871f39..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_many_through.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class HasManyThrough < CollectionAssociation #:nodoc: - include ThroughAssociation - - def associated_records_by_owner(preloader) - records_by_owner = super - - if reflection_scope.distinct_value - records_by_owner.each_value(&:uniq!) - end - - records_by_owner - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_one.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_one.rb deleted file mode 100644 index c4add621ca..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_one.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class HasOne < SingularAssociation #:nodoc: - def association_key_name - reflection.foreign_key - end - - def owner_key_name - reflection.active_record_primary_key - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_one_through.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_one_through.rb deleted file mode 100644 index f063f85574..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/has_one_through.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class HasOneThrough < SingularAssociation #:nodoc: - include ThroughAssociation - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/singular_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/singular_association.rb deleted file mode 100644 index 5c5828262e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/singular_association.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - class SingularAssociation < Association #:nodoc: - private - - def preload(preloader) - associated_records_by_owner(preloader).each do |owner, associated_records| - record = associated_records.first - - association = owner.association(reflection.name) - association.target = record - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/through_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/through_association.rb deleted file mode 100644 index ea88a7dcfb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/preloader/through_association.rb +++ /dev/null @@ -1,115 +0,0 @@ -module ActiveRecord - module Associations - class Preloader - module ThroughAssociation #:nodoc: - def through_reflection - reflection.through_reflection - end - - def source_reflection - reflection.source_reflection - end - - def associated_records_by_owner(preloader) - preloader.preload(owners, - through_reflection.name, - through_scope) - - through_records = owners.map do |owner| - association = owner.association through_reflection.name - - center = target_records_from_association(association) - [owner, Array(center)] - end - - reset_association owners, through_reflection.name - - middle_records = through_records.flat_map { |(_, rec)| rec } - - preloaders = preloader.preload(middle_records, - source_reflection.name, - reflection_scope) - - @preloaded_records = preloaders.flat_map(&:preloaded_records) - - middle_to_pl = preloaders.each_with_object({}) do |pl, h| - pl.owners.each { |middle| - h[middle] = pl - } - end - - through_records.each_with_object({}) do |(lhs, center), records_by_owner| - pl_to_middle = center.group_by { |record| middle_to_pl[record] } - - records_by_owner[lhs] = pl_to_middle.flat_map do |pl, middles| - rhs_records = middles.flat_map { |r| - association = r.association source_reflection.name - - target_records_from_association(association) - }.compact - - # Respect the order on `reflection_scope` if it exists, else use the natural order. - if reflection_scope.values[:order].present? - @id_map ||= id_to_index_map @preloaded_records - rhs_records.sort_by { |rhs| @id_map[rhs] } - else - rhs_records - end - end - end - end - - private - - def id_to_index_map(ids) - id_map = {} - ids.each_with_index { |id, index| id_map[id] = index } - id_map - end - - def reset_association(owners, association_name) - should_reset = (through_scope != through_reflection.klass.unscoped) || - (reflection.options[:source_type] && through_reflection.collection?) - - # Don't cache the association - we would only be caching a subset - if should_reset - owners.each { |owner| - owner.association(association_name).reset - } - end - end - - def through_scope - scope = through_reflection.klass.unscoped - values = reflection_scope.values - - if options[:source_type] - scope.where! reflection.foreign_type => options[:source_type] - else - unless reflection_scope.where_clause.empty? - scope.includes_values = Array(values[:includes] || options[:source]) - scope.where_clause = reflection_scope.where_clause - if joins = values[:joins] - scope.joins!(source_reflection.name => joins) - end - if left_outer_joins = values[:left_outer_joins] - scope.left_outer_joins!(source_reflection.name => left_outer_joins) - end - end - - scope.references! values[:references] - if scope.eager_loading? && order_values = values[:order] - scope = scope.order(order_values) - end - end - - scope - end - - def target_records_from_association(association) - association.loaded? ? association.target : association.reader - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/singular_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/singular_association.rb deleted file mode 100644 index 91580a28d0..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/singular_association.rb +++ /dev/null @@ -1,75 +0,0 @@ -module ActiveRecord - module Associations - class SingularAssociation < Association #:nodoc: - # Implements the reader method, e.g. foo.bar for Foo.has_one :bar - def reader - if !loaded? || stale_target? - reload - end - - target - end - - # Implements the writer method, e.g. foo.bar= for Foo.belongs_to :bar - def writer(record) - replace(record) - end - - def build(attributes = {}) - record = build_record(attributes) - yield(record) if block_given? - set_new_record(record) - record - end - - # Implements the reload reader method, e.g. foo.reload_bar for - # Foo.has_one :bar - def force_reload_reader - klass.uncached { reload } - target - end - - private - - def create_scope - scope.scope_for_create.stringify_keys.except(klass.primary_key) - end - - def find_target - return scope.take if skip_statement_cache? - - conn = klass.connection - sc = reflection.association_scope_cache(conn, owner) do - StatementCache.create(conn) { |params| - as = AssociationScope.create { params.bind } - target_scope.merge(as.scope(self, conn)).limit(1) - } - end - - binds = AssociationScope.get_bind_values(owner, reflection.chain) - sc.execute(binds, klass, conn) do |record| - set_inverse_instance record - end.first - rescue ::RangeError - nil - end - - def replace(record) - raise NotImplementedError, "Subclasses must implement a replace(record) method" - end - - def set_new_record(record) - replace(record) - end - - def _create_record(attributes, raise_error = false) - record = build_record(attributes) - yield(record) if block_given? - saved = record.save - set_new_record(record) - raise RecordInvalid.new(record) if !saved && raise_error - record - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/through_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/through_association.rb deleted file mode 100644 index 80dfd477cf..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/associations/through_association.rb +++ /dev/null @@ -1,106 +0,0 @@ -module ActiveRecord - # = Active Record Through Association - module Associations - module ThroughAssociation #:nodoc: - delegate :source_reflection, :through_reflection, to: :reflection - - private - - # We merge in these scopes for two reasons: - # - # 1. To get the default_scope conditions for any of the other reflections in the chain - # 2. To get the type conditions for any STI models in the chain - def target_scope - scope = super - reflection.chain.drop(1).each do |reflection| - relation = reflection.klass.scope_for_association - scope.merge!( - relation.except(:select, :create_with, :includes, :preload, :joins, :eager_load) - ) - end - scope - end - - # Construct attributes for :through pointing to owner and associate. This is used by the - # methods which create and delete records on the association. - # - # We only support indirectly modifying through associations which have a belongs_to source. - # This is the "has_many :tags, through: :taggings" situation, where the join model - # typically has a belongs_to on both side. In other words, associations which could also - # be represented as has_and_belongs_to_many associations. - # - # We do not support creating/deleting records on the association where the source has - # some other type, because this opens up a whole can of worms, and in basically any - # situation it is more natural for the user to just create or modify their join records - # directly as required. - def construct_join_attributes(*records) - ensure_mutable - - if source_reflection.association_primary_key(reflection.klass) == reflection.klass.primary_key - join_attributes = { source_reflection.name => records } - else - join_attributes = { - source_reflection.foreign_key => - records.map { |record| - record.send(source_reflection.association_primary_key(reflection.klass)) - } - } - end - - if options[:source_type] - join_attributes[source_reflection.foreign_type] = - records.map { |record| record.class.base_class.name } - end - - if records.count == 1 - Hash[join_attributes.map { |k, v| [k, v.first] }] - else - join_attributes - end - end - - # Note: this does not capture all cases, for example it would be crazy to try to - # properly support stale-checking for nested associations. - def stale_state - if through_reflection.belongs_to? - owner[through_reflection.foreign_key] && owner[through_reflection.foreign_key].to_s - end - end - - def foreign_key_present? - through_reflection.belongs_to? && !owner[through_reflection.foreign_key].nil? - end - - def ensure_mutable - unless source_reflection.belongs_to? - if reflection.has_one? - raise HasOneThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection) - else - raise HasManyThroughCantAssociateThroughHasOneOrManyReflection.new(owner, reflection) - end - end - end - - def ensure_not_nested - if reflection.nested? - if reflection.has_one? - raise HasOneThroughNestedAssociationsAreReadonly.new(owner, reflection) - else - raise HasManyThroughNestedAssociationsAreReadonly.new(owner, reflection) - end - end - end - - def build_record(attributes) - inverse = source_reflection.inverse_of - target = through_association.target - - if inverse && target && !target.is_a?(Array) - attributes[inverse.foreign_key] = target.id - end - - super(attributes) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute.rb deleted file mode 100644 index 78662433eb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute.rb +++ /dev/null @@ -1,240 +0,0 @@ -module ActiveRecord - class Attribute # :nodoc: - class << self - def from_database(name, value, type) - FromDatabase.new(name, value, type) - end - - def from_user(name, value, type, original_attribute = nil) - FromUser.new(name, value, type, original_attribute) - end - - def with_cast_value(name, value, type) - WithCastValue.new(name, value, type) - end - - def null(name) - Null.new(name) - end - - def uninitialized(name, type) - Uninitialized.new(name, type) - end - end - - attr_reader :name, :value_before_type_cast, :type - - # This method should not be called directly. - # Use #from_database or #from_user - def initialize(name, value_before_type_cast, type, original_attribute = nil) - @name = name - @value_before_type_cast = value_before_type_cast - @type = type - @original_attribute = original_attribute - end - - def value - # `defined?` is cheaper than `||=` when we get back falsy values - @value = type_cast(value_before_type_cast) unless defined?(@value) - @value - end - - def original_value - if assigned? - original_attribute.original_value - else - type_cast(value_before_type_cast) - end - end - - def value_for_database - type.serialize(value) - end - - def changed? - changed_from_assignment? || changed_in_place? - end - - def changed_in_place? - has_been_read? && type.changed_in_place?(original_value_for_database, value) - end - - def forgetting_assignment - with_value_from_database(value_for_database) - end - - def with_value_from_user(value) - type.assert_valid_value(value) - self.class.from_user(name, value, type, original_attribute || self) - end - - def with_value_from_database(value) - self.class.from_database(name, value, type) - end - - def with_cast_value(value) - self.class.with_cast_value(name, value, type) - end - - def with_type(type) - if changed_in_place? - with_value_from_user(value).with_type(type) - else - self.class.new(name, value_before_type_cast, type, original_attribute) - end - end - - def type_cast(*) - raise NotImplementedError - end - - def initialized? - true - end - - def came_from_user? - false - end - - def has_been_read? - defined?(@value) - end - - def ==(other) - self.class == other.class && - name == other.name && - value_before_type_cast == other.value_before_type_cast && - type == other.type - end - alias eql? == - - def hash - [self.class, name, value_before_type_cast, type].hash - end - - def init_with(coder) - @name = coder["name"] - @value_before_type_cast = coder["value_before_type_cast"] - @type = coder["type"] - @original_attribute = coder["original_attribute"] - @value = coder["value"] if coder.map.key?("value") - end - - def encode_with(coder) - coder["name"] = name - coder["value_before_type_cast"] = value_before_type_cast unless value_before_type_cast.nil? - coder["type"] = type if type - coder["original_attribute"] = original_attribute if original_attribute - coder["value"] = value if defined?(@value) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :original_attribute - alias_method :assigned?, :original_attribute - - def original_value_for_database - if assigned? - original_attribute.original_value_for_database - else - _original_value_for_database - end - end - - private - def initialize_dup(other) - if defined?(@value) && @value.duplicable? - @value = @value.dup - end - end - - def changed_from_assignment? - assigned? && type.changed?(original_value, value, value_before_type_cast) - end - - def _original_value_for_database - type.serialize(original_value) - end - - class FromDatabase < Attribute # :nodoc: - def type_cast(value) - type.deserialize(value) - end - - def _original_value_for_database - value_before_type_cast - end - end - - class FromUser < Attribute # :nodoc: - def type_cast(value) - type.cast(value) - end - - def came_from_user? - true - end - end - - class WithCastValue < Attribute # :nodoc: - def type_cast(value) - value - end - - def changed_in_place? - false - end - end - - class Null < Attribute # :nodoc: - def initialize(name) - super(name, nil, Type.default_value) - end - - def type_cast(*) - nil - end - - def with_type(type) - self.class.with_cast_value(name, nil, type) - end - - def with_value_from_database(value) - raise ActiveModel::MissingAttributeError, "can't write unknown attribute `#{name}`" - end - alias_method :with_value_from_user, :with_value_from_database - end - - class Uninitialized < Attribute # :nodoc: - UNINITIALIZED_ORIGINAL_VALUE = Object.new - - def initialize(name, type) - super(name, nil, type) - end - - def value - if block_given? - yield name - end - end - - def original_value - UNINITIALIZED_ORIGINAL_VALUE - end - - def value_for_database - end - - def initialized? - false - end - - def with_type(type) - self.class.new(name, type) - end - end - private_constant :FromDatabase, :FromUser, :Null, :Uninitialized, :WithCastValue - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute/user_provided_default.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute/user_provided_default.rb deleted file mode 100644 index 57f8bbed76..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute/user_provided_default.rb +++ /dev/null @@ -1,30 +0,0 @@ -require "active_record/attribute" - -module ActiveRecord - class Attribute # :nodoc: - class UserProvidedDefault < FromUser # :nodoc: - def initialize(name, value, type, database_default) - @user_provided_value = value - super(name, value, type, database_default) - end - - def value_before_type_cast - if user_provided_value.is_a?(Proc) - @memoized_value_before_type_cast ||= user_provided_value.call - else - @user_provided_value - end - end - - def with_type(type) - self.class.new(name, user_provided_value, type, original_attribute) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :user_provided_value - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_assignment.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_assignment.rb deleted file mode 100644 index d0dfca0cac..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_assignment.rb +++ /dev/null @@ -1,91 +0,0 @@ -require "active_model/forbidden_attributes_protection" - -module ActiveRecord - module AttributeAssignment - extend ActiveSupport::Concern - include ActiveModel::AttributeAssignment - - # Alias for ActiveModel::AttributeAssignment#assign_attributes. See ActiveModel::AttributeAssignment. - def attributes=(attributes) - assign_attributes(attributes) - end - - private - - def _assign_attributes(attributes) - multi_parameter_attributes = {} - nested_parameter_attributes = {} - - attributes.each do |k, v| - if k.include?("(") - multi_parameter_attributes[k] = attributes.delete(k) - elsif v.is_a?(Hash) - nested_parameter_attributes[k] = attributes.delete(k) - end - end - super(attributes) - - assign_nested_parameter_attributes(nested_parameter_attributes) unless nested_parameter_attributes.empty? - assign_multiparameter_attributes(multi_parameter_attributes) unless multi_parameter_attributes.empty? - end - - # Assign any deferred nested attributes after the base attributes have been set. - def assign_nested_parameter_attributes(pairs) - pairs.each { |k, v| _assign_attribute(k, v) } - end - - # Instantiates objects for all attribute classes that needs more than one constructor parameter. This is done - # by calling new on the column type or aggregation type (through composed_of) object with these parameters. - # So having the pairs written_on(1) = "2004", written_on(2) = "6", written_on(3) = "24", will instantiate - # written_on (a date type) with Date.new("2004", "6", "24"). You can also specify a typecast character in the - # parentheses to have the parameters typecasted before they're used in the constructor. Use i for Integer and - # f for Float. If all the values for a given attribute are empty, the attribute will be set to +nil+. - def assign_multiparameter_attributes(pairs) - execute_callstack_for_multiparameter_attributes( - extract_callstack_for_multiparameter_attributes(pairs) - ) - end - - def execute_callstack_for_multiparameter_attributes(callstack) - errors = [] - callstack.each do |name, values_with_empty_parameters| - begin - if values_with_empty_parameters.each_value.all?(&:nil?) - values = nil - else - values = values_with_empty_parameters - end - send("#{name}=", values) - rescue => ex - errors << AttributeAssignmentError.new("error on assignment #{values_with_empty_parameters.values.inspect} to #{name} (#{ex.message})", ex, name) - end - end - unless errors.empty? - error_descriptions = errors.map(&:message).join(",") - raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]" - end - end - - def extract_callstack_for_multiparameter_attributes(pairs) - attributes = {} - - pairs.each do |(multiparameter_name, value)| - attribute_name = multiparameter_name.split("(").first - attributes[attribute_name] ||= {} - - parameter_value = value.empty? ? nil : type_cast_attribute_value(multiparameter_name, value) - attributes[attribute_name][find_parameter_position(multiparameter_name)] ||= parameter_value - end - - attributes - end - - def type_cast_attribute_value(multiparameter_name, value) - multiparameter_name =~ /\([0-9]*([if])\)/ ? value.send("to_" + $1) : value - end - - def find_parameter_position(multiparameter_name) - multiparameter_name.scan(/\(([0-9]*).*\)/).first.first.to_i - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_decorators.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_decorators.rb deleted file mode 100644 index c39e9ce4c5..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_decorators.rb +++ /dev/null @@ -1,89 +0,0 @@ -module ActiveRecord - module AttributeDecorators # :nodoc: - extend ActiveSupport::Concern - - included do - class_attribute :attribute_type_decorations, instance_accessor: false # :internal: - self.attribute_type_decorations = TypeDecorator.new - end - - module ClassMethods # :nodoc: - # This method is an internal API used to create class macros such as - # +serialize+, and features like time zone aware attributes. - # - # Used to wrap the type of an attribute in a new type. - # When the schema for a model is loaded, attributes with the same name as - # +column_name+ will have their type yielded to the given block. The - # return value of that block will be used instead. - # - # Subsequent calls where +column_name+ and +decorator_name+ are the same - # will override the previous decorator, not decorate twice. This can be - # used to create idempotent class macros like +serialize+ - def decorate_attribute_type(column_name, decorator_name, &block) - matcher = ->(name, _) { name == column_name.to_s } - key = "_#{column_name}_#{decorator_name}" - decorate_matching_attribute_types(matcher, key, &block) - end - - # This method is an internal API used to create higher level features like - # time zone aware attributes. - # - # When the schema for a model is loaded, +matcher+ will be called for each - # attribute with its name and type. If the matcher returns a truthy value, - # the type will then be yielded to the given block, and the return value - # of that block will replace the type. - # - # Subsequent calls to this method with the same value for +decorator_name+ - # will replace the previous decorator, not decorate twice. This can be - # used to ensure that class macros are idempotent. - def decorate_matching_attribute_types(matcher, decorator_name, &block) - reload_schema_from_cache - decorator_name = decorator_name.to_s - - # Create new hashes so we don't modify parent classes - self.attribute_type_decorations = attribute_type_decorations.merge(decorator_name => [matcher, block]) - end - - private - - def load_schema! - super - attribute_types.each do |name, type| - decorated_type = attribute_type_decorations.apply(name, type) - define_attribute(name, decorated_type) - end - end - end - - class TypeDecorator # :nodoc: - delegate :clear, to: :@decorations - - def initialize(decorations = {}) - @decorations = decorations - end - - def merge(*args) - TypeDecorator.new(@decorations.merge(*args)) - end - - def apply(name, type) - decorations = decorators_for(name, type) - decorations.inject(type) do |new_type, block| - block.call(new_type) - end - end - - private - - def decorators_for(name, type) - matching(name, type).map(&:last) - end - - def matching(name, type) - @decorations.values.select do |(matcher, _)| - matcher.call(name, type) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods.rb deleted file mode 100644 index ebe06566cc..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods.rb +++ /dev/null @@ -1,451 +0,0 @@ -require "active_support/core_ext/enumerable" -require "active_support/core_ext/string/filters" -require "mutex_m" -require "concurrent/map" - -module ActiveRecord - # = Active Record Attribute Methods - module AttributeMethods - extend ActiveSupport::Concern - include ActiveModel::AttributeMethods - - included do - initialize_generated_modules - include Read - include Write - include BeforeTypeCast - include Query - include PrimaryKey - include TimeZoneConversion - include Dirty - include Serialization - - delegate :column_for_attribute, to: :class - end - - AttrNames = Module.new { - def self.set_name_cache(name, value) - const_name = "ATTR_#{name}" - unless const_defined? const_name - const_set const_name, value.dup.freeze - end - end - } - - BLACKLISTED_CLASS_METHODS = %w(private public protected allocate new name parent superclass) - - class GeneratedAttributeMethods < Module; end # :nodoc: - - module ClassMethods - def inherited(child_class) #:nodoc: - child_class.initialize_generated_modules - super - end - - def initialize_generated_modules # :nodoc: - @generated_attribute_methods = GeneratedAttributeMethods.new { extend Mutex_m } - @attribute_methods_generated = false - include @generated_attribute_methods - - super - end - - # Generates all the attribute related methods for columns in the database - # accessors, mutators and query methods. - def define_attribute_methods # :nodoc: - return false if @attribute_methods_generated - # Use a mutex; we don't want two threads simultaneously trying to define - # attribute methods. - generated_attribute_methods.synchronize do - return false if @attribute_methods_generated - superclass.define_attribute_methods unless self == base_class - super(attribute_names) - @attribute_methods_generated = true - end - true - end - - def undefine_attribute_methods # :nodoc: - generated_attribute_methods.synchronize do - super if defined?(@attribute_methods_generated) && @attribute_methods_generated - @attribute_methods_generated = false - end - end - - # Raises an ActiveRecord::DangerousAttributeError exception when an - # \Active \Record method is defined in the model, otherwise +false+. - # - # class Person < ActiveRecord::Base - # def save - # 'already defined by Active Record' - # end - # end - # - # Person.instance_method_already_implemented?(:save) - # # => ActiveRecord::DangerousAttributeError: save is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name. - # - # Person.instance_method_already_implemented?(:name) - # # => false - def instance_method_already_implemented?(method_name) - if dangerous_attribute_method?(method_name) - raise DangerousAttributeError, "#{method_name} is defined by Active Record. Check to make sure that you don't have an attribute or method with the same name." - end - - if superclass == Base - super - else - # If ThisClass < ... < SomeSuperClass < ... < Base and SomeSuperClass - # defines its own attribute method, then we don't want to overwrite that. - defined = method_defined_within?(method_name, superclass, Base) && - ! superclass.instance_method(method_name).owner.is_a?(GeneratedAttributeMethods) - defined || super - end - end - - # A method name is 'dangerous' if it is already (re)defined by Active Record, but - # not by any ancestors. (So 'puts' is not dangerous but 'save' is.) - def dangerous_attribute_method?(name) # :nodoc: - method_defined_within?(name, Base) - end - - def method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc: - if klass.method_defined?(name) || klass.private_method_defined?(name) - if superklass.method_defined?(name) || superklass.private_method_defined?(name) - klass.instance_method(name).owner != superklass.instance_method(name).owner - else - true - end - else - false - end - end - - # A class method is 'dangerous' if it is already (re)defined by Active Record, but - # not by any ancestors. (So 'puts' is not dangerous but 'new' is.) - def dangerous_class_method?(method_name) - BLACKLISTED_CLASS_METHODS.include?(method_name.to_s) || class_method_defined_within?(method_name, Base) - end - - def class_method_defined_within?(name, klass, superklass = klass.superclass) # :nodoc: - if klass.respond_to?(name, true) - if superklass.respond_to?(name, true) - klass.method(name).owner != superklass.method(name).owner - else - true - end - else - false - end - end - - # Returns +true+ if +attribute+ is an attribute method and table exists, - # +false+ otherwise. - # - # class Person < ActiveRecord::Base - # end - # - # Person.attribute_method?('name') # => true - # Person.attribute_method?(:age=) # => true - # Person.attribute_method?(:nothing) # => false - def attribute_method?(attribute) - super || (table_exists? && column_names.include?(attribute.to_s.sub(/=$/, ""))) - end - - # Returns an array of column names as strings if it's not an abstract class and - # table exists. Otherwise it returns an empty array. - # - # class Person < ActiveRecord::Base - # end - # - # Person.attribute_names - # # => ["id", "created_at", "updated_at", "name", "age"] - def attribute_names - @attribute_names ||= if !abstract_class? && table_exists? - attribute_types.keys - else - [] - end - end - - # Returns true if the given attribute exists, otherwise false. - # - # class Person < ActiveRecord::Base - # end - # - # Person.has_attribute?('name') # => true - # Person.has_attribute?(:age) # => true - # Person.has_attribute?(:nothing) # => false - def has_attribute?(attr_name) - attribute_types.key?(attr_name.to_s) - end - - # Returns the column object for the named attribute. - # Returns a +ActiveRecord::ConnectionAdapters::NullColumn+ if the - # named attribute does not exist. - # - # class Person < ActiveRecord::Base - # end - # - # person = Person.new - # person.column_for_attribute(:name) # the result depends on the ConnectionAdapter - # # => # - # - # person.column_for_attribute(:nothing) - # # => #, ...> - def column_for_attribute(name) - name = name.to_s - columns_hash.fetch(name) do - ConnectionAdapters::NullColumn.new(name) - end - end - end - - # A Person object with a name attribute can ask person.respond_to?(:name), - # person.respond_to?(:name=), and person.respond_to?(:name?) - # which will all return +true+. It also defines the attribute methods if they have - # not been generated. - # - # class Person < ActiveRecord::Base - # end - # - # person = Person.new - # person.respond_to?(:name) # => true - # person.respond_to?(:name=) # => true - # person.respond_to?(:name?) # => true - # person.respond_to?('age') # => true - # person.respond_to?('age=') # => true - # person.respond_to?('age?') # => true - # person.respond_to?(:nothing) # => false - def respond_to?(name, include_private = false) - return false unless super - - case name - when :to_partial_path - name = "to_partial_path".freeze - when :to_model - name = "to_model".freeze - else - name = name.to_s - end - - # If the result is true then check for the select case. - # For queries selecting a subset of columns, return false for unselected columns. - # We check defined?(@attributes) not to issue warnings if called on objects that - # have been allocated but not yet initialized. - if defined?(@attributes) && self.class.column_names.include?(name) - return has_attribute?(name) - end - - return true - end - - # Returns +true+ if the given attribute is in the attributes hash, otherwise +false+. - # - # class Person < ActiveRecord::Base - # end - # - # person = Person.new - # person.has_attribute?(:name) # => true - # person.has_attribute?('age') # => true - # person.has_attribute?(:nothing) # => false - def has_attribute?(attr_name) - @attributes.key?(attr_name.to_s) - end - - # Returns an array of names for the attributes available on this object. - # - # class Person < ActiveRecord::Base - # end - # - # person = Person.new - # person.attribute_names - # # => ["id", "created_at", "updated_at", "name", "age"] - def attribute_names - @attributes.keys - end - - # Returns a hash of all the attributes with their names as keys and the values of the attributes as values. - # - # class Person < ActiveRecord::Base - # end - # - # person = Person.create(name: 'Francesco', age: 22) - # person.attributes - # # => {"id"=>3, "created_at"=>Sun, 21 Oct 2012 04:53:04, "updated_at"=>Sun, 21 Oct 2012 04:53:04, "name"=>"Francesco", "age"=>22} - def attributes - @attributes.to_hash - end - - # Returns an #inspect-like string for the value of the - # attribute +attr_name+. String attributes are truncated up to 50 - # characters, Date and Time attributes are returned in the - # :db format. Other attributes return the value of - # #inspect without modification. - # - # person = Person.create!(name: 'David Heinemeier Hansson ' * 3) - # - # person.attribute_for_inspect(:name) - # # => "\"David Heinemeier Hansson David Heinemeier Hansson ...\"" - # - # person.attribute_for_inspect(:created_at) - # # => "\"2012-10-22 00:15:07\"" - # - # person.attribute_for_inspect(:tag_ids) - # # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]" - def attribute_for_inspect(attr_name) - value = read_attribute(attr_name) - - if value.is_a?(String) && value.length > 50 - "#{value[0, 50]}...".inspect - elsif value.is_a?(Date) || value.is_a?(Time) - %("#{value.to_s(:db)}") - else - value.inspect - end - end - - # Returns +true+ if the specified +attribute+ has been set by the user or by a - # database load and is neither +nil+ nor empty? (the latter only applies - # to objects that respond to empty?, most notably Strings). Otherwise, +false+. - # Note that it always returns +true+ with boolean attributes. - # - # class Task < ActiveRecord::Base - # end - # - # task = Task.new(title: '', is_done: false) - # task.attribute_present?(:title) # => false - # task.attribute_present?(:is_done) # => true - # task.title = 'Buy milk' - # task.is_done = true - # task.attribute_present?(:title) # => true - # task.attribute_present?(:is_done) # => true - def attribute_present?(attribute) - value = _read_attribute(attribute) - !value.nil? && !(value.respond_to?(:empty?) && value.empty?) - end - - # Returns the value of the attribute identified by attr_name after it has been typecast (for example, - # "2004-12-12" in a date column is cast to a date object, like Date.new(2004, 12, 12)). It raises - # ActiveModel::MissingAttributeError if the identified attribute is missing. - # - # Note: +:id+ is always present. - # - # class Person < ActiveRecord::Base - # belongs_to :organization - # end - # - # person = Person.new(name: 'Francesco', age: '22') - # person[:name] # => "Francesco" - # person[:age] # => 22 - # - # person = Person.select('id').first - # person[:name] # => ActiveModel::MissingAttributeError: missing attribute: name - # person[:organization_id] # => ActiveModel::MissingAttributeError: missing attribute: organization_id - def [](attr_name) - read_attribute(attr_name) { |n| missing_attribute(n, caller) } - end - - # Updates the attribute identified by attr_name with the specified +value+. - # (Alias for the protected #write_attribute method). - # - # class Person < ActiveRecord::Base - # end - # - # person = Person.new - # person[:age] = '22' - # person[:age] # => 22 - # person[:age].class # => Integer - def []=(attr_name, value) - write_attribute(attr_name, value) - end - - # Returns the name of all database fields which have been read from this - # model. This can be useful in development mode to determine which fields - # need to be selected. For performance critical pages, selecting only the - # required fields can be an easy performance win (assuming you aren't using - # all of the fields on the model). - # - # For example: - # - # class PostsController < ActionController::Base - # after_action :print_accessed_fields, only: :index - # - # def index - # @posts = Post.all - # end - # - # private - # - # def print_accessed_fields - # p @posts.first.accessed_fields - # end - # end - # - # Which allows you to quickly change your code to: - # - # class PostsController < ActionController::Base - # def index - # @posts = Post.select(:id, :title, :author_id, :updated_at) - # end - # end - def accessed_fields - @attributes.accessed - end - - protected - - def attribute_method?(attr_name) # :nodoc: - # We check defined? because Syck calls respond_to? before actually calling initialize. - defined?(@attributes) && @attributes.key?(attr_name) - end - - private - - def arel_attributes_with_values_for_create(attribute_names) - arel_attributes_with_values(attributes_for_create(attribute_names)) - end - - def arel_attributes_with_values_for_update(attribute_names) - arel_attributes_with_values(attributes_for_update(attribute_names)) - end - - # Returns a Hash of the Arel::Attributes and attribute values that have been - # typecasted for use in an Arel insert/update method. - def arel_attributes_with_values(attribute_names) - attrs = {} - arel_table = self.class.arel_table - - attribute_names.each do |name| - attrs[arel_table[name]] = typecasted_attribute_value(name) - end - attrs - end - - # Filters the primary keys and readonly attributes from the attribute names. - def attributes_for_update(attribute_names) - attribute_names.reject do |name| - readonly_attribute?(name) - end - end - - # Filters out the primary keys, from the attribute names, when the primary - # key is to be generated (e.g. the id attribute has no value). - def attributes_for_create(attribute_names) - attribute_names.reject do |name| - pk_attribute?(name) && id.nil? - end - end - - def readonly_attribute?(name) - self.class.readonly_attributes.include?(name) - end - - def pk_attribute?(name) - name == self.class.primary_key - end - - def typecasted_attribute_value(name) - _read_attribute(name) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/before_type_cast.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/before_type_cast.rb deleted file mode 100644 index 115eb1ef3f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/before_type_cast.rb +++ /dev/null @@ -1,76 +0,0 @@ -module ActiveRecord - module AttributeMethods - # = Active Record Attribute Methods Before Type Cast - # - # ActiveRecord::AttributeMethods::BeforeTypeCast provides a way to - # read the value of the attributes before typecasting and deserialization. - # - # class Task < ActiveRecord::Base - # end - # - # task = Task.new(id: '1', completed_on: '2012-10-21') - # task.id # => 1 - # task.completed_on # => Sun, 21 Oct 2012 - # - # task.attributes_before_type_cast - # # => {"id"=>"1", "completed_on"=>"2012-10-21", ... } - # task.read_attribute_before_type_cast('id') # => "1" - # task.read_attribute_before_type_cast('completed_on') # => "2012-10-21" - # - # In addition to #read_attribute_before_type_cast and #attributes_before_type_cast, - # it declares a method for all attributes with the *_before_type_cast - # suffix. - # - # task.id_before_type_cast # => "1" - # task.completed_on_before_type_cast # => "2012-10-21" - module BeforeTypeCast - extend ActiveSupport::Concern - - included do - attribute_method_suffix "_before_type_cast" - attribute_method_suffix "_came_from_user?" - end - - # Returns the value of the attribute identified by +attr_name+ before - # typecasting and deserialization. - # - # class Task < ActiveRecord::Base - # end - # - # task = Task.new(id: '1', completed_on: '2012-10-21') - # task.read_attribute('id') # => 1 - # task.read_attribute_before_type_cast('id') # => '1' - # task.read_attribute('completed_on') # => Sun, 21 Oct 2012 - # task.read_attribute_before_type_cast('completed_on') # => "2012-10-21" - # task.read_attribute_before_type_cast(:completed_on) # => "2012-10-21" - def read_attribute_before_type_cast(attr_name) - @attributes[attr_name.to_s].value_before_type_cast - end - - # Returns a hash of attributes before typecasting and deserialization. - # - # class Task < ActiveRecord::Base - # end - # - # task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21') - # task.attributes - # # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil} - # task.attributes_before_type_cast - # # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil} - def attributes_before_type_cast - @attributes.values_before_type_cast - end - - private - - # Handle *_before_type_cast for method_missing. - def attribute_before_type_cast(attribute_name) - read_attribute_before_type_cast(attribute_name) - end - - def attribute_came_from_user?(attribute_name) - @attributes[attribute_name].came_from_user? - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/dirty.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/dirty.rb deleted file mode 100644 index 9ee5e96494..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/dirty.rb +++ /dev/null @@ -1,334 +0,0 @@ -# frozen_string_literal: true -require "active_support/core_ext/module/attribute_accessors" -require "active_record/attribute_mutation_tracker" - -module ActiveRecord - module AttributeMethods - module Dirty - extend ActiveSupport::Concern - - include ActiveModel::Dirty - - included do - if self < ::ActiveRecord::Timestamp - raise "You cannot include Dirty after Timestamp" - end - - class_attribute :partial_writes, instance_writer: false - self.partial_writes = true - - after_create { changes_internally_applied } - after_update { changes_internally_applied } - - # Attribute methods for "changed in last call to save?" - attribute_method_affix(prefix: "saved_change_to_", suffix: "?") - attribute_method_prefix("saved_change_to_") - attribute_method_suffix("_before_last_save") - - # Attribute methods for "will change if I call save?" - attribute_method_affix(prefix: "will_save_change_to_", suffix: "?") - attribute_method_suffix("_change_to_be_saved", "_in_database") - end - - # Attempts to +save+ the record and clears changed attributes if successful. - def save(*) - if status = super - changes_applied - end - status - end - - # Attempts to save! the record and clears changed attributes if successful. - def save!(*) - super.tap do - changes_applied - end - end - - # reload the record and clears changed attributes. - def reload(*) - super.tap do - @previous_mutation_tracker = nil - clear_mutation_trackers - @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new - end - end - - def initialize_dup(other) # :nodoc: - super - @attributes = self.class._default_attributes.map do |attr| - attr.with_value_from_user(@attributes.fetch_value(attr.name)) - end - clear_mutation_trackers - end - - def changes_internally_applied # :nodoc: - @mutations_before_last_save = mutations_from_database - forget_attribute_assignments - @mutations_from_database = AttributeMutationTracker.new(@attributes) - end - - def changes_applied # :nodoc: - @previous_mutation_tracker = mutation_tracker - @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new - @mutation_tracker = nil - @mutations_from_database = nil - end - - def clear_changes_information # :nodoc: - @previous_mutation_tracker = nil - @changed_attributes = ActiveSupport::HashWithIndifferentAccess.new - forget_attribute_assignments - clear_mutation_trackers - end - - def raw_write_attribute(attr_name, *) # :nodoc: - result = super - clear_attribute_change(attr_name) - result - end - - def clear_attribute_changes(attr_names) # :nodoc: - super - attr_names.each do |attr_name| - clear_attribute_change(attr_name) - end - end - - def changed_attributes # :nodoc: - # This should only be set by methods which will call changed_attributes - # multiple times when it is known that the computed value cannot change. - if defined?(@cached_changed_attributes) - @cached_changed_attributes - else - emit_warning_if_needed("changed_attributes", "saved_changes.transform_values(&:first)") - super.reverse_merge(mutation_tracker.changed_values).freeze - end - end - - def changes # :nodoc: - cache_changed_attributes do - emit_warning_if_needed("changes", "saved_changes") - super - end - end - - def previous_changes # :nodoc: - unless previous_mutation_tracker.equal?(mutations_before_last_save) - ActiveSupport::Deprecation.warn(<<-EOW.strip_heredoc) - The behavior of `previous_changes` inside of after callbacks is - deprecated without replacement. In the next release of Rails, - this method inside of `after_save` will return the changes that - were just saved. - EOW - end - previous_mutation_tracker.changes - end - - def attribute_changed_in_place?(attr_name) # :nodoc: - mutation_tracker.changed_in_place?(attr_name) - end - - # Did this attribute change when we last saved? This method can be invoked - # as `saved_change_to_name?` instead of `saved_change_to_attribute?("name")`. - # Behaves similarly to +attribute_changed?+. This method is useful in - # after callbacks to determine if the call to save changed a certain - # attribute. - # - # ==== Options - # - # +from+ When passed, this method will return false unless the original - # value is equal to the given option - # - # +to+ When passed, this method will return false unless the value was - # changed to the given value - def saved_change_to_attribute?(attr_name, **options) - mutations_before_last_save.changed?(attr_name, **options) - end - - # Returns the change to an attribute during the last save. If the - # attribute was changed, the result will be an array containing the - # original value and the saved value. - # - # Behaves similarly to +attribute_change+. This method is useful in after - # callbacks, to see the change in an attribute that just occurred - # - # This method can be invoked as `saved_change_to_name` in instead of - # `saved_change_to_attribute("name")` - def saved_change_to_attribute(attr_name) - mutations_before_last_save.change_to_attribute(attr_name) - end - - # Returns the original value of an attribute before the last save. - # Behaves similarly to +attribute_was+. This method is useful in after - # callbacks to get the original value of an attribute before the save that - # just occurred - def attribute_before_last_save(attr_name) - mutations_before_last_save.original_value(attr_name) - end - - # Did the last call to `save` have any changes to change? - def saved_changes? - mutations_before_last_save.any_changes? - end - - # Returns a hash containing all the changes that were just saved. - def saved_changes - mutations_before_last_save.changes - end - - # Alias for `attribute_changed?` - def will_save_change_to_attribute?(attr_name, **options) - mutations_from_database.changed?(attr_name, **options) - end - - # Alias for `attribute_change` - def attribute_change_to_be_saved(attr_name) - mutations_from_database.change_to_attribute(attr_name) - end - - # Alias for `attribute_was` - def attribute_in_database(attr_name) - mutations_from_database.original_value(attr_name) - end - - # Alias for `changed?` - def has_changes_to_save? - mutations_from_database.any_changes? - end - - # Alias for `changes` - def changes_to_save - mutations_from_database.changes - end - - # Alias for `changed` - def changed_attribute_names_to_save - mutations_from_database.changed_attribute_names - end - - # Alias for `changed_attributes` - def attributes_in_database - mutations_from_database.changed_values - end - - def attribute_was(*) - emit_warning_if_needed("attribute_was", "attribute_before_last_save") - super - end - - def attribute_change(*) - emit_warning_if_needed("attribute_change", "saved_change_to_attribute") - super - end - - def attribute_changed?(*) - emit_warning_if_needed("attribute_changed?", "saved_change_to_attribute?") - super - end - - def changed?(*) - emit_warning_if_needed("changed?", "saved_changes?") - super - end - - def changed(*) - emit_warning_if_needed("changed", "saved_changes.keys") - super - end - - private - - def mutation_tracker - unless defined?(@mutation_tracker) - @mutation_tracker = nil - end - @mutation_tracker ||= AttributeMutationTracker.new(@attributes) - end - - def emit_warning_if_needed(method_name, new_method_name) - unless mutation_tracker.equal?(mutations_from_database) - ActiveSupport::Deprecation.warn(<<-EOW.squish) - The behavior of `#{method_name}` inside of after callbacks will - be changing in the next version of Rails. The new return value will reflect the - behavior of calling the method after `save` returned (e.g. the opposite of what - it returns now). To maintain the current behavior, use `#{new_method_name}` - instead. - EOW - end - end - - def mutations_from_database - unless defined?(@mutations_from_database) - @mutations_from_database = nil - end - @mutations_from_database ||= mutation_tracker - end - - def changes_include?(attr_name) - super || mutation_tracker.changed?(attr_name) - end - - def clear_attribute_change(attr_name) - mutation_tracker.forget_change(attr_name) - mutations_from_database.forget_change(attr_name) - end - - def attribute_will_change!(attr_name) - super - if self.class.has_attribute?(attr_name) - mutations_from_database.force_change(attr_name) - else - ActiveSupport::Deprecation.warn(<<-EOW.squish) - #{attr_name} is not an attribute known to Active Record. - This behavior is deprecated and will be removed in the next - version of Rails. If you'd like #{attr_name} to be managed - by Active Record, add `attribute :#{attr_name} to your class. - EOW - mutations_from_database.deprecated_force_change(attr_name) - end - end - - def _update_record(*) - partial_writes? ? super(keys_for_partial_write) : super - end - - def _create_record(*) - partial_writes? ? super(keys_for_partial_write) : super - end - - def keys_for_partial_write - changed_attribute_names_to_save & self.class.column_names - end - - def forget_attribute_assignments - @attributes = @attributes.map(&:forgetting_assignment) - end - - def clear_mutation_trackers - @mutation_tracker = nil - @mutations_from_database = nil - @mutations_before_last_save = nil - end - - def previous_mutation_tracker - @previous_mutation_tracker ||= NullMutationTracker.instance - end - - def mutations_before_last_save - @mutations_before_last_save ||= previous_mutation_tracker - end - - def cache_changed_attributes - @cached_changed_attributes = changed_attributes - yield - ensure - clear_changed_attributes_cache - end - - def clear_changed_attributes_cache - remove_instance_variable(:@cached_changed_attributes) if defined?(@cached_changed_attributes) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/primary_key.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/primary_key.rb deleted file mode 100644 index b5fd0cb370..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/primary_key.rb +++ /dev/null @@ -1,142 +0,0 @@ -require "set" - -module ActiveRecord - module AttributeMethods - module PrimaryKey - extend ActiveSupport::Concern - - # Returns this record's primary key value wrapped in an array if one is - # available. - def to_key - sync_with_transaction_state - key = id - [key] if key - end - - # Returns the primary key value. - def id - if pk = self.class.primary_key - sync_with_transaction_state - _read_attribute(pk) - end - end - - # Sets the primary key value. - def id=(value) - sync_with_transaction_state - write_attribute(self.class.primary_key, value) if self.class.primary_key - end - - # Queries the primary key value. - def id? - sync_with_transaction_state - query_attribute(self.class.primary_key) - end - - # Returns the primary key value before type cast. - def id_before_type_cast - sync_with_transaction_state - read_attribute_before_type_cast(self.class.primary_key) - end - - # Returns the primary key previous value. - def id_was - sync_with_transaction_state - attribute_was(self.class.primary_key) - end - - def id_in_database - sync_with_transaction_state - attribute_in_database(self.class.primary_key) - end - - private - - def attribute_method?(attr_name) - attr_name == "id" || super - end - - module ClassMethods - ID_ATTRIBUTE_METHODS = %w(id id= id? id_before_type_cast id_was id_in_database).to_set - - def instance_method_already_implemented?(method_name) - super || primary_key && ID_ATTRIBUTE_METHODS.include?(method_name) - end - - def dangerous_attribute_method?(method_name) - super && !ID_ATTRIBUTE_METHODS.include?(method_name) - end - - # Defines the primary key field -- can be overridden in subclasses. - # Overwriting will negate any effect of the +primary_key_prefix_type+ - # setting, though. - def primary_key - @primary_key = reset_primary_key unless defined? @primary_key - @primary_key - end - - # Returns a quoted version of the primary key name, used to construct - # SQL statements. - def quoted_primary_key - @quoted_primary_key ||= connection.quote_column_name(primary_key) - end - - def reset_primary_key #:nodoc: - if self == base_class - self.primary_key = get_primary_key(base_class.name) - else - self.primary_key = base_class.primary_key - end - end - - def get_primary_key(base_name) #:nodoc: - if base_name && primary_key_prefix_type == :table_name - base_name.foreign_key(false) - elsif base_name && primary_key_prefix_type == :table_name_with_underscore - base_name.foreign_key - else - if ActiveRecord::Base != self && table_exists? - pk = connection.schema_cache.primary_keys(table_name) - suppress_composite_primary_key(pk) - else - "id" - end - end - end - - # Sets the name of the primary key column. - # - # class Project < ActiveRecord::Base - # self.primary_key = 'sysid' - # end - # - # You can also define the #primary_key method yourself: - # - # class Project < ActiveRecord::Base - # def self.primary_key - # 'foo_' + super - # end - # end - # - # Project.primary_key # => "foo_id" - def primary_key=(value) - @primary_key = value && value.to_s - @quoted_primary_key = nil - @attributes_builder = nil - end - - private - - def suppress_composite_primary_key(pk) - return pk unless pk.is_a?(Array) - - warn <<-WARNING.strip_heredoc - WARNING: Active Record does not support composite primary key. - - #{table_name} has composite primary key. Composite primary key is ignored. - WARNING - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/query.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/query.rb deleted file mode 100644 index 10498f4322..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/query.rb +++ /dev/null @@ -1,40 +0,0 @@ -module ActiveRecord - module AttributeMethods - module Query - extend ActiveSupport::Concern - - included do - attribute_method_suffix "?" - end - - def query_attribute(attr_name) - value = self[attr_name] - - case value - when true then true - when false, nil then false - else - column = self.class.columns_hash[attr_name] - if column.nil? - if Numeric === value || value !~ /[^0-9]/ - !value.to_i.zero? - else - return false if ActiveModel::Type::Boolean::FALSE_VALUES.include?(value) - !value.blank? - end - elsif value.respond_to?(:zero?) - !value.zero? - else - !value.blank? - end - end - end - - private - # Handle *? for method_missing. - def attribute?(attribute_name) - query_attribute(attribute_name) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/read.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/read.rb deleted file mode 100644 index fdc4bf6621..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/read.rb +++ /dev/null @@ -1,79 +0,0 @@ -module ActiveRecord - module AttributeMethods - module Read - extend ActiveSupport::Concern - - module ClassMethods - private - - # We want to generate the methods via module_eval rather than - # define_method, because define_method is slower on dispatch. - # Evaluating many similar methods may use more memory as the instruction - # sequences are duplicated and cached (in MRI). define_method may - # be slower on dispatch, but if you're careful about the closure - # created, then define_method will consume much less memory. - # - # But sometimes the database might return columns with - # characters that are not allowed in normal method names (like - # 'my_column(omg)'. So to work around this we first define with - # the __temp__ identifier, and then use alias method to rename - # it to what we want. - # - # We are also defining a constant to hold the frozen string of - # the attribute name. Using a constant means that we do not have - # to allocate an object on each call to the attribute method. - # Making it frozen means that it doesn't get duped when used to - # key the @attributes in read_attribute. - def define_method_attribute(name) - safe_name = name.unpack("h*".freeze).first - temp_method = "__temp__#{safe_name}" - - ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name - - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 - def #{temp_method} - name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} - _read_attribute(name) { |n| missing_attribute(n, caller) } - end - STR - - generated_attribute_methods.module_eval do - alias_method name, temp_method - undef_method temp_method - end - end - end - - # Returns the value of the attribute identified by attr_name after - # it has been typecast (for example, "2004-12-12" in a date column is cast - # to a date object, like Date.new(2004, 12, 12)). - def read_attribute(attr_name, &block) - name = if self.class.attribute_alias?(attr_name) - self.class.attribute_alias(attr_name).to_s - else - attr_name.to_s - end - - name = self.class.primary_key if name == "id".freeze && self.class.primary_key - _read_attribute(name, &block) - end - - # This method exists to avoid the expensive primary_key check internally, without - # breaking compatibility with the read_attribute API - if defined?(JRUBY_VERSION) - # This form is significantly faster on JRuby, and this is one of our biggest hotspots. - # https://github.com/jruby/jruby/pull/2562 - def _read_attribute(attr_name, &block) # :nodoc - @attributes.fetch_value(attr_name.to_s, &block) - end - else - def _read_attribute(attr_name) # :nodoc: - @attributes.fetch_value(attr_name.to_s) { |n| yield n if block_given? } - end - end - - alias :attribute :_read_attribute - private :attribute - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/serialization.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/serialization.rb deleted file mode 100644 index 4d9aff76cc..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/serialization.rb +++ /dev/null @@ -1,67 +0,0 @@ -module ActiveRecord - module AttributeMethods - module Serialization - extend ActiveSupport::Concern - - module ClassMethods - # If you have an attribute that needs to be saved to the database as an - # object, and retrieved as the same object, then specify the name of that - # attribute using this method and it will be handled automatically. The - # serialization is done through YAML. If +class_name+ is specified, the - # serialized object must be of that class on assignment and retrieval. - # Otherwise SerializationTypeMismatch will be raised. - # - # Empty objects as {}, in the case of +Hash+, or [], in the case of - # +Array+, will always be persisted as null. - # - # Keep in mind that database adapters handle certain serialization tasks - # for you. For instance: +json+ and +jsonb+ types in PostgreSQL will be - # converted between JSON object/array syntax and Ruby +Hash+ or +Array+ - # objects transparently. There is no need to use #serialize in this - # case. - # - # For more complex cases, such as conversion to or from your application - # domain objects, consider using the ActiveRecord::Attributes API. - # - # ==== Parameters - # - # * +attr_name+ - The field name that should be serialized. - # * +class_name_or_coder+ - Optional, a coder object, which responds to +.load+ and +.dump+ - # or a class name that the object type should be equal to. - # - # ==== Example - # - # # Serialize a preferences attribute. - # class User < ActiveRecord::Base - # serialize :preferences - # end - # - # # Serialize preferences using JSON as coder. - # class User < ActiveRecord::Base - # serialize :preferences, JSON - # end - # - # # Serialize preferences as Hash using YAML coder. - # class User < ActiveRecord::Base - # serialize :preferences, Hash - # end - def serialize(attr_name, class_name_or_coder = Object) - # When ::JSON is used, force it to go through the Active Support JSON encoder - # to ensure special objects (e.g. Active Record models) are dumped correctly - # using the #as_json hook. - coder = if class_name_or_coder == ::JSON - Coders::JSON - elsif [:load, :dump].all? { |x| class_name_or_coder.respond_to?(x) } - class_name_or_coder - else - Coders::YAMLColumn.new(attr_name, class_name_or_coder) - end - - decorate_attribute_type(attr_name, :serialize) do |type| - Type::Serialized.new(type, coder) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/time_zone_conversion.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/time_zone_conversion.rb deleted file mode 100644 index 321d039ed4..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/time_zone_conversion.rb +++ /dev/null @@ -1,93 +0,0 @@ -module ActiveRecord - module AttributeMethods - module TimeZoneConversion - class TimeZoneConverter < DelegateClass(Type::Value) # :nodoc: - def deserialize(value) - convert_time_to_time_zone(super) - end - - def cast(value) - return if value.nil? - - if value.is_a?(Hash) - set_time_zone_without_conversion(super) - elsif value.respond_to?(:in_time_zone) - begin - super(user_input_in_time_zone(value)) || super - rescue ArgumentError - nil - end - else - map_avoiding_infinite_recursion(super) { |v| cast(v) } - end - end - - private - - def convert_time_to_time_zone(value) - return if value.nil? - - if value.acts_like?(:time) - value.in_time_zone - elsif value.is_a?(::Float) - value - else - map_avoiding_infinite_recursion(value) { |v| convert_time_to_time_zone(v) } - end - end - - def set_time_zone_without_conversion(value) - ::Time.zone.local_to_utc(value).try(:in_time_zone) if value - end - - def map_avoiding_infinite_recursion(value) - map(value) do |v| - if value.equal?(v) - nil - else - yield(v) - end - end - end - end - - extend ActiveSupport::Concern - - included do - mattr_accessor :time_zone_aware_attributes, instance_writer: false - self.time_zone_aware_attributes = false - - class_attribute :skip_time_zone_conversion_for_attributes, instance_writer: false - self.skip_time_zone_conversion_for_attributes = [] - - class_attribute :time_zone_aware_types, instance_writer: false - self.time_zone_aware_types = [:datetime, :time] - end - - module ClassMethods - private - - def inherited(subclass) - super - # We need to apply this decorator here, rather than on module inclusion. The closure - # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the - # sub class being decorated. As such, changes to `time_zone_aware_attributes`, or - # `skip_time_zone_conversion_for_attributes` would not be picked up. - subclass.class_eval do - matcher = ->(name, type) { create_time_zone_conversion_attribute?(name, type) } - decorate_matching_attribute_types(matcher, :_time_zone_conversion) do |type| - TimeZoneConverter.new(type) - end - end - end - - def create_time_zone_conversion_attribute?(name, cast_type) - enabled_for_column = time_zone_aware_attributes && - !skip_time_zone_conversion_for_attributes.include?(name.to_sym) - - enabled_for_column && time_zone_aware_types.include?(cast_type.type) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/write.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/write.rb deleted file mode 100644 index 75c5a1a600..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_methods/write.rb +++ /dev/null @@ -1,56 +0,0 @@ -module ActiveRecord - module AttributeMethods - module Write - extend ActiveSupport::Concern - - included do - attribute_method_suffix "=" - end - - module ClassMethods - private - - def define_method_attribute=(name) - safe_name = name.unpack("h*".freeze).first - ActiveRecord::AttributeMethods::AttrNames.set_name_cache safe_name, name - - generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 - def __temp__#{safe_name}=(value) - name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} - write_attribute(name, value) - end - alias_method #{(name + '=').inspect}, :__temp__#{safe_name}= - undef_method :__temp__#{safe_name}= - STR - end - end - - # Updates the attribute identified by attr_name with the - # specified +value+. Empty strings for Integer and Float columns are - # turned into +nil+. - def write_attribute(attr_name, value) - name = if self.class.attribute_alias?(attr_name) - self.class.attribute_alias(attr_name).to_s - else - attr_name.to_s - end - - name = self.class.primary_key if name == "id".freeze && self.class.primary_key - @attributes.write_from_user(name, value) - value - end - - def raw_write_attribute(attr_name, value) # :nodoc: - name = attr_name.to_s - @attributes.write_cast_value(name, value) - value - end - - private - # Handle *= for method_missing. - def attribute=(attribute_name, value) - write_attribute(attribute_name, value) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_mutation_tracker.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_mutation_tracker.rb deleted file mode 100644 index 1b11eabd22..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_mutation_tracker.rb +++ /dev/null @@ -1,122 +0,0 @@ -module ActiveRecord - class AttributeMutationTracker # :nodoc: - OPTION_NOT_GIVEN = Object.new - - def initialize(attributes) - @attributes = attributes - @forced_changes = Set.new - @deprecated_forced_changes = Set.new - end - - def changed_attribute_names - attr_names.select { |attr_name| changed?(attr_name) } - end - - def changed_values - attr_names.each_with_object({}.with_indifferent_access) do |attr_name, result| - if changed?(attr_name) - result[attr_name] = attributes[attr_name].original_value - end - end - end - - def changes - attr_names.each_with_object({}.with_indifferent_access) do |attr_name, result| - change = change_to_attribute(attr_name) - if change - result.merge!(attr_name => change) - end - end - end - - def change_to_attribute(attr_name) - attr_name = attr_name.to_s - if changed?(attr_name) - [attributes[attr_name].original_value, attributes.fetch_value(attr_name)] - end - end - - def any_changes? - attr_names.any? { |attr| changed?(attr) } || deprecated_forced_changes.any? - end - - def changed?(attr_name, from: OPTION_NOT_GIVEN, to: OPTION_NOT_GIVEN) - attr_name = attr_name.to_s - forced_changes.include?(attr_name) || - attributes[attr_name].changed? && - (OPTION_NOT_GIVEN == from || attributes[attr_name].original_value == from) && - (OPTION_NOT_GIVEN == to || attributes[attr_name].value == to) - end - - def changed_in_place?(attr_name) - attributes[attr_name.to_s].changed_in_place? - end - - def forget_change(attr_name) - attr_name = attr_name.to_s - attributes[attr_name] = attributes[attr_name].forgetting_assignment - forced_changes.delete(attr_name) - end - - def original_value(attr_name) - attributes[attr_name.to_s].original_value - end - - def force_change(attr_name) - forced_changes << attr_name.to_s - end - - def deprecated_force_change(attr_name) - deprecated_forced_changes << attr_name.to_s - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :attributes, :forced_changes, :deprecated_forced_changes - - private - - def attr_names - attributes.keys - end - end - - class NullMutationTracker # :nodoc: - include Singleton - - def changed_attribute_names(*) - [] - end - - def changed_values(*) - {} - end - - def changes(*) - {} - end - - def change_to_attribute(attr_name) - end - - def any_changes?(*) - false - end - - def changed?(*) - false - end - - def changed_in_place?(*) - false - end - - def forget_change(*) - end - - def original_value(*) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set.rb deleted file mode 100644 index 163c4dfd62..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set.rb +++ /dev/null @@ -1,113 +0,0 @@ -require "active_record/attribute_set/builder" -require "active_record/attribute_set/yaml_encoder" - -module ActiveRecord - class AttributeSet # :nodoc: - delegate :each_value, :fetch, :except, to: :attributes - - def initialize(attributes) - @attributes = attributes - end - - def [](name) - attributes[name] || Attribute.null(name) - end - - def []=(name, value) - attributes[name] = value - end - - def values_before_type_cast - attributes.transform_values(&:value_before_type_cast) - end - - def to_hash - initialized_attributes.transform_values(&:value) - end - alias_method :to_h, :to_hash - - def key?(name) - attributes.key?(name) && self[name].initialized? - end - - def keys - attributes.each_key.select { |name| self[name].initialized? } - end - - if defined?(JRUBY_VERSION) - # This form is significantly faster on JRuby, and this is one of our biggest hotspots. - # https://github.com/jruby/jruby/pull/2562 - def fetch_value(name, &block) - self[name].value(&block) - end - else - def fetch_value(name) - self[name].value { |n| yield n if block_given? } - end - end - - def write_from_database(name, value) - attributes[name] = self[name].with_value_from_database(value) - end - - def write_from_user(name, value) - attributes[name] = self[name].with_value_from_user(value) - end - - def write_cast_value(name, value) - attributes[name] = self[name].with_cast_value(value) - end - - def freeze - @attributes.freeze - super - end - - def deep_dup - dup.tap do |copy| - copy.instance_variable_set(:@attributes, attributes.deep_dup) - end - end - - def initialize_dup(_) - @attributes = attributes.dup - super - end - - def initialize_clone(_) - @attributes = attributes.clone - super - end - - def reset(key) - if key?(key) - write_from_database(key, nil) - end - end - - def accessed - attributes.select { |_, attr| attr.has_been_read? }.keys - end - - def map(&block) - new_attributes = attributes.transform_values(&block) - AttributeSet.new(new_attributes) - end - - def ==(other) - attributes == other.attributes - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :attributes - - private - - def initialized_attributes - attributes.select { |_, attr| attr.initialized? } - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set/builder.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set/builder.rb deleted file mode 100644 index db0379a2c8..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set/builder.rb +++ /dev/null @@ -1,126 +0,0 @@ -require "active_record/attribute" - -module ActiveRecord - class AttributeSet # :nodoc: - class Builder # :nodoc: - attr_reader :types, :default_attributes - - def initialize(types, default_attributes = {}) - @types = types - @default_attributes = default_attributes - end - - def build_from_database(values = {}, additional_types = {}) - attributes = LazyAttributeHash.new(types, values, additional_types, default_attributes) - AttributeSet.new(attributes) - end - end - end - - class LazyAttributeHash # :nodoc: - delegate :transform_values, :each_key, :each_value, :fetch, :except, to: :materialize - - def initialize(types, values, additional_types, default_attributes, delegate_hash = {}) - @types = types - @values = values - @additional_types = additional_types - @materialized = false - @delegate_hash = delegate_hash - @default_attributes = default_attributes - end - - def key?(key) - delegate_hash.key?(key) || values.key?(key) || types.key?(key) - end - - def [](key) - delegate_hash[key] || assign_default_value(key) - end - - def []=(key, value) - if frozen? - raise RuntimeError, "Can't modify frozen hash" - end - delegate_hash[key] = value - end - - def deep_dup - dup.tap do |copy| - copy.instance_variable_set(:@delegate_hash, delegate_hash.transform_values(&:dup)) - end - end - - def initialize_dup(_) - @delegate_hash = Hash[delegate_hash] - super - end - - def select - keys = types.keys | values.keys | delegate_hash.keys - keys.each_with_object({}) do |key, hash| - attribute = self[key] - if yield(key, attribute) - hash[key] = attribute - end - end - end - - def ==(other) - if other.is_a?(LazyAttributeHash) - materialize == other.materialize - else - materialize == other - end - end - - def marshal_dump - [@types, @values, @additional_types, @default_attributes, @delegate_hash] - end - - def marshal_load(values) - if values.is_a?(Hash) - empty_hash = {}.freeze - initialize(empty_hash, empty_hash, empty_hash, empty_hash, values) - @materialized = true - else - initialize(*values) - end - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :types, :values, :additional_types, :delegate_hash, :default_attributes - - def materialize - unless @materialized - values.each_key { |key| self[key] } - types.each_key { |key| self[key] } - unless frozen? - @materialized = true - end - end - delegate_hash - end - - private - - def assign_default_value(name) - type = additional_types.fetch(name, types[name]) - value_present = true - value = values.fetch(name) { value_present = false } - - if value_present - delegate_hash[name] = Attribute.from_database(name, value, type) - elsif types.key?(name) - attr = default_attributes[name] - if attr - delegate_hash[name] = attr.dup - else - delegate_hash[name] = Attribute.uninitialized(name, type) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set/yaml_encoder.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set/yaml_encoder.rb deleted file mode 100644 index 899de14792..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attribute_set/yaml_encoder.rb +++ /dev/null @@ -1,41 +0,0 @@ -module ActiveRecord - class AttributeSet - # Attempts to do more intelligent YAML dumping of an - # ActiveRecord::AttributeSet to reduce the size of the resulting string - class YAMLEncoder # :nodoc: - def initialize(default_types) - @default_types = default_types - end - - def encode(attribute_set, coder) - coder["concise_attributes"] = attribute_set.each_value.map do |attr| - if attr.type.equal?(default_types[attr.name]) - attr.with_type(nil) - else - attr - end - end - end - - def decode(coder) - if coder["attributes"] - coder["attributes"] - else - attributes_hash = Hash[coder["concise_attributes"].map do |attr| - if attr.type.nil? - attr = attr.with_type(default_types[attr.name]) - end - [attr.name, attr] - end] - AttributeSet.new(attributes_hash) - end - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :default_types - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attributes.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/attributes.rb deleted file mode 100644 index bc26e29f92..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/attributes.rb +++ /dev/null @@ -1,265 +0,0 @@ -require "active_record/attribute/user_provided_default" - -module ActiveRecord - # See ActiveRecord::Attributes::ClassMethods for documentation - module Attributes - extend ActiveSupport::Concern - - included do - class_attribute :attributes_to_define_after_schema_loads, instance_accessor: false # :internal: - self.attributes_to_define_after_schema_loads = {} - end - - module ClassMethods - # Defines an attribute with a type on this model. It will override the - # type of existing attributes if needed. This allows control over how - # values are converted to and from SQL when assigned to a model. It also - # changes the behavior of values passed to - # {ActiveRecord::Base.where}[rdoc-ref:QueryMethods#where]. This will let you use - # your domain objects across much of Active Record, without having to - # rely on implementation details or monkey patching. - # - # +name+ The name of the methods to define attribute methods for, and the - # column which this will persist to. - # - # +cast_type+ A symbol such as +:string+ or +:integer+, or a type object - # to be used for this attribute. See the examples below for more - # information about providing custom type objects. - # - # ==== Options - # - # The following options are accepted: - # - # +default+ The default value to use when no value is provided. If this option - # is not passed, the previous default value (if any) will be used. - # Otherwise, the default will be +nil+. - # - # +array+ (PostgreSQL only) specifies that the type should be an array (see the - # examples below). - # - # +range+ (PostgreSQL only) specifies that the type should be a range (see the - # examples below). - # - # ==== Examples - # - # The type detected by Active Record can be overridden. - # - # # db/schema.rb - # create_table :store_listings, force: true do |t| - # t.decimal :price_in_cents - # end - # - # # app/models/store_listing.rb - # class StoreListing < ActiveRecord::Base - # end - # - # store_listing = StoreListing.new(price_in_cents: '10.1') - # - # # before - # store_listing.price_in_cents # => BigDecimal(10.1) - # - # class StoreListing < ActiveRecord::Base - # attribute :price_in_cents, :integer - # end - # - # # after - # store_listing.price_in_cents # => 10 - # - # A default can also be provided. - # - # # db/schema.rb - # create_table :store_listings, force: true do |t| - # t.string :my_string, default: "original default" - # end - # - # StoreListing.new.my_string # => "original default" - # - # # app/models/store_listing.rb - # class StoreListing < ActiveRecord::Base - # attribute :my_string, :string, default: "new default" - # end - # - # StoreListing.new.my_string # => "new default" - # - # class Product < ActiveRecord::Base - # attribute :my_default_proc, :datetime, default: -> { Time.now } - # end - # - # Product.new.my_default_proc # => 2015-05-30 11:04:48 -0600 - # sleep 1 - # Product.new.my_default_proc # => 2015-05-30 11:04:49 -0600 - # - # \Attributes do not need to be backed by a database column. - # - # # app/models/my_model.rb - # class MyModel < ActiveRecord::Base - # attribute :my_string, :string - # attribute :my_int_array, :integer, array: true - # attribute :my_float_range, :float, range: true - # end - # - # model = MyModel.new( - # my_string: "string", - # my_int_array: ["1", "2", "3"], - # my_float_range: "[1,3.5]", - # ) - # model.attributes - # # => - # { - # my_string: "string", - # my_int_array: [1, 2, 3], - # my_float_range: 1.0..3.5 - # } - # - # ==== Creating Custom Types - # - # Users may also define their own custom types, as long as they respond - # to the methods defined on the value type. The method +deserialize+ or - # +cast+ will be called on your type object, with raw input from the - # database or from your controllers. See ActiveModel::Type::Value for the - # expected API. It is recommended that your type objects inherit from an - # existing type, or from ActiveRecord::Type::Value - # - # class MoneyType < ActiveRecord::Type::Integer - # def cast(value) - # if !value.kind_of?(Numeric) && value.include?('$') - # price_in_dollars = value.gsub(/\$/, '').to_f - # super(price_in_dollars * 100) - # else - # super - # end - # end - # end - # - # # config/initializers/types.rb - # ActiveRecord::Type.register(:money, MoneyType) - # - # # app/models/store_listing.rb - # class StoreListing < ActiveRecord::Base - # attribute :price_in_cents, :money - # end - # - # store_listing = StoreListing.new(price_in_cents: '$10.00') - # store_listing.price_in_cents # => 1000 - # - # For more details on creating custom types, see the documentation for - # ActiveModel::Type::Value. For more details on registering your types - # to be referenced by a symbol, see ActiveRecord::Type.register. You can - # also pass a type object directly, in place of a symbol. - # - # ==== \Querying - # - # When {ActiveRecord::Base.where}[rdoc-ref:QueryMethods#where] is called, it will - # use the type defined by the model class to convert the value to SQL, - # calling +serialize+ on your type object. For example: - # - # class Money < Struct.new(:amount, :currency) - # end - # - # class MoneyType < Type::Value - # def initialize(currency_converter:) - # @currency_converter = currency_converter - # end - # - # # value will be the result of +deserialize+ or - # # +cast+. Assumed to be an instance of +Money+ in - # # this case. - # def serialize(value) - # value_in_bitcoins = @currency_converter.convert_to_bitcoins(value) - # value_in_bitcoins.amount - # end - # end - # - # # config/initializers/types.rb - # ActiveRecord::Type.register(:money, MoneyType) - # - # # app/models/product.rb - # class Product < ActiveRecord::Base - # currency_converter = ConversionRatesFromTheInternet.new - # attribute :price_in_bitcoins, :money, currency_converter: currency_converter - # end - # - # Product.where(price_in_bitcoins: Money.new(5, "USD")) - # # => SELECT * FROM products WHERE price_in_bitcoins = 0.02230 - # - # Product.where(price_in_bitcoins: Money.new(5, "GBP")) - # # => SELECT * FROM products WHERE price_in_bitcoins = 0.03412 - # - # ==== Dirty Tracking - # - # The type of an attribute is given the opportunity to change how dirty - # tracking is performed. The methods +changed?+ and +changed_in_place?+ - # will be called from ActiveModel::Dirty. See the documentation for those - # methods in ActiveModel::Type::Value for more details. - def attribute(name, cast_type = Type::Value.new, **options) - name = name.to_s - reload_schema_from_cache - - self.attributes_to_define_after_schema_loads = - attributes_to_define_after_schema_loads.merge( - name => [cast_type, options] - ) - end - - # This is the low level API which sits beneath +attribute+. It only - # accepts type objects, and will do its work immediately instead of - # waiting for the schema to load. Automatic schema detection and - # ClassMethods#attribute both call this under the hood. While this method - # is provided so it can be used by plugin authors, application code - # should probably use ClassMethods#attribute. - # - # +name+ The name of the attribute being defined. Expected to be a +String+. - # - # +cast_type+ The type object to use for this attribute. - # - # +default+ The default value to use when no value is provided. If this option - # is not passed, the previous default value (if any) will be used. - # Otherwise, the default will be +nil+. A proc can also be passed, and - # will be called once each time a new value is needed. - # - # +user_provided_default+ Whether the default value should be cast using - # +cast+ or +deserialize+. - def define_attribute( - name, - cast_type, - default: NO_DEFAULT_PROVIDED, - user_provided_default: true - ) - attribute_types[name] = cast_type - define_default_attribute(name, default, cast_type, from_user: user_provided_default) - end - - def load_schema! # :nodoc: - super - attributes_to_define_after_schema_loads.each do |name, (type, options)| - if type.is_a?(Symbol) - type = ActiveRecord::Type.lookup(type, **options.except(:default)) - end - - define_attribute(name, type, **options.slice(:default)) - end - end - - private - - NO_DEFAULT_PROVIDED = Object.new # :nodoc: - private_constant :NO_DEFAULT_PROVIDED - - def define_default_attribute(name, value, type, from_user:) - if value == NO_DEFAULT_PROVIDED - default_attribute = _default_attributes[name].with_type(type) - elsif from_user - default_attribute = Attribute::UserProvidedDefault.new( - name, - value, - type, - _default_attributes.fetch(name.to_s) { nil }, - ) - else - default_attribute = Attribute.from_database(name, value, type) - end - _default_attributes[name] = default_attribute - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/autosave_association.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/autosave_association.rb deleted file mode 100644 index 607c54e481..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/autosave_association.rb +++ /dev/null @@ -1,496 +0,0 @@ -module ActiveRecord - # = Active Record Autosave Association - # - # AutosaveAssociation is a module that takes care of automatically saving - # associated records when their parent is saved. In addition to saving, it - # also destroys any associated records that were marked for destruction. - # (See #mark_for_destruction and #marked_for_destruction?). - # - # Saving of the parent, its associations, and the destruction of marked - # associations, all happen inside a transaction. This should never leave the - # database in an inconsistent state. - # - # If validations for any of the associations fail, their error messages will - # be applied to the parent. - # - # Note that it also means that associations marked for destruction won't - # be destroyed directly. They will however still be marked for destruction. - # - # Note that autosave: false is not same as not declaring :autosave. - # When the :autosave option is not present then new association records are - # saved but the updated association records are not saved. - # - # == Validation - # - # Child records are validated unless :validate is +false+. - # - # == Callbacks - # - # Association with autosave option defines several callbacks on your - # model (before_save, after_create, after_update). Please note that - # callbacks are executed in the order they were defined in - # model. You should avoid modifying the association content, before - # autosave callbacks are executed. Placing your callbacks after - # associations is usually a good practice. - # - # === One-to-one Example - # - # class Post < ActiveRecord::Base - # has_one :author, autosave: true - # end - # - # Saving changes to the parent and its associated model can now be performed - # automatically _and_ atomically: - # - # post = Post.find(1) - # post.title # => "The current global position of migrating ducks" - # post.author.name # => "alloy" - # - # post.title = "On the migration of ducks" - # post.author.name = "Eloy Duran" - # - # post.save - # post.reload - # post.title # => "On the migration of ducks" - # post.author.name # => "Eloy Duran" - # - # Destroying an associated model, as part of the parent's save action, is as - # simple as marking it for destruction: - # - # post.author.mark_for_destruction - # post.author.marked_for_destruction? # => true - # - # Note that the model is _not_ yet removed from the database: - # - # id = post.author.id - # Author.find_by(id: id).nil? # => false - # - # post.save - # post.reload.author # => nil - # - # Now it _is_ removed from the database: - # - # Author.find_by(id: id).nil? # => true - # - # === One-to-many Example - # - # When :autosave is not declared new children are saved when their parent is saved: - # - # class Post < ActiveRecord::Base - # has_many :comments # :autosave option is not declared - # end - # - # post = Post.new(title: 'ruby rocks') - # post.comments.build(body: 'hello world') - # post.save # => saves both post and comment - # - # post = Post.create(title: 'ruby rocks') - # post.comments.build(body: 'hello world') - # post.save # => saves both post and comment - # - # post = Post.create(title: 'ruby rocks') - # post.comments.create(body: 'hello world') - # post.save # => saves both post and comment - # - # When :autosave is true all children are saved, no matter whether they - # are new records or not: - # - # class Post < ActiveRecord::Base - # has_many :comments, autosave: true - # end - # - # post = Post.create(title: 'ruby rocks') - # post.comments.create(body: 'hello world') - # post.comments[0].body = 'hi everyone' - # post.comments.build(body: "good morning.") - # post.title += "!" - # post.save # => saves both post and comments. - # - # Destroying one of the associated models as part of the parent's save action - # is as simple as marking it for destruction: - # - # post.comments # => [#, # - # post.comments[1].mark_for_destruction - # post.comments[1].marked_for_destruction? # => true - # post.comments.length # => 2 - # - # Note that the model is _not_ yet removed from the database: - # - # id = post.comments.last.id - # Comment.find_by(id: id).nil? # => false - # - # post.save - # post.reload.comments.length # => 1 - # - # Now it _is_ removed from the database: - # - # Comment.find_by(id: id).nil? # => true - module AutosaveAssociation - extend ActiveSupport::Concern - - module AssociationBuilderExtension #:nodoc: - def self.build(model, reflection) - model.send(:add_autosave_association_callbacks, reflection) - end - - def self.valid_options - [ :autosave ] - end - end - - included do - Associations::Builder::Association.extensions << AssociationBuilderExtension - mattr_accessor :index_nested_attribute_errors, instance_writer: false - self.index_nested_attribute_errors = false - end - - module ClassMethods # :nodoc: - private - - def define_non_cyclic_method(name, &block) - return if method_defined?(name) - define_method(name) do |*args| - result = true; @_already_called ||= {} - # Loop prevention for validation of associations - unless @_already_called[name] - begin - @_already_called[name] = true - result = instance_eval(&block) - ensure - @_already_called[name] = false - end - end - - result - end - end - - # Adds validation and save callbacks for the association as specified by - # the +reflection+. - # - # For performance reasons, we don't check whether to validate at runtime. - # However the validation and callback methods are lazy and those methods - # get created when they are invoked for the very first time. However, - # this can change, for instance, when using nested attributes, which is - # called _after_ the association has been defined. Since we don't want - # the callbacks to get defined multiple times, there are guards that - # check if the save or validation methods have already been defined - # before actually defining them. - def add_autosave_association_callbacks(reflection) - save_method = :"autosave_associated_records_for_#{reflection.name}" - - if reflection.collection? - before_save :before_save_collection_association - after_save :after_save_collection_association - - define_non_cyclic_method(save_method) { save_collection_association(reflection) } - # Doesn't use after_save as that would save associations added in after_create/after_update twice - after_create save_method - after_update save_method - elsif reflection.has_one? - define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method) - # Configures two callbacks instead of a single after_save so that - # the model may rely on their execution order relative to its - # own callbacks. - # - # For example, given that after_creates run before after_saves, if - # we configured instead an after_save there would be no way to fire - # a custom after_create callback after the child association gets - # created. - after_create save_method - after_update save_method - else - define_non_cyclic_method(save_method) { throw(:abort) if save_belongs_to_association(reflection) == false } - before_save save_method - end - - define_autosave_validation_callbacks(reflection) - end - - def define_autosave_validation_callbacks(reflection) - validation_method = :"validate_associated_records_for_#{reflection.name}" - if reflection.validate? && !method_defined?(validation_method) - if reflection.collection? - method = :validate_collection_association - else - method = :validate_single_association - end - - define_non_cyclic_method(validation_method) do - send(method, reflection) - # TODO: remove the following line as soon as the return value of - # callbacks is ignored, that is, returning `false` does not - # display a deprecation warning or halts the callback chain. - true - end - validate validation_method - after_validation :_ensure_no_duplicate_errors - end - end - end - - # Reloads the attributes of the object as usual and clears marked_for_destruction flag. - def reload(options = nil) - @marked_for_destruction = false - @destroyed_by_association = nil - super - end - - # Marks this record to be destroyed as part of the parent's save transaction. - # This does _not_ actually destroy the record instantly, rather child record will be destroyed - # when parent.save is called. - # - # Only useful if the :autosave option on the parent is enabled for this associated model. - def mark_for_destruction - @marked_for_destruction = true - end - - # Returns whether or not this record will be destroyed as part of the parent's save transaction. - # - # Only useful if the :autosave option on the parent is enabled for this associated model. - def marked_for_destruction? - @marked_for_destruction - end - - # Records the association that is being destroyed and destroying this - # record in the process. - def destroyed_by_association=(reflection) - @destroyed_by_association = reflection - end - - # Returns the association for the parent being destroyed. - # - # Used to avoid updating the counter cache unnecessarily. - def destroyed_by_association - @destroyed_by_association - end - - # Returns whether or not this record has been changed in any way (including whether - # any of its nested autosave associations are likewise changed) - def changed_for_autosave? - new_record? || has_changes_to_save? || marked_for_destruction? || nested_records_changed_for_autosave? - end - - private - - # Returns the record for an association collection that should be validated - # or saved. If +autosave+ is +false+ only new records will be returned, - # unless the parent is/was a new record itself. - def associated_records_to_validate_or_save(association, new_record, autosave) - if new_record - association && association.target - elsif autosave - association.target.find_all(&:changed_for_autosave?) - else - association.target.find_all(&:new_record?) - end - end - - # go through nested autosave associations that are loaded in memory (without loading - # any new ones), and return true if is changed for autosave - def nested_records_changed_for_autosave? - @_nested_records_changed_for_autosave_already_called ||= false - return false if @_nested_records_changed_for_autosave_already_called - begin - @_nested_records_changed_for_autosave_already_called = true - self.class._reflections.values.any? do |reflection| - if reflection.options[:autosave] - association = association_instance_get(reflection.name) - association && Array.wrap(association.target).any?(&:changed_for_autosave?) - end - end - ensure - @_nested_records_changed_for_autosave_already_called = false - end - end - - # Validate the association if :validate or :autosave is - # turned on for the association. - def validate_single_association(reflection) - association = association_instance_get(reflection.name) - record = association && association.reader - association_valid?(reflection, record) if record - end - - # Validate the associated records if :validate or - # :autosave is turned on for the association specified by - # +reflection+. - def validate_collection_association(reflection) - if association = association_instance_get(reflection.name) - if records = associated_records_to_validate_or_save(association, new_record?, reflection.options[:autosave]) - records.each_with_index { |record, index| association_valid?(reflection, record, index) } - end - end - end - - # Returns whether or not the association is valid and applies any errors to - # the parent, self, if it wasn't. Skips any :autosave - # enabled records if they're marked_for_destruction? or destroyed. - def association_valid?(reflection, record, index = nil) - return true if record.destroyed? || (reflection.options[:autosave] && record.marked_for_destruction?) - - context = validation_context unless [:create, :update].include?(validation_context) - - unless valid = record.valid?(context) - if reflection.options[:autosave] - indexed_attribute = !index.nil? && (reflection.options[:index_errors] || ActiveRecord::Base.index_nested_attribute_errors) - - record.errors.each do |attribute, message| - attribute = normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) - errors[attribute] << message - errors[attribute].uniq! - end - - record.errors.details.each_key do |attribute| - reflection_attribute = - normalize_reflection_attribute(indexed_attribute, reflection, index, attribute).to_sym - - record.errors.details[attribute].each do |error| - errors.details[reflection_attribute] << error - errors.details[reflection_attribute].uniq! - end - end - else - errors.add(reflection.name) - end - end - valid - end - - def normalize_reflection_attribute(indexed_attribute, reflection, index, attribute) - if indexed_attribute - "#{reflection.name}[#{index}].#{attribute}" - else - "#{reflection.name}.#{attribute}" - end - end - - # Is used as a before_save callback to check while saving a collection - # association whether or not the parent was a new record before saving. - def before_save_collection_association - @new_record_before_save = new_record? - true - end - - def after_save_collection_association - @new_record_before_save = false - end - - # Saves any new associated records, or all loaded autosave associations if - # :autosave is enabled on the association. - # - # In addition, it destroys all children that were marked for destruction - # with #mark_for_destruction. - # - # This all happens inside a transaction, _if_ the Transactions module is included into - # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. - def save_collection_association(reflection) - if association = association_instance_get(reflection.name) - autosave = reflection.options[:autosave] - - # reconstruct the scope now that we know the owner's id - association.reset_scope if association.respond_to?(:reset_scope) - - if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave) - if autosave - records_to_destroy = records.select(&:marked_for_destruction?) - records_to_destroy.each { |record| association.destroy(record) } - records -= records_to_destroy - end - - records.each do |record| - next if record.destroyed? - - saved = true - - if autosave != false && (@new_record_before_save || record.new_record?) - if autosave - saved = association.insert_record(record, false) - else - association.insert_record(record) unless reflection.nested? - end - elsif autosave - saved = record.save(validate: false) - end - - raise ActiveRecord::Rollback unless saved - end - end - end - end - - # Saves the associated record if it's new or :autosave is enabled - # on the association. - # - # In addition, it will destroy the association if it was marked for - # destruction with #mark_for_destruction. - # - # This all happens inside a transaction, _if_ the Transactions module is included into - # ActiveRecord::Base after the AutosaveAssociation module, which it does by default. - def save_has_one_association(reflection) - association = association_instance_get(reflection.name) - record = association && association.load_target - - if record && !record.destroyed? - autosave = reflection.options[:autosave] - - if autosave && record.marked_for_destruction? - record.destroy - elsif autosave != false - key = reflection.options[:primary_key] ? send(reflection.options[:primary_key]) : id - - if (autosave && record.changed_for_autosave?) || new_record? || record_changed?(reflection, record, key) - unless reflection.through_reflection - record[reflection.foreign_key] = key - end - - saved = record.save(validate: !autosave) - raise ActiveRecord::Rollback if !saved && autosave - saved - end - end - end - end - - # If the record is new or it has changed, returns true. - def record_changed?(reflection, record, key) - record.new_record? || - (record.has_attribute?(reflection.foreign_key) && record[reflection.foreign_key] != key) || - record.will_save_change_to_attribute?(reflection.foreign_key) - end - - # Saves the associated record if it's new or :autosave is enabled. - # - # In addition, it will destroy the association if it was marked for destruction. - def save_belongs_to_association(reflection) - association = association_instance_get(reflection.name) - return unless association && association.loaded? && !association.stale_target? - - record = association.load_target - if record && !record.destroyed? - autosave = reflection.options[:autosave] - - if autosave && record.marked_for_destruction? - self[reflection.foreign_key] = nil - record.destroy - elsif autosave != false - saved = record.save(validate: !autosave) if record.new_record? || (autosave && record.changed_for_autosave?) - - if association.updated? - association_id = record.send(reflection.options[:primary_key] || :id) - self[reflection.foreign_key] = association_id - association.loaded! - end - - saved if autosave - end - end - end - - def _ensure_no_duplicate_errors - errors.messages.each_key do |attribute| - errors[attribute].uniq! - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/base.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/base.rb deleted file mode 100644 index ac1aa2df45..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/base.rb +++ /dev/null @@ -1,327 +0,0 @@ -require "yaml" -require "active_support/benchmarkable" -require "active_support/dependencies" -require "active_support/descendants_tracker" -require "active_support/time" -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/hash/deep_merge" -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/hash/transform_values" -require "active_support/core_ext/string/behavior" -require "active_support/core_ext/kernel/singleton_class" -require "active_support/core_ext/module/introspection" -require "active_support/core_ext/object/duplicable" -require "active_support/core_ext/class/subclasses" -require "active_record/attribute_decorators" -require "active_record/define_callbacks" -require "active_record/errors" -require "active_record/log_subscriber" -require "active_record/explain_subscriber" -require "active_record/relation/delegation" -require "active_record/attributes" -require "active_record/type_caster" - -module ActiveRecord #:nodoc: - # = Active Record - # - # Active Record objects don't specify their attributes directly, but rather infer them from - # the table definition with which they're linked. Adding, removing, and changing attributes - # and their type is done directly in the database. Any change is instantly reflected in the - # Active Record objects. The mapping that binds a given Active Record class to a certain - # database table will happen automatically in most common cases, but can be overwritten for the uncommon ones. - # - # See the mapping rules in table_name and the full example in link:files/activerecord/README_rdoc.html for more insight. - # - # == Creation - # - # Active Records accept constructor parameters either in a hash or as a block. The hash - # method is especially useful when you're receiving the data from somewhere else, like an - # HTTP request. It works like this: - # - # user = User.new(name: "David", occupation: "Code Artist") - # user.name # => "David" - # - # You can also use block initialization: - # - # user = User.new do |u| - # u.name = "David" - # u.occupation = "Code Artist" - # end - # - # And of course you can just create a bare object and specify the attributes after the fact: - # - # user = User.new - # user.name = "David" - # user.occupation = "Code Artist" - # - # == Conditions - # - # Conditions can either be specified as a string, array, or hash representing the WHERE-part of an SQL statement. - # The array form is to be used when the condition input is tainted and requires sanitization. The string form can - # be used for statements that don't involve tainted data. The hash form works much like the array form, except - # only equality and range is possible. Examples: - # - # class User < ActiveRecord::Base - # def self.authenticate_unsafely(user_name, password) - # where("user_name = '#{user_name}' AND password = '#{password}'").first - # end - # - # def self.authenticate_safely(user_name, password) - # where("user_name = ? AND password = ?", user_name, password).first - # end - # - # def self.authenticate_safely_simply(user_name, password) - # where(user_name: user_name, password: password).first - # end - # end - # - # The authenticate_unsafely method inserts the parameters directly into the query - # and is thus susceptible to SQL-injection attacks if the user_name and +password+ - # parameters come directly from an HTTP request. The authenticate_safely and - # authenticate_safely_simply both will sanitize the user_name and +password+ - # before inserting them in the query, which will ensure that an attacker can't escape the - # query and fake the login (or worse). - # - # When using multiple parameters in the conditions, it can easily become hard to read exactly - # what the fourth or fifth question mark is supposed to represent. In those cases, you can - # resort to named bind variables instead. That's done by replacing the question marks with - # symbols and supplying a hash with values for the matching symbol keys: - # - # Company.where( - # "id = :id AND name = :name AND division = :division AND created_at > :accounting_date", - # { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' } - # ).first - # - # Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND - # operator. For instance: - # - # Student.where(first_name: "Harvey", status: 1) - # Student.where(params[:student]) - # - # A range may be used in the hash to use the SQL BETWEEN operator: - # - # Student.where(grade: 9..12) - # - # An array may be used in the hash to use the SQL IN operator: - # - # Student.where(grade: [9,11,12]) - # - # When joining tables, nested hashes or keys written in the form 'table_name.column_name' - # can be used to qualify the table name of a particular condition. For instance: - # - # Student.joins(:schools).where(schools: { category: 'public' }) - # Student.joins(:schools).where('schools.category' => 'public' ) - # - # == Overwriting default accessors - # - # All column values are automatically available through basic accessors on the Active Record - # object, but sometimes you want to specialize this behavior. This can be done by overwriting - # the default accessors (using the same name as the attribute) and calling - # +super+ to actually change things. - # - # class Song < ActiveRecord::Base - # # Uses an integer of seconds to hold the length of the song - # - # def length=(minutes) - # super(minutes.to_i * 60) - # end - # - # def length - # super / 60 - # end - # end - # - # == Attribute query methods - # - # In addition to the basic accessors, query methods are also automatically available on the Active Record object. - # Query methods allow you to test whether an attribute value is present. - # Additionally, when dealing with numeric values, a query method will return false if the value is zero. - # - # For example, an Active Record User with the name attribute has a name? method that you can call - # to determine whether the user has a name: - # - # user = User.new(name: "David") - # user.name? # => true - # - # anonymous = User.new(name: "") - # anonymous.name? # => false - # - # == Accessing attributes before they have been typecasted - # - # Sometimes you want to be able to read the raw attribute data without having the column-determined - # typecast run its course first. That can be done by using the _before_type_cast - # accessors that all attributes have. For example, if your Account model has a balance attribute, - # you can call account.balance_before_type_cast or account.id_before_type_cast. - # - # This is especially useful in validation situations where the user might supply a string for an - # integer field and you want to display the original string back in an error message. Accessing the - # attribute normally would typecast the string to 0, which isn't what you want. - # - # == Dynamic attribute-based finders - # - # Dynamic attribute-based finders are a mildly deprecated way of getting (and/or creating) objects - # by simple queries without turning to SQL. They work by appending the name of an attribute - # to find_by_ like Person.find_by_user_name. - # Instead of writing Person.find_by(user_name: user_name), you can use - # Person.find_by_user_name(user_name). - # - # It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an - # ActiveRecord::RecordNotFound error if they do not return any records, - # like Person.find_by_last_name!. - # - # It's also possible to use multiple attributes in the same find_by_ by separating them with - # "_and_". - # - # Person.find_by(user_name: user_name, password: password) - # Person.find_by_user_name_and_password(user_name, password) # with dynamic finder - # - # It's even possible to call these dynamic finder methods on relations and named scopes. - # - # Payment.order("created_on").find_by_amount(50) - # - # == Saving arrays, hashes, and other non-mappable objects in text columns - # - # 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}[rdoc-ref:AttributeMethods::Serialization::ClassMethods#serialize]. - # This makes it possible to store arrays, hashes, and other non-mappable objects without doing - # any additional work. - # - # class User < ActiveRecord::Base - # serialize :preferences - # end - # - # user = User.create(preferences: { "background" => "black", "display" => large }) - # User.find(user.id).preferences # => { "background" => "black", "display" => large } - # - # You can also specify a class option as the second parameter that'll raise an exception - # if a serialized object is retrieved as a descendant of a class not in the hierarchy. - # - # class User < ActiveRecord::Base - # serialize :preferences, Hash - # end - # - # user = User.create(preferences: %w( one two three )) - # User.find(user.id).preferences # raises SerializationTypeMismatch - # - # When you specify a class option, the default value for that attribute will be a new - # instance of that class. - # - # class User < ActiveRecord::Base - # serialize :preferences, OpenStruct - # end - # - # user = User.new - # user.preferences.theme_color = "red" - # - # - # == Single table inheritance - # - # Active Record allows inheritance by storing the name of the class in a - # column that is named "type" by default. See ActiveRecord::Inheritance for - # more details. - # - # == Connection to multiple databases in different models - # - # Connections are usually created through - # {ActiveRecord::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] and retrieved - # by ActiveRecord::Base.connection. All classes inheriting from ActiveRecord::Base will use this - # connection. But you can also set a class-specific connection. For example, if Course is an - # ActiveRecord::Base, but resides in a different database, you can just say Course.establish_connection - # and Course and all of its subclasses will use this connection instead. - # - # This feature is implemented by keeping a connection pool in ActiveRecord::Base that is - # a hash indexed by the class. If a connection is requested, the - # {ActiveRecord::Base.retrieve_connection}[rdoc-ref:ConnectionHandling#retrieve_connection] method - # will go up the class-hierarchy until a connection is found in the connection pool. - # - # == Exceptions - # - # * ActiveRecordError - Generic error class and superclass of all other errors raised by Active Record. - # * AdapterNotSpecified - The configuration hash used in - # {ActiveRecord::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] - # didn't include an :adapter key. - # * AdapterNotFound - The :adapter key used in - # {ActiveRecord::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] - # specified a non-existent adapter - # (or a bad spelling of an existing one). - # * AssociationTypeMismatch - The object assigned to the association wasn't of the type - # specified in the association definition. - # * AttributeAssignmentError - An error occurred while doing a mass assignment through the - # {ActiveRecord::Base#attributes=}[rdoc-ref:AttributeAssignment#attributes=] method. - # You can inspect the +attribute+ property of the exception object to determine which attribute - # triggered the error. - # * ConnectionNotEstablished - No connection has been established. - # Use {ActiveRecord::Base.establish_connection}[rdoc-ref:ConnectionHandling#establish_connection] before querying. - # * MultiparameterAssignmentErrors - Collection of errors that occurred during a mass assignment using the - # {ActiveRecord::Base#attributes=}[rdoc-ref:AttributeAssignment#attributes=] method. - # The +errors+ property of this exception contains an array of - # AttributeAssignmentError - # objects that should be inspected to determine which attributes triggered the errors. - # * RecordInvalid - raised by {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!] and - # {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!] - # when the record is invalid. - # * RecordNotFound - No record responded to the {ActiveRecord::Base.find}[rdoc-ref:FinderMethods#find] method. - # Either the row with the given ID doesn't exist or the row didn't meet the additional restrictions. - # Some {ActiveRecord::Base.find}[rdoc-ref:FinderMethods#find] calls do not raise this exception to signal - # nothing was found, please check its documentation for further details. - # * SerializationTypeMismatch - The serialized object wasn't of the class specified as the second parameter. - # * StatementInvalid - The database server rejected the SQL statement. The precise error is added in the message. - # - # *Note*: The attributes listed are class-level attributes (accessible from both the class and instance level). - # So it's possible to assign a logger to the class through Base.logger= which will then be used by all - # instances in the current object space. - class Base - extend ActiveModel::Naming - - extend ActiveSupport::Benchmarkable - extend ActiveSupport::DescendantsTracker - - extend ConnectionHandling - extend QueryCache::ClassMethods - extend Querying - extend Translation - extend DynamicMatchers - extend Explain - extend Enum - extend Delegation::DelegateCache - extend CollectionCacheKey - - include Core - include Persistence - include ReadonlyAttributes - include ModelSchema - include Inheritance - include Scoping - include Sanitization - include AttributeAssignment - include ActiveModel::Conversion - include Integration - include Validations - include CounterCache - include Attributes - include AttributeDecorators - include Locking::Optimistic - include Locking::Pessimistic - include DefineCallbacks - include AttributeMethods - include Callbacks - include Timestamp - include Associations - include ActiveModel::SecurePassword - include AutosaveAssociation - include NestedAttributes - include Aggregations - include Transactions - include TouchLater - include NoTouching - include Reflection - include Serialization - include Store - include SecureToken - include Suppressor - end - - ActiveSupport.run_load_hooks(:active_record, Base) -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/callbacks.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/callbacks.rb deleted file mode 100644 index d63a2599b4..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/callbacks.rb +++ /dev/null @@ -1,351 +0,0 @@ -module ActiveRecord - # = Active Record \Callbacks - # - # \Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic - # before or after an alteration of the object state. This can be used to make sure that associated and - # dependent objects are deleted when {ActiveRecord::Base#destroy}[rdoc-ref:Persistence#destroy] is called (by overwriting +before_destroy+) or - # to massage attributes before they're validated (by overwriting +before_validation+). - # As an example of the callbacks initiated, consider the {ActiveRecord::Base#save}[rdoc-ref:Persistence#save] call for a new record: - # - # * (-) save - # * (-) valid - # * (1) before_validation - # * (-) validate - # * (2) after_validation - # * (3) before_save - # * (4) before_create - # * (-) create - # * (5) after_create - # * (6) after_save - # * (7) after_commit - # - # Also, an after_rollback callback can be configured to be triggered whenever a rollback is issued. - # Check out ActiveRecord::Transactions for more details about after_commit and - # after_rollback. - # - # Additionally, an after_touch callback is triggered whenever an - # object is touched. - # - # Lastly an after_find and after_initialize callback is triggered for each object that - # is found and instantiated by a finder, with after_initialize being triggered after new objects - # are instantiated as well. - # - # There are nineteen callbacks in total, which give you immense power to react and prepare for each state in the - # Active Record life cycle. The sequence for calling {ActiveRecord::Base#save}[rdoc-ref:Persistence#save] for an existing record is similar, - # except that each _create callback is replaced by the corresponding _update callback. - # - # Examples: - # class CreditCard < ActiveRecord::Base - # # Strip everything but digits, so the user can specify "555 234 34" or - # # "5552-3434" and both will mean "55523434" - # before_validation(on: :create) do - # self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number") - # end - # end - # - # class Subscription < ActiveRecord::Base - # before_create :record_signup - # - # private - # def record_signup - # self.signed_up_on = Date.today - # end - # end - # - # class Firm < ActiveRecord::Base - # # Disables access to the system, for associated clients and people when the firm is destroyed - # before_destroy { |record| Person.where(firm_id: record.id).update_all(access: 'disabled') } - # before_destroy { |record| Client.where(client_of: record.id).update_all(access: 'disabled') } - # end - # - # == Inheritable callback queues - # - # Besides the overwritable callback methods, it's also possible to register callbacks through the - # use of the callback macros. Their main advantage is that the macros add behavior into a callback - # queue that is kept intact down through an inheritance hierarchy. - # - # class Topic < ActiveRecord::Base - # before_destroy :destroy_author - # end - # - # class Reply < Topic - # before_destroy :destroy_readers - # end - # - # Now, when Topic#destroy is run only +destroy_author+ is called. When Reply#destroy is - # run, both +destroy_author+ and +destroy_readers+ are called. Contrast this to the following situation - # where the +before_destroy+ method is overridden: - # - # class Topic < ActiveRecord::Base - # def before_destroy() destroy_author end - # end - # - # class Reply < Topic - # def before_destroy() destroy_readers end - # end - # - # In that case, Reply#destroy would only run +destroy_readers+ and _not_ +destroy_author+. - # So, use the callback macros when you want to ensure that a certain callback is called for the entire - # hierarchy, and use the regular overwritable methods when you want to leave it up to each descendant - # to decide whether they want to call +super+ and trigger the inherited callbacks. - # - # *IMPORTANT:* In order for inheritance to work for the callback queues, you must specify the - # callbacks before specifying the associations. Otherwise, you might trigger the loading of a - # child before the parent has registered the callbacks and they won't be inherited. - # - # == Types of callbacks - # - # There are four types of callbacks accepted by the callback macros: Method references (symbol), callback objects, - # inline methods (using a proc), and inline eval methods (using a string). Method references and callback objects - # are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for - # creating mix-ins), and inline eval methods are deprecated. - # - # The method reference callbacks work by specifying a protected or private method available in the object, like this: - # - # class Topic < ActiveRecord::Base - # before_destroy :delete_parents - # - # private - # def delete_parents - # self.class.delete_all "parent_id = #{id}" - # end - # end - # - # The callback objects have methods named after the callback called with the record as the only parameter, such as: - # - # class BankAccount < ActiveRecord::Base - # before_save EncryptionWrapper.new - # after_save EncryptionWrapper.new - # after_initialize EncryptionWrapper.new - # end - # - # class EncryptionWrapper - # def before_save(record) - # record.credit_card_number = encrypt(record.credit_card_number) - # end - # - # def after_save(record) - # record.credit_card_number = decrypt(record.credit_card_number) - # end - # - # alias_method :after_initialize, :after_save - # - # private - # def encrypt(value) - # # Secrecy is committed - # end - # - # def decrypt(value) - # # Secrecy is unveiled - # end - # end - # - # So you specify the object you want messaged on a given callback. When that callback is triggered, the object has - # a method by the name of the callback messaged. You can make these callbacks more flexible by passing in other - # initialization data such as the name of the attribute to work with: - # - # class BankAccount < ActiveRecord::Base - # before_save EncryptionWrapper.new("credit_card_number") - # after_save EncryptionWrapper.new("credit_card_number") - # after_initialize EncryptionWrapper.new("credit_card_number") - # end - # - # class EncryptionWrapper - # def initialize(attribute) - # @attribute = attribute - # end - # - # def before_save(record) - # record.send("#{@attribute}=", encrypt(record.send("#{@attribute}"))) - # end - # - # def after_save(record) - # record.send("#{@attribute}=", decrypt(record.send("#{@attribute}"))) - # end - # - # alias_method :after_initialize, :after_save - # - # private - # def encrypt(value) - # # Secrecy is committed - # end - # - # def decrypt(value) - # # Secrecy is unveiled - # end - # end - # - # == before_validation* returning statements - # - # If the +before_validation+ callback throws +:abort+, the process will be - # aborted and {ActiveRecord::Base#save}[rdoc-ref:Persistence#save] will return +false+. - # If {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!] is called it will raise an ActiveRecord::RecordInvalid exception. - # Nothing will be appended to the errors object. - # - # == Canceling callbacks - # - # If a before_* callback throws +:abort+, all the later callbacks and - # the associated action are cancelled. - # Callbacks are generally run in the order they are defined, with the exception of callbacks defined as - # methods on the model, which are called last. - # - # == Ordering callbacks - # - # Sometimes the code needs that the callbacks execute in a specific order. For example, a +before_destroy+ - # callback (+log_children+ in this case) should be executed before the children get destroyed by the - # dependent: :destroy option. - # - # Let's look at the code below: - # - # class Topic < ActiveRecord::Base - # has_many :children, dependent: :destroy - # - # before_destroy :log_children - # - # private - # def log_children - # # Child processing - # end - # end - # - # In this case, the problem is that when the +before_destroy+ callback is executed, the children are not available - # because the {ActiveRecord::Base#destroy}[rdoc-ref:Persistence#destroy] callback gets executed first. - # You can use the +prepend+ option on the +before_destroy+ callback to avoid this. - # - # class Topic < ActiveRecord::Base - # has_many :children, dependent: :destroy - # - # before_destroy :log_children, prepend: true - # - # private - # def log_children - # # Child processing - # end - # end - # - # This way, the +before_destroy+ gets executed before the dependent: :destroy is called, and the data is still available. - # - # Also, there are cases when you want several callbacks of the same type to - # be executed in order. - # - # For example: - # - # class Topic - # has_many :children - # - # after_save :log_children - # after_save :do_something_else - # - # private - # - # def log_chidren - # # Child processing - # end - # - # def do_something_else - # # Something else - # end - # end - # - # In this case the +log_children+ gets executed before +do_something_else+. - # The same applies to all non-transactional callbacks. - # - # In case there are multiple transactional callbacks as seen below, the order - # is reversed. - # - # For example: - # - # class Topic - # has_many :children - # - # after_commit :log_children - # after_commit :do_something_else - # - # private - # - # def log_chidren - # # Child processing - # end - # - # def do_something_else - # # Something else - # end - # end - # - # In this case the +do_something_else+ gets executed before +log_children+. - # - # == \Transactions - # - # The entire callback chain of a {#save}[rdoc-ref:Persistence#save], {#save!}[rdoc-ref:Persistence#save!], - # or {#destroy}[rdoc-ref:Persistence#destroy] call runs within a transaction. That includes after_* hooks. - # If everything goes fine a COMMIT is executed once the chain has been completed. - # - # If a before_* callback cancels the action a ROLLBACK is issued. You - # can also trigger a ROLLBACK raising an exception in any of the callbacks, - # including after_* hooks. Note, however, that in that case the client - # needs to be aware of it because an ordinary {#save}[rdoc-ref:Persistence#save] will raise such exception - # instead of quietly returning +false+. - # - # == Debugging callbacks - # - # The callback chain is accessible via the _*_callbacks method on an object. Active Model \Callbacks support - # :before, :after and :around as values for the kind property. The kind property - # defines what part of the chain the callback runs in. - # - # To find all callbacks in the before_save callback chain: - # - # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) } - # - # Returns an array of callback objects that form the before_save chain. - # - # To further check if the before_save chain contains a proc defined as rest_when_dead use the filter property of the callback object: - # - # Topic._save_callbacks.select { |cb| cb.kind.eql?(:before) }.collect(&:filter).include?(:rest_when_dead) - # - # Returns true or false depending on whether the proc is contained in the before_save callback chain on a Topic model. - # - module Callbacks - extend ActiveSupport::Concern - - CALLBACKS = [ - :after_initialize, :after_find, :after_touch, :before_validation, :after_validation, - :before_save, :around_save, :after_save, :before_create, :around_create, - :after_create, :before_update, :around_update, :after_update, - :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback - ] - - def destroy #:nodoc: - @_destroy_callback_already_called ||= false - return if @_destroy_callback_already_called - @_destroy_callback_already_called = true - _run_destroy_callbacks { super } - rescue RecordNotDestroyed => e - @_association_destroy_exception = e - false - ensure - @_destroy_callback_already_called = false - end - - def touch(*) #:nodoc: - _run_touch_callbacks { super } - end - - def increment!(attribute, by = 1, touch: nil) # :nodoc: - touch ? _run_touch_callbacks { super } : super - end - - private - - def create_or_update(*) - _run_save_callbacks { super } - end - - def _create_record - _run_create_callbacks { super } - end - - def _update_record(*) - _run_update_callbacks { super } - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/coders/json.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/coders/json.rb deleted file mode 100644 index cb185a881e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/coders/json.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - module Coders # :nodoc: - class JSON # :nodoc: - def self.dump(obj) - ActiveSupport::JSON.encode(obj) - end - - def self.load(json) - ActiveSupport::JSON.decode(json) unless json.blank? - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/coders/yaml_column.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/coders/yaml_column.rb deleted file mode 100644 index 9c52a31b95..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/coders/yaml_column.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "yaml" - -module ActiveRecord - module Coders # :nodoc: - class YAMLColumn # :nodoc: - attr_accessor :object_class - - def initialize(attr_name, object_class = Object) - @attr_name = attr_name - @object_class = object_class - check_arity_of_constructor - end - - def dump(obj) - return if obj.nil? - - assert_valid_value(obj, action: "dump") - YAML.dump obj - end - - def load(yaml) - return object_class.new if object_class != Object && yaml.nil? - return yaml unless yaml.is_a?(String) && /^---/.match?(yaml) - obj = YAML.load(yaml) - - assert_valid_value(obj, action: "load") - obj ||= object_class.new if object_class != Object - - obj - end - - def assert_valid_value(obj, action:) - unless obj.nil? || obj.is_a?(object_class) - raise SerializationTypeMismatch, - "can't #{action} `#{@attr_name}`: was supposed to be a #{object_class}, but was a #{obj.class}. -- #{obj.inspect}" - end - end - - private - - def check_arity_of_constructor - load(nil) - rescue ArgumentError - raise ArgumentError, "Cannot serialize #{object_class}. Classes passed to `serialize` must have a 0 argument constructor." - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/collection_cache_key.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/collection_cache_key.rb deleted file mode 100644 index 0b3a078d67..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/collection_cache_key.rb +++ /dev/null @@ -1,49 +0,0 @@ -module ActiveRecord - module CollectionCacheKey - def collection_cache_key(collection = all, timestamp_column = :updated_at) # :nodoc: - query_signature = Digest::MD5.hexdigest(collection.to_sql) - key = "#{collection.model_name.cache_key}/query-#{query_signature}" - - if collection.loaded? || collection.distinct_value - size = collection.records.size - if size > 0 - timestamp = collection.max_by(×tamp_column)._read_attribute(timestamp_column) - end - else - column_type = type_for_attribute(timestamp_column.to_s) - column = "#{connection.quote_table_name(collection.table_name)}.#{connection.quote_column_name(timestamp_column)}" - select_values = "COUNT(*) AS #{connection.quote_column_name("size")}, MAX(%s) AS timestamp" - - if collection.has_limit_or_offset? - query = collection.spawn - query.select_values = [column] - subquery_alias = "subquery_for_cache_key" - subquery_column = "#{subquery_alias}.#{timestamp_column}" - subquery = query.arel.as(subquery_alias) - arel = Arel::SelectManager.new(query.engine).project(select_values % subquery_column).from(subquery) - else - query = collection.unscope(:order) - query.select_values = [select_values % column] - arel = query.arel - end - - result = connection.select_one(arel, nil, query.bound_attributes) - - if result.blank? - size = 0 - timestamp = nil - else - size = result["size"] - timestamp = column_type.deserialize(result["timestamp"]) - end - - end - - if timestamp - "#{key}-#{size}-#{timestamp.utc.to_s(cache_timestamp_format)}" - else - "#{key}-#{size}" - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/connection_pool.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/connection_pool.rb deleted file mode 100644 index f667d06f9e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ /dev/null @@ -1,989 +0,0 @@ -require "thread" -require "concurrent/map" -require "monitor" - -module ActiveRecord - # Raised when a connection could not be obtained within the connection - # acquisition timeout period: because max connections in pool - # are in use. - class ConnectionTimeoutError < ConnectionNotEstablished - end - - # Raised when a pool was unable to get ahold of all its connections - # to perform a "group" action such as - # {ActiveRecord::Base.connection_pool.disconnect!}[rdoc-ref:ConnectionAdapters::ConnectionPool#disconnect!] - # or {ActiveRecord::Base.clear_reloadable_connections!}[rdoc-ref:ConnectionAdapters::ConnectionHandler#clear_reloadable_connections!]. - class ExclusiveConnectionTimeoutError < ConnectionTimeoutError - end - - module ConnectionAdapters - # Connection pool base class for managing Active Record database - # connections. - # - # == Introduction - # - # A connection pool synchronizes thread access to a limited number of - # database connections. The basic idea is that each thread checks out a - # database connection from the pool, uses that connection, and checks the - # connection back in. ConnectionPool is completely thread-safe, and will - # ensure that a connection cannot be used by two threads at the same time, - # as long as ConnectionPool's contract is correctly followed. It will also - # handle cases in which there are more threads than connections: if all - # connections have been checked out, and a thread tries to checkout a - # connection anyway, then ConnectionPool will wait until some other thread - # has checked in a connection. - # - # == Obtaining (checking out) a connection - # - # Connections can be obtained and used from a connection pool in several - # ways: - # - # 1. Simply use {ActiveRecord::Base.connection}[rdoc-ref:ConnectionHandling.connection] - # as with Active Record 2.1 and - # earlier (pre-connection-pooling). Eventually, when you're done with - # the connection(s) and wish it to be returned to the pool, you call - # {ActiveRecord::Base.clear_active_connections!}[rdoc-ref:ConnectionAdapters::ConnectionHandler#clear_active_connections!]. - # This will be the default behavior for Active Record when used in conjunction with - # Action Pack's request handling cycle. - # 2. Manually check out a connection from the pool with - # {ActiveRecord::Base.connection_pool.checkout}[rdoc-ref:#checkout]. You are responsible for - # returning this connection to the pool when finished by calling - # {ActiveRecord::Base.connection_pool.checkin(connection)}[rdoc-ref:#checkin]. - # 3. Use {ActiveRecord::Base.connection_pool.with_connection(&block)}[rdoc-ref:#with_connection], which - # obtains a connection, yields it as the sole argument to the block, - # and returns it to the pool after the block completes. - # - # Connections in the pool are actually AbstractAdapter objects (or objects - # compatible with AbstractAdapter's interface). - # - # == Options - # - # There are several connection-pooling-related options that you can add to - # your database connection configuration: - # - # * +pool+: number indicating size of connection pool (default 5) - # * +checkout_timeout+: number of seconds to block and wait for a connection - # before giving up and raising a timeout error (default 5 seconds). - # * +reaping_frequency+: frequency in seconds to periodically run the - # Reaper, which attempts to find and recover connections from dead - # threads, which can occur if a programmer forgets to close a - # connection at the end of a thread or a thread dies unexpectedly. - # Regardless of this setting, the Reaper will be invoked before every - # blocking wait. (Default +nil+, which means don't schedule the Reaper). - # - #-- - # Synchronization policy: - # * all public methods can be called outside +synchronize+ - # * access to these instance variables needs to be in +synchronize+: - # * @connections - # * @now_connecting - # * private methods that require being called in a +synchronize+ blocks - # are now explicitly documented - class ConnectionPool - # Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool - # with which it shares a Monitor. But could be a generic Queue. - # - # The Queue in stdlib's 'thread' could replace this class except - # stdlib's doesn't support waiting with a timeout. - class Queue - def initialize(lock = Monitor.new) - @lock = lock - @cond = @lock.new_cond - @num_waiting = 0 - @queue = [] - end - - # Test if any threads are currently waiting on the queue. - def any_waiting? - synchronize do - @num_waiting > 0 - end - end - - # Returns the number of threads currently waiting on this - # queue. - def num_waiting - synchronize do - @num_waiting - end - end - - # Add +element+ to the queue. Never blocks. - def add(element) - synchronize do - @queue.push element - @cond.signal - end - end - - # If +element+ is in the queue, remove and return it, or +nil+. - def delete(element) - synchronize do - @queue.delete(element) - end - end - - # Remove all elements from the queue. - def clear - synchronize do - @queue.clear - end - end - - # Remove the head of the queue. - # - # If +timeout+ is not given, remove and return the head the - # queue if the number of available elements is strictly - # greater than the number of threads currently waiting (that - # is, don't jump ahead in line). Otherwise, return +nil+. - # - # If +timeout+ is given, block if there is no element - # available, waiting up to +timeout+ seconds for an element to - # become available. - # - # Raises: - # - ActiveRecord::ConnectionTimeoutError if +timeout+ is given and no element - # becomes available within +timeout+ seconds, - def poll(timeout = nil) - synchronize { internal_poll(timeout) } - end - - private - - def internal_poll(timeout) - no_wait_poll || (timeout && wait_poll(timeout)) - end - - def synchronize(&block) - @lock.synchronize(&block) - end - - # Test if the queue currently contains any elements. - def any? - !@queue.empty? - end - - # A thread can remove an element from the queue without - # waiting if and only if the number of currently available - # connections is strictly greater than the number of waiting - # threads. - def can_remove_no_wait? - @queue.size > @num_waiting - end - - # Removes and returns the head of the queue if possible, or +nil+. - def remove - @queue.shift - end - - # Remove and return the head the queue if the number of - # available elements is strictly greater than the number of - # threads currently waiting. Otherwise, return +nil+. - def no_wait_poll - remove if can_remove_no_wait? - end - - # Waits on the queue up to +timeout+ seconds, then removes and - # returns the head of the queue. - def wait_poll(timeout) - @num_waiting += 1 - - t0 = Time.now - elapsed = 0 - loop do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - @cond.wait(timeout - elapsed) - end - - return remove if any? - - elapsed = Time.now - t0 - if elapsed >= timeout - msg = "could not obtain a connection from the pool within %0.3f seconds (waited %0.3f seconds); all pooled connections were in use" % - [timeout, elapsed] - raise ConnectionTimeoutError, msg - end - end - ensure - @num_waiting -= 1 - end - end - - # Adds the ability to turn a basic fair FIFO queue into one - # biased to some thread. - module BiasableQueue # :nodoc: - class BiasedConditionVariable # :nodoc: - # semantics of condition variables guarantee that +broadcast+, +broadcast_on_biased+, - # +signal+ and +wait+ methods are only called while holding a lock - def initialize(lock, other_cond, preferred_thread) - @real_cond = lock.new_cond - @other_cond = other_cond - @preferred_thread = preferred_thread - @num_waiting_on_real_cond = 0 - end - - def broadcast - broadcast_on_biased - @other_cond.broadcast - end - - def broadcast_on_biased - @num_waiting_on_real_cond = 0 - @real_cond.broadcast - end - - def signal - if @num_waiting_on_real_cond > 0 - @num_waiting_on_real_cond -= 1 - @real_cond - else - @other_cond - end.signal - end - - def wait(timeout) - if Thread.current == @preferred_thread - @num_waiting_on_real_cond += 1 - @real_cond - else - @other_cond - end.wait(timeout) - end - end - - def with_a_bias_for(thread) - previous_cond = nil - new_cond = nil - synchronize do - previous_cond = @cond - @cond = new_cond = BiasedConditionVariable.new(@lock, @cond, thread) - end - yield - ensure - synchronize do - @cond = previous_cond if previous_cond - new_cond.broadcast_on_biased if new_cond # wake up any remaining sleepers - end - end - end - - # Connections must be leased while holding the main pool mutex. This is - # an internal subclass that also +.leases+ returned connections while - # still in queue's critical section (queue synchronizes with the same - # +@lock+ as the main pool) so that a returned connection is already - # leased and there is no need to re-enter synchronized block. - class ConnectionLeasingQueue < Queue # :nodoc: - include BiasableQueue - - private - def internal_poll(timeout) - conn = super - conn.lease if conn - conn - end - end - - # Every +frequency+ seconds, the reaper will call +reap+ on +pool+. - # A reaper instantiated with a +nil+ frequency will never reap the - # connection pool. - # - # Configure the frequency by setting "reaping_frequency" in your - # database yaml file. - class Reaper - attr_reader :pool, :frequency - - def initialize(pool, frequency) - @pool = pool - @frequency = frequency - end - - def run - return unless frequency - Thread.new(frequency, pool) { |t, p| - loop do - sleep t - p.reap - end - } - end - end - - include MonitorMixin - include QueryCache::ConnectionPoolConfiguration - - attr_accessor :automatic_reconnect, :checkout_timeout, :schema_cache - attr_reader :spec, :connections, :size, :reaper - - # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification - # object which describes database connection information (e.g. adapter, - # host name, username, password, etc), as well as the maximum size for - # this ConnectionPool. - # - # The default ConnectionPool maximum size is 5. - def initialize(spec) - super() - - @spec = spec - - @checkout_timeout = (spec.config[:checkout_timeout] && spec.config[:checkout_timeout].to_f) || 5 - @reaper = Reaper.new(self, (spec.config[:reaping_frequency] && spec.config[:reaping_frequency].to_f)) - @reaper.run - - # default max pool size to 5 - @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5 - - # This variable tracks the cache of threads mapped to reserved connections, with the - # sole purpose of speeding up the +connection+ method. It is not the authoritative - # registry of which thread owns which connection. Connection ownership is tracked by - # the +connection.owner+ attr on each +connection+ instance. - # The invariant works like this: if there is mapping of thread => conn, - # then that +thread+ does indeed own that +conn+. However, an absence of a such - # mapping does not mean that the +thread+ doesn't own the said connection. In - # that case +conn.owner+ attr should be consulted. - # Access and modification of +@thread_cached_conns+ does not require - # synchronization. - @thread_cached_conns = Concurrent::Map.new(initial_capacity: @size) - - @connections = [] - @automatic_reconnect = true - - # Connection pool allows for concurrent (outside the main +synchronize+ section) - # establishment of new connections. This variable tracks the number of threads - # currently in the process of independently establishing connections to the DB. - @now_connecting = 0 - - @threads_blocking_new_connections = 0 - - @available = ConnectionLeasingQueue.new self - - @lock_thread = false - end - - def lock_thread=(lock_thread) - if lock_thread - @lock_thread = Thread.current - else - @lock_thread = nil - end - end - - # Retrieve the connection associated with the current thread, or call - # #checkout to obtain one if necessary. - # - # #connection can be called any number of times; the connection is - # held in a cache keyed by a thread. - def connection - @thread_cached_conns[connection_cache_key(@lock_thread || Thread.current)] ||= checkout - end - - # Returns true if there is an open connection being used for the current thread. - # - # This method only works for connections that have been obtained through - # #connection or #with_connection methods. Connections obtained through - # #checkout will not be detected by #active_connection? - def active_connection? - @thread_cached_conns[connection_cache_key(Thread.current)] - end - - # Signal that the thread is finished with the current connection. - # #release_connection releases the connection-thread association - # and returns the connection to the pool. - # - # This method only works for connections that have been obtained through - # #connection or #with_connection methods, connections obtained through - # #checkout will not be automatically released. - def release_connection(owner_thread = Thread.current) - if conn = @thread_cached_conns.delete(connection_cache_key(owner_thread)) - checkin conn - end - end - - # If a connection obtained through #connection or #with_connection methods - # already exists yield it to the block. If no such connection - # exists checkout a connection, yield it to the block, and checkin the - # connection when finished. - def with_connection - unless conn = @thread_cached_conns[connection_cache_key(Thread.current)] - conn = connection - fresh_connection = true - end - yield conn - ensure - release_connection if fresh_connection - end - - # Returns true if a connection has already been opened. - def connected? - synchronize { @connections.any? } - end - - # Disconnects all connections in the pool, and clears the pool. - # - # Raises: - # - ActiveRecord::ExclusiveConnectionTimeoutError if unable to gain ownership of all - # connections in the pool within a timeout interval (default duration is - # spec.config[:checkout_timeout] * 2 seconds). - def disconnect(raise_on_acquisition_timeout = true) - with_exclusively_acquired_all_connections(raise_on_acquisition_timeout) do - synchronize do - @connections.each do |conn| - if conn.in_use? - conn.steal! - checkin conn - end - conn.disconnect! - end - @connections = [] - @available.clear - end - end - end - - # Disconnects all connections in the pool, and clears the pool. - # - # The pool first tries to gain ownership of all connections. If unable to - # do so within a timeout interval (default duration is - # spec.config[:checkout_timeout] * 2 seconds), then the pool is forcefully - # disconnected without any regard for other connection owning threads. - def disconnect! - disconnect(false) - end - - # Clears the cache which maps classes and re-connects connections that - # require reloading. - # - # Raises: - # - ActiveRecord::ExclusiveConnectionTimeoutError if unable to gain ownership of all - # connections in the pool within a timeout interval (default duration is - # spec.config[:checkout_timeout] * 2 seconds). - def clear_reloadable_connections(raise_on_acquisition_timeout = true) - with_exclusively_acquired_all_connections(raise_on_acquisition_timeout) do - synchronize do - @connections.each do |conn| - if conn.in_use? - conn.steal! - checkin conn - end - conn.disconnect! if conn.requires_reloading? - end - @connections.delete_if(&:requires_reloading?) - @available.clear - end - end - end - - # Clears the cache which maps classes and re-connects connections that - # require reloading. - # - # The pool first tries to gain ownership of all connections. If unable to - # do so within a timeout interval (default duration is - # spec.config[:checkout_timeout] * 2 seconds), then the pool forcefully - # clears the cache and reloads connections without any regard for other - # connection owning threads. - def clear_reloadable_connections! - clear_reloadable_connections(false) - end - - # Check-out a database connection from the pool, indicating that you want - # to use it. You should call #checkin when you no longer need this. - # - # This is done by either returning and leasing existing connection, or by - # creating a new connection and leasing it. - # - # If all connections are leased and the pool is at capacity (meaning the - # number of currently leased connections is greater than or equal to the - # size limit set), an ActiveRecord::ConnectionTimeoutError exception will be raised. - # - # Returns: an AbstractAdapter object. - # - # Raises: - # - ActiveRecord::ConnectionTimeoutError no connection can be obtained from the pool. - def checkout(checkout_timeout = @checkout_timeout) - checkout_and_verify(acquire_connection(checkout_timeout)) - end - - # Check-in a database connection back into the pool, indicating that you - # no longer need this connection. - # - # +conn+: an AbstractAdapter object, which was obtained by earlier by - # calling #checkout on this pool. - def checkin(conn) - conn.lock.synchronize do - synchronize do - remove_connection_from_thread_cache conn - - conn._run_checkin_callbacks do - conn.expire - end - - @available.add conn - end - end - end - - # Remove a connection from the connection pool. The connection will - # remain open and active but will no longer be managed by this pool. - def remove(conn) - needs_new_connection = false - - synchronize do - remove_connection_from_thread_cache conn - - @connections.delete conn - @available.delete conn - - # @available.any_waiting? => true means that prior to removing this - # conn, the pool was at its max size (@connections.size == @size). - # This would mean that any threads stuck waiting in the queue wouldn't - # know they could checkout_new_connection, so let's do it for them. - # Because condition-wait loop is encapsulated in the Queue class - # (that in turn is oblivious to ConnectionPool implementation), threads - # that are "stuck" there are helpless. They have no way of creating - # new connections and are completely reliant on us feeding available - # connections into the Queue. - needs_new_connection = @available.any_waiting? - end - - # This is intentionally done outside of the synchronized section as we - # would like not to hold the main mutex while checking out new connections. - # Thus there is some chance that needs_new_connection information is now - # stale, we can live with that (bulk_make_new_connections will make - # sure not to exceed the pool's @size limit). - bulk_make_new_connections(1) if needs_new_connection - end - - # Recover lost connections for the pool. A lost connection can occur if - # a programmer forgets to checkin a connection at the end of a thread - # or a thread dies unexpectedly. - def reap - stale_connections = synchronize do - @connections.select do |conn| - conn.in_use? && !conn.owner.alive? - end.each do |conn| - conn.steal! - end - end - - stale_connections.each do |conn| - if conn.active? - conn.reset! - checkin conn - else - remove conn - end - end - end - - def num_waiting_in_queue # :nodoc: - @available.num_waiting - end - - # Return connection pool's usage statistic - # Example: - # - # ActiveRecord::Base.connection_pool.stat # => { size: 15, connections: 1, busy: 1, dead: 0, idle: 0, waiting: 0, checkout_timeout: 5 } - def stat - synchronize do - { - size: size, - connections: @connections.size, - busy: @connections.count { |c| c.in_use? && c.owner.alive? }, - dead: @connections.count { |c| c.in_use? && !c.owner.alive? }, - idle: @connections.count { |c| !c.in_use? }, - waiting: num_waiting_in_queue, - checkout_timeout: checkout_timeout - } - end - end - - private - #-- - # this is unfortunately not concurrent - def bulk_make_new_connections(num_new_conns_needed) - num_new_conns_needed.times do - # try_to_checkout_new_connection will not exceed pool's @size limit - if new_conn = try_to_checkout_new_connection - # make the new_conn available to the starving threads stuck @available Queue - checkin(new_conn) - end - end - end - - #-- - # From the discussion on GitHub: - # https://github.com/rails/rails/pull/14938#commitcomment-6601951 - # This hook-in method allows for easier monkey-patching fixes needed by - # JRuby users that use Fibers. - def connection_cache_key(thread) - thread - end - - # Take control of all existing connections so a "group" action such as - # reload/disconnect can be performed safely. It is no longer enough to - # wrap it in +synchronize+ because some pool's actions are allowed - # to be performed outside of the main +synchronize+ block. - def with_exclusively_acquired_all_connections(raise_on_acquisition_timeout = true) - with_new_connections_blocked do - attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout) - yield - end - end - - def attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout = true) - collected_conns = synchronize do - # account for our own connections - @connections.select { |conn| conn.owner == Thread.current } - end - - newly_checked_out = [] - timeout_time = Time.now + (@checkout_timeout * 2) - - @available.with_a_bias_for(Thread.current) do - loop do - synchronize do - return if collected_conns.size == @connections.size && @now_connecting == 0 - remaining_timeout = timeout_time - Time.now - remaining_timeout = 0 if remaining_timeout < 0 - conn = checkout_for_exclusive_access(remaining_timeout) - collected_conns << conn - newly_checked_out << conn - end - end - end - rescue ExclusiveConnectionTimeoutError - # raise_on_acquisition_timeout == false means we are directed to ignore any - # timeouts and are expected to just give up: we've obtained as many connections - # as possible, note that in a case like that we don't return any of the - # +newly_checked_out+ connections. - - if raise_on_acquisition_timeout - release_newly_checked_out = true - raise - end - rescue Exception # if something else went wrong - # this can't be a "naked" rescue, because we have should return conns - # even for non-StandardErrors - release_newly_checked_out = true - raise - ensure - if release_newly_checked_out && newly_checked_out - # releasing only those conns that were checked out in this method, conns - # checked outside this method (before it was called) are not for us to release - newly_checked_out.each { |conn| checkin(conn) } - end - end - - #-- - # Must be called in a synchronize block. - def checkout_for_exclusive_access(checkout_timeout) - checkout(checkout_timeout) - rescue ConnectionTimeoutError - # this block can't be easily moved into attempt_to_checkout_all_existing_connections's - # rescue block, because doing so would put it outside of synchronize section, without - # being in a critical section thread_report might become inaccurate - msg = "could not obtain ownership of all database connections in #{checkout_timeout} seconds" - - thread_report = [] - @connections.each do |conn| - unless conn.owner == Thread.current - thread_report << "#{conn} is owned by #{conn.owner}" - end - end - - msg << " (#{thread_report.join(', ')})" if thread_report.any? - - raise ExclusiveConnectionTimeoutError, msg - end - - def with_new_connections_blocked - synchronize do - @threads_blocking_new_connections += 1 - end - - yield - ensure - num_new_conns_required = 0 - - synchronize do - @threads_blocking_new_connections -= 1 - - if @threads_blocking_new_connections.zero? - @available.clear - - num_new_conns_required = num_waiting_in_queue - - @connections.each do |conn| - next if conn.in_use? - - @available.add conn - num_new_conns_required -= 1 - end - end - end - - bulk_make_new_connections(num_new_conns_required) if num_new_conns_required > 0 - end - - # Acquire a connection by one of 1) immediately removing one - # from the queue of available connections, 2) creating a new - # connection if the pool is not at capacity, 3) waiting on the - # queue for a connection to become available. - # - # Raises: - # - ActiveRecord::ConnectionTimeoutError if a connection could not be acquired - # - #-- - # Implementation detail: the connection returned by +acquire_connection+ - # will already be "+connection.lease+ -ed" to the current thread. - def acquire_connection(checkout_timeout) - # NOTE: we rely on +@available.poll+ and +try_to_checkout_new_connection+ to - # +conn.lease+ the returned connection (and to do this in a +synchronized+ - # section). This is not the cleanest implementation, as ideally we would - # synchronize { conn.lease } in this method, but by leaving it to +@available.poll+ - # and +try_to_checkout_new_connection+ we can piggyback on +synchronize+ sections - # of the said methods and avoid an additional +synchronize+ overhead. - if conn = @available.poll || try_to_checkout_new_connection - conn - else - reap - @available.poll(checkout_timeout) - end - end - - #-- - # if owner_thread param is omitted, this must be called in synchronize block - def remove_connection_from_thread_cache(conn, owner_thread = conn.owner) - @thread_cached_conns.delete_pair(connection_cache_key(owner_thread), conn) - end - alias_method :release, :remove_connection_from_thread_cache - - def new_connection - Base.send(spec.adapter_method, spec.config).tap do |conn| - conn.schema_cache = schema_cache.dup if schema_cache - end - end - - # If the pool is not at a +@size+ limit, establish new connection. Connecting - # to the DB is done outside main synchronized section. - #-- - # Implementation constraint: a newly established connection returned by this - # method must be in the +.leased+ state. - def try_to_checkout_new_connection - # first in synchronized section check if establishing new conns is allowed - # and increment @now_connecting, to prevent overstepping this pool's @size - # constraint - do_checkout = synchronize do - if @threads_blocking_new_connections.zero? && (@connections.size + @now_connecting) < @size - @now_connecting += 1 - end - end - if do_checkout - begin - # if successfully incremented @now_connecting establish new connection - # outside of synchronized section - conn = checkout_new_connection - ensure - synchronize do - if conn - adopt_connection(conn) - # returned conn needs to be already leased - conn.lease - end - @now_connecting -= 1 - end - end - end - end - - def adopt_connection(conn) - conn.pool = self - @connections << conn - end - - def checkout_new_connection - raise ConnectionNotEstablished unless @automatic_reconnect - new_connection - end - - def checkout_and_verify(c) - c._run_checkout_callbacks do - c.verify! - end - c - rescue - remove c - c.disconnect! - raise - end - end - - # ConnectionHandler is a collection of ConnectionPool objects. It is used - # for keeping separate connection pools that connect to different databases. - # - # For example, suppose that you have 5 models, with the following hierarchy: - # - # class Author < ActiveRecord::Base - # end - # - # class BankAccount < ActiveRecord::Base - # end - # - # class Book < ActiveRecord::Base - # establish_connection "library_db" - # end - # - # class ScaryBook < Book - # end - # - # class GoodBook < Book - # end - # - # And a database.yml that looked like this: - # - # development: - # database: my_application - # host: localhost - # - # library_db: - # database: library - # host: some.library.org - # - # Your primary database in the development environment is "my_application" - # but the Book model connects to a separate database called "library_db" - # (this can even be a database on a different machine). - # - # Book, ScaryBook and GoodBook will all use the same connection pool to - # "library_db" while Author, BankAccount, and any other models you create - # will use the default connection pool to "my_application". - # - # The various connection pools are managed by a single instance of - # ConnectionHandler accessible via ActiveRecord::Base.connection_handler. - # All Active Record models use this handler to determine the connection pool that they - # should use. - # - # The ConnectionHandler class is not coupled with the Active models, as it has no knowlodge - # about the model. The model needs to pass a specification name to the handler, - # in order to lookup the correct connection pool. - class ConnectionHandler - def initialize - # These caches are keyed by spec.name (ConnectionSpecification#name). - @owner_to_pool = Concurrent::Map.new(initial_capacity: 2) do |h, k| - h[k] = Concurrent::Map.new(initial_capacity: 2) - end - end - - def connection_pool_list - owner_to_pool.values.compact - end - alias :connection_pools :connection_pool_list - - def establish_connection(config) - resolver = ConnectionSpecification::Resolver.new(Base.configurations) - spec = resolver.spec(config) - - remove_connection(spec.name) - - message_bus = ActiveSupport::Notifications.instrumenter - payload = { - connection_id: object_id - } - if spec - payload[:spec_name] = spec.name - payload[:config] = spec.config - end - - message_bus.instrument("!connection.active_record", payload) do - owner_to_pool[spec.name] = ConnectionAdapters::ConnectionPool.new(spec) - end - - owner_to_pool[spec.name] - end - - # Returns true if there are any active connections among the connection - # pools that the ConnectionHandler is managing. - def active_connections? - connection_pool_list.any?(&:active_connection?) - end - - # Returns any connections in use by the current thread back to the pool, - # and also returns connections to the pool cached by threads that are no - # longer alive. - def clear_active_connections! - connection_pool_list.each(&:release_connection) - end - - # Clears the cache which maps classes. - # - # See ConnectionPool#clear_reloadable_connections! for details. - def clear_reloadable_connections! - connection_pool_list.each(&:clear_reloadable_connections!) - end - - def clear_all_connections! - connection_pool_list.each(&:disconnect!) - end - - # Locate the connection of the nearest super class. This can be an - # active or defined connection: if it is the latter, it will be - # opened and set as the active connection for the class it was defined - # for (not necessarily the current class). - def retrieve_connection(spec_name) #:nodoc: - pool = retrieve_connection_pool(spec_name) - raise ConnectionNotEstablished, "No connection pool with '#{spec_name}' found." unless pool - conn = pool.connection - raise ConnectionNotEstablished, "No connection for '#{spec_name}' in connection pool" unless conn - conn - end - - # Returns true if a connection that's accessible to this class has - # already been opened. - def connected?(spec_name) - conn = retrieve_connection_pool(spec_name) - conn && conn.connected? - end - - # Remove the connection for this class. This will close the active - # connection and the defined connection (if they exist). The result - # can be used as an argument for #establish_connection, for easily - # re-establishing the connection. - def remove_connection(spec_name) - if pool = owner_to_pool.delete(spec_name) - pool.automatic_reconnect = false - pool.disconnect! - pool.spec.config - end - end - - # Retrieving the connection pool happens a lot, so we cache it in @owner_to_pool. - # This makes retrieving the connection pool O(1) once the process is warm. - # When a connection is established or removed, we invalidate the cache. - def retrieve_connection_pool(spec_name) - owner_to_pool.fetch(spec_name) do - # Check if a connection was previously established in an ancestor process, - # which may have been forked. - if ancestor_pool = pool_from_any_process_for(spec_name) - # A connection was established in an ancestor process that must have - # subsequently forked. We can't reuse the connection, but we can copy - # the specification and establish a new connection with it. - establish_connection(ancestor_pool.spec.to_hash).tap do |pool| - pool.schema_cache = ancestor_pool.schema_cache if ancestor_pool.schema_cache - end - else - owner_to_pool[spec_name] = nil - end - end - end - - private - - def owner_to_pool - @owner_to_pool[Process.pid] - end - - def pool_from_any_process_for(spec_name) - owner_to_pool = @owner_to_pool.values.reverse.find { |v| v[spec_name] } - owner_to_pool && owner_to_pool[spec_name] - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_limits.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_limits.rb deleted file mode 100644 index 407e019326..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_limits.rb +++ /dev/null @@ -1,65 +0,0 @@ -module ActiveRecord - module ConnectionAdapters # :nodoc: - module DatabaseLimits - # Returns the maximum length of a table alias. - def table_alias_length - 255 - end - - # Returns the maximum length of a column name. - def column_name_length - 64 - end - - # Returns the maximum length of a table name. - def table_name_length - 64 - end - - # Returns the maximum allowed length for an index name. This - # limit is enforced by \Rails and is less than or equal to - # #index_name_length. The gap between - # #index_name_length is to allow internal \Rails - # operations to use prefixes in temporary operations. - def allowed_index_name_length - index_name_length - end - - # Returns the maximum length of an index name. - def index_name_length - 64 - end - - # Returns the maximum number of columns per table. - def columns_per_table - 1024 - end - - # Returns the maximum number of indexes per table. - def indexes_per_table - 16 - end - - # Returns the maximum number of columns in a multicolumn index. - def columns_per_multicolumn_index - 16 - end - - # Returns the maximum number of elements in an IN (x,y,z) clause. - # +nil+ means no limit. - def in_clause_length - nil - end - - # Returns the maximum length of an SQL query. - def sql_query_length - 1048575 - end - - # Returns maximum number of joins in a single query. - def joins_per_query - 256 - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb deleted file mode 100644 index 32386b6b14..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/database_statements.rb +++ /dev/null @@ -1,399 +0,0 @@ -module ActiveRecord - module ConnectionAdapters # :nodoc: - module DatabaseStatements - def initialize - super - reset_transaction - end - - # Converts an arel AST to SQL - def to_sql(arel, binds = []) - if arel.respond_to?(:ast) - collected = visitor.accept(arel.ast, collector) - collected.compile(binds, self).freeze - else - arel.dup.freeze - end - end - - # This is used in the StatementCache object. It returns an object that - # can be used to query the database repeatedly. - def cacheable_query(klass, arel) # :nodoc: - collected = visitor.accept(arel.ast, collector) - if prepared_statements - klass.query(collected.value) - else - klass.partial_query(collected.value) - end - end - - # Returns an ActiveRecord::Result instance. - def select_all(arel, name = nil, binds = [], preparable: nil) - arel, binds = binds_from_relation arel, binds - sql = to_sql(arel, binds) - if !prepared_statements || (arel.is_a?(String) && preparable.nil?) - preparable = false - else - preparable = visitor.preparable - end - if prepared_statements && preparable - select_prepared(sql, name, binds) - else - select(sql, name, binds) - end - end - - # Returns a record hash with the column names as keys and column values - # as values. - def select_one(arel, name = nil, binds = []) - select_all(arel, name, binds).first - end - - # Returns a single value from a record - def select_value(arel, name = nil, binds = []) - single_value_from_rows(select_rows(arel, name, binds)) - end - - # Returns an array of the values of the first column in a select: - # select_values("SELECT id FROM companies LIMIT 3") => [1,2,3] - def select_values(arel, name = nil, binds = []) - select_rows(arel, name, binds).map(&:first) - end - - # Returns an array of arrays containing the field values. - # Order is the same as that returned by +columns+. - def select_rows(arel, name = nil, binds = []) - select_all(arel, name, binds).rows - end - - def query_value(sql, name = nil) # :nodoc: - single_value_from_rows(query(sql, name)) - end - - def query_values(sql, name = nil) # :nodoc: - query(sql, name).map(&:first) - end - - def query(sql, name = nil) # :nodoc: - exec_query(sql, name).rows - end - - # Executes the SQL statement in the context of this connection and returns - # the raw result from the connection adapter. - # Note: depending on your database connector, the result returned by this - # method may be manually memory managed. Consider using the exec_query - # wrapper instead. - def execute(sql, name = nil) - raise NotImplementedError - end - - # Executes +sql+ statement in the context of this connection using - # +binds+ as the bind substitutes. +name+ is logged along with - # the executed +sql+ statement. - def exec_query(sql, name = "SQL", binds = [], prepare: false) - raise NotImplementedError - end - - # Executes insert +sql+ statement in the context of this connection using - # +binds+ as the bind substitutes. +name+ is logged along with - # the executed +sql+ statement. - def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil) - sql, binds = sql_for_insert(sql, pk, nil, sequence_name, binds) - exec_query(sql, name, binds) - end - - # Executes delete +sql+ statement in the context of this connection using - # +binds+ as the bind substitutes. +name+ is logged along with - # the executed +sql+ statement. - def exec_delete(sql, name = nil, binds = []) - exec_query(sql, name, binds) - end - - # Executes the truncate statement. - def truncate(table_name, name = nil) - raise NotImplementedError - end - - # Executes update +sql+ statement in the context of this connection using - # +binds+ as the bind substitutes. +name+ is logged along with - # the executed +sql+ statement. - def exec_update(sql, name = nil, binds = []) - exec_query(sql, name, binds) - end - - # Executes an INSERT query and returns the new record's ID - # - # +id_value+ will be returned unless the value is +nil+, in - # which case the database will attempt to calculate the last inserted - # id and return that value. - # - # If the next id was calculated in advance (as in Oracle), it should be - # passed in as +id_value+. - def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) - value = exec_insert(to_sql(arel, binds), name, binds, pk, sequence_name) - id_value || last_inserted_id(value) - end - alias create insert - - # Executes the update statement and returns the number of rows affected. - def update(arel, name = nil, binds = []) - exec_update(to_sql(arel, binds), name, binds) - end - - # Executes the delete statement and returns the number of rows affected. - def delete(arel, name = nil, binds = []) - exec_delete(to_sql(arel, binds), name, binds) - end - - # Returns +true+ when the connection adapter supports prepared statement - # caching, otherwise returns +false+ - def supports_statement_cache? - false - end - - # Runs the given block in a database transaction, and returns the result - # of the block. - # - # == Nested transactions support - # - # Most databases don't support true nested transactions. At the time of - # writing, the only database that supports true nested transactions that - # we're aware of, is MS-SQL. - # - # In order to get around this problem, #transaction will emulate the effect - # of nested transactions, by using savepoints: - # http://dev.mysql.com/doc/refman/5.7/en/savepoint.html - # Savepoints are supported by MySQL and PostgreSQL. SQLite3 version >= '3.6.8' - # supports savepoints. - # - # It is safe to call this method if a database transaction is already open, - # i.e. if #transaction is called within another #transaction block. In case - # of a nested call, #transaction will behave as follows: - # - # - The block will be run without doing anything. All database statements - # that happen within the block are effectively appended to the already - # open database transaction. - # - However, if +:requires_new+ is set, the block will be wrapped in a - # database savepoint acting as a sub-transaction. - # - # === Caveats - # - # MySQL doesn't support DDL transactions. If you perform a DDL operation, - # then any created savepoints will be automatically released. For example, - # if you've created a savepoint, then you execute a CREATE TABLE statement, - # then the savepoint that was created will be automatically released. - # - # This means that, on MySQL, you shouldn't execute DDL operations inside - # a #transaction call that you know might create a savepoint. Otherwise, - # #transaction will raise exceptions when it tries to release the - # already-automatically-released savepoints: - # - # Model.connection.transaction do # BEGIN - # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 - # Model.connection.create_table(...) - # # active_record_1 now automatically released - # end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error! - # end - # - # == Transaction isolation - # - # If your database supports setting the isolation level for a transaction, you can set - # it like so: - # - # Post.transaction(isolation: :serializable) do - # # ... - # end - # - # Valid isolation levels are: - # - # * :read_uncommitted - # * :read_committed - # * :repeatable_read - # * :serializable - # - # You should consult the documentation for your database to understand the - # semantics of these different levels: - # - # * http://www.postgresql.org/docs/current/static/transaction-iso.html - # * https://dev.mysql.com/doc/refman/5.7/en/set-transaction.html - # - # An ActiveRecord::TransactionIsolationError will be raised if: - # - # * The adapter does not support setting the isolation level - # * You are joining an existing open transaction - # * You are creating a nested (savepoint) transaction - # - # The mysql2 and postgresql adapters support setting the transaction - # isolation level. - def transaction(requires_new: nil, isolation: nil, joinable: true) - if !requires_new && current_transaction.joinable? - if isolation - raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction" - end - yield - else - transaction_manager.within_new_transaction(isolation: isolation, joinable: joinable) { yield } - end - rescue ActiveRecord::Rollback - # rollbacks are silently swallowed - end - - attr_reader :transaction_manager #:nodoc: - - delegate :within_new_transaction, :open_transactions, :current_transaction, :begin_transaction, :commit_transaction, :rollback_transaction, to: :transaction_manager - - def transaction_open? - current_transaction.open? - end - - def reset_transaction #:nodoc: - @transaction_manager = ConnectionAdapters::TransactionManager.new(self) - end - - # Register a record with the current transaction so that its after_commit and after_rollback callbacks - # can be called. - def add_transaction_record(record) - current_transaction.add_record(record) - end - - def transaction_state - current_transaction.state - end - - # Begins the transaction (and turns off auto-committing). - def begin_db_transaction() end - - def transaction_isolation_levels - { - read_uncommitted: "READ UNCOMMITTED", - read_committed: "READ COMMITTED", - repeatable_read: "REPEATABLE READ", - serializable: "SERIALIZABLE" - } - end - - # Begins the transaction with the isolation level set. Raises an error by - # default; adapters that support setting the isolation level should implement - # this method. - def begin_isolated_db_transaction(isolation) - raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation" - end - - # Commits the transaction (and turns on auto-committing). - def commit_db_transaction() end - - # Rolls back the transaction (and turns on auto-committing). Must be - # done if the transaction block raises an exception or returns false. - def rollback_db_transaction - exec_rollback_db_transaction - end - - def exec_rollback_db_transaction() end #:nodoc: - - def rollback_to_savepoint(name = nil) - exec_rollback_to_savepoint(name) - end - - def default_sequence_name(table, column) - nil - end - - # Set the sequence to the max value of the table's column. - def reset_sequence!(table, column, sequence = nil) - # Do nothing by default. Implement for PostgreSQL, Oracle, ... - end - - # Inserts the given fixture into the table. Overridden in adapters that require - # something beyond a simple insert (eg. Oracle). - def insert_fixture(fixture, table_name) - fixture = fixture.stringify_keys - - columns = schema_cache.columns_hash(table_name) - binds = fixture.map do |name, value| - if column = columns[name] - type = lookup_cast_type_from_column(column) - Relation::QueryAttribute.new(name, value, type) - else - raise Fixture::FixtureError, %(table "#{table_name}" has no column named #{name.inspect}.) - end - end - key_list = fixture.keys.map { |name| quote_column_name(name) } - value_list = binds.map(&:value_for_database).map do |value| - begin - quote(value) - rescue TypeError - quote(YAML.dump(value)) - end - end - - execute "INSERT INTO #{quote_table_name(table_name)} (#{key_list.join(', ')}) VALUES (#{value_list.join(', ')})", "Fixture Insert" - end - - def empty_insert_statement_value - "DEFAULT VALUES" - end - - # Sanitizes the given LIMIT parameter in order to prevent SQL injection. - # - # The +limit+ may be anything that can evaluate to a string via #to_s. It - # should look like an integer, or an Arel SQL literal. - # - # Returns Integer and Arel::Nodes::SqlLiteral limits as is. - def sanitize_limit(limit) - if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral) - limit - else - Integer(limit) - end - end - - # The default strategy for an UPDATE with joins is to use a subquery. This doesn't work - # on MySQL (even when aliasing the tables), but MySQL allows using JOIN directly in - # an UPDATE statement, so in the MySQL adapters we redefine this to do that. - def join_to_update(update, select, key) # :nodoc: - subselect = subquery_for(key, select) - - update.where key.in(subselect) - end - alias join_to_delete join_to_update - - private - - # Returns a subquery for the given key using the join information. - def subquery_for(key, select) - subselect = select.clone - subselect.projections = [key] - subselect - end - - # Returns an ActiveRecord::Result instance. - def select(sql, name = nil, binds = []) - exec_query(sql, name, binds, prepare: false) - end - - def select_prepared(sql, name = nil, binds = []) - exec_query(sql, name, binds, prepare: true) - end - - def sql_for_insert(sql, pk, id_value, sequence_name, binds) - [sql, binds] - end - - def last_inserted_id(result) - single_value_from_rows(result.rows) - end - - def single_value_from_rows(rows) - row = rows.first - row && row.first - end - - def binds_from_relation(relation, binds) - if relation.is_a?(Relation) && binds.empty? - relation, binds = relation.arel, relation.bound_attributes - end - [relation, binds] - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/query_cache.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/query_cache.rb deleted file mode 100644 index a5b10e4081..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/query_cache.rb +++ /dev/null @@ -1,135 +0,0 @@ -module ActiveRecord - module ConnectionAdapters # :nodoc: - module QueryCache - class << self - def included(base) #:nodoc: - dirties_query_cache base, :insert, :update, :delete, :rollback_to_savepoint, :rollback_db_transaction - - base.set_callback :checkout, :after, :configure_query_cache! - base.set_callback :checkin, :after, :disable_query_cache! - end - - def dirties_query_cache(base, *method_names) - method_names.each do |method_name| - base.class_eval <<-end_code, __FILE__, __LINE__ + 1 - def #{method_name}(*) - clear_query_cache if @query_cache_enabled - super - end - end_code - end - end - end - - module ConnectionPoolConfiguration - def initialize(*) - super - @query_cache_enabled = Concurrent::Map.new { false } - end - - def enable_query_cache! - @query_cache_enabled[connection_cache_key(Thread.current)] = true - connection.enable_query_cache! if active_connection? - end - - def disable_query_cache! - @query_cache_enabled.delete connection_cache_key(Thread.current) - connection.disable_query_cache! if active_connection? - end - - def query_cache_enabled - @query_cache_enabled[connection_cache_key(Thread.current)] - end - end - - attr_reader :query_cache, :query_cache_enabled - - def initialize(*) - super - @query_cache = Hash.new { |h, sql| h[sql] = {} } - @query_cache_enabled = false - end - - # Enable the query cache within the block. - def cache - old, @query_cache_enabled = @query_cache_enabled, true - yield - ensure - @query_cache_enabled = old - clear_query_cache unless @query_cache_enabled - end - - def enable_query_cache! - @query_cache_enabled = true - end - - def disable_query_cache! - @query_cache_enabled = false - clear_query_cache - end - - # Disable the query cache within the block. - def uncached - old, @query_cache_enabled = @query_cache_enabled, false - yield - ensure - @query_cache_enabled = old - end - - # Clears the query cache. - # - # One reason you may wish to call this method explicitly is between queries - # that ask the database to randomize results. Otherwise the cache would see - # the same SQL query and repeatedly return the same result each time, silently - # undermining the randomness you were expecting. - def clear_query_cache - @lock.synchronize do - @query_cache.clear - end - end - - def select_all(arel, name = nil, binds = [], preparable: nil) - if @query_cache_enabled && !locked?(arel) - arel, binds = binds_from_relation arel, binds - sql = to_sql(arel, binds) - cache_sql(sql, name, binds) { super(sql, name, binds, preparable: preparable) } - else - super - end - end - - private - - def cache_sql(sql, name, binds) - @lock.synchronize do - result = - if @query_cache[sql].key?(binds) - ActiveSupport::Notifications.instrument( - "sql.active_record", - sql: sql, - binds: binds, - type_casted_binds: -> { type_casted_binds(binds) }, - name: name, - connection_id: object_id, - cached: true, - ) - @query_cache[sql][binds] - else - @query_cache[sql][binds] = yield - end - result.dup - end - end - - # If arel is locked this is a SELECT ... FOR UPDATE or somesuch. Such - # queries should not be cached. - def locked?(arel) - arel.respond_to?(:locked) && arel.locked - end - - def configure_query_cache! - enable_query_cache! if pool.query_cache_enabled - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/quoting.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/quoting.rb deleted file mode 100644 index 4440b828b5..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/quoting.rb +++ /dev/null @@ -1,218 +0,0 @@ -require "active_support/core_ext/big_decimal/conversions" -require "active_support/multibyte/chars" - -module ActiveRecord - module ConnectionAdapters # :nodoc: - module Quoting - # Quotes the column value to help prevent - # {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection]. - def quote(value) - value = id_value_for_database(value) if value.is_a?(Base) - - if value.respond_to?(:quoted_id) - at = value.method(:quoted_id).source_location - at &&= " at %s:%d" % at - - owner = value.method(:quoted_id).owner.to_s - klass = value.class.to_s - klass += "(#{owner})" unless owner == klass - - ActiveSupport::Deprecation.warn \ - "Defining #quoted_id is deprecated and will be ignored in Rails 5.2. (defined on #{klass}#{at})" - return value.quoted_id - end - - _quote(value) - end - - # Cast a +value+ to a type that the database understands. For example, - # SQLite does not understand dates, so this method will convert a Date - # to a String. - def type_cast(value, column = nil) - value = id_value_for_database(value) if value.is_a?(Base) - - if value.respond_to?(:quoted_id) && value.respond_to?(:id) - return value.id - end - - if column - value = type_cast_from_column(column, value) - end - - _type_cast(value) - rescue TypeError - to_type = column ? " to #{column.type}" : "" - raise TypeError, "can't cast #{value.class}#{to_type}" - end - - # If you are having to call this function, you are likely doing something - # wrong. The column does not have sufficient type information if the user - # provided a custom type on the class level either explicitly (via - # Attributes::ClassMethods#attribute) or implicitly (via - # AttributeMethods::Serialization::ClassMethods#serialize, +time_zone_aware_attributes+). - # In almost all cases, the sql type should only be used to change quoting behavior, when the primitive to - # represent the type doesn't sufficiently reflect the differences - # (varchar vs binary) for example. The type used to get this primitive - # should have been provided before reaching the connection adapter. - def type_cast_from_column(column, value) # :nodoc: - if column - type = lookup_cast_type_from_column(column) - type.serialize(value) - else - value - end - end - - # See docs for #type_cast_from_column - def lookup_cast_type_from_column(column) # :nodoc: - lookup_cast_type(column.sql_type) - end - - def fetch_type_metadata(sql_type) - cast_type = lookup_cast_type(sql_type) - SqlTypeMetadata.new( - sql_type: sql_type, - type: cast_type.type, - limit: cast_type.limit, - precision: cast_type.precision, - scale: cast_type.scale, - ) - end - - # Quotes a string, escaping any ' (single quote) and \ (backslash) - # characters. - def quote_string(s) - s.gsub('\\'.freeze, '\&\&'.freeze).gsub("'".freeze, "''".freeze) # ' (for ruby-mode) - end - - # Quotes the column name. Defaults to no quoting. - def quote_column_name(column_name) - column_name.to_s - end - - # Quotes the table name. Defaults to column name quoting. - def quote_table_name(table_name) - quote_column_name(table_name) - end - - # Override to return the quoted table name for assignment. Defaults to - # table quoting. - # - # This works for mysql2 where table.column can be used to - # resolve ambiguity. - # - # We override this in the sqlite3 and postgresql adapters to use only - # the column name (as per syntax requirements). - def quote_table_name_for_assignment(table, attr) - quote_table_name("#{table}.#{attr}") - end - - def quote_default_expression(value, column) # :nodoc: - if value.is_a?(Proc) - value.call - else - value = lookup_cast_type(column.sql_type).serialize(value) - quote(value) - end - end - - def quoted_true - "'t'".freeze - end - - def unquoted_true - "t".freeze - end - - def quoted_false - "'f'".freeze - end - - def unquoted_false - "f".freeze - end - - # Quote date/time values for use in SQL input. Includes microseconds - # if the value is a Time responding to usec. - def quoted_date(value) - if value.acts_like?(:time) - zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal - - if value.respond_to?(zone_conversion_method) - value = value.send(zone_conversion_method) - end - end - - result = value.to_s(:db) - if value.respond_to?(:usec) && value.usec > 0 - "#{result}.#{sprintf("%06d", value.usec)}" - else - result - end - end - - def quoted_time(value) # :nodoc: - value = value.change(year: 2000, month: 1, day: 1) - quoted_date(value).sub(/\A\d\d\d\d-\d\d-\d\d /, "") - end - - def quoted_binary(value) # :nodoc: - "'#{quote_string(value.to_s)}'" - end - - def type_casted_binds(binds) # :nodoc: - if binds.first.is_a?(Array) - binds.map { |column, value| type_cast(value, column) } - else - binds.map { |attr| type_cast(attr.value_for_database) } - end - end - - private - def id_value_for_database(value) - if primary_key = value.class.primary_key - value.instance_variable_get(:@attributes)[primary_key].value_for_database - end - end - - def types_which_need_no_typecasting - [nil, Numeric, String] - end - - def _quote(value) - case value - when String, ActiveSupport::Multibyte::Chars - "'#{quote_string(value.to_s)}'" - when true then quoted_true - when false then quoted_false - when nil then "NULL" - # BigDecimals need to be put in a non-normalized form and quoted. - when BigDecimal then value.to_s("F") - when Numeric, ActiveSupport::Duration then value.to_s - when Type::Binary::Data then quoted_binary(value) - when Type::Time::Value then "'#{quoted_time(value)}'" - when Date, Time then "'#{quoted_date(value)}'" - when Symbol then "'#{quote_string(value.to_s)}'" - when Class then "'#{value}'" - else raise TypeError, "can't quote #{value.class.name}" - end - end - - def _type_cast(value) - case value - when Symbol, ActiveSupport::Multibyte::Chars, Type::Binary::Data - value.to_s - when true then unquoted_true - when false then unquoted_false - # BigDecimals need to be put in a non-normalized form and quoted. - when BigDecimal then value.to_s("F") - when Type::Time::Value then quoted_time(value) - when Date, Time then quoted_date(value) - when *types_which_need_no_typecasting - value - else raise TypeError - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/savepoints.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/savepoints.rb deleted file mode 100644 index 3a06f75292..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/savepoints.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module Savepoints - def current_savepoint_name - current_transaction.savepoint_name - end - - def create_savepoint(name = current_savepoint_name) - execute("SAVEPOINT #{name}") - end - - def exec_rollback_to_savepoint(name = current_savepoint_name) - execute("ROLLBACK TO SAVEPOINT #{name}") - end - - def release_savepoint(name = current_savepoint_name) - execute("RELEASE SAVEPOINT #{name}") - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_creation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_creation.rb deleted file mode 100644 index 8c372f760d..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_creation.rb +++ /dev/null @@ -1,137 +0,0 @@ -require "active_support/core_ext/string/strip" - -module ActiveRecord - module ConnectionAdapters - class AbstractAdapter - class SchemaCreation # :nodoc: - def initialize(conn) - @conn = conn - @cache = {} - end - - def accept(o) - m = @cache[o.class] ||= "visit_#{o.class.name.split('::').last}" - send m, o - end - - delegate :quote_column_name, :quote_table_name, :quote_default_expression, :type_to_sql, - :options_include_default?, :supports_indexes_in_create?, :supports_foreign_keys_in_create?, :foreign_key_options, to: :@conn - private :quote_column_name, :quote_table_name, :quote_default_expression, :type_to_sql, - :options_include_default?, :supports_indexes_in_create?, :supports_foreign_keys_in_create?, :foreign_key_options - - private - - def visit_AlterTable(o) - sql = "ALTER TABLE #{quote_table_name(o.name)} " - sql << o.adds.map { |col| accept col }.join(" ") - sql << o.foreign_key_adds.map { |fk| visit_AddForeignKey fk }.join(" ") - sql << o.foreign_key_drops.map { |fk| visit_DropForeignKey fk }.join(" ") - end - - def visit_ColumnDefinition(o) - o.sql_type = type_to_sql(o.type, o.options) - column_sql = "#{quote_column_name(o.name)} #{o.sql_type}" - add_column_options!(column_sql, column_options(o)) unless o.type == :primary_key - column_sql - end - - def visit_AddColumnDefinition(o) - "ADD #{accept(o.column)}" - end - - def visit_TableDefinition(o) - create_sql = "CREATE#{' TEMPORARY' if o.temporary} TABLE #{quote_table_name(o.name)} " - - statements = o.columns.map { |c| accept c } - statements << accept(o.primary_keys) if o.primary_keys - - if supports_indexes_in_create? - statements.concat(o.indexes.map { |column_name, options| index_in_create(o.name, column_name, options) }) - end - - if supports_foreign_keys_in_create? - statements.concat(o.foreign_keys.map { |to_table, options| foreign_key_in_create(o.name, to_table, options) }) - end - - create_sql << "(#{statements.join(', ')})" if statements.present? - add_table_options!(create_sql, table_options(o)) - create_sql << " AS #{@conn.to_sql(o.as)}" if o.as - create_sql - end - - def visit_PrimaryKeyDefinition(o) - "PRIMARY KEY (#{o.name.map { |name| quote_column_name(name) }.join(', ')})" - end - - def visit_ForeignKeyDefinition(o) - sql = <<-SQL.strip_heredoc - CONSTRAINT #{quote_column_name(o.name)} - FOREIGN KEY (#{quote_column_name(o.column)}) - REFERENCES #{quote_table_name(o.to_table)} (#{quote_column_name(o.primary_key)}) - SQL - sql << " #{action_sql('DELETE', o.on_delete)}" if o.on_delete - sql << " #{action_sql('UPDATE', o.on_update)}" if o.on_update - sql - end - - def visit_AddForeignKey(o) - "ADD #{accept(o)}" - end - - def visit_DropForeignKey(name) - "DROP CONSTRAINT #{quote_column_name(name)}" - end - - def table_options(o) - table_options = {} - table_options[:comment] = o.comment - table_options[:options] = o.options - table_options - end - - def add_table_options!(create_sql, options) - if options_sql = options[:options] - create_sql << " #{options_sql}" - end - end - - def column_options(o) - o.options.merge(column: o) - end - - def add_column_options!(sql, options) - sql << " DEFAULT #{quote_default_expression(options[:default], options[:column])}" if options_include_default?(options) - # must explicitly check for :null to allow change_column to work on migrations - if options[:null] == false - sql << " NOT NULL" - end - if options[:auto_increment] == true - sql << " AUTO_INCREMENT" - end - if options[:primary_key] == true - sql << " PRIMARY KEY" - end - sql - end - - def foreign_key_in_create(from_table, to_table, options) - options = foreign_key_options(from_table, to_table, options) - accept ForeignKeyDefinition.new(from_table, to_table, options) - end - - def action_sql(action, dependency) - case dependency - when :nullify then "ON #{action} SET NULL" - when :cascade then "ON #{action} CASCADE" - when :restrict then "ON #{action} RESTRICT" - else - raise ArgumentError, <<-MSG.strip_heredoc - '#{dependency}' is not supported for :on_update or :on_delete. - Supported values are: :nullify, :cascade, :restrict - MSG - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_definitions.rb deleted file mode 100644 index cd7dbcc0c8..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ /dev/null @@ -1,627 +0,0 @@ -module ActiveRecord - module ConnectionAdapters #:nodoc: - # Abstract representation of an index definition on a table. Instances of - # this type are typically created and returned by methods in database - # adapters. e.g. ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter#indexes - IndexDefinition = Struct.new(:table, :name, :unique, :columns, :lengths, :orders, :where, :type, :using, :comment) #:nodoc: - - # Abstract representation of a column definition. Instances of this type - # are typically created by methods in TableDefinition, and added to the - # +columns+ attribute of said TableDefinition object, in order to be used - # for generating a number of table creation or table changing SQL statements. - ColumnDefinition = Struct.new(:name, :type, :options, :sql_type) do # :nodoc: - def primary_key? - options[:primary_key] - end - - [:limit, :precision, :scale, :default, :null, :collation, :comment].each do |option_name| - module_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{option_name} - options[:#{option_name}] - end - - def #{option_name}=(value) - options[:#{option_name}] = value - end - CODE - end - end - - AddColumnDefinition = Struct.new(:column) # :nodoc: - - ChangeColumnDefinition = Struct.new(:column, :name) #:nodoc: - - PrimaryKeyDefinition = Struct.new(:name) # :nodoc: - - ForeignKeyDefinition = Struct.new(:from_table, :to_table, :options) do #:nodoc: - def name - options[:name] - end - - def column - options[:column] - end - - def primary_key - options[:primary_key] || default_primary_key - end - - def on_delete - options[:on_delete] - end - - def on_update - options[:on_update] - end - - def custom_primary_key? - options[:primary_key] != default_primary_key - end - - def defined_for?(to_table_ord = nil, to_table: nil, **options) - if to_table_ord - self.to_table == to_table_ord.to_s - else - (to_table.nil? || to_table.to_s == self.to_table) && - options.all? { |k, v| self.options[k].to_s == v.to_s } - end - end - - private - def default_primary_key - "id" - end - end - - class ReferenceDefinition # :nodoc: - def initialize( - name, - polymorphic: false, - index: true, - foreign_key: false, - type: :bigint, - **options - ) - @name = name - @polymorphic = polymorphic - @index = index - @foreign_key = foreign_key - @type = type - @options = options - - if polymorphic && foreign_key - raise ArgumentError, "Cannot add a foreign key to a polymorphic relation" - end - end - - def add_to(table) - columns.each do |column_options| - table.column(*column_options) - end - - if index - table.index(column_names, index_options) - end - - if foreign_key - table.foreign_key(foreign_table_name, foreign_key_options) - end - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :name, :polymorphic, :index, :foreign_key, :type, :options - - private - - def as_options(value) - value.is_a?(Hash) ? value : {} - end - - def polymorphic_options - as_options(polymorphic).merge(options.slice(:null, :first, :after)) - end - - def index_options - as_options(index) - end - - def foreign_key_options - as_options(foreign_key).merge(column: column_name) - end - - def columns - result = [[column_name, type, options]] - if polymorphic - result.unshift(["#{name}_type", :string, polymorphic_options]) - end - result - end - - def column_name - "#{name}_id" - end - - def column_names - columns.map(&:first) - end - - def foreign_table_name - foreign_key_options.fetch(:to_table) do - Base.pluralize_table_names ? name.to_s.pluralize : name - end - end - end - - module ColumnMethods - # Appends a primary key definition to the table definition. - # Can be called multiple times, but this is probably not a good idea. - def primary_key(name, type = :primary_key, **options) - column(name, type, options.merge(primary_key: true)) - end - - # Appends a column or columns of a specified type. - # - # t.string(:goat) - # t.string(:goat, :sheep) - # - # See TableDefinition#column - [ - :bigint, - :binary, - :boolean, - :date, - :datetime, - :decimal, - :float, - :integer, - :string, - :text, - :time, - :timestamp, - :virtual, - ].each do |column_type| - module_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{column_type}(*args, **options) - args.each { |name| column(name, :#{column_type}, options) } - end - CODE - end - alias_method :numeric, :decimal - end - - # Represents the schema of an SQL table in an abstract way. This class - # provides methods for manipulating the schema representation. - # - # Inside migration files, the +t+ object in {create_table}[rdoc-ref:SchemaStatements#create_table] - # is actually of this type: - # - # class SomeMigration < ActiveRecord::Migration[5.0] - # def up - # create_table :foo do |t| - # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition" - # end - # end - # - # def down - # ... - # end - # end - # - class TableDefinition - include ColumnMethods - - attr_accessor :indexes - attr_reader :name, :temporary, :options, :as, :foreign_keys, :comment - - def initialize(name, temporary = false, options = nil, as = nil, comment: nil) - @columns_hash = {} - @indexes = [] - @foreign_keys = [] - @primary_keys = nil - @temporary = temporary - @options = options - @as = as - @name = name - @comment = comment - end - - def primary_keys(name = nil) # :nodoc: - @primary_keys = PrimaryKeyDefinition.new(name) if name - @primary_keys - end - - # Returns an array of ColumnDefinition objects for the columns of the table. - def columns; @columns_hash.values; end - - # Returns a ColumnDefinition for the column with name +name+. - def [](name) - @columns_hash[name.to_s] - end - - # Instantiates a new column for the table. - # See {connection.add_column}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_column] - # for available options. - # - # Additional options are: - # * :index - - # Create an index for the column. Can be either true or an options hash. - # - # This method returns self. - # - # == Examples - # - # # Assuming +td+ is an instance of TableDefinition - # td.column(:granted, :boolean, index: true) - # - # == Short-hand examples - # - # Instead of calling #column directly, you can also work with the short-hand definitions for the default types. - # They use the type as the method name instead of as a parameter and allow for multiple columns to be defined - # in a single statement. - # - # What can be written like this with the regular calls to column: - # - # create_table :products do |t| - # t.column :shop_id, :integer - # t.column :creator_id, :integer - # t.column :item_number, :string - # t.column :name, :string, default: "Untitled" - # t.column :value, :string, default: "Untitled" - # t.column :created_at, :datetime - # t.column :updated_at, :datetime - # end - # add_index :products, :item_number - # - # can also be written as follows using the short-hand: - # - # create_table :products do |t| - # t.integer :shop_id, :creator_id - # t.string :item_number, index: true - # t.string :name, :value, default: "Untitled" - # t.timestamps null: false - # end - # - # There's a short-hand method for each of the type values declared at the top. And then there's - # TableDefinition#timestamps that'll add +created_at+ and +updated_at+ as datetimes. - # - # TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type - # column if the :polymorphic option is supplied. If :polymorphic is a hash of - # options, these will be used when creating the _type column. The :index option - # will also create an index, similar to calling {add_index}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_index]. - # So what can be written like this: - # - # create_table :taggings do |t| - # t.integer :tag_id, :tagger_id, :taggable_id - # t.string :tagger_type - # t.string :taggable_type, default: 'Photo' - # end - # add_index :taggings, :tag_id, name: 'index_taggings_on_tag_id' - # add_index :taggings, [:tagger_id, :tagger_type] - # - # Can also be written as follows using references: - # - # create_table :taggings do |t| - # t.references :tag, index: { name: 'index_taggings_on_tag_id' } - # t.references :tagger, polymorphic: true, index: true - # t.references :taggable, polymorphic: { default: 'Photo' } - # end - def column(name, type, options = {}) - name = name.to_s - type = type.to_sym if type - options = options.dup - - if @columns_hash[name] && @columns_hash[name].primary_key? - raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table." - end - - index_options = options.delete(:index) - index(name, index_options.is_a?(Hash) ? index_options : {}) if index_options - @columns_hash[name] = new_column_definition(name, type, options) - self - end - - # remove the column +name+ from the table. - # remove_column(:account_id) - def remove_column(name) - @columns_hash.delete name.to_s - end - - # Adds index options to the indexes hash, keyed by column name - # This is primarily used to track indexes that need to be created after the table - # - # index(:account_id, name: 'index_projects_on_account_id') - def index(column_name, options = {}) - indexes << [column_name, options] - end - - def foreign_key(table_name, options = {}) # :nodoc: - table_name_prefix = ActiveRecord::Base.table_name_prefix - table_name_suffix = ActiveRecord::Base.table_name_suffix - table_name = "#{table_name_prefix}#{table_name}#{table_name_suffix}" - foreign_keys.push([table_name, options]) - end - - # Appends :datetime columns :created_at and - # :updated_at to the table. See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps] - # - # t.timestamps null: false - def timestamps(**options) - options[:null] = false if options[:null].nil? - - column(:created_at, :datetime, options) - column(:updated_at, :datetime, options) - end - - # Adds a reference. - # - # t.references(:user) - # t.belongs_to(:supplier, foreign_key: true) - # - # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use. - def references(*args, **options) - args.each do |ref_name| - ReferenceDefinition.new(ref_name, options).add_to(self) - end - end - alias :belongs_to :references - - def new_column_definition(name, type, **options) # :nodoc: - type = aliased_types(type.to_s, type) - options[:primary_key] ||= type == :primary_key - options[:null] = false if options[:primary_key] - create_column_definition(name, type, options) - end - - private - def create_column_definition(name, type, options) - ColumnDefinition.new(name, type, options) - end - - def aliased_types(name, fallback) - "timestamp" == name ? :datetime : fallback - end - end - - class AlterTable # :nodoc: - attr_reader :adds - attr_reader :foreign_key_adds - attr_reader :foreign_key_drops - - def initialize(td) - @td = td - @adds = [] - @foreign_key_adds = [] - @foreign_key_drops = [] - end - - def name; @td.name; end - - def add_foreign_key(to_table, options) - @foreign_key_adds << ForeignKeyDefinition.new(name, to_table, options) - end - - def drop_foreign_key(name) - @foreign_key_drops << name - end - - def add_column(name, type, options) - name = name.to_s - type = type.to_sym - @adds << AddColumnDefinition.new(@td.new_column_definition(name, type, options)) - end - end - - # Represents an SQL table in an abstract way for updating a table. - # Also see TableDefinition and {connection.create_table}[rdoc-ref:SchemaStatements#create_table] - # - # Available transformations are: - # - # change_table :table do |t| - # t.primary_key - # t.column - # t.index - # t.rename_index - # t.timestamps - # t.change - # t.change_default - # t.rename - # t.references - # t.belongs_to - # t.string - # t.text - # t.integer - # t.bigint - # t.float - # t.decimal - # t.numeric - # t.datetime - # t.timestamp - # t.time - # t.date - # t.binary - # t.boolean - # t.remove - # t.remove_references - # t.remove_belongs_to - # t.remove_index - # t.remove_timestamps - # end - # - class Table - include ColumnMethods - - attr_reader :name - - def initialize(table_name, base) - @name = table_name - @base = base - end - - # Adds a new column to the named table. - # - # t.column(:name, :string) - # - # See TableDefinition#column for details of the options you can use. - def column(column_name, type, options = {}) - @base.add_column(name, column_name, type, options) - end - - # Checks to see if a column exists. - # - # t.string(:name) unless t.column_exists?(:name, :string) - # - # See {connection.column_exists?}[rdoc-ref:SchemaStatements#column_exists?] - def column_exists?(column_name, type = nil, options = {}) - @base.column_exists?(name, column_name, type, options) - end - - # Adds a new index to the table. +column_name+ can be a single Symbol, or - # an Array of Symbols. - # - # t.index(:name) - # t.index([:branch_id, :party_id], unique: true) - # t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party') - # - # See {connection.add_index}[rdoc-ref:SchemaStatements#add_index] for details of the options you can use. - def index(column_name, options = {}) - @base.add_index(name, column_name, options) - end - - # Checks to see if an index exists. - # - # unless t.index_exists?(:branch_id) - # t.index(:branch_id) - # end - # - # See {connection.index_exists?}[rdoc-ref:SchemaStatements#index_exists?] - def index_exists?(column_name, options = {}) - @base.index_exists?(name, column_name, options) - end - - # Renames the given index on the table. - # - # t.rename_index(:user_id, :account_id) - # - # See {connection.rename_index}[rdoc-ref:SchemaStatements#rename_index] - def rename_index(index_name, new_index_name) - @base.rename_index(name, index_name, new_index_name) - end - - # Adds timestamps (+created_at+ and +updated_at+) columns to the table. - # - # t.timestamps(null: false) - # - # See {connection.add_timestamps}[rdoc-ref:SchemaStatements#add_timestamps] - def timestamps(options = {}) - @base.add_timestamps(name, options) - end - - # Changes the column's definition according to the new options. - # - # t.change(:name, :string, limit: 80) - # t.change(:description, :text) - # - # See TableDefinition#column for details of the options you can use. - def change(column_name, type, options = {}) - @base.change_column(name, column_name, type, options) - end - - # Sets a new default value for a column. - # - # t.change_default(:qualification, 'new') - # t.change_default(:authorized, 1) - # t.change_default(:status, from: nil, to: "draft") - # - # See {connection.change_column_default}[rdoc-ref:SchemaStatements#change_column_default] - def change_default(column_name, default_or_changes) - @base.change_column_default(name, column_name, default_or_changes) - end - - # Removes the column(s) from the table definition. - # - # t.remove(:qualification) - # t.remove(:qualification, :experience) - # - # See {connection.remove_columns}[rdoc-ref:SchemaStatements#remove_columns] - def remove(*column_names) - @base.remove_columns(name, *column_names) - end - - # Removes the given index from the table. - # - # t.remove_index(:branch_id) - # t.remove_index(column: [:branch_id, :party_id]) - # t.remove_index(name: :by_branch_party) - # - # See {connection.remove_index}[rdoc-ref:SchemaStatements#remove_index] - def remove_index(options = {}) - @base.remove_index(name, options) - end - - # Removes the timestamp columns (+created_at+ and +updated_at+) from the table. - # - # t.remove_timestamps - # - # See {connection.remove_timestamps}[rdoc-ref:SchemaStatements#remove_timestamps] - def remove_timestamps(options = {}) - @base.remove_timestamps(name, options) - end - - # Renames a column. - # - # t.rename(:description, :name) - # - # See {connection.rename_column}[rdoc-ref:SchemaStatements#rename_column] - def rename(column_name, new_column_name) - @base.rename_column(name, column_name, new_column_name) - end - - # Adds a reference. - # - # t.references(:user) - # t.belongs_to(:supplier, foreign_key: true) - # - # See {connection.add_reference}[rdoc-ref:SchemaStatements#add_reference] for details of the options you can use. - def references(*args, **options) - args.each do |ref_name| - @base.add_reference(name, ref_name, options) - end - end - alias :belongs_to :references - - # Removes a reference. Optionally removes a +type+ column. - # - # t.remove_references(:user) - # t.remove_belongs_to(:supplier, polymorphic: true) - # - # See {connection.remove_reference}[rdoc-ref:SchemaStatements#remove_reference] - def remove_references(*args, **options) - args.each do |ref_name| - @base.remove_reference(name, ref_name, options) - end - end - alias :remove_belongs_to :remove_references - - # Adds a foreign key. - # - # t.foreign_key(:authors) - # - # See {connection.add_foreign_key}[rdoc-ref:SchemaStatements#add_foreign_key] - def foreign_key(*args) # :nodoc: - @base.add_foreign_key(name, *args) - end - - # Checks to see if a foreign key exists. - # - # t.foreign_key(:authors) unless t.foreign_key_exists?(:authors) - # - # See {connection.foreign_key_exists?}[rdoc-ref:SchemaStatements#foreign_key_exists?] - def foreign_key_exists?(*args) # :nodoc: - @base.foreign_key_exists?(name, *args) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_dumper.rb deleted file mode 100644 index 34036d8a1d..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_dumper.rb +++ /dev/null @@ -1,117 +0,0 @@ -module ActiveRecord - module ConnectionAdapters # :nodoc: - # The goal of this module is to move Adapter specific column - # definitions to the Adapter instead of having it in the schema - # dumper itself. This code represents the normal case. - # We can then redefine how certain data types may be handled in the schema dumper on the - # Adapter level by over-writing this code inside the database specific adapters - module ColumnDumper - def column_spec(column) - [schema_type_with_virtual(column), prepare_column_options(column)] - end - - def column_spec_for_primary_key(column) - return {} if default_primary_key?(column) - spec = { id: schema_type(column).inspect } - spec.merge!(prepare_column_options(column).except!(:null)) - spec[:default] ||= "nil" if explicit_primary_key_default?(column) - spec - end - - # This can be overridden on an Adapter level basis to support other - # extended datatypes (Example: Adding an array option in the - # PostgreSQL::ColumnDumper) - def prepare_column_options(column) - spec = {} - - if limit = schema_limit(column) - spec[:limit] = limit - end - - if precision = schema_precision(column) - spec[:precision] = precision - end - - if scale = schema_scale(column) - spec[:scale] = scale - end - - default = schema_default(column) if column.has_default? - spec[:default] = default unless default.nil? - - spec[:null] = "false" unless column.null - - if collation = schema_collation(column) - spec[:collation] = collation - end - - spec[:comment] = column.comment.inspect if column.comment.present? - - spec - end - - # Lists the valid migration options - def migration_keys # :nodoc: - column_options_keys - end - deprecate :migration_keys - - private - - def default_primary_key?(column) - schema_type(column) == :bigint - end - - def explicit_primary_key_default?(column) - false - end - - def schema_type_with_virtual(column) - if supports_virtual_columns? && column.virtual? - :virtual - else - schema_type(column) - end - end - - def schema_type(column) - if column.bigint? - :bigint - else - column.type - end - end - - def schema_limit(column) - limit = column.limit unless column.bigint? - limit.inspect if limit && limit != native_database_types[column.type][:limit] - end - - def schema_precision(column) - column.precision.inspect if column.precision - end - - def schema_scale(column) - column.scale.inspect if column.scale - end - - def schema_default(column) - type = lookup_cast_type_from_column(column) - default = type.deserialize(column.default) - if default.nil? - schema_expression(column) - else - type.type_cast_for_schema(default) - end - end - - def schema_expression(column) - "-> { #{column.default_function.inspect} }" if column.default_function - end - - def schema_collation(column) - column.collation.inspect if column.collation - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_statements.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_statements.rb deleted file mode 100644 index b2bad27d61..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ /dev/null @@ -1,1325 +0,0 @@ -require "active_record/migration/join_table" -require "active_support/core_ext/string/access" -require "digest" - -module ActiveRecord - module ConnectionAdapters # :nodoc: - module SchemaStatements - include ActiveRecord::Migration::JoinTable - - # Returns a hash of mappings from the abstract data types to the native - # database types. See TableDefinition#column for details on the recognized - # abstract data types. - def native_database_types - {} - end - - def table_options(table_name) - nil - end - - # Returns the table comment that's stored in database metadata. - def table_comment(table_name) - nil - end - - # Truncates a table alias according to the limits of the current adapter. - def table_alias_for(table_name) - table_name[0...table_alias_length].tr(".", "_") - end - - # Returns the relation names useable to back Active Record models. - # For most adapters this means all #tables and #views. - def data_sources - query_values(data_source_sql, "SCHEMA") - rescue NotImplementedError - tables | views - end - - # Checks to see if the data source +name+ exists on the database. - # - # data_source_exists?(:ebooks) - # - def data_source_exists?(name) - query_values(data_source_sql(name), "SCHEMA").any? if name.present? - rescue NotImplementedError - data_sources.include?(name.to_s) - end - - # Returns an array of table names defined in the database. - def tables - query_values(data_source_sql(type: "BASE TABLE"), "SCHEMA") - end - - # Checks to see if the table +table_name+ exists on the database. - # - # table_exists?(:developers) - # - def table_exists?(table_name) - query_values(data_source_sql(table_name, type: "BASE TABLE"), "SCHEMA").any? if table_name.present? - rescue NotImplementedError - tables.include?(table_name.to_s) - end - - # Returns an array of view names defined in the database. - def views - query_values(data_source_sql(type: "VIEW"), "SCHEMA") - end - - # Checks to see if the view +view_name+ exists on the database. - # - # view_exists?(:ebooks) - # - def view_exists?(view_name) - query_values(data_source_sql(view_name, type: "VIEW"), "SCHEMA").any? if view_name.present? - rescue NotImplementedError - views.include?(view_name.to_s) - end - - # Returns an array of indexes for the given table. - def indexes(table_name, name = nil) - raise NotImplementedError, "#indexes is not implemented" - end - - # Checks to see if an index exists on a table for a given index definition. - # - # # Check an index exists - # index_exists?(:suppliers, :company_id) - # - # # Check an index on multiple columns exists - # index_exists?(:suppliers, [:company_id, :company_type]) - # - # # Check a unique index exists - # index_exists?(:suppliers, :company_id, unique: true) - # - # # Check an index with a custom name exists - # index_exists?(:suppliers, :company_id, name: "idx_company_id") - # - def index_exists?(table_name, column_name, options = {}) - column_names = Array(column_name).map(&:to_s) - checks = [] - checks << lambda { |i| i.columns == column_names } - checks << lambda { |i| i.unique } if options[:unique] - checks << lambda { |i| i.name == options[:name].to_s } if options[:name] - - indexes(table_name).any? { |i| checks.all? { |check| check[i] } } - end - - # Returns an array of Column objects for the table specified by +table_name+. - # See the concrete implementation for details on the expected parameter values. - def columns(table_name) - raise NotImplementedError, "#columns is not implemented" - end - - # Checks to see if a column exists in a given table. - # - # # Check a column exists - # column_exists?(:suppliers, :name) - # - # # Check a column exists of a particular type - # column_exists?(:suppliers, :name, :string) - # - # # Check a column exists with a specific definition - # column_exists?(:suppliers, :name, :string, limit: 100) - # column_exists?(:suppliers, :name, :string, default: 'default') - # column_exists?(:suppliers, :name, :string, null: false) - # column_exists?(:suppliers, :tax, :decimal, precision: 8, scale: 2) - # - def column_exists?(table_name, column_name, type = nil, options = {}) - column_name = column_name.to_s - checks = [] - checks << lambda { |c| c.name == column_name } - checks << lambda { |c| c.type == type } if type - column_options_keys.each do |attr| - checks << lambda { |c| c.send(attr) == options[attr] } if options.key?(attr) - end - - columns(table_name).any? { |c| checks.all? { |check| check[c] } } - end - - # Returns just a table's primary key - def primary_key(table_name) - pk = primary_keys(table_name) - pk = pk.first unless pk.size > 1 - pk - end - - # Creates a new table with the name +table_name+. +table_name+ may either - # be a String or a Symbol. - # - # There are two ways to work with #create_table. You can use the block - # form or the regular form, like this: - # - # === Block form - # - # # create_table() passes a TableDefinition object to the block. - # # This form will not only create the table, but also columns for the - # # table. - # - # create_table(:suppliers) do |t| - # t.column :name, :string, limit: 60 - # # Other fields here - # end - # - # === Block form, with shorthand - # - # # You can also use the column types as method calls, rather than calling the column method. - # create_table(:suppliers) do |t| - # t.string :name, limit: 60 - # # Other fields here - # end - # - # === Regular form - # - # # Creates a table called 'suppliers' with no columns. - # create_table(:suppliers) - # # Add a column to 'suppliers'. - # add_column(:suppliers, :name, :string, {limit: 60}) - # - # The +options+ hash can include the following keys: - # [:id] - # Whether to automatically add a primary key column. Defaults to true. - # Join tables for {ActiveRecord::Base.has_and_belongs_to_many}[rdoc-ref:Associations::ClassMethods#has_and_belongs_to_many] should set it to false. - # - # A Symbol can be used to specify the type of the generated primary key column. - # [:primary_key] - # The name of the primary key, if one is to be added automatically. - # Defaults to +id+. If :id is false, then this option is ignored. - # - # Note that Active Record models will automatically detect their - # primary key. This can be avoided by using - # {self.primary_key=}[rdoc-ref:AttributeMethods::PrimaryKey::ClassMethods#primary_key=] on the model - # to define the key explicitly. - # - # [:options] - # Any extra options you want appended to the table definition. - # [:temporary] - # Make a temporary table. - # [:force] - # Set to true to drop the table before creating it. - # Set to +:cascade+ to drop dependent objects as well. - # Defaults to false. - # [:as] - # SQL to use to generate the table. When this option is used, the block is - # ignored, as are the :id and :primary_key options. - # - # ====== Add a backend specific option to the generated SQL (MySQL) - # - # create_table(:suppliers, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8') - # - # generates: - # - # CREATE TABLE suppliers ( - # id int auto_increment PRIMARY KEY - # ) ENGINE=InnoDB DEFAULT CHARSET=utf8 - # - # ====== Rename the primary key column - # - # create_table(:objects, primary_key: 'guid') do |t| - # t.column :name, :string, limit: 80 - # end - # - # generates: - # - # CREATE TABLE objects ( - # guid int auto_increment PRIMARY KEY, - # name varchar(80) - # ) - # - # ====== Change the primary key column type - # - # create_table(:tags, id: :string) do |t| - # t.column :label, :string - # end - # - # generates: - # - # CREATE TABLE tags ( - # id varchar PRIMARY KEY, - # label varchar - # ) - # - # ====== Do not add a primary key column - # - # create_table(:categories_suppliers, id: false) do |t| - # t.column :category_id, :integer - # t.column :supplier_id, :integer - # end - # - # generates: - # - # CREATE TABLE categories_suppliers ( - # category_id int, - # supplier_id int - # ) - # - # ====== Create a temporary table based on a query - # - # create_table(:long_query, temporary: true, - # as: "SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id") - # - # generates: - # - # CREATE TEMPORARY TABLE long_query AS - # SELECT * FROM orders INNER JOIN line_items ON order_id=orders.id - # - # See also TableDefinition#column for details on how to create columns. - def create_table(table_name, comment: nil, **options) - td = create_table_definition table_name, options[:temporary], options[:options], options[:as], comment: comment - - if options[:id] != false && !options[:as] - pk = options.fetch(:primary_key) do - Base.get_primary_key table_name.to_s.singularize - end - - if pk.is_a?(Array) - td.primary_keys pk - else - td.primary_key pk, options.fetch(:id, :primary_key), options - end - end - - yield td if block_given? - - if options[:force] - drop_table(table_name, **options, if_exists: true) - end - - result = execute schema_creation.accept td - - unless supports_indexes_in_create? - td.indexes.each do |column_name, index_options| - add_index(table_name, column_name, index_options) - end - end - - if supports_comments? && !supports_comments_in_create? - change_table_comment(table_name, comment) if comment.present? - - td.columns.each do |column| - change_column_comment(table_name, column.name, column.comment) if column.comment.present? - end - end - - result - end - - # Creates a new join table with the name created using the lexical order of the first two - # arguments. These arguments can be a String or a Symbol. - # - # # Creates a table called 'assemblies_parts' with no id. - # create_join_table(:assemblies, :parts) - # - # You can pass an +options+ hash which can include the following keys: - # [:table_name] - # Sets the table name, overriding the default. - # [:column_options] - # Any extra options you want appended to the columns definition. - # [:options] - # Any extra options you want appended to the table definition. - # [:temporary] - # Make a temporary table. - # [:force] - # Set to true to drop the table before creating it. - # Defaults to false. - # - # Note that #create_join_table does not create any indices by default; you can use - # its block form to do so yourself: - # - # create_join_table :products, :categories do |t| - # t.index :product_id - # t.index :category_id - # end - # - # ====== Add a backend specific option to the generated SQL (MySQL) - # - # create_join_table(:assemblies, :parts, options: 'ENGINE=InnoDB DEFAULT CHARSET=utf8') - # - # generates: - # - # CREATE TABLE assemblies_parts ( - # assembly_id int NOT NULL, - # part_id int NOT NULL, - # ) ENGINE=InnoDB DEFAULT CHARSET=utf8 - # - def create_join_table(table_1, table_2, column_options: {}, **options) - join_table_name = find_join_table_name(table_1, table_2, options) - - column_options.reverse_merge!(null: false, index: false) - - t1_ref, t2_ref = [table_1, table_2].map { |t| t.to_s.singularize } - - create_table(join_table_name, options.merge!(id: false)) do |td| - td.references t1_ref, column_options - td.references t2_ref, column_options - yield td if block_given? - end - end - - # Drops the join table specified by the given arguments. - # See #create_join_table for details. - # - # Although this command ignores the block if one is given, it can be helpful - # to provide one in a migration's +change+ method so it can be reverted. - # In that case, the block will be used by #create_join_table. - def drop_join_table(table_1, table_2, options = {}) - join_table_name = find_join_table_name(table_1, table_2, options) - drop_table(join_table_name) - end - - # A block for changing columns in +table+. - # - # # change_table() yields a Table instance - # change_table(:suppliers) do |t| - # t.column :name, :string, limit: 60 - # # Other column alterations here - # end - # - # The +options+ hash can include the following keys: - # [:bulk] - # Set this to true to make this a bulk alter query, such as - # - # ALTER TABLE `users` ADD COLUMN age INT, ADD COLUMN birthdate DATETIME ... - # - # Defaults to false. - # - # ====== Add a column - # - # change_table(:suppliers) do |t| - # t.column :name, :string, limit: 60 - # end - # - # ====== Add 2 integer columns - # - # change_table(:suppliers) do |t| - # t.integer :width, :height, null: false, default: 0 - # end - # - # ====== Add created_at/updated_at columns - # - # change_table(:suppliers) do |t| - # t.timestamps - # end - # - # ====== Add a foreign key column - # - # change_table(:suppliers) do |t| - # t.references :company - # end - # - # Creates a company_id(integer) column. - # - # ====== Add a polymorphic foreign key column - # - # change_table(:suppliers) do |t| - # t.belongs_to :company, polymorphic: true - # end - # - # Creates company_type(varchar) and company_id(integer) columns. - # - # ====== Remove a column - # - # change_table(:suppliers) do |t| - # t.remove :company - # end - # - # ====== Remove several columns - # - # change_table(:suppliers) do |t| - # t.remove :company_id - # t.remove :width, :height - # end - # - # ====== Remove an index - # - # change_table(:suppliers) do |t| - # t.remove_index :company_id - # end - # - # See also Table for details on all of the various column transformations. - def change_table(table_name, options = {}) - if supports_bulk_alter? && options[:bulk] - recorder = ActiveRecord::Migration::CommandRecorder.new(self) - yield update_table_definition(table_name, recorder) - bulk_change_table(table_name, recorder.commands) - else - yield update_table_definition(table_name, self) - end - end - - # Renames a table. - # - # rename_table('octopuses', 'octopi') - # - def rename_table(table_name, new_name) - raise NotImplementedError, "rename_table is not implemented" - end - - # Drops a table from the database. - # - # [:force] - # Set to +:cascade+ to drop dependent objects as well. - # Defaults to false. - # [:if_exists] - # Set to +true+ to only drop the table if it exists. - # Defaults to false. - # - # Although this command ignores most +options+ and the block if one is given, - # it can be helpful to provide these in a migration's +change+ method so it can be reverted. - # In that case, +options+ and the block will be used by #create_table. - def drop_table(table_name, options = {}) - execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}" - end - - # Add a new +type+ column named +column_name+ to +table_name+. - # - # The +type+ parameter is normally one of the migrations native types, - # which is one of the following: - # :primary_key, :string, :text, - # :integer, :bigint, :float, :decimal, :numeric, - # :datetime, :time, :date, - # :binary, :boolean. - # - # You may use a type not in this list as long as it is supported by your - # database (for example, "polygon" in MySQL), but this will not be database - # agnostic and should usually be avoided. - # - # Available options are (none of these exists by default): - # * :limit - - # Requests a maximum column length. This is the number of characters for a :string column - # and number of bytes for :text, :binary and :integer columns. - # * :default - - # The column's default value. Use +nil+ for +NULL+. - # * :null - - # Allows or disallows +NULL+ values in the column. This option could - # have been named :null_allowed. - # * :precision - - # Specifies the precision for the :decimal and :numeric columns. - # * :scale - - # Specifies the scale for the :decimal and :numeric columns. - # - # Note: The precision is the total number of significant digits, - # and the scale is the number of digits that can be stored following - # the decimal point. For example, the number 123.45 has a precision of 5 - # and a scale of 2. A decimal with a precision of 5 and a scale of 2 can - # range from -999.99 to 999.99. - # - # Please be aware of different RDBMS implementations behavior with - # :decimal columns: - # * The SQL standard says the default scale should be 0, :scale <= - # :precision, and makes no comments about the requirements of - # :precision. - # * MySQL: :precision [1..63], :scale [0..30]. - # Default is (10,0). - # * PostgreSQL: :precision [1..infinity], - # :scale [0..infinity]. No default. - # * SQLite3: No restrictions on :precision and :scale, - # but the maximum supported :precision is 16. No default. - # * Oracle: :precision [1..38], :scale [-84..127]. - # Default is (38,0). - # * DB2: :precision [1..63], :scale [0..62]. - # Default unknown. - # * SqlServer: :precision [1..38], :scale [0..38]. - # Default (38,0). - # - # == Examples - # - # add_column(:users, :picture, :binary, limit: 2.megabytes) - # # ALTER TABLE "users" ADD "picture" blob(2097152) - # - # add_column(:articles, :status, :string, limit: 20, default: 'draft', null: false) - # # ALTER TABLE "articles" ADD "status" varchar(20) DEFAULT 'draft' NOT NULL - # - # add_column(:answers, :bill_gates_money, :decimal, precision: 15, scale: 2) - # # ALTER TABLE "answers" ADD "bill_gates_money" decimal(15,2) - # - # add_column(:measurements, :sensor_reading, :decimal, precision: 30, scale: 20) - # # ALTER TABLE "measurements" ADD "sensor_reading" decimal(30,20) - # - # # While :scale defaults to zero on most databases, it - # # probably wouldn't hurt to include it. - # add_column(:measurements, :huge_integer, :decimal, precision: 30) - # # ALTER TABLE "measurements" ADD "huge_integer" decimal(30) - # - # # Defines a column that stores an array of a type. - # add_column(:users, :skills, :text, array: true) - # # ALTER TABLE "users" ADD "skills" text[] - # - # # Defines a column with a database-specific type. - # add_column(:shapes, :triangle, 'polygon') - # # ALTER TABLE "shapes" ADD "triangle" polygon - def add_column(table_name, column_name, type, options = {}) - at = create_alter_table table_name - at.add_column(column_name, type, options) - execute schema_creation.accept at - end - - # Removes the given columns from the table definition. - # - # remove_columns(:suppliers, :qualification, :experience) - # - def remove_columns(table_name, *column_names) - raise ArgumentError.new("You must specify at least one column name. Example: remove_columns(:people, :first_name)") if column_names.empty? - column_names.each do |column_name| - remove_column(table_name, column_name) - end - end - - # Removes the column from the table definition. - # - # remove_column(:suppliers, :qualification) - # - # The +type+ and +options+ parameters will be ignored if present. It can be helpful - # to provide these in a migration's +change+ method so it can be reverted. - # In that case, +type+ and +options+ will be used by #add_column. - def remove_column(table_name, column_name, type = nil, options = {}) - execute "ALTER TABLE #{quote_table_name(table_name)} DROP #{quote_column_name(column_name)}" - end - - # Changes the column's definition according to the new options. - # See TableDefinition#column for details of the options you can use. - # - # change_column(:suppliers, :name, :string, limit: 80) - # change_column(:accounts, :description, :text) - # - def change_column(table_name, column_name, type, options = {}) - raise NotImplementedError, "change_column is not implemented" - end - - # Sets a new default value for a column: - # - # change_column_default(:suppliers, :qualification, 'new') - # change_column_default(:accounts, :authorized, 1) - # - # Setting the default to +nil+ effectively drops the default: - # - # change_column_default(:users, :email, nil) - # - # Passing a hash containing +:from+ and +:to+ will make this change - # reversible in migration: - # - # change_column_default(:posts, :state, from: nil, to: "draft") - # - def change_column_default(table_name, column_name, default_or_changes) - raise NotImplementedError, "change_column_default is not implemented" - end - - # Sets or removes a NOT NULL constraint on a column. The +null+ flag - # indicates whether the value can be +NULL+. For example - # - # change_column_null(:users, :nickname, false) - # - # says nicknames cannot be +NULL+ (adds the constraint), whereas - # - # change_column_null(:users, :nickname, true) - # - # allows them to be +NULL+ (drops the constraint). - # - # The method accepts an optional fourth argument to replace existing - # NULLs with some other value. Use that one when enabling the - # constraint if needed, since otherwise those rows would not be valid. - # - # Please note the fourth argument does not set a column's default. - def change_column_null(table_name, column_name, null, default = nil) - raise NotImplementedError, "change_column_null is not implemented" - end - - # Renames a column. - # - # rename_column(:suppliers, :description, :name) - # - def rename_column(table_name, column_name, new_column_name) - raise NotImplementedError, "rename_column is not implemented" - end - - # Adds a new index to the table. +column_name+ can be a single Symbol, or - # an Array of Symbols. - # - # The index will be named after the table and the column name(s), unless - # you pass :name as an option. - # - # ====== Creating a simple index - # - # add_index(:suppliers, :name) - # - # generates: - # - # CREATE INDEX suppliers_name_index ON suppliers(name) - # - # ====== Creating a unique index - # - # add_index(:accounts, [:branch_id, :party_id], unique: true) - # - # generates: - # - # CREATE UNIQUE INDEX accounts_branch_id_party_id_index ON accounts(branch_id, party_id) - # - # ====== Creating a named index - # - # add_index(:accounts, [:branch_id, :party_id], unique: true, name: 'by_branch_party') - # - # generates: - # - # CREATE UNIQUE INDEX by_branch_party ON accounts(branch_id, party_id) - # - # ====== Creating an index with specific key length - # - # add_index(:accounts, :name, name: 'by_name', length: 10) - # - # generates: - # - # CREATE INDEX by_name ON accounts(name(10)) - # - # ====== Creating an index with specific key lengths for multiple keys - # - # add_index(:accounts, [:name, :surname], name: 'by_name_surname', length: {name: 10, surname: 15}) - # - # generates: - # - # CREATE INDEX by_name_surname ON accounts(name(10), surname(15)) - # - # Note: SQLite doesn't support index length. - # - # ====== Creating an index with a sort order (desc or asc, asc is the default) - # - # add_index(:accounts, [:branch_id, :party_id, :surname], order: {branch_id: :desc, party_id: :asc}) - # - # generates: - # - # CREATE INDEX by_branch_desc_party ON accounts(branch_id DESC, party_id ASC, surname) - # - # Note: MySQL doesn't yet support index order (it accepts the syntax but ignores it). - # - # ====== Creating a partial index - # - # add_index(:accounts, [:branch_id, :party_id], unique: true, where: "active") - # - # generates: - # - # CREATE UNIQUE INDEX index_accounts_on_branch_id_and_party_id ON accounts(branch_id, party_id) WHERE active - # - # Note: Partial indexes are only supported for PostgreSQL and SQLite 3.8.0+. - # - # ====== Creating an index with a specific method - # - # add_index(:developers, :name, using: 'btree') - # - # generates: - # - # CREATE INDEX index_developers_on_name ON developers USING btree (name) -- PostgreSQL - # CREATE INDEX index_developers_on_name USING btree ON developers (name) -- MySQL - # - # Note: only supported by PostgreSQL and MySQL - # - # ====== Creating an index with a specific type - # - # add_index(:developers, :name, type: :fulltext) - # - # generates: - # - # CREATE FULLTEXT INDEX index_developers_on_name ON developers (name) -- MySQL - # - # Note: only supported by MySQL. - def add_index(table_name, column_name, options = {}) - index_name, index_type, index_columns, index_options = add_index_options(table_name, column_name, options) - execute "CREATE #{index_type} INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} (#{index_columns})#{index_options}" - end - - # Removes the given index from the table. - # - # Removes the index on +branch_id+ in the +accounts+ table if exactly one such index exists. - # - # remove_index :accounts, :branch_id - # - # Removes the index on +branch_id+ in the +accounts+ table if exactly one such index exists. - # - # remove_index :accounts, column: :branch_id - # - # Removes the index on +branch_id+ and +party_id+ in the +accounts+ table if exactly one such index exists. - # - # remove_index :accounts, column: [:branch_id, :party_id] - # - # Removes the index named +by_branch_party+ in the +accounts+ table. - # - # remove_index :accounts, name: :by_branch_party - # - def remove_index(table_name, options = {}) - index_name = index_name_for_remove(table_name, options) - execute "DROP INDEX #{quote_column_name(index_name)} ON #{quote_table_name(table_name)}" - end - - # Renames an index. - # - # Rename the +index_people_on_last_name+ index to +index_users_on_last_name+: - # - # rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name' - # - def rename_index(table_name, old_name, new_name) - validate_index_length!(table_name, new_name) - - # this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance) - old_index_def = indexes(table_name).detect { |i| i.name == old_name } - return unless old_index_def - add_index(table_name, old_index_def.columns, name: new_name, unique: old_index_def.unique) - remove_index(table_name, name: old_name) - end - - def index_name(table_name, options) #:nodoc: - if Hash === options - if options[:column] - "index_#{table_name}_on_#{Array(options[:column]) * '_and_'}" - elsif options[:name] - options[:name] - else - raise ArgumentError, "You must specify the index name" - end - else - index_name(table_name, index_name_options(options)) - end - end - - # Verifies the existence of an index with a given name. - def index_name_exists?(table_name, index_name, default = nil) - unless default.nil? - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing default to #index_name_exists? is deprecated without replacement. - MSG - end - index_name = index_name.to_s - indexes(table_name).detect { |i| i.name == index_name } - end - - # Adds a reference. The reference column is an integer by default, - # the :type option can be used to specify a different type. - # Optionally adds a +_type+ column, if :polymorphic option is provided. - # #add_reference and #add_belongs_to are acceptable. - # - # The +options+ hash can include the following keys: - # [:type] - # The reference column type. Defaults to +:integer+. - # [:index] - # Add an appropriate index. Defaults to true. - # See #add_index for usage of this option. - # [:foreign_key] - # Add an appropriate foreign key constraint. Defaults to false. - # [:polymorphic] - # Whether an additional +_type+ column should be added. Defaults to false. - # [:null] - # Whether the column allows nulls. Defaults to true. - # - # ====== Create a user_id integer column - # - # add_reference(:products, :user) - # - # ====== Create a user_id string column - # - # add_reference(:products, :user, type: :string) - # - # ====== Create supplier_id, supplier_type columns and appropriate index - # - # add_reference(:products, :supplier, polymorphic: true, index: true) - # - # ====== Create a supplier_id column with a unique index - # - # add_reference(:products, :supplier, index: { unique: true }) - # - # ====== Create a supplier_id column with a named index - # - # add_reference(:products, :supplier, index: { name: "my_supplier_index" }) - # - # ====== Create a supplier_id column and appropriate foreign key - # - # add_reference(:products, :supplier, foreign_key: true) - # - # ====== Create a supplier_id column and a foreign key to the firms table - # - # add_reference(:products, :supplier, foreign_key: {to_table: :firms}) - # - def add_reference(table_name, ref_name, **options) - ReferenceDefinition.new(ref_name, options).add_to(update_table_definition(table_name, self)) - end - alias :add_belongs_to :add_reference - - # Removes the reference(s). Also removes a +type+ column if one exists. - # #remove_reference and #remove_belongs_to are acceptable. - # - # ====== Remove the reference - # - # remove_reference(:products, :user, index: true) - # - # ====== Remove polymorphic reference - # - # remove_reference(:products, :supplier, polymorphic: true) - # - # ====== Remove the reference with a foreign key - # - # remove_reference(:products, :user, index: true, foreign_key: true) - # - def remove_reference(table_name, ref_name, foreign_key: false, polymorphic: false, **options) - if foreign_key - reference_name = Base.pluralize_table_names ? ref_name.to_s.pluralize : ref_name - if foreign_key.is_a?(Hash) - foreign_key_options = foreign_key - else - foreign_key_options = { to_table: reference_name } - end - foreign_key_options[:column] ||= "#{ref_name}_id" - remove_foreign_key(table_name, **foreign_key_options) - end - - remove_column(table_name, "#{ref_name}_id") - remove_column(table_name, "#{ref_name}_type") if polymorphic - end - alias :remove_belongs_to :remove_reference - - # Returns an array of foreign keys for the given table. - # The foreign keys are represented as ForeignKeyDefinition objects. - def foreign_keys(table_name) - raise NotImplementedError, "foreign_keys is not implemented" - end - - # Adds a new foreign key. +from_table+ is the table with the key column, - # +to_table+ contains the referenced primary key. - # - # The foreign key will be named after the following pattern: fk_rails_. - # +identifier+ is a 10 character long string which is deterministically generated from the - # +from_table+ and +column+. A custom name can be specified with the :name option. - # - # ====== Creating a simple foreign key - # - # add_foreign_key :articles, :authors - # - # generates: - # - # ALTER TABLE "articles" ADD CONSTRAINT fk_rails_e74ce85cbc FOREIGN KEY ("author_id") REFERENCES "authors" ("id") - # - # ====== Creating a foreign key on a specific column - # - # add_foreign_key :articles, :users, column: :author_id, primary_key: "lng_id" - # - # generates: - # - # ALTER TABLE "articles" ADD CONSTRAINT fk_rails_58ca3d3a82 FOREIGN KEY ("author_id") REFERENCES "users" ("lng_id") - # - # ====== Creating a cascading foreign key - # - # add_foreign_key :articles, :authors, on_delete: :cascade - # - # generates: - # - # ALTER TABLE "articles" ADD CONSTRAINT fk_rails_e74ce85cbc FOREIGN KEY ("author_id") REFERENCES "authors" ("id") ON DELETE CASCADE - # - # The +options+ hash can include the following keys: - # [:column] - # The foreign key column name on +from_table+. Defaults to to_table.singularize + "_id" - # [:primary_key] - # The primary key column name on +to_table+. Defaults to +id+. - # [:name] - # The constraint name. Defaults to fk_rails_. - # [:on_delete] - # Action that happens ON DELETE. Valid values are +:nullify+, +:cascade+ and +:restrict+ - # [:on_update] - # Action that happens ON UPDATE. Valid values are +:nullify+, +:cascade+ and +:restrict+ - def add_foreign_key(from_table, to_table, options = {}) - return unless supports_foreign_keys? - - options = foreign_key_options(from_table, to_table, options) - at = create_alter_table from_table - at.add_foreign_key to_table, options - - execute schema_creation.accept(at) - end - - # Removes the given foreign key from the table. Any option parameters provided - # will be used to re-add the foreign key in case of a migration rollback. - # It is recommended that you provide any options used when creating the foreign - # key so that the migration can be reverted properly. - # - # Removes the foreign key on +accounts.branch_id+. - # - # remove_foreign_key :accounts, :branches - # - # Removes the foreign key on +accounts.owner_id+. - # - # remove_foreign_key :accounts, column: :owner_id - # - # Removes the foreign key named +special_fk_name+ on the +accounts+ table. - # - # remove_foreign_key :accounts, name: :special_fk_name - # - # The +options+ hash accepts the same keys as SchemaStatements#add_foreign_key. - def remove_foreign_key(from_table, options_or_to_table = {}) - return unless supports_foreign_keys? - - fk_name_to_delete = foreign_key_for!(from_table, options_or_to_table).name - - at = create_alter_table from_table - at.drop_foreign_key fk_name_to_delete - - execute schema_creation.accept(at) - end - - # Checks to see if a foreign key exists on a table for a given foreign key definition. - # - # # Checks to see if a foreign key exists. - # foreign_key_exists?(:accounts, :branches) - # - # # Checks to see if a foreign key on a specified column exists. - # foreign_key_exists?(:accounts, column: :owner_id) - # - # # Checks to see if a foreign key with a custom name exists. - # foreign_key_exists?(:accounts, name: "special_fk_name") - # - def foreign_key_exists?(from_table, options_or_to_table = {}) - foreign_key_for(from_table, options_or_to_table).present? - end - - def foreign_key_for(from_table, options_or_to_table = {}) # :nodoc: - return unless supports_foreign_keys? - foreign_keys(from_table).detect { |fk| fk.defined_for? options_or_to_table } - end - - def foreign_key_for!(from_table, options_or_to_table = {}) # :nodoc: - foreign_key_for(from_table, options_or_to_table) || \ - raise(ArgumentError, "Table '#{from_table}' has no foreign key for #{options_or_to_table}") - end - - def foreign_key_column_for(table_name) # :nodoc: - prefix = Base.table_name_prefix - suffix = Base.table_name_suffix - name = table_name.to_s =~ /#{prefix}(.+)#{suffix}/ ? $1 : table_name.to_s - "#{name.singularize}_id" - end - - def foreign_key_options(from_table, to_table, options) # :nodoc: - options = options.dup - options[:column] ||= foreign_key_column_for(to_table) - options[:name] ||= foreign_key_name(from_table, options) - options - end - - def dump_schema_information #:nodoc: - versions = ActiveRecord::SchemaMigration.all_versions - insert_versions_sql(versions) if versions.any? - end - - def insert_versions_sql(versions) # :nodoc: - sm_table = quote_table_name(ActiveRecord::SchemaMigration.table_name) - - if versions.is_a?(Array) - sql = "INSERT INTO #{sm_table} (version) VALUES\n" - sql << versions.map { |v| "(#{quote(v)})" }.join(",\n") - sql << ";\n\n" - sql - else - "INSERT INTO #{sm_table} (version) VALUES (#{quote(versions)});" - end - end - - def initialize_schema_migrations_table # :nodoc: - ActiveRecord::SchemaMigration.create_table - end - deprecate :initialize_schema_migrations_table - - def initialize_internal_metadata_table # :nodoc: - ActiveRecord::InternalMetadata.create_table - end - deprecate :initialize_internal_metadata_table - - def internal_string_options_for_primary_key # :nodoc: - { primary_key: true } - end - - def assume_migrated_upto_version(version, migrations_paths) - migrations_paths = Array(migrations_paths) - version = version.to_i - sm_table = quote_table_name(ActiveRecord::SchemaMigration.table_name) - - migrated = ActiveRecord::SchemaMigration.all_versions.map(&:to_i) - versions = ActiveRecord::Migrator.migration_files(migrations_paths).map do |file| - ActiveRecord::Migrator.parse_migration_filename(file).first.to_i - end - - unless migrated.include?(version) - execute "INSERT INTO #{sm_table} (version) VALUES (#{quote(version)})" - end - - inserting = (versions - migrated).select { |v| v < version } - if inserting.any? - if (duplicate = inserting.detect { |v| inserting.count(v) > 1 }) - raise "Duplicate migration #{duplicate}. Please renumber your migrations to resolve the conflict." - end - if supports_multi_insert? - execute insert_versions_sql(inserting) - else - inserting.each do |v| - execute insert_versions_sql(v) - end - end - end - end - - def type_to_sql(type, limit: nil, precision: nil, scale: nil, **) # :nodoc: - type = type.to_sym if type - if native = native_database_types[type] - column_type_sql = (native.is_a?(Hash) ? native[:name] : native).dup - - if type == :decimal # ignore limit, use precision and scale - scale ||= native[:scale] - - if precision ||= native[:precision] - if scale - column_type_sql << "(#{precision},#{scale})" - else - column_type_sql << "(#{precision})" - end - elsif scale - raise ArgumentError, "Error adding decimal column: precision cannot be empty if scale is specified" - end - - elsif [:datetime, :timestamp, :time, :interval].include?(type) && precision ||= native[:precision] - if (0..6) === precision - column_type_sql << "(#{precision})" - else - raise(ActiveRecordError, "No #{native[:name]} type has precision of #{precision}. The allowed range of precision is from 0 to 6") - end - elsif (type != :primary_key) && (limit ||= native.is_a?(Hash) && native[:limit]) - column_type_sql << "(#{limit})" - end - - column_type_sql - else - type.to_s - end - end - - # Given a set of columns and an ORDER BY clause, returns the columns for a SELECT DISTINCT. - # PostgreSQL, MySQL, and Oracle override this for custom DISTINCT syntax - they - # require the order columns appear in the SELECT. - # - # columns_for_distinct("posts.id", ["posts.created_at desc"]) - # - def columns_for_distinct(columns, orders) # :nodoc: - columns - end - - # Adds timestamps (+created_at+ and +updated_at+) columns to +table_name+. - # Additional options (like +:null+) are forwarded to #add_column. - # - # add_timestamps(:suppliers, null: true) - # - def add_timestamps(table_name, options = {}) - options[:null] = false if options[:null].nil? - - add_column table_name, :created_at, :datetime, options - add_column table_name, :updated_at, :datetime, options - end - - # Removes the timestamp columns (+created_at+ and +updated_at+) from the table definition. - # - # remove_timestamps(:suppliers) - # - def remove_timestamps(table_name, options = {}) - remove_column table_name, :updated_at - remove_column table_name, :created_at - end - - def update_table_definition(table_name, base) #:nodoc: - Table.new(table_name, base) - end - - def add_index_options(table_name, column_name, comment: nil, **options) # :nodoc: - column_names = index_column_names(column_name) - - options.assert_valid_keys(:unique, :order, :name, :where, :length, :internal, :using, :algorithm, :type) - - index_type = options[:type].to_s if options.key?(:type) - index_type ||= options[:unique] ? "UNIQUE" : "" - index_name = options[:name].to_s if options.key?(:name) - index_name ||= index_name(table_name, column_names) - - if options.key?(:algorithm) - algorithm = index_algorithms.fetch(options[:algorithm]) { - raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}") - } - end - - using = "USING #{options[:using]}" if options[:using].present? - - if supports_partial_index? - index_options = options[:where] ? " WHERE #{options[:where]}" : "" - end - - validate_index_length!(table_name, index_name, options.fetch(:internal, false)) - - if data_source_exists?(table_name) && index_name_exists?(table_name, index_name) - raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' already exists" - end - index_columns = quoted_columns_for_index(column_names, options).join(", ") - - [index_name, index_type, index_columns, index_options, algorithm, using, comment] - end - - def options_include_default?(options) - options.include?(:default) && !(options[:null] == false && options[:default].nil?) - end - - # Changes the comment for a table or removes it if +nil+. - def change_table_comment(table_name, comment) - raise NotImplementedError, "#{self.class} does not support changing table comments" - end - - # Changes the comment for a column or removes it if +nil+. - def change_column_comment(table_name, column_name, comment) #:nodoc: - raise NotImplementedError, "#{self.class} does not support changing column comments" - end - - private - def column_options_keys - [:limit, :precision, :scale, :default, :null, :collation, :comment] - end - - def add_index_sort_order(quoted_columns, **options) - if order = options[:order] - case order - when Hash - order = order.symbolize_keys - quoted_columns.each { |name, column| column << " #{order[name].upcase}" if order[name].present? } - when String - quoted_columns.each { |name, column| column << " #{order.upcase}" if order.present? } - end - end - - quoted_columns - end - - # Overridden by the MySQL adapter for supporting index lengths - def add_options_for_index_columns(quoted_columns, **options) - if supports_index_sort_order? - quoted_columns = add_index_sort_order(quoted_columns, options) - end - - quoted_columns - end - - def quoted_columns_for_index(column_names, **options) - return [column_names] if column_names.is_a?(String) - - quoted_columns = Hash[column_names.map { |name| [name.to_sym, quote_column_name(name).dup] }] - add_options_for_index_columns(quoted_columns, options).values - end - - def index_name_for_remove(table_name, options = {}) - return options[:name] if can_remove_index_by_name?(options) - - checks = [] - - if options.is_a?(Hash) - checks << lambda { |i| i.name == options[:name].to_s } if options.key?(:name) - column_names = index_column_names(options[:column]) - else - column_names = index_column_names(options) - end - - if column_names.present? - checks << lambda { |i| index_name(table_name, i.columns) == index_name(table_name, column_names) } - end - - raise ArgumentError, "No name or columns specified" if checks.none? - - matching_indexes = indexes(table_name).select { |i| checks.all? { |check| check[i] } } - - if matching_indexes.count > 1 - raise ArgumentError, "Multiple indexes found on #{table_name} columns #{column_names}. " \ - "Specify an index name from #{matching_indexes.map(&:name).join(', ')}" - elsif matching_indexes.none? - raise ArgumentError, "No indexes found on #{table_name} with the options provided." - else - matching_indexes.first.name - end - end - - def rename_table_indexes(table_name, new_name) - indexes(new_name).each do |index| - generated_index_name = index_name(table_name, column: index.columns) - if generated_index_name == index.name - rename_index new_name, generated_index_name, index_name(new_name, column: index.columns) - end - end - end - - def rename_column_indexes(table_name, column_name, new_column_name) - column_name, new_column_name = column_name.to_s, new_column_name.to_s - indexes(table_name).each do |index| - next unless index.columns.include?(new_column_name) - old_columns = index.columns.dup - old_columns[old_columns.index(new_column_name)] = column_name - generated_index_name = index_name(table_name, column: old_columns) - if generated_index_name == index.name - rename_index table_name, generated_index_name, index_name(table_name, column: index.columns) - end - end - end - - def create_table_definition(*args) - TableDefinition.new(*args) - end - - def create_alter_table(name) - AlterTable.new create_table_definition(name) - end - - def index_column_names(column_names) - if column_names.is_a?(String) && /\W/.match?(column_names) - column_names - else - Array(column_names) - end - end - - def index_name_options(column_names) - if column_names.is_a?(String) && /\W/.match?(column_names) - column_names = column_names.scan(/\w+/).join("_") - end - - { column: column_names } - end - - def foreign_key_name(table_name, options) - identifier = "#{table_name}_#{options.fetch(:column)}_fk" - hashed_identifier = Digest::SHA256.hexdigest(identifier).first(10) - options.fetch(:name) do - "fk_rails_#{hashed_identifier}" - end - end - - def validate_index_length!(table_name, new_name, internal = false) - max_index_length = internal ? index_name_length : allowed_index_name_length - - if new_name.length > max_index_length - raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters" - end - end - - def extract_new_default_value(default_or_changes) - if default_or_changes.is_a?(Hash) && default_or_changes.has_key?(:from) && default_or_changes.has_key?(:to) - default_or_changes[:to] - else - default_or_changes - end - end - - def can_remove_index_by_name?(options) - options.is_a?(Hash) && options.key?(:name) && options.except(:name, :algorithm).empty? - end - - def data_source_sql(name = nil, type: nil) - raise NotImplementedError - end - - def quoted_scope(name = nil, type: nil) - raise NotImplementedError - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/transaction.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/transaction.rb deleted file mode 100644 index 19b7821494..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract/transaction.rb +++ /dev/null @@ -1,238 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - class TransactionState - VALID_STATES = Set.new([:committed, :rolledback, nil]) - - def initialize(state = nil) - @state = state - end - - def finalized? - @state - end - - def committed? - @state == :committed - end - - def rolledback? - @state == :rolledback - end - - def completed? - committed? || rolledback? - end - - def set_state(state) - unless VALID_STATES.include?(state) - raise ArgumentError, "Invalid transaction state: #{state}" - end - @state = state - end - end - - class NullTransaction #:nodoc: - def initialize; end - def state; end - def closed?; true; end - def open?; false; end - def joinable?; false; end - def add_record(record); end - end - - class Transaction #:nodoc: - attr_reader :connection, :state, :records, :savepoint_name - attr_writer :joinable - - def initialize(connection, options, run_commit_callbacks: false) - @connection = connection - @state = TransactionState.new - @records = [] - @joinable = options.fetch(:joinable, true) - @run_commit_callbacks = run_commit_callbacks - end - - def add_record(record) - records << record - end - - def rollback - @state.set_state(:rolledback) - end - - def rollback_records - ite = records.uniq - while record = ite.shift - record.rolledback!(force_restore_state: full_rollback?) - end - ensure - ite.each do |i| - i.rolledback!(force_restore_state: full_rollback?, should_run_callbacks: false) - end - end - - def commit - @state.set_state(:committed) - end - - def before_commit_records - records.uniq.each(&:before_committed!) if @run_commit_callbacks - end - - def commit_records - ite = records.uniq - while record = ite.shift - if @run_commit_callbacks - record.committed! - else - # if not running callbacks, only adds the record to the parent transaction - record.add_to_transaction - end - end - ensure - ite.each { |i| i.committed!(should_run_callbacks: false) } - end - - def full_rollback?; true; end - def joinable?; @joinable; end - def closed?; false; end - def open?; !closed?; end - end - - class SavepointTransaction < Transaction - def initialize(connection, savepoint_name, options, *args) - super(connection, options, *args) - if options[:isolation] - raise ActiveRecord::TransactionIsolationError, "cannot set transaction isolation in a nested transaction" - end - connection.create_savepoint(@savepoint_name = savepoint_name) - end - - def rollback - connection.rollback_to_savepoint(savepoint_name) - super - end - - def commit - connection.release_savepoint(savepoint_name) - super - end - - def full_rollback?; false; end - end - - class RealTransaction < Transaction - def initialize(connection, options, *args) - super - if options[:isolation] - connection.begin_isolated_db_transaction(options[:isolation]) - else - connection.begin_db_transaction - end - end - - def rollback - connection.rollback_db_transaction - super - end - - def commit - connection.commit_db_transaction - super - end - end - - class TransactionManager #:nodoc: - def initialize(connection) - @stack = [] - @connection = connection - end - - def begin_transaction(options = {}) - @connection.lock.synchronize do - run_commit_callbacks = !current_transaction.joinable? - transaction = - if @stack.empty? - RealTransaction.new(@connection, options, run_commit_callbacks: run_commit_callbacks) - else - SavepointTransaction.new(@connection, "active_record_#{@stack.size}", options, - run_commit_callbacks: run_commit_callbacks) - end - - @stack.push(transaction) - transaction - end - end - - def commit_transaction - @connection.lock.synchronize do - transaction = @stack.last - - begin - transaction.before_commit_records - ensure - @stack.pop - end - - transaction.commit - transaction.commit_records - end - end - - def rollback_transaction(transaction = nil) - @connection.lock.synchronize do - transaction ||= @stack.pop - transaction.rollback - transaction.rollback_records - end - end - - def within_new_transaction(options = {}) - @connection.lock.synchronize do - begin - transaction = begin_transaction options - yield - rescue Exception => error - if transaction - rollback_transaction - after_failure_actions(transaction, error) - end - raise - ensure - unless error - if Thread.current.status == "aborting" - rollback_transaction if transaction - else - begin - commit_transaction - rescue Exception - rollback_transaction(transaction) unless transaction.state.completed? - raise - end - end - end - end - end - end - - def open_transactions - @stack.size - end - - def current_transaction - @stack.last || NULL_TRANSACTION - end - - private - - NULL_TRANSACTION = NullTransaction.new - - # Deallocate invalidated prepared statements outside of the transaction - def after_failure_actions(transaction, error) - return unless transaction.is_a?(RealTransaction) - return unless error.is_a?(ActiveRecord::PreparedStatementCacheExpired) - @connection.clear_cache! - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract_adapter.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract_adapter.rb deleted file mode 100644 index e523a97aa5..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract_adapter.rb +++ /dev/null @@ -1,641 +0,0 @@ -require "active_record/type" -require "active_record/connection_adapters/determine_if_preparable_visitor" -require "active_record/connection_adapters/schema_cache" -require "active_record/connection_adapters/sql_type_metadata" -require "active_record/connection_adapters/abstract/schema_dumper" -require "active_record/connection_adapters/abstract/schema_creation" -require "active_support/concurrency/load_interlock_aware_monitor" -require "arel/collectors/bind" -require "arel/collectors/sql_string" - -module ActiveRecord - module ConnectionAdapters # :nodoc: - extend ActiveSupport::Autoload - - autoload :Column - autoload :ConnectionSpecification - - autoload_at "active_record/connection_adapters/abstract/schema_definitions" do - autoload :IndexDefinition - autoload :ColumnDefinition - autoload :ChangeColumnDefinition - autoload :ForeignKeyDefinition - autoload :TableDefinition - autoload :Table - autoload :AlterTable - autoload :ReferenceDefinition - end - - autoload_at "active_record/connection_adapters/abstract/connection_pool" do - autoload :ConnectionHandler - end - - autoload_under "abstract" do - autoload :SchemaStatements - autoload :DatabaseStatements - autoload :DatabaseLimits - autoload :Quoting - autoload :ConnectionPool - autoload :QueryCache - autoload :Savepoints - end - - autoload_at "active_record/connection_adapters/abstract/transaction" do - autoload :TransactionManager - autoload :NullTransaction - autoload :RealTransaction - autoload :SavepointTransaction - autoload :TransactionState - end - - # Active Record supports multiple database systems. AbstractAdapter and - # related classes form the abstraction layer which makes this possible. - # An AbstractAdapter represents a connection to a database, and provides an - # abstract interface for database-specific functionality such as establishing - # a connection, escaping values, building the right SQL fragments for +:offset+ - # and +:limit+ options, etc. - # - # All the concrete database adapters follow the interface laid down in this class. - # {ActiveRecord::Base.connection}[rdoc-ref:ConnectionHandling#connection] returns an AbstractAdapter object, which - # you can use. - # - # Most of the methods in the adapter are useful during migrations. Most - # notably, the instance methods provided by SchemaStatements are very useful. - class AbstractAdapter - ADAPTER_NAME = "Abstract".freeze - include ActiveSupport::Callbacks - define_callbacks :checkout, :checkin - - include Quoting, DatabaseStatements, SchemaStatements - include DatabaseLimits - include QueryCache - include ColumnDumper - include Savepoints - - SIMPLE_INT = /\A\d+\z/ - - attr_accessor :visitor, :pool - attr_reader :schema_cache, :owner, :logger, :prepared_statements, :lock - alias :in_use? :owner - - def self.type_cast_config_to_integer(config) - if config =~ SIMPLE_INT - config.to_i - else - config - end - end - - def self.type_cast_config_to_boolean(config) - if config == "false" - false - else - config - end - end - - def initialize(connection, logger = nil, config = {}) # :nodoc: - super() - - @connection = connection - @owner = nil - @instrumenter = ActiveSupport::Notifications.instrumenter - @logger = logger - @config = config - @pool = nil - @schema_cache = SchemaCache.new self - @quoted_column_names, @quoted_table_names = {}, {} - @visitor = arel_visitor - @lock = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new - - if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true }) - @prepared_statements = true - @visitor.extend(DetermineIfPreparableVisitor) - else - @prepared_statements = false - end - end - - class Version - include Comparable - - def initialize(version_string) - @version = version_string.split(".").map(&:to_i) - end - - def <=>(version_string) - @version <=> version_string.split(".").map(&:to_i) - end - end - - class BindCollector < Arel::Collectors::Bind - def compile(bvs, conn) - casted_binds = bvs.map(&:value_for_database) - super(casted_binds.map { |value| conn.quote(value) }) - end - end - - class SQLString < Arel::Collectors::SQLString - def compile(bvs, conn) - super(bvs) - end - end - - def collector - if prepared_statements - SQLString.new - else - BindCollector.new - end - end - - def arel_visitor # :nodoc: - Arel::Visitors::ToSql.new(self) - end - - def valid_type?(type) # :nodoc: - !native_database_types[type].nil? - end - - def schema_creation - SchemaCreation.new self - end - - # Returns an array of +Column+ objects for the table specified by +table_name+. - def columns(table_name) # :nodoc: - table_name = table_name.to_s - column_definitions(table_name).map do |field| - new_column_from_field(table_name, field) - end - end - - # this method must only be called while holding connection pool's mutex - def lease - if in_use? - msg = "Cannot lease connection, " - if @owner == Thread.current - msg << "it is already leased by the current thread." - else - msg << "it is already in use by a different thread: #{@owner}. " \ - "Current thread: #{Thread.current}." - end - raise ActiveRecordError, msg - end - - @owner = Thread.current - end - - def schema_cache=(cache) - cache.connection = self - @schema_cache = cache - end - - # this method must only be called while holding connection pool's mutex - def expire - if in_use? - if @owner != Thread.current - raise ActiveRecordError, "Cannot expire connection, " \ - "it is owned by a different thread: #{@owner}. " \ - "Current thread: #{Thread.current}." - end - - @owner = nil - else - raise ActiveRecordError, "Cannot expire connection, it is not currently leased." - end - end - - # this method must only be called while holding connection pool's mutex (and a desire for segfaults) - def steal! # :nodoc: - if in_use? - if @owner != Thread.current - pool.send :remove_connection_from_thread_cache, self, @owner - - @owner = Thread.current - end - else - raise ActiveRecordError, "Cannot steal connection, it is not currently leased." - end - end - - def unprepared_statement - old_prepared_statements, @prepared_statements = @prepared_statements, false - yield - ensure - @prepared_statements = old_prepared_statements - end - - # Returns the human-readable name of the adapter. Use mixed case - one - # can always use downcase if needed. - def adapter_name - self.class::ADAPTER_NAME - end - - def supports_migrations? # :nodoc: - true - end - deprecate :supports_migrations? - - def supports_primary_key? # :nodoc: - true - end - deprecate :supports_primary_key? - - # Does this adapter support DDL rollbacks in transactions? That is, would - # CREATE TABLE or ALTER TABLE get rolled back by a transaction? - def supports_ddl_transactions? - false - end - - def supports_bulk_alter? - false - end - - # Does this adapter support savepoints? - def supports_savepoints? - false - end - - # Does this adapter support application-enforced advisory locking? - def supports_advisory_locks? - false - end - - # Should primary key values be selected from their corresponding - # sequence before the insert statement? If true, next_sequence_value - # is called before each insert to set the record's primary key. - def prefetch_primary_key?(table_name = nil) - false - end - - # Does this adapter support index sort order? - def supports_index_sort_order? - false - end - - # Does this adapter support partial indices? - def supports_partial_index? - false - end - - # Does this adapter support expression indices? - def supports_expression_index? - false - end - - # Does this adapter support explain? - def supports_explain? - false - end - - # Does this adapter support setting the isolation level for a transaction? - def supports_transaction_isolation? - false - end - - # Does this adapter support database extensions? - def supports_extensions? - false - end - - # Does this adapter support creating indexes in the same statement as - # creating the table? - def supports_indexes_in_create? - false - end - - # Does this adapter support creating foreign key constraints? - def supports_foreign_keys? - false - end - - # Does this adapter support creating foreign key constraints - # in the same statement as creating the table? - def supports_foreign_keys_in_create? - supports_foreign_keys? - end - - # Does this adapter support views? - def supports_views? - false - end - - # Does this adapter support datetime with precision? - def supports_datetime_with_precision? - false - end - - # Does this adapter support json data type? - def supports_json? - false - end - - # Does this adapter support metadata comments on database objects (tables, columns, indexes)? - def supports_comments? - false - end - - # Can comments for tables, columns, and indexes be specified in create/alter table statements? - def supports_comments_in_create? - false - end - - # Does this adapter support multi-value insert? - def supports_multi_insert? - true - end - - # Does this adapter support virtual columns? - def supports_virtual_columns? - false - end - - # This is meant to be implemented by the adapters that support extensions - def disable_extension(name) - end - - # This is meant to be implemented by the adapters that support extensions - def enable_extension(name) - end - - # This is meant to be implemented by the adapters that support advisory - # locks - # - # Return true if we got the lock, otherwise false - def get_advisory_lock(lock_id) # :nodoc: - end - - # This is meant to be implemented by the adapters that support advisory - # locks. - # - # Return true if we released the lock, otherwise false - def release_advisory_lock(lock_id) # :nodoc: - end - - # A list of extensions, to be filled in by adapters that support them. - def extensions - [] - end - - # A list of index algorithms, to be filled by adapters that support them. - def index_algorithms - {} - end - - # REFERENTIAL INTEGRITY ==================================== - - # Override to turn off referential integrity while executing &block. - def disable_referential_integrity - yield - end - - # CONNECTION MANAGEMENT ==================================== - - # Checks whether the connection to the database is still active. This includes - # checking whether the database is actually capable of responding, i.e. whether - # the connection isn't stale. - def active? - end - - # Disconnects from the database if already connected, and establishes a - # new connection with the database. Implementors should call super if they - # override the default implementation. - def reconnect! - clear_cache! - reset_transaction - end - - # Disconnects from the database if already connected. Otherwise, this - # method does nothing. - def disconnect! - clear_cache! - reset_transaction - end - - # Reset the state of this connection, directing the DBMS to clear - # transactions and other connection-related server-side state. Usually a - # database-dependent operation. - # - # The default implementation does nothing; the implementation should be - # overridden by concrete adapters. - def reset! - # this should be overridden by concrete adapters - end - - ### - # Clear any caching the database adapter may be doing, for example - # clearing the prepared statement cache. This is database specific. - def clear_cache! - # this should be overridden by concrete adapters - end - - # Returns true if its required to reload the connection between requests for development mode. - def requires_reloading? - false - end - - # Checks whether the connection to the database is still active (i.e. not stale). - # This is done under the hood by calling #active?. If the connection - # is no longer active, then this method will reconnect to the database. - def verify!(*ignored) - if ignored.size > 0 - ActiveSupport::Deprecation.warn("Passing arguments to #verify method of the connection has no effect and has been deprecated. Please remove all arguments from the #verify method call.") - end - reconnect! unless active? - end - - # Provides access to the underlying database driver for this adapter. For - # example, this method returns a Mysql2::Client object in case of Mysql2Adapter, - # and a PG::Connection object in case of PostgreSQLAdapter. - # - # This is useful for when you need to call a proprietary method such as - # PostgreSQL's lo_* methods. - def raw_connection - @connection - end - - def case_sensitive_comparison(table, attribute, column, value) # :nodoc: - table[attribute].eq(value) - end - - def case_insensitive_comparison(table, attribute, column, value) # :nodoc: - if can_perform_case_insensitive_comparison_for?(column) - table[attribute].lower.eq(table.lower(value)) - else - table[attribute].eq(value) - end - end - - def can_perform_case_insensitive_comparison_for?(column) - true - end - private :can_perform_case_insensitive_comparison_for? - - # Check the connection back in to the connection pool - def close - pool.checkin self - end - - def type_map # :nodoc: - @type_map ||= Type::TypeMap.new.tap do |mapping| - initialize_type_map(mapping) - end - end - - def new_column(name, default, sql_type_metadata, null, table_name, default_function = nil, collation = nil) # :nodoc: - Column.new(name, default, sql_type_metadata, null, table_name, default_function, collation) - end - - def lookup_cast_type(sql_type) # :nodoc: - type_map.lookup(sql_type) - end - - def column_name_for_operation(operation, node) # :nodoc: - visitor.accept(node, collector).value - end - - def combine_bind_parameters( - from_clause: [], - join_clause: [], - where_clause: [], - having_clause: [], - limit: nil, - offset: nil - ) # :nodoc: - result = from_clause + join_clause + where_clause + having_clause - if limit - result << limit - end - if offset - result << offset - end - result - end - - def default_index_type?(index) # :nodoc: - index.using.nil? - end - - private - - def initialize_type_map(m) - register_class_with_limit m, %r(boolean)i, Type::Boolean - register_class_with_limit m, %r(char)i, Type::String - register_class_with_limit m, %r(binary)i, Type::Binary - register_class_with_limit m, %r(text)i, Type::Text - register_class_with_precision m, %r(date)i, Type::Date - register_class_with_precision m, %r(time)i, Type::Time - register_class_with_precision m, %r(datetime)i, Type::DateTime - register_class_with_limit m, %r(float)i, Type::Float - register_class_with_limit m, %r(int)i, Type::Integer - - m.alias_type %r(blob)i, "binary" - m.alias_type %r(clob)i, "text" - m.alias_type %r(timestamp)i, "datetime" - m.alias_type %r(numeric)i, "decimal" - m.alias_type %r(number)i, "decimal" - m.alias_type %r(double)i, "float" - - m.register_type(%r(decimal)i) do |sql_type| - scale = extract_scale(sql_type) - precision = extract_precision(sql_type) - - if scale == 0 - # FIXME: Remove this class as well - Type::DecimalWithoutScale.new(precision: precision) - else - Type::Decimal.new(precision: precision, scale: scale) - end - end - end - - def reload_type_map - type_map.clear - initialize_type_map(type_map) - end - - def register_class_with_limit(mapping, key, klass) - mapping.register_type(key) do |*args| - limit = extract_limit(args.last) - klass.new(limit: limit) - end - end - - def register_class_with_precision(mapping, key, klass) - mapping.register_type(key) do |*args| - precision = extract_precision(args.last) - klass.new(precision: precision) - end - end - - def extract_scale(sql_type) - case sql_type - when /\((\d+)\)/ then 0 - when /\((\d+)(,(\d+))\)/ then $3.to_i - end - end - - def extract_precision(sql_type) - $1.to_i if sql_type =~ /\((\d+)(,\d+)?\)/ - end - - def extract_limit(sql_type) - case sql_type - when /^bigint/i - 8 - when /\((.*)\)/ - $1.to_i - end - end - - def translate_exception_class(e, sql) - begin - message = "#{e.class.name}: #{e.message}: #{sql}" - rescue Encoding::CompatibilityError - message = "#{e.class.name}: #{e.message.force_encoding sql.encoding}: #{sql}" - end - - exception = translate_exception(e, message) - exception.set_backtrace e.backtrace - exception - end - - def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil) # :doc: - @instrumenter.instrument( - "sql.active_record", - sql: sql, - name: name, - binds: binds, - type_casted_binds: type_casted_binds, - statement_name: statement_name, - connection_id: object_id) do - @lock.synchronize do - yield - end - end - rescue => e - raise translate_exception_class(e, sql) - end - - def translate_exception(exception, message) - # override in derived class - case exception - when RuntimeError - exception - else - ActiveRecord::StatementInvalid.new(message) - end - end - - def without_prepared_statement?(binds) - !prepared_statements || binds.empty? - end - - def column_for(table_name, column_name) - column_name = column_name.to_s - columns(table_name).detect { |c| c.name == column_name } || - raise(ActiveRecordError, "No such column: #{table_name}.#{column_name}") - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract_mysql_adapter.rb deleted file mode 100644 index 6a8d333235..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ /dev/null @@ -1,960 +0,0 @@ -require "active_record/connection_adapters/abstract_adapter" -require "active_record/connection_adapters/statement_pool" -require "active_record/connection_adapters/mysql/column" -require "active_record/connection_adapters/mysql/explain_pretty_printer" -require "active_record/connection_adapters/mysql/quoting" -require "active_record/connection_adapters/mysql/schema_creation" -require "active_record/connection_adapters/mysql/schema_definitions" -require "active_record/connection_adapters/mysql/schema_dumper" -require "active_record/connection_adapters/mysql/schema_statements" -require "active_record/connection_adapters/mysql/type_metadata" - -require "active_support/core_ext/string/strip" - -module ActiveRecord - module ConnectionAdapters - class AbstractMysqlAdapter < AbstractAdapter - include MySQL::Quoting - include MySQL::ColumnDumper - include MySQL::SchemaStatements - - def update_table_definition(table_name, base) # :nodoc: - MySQL::Table.new(table_name, base) - end - - def schema_creation # :nodoc: - MySQL::SchemaCreation.new(self) - end - - def arel_visitor # :nodoc: - Arel::Visitors::MySQL.new(self) - end - - ## - # :singleton-method: - # By default, the Mysql2Adapter will consider all columns of type tinyint(1) - # as boolean. If you wish to disable this emulation you can add the following line - # to your application.rb file: - # - # ActiveRecord::ConnectionAdapters::Mysql2Adapter.emulate_booleans = false - class_attribute :emulate_booleans - self.emulate_booleans = true - - NATIVE_DATABASE_TYPES = { - primary_key: "bigint auto_increment PRIMARY KEY", - string: { name: "varchar", limit: 255 }, - text: { name: "text", limit: 65535 }, - integer: { name: "int", limit: 4 }, - float: { name: "float" }, - decimal: { name: "decimal" }, - datetime: { name: "datetime" }, - timestamp: { name: "timestamp" }, - time: { name: "time" }, - date: { name: "date" }, - binary: { name: "blob", limit: 65535 }, - boolean: { name: "tinyint", limit: 1 }, - json: { name: "json" }, - } - - INDEX_TYPES = [:fulltext, :spatial] - INDEX_USINGS = [:btree, :hash] - - class StatementPool < ConnectionAdapters::StatementPool - private def dealloc(stmt) - stmt[:stmt].close - end - end - - def initialize(connection, logger, connection_options, config) - super(connection, logger, config) - - @statements = StatementPool.new(self.class.type_cast_config_to_integer(config[:statement_limit])) - - if version < "5.1.10" - raise "Your version of MySQL (#{version_string}) is too old. Active Record supports MySQL >= 5.1.10." - end - end - - def version #:nodoc: - @version ||= Version.new(version_string) - end - - def mariadb? # :nodoc: - /mariadb/i.match?(full_version) - end - - def supports_bulk_alter? #:nodoc: - true - end - - # Returns true, since this connection adapter supports prepared statement - # caching. - def supports_statement_cache? - true - end - - # Technically MySQL allows to create indexes with the sort order syntax - # but at the moment (5.5) it doesn't yet implement them - def supports_index_sort_order? - true - end - - def supports_transaction_isolation? - true - end - - def supports_explain? - true - end - - def supports_indexes_in_create? - true - end - - def supports_foreign_keys? - true - end - - def supports_views? - true - end - - def supports_datetime_with_precision? - if mariadb? - version >= "5.3.0" - else - version >= "5.6.4" - end - end - - def supports_virtual_columns? - if mariadb? - version >= "5.2.0" - else - version >= "5.7.5" - end - end - - def supports_advisory_locks? - true - end - - def get_advisory_lock(lock_name, timeout = 0) # :nodoc: - query_value("SELECT GET_LOCK(#{quote(lock_name.to_s)}, #{timeout})") == 1 - end - - def release_advisory_lock(lock_name) # :nodoc: - query_value("SELECT RELEASE_LOCK(#{quote(lock_name.to_s)})") == 1 - end - - def native_database_types - NATIVE_DATABASE_TYPES - end - - def index_algorithms - { default: "ALGORITHM = DEFAULT", copy: "ALGORITHM = COPY", inplace: "ALGORITHM = INPLACE" } - end - - # HELPER METHODS =========================================== - - # The two drivers have slightly different ways of yielding hashes of results, so - # this method must be implemented to provide a uniform interface. - def each_hash(result) # :nodoc: - raise NotImplementedError - end - - def new_column(*args) #:nodoc: - MySQL::Column.new(*args) - end - - # Must return the MySQL error number from the exception, if the exception has an - # error number. - def error_number(exception) # :nodoc: - raise NotImplementedError - end - - # REFERENTIAL INTEGRITY ==================================== - - def disable_referential_integrity #:nodoc: - old = query_value("SELECT @@FOREIGN_KEY_CHECKS") - - begin - update("SET FOREIGN_KEY_CHECKS = 0") - yield - ensure - update("SET FOREIGN_KEY_CHECKS = #{old}") - end - end - - # CONNECTION MANAGEMENT ==================================== - - # Clears the prepared statements cache. - def clear_cache! - reload_type_map - @statements.clear - end - - #-- - # DATABASE STATEMENTS ====================================== - #++ - - def explain(arel, binds = []) - sql = "EXPLAIN #{to_sql(arel, binds)}" - start = Time.now - result = exec_query(sql, "EXPLAIN", binds) - elapsed = Time.now - start - - MySQL::ExplainPrettyPrinter.new.pp(result, elapsed) - end - - # Executes the SQL statement in the context of this connection. - def execute(sql, name = nil) - log(sql, name) do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - @connection.query(sql) - end - end - end - - # Mysql2Adapter doesn't have to free a result after using it, but we use this method - # to write stuff in an abstract way without concerning ourselves about whether it - # needs to be explicitly freed or not. - def execute_and_free(sql, name = nil) # :nodoc: - yield execute(sql, name) - end - - def begin_db_transaction - execute "BEGIN" - end - - def begin_isolated_db_transaction(isolation) - execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}" - begin_db_transaction - end - - def commit_db_transaction #:nodoc: - execute "COMMIT" - end - - def exec_rollback_db_transaction #:nodoc: - execute "ROLLBACK" - end - - # In the simple case, MySQL allows us to place JOINs directly into the UPDATE - # query. However, this does not allow for LIMIT, OFFSET and ORDER. To support - # these, we must use a subquery. - def join_to_update(update, select, key) # :nodoc: - if select.limit || select.offset || select.orders.any? - super - else - update.table select.source - update.wheres = select.constraints - end - end - - def empty_insert_statement_value - "VALUES ()" - end - - # SCHEMA STATEMENTS ======================================== - - # Drops the database specified on the +name+ attribute - # and creates it again using the provided +options+. - def recreate_database(name, options = {}) - drop_database(name) - sql = create_database(name, options) - reconnect! - sql - end - - # Create a new MySQL database with optional :charset and :collation. - # Charset defaults to utf8. - # - # Example: - # create_database 'charset_test', charset: 'latin1', collation: 'latin1_bin' - # create_database 'matt_development' - # create_database 'matt_development', charset: :big5 - def create_database(name, options = {}) - if options[:collation] - execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT CHARACTER SET #{quote_table_name(options[:charset] || 'utf8')} COLLATE #{quote_table_name(options[:collation])}" - else - execute "CREATE DATABASE #{quote_table_name(name)} DEFAULT CHARACTER SET #{quote_table_name(options[:charset] || 'utf8')}" - end - end - - # Drops a MySQL database. - # - # Example: - # drop_database('sebastian_development') - def drop_database(name) #:nodoc: - execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}" - end - - def current_database - query_value("SELECT database()", "SCHEMA") - end - - # Returns the database character set. - def charset - show_variable "character_set_database" - end - - # Returns the database collation strategy. - def collation - show_variable "collation_database" - end - - def truncate(table_name, name = nil) - execute "TRUNCATE TABLE #{quote_table_name(table_name)}", name - end - - # Returns an array of indexes for the given table. - def indexes(table_name, name = nil) #:nodoc: - if name - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing name to #indexes is deprecated without replacement. - MSG - end - - indexes = [] - current_index = nil - execute_and_free("SHOW KEYS FROM #{quote_table_name(table_name)}", "SCHEMA") do |result| - each_hash(result) do |row| - if current_index != row[:Key_name] - next if row[:Key_name] == "PRIMARY" # skip the primary key - current_index = row[:Key_name] - - mysql_index_type = row[:Index_type].downcase.to_sym - index_type = INDEX_TYPES.include?(mysql_index_type) ? mysql_index_type : nil - index_using = INDEX_USINGS.include?(mysql_index_type) ? mysql_index_type : nil - indexes << IndexDefinition.new(row[:Table], row[:Key_name], row[:Non_unique].to_i == 0, [], {}, nil, nil, index_type, index_using, row[:Index_comment].presence) - end - - indexes.last.columns << row[:Column_name] - indexes.last.lengths.merge!(row[:Column_name] => row[:Sub_part].to_i) if row[:Sub_part] - end - end - - indexes - end - - def new_column_from_field(table_name, field) # :nodoc: - type_metadata = fetch_type_metadata(field[:Type], field[:Extra]) - if type_metadata.type == :datetime && /\ACURRENT_TIMESTAMP(?:\(\))?\z/i.match?(field[:Default]) - default, default_function = nil, "CURRENT_TIMESTAMP" - else - default, default_function = field[:Default], nil - end - new_column(field[:Field], default, type_metadata, field[:Null] == "YES", table_name, default_function, field[:Collation], comment: field[:Comment].presence) - end - - def table_comment(table_name) # :nodoc: - scope = quoted_scope(table_name) - - query_value(<<-SQL.strip_heredoc, "SCHEMA") - SELECT table_comment - FROM information_schema.tables - WHERE table_schema = #{scope[:schema]} - AND table_name = #{scope[:name]} - SQL - end - - def create_table(table_name, **options) #:nodoc: - super(table_name, options: "ENGINE=InnoDB", **options) - end - - def bulk_change_table(table_name, operations) #:nodoc: - sqls = operations.flat_map do |command, args| - table, arguments = args.shift, args - method = :"#{command}_sql" - - if respond_to?(method, true) - send(method, table, *arguments) - else - raise "Unknown method called : #{method}(#{arguments.inspect})" - end - end.join(", ") - - execute("ALTER TABLE #{quote_table_name(table_name)} #{sqls}") - end - - # Renames a table. - # - # Example: - # rename_table('octopuses', 'octopi') - def rename_table(table_name, new_name) - execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}" - rename_table_indexes(table_name, new_name) - end - - # Drops a table from the database. - # - # [:force] - # Set to +:cascade+ to drop dependent objects as well. - # Defaults to false. - # [:if_exists] - # Set to +true+ to only drop the table if it exists. - # Defaults to false. - # [:temporary] - # Set to +true+ to drop temporary table. - # Defaults to false. - # - # Although this command ignores most +options+ and the block if one is given, - # it can be helpful to provide these in a migration's +change+ method so it can be reverted. - # In that case, +options+ and the block will be used by create_table. - def drop_table(table_name, options = {}) - execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}" - end - - def rename_index(table_name, old_name, new_name) - if supports_rename_index? - validate_index_length!(table_name, new_name) - - execute "ALTER TABLE #{quote_table_name(table_name)} RENAME INDEX #{quote_table_name(old_name)} TO #{quote_table_name(new_name)}" - else - super - end - end - - def change_column_default(table_name, column_name, default_or_changes) #:nodoc: - default = extract_new_default_value(default_or_changes) - column = column_for(table_name, column_name) - change_column table_name, column_name, column.sql_type, default: default - end - - def change_column_null(table_name, column_name, null, default = nil) #:nodoc: - column = column_for(table_name, column_name) - - unless null || default.nil? - execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") - end - - change_column table_name, column_name, column.sql_type, null: null - end - - def change_column(table_name, column_name, type, options = {}) #:nodoc: - execute("ALTER TABLE #{quote_table_name(table_name)} #{change_column_sql(table_name, column_name, type, options)}") - end - - def rename_column(table_name, column_name, new_column_name) #:nodoc: - execute("ALTER TABLE #{quote_table_name(table_name)} #{rename_column_sql(table_name, column_name, new_column_name)}") - rename_column_indexes(table_name, column_name, new_column_name) - end - - def add_index(table_name, column_name, options = {}) #:nodoc: - index_name, index_type, index_columns, _, index_algorithm, index_using, comment = add_index_options(table_name, column_name, options) - sql = "CREATE #{index_type} INDEX #{quote_column_name(index_name)} #{index_using} ON #{quote_table_name(table_name)} (#{index_columns}) #{index_algorithm}" - execute add_sql_comment!(sql, comment) - end - - def add_sql_comment!(sql, comment) # :nodoc: - sql << " COMMENT #{quote(comment)}" if comment.present? - sql - end - - def foreign_keys(table_name) - raise ArgumentError unless table_name.present? - - scope = quoted_scope(table_name) - - fk_info = exec_query(<<-SQL.strip_heredoc, "SCHEMA") - SELECT fk.referenced_table_name AS 'to_table', - fk.referenced_column_name AS 'primary_key', - fk.column_name AS 'column', - fk.constraint_name AS 'name', - rc.update_rule AS 'on_update', - rc.delete_rule AS 'on_delete' - FROM information_schema.referential_constraints rc - JOIN information_schema.key_column_usage fk - USING (constraint_schema, constraint_name) - WHERE fk.referenced_column_name IS NOT NULL - AND fk.table_schema = #{scope[:schema]} - AND fk.table_name = #{scope[:name]} - AND rc.constraint_schema = #{scope[:schema]} - AND rc.table_name = #{scope[:name]} - SQL - - fk_info.map do |row| - options = { - column: row["column"], - name: row["name"], - primary_key: row["primary_key"] - } - - options[:on_update] = extract_foreign_key_action(row["on_update"]) - options[:on_delete] = extract_foreign_key_action(row["on_delete"]) - - ForeignKeyDefinition.new(table_name, row["to_table"], options) - end - end - - def table_options(table_name) # :nodoc: - table_options = {} - - create_table_info = create_table_info(table_name) - - # strip create_definitions and partition_options - raw_table_options = create_table_info.sub(/\A.*\n\) /m, "").sub(/\n\/\*!.*\*\/\n\z/m, "").strip - - # strip AUTO_INCREMENT - raw_table_options.sub!(/(ENGINE=\w+)(?: AUTO_INCREMENT=\d+)/, '\1') - - table_options[:options] = raw_table_options - - # strip COMMENT - if raw_table_options.sub!(/ COMMENT='.+'/, "") - table_options[:comment] = table_comment(table_name) - end - - table_options - end - - # Maps logical Rails types to MySQL-specific data types. - def type_to_sql(type, limit: nil, precision: nil, scale: nil, unsigned: nil, **) # :nodoc: - sql = \ - case type.to_s - when "integer" - integer_to_sql(limit) - when "text" - text_to_sql(limit) - when "blob" - binary_to_sql(limit) - when "binary" - if (0..0xfff) === limit - "varbinary(#{limit})" - else - binary_to_sql(limit) - end - else - super - end - - sql << " unsigned" if unsigned && type != :primary_key - sql - end - - # SHOW VARIABLES LIKE 'name' - def show_variable(name) - query_value("SELECT @@#{name}", "SCHEMA") - rescue ActiveRecord::StatementInvalid - nil - end - - def primary_keys(table_name) # :nodoc: - raise ArgumentError unless table_name.present? - - scope = quoted_scope(table_name) - - query_values(<<-SQL.strip_heredoc, "SCHEMA") - SELECT column_name - FROM information_schema.key_column_usage - WHERE constraint_name = 'PRIMARY' - AND table_schema = #{scope[:schema]} - AND table_name = #{scope[:name]} - ORDER BY ordinal_position - SQL - end - - def case_sensitive_comparison(table, attribute, column, value) # :nodoc: - if column.collation && !column.case_sensitive? - table[attribute].eq(Arel::Nodes::Bin.new(value)) - else - super - end - end - - def can_perform_case_insensitive_comparison_for?(column) - column.case_sensitive? - end - private :can_perform_case_insensitive_comparison_for? - - # In MySQL 5.7.5 and up, ONLY_FULL_GROUP_BY affects handling of queries that use - # DISTINCT and ORDER BY. It requires the ORDER BY columns in the select list for - # distinct queries, and requires that the ORDER BY include the distinct column. - # See https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html - def columns_for_distinct(columns, orders) # :nodoc: - order_columns = orders.reject(&:blank?).map { |s| - # Convert Arel node to string - s = s.to_sql unless s.is_a?(String) - # Remove any ASC/DESC modifiers - s.gsub(/\s+(?:ASC|DESC)\b/i, "") - }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } - - [super, *order_columns].join(", ") - end - - def strict_mode? - self.class.type_cast_config_to_boolean(@config.fetch(:strict, true)) - end - - def default_index_type?(index) # :nodoc: - index.using == :btree || super - end - - private - - def initialize_type_map(m) - super - - register_class_with_limit m, %r(char)i, MysqlString - - m.register_type %r(tinytext)i, Type::Text.new(limit: 2**8 - 1) - m.register_type %r(tinyblob)i, Type::Binary.new(limit: 2**8 - 1) - m.register_type %r(text)i, Type::Text.new(limit: 2**16 - 1) - m.register_type %r(blob)i, Type::Binary.new(limit: 2**16 - 1) - m.register_type %r(mediumtext)i, Type::Text.new(limit: 2**24 - 1) - m.register_type %r(mediumblob)i, Type::Binary.new(limit: 2**24 - 1) - m.register_type %r(longtext)i, Type::Text.new(limit: 2**32 - 1) - m.register_type %r(longblob)i, Type::Binary.new(limit: 2**32 - 1) - m.register_type %r(^float)i, Type::Float.new(limit: 24) - m.register_type %r(^double)i, Type::Float.new(limit: 53) - m.register_type %r(^json)i, MysqlJson.new - - register_integer_type m, %r(^bigint)i, limit: 8 - register_integer_type m, %r(^int)i, limit: 4 - register_integer_type m, %r(^mediumint)i, limit: 3 - register_integer_type m, %r(^smallint)i, limit: 2 - register_integer_type m, %r(^tinyint)i, limit: 1 - - m.register_type %r(^tinyint\(1\))i, Type::Boolean.new if emulate_booleans - m.alias_type %r(year)i, "integer" - m.alias_type %r(bit)i, "binary" - - m.register_type(%r(enum)i) do |sql_type| - limit = sql_type[/^enum\((.+)\)/i, 1] - .split(",").map { |enum| enum.strip.length - 2 }.max - MysqlString.new(limit: limit) - end - - m.register_type(%r(^set)i) do |sql_type| - limit = sql_type[/^set\((.+)\)/i, 1] - .split(",").map { |set| set.strip.length - 1 }.sum - 1 - MysqlString.new(limit: limit) - end - end - - def register_integer_type(mapping, key, options) - mapping.register_type(key) do |sql_type| - if /\bunsigned\b/.match?(sql_type) - Type::UnsignedInteger.new(options) - else - Type::Integer.new(options) - end - end - end - - def extract_precision(sql_type) - if /\A(?:date)?time(?:stamp)?\b/.match?(sql_type) - super || 0 - else - super - end - end - - def fetch_type_metadata(sql_type, extra = "") - MySQL::TypeMetadata.new(super(sql_type), extra: extra) - end - - def add_index_length(quoted_columns, **options) - if length = options[:length] - case length - when Hash - length = length.symbolize_keys - quoted_columns.each { |name, column| column << "(#{length[name]})" if length[name].present? } - when Integer - quoted_columns.each { |name, column| column << "(#{length})" } - end - end - - quoted_columns - end - - def add_options_for_index_columns(quoted_columns, **options) - quoted_columns = add_index_length(quoted_columns, options) - super - end - - # See https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html - ER_DUP_ENTRY = 1062 - ER_NOT_NULL_VIOLATION = 1048 - ER_DO_NOT_HAVE_DEFAULT = 1364 - ER_NO_REFERENCED_ROW_2 = 1452 - ER_DATA_TOO_LONG = 1406 - ER_OUT_OF_RANGE = 1264 - ER_LOCK_DEADLOCK = 1213 - ER_CANNOT_ADD_FOREIGN = 1215 - ER_CANNOT_CREATE_TABLE = 1005 - - def translate_exception(exception, message) - case error_number(exception) - when ER_DUP_ENTRY - RecordNotUnique.new(message) - when ER_NO_REFERENCED_ROW_2 - InvalidForeignKey.new(message) - when ER_CANNOT_ADD_FOREIGN - mismatched_foreign_key(message) - when ER_CANNOT_CREATE_TABLE - if message.include?("errno: 150") - mismatched_foreign_key(message) - else - super - end - when ER_DATA_TOO_LONG - ValueTooLong.new(message) - when ER_OUT_OF_RANGE - RangeError.new(message) - when ER_NOT_NULL_VIOLATION, ER_DO_NOT_HAVE_DEFAULT - NotNullViolation.new(message) - when ER_LOCK_DEADLOCK - Deadlocked.new(message) - else - super - end - end - - def add_column_sql(table_name, column_name, type, options = {}) - td = create_table_definition(table_name) - cd = td.new_column_definition(column_name, type, options) - schema_creation.accept(AddColumnDefinition.new(cd)) - end - - def change_column_sql(table_name, column_name, type, options = {}) - column = column_for(table_name, column_name) - - unless options.key?(:default) - options[:default] = column.default - end - - unless options.key?(:null) - options[:null] = column.null - end - - unless options.key?(:comment) - options[:comment] = column.comment - end - - td = create_table_definition(table_name) - cd = td.new_column_definition(column.name, type, options) - schema_creation.accept(ChangeColumnDefinition.new(cd, column.name)) - end - - def rename_column_sql(table_name, column_name, new_column_name) - column = column_for(table_name, column_name) - options = { - default: column.default, - null: column.null, - auto_increment: column.auto_increment? - } - - current_type = exec_query("SHOW COLUMNS FROM #{quote_table_name(table_name)} LIKE #{quote(column_name)}", "SCHEMA").first["Type"] - td = create_table_definition(table_name) - cd = td.new_column_definition(new_column_name, current_type, options) - schema_creation.accept(ChangeColumnDefinition.new(cd, column.name)) - end - - def remove_column_sql(table_name, column_name, type = nil, options = {}) - "DROP #{quote_column_name(column_name)}" - end - - def remove_columns_sql(table_name, *column_names) - column_names.map { |column_name| remove_column_sql(table_name, column_name) } - end - - def add_index_sql(table_name, column_name, options = {}) - index_name, index_type, index_columns, _, index_algorithm, index_using = add_index_options(table_name, column_name, options) - index_algorithm[0, 0] = ", " if index_algorithm.present? - "ADD #{index_type} INDEX #{quote_column_name(index_name)} #{index_using} (#{index_columns})#{index_algorithm}" - end - - def remove_index_sql(table_name, options = {}) - index_name = index_name_for_remove(table_name, options) - "DROP INDEX #{index_name}" - end - - def add_timestamps_sql(table_name, options = {}) - [add_column_sql(table_name, :created_at, :datetime, options), add_column_sql(table_name, :updated_at, :datetime, options)] - end - - def remove_timestamps_sql(table_name, options = {}) - [remove_column_sql(table_name, :updated_at), remove_column_sql(table_name, :created_at)] - end - - # MySQL is too stupid to create a temporary table for use subquery, so we have - # to give it some prompting in the form of a subsubquery. Ugh! - def subquery_for(key, select) - subsubselect = select.clone - subsubselect.projections = [key] - - # Materialize subquery by adding distinct - # to work with MySQL 5.7.6 which sets optimizer_switch='derived_merge=on' - subsubselect.distinct unless select.limit || select.offset || select.orders.any? - - subselect = Arel::SelectManager.new(select.engine) - subselect.project Arel.sql(key.name) - subselect.from subsubselect.as("__active_record_temp") - end - - def supports_rename_index? - mariadb? ? false : version >= "5.7.6" - end - - def configure_connection - variables = @config.fetch(:variables, {}).stringify_keys - - # By default, MySQL 'where id is null' selects the last inserted id; Turn this off. - variables["sql_auto_is_null"] = 0 - - # Increase timeout so the server doesn't disconnect us. - wait_timeout = self.class.type_cast_config_to_integer(@config[:wait_timeout]) - wait_timeout = 2147483 unless wait_timeout.is_a?(Integer) - variables["wait_timeout"] = wait_timeout - - defaults = [":default", :default].to_set - - # Make MySQL reject illegal values rather than truncating or blanking them, see - # http://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_strict_all_tables - # If the user has provided another value for sql_mode, don't replace it. - if sql_mode = variables.delete("sql_mode") - sql_mode = quote(sql_mode) - elsif !defaults.include?(strict_mode?) - if strict_mode? - sql_mode = "CONCAT(@@sql_mode, ',STRICT_ALL_TABLES')" - else - sql_mode = "REPLACE(@@sql_mode, 'STRICT_TRANS_TABLES', '')" - sql_mode = "REPLACE(#{sql_mode}, 'STRICT_ALL_TABLES', '')" - sql_mode = "REPLACE(#{sql_mode}, 'TRADITIONAL', '')" - end - sql_mode = "CONCAT(#{sql_mode}, ',NO_AUTO_VALUE_ON_ZERO')" - end - sql_mode_assignment = "@@SESSION.sql_mode = #{sql_mode}, " if sql_mode - - # NAMES does not have an equals sign, see - # http://dev.mysql.com/doc/refman/5.7/en/set-statement.html#id944430 - # (trailing comma because variable_assignments will always have content) - if @config[:encoding] - encoding = "NAMES #{@config[:encoding]}" - encoding << " COLLATE #{@config[:collation]}" if @config[:collation] - encoding << ", " - end - - # Gather up all of the SET variables... - variable_assignments = variables.map do |k, v| - if defaults.include?(v) - "@@SESSION.#{k} = DEFAULT" # Sets the value to the global or compile default - elsif !v.nil? - "@@SESSION.#{k} = #{quote(v)}" - end - # or else nil; compact to clear nils out - end.compact.join(", ") - - # ...and send them all in one query - execute "SET #{encoding} #{sql_mode_assignment} #{variable_assignments}" - end - - def column_definitions(table_name) # :nodoc: - execute_and_free("SHOW FULL FIELDS FROM #{quote_table_name(table_name)}", "SCHEMA") do |result| - each_hash(result) - end - end - - def extract_foreign_key_action(specifier) # :nodoc: - case specifier - when "CASCADE"; :cascade - when "SET NULL"; :nullify - end - end - - def create_table_info(table_name) # :nodoc: - exec_query("SHOW CREATE TABLE #{quote_table_name(table_name)}", "SCHEMA").first["Create Table"] - end - - def create_table_definition(*args) # :nodoc: - MySQL::TableDefinition.new(*args) - end - - def mismatched_foreign_key(message) - match = %r/ - (?:CREATE|ALTER)\s+TABLE\s*(?:`?\w+`?\.)?`?(?\w+)`?.+? - FOREIGN\s+KEY\s*\(`?(?\w+)`?\)\s* - REFERENCES\s*(`?(?\w+)`?)\s*\(`?(?\w+)`?\) - /xmi.match(message) - - options = { - message: message, - } - - if match - options[:table] = match[:table] - options[:foreign_key] = match[:foreign_key] - options[:target_table] = match[:target_table] - options[:primary_key] = match[:primary_key] - options[:primary_key_column] = column_for(match[:target_table], match[:primary_key]) - end - - MismatchedForeignKey.new(options) - end - - def integer_to_sql(limit) # :nodoc: - case limit - when 1; "tinyint" - when 2; "smallint" - when 3; "mediumint" - when nil, 4; "int" - when 5..8; "bigint" - else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a decimal with scale 0 instead.") - end - end - - def text_to_sql(limit) # :nodoc: - case limit - when 0..0xff; "tinytext" - when nil, 0x100..0xffff; "text" - when 0x10000..0xffffff; "mediumtext" - when 0x1000000..0xffffffff; "longtext" - else raise(ActiveRecordError, "No text type has byte length #{limit}") - end - end - - def binary_to_sql(limit) # :nodoc: - case limit - when 0..0xff; "tinyblob" - when nil, 0x100..0xffff; "blob" - when 0x10000..0xffffff; "mediumblob" - when 0x1000000..0xffffffff; "longblob" - else raise(ActiveRecordError, "No binary type has byte length #{limit}") - end - end - - def version_string - full_version.match(/^(?:5\.5\.5-)?(\d+\.\d+\.\d+)/)[1] - end - - class MysqlJson < Type::Internal::AbstractJson # :nodoc: - end - - class MysqlString < Type::String # :nodoc: - def serialize(value) - case value - when true then MySQL::Quoting::QUOTED_TRUE - when false then MySQL::Quoting::QUOTED_FALSE - else super - end - end - - private - - def cast_value(value) - case value - when true then MySQL::Quoting::QUOTED_TRUE - when false then MySQL::Quoting::QUOTED_FALSE - else super - end - end - end - - ActiveRecord::Type.register(:json, MysqlJson, adapter: :mysql2) - ActiveRecord::Type.register(:string, MysqlString, adapter: :mysql2) - ActiveRecord::Type.register(:unsigned_integer, Type::UnsignedInteger, adapter: :mysql2) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/column.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/column.rb deleted file mode 100644 index ea7c8268fb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/column.rb +++ /dev/null @@ -1,89 +0,0 @@ -module ActiveRecord - # :stopdoc: - module ConnectionAdapters - # An abstract definition of a column in a table. - class Column - attr_reader :name, :default, :sql_type_metadata, :null, :table_name, :default_function, :collation, :comment - - delegate :precision, :scale, :limit, :type, :sql_type, to: :sql_type_metadata, allow_nil: true - - # Instantiates a new column in the table. - # - # +name+ is the column's name, such as supplier_id in supplier_id int. - # +default+ is the type-casted default value, such as +new+ in sales_stage varchar(20) default 'new'. - # +sql_type_metadata+ is various information about the type of the column - # +null+ determines if this column allows +NULL+ values. - def initialize(name, default, sql_type_metadata = nil, null = true, table_name = nil, default_function = nil, collation = nil, comment: nil, **) - @name = name.freeze - @table_name = table_name - @sql_type_metadata = sql_type_metadata - @null = null - @default = default - @default_function = default_function - @collation = collation - @comment = comment - end - - def has_default? - !default.nil? || default_function - end - - def bigint? - /\Abigint\b/.match?(sql_type) - end - - # Returns the human name of the column name. - # - # ===== Examples - # Column.new('sales_stage', ...).human_name # => 'Sales stage' - def human_name - Base.human_attribute_name(@name) - end - - def init_with(coder) - @name = coder["name"] - @table_name = coder["table_name"] - @sql_type_metadata = coder["sql_type_metadata"] - @null = coder["null"] - @default = coder["default"] - @default_function = coder["default_function"] - @collation = coder["collation"] - @comment = coder["comment"] - end - - def encode_with(coder) - coder["name"] = @name - coder["table_name"] = @table_name - coder["sql_type_metadata"] = @sql_type_metadata - coder["null"] = @null - coder["default"] = @default - coder["default_function"] = @default_function - coder["collation"] = @collation - coder["comment"] = @comment - end - - def ==(other) - other.is_a?(Column) && - attributes_for_hash == other.attributes_for_hash - end - alias :eql? :== - - def hash - attributes_for_hash.hash - end - - protected - - def attributes_for_hash - [self.class, name, default, sql_type_metadata, null, table_name, default_function, collation] - end - end - - class NullColumn < Column - def initialize(name) - super(name, nil) - end - end - end - # :startdoc: -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/connection_specification.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/connection_specification.rb deleted file mode 100644 index 3e4ea28f63..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/connection_specification.rb +++ /dev/null @@ -1,273 +0,0 @@ -require "uri" - -module ActiveRecord - module ConnectionAdapters - class ConnectionSpecification #:nodoc: - attr_reader :name, :config, :adapter_method - - def initialize(name, config, adapter_method) - @name, @config, @adapter_method = name, config, adapter_method - end - - def initialize_dup(original) - @config = original.config.dup - end - - def to_hash - @config.merge(name: @name) - end - - # Expands a connection string into a hash. - class ConnectionUrlResolver # :nodoc: - # == Example - # - # url = "postgresql://foo:bar@localhost:9000/foo_test?pool=5&timeout=3000" - # ConnectionUrlResolver.new(url).to_hash - # # => { - # "adapter" => "postgresql", - # "host" => "localhost", - # "port" => 9000, - # "database" => "foo_test", - # "username" => "foo", - # "password" => "bar", - # "pool" => "5", - # "timeout" => "3000" - # } - def initialize(url) - raise "Database URL cannot be empty" if url.blank? - @uri = uri_parser.parse(url) - @adapter = @uri.scheme && @uri.scheme.tr("-", "_") - @adapter = "postgresql" if @adapter == "postgres" - - if @uri.opaque - @uri.opaque, @query = @uri.opaque.split("?", 2) - else - @query = @uri.query - end - end - - # Converts the given URL to a full connection hash. - def to_hash - config = raw_config.reject { |_, value| value.blank? } - config.map { |key, value| config[key] = uri_parser.unescape(value) if value.is_a? String } - config - end - - private - - def uri - @uri - end - - def uri_parser - @uri_parser ||= URI::Parser.new - end - - # Converts the query parameters of the URI into a hash. - # - # "localhost?pool=5&reaping_frequency=2" - # # => { "pool" => "5", "reaping_frequency" => "2" } - # - # returns empty hash if no query present. - # - # "localhost" - # # => {} - def query_hash - Hash[(@query || "").split("&").map { |pair| pair.split("=") }] - end - - def raw_config - if uri.opaque - query_hash.merge( - "adapter" => @adapter, - "database" => uri.opaque) - else - query_hash.merge( - "adapter" => @adapter, - "username" => uri.user, - "password" => uri.password, - "port" => uri.port, - "database" => database_from_path, - "host" => uri.hostname) - end - end - - # Returns name of the database. - def database_from_path - if @adapter == "sqlite3" - # 'sqlite3:/foo' is absolute, because that makes sense. The - # corresponding relative version, 'sqlite3:foo', is handled - # elsewhere, as an "opaque". - - uri.path - else - # Only SQLite uses a filename as the "database" name; for - # anything else, a leading slash would be silly. - - uri.path.sub(%r{^/}, "") - end - end - end - - ## - # Builds a ConnectionSpecification from user input. - class Resolver # :nodoc: - attr_reader :configurations - - # Accepts a hash two layers deep, keys on the first layer represent - # environments such as "production". Keys must be strings. - def initialize(configurations) - @configurations = configurations - end - - # Returns a hash with database connection information. - # - # == Examples - # - # Full hash Configuration. - # - # configurations = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } } - # Resolver.new(configurations).resolve(:production) - # # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3"} - # - # Initialized with URL configuration strings. - # - # configurations = { "production" => "postgresql://localhost/foo" } - # Resolver.new(configurations).resolve(:production) - # # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } - # - def resolve(config) - if config - resolve_connection config - elsif env = ActiveRecord::ConnectionHandling::RAILS_ENV.call - resolve_symbol_connection env.to_sym - else - raise AdapterNotSpecified - end - end - - # Expands each key in @configurations hash into fully resolved hash - def resolve_all - config = configurations.dup - - if env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call - env_config = config[env] if config[env].is_a?(Hash) && !(config[env].key?("adapter") || config[env].key?("url")) - end - - config.reject! { |k, v| v.is_a?(Hash) && !(v.key?("adapter") || v.key?("url")) } - config.merge! env_config if env_config - - config.each do |key, value| - config[key] = resolve(value) if value - end - - config - end - - # Returns an instance of ConnectionSpecification for a given adapter. - # Accepts a hash one layer deep that contains all connection information. - # - # == Example - # - # config = { "production" => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } } - # spec = Resolver.new(config).spec(:production) - # spec.adapter_method - # # => "sqlite3_connection" - # spec.config - # # => { "host" => "localhost", "database" => "foo", "adapter" => "sqlite3" } - # - def spec(config) - spec = resolve(config).symbolize_keys - - raise(AdapterNotSpecified, "database configuration does not specify adapter") unless spec.key?(:adapter) - - path_to_adapter = "active_record/connection_adapters/#{spec[:adapter]}_adapter" - begin - require path_to_adapter - rescue Gem::LoadError => e - raise Gem::LoadError, "Specified '#{spec[:adapter]}' for database adapter, but the gem is not loaded. Add `gem '#{e.name}'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord)." - rescue LoadError => e - raise LoadError, "Could not load '#{path_to_adapter}'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.", e.backtrace - end - - adapter_method = "#{spec[:adapter]}_connection" - - unless ActiveRecord::Base.respond_to?(adapter_method) - raise AdapterNotFound, "database configuration specifies nonexistent #{spec.config[:adapter]} adapter" - end - - ConnectionSpecification.new(spec.delete(:name) || "primary", spec, adapter_method) - end - - private - - # Returns fully resolved connection, accepts hash, string or symbol. - # Always returns a hash. - # - # == Examples - # - # Symbol representing current environment. - # - # Resolver.new("production" => {}).resolve_connection(:production) - # # => {} - # - # One layer deep hash of connection values. - # - # Resolver.new({}).resolve_connection("adapter" => "sqlite3") - # # => { "adapter" => "sqlite3" } - # - # Connection URL. - # - # Resolver.new({}).resolve_connection("postgresql://localhost/foo") - # # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } - # - def resolve_connection(spec) - case spec - when Symbol - resolve_symbol_connection spec - when String - resolve_url_connection spec - when Hash - resolve_hash_connection spec - end - end - - # Takes the environment such as +:production+ or +:development+. - # This requires that the @configurations was initialized with a key that - # matches. - # - # Resolver.new("production" => {}).resolve_symbol_connection(:production) - # # => {} - # - def resolve_symbol_connection(spec) - if config = configurations[spec.to_s] - resolve_connection(config).merge("name" => spec.to_s) - else - raise(AdapterNotSpecified, "'#{spec}' database is not configured. Available: #{configurations.keys.inspect}") - end - end - - # Accepts a hash. Expands the "url" key that contains a - # URL database connection to a full connection - # hash and merges with the rest of the hash. - # Connection details inside of the "url" key win any merge conflicts - def resolve_hash_connection(spec) - if spec["url"] && spec["url"] !~ /^jdbc:/ - connection_hash = resolve_url_connection(spec.delete("url")) - spec.merge!(connection_hash) - end - spec - end - - # Takes a connection URL. - # - # Resolver.new({}).resolve_url_connection("postgresql://localhost/foo") - # # => { "host" => "localhost", "database" => "foo", "adapter" => "postgresql" } - # - def resolve_url_connection(url) - ConnectionUrlResolver.new(url).to_hash - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb deleted file mode 100644 index 0fdc185c45..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +++ /dev/null @@ -1,22 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module DetermineIfPreparableVisitor - attr_reader :preparable - - def accept(*) - @preparable = true - super - end - - def visit_Arel_Nodes_In(*) - @preparable = false - super - end - - def visit_Arel_Nodes_SqlLiteral(*) - @preparable = false - super - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/column.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/column.rb deleted file mode 100644 index c9ad47c035..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/column.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - class Column < ConnectionAdapters::Column # :nodoc: - delegate :extra, to: :sql_type_metadata, allow_nil: true - - def unsigned? - /\bunsigned(?: zerofill)?\z/.match?(sql_type) - end - - def case_sensitive? - collation && !/_ci\z/.match?(collation) - end - - def auto_increment? - extra == "auto_increment" - end - - def virtual? - /\b(?:VIRTUAL|STORED|PERSISTENT)\b/.match?(extra) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/database_statements.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/database_statements.rb deleted file mode 100644 index bda482a00f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/database_statements.rb +++ /dev/null @@ -1,95 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - module DatabaseStatements - # Returns an ActiveRecord::Result instance. - def select_all(arel, name = nil, binds = [], preparable: nil) # :nodoc: - result = if ExplainRegistry.collect? && prepared_statements - unprepared_statement { super } - else - super - end - @connection.next_result while @connection.more_results? - result - end - - def query(sql, name = nil) # :nodoc: - execute(sql, name).to_a - end - - # Executes the SQL statement in the context of this connection. - def execute(sql, name = nil) - # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been - # made since we established the connection - @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone - - super - end - - def exec_query(sql, name = "SQL", binds = [], prepare: false) - if without_prepared_statement?(binds) - execute_and_free(sql, name) do |result| - ActiveRecord::Result.new(result.fields, result.to_a) if result - end - else - exec_stmt_and_free(sql, name, binds, cache_stmt: prepare) do |_, result| - ActiveRecord::Result.new(result.fields, result.to_a) if result - end - end - end - - def exec_delete(sql, name = nil, binds = []) - if without_prepared_statement?(binds) - execute_and_free(sql, name) { @connection.affected_rows } - else - exec_stmt_and_free(sql, name, binds) { |stmt| stmt.affected_rows } - end - end - alias :exec_update :exec_delete - - private - - def last_inserted_id(result) - @connection.last_id - end - - def exec_stmt_and_free(sql, name, binds, cache_stmt: false) - # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been - # made since we established the connection - @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone - - type_casted_binds = type_casted_binds(binds) - - log(sql, name, binds, type_casted_binds) do - if cache_stmt - cache = @statements[sql] ||= { - stmt: @connection.prepare(sql) - } - stmt = cache[:stmt] - else - stmt = @connection.prepare(sql) - end - - begin - result = ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - stmt.execute(*type_casted_binds) - end - rescue Mysql2::Error => e - if cache_stmt - @statements.delete(sql) - else - stmt.close - end - raise e - end - - ret = yield stmt, result - result.free if result - stmt.close unless cache_stmt - ret - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb deleted file mode 100644 index 9691060cd3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +++ /dev/null @@ -1,70 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - class ExplainPrettyPrinter # :nodoc: - # Pretty prints the result of an EXPLAIN in a way that resembles the output of the - # MySQL shell: - # - # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ - # | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | - # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ - # | 1 | SIMPLE | users | const | PRIMARY | PRIMARY | 4 | const | 1 | | - # | 1 | SIMPLE | posts | ALL | NULL | NULL | NULL | NULL | 1 | Using where | - # +----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+ - # 2 rows in set (0.00 sec) - # - # This is an exercise in Ruby hyperrealism :). - def pp(result, elapsed) - widths = compute_column_widths(result) - separator = build_separator(widths) - - pp = [] - - pp << separator - pp << build_cells(result.columns, widths) - pp << separator - - result.rows.each do |row| - pp << build_cells(row, widths) - end - - pp << separator - pp << build_footer(result.rows.length, elapsed) - - pp.join("\n") + "\n" - end - - private - - def compute_column_widths(result) - [].tap do |widths| - result.columns.each_with_index do |column, i| - cells_in_column = [column] + result.rows.map { |r| r[i].nil? ? "NULL" : r[i].to_s } - widths << cells_in_column.map(&:length).max - end - end - end - - def build_separator(widths) - padding = 1 - "+" + widths.map { |w| "-" * (w + (padding * 2)) }.join("+") + "+" - end - - def build_cells(items, widths) - cells = [] - items.each_with_index do |item, i| - item = "NULL" if item.nil? - justifier = item.is_a?(Numeric) ? "rjust" : "ljust" - cells << item.to_s.send(justifier, widths[i]) - end - "| " + cells.join(" | ") + " |" - end - - def build_footer(nrows, elapsed) - rows_label = nrows == 1 ? "row" : "rows" - "#{nrows} #{rows_label} in set (%.2f sec)" % elapsed - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/quoting.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/quoting.rb deleted file mode 100644 index d4f5906b33..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/quoting.rb +++ /dev/null @@ -1,45 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - module Quoting # :nodoc: - QUOTED_TRUE, QUOTED_FALSE = "1".freeze, "0".freeze - - def quote_column_name(name) - @quoted_column_names[name] ||= "`#{super.gsub('`', '``')}`".freeze - end - - def quote_table_name(name) - @quoted_table_names[name] ||= super.gsub(".", "`.`").freeze - end - - def quoted_true - QUOTED_TRUE - end - - def unquoted_true - 1 - end - - def quoted_false - QUOTED_FALSE - end - - def unquoted_false - 0 - end - - def quoted_date(value) - if supports_datetime_with_precision? - super - else - super.sub(/\.\d{6}\z/, "") - end - end - - def quoted_binary(value) - "x'#{value.hex}'" - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_creation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_creation.rb deleted file mode 100644 index 083cd6340f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_creation.rb +++ /dev/null @@ -1,71 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - class SchemaCreation < AbstractAdapter::SchemaCreation # :nodoc: - delegate :add_sql_comment!, :mariadb?, to: :@conn - private :add_sql_comment!, :mariadb? - - private - - def visit_DropForeignKey(name) - "DROP FOREIGN KEY #{name}" - end - - def visit_AddColumnDefinition(o) - add_column_position!(super, column_options(o.column)) - end - - def visit_ChangeColumnDefinition(o) - change_column_sql = "CHANGE #{quote_column_name(o.name)} #{accept(o.column)}" - add_column_position!(change_column_sql, column_options(o.column)) - end - - def add_table_options!(create_sql, options) - add_sql_comment!(super, options[:comment]) - end - - def add_column_options!(sql, options) - # By default, TIMESTAMP columns are NOT NULL, cannot contain NULL values, - # and assigning NULL assigns the current timestamp. To permit a TIMESTAMP - # column to contain NULL, explicitly declare it with the NULL attribute. - # See http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html - if /\Atimestamp\b/.match?(options[:column].sql_type) && !options[:primary_key] - sql << " NULL" unless options[:null] == false || options_include_default?(options) - end - - if charset = options[:charset] - sql << " CHARACTER SET #{charset}" - end - - if collation = options[:collation] - sql << " COLLATE #{collation}" - end - - if as = options[:as] - sql << " AS (#{as})" - if options[:stored] - sql << (mariadb? ? " PERSISTENT" : " STORED") - end - end - - add_sql_comment!(super, options[:comment]) - end - - def add_column_position!(sql, options) - if options[:first] - sql << " FIRST" - elsif options[:after] - sql << " AFTER #{quote_column_name(options[:after])}" - end - - sql - end - - def index_in_create(table_name, column_name, options) - index_name, index_type, index_columns, _, _, index_using, comment = @conn.add_index_options(table_name, column_name, options) - add_sql_comment!("#{index_type} INDEX #{quote_column_name(index_name)} #{index_using} (#{index_columns})", comment) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_definitions.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_definitions.rb deleted file mode 100644 index 6d88c14d50..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_definitions.rb +++ /dev/null @@ -1,90 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - module ColumnMethods - def primary_key(name, type = :primary_key, **options) - options[:auto_increment] = true if [:integer, :bigint].include?(type) && !options.key?(:default) - super - end - - def blob(*args, **options) - args.each { |name| column(name, :blob, options) } - end - - def tinyblob(*args, **options) - args.each { |name| column(name, :tinyblob, options) } - end - - def mediumblob(*args, **options) - args.each { |name| column(name, :mediumblob, options) } - end - - def longblob(*args, **options) - args.each { |name| column(name, :longblob, options) } - end - - def tinytext(*args, **options) - args.each { |name| column(name, :tinytext, options) } - end - - def mediumtext(*args, **options) - args.each { |name| column(name, :mediumtext, options) } - end - - def longtext(*args, **options) - args.each { |name| column(name, :longtext, options) } - end - - def json(*args, **options) - args.each { |name| column(name, :json, options) } - end - - def unsigned_integer(*args, **options) - args.each { |name| column(name, :unsigned_integer, options) } - end - - def unsigned_bigint(*args, **options) - args.each { |name| column(name, :unsigned_bigint, options) } - end - - def unsigned_float(*args, **options) - args.each { |name| column(name, :unsigned_float, options) } - end - - def unsigned_decimal(*args, **options) - args.each { |name| column(name, :unsigned_decimal, options) } - end - end - - class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition - include ColumnMethods - - def new_column_definition(name, type, **options) # :nodoc: - case type - when :virtual - type = options[:type] - when :primary_key - type = :integer - options[:limit] ||= 8 - options[:auto_increment] = true - options[:primary_key] = true - when /\Aunsigned_(?.+)\z/ - type = $~[:type].to_sym - options[:unsigned] = true - end - - super - end - - private - def aliased_types(name, fallback) - fallback - end - end - - class Table < ActiveRecord::ConnectionAdapters::Table - include ColumnMethods - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_dumper.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_dumper.rb deleted file mode 100644 index 297beb610e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_dumper.rb +++ /dev/null @@ -1,80 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - module ColumnDumper # :nodoc: - def prepare_column_options(column) - spec = super - spec[:unsigned] = "true" if column.unsigned? - spec[:auto_increment] = "true" if column.auto_increment? - - if supports_virtual_columns? && column.virtual? - spec[:as] = extract_expression_for_virtual_column(column) - spec[:stored] = "true" if /\b(?:STORED|PERSISTENT)\b/.match?(column.extra) - spec = { type: schema_type(column).inspect }.merge!(spec) - end - - spec - end - - def column_spec_for_primary_key(column) - spec = super - spec.delete(:auto_increment) if column.type == :integer && column.auto_increment? - spec - end - - def migration_keys - super + [:unsigned] - end - - private - - def default_primary_key?(column) - super && column.auto_increment? && !column.unsigned? - end - - def explicit_primary_key_default?(column) - column.type == :integer && !column.auto_increment? - end - - def schema_type(column) - case column.sql_type - when /\Atimestamp\b/ - :timestamp - when "tinyblob" - :blob - else - super - end - end - - def schema_precision(column) - super unless /\A(?:date)?time(?:stamp)?\b/.match?(column.sql_type) && column.precision == 0 - end - - def schema_collation(column) - if column.collation && table_name = column.table_name - @table_collation_cache ||= {} - @table_collation_cache[table_name] ||= exec_query("SHOW TABLE STATUS LIKE #{quote(table_name)}", "SCHEMA").first["Collation"] - column.collation.inspect if column.collation != @table_collation_cache[table_name] - end - end - - def extract_expression_for_virtual_column(column) - if mariadb? && version < "10.2.5" - create_table_info = create_table_info(column.table_name) - if %r/#{quote_column_name(column.name)} #{Regexp.quote(column.sql_type)}(?: COLLATE \w+)? AS \((?.+?)\) #{column.extra}/ =~ create_table_info - $~[:expression].inspect - end - else - scope = quoted_scope(column.table_name) - sql = "SELECT generation_expression FROM information_schema.columns" \ - " WHERE table_schema = #{scope[:schema]}" \ - " AND table_name = #{scope[:name]}" \ - " AND column_name = #{quote(column.name)}" - query_value(sql, "SCHEMA").inspect - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_statements.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_statements.rb deleted file mode 100644 index 0452cdddf3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/schema_statements.rb +++ /dev/null @@ -1,43 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - module SchemaStatements # :nodoc: - def internal_string_options_for_primary_key - super.tap do |options| - if CHARSETS_OF_4BYTES_MAXLEN.include?(charset) && (mariadb? || version < "8.0.0") - options[:collation] = collation.sub(/\A[^_]+/, "utf8") - end - end - end - - private - CHARSETS_OF_4BYTES_MAXLEN = ["utf8mb4", "utf16", "utf16le", "utf32"] - - def data_source_sql(name = nil, type: nil) - scope = quoted_scope(name, type: type) - - sql = "SELECT table_name FROM information_schema.tables" - sql << " WHERE table_schema = #{scope[:schema]}" - sql << " AND table_name = #{scope[:name]}" if scope[:name] - sql << " AND table_type = #{scope[:type]}" if scope[:type] - sql - end - - def quoted_scope(name = nil, type: nil) - schema, name = extract_schema_qualified_name(name) - scope = {} - scope[:schema] = schema ? quote(schema) : "database()" - scope[:name] = quote(name) if name - scope[:type] = quote(type) if type - scope - end - - def extract_schema_qualified_name(string) - schema, name = string.to_s.scan(/[^`.\s]+|`[^`]*`/) - schema, name = nil, schema unless name - [schema, name] - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/type_metadata.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/type_metadata.rb deleted file mode 100644 index 9ad6a6c0d0..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql/type_metadata.rb +++ /dev/null @@ -1,33 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module MySQL - class TypeMetadata < DelegateClass(SqlTypeMetadata) # :nodoc: - undef to_yaml if method_defined?(:to_yaml) - - attr_reader :extra - - def initialize(type_metadata, extra: "") - super(type_metadata) - @type_metadata = type_metadata - @extra = extra - end - - def ==(other) - other.is_a?(MySQL::TypeMetadata) && - attributes_for_hash == other.attributes_for_hash - end - alias eql? == - - def hash - attributes_for_hash.hash - end - - protected - - def attributes_for_hash - [self.class, @type_metadata, extra] - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql2_adapter.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql2_adapter.rb deleted file mode 100644 index 6a90a582bb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/mysql2_adapter.rb +++ /dev/null @@ -1,123 +0,0 @@ -require "active_record/connection_adapters/abstract_mysql_adapter" -require "active_record/connection_adapters/mysql/database_statements" - -gem "mysql2", ">= 0.3.18", "< 0.6.0" -require "mysql2" -raise "mysql2 0.4.3 is not supported. Please upgrade to 0.4.4+" if Mysql2::VERSION == "0.4.3" - -module ActiveRecord - module ConnectionHandling # :nodoc: - # Establishes a connection to the database that's used by all Active Record objects. - def mysql2_connection(config) - config = config.symbolize_keys - config[:flags] ||= 0 - - if config[:flags].kind_of? Array - config[:flags].push "FOUND_ROWS".freeze - else - config[:flags] |= Mysql2::Client::FOUND_ROWS - end - - client = Mysql2::Client.new(config) - ConnectionAdapters::Mysql2Adapter.new(client, logger, nil, config) - rescue Mysql2::Error => error - if error.message.include?("Unknown database") - raise ActiveRecord::NoDatabaseError - else - raise - end - end - end - - module ConnectionAdapters - class Mysql2Adapter < AbstractMysqlAdapter - ADAPTER_NAME = "Mysql2".freeze - - include MySQL::DatabaseStatements - - def initialize(connection, logger, connection_options, config) - super - @prepared_statements = false unless config.key?(:prepared_statements) - configure_connection - end - - def supports_json? - !mariadb? && version >= "5.7.8" - end - - def supports_comments? - true - end - - def supports_comments_in_create? - true - end - - def supports_savepoints? - true - end - - # HELPER METHODS =========================================== - - def each_hash(result) # :nodoc: - if block_given? - result.each(as: :hash, symbolize_keys: true) do |row| - yield row - end - else - to_enum(:each_hash, result) - end - end - - def error_number(exception) - exception.error_number if exception.respond_to?(:error_number) - end - - #-- - # QUOTING ================================================== - #++ - - def quote_string(string) - @connection.escape(string) - end - - #-- - # CONNECTION MANAGEMENT ==================================== - #++ - - def active? - @connection.ping - end - - def reconnect! - super - disconnect! - connect - end - alias :reset! :reconnect! - - # Disconnects from the database if already connected. - # Otherwise, this method does nothing. - def disconnect! - super - @connection.close - end - - private - - def connect - @connection = Mysql2::Client.new(@config) - configure_connection - end - - def configure_connection - @connection.query_options.merge!(as: :array) - super - end - - def full_version - @full_version ||= @connection.server_info[:version] - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/column.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/column.rb deleted file mode 100644 index fa34bce235..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/column.rb +++ /dev/null @@ -1,42 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - # PostgreSQL-specific extensions to column definitions in a table. - class PostgreSQLColumn < Column #:nodoc: - delegate :array, :oid, :fmod, to: :sql_type_metadata - alias :array? :array - - def initialize(*, max_identifier_length: 63, **) - super - @max_identifier_length = max_identifier_length - end - - def serial? - return unless default_function - - if %r{\Anextval\('"?(?.+_(?seq\d*))"?'::regclass\)\z} =~ default_function - sequence_name_from_parts(table_name, name, suffix) == sequence_name - end - end - - protected - attr_reader :max_identifier_length - - private - def sequence_name_from_parts(table_name, column_name, suffix) - over_length = [table_name, column_name, suffix].map(&:length).sum + 2 - max_identifier_length - - if over_length > 0 - column_name_length = [(max_identifier_length - suffix.length - 2) / 2, column_name.length].min - over_length -= column_name.length - column_name_length - column_name = column_name[0, column_name_length - [over_length, 0].min] - end - - if over_length > 0 - table_name = table_name[0, table_name.length - over_length] - end - - "#{table_name}_#{column_name}_#{suffix}" - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/database_statements.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/database_statements.rb deleted file mode 100644 index ac5efbebeb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/database_statements.rb +++ /dev/null @@ -1,157 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module DatabaseStatements - def explain(arel, binds = []) - sql = "EXPLAIN #{to_sql(arel, binds)}" - PostgreSQL::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", binds)) - end - - # The internal PostgreSQL identifier of the money data type. - MONEY_COLUMN_TYPE_OID = 790 #:nodoc: - # The internal PostgreSQL identifier of the BYTEA data type. - BYTEA_COLUMN_TYPE_OID = 17 #:nodoc: - - # create a 2D array representing the result set - def result_as_array(res) #:nodoc: - # check if we have any binary column and if they need escaping - ftypes = Array.new(res.nfields) do |i| - [i, res.ftype(i)] - end - - rows = res.values - return rows unless ftypes.any? { |_, x| - x == BYTEA_COLUMN_TYPE_OID || x == MONEY_COLUMN_TYPE_OID - } - - typehash = ftypes.group_by { |_, type| type } - binaries = typehash[BYTEA_COLUMN_TYPE_OID] || [] - monies = typehash[MONEY_COLUMN_TYPE_OID] || [] - - rows.each do |row| - # unescape string passed BYTEA field (OID == 17) - binaries.each do |index, _| - row[index] = unescape_bytea(row[index]) - end - - # If this is a money type column and there are any currency symbols, - # then strip them off. Indeed it would be prettier to do this in - # PostgreSQLColumn.string_to_decimal but would break form input - # fields that call value_before_type_cast. - monies.each do |index, _| - data = row[index] - # Because money output is formatted according to the locale, there are two - # cases to consider (note the decimal separators): - # (1) $12,345,678.12 - # (2) $12.345.678,12 - case data - when /^-?\D+[\d,]+\.\d{2}$/ # (1) - data.gsub!(/[^-\d.]/, "") - when /^-?\D+[\d.]+,\d{2}$/ # (2) - data.gsub!(/[^-\d,]/, "").sub!(/,/, ".") - end - end - end - end - - # Queries the database and returns the results in an Array-like object - def query(sql, name = nil) #:nodoc: - log(sql, name) do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - result_as_array @connection.async_exec(sql) - end - end - end - - # Executes an SQL statement, returning a PG::Result object on success - # or raising a PG::Error exception otherwise. - # Note: the PG::Result object is manually memory managed; if you don't - # need it specifically, you may want consider the exec_query wrapper. - def execute(sql, name = nil) - log(sql, name) do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - @connection.async_exec(sql) - end - end - end - - def exec_query(sql, name = "SQL", binds = [], prepare: false) - execute_and_clear(sql, name, binds, prepare: prepare) do |result| - types = {} - fields = result.fields - fields.each_with_index do |fname, i| - ftype = result.ftype i - fmod = result.fmod i - types[fname] = get_oid_type(ftype, fmod, fname) - end - ActiveRecord::Result.new(fields, result.values, types) - end - end - - def exec_delete(sql, name = nil, binds = []) - execute_and_clear(sql, name, binds) { |result| result.cmd_tuples } - end - alias :exec_update :exec_delete - - def sql_for_insert(sql, pk, id_value, sequence_name, binds) # :nodoc: - if pk.nil? - # Extract the table from the insert sql. Yuck. - table_ref = extract_table_ref_from_insert_sql(sql) - pk = primary_key(table_ref) if table_ref - end - - if pk = suppress_composite_primary_key(pk) - sql = "#{sql} RETURNING #{quote_column_name(pk)}" - end - - super - end - private :sql_for_insert - - def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil) - if use_insert_returning? || pk == false - super - else - result = exec_query(sql, name, binds) - unless sequence_name - table_ref = extract_table_ref_from_insert_sql(sql) - if table_ref - pk = primary_key(table_ref) if pk.nil? - pk = suppress_composite_primary_key(pk) - sequence_name = default_sequence_name(table_ref, pk) - end - return result unless sequence_name - end - last_insert_id_result(sequence_name) - end - end - - # Begins a transaction. - def begin_db_transaction - execute "BEGIN" - end - - def begin_isolated_db_transaction(isolation) - begin_db_transaction - execute "SET TRANSACTION ISOLATION LEVEL #{transaction_isolation_levels.fetch(isolation)}" - end - - # Commits a transaction. - def commit_db_transaction - execute "COMMIT" - end - - # Aborts a transaction. - def exec_rollback_db_transaction - execute "ROLLBACK" - end - - private - - def suppress_composite_primary_key(pk) - pk unless pk.is_a?(Array) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb deleted file mode 100644 index 99f3a5bbdf..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/explain_pretty_printer.rb +++ /dev/null @@ -1,42 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - class ExplainPrettyPrinter # :nodoc: - # Pretty prints the result of an EXPLAIN in a way that resembles the output of the - # PostgreSQL shell: - # - # QUERY PLAN - # ------------------------------------------------------------------------------ - # Nested Loop Left Join (cost=0.00..37.24 rows=8 width=0) - # Join Filter: (posts.user_id = users.id) - # -> Index Scan using users_pkey on users (cost=0.00..8.27 rows=1 width=4) - # Index Cond: (id = 1) - # -> Seq Scan on posts (cost=0.00..28.88 rows=8 width=4) - # Filter: (posts.user_id = 1) - # (6 rows) - # - def pp(result) - header = result.columns.first - lines = result.rows.map(&:first) - - # We add 2 because there's one char of padding at both sides, note - # the extra hyphens in the example above. - width = [header, *lines].map(&:length).max + 2 - - pp = [] - - pp << header.center(width).rstrip - pp << "-" * width - - pp += lines.map { |line| " #{line}" } - - nrows = result.rows.length - rows_label = nrows == 1 ? "row" : "rows" - pp << "(#{nrows} #{rows_label})" - - pp.join("\n") + "\n" - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid.rb deleted file mode 100644 index 4098250f3e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "active_record/connection_adapters/postgresql/oid/array" -require "active_record/connection_adapters/postgresql/oid/bit" -require "active_record/connection_adapters/postgresql/oid/bit_varying" -require "active_record/connection_adapters/postgresql/oid/bytea" -require "active_record/connection_adapters/postgresql/oid/cidr" -require "active_record/connection_adapters/postgresql/oid/date_time" -require "active_record/connection_adapters/postgresql/oid/decimal" -require "active_record/connection_adapters/postgresql/oid/enum" -require "active_record/connection_adapters/postgresql/oid/hstore" -require "active_record/connection_adapters/postgresql/oid/inet" -require "active_record/connection_adapters/postgresql/oid/json" -require "active_record/connection_adapters/postgresql/oid/jsonb" -require "active_record/connection_adapters/postgresql/oid/money" -require "active_record/connection_adapters/postgresql/oid/oid" -require "active_record/connection_adapters/postgresql/oid/point" -require "active_record/connection_adapters/postgresql/oid/legacy_point" -require "active_record/connection_adapters/postgresql/oid/range" -require "active_record/connection_adapters/postgresql/oid/specialized_string" -require "active_record/connection_adapters/postgresql/oid/uuid" -require "active_record/connection_adapters/postgresql/oid/vector" -require "active_record/connection_adapters/postgresql/oid/xml" - -require "active_record/connection_adapters/postgresql/oid/type_map_initializer" - -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/array.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/array.rb deleted file mode 100644 index 15eb74a911..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/array.rb +++ /dev/null @@ -1,90 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Array < Type::Value # :nodoc: - include Type::Helpers::Mutable - - Data = Struct.new(:encoder, :values) # :nodoc: - - attr_reader :subtype, :delimiter - delegate :type, :user_input_in_time_zone, :limit, :precision, :scale, to: :subtype - - def initialize(subtype, delimiter = ",") - @subtype = subtype - @delimiter = delimiter - - @pg_encoder = PG::TextEncoder::Array.new name: "#{type}[]", delimiter: delimiter - @pg_decoder = PG::TextDecoder::Array.new name: "#{type}[]", delimiter: delimiter - end - - def deserialize(value) - case value - when ::String - type_cast_array(@pg_decoder.decode(value), :deserialize) - when Data - type_cast_array(value.values, :deserialize) - else - super - end - end - - def cast(value) - if value.is_a?(::String) - value = begin - @pg_decoder.decode(value) - rescue TypeError - # malformed array string is treated as [], will raise in PG 2.0 gem - # this keeps a consistent implementation - [] - end - end - type_cast_array(value, :cast) - end - - def serialize(value) - if value.is_a?(::Array) - casted_values = type_cast_array(value, :serialize) - Data.new(@pg_encoder, casted_values) - else - super - end - end - - def ==(other) - other.is_a?(Array) && - subtype == other.subtype && - delimiter == other.delimiter - end - - def type_cast_for_schema(value) - return super unless value.is_a?(::Array) - "[" + value.map { |v| subtype.type_cast_for_schema(v) }.join(", ") + "]" - end - - def map(value, &block) - value.map(&block) - end - - def changed_in_place?(raw_old_value, new_value) - deserialize(raw_old_value) != new_value - end - - def force_equality?(value) - value.is_a?(::Array) - end - - private - - def type_cast_array(value, method) - if value.is_a?(::Array) - value.map { |item| type_cast_array(item, method) } - else - @subtype.public_send(method, value) - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bit.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bit.rb deleted file mode 100644 index 0a505f46a7..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bit.rb +++ /dev/null @@ -1,54 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Bit < Type::Value # :nodoc: - def type - :bit - end - - def cast_value(value) - if ::String === value - case value - when /^0x/i - value[2..-1].hex.to_s(2) # Hexadecimal notation - else - value # Bit-string notation - end - else - value.to_s - end - end - - def serialize(value) - Data.new(super) if value - end - - class Data - def initialize(value) - @value = value - end - - def to_s - value - end - - def binary? - /\A[01]*\Z/.match?(value) - end - - def hex? - /\A[0-9A-F]*\Z/i.match?(value) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :value - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb deleted file mode 100644 index 4c21097d48..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bit_varying.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class BitVarying < OID::Bit # :nodoc: - def type - :bit_varying - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bytea.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bytea.rb deleted file mode 100644 index 702fa8175c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/bytea.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Bytea < Type::Binary # :nodoc: - def deserialize(value) - return if value.nil? - return value.to_s if value.is_a?(Type::Binary::Data) - PG::Connection.unescape_bytea(super) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/cidr.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/cidr.rb deleted file mode 100644 index 5225609e37..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "ipaddr" - -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Cidr < Type::Value # :nodoc: - def type - :cidr - end - - def type_cast_for_schema(value) - subnet_mask = value.instance_variable_get(:@mask_addr) - - # If the subnet mask is equal to /32, don't output it - if subnet_mask == (2**32 - 1) - "\"#{value}\"" - else - "\"#{value}/#{subnet_mask.to_s(2).count('1')}\"" - end - end - - def serialize(value) - if IPAddr === value - "#{value}/#{value.instance_variable_get(:@mask_addr).to_s(2).count('1')}" - else - value - end - end - - def cast_value(value) - if value.nil? - nil - elsif String === value - begin - IPAddr.new(value) - rescue ArgumentError - nil - end - else - value - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/date_time.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/date_time.rb deleted file mode 100644 index b7acbf7178..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/date_time.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class DateTime < Type::DateTime # :nodoc: - def cast_value(value) - case value - when "infinity" then ::Float::INFINITY - when "-infinity" then -::Float::INFINITY - when / BC$/ - astronomical_year = format("%04d", -value[/^\d+/].to_i + 1) - super(value.sub(/ BC$/, "").sub(/^\d+/, astronomical_year)) - else - super - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/decimal.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/decimal.rb deleted file mode 100644 index 5470a818c5..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/decimal.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Decimal < Type::Decimal # :nodoc: - def infinity(options = {}) - BigDecimal("Infinity") * (options[:negative] ? -1 : 1) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/enum.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/enum.rb deleted file mode 100644 index 950d23d516..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/enum.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Enum < Type::Value # :nodoc: - def type - :enum - end - - private - - def cast_value(value) - value.to_s - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/hstore.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/hstore.rb deleted file mode 100644 index 49dd4fc73f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +++ /dev/null @@ -1,69 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Hstore < Type::Value # :nodoc: - include Type::Helpers::Mutable - - def type - :hstore - end - - def deserialize(value) - if value.is_a?(::String) - ::Hash[value.scan(HstorePair).map { |k, v| - v = v.upcase == "NULL" ? nil : v.gsub(/\A"(.*)"\Z/m, '\1').gsub(/\\(.)/, '\1') - k = k.gsub(/\A"(.*)"\Z/m, '\1').gsub(/\\(.)/, '\1') - [k, v] - }] - else - value - end - end - - def serialize(value) - if value.is_a?(::Hash) - value.map { |k, v| "#{escape_hstore(k)}=>#{escape_hstore(v)}" }.join(", ") - elsif value.respond_to?(:to_unsafe_h) - serialize(value.to_unsafe_h) - else - value - end - end - - def accessor - ActiveRecord::Store::StringKeyedHashAccessor - end - - # Will compare the Hash equivalents of +raw_old_value+ and +new_value+. - # By comparing hashes, this avoids an edge case where the order of - # the keys change between the two hashes, and they would not be marked - # as equal. - def changed_in_place?(raw_old_value, new_value) - deserialize(raw_old_value) != new_value - end - - private - - HstorePair = begin - quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/ - unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/ - /(#{quoted_string}|#{unquoted_string})\s*=>\s*(#{quoted_string}|#{unquoted_string})/ - end - - def escape_hstore(value) - if value.nil? - "NULL" - else - if value == "" - '""' - else - '"%s"' % value.to_s.gsub(/(["\\])/, '\\\\\1') - end - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/inet.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/inet.rb deleted file mode 100644 index 96486fa65b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/inet.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Inet < Cidr # :nodoc: - def type - :inet - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/json.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/json.rb deleted file mode 100644 index dbc879ffd4..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/json.rb +++ /dev/null @@ -1,10 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Json < Type::Internal::AbstractJson - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb deleted file mode 100644 index 705cb7f0b3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/jsonb.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Jsonb < Json # :nodoc: - def type - :jsonb - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb deleted file mode 100644 index 775eecaf85..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +++ /dev/null @@ -1,43 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class LegacyPoint < Type::Value # :nodoc: - include Type::Helpers::Mutable - - def type - :point - end - - def cast(value) - case value - when ::String - if value[0] == "(" && value[-1] == ")" - value = value[1...-1] - end - cast(value.split(",")) - when ::Array - value.map { |v| Float(v) } - else - value - end - end - - def serialize(value) - if value.is_a?(::Array) - "(#{number_for_point(value[0])},#{number_for_point(value[1])})" - else - super - end - end - - private - - def number_for_point(number) - number.to_s.gsub(/\.0$/, "") - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/money.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/money.rb deleted file mode 100644 index 7a91272d1c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/money.rb +++ /dev/null @@ -1,39 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Money < Type::Decimal # :nodoc: - def type - :money - end - - def scale - 2 - end - - def cast_value(value) - return value unless ::String === value - - # Because money output is formatted according to the locale, there are two - # cases to consider (note the decimal separators): - # (1) $12,345,678.12 - # (2) $12.345.678,12 - # Negative values are represented as follows: - # (3) -$2.55 - # (4) ($2.55) - - value.sub!(/^\((.+)\)$/, '-\1') # (4) - case value - when /^-?\D+[\d,]+\.\d{2}$/ # (1) - value.gsub!(/[^-\d.]/, "") - when /^-?\D+[\d.]+,\d{2}$/ # (2) - value.gsub!(/[^-\d,]/, "").sub!(/,/, ".") - end - - super(value) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/oid.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/oid.rb deleted file mode 100644 index 9c2ac08b30..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/oid.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Oid < Type::Integer # :nodoc: - def type - :oid - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/point.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/point.rb deleted file mode 100644 index 7c764e7287..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/point.rb +++ /dev/null @@ -1,63 +0,0 @@ -module ActiveRecord - Point = Struct.new(:x, :y) - - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Point < Type::Value # :nodoc: - include Type::Helpers::Mutable - - def type - :point - end - - def cast(value) - case value - when ::String - return if value.blank? - - if value[0] == "(" && value[-1] == ")" - value = value[1...-1] - end - x, y = value.split(",") - build_point(x, y) - when ::Array - build_point(*value) - else - value - end - end - - def serialize(value) - case value - when ActiveRecord::Point - "(#{number_for_point(value.x)},#{number_for_point(value.y)})" - when ::Array - serialize(build_point(*value)) - else - super - end - end - - def type_cast_for_schema(value) - if ActiveRecord::Point === value - [value.x, value.y] - else - super - end - end - - private - - def number_for_point(number) - number.to_s.gsub(/\.0$/, "") - end - - def build_point(x, y) - ActiveRecord::Point.new(Float(x), Float(y)) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/range.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/range.rb deleted file mode 100644 index ea3d89ff3d..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/range.rb +++ /dev/null @@ -1,95 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Range < Type::Value # :nodoc: - attr_reader :subtype, :type - delegate :user_input_in_time_zone, to: :subtype - - def initialize(subtype, type = :range) - @subtype = subtype - @type = type - end - - def type_cast_for_schema(value) - value.inspect.gsub("Infinity", "::Float::INFINITY") - end - - def cast_value(value) - return if value == "empty" - return value unless value.is_a?(::String) - - extracted = extract_bounds(value) - from = type_cast_single extracted[:from] - to = type_cast_single extracted[:to] - - if !infinity?(from) && extracted[:exclude_start] - raise ArgumentError, "The Ruby Range object does not support excluding the beginning of a Range. (unsupported value: '#{value}')" - end - ::Range.new(from, to, extracted[:exclude_end]) - end - - def serialize(value) - if value.is_a?(::Range) - from = type_cast_single_for_database(value.begin) - to = type_cast_single_for_database(value.end) - "[#{from},#{to}#{value.exclude_end? ? ')' : ']'}" - else - super - end - end - - def ==(other) - other.is_a?(Range) && - other.subtype == subtype && - other.type == type - end - - def map(value) # :nodoc: - new_begin = yield(value.begin) - new_end = yield(value.end) - ::Range.new(new_begin, new_end, value.exclude_end?) - end - - def force_equality?(value) - value.is_a?(::Range) - end - - private - - def type_cast_single(value) - infinity?(value) ? value : @subtype.deserialize(value) - end - - def type_cast_single_for_database(value) - infinity?(value) ? "" : @subtype.serialize(value) - end - - def extract_bounds(value) - from, to = value[1..-2].split(",") - { - from: (value[1] == "," || from == "-infinity") ? infinity(negative: true) : from, - to: (value[-2] == "," || to == "infinity") ? infinity : to, - exclude_start: (value[0] == "("), - exclude_end: (value[-1] == ")") - } - end - - def infinity(negative: false) - if subtype.respond_to?(:infinity) - subtype.infinity(negative: negative) - elsif negative - -::Float::INFINITY - else - ::Float::INFINITY - end - end - - def infinity?(value) - value.respond_to?(:infinite?) && value.infinite? - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb deleted file mode 100644 index 564e82a4ac..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/specialized_string.rb +++ /dev/null @@ -1,16 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class SpecializedString < Type::String # :nodoc: - attr_reader :type - - def initialize(type, **options) - @type = type - super(options) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb deleted file mode 100644 index d9ae1aa7a2..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +++ /dev/null @@ -1,109 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - # This class uses the data from PostgreSQL pg_type table to build - # the OID -> Type mapping. - # - OID is an integer representing the type. - # - Type is an OID::Type object. - # This class has side effects on the +store+ passed during initialization. - class TypeMapInitializer # :nodoc: - def initialize(store) - @store = store - end - - def run(records) - nodes = records.reject { |row| @store.key? row["oid"].to_i } - mapped, nodes = nodes.partition { |row| @store.key? row["typname"] } - ranges, nodes = nodes.partition { |row| row["typtype"] == "r".freeze } - enums, nodes = nodes.partition { |row| row["typtype"] == "e".freeze } - domains, nodes = nodes.partition { |row| row["typtype"] == "d".freeze } - arrays, nodes = nodes.partition { |row| row["typinput"] == "array_in".freeze } - composites, nodes = nodes.partition { |row| row["typelem"].to_i != 0 } - - mapped.each { |row| register_mapped_type(row) } - enums.each { |row| register_enum_type(row) } - domains.each { |row| register_domain_type(row) } - arrays.each { |row| register_array_type(row) } - ranges.each { |row| register_range_type(row) } - composites.each { |row| register_composite_type(row) } - end - - def query_conditions_for_initial_load(type_map) - known_type_names = type_map.keys.map { |n| "'#{n}'" } - known_type_types = %w('r' 'e' 'd') - <<-SQL % [known_type_names.join(", "), known_type_types.join(", ")] - WHERE - t.typname IN (%s) - OR t.typtype IN (%s) - OR t.typinput = 'array_in(cstring,oid,integer)'::regprocedure - OR t.typelem != 0 - SQL - end - - private - def register_mapped_type(row) - alias_type row["oid"], row["typname"] - end - - def register_enum_type(row) - register row["oid"], OID::Enum.new - end - - def register_array_type(row) - register_with_subtype(row["oid"], row["typelem"].to_i) do |subtype| - OID::Array.new(subtype, row["typdelim"]) - end - end - - def register_range_type(row) - register_with_subtype(row["oid"], row["rngsubtype"].to_i) do |subtype| - OID::Range.new(subtype, row["typname"].to_sym) - end - end - - def register_domain_type(row) - if base_type = @store.lookup(row["typbasetype"].to_i) - register row["oid"], base_type - else - warn "unknown base type (OID: #{row["typbasetype"]}) for domain #{row["typname"]}." - end - end - - def register_composite_type(row) - if subtype = @store.lookup(row["typelem"].to_i) - register row["oid"], OID::Vector.new(row["typdelim"], subtype) - end - end - - def register(oid, oid_type = nil, &block) - oid = assert_valid_registration(oid, oid_type || block) - if block_given? - @store.register_type(oid, &block) - else - @store.register_type(oid, oid_type) - end - end - - def alias_type(oid, target) - oid = assert_valid_registration(oid, target) - @store.alias_type(oid, target) - end - - def register_with_subtype(oid, target_oid) - if @store.key?(target_oid) - register(oid) do |_, *args| - yield @store.lookup(target_oid, *args) - end - end - end - - def assert_valid_registration(oid, oid_type) - raise ArgumentError, "can't register nil type for OID #{oid}" if oid_type.nil? - oid.to_i - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/uuid.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/uuid.rb deleted file mode 100644 index 5e839228e9..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Uuid < Type::Value # :nodoc: - ACCEPTABLE_UUID = %r{\A\{?([a-fA-F0-9]{4}-?){8}\}?\z}x - - alias_method :serialize, :deserialize - - def type - :uuid - end - - def cast(value) - value.to_s[ACCEPTABLE_UUID, 0] - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/vector.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/vector.rb deleted file mode 100644 index b26e876b54..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/vector.rb +++ /dev/null @@ -1,26 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Vector < Type::Value # :nodoc: - attr_reader :delim, :subtype - - # +delim+ corresponds to the `typdelim` column in the pg_types - # table. +subtype+ is derived from the `typelem` column in the - # pg_types table. - def initialize(delim, subtype) - @delim = delim - @subtype = subtype - end - - # FIXME: this should probably split on +delim+ and use +subtype+ - # to cast the values. Unfortunately, the current Rails behavior - # is to just return the string. - def cast(value) - value - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/xml.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/xml.rb deleted file mode 100644 index d40d837cee..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/oid/xml.rb +++ /dev/null @@ -1,28 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module OID # :nodoc: - class Xml < Type::String # :nodoc: - def type - :xml - end - - def serialize(value) - return unless value - Data.new(super) - end - - class Data # :nodoc: - def initialize(value) - @value = value - end - - def to_s - @value - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/quoting.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/quoting.rb deleted file mode 100644 index 92067b748b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/quoting.rb +++ /dev/null @@ -1,150 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module Quoting - # Escapes binary strings for bytea input to the database. - def escape_bytea(value) - @connection.escape_bytea(value) if value - end - - # Unescapes bytea output from a database to the binary string it represents. - # NOTE: This is NOT an inverse of escape_bytea! This is only to be used - # on escaped binary output from database drive. - def unescape_bytea(value) - @connection.unescape_bytea(value) if value - end - - # Quotes strings for use in SQL input. - def quote_string(s) #:nodoc: - @connection.escape(s) - end - - # Checks the following cases: - # - # - table_name - # - "table.name" - # - schema_name.table_name - # - schema_name."table.name" - # - "schema.name".table_name - # - "schema.name"."table.name" - def quote_table_name(name) # :nodoc: - @quoted_table_names[name] ||= Utils.extract_schema_qualified_name(name.to_s).quoted.freeze - end - - # Quotes schema names for use in SQL queries. - def quote_schema_name(name) - PG::Connection.quote_ident(name) - end - - def quote_table_name_for_assignment(table, attr) - quote_column_name(attr) - end - - # Quotes column names for use in SQL queries. - def quote_column_name(name) # :nodoc: - @quoted_column_names[name] ||= PG::Connection.quote_ident(super).freeze - end - - # Quote date/time values for use in SQL input. - def quoted_date(value) #:nodoc: - if value.year <= 0 - bce_year = format("%04d", -value.year + 1) - super.sub(/^-?\d+/, bce_year) + " BC" - else - super - end - end - - def quoted_binary(value) # :nodoc: - "'#{escape_bytea(value.to_s)}'" - end - - def quote_default_expression(value, column) # :nodoc: - if value.is_a?(Proc) - value.call - elsif column.type == :uuid && value.is_a?(String) && /\(\)/.match?(value) - value # Does not quote function default values for UUID columns - elsif column.respond_to?(:array?) - value = type_cast_from_column(column, value) - quote(value) - else - super - end - end - - def lookup_cast_type_from_column(column) # :nodoc: - type_map.lookup(column.oid, column.fmod, column.sql_type) - end - - private - def lookup_cast_type(sql_type) - super(query_value("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").to_i) - end - - def _quote(value) - case value - when OID::Xml::Data - "xml '#{quote_string(value.to_s)}'" - when OID::Bit::Data - if value.binary? - "B'#{value}'" - elsif value.hex? - "X'#{value}'" - end - when Float - if value.infinite? || value.nan? - "'#{value}'" - else - super - end - when OID::Array::Data - _quote(encode_array(value)) - else - super - end - end - - def _type_cast(value) - case value - when Type::Binary::Data - # Return a bind param hash with format as binary. - # See https://deveiate.org/code/pg/PG/Connection.html#method-i-exec_prepared-doc - # for more information - { value: value.to_s, format: 1 } - when OID::Xml::Data, OID::Bit::Data - value.to_s - when OID::Array::Data - encode_array(value) - else - super - end - end - - def encode_array(array_data) - encoder = array_data.encoder - values = type_cast_array(array_data.values) - - result = encoder.encode(values) - if encoding = determine_encoding_of_strings_in_array(values) - result.force_encoding(encoding) - end - result - end - - def determine_encoding_of_strings_in_array(value) - case value - when ::Array then determine_encoding_of_strings_in_array(value.first) - when ::String then value.encoding - end - end - - def type_cast_array(values) - case values - when ::Array then values.map { |item| type_cast_array(item) } - else _type_cast(values) - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/referential_integrity.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/referential_integrity.rb deleted file mode 100644 index 44a7338bf5..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/referential_integrity.rb +++ /dev/null @@ -1,49 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module ReferentialIntegrity # :nodoc: - def supports_disable_referential_integrity? # :nodoc: - true - end - - def disable_referential_integrity # :nodoc: - if supports_disable_referential_integrity? - original_exception = nil - - begin - transaction(requires_new: true) do - execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";")) - end - rescue ActiveRecord::ActiveRecordError => e - original_exception = e - end - - begin - yield - rescue ActiveRecord::InvalidForeignKey => e - warn <<-WARNING -WARNING: Rails was not able to disable referential integrity. - -This is most likely caused due to missing permissions. -Rails needs superuser privileges to disable referential integrity. - - cause: #{original_exception.try(:message)} - - WARNING - raise e - end - - begin - transaction(requires_new: true) do - execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";")) - end - rescue ActiveRecord::ActiveRecordError - end - else - yield - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_creation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_creation.rb deleted file mode 100644 index e1d5089115..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_creation.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - class SchemaCreation < AbstractAdapter::SchemaCreation # :nodoc: - private - def add_column_options!(sql, options) - if options[:collation] - sql << " COLLATE \"#{options[:collation]}\"" - end - super - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_definitions.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_definitions.rb deleted file mode 100644 index 11ea1e5144..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_definitions.rb +++ /dev/null @@ -1,193 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module ColumnMethods - # Defines the primary key field. - # Use of the native PostgreSQL UUID type is supported, and can be used - # by defining your tables as such: - # - # create_table :stuffs, id: :uuid do |t| - # t.string :content - # t.timestamps - # end - # - # By default, this will use the +gen_random_uuid()+ function from the - # +pgcrypto+ extension. As that extension is only available in - # PostgreSQL 9.4+, for earlier versions an explicit default can be set - # to use +uuid_generate_v4()+ from the +uuid-ossp+ extension instead: - # - # create_table :stuffs, id: false do |t| - # t.primary_key :id, :uuid, default: "uuid_generate_v4()" - # t.uuid :foo_id - # t.timestamps - # end - # - # To enable the appropriate extension, which is a requirement, use - # the +enable_extension+ method in your migrations. - # - # To use a UUID primary key without any of the extensions, set the - # +:default+ option to +nil+: - # - # create_table :stuffs, id: false do |t| - # t.primary_key :id, :uuid, default: nil - # t.uuid :foo_id - # t.timestamps - # end - # - # You may also pass a custom stored procedure that returns a UUID or use a - # different UUID generation function from another library. - # - # Note that setting the UUID primary key default value to +nil+ will - # require you to assure that you always provide a UUID value before saving - # a record (as primary keys cannot be +nil+). This might be done via the - # +SecureRandom.uuid+ method and a +before_save+ callback, for instance. - def primary_key(name, type = :primary_key, **options) - options[:auto_increment] = true if [:integer, :bigint].include?(type) && !options.key?(:default) - if type == :uuid - options[:default] = options.fetch(:default, "gen_random_uuid()") - elsif options.delete(:auto_increment) == true && %i(integer bigint).include?(type) - type = if type == :bigint || options[:limit] == 8 - :bigserial - else - :serial - end - end - - super - end - - def bigserial(*args, **options) - args.each { |name| column(name, :bigserial, options) } - end - - def bit(*args, **options) - args.each { |name| column(name, :bit, options) } - end - - def bit_varying(*args, **options) - args.each { |name| column(name, :bit_varying, options) } - end - - def cidr(*args, **options) - args.each { |name| column(name, :cidr, options) } - end - - def citext(*args, **options) - args.each { |name| column(name, :citext, options) } - end - - def daterange(*args, **options) - args.each { |name| column(name, :daterange, options) } - end - - def hstore(*args, **options) - args.each { |name| column(name, :hstore, options) } - end - - def inet(*args, **options) - args.each { |name| column(name, :inet, options) } - end - - def interval(*args, **options) - args.each { |name| column(name, :interval, options) } - end - - def int4range(*args, **options) - args.each { |name| column(name, :int4range, options) } - end - - def int8range(*args, **options) - args.each { |name| column(name, :int8range, options) } - end - - def json(*args, **options) - args.each { |name| column(name, :json, options) } - end - - def jsonb(*args, **options) - args.each { |name| column(name, :jsonb, options) } - end - - def ltree(*args, **options) - args.each { |name| column(name, :ltree, options) } - end - - def macaddr(*args, **options) - args.each { |name| column(name, :macaddr, options) } - end - - def money(*args, **options) - args.each { |name| column(name, :money, options) } - end - - def numrange(*args, **options) - args.each { |name| column(name, :numrange, options) } - end - - def oid(*args, **options) - args.each { |name| column(name, :oid, options) } - end - - def point(*args, **options) - args.each { |name| column(name, :point, options) } - end - - def line(*args, **options) - args.each { |name| column(name, :line, options) } - end - - def lseg(*args, **options) - args.each { |name| column(name, :lseg, options) } - end - - def box(*args, **options) - args.each { |name| column(name, :box, options) } - end - - def path(*args, **options) - args.each { |name| column(name, :path, options) } - end - - def polygon(*args, **options) - args.each { |name| column(name, :polygon, options) } - end - - def circle(*args, **options) - args.each { |name| column(name, :circle, options) } - end - - def serial(*args, **options) - args.each { |name| column(name, :serial, options) } - end - - def tsrange(*args, **options) - args.each { |name| column(name, :tsrange, options) } - end - - def tstzrange(*args, **options) - args.each { |name| column(name, :tstzrange, options) } - end - - def tsvector(*args, **options) - args.each { |name| column(name, :tsvector, options) } - end - - def uuid(*args, **options) - args.each { |name| column(name, :uuid, options) } - end - - def xml(*args, **options) - args.each { |name| column(name, :xml, options) } - end - end - - class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition - include ColumnMethods - end - - class Table < ActiveRecord::ConnectionAdapters::Table - include ColumnMethods - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_dumper.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_dumper.rb deleted file mode 100644 index 5555a46b6b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +++ /dev/null @@ -1,43 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module ColumnDumper # :nodoc: - # Adds +:array+ option to the default set - def prepare_column_options(column) - spec = super - spec[:array] = "true" if column.array? - spec - end - - # Adds +:array+ as a valid migration key - def migration_keys - super + [:array] - end - - private - - def default_primary_key?(column) - schema_type(column) == :bigserial - end - - def explicit_primary_key_default?(column) - column.type == :uuid || (column.type == :integer && !column.serial?) - end - - def schema_type(column) - return super unless column.serial? - - if column.bigint? - :bigserial - else - :serial - end - end - - def schema_expression(column) - super unless column.serial? - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_statements.rb deleted file mode 100644 index 2d102e7656..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ /dev/null @@ -1,652 +0,0 @@ -require "active_support/core_ext/string/strip" - -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - module SchemaStatements - # Drops the database specified on the +name+ attribute - # and creates it again using the provided +options+. - def recreate_database(name, options = {}) #:nodoc: - drop_database(name) - create_database(name, options) - end - - # Create a new PostgreSQL database. Options include :owner, :template, - # :encoding (defaults to utf8), :collation, :ctype, - # :tablespace, and :connection_limit (note that MySQL uses - # :charset while PostgreSQL uses :encoding). - # - # Example: - # create_database config[:database], config - # create_database 'foo_development', encoding: 'unicode' - def create_database(name, options = {}) - options = { encoding: "utf8" }.merge!(options.symbolize_keys) - - option_string = options.inject("") do |memo, (key, value)| - memo += case key - when :owner - " OWNER = \"#{value}\"" - when :template - " TEMPLATE = \"#{value}\"" - when :encoding - " ENCODING = '#{value}'" - when :collation - " LC_COLLATE = '#{value}'" - when :ctype - " LC_CTYPE = '#{value}'" - when :tablespace - " TABLESPACE = \"#{value}\"" - when :connection_limit - " CONNECTION LIMIT = #{value}" - else - "" - end - end - - execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}" - end - - # Drops a PostgreSQL database. - # - # Example: - # drop_database 'matt_development' - def drop_database(name) #:nodoc: - execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}" - end - - def drop_table(table_name, options = {}) # :nodoc: - execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}" - end - - # Returns true if schema exists. - def schema_exists?(name) - query_value("SELECT COUNT(*) FROM pg_namespace WHERE nspname = #{quote(name)}", "SCHEMA").to_i > 0 - end - - # Verifies existence of an index with a given name. - def index_name_exists?(table_name, index_name, default = nil) - unless default.nil? - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing default to #index_name_exists? is deprecated without replacement. - MSG - end - table = quoted_scope(table_name) - index = quoted_scope(index_name) - - query_value(<<-SQL, "SCHEMA").to_i > 0 - SELECT COUNT(*) - FROM pg_class t - INNER JOIN pg_index d ON t.oid = d.indrelid - INNER JOIN pg_class i ON d.indexrelid = i.oid - LEFT JOIN pg_namespace n ON n.oid = i.relnamespace - WHERE i.relkind = 'i' - AND i.relname = #{index[:name]} - AND t.relname = #{table[:name]} - AND n.nspname = #{index[:schema]} - SQL - end - - # Returns an array of indexes for the given table. - def indexes(table_name, name = nil) # :nodoc: - if name - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing name to #indexes is deprecated without replacement. - MSG - end - - scope = quoted_scope(table_name) - - result = query(<<-SQL, "SCHEMA") - SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid, - pg_catalog.obj_description(i.oid, 'pg_class') AS comment, - (SELECT COUNT(*) FROM pg_opclass o - JOIN (SELECT unnest(string_to_array(d.indclass::text, ' '))::int oid) c - ON o.oid = c.oid WHERE o.opcdefault = 'f') - FROM pg_class t - INNER JOIN pg_index d ON t.oid = d.indrelid - INNER JOIN pg_class i ON d.indexrelid = i.oid - LEFT JOIN pg_namespace n ON n.oid = i.relnamespace - WHERE i.relkind = 'i' - AND d.indisprimary = 'f' - AND t.relname = #{scope[:name]} - AND n.nspname = #{scope[:schema]} - ORDER BY i.relname - SQL - - result.map do |row| - index_name = row[0] - unique = row[1] - indkey = row[2].split(" ").map(&:to_i) - inddef = row[3] - oid = row[4] - comment = row[5] - opclass = row[6] - - using, expressions, where = inddef.scan(/ USING (\w+?) \((.+?)\)(?: WHERE (.+))?\z/m).flatten - - if indkey.include?(0) || opclass > 0 - columns = expressions - else - columns = Hash[query(<<-SQL.strip_heredoc, "SCHEMA")].values_at(*indkey).compact - SELECT a.attnum, a.attname - FROM pg_attribute a - WHERE a.attrelid = #{oid} - AND a.attnum IN (#{indkey.join(",")}) - SQL - - # add info on sort order for columns (only desc order is explicitly specified, asc is the default) - orders = Hash[ - expressions.scan(/(\w+) DESC/).flatten.map { |order_column| [order_column, :desc] } - ] - end - - IndexDefinition.new(table_name, index_name, unique, columns, [], orders, where, nil, using.to_sym, comment.presence) - end.compact - end - - def new_column_from_field(table_name, field) # :nondoc: - column_name, type, default, notnull, oid, fmod, collation, comment = field - oid = oid.to_i - fmod = fmod.to_i - type_metadata = fetch_type_metadata(column_name, type, oid, fmod) - default_value = extract_value_from_default(default) - default_function = extract_default_function(default_value, default) - PostgreSQLColumn.new( - column_name, - default_value, - type_metadata, - !notnull, - table_name, - default_function, - collation, - comment: comment.presence, - max_identifier_length: max_identifier_length - ) - end - - def table_options(table_name) # :nodoc: - if comment = table_comment(table_name) - { comment: comment } - end - end - - # Returns a comment stored in database for given table - def table_comment(table_name) # :nodoc: - scope = quoted_scope(table_name, type: "BASE TABLE") - if scope[:name] - query_value(<<-SQL.strip_heredoc, "SCHEMA") - SELECT pg_catalog.obj_description(c.oid, 'pg_class') - FROM pg_catalog.pg_class c - LEFT JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE c.relname = #{scope[:name]} - AND c.relkind IN (#{scope[:type]}) - AND n.nspname = #{scope[:schema]} - SQL - end - end - - # Returns the current database name. - def current_database - query_value("SELECT current_database()", "SCHEMA") - end - - # Returns the current schema name. - def current_schema - query_value("SELECT current_schema", "SCHEMA") - end - - # Returns the current database encoding format. - def encoding - query_value("SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = current_database()", "SCHEMA") - end - - # Returns the current database collation. - def collation - query_value("SELECT datcollate FROM pg_database WHERE datname = current_database()", "SCHEMA") - end - - # Returns the current database ctype. - def ctype - query_value("SELECT datctype FROM pg_database WHERE datname = current_database()", "SCHEMA") - end - - # Returns an array of schema names. - def schema_names - query_values(<<-SQL, "SCHEMA") - SELECT nspname - FROM pg_namespace - WHERE nspname !~ '^pg_.*' - AND nspname NOT IN ('information_schema') - ORDER by nspname; - SQL - end - - # Creates a schema for the given schema name. - def create_schema(schema_name) - execute "CREATE SCHEMA #{quote_schema_name(schema_name)}" - end - - # Drops the schema for the given schema name. - def drop_schema(schema_name, options = {}) - execute "DROP SCHEMA#{' IF EXISTS' if options[:if_exists]} #{quote_schema_name(schema_name)} CASCADE" - end - - # Sets the schema search path to a string of comma-separated schema names. - # Names beginning with $ have to be quoted (e.g. $user => '$user'). - # See: http://www.postgresql.org/docs/current/static/ddl-schemas.html - # - # This should be not be called manually but set in database.yml. - def schema_search_path=(schema_csv) - if schema_csv - execute("SET search_path TO #{schema_csv}", "SCHEMA") - @schema_search_path = schema_csv - end - end - - # Returns the active schema search path. - def schema_search_path - @schema_search_path ||= query_value("SHOW search_path", "SCHEMA") - end - - # Returns the current client message level. - def client_min_messages - query_value("SHOW client_min_messages", "SCHEMA") - end - - # Set the client message level. - def client_min_messages=(level) - execute("SET client_min_messages TO '#{level}'", "SCHEMA") - end - - # Returns the sequence name for a table's primary key or some other specified key. - def default_sequence_name(table_name, pk = "id") #:nodoc: - result = serial_sequence(table_name, pk) - return nil unless result - Utils.extract_schema_qualified_name(result).to_s - rescue ActiveRecord::StatementInvalid - PostgreSQL::Name.new(nil, "#{table_name}_#{pk}_seq").to_s - end - - def serial_sequence(table, column) - query_value("SELECT pg_get_serial_sequence(#{quote(table)}, #{quote(column)})", "SCHEMA") - end - - # Sets the sequence of a table's primary key to the specified value. - def set_pk_sequence!(table, value) #:nodoc: - pk, sequence = pk_and_sequence_for(table) - - if pk - if sequence - quoted_sequence = quote_table_name(sequence) - - query_value("SELECT setval(#{quote(quoted_sequence)}, #{value})", "SCHEMA") - else - @logger.warn "#{table} has primary key #{pk} with no default sequence." if @logger - end - end - end - - # Resets the sequence of a table's primary key to the maximum value. - def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc: - unless pk && sequence - default_pk, default_sequence = pk_and_sequence_for(table) - - pk ||= default_pk - sequence ||= default_sequence - end - - if @logger && pk && !sequence - @logger.warn "#{table} has primary key #{pk} with no default sequence." - end - - if pk && sequence - quoted_sequence = quote_table_name(sequence) - max_pk = query_value("SELECT MAX(#{quote_column_name pk}) FROM #{quote_table_name(table)}", "SCHEMA") - if max_pk.nil? - if postgresql_version >= 100000 - minvalue = query_value("SELECT seqmin FROM pg_sequence WHERE seqrelid = #{quote(quoted_sequence)}::regclass", "SCHEMA") - else - minvalue = query_value("SELECT min_value FROM #{quoted_sequence}", "SCHEMA") - end - end - - query_value("SELECT setval(#{quote(quoted_sequence)}, #{max_pk ? max_pk : minvalue}, #{max_pk ? true : false})", "SCHEMA") - end - end - - # Returns a table's primary key and belonging sequence. - def pk_and_sequence_for(table) #:nodoc: - # First try looking for a sequence with a dependency on the - # given table's primary key. - result = query(<<-end_sql, "SCHEMA")[0] - SELECT attr.attname, nsp.nspname, seq.relname - FROM pg_class seq, - pg_attribute attr, - pg_depend dep, - pg_constraint cons, - pg_namespace nsp - WHERE seq.oid = dep.objid - AND seq.relkind = 'S' - AND attr.attrelid = dep.refobjid - AND attr.attnum = dep.refobjsubid - AND attr.attrelid = cons.conrelid - AND attr.attnum = cons.conkey[1] - AND seq.relnamespace = nsp.oid - AND cons.contype = 'p' - AND dep.classid = 'pg_class'::regclass - AND dep.refobjid = '#{quote_table_name(table)}'::regclass - end_sql - - if result.nil? || result.empty? - result = query(<<-end_sql, "SCHEMA")[0] - SELECT attr.attname, nsp.nspname, - CASE - WHEN pg_get_expr(def.adbin, def.adrelid) !~* 'nextval' THEN NULL - WHEN split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2) ~ '.' THEN - substr(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2), - strpos(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2), '.')+1) - ELSE split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2) - END - FROM pg_class t - JOIN pg_attribute attr ON (t.oid = attrelid) - JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum) - JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1]) - JOIN pg_namespace nsp ON (t.relnamespace = nsp.oid) - WHERE t.oid = '#{quote_table_name(table)}'::regclass - AND cons.contype = 'p' - AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval|uuid_generate' - end_sql - end - - pk = result.shift - if result.last - [pk, PostgreSQL::Name.new(*result)] - else - [pk, nil] - end - rescue - nil - end - - def primary_keys(table_name) # :nodoc: - query_values(<<-SQL.strip_heredoc, "SCHEMA") - SELECT a.attname - FROM ( - SELECT indrelid, indkey, generate_subscripts(indkey, 1) idx - FROM pg_index - WHERE indrelid = #{quote(quote_table_name(table_name))}::regclass - AND indisprimary - ) i - JOIN pg_attribute a - ON a.attrelid = i.indrelid - AND a.attnum = i.indkey[i.idx] - ORDER BY i.idx - SQL - end - - # Renames a table. - # Also renames a table's primary key sequence if the sequence name exists and - # matches the Active Record default. - # - # Example: - # rename_table('octopuses', 'octopi') - def rename_table(table_name, new_name) - clear_cache! - execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}" - pk, seq = pk_and_sequence_for(new_name) - if seq && seq.identifier == "#{table_name}_#{pk}_seq" - new_seq = "#{new_name}_#{pk}_seq" - idx = "#{table_name}_pkey" - new_idx = "#{new_name}_pkey" - execute "ALTER TABLE #{seq.quoted} RENAME TO #{quote_table_name(new_seq)}" - execute "ALTER INDEX #{quote_table_name(idx)} RENAME TO #{quote_table_name(new_idx)}" - end - - rename_table_indexes(table_name, new_name) - end - - def add_column(table_name, column_name, type, options = {}) #:nodoc: - clear_cache! - super - change_column_comment(table_name, column_name, options[:comment]) if options.key?(:comment) - end - - def change_column(table_name, column_name, type, options = {}) #:nodoc: - clear_cache! - quoted_table_name = quote_table_name(table_name) - quoted_column_name = quote_column_name(column_name) - sql_type = type_to_sql(type, options) - sql = "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quoted_column_name} TYPE #{sql_type}" - if options[:collation] - sql << " COLLATE \"#{options[:collation]}\"" - end - if options[:using] - sql << " USING #{options[:using]}" - elsif options[:cast_as] - cast_as_type = type_to_sql(options[:cast_as], options) - sql << " USING CAST(#{quoted_column_name} AS #{cast_as_type})" - end - execute sql - - change_column_default(table_name, column_name, options[:default]) if options.key?(:default) - change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null) - change_column_comment(table_name, column_name, options[:comment]) if options.key?(:comment) - end - - # Changes the default value of a table column. - def change_column_default(table_name, column_name, default_or_changes) # :nodoc: - clear_cache! - column = column_for(table_name, column_name) - return unless column - - default = extract_new_default_value(default_or_changes) - alter_column_query = "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} %s" - if default.nil? - # DEFAULT NULL results in the same behavior as DROP DEFAULT. However, PostgreSQL will - # cast the default to the columns type, which leaves us with a default like "default NULL::character varying". - execute alter_column_query % "DROP DEFAULT" - else - execute alter_column_query % "SET DEFAULT #{quote_default_expression(default, column)}" - end - end - - def change_column_null(table_name, column_name, null, default = nil) #:nodoc: - clear_cache! - unless null || default.nil? - column = column_for(table_name, column_name) - execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote_default_expression(default, column)} WHERE #{quote_column_name(column_name)} IS NULL") if column - end - execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL") - end - - # Adds comment for given table column or drops it if +comment+ is a +nil+ - def change_column_comment(table_name, column_name, comment) # :nodoc: - clear_cache! - execute "COMMENT ON COLUMN #{quote_table_name(table_name)}.#{quote_column_name(column_name)} IS #{quote(comment)}" - end - - # Adds comment for given table or drops it if +comment+ is a +nil+ - def change_table_comment(table_name, comment) # :nodoc: - clear_cache! - execute "COMMENT ON TABLE #{quote_table_name(table_name)} IS #{quote(comment)}" - end - - # Renames a column in a table. - def rename_column(table_name, column_name, new_column_name) #:nodoc: - clear_cache! - execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}" - rename_column_indexes(table_name, column_name, new_column_name) - end - - def add_index(table_name, column_name, options = {}) #:nodoc: - index_name, index_type, index_columns, index_options, index_algorithm, index_using, comment = add_index_options(table_name, column_name, options) - execute("CREATE #{index_type} INDEX #{index_algorithm} #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_using} (#{index_columns})#{index_options}").tap do - execute "COMMENT ON INDEX #{quote_column_name(index_name)} IS #{quote(comment)}" if comment - end - end - - def remove_index(table_name, options = {}) #:nodoc: - table = Utils.extract_schema_qualified_name(table_name.to_s) - - if options.is_a?(Hash) && options.key?(:name) - provided_index = Utils.extract_schema_qualified_name(options[:name].to_s) - - options[:name] = provided_index.identifier - table = PostgreSQL::Name.new(provided_index.schema, table.identifier) unless table.schema.present? - - if provided_index.schema.present? && table.schema != provided_index.schema - raise ArgumentError.new("Index schema '#{provided_index.schema}' does not match table schema '#{table.schema}'") - end - end - - index_to_remove = PostgreSQL::Name.new(table.schema, index_name_for_remove(table.to_s, options)) - algorithm = - if options.is_a?(Hash) && options.key?(:algorithm) - index_algorithms.fetch(options[:algorithm]) do - raise ArgumentError.new("Algorithm must be one of the following: #{index_algorithms.keys.map(&:inspect).join(', ')}") - end - end - execute "DROP INDEX #{algorithm} #{quote_table_name(index_to_remove)}" - end - - # Renames an index of a table. Raises error if length of new - # index name is greater than allowed limit. - def rename_index(table_name, old_name, new_name) - validate_index_length!(table_name, new_name) - - execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}" - end - - def foreign_keys(table_name) - scope = quoted_scope(table_name) - fk_info = exec_query(<<-SQL.strip_heredoc, "SCHEMA") - SELECT t2.oid::regclass::text AS to_table, a1.attname AS column, a2.attname AS primary_key, c.conname AS name, c.confupdtype AS on_update, c.confdeltype AS on_delete - FROM pg_constraint c - JOIN pg_class t1 ON c.conrelid = t1.oid - JOIN pg_class t2 ON c.confrelid = t2.oid - JOIN pg_attribute a1 ON a1.attnum = c.conkey[1] AND a1.attrelid = t1.oid - JOIN pg_attribute a2 ON a2.attnum = c.confkey[1] AND a2.attrelid = t2.oid - JOIN pg_namespace t3 ON c.connamespace = t3.oid - WHERE c.contype = 'f' - AND t1.relname = #{scope[:name]} - AND t3.nspname = #{scope[:schema]} - ORDER BY c.conname - SQL - - fk_info.map do |row| - options = { - column: row["column"], - name: row["name"], - primary_key: row["primary_key"] - } - - options[:on_delete] = extract_foreign_key_action(row["on_delete"]) - options[:on_update] = extract_foreign_key_action(row["on_update"]) - - ForeignKeyDefinition.new(table_name, row["to_table"], options) - end - end - - def extract_foreign_key_action(specifier) # :nodoc: - case specifier - when "c"; :cascade - when "n"; :nullify - when "r"; :restrict - end - end - - # Maps logical Rails types to PostgreSQL-specific data types. - def type_to_sql(type, limit: nil, precision: nil, scale: nil, array: nil, **) # :nodoc: - sql = \ - case type.to_s - when "binary" - # PostgreSQL doesn't support limits on binary (bytea) columns. - # The hard limit is 1GB, because of a 32-bit size field, and TOAST. - case limit - when nil, 0..0x3fffffff; super(type) - else raise(ActiveRecordError, "No binary type has byte size #{limit}.") - end - when "text" - # PostgreSQL doesn't support limits on text columns. - # The hard limit is 1GB, according to section 8.3 in the manual. - case limit - when nil, 0..0x3fffffff; super(type) - else raise(ActiveRecordError, "The limit on text can be at most 1GB - 1byte.") - end - when "integer" - case limit - when 1, 2; "smallint" - when nil, 3, 4; "integer" - when 5..8; "bigint" - else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with scale 0 instead.") - end - else - super - end - - sql << "[]" if array && type != :primary_key - sql - end - - # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and - # requires that the ORDER BY include the distinct column. - def columns_for_distinct(columns, orders) #:nodoc: - order_columns = orders.reject(&:blank?).map { |s| - # Convert Arel node to string - s = s.to_sql unless s.is_a?(String) - # Remove any ASC/DESC modifiers - s.gsub(/\s+(?:ASC|DESC)\b/i, "") - .gsub(/\s+NULLS\s+(?:FIRST|LAST)\b/i, "") - }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" } - - [super, *order_columns].join(", ") - end - - def fetch_type_metadata(column_name, sql_type, oid, fmod) - cast_type = get_oid_type(oid, fmod, column_name, sql_type) - simple_type = SqlTypeMetadata.new( - sql_type: sql_type, - type: cast_type.type, - limit: cast_type.limit, - precision: cast_type.precision, - scale: cast_type.scale, - ) - PostgreSQLTypeMetadata.new(simple_type, oid: oid, fmod: fmod) - end - - private - def data_source_sql(name = nil, type: nil) - scope = quoted_scope(name, type: type) - scope[:type] ||= "'r','v','m'" # (r)elation/table, (v)iew, (m)aterialized view - - sql = "SELECT c.relname FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace" - sql << " WHERE n.nspname = #{scope[:schema]}" - sql << " AND c.relname = #{scope[:name]}" if scope[:name] - sql << " AND c.relkind IN (#{scope[:type]})" - sql - end - - def quoted_scope(name = nil, type: nil) - schema, name = extract_schema_qualified_name(name) - type = \ - case type - when "BASE TABLE" - "'r'" - when "VIEW" - "'v','m'" - end - scope = {} - scope[:schema] = schema ? quote(schema) : "ANY (current_schemas(false))" - scope[:name] = quote(name) if name - scope[:type] = type if type - scope - end - - def extract_schema_qualified_name(string) - name = Utils.extract_schema_qualified_name(string.to_s) - [name.schema, name.identifier] - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/type_metadata.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/type_metadata.rb deleted file mode 100644 index f57179ae59..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/type_metadata.rb +++ /dev/null @@ -1,37 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - class PostgreSQLTypeMetadata < DelegateClass(SqlTypeMetadata) - undef to_yaml if method_defined?(:to_yaml) - - attr_reader :oid, :fmod, :array - - def initialize(type_metadata, oid: nil, fmod: nil) - super(type_metadata) - @type_metadata = type_metadata - @oid = oid - @fmod = fmod - @array = /\[\]$/.match?(type_metadata.sql_type) - end - - def sql_type - super.gsub(/\[\]$/, "".freeze) - end - - def ==(other) - other.is_a?(PostgreSQLTypeMetadata) && - attributes_for_hash == other.attributes_for_hash - end - alias eql? == - - def hash - attributes_for_hash.hash - end - - protected - - def attributes_for_hash - [self.class, @type_metadata, oid, fmod] - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/utils.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/utils.rb deleted file mode 100644 index aa7940188a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql/utils.rb +++ /dev/null @@ -1,79 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module PostgreSQL - # Value Object to hold a schema qualified name. - # This is usually the name of a PostgreSQL relation but it can also represent - # schema qualified type names. +schema+ and +identifier+ are unquoted to prevent - # double quoting. - class Name # :nodoc: - SEPARATOR = "." - attr_reader :schema, :identifier - - def initialize(schema, identifier) - @schema, @identifier = unquote(schema), unquote(identifier) - end - - def to_s - parts.join SEPARATOR - end - - def quoted - if schema - PG::Connection.quote_ident(schema) << SEPARATOR << PG::Connection.quote_ident(identifier) - else - PG::Connection.quote_ident(identifier) - end - end - - def ==(o) - o.class == self.class && o.parts == parts - end - alias_method :eql?, :== - - def hash - parts.hash - end - - protected - - def parts - @parts ||= [@schema, @identifier].compact - end - - private - def unquote(part) - if part && part.start_with?('"') - part[1..-2] - else - part - end - end - end - - module Utils # :nodoc: - extend self - - # Returns an instance of ActiveRecord::ConnectionAdapters::PostgreSQL::Name - # extracted from +string+. - # +schema+ is +nil+ if not specified in +string+. - # +schema+ and +identifier+ exclude surrounding quotes (regardless of whether provided in +string+) - # +string+ supports the range of schema/table references understood by PostgreSQL, for example: - # - # * table_name - # * "table.name" - # * schema_name.table_name - # * schema_name."table.name" - # * "schema_name".table_name - # * "schema.name"."table name" - def extract_schema_qualified_name(string) - schema, table = string.scan(/[^".\s]+|"[^"]*"/) - if table.nil? - table = schema - schema = nil - end - PostgreSQL::Name.new(schema, table) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql_adapter.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql_adapter.rb deleted file mode 100644 index eb2bffaf55..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/postgresql_adapter.rb +++ /dev/null @@ -1,879 +0,0 @@ -# Make sure we're using pg high enough for type casts and Ruby 2.2+ compatibility -gem "pg", ">= 0.18", "< 2.0" -require "pg" - -# Use async_exec instead of exec_params on pg versions before 1.1 -class ::PG::Connection - unless self.public_method_defined?(:async_exec_params) - remove_method :exec_params - alias exec_params async_exec - end -end - -require "active_record/connection_adapters/abstract_adapter" -require "active_record/connection_adapters/statement_pool" -require "active_record/connection_adapters/postgresql/column" -require "active_record/connection_adapters/postgresql/database_statements" -require "active_record/connection_adapters/postgresql/explain_pretty_printer" -require "active_record/connection_adapters/postgresql/oid" -require "active_record/connection_adapters/postgresql/quoting" -require "active_record/connection_adapters/postgresql/referential_integrity" -require "active_record/connection_adapters/postgresql/schema_creation" -require "active_record/connection_adapters/postgresql/schema_definitions" -require "active_record/connection_adapters/postgresql/schema_dumper" -require "active_record/connection_adapters/postgresql/schema_statements" -require "active_record/connection_adapters/postgresql/type_metadata" -require "active_record/connection_adapters/postgresql/utils" - -module ActiveRecord - module ConnectionHandling # :nodoc: - # Establishes a connection to the database that's used by all Active Record objects - def postgresql_connection(config) - conn_params = config.symbolize_keys - - conn_params.delete_if { |_, v| v.nil? } - - # Map ActiveRecords param names to PGs. - conn_params[:user] = conn_params.delete(:username) if conn_params[:username] - conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database] - - # Forward only valid config params to PG::Connection.connect. - valid_conn_param_keys = PG::Connection.conndefaults_hash.keys + [:requiressl] - conn_params.slice!(*valid_conn_param_keys) - - # The postgres drivers don't allow the creation of an unconnected PG::Connection object, - # so just pass a nil connection object for the time being. - ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config) - end - end - - module ConnectionAdapters - # The PostgreSQL adapter works with the native C (https://bitbucket.org/ged/ruby-pg) driver. - # - # Options: - # - # * :host - Defaults to a Unix-domain socket in /tmp. On machines without Unix-domain sockets, - # the default is to connect to localhost. - # * :port - Defaults to 5432. - # * :username - Defaults to be the same as the operating system name of the user running the application. - # * :password - Password to be used if the server demands password authentication. - # * :database - Defaults to be the same as the user name. - # * :schema_search_path - An optional schema search path for the connection given - # as a string of comma-separated schema names. This is backward-compatible with the :schema_order option. - # * :encoding - An optional client encoding that is used in a SET client_encoding TO - # call on the connection. - # * :min_messages - An optional client min messages that is used in a - # SET client_min_messages TO call on the connection. - # * :variables - An optional hash of additional parameters that - # will be used in SET SESSION key = val calls on the connection. - # * :insert_returning - An optional boolean to control the use of RETURNING for INSERT statements - # defaults to true. - # - # Any further options are used as connection parameters to libpq. See - # http://www.postgresql.org/docs/current/static/libpq-connect.html for the - # list of parameters. - # - # In addition, default connection parameters of libpq can be set per environment variables. - # See http://www.postgresql.org/docs/current/static/libpq-envars.html . - class PostgreSQLAdapter < AbstractAdapter - ADAPTER_NAME = "PostgreSQL".freeze - - NATIVE_DATABASE_TYPES = { - primary_key: "bigserial primary key", - string: { name: "character varying" }, - text: { name: "text" }, - integer: { name: "integer" }, - float: { name: "float" }, - decimal: { name: "decimal" }, - datetime: { name: "timestamp" }, - time: { name: "time" }, - date: { name: "date" }, - daterange: { name: "daterange" }, - numrange: { name: "numrange" }, - tsrange: { name: "tsrange" }, - tstzrange: { name: "tstzrange" }, - int4range: { name: "int4range" }, - int8range: { name: "int8range" }, - binary: { name: "bytea" }, - boolean: { name: "boolean" }, - xml: { name: "xml" }, - tsvector: { name: "tsvector" }, - hstore: { name: "hstore" }, - inet: { name: "inet" }, - cidr: { name: "cidr" }, - macaddr: { name: "macaddr" }, - uuid: { name: "uuid" }, - json: { name: "json" }, - jsonb: { name: "jsonb" }, - ltree: { name: "ltree" }, - citext: { name: "citext" }, - point: { name: "point" }, - line: { name: "line" }, - lseg: { name: "lseg" }, - box: { name: "box" }, - path: { name: "path" }, - polygon: { name: "polygon" }, - circle: { name: "circle" }, - bit: { name: "bit" }, - bit_varying: { name: "bit varying" }, - money: { name: "money" }, - interval: { name: "interval" }, - oid: { name: "oid" }, - } - - OID = PostgreSQL::OID #:nodoc: - - include PostgreSQL::Quoting - include PostgreSQL::ReferentialIntegrity - include PostgreSQL::SchemaStatements - include PostgreSQL::DatabaseStatements - include PostgreSQL::ColumnDumper - - def schema_creation # :nodoc: - PostgreSQL::SchemaCreation.new self - end - - def arel_visitor # :nodoc: - Arel::Visitors::PostgreSQL.new(self) - end - - # Returns true, since this connection adapter supports prepared statement - # caching. - def supports_statement_cache? - true - end - - def supports_index_sort_order? - true - end - - def supports_partial_index? - true - end - - def supports_expression_index? - true - end - - def supports_transaction_isolation? - true - end - - def supports_foreign_keys? - true - end - - def supports_views? - true - end - - def supports_datetime_with_precision? - true - end - - def supports_json? - postgresql_version >= 90200 - end - - def supports_comments? - true - end - - def supports_savepoints? - true - end - - def index_algorithms - { concurrently: "CONCURRENTLY" } - end - - class StatementPool < ConnectionAdapters::StatementPool - def initialize(connection, max) - super(max) - @connection = connection - @counter = 0 - end - - def next_key - "a#{@counter + 1}" - end - - def []=(sql, key) - super.tap { @counter += 1 } - end - - private - - def dealloc(key) - @connection.query "DEALLOCATE #{key}" if connection_active? - rescue PG::Error - end - - def connection_active? - @connection.status == PG::CONNECTION_OK - rescue PG::Error - false - end - end - - # Initializes and connects a PostgreSQL adapter. - def initialize(connection, logger, connection_parameters, config) - super(connection, logger, config) - - @connection_parameters = connection_parameters - - # @local_tz is initialized as nil to avoid warnings when connect tries to use it - @local_tz = nil - @max_identifier_length = nil - - connect - add_pg_encoders - @statements = StatementPool.new @connection, - self.class.type_cast_config_to_integer(config[:statement_limit]) - - if postgresql_version < 90100 - raise "Your version of PostgreSQL (#{postgresql_version}) is too old. Active Record supports PostgreSQL >= 9.1." - end - - add_pg_decoders - - @type_map = Type::HashLookupTypeMap.new - initialize_type_map(type_map) - @local_tz = execute("SHOW TIME ZONE", "SCHEMA").first["TimeZone"] - @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true - end - - # Clears the prepared statements cache. - def clear_cache! - @lock.synchronize do - @statements.clear - end - end - - def truncate(table_name, name = nil) - exec_query "TRUNCATE TABLE #{quote_table_name(table_name)}", name, [] - end - - # Is this connection alive and ready for queries? - def active? - @lock.synchronize do - @connection.query "SELECT 1" - end - true - rescue PG::Error - false - end - - # Close then reopen the connection. - def reconnect! - @lock.synchronize do - super - @connection.reset - configure_connection - end - end - - def reset! - @lock.synchronize do - clear_cache! - reset_transaction - unless @connection.transaction_status == ::PG::PQTRANS_IDLE - @connection.query "ROLLBACK" - end - @connection.query "DISCARD ALL" - configure_connection - end - end - - # Disconnects from the database if already connected. Otherwise, this - # method does nothing. - def disconnect! - @lock.synchronize do - super - @connection.close rescue nil - end - end - - def native_database_types #:nodoc: - NATIVE_DATABASE_TYPES - end - - def set_standard_conforming_strings - execute("SET standard_conforming_strings = on", "SCHEMA") - end - - def supports_ddl_transactions? - true - end - - def supports_advisory_locks? - true - end - - def supports_explain? - true - end - - def supports_extensions? - true - end - - # Range datatypes weren't introduced until PostgreSQL 9.2 - def supports_ranges? - postgresql_version >= 90200 - end - - def supports_materialized_views? - postgresql_version >= 90300 - end - - def supports_pgcrypto_uuid? - postgresql_version >= 90400 - end - - def get_advisory_lock(lock_id) # :nodoc: - unless lock_id.is_a?(Integer) && lock_id.bit_length <= 63 - raise(ArgumentError, "Postgres requires advisory lock ids to be a signed 64 bit integer") - end - query_value("SELECT pg_try_advisory_lock(#{lock_id})") - end - - def release_advisory_lock(lock_id) # :nodoc: - unless lock_id.is_a?(Integer) && lock_id.bit_length <= 63 - raise(ArgumentError, "Postgres requires advisory lock ids to be a signed 64 bit integer") - end - query_value("SELECT pg_advisory_unlock(#{lock_id})") - end - - def enable_extension(name) - exec_query("CREATE EXTENSION IF NOT EXISTS \"#{name}\"").tap { - reload_type_map - } - end - - def disable_extension(name) - exec_query("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE").tap { - reload_type_map - } - end - - def extension_enabled?(name) - if supports_extensions? - res = exec_query("SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL) as enabled", "SCHEMA") - res.cast_values.first - end - end - - def extensions - if supports_extensions? - exec_query("SELECT extname FROM pg_extension", "SCHEMA").cast_values - else - super - end - end - - # Returns the configured supported identifier length supported by PostgreSQL - def max_identifier_length - @max_identifier_length ||= query_value("SHOW max_identifier_length", "SCHEMA").to_i - end - alias table_alias_length max_identifier_length - alias index_name_length max_identifier_length - - # Set the authorized user for this session - def session_auth=(user) - clear_cache! - execute("SET SESSION AUTHORIZATION #{user}") - end - - def use_insert_returning? - @use_insert_returning - end - - def update_table_definition(table_name, base) #:nodoc: - PostgreSQL::Table.new(table_name, base) - end - - def column_name_for_operation(operation, node) # :nodoc: - OPERATION_ALIASES.fetch(operation) { operation.downcase } - end - - OPERATION_ALIASES = { # :nodoc: - "maximum" => "max", - "minimum" => "min", - "average" => "avg", - } - - # Returns the version of the connected PostgreSQL server. - def postgresql_version - @connection.server_version - end - - def default_index_type?(index) # :nodoc: - index.using == :btree || super - end - - private - - # See http://www.postgresql.org/docs/current/static/errcodes-appendix.html - VALUE_LIMIT_VIOLATION = "22001" - NUMERIC_VALUE_OUT_OF_RANGE = "22003" - NOT_NULL_VIOLATION = "23502" - FOREIGN_KEY_VIOLATION = "23503" - UNIQUE_VIOLATION = "23505" - SERIALIZATION_FAILURE = "40001" - DEADLOCK_DETECTED = "40P01" - - def translate_exception(exception, message) - return exception unless exception.respond_to?(:result) - - case exception.result.try(:error_field, PG::PG_DIAG_SQLSTATE) - when UNIQUE_VIOLATION - RecordNotUnique.new(message) - when FOREIGN_KEY_VIOLATION - InvalidForeignKey.new(message) - when VALUE_LIMIT_VIOLATION - ValueTooLong.new(message) - when NUMERIC_VALUE_OUT_OF_RANGE - RangeError.new(message) - when NOT_NULL_VIOLATION - NotNullViolation.new(message) - when SERIALIZATION_FAILURE - SerializationFailure.new(message) - when DEADLOCK_DETECTED - Deadlocked.new(message) - else - super - end - end - - def get_oid_type(oid, fmod, column_name, sql_type = "".freeze) - if !type_map.key?(oid) - load_additional_types(type_map, [oid]) - end - - type_map.fetch(oid, fmod, sql_type) { - warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String." - Type.default_value.tap do |cast_type| - type_map.register_type(oid, cast_type) - end - } - end - - def initialize_type_map(m) - register_class_with_limit m, "int2", Type::Integer - register_class_with_limit m, "int4", Type::Integer - register_class_with_limit m, "int8", Type::Integer - m.register_type "oid", OID::Oid.new - m.register_type "float4", Type::Float.new - m.alias_type "float8", "float4" - m.register_type "text", Type::Text.new - register_class_with_limit m, "varchar", Type::String - m.alias_type "char", "varchar" - m.alias_type "name", "varchar" - m.alias_type "bpchar", "varchar" - m.register_type "bool", Type::Boolean.new - register_class_with_limit m, "bit", OID::Bit - register_class_with_limit m, "varbit", OID::BitVarying - m.alias_type "timestamptz", "timestamp" - m.register_type "date", Type::Date.new - - m.register_type "money", OID::Money.new - m.register_type "bytea", OID::Bytea.new - m.register_type "point", OID::Point.new - m.register_type "hstore", OID::Hstore.new - m.register_type "json", OID::Json.new - m.register_type "jsonb", OID::Jsonb.new - m.register_type "cidr", OID::Cidr.new - m.register_type "inet", OID::Inet.new - m.register_type "uuid", OID::Uuid.new - m.register_type "xml", OID::Xml.new - m.register_type "tsvector", OID::SpecializedString.new(:tsvector) - m.register_type "macaddr", OID::SpecializedString.new(:macaddr) - m.register_type "citext", OID::SpecializedString.new(:citext) - m.register_type "ltree", OID::SpecializedString.new(:ltree) - m.register_type "line", OID::SpecializedString.new(:line) - m.register_type "lseg", OID::SpecializedString.new(:lseg) - m.register_type "box", OID::SpecializedString.new(:box) - m.register_type "path", OID::SpecializedString.new(:path) - m.register_type "polygon", OID::SpecializedString.new(:polygon) - m.register_type "circle", OID::SpecializedString.new(:circle) - - m.register_type "interval" do |_, _, sql_type| - precision = extract_precision(sql_type) - OID::SpecializedString.new(:interval, precision: precision) - end - - register_class_with_precision m, "time", Type::Time - register_class_with_precision m, "timestamp", OID::DateTime - - m.register_type "numeric" do |_, fmod, sql_type| - precision = extract_precision(sql_type) - scale = extract_scale(sql_type) - - # The type for the numeric depends on the width of the field, - # so we'll do something special here. - # - # When dealing with decimal columns: - # - # places after decimal = fmod - 4 & 0xffff - # places before decimal = (fmod - 4) >> 16 & 0xffff - if fmod && (fmod - 4 & 0xffff).zero? - # FIXME: Remove this class, and the second argument to - # lookups on PG - Type::DecimalWithoutScale.new(precision: precision) - else - OID::Decimal.new(precision: precision, scale: scale) - end - end - - load_additional_types(m) - end - - def extract_limit(sql_type) - case sql_type - when /^bigint/i, /^int8/i - 8 - when /^smallint/i - 2 - else - super - end - end - - # Extracts the value from a PostgreSQL column default definition. - def extract_value_from_default(default) - case default - # Quoted types - when /\A[\(B]?'(.*)'.*::"?([\w. ]+)"?(?:\[\])?\z/m - # The default 'now'::date is CURRENT_DATE - if $1 == "now".freeze && $2 == "date".freeze - nil - else - $1.gsub("''".freeze, "'".freeze) - end - # Boolean types - when "true".freeze, "false".freeze - default - # Numeric types - when /\A\(?(-?\d+(\.\d*)?)\)?(::bigint)?\z/ - $1 - # Object identifier types - when /\A-?\d+\z/ - $1 - else - # Anything else is blank, some user type, or some function - # and we can't know the value of that, so return nil. - nil - end - end - - def extract_default_function(default_value, default) - default if has_default_function?(default_value, default) - end - - def has_default_function?(default_value, default) - !default_value && %r{\w+\(.*\)|\(.*\)::\w+|CURRENT_DATE|CURRENT_TIMESTAMP}.match?(default) - end - - def load_additional_types(type_map, oids = nil) - initializer = OID::TypeMapInitializer.new(type_map) - - if supports_ranges? - query = <<-SQL - SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype - FROM pg_type as t - LEFT JOIN pg_range as r ON oid = rngtypid - SQL - else - query = <<-SQL - SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, t.typtype, t.typbasetype - FROM pg_type as t - SQL - end - - if oids - query += "WHERE t.oid::integer IN (%s)" % oids.join(", ") - else - query += initializer.query_conditions_for_initial_load(type_map) - end - - execute_and_clear(query, "SCHEMA", []) do |records| - initializer.run(records) - end - end - - FEATURE_NOT_SUPPORTED = "0A000" #:nodoc: - - def execute_and_clear(sql, name, binds, prepare: false) - if without_prepared_statement?(binds) - result = exec_no_cache(sql, name, []) - elsif !prepare - result = exec_no_cache(sql, name, binds) - else - result = exec_cache(sql, name, binds) - end - ret = yield result - result.clear - ret - end - - def exec_no_cache(sql, name, binds) - type_casted_binds = type_casted_binds(binds) - log(sql, name, binds, type_casted_binds) do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - @connection.exec_params(sql, type_casted_binds) - end - end - end - - def exec_cache(sql, name, binds) - stmt_key = prepare_statement(sql) - type_casted_binds = type_casted_binds(binds) - - log(sql, name, binds, type_casted_binds, stmt_key) do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - @connection.exec_prepared(stmt_key, type_casted_binds) - end - end - rescue ActiveRecord::StatementInvalid => e - raise unless is_cached_plan_failure?(e) - - # Nothing we can do if we are in a transaction because all commands - # will raise InFailedSQLTransaction - if in_transaction? - raise ActiveRecord::PreparedStatementCacheExpired.new(e.cause.message) - else - @lock.synchronize do - # outside of transactions we can simply flush this query and retry - @statements.delete sql_key(sql) - end - retry - end - end - - # Annoyingly, the code for prepared statements whose return value may - # have changed is FEATURE_NOT_SUPPORTED. - # - # This covers various different error types so we need to do additional - # work to classify the exception definitively as a - # ActiveRecord::PreparedStatementCacheExpired - # - # Check here for more details: - # http://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/backend/utils/cache/plancache.c#l573 - CACHED_PLAN_HEURISTIC = "cached plan must not change result type".freeze - def is_cached_plan_failure?(e) - pgerror = e.cause - code = pgerror.result.result_error_field(PG::PG_DIAG_SQLSTATE) - code == FEATURE_NOT_SUPPORTED && pgerror.message.include?(CACHED_PLAN_HEURISTIC) - rescue - false - end - - def in_transaction? - open_transactions > 0 - end - - # Returns the statement identifier for the client side cache - # of statements - def sql_key(sql) - "#{schema_search_path}-#{sql}" - end - - # Prepare the statement if it hasn't been prepared, return - # the statement key. - def prepare_statement(sql) - @lock.synchronize do - sql_key = sql_key(sql) - unless @statements.key? sql_key - nextkey = @statements.next_key - begin - @connection.prepare nextkey, sql - rescue => e - raise translate_exception_class(e, sql) - end - # Clear the queue - @connection.get_last_result - @statements[sql_key] = nextkey - end - @statements[sql_key] - end - end - - # Connects to a PostgreSQL server and sets up the adapter depending on the - # connected server's characteristics. - def connect - @connection = PG.connect(@connection_parameters) - configure_connection - rescue ::PG::Error => error - if error.message.include?("does not exist") - raise ActiveRecord::NoDatabaseError - else - raise - end - end - - # Configures the encoding, verbosity, schema search path, and time zone of the connection. - # This is called by #connect and should not be called manually. - def configure_connection - if @config[:encoding] - @connection.set_client_encoding(@config[:encoding]) - end - self.client_min_messages = @config[:min_messages] || "warning" - self.schema_search_path = @config[:schema_search_path] || @config[:schema_order] - - # Use standard-conforming strings so we don't have to do the E'...' dance. - set_standard_conforming_strings - - # If using Active Record's time zone support configure the connection to return - # TIMESTAMP WITH ZONE types in UTC. - # (SET TIME ZONE does not use an equals sign like other SET variables) - if ActiveRecord::Base.default_timezone == :utc - execute("SET time zone 'UTC'", "SCHEMA") - elsif @local_tz - execute("SET time zone '#{@local_tz}'", "SCHEMA") - end - - # SET statements from :variables config hash - # http://www.postgresql.org/docs/current/static/sql-set.html - variables = @config[:variables] || {} - variables.map do |k, v| - if v == ":default" || v == :default - # Sets the value to the global or compile default - execute("SET SESSION #{k} TO DEFAULT", "SCHEMA") - elsif !v.nil? - execute("SET SESSION #{k} TO #{quote(v)}", "SCHEMA") - end - end - end - - # Returns the current ID of a table's sequence. - def last_insert_id_result(sequence_name) - exec_query("SELECT currval('#{sequence_name}')", "SQL") - end - - # Returns the list of a table's column names, data types, and default values. - # - # The underlying query is roughly: - # SELECT column.name, column.type, default.value, column.comment - # FROM column LEFT JOIN default - # ON column.table_id = default.table_id - # AND column.num = default.column_num - # WHERE column.table_id = get_table_id('table_name') - # AND column.num > 0 - # AND NOT column.is_dropped - # ORDER BY column.num - # - # If the table name is not prefixed with a schema, the database will - # take the first match from the schema search path. - # - # Query implementation notes: - # - format_type includes the column size constraint, e.g. varchar(50) - # - ::regclass is a function that gives the id for a table name - def column_definitions(table_name) - query(<<-end_sql, "SCHEMA") - SELECT a.attname, format_type(a.atttypid, a.atttypmod), - pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod, - c.collname, col_description(a.attrelid, a.attnum) AS comment - FROM pg_attribute a - LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum - LEFT JOIN pg_type t ON a.atttypid = t.oid - LEFT JOIN pg_collation c ON a.attcollation = c.oid AND a.attcollation <> t.typcollation - WHERE a.attrelid = #{quote(quote_table_name(table_name))}::regclass - AND a.attnum > 0 AND NOT a.attisdropped - ORDER BY a.attnum - end_sql - end - - def extract_table_ref_from_insert_sql(sql) - sql[/into\s("[A-Za-z0-9_."\[\]\s]+"|[A-Za-z0-9_."\[\]]+)\s*/im] - $1.strip if $1 - end - - def create_table_definition(*args) - PostgreSQL::TableDefinition.new(*args) - end - - def can_perform_case_insensitive_comparison_for?(column) - @case_insensitive_cache ||= {} - @case_insensitive_cache[column.sql_type] ||= begin - sql = <<-end_sql - SELECT exists( - SELECT * FROM pg_proc - WHERE proname = 'lower' - AND proargtypes = ARRAY[#{quote column.sql_type}::regtype]::oidvector - ) OR exists( - SELECT * FROM pg_proc - INNER JOIN pg_cast - ON ARRAY[casttarget]::oidvector = proargtypes - WHERE proname = 'lower' - AND castsource = #{quote column.sql_type}::regtype - ) - end_sql - execute_and_clear(sql, "SCHEMA", []) do |result| - result.getvalue(0, 0) - end - end - end - - def add_pg_encoders - map = PG::TypeMapByClass.new - map[Integer] = PG::TextEncoder::Integer.new - map[TrueClass] = PG::TextEncoder::Boolean.new - map[FalseClass] = PG::TextEncoder::Boolean.new - @connection.type_map_for_queries = map - end - - def add_pg_decoders - coders_by_name = { - "int2" => PG::TextDecoder::Integer, - "int4" => PG::TextDecoder::Integer, - "int8" => PG::TextDecoder::Integer, - "oid" => PG::TextDecoder::Integer, - "float4" => PG::TextDecoder::Float, - "float8" => PG::TextDecoder::Float, - "bool" => PG::TextDecoder::Boolean, - } - known_coder_types = coders_by_name.keys.map { |n| quote(n) } - query = <<-SQL % known_coder_types.join(", ") - SELECT t.oid, t.typname - FROM pg_type as t - WHERE t.typname IN (%s) - SQL - coders = execute_and_clear(query, "SCHEMA", []) do |result| - result - .map { |row| construct_coder(row, coders_by_name[row["typname"]]) } - .compact - end - - map = PG::TypeMapByOid.new - coders.each { |coder| map.add_coder(coder) } - @connection.type_map_for_results = map - end - - def construct_coder(row, coder_class) - return unless coder_class - coder_class.new(oid: row["oid"].to_i, name: row["typname"]) - end - - ActiveRecord::Type.add_modifier({ array: true }, OID::Array, adapter: :postgresql) - ActiveRecord::Type.add_modifier({ range: true }, OID::Range, adapter: :postgresql) - ActiveRecord::Type.register(:bit, OID::Bit, adapter: :postgresql) - ActiveRecord::Type.register(:bit_varying, OID::BitVarying, adapter: :postgresql) - ActiveRecord::Type.register(:binary, OID::Bytea, adapter: :postgresql) - ActiveRecord::Type.register(:cidr, OID::Cidr, adapter: :postgresql) - ActiveRecord::Type.register(:datetime, OID::DateTime, adapter: :postgresql) - ActiveRecord::Type.register(:decimal, OID::Decimal, adapter: :postgresql) - ActiveRecord::Type.register(:enum, OID::Enum, adapter: :postgresql) - ActiveRecord::Type.register(:hstore, OID::Hstore, adapter: :postgresql) - ActiveRecord::Type.register(:inet, OID::Inet, adapter: :postgresql) - ActiveRecord::Type.register(:json, OID::Json, adapter: :postgresql) - ActiveRecord::Type.register(:jsonb, OID::Jsonb, adapter: :postgresql) - ActiveRecord::Type.register(:money, OID::Money, adapter: :postgresql) - ActiveRecord::Type.register(:point, OID::Point, adapter: :postgresql) - ActiveRecord::Type.register(:legacy_point, OID::LegacyPoint, adapter: :postgresql) - ActiveRecord::Type.register(:uuid, OID::Uuid, adapter: :postgresql) - ActiveRecord::Type.register(:vector, OID::Vector, adapter: :postgresql) - ActiveRecord::Type.register(:xml, OID::Xml, adapter: :postgresql) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/schema_cache.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/schema_cache.rb deleted file mode 100644 index 4d339b0a8c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/schema_cache.rb +++ /dev/null @@ -1,116 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - class SchemaCache - attr_reader :version - attr_accessor :connection - - def initialize(conn) - @connection = conn - - @columns = {} - @columns_hash = {} - @primary_keys = {} - @data_sources = {} - end - - def initialize_dup(other) - super - @columns = @columns.dup - @columns_hash = @columns_hash.dup - @primary_keys = @primary_keys.dup - @data_sources = @data_sources.dup - end - - def encode_with(coder) - coder["columns"] = @columns - coder["columns_hash"] = @columns_hash - coder["primary_keys"] = @primary_keys - coder["data_sources"] = @data_sources - coder["version"] = ActiveRecord::Migrator.current_version - end - - def init_with(coder) - @columns = coder["columns"] - @columns_hash = coder["columns_hash"] - @primary_keys = coder["primary_keys"] - @data_sources = coder["data_sources"] - @version = coder["version"] - end - - def primary_keys(table_name) - @primary_keys[table_name] ||= data_source_exists?(table_name) ? connection.primary_key(table_name) : nil - end - - # A cached lookup for table existence. - def data_source_exists?(name) - prepare_data_sources if @data_sources.empty? - return @data_sources[name] if @data_sources.key? name - - @data_sources[name] = connection.data_source_exists?(name) - end - - # Add internal cache for table with +table_name+. - def add(table_name) - if data_source_exists?(table_name) - primary_keys(table_name) - columns(table_name) - columns_hash(table_name) - end - end - - def data_sources(name) - @data_sources[name] - end - - # Get the columns for a table - def columns(table_name) - @columns[table_name] ||= connection.columns(table_name) - end - - # Get the columns for a table as a hash, key is the column name - # value is the column object. - def columns_hash(table_name) - @columns_hash[table_name] ||= Hash[columns(table_name).map { |col| - [col.name, col] - }] - end - - # Clears out internal caches - def clear! - @columns.clear - @columns_hash.clear - @primary_keys.clear - @data_sources.clear - @version = nil - end - - def size - [@columns, @columns_hash, @primary_keys, @data_sources].map(&:size).inject :+ - end - - # Clear out internal caches for the data source +name+. - def clear_data_source_cache!(name) - @columns.delete name - @columns_hash.delete name - @primary_keys.delete name - @data_sources.delete name - end - - def marshal_dump - # if we get current version during initialization, it happens stack over flow. - @version = ActiveRecord::Migrator.current_version - [@version, @columns, @columns_hash, @primary_keys, @data_sources] - end - - def marshal_load(array) - @version, @columns, @columns_hash, @primary_keys, @data_sources = array - end - - private - - def prepare_data_sources - connection.data_sources.each { |source| @data_sources[source] = true } - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sql_type_metadata.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sql_type_metadata.rb deleted file mode 100644 index 9e12ae0de8..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sql_type_metadata.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveRecord - # :stopdoc: - module ConnectionAdapters - class SqlTypeMetadata - attr_reader :sql_type, :type, :limit, :precision, :scale - - def initialize(sql_type: nil, type: nil, limit: nil, precision: nil, scale: nil) - @sql_type = sql_type - @type = type - @limit = limit - @precision = precision - @scale = scale - end - - def ==(other) - other.is_a?(SqlTypeMetadata) && - attributes_for_hash == other.attributes_for_hash - end - alias eql? == - - def hash - attributes_for_hash.hash - end - - protected - - def attributes_for_hash - [self.class, sql_type, type, limit, precision, scale] - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb deleted file mode 100644 index 6fe3e1211e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/explain_pretty_printer.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module SQLite3 - class ExplainPrettyPrinter # :nodoc: - # Pretty prints the result of an EXPLAIN QUERY PLAN in a way that resembles - # the output of the SQLite shell: - # - # 0|0|0|SEARCH TABLE users USING INTEGER PRIMARY KEY (rowid=?) (~1 rows) - # 0|1|1|SCAN TABLE posts (~100000 rows) - # - def pp(result) - result.rows.map do |row| - row.join("|") - end.join("\n") + "\n" - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/quoting.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/quoting.rb deleted file mode 100644 index 019f8fd052..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/quoting.rb +++ /dev/null @@ -1,45 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module SQLite3 - module Quoting # :nodoc: - def quote_string(s) - @connection.class.quote(s) - end - - def quote_table_name_for_assignment(table, attr) - quote_column_name(attr) - end - - def quote_column_name(name) - @quoted_column_names[name] ||= %Q("#{super.gsub('"', '""')}").freeze - end - - def quoted_time(value) - value = value.change(year: 2000, month: 1, day: 1) - quoted_date(value).sub(/\A\d\d\d\d-\d\d-\d\d /, "2000-01-01 ") - end - - def quoted_binary(value) - "x'#{value.hex}'" - end - - private - - def _type_cast(value) - case value - when BigDecimal - value.to_f - when String - if value.encoding == Encoding::ASCII_8BIT - super(value.encode(Encoding::UTF_8)) - else - super - end - else - super - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_creation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_creation.rb deleted file mode 100644 index bc798d1dbb..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_creation.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module SQLite3 - class SchemaCreation < AbstractAdapter::SchemaCreation # :nodoc: - private - def add_column_options!(sql, options) - if options[:collation] - sql << " COLLATE \"#{options[:collation]}\"" - end - super - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb deleted file mode 100644 index e157e4b218..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_definitions.rb +++ /dev/null @@ -1,28 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module SQLite3 - module ColumnMethods - def primary_key(name, type = :primary_key, **options) - if %i(integer bigint).include?(type) && (options.delete(:auto_increment) == true || !options.key?(:default)) - type = :primary_key - end - - super - end - end - - class TableDefinition < ActiveRecord::ConnectionAdapters::TableDefinition - include ColumnMethods - - def references(*args, **options) - super(*args, type: :integer, **options) - end - alias :belongs_to :references - end - - class Table < ActiveRecord::ConnectionAdapters::Table - include ColumnMethods - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb deleted file mode 100644 index eec018eda3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_dumper.rb +++ /dev/null @@ -1,17 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module SQLite3 - module ColumnDumper # :nodoc: - private - - def default_primary_key?(column) - schema_type(column) == :integer - end - - def explicit_primary_key_default?(column) - column.bigint? - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_statements.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_statements.rb deleted file mode 100644 index 4ba245a0d8..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3/schema_statements.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - module SQLite3 - module SchemaStatements # :nodoc: - private - def data_source_sql(name = nil, type: nil) - scope = quoted_scope(name, type: type) - scope[:type] ||= "'table','view'" - - sql = "SELECT name FROM sqlite_master WHERE name <> 'sqlite_sequence'" - sql << " AND name = #{scope[:name]}" if scope[:name] - sql << " AND type IN (#{scope[:type]})" - sql - end - - def quoted_scope(name = nil, type: nil) - type = \ - case type - when "BASE TABLE" - "'table'" - when "VIEW" - "'view'" - end - scope = {} - scope[:name] = quote(name) if name - scope[:type] = type if type - scope - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3_adapter.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3_adapter.rb deleted file mode 100644 index 7e11150e23..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ /dev/null @@ -1,586 +0,0 @@ -require "active_record/connection_adapters/abstract_adapter" -require "active_record/connection_adapters/statement_pool" -require "active_record/connection_adapters/sqlite3/explain_pretty_printer" -require "active_record/connection_adapters/sqlite3/quoting" -require "active_record/connection_adapters/sqlite3/schema_creation" -require "active_record/connection_adapters/sqlite3/schema_definitions" -require "active_record/connection_adapters/sqlite3/schema_dumper" -require "active_record/connection_adapters/sqlite3/schema_statements" - -gem "sqlite3", "~> 1.3", ">= 1.3.6" -require "sqlite3" - -module ActiveRecord - module ConnectionHandling # :nodoc: - def sqlite3_connection(config) - # Require database. - unless config[:database] - raise ArgumentError, "No database file specified. Missing argument: database" - end - - # Allow database path relative to Rails.root, but only if the database - # path is not the special path that tells sqlite to build a database only - # in memory. - if ":memory:" != config[:database] - config[:database] = File.expand_path(config[:database], Rails.root) if defined?(Rails.root) - dirname = File.dirname(config[:database]) - Dir.mkdir(dirname) unless File.directory?(dirname) - end - - db = SQLite3::Database.new( - config[:database].to_s, - results_as_hash: true - ) - - db.busy_timeout(ConnectionAdapters::SQLite3Adapter.type_cast_config_to_integer(config[:timeout])) if config[:timeout] - - ConnectionAdapters::SQLite3Adapter.new(db, logger, nil, config) - rescue Errno::ENOENT => error - if error.message.include?("No such file or directory") - raise ActiveRecord::NoDatabaseError - else - raise - end - end - end - - module ConnectionAdapters #:nodoc: - # The SQLite3 adapter works SQLite 3.6.16 or newer - # with the sqlite3-ruby drivers (available as gem from https://rubygems.org/gems/sqlite3). - # - # Options: - # - # * :database - Path to the database file. - class SQLite3Adapter < AbstractAdapter - ADAPTER_NAME = "SQLite".freeze - - include SQLite3::Quoting - include SQLite3::ColumnDumper - include SQLite3::SchemaStatements - - NATIVE_DATABASE_TYPES = { - primary_key: "INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL", - string: { name: "varchar" }, - text: { name: "text" }, - integer: { name: "integer" }, - float: { name: "float" }, - decimal: { name: "decimal" }, - datetime: { name: "datetime" }, - time: { name: "time" }, - date: { name: "date" }, - binary: { name: "blob" }, - boolean: { name: "boolean" } - } - - class StatementPool < ConnectionAdapters::StatementPool - private - - def dealloc(stmt) - stmt[:stmt].close unless stmt[:stmt].closed? - end - end - - def update_table_definition(table_name, base) # :nodoc: - SQLite3::Table.new(table_name, base) - end - - def schema_creation # :nodoc: - SQLite3::SchemaCreation.new self - end - - def arel_visitor # :nodoc: - Arel::Visitors::SQLite.new(self) - end - - def initialize(connection, logger, connection_options, config) - super(connection, logger, config) - - @active = nil - @statements = StatementPool.new(self.class.type_cast_config_to_integer(config[:statement_limit])) - - configure_connection - end - - def supports_ddl_transactions? - true - end - - def supports_savepoints? - true - end - - def supports_partial_index? - sqlite_version >= "3.8.0" - end - - # Returns true, since this connection adapter supports prepared statement - # caching. - def supports_statement_cache? - true - end - - def requires_reloading? - true - end - - def supports_foreign_keys_in_create? - sqlite_version >= "3.6.19" - end - - def supports_views? - true - end - - def supports_datetime_with_precision? - true - end - - def supports_multi_insert? - sqlite_version >= "3.7.11" - end - - def active? - @active != false - end - - # Disconnects from the database if already connected. Otherwise, this - # method does nothing. - def disconnect! - super - @active = false - @connection.close rescue nil - end - - # Clears the prepared statements cache. - def clear_cache! - @statements.clear - end - - def supports_index_sort_order? - true - end - - # Returns 62. SQLite supports index names up to 64 - # characters. The rest is used by Rails internally to perform - # temporary rename operations - def allowed_index_name_length - index_name_length - 2 - end - - def native_database_types #:nodoc: - NATIVE_DATABASE_TYPES - end - - # Returns the current database encoding format as a string, eg: 'UTF-8' - def encoding - @connection.encoding.to_s - end - - def supports_explain? - true - end - - # REFERENTIAL INTEGRITY ==================================== - - def disable_referential_integrity # :nodoc: - old = query_value("PRAGMA foreign_keys") - - begin - execute("PRAGMA foreign_keys = OFF") - yield - ensure - execute("PRAGMA foreign_keys = #{old}") - end - end - - #-- - # DATABASE STATEMENTS ====================================== - #++ - - def explain(arel, binds = []) - sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}" - SQLite3::ExplainPrettyPrinter.new.pp(exec_query(sql, "EXPLAIN", [])) - end - - def exec_query(sql, name = nil, binds = [], prepare: false) - type_casted_binds = type_casted_binds(binds) - - log(sql, name, binds, type_casted_binds) do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - # Don't cache statements if they are not prepared - unless prepare - stmt = @connection.prepare(sql) - begin - cols = stmt.columns - unless without_prepared_statement?(binds) - stmt.bind_params(type_casted_binds) - end - records = stmt.to_a - ensure - stmt.close - end - else - cache = @statements[sql] ||= { - stmt: @connection.prepare(sql) - } - stmt = cache[:stmt] - cols = cache[:cols] ||= stmt.columns - stmt.reset! - stmt.bind_params(type_casted_binds) - records = stmt.to_a - end - - ActiveRecord::Result.new(cols, records) - end - end - end - - def exec_delete(sql, name = "SQL", binds = []) - exec_query(sql, name, binds) - @connection.changes - end - alias :exec_update :exec_delete - - def last_inserted_id(result) - @connection.last_insert_row_id - end - - def execute(sql, name = nil) #:nodoc: - log(sql, name) do - ActiveSupport::Dependencies.interlock.permit_concurrent_loads do - @connection.execute(sql) - end - end - end - - def begin_db_transaction #:nodoc: - log("begin transaction", nil) { @connection.transaction } - end - - def commit_db_transaction #:nodoc: - log("commit transaction", nil) { @connection.commit } - end - - def exec_rollback_db_transaction #:nodoc: - log("rollback transaction", nil) { @connection.rollback } - end - - # SCHEMA STATEMENTS ======================================== - - def new_column_from_field(table_name, field) # :nondoc: - case field["dflt_value"] - when /^null$/i - field["dflt_value"] = nil - when /^'(.*)'$/m - field["dflt_value"] = $1.gsub("''", "'") - when /^"(.*)"$/m - field["dflt_value"] = $1.gsub('""', '"') - end - - collation = field["collation"] - sql_type = field["type"] - type_metadata = fetch_type_metadata(sql_type) - new_column(field["name"], field["dflt_value"], type_metadata, field["notnull"].to_i == 0, table_name, nil, collation) - end - - # Returns an array of indexes for the given table. - def indexes(table_name, name = nil) #:nodoc: - if name - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing name to #indexes is deprecated without replacement. - MSG - end - - exec_query("PRAGMA index_list(#{quote_table_name(table_name)})", "SCHEMA").map do |row| - sql = <<-SQL - SELECT sql - FROM sqlite_master - WHERE name=#{quote(row['name'])} AND type='index' - UNION ALL - SELECT sql - FROM sqlite_temp_master - WHERE name=#{quote(row['name'])} AND type='index' - SQL - index_sql = exec_query(sql).first["sql"] - match = /\sWHERE\s+(.+)$/i.match(index_sql) - where = match[1] if match - IndexDefinition.new( - table_name, - row["name"], - row["unique"] != 0, - exec_query("PRAGMA index_info('#{row['name']}')", "SCHEMA").map { |col| - col["name"] - }, nil, nil, where) - end - end - - def primary_keys(table_name) # :nodoc: - pks = table_structure(table_name).select { |f| f["pk"] > 0 } - pks.sort_by { |f| f["pk"] }.map { |f| f["name"] } - end - - def remove_index(table_name, options = {}) #:nodoc: - index_name = index_name_for_remove(table_name, options) - exec_query "DROP INDEX #{quote_column_name(index_name)}" - end - - # Renames a table. - # - # Example: - # rename_table('octopuses', 'octopi') - def rename_table(table_name, new_name) - exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}" - rename_table_indexes(table_name, new_name) - end - - # See: http://www.sqlite.org/lang_altertable.html - # SQLite has an additional restriction on the ALTER TABLE statement - def valid_alter_table_type?(type) - type.to_sym != :primary_key - end - - def add_column(table_name, column_name, type, options = {}) #:nodoc: - if valid_alter_table_type?(type) && !options[:primary_key] - super(table_name, column_name, type, options) - else - alter_table(table_name) do |definition| - definition.column(column_name, type, options) - end - end - end - - def remove_column(table_name, column_name, type = nil, options = {}) #:nodoc: - alter_table(table_name) do |definition| - definition.remove_column column_name - end - end - - def change_column_default(table_name, column_name, default_or_changes) #:nodoc: - default = extract_new_default_value(default_or_changes) - - alter_table(table_name) do |definition| - definition[column_name].default = default - end - end - - def change_column_null(table_name, column_name, null, default = nil) #:nodoc: - unless null || default.nil? - exec_query("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL") - end - alter_table(table_name) do |definition| - definition[column_name].null = null - end - end - - def change_column(table_name, column_name, type, options = {}) #:nodoc: - alter_table(table_name) do |definition| - definition[column_name].instance_eval do - self.type = type - self.limit = options[:limit] if options.include?(:limit) - self.default = options[:default] if options.include?(:default) - self.null = options[:null] if options.include?(:null) - self.precision = options[:precision] if options.include?(:precision) - self.scale = options[:scale] if options.include?(:scale) - self.collation = options[:collation] if options.include?(:collation) - end - end - end - - def rename_column(table_name, column_name, new_column_name) #:nodoc: - column = column_for(table_name, column_name) - alter_table(table_name, rename: { column.name => new_column_name.to_s }) - rename_column_indexes(table_name, column.name, new_column_name) - end - - def add_reference(table_name, ref_name, **options) # :nodoc: - super(table_name, ref_name, type: :integer, **options) - end - alias :add_belongs_to :add_reference - - def foreign_keys(table_name) - fk_info = exec_query("PRAGMA foreign_key_list(#{quote(table_name)})", "SCHEMA") - fk_info.map do |row| - options = { - column: row["from"], - primary_key: row["to"], - on_delete: extract_foreign_key_action(row["on_delete"]), - on_update: extract_foreign_key_action(row["on_update"]) - } - ForeignKeyDefinition.new(table_name, row["table"], options) - end - end - - private - - def table_structure(table_name) - structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", "SCHEMA") - raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty? - table_structure_with_collation(table_name, structure) - end - alias column_definitions table_structure - - def alter_table(table_name, options = {}) - altered_table_name = "a#{table_name}" - caller = lambda { |definition| yield definition if block_given? } - - transaction do - move_table(table_name, altered_table_name, - options.merge(temporary: true)) - move_table(altered_table_name, table_name, &caller) - end - end - - def move_table(from, to, options = {}, &block) - copy_table(from, to, options, &block) - drop_table(from) - end - - def copy_table(from, to, options = {}) - from_primary_key = primary_key(from) - options[:id] = false - create_table(to, options) do |definition| - @definition = definition - if from_primary_key.is_a?(Array) - @definition.primary_keys from_primary_key - end - columns(from).each do |column| - column_name = options[:rename] ? - (options[:rename][column.name] || - options[:rename][column.name.to_sym] || - column.name) : column.name - - @definition.column(column_name, column.type, - limit: column.limit, default: column.default, - precision: column.precision, scale: column.scale, - null: column.null, collation: column.collation, - primary_key: column_name == from_primary_key - ) - end - yield @definition if block_given? - end - copy_table_indexes(from, to, options[:rename] || {}) - copy_table_contents(from, to, - @definition.columns.map(&:name), - options[:rename] || {}) - end - - def copy_table_indexes(from, to, rename = {}) - indexes(from).each do |index| - name = index.name - # indexes sqlite creates for internal use start with `sqlite_` and - # don't need to be copied - next if name.starts_with?("sqlite_") - if to == "a#{from}" - name = "t#{name}" - elsif from == "a#{to}" - name = name[1..-1] - end - - to_column_names = columns(to).map(&:name) - columns = index.columns.map { |c| rename[c] || c }.select do |column| - to_column_names.include?(column) - end - - unless columns.empty? - # index name can't be the same - opts = { name: name.gsub(/(^|_)(#{from})_/, "\\1#{to}_"), internal: true } - opts[:unique] = true if index.unique - opts[:where] = index.where if index.where - add_index(to, columns, opts) - end - end - end - - def copy_table_contents(from, to, columns, rename = {}) - column_mappings = Hash[columns.map { |name| [name, name] }] - rename.each { |a| column_mappings[a.last] = a.first } - from_columns = columns(from).collect(&:name) - columns = columns.find_all { |col| from_columns.include?(column_mappings[col]) } - from_columns_to_copy = columns.map { |col| column_mappings[col] } - quoted_columns = columns.map { |col| quote_column_name(col) } * "," - quoted_from_columns = from_columns_to_copy.map { |col| quote_column_name(col) } * "," - - exec_query("INSERT INTO #{quote_table_name(to)} (#{quoted_columns}) - SELECT #{quoted_from_columns} FROM #{quote_table_name(from)}") - end - - def sqlite_version - @sqlite_version ||= SQLite3Adapter::Version.new(query_value("SELECT sqlite_version(*)")) - end - - def translate_exception(exception, message) - case exception.message - # SQLite 3.8.2 returns a newly formatted error message: - # UNIQUE constraint failed: *table_name*.*column_name* - # Older versions of SQLite return: - # column *column_name* is not unique - when /column(s)? .* (is|are) not unique/, /UNIQUE constraint failed: .*/ - RecordNotUnique.new(message) - when /.* may not be NULL/, /NOT NULL constraint failed: .*/ - NotNullViolation.new(message) - when /FOREIGN KEY constraint failed/i - InvalidForeignKey.new(message) - else - super - end - end - - COLLATE_REGEX = /.*\"(\w+)\".*collate\s+\"(\w+)\".*/i.freeze - - def table_structure_with_collation(table_name, basic_structure) - collation_hash = {} - sql = <<-SQL - SELECT sql FROM - (SELECT * FROM sqlite_master UNION ALL - SELECT * FROM sqlite_temp_master) - WHERE type = 'table' AND name = #{quote(table_name)} - SQL - - # Result will have following sample string - # CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, - # "password_digest" varchar COLLATE "NOCASE"); - result = exec_query(sql, "SCHEMA").first - - if result - # Splitting with left parentheses and picking up last will return all - # columns separated with comma(,). - columns_string = result["sql"].split("(").last - - columns_string.split(",").each do |column_string| - # This regex will match the column name and collation type and will save - # the value in $1 and $2 respectively. - collation_hash[$1] = $2 if COLLATE_REGEX =~ column_string - end - - basic_structure.map! do |column| - column_name = column["name"] - - if collation_hash.has_key? column_name - column["collation"] = collation_hash[column_name] - end - - column - end - else - basic_structure.to_hash - end - end - - def create_table_definition(*args) - SQLite3::TableDefinition.new(*args) - end - - def extract_foreign_key_action(specifier) - case specifier - when "CASCADE"; :cascade - when "SET NULL"; :nullify - when "RESTRICT"; :restrict - end - end - - def configure_connection - execute("PRAGMA foreign_keys = ON", "SCHEMA") - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/statement_pool.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/statement_pool.rb deleted file mode 100644 index 790db56185..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_adapters/statement_pool.rb +++ /dev/null @@ -1,59 +0,0 @@ -module ActiveRecord - module ConnectionAdapters - class StatementPool # :nodoc: - include Enumerable - - DEFAULT_STATEMENT_LIMIT = 1000 - - def initialize(statement_limit = nil) - @cache = Hash.new { |h, pid| h[pid] = {} } - @statement_limit = statement_limit || DEFAULT_STATEMENT_LIMIT - end - - def each(&block) - cache.each(&block) - end - - def key?(key) - cache.key?(key) - end - - def [](key) - cache[key] - end - - def length - cache.length - end - - def []=(sql, stmt) - while @statement_limit <= cache.size - dealloc(cache.shift.last) - end - cache[sql] = stmt - end - - def clear - cache.each_value do |stmt| - dealloc stmt - end - cache.clear - end - - def delete(key) - dealloc cache[key] - cache.delete(key) - end - - private - - def cache - @cache[Process.pid] - end - - def dealloc(stmt) - raise NotImplementedError - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_handling.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_handling.rb deleted file mode 100644 index 2ede92feff..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/connection_handling.rb +++ /dev/null @@ -1,143 +0,0 @@ -module ActiveRecord - module ConnectionHandling - RAILS_ENV = -> { (Rails.env if defined?(Rails.env)) || ENV["RAILS_ENV"] || ENV["RACK_ENV"] } - DEFAULT_ENV = -> { RAILS_ENV.call || "default_env" } - - # Establishes the connection to the database. Accepts a hash as input where - # the :adapter key must be specified with the name of a database adapter (in lower-case) - # example for regular databases (MySQL, PostgreSQL, etc): - # - # ActiveRecord::Base.establish_connection( - # adapter: "mysql2", - # host: "localhost", - # username: "myuser", - # password: "mypass", - # database: "somedatabase" - # ) - # - # Example for SQLite database: - # - # ActiveRecord::Base.establish_connection( - # adapter: "sqlite3", - # database: "path/to/dbfile" - # ) - # - # Also accepts keys as strings (for parsing from YAML for example): - # - # ActiveRecord::Base.establish_connection( - # "adapter" => "sqlite3", - # "database" => "path/to/dbfile" - # ) - # - # Or a URL: - # - # ActiveRecord::Base.establish_connection( - # "postgres://myuser:mypass@localhost/somedatabase" - # ) - # - # In case {ActiveRecord::Base.configurations}[rdoc-ref:Core.configurations] - # is set (Rails automatically loads the contents of config/database.yml into it), - # a symbol can also be given as argument, representing a key in the - # configuration hash: - # - # ActiveRecord::Base.establish_connection(:production) - # - # The exceptions AdapterNotSpecified, AdapterNotFound and +ArgumentError+ - # may be returned on an error. - def establish_connection(config = nil) - raise "Anonymous class is not allowed." unless name - - config ||= DEFAULT_ENV.call.to_sym - spec_name = self == Base ? "primary" : name - self.connection_specification_name = spec_name - - resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new(Base.configurations) - spec = resolver.resolve(config).symbolize_keys - spec[:name] = spec_name - - connection_handler.establish_connection(spec) - end - - class MergeAndResolveDefaultUrlConfig # :nodoc: - def initialize(raw_configurations) - @raw_config = raw_configurations.dup - @env = DEFAULT_ENV.call.to_s - end - - # Returns fully resolved connection hashes. - # Merges connection information from `ENV['DATABASE_URL']` if available. - def resolve - ConnectionAdapters::ConnectionSpecification::Resolver.new(config).resolve_all - end - - private - def config - @raw_config.dup.tap do |cfg| - if url = ENV["DATABASE_URL"] - cfg[@env] ||= {} - cfg[@env]["url"] ||= url - end - end - end - end - - # Returns the connection currently associated with the class. This can - # also be used to "borrow" the connection to do database work unrelated - # to any of the specific Active Records. - def connection - retrieve_connection - end - - attr_writer :connection_specification_name - - # Return the specification name from the current class or its parent. - def connection_specification_name - if !defined?(@connection_specification_name) || @connection_specification_name.nil? - return self == Base ? "primary" : superclass.connection_specification_name - end - @connection_specification_name - end - - # Returns the configuration of the associated connection as a hash: - # - # ActiveRecord::Base.connection_config - # # => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"} - # - # Please use only for reading. - def connection_config - connection_pool.spec.config - end - - def connection_pool - connection_handler.retrieve_connection_pool(connection_specification_name) || raise(ConnectionNotEstablished) - end - - def retrieve_connection - connection_handler.retrieve_connection(connection_specification_name) - end - - # Returns +true+ if Active Record is connected. - def connected? - connection_handler.connected?(connection_specification_name) - end - - def remove_connection(name = nil) - name ||= @connection_specification_name if defined?(@connection_specification_name) - # if removing a connection that has a pool, we reset the - # connection_specification_name so it will use the parent - # pool. - if connection_handler.retrieve_connection_pool(name) - self.connection_specification_name = nil - end - - connection_handler.remove_connection(name) - end - - def clear_cache! # :nodoc: - connection.schema_cache.clear! - end - - delegate :clear_active_connections!, :clear_reloadable_connections!, - :clear_all_connections!, to: :connection_handler - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/core.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/core.rb deleted file mode 100644 index 8f78330d4a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/core.rb +++ /dev/null @@ -1,579 +0,0 @@ -require "thread" -require "active_support/core_ext/hash/indifferent_access" -require "active_support/core_ext/object/duplicable" -require "active_support/core_ext/string/filters" - -module ActiveRecord - module Core - extend ActiveSupport::Concern - - included do - ## - # :singleton-method: - # - # Accepts a logger conforming to the interface of Log4r which is then - # passed on to any new database connections made and which can be - # retrieved on both a class and instance level by calling +logger+. - mattr_accessor :logger, instance_writer: false - - ## - # Contains the database configuration - as is typically stored in config/database.yml - - # as a Hash. - # - # For example, the following database.yml... - # - # development: - # adapter: sqlite3 - # database: db/development.sqlite3 - # - # production: - # adapter: sqlite3 - # database: db/production.sqlite3 - # - # ...would result in ActiveRecord::Base.configurations to look like this: - # - # { - # 'development' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/development.sqlite3' - # }, - # 'production' => { - # 'adapter' => 'sqlite3', - # 'database' => 'db/production.sqlite3' - # } - # } - def self.configurations=(config) - @@configurations = ActiveRecord::ConnectionHandling::MergeAndResolveDefaultUrlConfig.new(config).resolve - end - self.configurations = {} - - # Returns fully resolved configurations hash - def self.configurations - @@configurations - end - - ## - # :singleton-method: - # Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling - # dates and times from the database. This is set to :utc by default. - mattr_accessor :default_timezone, instance_writer: false - self.default_timezone = :utc - - ## - # :singleton-method: - # Specifies the format to use when dumping the database schema with Rails' - # Rakefile. If :sql, the schema is dumped as (potentially database- - # specific) SQL statements. If :ruby, the schema is dumped as an - # ActiveRecord::Schema file which can be loaded into any database that - # supports migrations. Use :ruby if you want to have different database - # adapters for, e.g., your development and test environments. - mattr_accessor :schema_format, instance_writer: false - self.schema_format = :ruby - - ## - # :singleton-method: - # Specifies if an error should be raised if the query has an order being - # ignored when doing batch queries. Useful in applications where the - # scope being ignored is error-worthy, rather than a warning. - mattr_accessor :error_on_ignored_order, instance_writer: false - self.error_on_ignored_order = false - - def self.error_on_ignored_order_or_limit - ActiveSupport::Deprecation.warn(<<-MSG.squish) - The flag error_on_ignored_order_or_limit is deprecated. Limits are - now supported. Please use error_on_ignored_order instead. - MSG - error_on_ignored_order - end - - def error_on_ignored_order_or_limit - self.class.error_on_ignored_order_or_limit - end - - def self.error_on_ignored_order_or_limit=(value) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - The flag error_on_ignored_order_or_limit is deprecated. Limits are - now supported. Please use error_on_ignored_order= instead. - MSG - self.error_on_ignored_order = value - end - - ## - # :singleton-method: - # Specify whether or not to use timestamps for migration versions - mattr_accessor :timestamped_migrations, instance_writer: false - self.timestamped_migrations = true - - ## - # :singleton-method: - # Specify whether schema dump should happen at the end of the - # db:migrate rake task. This is true by default, which is useful for the - # development environment. This should ideally be false in the production - # environment where dumping schema is rarely needed. - mattr_accessor :dump_schema_after_migration, instance_writer: false - self.dump_schema_after_migration = true - - ## - # :singleton-method: - # Specifies which database schemas to dump when calling db:structure:dump. - # If the value is :schema_search_path (the default), any schemas listed in - # schema_search_path are dumped. Use :all to dump all schemas regardless - # of schema_search_path, or a string of comma separated schemas for a - # custom list. - mattr_accessor :dump_schemas, instance_writer: false - self.dump_schemas = :schema_search_path - - ## - # :singleton-method: - # Specify a threshold for the size of query result sets. If the number of - # records in the set exceeds the threshold, a warning is logged. This can - # be used to identify queries which load thousands of records and - # potentially cause memory bloat. - mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false - self.warn_on_records_fetched_greater_than = nil - - mattr_accessor :maintain_test_schema, instance_accessor: false - - mattr_accessor :belongs_to_required_by_default, instance_accessor: false - - class_attribute :default_connection_handler, instance_writer: false - - def self.connection_handler - ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler - end - - def self.connection_handler=(handler) - ActiveRecord::RuntimeRegistry.connection_handler = handler - end - - self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new - end - - module ClassMethods - def allocate - define_attribute_methods - super - end - - def initialize_find_by_cache # :nodoc: - @find_by_statement_cache = { true => {}.extend(Mutex_m), false => {}.extend(Mutex_m) } - end - - def inherited(child_class) # :nodoc: - # initialize cache at class definition for thread safety - child_class.initialize_find_by_cache - super - end - - def find(*ids) # :nodoc: - # We don't have cache keys for this stuff yet - return super unless ids.length == 1 - return super if block_given? || - primary_key.nil? || - scope_attributes? || - columns_hash.include?(inheritance_column) - - id = ids.first - - return super if id.kind_of?(Array) || - id.is_a?(ActiveRecord::Base) - - key = primary_key - - statement = cached_find_by_statement(key) { |params| - where(key => params.bind).limit(1) - } - - record = statement.execute([id], self, connection).first - unless record - raise RecordNotFound.new("Couldn't find #{name} with '#{primary_key}'=#{id}", - name, primary_key, id) - end - record - rescue ::RangeError - raise RecordNotFound.new("Couldn't find #{name} with an out of range value for '#{primary_key}'", - name, primary_key) - end - - def find_by(*args) # :nodoc: - return super if scope_attributes? || reflect_on_all_aggregations.any? - - hash = args.first - - return super if !(Hash === hash) || hash.values.any? { |v| - v.nil? || Array === v || Hash === v || Relation === v || Base === v - } - - # We can't cache Post.find_by(author: david) ...yet - return super unless hash.keys.all? { |k| columns_hash.has_key?(k.to_s) } - - keys = hash.keys - - statement = cached_find_by_statement(keys) { |params| - wheres = keys.each_with_object({}) { |param, o| - o[param] = params.bind - } - where(wheres).limit(1) - } - begin - statement.execute(hash.values, self, connection).first - rescue TypeError - raise ActiveRecord::StatementInvalid - rescue ::RangeError - nil - end - end - - def find_by!(*args) # :nodoc: - find_by(*args) || raise(RecordNotFound.new("Couldn't find #{name}", name)) - end - - def initialize_generated_modules # :nodoc: - generated_association_methods - end - - def generated_association_methods - @generated_association_methods ||= begin - mod = const_set(:GeneratedAssociationMethods, Module.new) - private_constant :GeneratedAssociationMethods - include mod - - mod - end - end - - # Returns a string like 'Post(id:integer, title:string, body:text)' - def inspect - if self == Base - super - elsif abstract_class? - "#{super}(abstract)" - elsif !connected? - "#{super} (call '#{super}.connection' to establish a connection)" - elsif table_exists? - attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ", " - "#{super}(#{attr_list})" - else - "#{super}(Table doesn't exist)" - end - end - - # Overwrite the default class equality method to provide support for association proxies. - def ===(object) - object.is_a?(self) - end - - # Returns an instance of Arel::Table loaded with the current table name. - # - # class Post < ActiveRecord::Base - # scope :published_and_commented, -> { published.and(arel_table[:comments_count].gt(0)) } - # end - def arel_table # :nodoc: - @arel_table ||= Arel::Table.new(table_name, type_caster: type_caster) - end - - # Returns the Arel engine. - def arel_engine # :nodoc: - @arel_engine ||= - if Base == self || connection_handler.retrieve_connection_pool(connection_specification_name) - self - else - superclass.arel_engine - end - end - - def arel_attribute(name, table = arel_table) # :nodoc: - name = attribute_alias(name) if attribute_alias?(name) - table[name] - end - - def predicate_builder # :nodoc: - @predicate_builder ||= PredicateBuilder.new(table_metadata) - end - - def type_caster # :nodoc: - TypeCaster::Map.new(self) - end - - private - - def cached_find_by_statement(key, &block) - cache = @find_by_statement_cache[connection.prepared_statements] - cache[key] || cache.synchronize { - cache[key] ||= StatementCache.create(connection, &block) - } - end - - def relation - relation = Relation.create(self, arel_table, predicate_builder) - - if finder_needs_type_condition? && !ignore_default_scope? - relation.where(type_condition).create_with(inheritance_column.to_s => sti_name) - else - relation - end - end - - def table_metadata - TableMetadata.new(self, arel_table) - end - end - - # New objects can be instantiated as either empty (pass no construction parameter) or pre-set with - # attributes but not yet saved (pass a hash with key names matching the associated table column names). - # In both instances, valid attribute keys are determined by the column names of the associated table -- - # hence you can't have attributes that aren't part of the table columns. - # - # ==== Example: - # # Instantiates a single new object - # User.new(first_name: 'Jamie') - def initialize(attributes = nil) - self.class.define_attribute_methods - @attributes = self.class._default_attributes.deep_dup - - init_internals - initialize_internals_callback - - assign_attributes(attributes) if attributes - - yield self if block_given? - _run_initialize_callbacks - end - - # Initialize an empty model object from +coder+. +coder+ should be - # the result of previously encoding an Active Record model, using - # #encode_with. - # - # class Post < ActiveRecord::Base - # end - # - # old_post = Post.new(title: "hello world") - # coder = {} - # old_post.encode_with(coder) - # - # post = Post.allocate - # post.init_with(coder) - # post.title # => 'hello world' - def init_with(coder) - coder = LegacyYamlAdapter.convert(self.class, coder) - @attributes = self.class.yaml_encoder.decode(coder) - - init_internals - - @new_record = coder["new_record"] - - self.class.define_attribute_methods - - yield self if block_given? - - _run_find_callbacks - _run_initialize_callbacks - - self - end - - ## - # :method: clone - # Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied. - # That means that modifying attributes of the clone will modify the original, since they will both point to the - # same attributes hash. If you need a copy of your attributes hash, please use the #dup method. - # - # user = User.first - # new_user = user.clone - # user.name # => "Bob" - # new_user.name = "Joe" - # user.name # => "Joe" - # - # user.object_id == new_user.object_id # => false - # user.name.object_id == new_user.name.object_id # => true - # - # user.name.object_id == user.dup.name.object_id # => false - - ## - # :method: dup - # Duped objects have no id assigned and are treated as new records. Note - # that this is a "shallow" copy as it copies the object's attributes - # only, not its associations. The extent of a "deep" copy is application - # specific and is therefore left to the application to implement according - # to its need. - # The dup method does not preserve the timestamps (created|updated)_(at|on). - - ## - def initialize_dup(other) # :nodoc: - @attributes = @attributes.deep_dup - @attributes.reset(self.class.primary_key) - - _run_initialize_callbacks - - @new_record = true - @destroyed = false - - super - end - - # Populate +coder+ with attributes about this record that should be - # serialized. The structure of +coder+ defined in this method is - # guaranteed to match the structure of +coder+ passed to the #init_with - # method. - # - # Example: - # - # class Post < ActiveRecord::Base - # end - # coder = {} - # Post.new.encode_with(coder) - # coder # => {"attributes" => {"id" => nil, ... }} - def encode_with(coder) - self.class.yaml_encoder.encode(@attributes, coder) - coder["new_record"] = new_record? - coder["active_record_yaml_version"] = 2 - end - - # Returns true if +comparison_object+ is the same exact object, or +comparison_object+ - # is of the same type and +self+ has an ID and it is equal to +comparison_object.id+. - # - # Note that new records are different from any other record by definition, unless the - # other record is the receiver itself. Besides, if you fetch existing records with - # +select+ and leave the ID out, you're on your own, this predicate will return false. - # - # Note also that destroying a record preserves its ID in the model instance, so deleted - # models are still comparable. - def ==(comparison_object) - super || - comparison_object.instance_of?(self.class) && - !id.nil? && - comparison_object.id == id - end - alias :eql? :== - - # Delegates to id in order to allow two records of the same type and id to work with something like: - # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] - def hash - if id - self.class.hash ^ id.hash - else - super - end - end - - # Clone and freeze the attributes hash such that associations are still - # accessible, even on destroyed records, but cloned models will not be - # frozen. - def freeze - @attributes = @attributes.clone.freeze - self - end - - # Returns +true+ if the attributes hash has been frozen. - def frozen? - @attributes.frozen? - end - - # Allows sort on objects - def <=>(other_object) - if other_object.is_a?(self.class) - to_key <=> other_object.to_key - else - super - end - end - - # Returns +true+ if the record is read only. Records loaded through joins with piggy-back - # attributes will be marked as read only since they cannot be saved. - def readonly? - @readonly - end - - # Marks this record as read only. - def readonly! - @readonly = true - end - - def connection_handler - self.class.connection_handler - end - - # Returns the contents of the record as a nicely formatted string. - def inspect - # We check defined?(@attributes) not to issue warnings if the object is - # allocated but not initialized. - inspection = if defined?(@attributes) && @attributes - self.class.attribute_names.collect do |name| - if has_attribute?(name) - "#{name}: #{attribute_for_inspect(name)}" - end - end.compact.join(", ") - else - "not initialized" - end - - "#<#{self.class} #{inspection}>" - end - - # Takes a PP and prettily prints this record to it, allowing you to get a nice result from pp record - # when pp is required. - def pretty_print(pp) - return super if custom_inspect_method_defined? - pp.object_address_group(self) do - if defined?(@attributes) && @attributes - column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? } - pp.seplist(column_names, proc { pp.text "," }) do |column_name| - column_value = read_attribute(column_name) - pp.breakable " " - pp.group(1) do - pp.text column_name - pp.text ":" - pp.breakable - pp.pp column_value - end - end - else - pp.breakable " " - pp.text "not initialized" - end - end - end - - # Returns a hash of the given methods with their names as keys and returned values as values. - def slice(*methods) - Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access - end - - private - - # +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of - # the array, and then rescues from the possible +NoMethodError+. If those elements are - # +ActiveRecord::Base+'s, then this triggers the various +method_missing+'s that we have, - # which significantly impacts upon performance. - # - # So we can avoid the +method_missing+ hit by explicitly defining +#to_ary+ as +nil+ here. - # - # See also http://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html - def to_ary - nil - end - - def init_internals - @readonly = false - @destroyed = false - @marked_for_destruction = false - @destroyed_by_association = nil - @new_record = true - @_start_transaction_state = {} - @transaction_state = nil - end - - def initialize_internals_callback - end - - def thaw - if frozen? - @attributes = @attributes.dup - end - end - - def custom_inspect_method_defined? - self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/counter_cache.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/counter_cache.rb deleted file mode 100644 index 6830a5983d..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/counter_cache.rb +++ /dev/null @@ -1,211 +0,0 @@ -module ActiveRecord - # = Active Record Counter Cache - module CounterCache - extend ActiveSupport::Concern - - module ClassMethods - # Resets one or more counter caches to their correct value using an SQL - # count query. This is useful when adding new counter caches, or if the - # counter has been corrupted or modified directly by SQL. - # - # ==== Parameters - # - # * +id+ - The id of the object you wish to reset a counter on. - # * +counters+ - One or more association counters to reset. Association name or counter name can be given. - # * :touch - Touch timestamp columns when updating. - # Pass +true+ to touch +updated_at+ and/or +updated_on+. Pass a symbol to - # touch that column or an array of symbols to touch just those ones. - # - # ==== Examples - # - # # For the Post with id #1, reset the comments_count - # Post.reset_counters(1, :comments) - # - # # Like above, but also touch the +updated_at+ and/or +updated_on+ - # # attributes. - # Post.reset_counters(1, :comments, touch: true) - def reset_counters(id, *counters, touch: nil) - object = find(id) - - counters.each do |counter_association| - has_many_association = _reflect_on_association(counter_association) - unless has_many_association - has_many = reflect_on_all_associations(:has_many) - has_many_association = has_many.find { |association| association.counter_cache_column && association.counter_cache_column.to_sym == counter_association.to_sym } - counter_association = has_many_association.plural_name if has_many_association - end - raise ArgumentError, "'#{name}' has no association called '#{counter_association}'" unless has_many_association - - if has_many_association.is_a? ActiveRecord::Reflection::ThroughReflection - has_many_association = has_many_association.through_reflection - end - - foreign_key = has_many_association.foreign_key.to_s - child_class = has_many_association.klass - reflection = child_class._reflections.values.find { |e| e.belongs_to? && e.foreign_key.to_s == foreign_key && e.options[:counter_cache].present? } - counter_name = reflection.counter_cache_column - - updates = { counter_name => object.send(counter_association).count(:all) } - - if touch - names = touch if touch != true - updates.merge!(touch_attributes_with_time(*names)) - end - - unscoped.where(primary_key => object.id).update_all(updates) - end - - return true - end - - # A generic "counter updater" implementation, intended primarily to be - # used by #increment_counter and #decrement_counter, but which may also - # be useful on its own. It simply does a direct SQL update for the record - # with the given ID, altering the given hash of counters by the amount - # given by the corresponding value: - # - # ==== Parameters - # - # * +id+ - The id of the object you wish to update a counter on or an array of ids. - # * +counters+ - A Hash containing the names of the fields - # to update as keys and the amount to update the field by as values. - # * :touch option - Touch timestamp columns when updating. - # If attribute names are passed, they are updated along with updated_at/on - # attributes. - # - # ==== Examples - # - # # For the Post with id of 5, decrement the comment_count by 1, and - # # increment the action_count by 1 - # Post.update_counters 5, comment_count: -1, action_count: 1 - # # Executes the following SQL: - # # UPDATE posts - # # SET comment_count = COALESCE(comment_count, 0) - 1, - # # action_count = COALESCE(action_count, 0) + 1 - # # WHERE id = 5 - # - # # For the Posts with id of 10 and 15, increment the comment_count by 1 - # Post.update_counters [10, 15], comment_count: 1 - # # Executes the following SQL: - # # UPDATE posts - # # SET comment_count = COALESCE(comment_count, 0) + 1 - # # WHERE id IN (10, 15) - # - # # For the Posts with id of 10 and 15, increment the comment_count by 1 - # # and update the updated_at value for each counter. - # Post.update_counters [10, 15], comment_count: 1, touch: true - # # Executes the following SQL: - # # UPDATE posts - # # SET comment_count = COALESCE(comment_count, 0) + 1, - # # `updated_at` = '2016-10-13T09:59:23-05:00' - # # WHERE id IN (10, 15) - def update_counters(id, counters) - touch = counters.delete(:touch) - - updates = counters.map do |counter_name, value| - operator = value < 0 ? "-" : "+" - quoted_column = connection.quote_column_name(counter_name) - "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{value.abs}" - end - - if touch - names = touch if touch != true - touch_updates = touch_attributes_with_time(*names) - updates << sanitize_sql_for_assignment(touch_updates) unless touch_updates.empty? - end - - unscoped.where(primary_key => id).update_all updates.join(", ") - end - - # Increment a numeric field by one, via a direct SQL update. - # - # This method is used primarily for maintaining counter_cache columns that are - # used to store aggregate values. For example, a +DiscussionBoard+ may cache - # posts_count and comments_count to avoid running an SQL query to calculate the - # number of posts and comments there are, each time it is displayed. - # - # ==== Parameters - # - # * +counter_name+ - The name of the field that should be incremented. - # * +id+ - The id of the object that should be incremented or an array of ids. - # * :touch - Touch timestamp columns when updating. - # Pass +true+ to touch +updated_at+ and/or +updated_on+. Pass a symbol to - # touch that column or an array of symbols to touch just those ones. - # - # ==== Examples - # - # # Increment the posts_count column for the record with an id of 5 - # DiscussionBoard.increment_counter(:posts_count, 5) - # - # # Increment the posts_count column for the record with an id of 5 - # # and update the updated_at value. - # DiscussionBoard.increment_counter(:posts_count, 5, touch: true) - def increment_counter(counter_name, id, touch: nil) - update_counters(id, counter_name => 1, touch: touch) - end - - # Decrement a numeric field by one, via a direct SQL update. - # - # This works the same as #increment_counter but reduces the column value by - # 1 instead of increasing it. - # - # ==== Parameters - # - # * +counter_name+ - The name of the field that should be decremented. - # * +id+ - The id of the object that should be decremented or an array of ids. - # * :touch - Touch timestamp columns when updating. - # Pass +true+ to touch +updated_at+ and/or +updated_on+. Pass a symbol to - # touch that column or an array of symbols to touch just those ones. - # - # ==== Examples - # - # # Decrement the posts_count column for the record with an id of 5 - # DiscussionBoard.decrement_counter(:posts_count, 5) - # - # # Decrement the posts_count column for the record with an id of 5 - # # and update the updated_at value. - # DiscussionBoard.decrement_counter(:posts_count, 5, touch: true) - def decrement_counter(counter_name, id, touch: nil) - update_counters(id, counter_name => -1, touch: touch) - end - end - - private - - def _create_record(*) - id = super - - each_counter_cached_associations do |association| - if send(association.reflection.name) - association.increment_counters - @_after_create_counter_called = true - end - end - - id - end - - def destroy_row - affected_rows = super - - if affected_rows > 0 - each_counter_cached_associations do |association| - foreign_key = association.reflection.foreign_key.to_sym - unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == foreign_key - if send(association.reflection.name) - association.decrement_counters - end - end - end - end - - affected_rows - end - - def each_counter_cached_associations - _reflections.each do |name, reflection| - yield association(name.to_sym) if reflection.belongs_to? && reflection.counter_cache_column - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/define_callbacks.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/define_callbacks.rb deleted file mode 100644 index 7d955a24be..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/define_callbacks.rb +++ /dev/null @@ -1,20 +0,0 @@ -module ActiveRecord - # This module exists because `ActiveRecord::AttributeMethods::Dirty` needs to - # define callbacks, but continue to have its version of `save` be the super - # method of `ActiveRecord::Callbacks`. This will be removed when the removal - # of deprecated code removes this need. - module DefineCallbacks - extend ActiveSupport::Concern - - module ClassMethods # :nodoc: - include ActiveModel::Callbacks - end - - included do - include ActiveModel::Validations::Callbacks - - define_model_callbacks :initialize, :find, :touch, only: :after - define_model_callbacks :save, :create, :update, :destroy - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/dynamic_matchers.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/dynamic_matchers.rb deleted file mode 100644 index 08d42f3dd4..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/dynamic_matchers.rb +++ /dev/null @@ -1,122 +0,0 @@ - -module ActiveRecord - module DynamicMatchers #:nodoc: - def respond_to_missing?(name, include_private = false) - if self == Base - super - else - match = Method.match(self, name) - match && match.valid? || super - end - end - - private - - def method_missing(name, *arguments, &block) - match = Method.match(self, name) - - if match && match.valid? - match.define - send(name, *arguments, &block) - else - super - end - end - - class Method - @matchers = [] - - class << self - attr_reader :matchers - - def match(model, name) - klass = matchers.find { |k| k.pattern.match?(name) } - klass.new(model, name) if klass - end - - def pattern - @pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/ - end - - def prefix - raise NotImplementedError - end - - def suffix - "" - end - end - - attr_reader :model, :name, :attribute_names - - def initialize(model, name) - @model = model - @name = name.to_s - @attribute_names = @name.match(self.class.pattern)[1].split("_and_") - @attribute_names.map! { |n| @model.attribute_aliases[n] || n } - end - - def valid? - attribute_names.all? { |name| model.columns_hash[name] || model.reflect_on_aggregation(name.to_sym) } - end - - def define - model.class_eval <<-CODE, __FILE__, __LINE__ + 1 - def self.#{name}(#{signature}) - #{body} - end - CODE - end - - private - - def body - "#{finder}(#{attributes_hash})" - end - - # The parameters in the signature may have reserved Ruby words, in order - # to prevent errors, we start each param name with `_`. - def signature - attribute_names.map { |name| "_#{name}" }.join(", ") - end - - # Given that the parameters starts with `_`, the finder needs to use the - # same parameter name. - def attributes_hash - "{" + attribute_names.map { |name| ":#{name} => _#{name}" }.join(",") + "}" - end - - def finder - raise NotImplementedError - end - end - - class FindBy < Method - Method.matchers << self - - def self.prefix - "find_by" - end - - def finder - "find_by" - end - end - - class FindByBang < Method - Method.matchers << self - - def self.prefix - "find_by" - end - - def self.suffix - "!" - end - - def finder - "find_by!" - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/enum.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/enum.rb deleted file mode 100644 index 0ab03b2ab3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/enum.rb +++ /dev/null @@ -1,239 +0,0 @@ -require "active_support/core_ext/object/deep_dup" - -module ActiveRecord - # Declare an enum attribute where the values map to integers in the database, - # but can be queried by name. Example: - # - # class Conversation < ActiveRecord::Base - # enum status: [ :active, :archived ] - # end - # - # # conversation.update! status: 0 - # conversation.active! - # conversation.active? # => true - # conversation.status # => "active" - # - # # conversation.update! status: 1 - # conversation.archived! - # conversation.archived? # => true - # conversation.status # => "archived" - # - # # conversation.status = 1 - # conversation.status = "archived" - # - # conversation.status = nil - # conversation.status.nil? # => true - # conversation.status # => nil - # - # Scopes based on the allowed values of the enum field will be provided - # as well. With the above example: - # - # Conversation.active - # Conversation.archived - # - # Of course, you can also query them directly if the scopes don't fit your - # needs: - # - # Conversation.where(status: [:active, :archived]) - # Conversation.where.not(status: :active) - # - # You can set the default value from the database declaration, like: - # - # create_table :conversations do |t| - # t.column :status, :integer, default: 0 - # end - # - # Good practice is to let the first declared status be the default. - # - # Finally, it's also possible to explicitly map the relation between attribute and - # database integer with a hash: - # - # class Conversation < ActiveRecord::Base - # enum status: { active: 0, archived: 1 } - # end - # - # Note that when an array is used, the implicit mapping from the values to database - # integers is derived from the order the values appear in the array. In the example, - # :active is mapped to +0+ as it's the first element, and :archived - # is mapped to +1+. In general, the +i+-th element is mapped to i-1 in the - # database. - # - # Therefore, once a value is added to the enum array, its position in the array must - # be maintained, and new values should only be added to the end of the array. To - # remove unused values, the explicit hash syntax should be used. - # - # In rare circumstances you might need to access the mapping directly. - # The mappings are exposed through a class method with the pluralized attribute - # name, which return the mapping in a +HashWithIndifferentAccess+: - # - # Conversation.statuses[:active] # => 0 - # Conversation.statuses["archived"] # => 1 - # - # Use that class method when you need to know the ordinal value of an enum. - # For example, you can use that when manually building SQL strings: - # - # Conversation.where("status <> ?", Conversation.statuses[:archived]) - # - # You can use the +:_prefix+ or +:_suffix+ options when you need to define - # multiple enums with same values. If the passed value is +true+, the methods - # are prefixed/suffixed with the name of the enum. It is also possible to - # supply a custom value: - # - # class Conversation < ActiveRecord::Base - # enum status: [:active, :archived], _suffix: true - # enum comments_status: [:active, :inactive], _prefix: :comments - # end - # - # With the above example, the bang and predicate methods along with the - # associated scopes are now prefixed and/or suffixed accordingly: - # - # conversation.active_status! - # conversation.archived_status? # => false - # - # conversation.comments_inactive! - # conversation.comments_active? # => false - - module Enum - def self.extended(base) # :nodoc: - base.class_attribute(:defined_enums, instance_writer: false) - base.defined_enums = {} - end - - def inherited(base) # :nodoc: - base.defined_enums = defined_enums.deep_dup - super - end - - class EnumType < Type::Value # :nodoc: - delegate :type, to: :subtype - - def initialize(name, mapping, subtype) - @name = name - @mapping = mapping - @subtype = subtype - end - - def cast(value) - return if value.blank? - - if mapping.has_key?(value) - value.to_s - elsif mapping.has_value?(value) - mapping.key(value) - else - assert_valid_value(value) - end - end - - def deserialize(value) - return if value.nil? - mapping.key(subtype.deserialize(value)) - end - - def serialize(value) - mapping.fetch(value, value) - end - - def assert_valid_value(value) - unless value.blank? || mapping.has_key?(value) || mapping.has_value?(value) - raise ArgumentError, "'#{value}' is not a valid #{name}" - end - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :name, :mapping, :subtype - end - - def enum(definitions) - klass = self - enum_prefix = definitions.delete(:_prefix) - enum_suffix = definitions.delete(:_suffix) - definitions.each do |name, values| - # statuses = { } - enum_values = ActiveSupport::HashWithIndifferentAccess.new - name = name.to_sym - - # def self.statuses() statuses end - detect_enum_conflict!(name, name.to_s.pluralize, true) - klass.singleton_class.send(:define_method, name.to_s.pluralize) { enum_values } - - detect_enum_conflict!(name, name) - detect_enum_conflict!(name, "#{name}=") - - attr = attribute_alias?(name) ? attribute_alias(name) : name - decorate_attribute_type(attr, :enum) do |subtype| - EnumType.new(attr, enum_values, subtype) - end - - _enum_methods_module.module_eval do - pairs = values.respond_to?(:each_pair) ? values.each_pair : values.each_with_index - pairs.each do |value, i| - if enum_prefix == true - prefix = "#{name}_" - elsif enum_prefix - prefix = "#{enum_prefix}_" - end - if enum_suffix == true - suffix = "_#{name}" - elsif enum_suffix - suffix = "_#{enum_suffix}" - end - - value_method_name = "#{prefix}#{value}#{suffix}" - enum_values[value] = i - - # def active?() status == 0 end - klass.send(:detect_enum_conflict!, name, "#{value_method_name}?") - define_method("#{value_method_name}?") { self[attr] == value.to_s } - - # def active!() update! status: :active end - klass.send(:detect_enum_conflict!, name, "#{value_method_name}!") - define_method("#{value_method_name}!") { update!(attr => value) } - - # scope :active, -> { where status: 0 } - klass.send(:detect_enum_conflict!, name, value_method_name, true) - klass.scope value_method_name, -> { where(attr => value) } - end - end - defined_enums[name.to_s] = enum_values - end - end - - private - def _enum_methods_module - @_enum_methods_module ||= begin - mod = Module.new - include mod - mod - end - end - - ENUM_CONFLICT_MESSAGE = \ - "You tried to define an enum named \"%{enum}\" on the model \"%{klass}\", but " \ - "this will generate a %{type} method \"%{method}\", which is already defined " \ - "by %{source}." - - def detect_enum_conflict!(enum_name, method_name, klass_method = false) - if klass_method && dangerous_class_method?(method_name) - raise_conflict_error(enum_name, method_name, type: "class") - elsif !klass_method && dangerous_attribute_method?(method_name) - raise_conflict_error(enum_name, method_name) - elsif !klass_method && method_defined_within?(method_name, _enum_methods_module, Module) - raise_conflict_error(enum_name, method_name, source: "another enum") - end - end - - def raise_conflict_error(enum_name, method_name, type: "instance", source: "Active Record") - raise ArgumentError, ENUM_CONFLICT_MESSAGE % { - enum: enum_name, - klass: name, - type: type, - method: method_name, - source: source - } - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/errors.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/errors.rb deleted file mode 100644 index be24905281..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/errors.rb +++ /dev/null @@ -1,341 +0,0 @@ -module ActiveRecord - # = Active Record Errors - # - # Generic Active Record exception class. - class ActiveRecordError < StandardError - end - - # Raised when the single-table inheritance mechanism fails to locate the subclass - # (for example due to improper usage of column that - # {ActiveRecord::Base.inheritance_column}[rdoc-ref:ModelSchema::ClassMethods#inheritance_column] - # points to). - class SubclassNotFound < ActiveRecordError - end - - # Raised when an object assigned to an association has an incorrect type. - # - # class Ticket < ActiveRecord::Base - # has_many :patches - # end - # - # class Patch < ActiveRecord::Base - # belongs_to :ticket - # end - # - # # Comments are not patches, this assignment raises AssociationTypeMismatch. - # @ticket.patches << Comment.new(content: "Please attach tests to your patch.") - class AssociationTypeMismatch < ActiveRecordError - end - - # Raised when unserialized object's type mismatches one specified for serializable field. - class SerializationTypeMismatch < ActiveRecordError - end - - # Raised when adapter not specified on connection (or configuration file - # +config/database.yml+ misses adapter field). - class AdapterNotSpecified < ActiveRecordError - end - - # Raised when Active Record cannot find database adapter specified in - # +config/database.yml+ or programmatically. - class AdapterNotFound < ActiveRecordError - end - - # Raised when connection to the database could not been established (for example when - # {ActiveRecord::Base.connection=}[rdoc-ref:ConnectionHandling#connection] - # is given a +nil+ object). - class ConnectionNotEstablished < ActiveRecordError - end - - # Raised when Active Record cannot find a record by given id or set of ids. - class RecordNotFound < ActiveRecordError - attr_reader :model, :primary_key, :id - - def initialize(message = nil, model = nil, primary_key = nil, id = nil) - @primary_key = primary_key - @model = model - @id = id - - super(message) - end - end - - # Raised by {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!] and - # {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!] - # methods when a record is invalid and can not be saved. - class RecordNotSaved < ActiveRecordError - attr_reader :record - - def initialize(message = nil, record = nil) - @record = record - super(message) - end - end - - # Raised by {ActiveRecord::Base#destroy!}[rdoc-ref:Persistence#destroy!] - # when a call to {#destroy}[rdoc-ref:Persistence#destroy!] - # would return false. - # - # begin - # complex_operation_that_internally_calls_destroy! - # rescue ActiveRecord::RecordNotDestroyed => invalid - # puts invalid.record.errors - # end - # - class RecordNotDestroyed < ActiveRecordError - attr_reader :record - - def initialize(message = nil, record = nil) - @record = record - super(message) - end - end - - # Superclass for all database execution errors. - # - # Wraps the underlying database error as +cause+. - class StatementInvalid < ActiveRecordError - def initialize(message = nil) - super(message || $!.try(:message)) - end - end - - # Defunct wrapper class kept for compatibility. - # StatementInvalid wraps the original exception now. - class WrappedDatabaseException < StatementInvalid - end - - # Raised when a record cannot be inserted because it would violate a uniqueness constraint. - class RecordNotUnique < WrappedDatabaseException - end - - # Raised when a record cannot be inserted or updated because it references a non-existent record. - class InvalidForeignKey < WrappedDatabaseException - end - - # Raised when a foreign key constraint cannot be added because the column type does not match the referenced column type. - class MismatchedForeignKey < StatementInvalid - def initialize( - adapter = nil, - message: nil, - sql: nil, - binds: nil, - table: nil, - foreign_key: nil, - target_table: nil, - primary_key: nil, - primary_key_column: nil - ) - if table - type = primary_key_column.bigint? ? :bigint : primary_key_column.type - msg = <<-EOM.squish - Column `#{foreign_key}` on table `#{table}` does not match column `#{primary_key}` on `#{target_table}`, - which has type `#{primary_key_column.sql_type}`. - To resolve this issue, change the type of the `#{foreign_key}` column on `#{table}` to be :#{type}. - (For example `t.#{type} :#{foreign_key}`). - EOM - else - msg = <<-EOM.squish - There is a mismatch between the foreign key and primary key column types. - Verify that the foreign key column type and the primary key of the associated table match types. - EOM - end - if message - msg << "\nOriginal message: #{message}" - end - super(msg) - end - end - - # Raised when a record cannot be inserted or updated because it would violate a not null constraint. - class NotNullViolation < StatementInvalid - end - - # Raised when a record cannot be inserted or updated because a value too long for a column type. - class ValueTooLong < StatementInvalid - end - - # Raised when values that executed are out of range. - class RangeError < StatementInvalid - end - - # Raised when number of bind variables in statement given to +:condition+ key - # (for example, when using {ActiveRecord::Base.find}[rdoc-ref:FinderMethods#find] method) - # does not match number of expected values supplied. - # - # For example, when there are two placeholders with only one value supplied: - # - # Location.where("lat = ? AND lng = ?", 53.7362) - class PreparedStatementInvalid < ActiveRecordError - end - - # Raised when a given database does not exist. - class NoDatabaseError < StatementInvalid - end - - # Raised when Postgres returns 'cached plan must not change result type' and - # we cannot retry gracefully (e.g. inside a transaction) - class PreparedStatementCacheExpired < StatementInvalid - end - - # Raised on attempt to save stale record. Record is stale when it's being saved in another query after - # instantiation, for example, when two users edit the same wiki page and one starts editing and saves - # the page before the other. - # - # Read more about optimistic locking in ActiveRecord::Locking module - # documentation. - class StaleObjectError < ActiveRecordError - attr_reader :record, :attempted_action - - def initialize(record = nil, attempted_action = nil) - if record && attempted_action - @record = record - @attempted_action = attempted_action - super("Attempted to #{attempted_action} a stale object: #{record.class.name}.") - else - super("Stale object error.") - end - end - end - - # Raised when association is being configured improperly or user tries to use - # offset and limit together with - # {ActiveRecord::Base.has_many}[rdoc-ref:Associations::ClassMethods#has_many] or - # {ActiveRecord::Base.has_and_belongs_to_many}[rdoc-ref:Associations::ClassMethods#has_and_belongs_to_many] - # associations. - class ConfigurationError < ActiveRecordError - end - - # Raised on attempt to update record that is instantiated as read only. - class ReadOnlyRecord < ActiveRecordError - end - - # {ActiveRecord::Base.transaction}[rdoc-ref:Transactions::ClassMethods#transaction] - # uses this exception to distinguish a deliberate rollback from other exceptional situations. - # Normally, raising an exception will cause the - # {.transaction}[rdoc-ref:Transactions::ClassMethods#transaction] method to rollback - # the database transaction *and* pass on the exception. But if you raise an - # ActiveRecord::Rollback exception, then the database transaction will be rolled back, - # without passing on the exception. - # - # For example, you could do this in your controller to rollback a transaction: - # - # class BooksController < ActionController::Base - # def create - # Book.transaction do - # book = Book.new(params[:book]) - # book.save! - # if today_is_friday? - # # The system must fail on Friday so that our support department - # # won't be out of job. We silently rollback this transaction - # # without telling the user. - # raise ActiveRecord::Rollback, "Call tech support!" - # end - # end - # # ActiveRecord::Rollback is the only exception that won't be passed on - # # by ActiveRecord::Base.transaction, so this line will still be reached - # # even on Friday. - # redirect_to root_url - # end - # end - class Rollback < ActiveRecordError - end - - # Raised when attribute has a name reserved by Active Record (when attribute - # has name of one of Active Record instance methods). - class DangerousAttributeError < ActiveRecordError - end - - # Raised when unknown attributes are supplied via mass assignment. - UnknownAttributeError = ActiveModel::UnknownAttributeError - - # Raised when an error occurred while doing a mass assignment to an attribute through the - # {ActiveRecord::Base#attributes=}[rdoc-ref:AttributeAssignment#attributes=] method. - # The exception has an +attribute+ property that is the name of the offending attribute. - class AttributeAssignmentError < ActiveRecordError - attr_reader :exception, :attribute - - def initialize(message = nil, exception = nil, attribute = nil) - super(message) - @exception = exception - @attribute = attribute - end - end - - # Raised when there are multiple errors while doing a mass assignment through the - # {ActiveRecord::Base#attributes=}[rdoc-ref:AttributeAssignment#attributes=] - # method. The exception has an +errors+ property that contains an array of AttributeAssignmentError - # objects, each corresponding to the error while assigning to an attribute. - class MultiparameterAssignmentErrors < ActiveRecordError - attr_reader :errors - - def initialize(errors = nil) - @errors = errors - end - end - - # Raised when a primary key is needed, but not specified in the schema or model. - class UnknownPrimaryKey < ActiveRecordError - attr_reader :model - - def initialize(model = nil, description = nil) - if model - message = "Unknown primary key for table #{model.table_name} in model #{model}." - message += "\n#{description}" if description - @model = model - super(message) - else - super("Unknown primary key.") - end - end - end - - # Raised when a relation cannot be mutated because it's already loaded. - # - # class Task < ActiveRecord::Base - # end - # - # relation = Task.all - # relation.loaded? # => true - # - # # Methods which try to mutate a loaded relation fail. - # relation.where!(title: 'TODO') # => ActiveRecord::ImmutableRelation - # relation.limit!(5) # => ActiveRecord::ImmutableRelation - class ImmutableRelation < ActiveRecordError - end - - # TransactionIsolationError will be raised under the following conditions: - # - # * The adapter does not support setting the isolation level - # * You are joining an existing open transaction - # * You are creating a nested (savepoint) transaction - # - # The mysql2 and postgresql adapters support setting the transaction isolation level. - class TransactionIsolationError < ActiveRecordError - end - - # TransactionRollbackError will be raised when a transaction is rolled - # back by the database due to a serialization failure or a deadlock. - # - # See the following: - # - # * http://www.postgresql.org/docs/current/static/transaction-iso.html - # * https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html#error_er_lock_deadlock - class TransactionRollbackError < StatementInvalid - end - - # SerializationFailure will be raised when a transaction is rolled - # back by the database due to a serialization failure. - class SerializationFailure < TransactionRollbackError - end - - # Deadlocked will be raised when a transaction is rolled - # back by the database when a deadlock is encountered. - class Deadlocked < TransactionRollbackError - end - - # IrreversibleOrderError is raised when a relation's order is too complex for - # +reverse_order+ to automatically reverse. - class IrreversibleOrderError < ActiveRecordError - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain.rb deleted file mode 100644 index 8f7ae2c33c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "active_record/explain_registry" - -module ActiveRecord - module Explain - # Executes the block with the collect flag enabled. Queries are collected - # asynchronously by the subscriber and returned. - def collecting_queries_for_explain # :nodoc: - ExplainRegistry.collect = true - yield - ExplainRegistry.queries - ensure - ExplainRegistry.reset - end - - # Makes the adapter execute EXPLAIN for the tuples of queries and bindings. - # Returns a formatted string ready to be logged. - def exec_explain(queries) # :nodoc: - str = queries.map do |sql, binds| - msg = "EXPLAIN for: #{sql}" - unless binds.empty? - msg << " " - msg << binds.map { |attr| render_bind(attr) }.inspect - end - msg << "\n" - msg << connection.explain(sql, binds) - end.join("\n") - - # Overriding inspect to be more human readable, especially in the console. - def str.inspect - self - end - - str - end - - private - - def render_bind(attr) - value = if attr.type.binary? && attr.value - "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>" - else - connection.type_cast(attr.value_for_database) - end - - [attr.name, value] - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain_registry.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain_registry.rb deleted file mode 100644 index ef1ce3dc85..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain_registry.rb +++ /dev/null @@ -1,30 +0,0 @@ -require "active_support/per_thread_registry" - -module ActiveRecord - # This is a thread locals registry for EXPLAIN. For example - # - # ActiveRecord::ExplainRegistry.queries - # - # returns the collected queries local to the current thread. - # - # See the documentation of ActiveSupport::PerThreadRegistry - # for further details. - class ExplainRegistry # :nodoc: - extend ActiveSupport::PerThreadRegistry - - attr_accessor :queries, :collect - - def initialize - reset - end - - def collect? - @collect - end - - def reset - @collect = false - @queries = [] - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain_subscriber.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain_subscriber.rb deleted file mode 100644 index abd8cfc8f2..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/explain_subscriber.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "active_support/notifications" -require "active_record/explain_registry" - -module ActiveRecord - class ExplainSubscriber # :nodoc: - def start(name, id, payload) - # unused - end - - def finish(name, id, payload) - if ExplainRegistry.collect? && !ignore_payload?(payload) - ExplainRegistry.queries << payload.values_at(:sql, :binds) - end - end - - # SCHEMA queries cannot be EXPLAINed, also we do not want to run EXPLAIN on - # our own EXPLAINs no matter how loopingly beautiful that would be. - # - # On the other hand, we want to monitor the performance of our real database - # queries, not the performance of the access to the query cache. - IGNORED_PAYLOADS = %w(SCHEMA EXPLAIN) - EXPLAINED_SQLS = /\A\s*(with|select|update|delete|insert)\b/i - def ignore_payload?(payload) - payload[:exception] || - payload[:cached] || - IGNORED_PAYLOADS.include?(payload[:name]) || - payload[:sql] !~ EXPLAINED_SQLS - end - - ActiveSupport::Notifications.subscribe("sql.active_record", new) - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/fixture_set/file.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/fixture_set/file.rb deleted file mode 100644 index 6cf2e01179..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/fixture_set/file.rb +++ /dev/null @@ -1,80 +0,0 @@ -require "erb" -require "yaml" - -module ActiveRecord - class FixtureSet - class File # :nodoc: - include Enumerable - - ## - # Open a fixture file named +file+. When called with a block, the block - # is called with the filehandle and the filehandle is automatically closed - # when the block finishes. - def self.open(file) - x = new file - block_given? ? yield(x) : x - end - - def initialize(file) - @file = file - end - - def each(&block) - rows.each(&block) - end - - def model_class - config_row["model_class"] - end - - private - def rows - @rows ||= raw_rows.reject { |fixture_name, _| fixture_name == "_fixture" } - end - - def config_row - @config_row ||= begin - row = raw_rows.find { |fixture_name, _| fixture_name == "_fixture" } - if row - row.last - else - { 'model_class': nil } - end - end - end - - def raw_rows - @raw_rows ||= begin - data = YAML.load(render(IO.read(@file))) - data ? validate(data).to_a : [] - rescue ArgumentError, Psych::SyntaxError => error - raise Fixture::FormatError, "a YAML error occurred parsing #{@file}. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Please have a look at http://www.yaml.org/faq.html\nThe exact error was:\n #{error.class}: #{error}", error.backtrace - end - end - - def prepare_erb(content) - erb = ERB.new(content) - erb.filename = @file - erb - end - - def render(content) - context = ActiveRecord::FixtureSet::RenderContext.create_subclass.new - prepare_erb(content).result(context.get_binding) - end - - # Validate our unmarshalled data. - def validate(data) - unless Hash === data || YAML::Omap === data - raise Fixture::FormatError, "fixture is not a hash: #{@file}" - end - - invalid = data.reject { |_, row| Hash === row } - if invalid.any? - raise Fixture::FormatError, "fixture key is not a hash: #{@file}, keys: #{invalid.keys.inspect}" - end - data - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/fixtures.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/fixtures.rb deleted file mode 100644 index e79167d568..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/fixtures.rb +++ /dev/null @@ -1,1058 +0,0 @@ -require "erb" -require "yaml" -require "zlib" -require "set" -require "active_support/dependencies" -require "active_support/core_ext/digest/uuid" -require "active_record/fixture_set/file" -require "active_record/errors" - -module ActiveRecord - class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc: - end - - # \Fixtures are a way of organizing data that you want to test against; in short, sample data. - # - # They are stored in YAML files, one file per model, which are placed in the directory - # appointed by ActiveSupport::TestCase.fixture_path=(path) (this is automatically - # configured for Rails, so you can just put your files in /test/fixtures/). - # The fixture file ends with the +.yml+ file extension, for example: - # /test/fixtures/web_sites.yml). - # - # The format of a fixture file looks like this: - # - # rubyonrails: - # id: 1 - # name: Ruby on Rails - # url: http://www.rubyonrails.org - # - # google: - # id: 2 - # name: Google - # url: http://www.google.com - # - # This fixture file includes two fixtures. Each YAML fixture (ie. record) is given a name and - # is followed by an indented list of key/value pairs in the "key: value" format. Records are - # separated by a blank line for your viewing pleasure. - # - # Note: Fixtures are unordered. If you want ordered fixtures, use the omap YAML type. - # See http://yaml.org/type/omap.html - # for the specification. You will need ordered fixtures when you have foreign key constraints - # on keys in the same table. This is commonly needed for tree structures. Example: - # - # --- !omap - # - parent: - # id: 1 - # parent_id: NULL - # title: Parent - # - child: - # id: 2 - # parent_id: 1 - # title: Child - # - # = Using Fixtures in Test Cases - # - # Since fixtures are a testing construct, we use them in our unit and functional tests. There - # are two ways to use the fixtures, but first let's take a look at a sample unit test: - # - # require 'test_helper' - # - # class WebSiteTest < ActiveSupport::TestCase - # test "web_site_count" do - # assert_equal 2, WebSite.count - # end - # end - # - # By default, +test_helper.rb+ will load all of your fixtures into your test - # database, so this test will succeed. - # - # The testing environment will automatically load all the fixtures into the database before each - # test. To ensure consistent data, the environment deletes the fixtures before running the load. - # - # In addition to being available in the database, the fixture's data may also be accessed by - # using a special dynamic method, which has the same name as the model, and accepts the - # name of the fixture to instantiate: - # - # test "find" do - # assert_equal "Ruby on Rails", web_sites(:rubyonrails).name - # end - # - # Alternatively, you may enable auto-instantiation of the fixture data. For instance, take the - # following tests: - # - # test "find_alt_method_1" do - # assert_equal "Ruby on Rails", @web_sites['rubyonrails']['name'] - # end - # - # test "find_alt_method_2" do - # assert_equal "Ruby on Rails", @rubyonrails.name - # end - # - # In order to use these methods to access fixtured data within your test cases, you must specify one of the - # following in your ActiveSupport::TestCase-derived class: - # - # - to fully enable instantiated fixtures (enable alternate methods #1 and #2 above) - # self.use_instantiated_fixtures = true - # - # - create only the hash for the fixtures, do not 'find' each instance (enable alternate method #1 only) - # self.use_instantiated_fixtures = :no_instances - # - # Using either of these alternate methods incurs a performance hit, as the fixtured data must be fully - # traversed in the database to create the fixture hash and/or instance variables. This is expensive for - # large sets of fixtured data. - # - # = Dynamic fixtures with ERB - # - # Sometimes you don't care about the content of the fixtures as much as you care about the volume. - # In these cases, you can mix ERB in with your YAML fixtures to create a bunch of fixtures for load - # testing, like: - # - # <% 1.upto(1000) do |i| %> - # fix_<%= i %>: - # id: <%= i %> - # name: guy_<%= i %> - # <% end %> - # - # This will create 1000 very simple fixtures. - # - # Using ERB, you can also inject dynamic values into your fixtures with inserts like - # <%= Date.today.strftime("%Y-%m-%d") %>. - # This is however a feature to be used with some caution. The point of fixtures are that they're - # stable units of predictable sample data. If you feel that you need to inject dynamic values, then - # perhaps you should reexamine whether your application is properly testable. Hence, dynamic values - # in fixtures are to be considered a code smell. - # - # Helper methods defined in a fixture will not be available in other fixtures, to prevent against - # unwanted inter-test dependencies. Methods used by multiple fixtures should be defined in a module - # that is included in ActiveRecord::FixtureSet.context_class. - # - # - define a helper method in `test_helper.rb` - # module FixtureFileHelpers - # def file_sha(path) - # Digest::SHA2.hexdigest(File.read(Rails.root.join('test/fixtures', path))) - # end - # end - # ActiveRecord::FixtureSet.context_class.include FixtureFileHelpers - # - # - use the helper method in a fixture - # photo: - # name: kitten.png - # sha: <%= file_sha 'files/kitten.png' %> - # - # = Transactional Tests - # - # Test cases can use begin+rollback to isolate their changes to the database instead of having to - # delete+insert for every test case. - # - # class FooTest < ActiveSupport::TestCase - # self.use_transactional_tests = true - # - # test "godzilla" do - # assert !Foo.all.empty? - # Foo.destroy_all - # assert Foo.all.empty? - # end - # - # test "godzilla aftermath" do - # assert !Foo.all.empty? - # end - # end - # - # If you preload your test database with all fixture data (probably in the rake task) and use - # transactional tests, then you may omit all fixtures declarations in your test cases since - # all the data's already there and every case rolls back its changes. - # - # In order to use instantiated fixtures with preloaded data, set +self.pre_loaded_fixtures+ to - # true. This will provide access to fixture data for every table that has been loaded through - # fixtures (depending on the value of +use_instantiated_fixtures+). - # - # When *not* to use transactional tests: - # - # 1. You're testing whether a transaction works correctly. Nested transactions don't commit until - # all parent transactions commit, particularly, the fixtures transaction which is begun in setup - # and rolled back in teardown. Thus, you won't be able to verify - # the results of your transaction until Active Record supports nested transactions or savepoints (in progress). - # 2. Your database does not support transactions. Every Active Record database supports transactions except MySQL MyISAM. - # Use InnoDB, MaxDB, or NDB instead. - # - # = Advanced Fixtures - # - # Fixtures that don't specify an ID get some extra features: - # - # * Stable, autogenerated IDs - # * Label references for associations (belongs_to, has_one, has_many) - # * HABTM associations as inline lists - # - # There are some more advanced features available even if the id is specified: - # - # * Autofilled timestamp columns - # * Fixture label interpolation - # * Support for YAML defaults - # - # == Stable, Autogenerated IDs - # - # Here, have a monkey fixture: - # - # george: - # id: 1 - # name: George the Monkey - # - # reginald: - # id: 2 - # name: Reginald the Pirate - # - # Each of these fixtures has two unique identifiers: one for the database - # and one for the humans. Why don't we generate the primary key instead? - # Hashing each fixture's label yields a consistent ID: - # - # george: # generated id: 503576764 - # name: George the Monkey - # - # reginald: # generated id: 324201669 - # name: Reginald the Pirate - # - # Active Record looks at the fixture's model class, discovers the correct - # primary key, and generates it right before inserting the fixture - # into the database. - # - # The generated ID for a given label is constant, so we can discover - # any fixture's ID without loading anything, as long as we know the label. - # - # == Label references for associations (belongs_to, has_one, has_many) - # - # Specifying foreign keys in fixtures can be very fragile, not to - # mention difficult to read. Since Active Record can figure out the ID of - # any fixture from its label, you can specify FK's by label instead of ID. - # - # === belongs_to - # - # Let's break out some more monkeys and pirates. - # - # ### in pirates.yml - # - # reginald: - # id: 1 - # name: Reginald the Pirate - # monkey_id: 1 - # - # ### in monkeys.yml - # - # george: - # id: 1 - # name: George the Monkey - # pirate_id: 1 - # - # Add a few more monkeys and pirates and break this into multiple files, - # and it gets pretty hard to keep track of what's going on. Let's - # use labels instead of IDs: - # - # ### in pirates.yml - # - # reginald: - # name: Reginald the Pirate - # monkey: george - # - # ### in monkeys.yml - # - # george: - # name: George the Monkey - # pirate: reginald - # - # Pow! All is made clear. Active Record reflects on the fixture's model class, - # finds all the +belongs_to+ associations, and allows you to specify - # a target *label* for the *association* (monkey: george) rather than - # a target *id* for the *FK* (monkey_id: 1). - # - # ==== Polymorphic belongs_to - # - # Supporting polymorphic relationships is a little bit more complicated, since - # Active Record needs to know what type your association is pointing at. Something - # like this should look familiar: - # - # ### in fruit.rb - # - # belongs_to :eater, polymorphic: true - # - # ### in fruits.yml - # - # apple: - # id: 1 - # name: apple - # eater_id: 1 - # eater_type: Monkey - # - # Can we do better? You bet! - # - # apple: - # eater: george (Monkey) - # - # Just provide the polymorphic target type and Active Record will take care of the rest. - # - # === has_and_belongs_to_many - # - # Time to give our monkey some fruit. - # - # ### in monkeys.yml - # - # george: - # id: 1 - # name: George the Monkey - # - # ### in fruits.yml - # - # apple: - # id: 1 - # name: apple - # - # orange: - # id: 2 - # name: orange - # - # grape: - # id: 3 - # name: grape - # - # ### in fruits_monkeys.yml - # - # apple_george: - # fruit_id: 1 - # monkey_id: 1 - # - # orange_george: - # fruit_id: 2 - # monkey_id: 1 - # - # grape_george: - # fruit_id: 3 - # monkey_id: 1 - # - # Let's make the HABTM fixture go away. - # - # ### in monkeys.yml - # - # george: - # id: 1 - # name: George the Monkey - # fruits: apple, orange, grape - # - # ### in fruits.yml - # - # apple: - # name: apple - # - # orange: - # name: orange - # - # grape: - # name: grape - # - # Zap! No more fruits_monkeys.yml file. We've specified the list of fruits - # on George's fixture, but we could've just as easily specified a list - # of monkeys on each fruit. As with +belongs_to+, Active Record reflects on - # the fixture's model class and discovers the +has_and_belongs_to_many+ - # associations. - # - # == Autofilled Timestamp Columns - # - # If your table/model specifies any of Active Record's - # standard timestamp columns (+created_at+, +created_on+, +updated_at+, +updated_on+), - # they will automatically be set to Time.now. - # - # If you've set specific values, they'll be left alone. - # - # == Fixture label interpolation - # - # The label of the current fixture is always available as a column value: - # - # geeksomnia: - # name: Geeksomnia's Account - # subdomain: $LABEL - # email: $LABEL@email.com - # - # Also, sometimes (like when porting older join table fixtures) you'll need - # to be able to get a hold of the identifier for a given label. ERB - # to the rescue: - # - # george_reginald: - # monkey_id: <%= ActiveRecord::FixtureSet.identify(:reginald) %> - # pirate_id: <%= ActiveRecord::FixtureSet.identify(:george) %> - # - # == Support for YAML defaults - # - # You can set and reuse defaults in your fixtures YAML file. - # This is the same technique used in the +database.yml+ file to specify - # defaults: - # - # DEFAULTS: &DEFAULTS - # created_on: <%= 3.weeks.ago.to_s(:db) %> - # - # first: - # name: Smurf - # <<: *DEFAULTS - # - # second: - # name: Fraggle - # <<: *DEFAULTS - # - # Any fixture labeled "DEFAULTS" is safely ignored. - # - # == Configure the fixture model class - # - # It's possible to set the fixture's model class directly in the YAML file. - # This is helpful when fixtures are loaded outside tests and - # +set_fixture_class+ is not available (e.g. - # when running rails db:fixtures:load). - # - # _fixture: - # model_class: User - # david: - # name: David - # - # Any fixtures labeled "_fixture" are safely ignored. - class FixtureSet - #-- - # An instance of FixtureSet is normally stored in a single YAML file and - # possibly in a folder with the same name. - #++ - - MAX_ID = 2**30 - 1 - - @@all_cached_fixtures = Hash.new { |h, k| h[k] = {} } - - def self.default_fixture_model_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc: - config.pluralize_table_names ? - fixture_set_name.singularize.camelize : - fixture_set_name.camelize - end - - def self.default_fixture_table_name(fixture_set_name, config = ActiveRecord::Base) # :nodoc: - "#{ config.table_name_prefix }"\ - "#{ fixture_set_name.tr('/', '_') }"\ - "#{ config.table_name_suffix }".to_sym - end - - def self.reset_cache - @@all_cached_fixtures.clear - end - - def self.cache_for_connection(connection) - @@all_cached_fixtures[connection] - end - - def self.fixture_is_cached?(connection, table_name) - cache_for_connection(connection)[table_name] - end - - def self.cached_fixtures(connection, keys_to_fetch = nil) - if keys_to_fetch - cache_for_connection(connection).values_at(*keys_to_fetch) - else - cache_for_connection(connection).values - end - end - - def self.cache_fixtures(connection, fixtures_map) - cache_for_connection(connection).update(fixtures_map) - end - - def self.instantiate_fixtures(object, fixture_set, load_instances = true) - if load_instances - fixture_set.each do |fixture_name, fixture| - begin - object.instance_variable_set "@#{fixture_name}", fixture.find - rescue FixtureClassNotFound - nil - end - end - end - end - - def self.instantiate_all_loaded_fixtures(object, load_instances = true) - all_loaded_fixtures.each_value do |fixture_set| - instantiate_fixtures(object, fixture_set, load_instances) - end - end - - cattr_accessor :all_loaded_fixtures - self.all_loaded_fixtures = {} - - class ClassCache - def initialize(class_names, config) - @class_names = class_names.stringify_keys - @config = config - - # Remove string values that aren't constants or subclasses of AR - @class_names.delete_if { |klass_name, klass| !insert_class(@class_names, klass_name, klass) } - end - - def [](fs_name) - @class_names.fetch(fs_name) { - klass = default_fixture_model(fs_name, @config).safe_constantize - insert_class(@class_names, fs_name, klass) - } - end - - private - - def insert_class(class_names, name, klass) - # We only want to deal with AR objects. - if klass && klass < ActiveRecord::Base - class_names[name] = klass - else - class_names[name] = nil - end - end - - def default_fixture_model(fs_name, config) - ActiveRecord::FixtureSet.default_fixture_model_name(fs_name, config) - end - end - - def self.create_fixtures(fixtures_directory, fixture_set_names, class_names = {}, config = ActiveRecord::Base) - fixture_set_names = Array(fixture_set_names).map(&:to_s) - class_names = ClassCache.new class_names, config - - # FIXME: Apparently JK uses this. - connection = block_given? ? yield : ActiveRecord::Base.connection - - files_to_read = fixture_set_names.reject { |fs_name| - fixture_is_cached?(connection, fs_name) - } - - unless files_to_read.empty? - connection.disable_referential_integrity do - fixtures_map = {} - - fixture_sets = files_to_read.map do |fs_name| - klass = class_names[fs_name] - conn = klass ? klass.connection : connection - fixtures_map[fs_name] = new( # ActiveRecord::FixtureSet.new - conn, - fs_name, - klass, - ::File.join(fixtures_directory, fs_name)) - end - - update_all_loaded_fixtures fixtures_map - - connection.transaction(requires_new: true) do - deleted_tables = Hash.new { |h, k| h[k] = Set.new } - fixture_sets.each do |fs| - conn = fs.model_class.respond_to?(:connection) ? fs.model_class.connection : connection - table_rows = fs.table_rows - - table_rows.each_key do |table| - unless deleted_tables[conn].include? table - conn.delete "DELETE FROM #{conn.quote_table_name(table)}", "Fixture Delete" - end - deleted_tables[conn] << table - end - - table_rows.each do |fixture_set_name, rows| - rows.each do |row| - conn.insert_fixture(row, fixture_set_name) - end - end - - # Cap primary key sequences to max(pk). - if conn.respond_to?(:reset_pk_sequence!) - conn.reset_pk_sequence!(fs.table_name) - end - end - end - - cache_fixtures(connection, fixtures_map) - end - end - cached_fixtures(connection, fixture_set_names) - end - - # Returns a consistent, platform-independent identifier for +label+. - # Integer identifiers are values less than 2^30. UUIDs are RFC 4122 version 5 SHA-1 hashes. - def self.identify(label, column_type = :integer) - if column_type == :uuid - Digest::UUID.uuid_v5(Digest::UUID::OID_NAMESPACE, label.to_s) - else - Zlib.crc32(label.to_s) % MAX_ID - end - end - - # Superclass for the evaluation contexts used by ERB fixtures. - def self.context_class - @context_class ||= Class.new - end - - def self.update_all_loaded_fixtures(fixtures_map) # :nodoc: - all_loaded_fixtures.update(fixtures_map) - end - - attr_reader :table_name, :name, :fixtures, :model_class, :config - - def initialize(connection, name, class_name, path, config = ActiveRecord::Base) - @name = name - @path = path - @config = config - - self.model_class = class_name - - @fixtures = read_fixture_files(path) - - @connection = connection - - @table_name = (model_class.respond_to?(:table_name) ? - model_class.table_name : - self.class.default_fixture_table_name(name, config)) - end - - def [](x) - fixtures[x] - end - - def []=(k, v) - fixtures[k] = v - end - - def each(&block) - fixtures.each(&block) - end - - def size - fixtures.size - end - - # Returns a hash of rows to be inserted. The key is the table, the value is - # a list of rows to insert to that table. - def table_rows - now = config.default_timezone == :utc ? Time.now.utc : Time.now - - # allow a standard key to be used for doing defaults in YAML - fixtures.delete("DEFAULTS") - - # track any join tables we need to insert later - rows = Hash.new { |h, table| h[table] = [] } - - rows[table_name] = fixtures.map do |label, fixture| - row = fixture.to_hash - - if model_class - # fill in timestamp columns if they aren't specified and the model is set to record_timestamps - if model_class.record_timestamps - timestamp_column_names.each do |c_name| - row[c_name] = now unless row.key?(c_name) - end - end - - # interpolate the fixture label - row.each do |key, value| - row[key] = value.gsub("$LABEL", label.to_s) if value.is_a?(String) - end - - # generate a primary key if necessary - if has_primary_key_column? && !row.include?(primary_key_name) - row[primary_key_name] = ActiveRecord::FixtureSet.identify(label, primary_key_type) - end - - # Resolve enums - model_class.defined_enums.each do |name, values| - if row.include?(name) - row[name] = values.fetch(row[name], row[name]) - end - end - - # If STI is used, find the correct subclass for association reflection - reflection_class = - if row.include?(inheritance_column_name) - row[inheritance_column_name].constantize rescue model_class - else - model_class - end - - reflection_class._reflections.each_value do |association| - case association.macro - when :belongs_to - # Do not replace association name with association foreign key if they are named the same - fk_name = (association.options[:foreign_key] || "#{association.name}_id").to_s - - if association.name.to_s != fk_name && value = row.delete(association.name.to_s) - if association.polymorphic? && value.sub!(/\s*\(([^\)]*)\)\s*$/, "") - # support polymorphic belongs_to as "label (Type)" - row[association.foreign_type] = $1 - end - - fk_type = reflection_class.type_for_attribute(fk_name).type - row[fk_name] = ActiveRecord::FixtureSet.identify(value, fk_type) - end - when :has_many - if association.options[:through] - add_join_records(rows, row, HasManyThroughProxy.new(association)) - end - end - end - end - - row - end - rows - end - - class ReflectionProxy # :nodoc: - def initialize(association) - @association = association - end - - def join_table - @association.join_table - end - - def name - @association.name - end - - def primary_key_type - @association.klass.type_for_attribute(@association.klass.primary_key).type - end - end - - class HasManyThroughProxy < ReflectionProxy # :nodoc: - def rhs_key - @association.foreign_key - end - - def lhs_key - @association.through_reflection.foreign_key - end - - def join_table - @association.through_reflection.table_name - end - end - - private - def primary_key_name - @primary_key_name ||= model_class && model_class.primary_key - end - - def primary_key_type - @primary_key_type ||= model_class && model_class.type_for_attribute(model_class.primary_key).type - end - - def add_join_records(rows, row, association) - # This is the case when the join table has no fixtures file - if (targets = row.delete(association.name.to_s)) - table_name = association.join_table - column_type = association.primary_key_type - lhs_key = association.lhs_key - rhs_key = association.rhs_key - - targets = targets.is_a?(Array) ? targets : targets.split(/\s*,\s*/) - rows[table_name].concat targets.map { |target| - { lhs_key => row[primary_key_name], - rhs_key => ActiveRecord::FixtureSet.identify(target, column_type) } - } - end - end - - def has_primary_key_column? - @has_primary_key_column ||= primary_key_name && - model_class.columns.any? { |c| c.name == primary_key_name } - end - - def timestamp_column_names - @timestamp_column_names ||= - %w(created_at created_on updated_at updated_on) & column_names - end - - def inheritance_column_name - @inheritance_column_name ||= model_class && model_class.inheritance_column - end - - def column_names - @column_names ||= @connection.columns(@table_name).collect(&:name) - end - - def model_class=(class_name) - if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any? - @model_class = class_name - else - @model_class = class_name.safe_constantize if class_name - end - end - - # Loads the fixtures from the YAML file at +path+. - # If the file sets the +model_class+ and current instance value is not set, - # it uses the file value. - def read_fixture_files(path) - yaml_files = Dir["#{path}/{**,*}/*.yml"].select { |f| - ::File.file?(f) - } + [yaml_file_path(path)] - - yaml_files.each_with_object({}) do |file, fixtures| - FixtureSet::File.open(file) do |fh| - self.model_class ||= fh.model_class if fh.model_class - fh.each do |fixture_name, row| - fixtures[fixture_name] = ActiveRecord::Fixture.new(row, model_class) - end - end - end - end - - def yaml_file_path(path) - "#{path}.yml" - end - end - - class Fixture #:nodoc: - include Enumerable - - class FixtureError < StandardError #:nodoc: - end - - class FormatError < FixtureError #:nodoc: - end - - attr_reader :model_class, :fixture - - def initialize(fixture, model_class) - @fixture = fixture - @model_class = model_class - end - - def class_name - model_class.name if model_class - end - - def each - fixture.each { |item| yield item } - end - - def [](key) - fixture[key] - end - - alias :to_hash :fixture - - def find - if model_class - model_class.unscoped do - model_class.find(fixture[model_class.primary_key]) - end - else - raise FixtureClassNotFound, "No class attached to find." - end - end - end -end - -module ActiveRecord - module TestFixtures - extend ActiveSupport::Concern - - def before_setup # :nodoc: - setup_fixtures - super - end - - def after_teardown # :nodoc: - super - teardown_fixtures - end - - included do - class_attribute :fixture_path, instance_writer: false - class_attribute :fixture_table_names - class_attribute :fixture_class_names - class_attribute :use_transactional_tests - class_attribute :use_instantiated_fixtures # true, false, or :no_instances - class_attribute :pre_loaded_fixtures - class_attribute :config - - self.fixture_table_names = [] - self.use_instantiated_fixtures = false - self.pre_loaded_fixtures = false - self.config = ActiveRecord::Base - - self.fixture_class_names = {} - self.use_transactional_tests = true - end - - module ClassMethods - # Sets the model class for a fixture when the class name cannot be inferred from the fixture name. - # - # Examples: - # - # set_fixture_class some_fixture: SomeModel, - # 'namespaced/fixture' => Another::Model - # - # The keys must be the fixture names, that coincide with the short paths to the fixture files. - def set_fixture_class(class_names = {}) - self.fixture_class_names = fixture_class_names.merge(class_names.stringify_keys) - end - - def fixtures(*fixture_set_names) - if fixture_set_names.first == :all - fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"].uniq - fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] } - else - fixture_set_names = fixture_set_names.flatten.map(&:to_s) - end - - self.fixture_table_names |= fixture_set_names - setup_fixture_accessors(fixture_set_names) - end - - def setup_fixture_accessors(fixture_set_names = nil) - fixture_set_names = Array(fixture_set_names || fixture_table_names) - methods = Module.new do - fixture_set_names.each do |fs_name| - fs_name = fs_name.to_s - accessor_name = fs_name.tr("/", "_").to_sym - - define_method(accessor_name) do |*fixture_names| - force_reload = fixture_names.pop if fixture_names.last == true || fixture_names.last == :reload - - @fixture_cache[fs_name] ||= {} - - instances = fixture_names.map do |f_name| - f_name = f_name.to_s if f_name.is_a?(Symbol) - @fixture_cache[fs_name].delete(f_name) if force_reload - - if @loaded_fixtures[fs_name][f_name] - @fixture_cache[fs_name][f_name] ||= @loaded_fixtures[fs_name][f_name].find - else - raise StandardError, "No fixture named '#{f_name}' found for fixture set '#{fs_name}'" - end - end - - instances.size == 1 ? instances.first : instances - end - private accessor_name - end - end - include methods - end - - def uses_transaction(*methods) - @uses_transaction = [] unless defined?(@uses_transaction) - @uses_transaction.concat methods.map(&:to_s) - end - - def uses_transaction?(method) - @uses_transaction = [] unless defined?(@uses_transaction) - @uses_transaction.include?(method.to_s) - end - end - - def run_in_transaction? - use_transactional_tests && - !self.class.uses_transaction?(method_name) - end - - def setup_fixtures(config = ActiveRecord::Base) - if pre_loaded_fixtures && !use_transactional_tests - raise RuntimeError, "pre_loaded_fixtures requires use_transactional_tests" - end - - @fixture_cache = {} - @fixture_connections = [] - @@already_loaded_fixtures ||= {} - @connection_subscriber = nil - - # Load fixtures once and begin transaction. - if run_in_transaction? - if @@already_loaded_fixtures[self.class] - @loaded_fixtures = @@already_loaded_fixtures[self.class] - else - @loaded_fixtures = load_fixtures(config) - @@already_loaded_fixtures[self.class] = @loaded_fixtures - end - - # Begin transactions for connections already established - @fixture_connections = enlist_fixture_connections - @fixture_connections.each do |connection| - connection.begin_transaction joinable: false - connection.pool.lock_thread = true - end - - # When connections are established in the future, begin a transaction too - @connection_subscriber = ActiveSupport::Notifications.subscribe("!connection.active_record") do |_, _, _, _, payload| - spec_name = payload[:spec_name] if payload.key?(:spec_name) - - if spec_name - begin - connection = ActiveRecord::Base.connection_handler.retrieve_connection(spec_name) - rescue ConnectionNotEstablished - connection = nil - end - - if connection && !@fixture_connections.include?(connection) - connection.begin_transaction joinable: false - connection.pool.lock_thread = true - @fixture_connections << connection - end - end - end - - # Load fixtures for every test. - else - ActiveRecord::FixtureSet.reset_cache - @@already_loaded_fixtures[self.class] = nil - @loaded_fixtures = load_fixtures(config) - end - - # Instantiate fixtures for every test if requested. - instantiate_fixtures if use_instantiated_fixtures - end - - def teardown_fixtures - # Rollback changes if a transaction is active. - if run_in_transaction? - ActiveSupport::Notifications.unsubscribe(@connection_subscriber) if @connection_subscriber - @fixture_connections.each do |connection| - connection.rollback_transaction if connection.transaction_open? - connection.pool.lock_thread = false - end - @fixture_connections.clear - else - ActiveRecord::FixtureSet.reset_cache - end - - ActiveRecord::Base.clear_active_connections! - end - - def enlist_fixture_connections - ActiveRecord::Base.connection_handler.connection_pool_list.map(&:connection) - end - - private - def load_fixtures(config) - fixtures = ActiveRecord::FixtureSet.create_fixtures(fixture_path, fixture_table_names, fixture_class_names, config) - Hash[fixtures.map { |f| [f.name, f] }] - end - - def instantiate_fixtures - if pre_loaded_fixtures - raise RuntimeError, "Load fixtures before instantiating them." if ActiveRecord::FixtureSet.all_loaded_fixtures.empty? - ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?) - else - raise RuntimeError, "Load fixtures before instantiating them." if @loaded_fixtures.nil? - @loaded_fixtures.each_value do |fixture_set| - ActiveRecord::FixtureSet.instantiate_fixtures(self, fixture_set, load_instances?) - end - end - end - - def load_instances? - use_instantiated_fixtures != :no_instances - end - end -end - -class ActiveRecord::FixtureSet::RenderContext # :nodoc: - def self.create_subclass - Class.new ActiveRecord::FixtureSet.context_class do - def get_binding - binding() - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/gem_version.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/gem_version.rb deleted file mode 100644 index 53a743db3c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - # Returns the version of the currently loaded Active Record as a Gem::Version - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/inheritance.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/inheritance.rb deleted file mode 100644 index fbdaeaae51..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/inheritance.rb +++ /dev/null @@ -1,253 +0,0 @@ -require "active_support/core_ext/hash/indifferent_access" - -module ActiveRecord - # == Single table inheritance - # - # Active Record allows inheritance by storing the name of the class in a column that by - # default is named "type" (can be changed by overwriting Base.inheritance_column). - # This means that an inheritance looking like this: - # - # class Company < ActiveRecord::Base; end - # class Firm < Company; end - # class Client < Company; end - # class PriorityClient < Client; end - # - # When you do Firm.create(name: "37signals"), this record will be saved in - # the companies table with type = "Firm". You can then fetch this row again using - # Company.where(name: '37signals').first and it will return a Firm object. - # - # Be aware that because the type column is an attribute on the record every new - # subclass will instantly be marked as dirty and the type column will be included - # in the list of changed attributes on the record. This is different from non - # Single Table Inheritance(STI) classes: - # - # Company.new.changed? # => false - # Firm.new.changed? # => true - # Firm.new.changes # => {"type"=>["","Firm"]} - # - # 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 like normal subclasses with no special magic - # for differentiating between them or reloading the right type with find. - # - # Note, all the attributes for all the cases are kept in the same table. Read more: - # http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html - # - module Inheritance - extend ActiveSupport::Concern - - included do - # Determines whether to store the full constant name including namespace when using STI. - # This is true, by default. - class_attribute :store_full_sti_class, instance_writer: false - self.store_full_sti_class = true - end - - module ClassMethods - # Determines if one of the attributes passed in is the inheritance column, - # and if the inheritance column is attr accessible, it initializes an - # instance of the given subclass instead of the base class. - def new(*args, &block) - if abstract_class? || self == Base - raise NotImplementedError, "#{self} is an abstract class and cannot be instantiated." - end - - attrs = args.first - if has_attribute?(inheritance_column) - subclass = subclass_from_attributes(attrs) - - if subclass.nil? && base_class == self - subclass = subclass_from_attributes(column_defaults) - end - end - - if subclass && subclass != self - subclass.new(*args, &block) - else - super - end - end - - # Returns +true+ if this does not need STI type condition. Returns - # +false+ if STI type condition needs to be applied. - def descends_from_active_record? - if self == Base - false - elsif superclass.abstract_class? - superclass.descends_from_active_record? - else - superclass == Base || !columns_hash.include?(inheritance_column) - end - end - - def finder_needs_type_condition? #:nodoc: - # This is like this because benchmarking justifies the strange :false stuff - :true == (@finder_needs_type_condition ||= descends_from_active_record? ? :false : :true) - end - - # Returns the class descending directly from ActiveRecord::Base, or - # an abstract class, if any, in the inheritance hierarchy. - # - # If A extends ActiveRecord::Base, A.base_class will return A. If B descends from A - # through some arbitrarily deep hierarchy, B.base_class will return A. - # - # If B < A and C < B and if A is an abstract_class then both B.base_class - # and C.base_class would return B as the answer since A is an abstract_class. - def base_class - unless self < Base - raise ActiveRecordError, "#{name} doesn't belong in a hierarchy descending from ActiveRecord" - end - - if superclass == Base || superclass.abstract_class? - self - else - superclass.base_class - end - end - - # Set this to true if this is an abstract class (see abstract_class?). - # If you are using inheritance with ActiveRecord and don't want child classes - # to utilize the implied STI table name of the parent class, this will need to be true. - # For example, given the following: - # - # class SuperClass < ActiveRecord::Base - # self.abstract_class = true - # end - # class Child < SuperClass - # self.table_name = 'the_table_i_really_want' - # end - # - # - # self.abstract_class = true is required to make Child<.find,.create, or any Arel method> use the_table_i_really_want instead of a table called super_classes - # - attr_accessor :abstract_class - - # Returns whether this class is an abstract class or not. - def abstract_class? - defined?(@abstract_class) && @abstract_class == true - end - - def sti_name - store_full_sti_class ? name : name.demodulize - end - - def inherited(subclass) - subclass.instance_variable_set(:@_type_candidates_cache, Concurrent::Map.new) - super - end - - protected - - # Returns the class type of the record using the current module as a prefix. So descendants of - # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. - def compute_type(type_name) - if type_name.start_with?("::".freeze) - # If the type is prefixed with a scope operator then we assume that - # the type_name is an absolute reference. - ActiveSupport::Dependencies.constantize(type_name) - else - type_candidate = @_type_candidates_cache[type_name] - if type_candidate && type_constant = ActiveSupport::Dependencies.safe_constantize(type_candidate) - return type_constant - end - - # Build a list of candidates to search for - candidates = [] - name.scan(/::|$/) { candidates.unshift "#{$`}::#{type_name}" } - candidates << type_name - - candidates.each do |candidate| - constant = ActiveSupport::Dependencies.safe_constantize(candidate) - if candidate == constant.to_s - @_type_candidates_cache[type_name] = candidate - return constant - end - end - - raise NameError.new("uninitialized constant #{candidates.first}", candidates.first) - end - end - - private - - # Called by +instantiate+ to decide which class to use for a new - # record instance. For single-table inheritance, we check the record - # for a +type+ column and return the corresponding class. - def discriminate_class_for_record(record) - if using_single_table_inheritance?(record) - find_sti_class(record[inheritance_column]) - else - super - end - end - - def using_single_table_inheritance?(record) - record[inheritance_column].present? && has_attribute?(inheritance_column) - end - - def find_sti_class(type_name) - type_name = base_class.type_for_attribute(inheritance_column).cast(type_name) - subclass = begin - if store_full_sti_class - ActiveSupport::Dependencies.constantize(type_name) - else - compute_type(type_name) - end - rescue NameError - raise SubclassNotFound, - "The single-table inheritance mechanism failed to locate the subclass: '#{type_name}'. " \ - "This error is raised because the column '#{inheritance_column}' is reserved for storing the class in case of inheritance. " \ - "Please rename this column if you didn't intend it to be used for storing the inheritance class " \ - "or overwrite #{name}.inheritance_column to use another column for that information." - end - unless subclass == self || descendants.include?(subclass) - raise SubclassNotFound, "Invalid single-table inheritance type: #{subclass.name} is not a subclass of #{name}" - end - subclass - end - - def type_condition(table = arel_table) - sti_column = arel_attribute(inheritance_column, table) - sti_names = ([self] + descendants).map(&:sti_name) - - sti_column.in(sti_names) - end - - # Detect the subclass from the inheritance column of attrs. If the inheritance column value - # is not self or a valid subclass, raises ActiveRecord::SubclassNotFound - def subclass_from_attributes(attrs) - attrs = attrs.to_h if attrs.respond_to?(:permitted?) - if attrs.is_a?(Hash) - subclass_name = attrs.with_indifferent_access[inheritance_column] - - if subclass_name.present? - find_sti_class(subclass_name) - end - end - end - end - - def initialize_dup(other) - super - ensure_proper_type - end - - private - - def initialize_internals_callback - super - ensure_proper_type - end - - # Sets the attribute used for single table inheritance to this class name if this is not the - # ActiveRecord::Base descendant. - # Considering the hierarchy Reply < Message < ActiveRecord::Base, this makes it possible to - # do Reply.new without having to set Reply[Reply.inheritance_column] = "Reply" yourself. - # No such attribute would be set for objects of the Message class in that example. - def ensure_proper_type - klass = self.class - if klass.finder_needs_type_condition? - write_attribute(klass.inheritance_column, klass.sti_name) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/integration.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/integration.rb deleted file mode 100644 index 8e71b60b29..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/integration.rb +++ /dev/null @@ -1,116 +0,0 @@ -require "active_support/core_ext/string/filters" - -module ActiveRecord - module Integration - extend ActiveSupport::Concern - - included do - ## - # :singleton-method: - # Indicates the format used to generate the timestamp in the cache key. - # Accepts any of the symbols in Time::DATE_FORMATS. - # - # This is +:usec+, by default. - class_attribute :cache_timestamp_format, instance_writer: false - self.cache_timestamp_format = :usec - end - - # Returns a +String+, which Action Pack uses for constructing a URL to this - # object. The default implementation returns this record's id as a +String+, - # or +nil+ if this record's unsaved. - # - # For example, suppose that you have a User model, and that you have a - # resources :users route. Normally, +user_path+ will - # construct a path with the user object's 'id' in it: - # - # user = User.find_by(name: 'Phusion') - # user_path(user) # => "/users/1" - # - # You can override +to_param+ in your model to make +user_path+ construct - # a path using the user's name instead of the user's id: - # - # class User < ActiveRecord::Base - # def to_param # overridden - # name - # end - # end - # - # user = User.find_by(name: 'Phusion') - # user_path(user) # => "/users/Phusion" - def to_param - # We can't use alias_method here, because method 'id' optimizes itself on the fly. - id && id.to_s # Be sure to stringify the id for routes - end - - # Returns a cache key that can be used to identify this record. - # - # Product.new.cache_key # => "products/new" - # Product.find(5).cache_key # => "products/5" (updated_at not available) - # Person.find(5).cache_key # => "people/5-20071224150000" (updated_at available) - # - # You can also pass a list of named timestamps, and the newest in the list will be - # used to generate the key: - # - # Person.find(5).cache_key(:updated_at, :last_reviewed_at) - def cache_key(*timestamp_names) - if new_record? - "#{model_name.cache_key}/new" - else - timestamp = if timestamp_names.any? - max_updated_column_timestamp(timestamp_names) - else - max_updated_column_timestamp - end - - if timestamp - timestamp = timestamp.utc.to_s(cache_timestamp_format) - "#{model_name.cache_key}/#{id}-#{timestamp}" - else - "#{model_name.cache_key}/#{id}" - end - end - end - - module ClassMethods - # Defines your model's +to_param+ method to generate "pretty" URLs - # using +method_name+, which can be any attribute or method that - # responds to +to_s+. - # - # class User < ActiveRecord::Base - # to_param :name - # end - # - # user = User.find_by(name: 'Fancy Pants') - # user.id # => 123 - # user_path(user) # => "/users/123-fancy-pants" - # - # Values longer than 20 characters will be truncated. The value - # is truncated word by word. - # - # user = User.find_by(name: 'David Heinemeier Hansson') - # user.id # => 125 - # user_path(user) # => "/users/125-david-heinemeier" - # - # Because the generated param begins with the record's +id+, it is - # suitable for passing to +find+. In a controller, for example: - # - # params[:id] # => "123-fancy-pants" - # User.find(params[:id]).id # => 123 - def to_param(method_name = nil) - if method_name.nil? - super() - else - define_method :to_param do - if (default = super()) && - (result = send(method_name).to_s).present? && - (param = result.squish.parameterize.truncate(20, separator: /-/, omission: "")).present? - "#{default}-#{param}" - else - default - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/internal_metadata.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/internal_metadata.rb deleted file mode 100644 index 25ee9d6bfe..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/internal_metadata.rb +++ /dev/null @@ -1,43 +0,0 @@ -require "active_record/scoping/default" -require "active_record/scoping/named" - -module ActiveRecord - # This class is used to create a table that keeps track of values and keys such - # as which environment migrations were run in. - class InternalMetadata < ActiveRecord::Base # :nodoc: - class << self - def primary_key - "key" - end - - def table_name - "#{table_name_prefix}#{ActiveRecord::Base.internal_metadata_table_name}#{table_name_suffix}" - end - - def []=(key, value) - find_or_initialize_by(key: key).update_attributes!(value: value) - end - - def [](key) - where(key: key).pluck(:value).first - end - - def table_exists? - connection.table_exists?(table_name) - end - - # Creates an internal metadata table with columns +key+ and +value+ - def create_table - unless table_exists? - key_options = connection.internal_string_options_for_primary_key - - connection.create_table(table_name, id: false) do |t| - t.string :key, key_options - t.string :value - t.timestamps - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/legacy_yaml_adapter.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/legacy_yaml_adapter.rb deleted file mode 100644 index c7683f68c7..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/legacy_yaml_adapter.rb +++ /dev/null @@ -1,46 +0,0 @@ -module ActiveRecord - module LegacyYamlAdapter - def self.convert(klass, coder) - return coder unless coder.is_a?(Psych::Coder) - - case coder["active_record_yaml_version"] - when 1, 2 then coder - else - if coder["attributes"].is_a?(AttributeSet) - Rails420.convert(klass, coder) - else - Rails41.convert(klass, coder) - end - end - end - - module Rails420 - def self.convert(klass, coder) - attribute_set = coder["attributes"] - - klass.attribute_names.each do |attr_name| - attribute = attribute_set[attr_name] - if attribute.type.is_a?(Delegator) - type_from_klass = klass.type_for_attribute(attr_name) - attribute_set[attr_name] = attribute.with_type(type_from_klass) - end - end - - coder - end - end - - module Rails41 - def self.convert(klass, coder) - attributes = klass.attributes_builder - .build_from_database(coder["attributes"]) - new_record = coder["attributes"][klass.primary_key].blank? - - { - "attributes" => attributes, - "new_record" => new_record, - } - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/locale/en.yml b/debian/gems-compat/activerecord-5.1.7/lib/active_record/locale/en.yml deleted file mode 100644 index 0b35027b2b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/locale/en.yml +++ /dev/null @@ -1,48 +0,0 @@ -en: - # Attributes names common to most models - #attributes: - #created_at: "Created at" - #updated_at: "Updated at" - - # Default error messages - errors: - messages: - required: "must exist" - taken: "has already been taken" - - # Active Record models configuration - activerecord: - errors: - messages: - record_invalid: "Validation failed: %{errors}" - restrict_dependent_destroy: - has_one: "Cannot delete record because a dependent %{record} exists" - has_many: "Cannot delete record because dependent %{record} exist" - # Append your own errors here or at the model/attributes scope. - - # You can define own errors for models or model attributes. - # The values :model, :attribute and :value are always available for interpolation. - # - # For example, - # models: - # user: - # blank: "This is a custom blank message for %{model}: %{attribute}" - # attributes: - # login: - # blank: "This is a custom blank message for User login" - # Will define custom blank validation message for User model and - # custom blank validation message for login attribute of User model. - #models: - - # Translate model names. Used in Model.human_name(). - #models: - # For example, - # user: "Dude" - # will translate User model name to "Dude" - - # Translate model attribute names. Used in Model.human_attribute_name(attribute). - #attributes: - # For example, - # user: - # login: "Handle" - # will translate User attribute "login" as "Handle" diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/locking/optimistic.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/locking/optimistic.rb deleted file mode 100644 index e3b1049d87..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/locking/optimistic.rb +++ /dev/null @@ -1,201 +0,0 @@ -module ActiveRecord - module Locking - # == What is Optimistic Locking - # - # Optimistic locking allows multiple users to access the same record for edits, and assumes a minimum of - # conflicts with the data. It does this by checking whether another process has made changes to a record since - # it was opened, an ActiveRecord::StaleObjectError exception is thrown if that has occurred - # and the update is ignored. - # - # Check out ActiveRecord::Locking::Pessimistic for an alternative. - # - # == Usage - # - # Active Record supports optimistic locking if the +lock_version+ field is present. Each update to the - # record increments the +lock_version+ column and the locking facilities ensure that records instantiated twice - # will let the last one saved raise a +StaleObjectError+ if the first was also updated. Example: - # - # p1 = Person.find(1) - # p2 = Person.find(1) - # - # p1.first_name = "Michael" - # p1.save - # - # p2.first_name = "should fail" - # p2.save # Raises an ActiveRecord::StaleObjectError - # - # Optimistic locking will also check for stale data when objects are destroyed. Example: - # - # p1 = Person.find(1) - # p2 = Person.find(1) - # - # p1.first_name = "Michael" - # p1.save - # - # p2.destroy # Raises an ActiveRecord::StaleObjectError - # - # You're then responsible for dealing with the conflict by rescuing the exception and either rolling back, merging, - # or otherwise apply the business logic needed to resolve the conflict. - # - # This locking mechanism will function inside a single Ruby process. To make it work across all - # web requests, the recommended approach is to add +lock_version+ as a hidden field to your form. - # - # This behavior can be turned off by setting ActiveRecord::Base.lock_optimistically = false. - # To override the name of the +lock_version+ column, set the locking_column class attribute: - # - # class Person < ActiveRecord::Base - # self.locking_column = :lock_person - # end - # - module Optimistic - extend ActiveSupport::Concern - - included do - class_attribute :lock_optimistically, instance_writer: false - self.lock_optimistically = true - end - - def locking_enabled? #:nodoc: - self.class.locking_enabled? - end - - private - def _create_record(attribute_names = self.attribute_names, *) - if locking_enabled? - # We always want to persist the locking version, even if we don't detect - # a change from the default, since the database might have no default - attribute_names |= [self.class.locking_column] - end - super - end - - def _touch_row(attribute_names, time) - super - ensure - clear_attribute_change(self.class.locking_column) if locking_enabled? - end - - def _update_row(attribute_names, attempted_action = "update") - return super unless locking_enabled? - - begin - locking_column = self.class.locking_column - previous_lock_value = read_attribute_before_type_cast(locking_column) - attribute_names << locking_column - - self[locking_column] += 1 - - affected_rows = self.class.unscoped._update_record( - arel_attributes_with_values(attribute_names), - self.class.primary_key => id_in_database, - locking_column => previous_lock_value - ) - - if affected_rows != 1 - raise ActiveRecord::StaleObjectError.new(self, attempted_action) - end - - affected_rows - - # If something went wrong, revert the locking_column value. - rescue Exception - self[locking_column] = previous_lock_value.to_i - raise - end - end - - def destroy_row - affected_rows = super - - if locking_enabled? && affected_rows != 1 - raise ActiveRecord::StaleObjectError.new(self, "destroy") - end - - affected_rows - end - - def relation_for_destroy - relation = super - - if locking_enabled? - locking_column = self.class.locking_column - relation = relation.where(locking_column => read_attribute_before_type_cast(locking_column)) - end - - relation - end - - module ClassMethods - DEFAULT_LOCKING_COLUMN = "lock_version" - - # Returns true if the +lock_optimistically+ flag is set to true - # (which it is, by default) and the table includes the - # +locking_column+ column (defaults to +lock_version+). - def locking_enabled? - lock_optimistically && columns_hash[locking_column] - end - - # Set the column to use for optimistic locking. Defaults to +lock_version+. - def locking_column=(value) - reload_schema_from_cache - @locking_column = value.to_s - end - - # The version column used for optimistic locking. Defaults to +lock_version+. - def locking_column - @locking_column = DEFAULT_LOCKING_COLUMN unless defined?(@locking_column) - @locking_column - end - - # Reset the column used for optimistic locking back to the +lock_version+ default. - def reset_locking_column - self.locking_column = DEFAULT_LOCKING_COLUMN - end - - # Make sure the lock version column gets updated when counters are - # updated. - def update_counters(id, counters) - counters = counters.merge(locking_column => 1) if locking_enabled? - super - end - - private - - # We need to apply this decorator here, rather than on module inclusion. The closure - # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the - # sub class being decorated. As such, changes to `lock_optimistically`, or - # `locking_column` would not be picked up. - def inherited(subclass) - subclass.class_eval do - is_lock_column = ->(name, _) { lock_optimistically && name == locking_column } - decorate_matching_attribute_types(is_lock_column, :_optimistic_locking) do |type| - LockingType.new(type) - end - end - super - end - end - end - - # In de/serialize we change `nil` to 0, so that we can allow passing - # `nil` values to `lock_version`, and not result in `ActiveRecord::StaleObjectError` - # during update record. - class LockingType < DelegateClass(Type::Value) # :nodoc: - def deserialize(value) - super.to_i - end - - def serialize(value) - super.to_i - end - - def init_with(coder) - __setobj__(coder["subtype"]) - end - - def encode_with(coder) - coder["subtype"] = __getobj__ - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/locking/pessimistic.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/locking/pessimistic.rb deleted file mode 100644 index 34ae3729c4..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/locking/pessimistic.rb +++ /dev/null @@ -1,86 +0,0 @@ -module ActiveRecord - module Locking - # Locking::Pessimistic provides support for row-level locking using - # SELECT ... FOR UPDATE and other lock types. - # - # Chain ActiveRecord::Base#find to ActiveRecord::QueryMethods#lock to obtain an exclusive - # lock on the selected rows: - # # select * from accounts where id=1 for update - # Account.lock.find(1) - # - # Call lock('some locking clause') to use a database-specific locking clause - # of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example: - # - # Account.transaction do - # # select * from accounts where name = 'shugo' limit 1 for update - # shugo = Account.where("name = 'shugo'").lock(true).first - # yuko = Account.where("name = 'yuko'").lock(true).first - # shugo.balance -= 100 - # shugo.save! - # yuko.balance += 100 - # yuko.save! - # end - # - # You can also use ActiveRecord::Base#lock! method to lock one record by id. - # This may be better if you don't need to lock every row. Example: - # - # Account.transaction do - # # select * from accounts where ... - # accounts = Account.where(...) - # account1 = accounts.detect { |account| ... } - # account2 = accounts.detect { |account| ... } - # # select * from accounts where id=? for update - # account1.lock! - # account2.lock! - # account1.balance -= 100 - # account1.save! - # account2.balance += 100 - # account2.save! - # end - # - # You can start a transaction and acquire the lock in one go by calling - # with_lock with a block. The block is called from within - # a transaction, the object is already locked. Example: - # - # account = Account.first - # account.with_lock do - # # This block is called within a transaction, - # # account is already locked. - # account.balance -= 100 - # account.save! - # end - # - # Database-specific information on row locking: - # MySQL: http://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html - # PostgreSQL: http://www.postgresql.org/docs/current/interactive/sql-select.html#SQL-FOR-UPDATE-SHARE - module Pessimistic - # Obtain a row lock on this record. Reloads the record to obtain the requested - # lock. Pass an SQL locking clause to append the end of the SELECT statement - # or pass true for "FOR UPDATE" (the default, an exclusive row lock). Returns - # the locked record. - def lock!(lock = true) - if persisted? - if has_changes_to_save? - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Locking a record with unpersisted changes is deprecated and will raise an - exception in Rails 5.2. Use `save` to persist the changes, or `reload` to - discard them explicitly. - MSG - end - reload(lock: lock) - end - self - end - - # Wraps the passed block in a transaction, locking the object - # before yielding. You can pass the SQL locking clause - # as argument (see lock!). - def with_lock(lock = true) - transaction do - lock!(lock) - yield - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/log_subscriber.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/log_subscriber.rb deleted file mode 100644 index e39ca5f6dc..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/log_subscriber.rb +++ /dev/null @@ -1,94 +0,0 @@ -module ActiveRecord - class LogSubscriber < ActiveSupport::LogSubscriber - IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"] - - def self.runtime=(value) - ActiveRecord::RuntimeRegistry.sql_runtime = value - end - - def self.runtime - ActiveRecord::RuntimeRegistry.sql_runtime ||= 0 - end - - def self.reset_runtime - rt, self.runtime = runtime, 0 - rt - end - - def sql(event) - self.class.runtime += event.duration - return unless logger.debug? - - payload = event.payload - - return if IGNORE_PAYLOAD_NAMES.include?(payload[:name]) - - name = "#{payload[:name]} (#{event.duration.round(1)}ms)" - name = "CACHE #{name}" if payload[:cached] - sql = payload[:sql] - binds = nil - - unless (payload[:binds] || []).empty? - casted_params = type_casted_binds(payload[:type_casted_binds]) - binds = " " + payload[:binds].zip(casted_params).map { |attr, value| - render_bind(attr, value) - }.inspect - end - - name = colorize_payload_name(name, payload[:name]) - sql = color(sql, sql_color(sql), true) - - debug " #{name} #{sql}#{binds}" - end - - private - def type_casted_binds(casted_binds) - casted_binds.respond_to?(:call) ? casted_binds.call : casted_binds - end - - def render_bind(attr, value) - if attr.is_a?(Array) - attr = attr.first - elsif attr.type.binary? && attr.value - value = "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>" - end - - [attr && attr.name, value] - end - - def colorize_payload_name(name, payload_name) - if payload_name.blank? || payload_name == "SQL" # SQL vs Model Load/Exists - color(name, MAGENTA, true) - else - color(name, CYAN, true) - end - end - - def sql_color(sql) - case sql - when /\A\s*rollback/mi - RED - when /select .*for update/mi, /\A\s*lock/mi - WHITE - when /\A\s*select/i - BLUE - when /\A\s*insert/i - GREEN - when /\A\s*update/i - YELLOW - when /\A\s*delete/i - RED - when /transaction\s*\Z/i - CYAN - else - MAGENTA - end - end - - def logger - ActiveRecord::Base.logger - end - end -end - -ActiveRecord::LogSubscriber.attach_to :active_record diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration.rb deleted file mode 100644 index 4e1df1432c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration.rb +++ /dev/null @@ -1,1328 +0,0 @@ -require "set" -require "zlib" -require "active_support/core_ext/module/attribute_accessors" - -module ActiveRecord - class MigrationError < ActiveRecordError#:nodoc: - def initialize(message = nil) - message = "\n\n#{message}\n\n" if message - super - end - end - - # Exception that can be raised to stop migrations from being rolled back. - # For example the following migration is not reversible. - # Rolling back this migration will raise an ActiveRecord::IrreversibleMigration error. - # - # class IrreversibleMigrationExample < ActiveRecord::Migration[5.0] - # def change - # create_table :distributors do |t| - # t.string :zipcode - # end - # - # execute <<-SQL - # ALTER TABLE distributors - # ADD CONSTRAINT zipchk - # CHECK (char_length(zipcode) = 5) NO INHERIT; - # SQL - # end - # end - # - # There are two ways to mitigate this problem. - # - # 1. Define #up and #down methods instead of #change: - # - # class ReversibleMigrationExample < ActiveRecord::Migration[5.0] - # def up - # create_table :distributors do |t| - # t.string :zipcode - # end - # - # execute <<-SQL - # ALTER TABLE distributors - # ADD CONSTRAINT zipchk - # CHECK (char_length(zipcode) = 5) NO INHERIT; - # SQL - # end - # - # def down - # execute <<-SQL - # ALTER TABLE distributors - # DROP CONSTRAINT zipchk - # SQL - # - # drop_table :distributors - # end - # end - # - # 2. Use the #reversible method in #change method: - # - # class ReversibleMigrationExample < ActiveRecord::Migration[5.0] - # def change - # create_table :distributors do |t| - # t.string :zipcode - # end - # - # reversible do |dir| - # dir.up do - # execute <<-SQL - # ALTER TABLE distributors - # ADD CONSTRAINT zipchk - # CHECK (char_length(zipcode) = 5) NO INHERIT; - # SQL - # end - # - # dir.down do - # execute <<-SQL - # ALTER TABLE distributors - # DROP CONSTRAINT zipchk - # SQL - # end - # end - # end - # end - class IrreversibleMigration < MigrationError - end - - class DuplicateMigrationVersionError < MigrationError#:nodoc: - def initialize(version = nil) - if version - super("Multiple migrations have the version number #{version}.") - else - super("Duplicate migration version error.") - end - end - end - - class DuplicateMigrationNameError < MigrationError#:nodoc: - def initialize(name = nil) - if name - super("Multiple migrations have the name #{name}.") - else - super("Duplicate migration name.") - end - end - end - - class UnknownMigrationVersionError < MigrationError #:nodoc: - def initialize(version = nil) - if version - super("No migration with version number #{version}.") - else - super("Unknown migration version.") - end - end - end - - class IllegalMigrationNameError < MigrationError#:nodoc: - def initialize(name = nil) - if name - super("Illegal name for migration file: #{name}\n\t(only lower case letters, numbers, and '_' allowed).") - else - super("Illegal name for migration.") - end - end - end - - class PendingMigrationError < MigrationError#:nodoc: - def initialize(message = nil) - if !message && defined?(Rails.env) - super("Migrations are pending. To resolve this issue, run:\n\n bin/rails db:migrate RAILS_ENV=#{::Rails.env}") - elsif !message - super("Migrations are pending. To resolve this issue, run:\n\n bin/rails db:migrate") - else - super - end - end - end - - class ConcurrentMigrationError < MigrationError #:nodoc: - DEFAULT_MESSAGE = "Cannot run migrations because another migration process is currently running.".freeze - - def initialize(message = DEFAULT_MESSAGE) - super - end - end - - class NoEnvironmentInSchemaError < MigrationError #:nodoc: - def initialize - msg = "Environment data not found in the schema. To resolve this issue, run: \n\n bin/rails db:environment:set" - if defined?(Rails.env) - super("#{msg} RAILS_ENV=#{::Rails.env}") - else - super(msg) - end - end - end - - class ProtectedEnvironmentError < ActiveRecordError #:nodoc: - def initialize(env = "production") - msg = "You are attempting to run a destructive action against your '#{env}' database.\n" - msg << "If you are sure you want to continue, run the same command with the environment variable:\n" - msg << "DISABLE_DATABASE_ENVIRONMENT_CHECK=1" - super(msg) - end - end - - class EnvironmentMismatchError < ActiveRecordError - def initialize(current: nil, stored: nil) - msg = "You are attempting to modify a database that was last run in `#{ stored }` environment.\n" - msg << "You are running in `#{ current }` environment. " - msg << "If you are sure you want to continue, first set the environment using:\n\n" - msg << " bin/rails db:environment:set" - if defined?(Rails.env) - super("#{msg} RAILS_ENV=#{::Rails.env}\n\n") - else - super("#{msg}\n\n") - end - end - end - - # = Active Record Migrations - # - # Migrations can manage the evolution of a schema used by several physical - # databases. It's a solution to the common problem of adding a field to make - # a new feature work in your local database, but being unsure of how to - # push that change to other developers and to the production server. With - # migrations, you can describe the transformations in self-contained classes - # that can be checked into version control systems and executed against - # another database that might be one, two, or five versions behind. - # - # Example of a simple migration: - # - # class AddSsl < ActiveRecord::Migration[5.0] - # def up - # add_column :accounts, :ssl_enabled, :boolean, default: true - # end - # - # def down - # remove_column :accounts, :ssl_enabled - # end - # end - # - # This migration will add a boolean flag to the accounts table and remove it - # if you're backing out of the migration. It shows how all migrations have - # two methods +up+ and +down+ that describes the transformations - # required to implement or remove the migration. These methods can consist - # of both the migration specific methods like +add_column+ and +remove_column+, - # but may also contain regular Ruby code for generating data needed for the - # transformations. - # - # Example of a more complex migration that also needs to initialize data: - # - # class AddSystemSettings < ActiveRecord::Migration[5.0] - # def up - # create_table :system_settings do |t| - # t.string :name - # t.string :label - # t.text :value - # t.string :type - # t.integer :position - # end - # - # SystemSetting.create name: 'notice', - # label: 'Use notice?', - # value: 1 - # end - # - # def down - # drop_table :system_settings - # end - # end - # - # This migration first adds the +system_settings+ table, then creates the very - # first row in it using the Active Record model that relies on the table. It - # also uses the more advanced +create_table+ syntax where you can specify a - # complete table schema in one block call. - # - # == Available transformations - # - # === Creation - # - # * create_join_table(table_1, table_2, options): Creates a join - # table having its name as the lexical order of the first two - # arguments. See - # ActiveRecord::ConnectionAdapters::SchemaStatements#create_join_table for - # details. - # * create_table(name, options): Creates a table called +name+ and - # makes the table object available to a block that can then add columns to it, - # following the same format as +add_column+. See example above. The options hash - # is for fragments like "DEFAULT CHARSET=UTF-8" that are appended to the create - # table definition. - # * add_column(table_name, column_name, type, options): Adds a new column - # to the table called +table_name+ - # named +column_name+ specified to be one of the following types: - # :string, :text, :integer, :float, - # :decimal, :datetime, :timestamp, :time, - # :date, :binary, :boolean. A default value can be - # specified by passing an +options+ hash like { default: 11 }. - # Other options include :limit and :null (e.g. - # { limit: 50, null: false }) -- see - # ActiveRecord::ConnectionAdapters::TableDefinition#column for details. - # * add_foreign_key(from_table, to_table, options): Adds a new - # foreign key. +from_table+ is the table with the key column, +to_table+ contains - # the referenced primary key. - # * add_index(table_name, column_names, options): Adds a new index - # with the name of the column. Other options include - # :name, :unique (e.g. - # { name: 'users_name_index', unique: true }) and :order - # (e.g. { order: { name: :desc } }). - # * add_reference(:table_name, :reference_name): Adds a new column - # +reference_name_id+ by default an integer. See - # ActiveRecord::ConnectionAdapters::SchemaStatements#add_reference for details. - # * add_timestamps(table_name, options): Adds timestamps (+created_at+ - # and +updated_at+) columns to +table_name+. - # - # === Modification - # - # * change_column(table_name, column_name, type, options): Changes - # the column to a different type using the same parameters as add_column. - # * change_column_default(table_name, column_name, default_or_changes): - # Sets a default value for +column_name+ defined by +default_or_changes+ on - # +table_name+. Passing a hash containing :from and :to - # as +default_or_changes+ will make this change reversible in the migration. - # * change_column_null(table_name, column_name, null, default = nil): - # Sets or removes a +NOT NULL+ constraint on +column_name+. The +null+ flag - # indicates whether the value can be +NULL+. See - # ActiveRecord::ConnectionAdapters::SchemaStatements#change_column_null for - # details. - # * change_table(name, options): Allows to make column alterations to - # the table called +name+. It makes the table object available to a block that - # can then add/remove columns, indexes or foreign keys to it. - # * rename_column(table_name, column_name, new_column_name): Renames - # a column but keeps the type and content. - # * rename_index(table_name, old_name, new_name): Renames an index. - # * rename_table(old_name, new_name): Renames the table called +old_name+ - # to +new_name+. - # - # === Deletion - # - # * drop_table(name): Drops the table called +name+. - # * drop_join_table(table_1, table_2, options): Drops the join table - # specified by the given arguments. - # * remove_column(table_name, column_name, type, options): Removes the column - # named +column_name+ from the table called +table_name+. - # * remove_columns(table_name, *column_names): Removes the given - # columns from the table definition. - # * remove_foreign_key(from_table, options_or_to_table): Removes the - # given foreign key from the table called +table_name+. - # * remove_index(table_name, column: column_names): Removes the index - # specified by +column_names+. - # * remove_index(table_name, name: index_name): Removes the index - # specified by +index_name+. - # * remove_reference(table_name, ref_name, options): Removes the - # reference(s) on +table_name+ specified by +ref_name+. - # * remove_timestamps(table_name, options): Removes the timestamp - # columns (+created_at+ and +updated_at+) from the table definition. - # - # == Irreversible transformations - # - # Some transformations are destructive in a manner that cannot be reversed. - # Migrations of that kind should raise an ActiveRecord::IrreversibleMigration - # exception in their +down+ method. - # - # == Running migrations from within Rails - # - # The Rails package has several tools to help create and apply migrations. - # - # To generate a new migration, you can use - # rails generate migration MyNewMigration - # - # where MyNewMigration is the name of your migration. The generator will - # create an empty migration file timestamp_my_new_migration.rb - # in the db/migrate/ directory where timestamp is the - # UTC formatted date and time that the migration was generated. - # - # There is a special syntactic shortcut to generate migrations that add fields to a table. - # - # rails generate migration add_fieldname_to_tablename fieldname:string - # - # This will generate the file timestamp_add_fieldname_to_tablename.rb, which will look like this: - # class AddFieldnameToTablename < ActiveRecord::Migration[5.0] - # def change - # add_column :tablenames, :fieldname, :string - # end - # end - # - # To run migrations against the currently configured database, use - # rails db:migrate. This will update the database by running all of the - # pending migrations, creating the schema_migrations table - # (see "About the schema_migrations table" section below) if missing. It will also - # invoke the db:schema:dump task, which will update your db/schema.rb file - # to match the structure of your database. - # - # To roll the database back to a previous migration version, use - # rails db:migrate VERSION=X where X is the version to which - # you wish to downgrade. Alternatively, you can also use the STEP option if you - # wish to rollback last few migrations. rails db:migrate STEP=2 will rollback - # the latest two migrations. - # - # If any of the migrations throw an ActiveRecord::IrreversibleMigration exception, - # that step will fail and you'll have some manual work to do. - # - # == Database support - # - # Migrations are currently supported in MySQL, PostgreSQL, SQLite, - # SQL Server, and Oracle (all supported databases except DB2). - # - # == More examples - # - # Not all migrations change the schema. Some just fix the data: - # - # class RemoveEmptyTags < ActiveRecord::Migration[5.0] - # def up - # Tag.all.each { |tag| tag.destroy if tag.pages.empty? } - # end - # - # def down - # # not much we can do to restore deleted data - # raise ActiveRecord::IrreversibleMigration, "Can't recover the deleted tags" - # end - # end - # - # Others remove columns when they migrate up instead of down: - # - # class RemoveUnnecessaryItemAttributes < ActiveRecord::Migration[5.0] - # def up - # remove_column :items, :incomplete_items_count - # remove_column :items, :completed_items_count - # end - # - # def down - # add_column :items, :incomplete_items_count - # add_column :items, :completed_items_count - # end - # end - # - # And sometimes you need to do something in SQL not abstracted directly by migrations: - # - # class MakeJoinUnique < ActiveRecord::Migration[5.0] - # def up - # execute "ALTER TABLE `pages_linked_pages` ADD UNIQUE `page_id_linked_page_id` (`page_id`,`linked_page_id`)" - # end - # - # def down - # execute "ALTER TABLE `pages_linked_pages` DROP INDEX `page_id_linked_page_id`" - # end - # end - # - # == Using a model after changing its table - # - # Sometimes you'll want to add a column in a migration and populate it - # immediately after. In that case, you'll need to make a call to - # Base#reset_column_information in order to ensure that the model has the - # latest column data from after the new column was added. Example: - # - # class AddPeopleSalary < ActiveRecord::Migration[5.0] - # def up - # add_column :people, :salary, :integer - # Person.reset_column_information - # Person.all.each do |p| - # p.update_attribute :salary, SalaryCalculator.compute(p) - # end - # end - # end - # - # == Controlling verbosity - # - # By default, migrations will describe the actions they are taking, writing - # them to the console as they happen, along with benchmarks describing how - # long each step took. - # - # You can quiet them down by setting ActiveRecord::Migration.verbose = false. - # - # You can also insert your own messages and benchmarks by using the +say_with_time+ - # method: - # - # def up - # ... - # say_with_time "Updating salaries..." do - # Person.all.each do |p| - # p.update_attribute :salary, SalaryCalculator.compute(p) - # end - # end - # ... - # end - # - # The phrase "Updating salaries..." would then be printed, along with the - # benchmark for the block when the block completes. - # - # == Timestamped Migrations - # - # By default, Rails generates migrations that look like: - # - # 20080717013526_your_migration_name.rb - # - # The prefix is a generation timestamp (in UTC). - # - # If you'd prefer to use numeric prefixes, you can turn timestamped migrations - # off by setting: - # - # config.active_record.timestamped_migrations = false - # - # In application.rb. - # - # == Reversible Migrations - # - # Reversible migrations are migrations that know how to go +down+ for you. - # You simply supply the +up+ logic, and the Migration system figures out - # how to execute the down commands for you. - # - # To define a reversible migration, define the +change+ method in your - # migration like this: - # - # class TenderloveMigration < ActiveRecord::Migration[5.0] - # def change - # create_table(:horses) do |t| - # t.column :content, :text - # t.column :remind_at, :datetime - # end - # end - # end - # - # This migration will create the horses table for you on the way up, and - # automatically figure out how to drop the table on the way down. - # - # Some commands like +remove_column+ cannot be reversed. If you care to - # define how to move up and down in these cases, you should define the +up+ - # and +down+ methods as before. - # - # If a command cannot be reversed, an - # ActiveRecord::IrreversibleMigration exception will be raised when - # the migration is moving down. - # - # For a list of commands that are reversible, please see - # ActiveRecord::Migration::CommandRecorder. - # - # == Transactional Migrations - # - # If the database adapter supports DDL transactions, all migrations will - # automatically be wrapped in a transaction. There are queries that you - # can't execute inside a transaction though, and for these situations - # you can turn the automatic transactions off. - # - # class ChangeEnum < ActiveRecord::Migration[5.0] - # disable_ddl_transaction! - # - # def up - # execute "ALTER TYPE model_size ADD VALUE 'new_value'" - # end - # end - # - # Remember that you can still open your own transactions, even if you - # are in a Migration with self.disable_ddl_transaction!. - class Migration - autoload :CommandRecorder, "active_record/migration/command_recorder" - autoload :Compatibility, "active_record/migration/compatibility" - - # This must be defined before the inherited hook, below - class Current < Migration # :nodoc: - end - - def self.inherited(subclass) # :nodoc: - super - if subclass.superclass == Migration - raise StandardError, "Directly inheriting from ActiveRecord::Migration is not supported. " \ - "Please specify the Rails release the migration was written for:\n" \ - "\n" \ - " class #{subclass} < ActiveRecord::Migration[4.2]" - end - end - - def self.[](version) - Compatibility.find(version) - end - - def self.current_version - ActiveRecord::VERSION::STRING.to_f - end - - MigrationFilenameRegexp = /\A([0-9]+)_([_a-z0-9]*)\.?([_a-z0-9]*)?\.rb\z/ # :nodoc: - - # This class is used to verify that all migrations have been run before - # loading a web page if config.active_record.migration_error is set to :page_load - class CheckPending - def initialize(app) - @app = app - @last_check = 0 - end - - def call(env) - mtime = ActiveRecord::Migrator.last_migration.mtime.to_i - if @last_check < mtime - ActiveRecord::Migration.check_pending!(connection) - @last_check = mtime - end - @app.call(env) - end - - private - - def connection - ActiveRecord::Base.connection - end - end - - class << self - attr_accessor :delegate # :nodoc: - attr_accessor :disable_ddl_transaction # :nodoc: - - def nearest_delegate # :nodoc: - delegate || superclass.nearest_delegate - end - - # Raises ActiveRecord::PendingMigrationError error if any migrations are pending. - def check_pending!(connection = Base.connection) - raise ActiveRecord::PendingMigrationError if ActiveRecord::Migrator.needs_migration?(connection) - end - - def load_schema_if_pending! - if ActiveRecord::Migrator.needs_migration? || !ActiveRecord::Migrator.any_migrations? - # Roundtrip to Rake to allow plugins to hook into database initialization. - FileUtils.cd Rails.root do - current_config = Base.connection_config - Base.clear_all_connections! - system("bin/rails db:test:prepare") - # Establish a new connection, the old database may be gone (db:test:prepare uses purge) - Base.establish_connection(current_config) - end - check_pending! - end - end - - def maintain_test_schema! # :nodoc: - if ActiveRecord::Base.maintain_test_schema - suppress_messages { load_schema_if_pending! } - end - end - - def method_missing(name, *args, &block) # :nodoc: - nearest_delegate.send(name, *args, &block) - end - - def migrate(direction) - new.migrate direction - end - - # Disable the transaction wrapping this migration. - # You can still create your own transactions even after calling #disable_ddl_transaction! - # - # For more details read the {"Transactional Migrations" section above}[rdoc-ref:Migration]. - def disable_ddl_transaction! - @disable_ddl_transaction = true - end - end - - def disable_ddl_transaction # :nodoc: - self.class.disable_ddl_transaction - end - - cattr_accessor :verbose - attr_accessor :name, :version - - def initialize(name = self.class.name, version = nil) - @name = name - @version = version - @connection = nil - end - - self.verbose = true - # instantiate the delegate object after initialize is defined - self.delegate = new - - # Reverses the migration commands for the given block and - # the given migrations. - # - # The following migration will remove the table 'horses' - # and create the table 'apples' on the way up, and the reverse - # on the way down. - # - # class FixTLMigration < ActiveRecord::Migration[5.0] - # def change - # revert do - # create_table(:horses) do |t| - # t.text :content - # t.datetime :remind_at - # end - # end - # create_table(:apples) do |t| - # t.string :variety - # end - # end - # end - # - # Or equivalently, if +TenderloveMigration+ is defined as in the - # documentation for Migration: - # - # require_relative '20121212123456_tenderlove_migration' - # - # class FixupTLMigration < ActiveRecord::Migration[5.0] - # def change - # revert TenderloveMigration - # - # create_table(:apples) do |t| - # t.string :variety - # end - # end - # end - # - # This command can be nested. - def revert(*migration_classes) - run(*migration_classes.reverse, revert: true) unless migration_classes.empty? - if block_given? - if connection.respond_to? :revert - connection.revert { yield } - else - recorder = CommandRecorder.new(connection) - @connection = recorder - suppress_messages do - connection.revert { yield } - end - @connection = recorder.delegate - recorder.commands.each do |cmd, args, block| - send(cmd, *args, &block) - end - end - end - end - - def reverting? - connection.respond_to?(:reverting) && connection.reverting - end - - ReversibleBlockHelper = Struct.new(:reverting) do # :nodoc: - def up - yield unless reverting - end - - def down - yield if reverting - end - end - - # Used to specify an operation that can be run in one direction or another. - # Call the methods +up+ and +down+ of the yielded object to run a block - # only in one given direction. - # The whole block will be called in the right order within the migration. - # - # In the following example, the looping on users will always be done - # when the three columns 'first_name', 'last_name' and 'full_name' exist, - # even when migrating down: - # - # class SplitNameMigration < ActiveRecord::Migration[5.0] - # def change - # add_column :users, :first_name, :string - # add_column :users, :last_name, :string - # - # reversible do |dir| - # User.reset_column_information - # User.all.each do |u| - # dir.up { u.first_name, u.last_name = u.full_name.split(' ') } - # dir.down { u.full_name = "#{u.first_name} #{u.last_name}" } - # u.save - # end - # end - # - # revert { add_column :users, :full_name, :string } - # end - # end - def reversible - helper = ReversibleBlockHelper.new(reverting?) - execute_block { yield helper } - end - - # Runs the given migration classes. - # Last argument can specify options: - # - :direction (default is :up) - # - :revert (default is false) - def run(*migration_classes) - opts = migration_classes.extract_options! - dir = opts[:direction] || :up - dir = (dir == :down ? :up : :down) if opts[:revert] - if reverting? - # If in revert and going :up, say, we want to execute :down without reverting, so - revert { run(*migration_classes, direction: dir, revert: true) } - else - migration_classes.each do |migration_class| - migration_class.new.exec_migration(connection, dir) - end - end - end - - def up - self.class.delegate = self - return unless self.class.respond_to?(:up) - self.class.up - end - - def down - self.class.delegate = self - return unless self.class.respond_to?(:down) - self.class.down - end - - # Execute this migration in the named direction - def migrate(direction) - return unless respond_to?(direction) - - case direction - when :up then announce "migrating" - when :down then announce "reverting" - end - - time = nil - ActiveRecord::Base.connection_pool.with_connection do |conn| - time = Benchmark.measure do - exec_migration(conn, direction) - end - end - - case direction - when :up then announce "migrated (%.4fs)" % time.real; write - when :down then announce "reverted (%.4fs)" % time.real; write - end - end - - def exec_migration(conn, direction) - @connection = conn - if respond_to?(:change) - if direction == :down - revert { change } - else - change - end - else - send(direction) - end - ensure - @connection = nil - end - - def write(text = "") - puts(text) if verbose - end - - def announce(message) - text = "#{version} #{name}: #{message}" - length = [0, 75 - text.length].max - write "== %s %s" % [text, "=" * length] - end - - def say(message, subitem = false) - write "#{subitem ? " ->" : "--"} #{message}" - end - - def say_with_time(message) - say(message) - result = nil - time = Benchmark.measure { result = yield } - say "%.4fs" % time.real, :subitem - say("#{result} rows", :subitem) if result.is_a?(Integer) - result - end - - def suppress_messages - save, self.verbose = verbose, false - yield - ensure - self.verbose = save - end - - def connection - @connection || ActiveRecord::Base.connection - end - - def method_missing(method, *arguments, &block) - arg_list = arguments.map(&:inspect) * ", " - - say_with_time "#{method}(#{arg_list})" do - unless connection.respond_to? :revert - unless arguments.empty? || [:execute, :enable_extension, :disable_extension].include?(method) - arguments[0] = proper_table_name(arguments.first, table_name_options) - if [:rename_table, :add_foreign_key].include?(method) || - (method == :remove_foreign_key && !arguments.second.is_a?(Hash)) - arguments[1] = proper_table_name(arguments.second, table_name_options) - end - end - end - return super unless connection.respond_to?(method) - connection.send(method, *arguments, &block) - end - end - - def copy(destination, sources, options = {}) - copied = [] - - FileUtils.mkdir_p(destination) unless File.exist?(destination) - - destination_migrations = ActiveRecord::Migrator.migrations(destination) - last = destination_migrations.last - sources.each do |scope, path| - source_migrations = ActiveRecord::Migrator.migrations(path) - - source_migrations.each do |migration| - source = File.binread(migration.filename) - inserted_comment = "# This migration comes from #{scope} (originally #{migration.version})\n" - if /\A#.*\b(?:en)?coding:\s*\S+/ =~ source - # If we have a magic comment in the original migration, - # insert our comment after the first newline(end of the magic comment line) - # so the magic keep working. - # Note that magic comments must be at the first line(except sh-bang). - source[/\n/] = "\n#{inserted_comment}" - else - source = "#{inserted_comment}#{source}" - end - - if duplicate = destination_migrations.detect { |m| m.name == migration.name } - if options[:on_skip] && duplicate.scope != scope.to_s - options[:on_skip].call(scope, migration) - end - next - end - - migration.version = next_migration_number(last ? last.version + 1 : 0).to_i - new_path = File.join(destination, "#{migration.version}_#{migration.name.underscore}.#{scope}.rb") - old_path, migration.filename = migration.filename, new_path - last = migration - - File.binwrite(migration.filename, source) - copied << migration - options[:on_copy].call(scope, migration, old_path) if options[:on_copy] - destination_migrations << migration - end - end - - copied - end - - # Finds the correct table name given an Active Record object. - # Uses the Active Record object's own table_name, or pre/suffix from the - # options passed in. - def proper_table_name(name, options = {}) - if name.respond_to? :table_name - name.table_name - else - "#{options[:table_name_prefix]}#{name}#{options[:table_name_suffix]}" - end - end - - # Determines the version number of the next migration. - def next_migration_number(number) - if ActiveRecord::Base.timestamped_migrations - [Time.now.utc.strftime("%Y%m%d%H%M%S"), "%.14d" % number].max - else - SchemaMigration.normalize_migration_number(number) - end - end - - # Builds a hash for use in ActiveRecord::Migration#proper_table_name using - # the Active Record object's table_name prefix and suffix - def table_name_options(config = ActiveRecord::Base) #:nodoc: - { - table_name_prefix: config.table_name_prefix, - table_name_suffix: config.table_name_suffix - } - end - - private - def execute_block - if connection.respond_to? :execute_block - super # use normal delegation to record the block - else - yield - end - end - end - - # MigrationProxy is used to defer loading of the actual migration classes - # until they are needed - MigrationProxy = Struct.new(:name, :version, :filename, :scope) do - def initialize(name, version, filename, scope) - super - @migration = nil - end - - def basename - File.basename(filename) - end - - def mtime - File.mtime filename - end - - delegate :migrate, :announce, :write, :disable_ddl_transaction, to: :migration - - private - - def migration - @migration ||= load_migration - end - - def load_migration - require(File.expand_path(filename)) - name.constantize.new(name, version) - end - end - - class NullMigration < MigrationProxy #:nodoc: - def initialize - super(nil, 0, nil, nil) - end - - def mtime - 0 - end - end - - class Migrator#:nodoc: - class << self - attr_writer :migrations_paths - alias :migrations_path= :migrations_paths= - - def migrate(migrations_paths, target_version = nil, &block) - case - when target_version.nil? - up(migrations_paths, target_version, &block) - when current_version == 0 && target_version == 0 - [] - when current_version > target_version - down(migrations_paths, target_version, &block) - else - up(migrations_paths, target_version, &block) - end - end - - def rollback(migrations_paths, steps = 1) - move(:down, migrations_paths, steps) - end - - def forward(migrations_paths, steps = 1) - move(:up, migrations_paths, steps) - end - - def up(migrations_paths, target_version = nil) - migrations = migrations(migrations_paths) - migrations.select! { |m| yield m } if block_given? - - new(:up, migrations, target_version).migrate - end - - def down(migrations_paths, target_version = nil) - migrations = migrations(migrations_paths) - migrations.select! { |m| yield m } if block_given? - - new(:down, migrations, target_version).migrate - end - - def run(direction, migrations_paths, target_version) - new(direction, migrations(migrations_paths), target_version).run - end - - def open(migrations_paths) - new(:up, migrations(migrations_paths), nil) - end - - def schema_migrations_table_name - SchemaMigration.table_name - end - deprecate :schema_migrations_table_name - - def get_all_versions(connection = Base.connection) - if SchemaMigration.table_exists? - SchemaMigration.all_versions.map(&:to_i) - else - [] - end - end - - def current_version(connection = Base.connection) - get_all_versions(connection).max || 0 - end - - def needs_migration?(connection = Base.connection) - (migrations(migrations_paths).collect(&:version) - get_all_versions(connection)).size > 0 - end - - def any_migrations? - migrations(migrations_paths).any? - end - - def last_migration #:nodoc: - migrations(migrations_paths).last || NullMigration.new - end - - def migrations_paths - @migrations_paths ||= ["db/migrate"] - # just to not break things if someone uses: migrations_path = some_string - Array(@migrations_paths) - end - - def parse_migration_filename(filename) # :nodoc: - File.basename(filename).scan(Migration::MigrationFilenameRegexp).first - end - - def migrations(paths) - paths = Array(paths) - - migrations = migration_files(paths).map do |file| - version, name, scope = parse_migration_filename(file) - raise IllegalMigrationNameError.new(file) unless version - version = version.to_i - name = name.camelize - - MigrationProxy.new(name, version, file, scope) - end - - migrations.sort_by(&:version) - end - - def migrations_status(paths) - paths = Array(paths) - - db_list = ActiveRecord::SchemaMigration.normalized_versions - - file_list = migration_files(paths).map do |file| - version, name, scope = parse_migration_filename(file) - raise IllegalMigrationNameError.new(file) unless version - version = ActiveRecord::SchemaMigration.normalize_migration_number(version) - status = db_list.delete(version) ? "up" : "down" - [status, version, (name + scope).humanize] - end.compact - - db_list.map! do |version| - ["up", version, "********** NO FILE **********"] - end - - (db_list + file_list).sort_by { |_, version, _| version } - end - - def migration_files(paths) - Dir[*paths.flat_map { |path| "#{path}/**/[0-9]*_*.rb" }] - end - - private - - def move(direction, migrations_paths, steps) - migrator = new(direction, migrations(migrations_paths)) - start_index = migrator.migrations.index(migrator.current_migration) - - if start_index - finish = migrator.migrations[start_index + steps] - version = finish ? finish.version : 0 - send(direction, migrations_paths, version) - end - end - end - - def initialize(direction, migrations, target_version = nil) - @direction = direction - @target_version = target_version - @migrated_versions = nil - @migrations = migrations - - validate(@migrations) - - ActiveRecord::SchemaMigration.create_table - ActiveRecord::InternalMetadata.create_table - end - - def current_version - migrated.max || 0 - end - - def current_migration - migrations.detect { |m| m.version == current_version } - end - alias :current :current_migration - - def run - if use_advisory_lock? - with_advisory_lock { run_without_lock } - else - run_without_lock - end - end - - def migrate - if use_advisory_lock? - with_advisory_lock { migrate_without_lock } - else - migrate_without_lock - end - end - - def runnable - runnable = migrations[start..finish] - if up? - runnable.reject { |m| ran?(m) } - else - # skip the last migration if we're headed down, but not ALL the way down - runnable.pop if target - runnable.find_all { |m| ran?(m) } - end - end - - def migrations - down? ? @migrations.reverse : @migrations.sort_by(&:version) - end - - def pending_migrations - already_migrated = migrated - migrations.reject { |m| already_migrated.include?(m.version) } - end - - def migrated - @migrated_versions || load_migrated - end - - def load_migrated - @migrated_versions = Set.new(self.class.get_all_versions) - end - - private - - # Used for running a specific migration. - def run_without_lock - migration = migrations.detect { |m| m.version == @target_version } - raise UnknownMigrationVersionError.new(@target_version) if migration.nil? - result = execute_migration_in_transaction(migration, @direction) - - record_environment - result - end - - # Used for running multiple migrations up to or down to a certain value. - def migrate_without_lock - if invalid_target? - raise UnknownMigrationVersionError.new(@target_version) - end - - result = runnable.each do |migration| - execute_migration_in_transaction(migration, @direction) - end - - record_environment - result - end - - # Stores the current environment in the database. - def record_environment - return if down? - ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Migrator.current_environment - end - - def ran?(migration) - migrated.include?(migration.version.to_i) - end - - # Return true if a valid version is not provided. - def invalid_target? - !target && @target_version && @target_version > 0 - end - - def execute_migration_in_transaction(migration, direction) - return if down? && !migrated.include?(migration.version.to_i) - return if up? && migrated.include?(migration.version.to_i) - - Base.logger.info "Migrating to #{migration.name} (#{migration.version})" if Base.logger - - ddl_transaction(migration) do - migration.migrate(direction) - record_version_state_after_migrating(migration.version) - end - rescue => e - msg = "An error has occurred, " - msg << "this and " if use_transaction?(migration) - msg << "all later migrations canceled:\n\n#{e}" - raise StandardError, msg, e.backtrace - end - - def target - migrations.detect { |m| m.version == @target_version } - end - - def finish - migrations.index(target) || migrations.size - 1 - end - - def start - up? ? 0 : (migrations.index(current) || 0) - end - - def validate(migrations) - name , = migrations.group_by(&:name).find { |_, v| v.length > 1 } - raise DuplicateMigrationNameError.new(name) if name - - version , = migrations.group_by(&:version).find { |_, v| v.length > 1 } - raise DuplicateMigrationVersionError.new(version) if version - end - - def record_version_state_after_migrating(version) - if down? - migrated.delete(version) - ActiveRecord::SchemaMigration.where(version: version.to_s).delete_all - else - migrated << version - ActiveRecord::SchemaMigration.create!(version: version.to_s) - end - end - - def self.last_stored_environment - return nil if current_version == 0 - raise NoEnvironmentInSchemaError unless ActiveRecord::InternalMetadata.table_exists? - - environment = ActiveRecord::InternalMetadata[:environment] - raise NoEnvironmentInSchemaError unless environment - environment - end - - def self.current_environment - ActiveRecord::ConnectionHandling::DEFAULT_ENV.call - end - - def self.protected_environment? - ActiveRecord::Base.protected_environments.include?(last_stored_environment) if last_stored_environment - end - - def up? - @direction == :up - end - - def down? - @direction == :down - end - - # Wrap the migration in a transaction only if supported by the adapter. - def ddl_transaction(migration) - if use_transaction?(migration) - Base.transaction { yield } - else - yield - end - end - - def use_transaction?(migration) - !migration.disable_ddl_transaction && Base.connection.supports_ddl_transactions? - end - - def use_advisory_lock? - Base.connection.supports_advisory_locks? - end - - def with_advisory_lock - lock_id = generate_migrator_advisory_lock_id - got_lock = Base.connection.get_advisory_lock(lock_id) - raise ConcurrentMigrationError unless got_lock - load_migrated # reload schema_migrations to be sure it wasn't changed by another process before we got the lock - yield - ensure - Base.connection.release_advisory_lock(lock_id) if got_lock - end - - MIGRATOR_SALT = 2053462845 - def generate_migrator_advisory_lock_id - db_name_hash = Zlib.crc32(Base.connection.current_database) - MIGRATOR_SALT * db_name_hash - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/command_recorder.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/command_recorder.rb deleted file mode 100644 index 03103bba98..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/command_recorder.rb +++ /dev/null @@ -1,238 +0,0 @@ -module ActiveRecord - class Migration - # ActiveRecord::Migration::CommandRecorder records commands done during - # a migration and knows how to reverse those commands. The CommandRecorder - # knows how to invert the following commands: - # - # * add_column - # * add_foreign_key - # * add_index - # * add_reference - # * add_timestamps - # * change_column - # * change_column_default (must supply a :from and :to option) - # * change_column_null - # * create_join_table - # * create_table - # * disable_extension - # * drop_join_table - # * drop_table (must supply a block) - # * enable_extension - # * remove_column (must supply a type) - # * remove_columns (must specify at least one column name or more) - # * remove_foreign_key (must supply a second table) - # * remove_index - # * remove_reference - # * remove_timestamps - # * rename_column - # * rename_index - # * rename_table - class CommandRecorder - ReversibleAndIrreversibleMethods = [:create_table, :create_join_table, :rename_table, :add_column, :remove_column, - :rename_index, :rename_column, :add_index, :remove_index, :add_timestamps, :remove_timestamps, - :change_column_default, :add_reference, :remove_reference, :transaction, - :drop_join_table, :drop_table, :execute_block, :enable_extension, :disable_extension, - :change_column, :execute, :remove_columns, :change_column_null, - :add_foreign_key, :remove_foreign_key - ] - include JoinTable - - attr_accessor :commands, :delegate, :reverting - - def initialize(delegate = nil) - @commands = [] - @delegate = delegate - @reverting = false - end - - # While executing the given block, the recorded will be in reverting mode. - # All commands recorded will end up being recorded reverted - # and in reverse order. - # For example: - # - # recorder.revert{ recorder.record(:rename_table, [:old, :new]) } - # # same effect as recorder.record(:rename_table, [:new, :old]) - def revert - @reverting = !@reverting - previous = @commands - @commands = [] - yield - ensure - @commands = previous.concat(@commands.reverse) - @reverting = !@reverting - end - - # Record +command+. +command+ should be a method name and arguments. - # For example: - # - # recorder.record(:method_name, [:arg1, :arg2]) - def record(*command, &block) - if @reverting - @commands << inverse_of(*command, &block) - else - @commands << (command << block) - end - end - - # Returns the inverse of the given command. For example: - # - # recorder.inverse_of(:rename_table, [:old, :new]) - # # => [:rename_table, [:new, :old]] - # - # This method will raise an +IrreversibleMigration+ exception if it cannot - # invert the +command+. - def inverse_of(command, args, &block) - method = :"invert_#{command}" - raise IrreversibleMigration, <<-MSG.strip_heredoc unless respond_to?(method, true) - This migration uses #{command}, which is not automatically reversible. - To make the migration reversible you can either: - 1. Define #up and #down methods in place of the #change method. - 2. Use the #reversible method to define reversible behavior. - MSG - send(method, args, &block) - end - - def respond_to_missing?(*args) # :nodoc: - super || delegate.respond_to?(*args) - end - - ReversibleAndIrreversibleMethods.each do |method| - class_eval <<-EOV, __FILE__, __LINE__ + 1 - def #{method}(*args, &block) # def create_table(*args, &block) - record(:"#{method}", args, &block) # record(:create_table, args, &block) - end # end - EOV - end - alias :add_belongs_to :add_reference - alias :remove_belongs_to :remove_reference - - def change_table(table_name, options = {}) # :nodoc: - yield delegate.update_table_definition(table_name, self) - end - - private - - module StraightReversions - private - { transaction: :transaction, - execute_block: :execute_block, - create_table: :drop_table, - create_join_table: :drop_join_table, - add_column: :remove_column, - add_timestamps: :remove_timestamps, - add_reference: :remove_reference, - enable_extension: :disable_extension - }.each do |cmd, inv| - [[inv, cmd], [cmd, inv]].uniq.each do |method, inverse| - class_eval <<-EOV, __FILE__, __LINE__ + 1 - def invert_#{method}(args, &block) # def invert_create_table(args, &block) - [:#{inverse}, args, block] # [:drop_table, args, block] - end # end - EOV - end - end - end - - include StraightReversions - - def invert_drop_table(args, &block) - if args.size == 1 && block == nil - raise ActiveRecord::IrreversibleMigration, "To avoid mistakes, drop_table is only reversible if given options or a block (can be empty)." - end - super - end - - def invert_rename_table(args) - [:rename_table, args.reverse] - end - - def invert_remove_column(args) - raise ActiveRecord::IrreversibleMigration, "remove_column is only reversible if given a type." if args.size <= 2 - super - end - - def invert_rename_index(args) - [:rename_index, [args.first] + args.last(2).reverse] - end - - def invert_rename_column(args) - [:rename_column, [args.first] + args.last(2).reverse] - end - - def invert_add_index(args) - table, columns, options = *args - options ||= {} - - index_name = options[:name] - options_hash = index_name ? { name: index_name } : { column: columns } - - [:remove_index, [table, options_hash]] - end - - def invert_remove_index(args) - table, options_or_column = *args - if (options = options_or_column).is_a?(Hash) - unless options[:column] - raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option." - end - options = options.dup - [:add_index, [table, options.delete(:column), options]] - elsif (column = options_or_column).present? - [:add_index, [table, column]] - end - end - - alias :invert_add_belongs_to :invert_add_reference - alias :invert_remove_belongs_to :invert_remove_reference - - def invert_change_column_default(args) - table, column, options = *args - - unless options && options.is_a?(Hash) && options.has_key?(:from) && options.has_key?(:to) - raise ActiveRecord::IrreversibleMigration, "change_column_default is only reversible if given a :from and :to option." - end - - [:change_column_default, [table, column, from: options[:to], to: options[:from]]] - end - - def invert_change_column_null(args) - args[2] = !args[2] - [:change_column_null, args] - end - - def invert_add_foreign_key(args) - from_table, to_table, add_options = args - add_options ||= {} - - if add_options[:name] - options = { name: add_options[:name] } - elsif add_options[:column] - options = { column: add_options[:column] } - else - options = to_table - end - - [:remove_foreign_key, [from_table, options]] - end - - def invert_remove_foreign_key(args) - from_table, to_table, remove_options = args - raise ActiveRecord::IrreversibleMigration, "remove_foreign_key is only reversible if given a second table" if to_table.nil? || to_table.is_a?(Hash) - - reversed_args = [from_table, to_table] - reversed_args << remove_options if remove_options - - [:add_foreign_key, reversed_args] - end - - # Forwards any missing method call to the \target. - def method_missing(method, *args, &block) - if @delegate.respond_to?(method) - @delegate.send(method, *args, &block) - else - super - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/compatibility.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/compatibility.rb deleted file mode 100644 index d3eda369d3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/compatibility.rb +++ /dev/null @@ -1,179 +0,0 @@ -module ActiveRecord - class Migration - module Compatibility # :nodoc: all - def self.find(version) - version = version.to_s - name = "V#{version.tr('.', '_')}" - unless const_defined?(name) - versions = constants.grep(/\AV[0-9_]+\z/).map { |s| s.to_s.delete("V").tr("_", ".").inspect } - raise ArgumentError, "Unknown migration version #{version.inspect}; expected one of #{versions.sort.join(', ')}" - end - const_get(name) - end - - V5_1 = Current - - class V5_0 < V5_1 - module TableDefinition - def references(*args, **options) - super(*args, type: :integer, **options) - end - alias :belongs_to :references - end - - def create_table(table_name, options = {}) - if adapter_name == "PostgreSQL" - if options[:id] == :uuid && !options.key?(:default) - options[:default] = "uuid_generate_v4()" - end - end - - unless adapter_name == "Mysql2" && options[:id] == :bigint - if [:integer, :bigint].include?(options[:id]) && !options.key?(:default) - options[:default] = nil - end - end - - # Since 5.1 Postgres adapter uses bigserial type for primary - # keys by default and MySQL uses bigint. This compat layer makes old migrations utilize - # serial/int type instead -- the way it used to work before 5.1. - unless options.key?(:id) - options[:id] = :integer - end - - if block_given? - super do |t| - yield compatible_table_definition(t) - end - else - super - end - end - - def change_table(table_name, options = {}) - if block_given? - super do |t| - yield compatible_table_definition(t) - end - else - super - end - end - - def create_join_table(table_1, table_2, column_options: {}, **options) - column_options.reverse_merge!(type: :integer) - - if block_given? - super do |t| - yield compatible_table_definition(t) - end - else - super - end - end - - def add_reference(table_name, ref_name, **options) - super(table_name, ref_name, type: :integer, **options) - end - alias :add_belongs_to :add_reference - - private - def compatible_table_definition(t) - class << t - prepend TableDefinition - end - t - end - end - - class V4_2 < V5_0 - module TableDefinition - def references(*, **options) - options[:index] ||= false - super - end - alias :belongs_to :references - - def timestamps(**options) - options[:null] = true if options[:null].nil? - super - end - end - - def create_table(table_name, options = {}) - if block_given? - super do |t| - yield compatible_table_definition(t) - end - else - super - end - end - - def change_table(table_name, options = {}) - if block_given? - super do |t| - yield compatible_table_definition(t) - end - else - super - end - end - - def add_reference(*, **options) - options[:index] ||= false - super - end - alias :add_belongs_to :add_reference - - def add_timestamps(_, **options) - options[:null] = true if options[:null].nil? - super - end - - def index_exists?(table_name, column_name, options = {}) - column_names = Array(column_name).map(&:to_s) - options[:name] = - if options[:name].present? - options[:name].to_s - else - index_name(table_name, column: column_names) - end - super - end - - def remove_index(table_name, options = {}) - options = { column: options } unless options.is_a?(Hash) - options[:name] = index_name_for_remove(table_name, options) - super(table_name, options) - end - - private - def compatible_table_definition(t) - class << t - prepend TableDefinition - end - super - end - - def index_name_for_remove(table_name, options = {}) - index_name = index_name(table_name, options) - - unless index_name_exists?(table_name, index_name) - if options.is_a?(Hash) && options.has_key?(:name) - options_without_column = options.dup - options_without_column.delete :column - index_name_without_column = index_name(table_name, options_without_column) - - return index_name_without_column if index_name_exists?(table_name, index_name_without_column) - end - - raise ArgumentError, "Index name '#{index_name}' on table '#{table_name}' does not exist" - end - - index_name - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/join_table.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/join_table.rb deleted file mode 100644 index 89789f00ea..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/migration/join_table.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - class Migration - module JoinTable #:nodoc: - private - - def find_join_table_name(table_1, table_2, options = {}) - options.delete(:table_name) || join_table_name(table_1, table_2) - end - - def join_table_name(table_1, table_2) - ModelSchema.derive_join_table_name(table_1, table_2).to_sym - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/model_schema.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/model_schema.rb deleted file mode 100644 index 8052417685..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/model_schema.rb +++ /dev/null @@ -1,526 +0,0 @@ -require "monitor" - -module ActiveRecord - module ModelSchema - extend ActiveSupport::Concern - - ## - # :singleton-method: primary_key_prefix_type - # :call-seq: primary_key_prefix_type - # - # The prefix type that will be prepended to every primary key column name. - # The options are +:table_name+ and +:table_name_with_underscore+. If the first is specified, - # the Product class will look for "productid" instead of "id" as the primary column. If the - # latter is specified, the Product class will look for "product_id" instead of "id". Remember - # that this is a global setting for all Active Records. - - ## - # :singleton-method: primary_key_prefix_type= - # :call-seq: primary_key_prefix_type=(prefix_type) - # - # Sets the prefix type that will be prepended to every primary key column name. - # The options are +:table_name+ and +:table_name_with_underscore+. If the first is specified, - # the Product class will look for "productid" instead of "id" as the primary column. If the - # latter is specified, the Product class will look for "product_id" instead of "id". Remember - # that this is a global setting for all Active Records. - - ## - # :singleton-method: table_name_prefix - # :call-seq: table_name_prefix - # - # The prefix string to prepend to every table name. - - ## - # :singleton-method: table_name_prefix= - # :call-seq: table_name_prefix=(prefix) - # - # Sets the prefix string to prepend to every table name. So if set to "basecamp_", all table - # names will be named like "basecamp_projects", "basecamp_people", etc. This is a convenient - # way of creating a namespace for tables in a shared database. By default, the prefix is the - # empty string. - # - # If you are organising your models within modules you can add a prefix to the models within - # a namespace by defining a singleton method in the parent module called table_name_prefix which - # returns your chosen prefix. - - ## - # :singleton-method: table_name_suffix - # :call-seq: table_name_suffix - # - # The suffix string to append to every table name. - - ## - # :singleton-method: table_name_suffix= - # :call-seq: table_name_suffix=(suffix) - # - # Works like +table_name_prefix=+, but appends instead of prepends (set to "_basecamp" gives "projects_basecamp", - # "people_basecamp"). By default, the suffix is the empty string. - # - # If you are organising your models within modules, you can add a suffix to the models within - # a namespace by defining a singleton method in the parent module called table_name_suffix which - # returns your chosen suffix. - - ## - # :singleton-method: schema_migrations_table_name - # :call-seq: schema_migrations_table_name - # - # The name of the schema migrations table. By default, the value is "schema_migrations". - - ## - # :singleton-method: schema_migrations_table_name= - # :call-seq: schema_migrations_table_name=(table_name) - # - # Sets the name of the schema migrations table. - - ## - # :singleton-method: internal_metadata_table_name - # :call-seq: internal_metadata_table_name - # - # The name of the internal metadata table. By default, the value is "ar_internal_metadata". - - ## - # :singleton-method: internal_metadata_table_name= - # :call-seq: internal_metadata_table_name=(table_name) - # - # Sets the name of the internal metadata table. - - ## - # :singleton-method: pluralize_table_names - # :call-seq: pluralize_table_names - # - # Indicates whether table names should be the pluralized versions of the corresponding class names. - # If true, the default table name for a Product class will be "products". If false, it would just be "product". - # See table_name for the full rules on table/class naming. This is true, by default. - - ## - # :singleton-method: pluralize_table_names= - # :call-seq: pluralize_table_names=(value) - # - # Set whether table names should be the pluralized versions of the corresponding class names. - # If true, the default table name for a Product class will be "products". If false, it would just be "product". - # See table_name for the full rules on table/class naming. This is true, by default. - - included do - mattr_accessor :primary_key_prefix_type, instance_writer: false - - class_attribute :table_name_prefix, instance_writer: false - self.table_name_prefix = "" - - class_attribute :table_name_suffix, instance_writer: false - self.table_name_suffix = "" - - class_attribute :schema_migrations_table_name, instance_accessor: false - self.schema_migrations_table_name = "schema_migrations" - - class_attribute :internal_metadata_table_name, instance_accessor: false - self.internal_metadata_table_name = "ar_internal_metadata" - - class_attribute :pluralize_table_names, instance_writer: false - self.pluralize_table_names = true - - self.protected_environments = ["production"] - self.inheritance_column = "type" - self.ignored_columns = [].freeze - - delegate :type_for_attribute, to: :class - - initialize_load_schema_monitor - end - - # Derives the join table name for +first_table+ and +second_table+. The - # table names appear in alphabetical order. A common prefix is removed - # (useful for namespaced models like Music::Artist and Music::Record): - # - # artists, records => artists_records - # records, artists => artists_records - # music_artists, music_records => music_artists_records - def self.derive_join_table_name(first_table, second_table) # :nodoc: - [first_table.to_s, second_table.to_s].sort.join("\0").gsub(/^(.*_)(.+)\0\1(.+)/, '\1\2_\3').tr("\0", "_") - end - - module ClassMethods - # Guesses the table name (in forced lower-case) based on the name of the class in the - # inheritance hierarchy descending directly from ActiveRecord::Base. So if the hierarchy - # looks like: Reply < Message < ActiveRecord::Base, then Message is used - # to guess the table name even when called on Reply. The rules used to do the guess - # are handled by the Inflector class in Active Support, which knows almost all common - # English inflections. You can add new inflections in config/initializers/inflections.rb. - # - # Nested classes are given table names prefixed by the singular form of - # the parent's table name. Enclosing modules are not considered. - # - # ==== Examples - # - # class Invoice < ActiveRecord::Base - # end - # - # file class table_name - # invoice.rb Invoice invoices - # - # class Invoice < ActiveRecord::Base - # class Lineitem < ActiveRecord::Base - # end - # end - # - # file class table_name - # invoice.rb Invoice::Lineitem invoice_lineitems - # - # module Invoice - # class Lineitem < ActiveRecord::Base - # end - # end - # - # file class table_name - # invoice/lineitem.rb Invoice::Lineitem lineitems - # - # Additionally, the class-level +table_name_prefix+ is prepended and the - # +table_name_suffix+ is appended. So if you have "myapp_" as a prefix, - # the table name guess for an Invoice class becomes "myapp_invoices". - # Invoice::Lineitem becomes "myapp_invoice_lineitems". - # - # You can also set your own table name explicitly: - # - # class Mouse < ActiveRecord::Base - # self.table_name = "mice" - # end - def table_name - reset_table_name unless defined?(@table_name) - @table_name - end - - # Sets the table name explicitly. Example: - # - # class Project < ActiveRecord::Base - # self.table_name = "project" - # end - def table_name=(value) - value = value && value.to_s - - if defined?(@table_name) - return if value == @table_name - reset_column_information if connected? - end - - @table_name = value - @quoted_table_name = nil - @arel_table = nil - @sequence_name = nil unless defined?(@explicit_sequence_name) && @explicit_sequence_name - @predicate_builder = nil - end - - # Returns a quoted version of the table name, used to construct SQL statements. - def quoted_table_name - @quoted_table_name ||= connection.quote_table_name(table_name) - end - - # Computes the table name, (re)sets it internally, and returns it. - def reset_table_name #:nodoc: - self.table_name = if abstract_class? - superclass == Base ? nil : superclass.table_name - elsif superclass.abstract_class? - superclass.table_name || compute_table_name - else - compute_table_name - end - end - - def full_table_name_prefix #:nodoc: - (parents.detect { |p| p.respond_to?(:table_name_prefix) } || self).table_name_prefix - end - - def full_table_name_suffix #:nodoc: - (parents.detect { |p| p.respond_to?(:table_name_suffix) } || self).table_name_suffix - end - - # The array of names of environments where destructive actions should be prohibited. By default, - # the value is ["production"]. - def protected_environments - if defined?(@protected_environments) - @protected_environments - else - superclass.protected_environments - end - end - - # Sets an array of names of environments where destructive actions should be prohibited. - def protected_environments=(environments) - @protected_environments = environments.map(&:to_s) - end - - # Defines the name of the table column which will store the class name on single-table - # inheritance situations. - # - # The default inheritance column name is +type+, which means it's a - # reserved word inside Active Record. To be able to use single-table - # inheritance with another column name, or to use the column +type+ in - # your own model for something else, you can set +inheritance_column+: - # - # self.inheritance_column = 'zoink' - def inheritance_column - (@inheritance_column ||= nil) || superclass.inheritance_column - end - - # Sets the value of inheritance_column - def inheritance_column=(value) - @inheritance_column = value.to_s - @explicit_inheritance_column = true - end - - # The list of columns names the model should ignore. Ignored columns won't have attribute - # accessors defined, and won't be referenced in SQL queries. - def ignored_columns - if defined?(@ignored_columns) - @ignored_columns - else - superclass.ignored_columns - end - end - - # Sets the columns names the model should ignore. Ignored columns won't have attribute - # accessors defined, and won't be referenced in SQL queries. - def ignored_columns=(columns) - @ignored_columns = columns.map(&:to_s) - end - - def sequence_name - if base_class == self - @sequence_name ||= reset_sequence_name - else - (@sequence_name ||= nil) || base_class.sequence_name - end - end - - def reset_sequence_name #:nodoc: - @explicit_sequence_name = false - @sequence_name = connection.default_sequence_name(table_name, primary_key) - end - - # Sets the name of the sequence to use when generating ids to the given - # value, or (if the value is +nil+ or +false+) to the value returned by the - # given block. This is required for Oracle and is useful for any - # database which relies on sequences for primary key generation. - # - # If a sequence name is not explicitly set when using Oracle, - # it will default to the commonly used pattern of: #{table_name}_seq - # - # If a sequence name is not explicitly set when using PostgreSQL, it - # will discover the sequence corresponding to your primary key for you. - # - # class Project < ActiveRecord::Base - # self.sequence_name = "projectseq" # default would have been "project_seq" - # end - def sequence_name=(value) - @sequence_name = value.to_s - @explicit_sequence_name = true - end - - # Determines if the primary key values should be selected from their - # corresponding sequence before the insert statement. - def prefetch_primary_key? - connection.prefetch_primary_key?(table_name) - end - - # Returns the next value that will be used as the primary key on - # an insert statement. - def next_sequence_value - connection.next_sequence_value(sequence_name) - end - - # Indicates whether the table associated with this class exists - def table_exists? - connection.schema_cache.data_source_exists?(table_name) - end - - def attributes_builder # :nodoc: - unless defined?(@attributes_builder) && @attributes_builder - defaults = _default_attributes.except(*(column_names - [primary_key])) - @attributes_builder = AttributeSet::Builder.new(attribute_types, defaults) - end - @attributes_builder - end - - def columns_hash # :nodoc: - load_schema - @columns_hash - end - - def columns - load_schema - @columns ||= columns_hash.values - end - - def attribute_types # :nodoc: - load_schema - @attribute_types ||= Hash.new(Type.default_value) - end - - def yaml_encoder # :nodoc: - @yaml_encoder ||= AttributeSet::YAMLEncoder.new(attribute_types) - end - - # Returns the type of the attribute with the given name, after applying - # all modifiers. This method is the only valid source of information for - # anything related to the types of a model's attributes. This method will - # access the database and load the model's schema if it is required. - # - # The return value of this method will implement the interface described - # by ActiveModel::Type::Value (though the object itself may not subclass - # it). - # - # +attr_name+ The name of the attribute to retrieve the type for. Must be - # a string - def type_for_attribute(attr_name, &block) - if block - attribute_types.fetch(attr_name, &block) - else - attribute_types[attr_name] - end - end - - # Returns a hash where the keys are column names and the values are - # default values when instantiating the Active Record object for this table. - def column_defaults - load_schema - _default_attributes.deep_dup.to_hash - end - - def _default_attributes # :nodoc: - @default_attributes ||= AttributeSet.new({}) - end - - # Returns an array of column names as strings. - def column_names - @column_names ||= columns.map(&:name) - end - - # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", - # and columns used for single table inheritance have been removed. - def content_columns - @content_columns ||= columns.reject do |c| - c.name == primary_key || - c.name == inheritance_column || - c.name.end_with?("_id") || - c.name.end_with?("_count") - end - end - - # Resets all the cached information about columns, which will cause them - # to be reloaded on the next request. - # - # The most common usage pattern for this method is probably in a migration, - # when just after creating a table you want to populate it with some default - # values, eg: - # - # class CreateJobLevels < ActiveRecord::Migration[5.0] - # def up - # create_table :job_levels do |t| - # t.integer :id - # t.string :name - # - # t.timestamps - # end - # - # JobLevel.reset_column_information - # %w{assistant executive manager director}.each do |type| - # JobLevel.create(name: type) - # end - # end - # - # def down - # drop_table :job_levels - # end - # end - def reset_column_information - connection.clear_cache! - undefine_attribute_methods - connection.schema_cache.clear_data_source_cache!(table_name) - - reload_schema_from_cache - initialize_find_by_cache - end - - protected - - def initialize_load_schema_monitor - @load_schema_monitor = Monitor.new - end - - private - - def inherited(child_class) - super - child_class.initialize_load_schema_monitor - end - - def schema_loaded? - defined?(@schema_loaded) && @schema_loaded - end - - def load_schema - return if schema_loaded? - @load_schema_monitor.synchronize do - return if defined?(@columns_hash) && @columns_hash - - load_schema! - - @schema_loaded = true - end - end - - def load_schema! - @columns_hash = connection.schema_cache.columns_hash(table_name).except(*ignored_columns) - @columns_hash.each do |name, column| - define_attribute( - name, - connection.lookup_cast_type_from_column(column), - default: column.default, - user_provided_default: false - ) - end - end - - def reload_schema_from_cache - @arel_engine = nil - @arel_table = nil - @column_names = nil - @attribute_types = nil - @content_columns = nil - @default_attributes = nil - @inheritance_column = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column - @attributes_builder = nil - @columns = nil - @columns_hash = nil - @schema_loaded = false - @attribute_names = nil - @yaml_encoder = nil - direct_descendants.each do |descendant| - descendant.send(:reload_schema_from_cache) - end - end - - # Guesses the table name, but does not decorate it with prefix and suffix information. - def undecorated_table_name(class_name = base_class.name) - table_name = class_name.to_s.demodulize.underscore - pluralize_table_names ? table_name.pluralize : table_name - end - - # Computes and returns a table name according to default conventions. - def compute_table_name - base = base_class - if self == base - # Nested classes are prefixed with singular parent table name. - if parent < Base && !parent.abstract_class? - contained = parent.table_name - contained = contained.singularize if parent.pluralize_table_names - contained += "_" - end - - "#{full_table_name_prefix}#{contained}#{undecorated_table_name(name)}#{full_table_name_suffix}" - else - # STI subclasses always use their superclass' table. - base.table_name - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/nested_attributes.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/nested_attributes.rb deleted file mode 100644 index 01ecd79b8f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/nested_attributes.rb +++ /dev/null @@ -1,588 +0,0 @@ -require "active_support/core_ext/hash/except" -require "active_support/core_ext/object/try" -require "active_support/core_ext/hash/indifferent_access" - -module ActiveRecord - module NestedAttributes #:nodoc: - class TooManyRecords < ActiveRecordError - end - - extend ActiveSupport::Concern - - included do - class_attribute :nested_attributes_options, instance_writer: false - self.nested_attributes_options = {} - end - - # = Active Record Nested Attributes - # - # Nested attributes allow you to save attributes on associated records - # through the parent. By default nested attribute updating is turned off - # and you can enable it using the accepts_nested_attributes_for class - # method. When you enable nested attributes an attribute writer is - # defined on the model. - # - # The attribute writer is named after the association, which means that - # in the following example, two new methods are added to your model: - # - # author_attributes=(attributes) and - # pages_attributes=(attributes). - # - # class Book < ActiveRecord::Base - # has_one :author - # has_many :pages - # - # accepts_nested_attributes_for :author, :pages - # end - # - # Note that the :autosave option is automatically enabled on every - # association that accepts_nested_attributes_for is used for. - # - # === One-to-one - # - # Consider a Member model that has one Avatar: - # - # class Member < ActiveRecord::Base - # has_one :avatar - # accepts_nested_attributes_for :avatar - # end - # - # Enabling nested attributes on a one-to-one association allows you to - # create the member and avatar in one go: - # - # params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } } - # member = Member.create(params[:member]) - # member.avatar.id # => 2 - # member.avatar.icon # => 'smiling' - # - # It also allows you to update the avatar through the member: - # - # params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } } - # member.update params[:member] - # member.avatar.icon # => 'sad' - # - # By default you will only be able to set and update attributes on the - # associated model. If you want to destroy the associated model through the - # attributes hash, you have to enable it first using the - # :allow_destroy option. - # - # class Member < ActiveRecord::Base - # has_one :avatar - # accepts_nested_attributes_for :avatar, allow_destroy: true - # end - # - # Now, when you add the _destroy key to the attributes hash, with a - # value that evaluates to +true+, you will destroy the associated model: - # - # member.avatar_attributes = { id: '2', _destroy: '1' } - # member.avatar.marked_for_destruction? # => true - # member.save - # member.reload.avatar # => nil - # - # Note that the model will _not_ be destroyed until the parent is saved. - # - # Also note that the model will not be destroyed unless you also specify - # its id in the updated hash. - # - # === One-to-many - # - # Consider a member that has a number of posts: - # - # class Member < ActiveRecord::Base - # has_many :posts - # accepts_nested_attributes_for :posts - # end - # - # You can now set or update attributes on the associated posts through - # an attribute hash for a member: include the key +:posts_attributes+ - # with an array of hashes of post attributes as a value. - # - # For each hash that does _not_ have an id key a new record will - # be instantiated, unless the hash also contains a _destroy key - # that evaluates to +true+. - # - # params = { member: { - # name: 'joe', posts_attributes: [ - # { title: 'Kari, the awesome Ruby documentation browser!' }, - # { title: 'The egalitarian assumption of the modern citizen' }, - # { title: '', _destroy: '1' } # this will be ignored - # ] - # }} - # - # member = Member.create(params[:member]) - # member.posts.length # => 2 - # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!' - # member.posts.second.title # => 'The egalitarian assumption of the modern citizen' - # - # You may also set a +:reject_if+ proc to silently ignore any new record - # hashes if they fail to pass your criteria. For example, the previous - # example could be rewritten as: - # - # class Member < ActiveRecord::Base - # has_many :posts - # accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? } - # end - # - # params = { member: { - # name: 'joe', posts_attributes: [ - # { title: 'Kari, the awesome Ruby documentation browser!' }, - # { title: 'The egalitarian assumption of the modern citizen' }, - # { title: '' } # this will be ignored because of the :reject_if proc - # ] - # }} - # - # member = Member.create(params[:member]) - # member.posts.length # => 2 - # member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!' - # member.posts.second.title # => 'The egalitarian assumption of the modern citizen' - # - # Alternatively, +:reject_if+ also accepts a symbol for using methods: - # - # class Member < ActiveRecord::Base - # has_many :posts - # accepts_nested_attributes_for :posts, reject_if: :new_record? - # end - # - # class Member < ActiveRecord::Base - # has_many :posts - # accepts_nested_attributes_for :posts, reject_if: :reject_posts - # - # def reject_posts(attributes) - # attributes['title'].blank? - # end - # end - # - # If the hash contains an id key that matches an already - # associated record, the matching record will be modified: - # - # member.attributes = { - # name: 'Joe', - # posts_attributes: [ - # { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' }, - # { id: 2, title: '[UPDATED] other post' } - # ] - # } - # - # member.posts.first.title # => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' - # member.posts.second.title # => '[UPDATED] other post' - # - # However, the above applies if the parent model is being updated as well. - # For example, If you wanted to create a +member+ named _joe_ and wanted to - # update the +posts+ at the same time, that would give an - # ActiveRecord::RecordNotFound error. - # - # By default the associated records are protected from being destroyed. If - # you want to destroy any of the associated records through the attributes - # hash, you have to enable it first using the :allow_destroy - # option. This will allow you to also use the _destroy key to - # destroy existing records: - # - # class Member < ActiveRecord::Base - # has_many :posts - # accepts_nested_attributes_for :posts, allow_destroy: true - # end - # - # params = { member: { - # posts_attributes: [{ id: '2', _destroy: '1' }] - # }} - # - # member.attributes = params[:member] - # member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true - # member.posts.length # => 2 - # member.save - # member.reload.posts.length # => 1 - # - # Nested attributes for an associated collection can also be passed in - # the form of a hash of hashes instead of an array of hashes: - # - # Member.create( - # name: 'joe', - # posts_attributes: { - # first: { title: 'Foo' }, - # second: { title: 'Bar' } - # } - # ) - # - # has the same effect as - # - # Member.create( - # name: 'joe', - # posts_attributes: [ - # { title: 'Foo' }, - # { title: 'Bar' } - # ] - # ) - # - # The keys of the hash which is the value for +:posts_attributes+ are - # ignored in this case. - # However, it is not allowed to use 'id' or :id for one of - # such keys, otherwise the hash will be wrapped in an array and - # interpreted as an attribute hash for a single post. - # - # Passing attributes for an associated collection in the form of a hash - # of hashes can be used with hashes generated from HTTP/HTML parameters, - # where there may be no natural way to submit an array of hashes. - # - # === Saving - # - # All changes to models, including the destruction of those marked for - # destruction, are saved and destroyed automatically and atomically when - # the parent model is saved. This happens inside the transaction initiated - # by the parent's save method. See ActiveRecord::AutosaveAssociation. - # - # === Validating the presence of a parent model - # - # If you want to validate that a child record is associated with a parent - # record, you can use the +validates_presence_of+ method and the +:inverse_of+ - # key as this example illustrates: - # - # class Member < ActiveRecord::Base - # has_many :posts, inverse_of: :member - # accepts_nested_attributes_for :posts - # end - # - # class Post < ActiveRecord::Base - # belongs_to :member, inverse_of: :posts - # validates_presence_of :member - # end - # - # Note that if you do not specify the +:inverse_of+ option, then - # Active Record will try to automatically guess the inverse association - # based on heuristics. - # - # For one-to-one nested associations, if you build the new (in-memory) - # child object yourself before assignment, then this module will not - # overwrite it, e.g.: - # - # class Member < ActiveRecord::Base - # has_one :avatar - # accepts_nested_attributes_for :avatar - # - # def avatar - # super || build_avatar(width: 200) - # end - # end - # - # member = Member.new - # member.avatar_attributes = {icon: 'sad'} - # member.avatar.width # => 200 - module ClassMethods - REJECT_ALL_BLANK_PROC = proc { |attributes| attributes.all? { |key, value| key == "_destroy" || value.blank? } } - - # Defines an attributes writer for the specified association(s). - # - # Supported options: - # [:allow_destroy] - # If true, destroys any members from the attributes hash with a - # _destroy key and a value that evaluates to +true+ - # (eg. 1, '1', true, or 'true'). This option is off by default. - # [:reject_if] - # Allows you to specify a Proc or a Symbol pointing to a method - # that checks whether a record should be built for a certain attribute - # hash. The hash is passed to the supplied Proc or the method - # and it should return either +true+ or +false+. When no +:reject_if+ - # is specified, a record will be built for all attribute hashes that - # do not have a _destroy value that evaluates to true. - # Passing :all_blank instead of a Proc will create a proc - # that will reject a record where all the attributes are blank excluding - # any value for +_destroy+. - # [:limit] - # Allows you to specify the maximum number of associated records that - # can be processed with the nested attributes. Limit also can be specified - # as a Proc or a Symbol pointing to a method that should return a number. - # If the size of the nested attributes array exceeds the specified limit, - # NestedAttributes::TooManyRecords exception is raised. If omitted, any - # number of associations can be processed. - # Note that the +:limit+ option is only applicable to one-to-many - # associations. - # [:update_only] - # For a one-to-one association, this option allows you to specify how - # nested attributes are going to be used when an associated record already - # exists. In general, an existing record may either be updated with the - # new set of attribute values or be replaced by a wholly new record - # containing those values. By default the +:update_only+ option is +false+ - # and the nested attributes are used to update the existing record only - # if they include the record's :id value. Otherwise a new - # record will be instantiated and used to replace the existing one. - # However if the +:update_only+ option is +true+, the nested attributes - # are used to update the record's attributes always, regardless of - # whether the :id is present. The option is ignored for collection - # associations. - # - # Examples: - # # creates avatar_attributes= - # accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? } - # # creates avatar_attributes= - # accepts_nested_attributes_for :avatar, reject_if: :all_blank - # # creates avatar_attributes= and posts_attributes= - # accepts_nested_attributes_for :avatar, :posts, allow_destroy: true - def accepts_nested_attributes_for(*attr_names) - options = { allow_destroy: false, update_only: false } - options.update(attr_names.extract_options!) - options.assert_valid_keys(:allow_destroy, :reject_if, :limit, :update_only) - options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank - - attr_names.each do |association_name| - if reflection = _reflect_on_association(association_name) - reflection.autosave = true - define_autosave_validation_callbacks(reflection) - - nested_attributes_options = self.nested_attributes_options.dup - nested_attributes_options[association_name.to_sym] = options - self.nested_attributes_options = nested_attributes_options - - type = (reflection.collection? ? :collection : :one_to_one) - generate_association_writer(association_name, type) - else - raise ArgumentError, "No association found for name `#{association_name}'. Has it been defined yet?" - end - end - end - - private - - # Generates a writer method for this association. Serves as a point for - # accessing the objects in the association. For example, this method - # could generate the following: - # - # def pirate_attributes=(attributes) - # assign_nested_attributes_for_one_to_one_association(:pirate, attributes) - # end - # - # This redirects the attempts to write objects in an association through - # the helper methods defined below. Makes it seem like the nested - # associations are just regular associations. - def generate_association_writer(association_name, type) - generated_association_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1 - if method_defined?(:#{association_name}_attributes=) - remove_method(:#{association_name}_attributes=) - end - def #{association_name}_attributes=(attributes) - assign_nested_attributes_for_#{type}_association(:#{association_name}, attributes) - end - eoruby - end - end - - # Returns ActiveRecord::AutosaveAssociation::marked_for_destruction? It's - # used in conjunction with fields_for to build a form element for the - # destruction of this association. - # - # See ActionView::Helpers::FormHelper::fields_for for more info. - def _destroy - marked_for_destruction? - end - - private - - # Attribute hash keys that should not be assigned as normal attributes. - # These hash keys are nested attributes implementation details. - UNASSIGNABLE_KEYS = %w( id _destroy ) - - # Assigns the given attributes to the association. - # - # If an associated record does not yet exist, one will be instantiated. If - # an associated record already exists, the method's behavior depends on - # the value of the update_only option. If update_only is +false+ and the - # given attributes include an :id that matches the existing record's - # id, then the existing record will be modified. If no :id is provided - # it will be replaced with a new record. If update_only is +true+ the existing - # record will be modified regardless of whether an :id is provided. - # - # If the given attributes include a matching :id attribute, or - # update_only is true, and a :_destroy key set to a truthy value, - # then the existing record will be marked for destruction. - def assign_nested_attributes_for_one_to_one_association(association_name, attributes) - options = nested_attributes_options[association_name] - if attributes.respond_to?(:permitted?) - attributes = attributes.to_h - end - attributes = attributes.with_indifferent_access - existing_record = send(association_name) - - if (options[:update_only] || !attributes["id"].blank?) && existing_record && - (options[:update_only] || existing_record.id.to_s == attributes["id"].to_s) - assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) unless call_reject_if(association_name, attributes) - - elsif attributes["id"].present? - raise_nested_attributes_record_not_found!(association_name, attributes["id"]) - - elsif !reject_new_record?(association_name, attributes) - assignable_attributes = attributes.except(*UNASSIGNABLE_KEYS) - - if existing_record && existing_record.new_record? - existing_record.assign_attributes(assignable_attributes) - association(association_name).initialize_attributes(existing_record) - else - method = "build_#{association_name}" - if respond_to?(method) - send(method, assignable_attributes) - else - raise ArgumentError, "Cannot build association `#{association_name}'. Are you trying to build a polymorphic one-to-one association?" - end - end - end - end - - # Assigns the given attributes to the collection association. - # - # Hashes with an :id value matching an existing associated record - # will update that record. Hashes without an :id value will build - # a new record for the association. Hashes with a matching :id - # value and a :_destroy key set to a truthy value will mark the - # matched record for destruction. - # - # For example: - # - # assign_nested_attributes_for_collection_association(:people, { - # '1' => { id: '1', name: 'Peter' }, - # '2' => { name: 'John' }, - # '3' => { id: '2', _destroy: true } - # }) - # - # Will update the name of the Person with ID 1, build a new associated - # person with the name 'John', and mark the associated Person with ID 2 - # for destruction. - # - # Also accepts an Array of attribute hashes: - # - # assign_nested_attributes_for_collection_association(:people, [ - # { id: '1', name: 'Peter' }, - # { name: 'John' }, - # { id: '2', _destroy: true } - # ]) - def assign_nested_attributes_for_collection_association(association_name, attributes_collection) - options = nested_attributes_options[association_name] - if attributes_collection.respond_to?(:permitted?) - attributes_collection = attributes_collection.to_h - end - - unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array) - raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})" - end - - check_record_limit!(options[:limit], attributes_collection) - - if attributes_collection.is_a? Hash - keys = attributes_collection.keys - attributes_collection = if keys.include?("id") || keys.include?(:id) - [attributes_collection] - else - attributes_collection.values - end - end - - association = association(association_name) - - existing_records = if association.loaded? - association.target - else - attribute_ids = attributes_collection.map { |a| a["id"] || a[:id] }.compact - attribute_ids.empty? ? [] : association.scope.where(association.klass.primary_key => attribute_ids) - end - - attributes_collection.each do |attributes| - if attributes.respond_to?(:permitted?) - attributes = attributes.to_h - end - attributes = attributes.with_indifferent_access - - if attributes["id"].blank? - unless reject_new_record?(association_name, attributes) - association.build(attributes.except(*UNASSIGNABLE_KEYS)) - end - elsif existing_record = existing_records.detect { |record| record.id.to_s == attributes["id"].to_s } - unless call_reject_if(association_name, attributes) - # Make sure we are operating on the actual object which is in the association's - # proxy_target array (either by finding it, or adding it if not found) - # Take into account that the proxy_target may have changed due to callbacks - target_record = association.target.detect { |record| record.id.to_s == attributes["id"].to_s } - if target_record - existing_record = target_record - else - association.add_to_target(existing_record, :skip_callbacks) - end - - assign_to_or_mark_for_destruction(existing_record, attributes, options[:allow_destroy]) - end - else - raise_nested_attributes_record_not_found!(association_name, attributes["id"]) - end - end - end - - # Takes in a limit and checks if the attributes_collection has too many - # records. It accepts limit in the form of symbol, proc, or - # number-like object (anything that can be compared with an integer). - # - # Raises TooManyRecords error if the attributes_collection is - # larger than the limit. - def check_record_limit!(limit, attributes_collection) - if limit - limit = \ - case limit - when Symbol - send(limit) - when Proc - limit.call - else - limit - end - - if limit && attributes_collection.size > limit - raise TooManyRecords, "Maximum #{limit} records are allowed. Got #{attributes_collection.size} records instead." - end - end - end - - # Updates a record with the +attributes+ or marks it for destruction if - # +allow_destroy+ is +true+ and has_destroy_flag? returns +true+. - def assign_to_or_mark_for_destruction(record, attributes, allow_destroy) - record.assign_attributes(attributes.except(*UNASSIGNABLE_KEYS)) - record.mark_for_destruction if has_destroy_flag?(attributes) && allow_destroy - end - - # Determines if a hash contains a truthy _destroy key. - def has_destroy_flag?(hash) - Type::Boolean.new.cast(hash["_destroy"]) - end - - # Determines if a new record should be rejected by checking - # has_destroy_flag? or if a :reject_if proc exists for this - # association and evaluates to +true+. - def reject_new_record?(association_name, attributes) - will_be_destroyed?(association_name, attributes) || call_reject_if(association_name, attributes) - end - - # Determines if a record with the particular +attributes+ should be - # rejected by calling the reject_if Symbol or Proc (if defined). - # The reject_if option is defined by +accepts_nested_attributes_for+. - # - # Returns false if there is a +destroy_flag+ on the attributes. - def call_reject_if(association_name, attributes) - return false if will_be_destroyed?(association_name, attributes) - - case callback = nested_attributes_options[association_name][:reject_if] - when Symbol - method(callback).arity == 0 ? send(callback) : send(callback, attributes) - when Proc - callback.call(attributes) - end - end - - # Only take into account the destroy flag if :allow_destroy is true - def will_be_destroyed?(association_name, attributes) - allow_destroy?(association_name) && has_destroy_flag?(attributes) - end - - def allow_destroy?(association_name) - nested_attributes_options[association_name][:allow_destroy] - end - - def raise_nested_attributes_record_not_found!(association_name, record_id) - model = self.class._reflect_on_association(association_name).klass.name - raise RecordNotFound.new("Couldn't find #{model} with ID=#{record_id} for #{self.class.name} with ID=#{id}", - model, "id", record_id) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/no_touching.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/no_touching.rb deleted file mode 100644 index 4059020e25..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/no_touching.rb +++ /dev/null @@ -1,56 +0,0 @@ -module ActiveRecord - # = Active Record No Touching - module NoTouching - extend ActiveSupport::Concern - - module ClassMethods - # Lets you selectively disable calls to `touch` for the - # duration of a block. - # - # ==== Examples - # ActiveRecord::Base.no_touching do - # Project.first.touch # does nothing - # Message.first.touch # does nothing - # end - # - # Project.no_touching do - # Project.first.touch # does nothing - # Message.first.touch # works, but does not touch the associated project - # end - # - def no_touching(&block) - NoTouching.apply_to(self, &block) - end - end - - class << self - def apply_to(klass) #:nodoc: - klasses.push(klass) - yield - ensure - klasses.pop - end - - def applied_to?(klass) #:nodoc: - klasses.any? { |k| k >= klass } - end - - private - def klasses - Thread.current[:no_touching_classes] ||= [] - end - end - - def no_touching? - NoTouching.applied_to?(self.class) - end - - def touch_later(*) # :nodoc: - super unless no_touching? - end - - def touch(*) # :nodoc: - super unless no_touching? - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/null_relation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/null_relation.rb deleted file mode 100644 index 26966f9433..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/null_relation.rb +++ /dev/null @@ -1,66 +0,0 @@ -module ActiveRecord - module NullRelation # :nodoc: - def pluck(*column_names) - [] - end - - def delete_all - 0 - end - - def update_all(_updates) - 0 - end - - def delete(_id_or_array) - 0 - end - - def empty? - true - end - - def none? - true - end - - def any? - false - end - - def one? - false - end - - def many? - false - end - - def to_sql - "" - end - - def calculate(operation, _column_name) - case operation - when :count, :sum - group_values.any? ? Hash.new : 0 - when :average, :minimum, :maximum - group_values.any? ? Hash.new : nil - end - end - - def exists?(_conditions = :none) - false - end - - def or(other) - other.spawn - end - - private - - def exec_queries - @records = [].freeze - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/persistence.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/persistence.rb deleted file mode 100644 index 6988cd33e7..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/persistence.rb +++ /dev/null @@ -1,612 +0,0 @@ -module ActiveRecord - # = Active Record \Persistence - module Persistence - extend ActiveSupport::Concern - - module ClassMethods - # Creates an object (or multiple objects) and saves it to the database, if validations pass. - # The resulting object is returned whether the object was saved successfully to the database or not. - # - # The +attributes+ parameter can be either a Hash or an Array of Hashes. These Hashes describe the - # attributes on the objects that are to be created. - # - # ==== Examples - # # Create a single new object - # User.create(first_name: 'Jamie') - # - # # Create an Array of new objects - # User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) - # - # # Create a single object and pass it into a block to set other attributes. - # User.create(first_name: 'Jamie') do |u| - # u.is_admin = false - # end - # - # # Creating an Array of new objects using a block, where the block is executed for each object: - # User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u| - # u.is_admin = false - # end - def create(attributes = nil, &block) - if attributes.is_a?(Array) - attributes.collect { |attr| create(attr, &block) } - else - object = new(attributes, &block) - object.save - object - end - end - - # Creates an object (or multiple objects) and saves it to the database, - # if validations pass. Raises a RecordInvalid error if validations fail, - # unlike Base#create. - # - # The +attributes+ parameter can be either a Hash or an Array of Hashes. - # These describe which attributes to be created on the object, or - # multiple objects when given an Array of Hashes. - def create!(attributes = nil, &block) - if attributes.is_a?(Array) - attributes.collect { |attr| create!(attr, &block) } - else - object = new(attributes, &block) - object.save! - object - end - end - - # Given an attributes hash, +instantiate+ returns a new instance of - # the appropriate class. Accepts only keys as strings. - # - # For example, +Post.all+ may return Comments, Messages, and Emails - # by storing the record's subclass in a +type+ attribute. By calling - # +instantiate+ instead of +new+, finder methods ensure they get new - # instances of the appropriate class for each record. - # - # See ActiveRecord::Inheritance#discriminate_class_for_record to see - # how this "single-table" inheritance mapping is implemented. - def instantiate(attributes, column_types = {}, &block) - klass = discriminate_class_for_record(attributes) - attributes = klass.attributes_builder.build_from_database(attributes, column_types) - klass.allocate.init_with("attributes" => attributes, "new_record" => false, &block) - end - - private - # Called by +instantiate+ to decide which class to use for a new - # record instance. - # - # See +ActiveRecord::Inheritance#discriminate_class_for_record+ for - # the single-table inheritance discriminator. - def discriminate_class_for_record(record) - self - end - end - - # Returns true if this object hasn't been saved yet -- that is, a record - # for the object doesn't exist in the database yet; otherwise, returns false. - def new_record? - sync_with_transaction_state - @new_record - end - - # Returns true if this object has been destroyed, otherwise returns false. - def destroyed? - sync_with_transaction_state - @destroyed - end - - # Returns true if the record is persisted, i.e. it's not a new record and it was - # not destroyed, otherwise returns false. - def persisted? - sync_with_transaction_state - !(@new_record || @destroyed) - end - - ## - # :call-seq: - # save(*args) - # - # Saves the model. - # - # If the model is new, a record gets created in the database, otherwise - # the existing record gets updated. - # - # By default, save always runs validations. If any of them fail the action - # is cancelled and #save returns +false+, and the record won't be saved. However, if you supply - # validate: false, validations are bypassed altogether. See - # ActiveRecord::Validations for more information. - # - # By default, #save also sets the +updated_at+/+updated_on+ attributes to - # the current time. However, if you supply touch: false, these - # timestamps will not be updated. - # - # There's a series of callbacks associated with #save. If any of the - # before_* callbacks throws +:abort+ the action is cancelled and - # #save returns +false+. See ActiveRecord::Callbacks for further - # details. - # - # Attributes marked as readonly are silently ignored if the record is - # being updated. - def save(*args, &block) - create_or_update(*args, &block) - rescue ActiveRecord::RecordInvalid - false - end - - ## - # :call-seq: - # save!(*args) - # - # Saves the model. - # - # If the model is new, a record gets created in the database, otherwise - # the existing record gets updated. - # - # By default, #save! always runs validations. If any of them fail - # ActiveRecord::RecordInvalid gets raised, and the record won't be saved. However, if you supply - # validate: false, validations are bypassed altogether. See - # ActiveRecord::Validations for more information. - # - # By default, #save! also sets the +updated_at+/+updated_on+ attributes to - # the current time. However, if you supply touch: false, these - # timestamps will not be updated. - # - # There's a series of callbacks associated with #save!. If any of - # the before_* callbacks throws +:abort+ the action is cancelled - # and #save! raises ActiveRecord::RecordNotSaved. See - # ActiveRecord::Callbacks for further details. - # - # Attributes marked as readonly are silently ignored if the record is - # being updated. - # - # Unless an error is raised, returns true. - def save!(*args, &block) - create_or_update(*args, &block) || raise(RecordNotSaved.new("Failed to save the record", self)) - end - - # Deletes the record in the database and freezes this instance to - # reflect that no changes should be made (since they can't be - # persisted). Returns the frozen instance. - # - # The row is simply removed with an SQL +DELETE+ statement on the - # record's primary key, and no callbacks are executed. - # - # Note that this will also delete records marked as {#readonly?}[rdoc-ref:Core#readonly?]. - # - # To enforce the object's +before_destroy+ and +after_destroy+ - # callbacks or any :dependent association - # options, use #destroy. - def delete - self.class.delete(id) if persisted? - @destroyed = true - freeze - end - - # Deletes the record in the database and freezes this instance to reflect - # that no changes should be made (since they can't be persisted). - # - # There's a series of callbacks associated with #destroy. If the - # before_destroy callback throws +:abort+ the action is cancelled - # and #destroy returns +false+. - # See ActiveRecord::Callbacks for further details. - def destroy - _raise_readonly_record_error if readonly? - destroy_associations - self.class.connection.add_transaction_record(self) - @_trigger_destroy_callback = if persisted? - destroy_row > 0 - else - true - end - @destroyed = true - freeze - end - - # Deletes the record in the database and freezes this instance to reflect - # that no changes should be made (since they can't be persisted). - # - # There's a series of callbacks associated with #destroy!. If the - # before_destroy callback throws +:abort+ the action is cancelled - # and #destroy! raises ActiveRecord::RecordNotDestroyed. - # See ActiveRecord::Callbacks for further details. - def destroy! - destroy || _raise_record_not_destroyed - end - - # Returns an instance of the specified +klass+ with the attributes of the - # current record. This is mostly useful in relation to single-table - # inheritance structures where you want a subclass to appear as the - # superclass. This can be used along with record identification in - # Action Pack to allow, say, Client < Company to do something - # like render partial: @client.becomes(Company) to render that - # instance using the companies/company partial instead of clients/client. - # - # Note: The new instance will share a link to the same attributes as the original class. - # Therefore the sti column value will still be the same. - # Any change to the attributes on either instance will affect both instances. - # If you want to change the sti column as well, use #becomes! instead. - def becomes(klass) - became = klass.new - became.instance_variable_set("@attributes", @attributes) - became.instance_variable_set("@mutation_tracker", @mutation_tracker ||= nil) - became.instance_variable_set("@mutations_from_database", @mutations_from_database ||= nil) - became.instance_variable_set("@changed_attributes", attributes_changed_by_setter) - became.instance_variable_set("@new_record", new_record?) - became.instance_variable_set("@destroyed", destroyed?) - became.errors.copy!(errors) - became - end - - # Wrapper around #becomes that also changes the instance's sti column value. - # This is especially useful if you want to persist the changed class in your - # database. - # - # Note: The old instance's sti column value will be changed too, as both objects - # share the same set of attributes. - def becomes!(klass) - became = becomes(klass) - sti_type = nil - if !klass.descends_from_active_record? - sti_type = klass.sti_name - end - became.public_send("#{klass.inheritance_column}=", sti_type) - became - end - - # Updates a single attribute and saves the record. - # This is especially useful for boolean flags on existing records. Also note that - # - # * Validation is skipped. - # * \Callbacks are invoked. - # * updated_at/updated_on column is updated if that column is available. - # * Updates all the attributes that are dirty in this object. - # - # This method raises an ActiveRecord::ActiveRecordError if the - # attribute is marked as readonly. - # - # Also see #update_column. - def update_attribute(name, value) - name = name.to_s - verify_readonly_attribute(name) - public_send("#{name}=", value) - - save(validate: false) - end - - # Updates the attributes of the model from the passed-in hash and saves the - # record, all wrapped in a transaction. If the object is invalid, the saving - # will fail and false will be returned. - def update(attributes) - # The following transaction covers any possible database side-effects of the - # attributes assignment. For example, setting the IDs of a child collection. - with_transaction_returning_status do - assign_attributes(attributes) - save - end - end - - alias update_attributes update - - # Updates its receiver just like #update but calls #save! instead - # of +save+, so an exception is raised if the record is invalid and saving will fail. - def update!(attributes) - # The following transaction covers any possible database side-effects of the - # attributes assignment. For example, setting the IDs of a child collection. - with_transaction_returning_status do - assign_attributes(attributes) - save! - end - end - - alias update_attributes! update! - - # Equivalent to update_columns(name => value). - def update_column(name, value) - update_columns(name => value) - end - - # Updates the attributes directly in the database issuing an UPDATE SQL - # statement and sets them in the receiver: - # - # user.update_columns(last_request_at: Time.current) - # - # This is the fastest way to update attributes because it goes straight to - # the database, but take into account that in consequence the regular update - # procedures are totally bypassed. In particular: - # - # * \Validations are skipped. - # * \Callbacks are skipped. - # * +updated_at+/+updated_on+ are not updated. - # * However, attributes are serialized with the same rules as ActiveRecord::Relation#update_all - # - # This method raises an ActiveRecord::ActiveRecordError when called on new - # objects, or when at least one of the attributes is marked as readonly. - def update_columns(attributes) - raise ActiveRecordError, "cannot update a new record" if new_record? - raise ActiveRecordError, "cannot update a destroyed record" if destroyed? - - attributes.each_key do |key| - verify_readonly_attribute(key.to_s) - end - - updated_count = self.class.unscoped.where(self.class.primary_key => id).update_all(attributes) - - attributes.each do |k, v| - raw_write_attribute(k, v) - end - - updated_count == 1 - end - - # Initializes +attribute+ to zero if +nil+ and adds the value passed as +by+ (default is 1). - # The increment is performed directly on the underlying attribute, no setter is invoked. - # Only makes sense for number-based attributes. Returns +self+. - def increment(attribute, by = 1) - self[attribute] ||= 0 - self[attribute] += by - self - end - - # Wrapper around #increment that writes the update to the database. - # Only +attribute+ is updated; the record itself is not saved. - # This means that any other modified attributes will still be dirty. - # Validations and callbacks are skipped. Supports the `touch` option from - # +update_counters+, see that for more. - # Returns +self+. - def increment!(attribute, by = 1, touch: nil) - increment(attribute, by) - change = public_send(attribute) - (attribute_in_database(attribute.to_s) || 0) - self.class.update_counters(id, attribute => change, touch: touch) - clear_attribute_change(attribute) # eww - self - end - - # Initializes +attribute+ to zero if +nil+ and subtracts the value passed as +by+ (default is 1). - # The decrement is performed directly on the underlying attribute, no setter is invoked. - # Only makes sense for number-based attributes. Returns +self+. - def decrement(attribute, by = 1) - increment(attribute, -by) - end - - # Wrapper around #decrement that writes the update to the database. - # Only +attribute+ is updated; the record itself is not saved. - # This means that any other modified attributes will still be dirty. - # Validations and callbacks are skipped. Supports the `touch` option from - # +update_counters+, see that for more. - # Returns +self+. - def decrement!(attribute, by = 1, touch: nil) - increment!(attribute, -by, touch: touch) - end - - # Assigns to +attribute+ the boolean opposite of attribute?. So - # if the predicate returns +true+ the attribute will become +false+. This - # method toggles directly the underlying value without calling any setter. - # Returns +self+. - # - # Example: - # - # user = User.first - # user.banned? # => false - # user.toggle(:banned) - # user.banned? # => true - # - def toggle(attribute) - self[attribute] = !public_send("#{attribute}?") - self - end - - # Wrapper around #toggle that saves the record. This method differs from - # its non-bang version in the sense that it passes through the attribute setter. - # Saving is not subjected to validation checks. Returns +true+ if the - # record could be saved. - def toggle!(attribute) - toggle(attribute).update_attribute(attribute, self[attribute]) - end - - # Reloads the record from the database. - # - # This method finds the record by its primary key (which could be assigned - # manually) and modifies the receiver in-place: - # - # account = Account.new - # # => # - # account.id = 1 - # account.reload - # # Account Load (1.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 1]] - # # => # - # - # Attributes are reloaded from the database, and caches busted, in - # particular the associations cache and the QueryCache. - # - # If the record no longer exists in the database ActiveRecord::RecordNotFound - # is raised. Otherwise, in addition to the in-place modification the method - # returns +self+ for convenience. - # - # The optional :lock flag option allows you to lock the reloaded record: - # - # reload(lock: true) # reload with pessimistic locking - # - # Reloading is commonly used in test suites to test something is actually - # written to the database, or when some action modifies the corresponding - # row in the database but not the object in memory: - # - # assert account.deposit!(25) - # assert_equal 25, account.credit # check it is updated in memory - # assert_equal 25, account.reload.credit # check it is also persisted - # - # Another common use case is optimistic locking handling: - # - # def with_optimistic_retry - # begin - # yield - # rescue ActiveRecord::StaleObjectError - # begin - # # Reload lock_version in particular. - # reload - # rescue ActiveRecord::RecordNotFound - # # If the record is gone there is nothing to do. - # else - # retry - # end - # end - # end - # - def reload(options = nil) - self.class.connection.clear_query_cache - - fresh_object = - if options && options[:lock] - self.class.unscoped { self.class.lock(options[:lock]).find(id) } - else - self.class.unscoped { self.class.find(id) } - end - - @attributes = fresh_object.instance_variable_get("@attributes") - @new_record = false - self - end - - # Saves the record with the updated_at/on attributes set to the current time - # or the time specified. - # Please note that no validation is performed and only the +after_touch+, - # +after_commit+ and +after_rollback+ callbacks are executed. - # - # This method can be passed attribute names and an optional time argument. - # If attribute names are passed, they are updated along with updated_at/on - # attributes. If no time argument is passed, the current time is used as default. - # - # product.touch # updates updated_at/on with current time - # product.touch(time: Time.new(2015, 2, 16, 0, 0, 0)) # updates updated_at/on with specified time - # product.touch(:designed_at) # updates the designed_at attribute and updated_at/on - # product.touch(:started_at, :ended_at) # updates started_at, ended_at and updated_at/on attributes - # - # If used along with {belongs_to}[rdoc-ref:Associations::ClassMethods#belongs_to] - # then +touch+ will invoke +touch+ method on associated object. - # - # class Brake < ActiveRecord::Base - # belongs_to :car, touch: true - # end - # - # class Car < ActiveRecord::Base - # belongs_to :corporation, touch: true - # end - # - # # triggers @brake.car.touch and @brake.car.corporation.touch - # @brake.touch - # - # Note that +touch+ must be used on a persisted object, or else an - # ActiveRecordError will be thrown. For example: - # - # ball = Ball.new - # ball.touch(:updated_at) # => raises ActiveRecordError - # - def touch(*names, time: nil) - unless persisted? - raise ActiveRecordError, <<-MSG.squish - cannot touch on a new or destroyed record object. Consider using - persisted?, new_record?, or destroyed? before touching - MSG - end - - attribute_names = timestamp_attributes_for_update_in_model - attribute_names |= names.map(&:to_s) - - unless attribute_names.empty? - affected_rows = _touch_row(attribute_names, time) - @_trigger_update_callback = affected_rows == 1 - else - true - end - end - - private - - # A hook to be overridden by association modules. - def destroy_associations - end - - def destroy_row - relation_for_destroy.delete_all - end - - def relation_for_destroy - self.class.unscoped.where(self.class.primary_key => id) - end - - def _touch_row(attribute_names, time) - time ||= current_time_from_proper_timezone - - attribute_names.each do |attr_name| - write_attribute(attr_name, time) - clear_attribute_change(attr_name) - end - - _update_row(attribute_names, "touch") - end - - def _update_row(attribute_names, attempted_action = "update") - self.class.unscoped._update_record( - arel_attributes_with_values(attribute_names), - self.class.primary_key => id_in_database - ) - end - - def create_or_update(*args, &block) - _raise_readonly_record_error if readonly? - result = new_record? ? _create_record(&block) : _update_record(*args, &block) - result != false - end - - # Updates the associated record with values matching those of the instance attributes. - # Returns the number of affected rows. - def _update_record(attribute_names = self.attribute_names) - attribute_names &= self.class.column_names - attribute_names = attributes_for_update(attribute_names) - - if attribute_names.empty? - affected_rows = 0 - @_trigger_update_callback = true - else - affected_rows = _update_row(attribute_names) - @_trigger_update_callback = affected_rows == 1 - end - - yield(self) if block_given? - - affected_rows - end - - # Creates a record with values matching those of the instance attributes - # and returns its id. - def _create_record(attribute_names = self.attribute_names) - attribute_names &= self.class.column_names - attributes_values = arel_attributes_with_values_for_create(attribute_names) - - new_id = self.class.unscoped.insert attributes_values - self.id ||= new_id if self.class.primary_key - - @new_record = false - - yield(self) if block_given? - - id - end - - def verify_readonly_attribute(name) - raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name) - end - - def _raise_record_not_destroyed - @_association_destroy_exception ||= nil - raise @_association_destroy_exception || RecordNotDestroyed.new("Failed to destroy the record", self) - ensure - @_association_destroy_exception = nil - end - - def belongs_to_touch_method - :touch - end - - def _raise_readonly_record_error - raise ReadOnlyRecord, "#{self.class} is marked as readonly" - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/query_cache.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/query_cache.rb deleted file mode 100644 index ee549bd717..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/query_cache.rb +++ /dev/null @@ -1,47 +0,0 @@ -module ActiveRecord - # = Active Record Query Cache - class QueryCache - module ClassMethods - # Enable the query cache within the block if Active Record is configured. - # If it's not, it will execute the given block. - def cache(&block) - if connected? || !configurations.empty? - connection.cache(&block) - else - yield - end - end - - # Disable the query cache within the block if Active Record is configured. - # If it's not, it will execute the given block. - def uncached(&block) - if connected? || !configurations.empty? - connection.uncached(&block) - else - yield - end - end - end - - def self.run - caching_pool = ActiveRecord::Base.connection_pool - caching_was_enabled = caching_pool.query_cache_enabled - - caching_pool.enable_query_cache! - - [caching_pool, caching_was_enabled] - end - - def self.complete((caching_pool, caching_was_enabled)) - caching_pool.disable_query_cache! unless caching_was_enabled - - ActiveRecord::Base.connection_handler.connection_pool_list.each do |pool| - pool.release_connection if pool.active_connection? && !pool.connection.transaction_open? - end - end - - def self.install_executor_hooks(executor = ActiveSupport::Executor) - executor.register_hook(self) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/querying.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/querying.rb deleted file mode 100644 index b16e178358..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/querying.rb +++ /dev/null @@ -1,68 +0,0 @@ -module ActiveRecord - module Querying - delegate :find, :take, :take!, :first, :first!, :last, :last!, :exists?, :any?, :many?, :none?, :one?, to: :all - delegate :second, :second!, :third, :third!, :fourth, :fourth!, :fifth, :fifth!, :forty_two, :forty_two!, :third_to_last, :third_to_last!, :second_to_last, :second_to_last!, to: :all - delegate :first_or_create, :first_or_create!, :first_or_initialize, to: :all - delegate :find_or_create_by, :find_or_create_by!, :find_or_initialize_by, to: :all - delegate :find_by, :find_by!, to: :all - delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, to: :all - delegate :find_each, :find_in_batches, :in_batches, to: :all - delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins, :left_joins, :left_outer_joins, :or, - :where, :rewhere, :preload, :eager_load, :includes, :from, :lock, :readonly, :extending, - :having, :create_with, :distinct, :references, :none, :unscope, :merge, to: :all - delegate :count, :average, :minimum, :maximum, :sum, :calculate, to: :all - delegate :pluck, :ids, to: :all - - # Executes a custom SQL query against your database and returns all the results. The results will - # be returned as an array with columns requested encapsulated as attributes of the model you call - # this method from. If you call Product.find_by_sql then the results will be returned in - # a +Product+ object with the attributes you specified in the SQL query. - # - # If you call a complicated SQL query which spans multiple tables the columns specified by the - # SELECT will be attributes of the model, whether or not they are columns of the corresponding - # table. - # - # The +sql+ parameter is a full SQL query as a string. It will be called as is, there will be - # no database agnostic conversions performed. This should be a last resort because using, for example, - # MySQL specific terms will lock you to using that particular database engine or require you to - # change your call if you switch engines. - # - # # A simple SQL query spanning multiple tables - # Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id" - # # => [#"Ruby Meetup", "first_name"=>"Quentin"}>, ...] - # - # You can use the same string replacement techniques as you can with ActiveRecord::QueryMethods#where: - # - # Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date] - # Post.find_by_sql ["SELECT body FROM comments WHERE author = :user_id OR approved_by = :user_id", { :user_id => user_id }] - def find_by_sql(sql, binds = [], preparable: nil, &block) - result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds, preparable: preparable) - column_types = result_set.column_types.dup - columns_hash.each_key { |k| column_types.delete k } - message_bus = ActiveSupport::Notifications.instrumenter - - payload = { - record_count: result_set.length, - class_name: name - } - - message_bus.instrument("instantiation.active_record", payload) do - result_set.map { |record| instantiate(record, column_types, &block) } - end - end - - # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. - # The use of this method should be restricted to complicated SQL queries that can't be executed - # using the ActiveRecord::Calculations class methods. Look into those before using this. - # - # Product.count_by_sql "SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id" - # # => 12 - # - # ==== Parameters - # - # * +sql+ - An SQL statement which should return a count query from the database, see the example above. - def count_by_sql(sql) - connection.select_value(sanitize_sql(sql), "#{name} Count").to_i - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railtie.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/railtie.rb deleted file mode 100644 index 0276d41494..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railtie.rb +++ /dev/null @@ -1,170 +0,0 @@ -require "active_record" -require "rails" -require "active_model/railtie" - -# For now, action_controller must always be present with -# Rails, so let's make sure that it gets required before -# here. This is needed for correctly setting up the middleware. -# In the future, this might become an optional require. -require "action_controller/railtie" - -module ActiveRecord - # = Active Record Railtie - class Railtie < Rails::Railtie # :nodoc: - config.active_record = ActiveSupport::OrderedOptions.new - - config.app_generators.orm :active_record, migration: true, - timestamps: true - - config.action_dispatch.rescue_responses.merge!( - "ActiveRecord::RecordNotFound" => :not_found, - "ActiveRecord::StaleObjectError" => :conflict, - "ActiveRecord::RecordInvalid" => :unprocessable_entity, - "ActiveRecord::RecordNotSaved" => :unprocessable_entity - ) - - config.active_record.use_schema_cache_dump = true - config.active_record.maintain_test_schema = true - - config.eager_load_namespaces << ActiveRecord - - rake_tasks do - namespace :db do - task :load_config do - ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration - - if defined?(ENGINE_ROOT) && engine = Rails::Engine.find(ENGINE_ROOT) - if engine.paths["db/migrate"].existent - ActiveRecord::Tasks::DatabaseTasks.migrations_paths += engine.paths["db/migrate"].to_a - end - end - end - end - - load "active_record/railties/databases.rake" - end - - # When loading console, force ActiveRecord::Base to be loaded - # to avoid cross references when loading a constant for the - # first time. Also, make it output to STDERR. - console do |app| - require "active_record/railties/console_sandbox" if app.sandbox? - require "active_record/base" - unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDERR, STDOUT) - console = ActiveSupport::Logger.new(STDERR) - Rails.logger.extend ActiveSupport::Logger.broadcast console - end - end - - runner do - require "active_record/base" - end - - initializer "active_record.initialize_timezone" do - ActiveSupport.on_load(:active_record) do - self.time_zone_aware_attributes = true - self.default_timezone = :utc - end - end - - initializer "active_record.logger" do - ActiveSupport.on_load(:active_record) { self.logger ||= ::Rails.logger } - end - - initializer "active_record.migration_error" do - if config.active_record.delete(:migration_error) == :page_load - config.app_middleware.insert_after ::ActionDispatch::Callbacks, - ActiveRecord::Migration::CheckPending - end - end - - initializer "active_record.check_schema_cache_dump" do - if config.active_record.delete(:use_schema_cache_dump) - config.after_initialize do |app| - ActiveSupport.on_load(:active_record) do - filename = File.join(app.config.paths["db"].first, "schema_cache.yml") - - if File.file?(filename) - cache = YAML.load(File.read(filename)) - if cache.version == ActiveRecord::Migrator.current_version - connection.schema_cache = cache - connection_pool.schema_cache = cache.dup - else - warn "Ignoring db/schema_cache.yml because it has expired. The current schema version is #{ActiveRecord::Migrator.current_version}, but the one in the cache is #{cache.version}." - end - end - end - end - end - end - - initializer "active_record.warn_on_records_fetched_greater_than" do - if config.active_record.warn_on_records_fetched_greater_than - ActiveSupport.on_load(:active_record) do - require "active_record/relation/record_fetch_warning" - end - end - end - - initializer "active_record.set_configs" do |app| - ActiveSupport.on_load(:active_record) do - app.config.active_record.each do |k, v| - send "#{k}=", v - end - end - end - - # This sets the database configuration from Configuration#database_configuration - # and then establishes the connection. - initializer "active_record.initialize_database" do - ActiveSupport.on_load(:active_record) do - self.configurations = Rails.application.config.database_configuration - - begin - establish_connection - rescue ActiveRecord::NoDatabaseError - warn <<-end_warning -Oops - You have a database configured, but it doesn't exist yet! - -Here's how to get started: - - 1. Configure your database in config/database.yml. - 2. Run `bin/rails db:create` to create the database. - 3. Run `bin/rails db:setup` to load your database schema. -end_warning - raise - end - end - end - - # Expose database runtime to controller for logging. - initializer "active_record.log_runtime" do - require "active_record/railties/controller_runtime" - ActiveSupport.on_load(:action_controller) do - include ActiveRecord::Railties::ControllerRuntime - end - end - - initializer "active_record.set_reloader_hooks" do - ActiveSupport.on_load(:active_record) do - ActiveSupport::Reloader.before_class_unload do - if ActiveRecord::Base.connected? - ActiveRecord::Base.clear_cache! - ActiveRecord::Base.clear_reloadable_connections! - end - end - end - end - - initializer "active_record.set_executor_hooks" do - ActiveSupport.on_load(:active_record) do - ActiveRecord::QueryCache.install_executor_hooks - end - end - - initializer "active_record.add_watchable_files" do |app| - path = app.paths["db"].first - config.watchable_files.concat ["#{path}/schema.rb", "#{path}/structure.sql"] - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/console_sandbox.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/console_sandbox.rb deleted file mode 100644 index 604a220303..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/console_sandbox.rb +++ /dev/null @@ -1,5 +0,0 @@ -ActiveRecord::Base.connection.begin_transaction(joinable: false) - -at_exit do - ActiveRecord::Base.connection.rollback_transaction -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/controller_runtime.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/controller_runtime.rb deleted file mode 100644 index 8658188623..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/controller_runtime.rb +++ /dev/null @@ -1,54 +0,0 @@ -require "active_support/core_ext/module/attr_internal" -require "active_record/log_subscriber" - -module ActiveRecord - module Railties # :nodoc: - module ControllerRuntime #:nodoc: - extend ActiveSupport::Concern - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_internal :db_runtime - - private - - def process_action(action, *args) - # We also need to reset the runtime before each action - # because of queries in middleware or in cases we are streaming - # and it won't be cleaned up by the method below. - ActiveRecord::LogSubscriber.reset_runtime - super - end - - def cleanup_view_runtime - if logger && logger.info? && ActiveRecord::Base.connected? - db_rt_before_render = ActiveRecord::LogSubscriber.reset_runtime - self.db_runtime = (db_runtime || 0) + db_rt_before_render - runtime = super - db_rt_after_render = ActiveRecord::LogSubscriber.reset_runtime - self.db_runtime += db_rt_after_render - runtime - db_rt_after_render - else - super - end - end - - def append_info_to_payload(payload) - super - if ActiveRecord::Base.connected? - payload[:db_runtime] = (db_runtime || 0) + ActiveRecord::LogSubscriber.reset_runtime - end - end - - module ClassMethods # :nodoc: - def log_process_action(payload) - messages, db_runtime = super, payload[:db_runtime] - messages << ("ActiveRecord: %.1fms" % db_runtime.to_f) if db_runtime - messages - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/databases.rake b/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/databases.rake deleted file mode 100644 index 080669e09e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/databases.rake +++ /dev/null @@ -1,367 +0,0 @@ -require "active_record" - -db_namespace = namespace :db do - desc "Set the environment value for the database" - task "environment:set" => [:environment, :load_config] do - ActiveRecord::InternalMetadata.create_table - ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Migrator.current_environment - end - - task check_protected_environments: [:environment, :load_config] do - ActiveRecord::Tasks::DatabaseTasks.check_protected_environments! - end - - task :load_config do - ActiveRecord::Base.configurations = ActiveRecord::Tasks::DatabaseTasks.database_configuration || {} - ActiveRecord::Migrator.migrations_paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths - end - - namespace :create do - task all: :load_config do - ActiveRecord::Tasks::DatabaseTasks.create_all - end - end - - desc "Creates the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:create:all to create all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to creating the development and test databases." - task create: [:load_config] do - ActiveRecord::Tasks::DatabaseTasks.create_current - end - - namespace :drop do - task all: [:load_config, :check_protected_environments] do - ActiveRecord::Tasks::DatabaseTasks.drop_all - end - end - - desc "Drops the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:drop:all to drop all databases in the config). Without RAILS_ENV or when RAILS_ENV is development, it defaults to dropping the development and test databases." - task drop: [:load_config, :check_protected_environments] do - db_namespace["drop:_unsafe"].invoke - end - - task "drop:_unsafe" => [:load_config] do - ActiveRecord::Tasks::DatabaseTasks.drop_current - end - - namespace :purge do - task all: [:load_config, :check_protected_environments] do - ActiveRecord::Tasks::DatabaseTasks.purge_all - end - end - - # desc "Empty the database from DATABASE_URL or config/database.yml for the current RAILS_ENV (use db:purge:all to purge all databases in the config). Without RAILS_ENV it defaults to purging the development and test databases." - task purge: [:load_config, :check_protected_environments] do - ActiveRecord::Tasks::DatabaseTasks.purge_current - end - - desc "Migrate the database (options: VERSION=x, VERBOSE=false, SCOPE=blog)." - task migrate: [:environment, :load_config] do - ActiveRecord::Tasks::DatabaseTasks.migrate - db_namespace["_dump"].invoke - end - - # IMPORTANT: This task won't dump the schema if ActiveRecord::Base.dump_schema_after_migration is set to false - task :_dump do - if ActiveRecord::Base.dump_schema_after_migration - case ActiveRecord::Base.schema_format - when :ruby then db_namespace["schema:dump"].invoke - when :sql then db_namespace["structure:dump"].invoke - else - raise "unknown schema format #{ActiveRecord::Base.schema_format}" - end - end - # Allow this task to be called as many times as required. An example is the - # migrate:redo task, which calls other two internally that depend on this one. - db_namespace["_dump"].reenable - end - - namespace :migrate do - # desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).' - task redo: [:environment, :load_config] do - raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty? - - if ENV["VERSION"] - db_namespace["migrate:down"].invoke - db_namespace["migrate:up"].invoke - else - db_namespace["rollback"].invoke - db_namespace["migrate"].invoke - end - end - - # desc 'Resets your database using your migrations for the current environment' - task reset: ["db:drop", "db:create", "db:migrate"] - - # desc 'Runs the "up" for a given migration VERSION.' - task up: [:environment, :load_config] do - raise "VERSION is required" if !ENV["VERSION"] || ENV["VERSION"].empty? - - version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil - ActiveRecord::Migrator.run(:up, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version) - db_namespace["_dump"].invoke - end - - # desc 'Runs the "down" for a given migration VERSION.' - task down: [:environment, :load_config] do - raise "VERSION is required - To go down one migration, use db:rollback" if !ENV["VERSION"] || ENV["VERSION"].empty? - version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil - ActiveRecord::Migrator.run(:down, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version) - db_namespace["_dump"].invoke - end - - desc "Display status of migrations" - task status: [:environment, :load_config] do - unless ActiveRecord::SchemaMigration.table_exists? - abort "Schema migrations table does not exist yet." - end - - # output - puts "\ndatabase: #{ActiveRecord::Base.connection_config[:database]}\n\n" - puts "#{'Status'.center(8)} #{'Migration ID'.ljust(14)} Migration Name" - puts "-" * 50 - paths = ActiveRecord::Tasks::DatabaseTasks.migrations_paths - ActiveRecord::Migrator.migrations_status(paths).each do |status, version, name| - puts "#{status.center(8)} #{version.ljust(14)} #{name}" - end - puts - end - end - - desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)." - task rollback: [:environment, :load_config] do - step = ENV["STEP"] ? ENV["STEP"].to_i : 1 - ActiveRecord::Migrator.rollback(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step) - db_namespace["_dump"].invoke - end - - # desc 'Pushes the schema to the next version (specify steps w/ STEP=n).' - task forward: [:environment, :load_config] do - step = ENV["STEP"] ? ENV["STEP"].to_i : 1 - ActiveRecord::Migrator.forward(ActiveRecord::Tasks::DatabaseTasks.migrations_paths, step) - db_namespace["_dump"].invoke - end - - # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.' - task reset: [ "db:drop", "db:setup" ] - - # desc "Retrieves the charset for the current environment's database" - task charset: [:environment, :load_config] do - puts ActiveRecord::Tasks::DatabaseTasks.charset_current - end - - # desc "Retrieves the collation for the current environment's database" - task collation: [:environment, :load_config] do - begin - puts ActiveRecord::Tasks::DatabaseTasks.collation_current - rescue NoMethodError - $stderr.puts "Sorry, your database adapter is not supported yet. Feel free to submit a patch." - end - end - - desc "Retrieves the current schema version number" - task version: [:environment, :load_config] do - puts "Current version: #{ActiveRecord::Migrator.current_version}" - end - - # desc "Raises an error if there are pending migrations" - task abort_if_pending_migrations: [:environment, :load_config] do - pending_migrations = ActiveRecord::Migrator.open(ActiveRecord::Tasks::DatabaseTasks.migrations_paths).pending_migrations - - if pending_migrations.any? - puts "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}" - pending_migrations.each do |pending_migration| - puts " %4d %s" % [pending_migration.version, pending_migration.name] - end - abort %{Run `rails db:migrate` to update your database then try again.} - end - end - - desc "Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)" - task setup: ["db:schema:load_if_ruby", "db:structure:load_if_sql", :seed] - - desc "Loads the seed data from db/seeds.rb" - task :seed do - db_namespace["abort_if_pending_migrations"].invoke - ActiveRecord::Tasks::DatabaseTasks.load_seed - end - - namespace :fixtures do - desc "Loads fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y. Load from subdirectory in test/fixtures using FIXTURES_DIR=z. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures." - task load: [:environment, :load_config] do - require "active_record/fixtures" - - base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path - - fixtures_dir = if ENV["FIXTURES_DIR"] - File.join base_dir, ENV["FIXTURES_DIR"] - else - base_dir - end - - fixture_files = if ENV["FIXTURES"] - ENV["FIXTURES"].split(",") - else - # The use of String#[] here is to support namespaced fixtures. - Dir["#{fixtures_dir}/**/*.yml"].map { |f| f[(fixtures_dir.size + 1)..-5] } - end - - ActiveRecord::FixtureSet.create_fixtures(fixtures_dir, fixture_files) - end - - # desc "Search for a fixture given a LABEL or ID. Specify an alternative path (eg. spec/fixtures) using FIXTURES_PATH=spec/fixtures." - task identify: [:environment, :load_config] do - require "active_record/fixtures" - - label, id = ENV["LABEL"], ENV["ID"] - raise "LABEL or ID required" if label.blank? && id.blank? - - puts %Q(The fixture ID for "#{label}" is #{ActiveRecord::FixtureSet.identify(label)}.) if label - - base_dir = ActiveRecord::Tasks::DatabaseTasks.fixtures_path - - Dir["#{base_dir}/**/*.yml"].each do |file| - if data = YAML::load(ERB.new(IO.read(file)).result) - data.each_key do |key| - key_id = ActiveRecord::FixtureSet.identify(key) - - if key == label || key_id == id.to_i - puts "#{file}: #{key} (#{key_id})" - end - end - end - end - end - end - - namespace :schema do - desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record" - task dump: [:environment, :load_config] do - require "active_record/schema_dumper" - filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema.rb") - File.open(filename, "w:utf-8") do |file| - ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file) - end - db_namespace["schema:dump"].reenable - end - - desc "Loads a schema.rb file into the database" - task load: [:environment, :load_config, :check_protected_environments] do - ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:ruby, ENV["SCHEMA"]) - end - - task load_if_ruby: ["db:create", :environment] do - db_namespace["schema:load"].invoke if ActiveRecord::Base.schema_format == :ruby - end - - namespace :cache do - desc "Creates a db/schema_cache.yml file." - task dump: [:environment, :load_config] do - conn = ActiveRecord::Base.connection - filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.yml") - ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(conn, filename) - end - - desc "Clears a db/schema_cache.yml file." - task clear: [:environment, :load_config] do - filename = File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "schema_cache.yml") - rm_f filename, verbose: false - end - end - - end - - namespace :structure do - desc "Dumps the database structure to db/structure.sql. Specify another file with SCHEMA=db/my_structure.sql" - task dump: [:environment, :load_config] do - filename = ENV["SCHEMA"] || File.join(ActiveRecord::Tasks::DatabaseTasks.db_dir, "structure.sql") - current_config = ActiveRecord::Tasks::DatabaseTasks.current_config - ActiveRecord::Tasks::DatabaseTasks.structure_dump(current_config, filename) - - if ActiveRecord::SchemaMigration.table_exists? - File.open(filename, "a") do |f| - f.puts ActiveRecord::Base.connection.dump_schema_information - f.print "\n" - end - end - db_namespace["structure:dump"].reenable - end - - desc "Recreates the databases from the structure.sql file" - task load: [:environment, :load_config, :check_protected_environments] do - ActiveRecord::Tasks::DatabaseTasks.load_schema_current(:sql, ENV["SCHEMA"]) - end - - task load_if_sql: ["db:create", :environment] do - db_namespace["structure:load"].invoke if ActiveRecord::Base.schema_format == :sql - end - end - - namespace :test do - # desc "Recreate the test database from the current schema" - task load: %w(db:test:purge) do - case ActiveRecord::Base.schema_format - when :ruby - db_namespace["test:load_schema"].invoke - when :sql - db_namespace["test:load_structure"].invoke - end - end - - # desc "Recreate the test database from an existent schema.rb file" - task load_schema: %w(db:test:purge) do - begin - should_reconnect = ActiveRecord::Base.connection_pool.active_connection? - ActiveRecord::Schema.verbose = false - ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :ruby, ENV["SCHEMA"], "test" - ensure - if should_reconnect - ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env]) - end - end - end - - # desc "Recreate the test database from an existent structure.sql file" - task load_structure: %w(db:test:purge) do - ActiveRecord::Tasks::DatabaseTasks.load_schema ActiveRecord::Base.configurations["test"], :sql, ENV["SCHEMA"], "test" - end - - # desc "Empty the test database" - task purge: %w(environment load_config check_protected_environments) do - ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations["test"] - end - - # desc 'Load the test schema' - task prepare: %w(environment load_config) do - unless ActiveRecord::Base.configurations.blank? - db_namespace["test:load"].invoke - end - end - end -end - -namespace :railties do - namespace :install do - # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2" - task migrations: :'db:load_config' do - to_load = ENV["FROM"].blank? ? :all : ENV["FROM"].split(",").map(&:strip) - railties = {} - Rails.application.migration_railties.each do |railtie| - next unless to_load == :all || to_load.include?(railtie.railtie_name) - - if railtie.respond_to?(:paths) && (path = railtie.paths["db/migrate"].first) - railties[railtie.railtie_name] = path - end - end - - on_skip = Proc.new do |name, migration| - puts "NOTE: Migration #{migration.basename} from #{name} has been skipped. Migration with the same name already exists." - end - - on_copy = Proc.new do |name, migration| - puts "Copied migration #{migration.basename} from #{name}" - end - - ActiveRecord::Migration.copy(ActiveRecord::Tasks::DatabaseTasks.migrations_paths.first, railties, - on_skip: on_skip, on_copy: on_copy) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/jdbcmysql_error.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/jdbcmysql_error.rb deleted file mode 100644 index d7cf4df339..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/railties/jdbcmysql_error.rb +++ /dev/null @@ -1,16 +0,0 @@ -#FIXME Remove if ArJdbcMysql will give. -module ArJdbcMySQL #:nodoc: - class Error < StandardError #:nodoc: - attr_accessor :error_number, :sql_state - - def initialize(msg) - super - @error_number = nil - @sql_state = nil - end - - # Mysql gem compatibility - alias_method :errno, :error_number - alias_method :error, :message - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/readonly_attributes.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/readonly_attributes.rb deleted file mode 100644 index 6274996ab8..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/readonly_attributes.rb +++ /dev/null @@ -1,23 +0,0 @@ -module ActiveRecord - module ReadonlyAttributes - extend ActiveSupport::Concern - - included do - class_attribute :_attr_readonly, instance_accessor: false - self._attr_readonly = [] - end - - module ClassMethods - # Attributes listed as readonly will be used to create a new record but update operations will - # ignore these fields. - def attr_readonly(*attributes) - self._attr_readonly = Set.new(attributes.map(&:to_s)) + (_attr_readonly || []) - end - - # Returns an array of all the attributes that have been specified as readonly. - def readonly_attributes - _attr_readonly - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/reflection.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/reflection.rb deleted file mode 100644 index 99454c301b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/reflection.rb +++ /dev/null @@ -1,1126 +0,0 @@ -require "thread" -require "active_support/core_ext/string/filters" -require "active_support/deprecation" - -module ActiveRecord - # = Active Record Reflection - module Reflection # :nodoc: - extend ActiveSupport::Concern - - included do - class_attribute :_reflections, instance_writer: false - class_attribute :aggregate_reflections, instance_writer: false - self._reflections = {} - self.aggregate_reflections = {} - end - - def self.create(macro, name, scope, options, ar) - klass = \ - case macro - when :composed_of - AggregateReflection - when :has_many - HasManyReflection - when :has_one - HasOneReflection - when :belongs_to - BelongsToReflection - else - raise "Unsupported Macro: #{macro}" - end - - reflection = klass.new(name, scope, options, ar) - options[:through] ? ThroughReflection.new(reflection) : reflection - end - - def self.add_reflection(ar, name, reflection) - ar.clear_reflections_cache - name = name.to_s - ar._reflections = ar._reflections.except(name).merge!(name => reflection) - end - - def self.add_aggregate_reflection(ar, name, reflection) - ar.aggregate_reflections = ar.aggregate_reflections.merge(name.to_s => reflection) - end - - # \Reflection enables the ability to examine the associations and aggregations of - # Active Record classes and objects. This information, for example, - # can be used in a form builder that takes an Active Record object - # and creates input fields for all of the attributes depending on their type - # and displays the associations to other objects. - # - # MacroReflection class has info for AggregateReflection and AssociationReflection - # classes. - module ClassMethods - # Returns an array of AggregateReflection objects for all the aggregations in the class. - def reflect_on_all_aggregations - aggregate_reflections.values - end - - # Returns the AggregateReflection object for the named +aggregation+ (use the symbol). - # - # Account.reflect_on_aggregation(:balance) # => the balance AggregateReflection - # - def reflect_on_aggregation(aggregation) - aggregate_reflections[aggregation.to_s] - end - - # Returns a Hash of name of the reflection as the key and an AssociationReflection as the value. - # - # Account.reflections # => {"balance" => AggregateReflection} - # - def reflections - @__reflections ||= begin - ref = {} - - _reflections.each do |name, reflection| - parent_reflection = reflection.parent_reflection - - if parent_reflection - parent_name = parent_reflection.name - ref[parent_name.to_s] = parent_reflection - else - ref[name] = reflection - end - end - - ref - end - end - - # Returns an array of AssociationReflection objects for all the - # associations in the class. If you only want to reflect on a certain - # association type, pass in the symbol (:has_many, :has_one, - # :belongs_to) as the first parameter. - # - # Example: - # - # Account.reflect_on_all_associations # returns an array of all associations - # Account.reflect_on_all_associations(:has_many) # returns an array of all has_many associations - # - def reflect_on_all_associations(macro = nil) - association_reflections = reflections.values - association_reflections.select! { |reflection| reflection.macro == macro } if macro - association_reflections - end - - # Returns the AssociationReflection object for the +association+ (use the symbol). - # - # Account.reflect_on_association(:owner) # returns the owner AssociationReflection - # Invoice.reflect_on_association(:line_items).macro # returns :has_many - # - def reflect_on_association(association) - reflections[association.to_s] - end - - def _reflect_on_association(association) #:nodoc: - _reflections[association.to_s] - end - - # Returns an array of AssociationReflection objects for all associations which have :autosave enabled. - def reflect_on_all_autosave_associations - reflections.values.select { |reflection| reflection.options[:autosave] } - end - - def clear_reflections_cache # :nodoc: - @__reflections = nil - end - end - - # Holds all the methods that are shared between MacroReflection and ThroughReflection. - # - # AbstractReflection - # MacroReflection - # AggregateReflection - # AssociationReflection - # HasManyReflection - # HasOneReflection - # BelongsToReflection - # HasAndBelongsToManyReflection - # ThroughReflection - # PolymorphicReflection - # RuntimeReflection - class AbstractReflection # :nodoc: - def through_reflection? - false - end - - def table_name - klass.table_name - end - - # Returns a new, unsaved instance of the associated class. +attributes+ will - # be passed to the class's constructor. - def build_association(attributes, &block) - klass.new(attributes, &block) - end - - def quoted_table_name - klass.quoted_table_name - end - - def primary_key_type - klass.type_for_attribute(klass.primary_key) - end - - # Returns the class name for the macro. - # - # composed_of :balance, class_name: 'Money' returns 'Money' - # has_many :clients returns 'Client' - def class_name - @class_name ||= (options[:class_name] || derive_class_name).to_s - end - - JoinKeys = Struct.new(:key, :foreign_key) # :nodoc: - - def join_keys - get_join_keys klass - end - - # Returns a list of scopes that should be applied for this Reflection - # object when querying the database. - def scopes - scope ? [scope] : [] - end - - def scope_chain - chain.map(&:scopes) - end - deprecate :scope_chain - - def join_scope(table) - predicate_builder = predicate_builder(table) - scope_chain_items = join_scopes(table, predicate_builder) - klass_scope = klass_join_scope(table, predicate_builder) - - scope_chain_items.inject(klass_scope || scope_chain_items.shift, &:merge!) - end - - def join_scopes(table, predicate_builder) # :nodoc: - if scope - [build_scope(table, predicate_builder).instance_exec(&scope)] - else - [] - end - end - - def klass_join_scope(table, predicate_builder) # :nodoc: - relation = build_scope(table, predicate_builder) - klass.scope_for_association(relation) - end - - def constraints - chain.map(&:scopes).flatten - end - - def counter_cache_column - if belongs_to? - if options[:counter_cache] == true - "#{active_record.name.demodulize.underscore.pluralize}_count" - elsif options[:counter_cache] - options[:counter_cache].to_s - end - else - options[:counter_cache] ? options[:counter_cache].to_s : "#{name}_count" - end - end - - def inverse_of - return unless inverse_name - - @inverse_of ||= klass._reflect_on_association inverse_name - end - - def check_validity_of_inverse! - unless polymorphic? - if has_inverse? && inverse_of.nil? - raise InverseOfAssociationNotFoundError.new(self) - end - end - end - - # This shit is nasty. We need to avoid the following situation: - # - # * An associated record is deleted via record.destroy - # * Hence the callbacks run, and they find a belongs_to on the record with a - # :counter_cache options which points back at our owner. So they update the - # counter cache. - # * In which case, we must make sure to *not* update the counter cache, or else - # it will be decremented twice. - # - # Hence this method. - def inverse_which_updates_counter_cache - return @inverse_which_updates_counter_cache if defined?(@inverse_which_updates_counter_cache) - @inverse_which_updates_counter_cache = klass.reflect_on_all_associations(:belongs_to).find do |inverse| - inverse.counter_cache_column == counter_cache_column - end - end - alias inverse_updates_counter_cache? inverse_which_updates_counter_cache - - def inverse_updates_counter_in_memory? - inverse_of && inverse_which_updates_counter_cache == inverse_of - end - - # Returns whether a counter cache should be used for this association. - # - # The counter_cache option must be given on either the owner or inverse - # association, and the column must be present on the owner. - def has_cached_counter? - options[:counter_cache] || - inverse_which_updates_counter_cache && inverse_which_updates_counter_cache.options[:counter_cache] && - !!active_record.columns_hash[counter_cache_column] - end - - def counter_must_be_updated_by_has_many? - !inverse_updates_counter_in_memory? && has_cached_counter? - end - - def alias_candidate(name) - "#{plural_name}_#{name}" - end - - def chain - collect_join_chain - end - - def get_join_keys(association_klass) - JoinKeys.new(join_pk(association_klass), join_fk) - end - - def build_scope(table, predicate_builder = predicate_builder(table)) - Relation.create(klass, table, predicate_builder) - end - - private - def predicate_builder(table) - PredicateBuilder.new(TableMetadata.new(klass, table)) - end - - def join_pk(_) - foreign_key - end - - def join_fk - active_record_primary_key - end - end - - # Base class for AggregateReflection and AssociationReflection. Objects of - # AggregateReflection and AssociationReflection are returned by the Reflection::ClassMethods. - class MacroReflection < AbstractReflection - # Returns the name of the macro. - # - # composed_of :balance, class_name: 'Money' returns :balance - # has_many :clients returns :clients - attr_reader :name - - attr_reader :scope - - # Returns the hash of options used for the macro. - # - # composed_of :balance, class_name: 'Money' returns { class_name: "Money" } - # has_many :clients returns {} - attr_reader :options - - attr_reader :active_record - - attr_reader :plural_name # :nodoc: - - def initialize(name, scope, options, active_record) - @name = name - @scope = scope - @options = options - @active_record = active_record - @klass = options[:anonymous_class] - @plural_name = active_record.pluralize_table_names ? - name.to_s.pluralize : name.to_s - end - - def autosave=(autosave) - @options[:autosave] = autosave - parent_reflection = self.parent_reflection - if parent_reflection - parent_reflection.autosave = autosave - end - end - - # Returns the class for the macro. - # - # composed_of :balance, class_name: 'Money' returns the Money class - # has_many :clients returns the Client class - def klass - @klass ||= compute_class(class_name) - end - - def compute_class(name) - name.constantize - end - - # Returns +true+ if +self+ and +other_aggregation+ have the same +name+ attribute, +active_record+ attribute, - # and +other_aggregation+ has an options hash assigned to it. - def ==(other_aggregation) - super || - other_aggregation.kind_of?(self.class) && - name == other_aggregation.name && - !other_aggregation.options.nil? && - active_record == other_aggregation.active_record - end - - def scope_for(klass) - scope ? klass.unscoped.instance_exec(nil, &scope) : klass.unscoped - end - - private - def derive_class_name - name.to_s.camelize - end - end - - # Holds all the metadata about an aggregation as it was specified in the - # Active Record class. - class AggregateReflection < MacroReflection #:nodoc: - def mapping - mapping = options[:mapping] || [name, name] - mapping.first.is_a?(Array) ? mapping : [mapping] - end - end - - # Holds all the metadata about an association as it was specified in the - # Active Record class. - class AssociationReflection < MacroReflection #:nodoc: - # Returns the target association's class. - # - # class Author < ActiveRecord::Base - # has_many :books - # end - # - # Author.reflect_on_association(:books).klass - # # => Book - # - # Note: Do not call +klass.new+ or +klass.create+ to instantiate - # a new association object. Use +build_association+ or +create_association+ - # instead. This allows plugins to hook into association object creation. - def klass - @klass ||= compute_class(class_name) - end - - def compute_class(name) - active_record.send(:compute_type, name) - end - - attr_reader :type, :foreign_type - attr_accessor :parent_reflection # Reflection - - def initialize(name, scope, options, active_record) - super - @type = options[:as] && (options[:foreign_type] || "#{options[:as]}_type") - @foreign_type = options[:foreign_type] || "#{name}_type" - @constructable = calculate_constructable(macro, options) - @association_scope_cache = {} - @scope_lock = Mutex.new - - if options[:class_name] && options[:class_name].class == Class - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing a class to the `class_name` is deprecated and will raise - an ArgumentError in Rails 5.2. It eagerloads more classes than - necessary and potentially creates circular dependencies. - - Please pass the class name as a string: - `#{macro} :#{name}, class_name: '#{options[:class_name]}'` - MSG - end - end - - def association_scope_cache(conn, owner) - key = conn.prepared_statements - if polymorphic? - key = [key, owner._read_attribute(@foreign_type)] - end - @association_scope_cache[key] ||= @scope_lock.synchronize { - @association_scope_cache[key] ||= yield - } - end - - def constructable? # :nodoc: - @constructable - end - - def join_table - @join_table ||= options[:join_table] || derive_join_table - end - - def foreign_key - @foreign_key ||= options[:foreign_key] || derive_foreign_key.freeze - end - - def association_foreign_key - @association_foreign_key ||= options[:association_foreign_key] || class_name.foreign_key - end - - # klass option is necessary to support loading polymorphic associations - def association_primary_key(klass = nil) - options[:primary_key] || primary_key(klass || self.klass) - end - - def association_primary_key_type - klass.type_for_attribute(association_primary_key.to_s) - end - - def active_record_primary_key - @active_record_primary_key ||= options[:primary_key] || primary_key(active_record) - end - - def check_validity! - check_validity_of_inverse! - end - - def check_preloadable! - return unless scope - - if scope.arity > 0 - raise ArgumentError, <<-MSG.squish - The association scope '#{name}' is instance dependent (the scope - block takes an argument). Preloading instance dependent scopes is - not supported. - MSG - end - end - alias :check_eager_loadable! :check_preloadable! - - def join_id_for(owner) # :nodoc: - owner[active_record_primary_key] - end - - def through_reflection - nil - end - - def source_reflection - self - end - - # A chain of reflections from this one back to the owner. For more see the explanation in - # ThroughReflection. - def collect_join_chain - [self] - end - - # This is for clearing cache on the reflection. Useful for tests that need to compare - # SQL queries on associations. - def clear_association_scope_cache # :nodoc: - @association_scope_cache.clear - end - - def nested? - false - end - - def has_scope? - scope - end - - def has_inverse? - inverse_name - end - - def polymorphic_inverse_of(associated_class) - if has_inverse? - if inverse_relationship = associated_class._reflect_on_association(options[:inverse_of]) - inverse_relationship - else - raise InverseOfAssociationNotFoundError.new(self, associated_class) - end - end - end - - # Returns the macro type. - # - # has_many :clients returns :has_many - def macro; raise NotImplementedError; end - - # Returns whether or not this association reflection is for a collection - # association. Returns +true+ if the +macro+ is either +has_many+ or - # +has_and_belongs_to_many+, +false+ otherwise. - def collection? - false - end - - # Returns whether or not the association should be validated as part of - # the parent's validation. - # - # Unless you explicitly disable validation with - # validate: false, validation will take place when: - # - # * you explicitly enable validation; validate: true - # * you use autosave; autosave: true - # * the association is a +has_many+ association - def validate? - !options[:validate].nil? ? options[:validate] : (options[:autosave] == true || collection?) - end - - # Returns +true+ if +self+ is a +belongs_to+ reflection. - def belongs_to?; false; end - - # Returns +true+ if +self+ is a +has_one+ reflection. - def has_one?; false; end - - def association_class; raise NotImplementedError; end - - def polymorphic? - options[:polymorphic] - end - - VALID_AUTOMATIC_INVERSE_MACROS = [:has_many, :has_one, :belongs_to] - INVALID_AUTOMATIC_INVERSE_OPTIONS = [:conditions, :through, :polymorphic, :foreign_key] - - def add_as_source(seed) - seed - end - - def add_as_polymorphic_through(reflection, seed) - seed + [PolymorphicReflection.new(self, reflection)] - end - - def add_as_through(seed) - seed + [self] - end - - def extensions - Array(options[:extend]) - end - - protected - - def actual_source_reflection # FIXME: this is a horrible name - self - end - - private - - def calculate_constructable(macro, options) - true - end - - # Attempts to find the inverse association name automatically. - # If it cannot find a suitable inverse association name, it returns - # +nil+. - def inverse_name - unless defined?(@inverse_name) - @inverse_name = options.fetch(:inverse_of) { automatic_inverse_of } - end - - @inverse_name - end - - # returns either +nil+ or the inverse association name that it finds. - def automatic_inverse_of - if can_find_inverse_of_automatically?(self) - inverse_name = ActiveSupport::Inflector.underscore(options[:as] || active_record.name.demodulize).to_sym - - begin - reflection = klass._reflect_on_association(inverse_name) - rescue NameError - # Give up: we couldn't compute the klass type so we won't be able - # to find any associations either. - reflection = false - end - - if valid_inverse_reflection?(reflection) - return inverse_name - end - end - end - - # Checks if the inverse reflection that is returned from the - # +automatic_inverse_of+ method is a valid reflection. We must - # make sure that the reflection's active_record name matches up - # with the current reflection's klass name. - # - # Note: klass will always be valid because when there's a NameError - # from calling +klass+, +reflection+ will already be set to false. - def valid_inverse_reflection?(reflection) - reflection && - klass.name == reflection.active_record.name && - can_find_inverse_of_automatically?(reflection) - end - - # Checks to see if the reflection doesn't have any options that prevent - # us from being able to guess the inverse automatically. First, the - # inverse_of option cannot be set to false. Second, we must - # have has_many, has_one, belongs_to associations. - # Third, we must not have options such as :polymorphic or - # :foreign_key which prevent us from correctly guessing the - # inverse association. - # - # Anything with a scope can additionally ruin our attempt at finding an - # inverse, so we exclude reflections with scopes. - def can_find_inverse_of_automatically?(reflection) - reflection.options[:inverse_of] != false && - VALID_AUTOMATIC_INVERSE_MACROS.include?(reflection.macro) && - !INVALID_AUTOMATIC_INVERSE_OPTIONS.any? { |opt| reflection.options[opt] } && - !reflection.scope - end - - def derive_class_name - class_name = name.to_s - class_name = class_name.singularize if collection? - class_name.camelize - end - - def derive_foreign_key - if belongs_to? - "#{name}_id" - elsif options[:as] - "#{options[:as]}_id" - else - active_record.name.foreign_key - end - end - - def derive_join_table - ModelSchema.derive_join_table_name active_record.table_name, klass.table_name - end - - def primary_key(klass) - klass.primary_key || raise(UnknownPrimaryKey.new(klass)) - end - end - - class HasManyReflection < AssociationReflection # :nodoc: - def macro; :has_many; end - - def collection?; true; end - - def association_class - if options[:through] - Associations::HasManyThroughAssociation - else - Associations::HasManyAssociation - end - end - - def association_primary_key(klass = nil) - primary_key(klass || self.klass) - end - end - - class HasOneReflection < AssociationReflection # :nodoc: - def macro; :has_one; end - - def has_one?; true; end - - def association_class - if options[:through] - Associations::HasOneThroughAssociation - else - Associations::HasOneAssociation - end - end - - private - - def calculate_constructable(macro, options) - !options[:through] - end - end - - class BelongsToReflection < AssociationReflection # :nodoc: - def macro; :belongs_to; end - - def belongs_to?; true; end - - def association_class - if polymorphic? - Associations::BelongsToPolymorphicAssociation - else - Associations::BelongsToAssociation - end - end - - def join_id_for(owner) # :nodoc: - owner[foreign_key] - end - - private - - def calculate_constructable(macro, options) - !polymorphic? - end - - def join_fk - foreign_key - end - - def join_pk(klass) - polymorphic? ? association_primary_key(klass) : association_primary_key - end - end - - class HasAndBelongsToManyReflection < AssociationReflection # :nodoc: - def initialize(name, scope, options, active_record) - super - end - - def macro; :has_and_belongs_to_many; end - - def collection? - true - end - end - - # Holds all the metadata about a :through association as it was specified - # in the Active Record class. - class ThroughReflection < AbstractReflection #:nodoc: - attr_reader :delegate_reflection - delegate :foreign_key, :foreign_type, :association_foreign_key, - :active_record_primary_key, :type, :get_join_keys, to: :source_reflection - - def initialize(delegate_reflection) - @delegate_reflection = delegate_reflection - @klass = delegate_reflection.options[:anonymous_class] - @source_reflection_name = delegate_reflection.options[:source] - end - - def through_reflection? - true - end - - def klass - @klass ||= delegate_reflection.compute_class(class_name) - end - - # Returns the source of the through reflection. It checks both a singularized - # and pluralized form for :belongs_to or :has_many. - # - # class Post < ActiveRecord::Base - # has_many :taggings - # has_many :tags, through: :taggings - # end - # - # class Tagging < ActiveRecord::Base - # belongs_to :post - # belongs_to :tag - # end - # - # tags_reflection = Post.reflect_on_association(:tags) - # tags_reflection.source_reflection - # # => - # - def source_reflection - through_reflection.klass._reflect_on_association(source_reflection_name) - end - - # Returns the AssociationReflection object specified in the :through option - # of a HasManyThrough or HasOneThrough association. - # - # class Post < ActiveRecord::Base - # has_many :taggings - # has_many :tags, through: :taggings - # end - # - # tags_reflection = Post.reflect_on_association(:tags) - # tags_reflection.through_reflection - # # => - # - def through_reflection - active_record._reflect_on_association(options[:through]) - end - - # Returns an array of reflections which are involved in this association. Each item in the - # array corresponds to a table which will be part of the query for this association. - # - # The chain is built by recursively calling #chain on the source reflection and the through - # reflection. The base case for the recursion is a normal association, which just returns - # [self] as its #chain. - # - # class Post < ActiveRecord::Base - # has_many :taggings - # has_many :tags, through: :taggings - # end - # - # tags_reflection = Post.reflect_on_association(:tags) - # tags_reflection.chain - # # => [, - # ] - # - def collect_join_chain - collect_join_reflections [self] - end - - # This is for clearing cache on the reflection. Useful for tests that need to compare - # SQL queries on associations. - def clear_association_scope_cache # :nodoc: - delegate_reflection.clear_association_scope_cache - source_reflection.clear_association_scope_cache - through_reflection.clear_association_scope_cache - end - - def scopes - source_reflection.scopes + super - end - - def join_scopes(table, predicate_builder) # :nodoc: - source_reflection.join_scopes(table, predicate_builder) + super - end - - def source_type_scope - through_reflection.klass.where(foreign_type => options[:source_type]) - end - - def has_scope? - scope || options[:source_type] || - source_reflection.has_scope? || - through_reflection.has_scope? - end - - # A through association is nested if there would be more than one join table - def nested? - source_reflection.through_reflection? || through_reflection.through_reflection? - end - - # We want to use the klass from this reflection, rather than just delegate straight to - # the source_reflection, because the source_reflection may be polymorphic. We still - # need to respect the source_reflection's :primary_key option, though. - def association_primary_key(klass = nil) - # Get the "actual" source reflection if the immediate source reflection has a - # source reflection itself - actual_source_reflection.options[:primary_key] || primary_key(klass || self.klass) - end - - def association_primary_key_type - klass.type_for_attribute(association_primary_key.to_s) - end - - # Gets an array of possible :through source reflection names in both singular and plural form. - # - # class Post < ActiveRecord::Base - # has_many :taggings - # has_many :tags, through: :taggings - # end - # - # tags_reflection = Post.reflect_on_association(:tags) - # tags_reflection.source_reflection_names - # # => [:tag, :tags] - # - def source_reflection_names - options[:source] ? [options[:source]] : [name.to_s.singularize, name].uniq - end - - def source_reflection_name # :nodoc: - return @source_reflection_name if @source_reflection_name - - names = [name.to_s.singularize, name].collect(&:to_sym).uniq - names = names.find_all { |n| - through_reflection.klass._reflect_on_association(n) - } - - if names.length > 1 - raise AmbiguousSourceReflectionForThroughAssociation.new( - active_record.name, - macro, - name, - options, - source_reflection_names - ) - end - - @source_reflection_name = names.first - end - - def source_options - source_reflection.options - end - - def through_options - through_reflection.options - end - - def join_id_for(owner) # :nodoc: - source_reflection.join_id_for(owner) - end - - def check_validity! - if through_reflection.nil? - raise HasManyThroughAssociationNotFoundError.new(active_record.name, self) - end - - if through_reflection.polymorphic? - if has_one? - raise HasOneAssociationPolymorphicThroughError.new(active_record.name, self) - else - raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self) - end - end - - if source_reflection.nil? - raise HasManyThroughSourceAssociationNotFoundError.new(self) - end - - if options[:source_type] && !source_reflection.polymorphic? - raise HasManyThroughAssociationPointlessSourceTypeError.new(active_record.name, self, source_reflection) - end - - if source_reflection.polymorphic? && options[:source_type].nil? - raise HasManyThroughAssociationPolymorphicSourceError.new(active_record.name, self, source_reflection) - end - - if has_one? && through_reflection.collection? - raise HasOneThroughCantAssociateThroughCollection.new(active_record.name, self, through_reflection) - end - - if parent_reflection.nil? - reflections = active_record.reflections.keys.map(&:to_sym) - - if reflections.index(through_reflection.name) > reflections.index(name) - raise HasManyThroughOrderError.new(active_record.name, self, through_reflection) - end - end - - check_validity_of_inverse! - end - - def constraints - scope_chain = source_reflection.constraints - scope_chain << scope if scope - scope_chain - end - - def add_as_source(seed) - collect_join_reflections seed - end - - def add_as_polymorphic_through(reflection, seed) - collect_join_reflections(seed + [PolymorphicReflection.new(self, reflection)]) - end - - def add_as_through(seed) - collect_join_reflections(seed + [self]) - end - - def collect_join_reflections(seed) - a = source_reflection.add_as_source seed - if options[:source_type] - through_reflection.add_as_polymorphic_through self, a - else - through_reflection.add_as_through a - end - end - - private - - def actual_source_reflection # FIXME: this is a horrible name - source_reflection.send(:actual_source_reflection) - end - - def primary_key(klass) - klass.primary_key || raise(UnknownPrimaryKey.new(klass)) - end - - def inverse_name; delegate_reflection.send(:inverse_name); end - - def derive_class_name - # get the class_name of the belongs_to association of the through reflection - options[:source_type] || source_reflection.class_name - end - - delegate_methods = AssociationReflection.public_instance_methods - - public_instance_methods - - delegate(*delegate_methods, to: :delegate_reflection) - end - - class PolymorphicReflection < AbstractReflection # :nodoc: - def initialize(reflection, previous_reflection) - @reflection = reflection - @previous_reflection = previous_reflection - end - - def scopes - scopes = @previous_reflection.scopes - if @previous_reflection.options[:source_type] - scopes + [@previous_reflection.source_type_scope] - else - scopes - end - end - - def join_scopes(table, predicate_builder) # :nodoc: - scopes = @previous_reflection.join_scopes(table, predicate_builder) + super - if @previous_reflection.options[:source_type] - scopes + [@previous_reflection.source_type_scope] - else - scopes - end - end - - def klass - @reflection.klass - end - - def scope - @reflection.scope - end - - def table_name - @reflection.table_name - end - - def plural_name - @reflection.plural_name - end - - def type - @reflection.type - end - - def constraints - @reflection.constraints + [source_type_info] - end - - def source_type_info - type = @previous_reflection.foreign_type - source_type = @previous_reflection.options[:source_type] - lambda { |object| where(type => source_type) } - end - - def get_join_keys(association_klass) - @reflection.get_join_keys(association_klass) - end - end - - class RuntimeReflection < PolymorphicReflection # :nodoc: - attr_accessor :next - - def initialize(reflection, association) - @reflection = reflection - @association = association - end - - def klass - @association.klass - end - - def table_name - klass.table_name - end - - def constraints - @reflection.constraints - end - - def source_type_info - @reflection.source_type_info - end - - def alias_candidate(name) - "#{plural_name}_#{name}_join" - end - - def alias_name - Arel::Table.new(table_name, type_caster: klass.type_caster) - end - - def all_includes; yield; end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation.rb deleted file mode 100644 index a0f3b574ed..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation.rb +++ /dev/null @@ -1,723 +0,0 @@ -module ActiveRecord - # = Active Record \Relation - class Relation - MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group, - :order, :joins, :left_joins, :left_outer_joins, :references, - :extending, :unscope] - - SINGLE_VALUE_METHODS = [:limit, :offset, :lock, :readonly, :reordering, - :reverse_order, :distinct, :create_with] - CLAUSE_METHODS = [:where, :having, :from] - INVALID_METHODS_FOR_DELETE_ALL = [:limit, :distinct, :offset, :group, :having] - - VALUE_METHODS = MULTI_VALUE_METHODS + SINGLE_VALUE_METHODS + CLAUSE_METHODS - - include Enumerable - include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation - - attr_reader :table, :klass, :loaded, :predicate_builder - alias :model :klass - alias :loaded? :loaded - - def initialize(klass, table, predicate_builder, values = {}) - @klass = klass - @table = table - @values = values - @offsets = {} - @loaded = false - @predicate_builder = predicate_builder - end - - def initialize_copy(other) - @values = @values.dup - reset - end - - def insert(values) # :nodoc: - primary_key_value = nil - - if primary_key && Hash === values - primary_key_value = values[values.keys.find { |k| - k.name == primary_key - }] - - if !primary_key_value && klass.prefetch_primary_key? - primary_key_value = klass.next_sequence_value - values[arel_attribute(klass.primary_key)] = primary_key_value - end - end - - im = arel.create_insert - im.into @table - - substitutes, binds = substitute_values values - - if values.empty? # empty insert - im.values = Arel.sql(connection.empty_insert_statement_value) - else - im.insert substitutes - end - - @klass.connection.insert( - im, - "SQL", - primary_key || false, - primary_key_value, - nil, - binds) - end - - def _update_record(values, constraints) # :nodoc: - substitutes, binds = substitute_values values - - scope = @klass.unscoped - - if @klass.finder_needs_type_condition? - scope.unscope!(where: @klass.inheritance_column) - end - - relation = scope.where(constraints) - bvs = binds + relation.bound_attributes - um = relation - .arel - .compile_update(substitutes, @klass.primary_key) - - @klass.connection.update( - um, - "SQL", - bvs, - ) - end - - def substitute_values(values) # :nodoc: - binds = [] - substitutes = [] - - values.each do |arel_attr, value| - binds.push QueryAttribute.new(arel_attr.name, value, klass.type_for_attribute(arel_attr.name)) - substitutes.push [arel_attr, Arel::Nodes::BindParam.new] - end - - [substitutes, binds] - end - - def arel_attribute(name) # :nodoc: - klass.arel_attribute(name, table) - end - - # Initializes new record from relation while maintaining the current - # scope. - # - # Expects arguments in the same format as {ActiveRecord::Base.new}[rdoc-ref:Core.new]. - # - # users = User.where(name: 'DHH') - # user = users.new # => # - # - # You can also pass a block to new with the new record as argument: - # - # user = users.new { |user| user.name = 'Oscar' } - # user.name # => Oscar - def new(*args, &block) - scoping { @klass.new(*args, &block) } - end - - alias build new - - # Tries to create a new record with the same scoped attributes - # defined in the relation. Returns the initialized object if validation fails. - # - # Expects arguments in the same format as - # {ActiveRecord::Base.create}[rdoc-ref:Persistence::ClassMethods#create]. - # - # ==== Examples - # - # users = User.where(name: 'Oscar') - # users.create # => # - # - # users.create(name: 'fxn') - # users.create # => # - # - # users.create { |user| user.name = 'tenderlove' } - # # => # - # - # users.create(name: nil) # validation on name - # # => # - def create(*args, &block) - scoping { @klass.create(*args, &block) } - end - - # Similar to #create, but calls - # {create!}[rdoc-ref:Persistence::ClassMethods#create!] - # on the base class. Raises an exception if a validation error occurs. - # - # Expects arguments in the same format as - # {ActiveRecord::Base.create!}[rdoc-ref:Persistence::ClassMethods#create!]. - def create!(*args, &block) - scoping { @klass.create!(*args, &block) } - end - - def first_or_create(attributes = nil, &block) # :nodoc: - first || create(attributes, &block) - end - - def first_or_create!(attributes = nil, &block) # :nodoc: - first || create!(attributes, &block) - end - - def first_or_initialize(attributes = nil, &block) # :nodoc: - first || new(attributes, &block) - end - - # Finds the first record with the given attributes, or creates a record - # with the attributes if one is not found: - # - # # Find the first user named "Penélope" or create a new one. - # User.find_or_create_by(first_name: 'Penélope') - # # => # - # - # # Find the first user named "Penélope" or create a new one. - # # We already have one so the existing record will be returned. - # User.find_or_create_by(first_name: 'Penélope') - # # => # - # - # # Find the first user named "Scarlett" or create a new one with - # # a particular last name. - # User.create_with(last_name: 'Johansson').find_or_create_by(first_name: 'Scarlett') - # # => # - # - # This method accepts a block, which is passed down to #create. The last example - # above can be alternatively written this way: - # - # # Find the first user named "Scarlett" or create a new one with a - # # different last name. - # User.find_or_create_by(first_name: 'Scarlett') do |user| - # user.last_name = 'Johansson' - # end - # # => # - # - # This method always returns a record, but if creation was attempted and - # failed due to validation errors it won't be persisted, you get what - # #create returns in such situation. - # - # Please note *this method is not atomic*, it runs first a SELECT, and if - # there are no results an INSERT is attempted. If there are other threads - # or processes there is a race condition between both calls and it could - # be the case that you end up with two similar records. - # - # Whether that is a problem or not depends on the logic of the - # application, but in the particular case in which rows have a UNIQUE - # constraint an exception may be raised, just retry: - # - # begin - # CreditAccount.transaction(requires_new: true) do - # CreditAccount.find_or_create_by(user_id: user.id) - # end - # rescue ActiveRecord::RecordNotUnique - # retry - # end - # - def find_or_create_by(attributes, &block) - find_by(attributes) || create(attributes, &block) - end - - # Like #find_or_create_by, but calls - # {create!}[rdoc-ref:Persistence::ClassMethods#create!] so an exception - # is raised if the created record is invalid. - def find_or_create_by!(attributes, &block) - find_by(attributes) || create!(attributes, &block) - end - - # Like #find_or_create_by, but calls {new}[rdoc-ref:Core#new] - # instead of {create}[rdoc-ref:Persistence::ClassMethods#create]. - def find_or_initialize_by(attributes, &block) - find_by(attributes) || new(attributes, &block) - end - - # Runs EXPLAIN on the query or queries triggered by this relation and - # returns the result as a string. The string is formatted imitating the - # ones printed by the database shell. - # - # Note that this method actually runs the queries, since the results of some - # are needed by the next ones when eager loading is going on. - # - # Please see further details in the - # {Active Record Query Interface guide}[http://guides.rubyonrails.org/active_record_querying.html#running-explain]. - def explain - exec_explain(collecting_queries_for_explain { exec_queries }) - end - - # Converts relation objects to Array. - def to_a - records.dup - end - - def records # :nodoc: - load - @records - end - - # Serializes the relation objects Array. - def encode_with(coder) - coder.represent_seq(nil, records) - end - - # Returns size of the records. - def size - loaded? ? @records.length : count(:all) - end - - # Returns true if there are no records. - def empty? - return @records.empty? if loaded? - !exists? - end - - # Returns true if there are no records. - def none? - return super if block_given? - empty? - end - - # Returns true if there are any records. - def any? - return super if block_given? - !empty? - end - - # Returns true if there is exactly one record. - def one? - return super if block_given? - limit_value ? records.one? : size == 1 - end - - # Returns true if there is more than one record. - def many? - return super if block_given? - limit_value ? records.many? : size > 1 - end - - # Returns a cache key that can be used to identify the records fetched by - # this query. The cache key is built with a fingerprint of the sql query, - # the number of records matched by the query and a timestamp of the last - # updated record. When a new record comes to match the query, or any of - # the existing records is updated or deleted, the cache key changes. - # - # Product.where("name like ?", "%Cosmic Encounter%").cache_key - # # => "products/query-1850ab3d302391b85b8693e941286659-1-20150714212553907087000" - # - # If the collection is loaded, the method will iterate through the records - # to generate the timestamp, otherwise it will trigger one SQL query like: - # - # SELECT COUNT(*), MAX("products"."updated_at") FROM "products" WHERE (name like '%Cosmic Encounter%') - # - # You can also pass a custom timestamp column to fetch the timestamp of the - # last updated record. - # - # Product.where("name like ?", "%Game%").cache_key(:last_reviewed_at) - # - # You can customize the strategy to generate the key on a per model basis - # overriding ActiveRecord::Base#collection_cache_key. - def cache_key(timestamp_column = :updated_at) - @cache_keys ||= {} - @cache_keys[timestamp_column] ||= @klass.collection_cache_key(self, timestamp_column) - end - - # Scope all queries to the current scope. - # - # Comment.where(post_id: 1).scoping do - # Comment.first - # end - # # => SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = 1 ORDER BY "comments"."id" ASC LIMIT 1 - # - # Please check unscoped if you want to remove all previous scopes (including - # the default_scope) during the execution of a block. - def scoping - previous, klass.current_scope = klass.current_scope(true), self - yield - ensure - klass.current_scope = previous - end - - # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE - # statement and sends it straight to the database. It does not instantiate the involved models and it does not - # trigger Active Record callbacks or validations. However, values passed to #update_all will still go through - # Active Record's normal type casting and serialization. - # - # ==== Parameters - # - # * +updates+ - A string, array, or hash representing the SET part of an SQL statement. - # - # ==== Examples - # - # # Update all customers with the given attributes - # Customer.update_all wants_email: true - # - # # Update all books with 'Rails' in their title - # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David') - # - # # Update all books that match conditions, but limit it to 5 ordered by date - # Book.where('title LIKE ?', '%Rails%').order(:created_at).limit(5).update_all(author: 'David') - # - # # Update all invoices and set the number column to its id value. - # Invoice.update_all('number = id') - def update_all(updates) - raise ArgumentError, "Empty list of attributes to change" if updates.blank? - - stmt = Arel::UpdateManager.new - - stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)) - stmt.table(table) - - if has_join_values? - @klass.connection.join_to_update(stmt, arel, arel_attribute(primary_key)) - else - stmt.key = arel_attribute(primary_key) - stmt.take(arel.limit) - stmt.order(*arel.orders) - stmt.wheres = arel.constraints - end - - @klass.connection.update stmt, "SQL", bound_attributes - end - - # Updates an object (or multiple objects) and saves it to the database, if validations pass. - # The resulting object is returned whether the object was saved successfully to the database or not. - # - # ==== Parameters - # - # * +id+ - This should be the id or an array of ids to be updated. - # * +attributes+ - This should be a hash of attributes or an array of hashes. - # - # ==== Examples - # - # # Updates one record - # Person.update(15, user_name: 'Samuel', group: 'expert') - # - # # Updates multiple records - # people = { 1 => { "first_name" => "David" }, 2 => { "first_name" => "Jeremy" } } - # Person.update(people.keys, people.values) - # - # # Updates multiple records from the result of a relation - # people = Person.where(group: 'expert') - # people.update(group: 'masters') - # - # Note: Updating a large number of records will run an - # UPDATE query for each record, which may cause a performance - # issue. So if it is not needed to run callbacks for each update, it is - # preferred to use #update_all for updating all records using - # a single query. - def update(id = :all, attributes) - if id.is_a?(Array) - id.map.with_index { |one_id, idx| update(one_id, attributes[idx]) } - elsif id == :all - records.each { |record| record.update(attributes) } - else - if ActiveRecord::Base === id - raise ArgumentError, <<-MSG.squish - You are passing an instance of ActiveRecord::Base to `update`. - Please pass the id of the object by calling `.id`. - MSG - end - object = find(id) - object.update(attributes) - object - end - end - - # Destroys the records by instantiating each - # record and calling its {#destroy}[rdoc-ref:Persistence#destroy] method. - # Each object's callbacks are executed (including :dependent association options). - # Returns the collection of objects that were destroyed; each will be frozen, to - # reflect that no changes should be made (since they can't be persisted). - # - # Note: Instantiation, callback execution, and deletion of each - # record can be time consuming when you're removing many records at - # once. It generates at least one SQL +DELETE+ query per record (or - # possibly more, to enforce your callbacks). If you want to delete many - # rows quickly, without concern for their associations or callbacks, use - # #delete_all instead. - # - # ==== Examples - # - # Person.where(age: 0..18).destroy_all - def destroy_all - records.each(&:destroy).tap { reset } - end - - # Destroy an object (or multiple objects) that has the given id. The object is instantiated first, - # therefore all callbacks and filters are fired off before the object is deleted. This method is - # less efficient than #delete but allows cleanup methods and other actions to be run. - # - # This essentially finds the object (or multiple objects) with the given id, creates a new object - # from the attributes, and then calls destroy on it. - # - # ==== Parameters - # - # * +id+ - Can be either an Integer or an Array of Integers. - # - # ==== Examples - # - # # Destroy a single object - # Todo.destroy(1) - # - # # Destroy multiple objects - # todos = [1,2,3] - # Todo.destroy(todos) - def destroy(id) - if id.is_a?(Array) - id.map { |one_id| destroy(one_id) } - else - find(id).destroy - end - end - - # Deletes the records without instantiating the records - # first, and hence not calling the {#destroy}[rdoc-ref:Persistence#destroy] - # method nor invoking callbacks. - # This is a single SQL DELETE statement that goes straight to the database, much more - # efficient than #destroy_all. Be careful with relations though, in particular - # :dependent rules defined on associations are not honored. Returns the - # number of rows affected. - # - # Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all - # - # Both calls delete the affected posts all at once with a single DELETE statement. - # If you need to destroy dependent associations or call your before_* or - # +after_destroy+ callbacks, use the #destroy_all method instead. - # - # If an invalid method is supplied, #delete_all raises an ActiveRecordError: - # - # Post.limit(100).delete_all - # # => ActiveRecord::ActiveRecordError: delete_all doesn't support limit - def delete_all - invalid_methods = INVALID_METHODS_FOR_DELETE_ALL.select do |method| - value = get_value(method) - SINGLE_VALUE_METHODS.include?(method) ? value : value.any? - end - if invalid_methods.any? - raise ActiveRecordError.new("delete_all doesn't support #{invalid_methods.join(', ')}") - end - - stmt = Arel::DeleteManager.new - stmt.from(table) - - if has_join_values? - @klass.connection.join_to_delete(stmt, arel, arel_attribute(primary_key)) - else - stmt.wheres = arel.constraints - end - - affected = @klass.connection.delete(stmt, "SQL", bound_attributes) - - reset - affected - end - - # Deletes the row with a primary key matching the +id+ argument, using a - # SQL +DELETE+ statement, and returns the number of rows deleted. Active - # Record objects are not instantiated, so the object's callbacks are not - # executed, including any :dependent association options. - # - # You can delete multiple rows at once by passing an Array of ids. - # - # Note: Although it is often much faster than the alternative, - # #destroy, skipping callbacks might bypass business logic in - # your application that ensures referential integrity or performs other - # essential jobs. - # - # ==== Examples - # - # # Delete a single row - # Todo.delete(1) - # - # # Delete multiple rows - # Todo.delete([2,3,4]) - def delete(id_or_array) - where(primary_key => id_or_array).delete_all - end - - # Causes the records to be loaded from the database if they have not - # been loaded already. You can use this if for some reason you need - # to explicitly load some records before actually using them. The - # return value is the relation itself, not the records. - # - # Post.where(published: true).load # => # - def load(&block) - exec_queries(&block) unless loaded? - - self - end - - # Forces reloading of relation. - def reload - reset - load - end - - def reset - @last = @to_sql = @order_clause = @scope_for_create = @arel = @loaded = nil - @should_eager_load = @join_dependency = nil - @records = [].freeze - @offsets = {} - self - end - - # Returns sql statement for the relation. - # - # User.where(name: 'Oscar').to_sql - # # => SELECT "users".* FROM "users" WHERE "users"."name" = 'Oscar' - def to_sql - @to_sql ||= begin - relation = self - - if eager_loading? - find_with_associations { |rel, _| relation = rel } - end - - conn = klass.connection - conn.unprepared_statement { - conn.to_sql(relation.arel, relation.bound_attributes) - } - end - end - - # Returns a hash of where conditions. - # - # User.where(name: 'Oscar').where_values_hash - # # => {name: "Oscar"} - def where_values_hash(relation_table_name = table_name) - where_clause.to_h(relation_table_name) - end - - def scope_for_create - @scope_for_create ||= where_values_hash.merge(create_with_value) - end - - # Returns true if relation needs eager loading. - def eager_loading? - @should_eager_load ||= - eager_load_values.any? || - includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?) - end - - # Joins that are also marked for preloading. In which case we should just eager load them. - # Note that this is a naive implementation because we could have strings and symbols which - # represent the same association, but that aren't matched by this. Also, we could have - # nested hashes which partially match, e.g. { a: :b } & { a: [:b, :c] } - def joined_includes_values - includes_values & joins_values - end - - # Compares two relations for equality. - def ==(other) - case other - when Associations::CollectionProxy, AssociationRelation - self == other.records - when Relation - other.to_sql == to_sql - when Array - records == other - end - end - - def pretty_print(q) - q.pp(records) - end - - # Returns true if relation is blank. - def blank? - records.blank? - end - - def values - @values.dup - end - - def inspect - subject = loaded? ? records : self - entries = subject.take([limit_value, 11].compact.min).map!(&:inspect) - - entries[10] = "..." if entries.size == 11 - - "#<#{self.class.name} [#{entries.join(', ')}]>" - end - - def empty_scope? # :nodoc: - @values == klass.unscoped.values - end - - def has_limit_or_offset? # :nodoc: - limit_value || offset_value - end - - protected - - def load_records(records) - @records = records.freeze - @loaded = true - end - - private - - def has_join_values? - joins_values.any? || left_outer_joins_values.any? - end - - def exec_queries(&block) - @records = - if eager_loading? - find_with_associations do |relation, join_dependency| - if ActiveRecord::NullRelation === relation - [] - else - rows = connection.select_all(relation.arel, "SQL", relation.bound_attributes) - join_dependency.instantiate(rows, &block) - end.freeze - end - else - klass.find_by_sql(arel, bound_attributes, &block).freeze - end - - preload = preload_values - preload += includes_values unless eager_loading? - preloader = nil - preload.each do |associations| - preloader ||= build_preloader - preloader.preload @records, associations - end - - @records.each(&:readonly!) if readonly_value - - @loaded = true - @records - end - - def build_preloader - ActiveRecord::Associations::Preloader.new - end - - def references_eager_loaded_tables? - joined_tables = arel.join_sources.map do |join| - if join.is_a?(Arel::Nodes::StringJoin) - tables_in_string(join.left) - else - [join.left.table_name, join.left.table_alias] - end - end - - joined_tables += [table.name, table.table_alias] - - # always convert table names to downcase as in Oracle quoted table names are in uppercase - joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq - - (references_values - joined_tables).any? - end - - def tables_in_string(string) - return [] if string.blank? - # always convert table names to downcase as in Oracle quoted table names are in uppercase - # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries - string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ["raw_sql_"] - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/batches.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/batches.rb deleted file mode 100644 index 13a2c3f511..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/batches.rb +++ /dev/null @@ -1,272 +0,0 @@ -require "active_record/relation/batches/batch_enumerator" - -module ActiveRecord - module Batches - ORDER_IGNORE_MESSAGE = "Scoped order is ignored, it's forced to be batch order." - - # Looping through a collection of records from the database - # (using the Scoping::Named::ClassMethods.all method, for example) - # is very inefficient since it will try to instantiate all the objects at once. - # - # In that case, batch processing methods allow you to work - # with the records in batches, thereby greatly reducing memory consumption. - # - # The #find_each method uses #find_in_batches with a batch size of 1000 (or as - # specified by the +:batch_size+ option). - # - # Person.find_each do |person| - # person.do_awesome_stuff - # end - # - # Person.where("age > 21").find_each do |person| - # person.party_all_night! - # end - # - # If you do not provide a block to #find_each, it will return an Enumerator - # for chaining with other methods: - # - # Person.find_each.with_index do |person, index| - # person.award_trophy(index + 1) - # end - # - # ==== Options - # * :batch_size - Specifies the size of the batch. Defaults to 1000. - # * :start - Specifies the primary key value to start from, inclusive of the value. - # * :finish - Specifies the primary key value to end at, inclusive of the value. - # * :error_on_ignore - Overrides the application config to specify if an error should be raised when - # an order is present in the relation. - # - # Limits are honored, and if present there is no requirement for the batch - # size: it can be less than, equal to, or greater than the limit. - # - # The options +start+ and +finish+ are especially useful if you want - # multiple workers dealing with the same processing queue. You can make - # worker 1 handle all the records between id 1 and 9999 and worker 2 - # handle from 10000 and beyond by setting the +:start+ and +:finish+ - # option on each worker. - # - # # Let's process from record 10_000 on. - # Person.find_each(start: 10_000) do |person| - # person.party_all_night! - # end - # - # NOTE: It's not possible to set the order. That is automatically set to - # ascending on the primary key ("id ASC") to make the batch ordering - # work. This also means that this method only works when the primary key is - # orderable (e.g. an integer or string). - # - # NOTE: By its nature, batch processing is subject to race conditions if - # other processes are modifying the database. - def find_each(start: nil, finish: nil, batch_size: 1000, error_on_ignore: nil) - if block_given? - find_in_batches(start: start, finish: finish, batch_size: batch_size, error_on_ignore: error_on_ignore) do |records| - records.each { |record| yield record } - end - else - enum_for(:find_each, start: start, finish: finish, batch_size: batch_size, error_on_ignore: error_on_ignore) do - relation = self - apply_limits(relation, start, finish).size - end - end - end - - # Yields each batch of records that was found by the find options as - # an array. - # - # Person.where("age > 21").find_in_batches do |group| - # sleep(50) # Make sure it doesn't get too crowded in there! - # group.each { |person| person.party_all_night! } - # end - # - # If you do not provide a block to #find_in_batches, it will return an Enumerator - # for chaining with other methods: - # - # Person.find_in_batches.with_index do |group, batch| - # puts "Processing group ##{batch}" - # group.each(&:recover_from_last_night!) - # end - # - # To be yielded each record one by one, use #find_each instead. - # - # ==== Options - # * :batch_size - Specifies the size of the batch. Defaults to 1000. - # * :start - Specifies the primary key value to start from, inclusive of the value. - # * :finish - Specifies the primary key value to end at, inclusive of the value. - # * :error_on_ignore - Overrides the application config to specify if an error should be raised when - # an order is present in the relation. - # - # Limits are honored, and if present there is no requirement for the batch - # size: it can be less than, equal to, or greater than the limit. - # - # The options +start+ and +finish+ are especially useful if you want - # multiple workers dealing with the same processing queue. You can make - # worker 1 handle all the records between id 1 and 9999 and worker 2 - # handle from 10000 and beyond by setting the +:start+ and +:finish+ - # option on each worker. - # - # # Let's process from record 10_000 on. - # Person.find_in_batches(start: 10_000) do |group| - # group.each { |person| person.party_all_night! } - # end - # - # NOTE: It's not possible to set the order. That is automatically set to - # ascending on the primary key ("id ASC") to make the batch ordering - # work. This also means that this method only works when the primary key is - # orderable (e.g. an integer or string). - # - # NOTE: By its nature, batch processing is subject to race conditions if - # other processes are modifying the database. - def find_in_batches(start: nil, finish: nil, batch_size: 1000, error_on_ignore: nil) - relation = self - unless block_given? - return to_enum(:find_in_batches, start: start, finish: finish, batch_size: batch_size, error_on_ignore: error_on_ignore) do - total = apply_limits(relation, start, finish).size - (total - 1).div(batch_size) + 1 - end - end - - in_batches(of: batch_size, start: start, finish: finish, load: true, error_on_ignore: error_on_ignore) do |batch| - yield batch.to_a - end - end - - # Yields ActiveRecord::Relation objects to work with a batch of records. - # - # Person.where("age > 21").in_batches do |relation| - # relation.delete_all - # sleep(10) # Throttle the delete queries - # end - # - # If you do not provide a block to #in_batches, it will return a - # BatchEnumerator which is enumerable. - # - # Person.in_batches.each_with_index do |relation, batch_index| - # puts "Processing relation ##{batch_index}" - # relation.delete_all - # end - # - # Examples of calling methods on the returned BatchEnumerator object: - # - # Person.in_batches.delete_all - # Person.in_batches.update_all(awesome: true) - # Person.in_batches.each_record(&:party_all_night!) - # - # ==== Options - # * :of - Specifies the size of the batch. Defaults to 1000. - # * :load - Specifies if the relation should be loaded. Defaults to false. - # * :start - Specifies the primary key value to start from, inclusive of the value. - # * :finish - Specifies the primary key value to end at, inclusive of the value. - # * :error_on_ignore - Overrides the application config to specify if an error should be raised when - # an order is present in the relation. - # - # Limits are honored, and if present there is no requirement for the batch - # size, it can be less than, equal, or greater than the limit. - # - # The options +start+ and +finish+ are especially useful if you want - # multiple workers dealing with the same processing queue. You can make - # worker 1 handle all the records between id 1 and 9999 and worker 2 - # handle from 10000 and beyond by setting the +:start+ and +:finish+ - # option on each worker. - # - # # Let's process from record 10_000 on. - # Person.in_batches(start: 10_000).update_all(awesome: true) - # - # An example of calling where query method on the relation: - # - # Person.in_batches.each do |relation| - # relation.update_all('age = age + 1') - # relation.where('age > 21').update_all(should_party: true) - # relation.where('age <= 21').delete_all - # end - # - # NOTE: If you are going to iterate through each record, you should call - # #each_record on the yielded BatchEnumerator: - # - # Person.in_batches.each_record(&:party_all_night!) - # - # NOTE: It's not possible to set the order. That is automatically set to - # ascending on the primary key ("id ASC") to make the batch ordering - # consistent. Therefore the primary key must be orderable, e.g. an integer - # or a string. - # - # NOTE: By its nature, batch processing is subject to race conditions if - # other processes are modifying the database. - def in_batches(of: 1000, start: nil, finish: nil, load: false, error_on_ignore: nil) - relation = self - unless block_given? - return BatchEnumerator.new(of: of, start: start, finish: finish, relation: self) - end - - if arel.orders.present? - act_on_ignored_order(error_on_ignore) - end - - batch_limit = of - if limit_value - remaining = limit_value - batch_limit = remaining if remaining < batch_limit - end - - relation = relation.reorder(batch_order).limit(batch_limit) - relation = apply_limits(relation, start, finish) - batch_relation = relation - - loop do - if load - records = batch_relation.records - ids = records.map(&:id) - yielded_relation = where(primary_key => ids) - yielded_relation.load_records(records) - else - ids = batch_relation.pluck(primary_key) - yielded_relation = where(primary_key => ids) - end - - break if ids.empty? - - primary_key_offset = ids.last - raise ArgumentError.new("Primary key not included in the custom select clause") unless primary_key_offset - - yield yielded_relation - - break if ids.length < batch_limit - - if limit_value - remaining -= ids.length - - if remaining == 0 - # Saves a useless iteration when the limit is a multiple of the - # batch size. - break - elsif remaining < batch_limit - relation = relation.limit(remaining) - end - end - - batch_relation = relation.where(arel_attribute(primary_key).gt(primary_key_offset)) - end - end - - private - - def apply_limits(relation, start, finish) - relation = relation.where(arel_attribute(primary_key).gteq(start)) if start - relation = relation.where(arel_attribute(primary_key).lteq(finish)) if finish - relation - end - - def batch_order - "#{quoted_table_name}.#{quoted_primary_key} ASC" - end - - def act_on_ignored_order(error_on_ignore) - raise_error = (error_on_ignore.nil? ? klass.error_on_ignored_order : error_on_ignore) - - if raise_error - raise ArgumentError.new(ORDER_IGNORE_MESSAGE) - elsif logger - logger.warn(ORDER_IGNORE_MESSAGE) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/batches/batch_enumerator.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/batches/batch_enumerator.rb deleted file mode 100644 index 3555779ec2..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/batches/batch_enumerator.rb +++ /dev/null @@ -1,67 +0,0 @@ -module ActiveRecord - module Batches - class BatchEnumerator - include Enumerable - - def initialize(of: 1000, start: nil, finish: nil, relation:) #:nodoc: - @of = of - @relation = relation - @start = start - @finish = finish - end - - # Looping through a collection of records from the database (using the - # +all+ method, for example) is very inefficient since it will try to - # instantiate all the objects at once. - # - # In that case, batch processing methods allow you to work with the - # records in batches, thereby greatly reducing memory consumption. - # - # Person.in_batches.each_record do |person| - # person.do_awesome_stuff - # end - # - # Person.where("age > 21").in_batches(of: 10).each_record do |person| - # person.party_all_night! - # end - # - # If you do not provide a block to #each_record, it will return an Enumerator - # for chaining with other methods: - # - # Person.in_batches.each_record.with_index do |person, index| - # person.award_trophy(index + 1) - # end - def each_record - return to_enum(:each_record) unless block_given? - - @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: true).each do |relation| - relation.records.each { |record| yield record } - end - end - - # Delegates #delete_all, #update_all, #destroy_all methods to each batch. - # - # People.in_batches.delete_all - # People.where('age < 10').in_batches.destroy_all - # People.in_batches.update_all('age = age + 1') - [:delete_all, :update_all, :destroy_all].each do |method| - define_method(method) do |*args, &block| - @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: false).each do |relation| - relation.send(method, *args, &block) - end - end - end - - # Yields an ActiveRecord::Relation object for each batch of records. - # - # Person.in_batches.each do |relation| - # relation.update_all(awesome: true) - # end - def each - enum = @relation.to_enum(:in_batches, of: @of, start: @start, finish: @finish, load: false) - return enum.each { |relation| yield relation } if block_given? - enum - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/calculations.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/calculations.rb deleted file mode 100644 index b6cc29bdda..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/calculations.rb +++ /dev/null @@ -1,392 +0,0 @@ -module ActiveRecord - module Calculations - # Count the records. - # - # Person.count - # # => the total count of all people - # - # Person.count(:age) - # # => returns the total count of all people whose age is present in database - # - # Person.count(:all) - # # => performs a COUNT(*) (:all is an alias for '*') - # - # Person.distinct.count(:age) - # # => counts the number of different age values - # - # If #count is used with {Relation#group}[rdoc-ref:QueryMethods#group], - # it returns a Hash whose keys represent the aggregated column, - # and the values are the respective amounts: - # - # Person.group(:city).count - # # => { 'Rome' => 5, 'Paris' => 3 } - # - # If #count is used with {Relation#group}[rdoc-ref:QueryMethods#group] for multiple columns, it returns a Hash whose - # keys are an array containing the individual values of each column and the value - # of each key would be the #count. - # - # Article.group(:status, :category).count - # # => {["draft", "business"]=>10, ["draft", "technology"]=>4, - # ["published", "business"]=>0, ["published", "technology"]=>2} - # - # If #count is used with {Relation#select}[rdoc-ref:QueryMethods#select], it will count the selected columns: - # - # Person.select(:age).count - # # => counts the number of different age values - # - # Note: not all valid {Relation#select}[rdoc-ref:QueryMethods#select] expressions are valid #count expressions. The specifics differ - # between databases. In invalid cases, an error from the database is thrown. - def count(column_name = nil) - return super() if block_given? - calculate(:count, column_name) - end - - # Calculates the average value on a given column. Returns +nil+ if there's - # no row. See #calculate for examples with options. - # - # Person.average(:age) # => 35.8 - def average(column_name) - calculate(:average, column_name) - end - - # Calculates the minimum value on a given column. The value is returned - # with the same data type of the column, or +nil+ if there's no row. See - # #calculate for examples with options. - # - # Person.minimum(:age) # => 7 - def minimum(column_name) - calculate(:minimum, column_name) - end - - # Calculates the maximum value on a given column. The value is returned - # with the same data type of the column, or +nil+ if there's no row. See - # #calculate for examples with options. - # - # Person.maximum(:age) # => 93 - def maximum(column_name) - calculate(:maximum, column_name) - end - - # Calculates the sum of values on a given column. The value is returned - # with the same data type of the column, +0+ if there's no row. See - # #calculate for examples with options. - # - # Person.sum(:age) # => 4562 - def sum(column_name = nil) - return super() if block_given? - calculate(:sum, column_name) - end - - # This calculates aggregate values in the given column. Methods for #count, #sum, #average, - # #minimum, and #maximum have been added as shortcuts. - # - # Person.calculate(:count, :all) # The same as Person.count - # Person.average(:age) # SELECT AVG(age) FROM people... - # - # # Selects the minimum age for any family without any minors - # Person.group(:last_name).having("min(age) > 17").minimum(:age) - # - # Person.sum("2 * age") - # - # There are two basic forms of output: - # - # * Single aggregate value: The single value is type cast to Integer for COUNT, Float - # for AVG, and the given column's type for everything else. - # - # * Grouped values: This returns an ordered hash of the values and groups them. It - # takes either a column name, or the name of a belongs_to association. - # - # values = Person.group('last_name').maximum(:age) - # puts values["Drake"] - # # => 43 - # - # drake = Family.find_by(last_name: 'Drake') - # values = Person.group(:family).maximum(:age) # Person belongs_to :family - # puts values[drake] - # # => 43 - # - # values.each do |family, max_age| - # ... - # end - def calculate(operation, column_name) - if has_include?(column_name) - relation = construct_relation_for_association_calculations - - if operation.to_s.downcase == "count" - relation.distinct! - # PostgreSQL: ORDER BY expressions must appear in SELECT list when using DISTINCT - if (column_name == :all || column_name.nil?) && select_values.empty? - relation.order_values = [] - end - end - - relation.calculate(operation, column_name) - else - perform_calculation(operation, column_name) - end - end - - # Use #pluck as a shortcut to select one or more attributes without - # loading a bunch of records just to grab the attributes you want. - # - # Person.pluck(:name) - # - # instead of - # - # Person.all.map(&:name) - # - # Pluck returns an Array of attribute values type-casted to match - # the plucked column names, if they can be deduced. Plucking an SQL fragment - # returns String values by default. - # - # Person.pluck(:name) - # # SELECT people.name FROM people - # # => ['David', 'Jeremy', 'Jose'] - # - # Person.pluck(:id, :name) - # # SELECT people.id, people.name FROM people - # # => [[1, 'David'], [2, 'Jeremy'], [3, 'Jose']] - # - # Person.distinct.pluck(:role) - # # SELECT DISTINCT role FROM people - # # => ['admin', 'member', 'guest'] - # - # Person.where(age: 21).limit(5).pluck(:id) - # # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5 - # # => [2, 3] - # - # Person.pluck('DATEDIFF(updated_at, created_at)') - # # SELECT DATEDIFF(updated_at, created_at) FROM people - # # => ['0', '27761', '173'] - # - # See also #ids. - # - def pluck(*column_names) - if loaded? && (column_names.map(&:to_s) - @klass.attribute_names - @klass.attribute_aliases.keys).empty? - return records.pluck(*column_names) - end - - if has_include?(column_names.first) - construct_relation_for_association_calculations.pluck(*column_names) - else - relation = spawn - relation.select_values = column_names.map { |cn| - @klass.has_attribute?(cn) || @klass.attribute_alias?(cn) ? arel_attribute(cn) : cn - } - result = klass.connection.select_all(relation.arel, nil, bound_attributes) - result.cast_values(klass.attribute_types) - end - end - - # Pluck all the ID's for the relation using the table's primary key - # - # Person.ids # SELECT people.id FROM people - # Person.joins(:companies).ids # SELECT people.id FROM people INNER JOIN companies ON companies.person_id = people.id - def ids - pluck primary_key - end - - private - - def has_include?(column_name) - eager_loading? || (includes_values.present? && column_name && column_name != :all) - end - - def perform_calculation(operation, column_name) - operation = operation.to_s.downcase - - # If #count is used with #distinct (i.e. `relation.distinct.count`) it is - # considered distinct. - distinct = distinct_value - - if operation == "count" - column_name ||= select_for_count - if column_name == :all - if distinct && (group_values.any? || select_values.empty? && order_values.empty?) - column_name = primary_key - end - elsif column_name =~ /\s*DISTINCT[\s(]+/i - distinct = nil - end - end - - if group_values.any? - execute_grouped_calculation(operation, column_name, distinct) - else - execute_simple_calculation(operation, column_name, distinct) - end - end - - def aggregate_column(column_name) - return column_name if Arel::Expressions === column_name - - if @klass.has_attribute?(column_name.to_s) || @klass.attribute_alias?(column_name.to_s) - @klass.arel_attribute(column_name) - else - Arel.sql(column_name == :all ? "*" : column_name.to_s) - end - end - - def operation_over_aggregate_column(column, operation, distinct) - operation == "count" ? column.count(distinct) : column.send(operation) - end - - def execute_simple_calculation(operation, column_name, distinct) #:nodoc: - column_alias = column_name - - if operation == "count" && (column_name == :all && distinct || has_limit_or_offset?) - # Shortcut when limit is zero. - return 0 if limit_value == 0 - - query_builder = build_count_subquery(spawn, column_name, distinct) - else - # PostgreSQL doesn't like ORDER BY when there are no GROUP BY - relation = unscope(:order).distinct!(false) - - column = aggregate_column(column_name) - - select_value = operation_over_aggregate_column(column, operation, distinct) - if operation == "sum" && distinct - select_value.distinct = true - end - - column_alias = select_value.alias - column_alias ||= @klass.connection.column_name_for_operation(operation, select_value) - relation.select_values = [select_value] - - query_builder = relation.arel - end - - result = @klass.connection.select_all(query_builder, nil, bound_attributes) - row = result.first - value = row && row.values.first - type = result.column_types.fetch(column_alias) do - type_for(column_name) - end - - type_cast_calculated_value(value, type, operation) - end - - def execute_grouped_calculation(operation, column_name, distinct) #:nodoc: - group_attrs = group_values - - if group_attrs.first.respond_to?(:to_sym) - association = @klass._reflect_on_association(group_attrs.first) - associated = group_attrs.size == 1 && association && association.belongs_to? # only count belongs_to associations - group_fields = Array(associated ? association.foreign_key : group_attrs) - else - group_fields = group_attrs - end - group_fields = arel_columns(group_fields) - - group_aliases = group_fields.map { |field| column_alias_for(field) } - group_columns = group_aliases.zip(group_fields) - - if operation == "count" && column_name == :all - aggregate_alias = "count_all" - else - aggregate_alias = column_alias_for([operation, column_name].join(" ")) - end - - select_values = [ - operation_over_aggregate_column( - aggregate_column(column_name), - operation, - distinct).as(aggregate_alias) - ] - select_values += self.select_values unless having_clause.empty? - - select_values.concat group_columns.map { |aliaz, field| - if field.respond_to?(:as) - field.as(aliaz) - else - "#{field} AS #{aliaz}" - end - } - - relation = except(:group).distinct!(false) - relation.group_values = group_fields - relation.select_values = select_values - - calculated_data = @klass.connection.select_all(relation, nil, relation.bound_attributes) - - if association - key_ids = calculated_data.collect { |row| row[group_aliases.first] } - key_records = association.klass.base_class.where(association.klass.base_class.primary_key => key_ids) - key_records = Hash[key_records.map { |r| [r.id, r] }] - end - - Hash[calculated_data.map do |row| - key = group_columns.map { |aliaz, col_name| - type = type_for(col_name) do - calculated_data.column_types.fetch(aliaz, Type.default_value) - end - type_cast_calculated_value(row[aliaz], type) - } - key = key.first if key.size == 1 - key = key_records[key] if associated - - type = calculated_data.column_types.fetch(aggregate_alias) { type_for(column_name) } - [key, type_cast_calculated_value(row[aggregate_alias], type, operation)] - end] - end - - # Converts the given keys to the value that the database adapter returns as - # a usable column name: - # - # column_alias_for("users.id") # => "users_id" - # column_alias_for("sum(id)") # => "sum_id" - # column_alias_for("count(distinct users.id)") # => "count_distinct_users_id" - # column_alias_for("count(*)") # => "count_all" - def column_alias_for(keys) - if keys.respond_to? :name - keys = "#{keys.relation.name}.#{keys.name}" - end - - table_name = keys.to_s.downcase - table_name.gsub!(/\*/, "all") - table_name.gsub!(/\W+/, " ") - table_name.strip! - table_name.gsub!(/ +/, "_") - - @klass.connection.table_alias_for(table_name) - end - - def type_for(field, &block) - field_name = field.respond_to?(:name) ? field.name.to_s : field.to_s.split(".").last - @klass.type_for_attribute(field_name, &block) - end - - def type_cast_calculated_value(value, type, operation = nil) - case operation - when "count" then value.to_i - when "sum" then type.deserialize(value || 0) - when "average" then value.respond_to?(:to_d) ? value.to_d : value - else type.deserialize(value) - end - end - - def select_for_count - if select_values.present? - return select_values.first if select_values.one? - select_values.join(", ") - else - :all - end - end - - def build_count_subquery(relation, column_name, distinct) - if column_name == :all - relation.select_values = [ Arel.sql(FinderMethods::ONE_AS_ONE) ] unless distinct - else - column_alias = Arel.sql("count_column") - relation.select_values = [ aggregate_column(column_name).as(column_alias) ] - end - - subquery = relation.arel.as(Arel.sql("subquery_for_count")) - select_value = operation_over_aggregate_column(column_alias || Arel.star, "count", false) - - Arel::SelectManager.new(subquery).project(select_value) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/delegation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/delegation.rb deleted file mode 100644 index 50378f9d99..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/delegation.rb +++ /dev/null @@ -1,129 +0,0 @@ -module ActiveRecord - module Delegation # :nodoc: - module DelegateCache # :nodoc: - def relation_delegate_class(klass) - @relation_delegate_cache[klass] - end - - def initialize_relation_delegate_cache - @relation_delegate_cache = cache = {} - [ - ActiveRecord::Relation, - ActiveRecord::Associations::CollectionProxy, - ActiveRecord::AssociationRelation - ].each do |klass| - delegate = Class.new(klass) { - include ClassSpecificRelation - } - mangled_name = klass.name.gsub("::".freeze, "_".freeze) - const_set mangled_name, delegate - private_constant mangled_name - - cache[klass] = delegate - end - end - - def inherited(child_class) - child_class.initialize_relation_delegate_cache - super - end - end - - extend ActiveSupport::Concern - - # This module creates compiled delegation methods dynamically at runtime, which makes - # subsequent calls to that method faster by avoiding method_missing. The delegations - # may vary depending on the klass of a relation, so we create a subclass of Relation - # for each different klass, and the delegations are compiled into that subclass only. - - delegate :to_xml, :encode_with, :length, :each, :uniq, :to_ary, :join, - :[], :&, :|, :+, :-, :sample, :reverse, :compact, :in_groups, :in_groups_of, - :to_sentence, :to_formatted_s, :as_json, - :shuffle, :split, :index, to: :records - - delegate :table_name, :quoted_table_name, :primary_key, :quoted_primary_key, - :connection, :columns_hash, to: :klass - - module ClassSpecificRelation # :nodoc: - extend ActiveSupport::Concern - - included do - @delegation_mutex = Mutex.new - end - - module ClassMethods # :nodoc: - def name - superclass.name - end - - def delegate_to_scoped_klass(method) - @delegation_mutex.synchronize do - return if method_defined?(method) - - if /\A[a-zA-Z_]\w*[!?]?\z/.match?(method) - module_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{method}(*args, &block) - scoping { @klass.#{method}(*args, &block) } - end - RUBY - else - define_method method do |*args, &block| - scoping { @klass.public_send(method, *args, &block) } - end - end - end - end - - def delegate(method, opts = {}) - @delegation_mutex.synchronize do - return if method_defined?(method) - super - end - end - end - - private - - def method_missing(method, *args, &block) - if @klass.respond_to?(method) - self.class.delegate_to_scoped_klass(method) - scoping { @klass.public_send(method, *args, &block) } - elsif arel.respond_to?(method) - self.class.delegate method, to: :arel - arel.public_send(method, *args, &block) - else - super - end - end - end - - module ClassMethods # :nodoc: - def create(klass, *args) - relation_class_for(klass).new(klass, *args) - end - - private - - def relation_class_for(klass) - klass.relation_delegate_class(self) - end - end - - def respond_to_missing?(method, include_private = false) - super || @klass.respond_to?(method, include_private) || - arel.respond_to?(method, include_private) - end - - private - - def method_missing(method, *args, &block) - if @klass.respond_to?(method) - scoping { @klass.public_send(method, *args, &block) } - elsif arel.respond_to?(method) - arel.public_send(method, *args, &block) - else - super - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/finder_methods.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/finder_methods.rb deleted file mode 100644 index aa2b9ccfb7..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/finder_methods.rb +++ /dev/null @@ -1,566 +0,0 @@ -require "active_support/core_ext/string/filters" - -module ActiveRecord - module FinderMethods - ONE_AS_ONE = "1 AS one" - - # 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]). - # If one or more records can not be found for the requested ids, then RecordNotFound will be raised. If the primary key - # is an integer, find by id coerces its arguments using +to_i+. - # - # Person.find(1) # returns the object for ID = 1 - # Person.find("1") # returns the object for ID = 1 - # Person.find("31-sarah") # returns the object for ID = 31 - # Person.find(1, 2, 6) # returns an array for objects with IDs in (1, 2, 6) - # Person.find([7, 17]) # returns an array for objects with IDs in (7, 17) - # Person.find([1]) # returns an array for the object with ID = 1 - # Person.where("administrator = 1").order("created_on DESC").find(1) - # - # NOTE: The returned records may not be in the same order as the ids you - # provide since database rows are unordered. You will need to provide an explicit QueryMethods#order - # option if you want the results to be sorted. - # - # ==== Find with lock - # - # Example for find with a lock: Imagine two concurrent transactions: - # each will read person.visits == 2, add 1 to it, and save, resulting - # in two saves of person.visits = 3. By locking the row, the second - # transaction has to wait until the first is finished; we get the - # expected person.visits == 4. - # - # Person.transaction do - # person = Person.lock(true).find(1) - # person.visits += 1 - # person.save! - # end - # - # ==== Variations of #find - # - # Person.where(name: 'Spartacus', rating: 4) - # # returns a chainable list (which can be empty). - # - # Person.find_by(name: 'Spartacus', rating: 4) - # # returns the first item or nil. - # - # Person.find_or_initialize_by(name: 'Spartacus', rating: 4) - # # returns the first item or returns a new instance (requires you call .save to persist against the database). - # - # Person.find_or_create_by(name: 'Spartacus', rating: 4) - # # returns the first item or creates it and returns it. - # - # ==== Alternatives for #find - # - # Person.where(name: 'Spartacus', rating: 4).exists?(conditions = :none) - # # returns a boolean indicating if any record with the given conditions exist. - # - # Person.where(name: 'Spartacus', rating: 4).select("field1, field2, field3") - # # returns a chainable list of instances with only the mentioned fields. - # - # Person.where(name: 'Spartacus', rating: 4).ids - # # returns an Array of ids. - # - # Person.where(name: 'Spartacus', rating: 4).pluck(:field1, :field2) - # # returns an Array of the required fields. - def find(*args) - return super if block_given? - find_with_ids(*args) - end - - # Finds the first record matching the specified conditions. There - # is no implied ordering so if order matters, you should specify it - # yourself. - # - # If no record is found, returns nil. - # - # Post.find_by name: 'Spartacus', rating: 4 - # Post.find_by "published_at < ?", 2.weeks.ago - def find_by(arg, *args) - where(arg, *args).take - rescue ::RangeError - nil - end - - # Like #find_by, except that if no record is found, raises - # an ActiveRecord::RecordNotFound error. - def find_by!(arg, *args) - where(arg, *args).take! - rescue ::RangeError - raise RecordNotFound.new("Couldn't find #{@klass.name} with an out of range value", - @klass.name) - end - - # Gives a record (or N records if a parameter is supplied) without any implied - # order. The order will depend on the database implementation. - # If an order is supplied it will be respected. - # - # Person.take # returns an object fetched by SELECT * FROM people LIMIT 1 - # Person.take(5) # returns 5 objects fetched by SELECT * FROM people LIMIT 5 - # Person.where(["name LIKE '%?'", name]).take - def take(limit = nil) - limit ? find_take_with_limit(limit) : find_take - end - - # Same as #take but raises ActiveRecord::RecordNotFound if no record - # is found. Note that #take! accepts no arguments. - def take! - take || raise_record_not_found_exception! - end - - # Find the first record (or first N records if a parameter is supplied). - # If no order is defined it will order by primary key. - # - # Person.first # returns the first object fetched by SELECT * FROM people ORDER BY people.id LIMIT 1 - # Person.where(["user_name = ?", user_name]).first - # Person.where(["user_name = :u", { u: user_name }]).first - # Person.order("created_on DESC").offset(5).first - # Person.first(3) # returns the first three objects fetched by SELECT * FROM people ORDER BY people.id LIMIT 3 - # - def first(limit = nil) - if limit - find_nth_with_limit(0, limit) - else - find_nth 0 - end - end - - # Same as #first but raises ActiveRecord::RecordNotFound if no record - # is found. Note that #first! accepts no arguments. - def first! - first || raise_record_not_found_exception! - end - - # Find the last record (or last N records if a parameter is supplied). - # If no order is defined it will order by primary key. - # - # Person.last # returns the last object fetched by SELECT * FROM people - # Person.where(["user_name = ?", user_name]).last - # Person.order("created_on DESC").offset(5).last - # Person.last(3) # returns the last three objects fetched by SELECT * FROM people. - # - # Take note that in that last case, the results are sorted in ascending order: - # - # [#, #, #] - # - # and not: - # - # [#, #, #] - def last(limit = nil) - return find_last(limit) if loaded? || limit_value - - result = limit(limit) - result.order!(arel_attribute(primary_key)) if order_values.empty? && primary_key - result = result.reverse_order! - - limit ? result.reverse : result.first - end - - # Same as #last but raises ActiveRecord::RecordNotFound if no record - # is found. Note that #last! accepts no arguments. - def last! - last || raise_record_not_found_exception! - end - - # Find the second record. - # If no order is defined it will order by primary key. - # - # Person.second # returns the second object fetched by SELECT * FROM people - # Person.offset(3).second # returns the second object from OFFSET 3 (which is OFFSET 4) - # Person.where(["user_name = :u", { u: user_name }]).second - def second - find_nth 1 - end - - # Same as #second but raises ActiveRecord::RecordNotFound if no record - # is found. - def second! - second || raise_record_not_found_exception! - end - - # Find the third record. - # If no order is defined it will order by primary key. - # - # Person.third # returns the third object fetched by SELECT * FROM people - # Person.offset(3).third # returns the third object from OFFSET 3 (which is OFFSET 5) - # Person.where(["user_name = :u", { u: user_name }]).third - def third - find_nth 2 - end - - # Same as #third but raises ActiveRecord::RecordNotFound if no record - # is found. - def third! - third || raise_record_not_found_exception! - end - - # Find the fourth record. - # If no order is defined it will order by primary key. - # - # Person.fourth # returns the fourth object fetched by SELECT * FROM people - # Person.offset(3).fourth # returns the fourth object from OFFSET 3 (which is OFFSET 6) - # Person.where(["user_name = :u", { u: user_name }]).fourth - def fourth - find_nth 3 - end - - # Same as #fourth but raises ActiveRecord::RecordNotFound if no record - # is found. - def fourth! - fourth || raise_record_not_found_exception! - end - - # Find the fifth record. - # If no order is defined it will order by primary key. - # - # Person.fifth # returns the fifth object fetched by SELECT * FROM people - # Person.offset(3).fifth # returns the fifth object from OFFSET 3 (which is OFFSET 7) - # Person.where(["user_name = :u", { u: user_name }]).fifth - def fifth - find_nth 4 - end - - # Same as #fifth but raises ActiveRecord::RecordNotFound if no record - # is found. - def fifth! - fifth || raise_record_not_found_exception! - end - - # Find the forty-second record. Also known as accessing "the reddit". - # If no order is defined it will order by primary key. - # - # Person.forty_two # returns the forty-second object fetched by SELECT * FROM people - # Person.offset(3).forty_two # returns the forty-second object from OFFSET 3 (which is OFFSET 44) - # Person.where(["user_name = :u", { u: user_name }]).forty_two - def forty_two - find_nth 41 - end - - # Same as #forty_two but raises ActiveRecord::RecordNotFound if no record - # is found. - def forty_two! - forty_two || raise_record_not_found_exception! - end - - # Find the third-to-last record. - # If no order is defined it will order by primary key. - # - # Person.third_to_last # returns the third-to-last object fetched by SELECT * FROM people - # Person.offset(3).third_to_last # returns the third-to-last object from OFFSET 3 - # Person.where(["user_name = :u", { u: user_name }]).third_to_last - def third_to_last - find_nth_from_last 3 - end - - # Same as #third_to_last but raises ActiveRecord::RecordNotFound if no record - # is found. - def third_to_last! - third_to_last || raise_record_not_found_exception! - end - - # Find the second-to-last record. - # If no order is defined it will order by primary key. - # - # Person.second_to_last # returns the second-to-last object fetched by SELECT * FROM people - # Person.offset(3).second_to_last # returns the second-to-last object from OFFSET 3 - # Person.where(["user_name = :u", { u: user_name }]).second_to_last - def second_to_last - find_nth_from_last 2 - end - - # Same as #second_to_last but raises ActiveRecord::RecordNotFound if no record - # is found. - def second_to_last! - second_to_last || raise_record_not_found_exception! - end - - # Returns true if a record exists in the table that matches the +id+ or - # conditions given, or false otherwise. The argument can take six forms: - # - # * Integer - Finds the record with this primary key. - # * String - Finds the record with a primary key corresponding to this - # string (such as '5'). - # * Array - Finds the record that matches these +find+-style conditions - # (such as ['name LIKE ?', "%#{query}%"]). - # * Hash - Finds the record that matches these +find+-style conditions - # (such as {name: 'David'}). - # * +false+ - Returns always +false+. - # * No args - Returns +false+ if the table is empty, +true+ otherwise. - # - # For more information about specifying conditions as a hash or array, - # see the Conditions section in the introduction to ActiveRecord::Base. - # - # Note: You can't pass in a condition as a string (like name = - # 'Jamie'), since it would be sanitized and then queried against - # the primary key column, like id = 'name = \'Jamie\''. - # - # Person.exists?(5) - # Person.exists?('5') - # Person.exists?(['name LIKE ?', "%#{query}%"]) - # Person.exists?(id: [1, 4, 8]) - # Person.exists?(name: 'David') - # Person.exists?(false) - # Person.exists? - def exists?(conditions = :none) - if Base === conditions - raise ArgumentError, <<-MSG.squish - You are passing an instance of ActiveRecord::Base to `exists?`. - Please pass the id of the object by calling `.id`. - MSG - end - - return false if !conditions || limit_value == 0 - - relation = self unless eager_loading? - relation ||= apply_join_dependency(self, construct_join_dependency(eager_loading: false)) - - return false if ActiveRecord::NullRelation === relation - - relation = construct_relation_for_exists(relation, conditions) - - connection.select_value(relation, "#{name} Exists", relation.bound_attributes) ? true : false - rescue ::RangeError - false - end - - # This method is called whenever no records are found with either a single - # id or multiple ids and raises an ActiveRecord::RecordNotFound exception. - # - # The error message is different depending on whether a single id or - # multiple ids are provided. If multiple ids are provided, then the number - # of results obtained should be provided in the +result_size+ argument and - # the expected number of results should be provided in the +expected_size+ - # argument. - def raise_record_not_found_exception!(ids = nil, result_size = nil, expected_size = nil, key = primary_key) # :nodoc: - conditions = arel.where_sql(@klass.arel_engine) - conditions = " [#{conditions}]" if conditions - name = @klass.name - - if ids.nil? - error = "Couldn't find #{name}" - error << " with#{conditions}" if conditions - raise RecordNotFound.new(error, name) - elsif Array(ids).size == 1 - error = "Couldn't find #{name} with '#{key}'=#{ids}#{conditions}" - raise RecordNotFound.new(error, name, key, ids) - else - error = "Couldn't find all #{name.pluralize} with '#{key}': " - error << "(#{ids.join(", ")})#{conditions} (found #{result_size} results, but was looking for #{expected_size})" - - raise RecordNotFound.new(error, name, primary_key, ids) - end - end - - private - - def offset_index - offset_value || 0 - end - - def find_with_associations - # NOTE: the JoinDependency constructed here needs to know about - # any joins already present in `self`, so pass them in - # - # failing to do so means that in cases like activerecord/test/cases/associations/inner_join_association_test.rb:136 - # incorrect SQL is generated. In that case, the join dependency for - # SpecialCategorizations is constructed without knowledge of the - # preexisting join in joins_values to categorizations (by way of - # the `has_many :through` for categories). - # - join_dependency = construct_join_dependency(joins_values) - - aliases = join_dependency.aliases - relation = select aliases.columns - relation = apply_join_dependency(relation, join_dependency) - - yield relation, join_dependency - end - - def construct_relation_for_exists(relation, conditions) - relation = relation.except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1) - - case conditions - when Array, Hash - relation.where!(conditions) unless conditions.empty? - else - relation.where!(primary_key => conditions) unless conditions == :none - end - - relation - end - - def construct_join_dependency(joins = [], eager_loading: true) - including = eager_load_values + includes_values - ActiveRecord::Associations::JoinDependency.new(@klass, including, joins, eager_loading: eager_loading) - end - - def construct_relation_for_association_calculations - apply_join_dependency(self, construct_join_dependency(joins_values)) - end - - def apply_join_dependency(relation, join_dependency) - relation = relation.except(:includes, :eager_load, :preload).joins!(join_dependency) - - if using_limitable_reflections?(join_dependency.reflections) - relation - else - if relation.limit_value - limited_ids = limited_ids_for(relation) - limited_ids.empty? ? relation.none! : relation.where!(primary_key => limited_ids) - end - relation.except(:limit, :offset) - end - end - - def limited_ids_for(relation) - values = @klass.connection.columns_for_distinct( - "#{quoted_table_name}.#{quoted_primary_key}", relation.order_values) - - relation = relation.except(:select).select(values).distinct! - arel = relation.arel - - id_rows = @klass.connection.select_all(arel, "SQL", relation.bound_attributes) - id_rows.map { |row| row[primary_key] } - end - - def using_limitable_reflections?(reflections) - reflections.none?(&:collection?) - end - - def find_with_ids(*ids) - raise UnknownPrimaryKey.new(@klass) if primary_key.nil? - - expects_array = ids.first.kind_of?(Array) - return [] if expects_array && ids.first.empty? - - ids = ids.flatten.compact.uniq - - case ids.size - when 0 - raise RecordNotFound, "Couldn't find #{@klass.name} without an ID" - when 1 - result = find_one(ids.first) - expects_array ? [ result ] : result - else - find_some(ids) - end - rescue ::RangeError - raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID" - end - - def find_one(id) - if ActiveRecord::Base === id - raise ArgumentError, <<-MSG.squish - You are passing an instance of ActiveRecord::Base to `find`. - Please pass the id of the object by calling `.id`. - MSG - end - - relation = where(primary_key => id) - record = relation.take - - raise_record_not_found_exception!(id, 0, 1) unless record - - record - end - - def find_some(ids) - return find_some_ordered(ids) unless order_values.present? - - result = where(primary_key => ids).to_a - - expected_size = - if limit_value && ids.size > limit_value - limit_value - else - ids.size - end - - # 11 ids with limit 3, offset 9 should give 2 results. - if offset_value && (ids.size - offset_value < expected_size) - expected_size = ids.size - offset_value - end - - if result.size == expected_size - result - else - raise_record_not_found_exception!(ids, result.size, expected_size) - end - end - - def find_some_ordered(ids) - ids = ids.slice(offset_value || 0, limit_value || ids.size) || [] - - result = except(:limit, :offset).where(primary_key => ids).records - - if result.size == ids.size - pk_type = @klass.type_for_attribute(primary_key) - - records_by_id = result.index_by(&:id) - ids.map { |id| records_by_id.fetch(pk_type.cast(id)) } - else - raise_record_not_found_exception!(ids, result.size, ids.size) - end - end - - def find_take - if loaded? - records.first - else - @take ||= limit(1).records.first - end - end - - def find_take_with_limit(limit) - if loaded? - records.take(limit) - else - limit(limit).to_a - end - end - - def find_nth(index) - @offsets[offset_index + index] ||= find_nth_with_limit(index, 1).first - end - - def find_nth_with_limit(index, limit) - if loaded? - records[index, limit] || [] - else - relation = if order_values.empty? && primary_key - order(arel_attribute(primary_key).asc) - else - self - end - - if limit_value.nil? || index < limit_value - relation = relation.offset(offset_index + index) unless index.zero? - relation.limit(limit).to_a - else - [] - end - end - end - - def find_nth_from_last(index) - if loaded? - records[-index] - else - relation = if order_values.empty? && primary_key - order(arel_attribute(primary_key).asc) - else - self - end - - relation.to_a[-index] - # TODO: can be made more performant on large result sets by - # for instance, last(index)[-index] (which would require - # refactoring the last(n) finder method to make test suite pass), - # or by using a combination of reverse_order, limit, and offset, - # e.g., reverse_order.offset(index-1).first - end - end - - def find_last(limit) - limit ? records.last(limit) : records.last - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/from_clause.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/from_clause.rb deleted file mode 100644 index 8945cb0cc5..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/from_clause.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveRecord - class Relation - class FromClause # :nodoc: - attr_reader :value, :name - - def initialize(value, name) - @value = value - @name = name - end - - def binds - if value.is_a?(Relation) - value.bound_attributes - else - [] - end - end - - def merge(other) - self - end - - def empty? - value.nil? - end - - def self.empty - @empty ||= new(nil, nil) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/merger.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/merger.rb deleted file mode 100644 index 5dac00724a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/merger.rb +++ /dev/null @@ -1,163 +0,0 @@ -require "active_support/core_ext/hash/keys" - -module ActiveRecord - class Relation - class HashMerger # :nodoc: - attr_reader :relation, :hash - - def initialize(relation, hash) - hash.assert_valid_keys(*Relation::VALUE_METHODS) - - @relation = relation - @hash = hash - end - - def merge #:nodoc: - Merger.new(relation, other).merge - end - - # Applying values to a relation has some side effects. E.g. - # interpolation might take place for where values. So we should - # build a relation to merge in rather than directly merging - # the values. - def other - other = Relation.create(relation.klass, relation.table, relation.predicate_builder) - hash.each { |k, v| - if k == :joins - if Hash === v - other.joins!(v) - else - other.joins!(*v) - end - elsif k == :select - other._select!(v) - else - other.send("#{k}!", v) - end - } - other - end - end - - class Merger # :nodoc: - attr_reader :relation, :values, :other - - def initialize(relation, other) - @relation = relation - @values = other.values - @other = other - end - - NORMAL_VALUES = Relation::VALUE_METHODS - - Relation::CLAUSE_METHODS - - [:includes, :preload, :joins, :order, :reverse_order, :lock, :create_with, :reordering] # :nodoc: - - def normal_values - NORMAL_VALUES - end - - def merge - normal_values.each do |name| - value = values[name] - # The unless clause is here mostly for performance reasons (since the `send` call might be moderately - # expensive), most of the time the value is going to be `nil` or `.blank?`, the only catch is that - # `false.blank?` returns `true`, so there needs to be an extra check so that explicit `false` values - # don't fall through the cracks. - unless value.nil? || (value.blank? && false != value) - if name == :select - relation._select!(*value) - else - relation.send("#{name}!", *value) - end - end - end - - merge_multi_values - merge_single_values - merge_clauses - merge_preloads - merge_joins - - relation - end - - private - - def merge_preloads - return if other.preload_values.empty? && other.includes_values.empty? - - if other.klass == relation.klass - relation.preload!(*other.preload_values) unless other.preload_values.empty? - relation.includes!(other.includes_values) unless other.includes_values.empty? - else - reflection = relation.klass.reflect_on_all_associations.find do |r| - r.class_name == other.klass.name - end || return - - unless other.preload_values.empty? - relation.preload! reflection.name => other.preload_values - end - - unless other.includes_values.empty? - relation.includes! reflection.name => other.includes_values - end - end - end - - def merge_joins - return if other.joins_values.blank? - - if other.klass == relation.klass - relation.joins!(*other.joins_values) - else - joins_dependency, rest = other.joins_values.partition do |join| - case join - when Hash, Symbol, Array - true - else - false - end - end - - join_dependency = ActiveRecord::Associations::JoinDependency.new(other.klass, - joins_dependency, - []) - relation.joins! rest - - @relation = relation.joins join_dependency - end - end - - def merge_multi_values - if other.reordering_value - # override any order specified in the original relation - relation.reorder! other.order_values - elsif other.order_values - # merge in order_values from relation - relation.order! other.order_values - end - - relation.extend(*other.extending_values) unless other.extending_values.blank? - end - - def merge_single_values - if relation.from_clause.empty? - relation.from_clause = other.from_clause - end - relation.lock_value ||= other.lock_value - - unless other.create_with_value.blank? - relation.create_with_value = (relation.create_with_value || {}).merge(other.create_with_value) - end - end - - def merge_clauses - CLAUSE_METHODS.each do |method| - clause = relation.get_value(method) - other_clause = other.get_value(method) - relation.set_value(method, clause.merge(other_clause)) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder.rb deleted file mode 100644 index 6d67722c98..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder.rb +++ /dev/null @@ -1,171 +0,0 @@ -module ActiveRecord - class PredicateBuilder # :nodoc: - require "active_record/relation/predicate_builder/array_handler" - require "active_record/relation/predicate_builder/association_query_handler" - require "active_record/relation/predicate_builder/base_handler" - require "active_record/relation/predicate_builder/basic_object_handler" - require "active_record/relation/predicate_builder/polymorphic_array_handler" - require "active_record/relation/predicate_builder/range_handler" - require "active_record/relation/predicate_builder/relation_handler" - - delegate :resolve_column_aliases, to: :table - - def initialize(table) - @table = table - @handlers = [] - - register_handler(BasicObject, BasicObjectHandler.new) - register_handler(Base, BaseHandler.new(self)) - register_handler(Range, RangeHandler.new) - register_handler(RangeHandler::RangeWithBinds, RangeHandler.new) - register_handler(Relation, RelationHandler.new) - register_handler(Array, ArrayHandler.new(self)) - register_handler(AssociationQueryValue, AssociationQueryHandler.new(self)) - register_handler(PolymorphicArrayValue, PolymorphicArrayHandler.new(self)) - end - - def build_from_hash(attributes) - attributes = convert_dot_notation_to_hash(attributes) - expand_from_hash(attributes) - end - - def create_binds(attributes) - attributes = convert_dot_notation_to_hash(attributes) - create_binds_for_hash(attributes) - end - - def self.references(attributes) - attributes.map do |key, value| - if value.is_a?(Hash) - key - else - key = key.to_s - key.split(".".freeze).first if key.include?(".".freeze) - end - end.compact - end - - # Define how a class is converted to Arel nodes when passed to +where+. - # The handler can be any object that responds to +call+, and will be used - # for any value that +===+ the class given. For example: - # - # MyCustomDateRange = Struct.new(:start, :end) - # handler = proc do |column, range| - # Arel::Nodes::Between.new(column, - # Arel::Nodes::And.new([range.start, range.end]) - # ) - # end - # ActiveRecord::PredicateBuilder.new("users").register_handler(MyCustomDateRange, handler) - def register_handler(klass, handler) - @handlers.unshift([klass, handler]) - end - - def build(attribute, value) - handler_for(value).call(attribute, value) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :table - - def expand_from_hash(attributes) - return ["1=0"] if attributes.empty? - - attributes.flat_map do |key, value| - if value.is_a?(Hash) && !table.has_column?(key) - associated_predicate_builder(key).expand_from_hash(value) - else - build(table.arel_attribute(key), value) - end - end - end - - def create_binds_for_hash(attributes) - result = attributes.dup - binds = [] - - attributes.each do |column_name, value| - case - when value.is_a?(Hash) && !table.has_column?(column_name) - attrs, bvs = associated_predicate_builder(column_name).create_binds_for_hash(value) - result[column_name] = attrs - binds += bvs - next - when value.is_a?(Relation) - binds += value.bound_attributes - when value.is_a?(Range) && !table.type(column_name).force_equality?(value) - first = value.begin - last = value.end - unless first.respond_to?(:infinite?) && first.infinite? - binds << build_bind_param(column_name, first) - first = Arel::Nodes::BindParam.new - end - unless last.respond_to?(:infinite?) && last.infinite? - binds << build_bind_param(column_name, last) - last = Arel::Nodes::BindParam.new - end - - result[column_name] = RangeHandler::RangeWithBinds.new(first, last, value.exclude_end?) - else - if can_be_bound?(column_name, value) - result[column_name] = Arel::Nodes::BindParam.new - binds << build_bind_param(column_name, value) - end - end - - # Find the foreign key when using queries such as: - # Post.where(author: author) - # - # For polymorphic relationships, find the foreign key and type: - # PriceEstimate.where(estimate_of: treasure) - if table.associated_with?(column_name) - result[column_name] = AssociationQueryHandler.value_for(table, column_name, value) - end - end - - [result, binds] - end - - private - - def associated_predicate_builder(association_name) - self.class.new(table.associated_table(association_name)) - end - - def convert_dot_notation_to_hash(attributes) - dot_notation = attributes.select do |k, v| - k.include?(".".freeze) && !v.is_a?(Hash) - end - - dot_notation.each_key do |key| - table_name, column_name = key.split(".".freeze) - value = attributes.delete(key) - attributes[table_name] ||= {} - - attributes[table_name] = attributes[table_name].merge(column_name => value) - end - - attributes - end - - def handler_for(object) - @handlers.detect { |klass, _| klass === object }.last - end - - def can_be_bound?(column_name, value) - return if table.associated_with?(column_name) - case value - when Array, Range - table.type(column_name).force_equality?(value) - else - !value.nil? && handler_for(value).is_a?(BasicObjectHandler) - end - end - - def build_bind_param(column_name, value) - Relation::QueryAttribute.new(column_name.to_s, value, table.type(column_name)) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/array_handler.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/array_handler.rb deleted file mode 100644 index 88b6c37d43..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/array_handler.rb +++ /dev/null @@ -1,45 +0,0 @@ -module ActiveRecord - class PredicateBuilder - class ArrayHandler # :nodoc: - def initialize(predicate_builder) - @predicate_builder = predicate_builder - end - - def call(attribute, value) - values = value.map { |x| x.is_a?(Base) ? x.id : x } - nils, values = values.partition(&:nil?) - - return attribute.in([]) if values.empty? && nils.empty? - - ranges, values = values.partition { |v| v.is_a?(Range) } - - values_predicate = - case values.length - when 0 then NullPredicate - when 1 then predicate_builder.build(attribute, values.first) - else attribute.in(values) - end - - unless nils.empty? - values_predicate = values_predicate.or(predicate_builder.build(attribute, nil)) - end - - array_predicates = ranges.map { |range| predicate_builder.build(attribute, range) } - array_predicates.unshift(values_predicate) - array_predicates.inject { |composite, predicate| composite.or(predicate) } - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :predicate_builder - - module NullPredicate # :nodoc: - def self.or(other) - other - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/association_query_handler.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/association_query_handler.rb deleted file mode 100644 index 29860ec677..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/association_query_handler.rb +++ /dev/null @@ -1,88 +0,0 @@ -module ActiveRecord - class PredicateBuilder - class AssociationQueryHandler # :nodoc: - def self.value_for(table, column, value) - associated_table = table.associated_table(column) - klass = if associated_table.polymorphic_association? && ::Array === value && value.first.is_a?(Base) - PolymorphicArrayValue - else - AssociationQueryValue - end - - klass.new(associated_table, value) - end - - def initialize(predicate_builder) - @predicate_builder = predicate_builder - end - - def call(attribute, value) - queries = {} - - table = value.associated_table - if value.base_class - queries[table.association_foreign_type.to_s] = value.base_class.name - end - - queries[table.association_foreign_key.to_s] = value.ids - predicate_builder.build_from_hash(queries) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :predicate_builder - end - - class AssociationQueryValue # :nodoc: - attr_reader :associated_table, :value - - def initialize(associated_table, value) - @associated_table = associated_table - @value = value - end - - def ids - case value - when Relation - value.select(primary_key) - when Array - value.map { |v| convert_to_id(v) } - else - convert_to_id(value) - end - end - - def base_class - if associated_table.polymorphic_association? - @base_class ||= polymorphic_base_class_from_value - end - end - - private - - def primary_key - associated_table.association_primary_key(base_class) - end - - def polymorphic_base_class_from_value - case value - when Relation - value.klass.base_class - when Base - value.class.base_class - end - end - - def convert_to_id(value) - case value - when Base - value._read_attribute(primary_key) - else - value - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/base_handler.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/base_handler.rb deleted file mode 100644 index 3bb1037885..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/base_handler.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActiveRecord - class PredicateBuilder - class BaseHandler # :nodoc: - def initialize(predicate_builder) - @predicate_builder = predicate_builder - end - - def call(attribute, value) - predicate_builder.build(attribute, value.id) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :predicate_builder - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/basic_object_handler.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/basic_object_handler.rb deleted file mode 100644 index 79cde00303..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/basic_object_handler.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActiveRecord - class PredicateBuilder - class BasicObjectHandler # :nodoc: - def call(attribute, value) - attribute.eq(value) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb deleted file mode 100644 index 335124c952..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/polymorphic_array_handler.rb +++ /dev/null @@ -1,59 +0,0 @@ -module ActiveRecord - class PredicateBuilder - class PolymorphicArrayHandler # :nodoc: - def initialize(predicate_builder) - @predicate_builder = predicate_builder - end - - def call(attribute, value) - table = value.associated_table - queries = value.type_to_ids_mapping.map do |type, ids| - { table.association_foreign_type.to_s => type, table.association_foreign_key.to_s => ids } - end - - predicates = queries.map { |query| predicate_builder.build_from_hash(query) } - - if predicates.size > 1 - type_and_ids_predicates = predicates.map { |type_predicate, id_predicate| Arel::Nodes::Grouping.new(type_predicate.and(id_predicate)) } - type_and_ids_predicates.inject(&:or) - else - predicates.first - end - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :predicate_builder - end - - class PolymorphicArrayValue # :nodoc: - attr_reader :associated_table, :values - - def initialize(associated_table, values) - @associated_table = associated_table - @values = values - end - - def type_to_ids_mapping - default_hash = Hash.new { |hsh, key| hsh[key] = [] } - values.each_with_object(default_hash) { |value, hash| hash[base_class(value).name] << convert_to_id(value) } - end - - private - - def primary_key(value) - associated_table.association_primary_key(base_class(value)) - end - - def base_class(value) - value.class.base_class - end - - def convert_to_id(value) - value._read_attribute(primary_key(value)) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/range_handler.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/range_handler.rb deleted file mode 100644 index 5db778e19c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/range_handler.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActiveRecord - class PredicateBuilder - class RangeHandler # :nodoc: - RangeWithBinds = Struct.new(:begin, :end, :exclude_end?) - - def call(attribute, value) - if value.begin.respond_to?(:infinite?) && value.begin.infinite? - if value.end.respond_to?(:infinite?) && value.end.infinite? - attribute.not_in([]) - elsif value.exclude_end? - attribute.lt(value.end) - else - attribute.lteq(value.end) - end - elsif value.end.respond_to?(:infinite?) && value.end.infinite? - attribute.gteq(value.begin) - elsif value.exclude_end? - attribute.gteq(value.begin).and(attribute.lt(value.end)) - else - attribute.between(value) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/relation_handler.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/relation_handler.rb deleted file mode 100644 index 8a910a82fe..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/predicate_builder/relation_handler.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - class PredicateBuilder - class RelationHandler # :nodoc: - def call(attribute, value) - if value.select_values.empty? - value = value.select(value.arel_attribute(value.klass.primary_key)) - end - - attribute.in(value.arel) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/query_attribute.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/query_attribute.rb deleted file mode 100644 index a68e508fcc..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/query_attribute.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "active_record/attribute" - -module ActiveRecord - class Relation - class QueryAttribute < Attribute # :nodoc: - def type_cast(value) - value - end - - def value_for_database - @value_for_database ||= super - end - - def with_cast_value(value) - QueryAttribute.new(name, value, type) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/query_methods.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/query_methods.rb deleted file mode 100644 index 3d0383995b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/query_methods.rb +++ /dev/null @@ -1,1204 +0,0 @@ -require "active_record/relation/from_clause" -require "active_record/relation/query_attribute" -require "active_record/relation/where_clause" -require "active_record/relation/where_clause_factory" -require "active_model/forbidden_attributes_protection" - -module ActiveRecord - module QueryMethods - extend ActiveSupport::Concern - - include ActiveModel::ForbiddenAttributesProtection - - # WhereChain objects act as placeholder for queries in which #where does not have any parameter. - # In this case, #where must be chained with #not to return a new relation. - class WhereChain - include ActiveModel::ForbiddenAttributesProtection - - def initialize(scope) - @scope = scope - end - - # Returns a new relation expressing WHERE + NOT condition according to - # the conditions in the arguments. - # - # #not accepts conditions as a string, array, or hash. See QueryMethods#where for - # more details on each format. - # - # User.where.not("name = 'Jon'") - # # SELECT * FROM users WHERE NOT (name = 'Jon') - # - # User.where.not(["name = ?", "Jon"]) - # # SELECT * FROM users WHERE NOT (name = 'Jon') - # - # User.where.not(name: "Jon") - # # SELECT * FROM users WHERE name != 'Jon' - # - # User.where.not(name: nil) - # # SELECT * FROM users WHERE name IS NOT NULL - # - # User.where.not(name: %w(Ko1 Nobu)) - # # SELECT * FROM users WHERE name NOT IN ('Ko1', 'Nobu') - # - # User.where.not(name: "Jon", role: "admin") - # # SELECT * FROM users WHERE name != 'Jon' AND role != 'admin' - def not(opts, *rest) - opts = sanitize_forbidden_attributes(opts) - - where_clause = @scope.send(:where_clause_factory).build(opts, rest) - - @scope.references!(PredicateBuilder.references(opts)) if Hash === opts - @scope.where_clause += where_clause.invert - @scope - end - end - - FROZEN_EMPTY_ARRAY = [].freeze - FROZEN_EMPTY_HASH = {}.freeze - - Relation::VALUE_METHODS.each do |name| - method_name = \ - case name - when *Relation::MULTI_VALUE_METHODS then "#{name}_values" - when *Relation::SINGLE_VALUE_METHODS then "#{name}_value" - when *Relation::CLAUSE_METHODS then "#{name}_clause" - end - class_eval <<-CODE, __FILE__, __LINE__ + 1 - def #{method_name} # def includes_values - get_value(#{name.inspect}) # get_value(:includes) - end # end - - def #{method_name}=(value) # def includes_values=(value) - set_value(#{name.inspect}, value) # set_value(:includes, value) - end # end - CODE - end - - def bound_attributes - if limit_value - limit_bind = Attribute.with_cast_value( - "LIMIT".freeze, - connection.sanitize_limit(limit_value), - Type.default_value, - ) - end - if offset_value - offset_bind = Attribute.with_cast_value( - "OFFSET".freeze, - offset_value.to_i, - Type.default_value, - ) - end - connection.combine_bind_parameters( - from_clause: from_clause.binds, - join_clause: arel.bind_values, - where_clause: where_clause.binds, - having_clause: having_clause.binds, - limit: limit_bind, - offset: offset_bind, - ) - end - - alias extensions extending_values - - # Specify relationships to be included in the result set. For - # example: - # - # users = User.includes(:address) - # users.each do |user| - # user.address.city - # end - # - # allows you to access the +address+ attribute of the +User+ model without - # firing an additional query. This will often result in a - # performance improvement over a simple join. - # - # You can also specify multiple relationships, like this: - # - # users = User.includes(:address, :friends) - # - # Loading nested relationships is possible using a Hash: - # - # users = User.includes(:address, friends: [:address, :followers]) - # - # === conditions - # - # If you want to add conditions to your included models you'll have - # to explicitly reference them. For example: - # - # User.includes(:posts).where('posts.name = ?', 'example') - # - # Will throw an error, but this will work: - # - # User.includes(:posts).where('posts.name = ?', 'example').references(:posts) - # - # Note that #includes works with association names while #references needs - # the actual table name. - def includes(*args) - check_if_method_has_arguments!(:includes, args) - spawn.includes!(*args) - end - - def includes!(*args) # :nodoc: - args.reject!(&:blank?) - args.flatten! - - self.includes_values |= args - self - end - - # Forces eager loading by performing a LEFT OUTER JOIN on +args+: - # - # User.eager_load(:posts) - # # SELECT "users"."id" AS t0_r0, "users"."name" AS t0_r1, ... - # # FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = - # # "users"."id" - def eager_load(*args) - check_if_method_has_arguments!(:eager_load, args) - spawn.eager_load!(*args) - end - - def eager_load!(*args) # :nodoc: - self.eager_load_values += args - self - end - - # Allows preloading of +args+, in the same way that #includes does: - # - # User.preload(:posts) - # # SELECT "posts".* FROM "posts" WHERE "posts"."user_id" IN (1, 2, 3) - def preload(*args) - check_if_method_has_arguments!(:preload, args) - spawn.preload!(*args) - end - - def preload!(*args) # :nodoc: - self.preload_values += args - self - end - - # Use to indicate that the given +table_names+ are referenced by an SQL string, - # and should therefore be JOINed in any query rather than loaded separately. - # This method only works in conjunction with #includes. - # See #includes for more details. - # - # User.includes(:posts).where("posts.name = 'foo'") - # # Doesn't JOIN the posts table, resulting in an error. - # - # User.includes(:posts).where("posts.name = 'foo'").references(:posts) - # # Query now knows the string references posts, so adds a JOIN - def references(*table_names) - check_if_method_has_arguments!(:references, table_names) - spawn.references!(*table_names) - end - - def references!(*table_names) # :nodoc: - table_names.flatten! - table_names.map!(&:to_s) - - self.references_values |= table_names - self - end - - # Works in two unique ways. - # - # First: takes a block so it can be used just like +Array#select+. - # - # Model.all.select { |m| m.field == value } - # - # This will build an array of objects from the database for the scope, - # converting them into an array and iterating through them using +Array#select+. - # - # Second: Modifies the SELECT statement for the query so that only certain - # fields are retrieved: - # - # Model.select(:field) - # # => [#] - # - # Although in the above example it looks as though this method returns an - # array, it actually returns a relation object and can have other query - # methods appended to it, such as the other methods in ActiveRecord::QueryMethods. - # - # The argument to the method can also be an array of fields. - # - # Model.select(:field, :other_field, :and_one_more) - # # => [#] - # - # You can also use one or more strings, which will be used unchanged as SELECT fields. - # - # Model.select('field AS field_one', 'other_field AS field_two') - # # => [#] - # - # If an alias was specified, it will be accessible from the resulting objects: - # - # Model.select('field AS field_one').first.field_one - # # => "value" - # - # Accessing attributes of an object that do not have fields retrieved by a select - # except +id+ will throw ActiveModel::MissingAttributeError: - # - # Model.select(:field).first.other_field - # # => ActiveModel::MissingAttributeError: missing attribute: other_field - def select(*fields) - if block_given? - if fields.any? - raise ArgumentError, "`select' with block doesn't take arguments." - end - - return super() - end - - raise ArgumentError, "Call this with at least one field" if fields.empty? - spawn._select!(*fields) - end - - def _select!(*fields) # :nodoc: - fields.flatten! - fields.map! do |field| - klass.attribute_alias?(field) ? klass.attribute_alias(field).to_sym : field - end - self.select_values += fields - self - end - - # Allows to specify a group attribute: - # - # User.group(:name) - # # SELECT "users".* FROM "users" GROUP BY name - # - # Returns an array with distinct records based on the +group+ attribute: - # - # User.select([:id, :name]) - # # => [#, #, #] - # - # User.group(:name) - # # => [#, #] - # - # User.group('name AS grouped_name, age') - # # => [#, #, #] - # - # Passing in an array of attributes to group by is also supported. - # - # User.select([:id, :first_name]).group(:id, :first_name).first(3) - # # => [#, #, #] - def group(*args) - check_if_method_has_arguments!(:group, args) - spawn.group!(*args) - end - - def group!(*args) # :nodoc: - args.flatten! - - self.group_values += args - self - end - - # Allows to specify an order attribute: - # - # User.order(:name) - # # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC - # - # User.order(email: :desc) - # # SELECT "users".* FROM "users" ORDER BY "users"."email" DESC - # - # User.order(:name, email: :desc) - # # SELECT "users".* FROM "users" ORDER BY "users"."name" ASC, "users"."email" DESC - # - # User.order('name') - # # SELECT "users".* FROM "users" ORDER BY name - # - # User.order('name DESC') - # # SELECT "users".* FROM "users" ORDER BY name DESC - # - # User.order('name DESC, email') - # # SELECT "users".* FROM "users" ORDER BY name DESC, email - def order(*args) - check_if_method_has_arguments!(:order, args) - spawn.order!(*args) - end - - def order!(*args) # :nodoc: - preprocess_order_args(args) - - self.order_values += args - self - end - - # Replaces any existing order defined on the relation with the specified order. - # - # User.order('email DESC').reorder('id ASC') # generated SQL has 'ORDER BY id ASC' - # - # Subsequent calls to order on the same relation will be appended. For example: - # - # User.order('email DESC').reorder('id ASC').order('name ASC') - # - # generates a query with 'ORDER BY id ASC, name ASC'. - def reorder(*args) - check_if_method_has_arguments!(:reorder, args) - spawn.reorder!(*args) - end - - def reorder!(*args) # :nodoc: - preprocess_order_args(args) - - self.reordering_value = true - self.order_values = args - self - end - - VALID_UNSCOPING_VALUES = Set.new([:where, :select, :group, :order, :lock, - :limit, :offset, :joins, :includes, :from, - :readonly, :having]) - - # Removes an unwanted relation that is already defined on a chain of relations. - # This is useful when passing around chains of relations and would like to - # modify the relations without reconstructing the entire chain. - # - # User.order('email DESC').unscope(:order) == User.all - # - # The method arguments are symbols which correspond to the names of the methods - # which should be unscoped. The valid arguments are given in VALID_UNSCOPING_VALUES. - # The method can also be called with multiple arguments. For example: - # - # User.order('email DESC').select('id').where(name: "John") - # .unscope(:order, :select, :where) == User.all - # - # One can additionally pass a hash as an argument to unscope specific +:where+ values. - # This is done by passing a hash with a single key-value pair. The key should be - # +:where+ and the value should be the where value to unscope. For example: - # - # User.where(name: "John", active: true).unscope(where: :name) - # == User.where(active: true) - # - # This method is similar to #except, but unlike - # #except, it persists across merges: - # - # User.order('email').merge(User.except(:order)) - # == User.order('email') - # - # User.order('email').merge(User.unscope(:order)) - # == User.all - # - # This means it can be used in association definitions: - # - # has_many :comments, -> { unscope(where: :trashed) } - # - def unscope(*args) - check_if_method_has_arguments!(:unscope, args) - spawn.unscope!(*args) - end - - def unscope!(*args) # :nodoc: - args.flatten! - self.unscope_values += args - - args.each do |scope| - case scope - when Symbol - if !VALID_UNSCOPING_VALUES.include?(scope) - raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}." - end - set_value(scope, nil) - when Hash - scope.each do |key, target_value| - if key != :where - raise ArgumentError, "Hash arguments in .unscope(*args) must have :where as the key." - end - - target_values = Array(target_value).map(&:to_s) - self.where_clause = where_clause.except(*target_values) - end - else - raise ArgumentError, "Unrecognized scoping: #{args.inspect}. Use .unscope(where: :attribute_name) or .unscope(:order), for example." - end - end - - self - end - - # Performs a joins on +args+. The given symbol(s) should match the name of - # the association(s). - # - # User.joins(:posts) - # # SELECT "users".* - # # FROM "users" - # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id" - # - # Multiple joins: - # - # User.joins(:posts, :account) - # # SELECT "users".* - # # FROM "users" - # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id" - # # INNER JOIN "accounts" ON "accounts"."id" = "users"."account_id" - # - # Nested joins: - # - # User.joins(posts: [:comments]) - # # SELECT "users".* - # # FROM "users" - # # INNER JOIN "posts" ON "posts"."user_id" = "users"."id" - # # INNER JOIN "comments" "comments_posts" - # # ON "comments_posts"."post_id" = "posts"."id" - # - # You can use strings in order to customize your joins: - # - # User.joins("LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id") - # # SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id - def joins(*args) - check_if_method_has_arguments!(:joins, args) - spawn.joins!(*args) - end - - def joins!(*args) # :nodoc: - args.compact! - args.flatten! - self.joins_values += args - self - end - - # Performs a left outer joins on +args+: - # - # User.left_outer_joins(:posts) - # => SELECT "users".* FROM "users" LEFT OUTER JOIN "posts" ON "posts"."user_id" = "users"."id" - # - def left_outer_joins(*args) - check_if_method_has_arguments!(:left_outer_joins, args) - - args.compact! - args.flatten! - - spawn.left_outer_joins!(*args) - end - alias :left_joins :left_outer_joins - - def left_outer_joins!(*args) # :nodoc: - self.left_outer_joins_values += args - self - end - - # Returns a new relation, which is the result of filtering the current relation - # according to the conditions in the arguments. - # - # #where accepts conditions in one of several formats. In the examples below, the resulting - # SQL is given as an illustration; the actual query generated may be different depending - # on the database adapter. - # - # === string - # - # A single string, without additional arguments, is passed to the query - # constructor as an SQL fragment, and used in the where clause of the query. - # - # Client.where("orders_count = '2'") - # # SELECT * from clients where orders_count = '2'; - # - # Note that building your own string from user input may expose your application - # to injection attacks if not done properly. As an alternative, it is recommended - # to use one of the following methods. - # - # === array - # - # If an array is passed, then the first element of the array is treated as a template, and - # the remaining elements are inserted into the template to generate the condition. - # Active Record takes care of building the query to avoid injection attacks, and will - # convert from the ruby type to the database type where needed. Elements are inserted - # into the string in the order in which they appear. - # - # User.where(["name = ? and email = ?", "Joe", "joe@example.com"]) - # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'; - # - # Alternatively, you can use named placeholders in the template, and pass a hash as the - # second element of the array. The names in the template are replaced with the corresponding - # values from the hash. - # - # User.where(["name = :name and email = :email", { name: "Joe", email: "joe@example.com" }]) - # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'; - # - # This can make for more readable code in complex queries. - # - # Lastly, you can use sprintf-style % escapes in the template. This works slightly differently - # than the previous methods; you are responsible for ensuring that the values in the template - # are properly quoted. The values are passed to the connector for quoting, but the caller - # is responsible for ensuring they are enclosed in quotes in the resulting SQL. After quoting, - # the values are inserted using the same escapes as the Ruby core method +Kernel::sprintf+. - # - # User.where(["name = '%s' and email = '%s'", "Joe", "joe@example.com"]) - # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'; - # - # If #where is called with multiple arguments, these are treated as if they were passed as - # the elements of a single array. - # - # User.where("name = :name and email = :email", { name: "Joe", email: "joe@example.com" }) - # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com'; - # - # When using strings to specify conditions, you can use any operator available from - # the database. While this provides the most flexibility, you can also unintentionally introduce - # dependencies on the underlying database. If your code is intended for general consumption, - # test with multiple database backends. - # - # === hash - # - # #where will also accept a hash condition, in which the keys are fields and the values - # are values to be searched for. - # - # Fields can be symbols or strings. Values can be single values, arrays, or ranges. - # - # User.where({ name: "Joe", email: "joe@example.com" }) - # # SELECT * FROM users WHERE name = 'Joe' AND email = 'joe@example.com' - # - # User.where({ name: ["Alice", "Bob"]}) - # # SELECT * FROM users WHERE name IN ('Alice', 'Bob') - # - # User.where({ created_at: (Time.now.midnight - 1.day)..Time.now.midnight }) - # # SELECT * FROM users WHERE (created_at BETWEEN '2012-06-09 07:00:00.000000' AND '2012-06-10 07:00:00.000000') - # - # In the case of a belongs_to relationship, an association key can be used - # to specify the model if an ActiveRecord object is used as the value. - # - # author = Author.find(1) - # - # # The following queries will be equivalent: - # Post.where(author: author) - # Post.where(author_id: author) - # - # This also works with polymorphic belongs_to relationships: - # - # treasure = Treasure.create(name: 'gold coins') - # treasure.price_estimates << PriceEstimate.create(price: 125) - # - # # The following queries will be equivalent: - # PriceEstimate.where(estimate_of: treasure) - # PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure) - # - # === Joins - # - # If the relation is the result of a join, you may create a condition which uses any of the - # tables in the join. For string and array conditions, use the table name in the condition. - # - # User.joins(:posts).where("posts.created_at < ?", Time.now) - # - # For hash conditions, you can either use the table name in the key, or use a sub-hash. - # - # User.joins(:posts).where({ "posts.published" => true }) - # User.joins(:posts).where({ posts: { published: true } }) - # - # === no argument - # - # If no argument is passed, #where returns a new instance of WhereChain, that - # can be chained with #not to return a new relation that negates the where clause. - # - # User.where.not(name: "Jon") - # # SELECT * FROM users WHERE name != 'Jon' - # - # See WhereChain for more details on #not. - # - # === blank condition - # - # If the condition is any blank-ish object, then #where is a no-op and returns - # the current relation. - def where(opts = :chain, *rest) - if :chain == opts - WhereChain.new(spawn) - elsif opts.blank? - self - else - spawn.where!(opts, *rest) - end - end - - def where!(opts, *rest) # :nodoc: - opts = sanitize_forbidden_attributes(opts) - references!(PredicateBuilder.references(opts)) if Hash === opts - self.where_clause += where_clause_factory.build(opts, rest) - self - end - - # Allows you to change a previously set where condition for a given attribute, instead of appending to that condition. - # - # Post.where(trashed: true).where(trashed: false) - # # WHERE `trashed` = 1 AND `trashed` = 0 - # - # Post.where(trashed: true).rewhere(trashed: false) - # # WHERE `trashed` = 0 - # - # Post.where(active: true).where(trashed: true).rewhere(trashed: false) - # # WHERE `active` = 1 AND `trashed` = 0 - # - # This is short-hand for unscope(where: conditions.keys).where(conditions). - # Note that unlike reorder, we're only unscoping the named conditions -- not the entire where statement. - def rewhere(conditions) - unscope(where: conditions.keys).where(conditions) - end - - # Returns a new relation, which is the logical union of this relation and the one passed as an - # argument. - # - # The two relations must be structurally compatible: they must be scoping the same model, and - # they must differ only by #where (if no #group has been defined) or #having (if a #group is - # present). Neither relation may have a #limit, #offset, or #distinct set. - # - # Post.where("id = 1").or(Post.where("author_id = 3")) - # # SELECT `posts`.* FROM `posts` WHERE ((id = 1) OR (author_id = 3)) - # - def or(other) - unless other.is_a? Relation - raise ArgumentError, "You have passed #{other.class.name} object to #or. Pass an ActiveRecord::Relation object instead." - end - - spawn.or!(other) - end - - def or!(other) # :nodoc: - incompatible_values = structurally_incompatible_values_for_or(other) - - unless incompatible_values.empty? - raise ArgumentError, "Relation passed to #or must be structurally compatible. Incompatible values: #{incompatible_values}" - end - - self.where_clause = self.where_clause.or(other.where_clause) - self.having_clause = having_clause.or(other.having_clause) - - self - end - - # Allows to specify a HAVING clause. Note that you can't use HAVING - # without also specifying a GROUP clause. - # - # Order.having('SUM(price) > 30').group('user_id') - def having(opts, *rest) - opts.blank? ? self : spawn.having!(opts, *rest) - end - - def having!(opts, *rest) # :nodoc: - opts = sanitize_forbidden_attributes(opts) - references!(PredicateBuilder.references(opts)) if Hash === opts - - self.having_clause += having_clause_factory.build(opts, rest) - self - end - - # Specifies a limit for the number of records to retrieve. - # - # User.limit(10) # generated SQL has 'LIMIT 10' - # - # User.limit(10).limit(20) # generated SQL has 'LIMIT 20' - def limit(value) - spawn.limit!(value) - end - - def limit!(value) # :nodoc: - self.limit_value = value - self - end - - # Specifies the number of rows to skip before returning rows. - # - # User.offset(10) # generated SQL has "OFFSET 10" - # - # Should be used with order. - # - # User.offset(10).order("name ASC") - def offset(value) - spawn.offset!(value) - end - - def offset!(value) # :nodoc: - self.offset_value = value - self - end - - # Specifies locking settings (default to +true+). For more information - # on locking, please see ActiveRecord::Locking. - def lock(locks = true) - spawn.lock!(locks) - end - - def lock!(locks = true) # :nodoc: - case locks - when String, TrueClass, NilClass - self.lock_value = locks || true - else - self.lock_value = false - end - - self - end - - # Returns a chainable relation with zero records. - # - # The returned relation implements the Null Object pattern. It is an - # object with defined null behavior and always returns an empty array of - # records without querying the database. - # - # Any subsequent condition chained to the returned relation will continue - # generating an empty relation and will not fire any query to the database. - # - # Used in cases where a method or scope could return zero records but the - # result needs to be chainable. - # - # For example: - # - # @posts = current_user.visible_posts.where(name: params[:name]) - # # the visible_posts method is expected to return a chainable Relation - # - # def visible_posts - # case role - # when 'Country Manager' - # Post.where(country: country) - # when 'Reviewer' - # Post.published - # when 'Bad User' - # Post.none # It can't be chained if [] is returned. - # end - # end - # - def none - spawn.none! - end - - def none! # :nodoc: - where!("1=0").extending!(NullRelation) - end - - # Sets readonly attributes for the returned relation. If value is - # true (default), attempting to update a record will result in an error. - # - # users = User.readonly - # users.first.save - # => ActiveRecord::ReadOnlyRecord: User is marked as readonly - def readonly(value = true) - spawn.readonly!(value) - end - - def readonly!(value = true) # :nodoc: - self.readonly_value = value - self - end - - # Sets attributes to be used when creating new records from a - # relation object. - # - # users = User.where(name: 'Oscar') - # users.new.name # => 'Oscar' - # - # users = users.create_with(name: 'DHH') - # users.new.name # => 'DHH' - # - # You can pass +nil+ to #create_with to reset attributes: - # - # users = users.create_with(nil) - # users.new.name # => 'Oscar' - def create_with(value) - spawn.create_with!(value) - end - - def create_with!(value) # :nodoc: - if value - value = sanitize_forbidden_attributes(value) - self.create_with_value = create_with_value.merge(value) - else - self.create_with_value = {} - end - - self - end - - # Specifies table from which the records will be fetched. For example: - # - # Topic.select('title').from('posts') - # # SELECT title FROM posts - # - # Can accept other relation objects. For example: - # - # Topic.select('title').from(Topic.approved) - # # SELECT title FROM (SELECT * FROM topics WHERE approved = 't') subquery - # - # Topic.select('a.title').from(Topic.approved, :a) - # # SELECT a.title FROM (SELECT * FROM topics WHERE approved = 't') a - # - def from(value, subquery_name = nil) - spawn.from!(value, subquery_name) - end - - def from!(value, subquery_name = nil) # :nodoc: - self.from_clause = Relation::FromClause.new(value, subquery_name) - self - end - - # Specifies whether the records should be unique or not. For example: - # - # User.select(:name) - # # Might return two records with the same name - # - # User.select(:name).distinct - # # Returns 1 record per distinct name - # - # User.select(:name).distinct.distinct(false) - # # You can also remove the uniqueness - def distinct(value = true) - spawn.distinct!(value) - end - - # Like #distinct, but modifies relation in place. - def distinct!(value = true) # :nodoc: - self.distinct_value = value - self - end - - # Used to extend a scope with additional methods, either through - # a module or through a block provided. - # - # The object returned is a relation, which can be further extended. - # - # === Using a module - # - # module Pagination - # def page(number) - # # pagination code goes here - # end - # end - # - # scope = Model.all.extending(Pagination) - # scope.page(params[:page]) - # - # You can also pass a list of modules: - # - # scope = Model.all.extending(Pagination, SomethingElse) - # - # === Using a block - # - # scope = Model.all.extending do - # def page(number) - # # pagination code goes here - # end - # end - # scope.page(params[:page]) - # - # You can also use a block and a module list: - # - # scope = Model.all.extending(Pagination) do - # def per_page(number) - # # pagination code goes here - # end - # end - def extending(*modules, &block) - if modules.any? || block - spawn.extending!(*modules, &block) - else - self - end - end - - def extending!(*modules, &block) # :nodoc: - modules << Module.new(&block) if block - modules.flatten! - - self.extending_values += modules - extend(*extending_values) if extending_values.any? - - self - end - - # Reverse the existing order clause on the relation. - # - # User.order('name ASC').reverse_order # generated SQL has 'ORDER BY name DESC' - def reverse_order - spawn.reverse_order! - end - - def reverse_order! # :nodoc: - orders = order_values.uniq - orders.reject!(&:blank?) - self.order_values = reverse_sql_order(orders) - self - end - - # Returns the Arel object associated with the relation. - def arel # :nodoc: - @arel ||= build_arel - end - - # Returns a relation value with a given name - def get_value(name) # :nodoc: - @values[name] || default_value_for(name) - end - - # Sets the relation value with the given name - def set_value(name, value) # :nodoc: - assert_mutability! - @values[name] = value - end - - private - - def assert_mutability! - raise ImmutableRelation if @loaded - raise ImmutableRelation if defined?(@arel) && @arel - end - - def build_arel - arel = Arel::SelectManager.new(table) - - build_joins(arel, joins_values.flatten) unless joins_values.empty? - build_left_outer_joins(arel, left_outer_joins_values.flatten) unless left_outer_joins_values.empty? - - arel.where(where_clause.ast) unless where_clause.empty? - arel.having(having_clause.ast) unless having_clause.empty? - arel.take(Arel::Nodes::BindParam.new) if limit_value - arel.skip(Arel::Nodes::BindParam.new) if offset_value - arel.group(*arel_columns(group_values.uniq.reject(&:blank?))) unless group_values.empty? - - build_order(arel) - - build_select(arel) - - arel.distinct(distinct_value) - arel.from(build_from) unless from_clause.empty? - arel.lock(lock_value) if lock_value - - arel - end - - def build_from - opts = from_clause.value - name = from_clause.name - case opts - when Relation - name ||= "subquery" - opts.arel.as(name.to_s) - else - opts - end - end - - def build_left_outer_joins(manager, outer_joins) - buckets = outer_joins.group_by do |join| - case join - when Hash, Symbol, Array - :association_join - else - raise ArgumentError, "only Hash, Symbol and Array are allowed" - end - end - - build_join_query(manager, buckets, Arel::Nodes::OuterJoin) - end - - def build_joins(manager, joins) - buckets = joins.group_by do |join| - case join - when String - :string_join - when Hash, Symbol, Array - :association_join - when ActiveRecord::Associations::JoinDependency - :stashed_join - when Arel::Nodes::Join - :join_node - else - raise "unknown class: %s" % join.class.name - end - end - - build_join_query(manager, buckets, Arel::Nodes::InnerJoin) - end - - def build_join_query(manager, buckets, join_type) - buckets.default = [] - - association_joins = buckets[:association_join] - stashed_association_joins = buckets[:stashed_join] - join_nodes = buckets[:join_node].uniq - string_joins = buckets[:string_join].map(&:strip).uniq - - join_list = join_nodes + convert_join_strings_to_ast(manager, string_joins) - - join_dependency = ActiveRecord::Associations::JoinDependency.new( - @klass, - association_joins, - join_list - ) - - join_infos = join_dependency.join_constraints stashed_association_joins, join_type - - join_infos.each do |info| - info.joins.each { |join| manager.from(join) } - manager.bind_values.concat info.binds - end - - manager.join_sources.concat(join_list) - - manager - end - - def convert_join_strings_to_ast(table, joins) - joins - .flatten - .reject(&:blank?) - .map { |join| table.create_string_join(Arel.sql(join)) } - end - - def build_select(arel) - if select_values.any? - arel.project(*arel_columns(select_values.uniq)) - elsif klass.ignored_columns.any? - arel.project(*klass.column_names.map { |field| arel_attribute(field) }) - else - arel.project(@klass.arel_table[Arel.star]) - end - end - - def arel_columns(columns) - columns.map do |field| - if (Symbol === field || String === field) && (klass.has_attribute?(field) || klass.attribute_alias?(field)) && !from_clause.value - arel_attribute(field) - elsif Symbol === field - connection.quote_table_name(field.to_s) - else - field - end - end - end - - def reverse_sql_order(order_query) - if order_query.empty? - return [arel_attribute(primary_key).desc] if primary_key - raise IrreversibleOrderError, - "Relation has no current order and table has no primary key to be used as default order" - end - - order_query.flat_map do |o| - case o - when Arel::Attribute - o.desc - when Arel::Nodes::Ordering - o.reverse - when String - if does_not_support_reverse?(o) - raise IrreversibleOrderError, "Order #{o.inspect} can not be reversed automatically" - end - o.split(",").map! do |s| - s.strip! - s.gsub!(/\sasc\Z/i, " DESC") || s.gsub!(/\sdesc\Z/i, " ASC") || (s << " DESC") - end - else - o - end - end - end - - def does_not_support_reverse?(order) - # Uses SQL function with multiple arguments. - (order.include?(",") && order.split(",").find { |section| section.count("(") != section.count(")") }) || - # Uses "nulls first" like construction. - /nulls (first|last)\Z/i.match?(order) - end - - def build_order(arel) - orders = order_values.uniq - orders.reject!(&:blank?) - - arel.order(*orders) unless orders.empty? - end - - VALID_DIRECTIONS = [:asc, :desc, :ASC, :DESC, - "asc", "desc", "ASC", "DESC"] # :nodoc: - - def validate_order_args(args) - args.each do |arg| - next unless arg.is_a?(Hash) - arg.each do |_key, value| - raise ArgumentError, "Direction \"#{value}\" is invalid. Valid " \ - "directions are: #{VALID_DIRECTIONS.inspect}" unless VALID_DIRECTIONS.include?(value) - end - end - end - - def preprocess_order_args(order_args) - order_args.map! do |arg| - klass.send(:sanitize_sql_for_order, arg) - end - order_args.flatten! - validate_order_args(order_args) - - references = order_args.grep(String) - references.map! { |arg| arg =~ /^([a-zA-Z]\w*)\.(\w+)/ && $1 }.compact! - references!(references) if references.any? - - # if a symbol is given we prepend the quoted table name - order_args.map! do |arg| - case arg - when Symbol - arel_attribute(arg).asc - when Hash - arg.map { |field, dir| - case field - when Arel::Nodes::SqlLiteral - field.send(dir.downcase) - else - arel_attribute(field).send(dir.downcase) - end - } - else - arg - end - end.flatten! - end - - # Checks to make sure that the arguments are not blank. Note that if some - # blank-like object were initially passed into the query method, then this - # method will not raise an error. - # - # Example: - # - # Post.references() # raises an error - # Post.references([]) # does not raise an error - # - # This particular method should be called with a method_name and the args - # passed into that method as an input. For example: - # - # def references(*args) - # check_if_method_has_arguments!("references", args) - # ... - # end - def check_if_method_has_arguments!(method_name, args) - if args.blank? - raise ArgumentError, "The method .#{method_name}() must contain arguments." - end - end - - STRUCTURAL_OR_METHODS = Relation::VALUE_METHODS - [:extending, :where, :having] - def structurally_incompatible_values_for_or(other) - STRUCTURAL_OR_METHODS.reject do |method| - get_value(method) == other.get_value(method) - end - end - - def where_clause_factory - @where_clause_factory ||= Relation::WhereClauseFactory.new(klass, predicate_builder) - end - alias having_clause_factory where_clause_factory - - DEFAULT_VALUES = { - create_with: FROZEN_EMPTY_HASH, - readonly: false, - where: Relation::WhereClause.empty, - having: Relation::WhereClause.empty, - from: Relation::FromClause.empty - } - - Relation::MULTI_VALUE_METHODS.each do |value| - DEFAULT_VALUES[value] ||= FROZEN_EMPTY_ARRAY - end - - Relation::SINGLE_VALUE_METHODS.each do |value| - DEFAULT_VALUES[value] = nil if DEFAULT_VALUES[value].nil? - end - - def default_value_for(name) - DEFAULT_VALUES.fetch(name) do - raise ArgumentError, "unknown relation value #{name.inspect}" - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/record_fetch_warning.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/record_fetch_warning.rb deleted file mode 100644 index 31544c730e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/record_fetch_warning.rb +++ /dev/null @@ -1,49 +0,0 @@ -module ActiveRecord - class Relation - module RecordFetchWarning - # When this module is prepended to ActiveRecord::Relation and - # +config.active_record.warn_on_records_fetched_greater_than+ is - # set to an integer, if the number of records a query returns is - # greater than the value of +warn_on_records_fetched_greater_than+, - # a warning is logged. This allows for the detection of queries that - # return a large number of records, which could cause memory bloat. - # - # In most cases, fetching large number of records can be performed - # efficiently using the ActiveRecord::Batches methods. - # See ActiveRecord::Batches for more information. - def exec_queries - QueryRegistry.reset - - super.tap do - if logger && warn_on_records_fetched_greater_than - if @records.length > warn_on_records_fetched_greater_than - logger.warn "Query fetched #{@records.size} #{@klass} records: #{QueryRegistry.queries.join(";")}" - end - end - end - end - - # :stopdoc: - ActiveSupport::Notifications.subscribe("sql.active_record") do |*, payload| - QueryRegistry.queries << payload[:sql] - end - # :startdoc: - - class QueryRegistry # :nodoc: - extend ActiveSupport::PerThreadRegistry - - attr_reader :queries - - def initialize - @queries = [] - end - - def reset - @queries.clear - end - end - end - end -end - -ActiveRecord::Relation.prepend ActiveRecord::Relation::RecordFetchWarning diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/spawn_methods.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/spawn_methods.rb deleted file mode 100644 index ada89b5ec3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/spawn_methods.rb +++ /dev/null @@ -1,75 +0,0 @@ -require "active_support/core_ext/hash/except" -require "active_support/core_ext/hash/slice" -require "active_record/relation/merger" - -module ActiveRecord - module SpawnMethods - # This is overridden by Associations::CollectionProxy - def spawn #:nodoc: - clone - end - - # Merges in the conditions from other, if other is an ActiveRecord::Relation. - # Returns an array representing the intersection of the resulting records with other, if other is an array. - # - # Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) ) - # # Performs a single join query with both where conditions. - # - # recent_posts = Post.order('created_at DESC').first(5) - # Post.where(published: true).merge(recent_posts) - # # Returns the intersection of all published posts with the 5 most recently created posts. - # # (This is just an example. You'd probably want to do this with a single query!) - # - # Procs will be evaluated by merge: - # - # Post.where(published: true).merge(-> { joins(:comments) }) - # # => Post.where(published: true).joins(:comments) - # - # This is mainly intended for sharing common conditions between multiple associations. - def merge(other) - if other.is_a?(Array) - records & other - elsif other - spawn.merge!(other) - else - raise ArgumentError, "invalid argument: #{other.inspect}." - end - end - - def merge!(other) # :nodoc: - if other.is_a?(Hash) - Relation::HashMerger.new(self, other).merge - elsif other.is_a?(Relation) - Relation::Merger.new(self, other).merge - elsif other.respond_to?(:to_proc) - instance_exec(&other) - else - raise ArgumentError, "#{other.inspect} is not an ActiveRecord::Relation" - end - end - - # Removes from the query the condition(s) specified in +skips+. - # - # Post.order('id asc').except(:order) # discards the order condition - # Post.where('id > 10').order('id asc').except(:where) # discards the where condition but keeps the order - def except(*skips) - relation_with values.except(*skips) - end - - # Removes any condition from the query other than the one(s) specified in +onlies+. - # - # Post.order('id asc').only(:where) # discards the order condition - # Post.order('id asc').only(:where, :order) # uses the specified order - def only(*onlies) - relation_with values.slice(*onlies) - end - - private - - def relation_with(values) - result = Relation.create(klass, table, predicate_builder, values) - result.extend(*extending_values) if extending_values.any? - result - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/where_clause.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/where_clause.rb deleted file mode 100644 index 7542ea4d8c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/where_clause.rb +++ /dev/null @@ -1,189 +0,0 @@ -module ActiveRecord - class Relation - class WhereClause # :nodoc: - attr_reader :binds - - delegate :any?, :empty?, to: :predicates - - def initialize(predicates, binds) - @predicates = predicates - @binds = binds - end - - def +(other) - WhereClause.new( - predicates + other.predicates, - binds + other.binds, - ) - end - - def merge(other) - WhereClause.new( - predicates_unreferenced_by(other) + other.predicates, - non_conflicting_binds(other) + other.binds, - ) - end - - def except(*columns) - WhereClause.new(*except_predicates_and_binds(columns)) - end - - def or(other) - if empty? - self - elsif other.empty? - other - else - WhereClause.new( - [ast.or(other.ast)], - binds + other.binds - ) - end - end - - def to_h(table_name = nil) - equalities = predicates.grep(Arel::Nodes::Equality) - if table_name - equalities = equalities.select do |node| - node.left.relation.name == table_name - end - end - - binds = self.binds.map { |attr| [attr.name, attr.value] }.to_h - - equalities.map { |node| - name = node.left.name - [name, binds.fetch(name.to_s) { - case node.right - when Array then node.right.map(&:val) - when Arel::Nodes::Casted, Arel::Nodes::Quoted - node.right.val - end - }] - }.to_h - end - - def ast - Arel::Nodes::And.new(predicates_with_wrapped_sql_literals) - end - - def ==(other) - other.is_a?(WhereClause) && - predicates == other.predicates && - binds == other.binds - end - - def invert - WhereClause.new(inverted_predicates, binds) - end - - def self.empty - @empty ||= new([], []) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :predicates - - def referenced_columns - @referenced_columns ||= begin - equality_nodes = predicates.select { |n| equality_node?(n) } - Set.new(equality_nodes, &:left) - end - end - - private - - def predicates_unreferenced_by(other) - predicates.reject do |n| - equality_node?(n) && other.referenced_columns.include?(n.left) - end - end - - def equality_node?(node) - node.respond_to?(:operator) && node.operator == :== - end - - def non_conflicting_binds(other) - conflicts = referenced_columns & other.referenced_columns - conflicts.map! { |node| node.name.to_s } - binds.reject { |attr| conflicts.include?(attr.name) } - end - - def inverted_predicates - predicates.map { |node| invert_predicate(node) } - end - - def invert_predicate(node) - case node - when NilClass - raise ArgumentError, "Invalid argument for .where.not(), got nil." - when Arel::Nodes::In - Arel::Nodes::NotIn.new(node.left, node.right) - when Arel::Nodes::Equality - Arel::Nodes::NotEqual.new(node.left, node.right) - when String - Arel::Nodes::Not.new(Arel::Nodes::SqlLiteral.new(node)) - else - Arel::Nodes::Not.new(node) - end - end - - def except_predicates_and_binds(columns) - except_binds = [] - binds_index = 0 - - predicates = self.predicates.reject do |node| - binds_contains = node.grep(Arel::Nodes::BindParam).size if node.is_a?(Arel::Nodes::Node) - - except = \ - case node - when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThan, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThan, Arel::Nodes::GreaterThanOrEqual - subrelation = (node.left.kind_of?(Arel::Attributes::Attribute) ? node.left : node.right) - columns.include?(subrelation.name.to_s) - end - - if except && binds_contains > 0 - (binds_index...(binds_index + binds_contains)).each do |i| - except_binds[i] = true - end - end - - binds_index += binds_contains if binds_contains - - except - end - - binds = self.binds.reject.with_index do |_, i| - except_binds[i] - end - - [predicates, binds] - end - - def predicates_with_wrapped_sql_literals - non_empty_predicates.map do |node| - if Arel::Nodes::Equality === node - node - else - wrap_sql_literal(node) - end - end - end - - ARRAY_WITH_EMPTY_STRING = [""] - def non_empty_predicates - predicates - ARRAY_WITH_EMPTY_STRING - end - - def wrap_sql_literal(node) - if ::String === node - node = Arel.sql(node) - end - Arel::Nodes::Grouping.new(node) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/where_clause_factory.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/where_clause_factory.rb deleted file mode 100644 index 04bee73e8f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/relation/where_clause_factory.rb +++ /dev/null @@ -1,77 +0,0 @@ -module ActiveRecord - class Relation - class WhereClauseFactory # :nodoc: - def initialize(klass, predicate_builder) - @klass = klass - @predicate_builder = predicate_builder - end - - def build(opts, other) - case opts - when String, Array - parts = [klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))] - when Hash - attributes = predicate_builder.resolve_column_aliases(opts) - attributes = klass.send(:expand_hash_conditions_for_aggregates, attributes) - attributes.stringify_keys! - - if perform_case_sensitive?(options = other.last) - parts, binds = build_for_case_sensitive(attributes, options) - else - attributes, binds = predicate_builder.create_binds(attributes) - parts = predicate_builder.build_from_hash(attributes) - end - when Arel::Nodes::Node - parts = [opts] - else - raise ArgumentError, "Unsupported argument type: #{opts} (#{opts.class})" - end - - WhereClause.new(parts, binds || []) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :klass, :predicate_builder - - private - - def perform_case_sensitive?(options) - options && options.key?(:case_sensitive) - end - - def build_for_case_sensitive(attributes, options) - parts, binds = [], [] - table = klass.arel_table - - attributes.each do |attribute, value| - if reflection = klass._reflect_on_association(attribute) - attribute = reflection.foreign_key.to_s - value = value[reflection.klass.primary_key] unless value.nil? - end - - if value.nil? - parts << table[attribute].eq(value) - else - column = klass.column_for_attribute(attribute) - - binds << predicate_builder.send(:build_bind_param, attribute, value) - value = Arel::Nodes::BindParam.new - - predicate = if options[:case_sensitive] - klass.connection.case_sensitive_comparison(table, attribute, column, value) - else - klass.connection.case_insensitive_comparison(table, attribute, column, value) - end - - parts << predicate - end - end - - [parts, binds] - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/result.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/result.rb deleted file mode 100644 index 26b1d48e9e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/result.rb +++ /dev/null @@ -1,147 +0,0 @@ -module ActiveRecord - ### - # This class encapsulates a result returned from calling - # {#exec_query}[rdoc-ref:ConnectionAdapters::DatabaseStatements#exec_query] - # on any database connection adapter. For example: - # - # result = ActiveRecord::Base.connection.exec_query('SELECT id, title, body FROM posts') - # result # => # - # - # # Get the column names of the result: - # result.columns - # # => ["id", "title", "body"] - # - # # Get the record values of the result: - # result.rows - # # => [[1, "title_1", "body_1"], - # [2, "title_2", "body_2"], - # ... - # ] - # - # # Get an array of hashes representing the result (column => value): - # result.to_hash - # # => [{"id" => 1, "title" => "title_1", "body" => "body_1"}, - # {"id" => 2, "title" => "title_2", "body" => "body_2"}, - # ... - # ] - # - # # ActiveRecord::Result also includes Enumerable. - # result.each do |row| - # puts row['title'] + " " + row['body'] - # end - class Result - include Enumerable - - attr_reader :columns, :rows, :column_types - - def initialize(columns, rows, column_types = {}) - @columns = columns - @rows = rows - @hash_rows = nil - @column_types = column_types - end - - # Returns the number of elements in the rows array. - def length - @rows.length - end - - # Calls the given block once for each element in row collection, passing - # row as parameter. - # - # Returns an +Enumerator+ if no block is given. - def each - if block_given? - hash_rows.each { |row| yield row } - else - hash_rows.to_enum { @rows.size } - end - end - - # Returns an array of hashes representing each row record. - def to_hash - hash_rows - end - - alias :map! :map - alias :collect! :map - - # Returns true if there are no records, otherwise false. - def empty? - rows.empty? - end - - # Returns an array of hashes representing each row record. - def to_ary - hash_rows - end - - def [](idx) - hash_rows[idx] - end - - # Returns the first record from the rows collection. - # If the rows collection is empty, returns +nil+. - def first - return nil if @rows.empty? - Hash[@columns.zip(@rows.first)] - end - - # Returns the last record from the rows collection. - # If the rows collection is empty, returns +nil+. - def last - return nil if @rows.empty? - Hash[@columns.zip(@rows.last)] - end - - def cast_values(type_overrides = {}) # :nodoc: - types = columns.map { |name| column_type(name, type_overrides) } - result = rows.map do |values| - types.zip(values).map { |type, value| type.deserialize(value) } - end - - columns.one? ? result.map!(&:first) : result - end - - def initialize_copy(other) - @columns = columns.dup - @rows = rows.dup - @column_types = column_types.dup - @hash_rows = nil - end - - private - - def column_type(name, type_overrides = {}) - type_overrides.fetch(name) do - column_types.fetch(name, Type.default_value) - end - end - - def hash_rows - @hash_rows ||= - begin - # We freeze the strings to prevent them getting duped when - # used as keys in ActiveRecord::Base's @attributes hash - columns = @columns.map { |c| c.dup.freeze } - @rows.map { |row| - # In the past we used Hash[columns.zip(row)] - # though elegant, the verbose way is much more efficient - # both time and memory wise cause it avoids a big array allocation - # this method is called a lot and needs to be micro optimised - hash = {} - - index = 0 - length = columns.length - - while index < length - hash[columns[index]] = row[index] - index += 1 - end - - hash - } - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/runtime_registry.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/runtime_registry.rb deleted file mode 100644 index b79eb2263f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/runtime_registry.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "active_support/per_thread_registry" - -module ActiveRecord - # This is a thread locals registry for Active Record. For example: - # - # ActiveRecord::RuntimeRegistry.connection_handler - # - # returns the connection handler local to the current thread. - # - # See the documentation of ActiveSupport::PerThreadRegistry - # for further details. - class RuntimeRegistry # :nodoc: - extend ActiveSupport::PerThreadRegistry - - attr_accessor :connection_handler, :sql_runtime - - [:connection_handler, :sql_runtime].each do |val| - class_eval %{ def self.#{val}; instance.#{val}; end }, __FILE__, __LINE__ - class_eval %{ def self.#{val}=(x); instance.#{val}=x; end }, __FILE__, __LINE__ - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/sanitization.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/sanitization.rb deleted file mode 100644 index 64bda1539c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/sanitization.rb +++ /dev/null @@ -1,214 +0,0 @@ -module ActiveRecord - module Sanitization - extend ActiveSupport::Concern - - module ClassMethods - private - - # Accepts an array or string of SQL conditions and sanitizes - # them into a valid SQL fragment for a WHERE clause. - # - # sanitize_sql_for_conditions(["name=? and group_id=?", "foo'bar", 4]) - # # => "name='foo''bar' and group_id=4" - # - # sanitize_sql_for_conditions(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4]) - # # => "name='foo''bar' and group_id='4'" - # - # sanitize_sql_for_conditions(["name='%s' and group_id='%s'", "foo'bar", 4]) - # # => "name='foo''bar' and group_id='4'" - # - # sanitize_sql_for_conditions("name='foo''bar' and group_id='4'") - # # => "name='foo''bar' and group_id='4'" - def sanitize_sql_for_conditions(condition) # :doc: - return nil if condition.blank? - - case condition - when Array; sanitize_sql_array(condition) - else condition - end - end - alias :sanitize_sql :sanitize_sql_for_conditions - alias :sanitize_conditions :sanitize_sql - deprecate sanitize_conditions: :sanitize_sql - - # Accepts an array, hash, or string of SQL conditions and sanitizes - # them into a valid SQL fragment for a SET clause. - # - # sanitize_sql_for_assignment(["name=? and group_id=?", nil, 4]) - # # => "name=NULL and group_id=4" - # - # sanitize_sql_for_assignment(["name=:name and group_id=:group_id", name: nil, group_id: 4]) - # # => "name=NULL and group_id=4" - # - # Post.send(:sanitize_sql_for_assignment, { name: nil, group_id: 4 }) - # # => "`posts`.`name` = NULL, `posts`.`group_id` = 4" - # - # sanitize_sql_for_assignment("name=NULL and group_id='4'") - # # => "name=NULL and group_id='4'" - def sanitize_sql_for_assignment(assignments, default_table_name = table_name) # :doc: - case assignments - when Array; sanitize_sql_array(assignments) - when Hash; sanitize_sql_hash_for_assignment(assignments, default_table_name) - else assignments - end - end - - # Accepts an array, or string of SQL conditions and sanitizes - # them into a valid SQL fragment for an ORDER clause. - # - # sanitize_sql_for_order(["field(id, ?)", [1,3,2]]) - # # => "field(id, 1,3,2)" - # - # sanitize_sql_for_order("id ASC") - # # => "id ASC" - def sanitize_sql_for_order(condition) # :doc: - if condition.is_a?(Array) && condition.first.to_s.include?("?") - sanitize_sql_array(condition) - else - condition - end - end - - # Accepts a hash of SQL conditions and replaces those attributes - # that correspond to a {#composed_of}[rdoc-ref:Aggregations::ClassMethods#composed_of] - # relationship with their expanded aggregate attribute values. - # - # Given: - # - # class Person < ActiveRecord::Base - # composed_of :address, class_name: "Address", - # mapping: [%w(address_street street), %w(address_city city)] - # end - # - # Then: - # - # { address: Address.new("813 abc st.", "chicago") } - # # => { address_street: "813 abc st.", address_city: "chicago" } - def expand_hash_conditions_for_aggregates(attrs) # :doc: - expanded_attrs = {} - attrs.each do |attr, value| - if aggregation = reflect_on_aggregation(attr.to_sym) - mapping = aggregation.mapping - mapping.each do |field_attr, aggregate_attr| - if mapping.size == 1 && !value.respond_to?(aggregate_attr) - expanded_attrs[field_attr] = value - else - expanded_attrs[field_attr] = value.send(aggregate_attr) - end - end - else - expanded_attrs[attr] = value - end - end - expanded_attrs - end - - # Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause. - # - # sanitize_sql_hash_for_assignment({ status: nil, group_id: 1 }, "posts") - # # => "`posts`.`status` = NULL, `posts`.`group_id` = 1" - def sanitize_sql_hash_for_assignment(attrs, table) # :doc: - c = connection - attrs.map do |attr, value| - value = type_for_attribute(attr.to_s).serialize(value) - "#{c.quote_table_name_for_assignment(table, attr)} = #{c.quote(value)}" - end.join(", ") - end - - # Sanitizes a +string+ so that it is safe to use within an SQL - # LIKE statement. This method uses +escape_character+ to escape all occurrences of "\", "_" and "%". - # - # sanitize_sql_like("100%") - # # => "100\\%" - # - # sanitize_sql_like("snake_cased_string") - # # => "snake\\_cased\\_string" - # - # sanitize_sql_like("100%", "!") - # # => "100!%" - # - # sanitize_sql_like("snake_cased_string", "!") - # # => "snake!_cased!_string" - def sanitize_sql_like(string, escape_character = "\\") # :doc: - pattern = Regexp.union(escape_character, "%", "_") - string.gsub(pattern) { |x| [escape_character, x].join } - end - - # Accepts an array of conditions. The array has each value - # sanitized and interpolated into the SQL statement. - # - # sanitize_sql_array(["name=? and group_id=?", "foo'bar", 4]) - # # => "name='foo''bar' and group_id=4" - # - # sanitize_sql_array(["name=:name and group_id=:group_id", name: "foo'bar", group_id: 4]) - # # => "name='foo''bar' and group_id=4" - # - # sanitize_sql_array(["name='%s' and group_id='%s'", "foo'bar", 4]) - # # => "name='foo''bar' and group_id='4'" - def sanitize_sql_array(ary) # :doc: - statement, *values = ary - if values.first.is_a?(Hash) && /:\w+/.match?(statement) - replace_named_bind_variables(statement, values.first) - elsif statement.include?("?") - replace_bind_variables(statement, values) - elsif statement.blank? - statement - else - statement % values.collect { |value| connection.quote_string(value.to_s) } - end - end - - def replace_bind_variables(statement, values) - raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size) - bound = values.dup - c = connection - statement.gsub(/\?/) do - replace_bind_variable(bound.shift, c) - end - end - - def replace_bind_variable(value, c = connection) - if ActiveRecord::Relation === value - value.to_sql - else - quote_bound_value(value, c) - end - end - - def replace_named_bind_variables(statement, bind_vars) - statement.gsub(/(:?):([a-zA-Z]\w*)/) do |match| - if $1 == ":" # skip postgresql casts - match # return the whole match - elsif bind_vars.include?(match = $2.to_sym) - replace_bind_variable(bind_vars[match]) - else - raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}" - end - end - end - - def quote_bound_value(value, c = connection) - if value.respond_to?(:map) && !value.acts_like?(:string) - if value.respond_to?(:empty?) && value.empty? - c.quote(nil) - else - value.map { |v| c.quote(v) }.join(",") - end - else - c.quote(value) - end - end - - def raise_if_bind_arity_mismatch(statement, expected, provided) - unless expected == provided - raise PreparedStatementInvalid, "wrong number of bind variables (#{provided} for #{expected}) in: #{statement}" - end - end - end - - def quoted_id # :nodoc: - self.class.connection.quote(@attributes[self.class.primary_key].value_for_database) - end - deprecate :quoted_id - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema.rb deleted file mode 100644 index 5104427339..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema.rb +++ /dev/null @@ -1,68 +0,0 @@ -module ActiveRecord - # = Active Record \Schema - # - # Allows programmers to programmatically define a schema in a portable - # DSL. This means you can define tables, indexes, etc. without using SQL - # directly, so your applications can more easily support multiple - # databases. - # - # Usage: - # - # ActiveRecord::Schema.define do - # create_table :authors do |t| - # t.string :name, null: false - # end - # - # add_index :authors, :name, :unique - # - # create_table :posts do |t| - # t.integer :author_id, null: false - # t.string :subject - # t.text :body - # t.boolean :private, default: false - # end - # - # add_index :posts, :author_id - # end - # - # ActiveRecord::Schema is only supported by database adapters that also - # support migrations, the two features being very similar. - class Schema < Migration::Current - # Eval the given block. All methods available to the current connection - # adapter are available within the block, so you can easily use the - # database definition DSL to build up your schema ( - # {create_table}[rdoc-ref:ConnectionAdapters::SchemaStatements#create_table], - # {add_index}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_index], etc.). - # - # The +info+ hash is optional, and if given is used to define metadata - # about the current schema (currently, only the schema's version): - # - # ActiveRecord::Schema.define(version: 20380119000001) do - # ... - # end - def self.define(info = {}, &block) - new.define(info, &block) - end - - def define(info, &block) # :nodoc: - instance_eval(&block) - - if info[:version].present? - ActiveRecord::SchemaMigration.create_table - connection.assume_migrated_upto_version(info[:version], migrations_paths) - end - - ActiveRecord::InternalMetadata.create_table - ActiveRecord::InternalMetadata[:environment] = ActiveRecord::Migrator.current_environment - end - - private - # Returns the migrations paths. - # - # ActiveRecord::Schema.new.migrations_paths - # # => ["db/migrate"] # Rails migration path by default. - def migrations_paths - ActiveRecord::Migrator.migrations_paths - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema_dumper.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema_dumper.rb deleted file mode 100644 index 2bbfd01698..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema_dumper.rb +++ /dev/null @@ -1,245 +0,0 @@ -require "stringio" - -module ActiveRecord - # = Active Record Schema Dumper - # - # This class is used to dump the database schema for some connection to some - # output format (i.e., ActiveRecord::Schema). - class SchemaDumper #:nodoc: - private_class_method :new - - ## - # :singleton-method: - # A list of tables which should not be dumped to the schema. - # Acceptable values are strings as well as regexp. - # This setting is only used if ActiveRecord::Base.schema_format == :ruby - cattr_accessor :ignore_tables - @@ignore_tables = [] - - class << self - def dump(connection = ActiveRecord::Base.connection, stream = STDOUT, config = ActiveRecord::Base) - new(connection, generate_options(config)).dump(stream) - stream - end - - private - def generate_options(config) - { - table_name_prefix: config.table_name_prefix, - table_name_suffix: config.table_name_suffix - } - end - end - - def dump(stream) - header(stream) - extensions(stream) - tables(stream) - trailer(stream) - stream - end - - private - - def initialize(connection, options = {}) - @connection = connection - @version = Migrator::current_version rescue nil - @options = options - end - - def header(stream) - define_params = @version ? "version: #{@version}" : "" - - stream.puts <
    e - stream.puts "# Could not dump table #{table.inspect} because of following #{e.class}" - stream.puts "# #{e.message}" - stream.puts - end - - stream - end - - # Keep it for indexing materialized views - def indexes(table, stream) - if (indexes = @connection.indexes(table)).any? - add_index_statements = indexes.map do |index| - table_name = remove_prefix_and_suffix(index.table).inspect - " add_index #{([table_name] + index_parts(index)).join(', ')}" - end - - stream.puts add_index_statements.sort.join("\n") - stream.puts - end - end - - def indexes_in_create(table, stream) - if (indexes = @connection.indexes(table)).any? - index_statements = indexes.map do |index| - " t.index #{index_parts(index).join(', ')}" - end - stream.puts index_statements.sort.join("\n") - end - end - - def index_parts(index) - index_parts = [ - index.columns.inspect, - "name: #{index.name.inspect}", - ] - index_parts << "unique: true" if index.unique - index_parts << "length: { #{format_options(index.lengths)} }" if index.lengths.present? - index_parts << "order: { #{format_options(index.orders)} }" if index.orders.present? - index_parts << "where: #{index.where.inspect}" if index.where - index_parts << "using: #{index.using.inspect}" if !@connection.default_index_type?(index) - index_parts << "type: #{index.type.inspect}" if index.type - index_parts << "comment: #{index.comment.inspect}" if index.comment - index_parts - end - - def foreign_keys(table, stream) - if (foreign_keys = @connection.foreign_keys(table)).any? - add_foreign_key_statements = foreign_keys.map do |foreign_key| - parts = [ - "add_foreign_key #{remove_prefix_and_suffix(foreign_key.from_table).inspect}", - remove_prefix_and_suffix(foreign_key.to_table).inspect, - ] - - if foreign_key.column != @connection.foreign_key_column_for(foreign_key.to_table) - parts << "column: #{foreign_key.column.inspect}" - end - - if foreign_key.custom_primary_key? - parts << "primary_key: #{foreign_key.primary_key.inspect}" - end - - if foreign_key.name !~ /^fk_rails_[0-9a-f]{10}$/ - parts << "name: #{foreign_key.name.inspect}" - end - - parts << "on_update: #{foreign_key.on_update.inspect}" if foreign_key.on_update - parts << "on_delete: #{foreign_key.on_delete.inspect}" if foreign_key.on_delete - - " #{parts.join(', ')}" - end - - stream.puts add_foreign_key_statements.sort.join("\n") - end - end - - def format_colspec(colspec) - colspec.map { |key, value| "#{key}: #{value}" }.join(", ") - end - - def format_options(options) - options.map { |key, value| "#{key}: #{value.inspect}" }.join(", ") - end - - def remove_prefix_and_suffix(table) - table.gsub(/^(#{@options[:table_name_prefix]})(.+)(#{@options[:table_name_suffix]})$/, "\\2") - end - - def ignored?(table_name) - [ActiveRecord::Base.schema_migrations_table_name, ActiveRecord::Base.internal_metadata_table_name, ignore_tables].flatten.any? do |ignored| - ignored === remove_prefix_and_suffix(table_name) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema_migration.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema_migration.rb deleted file mode 100644 index f59737afb0..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/schema_migration.rb +++ /dev/null @@ -1,54 +0,0 @@ -require "active_record/scoping/default" -require "active_record/scoping/named" - -module ActiveRecord - # This class is used to create a table that keeps track of which migrations - # have been applied to a given database. When a migration is run, its schema - # number is inserted in to the `SchemaMigration.table_name` so it doesn't need - # to be executed the next time. - class SchemaMigration < ActiveRecord::Base # :nodoc: - class << self - def primary_key - "version" - end - - def table_name - "#{table_name_prefix}#{ActiveRecord::Base.schema_migrations_table_name}#{table_name_suffix}" - end - - def table_exists? - connection.table_exists?(table_name) - end - - def create_table - unless table_exists? - version_options = connection.internal_string_options_for_primary_key - - connection.create_table(table_name, id: false) do |t| - t.string :version, version_options - end - end - end - - def drop_table - connection.drop_table table_name, if_exists: true - end - - def normalize_migration_number(number) - "%.3d" % number.to_i - end - - def normalized_versions - all_versions.map { |v| normalize_migration_number v } - end - - def all_versions - order(:version).pluck(:version) - end - end - - def version - super.to_i - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping.rb deleted file mode 100644 index 94e0ef6724..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping.rb +++ /dev/null @@ -1,105 +0,0 @@ -require "active_support/per_thread_registry" - -module ActiveRecord - module Scoping - extend ActiveSupport::Concern - - included do - include Default - include Named - end - - module ClassMethods - def current_scope(skip_inherited_scope = false) # :nodoc: - ScopeRegistry.value_for(:current_scope, self, skip_inherited_scope) - end - - def current_scope=(scope) #:nodoc: - ScopeRegistry.set_value_for(:current_scope, self, scope) - end - - # Collects attributes from scopes that should be applied when creating - # an AR instance for the particular class this is called on. - def scope_attributes # :nodoc: - all.scope_for_create - end - - # Are there attributes associated with this scope? - def scope_attributes? # :nodoc: - current_scope - end - end - - def populate_with_current_scope_attributes # :nodoc: - return unless self.class.scope_attributes? - - self.class.scope_attributes.each do |att, value| - send("#{att}=", value) if respond_to?("#{att}=") - end - end - - def initialize_internals_callback # :nodoc: - super - populate_with_current_scope_attributes - end - - # This class stores the +:current_scope+ and +:ignore_default_scope+ values - # for different classes. The registry is stored as a thread local, which is - # accessed through +ScopeRegistry.current+. - # - # This class allows you to store and get the scope values on different - # classes and different types of scopes. For example, if you are attempting - # to get the current_scope for the +Board+ model, then you would use the - # following code: - # - # registry = ActiveRecord::Scoping::ScopeRegistry - # registry.set_value_for(:current_scope, Board, some_new_scope) - # - # Now when you run: - # - # registry.value_for(:current_scope, Board) - # - # You will obtain whatever was defined in +some_new_scope+. The #value_for - # and #set_value_for methods are delegated to the current ScopeRegistry - # object, so the above example code can also be called as: - # - # ActiveRecord::Scoping::ScopeRegistry.set_value_for(:current_scope, - # Board, some_new_scope) - class ScopeRegistry # :nodoc: - extend ActiveSupport::PerThreadRegistry - - VALID_SCOPE_TYPES = [:current_scope, :ignore_default_scope] - - def initialize - @registry = Hash.new { |hash, key| hash[key] = {} } - end - - # Obtains the value for a given +scope_type+ and +model+. - def value_for(scope_type, model, skip_inherited_scope = false) - raise_invalid_scope_type!(scope_type) - return @registry[scope_type][model.name] if skip_inherited_scope - klass = model - base = model.base_class - while klass <= base - value = @registry[scope_type][klass.name] - return value if value - klass = klass.superclass - end - end - - # Sets the +value+ for a given +scope_type+ and +model+. - def set_value_for(scope_type, model, value) - raise_invalid_scope_type!(scope_type) - @registry[scope_type][model.name] = value - end - - private - - def raise_invalid_scope_type!(scope_type) - if !VALID_SCOPE_TYPES.include?(scope_type) - raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES" - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping/default.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping/default.rb deleted file mode 100644 index d561718b65..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping/default.rb +++ /dev/null @@ -1,153 +0,0 @@ -module ActiveRecord - module Scoping - module Default - extend ActiveSupport::Concern - - included do - # Stores the default scope for the class. - class_attribute :default_scopes, instance_writer: false, instance_predicate: false - class_attribute :default_scope_override, instance_writer: false, instance_predicate: false - - self.default_scopes = [] - self.default_scope_override = nil - end - - module ClassMethods - # Returns a scope for the model without the previously set scopes. - # - # class Post < ActiveRecord::Base - # def self.default_scope - # where(published: true) - # end - # end - # - # Post.all # Fires "SELECT * FROM posts WHERE published = true" - # Post.unscoped.all # Fires "SELECT * FROM posts" - # Post.where(published: false).unscoped.all # Fires "SELECT * FROM posts" - # - # This method also accepts a block. All queries inside the block will - # not use the previously set scopes. - # - # Post.unscoped { - # Post.limit(10) # Fires "SELECT * FROM posts LIMIT 10" - # } - def unscoped - block_given? ? relation.scoping { yield } : relation - end - - # Are there attributes associated with this scope? - def scope_attributes? # :nodoc: - super || default_scopes.any? || respond_to?(:default_scope) - end - - def before_remove_const #:nodoc: - self.current_scope = nil - end - - private - - # Use this macro in your model to set a default scope for all operations on - # the model. - # - # class Article < ActiveRecord::Base - # default_scope { where(published: true) } - # end - # - # Article.all # => SELECT * FROM articles WHERE published = true - # - # The #default_scope is also applied while creating/building a record. - # It is not applied while updating a record. - # - # Article.new.published # => true - # Article.create.published # => true - # - # (You can also pass any object which responds to +call+ to the - # +default_scope+ macro, and it will be called when building the - # default scope.) - # - # If you use multiple #default_scope declarations in your model then - # they will be merged together: - # - # class Article < ActiveRecord::Base - # default_scope { where(published: true) } - # default_scope { where(rating: 'G') } - # end - # - # Article.all # => SELECT * FROM articles WHERE published = true AND rating = 'G' - # - # This is also the case with inheritance and module includes where the - # parent or module defines a #default_scope and the child or including - # class defines a second one. - # - # If you need to do more complex things with a default scope, you can - # alternatively define it as a class method: - # - # class Article < ActiveRecord::Base - # def self.default_scope - # # Should return a scope, you can call 'super' here etc. - # end - # end - def default_scope(scope = nil) # :doc: - scope = Proc.new if block_given? - - if scope.is_a?(Relation) || !scope.respond_to?(:call) - raise ArgumentError, - "Support for calling #default_scope without a block is removed. For example instead " \ - "of `default_scope where(color: 'red')`, please use " \ - "`default_scope { where(color: 'red') }`. (Alternatively you can just redefine " \ - "self.default_scope.)" - end - - self.default_scopes += [scope] - end - - def build_default_scope(base_rel = nil) - return if abstract_class? - - if default_scope_override.nil? - self.default_scope_override = !Base.is_a?(method(:default_scope).owner) - end - - if default_scope_override - # The user has defined their own default scope method, so call that - evaluate_default_scope do - if scope = default_scope - (base_rel ||= relation).merge(scope) - end - end - elsif default_scopes.any? - base_rel ||= relation - evaluate_default_scope do - default_scopes.inject(base_rel) do |default_scope, scope| - scope = scope.respond_to?(:to_proc) ? scope : scope.method(:call) - default_scope.merge(base_rel.instance_exec(&scope)) - end - end - end - end - - def ignore_default_scope? - ScopeRegistry.value_for(:ignore_default_scope, base_class) - end - - def ignore_default_scope=(ignore) - ScopeRegistry.set_value_for(:ignore_default_scope, base_class, ignore) - end - - # The ignore_default_scope flag is used to prevent an infinite recursion - # situation where a default scope references a scope which has a default - # scope which references a scope... - def evaluate_default_scope - return if ignore_default_scope? - - begin - self.ignore_default_scope = true - yield - ensure - self.ignore_default_scope = false - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping/named.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping/named.rb deleted file mode 100644 index bf9b5c990c..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/scoping/named.rb +++ /dev/null @@ -1,197 +0,0 @@ -require "active_support/core_ext/array" -require "active_support/core_ext/hash/except" -require "active_support/core_ext/kernel/singleton_class" - -module ActiveRecord - # = Active Record \Named \Scopes - module Scoping - module Named - extend ActiveSupport::Concern - - module ClassMethods - # Returns an ActiveRecord::Relation scope object. - # - # posts = Post.all - # posts.size # Fires "select count(*) from posts" and returns the count - # posts.each {|p| puts p.name } # Fires "select * from posts" and loads post objects - # - # fruits = Fruit.all - # fruits = fruits.where(color: 'red') if options[:red_only] - # fruits = fruits.limit(10) if limited? - # - # You can define a scope that applies to all finders using - # {default_scope}[rdoc-ref:Scoping::Default::ClassMethods#default_scope]. - def all - if current_scope - current_scope.clone - else - default_scoped - end - end - - def scope_for_association(scope = relation) # :nodoc: - current_scope = self.current_scope - - if current_scope && current_scope.empty_scope? - scope - else - default_scoped(scope) - end - end - - def default_scoped(scope = relation) # :nodoc: - build_default_scope(scope) || scope - end - - def default_extensions # :nodoc: - if scope = current_scope || build_default_scope - scope.extensions - else - [] - end - end - - # Adds a class method for retrieving and querying objects. - # The method is intended to return an ActiveRecord::Relation - # object, which is composable with other scopes. - # If it returns +nil+ or +false+, an - # {all}[rdoc-ref:Scoping::Named::ClassMethods#all] scope is returned instead. - # - # A \scope represents a narrowing of a database query, such as - # where(color: :red).select('shirts.*').includes(:washing_instructions). - # - # class Shirt < ActiveRecord::Base - # scope :red, -> { where(color: 'red') } - # scope :dry_clean_only, -> { joins(:washing_instructions).where('washing_instructions.dry_clean_only = ?', true) } - # end - # - # The above calls to #scope define class methods Shirt.red and - # Shirt.dry_clean_only. Shirt.red, in effect, - # represents the query Shirt.where(color: 'red'). - # - # You should always pass a callable object to the scopes defined - # with #scope. This ensures that the scope is re-evaluated each - # time it is called. - # - # Note that this is simply 'syntactic sugar' for defining an actual - # class method: - # - # class Shirt < ActiveRecord::Base - # def self.red - # where(color: 'red') - # end - # end - # - # Unlike Shirt.find(...), however, the object returned by - # Shirt.red is not an Array but an ActiveRecord::Relation, - # which is composable with other scopes; it resembles the association object - # constructed by a {has_many}[rdoc-ref:Associations::ClassMethods#has_many] - # declaration. For instance, you can invoke Shirt.red.first, Shirt.red.count, - # Shirt.red.where(size: 'small'). Also, just as with the - # association objects, named \scopes act like an Array, implementing - # Enumerable; Shirt.red.each(&block), Shirt.red.first, - # and Shirt.red.inject(memo, &block) all behave as if - # Shirt.red really was an array. - # - # These named \scopes are composable. For instance, - # Shirt.red.dry_clean_only will produce all shirts that are - # both red and dry clean only. Nested finds and calculations also work - # with these compositions: Shirt.red.dry_clean_only.count - # returns the number of garments for which these criteria obtain. - # Similarly with Shirt.red.dry_clean_only.average(:thread_count). - # - # All scopes are available as class methods on the ActiveRecord::Base - # descendant upon which the \scopes were defined. But they are also - # available to {has_many}[rdoc-ref:Associations::ClassMethods#has_many] - # associations. If, - # - # class Person < ActiveRecord::Base - # has_many :shirts - # end - # - # then elton.shirts.red.dry_clean_only will return all of - # Elton's red, dry clean only shirts. - # - # \Named scopes can also have extensions, just as with - # {has_many}[rdoc-ref:Associations::ClassMethods#has_many] declarations: - # - # class Shirt < ActiveRecord::Base - # scope :red, -> { where(color: 'red') } do - # def dom_id - # 'red_shirts' - # end - # end - # end - # - # Scopes can also be used while creating/building a record. - # - # class Article < ActiveRecord::Base - # scope :published, -> { where(published: true) } - # end - # - # Article.published.new.published # => true - # Article.published.create.published # => true - # - # \Class methods on your model are automatically available - # on scopes. Assuming the following setup: - # - # class Article < ActiveRecord::Base - # scope :published, -> { where(published: true) } - # scope :featured, -> { where(featured: true) } - # - # def self.latest_article - # order('published_at desc').first - # end - # - # def self.titles - # pluck(:title) - # end - # end - # - # We are able to call the methods like this: - # - # Article.published.featured.latest_article - # Article.featured.titles - def scope(name, body, &block) - unless body.respond_to?(:call) - raise ArgumentError, "The scope body needs to be callable." - end - - if dangerous_class_method?(name) - raise ArgumentError, "You tried to define a scope named \"#{name}\" " \ - "on the model \"#{self.name}\", but Active Record already defined " \ - "a class method with the same name." - end - - valid_scope_name?(name) - extension = Module.new(&block) if block - - if body.respond_to?(:to_proc) - singleton_class.send(:define_method, name) do |*args| - scope = all.scoping { instance_exec(*args, &body) } - scope = scope.extending(extension) if extension - - scope || all - end - else - singleton_class.send(:define_method, name) do |*args| - scope = all.scoping { body.call(*args) } - scope = scope.extending(extension) if extension - - scope || all - end - end - end - - private - - def valid_scope_name?(name) - if respond_to?(name, true) && logger - logger.warn "Creating scope :#{name}. " \ - "Overwriting existing method #{self.name}.#{name}." - end - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/secure_token.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/secure_token.rb deleted file mode 100644 index 115799cc20..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/secure_token.rb +++ /dev/null @@ -1,38 +0,0 @@ -module ActiveRecord - module SecureToken - extend ActiveSupport::Concern - - module ClassMethods - # Example using #has_secure_token - # - # # Schema: User(token:string, auth_token:string) - # class User < ActiveRecord::Base - # has_secure_token - # has_secure_token :auth_token - # end - # - # user = User.new - # user.save - # user.token # => "pX27zsMN2ViQKta1bGfLmVJE" - # user.auth_token # => "77TMHrHJFvFDwodq8w7Ev2m7" - # user.regenerate_token # => true - # user.regenerate_auth_token # => true - # - # SecureRandom::base58 is used to generate the 24-character unique token, so collisions are highly unlikely. - # - # Note that it's still possible to generate a race condition in the database in the same way that - # {validates_uniqueness_of}[rdoc-ref:Validations::ClassMethods#validates_uniqueness_of] can. - # You're encouraged to add a unique index in the database to deal with this even more unlikely scenario. - def has_secure_token(attribute = :token) - # Load securerandom only when has_secure_token is used. - require "active_support/core_ext/securerandom" - define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token } - before_create { send("#{attribute}=", self.class.generate_unique_secure_token) unless send("#{attribute}?") } - end - - def generate_unique_secure_token - SecureRandom.base58(24) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/serialization.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/serialization.rb deleted file mode 100644 index db2bd0b55e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/serialization.rb +++ /dev/null @@ -1,20 +0,0 @@ -module ActiveRecord #:nodoc: - # = Active Record \Serialization - module Serialization - extend ActiveSupport::Concern - include ActiveModel::Serializers::JSON - - included do - self.include_root_in_json = false - end - - def serializable_hash(options = nil) - options = options.try(:dup) || {} - - options[:except] = Array(options[:except]).map(&:to_s) - options[:except] |= Array(self.class.inheritance_column) - - super(options) - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/statement_cache.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/statement_cache.rb deleted file mode 100644 index 1877489e55..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/statement_cache.rb +++ /dev/null @@ -1,111 +0,0 @@ -module ActiveRecord - # Statement cache is used to cache a single statement in order to avoid creating the AST again. - # Initializing the cache is done by passing the statement in the create block: - # - # cache = StatementCache.create(Book.connection) do |params| - # Book.where(name: "my book").where("author_id > 3") - # end - # - # The cached statement is executed by using the - # {connection.execute}[rdoc-ref:ConnectionAdapters::DatabaseStatements#execute] method: - # - # cache.execute([], Book, Book.connection) - # - # The relation returned by the block is cached, and for each - # {execute}[rdoc-ref:ConnectionAdapters::DatabaseStatements#execute] - # call the cached relation gets duped. Database is queried when +to_a+ is called on the relation. - # - # If you want to cache the statement without the values you can use the +bind+ method of the - # block parameter. - # - # cache = StatementCache.create(Book.connection) do |params| - # Book.where(name: params.bind) - # end - # - # And pass the bind values as the first argument of +execute+ call. - # - # cache.execute(["my book"], Book, Book.connection) - class StatementCache # :nodoc: - class Substitute; end # :nodoc: - - class Query # :nodoc: - def initialize(sql) - @sql = sql - end - - def sql_for(binds, connection) - @sql - end - end - - class PartialQuery < Query # :nodoc: - def initialize(values) - @values = values - @indexes = values.each_with_index.find_all { |thing, i| - Arel::Nodes::BindParam === thing - }.map(&:last) - end - - def sql_for(binds, connection) - val = @values.dup - casted_binds = binds.map(&:value_for_database) - @indexes.each { |i| val[i] = connection.quote(casted_binds.shift) } - val.join - end - end - - def self.query(sql) - Query.new(sql) - end - - def self.partial_query(values) - PartialQuery.new(values) - end - - class Params # :nodoc: - def bind; Substitute.new; end - end - - class BindMap # :nodoc: - def initialize(bound_attributes) - @indexes = [] - @bound_attributes = bound_attributes - - bound_attributes.each_with_index do |attr, i| - if Substitute === attr.value - @indexes << i - end - end - end - - def bind(values) - bas = @bound_attributes.dup - @indexes.each_with_index { |offset, i| bas[offset] = bas[offset].with_cast_value(values[i]) } - bas - end - end - - attr_reader :bind_map, :query_builder - - def self.create(connection, block = Proc.new) - relation = block.call Params.new - bind_map = BindMap.new relation.bound_attributes - query_builder = connection.cacheable_query(self, relation.arel) - new query_builder, bind_map - end - - def initialize(query_builder, bind_map) - @query_builder = query_builder - @bind_map = bind_map - end - - def execute(params, klass, connection, &block) - bind_values = bind_map.bind params - - sql = query_builder.sql_for bind_values, connection - - klass.find_by_sql(sql, bind_values, preparable: true, &block) - end - alias :call :execute - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/store.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/store.rb deleted file mode 100644 index 006afe7495..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/store.rb +++ /dev/null @@ -1,209 +0,0 @@ -require "active_support/core_ext/hash/indifferent_access" - -module ActiveRecord - # Store gives you a thin wrapper around serialize for the purpose of storing hashes in a single column. - # It's like a simple key/value store baked into your record when you don't care about being able to - # query that store outside the context of a single record. - # - # You can then declare accessors to this store that are then accessible just like any other attribute - # of the model. This is very helpful for easily exposing store keys to a form or elsewhere that's - # already built around just accessing attributes on the model. - # - # Make sure that you declare the database column used for the serialized store as a text, so there's - # plenty of room. - # - # You can set custom coder to encode/decode your serialized attributes to/from different formats. - # JSON, YAML, Marshal are supported out of the box. Generally it can be any wrapper that provides +load+ and +dump+. - # - # NOTE: If you are using PostgreSQL specific columns like +hstore+ or +json+ there is no need for - # the serialization provided by {.store}[rdoc-ref:rdoc-ref:ClassMethods#store]. - # Simply use {.store_accessor}[rdoc-ref:ClassMethods#store_accessor] instead to generate - # the accessor methods. Be aware that these columns use a string keyed hash and do not allow access - # using a symbol. - # - # NOTE: The default validations with the exception of +uniqueness+ will work. - # For example, if you want to check for +uniqueness+ with +hstore+ you will - # need to use a custom validation to handle it. - # - # Examples: - # - # class User < ActiveRecord::Base - # store :settings, accessors: [ :color, :homepage ], coder: JSON - # end - # - # u = User.new(color: 'black', homepage: '37signals.com') - # u.color # Accessor stored attribute - # u.settings[:country] = 'Denmark' # Any attribute, even if not specified with an accessor - # - # # There is no difference between strings and symbols for accessing custom attributes - # u.settings[:country] # => 'Denmark' - # u.settings['country'] # => 'Denmark' - # - # # Add additional accessors to an existing store through store_accessor - # class SuperUser < User - # store_accessor :settings, :privileges, :servants - # end - # - # The stored attribute names can be retrieved using {.stored_attributes}[rdoc-ref:rdoc-ref:ClassMethods#stored_attributes]. - # - # User.stored_attributes[:settings] # [:color, :homepage] - # - # == Overwriting default accessors - # - # All stored values are automatically available through accessors on the Active Record - # object, but sometimes you want to specialize this behavior. This can be done by overwriting - # the default accessors (using the same name as the attribute) and calling super - # to actually change things. - # - # class Song < ActiveRecord::Base - # # Uses a stored integer to hold the volume adjustment of the song - # store :settings, accessors: [:volume_adjustment] - # - # def volume_adjustment=(decibels) - # super(decibels.to_i) - # end - # - # def volume_adjustment - # super.to_i - # end - # end - module Store - extend ActiveSupport::Concern - - included do - class << self - attr_accessor :local_stored_attributes - end - end - - module ClassMethods - def store(store_attribute, options = {}) - serialize store_attribute, IndifferentCoder.new(store_attribute, options[:coder]) - store_accessor(store_attribute, options[:accessors]) if options.has_key? :accessors - end - - def store_accessor(store_attribute, *keys) - keys = keys.flatten - - _store_accessors_module.module_eval do - keys.each do |key| - define_method("#{key}=") do |value| - write_store_attribute(store_attribute, key, value) - end - - define_method(key) do - read_store_attribute(store_attribute, key) - end - end - end - - # assign new store attribute and create new hash to ensure that each class in the hierarchy - # has its own hash of stored attributes. - self.local_stored_attributes ||= {} - self.local_stored_attributes[store_attribute] ||= [] - self.local_stored_attributes[store_attribute] |= keys - end - - def _store_accessors_module # :nodoc: - @_store_accessors_module ||= begin - mod = Module.new - include mod - mod - end - end - - def stored_attributes - parent = superclass.respond_to?(:stored_attributes) ? superclass.stored_attributes : {} - if local_stored_attributes - parent.merge!(local_stored_attributes) { |k, a, b| a | b } - end - parent - end - end - - private - def read_store_attribute(store_attribute, key) # :doc: - accessor = store_accessor_for(store_attribute) - accessor.read(self, store_attribute, key) - end - - def write_store_attribute(store_attribute, key, value) # :doc: - accessor = store_accessor_for(store_attribute) - accessor.write(self, store_attribute, key, value) - end - - def store_accessor_for(store_attribute) - type_for_attribute(store_attribute.to_s).accessor - end - - class HashAccessor # :nodoc: - def self.read(object, attribute, key) - prepare(object, attribute) - object.public_send(attribute)[key] - end - - def self.write(object, attribute, key, value) - prepare(object, attribute) - if value != read(object, attribute, key) - object.public_send :"#{attribute}_will_change!" - object.public_send(attribute)[key] = value - end - end - - def self.prepare(object, attribute) - object.public_send :"#{attribute}=", {} unless object.send(attribute) - end - end - - class StringKeyedHashAccessor < HashAccessor # :nodoc: - def self.read(object, attribute, key) - super object, attribute, key.to_s - end - - def self.write(object, attribute, key, value) - super object, attribute, key.to_s, value - end - end - - class IndifferentHashAccessor < ActiveRecord::Store::HashAccessor # :nodoc: - def self.prepare(object, store_attribute) - attribute = object.send(store_attribute) - unless attribute.is_a?(ActiveSupport::HashWithIndifferentAccess) - attribute = IndifferentCoder.as_indifferent_hash(attribute) - object.send :"#{store_attribute}=", attribute - end - attribute - end - end - - class IndifferentCoder # :nodoc: - def initialize(attr_name, coder_or_class_name) - @coder = - if coder_or_class_name.respond_to?(:load) && coder_or_class_name.respond_to?(:dump) - coder_or_class_name - else - ActiveRecord::Coders::YAMLColumn.new(attr_name, coder_or_class_name || Object) - end - end - - def dump(obj) - @coder.dump self.class.as_indifferent_hash(obj) - end - - def load(yaml) - self.class.as_indifferent_hash(@coder.load(yaml || "")) - end - - def self.as_indifferent_hash(obj) - case obj - when ActiveSupport::HashWithIndifferentAccess - obj - when Hash - obj.with_indifferent_access - else - ActiveSupport::HashWithIndifferentAccess.new - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/suppressor.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/suppressor.rb deleted file mode 100644 index d9acb1a1dc..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/suppressor.rb +++ /dev/null @@ -1,59 +0,0 @@ -module ActiveRecord - # ActiveRecord::Suppressor prevents the receiver from being saved during - # a given block. - # - # For example, here's a pattern of creating notifications when new comments - # are posted. (The notification may in turn trigger an email, a push - # notification, or just appear in the UI somewhere): - # - # class Comment < ActiveRecord::Base - # belongs_to :commentable, polymorphic: true - # after_create -> { Notification.create! comment: self, - # recipients: commentable.recipients } - # end - # - # That's what you want the bulk of the time. New comment creates a new - # Notification. But there may well be off cases, like copying a commentable - # and its comments, where you don't want that. So you'd have a concern - # something like this: - # - # module Copyable - # def copy_to(destination) - # Notification.suppress do - # # Copy logic that creates new comments that we do not want - # # triggering notifications. - # end - # end - # end - module Suppressor - extend ActiveSupport::Concern - - module ClassMethods - def suppress(&block) - previous_state = SuppressorRegistry.suppressed[name] - SuppressorRegistry.suppressed[name] = true - yield - ensure - SuppressorRegistry.suppressed[name] = previous_state - end - end - - def save(*) # :nodoc: - SuppressorRegistry.suppressed[self.class.name] ? true : super - end - - def save!(*) # :nodoc: - SuppressorRegistry.suppressed[self.class.name] ? true : super - end - end - - class SuppressorRegistry # :nodoc: - extend ActiveSupport::PerThreadRegistry - - attr_reader :suppressed - - def initialize - @suppressed = {} - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/table_metadata.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/table_metadata.rb deleted file mode 100644 index 71efc1829a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/table_metadata.rb +++ /dev/null @@ -1,73 +0,0 @@ -module ActiveRecord - class TableMetadata # :nodoc: - delegate :foreign_type, :foreign_key, to: :association, prefix: true - delegate :association_primary_key, to: :association - - def initialize(klass, arel_table, association = nil) - @klass = klass - @arel_table = arel_table - @association = association - end - - def resolve_column_aliases(hash) - new_hash = hash.dup - hash.each do |key, _| - if (key.is_a?(Symbol)) && klass.attribute_alias?(key) - new_hash[klass.attribute_alias(key)] = new_hash.delete(key) - end - end - new_hash - end - - def arel_attribute(column_name) - if klass - klass.arel_attribute(column_name, arel_table) - else - arel_table[column_name] - end - end - - def type(column_name) - if klass - klass.type_for_attribute(column_name.to_s) - else - Type.default_value - end - end - - def has_column?(column_name) - klass && klass.columns_hash.key?(column_name.to_s) - end - - def associated_with?(association_name) - klass && klass._reflect_on_association(association_name) - end - - def associated_table(table_name) - association = klass._reflect_on_association(table_name) || klass._reflect_on_association(table_name.to_s.singularize) - - if !association && table_name == arel_table.name - return self - elsif association && !association.polymorphic? - association_klass = association.klass - arel_table = association_klass.arel_table.alias(table_name) - else - type_caster = TypeCaster::Connection.new(klass, table_name) - association_klass = nil - arel_table = Arel::Table.new(table_name, type_caster: type_caster) - end - - TableMetadata.new(association_klass, arel_table, association) - end - - def polymorphic_association? - association && association.polymorphic? - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :klass, :arel_table, :association - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/database_tasks.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/database_tasks.rb deleted file mode 100644 index aa2efc2e06..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/database_tasks.rb +++ /dev/null @@ -1,326 +0,0 @@ -module ActiveRecord - module Tasks # :nodoc: - class DatabaseAlreadyExists < StandardError; end # :nodoc: - class DatabaseNotSupported < StandardError; end # :nodoc: - - # ActiveRecord::Tasks::DatabaseTasks is a utility class, which encapsulates - # logic behind common tasks used to manage database and migrations. - # - # The tasks defined here are used with Rake tasks provided by Active Record. - # - # In order to use DatabaseTasks, a few config values need to be set. All the needed - # config values are set by Rails already, so it's necessary to do it only if you - # want to change the defaults or when you want to use Active Record outside of Rails - # (in such case after configuring the database tasks, you can also use the rake tasks - # defined in Active Record). - # - # The possible config values are: - # - # * +env+: current environment (like Rails.env). - # * +database_configuration+: configuration of your databases (as in +config/database.yml+). - # * +db_dir+: your +db+ directory. - # * +fixtures_path+: a path to fixtures directory. - # * +migrations_paths+: a list of paths to directories with migrations. - # * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method. - # * +root+: a path to the root of the application. - # - # Example usage of DatabaseTasks outside Rails could look as such: - # - # include ActiveRecord::Tasks - # DatabaseTasks.database_configuration = YAML.load_file('my_database_config.yml') - # DatabaseTasks.db_dir = 'db' - # # other settings... - # - # DatabaseTasks.create_current('production') - module DatabaseTasks - ## - # :singleton-method: - # Extra flags passed to database CLI tool (mysqldump/pg_dump) when calling db:structure:dump - mattr_accessor :structure_dump_flags, instance_accessor: false - - ## - # :singleton-method: - # Extra flags passed to database CLI tool when calling db:structure:load - mattr_accessor :structure_load_flags, instance_accessor: false - - extend self - - attr_writer :current_config, :db_dir, :migrations_paths, :fixtures_path, :root, :env, :seed_loader - attr_accessor :database_configuration - - LOCAL_HOSTS = ["127.0.0.1", "localhost"] - - def check_protected_environments! - unless ENV["DISABLE_DATABASE_ENVIRONMENT_CHECK"] - current = ActiveRecord::Migrator.current_environment - stored = ActiveRecord::Migrator.last_stored_environment - - if ActiveRecord::Migrator.protected_environment? - raise ActiveRecord::ProtectedEnvironmentError.new(stored) - end - - if stored && stored != current - raise ActiveRecord::EnvironmentMismatchError.new(current: current, stored: stored) - end - end - rescue ActiveRecord::NoDatabaseError - end - - def register_task(pattern, task) - @tasks ||= {} - @tasks[pattern] = task - end - - register_task(/mysql/, ActiveRecord::Tasks::MySQLDatabaseTasks) - register_task(/postgresql/, ActiveRecord::Tasks::PostgreSQLDatabaseTasks) - register_task(/sqlite/, ActiveRecord::Tasks::SQLiteDatabaseTasks) - - def db_dir - @db_dir ||= Rails.application.config.paths["db"].first - end - - def migrations_paths - @migrations_paths ||= Rails.application.paths["db/migrate"].to_a - end - - def fixtures_path - @fixtures_path ||= if ENV["FIXTURES_PATH"] - File.join(root, ENV["FIXTURES_PATH"]) - else - File.join(root, "test", "fixtures") - end - end - - def root - @root ||= Rails.root - end - - def env - @env ||= Rails.env - end - - def seed_loader - @seed_loader ||= Rails.application - end - - def current_config(options = {}) - options.reverse_merge! env: env - if options.has_key?(:config) - @current_config = options[:config] - else - @current_config ||= ActiveRecord::Base.configurations[options[:env]] - end - end - - def create(*arguments) - configuration = arguments.first - class_for_adapter(configuration["adapter"]).new(*arguments).create - $stdout.puts "Created database '#{configuration['database']}'" - rescue DatabaseAlreadyExists - $stderr.puts "Database '#{configuration['database']}' already exists" - rescue Exception => error - $stderr.puts error - $stderr.puts "Couldn't create '#{configuration['database']}' database. Please check your configuration." - raise - end - - def create_all - old_pool = ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base.connection_specification_name) - each_local_configuration { |configuration| create configuration } - if old_pool - ActiveRecord::Base.connection_handler.establish_connection(old_pool.spec.to_hash) - end - end - - def create_current(environment = env) - each_current_configuration(environment) { |configuration| - create configuration - } - ActiveRecord::Base.establish_connection(environment.to_sym) - end - - def drop(*arguments) - configuration = arguments.first - class_for_adapter(configuration["adapter"]).new(*arguments).drop - $stdout.puts "Dropped database '#{configuration['database']}'" - rescue ActiveRecord::NoDatabaseError - $stderr.puts "Database '#{configuration['database']}' does not exist" - rescue Exception => error - $stderr.puts error - $stderr.puts "Couldn't drop database '#{configuration['database']}'" - raise - end - - def drop_all - each_local_configuration { |configuration| drop configuration } - end - - def drop_current(environment = env) - each_current_configuration(environment) { |configuration| - drop configuration - } - end - - def migrate - raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty? - - verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true - version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil - scope = ENV["SCOPE"] - verbose_was, Migration.verbose = Migration.verbose, verbose - Migrator.migrate(migrations_paths, version) do |migration| - scope.blank? || scope == migration.scope - end - ActiveRecord::Base.clear_cache! - ensure - Migration.verbose = verbose_was - end - - def charset_current(environment = env) - charset ActiveRecord::Base.configurations[environment] - end - - def charset(*arguments) - configuration = arguments.first - class_for_adapter(configuration["adapter"]).new(*arguments).charset - end - - def collation_current(environment = env) - collation ActiveRecord::Base.configurations[environment] - end - - def collation(*arguments) - configuration = arguments.first - class_for_adapter(configuration["adapter"]).new(*arguments).collation - end - - def purge(configuration) - class_for_adapter(configuration["adapter"]).new(configuration).purge - end - - def purge_all - each_local_configuration { |configuration| - purge configuration - } - end - - def purge_current(environment = env) - each_current_configuration(environment) { |configuration| - purge configuration - } - ActiveRecord::Base.establish_connection(environment.to_sym) - end - - def structure_dump(*arguments) - configuration = arguments.first - filename = arguments.delete_at 1 - class_for_adapter(configuration["adapter"]).new(*arguments).structure_dump(filename, structure_dump_flags) - end - - def structure_load(*arguments) - configuration = arguments.first - filename = arguments.delete_at 1 - class_for_adapter(configuration["adapter"]).new(*arguments).structure_load(filename, structure_load_flags) - end - - def load_schema(configuration, format = ActiveRecord::Base.schema_format, file = nil, environment = env) # :nodoc: - file ||= schema_file(format) - - check_schema_file(file) - ActiveRecord::Base.establish_connection(configuration) - - case format - when :ruby - load(file) - when :sql - structure_load(configuration, file) - else - raise ArgumentError, "unknown format #{format.inspect}" - end - ActiveRecord::InternalMetadata.create_table - ActiveRecord::InternalMetadata[:environment] = environment - end - - def schema_file(format = ActiveRecord::Base.schema_format) - case format - when :ruby - File.join(db_dir, "schema.rb") - when :sql - File.join(db_dir, "structure.sql") - end - end - - def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env) - each_current_configuration(environment) { |configuration, configuration_environment| - load_schema configuration, format, file, configuration_environment - } - ActiveRecord::Base.establish_connection(environment.to_sym) - end - - def check_schema_file(filename) - unless File.exist?(filename) - message = %{#{filename} doesn't exist yet. Run `rails db:migrate` to create it, then try again.} - message << %{ If you do not intend to use a database, you should instead alter #{Rails.root}/config/application.rb to limit the frameworks that will be loaded.} if defined?(::Rails.root) - Kernel.abort message - end - end - - def load_seed - if seed_loader - seed_loader.load_seed - else - raise "You tried to load seed data, but no seed loader is specified. Please specify seed " \ - "loader with ActiveRecord::Tasks::DatabaseTasks.seed_loader = your_seed_loader\n" \ - "Seed loader should respond to load_seed method" - end - end - - # Dumps the schema cache in YAML format for the connection into the file - # - # ==== Examples: - # ActiveRecord::Tasks::DatabaseTasks.dump_schema_cache(ActiveRecord::Base.connection, "tmp/schema_dump.yaml") - def dump_schema_cache(conn, filename) - conn.schema_cache.clear! - conn.data_sources.each { |table| conn.schema_cache.add(table) } - open(filename, "wb") { |f| f.write(YAML.dump(conn.schema_cache)) } - end - - private - - def class_for_adapter(adapter) - key = @tasks.keys.detect { |pattern| adapter[pattern] } - unless key - raise DatabaseNotSupported, "Rake tasks not supported by '#{adapter}' adapter" - end - @tasks[key] - end - - def each_current_configuration(environment) - environments = [environment] - environments << "test" if environment == "development" - - ActiveRecord::Base.configurations.slice(*environments).each do |configuration_environment, configuration| - next unless configuration["database"] - - yield configuration, configuration_environment - end - end - - def each_local_configuration - ActiveRecord::Base.configurations.each_value do |configuration| - next unless configuration["database"] - - if local_database?(configuration) - yield configuration - else - $stderr.puts "This task only modifies local databases. #{configuration['database']} is on a remote host." - end - end - end - - def local_database?(configuration) - configuration["host"].blank? || LOCAL_HOSTS.include?(configuration["host"]) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/mysql_database_tasks.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/mysql_database_tasks.rb deleted file mode 100644 index 78df8c1fe1..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/mysql_database_tasks.rb +++ /dev/null @@ -1,154 +0,0 @@ -module ActiveRecord - module Tasks # :nodoc: - class MySQLDatabaseTasks # :nodoc: - ACCESS_DENIED_ERROR = 1045 - - delegate :connection, :establish_connection, to: ActiveRecord::Base - - def initialize(configuration) - @configuration = configuration - end - - def create - establish_connection configuration_without_database - connection.create_database configuration["database"], creation_options - establish_connection configuration - rescue ActiveRecord::StatementInvalid => error - if error.message.include?("database exists") - raise DatabaseAlreadyExists - else - raise - end - rescue error_class => error - if error.respond_to?(:errno) && error.errno == ACCESS_DENIED_ERROR - $stdout.print error.message - establish_connection root_configuration_without_database - connection.create_database configuration["database"], creation_options - if configuration["username"] != "root" - connection.execute grant_statement.gsub(/\s+/, " ").strip - end - establish_connection configuration - else - $stderr.puts error.inspect - $stderr.puts "Couldn't create database for #{configuration.inspect}, #{creation_options.inspect}" - $stderr.puts "(If you set the charset manually, make sure you have a matching collation)" if configuration["encoding"] - end - end - - def drop - establish_connection configuration - connection.drop_database configuration["database"] - end - - def purge - establish_connection configuration - connection.recreate_database configuration["database"], creation_options - end - - def charset - connection.charset - end - - def collation - connection.collation - end - - def structure_dump(filename, extra_flags) - args = prepare_command_options - args.concat(["--result-file", "#{filename}"]) - args.concat(["--no-data"]) - args.concat(["--routines"]) - args.concat(["--skip-comments"]) - args.concat(["#{configuration['database']}"]) - args.unshift(*extra_flags) if extra_flags - - run_cmd("mysqldump", args, "dumping") - end - - def structure_load(filename, extra_flags) - args = prepare_command_options - args.concat(["--execute", %{SET FOREIGN_KEY_CHECKS = 0; SOURCE #{filename}; SET FOREIGN_KEY_CHECKS = 1}]) - args.concat(["--database", "#{configuration['database']}"]) - args.unshift(*extra_flags) if extra_flags - - run_cmd("mysql", args, "loading") - end - - private - - def configuration - @configuration - end - - def configuration_without_database - configuration.merge("database" => nil) - end - - def creation_options - Hash.new.tap do |options| - options[:charset] = configuration["encoding"] if configuration.include? "encoding" - options[:collation] = configuration["collation"] if configuration.include? "collation" - end - end - - def error_class - if configuration["adapter"].include?("jdbc") - require "active_record/railties/jdbcmysql_error" - ArJdbcMySQL::Error - elsif defined?(Mysql2) - Mysql2::Error - else - StandardError - end - end - - def grant_statement - <<-SQL -GRANT ALL PRIVILEGES ON `#{configuration['database']}`.* - TO '#{configuration['username']}'@'localhost' -IDENTIFIED BY '#{configuration['password']}' WITH GRANT OPTION; - SQL - end - - def root_configuration_without_database - configuration_without_database.merge( - "username" => "root", - "password" => root_password - ) - end - - def root_password - $stdout.print "Please provide the root password for your MySQL installation\n>" - $stdin.gets.strip - end - - def prepare_command_options - args = { - "host" => "--host", - "port" => "--port", - "socket" => "--socket", - "username" => "--user", - "password" => "--password", - "encoding" => "--default-character-set", - "sslca" => "--ssl-ca", - "sslcert" => "--ssl-cert", - "sslcapath" => "--ssl-capath", - "sslcipher" => "--ssl-cipher", - "sslkey" => "--ssl-key" - }.map { |opt, arg| "#{arg}=#{configuration[opt]}" if configuration[opt] }.compact - - args - end - - def run_cmd(cmd, args, action) - fail run_cmd_error(cmd, args, action) unless Kernel.system(cmd, *args) - end - - def run_cmd_error(cmd, args, action) - msg = "failed to execute: `#{cmd}`\n" - msg << "Please check the output above for any errors and make sure that `#{cmd}` is installed in your PATH and has proper permissions.\n\n" - msg - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/postgresql_database_tasks.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/postgresql_database_tasks.rb deleted file mode 100644 index 355a8d82d9..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/postgresql_database_tasks.rb +++ /dev/null @@ -1,135 +0,0 @@ -require "tempfile" - -module ActiveRecord - module Tasks # :nodoc: - class PostgreSQLDatabaseTasks # :nodoc: - DEFAULT_ENCODING = ENV["CHARSET"] || "utf8" - ON_ERROR_STOP_1 = "ON_ERROR_STOP=1".freeze - SQL_COMMENT_BEGIN = "--".freeze - - delegate :connection, :establish_connection, :clear_active_connections!, - to: ActiveRecord::Base - - def initialize(configuration) - @configuration = configuration - end - - def create(master_established = false) - establish_master_connection unless master_established - connection.create_database configuration["database"], - configuration.merge("encoding" => encoding) - establish_connection configuration - rescue ActiveRecord::StatementInvalid => error - if error.cause.is_a?(PG::DuplicateDatabase) - raise DatabaseAlreadyExists - else - raise - end - end - - def drop - establish_master_connection - connection.drop_database configuration["database"] - end - - def charset - connection.encoding - end - - def collation - connection.collation - end - - def purge - clear_active_connections! - drop - create true - end - - def structure_dump(filename, extra_flags) - set_psql_env - - search_path = \ - case ActiveRecord::Base.dump_schemas - when :schema_search_path - configuration["schema_search_path"] - when :all - nil - when String - ActiveRecord::Base.dump_schemas - end - - args = ["-s", "-x", "-O", "-f", filename] - args.concat(Array(extra_flags)) if extra_flags - unless search_path.blank? - args += search_path.split(",").map do |part| - "--schema=#{part.strip}" - end - end - args << configuration["database"] - run_cmd("pg_dump", args, "dumping") - remove_sql_header_comments(filename) - File.open(filename, "a") { |f| f << "SET search_path TO #{connection.schema_search_path};\n\n" } - end - - def structure_load(filename, extra_flags) - set_psql_env - args = ["-v", ON_ERROR_STOP_1, "-q", "-f", filename] - args.concat(Array(extra_flags)) if extra_flags - args << configuration["database"] - run_cmd("psql", args, "loading") - end - - private - - def configuration - @configuration - end - - def encoding - configuration["encoding"] || DEFAULT_ENCODING - end - - def establish_master_connection - establish_connection configuration.merge( - "database" => "postgres", - "schema_search_path" => "public" - ) - end - - def set_psql_env - ENV["PGHOST"] = configuration["host"] if configuration["host"] - ENV["PGPORT"] = configuration["port"].to_s if configuration["port"] - ENV["PGPASSWORD"] = configuration["password"].to_s if configuration["password"] - ENV["PGUSER"] = configuration["username"].to_s if configuration["username"] - end - - def run_cmd(cmd, args, action) - fail run_cmd_error(cmd, args, action) unless Kernel.system(cmd, *args) - end - - def run_cmd_error(cmd, args, action) - msg = "failed to execute:\n" - msg << "#{cmd} #{args.join(' ')}\n\n" - msg << "Please check the output above for any errors and make sure that `#{cmd}` is installed in your PATH and has proper permissions.\n\n" - msg - end - - def remove_sql_header_comments(filename) - removing_comments = true - tempfile = Tempfile.open("uncommented_structure.sql") - begin - File.foreach(filename) do |line| - unless removing_comments && (line.start_with?(SQL_COMMENT_BEGIN) || line.blank?) - tempfile << line - removing_comments = false - end - end - ensure - tempfile.close - end - FileUtils.mv(tempfile.path, filename) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/sqlite_database_tasks.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/sqlite_database_tasks.rb deleted file mode 100644 index 1f756c2979..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/tasks/sqlite_database_tasks.rb +++ /dev/null @@ -1,61 +0,0 @@ -module ActiveRecord - module Tasks # :nodoc: - class SQLiteDatabaseTasks # :nodoc: - delegate :connection, :establish_connection, to: ActiveRecord::Base - - def initialize(configuration, root = ActiveRecord::Tasks::DatabaseTasks.root) - @configuration, @root = configuration, root - end - - def create - raise DatabaseAlreadyExists if File.exist?(configuration["database"]) - - establish_connection configuration - connection - end - - def drop - require "pathname" - path = Pathname.new configuration["database"] - file = path.absolute? ? path.to_s : File.join(root, path) - - FileUtils.rm(file) - rescue Errno::ENOENT => error - raise NoDatabaseError.new(error.message) - end - - def purge - drop - rescue NoDatabaseError - ensure - create - end - - def charset - connection.encoding - end - - def structure_dump(filename, extra_flags) - dbfile = configuration["database"] - flags = extra_flags.join(" ") if extra_flags - `sqlite3 #{flags} #{dbfile} .schema > #{filename}` - end - - def structure_load(filename, extra_flags) - dbfile = configuration["database"] - flags = extra_flags.join(" ") if extra_flags - `sqlite3 #{flags} #{dbfile} < "#{filename}"` - end - - private - - def configuration - @configuration - end - - def root - @root - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/timestamp.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/timestamp.rb deleted file mode 100644 index b638e8287e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/timestamp.rb +++ /dev/null @@ -1,153 +0,0 @@ -# frozen_string_literal: true -module ActiveRecord - # = Active Record \Timestamp - # - # Active Record automatically timestamps create and update operations if the - # table has fields named created_at/created_on or - # updated_at/updated_on. - # - # Timestamping can be turned off by setting: - # - # config.active_record.record_timestamps = false - # - # Timestamps are in UTC by default but you can use the local timezone by setting: - # - # config.active_record.default_timezone = :local - # - # == Time Zone aware attributes - # - # Active Record keeps all the datetime and time columns - # timezone aware. By default, these values are stored in the database as UTC - # and converted back to the current Time.zone when pulled from the database. - # - # This feature can be turned off completely by setting: - # - # config.active_record.time_zone_aware_attributes = false - # - # You can also specify that only datetime columns should be time-zone - # aware (while time should not) by setting: - # - # ActiveRecord::Base.time_zone_aware_types = [:datetime] - # - # You can also add database specific timezone aware types. For example, for PostgreSQL: - # - # ActiveRecord::Base.time_zone_aware_types += [:tsrange, :tstzrange] - # - # Finally, you can indicate specific attributes of a model for which time zone - # conversion should not applied, for instance by setting: - # - # class Topic < ActiveRecord::Base - # self.skip_time_zone_conversion_for_attributes = [:written_on] - # end - module Timestamp - extend ActiveSupport::Concern - - included do - class_attribute :record_timestamps - self.record_timestamps = true - end - - def initialize_dup(other) # :nodoc: - super - clear_timestamp_attributes - end - - class_methods do - def touch_attributes_with_time(*names, time: nil) - attribute_names = timestamp_attributes_for_update_in_model - attribute_names |= names.map(&:to_s) - time ||= current_time_from_proper_timezone - attribute_names.each_with_object({}) { |attr_name, result| result[attr_name] = time } - end - - private - def timestamp_attributes_for_create_in_model - timestamp_attributes_for_create.select { |c| column_names.include?(c) } - end - - def timestamp_attributes_for_update_in_model - timestamp_attributes_for_update.select { |c| column_names.include?(c) } - end - - def all_timestamp_attributes_in_model - timestamp_attributes_for_create_in_model + timestamp_attributes_for_update_in_model - end - - def timestamp_attributes_for_create - ["created_at", "created_on"] - end - - def timestamp_attributes_for_update - ["updated_at", "updated_on"] - end - - def current_time_from_proper_timezone - default_timezone == :utc ? Time.now.utc : Time.now - end - end - - private - - def _create_record - if record_timestamps - current_time = current_time_from_proper_timezone - - all_timestamp_attributes_in_model.each do |column| - if !attribute_present?(column) - write_attribute(column, current_time) - end - end - end - - super - end - - def _update_record(*args, touch: true, **options) - if touch && should_record_timestamps? - current_time = current_time_from_proper_timezone - - timestamp_attributes_for_update_in_model.each do |column| - next if will_save_change_to_attribute?(column) - write_attribute(column, current_time) - end - end - super(*args) - end - - def should_record_timestamps? - record_timestamps && (!partial_writes? || has_changes_to_save?) - end - - def timestamp_attributes_for_create_in_model - self.class.send(:timestamp_attributes_for_create_in_model) - end - - def timestamp_attributes_for_update_in_model - self.class.send(:timestamp_attributes_for_update_in_model) - end - - def all_timestamp_attributes_in_model - self.class.send(:all_timestamp_attributes_in_model) - end - - def current_time_from_proper_timezone - self.class.send(:current_time_from_proper_timezone) - end - - def max_updated_column_timestamp(timestamp_names = self.class.send(:timestamp_attributes_for_update)) - timestamp_names - .map { |attr| self[attr] } - .compact - .map(&:to_time) - .max - end - - # Clear attributes and changed_attributes - def clear_timestamp_attributes - all_timestamp_attributes_in_model.each do |attribute_name| - self[attribute_name] = nil - clear_attribute_changes([attribute_name]) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/touch_later.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/touch_later.rb deleted file mode 100644 index cacde9c881..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/touch_later.rb +++ /dev/null @@ -1,62 +0,0 @@ -module ActiveRecord - # = Active Record Touch Later - module TouchLater - extend ActiveSupport::Concern - - included do - before_commit_without_transaction_enrollment :touch_deferred_attributes - end - - def touch_later(*names) # :nodoc: - unless persisted? - raise ActiveRecordError, <<-MSG.squish - cannot touch on a new or destroyed record object. Consider using - persisted?, new_record?, or destroyed? before touching - MSG - end - - @_defer_touch_attrs ||= timestamp_attributes_for_update_in_model - @_defer_touch_attrs |= names - @_touch_time = current_time_from_proper_timezone - - surreptitiously_touch @_defer_touch_attrs - self.class.connection.add_transaction_record self - - # touch the parents as we are not calling the after_save callbacks - self.class.reflect_on_all_associations(:belongs_to).each do |r| - if touch = r.options[:touch] - ActiveRecord::Associations::Builder::BelongsTo.touch_record(self, changes_to_save, r.foreign_key, r.name, touch, :touch_later) - end - end - end - - def touch(*names, time: nil) # :nodoc: - if has_defer_touch_attrs? - names |= @_defer_touch_attrs - end - super(*names, time: time) - end - - private - - def surreptitiously_touch(attrs) - attrs.each { |attr| write_attribute attr, @_touch_time } - clear_attribute_changes attrs - end - - def touch_deferred_attributes - if has_defer_touch_attrs? && persisted? - touch(*@_defer_touch_attrs, time: @_touch_time) - @_defer_touch_attrs, @_touch_time = nil, nil - end - end - - def has_defer_touch_attrs? - defined?(@_defer_touch_attrs) && @_defer_touch_attrs.present? - end - - def belongs_to_touch_method - :touch_later - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/transactions.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/transactions.rb deleted file mode 100644 index 45795fa287..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/transactions.rb +++ /dev/null @@ -1,497 +0,0 @@ -module ActiveRecord - # See ActiveRecord::Transactions::ClassMethods for documentation. - module Transactions - extend ActiveSupport::Concern - #:nodoc: - ACTIONS = [:create, :destroy, :update] - - included do - define_callbacks :commit, :rollback, - :before_commit, - :before_commit_without_transaction_enrollment, - :commit_without_transaction_enrollment, - :rollback_without_transaction_enrollment, - scope: [:kind, :name] - end - - # = Active Record Transactions - # - # \Transactions are protective blocks where SQL statements are only permanent - # if they can all succeed as one atomic action. The classic example is a - # transfer between two accounts where you can only have a deposit if the - # withdrawal succeeded and vice versa. \Transactions enforce the integrity of - # the database and guard the data against program errors or database - # break-downs. So basically you should use transaction blocks whenever you - # have a number of statements that must be executed together or not at all. - # - # For example: - # - # ActiveRecord::Base.transaction do - # david.withdrawal(100) - # mary.deposit(100) - # end - # - # This example will only take money from David and give it to Mary if neither - # +withdrawal+ nor +deposit+ raise an exception. Exceptions will force a - # ROLLBACK that returns the database to the state before the transaction - # began. Be aware, though, that the objects will _not_ have their instance - # data returned to their pre-transactional state. - # - # == Different Active Record classes in a single transaction - # - # Though the #transaction class method is called on some Active Record class, - # the objects within the transaction block need not all be instances of - # that class. This is because transactions are per-database connection, not - # per-model. - # - # In this example a +balance+ record is transactionally saved even - # though #transaction is called on the +Account+ class: - # - # Account.transaction do - # balance.save! - # account.save! - # end - # - # The #transaction method is also available as a model instance method. - # For example, you can also do this: - # - # balance.transaction do - # balance.save! - # account.save! - # end - # - # == Transactions are not distributed across database connections - # - # A transaction acts on a single database connection. If you have - # multiple class-specific databases, the transaction will not protect - # interaction among them. One workaround is to begin a transaction - # on each class whose models you alter: - # - # Student.transaction do - # Course.transaction do - # course.enroll(student) - # student.units += course.units - # end - # end - # - # This is a poor solution, but fully distributed transactions are beyond - # the scope of Active Record. - # - # == +save+ and +destroy+ are automatically wrapped in a transaction - # - # Both {#save}[rdoc-ref:Persistence#save] and - # {#destroy}[rdoc-ref:Persistence#destroy] come wrapped in a transaction that ensures - # that whatever you do in validations or callbacks will happen under its - # protected cover. So you can use validations to check for values that - # the transaction depends on or you can raise exceptions in the callbacks - # to rollback, including after_* callbacks. - # - # As a consequence changes to the database are not seen outside your connection - # until the operation is complete. For example, if you try to update the index - # of a search engine in +after_save+ the indexer won't see the updated record. - # The #after_commit callback is the only one that is triggered once the update - # is committed. See below. - # - # == Exception handling and rolling back - # - # Also have in mind that exceptions thrown within a transaction block will - # be propagated (after triggering the ROLLBACK), so you should be ready to - # catch those in your application code. - # - # One exception is the ActiveRecord::Rollback exception, which will trigger - # a ROLLBACK when raised, but not be re-raised by the transaction block. - # - # *Warning*: one should not catch ActiveRecord::StatementInvalid exceptions - # inside a transaction block. ActiveRecord::StatementInvalid exceptions indicate that an - # error occurred at the database level, for example when a unique constraint - # is violated. On some database systems, such as PostgreSQL, database errors - # inside a transaction cause the entire transaction to become unusable - # until it's restarted from the beginning. Here is an example which - # demonstrates the problem: - # - # # Suppose that we have a Number model with a unique column called 'i'. - # Number.transaction do - # Number.create(i: 0) - # begin - # # This will raise a unique constraint error... - # Number.create(i: 0) - # rescue ActiveRecord::StatementInvalid - # # ...which we ignore. - # end - # - # # On PostgreSQL, the transaction is now unusable. The following - # # statement will cause a PostgreSQL error, even though the unique - # # constraint is no longer violated: - # Number.create(i: 1) - # # => "PG::Error: ERROR: current transaction is aborted, commands - # # ignored until end of transaction block" - # end - # - # One should restart the entire transaction if an - # ActiveRecord::StatementInvalid occurred. - # - # == Nested transactions - # - # #transaction calls can be nested. By default, this makes all database - # statements in the nested transaction block become part of the parent - # transaction. For example, the following behavior may be surprising: - # - # User.transaction do - # User.create(username: 'Kotori') - # User.transaction do - # User.create(username: 'Nemu') - # raise ActiveRecord::Rollback - # end - # end - # - # creates both "Kotori" and "Nemu". Reason is the ActiveRecord::Rollback - # exception in the nested block does not issue a ROLLBACK. Since these exceptions - # are captured in transaction blocks, the parent block does not see it and the - # real transaction is committed. - # - # In order to get a ROLLBACK for the nested transaction you may ask for a real - # sub-transaction by passing requires_new: true. If anything goes wrong, - # the database rolls back to the beginning of the sub-transaction without rolling - # back the parent transaction. If we add it to the previous example: - # - # User.transaction do - # User.create(username: 'Kotori') - # User.transaction(requires_new: true) do - # User.create(username: 'Nemu') - # raise ActiveRecord::Rollback - # end - # end - # - # only "Kotori" is created. This works on MySQL and PostgreSQL. SQLite3 version >= '3.6.8' also supports it. - # - # Most databases don't support true nested transactions. At the time of - # writing, the only database that we're aware of that supports true nested - # transactions, is MS-SQL. Because of this, Active Record emulates nested - # transactions by using savepoints on MySQL and PostgreSQL. See - # http://dev.mysql.com/doc/refman/5.7/en/savepoint.html - # for more information about savepoints. - # - # === \Callbacks - # - # There are two types of callbacks associated with committing and rolling back transactions: - # #after_commit and #after_rollback. - # - # #after_commit callbacks are called on every record saved or destroyed within a - # transaction immediately after the transaction is committed. #after_rollback callbacks - # are called on every record saved or destroyed within a transaction immediately after the - # transaction or savepoint is rolled back. - # - # These callbacks are useful for interacting with other systems since you will be guaranteed - # that the callback is only executed when the database is in a permanent state. For example, - # #after_commit is a good spot to put in a hook to clearing a cache since clearing it from - # within a transaction could trigger the cache to be regenerated before the database is updated. - # - # === Caveats - # - # If you're on MySQL, then do not use Data Definition Language(DDL) operations in nested - # transactions blocks that are emulated with savepoints. That is, do not execute statements - # like 'CREATE TABLE' inside such blocks. This is because MySQL automatically - # releases all savepoints upon executing a DDL operation. When +transaction+ - # is finished and tries to release the savepoint it created earlier, a - # database error will occur because the savepoint has already been - # automatically released. The following example demonstrates the problem: - # - # Model.connection.transaction do # BEGIN - # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 - # Model.connection.create_table(...) # active_record_1 now automatically released - # end # RELEASE SAVEPOINT active_record_1 - # # ^^^^ BOOM! database error! - # end - # - # Note that "TRUNCATE" is also a MySQL DDL statement! - module ClassMethods - # See the ConnectionAdapters::DatabaseStatements#transaction API docs. - def transaction(options = {}, &block) - connection.transaction(options, &block) - end - - def before_commit(*args, &block) # :nodoc: - set_options_for_callbacks!(args) - set_callback(:before_commit, :before, *args, &block) - end - - # This callback is called after a record has been created, updated, or destroyed. - # - # You can specify that the callback should only be fired by a certain action with - # the +:on+ option: - # - # after_commit :do_foo, on: :create - # after_commit :do_bar, on: :update - # after_commit :do_baz, on: :destroy - # - # after_commit :do_foo_bar, on: [:create, :update] - # after_commit :do_bar_baz, on: [:update, :destroy] - # - def after_commit(*args, &block) - set_options_for_callbacks!(args) - set_callback(:commit, :after, *args, &block) - end - - # Shortcut for after_commit :hook, on: :create. - def after_create_commit(*args, &block) - set_options_for_callbacks!(args, on: :create) - set_callback(:commit, :after, *args, &block) - end - - # Shortcut for after_commit :hook, on: :update. - def after_update_commit(*args, &block) - set_options_for_callbacks!(args, on: :update) - set_callback(:commit, :after, *args, &block) - end - - # Shortcut for after_commit :hook, on: :destroy. - def after_destroy_commit(*args, &block) - set_options_for_callbacks!(args, on: :destroy) - set_callback(:commit, :after, *args, &block) - end - - # This callback is called after a create, update, or destroy are rolled back. - # - # Please check the documentation of #after_commit for options. - def after_rollback(*args, &block) - set_options_for_callbacks!(args) - set_callback(:rollback, :after, *args, &block) - end - - def before_commit_without_transaction_enrollment(*args, &block) # :nodoc: - set_options_for_callbacks!(args) - set_callback(:before_commit_without_transaction_enrollment, :before, *args, &block) - end - - def after_commit_without_transaction_enrollment(*args, &block) # :nodoc: - set_options_for_callbacks!(args) - set_callback(:commit_without_transaction_enrollment, :after, *args, &block) - end - - def after_rollback_without_transaction_enrollment(*args, &block) # :nodoc: - set_options_for_callbacks!(args) - set_callback(:rollback_without_transaction_enrollment, :after, *args, &block) - end - - private - - def set_options_for_callbacks!(args, enforced_options = {}) - options = args.extract_options!.merge!(enforced_options) - args << options - - if options[:on] - fire_on = Array(options[:on]) - assert_valid_transaction_action(fire_on) - options[:if] = Array(options[:if]) - options[:if].unshift("transaction_include_any_action?(#{fire_on})") - end - end - - def assert_valid_transaction_action(actions) - if (actions - ACTIONS).any? - raise ArgumentError, ":on conditions for after_commit and after_rollback callbacks have to be one of #{ACTIONS}" - end - end - end - - # See ActiveRecord::Transactions::ClassMethods for detailed documentation. - def transaction(options = {}, &block) - self.class.transaction(options, &block) - end - - def destroy #:nodoc: - with_transaction_returning_status { super } - end - - def save(*) #:nodoc: - rollback_active_record_state! do - with_transaction_returning_status { super } - end - end - - def save!(*) #:nodoc: - with_transaction_returning_status { super } - end - - def touch(*) #:nodoc: - with_transaction_returning_status { super } - end - - # Reset id and @new_record if the transaction rolls back. - def rollback_active_record_state! - remember_transaction_record_state - yield - rescue Exception - restore_transaction_record_state - raise - ensure - clear_transaction_record_state - end - - def before_committed! # :nodoc: - _run_before_commit_without_transaction_enrollment_callbacks - _run_before_commit_callbacks - end - - # Call the #after_commit callbacks. - # - # Ensure that it is not called if the object was never persisted (failed create), - # but call it after the commit of a destroyed object. - def committed!(should_run_callbacks: true) #:nodoc: - if should_run_callbacks && destroyed? || persisted? - _run_commit_without_transaction_enrollment_callbacks - _run_commit_callbacks - end - ensure - force_clear_transaction_record_state - end - - # Call the #after_rollback callbacks. The +force_restore_state+ argument indicates if the record - # state should be rolled back to the beginning or just to the last savepoint. - def rolledback!(force_restore_state: false, should_run_callbacks: true) #:nodoc: - if should_run_callbacks - _run_rollback_callbacks - _run_rollback_without_transaction_enrollment_callbacks - end - ensure - restore_transaction_record_state(force_restore_state) - clear_transaction_record_state - end - - # Add the record to the current transaction so that the #after_rollback and #after_commit callbacks - # can be called. - def add_to_transaction - if has_transactional_callbacks? - self.class.connection.add_transaction_record(self) - else - sync_with_transaction_state - set_transaction_state(self.class.connection.transaction_state) - end - remember_transaction_record_state - end - - # Executes +method+ within a transaction and captures its return value as a - # status flag. If the status is true the transaction is committed, otherwise - # a ROLLBACK is issued. In any case the status flag is returned. - # - # This method is available within the context of an ActiveRecord::Base - # instance. - def with_transaction_returning_status - status = nil - self.class.transaction do - add_to_transaction - begin - status = yield - rescue ActiveRecord::Rollback - clear_transaction_record_state - status = nil - end - - raise ActiveRecord::Rollback unless status - end - status - ensure - if @transaction_state && @transaction_state.committed? - clear_transaction_record_state - end - end - - private - - # Save the new record state and id of a record so it can be restored later if a transaction fails. - def remember_transaction_record_state - @_start_transaction_state[:id] = id - @_start_transaction_state.reverse_merge!( - new_record: @new_record, - destroyed: @destroyed, - frozen?: frozen?, - ) - @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) + 1 - end - - # Clear the new record state and id of a record. - def clear_transaction_record_state - @_start_transaction_state[:level] = (@_start_transaction_state[:level] || 0) - 1 - force_clear_transaction_record_state if @_start_transaction_state[:level] < 1 - end - - # Force to clear the transaction record state. - def force_clear_transaction_record_state - @_start_transaction_state.clear - end - - # Restore the new record state and id of a record that was previously saved by a call to save_record_state. - def restore_transaction_record_state(force = false) - unless @_start_transaction_state.empty? - transaction_level = (@_start_transaction_state[:level] || 0) - 1 - if transaction_level < 1 || force - restore_state = @_start_transaction_state - thaw - @new_record = restore_state[:new_record] - @destroyed = restore_state[:destroyed] - pk = self.class.primary_key - if pk && read_attribute(pk) != restore_state[:id] - write_attribute(pk, restore_state[:id]) - end - freeze if restore_state[:frozen?] - end - end - end - - # Determine if a record was created or destroyed in a transaction. State should be one of :new_record or :destroyed. - def transaction_record_state(state) - @_start_transaction_state[state] - end - - # Determine if a transaction included an action for :create, :update, or :destroy. Used in filtering callbacks. - def transaction_include_any_action?(actions) - actions.any? do |action| - case action - when :create - transaction_record_state(:new_record) - when :destroy - defined?(@_trigger_destroy_callback) && @_trigger_destroy_callback - when :update - !(transaction_record_state(:new_record) || destroyed?) && - (defined?(@_trigger_update_callback) && @_trigger_update_callback) - end - end - end - - def set_transaction_state(state) - @transaction_state = state - end - - def has_transactional_callbacks? - !_rollback_callbacks.empty? || !_commit_callbacks.empty? || !_before_commit_callbacks.empty? - end - - # Updates the attributes on this particular Active Record object so that - # if it's associated with a transaction, then the state of the Active Record - # object will be updated to reflect the current state of the transaction. - # - # The +@transaction_state+ variable stores the states of the associated - # transaction. This relies on the fact that a transaction can only be in - # one rollback or commit (otherwise a list of states would be required). - # Each Active Record object inside of a transaction carries that transaction's - # TransactionState. - # - # This method checks to see if the ActiveRecord object's state reflects - # the TransactionState, and rolls back or commits the Active Record object - # as appropriate. - # - # Since Active Record objects can be inside multiple transactions, this - # method recursively goes through the parent of the TransactionState and - # checks if the Active Record object reflects the state of the object. - def sync_with_transaction_state - update_attributes_from_transaction_state(@transaction_state) - end - - def update_attributes_from_transaction_state(transaction_state) - if transaction_state && transaction_state.finalized? - restore_transaction_record_state if transaction_state.rolledback? - clear_transaction_record_state - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/translation.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/translation.rb deleted file mode 100644 index ddcb5f2a7a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/translation.rb +++ /dev/null @@ -1,22 +0,0 @@ -module ActiveRecord - module Translation - include ActiveModel::Translation - - # Set the lookup ancestors for ActiveModel. - def lookup_ancestors #:nodoc: - klass = self - classes = [klass] - return classes if klass == ActiveRecord::Base - - while klass != klass.base_class - classes << klass = klass.superclass - end - classes - end - - # Set the i18n scope to overwrite ActiveModel. - def i18n_scope #:nodoc: - :activerecord - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type.rb deleted file mode 100644 index 4f632660a8..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type.rb +++ /dev/null @@ -1,76 +0,0 @@ -require "active_model/type" - -require "active_record/type/internal/abstract_json" -require "active_record/type/internal/timezone" - -require "active_record/type/date" -require "active_record/type/date_time" -require "active_record/type/decimal_without_scale" -require "active_record/type/time" -require "active_record/type/text" -require "active_record/type/unsigned_integer" - -require "active_record/type/serialized" -require "active_record/type/adapter_specific_registry" - -require "active_record/type/type_map" -require "active_record/type/hash_lookup_type_map" - -module ActiveRecord - module Type - @registry = AdapterSpecificRegistry.new - - class << self - attr_accessor :registry # :nodoc: - delegate :add_modifier, to: :registry - - # Add a new type to the registry, allowing it to be referenced as a - # symbol by {ActiveRecord::Base.attribute}[rdoc-ref:Attributes::ClassMethods#attribute]. - # If your type is only meant to be used with a specific database adapter, you can - # do so by passing adapter: :postgresql. If your type has the same - # name as a native type for the current adapter, an exception will be - # raised unless you specify an +:override+ option. override: true will - # cause your type to be used instead of the native type. override: - # false will cause the native type to be used over yours if one exists. - def register(type_name, klass = nil, **options, &block) - registry.register(type_name, klass, **options, &block) - end - - def lookup(*args, adapter: current_adapter_name, **kwargs) # :nodoc: - registry.lookup(*args, adapter: adapter, **kwargs) - end - - def default_value # :nodoc: - @default_value ||= Value.new - end - - private - - def current_adapter_name - ActiveRecord::Base.connection.adapter_name.downcase.to_sym - end - end - - Helpers = ActiveModel::Type::Helpers - BigInteger = ActiveModel::Type::BigInteger - Binary = ActiveModel::Type::Binary - Boolean = ActiveModel::Type::Boolean - Decimal = ActiveModel::Type::Decimal - Float = ActiveModel::Type::Float - Integer = ActiveModel::Type::Integer - String = ActiveModel::Type::String - Value = ActiveModel::Type::Value - - register(:big_integer, Type::BigInteger, override: false) - register(:binary, Type::Binary, override: false) - register(:boolean, Type::Boolean, override: false) - register(:date, Type::Date, override: false) - register(:datetime, Type::DateTime, override: false) - register(:decimal, Type::Decimal, override: false) - register(:float, Type::Float, override: false) - register(:integer, Type::Integer, override: false) - register(:string, Type::String, override: false) - register(:text, Type::Text, override: false) - register(:time, Type::Time, override: false) - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/adapter_specific_registry.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/adapter_specific_registry.rb deleted file mode 100644 index 7cc866f7a7..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/adapter_specific_registry.rb +++ /dev/null @@ -1,134 +0,0 @@ -require "active_model/type/registry" - -module ActiveRecord - # :stopdoc: - module Type - class AdapterSpecificRegistry < ActiveModel::Type::Registry - def add_modifier(options, klass, **args) - registrations << DecorationRegistration.new(options, klass, **args) - end - - private - - def registration_klass - Registration - end - - def find_registration(symbol, *args) - registrations - .select { |registration| registration.matches?(symbol, *args) } - .max - end - end - - class Registration - def initialize(name, block, adapter: nil, override: nil) - @name = name - @block = block - @adapter = adapter - @override = override - end - - def call(_registry, *args, adapter: nil, **kwargs) - if kwargs.any? # https://bugs.ruby-lang.org/issues/10856 - block.call(*args, **kwargs) - else - block.call(*args) - end - end - - def matches?(type_name, *args, **kwargs) - type_name == name && matches_adapter?(**kwargs) - end - - def <=>(other) - if conflicts_with?(other) - raise TypeConflictError.new("Type #{name} was registered for all - adapters, but shadows a native type with - the same name for #{other.adapter}".squish) - end - priority <=> other.priority - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :name, :block, :adapter, :override - - def priority - result = 0 - if adapter - result |= 1 - end - if override - result |= 2 - end - result - end - - def priority_except_adapter - priority & 0b111111100 - end - - private - - def matches_adapter?(adapter: nil, **) - (self.adapter.nil? || adapter == self.adapter) - end - - def conflicts_with?(other) - same_priority_except_adapter?(other) && - has_adapter_conflict?(other) - end - - def same_priority_except_adapter?(other) - priority_except_adapter == other.priority_except_adapter - end - - def has_adapter_conflict?(other) - (override.nil? && other.adapter) || - (adapter && other.override.nil?) - end - end - - class DecorationRegistration < Registration - def initialize(options, klass, adapter: nil) - @options = options - @klass = klass - @adapter = adapter - end - - def call(registry, *args, **kwargs) - subtype = registry.lookup(*args, **kwargs.except(*options.keys)) - klass.new(subtype) - end - - def matches?(*args, **kwargs) - matches_adapter?(**kwargs) && matches_options?(**kwargs) - end - - def priority - super | 4 - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :options, :klass - - private - - def matches_options?(**kwargs) - options.all? do |key, value| - kwargs[key] == value - end - end - end - end - - class TypeConflictError < StandardError - end - # :startdoc: -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/date.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/date.rb deleted file mode 100644 index ccafed054e..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/date.rb +++ /dev/null @@ -1,7 +0,0 @@ -module ActiveRecord - module Type - class Date < ActiveModel::Type::Date - include Internal::Timezone - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/date_time.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/date_time.rb deleted file mode 100644 index 1fb9380ecd..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/date_time.rb +++ /dev/null @@ -1,7 +0,0 @@ -module ActiveRecord - module Type - class DateTime < ActiveModel::Type::DateTime - include Internal::Timezone - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/decimal_without_scale.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/decimal_without_scale.rb deleted file mode 100644 index 53a5e205da..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/decimal_without_scale.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveRecord - module Type - class DecimalWithoutScale < ActiveModel::Type::BigInteger # :nodoc: - def type - :decimal - end - - def type_cast_for_schema(value) - value.to_s.inspect - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/hash_lookup_type_map.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/hash_lookup_type_map.rb deleted file mode 100644 index 0145d5d6c1..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/hash_lookup_type_map.rb +++ /dev/null @@ -1,23 +0,0 @@ -module ActiveRecord - module Type - class HashLookupTypeMap < TypeMap # :nodoc: - def alias_type(type, alias_type) - register_type(type) { |_, *args| lookup(alias_type, *args) } - end - - def key?(key) - @mapping.key?(key) - end - - def keys - @mapping.keys - end - - private - - def perform_fetch(type, *args, &block) - @mapping.fetch(type, block).call(type, *args) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/internal/abstract_json.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/internal/abstract_json.rb deleted file mode 100644 index a8d6a63465..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/internal/abstract_json.rb +++ /dev/null @@ -1,37 +0,0 @@ -module ActiveRecord - module Type - module Internal # :nodoc: - class AbstractJson < ActiveModel::Type::Value # :nodoc: - include ActiveModel::Type::Helpers::Mutable - - def type - :json - end - - def deserialize(value) - if value.is_a?(::String) - ::ActiveSupport::JSON.decode(value) rescue nil - else - value - end - end - - def serialize(value) - if value.nil? - nil - else - ::ActiveSupport::JSON.encode(value) - end - end - - def changed_in_place?(raw_old_value, new_value) - deserialize(raw_old_value) != new_value - end - - def accessor - ActiveRecord::Store::StringKeyedHashAccessor - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/internal/timezone.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/internal/timezone.rb deleted file mode 100644 index 947e06158a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/internal/timezone.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module Type - module Internal - module Timezone - def is_utc? - ActiveRecord::Base.default_timezone == :utc - end - - def default_timezone - ActiveRecord::Base.default_timezone - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/serialized.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/serialized.rb deleted file mode 100644 index c31b3d562a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/serialized.rb +++ /dev/null @@ -1,69 +0,0 @@ -module ActiveRecord - module Type - class Serialized < DelegateClass(ActiveModel::Type::Value) # :nodoc: - undef to_yaml if method_defined?(:to_yaml) - - include ActiveModel::Type::Helpers::Mutable - - attr_reader :subtype, :coder - - def initialize(subtype, coder) - @subtype = subtype - @coder = coder - super(subtype) - end - - def deserialize(value) - if default_value?(value) - value - else - coder.load(super) - end - end - - def serialize(value) - return if value.nil? - unless default_value?(value) - super coder.dump(value) - end - end - - def inspect - Kernel.instance_method(:inspect).bind(self).call - end - - def changed_in_place?(raw_old_value, value) - return false if value.nil? - raw_new_value = encoded(value) - raw_old_value.nil? != raw_new_value.nil? || - subtype.changed_in_place?(raw_old_value, raw_new_value) - end - - def accessor - ActiveRecord::Store::IndifferentHashAccessor - end - - def assert_valid_value(value) - if coder.respond_to?(:assert_valid_value) - coder.assert_valid_value(value, action: "serialize") - end - end - - def force_equality?(value) - coder.respond_to?(:object_class) && value.is_a?(coder.object_class) - end - - private - - def default_value?(value) - value == coder.load(nil) - end - - def encoded(value) - unless default_value?(value) - coder.dump(value) - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/text.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/text.rb deleted file mode 100644 index cb1949700a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/text.rb +++ /dev/null @@ -1,9 +0,0 @@ -module ActiveRecord - module Type - class Text < ActiveModel::Type::String # :nodoc: - def type - :text - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/time.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/time.rb deleted file mode 100644 index b9bac87c67..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/time.rb +++ /dev/null @@ -1,19 +0,0 @@ -module ActiveRecord - module Type - class Time < ActiveModel::Type::Time - include Internal::Timezone - - class Value < DelegateClass(::Time) # :nodoc: - end - - def serialize(value) - case value = super - when ::Time - Value.new(value) - else - value - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/type_map.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/type_map.rb deleted file mode 100644 index 7bce82a1ff..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/type_map.rb +++ /dev/null @@ -1,60 +0,0 @@ -require "concurrent/map" - -module ActiveRecord - module Type - class TypeMap # :nodoc: - def initialize - @mapping = {} - @cache = Concurrent::Map.new do |h, key| - h.fetch_or_store(key, Concurrent::Map.new) - end - end - - def lookup(lookup_key, *args) - fetch(lookup_key, *args) { Type.default_value } - end - - def fetch(lookup_key, *args, &block) - @cache[lookup_key].fetch_or_store(args) do - perform_fetch(lookup_key, *args, &block) - end - end - - def register_type(key, value = nil, &block) - raise ::ArgumentError unless value || block - @cache.clear - - if block - @mapping[key] = block - else - @mapping[key] = proc { value } - end - end - - def alias_type(key, target_key) - register_type(key) do |sql_type, *args| - metadata = sql_type[/\(.*\)/, 0] - lookup("#{target_key}#{metadata}", *args) - end - end - - def clear - @mapping.clear - end - - private - - def perform_fetch(lookup_key, *args) - matching_pair = @mapping.reverse_each.detect do |key, _| - key === lookup_key - end - - if matching_pair - matching_pair.last.call(lookup_key, *args) - else - yield lookup_key, *args - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/unsigned_integer.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/unsigned_integer.rb deleted file mode 100644 index 9ae0109f9f..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type/unsigned_integer.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveRecord - module Type - class UnsignedInteger < ActiveModel::Type::Integer # :nodoc: - private - - def max_value - super * 2 - end - - def min_value - 0 - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster.rb deleted file mode 100644 index f1686e4913..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster.rb +++ /dev/null @@ -1,7 +0,0 @@ -require "active_record/type_caster/map" -require "active_record/type_caster/connection" - -module ActiveRecord - module TypeCaster # :nodoc: - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster/connection.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster/connection.rb deleted file mode 100644 index 9f7bbe8843..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster/connection.rb +++ /dev/null @@ -1,31 +0,0 @@ -module ActiveRecord - module TypeCaster - class Connection # :nodoc: - def initialize(klass, table_name) - @klass = klass - @table_name = table_name - end - - def type_cast_for_database(attribute_name, value) - return value if value.is_a?(Arel::Nodes::BindParam) - column = column_for(attribute_name) - connection.type_cast_from_column(column, value) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :table_name - delegate :connection, to: :@klass - - private - - def column_for(attribute_name) - if connection.schema_cache.data_source_exists?(table_name) - connection.schema_cache.columns_hash(table_name)[attribute_name.to_s] - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster/map.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster/map.rb deleted file mode 100644 index 9f79723125..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/type_caster/map.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActiveRecord - module TypeCaster - class Map # :nodoc: - def initialize(types) - @types = types - end - - def type_cast_for_database(attr_name, value) - return value if value.is_a?(Arel::Nodes::BindParam) - type = types.type_for_attribute(attr_name.to_s) - type.serialize(value) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :types - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations.rb deleted file mode 100644 index 9633f226f0..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations.rb +++ /dev/null @@ -1,91 +0,0 @@ -module ActiveRecord - # = Active Record \RecordInvalid - # - # Raised by {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!] and - # {ActiveRecord::Base#create!}[rdoc-ref:Persistence::ClassMethods#create!] when the record is invalid. - # Use the #record method to retrieve the record which did not validate. - # - # begin - # complex_operation_that_internally_calls_save! - # rescue ActiveRecord::RecordInvalid => invalid - # puts invalid.record.errors - # end - class RecordInvalid < ActiveRecordError - attr_reader :record - - def initialize(record = nil) - if record - @record = record - errors = @record.errors.full_messages.join(", ") - message = I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", errors: errors, default: :"errors.messages.record_invalid") - else - message = "Record invalid" - end - - super(message) - end - end - - # = Active Record \Validations - # - # Active Record includes the majority of its validations from ActiveModel::Validations - # all of which accept the :on argument to define the context where the - # validations are active. Active Record will always supply either the context of - # :create or :update dependent on whether the model is a - # {new_record?}[rdoc-ref:Persistence#new_record?]. - module Validations - extend ActiveSupport::Concern - include ActiveModel::Validations - - # The validation process on save can be skipped by passing validate: false. - # The regular {ActiveRecord::Base#save}[rdoc-ref:Persistence#save] method is replaced - # with this when the validations module is mixed in, which it is by default. - def save(options = {}) - perform_validations(options) ? super : false - end - - # Attempts to save the record just like {ActiveRecord::Base#save}[rdoc-ref:Base#save] but - # will raise an ActiveRecord::RecordInvalid exception instead of returning +false+ if the record is not valid. - def save!(options = {}) - perform_validations(options) ? super : raise_validation_error - end - - # Runs all the validations within the specified context. Returns +true+ if - # no errors are found, +false+ otherwise. - # - # Aliased as #validate. - # - # If the argument is +false+ (default is +nil+), the context is set to :create if - # {new_record?}[rdoc-ref:Persistence#new_record?] is +true+, and to :update if it is not. - # - # \Validations with no :on option will run no matter the context. \Validations with - # some :on option will only run in the specified context. - def valid?(context = nil) - context ||= default_validation_context - output = super(context) - errors.empty? && output - end - - alias_method :validate, :valid? - - private - - def default_validation_context - new_record? ? :create : :update - end - - def raise_validation_error - raise(RecordInvalid.new(self)) - end - - def perform_validations(options = {}) - options[:validate] == false || valid?(options[:context]) - end - end -end - -require "active_record/validations/associated" -require "active_record/validations/uniqueness" -require "active_record/validations/presence" -require "active_record/validations/absence" -require "active_record/validations/length" diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/absence.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/absence.rb deleted file mode 100644 index 641d041f3d..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/absence.rb +++ /dev/null @@ -1,23 +0,0 @@ -module ActiveRecord - module Validations - class AbsenceValidator < ActiveModel::Validations::AbsenceValidator # :nodoc: - def validate_each(record, attribute, association_or_value) - if record.class._reflect_on_association(attribute) - association_or_value = Array.wrap(association_or_value).reject(&:marked_for_destruction?) - end - super - end - end - - module ClassMethods - # Validates that the specified attributes are not present (as defined by - # Object#present?). If the attribute is an association, the associated object - # is considered absent if it was marked for destruction. - # - # See ActiveModel::Validations::HelperMethods.validates_absence_of for more information. - def validates_absence_of(*attr_names) - validates_with AbsenceValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/associated.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/associated.rb deleted file mode 100644 index c695965d7b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/associated.rb +++ /dev/null @@ -1,58 +0,0 @@ -module ActiveRecord - module Validations - class AssociatedValidator < ActiveModel::EachValidator #:nodoc: - def validate_each(record, attribute, value) - if Array(value).reject { |r| valid_object?(r) }.any? - record.errors.add(attribute, :invalid, options.merge(value: value)) - end - end - - private - - def valid_object?(record) - (record.respond_to?(:marked_for_destruction?) && record.marked_for_destruction?) || record.valid? - end - end - - module ClassMethods - # Validates whether the associated object or objects are all valid. - # Works with any kind of association. - # - # class Book < ActiveRecord::Base - # has_many :pages - # belongs_to :library - # - # validates_associated :pages, :library - # end - # - # WARNING: This validation must not be used on both ends of an association. - # Doing so will lead to a circular dependency and cause infinite recursion. - # - # NOTE: This validation will not fail if the association hasn't been - # assigned. If you want to ensure that the association is both present and - # guaranteed to be valid, you also need to use - # {validates_presence_of}[rdoc-ref:Validations::ClassMethods#validates_presence_of]. - # - # Configuration options: - # - # * :message - A custom error message (default is: "is invalid"). - # * :on - Specifies the contexts where this validation is active. - # Runs in all validation contexts by default +nil+. You can pass a symbol - # or an array of symbols. (e.g. on: :create or - # on: :custom_validation_context or - # on: [:create, :custom_validation_context]) - # * :if - Specifies a method, proc or string to call to determine - # if the validation should occur (e.g. if: :allow_validation, - # or if: Proc.new { |user| user.signup_step > 2 }). The method, - # proc or string should return or evaluate to a +true+ or +false+ value. - # * :unless - Specifies a method, proc or string to call to - # determine if the validation should not occur (e.g. unless: :skip_validation, - # or unless: Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a +true+ or +false+ - # value. - def validates_associated(*attr_names) - validates_with AssociatedValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/length.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/length.rb deleted file mode 100644 index 0e0cebce4a..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/length.rb +++ /dev/null @@ -1,24 +0,0 @@ -module ActiveRecord - module Validations - class LengthValidator < ActiveModel::Validations::LengthValidator # :nodoc: - def validate_each(record, attribute, association_or_value) - if association_or_value.respond_to?(:loaded?) && association_or_value.loaded? - association_or_value = association_or_value.target.reject(&:marked_for_destruction?) - end - super - end - end - - module ClassMethods - # Validates that the specified attributes match the length restrictions supplied. - # If the attribute is an association, records that are marked for destruction are not counted. - # - # See ActiveModel::Validations::HelperMethods.validates_length_of for more information. - def validates_length_of(*attr_names) - validates_with LengthValidator, _merge_attributes(attr_names) - end - - alias_method :validates_size_of, :validates_length_of - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/presence.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/presence.rb deleted file mode 100644 index 7cfd55f516..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/presence.rb +++ /dev/null @@ -1,66 +0,0 @@ -module ActiveRecord - module Validations - class PresenceValidator < ActiveModel::Validations::PresenceValidator # :nodoc: - def validate_each(record, attribute, association_or_value) - if record.class._reflect_on_association(attribute) - association_or_value = Array.wrap(association_or_value).reject(&:marked_for_destruction?) - end - super - end - end - - module ClassMethods - # Validates that the specified attributes are not blank (as defined by - # Object#blank?), and, if the attribute is an association, that the - # associated object is not marked for destruction. Happens by default - # on save. - # - # class Person < ActiveRecord::Base - # has_one :face - # validates_presence_of :face - # end - # - # The face attribute must be in the object and it cannot be blank or marked - # for destruction. - # - # If you want to validate the presence of a boolean field (where the real values - # are true and false), you will want to use - # validates_inclusion_of :field_name, in: [true, false]. - # - # This is due to the way Object#blank? handles boolean values: - # false.blank? # => true. - # - # This validator defers to the Active Model validation for presence, adding the - # check to see that an associated object is not marked for destruction. This - # prevents the parent object from validating successfully and saving, which then - # deletes the associated object, thus putting the parent object into an invalid - # state. - # - # NOTE: This validation will not fail while using it with an association - # if the latter was assigned but not valid. If you want to ensure that - # it is both present and valid, you also need to use - # {validates_associated}[rdoc-ref:Validations::ClassMethods#validates_associated]. - # - # Configuration options: - # * :message - A custom error message (default is: "can't be blank"). - # * :on - Specifies the contexts where this validation is active. - # Runs in all validation contexts by default +nil+. You can pass a symbol - # or an array of symbols. (e.g. on: :create or - # on: :custom_validation_context or - # on: [:create, :custom_validation_context]) - # * :if - Specifies a method, proc or string to call to determine if - # the validation should occur (e.g. if: :allow_validation, or - # if: Proc.new { |user| user.signup_step > 2 }). The method, proc - # or string should return or evaluate to a +true+ or +false+ value. - # * :unless - Specifies a method, proc or string to call to determine - # if the validation should not occur (e.g. unless: :skip_validation, - # or unless: Proc.new { |user| user.signup_step <= 2 }). The method, - # proc or string should return or evaluate to a +true+ or +false+ value. - # * :strict - Specifies whether validation should be strict. - # See ActiveModel::Validations#validates! for more information. - def validates_presence_of(*attr_names) - validates_with PresenceValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/uniqueness.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/uniqueness.rb deleted file mode 100644 index b4aaca8701..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/validations/uniqueness.rb +++ /dev/null @@ -1,208 +0,0 @@ -module ActiveRecord - module Validations - class UniquenessValidator < ActiveModel::EachValidator # :nodoc: - def initialize(options) - if options[:conditions] && !options[:conditions].respond_to?(:call) - raise ArgumentError, "#{options[:conditions]} was passed as :conditions but is not callable. " \ - "Pass a callable instead: `conditions: -> { where(approved: true) }`" - end - super({ case_sensitive: true }.merge!(options)) - @klass = options[:class] - end - - def validate_each(record, attribute, value) - finder_class = find_finder_class_for(record) - value = map_enum_attribute(finder_class, attribute, value) - - relation = build_relation(finder_class, attribute, value) - if record.persisted? - if finder_class.primary_key - relation = relation.where.not(finder_class.primary_key => record.id_in_database) - else - raise UnknownPrimaryKey.new(finder_class, "Can not validate uniqueness for persisted record without primary key.") - end - end - relation = scope_relation(record, relation) - relation = relation.merge(options[:conditions]) if options[:conditions] - - if relation.exists? - error_options = options.except(:case_sensitive, :scope, :conditions) - error_options[:value] = value - - record.errors.add(attribute, :taken, error_options) - end - end - - private - # The check for an existing value should be run from a class that - # isn't abstract. This means working down from the current class - # (self), to the first non-abstract class. Since classes don't know - # their subclasses, we have to build the hierarchy between self and - # the record's class. - def find_finder_class_for(record) - class_hierarchy = [record.class] - - while class_hierarchy.first != @klass - class_hierarchy.unshift(class_hierarchy.first.superclass) - end - - class_hierarchy.detect { |klass| !klass.abstract_class? } - end - - def build_relation(klass, attribute, value) - klass.unscoped.where!({ attribute => value }, options) - end - - def scope_relation(record, relation) - Array(options[:scope]).each do |scope_item| - scope_value = if record.class._reflect_on_association(scope_item) - record.association(scope_item).reader - else - record._read_attribute(scope_item) - end - relation = relation.where(scope_item => scope_value) - end - - relation - end - - def map_enum_attribute(klass, attribute, value) - mapping = klass.defined_enums[attribute.to_s] - value = mapping[value] if value && mapping - value - end - end - - module ClassMethods - # Validates whether the value of the specified attributes are unique - # across the system. Useful for making sure that only one user - # can be named "davidhh". - # - # class Person < ActiveRecord::Base - # validates_uniqueness_of :user_name - # end - # - # It can also validate whether the value of the specified attributes are - # unique based on a :scope parameter: - # - # class Person < ActiveRecord::Base - # validates_uniqueness_of :user_name, scope: :account_id - # end - # - # Or even multiple scope parameters. For example, making sure that a - # teacher can only be on the schedule once per semester for a particular - # class. - # - # class TeacherSchedule < ActiveRecord::Base - # validates_uniqueness_of :teacher_id, scope: [:semester_id, :class_id] - # end - # - # It is also possible to limit the uniqueness constraint to a set of - # records matching certain conditions. In this example archived articles - # are not being taken into consideration when validating uniqueness - # of the title attribute: - # - # class Article < ActiveRecord::Base - # validates_uniqueness_of :title, conditions: -> { where.not(status: 'archived') } - # end - # - # When the record is created, a check is performed to make sure that no - # record exists in the database with the given value for the specified - # attribute (that maps to a column). When the record is updated, - # the same check is made but disregarding the record itself. - # - # Configuration options: - # - # * :message - Specifies a custom error message (default is: - # "has already been taken"). - # * :scope - One or more columns by which to limit the scope of - # the uniqueness constraint. - # * :conditions - Specify the conditions to be included as a - # WHERE SQL fragment to limit the uniqueness constraint lookup - # (e.g. conditions: -> { where(status: 'active') }). - # * :case_sensitive - Looks for an exact match. Ignored by - # non-text columns (+true+ by default). - # * :allow_nil - If set to +true+, skips this validation if the - # attribute is +nil+ (default is +false+). - # * :allow_blank - If set to +true+, skips this validation if the - # attribute is blank (default is +false+). - # * :if - Specifies a method, proc or string to call to determine - # if the validation should occur (e.g. if: :allow_validation, - # or if: Proc.new { |user| user.signup_step > 2 }). The method, - # proc or string should return or evaluate to a +true+ or +false+ value. - # * :unless - Specifies a method, proc or string to call to - # determine if the validation should not occur (e.g. unless: :skip_validation, - # or unless: Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a +true+ or +false+ - # value. - # - # === Concurrency and integrity - # - # Using this validation method in conjunction with - # {ActiveRecord::Base#save}[rdoc-ref:Persistence#save] - # does not guarantee the absence of duplicate record insertions, because - # uniqueness checks on the application level are inherently prone to race - # conditions. For example, suppose that two users try to post a Comment at - # the same time, and a Comment's title must be unique. At the database-level, - # the actions performed by these users could be interleaved in the following manner: - # - # User 1 | User 2 - # ------------------------------------+-------------------------------------- - # # User 1 checks whether there's | - # # already a comment with the title | - # # 'My Post'. This is not the case. | - # SELECT * FROM comments | - # WHERE title = 'My Post' | - # | - # | # User 2 does the same thing and also - # | # infers that their title is unique. - # | SELECT * FROM comments - # | WHERE title = 'My Post' - # | - # # User 1 inserts their comment. | - # INSERT INTO comments | - # (title, content) VALUES | - # ('My Post', 'hi!') | - # | - # | # User 2 does the same thing. - # | INSERT INTO comments - # | (title, content) VALUES - # | ('My Post', 'hello!') - # | - # | # ^^^^^^ - # | # Boom! We now have a duplicate - # | # title! - # - # This could even happen if you use transactions with the 'serializable' - # isolation level. The best way to work around this problem is to add a unique - # index to the database table using - # {connection.add_index}[rdoc-ref:ConnectionAdapters::SchemaStatements#add_index]. - # In the rare case that a race condition occurs, the database will guarantee - # the field's uniqueness. - # - # When the database catches such a duplicate insertion, - # {ActiveRecord::Base#save}[rdoc-ref:Persistence#save] will raise an ActiveRecord::StatementInvalid - # exception. You can either choose to let this error propagate (which - # will result in the default Rails exception page being shown), or you - # can catch it and restart the transaction (e.g. by telling the user - # that the title already exists, and asking them to re-enter the title). - # This technique is also known as - # {optimistic concurrency control}[http://en.wikipedia.org/wiki/Optimistic_concurrency_control]. - # - # The bundled ActiveRecord::ConnectionAdapters distinguish unique index - # constraint errors from other types of database errors by throwing an - # ActiveRecord::RecordNotUnique exception. For other adapters you will - # have to parse the (database-specific) exception message to detect such - # a case. - # - # The following bundled adapters throw the ActiveRecord::RecordNotUnique exception: - # - # * ActiveRecord::ConnectionAdapters::Mysql2Adapter. - # * ActiveRecord::ConnectionAdapters::SQLite3Adapter. - # * ActiveRecord::ConnectionAdapters::PostgreSQLAdapter. - def validates_uniqueness_of(*attr_names) - validates_with UniquenessValidator, _merge_attributes(attr_names) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/active_record/version.rb b/debian/gems-compat/activerecord-5.1.7/lib/active_record/version.rb deleted file mode 100644 index 146cfacc18..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/active_record/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module ActiveRecord - # Returns the version of the currently loaded ActiveRecord as a Gem::Version - def self.version - gem_version - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record.rb deleted file mode 100644 index 68fca44e3b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "rails/generators/named_base" -require "rails/generators/active_model" -require "rails/generators/active_record/migration" -require "active_record" - -module ActiveRecord - module Generators # :nodoc: - class Base < Rails::Generators::NamedBase # :nodoc: - include ActiveRecord::Generators::Migration - - # Set the current directory as base for the inherited generators. - def self.base_root - File.dirname(__FILE__) - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration.rb deleted file mode 100644 index 47c0981a49..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration.rb +++ /dev/null @@ -1,33 +0,0 @@ -require "rails/generators/migration" - -module ActiveRecord - module Generators # :nodoc: - module Migration - extend ActiveSupport::Concern - include Rails::Generators::Migration - - module ClassMethods - # Implement the required interface for Rails::Generators::Migration. - def next_migration_number(dirname) - next_migration_number = current_migration_number(dirname) + 1 - ActiveRecord::Migration.next_migration_number(next_migration_number) - end - end - - private - - def primary_key_type - key_type = options[:primary_key_type] - ", id: :#{key_type}" if key_type - end - - def db_migrate_path - if defined?(Rails.application) && Rails.application - Rails.application.config.paths["db/migrate"].to_ary.first - else - "db/migrate" - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/migration_generator.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/migration_generator.rb deleted file mode 100644 index 1f1c47499b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/migration_generator.rb +++ /dev/null @@ -1,76 +0,0 @@ -require "rails/generators/active_record" - -module ActiveRecord - module Generators # :nodoc: - class MigrationGenerator < Base # :nodoc: - argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" - - class_option :primary_key_type, type: :string, desc: "The type for primary key" - - def create_migration_file - set_local_assigns! - validate_file_name! - migration_template @migration_template, File.join(db_migrate_path, "#{file_name}.rb") - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - attr_reader :migration_action, :join_tables - - private - - # Sets the default migration template that is being used for the generation of the migration. - # Depending on command line arguments, the migration template and the table name instance - # variables are set up. - def set_local_assigns! - @migration_template = "migration.rb" - case file_name - when /^(add|remove)_.*_(?:to|from)_(.*)/ - @migration_action = $1 - @table_name = normalize_table_name($2) - when /join_table/ - if attributes.length == 2 - @migration_action = "join" - @join_tables = pluralize_table_names? ? attributes.map(&:plural_name) : attributes.map(&:singular_name) - - set_index_names - end - when /^create_(.+)/ - @table_name = normalize_table_name($1) - @migration_template = "create_table_migration.rb" - end - end - - def set_index_names - attributes.each_with_index do |attr, i| - attr.index_name = [attr, attributes[i - 1]].map { |a| index_name_for(a) } - end - end - - def index_name_for(attribute) - if attribute.foreign_key? - attribute.name - else - attribute.name.singularize.foreign_key - end.to_sym - end - - def attributes_with_index - attributes.select { |a| !a.reference? && a.has_index? } - end - - # A migration file name can only contain underscores (_), lowercase characters, - # and numbers 0-9. Any other file name will raise an IllegalMigrationNameError. - def validate_file_name! - unless /^[_a-z0-9]+$/.match?(file_name) - raise IllegalMigrationNameError.new(file_name) - end - end - - def normalize_table_name(_table_name) - pluralize_table_names? ? _table_name.pluralize : _table_name.singularize - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/templates/create_table_migration.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/templates/create_table_migration.rb deleted file mode 100644 index 5f7201cfe1..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +++ /dev/null @@ -1,24 +0,0 @@ -class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>] - def change - create_table :<%= table_name %><%= primary_key_type %> do |t| -<% attributes.each do |attribute| -%> -<% if attribute.password_digest? -%> - t.string :password_digest<%= attribute.inject_options %> -<% elsif attribute.token? -%> - t.string :<%= attribute.name %><%= attribute.inject_options %> -<% else -%> - t.<%= attribute.type %> :<%= attribute.name %><%= attribute.inject_options %> -<% end -%> -<% end -%> -<% if options[:timestamps] %> - t.timestamps -<% end -%> - end -<% attributes.select(&:token?).each do |attribute| -%> - add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true -<% end -%> -<% attributes_with_index.each do |attribute| -%> - add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> -<% end -%> - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/templates/migration.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/templates/migration.rb deleted file mode 100644 index 481c70201b..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/migration/templates/migration.rb +++ /dev/null @@ -1,46 +0,0 @@ -class <%= migration_class_name %> < ActiveRecord::Migration[<%= ActiveRecord::Migration.current_version %>] -<%- if migration_action == 'add' -%> - def change -<% attributes.each do |attribute| -%> - <%- if attribute.reference? -%> - add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %> - <%- elsif attribute.token? -%> - add_column :<%= table_name %>, :<%= attribute.name %>, :string<%= attribute.inject_options %> - add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %>, unique: true - <%- else -%> - add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %> - <%- if attribute.has_index? -%> - add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> - <%- end -%> - <%- end -%> -<%- end -%> - end -<%- elsif migration_action == 'join' -%> - def change - create_join_table :<%= join_tables.first %>, :<%= join_tables.second %> do |t| - <%- attributes.each do |attribute| -%> - <%- if attribute.reference? -%> - t.references :<%= attribute.name %><%= attribute.inject_options %> - <%- else -%> - <%= '# ' unless attribute.has_index? -%>t.index <%= attribute.index_name %><%= attribute.inject_index_options %> - <%- end -%> - <%- end -%> - end - end -<%- else -%> - def change -<% attributes.each do |attribute| -%> -<%- if migration_action -%> - <%- if attribute.reference? -%> - remove_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %> - <%- else -%> - <%- if attribute.has_index? -%> - remove_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> - <%- end -%> - remove_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %> - <%- end -%> -<%- end -%> -<%- end -%> - end -<%- end -%> -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/model_generator.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/model_generator.rb deleted file mode 100644 index 5cec07d2e3..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/model_generator.rb +++ /dev/null @@ -1,69 +0,0 @@ -require "rails/generators/active_record" - -module ActiveRecord - module Generators # :nodoc: - class ModelGenerator < Base # :nodoc: - argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" - - check_class_collision - - class_option :migration, type: :boolean - class_option :timestamps, type: :boolean - class_option :parent, type: :string, desc: "The parent class for the generated model" - class_option :indexes, type: :boolean, default: true, desc: "Add indexes for references and belongs_to columns" - class_option :primary_key_type, type: :string, desc: "The type for primary key" - - # creates the migration file for the model. - def create_migration_file - return unless options[:migration] && options[:parent].nil? - attributes.each { |a| a.attr_options.delete(:index) if a.reference? && !a.has_index? } if options[:indexes] == false - migration_template "../../migration/templates/create_table_migration.rb", File.join(db_migrate_path, "create_#{table_name}.rb") - end - - def create_model_file - generate_application_record - template "model.rb", File.join("app/models", class_path, "#{file_name}.rb") - end - - def create_module_file - return if regular_class_path.empty? - generate_application_record - template "module.rb", File.join("app/models", "#{class_path.join('/')}.rb") if behavior == :invoke - end - - hook_for :test_framework - - private - - def attributes_with_index - attributes.select { |a| !a.reference? && a.has_index? } - end - - # FIXME: Change this file to a symlink once RubyGems 2.5.0 is required. - def generate_application_record - if behavior == :invoke && !application_record_exist? - template "application_record.rb", application_record_file_name - end - end - - # Used by the migration template to determine the parent name of the model - def parent_class_name - options[:parent] || "ApplicationRecord" - end - - def application_record_exist? - file_exist = nil - in_root { file_exist = File.exist?(application_record_file_name) } - file_exist - end - - def application_record_file_name - @application_record_file_name ||= if mountable_engine? - "app/models/#{namespaced_path}/application_record.rb" - else - "app/models/application_record.rb" - end - end - end - end -end diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/application_record.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/application_record.rb deleted file mode 100644 index 60050e0bf8..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/application_record.rb +++ /dev/null @@ -1,5 +0,0 @@ -<% module_namespacing do -%> -class ApplicationRecord < ActiveRecord::Base - self.abstract_class = true -end -<% end -%> diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/model.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/model.rb deleted file mode 100644 index 55dc65c8ad..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/model.rb +++ /dev/null @@ -1,13 +0,0 @@ -<% module_namespacing do -%> -class <%= class_name %> < <%= parent_class_name.classify %> -<% attributes.select(&:reference?).each do |attribute| -%> - belongs_to :<%= attribute.name %><%= ', polymorphic: true' if attribute.polymorphic? %><%= ', required: true' if attribute.required? %> -<% end -%> -<% attributes.select(&:token?).each do |attribute| -%> - has_secure_token<% if attribute.name != "token" %> :<%= attribute.name %><% end %> -<% end -%> -<% if attributes.any?(&:password_digest?) -%> - has_secure_password -<% end -%> -end -<% end -%> diff --git a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/module.rb b/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/module.rb deleted file mode 100644 index a3bf1c37b6..0000000000 --- a/debian/gems-compat/activerecord-5.1.7/lib/rails/generators/active_record/model/templates/module.rb +++ /dev/null @@ -1,7 +0,0 @@ -<% module_namespacing do -%> -module <%= class_path.map(&:camelize).join('::') %> - def self.table_name_prefix - '<%= namespaced? ? namespaced_class_path.join('_') : class_path.join('_') %>_' - end -end -<% end -%> diff --git a/debian/gems-compat/activesupport-5.1.7/CHANGELOG.md b/debian/gems-compat/activesupport-5.1.7/CHANGELOG.md deleted file mode 100644 index 4e386f04bc..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,788 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* No changes. - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* Return all mappings for a timezone identifier in `country_zones` - - Some timezones like `Europe/London` have multiple mappings in - `ActiveSupport::TimeZone::MAPPING` so return all of them instead - of the first one found by using `Hash#value`. e.g: - - # Before - ActiveSupport::TimeZone.country_zones("GB") # => ["Edinburgh"] - - # After - ActiveSupport::TimeZone.country_zones("GB") # => ["Edinburgh", "London"] - - Fixes #31668. - - *Andrew White* - - -## Rails 5.1.5 (February 14, 2018) ## - -* No changes. - - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* No changes. - - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* Fix modulo operations involving durations - - Rails 5.1 introduce an `ActiveSupport::Duration::Scalar` class as a wrapper - around a numeric value as a way of ensuring a duration was the outcome of - an expression. However the implementation was missing support for modulo - operations. This support has now been added and should result in a duration - being returned from expressions involving modulo operations. - - Prior to Rails 5.1: - - 5.minutes % 2.minutes - => 60 - - Now: - - 5.minutes % 2.minutes - => 1 minute - - Fixes #29603 and #29743. - - *Sayan Chakraborty*, *Andrew White* - -* Fix division where a duration is the denominator - - PR #29163 introduced a change in behavior when a duration was the denominator - in a calculation - this was incorrect as dividing by a duration should always - return a `Numeric`. The behavior of previous versions of Rails has been restored. - - Fixes #29592. - - *Andrew White* - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* No changes. - - -## Rails 5.1.2 (June 26, 2017) ## - -* Cache: Restore the `options = nil` argument for `LocalStore#clear` - that was removed in 5.1.0. Restores compatibility with backends that - take an options argument and use the local cache strategy. - - *Jeremy Daer* - -* Fix implicit coercion calculations with scalars and durations - - Previously calculations where the scalar is first would be converted to a duration - of seconds but this causes issues with dates being converted to times, e.g: - - Time.zone = "Beijing" # => Asia/Shanghai - date = Date.civil(2017, 5, 20) # => Mon, 20 May 2017 - 2 * 1.day # => 172800 seconds - date + 2 * 1.day # => Mon, 22 May 2017 00:00:00 CST +08:00 - - Now the `ActiveSupport::Duration::Scalar` calculation methods will try to maintain - the part structure of the duration where possible, e.g: - - Time.zone = "Beijing" # => Asia/Shanghai - date = Date.civil(2017, 5, 20) # => Mon, 20 May 2017 - 2 * 1.day # => 2 days - date + 2 * 1.day # => Mon, 22 May 2017 - - Fixes #29160, #28970. - - *Andrew White* - - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* `ActiveSupport::EventedFileUpdateChecker` no longer listens to - directories outside of the application directory. - - *radiospiel* - -* Return unmapped timezones from `country_zones` - - If a country doesn't exist in the MAPPINGS hash then create a new - `ActiveSupport::Timezone` instance using the supplied timezone id. - - Fixes #28431. - - *Andrew White* - -* Add ActiveSupport::Deprecation::DeprecatedConstantAccessor - - Provides transparent deprecation of constants, compatible with exceptions. - Example usage: - - module Example - include ActiveSupport::Deprecation::DeprecatedConstantAccessor - deprecate_constant 'OldException', 'Elsewhere::NewException' - end - - *Dominic Cleal* - -* Fixed bug in `DateAndTime::Compatibility#to_time` that caused it to - raise `RuntimeError: can't modify frozen Time` when called on any frozen `Time`. - Properly pass through the frozen `Time` or `ActiveSupport::TimeWithZone` object - when calling `#to_time`. - - *Kevin McPhillips* & *Andrew White* - -* Remove implicit coercion deprecation of durations - - In #28204 we deprecated implicit conversion of durations to a numeric which - represented the number of seconds in the duration because of unwanted side - effects with calculations on durations and dates. This unfortunately had - the side effect of forcing a explicit cast when configuring third-party - libraries like expiration in Redis, e.g: - - redis.expire("foo", 5.minutes) - - To work around this we've removed the deprecation and added a private class - that wraps the numeric and can perform calculation involving durations and - ensure that they remain a duration irrespective of the order of operations. - - *Andrew White* - -* Update `titleize` regex to allow apostrophes - - In 4b685aa the regex in `titleize` was updated to not match apostrophes to - better reflect the nature of the transformation. Unfortunately, this had the - side effect of breaking capitalization on the first word of a sub-string, e.g: - - >> "This was 'fake news'".titleize - => "This Was 'fake News'" - - This is fixed by extending the look-behind to also check for a word - character on the other side of the apostrophe. - - Fixes #28312. - - *Andrew White* - -* Add `rfc3339` aliases to `xmlschema` for `Time` and `ActiveSupport::TimeWithZone` - - For naming consistency when using the RFC 3339 profile of ISO 8601 in applications. - - *Andrew White* - -* Add `Time.rfc3339` parsing method - - `Time.xmlschema` and consequently its alias `iso8601` accepts timestamps - without a offset in contravention of the RFC 3339 standard. This method - enforces that constraint and raises an `ArgumentError` if it doesn't. - - *Andrew White* - -* Add `ActiveSupport::TimeZone.rfc3339` parsing method - - Previously, there was no way to get a RFC 3339 timestamp into a specific - timezone without either using `parse` or chaining methods. The new method - allows parsing directly into the timezone, e.g: - - >> Time.zone = "Hawaii" - => "Hawaii" - >> Time.zone.rfc3339("1999-12-31T14:00:00Z") - => Fri, 31 Dec 1999 14:00:00 HST -10:00 - - This new method has stricter semantics than the current `parse` method, - and will raise an `ArgumentError` instead of returning nil, e.g: - - >> Time.zone = "Hawaii" - => "Hawaii" - >> Time.zone.rfc3339("foobar") - ArgumentError: invalid date - >> Time.zone.parse("foobar") - => nil - - It will also raise an `ArgumentError` when either the time or offset - components are missing, e.g: - - >> Time.zone = "Hawaii" - => "Hawaii" - >> Time.zone.rfc3339("1999-12-31") - ArgumentError: invalid date - >> Time.zone.rfc3339("1999-12-31T14:00:00") - ArgumentError: invalid date - - *Andrew White* - -* Add `ActiveSupport::TimeZone.iso8601` parsing method - - Previously, there was no way to get a ISO 8601 timestamp into a specific - timezone without either using `parse` or chaining methods. The new method - allows parsing directly into the timezone, e.g: - - >> Time.zone = "Hawaii" - => "Hawaii" - >> Time.zone.iso8601("1999-12-31T14:00:00Z") - => Fri, 31 Dec 1999 14:00:00 HST -10:00 - - If the timestamp is a ISO 8601 date (YYYY-MM-DD), then the time is set - to midnight, e.g: - - >> Time.zone = "Hawaii" - => "Hawaii" - >> Time.zone.iso8601("1999-12-31") - => Fri, 31 Dec 1999 00:00:00 HST -10:00 - - This new method has stricter semantics than the current `parse` method, - and will raise an `ArgumentError` instead of returning nil, e.g: - - >> Time.zone = "Hawaii" - => "Hawaii" - >> Time.zone.iso8601("foobar") - ArgumentError: invalid date - >> Time.zone.parse("foobar") - => nil - - *Andrew White* - -* Deprecate implicit coercion of `ActiveSupport::Duration` - - Currently `ActiveSupport::Duration` implicitly converts to a seconds - value when used in a calculation except for the explicit examples of - addition and subtraction where the duration is the receiver, e.g: - - >> 2 * 1.day - => 172800 - - This results in lots of confusion especially when using durations - with dates because adding/subtracting a value from a date treats - integers as a day and not a second, e.g: - - >> Date.today - => Wed, 01 Mar 2017 - >> Date.today + 2 * 1.day - => Mon, 10 Apr 2490 - - To fix this we're implementing `coerce` so that we can provide a - deprecation warning with the intent of removing the implicit coercion - in Rails 5.2, e.g: - - >> 2 * 1.day - DEPRECATION WARNING: Implicit coercion of ActiveSupport::Duration - to a Numeric is deprecated and will raise a TypeError in Rails 5.2. - => 172800 - - In Rails 5.2 it will raise `TypeError`, e.g: - - >> 2 * 1.day - TypeError: ActiveSupport::Duration can't be coerced into Integer - - This is the same behavior as with other types in Ruby, e.g: - - >> 2 * "foo" - TypeError: String can't be coerced into Integer - >> "foo" * 2 - => "foofoo" - - As part of this deprecation add `*` and `/` methods to `AS::Duration` - so that calculations that keep the duration as the receiver work - correctly whether the final receiver is a `Date` or `Time`, e.g: - - >> Date.today - => Wed, 01 Mar 2017 - >> Date.today + 1.day * 2 - => Fri, 03 Mar 2017 - - Fixes #27457. - - *Andrew White* - -* Update `DateTime#change` to support `:usec` and `:nsec` options. - - Adding support for these options now allows us to update the `DateTime#end_of` - methods to match the equivalent `Time#end_of` methods, e.g: - - datetime = DateTime.now.end_of_day - datetime.nsec == 999999999 # => true - - Fixes #21424. - - *Dan Moore*, *Andrew White* - -* Add `ActiveSupport::Duration#before` and `#after` as aliases for `#until` and `#since` - - These read more like English and require less mental gymnastics to read and write. - - Before: - - 2.weeks.since(customer_start_date) - 5.days.until(today) - - After: - - 2.weeks.after(customer_start_date) - 5.days.before(today) - - *Nick Johnstone* - -* Soft-deprecated the top-level `HashWithIndifferentAccess` constant. - `ActiveSupport::HashWithIndifferentAccess` should be used instead. - - Fixes #28157. - - *Robin Dupret* - -* In Core Extensions, make `MarshalWithAutoloading#load` pass through the second, optional - argument for `Marshal#load( source [, proc] )`. This way we don't have to do - `Marshal.method(:load).super_method.call(source, proc)` just to be able to pass a proc. - - *Jeff Latz* - -* `ActiveSupport::Gzip.decompress` now checks checksum and length in footer. - - *Dylan Thacker-Smith* - -* Cache `ActiveSupport::TimeWithZone#to_datetime` before freezing. - - *Adam Rice* - -* Deprecate `ActiveSupport.halt_callback_chains_on_return_false`. - - *Rafael Mendonça França* - -* Remove deprecated behavior that halts callbacks when the return is false. - - *Rafael Mendonça França* - -* Deprecate passing string to `:if` and `:unless` conditional options - on `set_callback` and `skip_callback`. - - *Ryuta Kamizono* - -* Raise `ArgumentError` when passing string to define callback. - - *Ryuta Kamizono* - -* Updated Unicode version to 9.0.0 - - Now we can handle new emojis such like "👩‍👩‍👧‍👦" ("\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}"). - - version 8.0.0 - - "👩‍👩‍👧‍👦".mb_chars.grapheme_length # => 4 - "👩‍👩‍👧‍👦".mb_chars.reverse # => "👦👧‍👩‍👩‍" - - version 9.0.0 - - "👩‍👩‍👧‍👦".mb_chars.grapheme_length # => 1 - "👩‍👩‍👧‍👦".mb_chars.reverse # => "👩‍👩‍👧‍👦" - - *Fumiaki MATSUSHIMA* - -* Changed `ActiveSupport::Inflector#transliterate` to raise `ArgumentError` when it receives - anything except a string. - - *Kevin McPhillips* - -* Fixed bugs that `StringInquirer#respond_to_missing?` and - `ArrayInquirer#respond_to_missing?` do not fallback to `super`. - - *Akira Matsuda* - -* Fix inconsistent results when parsing large durations and constructing durations from code - - ActiveSupport::Duration.parse('P3Y') == 3.years # It should be true - - Duration parsing made independent from any moment of time: - Fixed length in seconds is assigned to each duration part during parsing. - - Changed duration of months and years in seconds to more accurate and logical: - - 1. The value of 365.2425 days in Gregorian year is more accurate - as it accounts for every 400th non-leap year. - - 2. Month's length is bound to year's duration, which makes - sensible comparisons like `12.months == 1.year` to be `true` - and nonsensical ones like `30.days == 1.month` to be `false`. - - Calculations on times and dates with durations shouldn't be affected as - duration's numeric value isn't used in calculations, only parts are used. - - Methods on `Numeric` like `2.days` now use these predefined durations - to avoid duplication of duration constants through the codebase and - eliminate creation of intermediate durations. - - *Andrey Novikov*, *Andrew White* - -* Change return value of `Rational#duplicable?`, `ComplexClass#duplicable?` - to false. - - *utilum* - -* Change return value of `NilClass#duplicable?`, `FalseClass#duplicable?`, - `TrueClass#duplicable?`, `Symbol#duplicable?` and `Numeric#duplicable?` - to true with Ruby 2.4+. These classes can dup with Ruby 2.4+. - - *Yuji Yaginuma* - -* Remove deprecated class `ActiveSupport::Concurrency::Latch`. - - *Andrew White* - -* Remove deprecated separator argument from `parameterize`. - - *Andrew White* - -* Remove deprecated method `Numeric#to_formatted_s`. - - *Andrew White* - -* Remove deprecated method `alias_method_chain`. - - *Andrew White* - -* Remove deprecated constant `MissingSourceFile`. - - *Andrew White* - -* Remove deprecated methods `Module.qualified_const_defined?`, - `Module.qualified_const_get` and `Module.qualified_const_set`. - - *Andrew White* - -* Remove deprecated `:prefix` option from `number_to_human_size`. - - *Andrew White* - -* Remove deprecated method `ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default`. - - *Andrew White* - -* Remove deprecated file `active_support/core_ext/time/marshal.rb`. - - *Andrew White* - -* Remove deprecated file `active_support/core_ext/struct.rb`. - - *Andrew White* - -* Remove deprecated file `active_support/core_ext/module/method_transplanting.rb`. - - *Andrew White* - -* Remove deprecated method `Module.local_constants`. - - *Andrew White* - -* Remove deprecated file `active_support/core_ext/kernel/debugger.rb`. - - *Andrew White* - -* Remove deprecated method `ActiveSupport::Cache::Store#namespaced_key`. - - *Andrew White* - -* Remove deprecated method `ActiveSupport::Cache::Strategy::LocalCache::LocalStore#set_cache_value`. - - *Andrew White* - -* Remove deprecated method `ActiveSupport::Cache::MemCacheStore#escape_key`. - - *Andrew White* - -* Remove deprecated method `ActiveSupport::Cache::FileStore#key_file_path`. - - *Andrew White* - -* Ensure duration parsing is consistent across DST changes. - - Previously `ActiveSupport::Duration.parse` used `Time.current` and - `Time#advance` to calculate the number of seconds in the duration - from an arbitrary collection of parts. However as `advance` tries to - be consistent across DST boundaries this meant that either the - duration was shorter or longer depending on the time of year. - - This was fixed by using an absolute reference point in UTC which - isn't subject to DST transitions. An arbitrary date of Jan 1st, 2000 - was chosen for no other reason that it seemed appropriate. - - Additionally, duration parsing should now be marginally faster as we - are no longer creating instances of `ActiveSupport::TimeWithZone` - every time we parse a duration string. - - Fixes #26941. - - *Andrew White* - -* Use `Hash#compact` and `Hash#compact!` from Ruby 2.4. Old Ruby versions - will continue to get these methods from Active Support as before. - - *Prathamesh Sonpatki* - -* Fix `ActiveSupport::TimeZone#strptime`. - Support for timestamps in format of seconds (%s) and milliseconds (%Q). - - Fixes #26840. - - *Lev Denisov* - -* Fix `DateAndTime::Calculations#copy_time_to`. Copy `nsec` instead of `usec`. - - Jumping forward or backward between weeks now preserves nanosecond digits. - - *Josua Schmid* - -* Fix `ActiveSupport::TimeWithZone#in` across DST boundaries. - - Previously calls to `in` were being sent to the non-DST aware - method `Time#since` via `method_missing`. It is now aliased to - the DST aware `ActiveSupport::TimeWithZone#+` which handles - transitions across DST boundaries, e.g: - - Time.zone = "US/Eastern" - - t = Time.zone.local(2016,11,6,1) - # => Sun, 06 Nov 2016 01:00:00 EDT -05:00 - - t.in(1.hour) - # => Sun, 06 Nov 2016 01:00:00 EST -05:00 - - Fixes #26580. - - *Thomas Balthazar* - -* Remove unused parameter `options = nil` for `#clear` of - `ActiveSupport::Cache::Strategy::LocalCache::LocalStore` and - `ActiveSupport::Cache::Strategy::LocalCache`. - - *Yosuke Kabuto* - -* Fix `thread_mattr_accessor` subclass no longer overwrites parent. - - Assigning a value to a subclass using `thread_mattr_accessor` no - longer changes the value of the parent class. This brings the - behavior inline with the documentation. - - Given: - - class Account - thread_mattr_accessor :user - end - - class Customer < Account - end - - Account.user = "DHH" - Customer.user = "Rafael" - - Before: - - Account.user # => "Rafael" - - After: - - Account.user # => "DHH" - - *Shinichi Maeshima* - -* Since weeks are no longer converted to days, add `:weeks` to the list of - parts that `ActiveSupport::TimeWithZone` will recognize as possibly being - of variable duration to take account of DST transitions. - - Fixes #26039. - - *Andrew White* - -* Defines `Regexp.match?` for Ruby versions prior to 2.4. The predicate - has the same interface, but it does not have the performance boost. Its - purpose is to be able to write 2.4 compatible code. - - *Xavier Noria* - -* Allow `MessageEncryptor` to take advantage of authenticated encryption modes. - - AEAD modes like `aes-256-gcm` provide both confidentiality and data - authenticity, eliminating the need to use `MessageVerifier` to check if the - encrypted data has been tampered with. This speeds up encryption/decryption - and results in shorter cipher text. - - *Bart de Water* - -* Introduce `assert_changes` and `assert_no_changes`. - - `assert_changes` is a more general `assert_difference` that works with any - value. - - assert_changes 'Error.current', from: nil, to: 'ERR' do - expected_bad_operation - end - - Can be called with strings, to be evaluated in the binding (context) of - the block given to the assertion, or a lambda. - - assert_changes -> { Error.current }, from: nil, to: 'ERR' do - expected_bad_operation - end - - The `from` and `to` arguments are compared with the case operator (`===`). - - assert_changes 'Error.current', from: nil, to: Error do - expected_bad_operation - end - - This is pretty useful, if you need to loosely compare a value. For example, - you need to test a token has been generated and it has that many random - characters. - - user = User.start_registration - assert_changes 'user.token', to: /\w{32}/ do - user.finish_registration - end - - *Genadi Samokovarov* - -* Fix `ActiveSupport::TimeZone#strptime`. Now raises `ArgumentError` when the - given time doesn't match the format. The error is the same as the one given - by Ruby's `Date.strptime`. Previously it raised - `NoMethodError: undefined method empty? for nil:NilClass.` due to a bug. - - Fixes #25701. - - *John Gesimondo* - -* `travel/travel_to` travel time helpers, now raise on nested calls, - as this can lead to confusing time stubbing. - - Instead of: - - travel_to 2.days.from_now do - # 2 days from today - travel_to 3.days.from_now do - # 5 days from today - end - end - - preferred way to achieve above is: - - travel 2.days do - # 2 days from today - end - - travel 5.days do - # 5 days from today - end - - *Vipul A M* - -* Support parsing JSON time in ISO8601 local time strings in - `ActiveSupport::JSON.decode` when `parse_json_times` is enabled. - Strings in the format of `YYYY-MM-DD hh:mm:ss` (without a `Z` at - the end) will be parsed in the local timezone (`Time.zone`). In - addition, date strings (`YYYY-MM-DD`) are now parsed into `Date` - objects. - - *Grzegorz Witek* - -* Fixed `ActiveSupport::Logger.broadcast` so that calls to `#silence` now - properly delegate to all loggers. Silencing now properly suppresses logging - to both the log and the console. - - *Kevin McPhillips* - -* Remove deprecated arguments in `assert_nothing_raised`. - - *Rafel Mendonça França* - -* `Date.to_s` doesn't produce too many spaces. For example, `to_s(:short)` - will now produce `01 Feb` instead of ` 1 Feb`. - - Fixes #25251. - - *Sean Griffin* - -* Introduce `Module#delegate_missing_to`. - - When building a decorator, a common pattern emerges: - - class Partition - def initialize(first_event) - @events = [ first_event ] - end - - def people - if @events.first.detail.people.any? - @events.collect { |e| Array(e.detail.people) }.flatten.uniq - else - @events.collect(&:creator).uniq - end - end - - private - def respond_to_missing?(name, include_private = false) - @events.respond_to?(name, include_private) - end - - def method_missing(method, *args, &block) - @events.send(method, *args, &block) - end - end - - With `Module#delegate_missing_to`, the above is condensed to: - - class Partition - delegate_missing_to :@events - - def initialize(first_event) - @events = [ first_event ] - end - - def people - if @events.first.detail.people.any? - @events.collect { |e| Array(e.detail.people) }.flatten.uniq - else - @events.collect(&:creator).uniq - end - end - end - - *Genadi Samokovarov*, *DHH* - -* Rescuable: If a handler doesn't match the exception, check for handlers - matching the exception's cause. - - *Jeremy Daer* - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activesupport/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/activesupport-5.1.7/MIT-LICENSE b/debian/gems-compat/activesupport-5.1.7/MIT-LICENSE deleted file mode 100644 index 6b3cead1a7..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2005-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/activesupport-5.1.7/README.rdoc b/debian/gems-compat/activesupport-5.1.7/README.rdoc deleted file mode 100644 index 14ce204303..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/README.rdoc +++ /dev/null @@ -1,39 +0,0 @@ -= Active Support -- Utility classes and Ruby extensions from Rails - -Active Support is a collection of utility classes and standard library -extensions that were found useful for the Rails framework. These additions -reside in this package so they can be loaded as needed in Ruby projects -outside of Rails. - - -== Download and installation - -The latest version of Active Support can be installed with RubyGems: - - $ gem install activesupport - -Source code can be downloaded as part of the Rails project on GitHub: - -* https://github.com/rails/rails/tree/master/activesupport - - -== License - -Active Support is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - - -== Support - -API documentation is at: - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core diff --git a/debian/gems-compat/activesupport-5.1.7/activesupport.gemspec b/debian/gems-compat/activesupport-5.1.7/activesupport.gemspec deleted file mode 100644 index 294bb3bad3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/activesupport.gemspec +++ /dev/null @@ -1,46 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: activesupport 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "activesupport".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/activesupport/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/activesupport" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.".freeze - s.email = "david@loudthinking.com".freeze - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "README.rdoc".freeze, "lib/active_support.rb".freeze, "lib/active_support/all.rb".freeze, "lib/active_support/array_inquirer.rb".freeze, "lib/active_support/backtrace_cleaner.rb".freeze, "lib/active_support/benchmarkable.rb".freeze, "lib/active_support/builder.rb".freeze, "lib/active_support/cache.rb".freeze, "lib/active_support/cache/file_store.rb".freeze, "lib/active_support/cache/mem_cache_store.rb".freeze, "lib/active_support/cache/memory_store.rb".freeze, "lib/active_support/cache/null_store.rb".freeze, "lib/active_support/cache/strategy/local_cache.rb".freeze, "lib/active_support/cache/strategy/local_cache_middleware.rb".freeze, "lib/active_support/callbacks.rb".freeze, "lib/active_support/concern.rb".freeze, "lib/active_support/concurrency/load_interlock_aware_monitor.rb".freeze, "lib/active_support/concurrency/share_lock.rb".freeze, "lib/active_support/configurable.rb".freeze, "lib/active_support/core_ext.rb".freeze, "lib/active_support/core_ext/array.rb".freeze, "lib/active_support/core_ext/array/access.rb".freeze, "lib/active_support/core_ext/array/conversions.rb".freeze, "lib/active_support/core_ext/array/extract_options.rb".freeze, "lib/active_support/core_ext/array/grouping.rb".freeze, "lib/active_support/core_ext/array/inquiry.rb".freeze, "lib/active_support/core_ext/array/prepend_and_append.rb".freeze, "lib/active_support/core_ext/array/wrap.rb".freeze, "lib/active_support/core_ext/benchmark.rb".freeze, "lib/active_support/core_ext/big_decimal.rb".freeze, "lib/active_support/core_ext/big_decimal/conversions.rb".freeze, "lib/active_support/core_ext/class.rb".freeze, "lib/active_support/core_ext/class/attribute.rb".freeze, "lib/active_support/core_ext/class/attribute_accessors.rb".freeze, "lib/active_support/core_ext/class/subclasses.rb".freeze, "lib/active_support/core_ext/date.rb".freeze, "lib/active_support/core_ext/date/acts_like.rb".freeze, "lib/active_support/core_ext/date/blank.rb".freeze, "lib/active_support/core_ext/date/calculations.rb".freeze, "lib/active_support/core_ext/date/conversions.rb".freeze, "lib/active_support/core_ext/date/zones.rb".freeze, "lib/active_support/core_ext/date_and_time/calculations.rb".freeze, "lib/active_support/core_ext/date_and_time/compatibility.rb".freeze, "lib/active_support/core_ext/date_and_time/zones.rb".freeze, "lib/active_support/core_ext/date_time.rb".freeze, "lib/active_support/core_ext/date_time/acts_like.rb".freeze, "lib/active_support/core_ext/date_time/blank.rb".freeze, "lib/active_support/core_ext/date_time/calculations.rb".freeze, "lib/active_support/core_ext/date_time/compatibility.rb".freeze, "lib/active_support/core_ext/date_time/conversions.rb".freeze, "lib/active_support/core_ext/digest/uuid.rb".freeze, "lib/active_support/core_ext/enumerable.rb".freeze, "lib/active_support/core_ext/file.rb".freeze, "lib/active_support/core_ext/file/atomic.rb".freeze, "lib/active_support/core_ext/hash.rb".freeze, "lib/active_support/core_ext/hash/compact.rb".freeze, "lib/active_support/core_ext/hash/conversions.rb".freeze, "lib/active_support/core_ext/hash/deep_merge.rb".freeze, "lib/active_support/core_ext/hash/except.rb".freeze, "lib/active_support/core_ext/hash/indifferent_access.rb".freeze, "lib/active_support/core_ext/hash/keys.rb".freeze, "lib/active_support/core_ext/hash/reverse_merge.rb".freeze, "lib/active_support/core_ext/hash/slice.rb".freeze, "lib/active_support/core_ext/hash/transform_values.rb".freeze, "lib/active_support/core_ext/integer.rb".freeze, "lib/active_support/core_ext/integer/inflections.rb".freeze, "lib/active_support/core_ext/integer/multiple.rb".freeze, "lib/active_support/core_ext/integer/time.rb".freeze, "lib/active_support/core_ext/kernel.rb".freeze, "lib/active_support/core_ext/kernel/agnostics.rb".freeze, "lib/active_support/core_ext/kernel/concern.rb".freeze, "lib/active_support/core_ext/kernel/reporting.rb".freeze, "lib/active_support/core_ext/kernel/singleton_class.rb".freeze, "lib/active_support/core_ext/load_error.rb".freeze, "lib/active_support/core_ext/marshal.rb".freeze, "lib/active_support/core_ext/module.rb".freeze, "lib/active_support/core_ext/module/aliasing.rb".freeze, "lib/active_support/core_ext/module/anonymous.rb".freeze, "lib/active_support/core_ext/module/attr_internal.rb".freeze, "lib/active_support/core_ext/module/attribute_accessors.rb".freeze, "lib/active_support/core_ext/module/attribute_accessors_per_thread.rb".freeze, "lib/active_support/core_ext/module/concerning.rb".freeze, "lib/active_support/core_ext/module/delegation.rb".freeze, "lib/active_support/core_ext/module/deprecation.rb".freeze, "lib/active_support/core_ext/module/introspection.rb".freeze, "lib/active_support/core_ext/module/reachable.rb".freeze, "lib/active_support/core_ext/module/remove_method.rb".freeze, "lib/active_support/core_ext/name_error.rb".freeze, "lib/active_support/core_ext/numeric.rb".freeze, "lib/active_support/core_ext/numeric/bytes.rb".freeze, "lib/active_support/core_ext/numeric/conversions.rb".freeze, "lib/active_support/core_ext/numeric/inquiry.rb".freeze, "lib/active_support/core_ext/numeric/time.rb".freeze, "lib/active_support/core_ext/object.rb".freeze, "lib/active_support/core_ext/object/acts_like.rb".freeze, "lib/active_support/core_ext/object/blank.rb".freeze, "lib/active_support/core_ext/object/conversions.rb".freeze, "lib/active_support/core_ext/object/deep_dup.rb".freeze, "lib/active_support/core_ext/object/duplicable.rb".freeze, "lib/active_support/core_ext/object/inclusion.rb".freeze, "lib/active_support/core_ext/object/instance_variables.rb".freeze, "lib/active_support/core_ext/object/json.rb".freeze, "lib/active_support/core_ext/object/to_param.rb".freeze, "lib/active_support/core_ext/object/to_query.rb".freeze, "lib/active_support/core_ext/object/try.rb".freeze, "lib/active_support/core_ext/object/with_options.rb".freeze, "lib/active_support/core_ext/range.rb".freeze, "lib/active_support/core_ext/range/conversions.rb".freeze, "lib/active_support/core_ext/range/each.rb".freeze, "lib/active_support/core_ext/range/include_range.rb".freeze, "lib/active_support/core_ext/range/overlaps.rb".freeze, "lib/active_support/core_ext/regexp.rb".freeze, "lib/active_support/core_ext/securerandom.rb".freeze, "lib/active_support/core_ext/string.rb".freeze, "lib/active_support/core_ext/string/access.rb".freeze, "lib/active_support/core_ext/string/behavior.rb".freeze, "lib/active_support/core_ext/string/conversions.rb".freeze, "lib/active_support/core_ext/string/exclude.rb".freeze, "lib/active_support/core_ext/string/filters.rb".freeze, "lib/active_support/core_ext/string/indent.rb".freeze, "lib/active_support/core_ext/string/inflections.rb".freeze, "lib/active_support/core_ext/string/inquiry.rb".freeze, "lib/active_support/core_ext/string/multibyte.rb".freeze, "lib/active_support/core_ext/string/output_safety.rb".freeze, "lib/active_support/core_ext/string/starts_ends_with.rb".freeze, "lib/active_support/core_ext/string/strip.rb".freeze, "lib/active_support/core_ext/string/zones.rb".freeze, "lib/active_support/core_ext/time.rb".freeze, "lib/active_support/core_ext/time/acts_like.rb".freeze, "lib/active_support/core_ext/time/calculations.rb".freeze, "lib/active_support/core_ext/time/compatibility.rb".freeze, "lib/active_support/core_ext/time/conversions.rb".freeze, "lib/active_support/core_ext/time/zones.rb".freeze, "lib/active_support/core_ext/uri.rb".freeze, "lib/active_support/dependencies.rb".freeze, "lib/active_support/dependencies/autoload.rb".freeze, "lib/active_support/dependencies/interlock.rb".freeze, "lib/active_support/deprecation.rb".freeze, "lib/active_support/deprecation/behaviors.rb".freeze, "lib/active_support/deprecation/constant_accessor.rb".freeze, "lib/active_support/deprecation/instance_delegator.rb".freeze, "lib/active_support/deprecation/method_wrappers.rb".freeze, "lib/active_support/deprecation/proxy_wrappers.rb".freeze, "lib/active_support/deprecation/reporting.rb".freeze, "lib/active_support/descendants_tracker.rb".freeze, "lib/active_support/duration.rb".freeze, "lib/active_support/duration/iso8601_parser.rb".freeze, "lib/active_support/duration/iso8601_serializer.rb".freeze, "lib/active_support/evented_file_update_checker.rb".freeze, "lib/active_support/execution_wrapper.rb".freeze, "lib/active_support/executor.rb".freeze, "lib/active_support/file_update_checker.rb".freeze, "lib/active_support/gem_version.rb".freeze, "lib/active_support/gzip.rb".freeze, "lib/active_support/hash_with_indifferent_access.rb".freeze, "lib/active_support/i18n.rb".freeze, "lib/active_support/i18n_railtie.rb".freeze, "lib/active_support/inflections.rb".freeze, "lib/active_support/inflector.rb".freeze, "lib/active_support/inflector/inflections.rb".freeze, "lib/active_support/inflector/methods.rb".freeze, "lib/active_support/inflector/transliterate.rb".freeze, "lib/active_support/json.rb".freeze, "lib/active_support/json/decoding.rb".freeze, "lib/active_support/json/encoding.rb".freeze, "lib/active_support/key_generator.rb".freeze, "lib/active_support/lazy_load_hooks.rb".freeze, "lib/active_support/locale/en.yml".freeze, "lib/active_support/log_subscriber.rb".freeze, "lib/active_support/log_subscriber/test_helper.rb".freeze, "lib/active_support/logger.rb".freeze, "lib/active_support/logger_silence.rb".freeze, "lib/active_support/logger_thread_safe_level.rb".freeze, "lib/active_support/message_encryptor.rb".freeze, "lib/active_support/message_verifier.rb".freeze, "lib/active_support/multibyte.rb".freeze, "lib/active_support/multibyte/chars.rb".freeze, "lib/active_support/multibyte/unicode.rb".freeze, "lib/active_support/notifications.rb".freeze, "lib/active_support/notifications/fanout.rb".freeze, "lib/active_support/notifications/instrumenter.rb".freeze, "lib/active_support/number_helper.rb".freeze, "lib/active_support/number_helper/number_converter.rb".freeze, "lib/active_support/number_helper/number_to_currency_converter.rb".freeze, "lib/active_support/number_helper/number_to_delimited_converter.rb".freeze, "lib/active_support/number_helper/number_to_human_converter.rb".freeze, "lib/active_support/number_helper/number_to_human_size_converter.rb".freeze, "lib/active_support/number_helper/number_to_percentage_converter.rb".freeze, "lib/active_support/number_helper/number_to_phone_converter.rb".freeze, "lib/active_support/number_helper/number_to_rounded_converter.rb".freeze, "lib/active_support/number_helper/rounding_helper.rb".freeze, "lib/active_support/option_merger.rb".freeze, "lib/active_support/ordered_hash.rb".freeze, "lib/active_support/ordered_options.rb".freeze, "lib/active_support/per_thread_registry.rb".freeze, "lib/active_support/proxy_object.rb".freeze, "lib/active_support/rails.rb".freeze, "lib/active_support/railtie.rb".freeze, "lib/active_support/reloader.rb".freeze, "lib/active_support/rescuable.rb".freeze, "lib/active_support/security_utils.rb".freeze, "lib/active_support/string_inquirer.rb".freeze, "lib/active_support/subscriber.rb".freeze, "lib/active_support/tagged_logging.rb".freeze, "lib/active_support/test_case.rb".freeze, "lib/active_support/testing/assertions.rb".freeze, "lib/active_support/testing/autorun.rb".freeze, "lib/active_support/testing/constant_lookup.rb".freeze, "lib/active_support/testing/declarative.rb".freeze, "lib/active_support/testing/deprecation.rb".freeze, "lib/active_support/testing/file_fixtures.rb".freeze, "lib/active_support/testing/isolation.rb".freeze, "lib/active_support/testing/method_call_assertions.rb".freeze, "lib/active_support/testing/setup_and_teardown.rb".freeze, "lib/active_support/testing/stream.rb".freeze, "lib/active_support/testing/tagged_logging.rb".freeze, "lib/active_support/testing/time_helpers.rb".freeze, "lib/active_support/time.rb".freeze, "lib/active_support/time_with_zone.rb".freeze, "lib/active_support/values/time_zone.rb".freeze, "lib/active_support/values/unicode_tables.dat".freeze, "lib/active_support/version.rb".freeze, "lib/active_support/xml_mini.rb".freeze, "lib/active_support/xml_mini/jdom.rb".freeze, "lib/active_support/xml_mini/libxml.rb".freeze, "lib/active_support/xml_mini/libxmlsax.rb".freeze, "lib/active_support/xml_mini/nokogiri.rb".freeze, "lib/active_support/xml_mini/nokogirisax.rb".freeze, "lib/active_support/xml_mini/rexml.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.rdoc_options = ["--encoding".freeze, "UTF-8".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.rubygems_version = "2.7.6.2".freeze - s.summary = "A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, [">= 1.0.2", "~> 1.0"]) - s.add_runtime_dependency(%q.freeze, ["< 2", ">= 0.7"]) - s.add_runtime_dependency(%q.freeze, ["~> 5.1"]) - s.add_runtime_dependency(%q.freeze, ["~> 1.1"]) - else - s.add_dependency(%q.freeze, [">= 1.0.2", "~> 1.0"]) - s.add_dependency(%q.freeze, ["< 2", ">= 0.7"]) - s.add_dependency(%q.freeze, ["~> 5.1"]) - s.add_dependency(%q.freeze, ["~> 1.1"]) - end - else - s.add_dependency(%q.freeze, [">= 1.0.2", "~> 1.0"]) - s.add_dependency(%q.freeze, ["< 2", ">= 0.7"]) - s.add_dependency(%q.freeze, ["~> 5.1"]) - s.add_dependency(%q.freeze, ["~> 1.1"]) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support.rb deleted file mode 100644 index 03e3ce821a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support.rb +++ /dev/null @@ -1,103 +0,0 @@ -#-- -# Copyright (c) 2005-2017 David Heinemeier Hansson -# -# Permission is hereby granted, free of charge, to any person obtaining -# a copy of this software and associated documentation files (the -# "Software"), to deal in the Software without restriction, including -# without limitation the rights to use, copy, modify, merge, publish, -# distribute, sublicense, and/or sell copies of the Software, and to -# permit persons to whom the Software is furnished to do so, subject to -# the following conditions: -# -# The above copyright notice and this permission notice shall be -# included in all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -#++ - -require "securerandom" -require "active_support/dependencies/autoload" -require "active_support/version" -require "active_support/logger" -require "active_support/lazy_load_hooks" -require "active_support/core_ext/date_and_time/compatibility" - -module ActiveSupport - extend ActiveSupport::Autoload - - autoload :Concern - autoload :Dependencies - autoload :DescendantsTracker - autoload :ExecutionWrapper - autoload :Executor - autoload :FileUpdateChecker - autoload :EventedFileUpdateChecker - autoload :LogSubscriber - autoload :Notifications - autoload :Reloader - - eager_autoload do - autoload :BacktraceCleaner - autoload :ProxyObject - autoload :Benchmarkable - autoload :Cache - autoload :Callbacks - autoload :Configurable - autoload :Deprecation - autoload :Gzip - autoload :Inflector - autoload :JSON - autoload :KeyGenerator - autoload :MessageEncryptor - autoload :MessageVerifier - autoload :Multibyte - autoload :NumberHelper - autoload :OptionMerger - autoload :OrderedHash - autoload :OrderedOptions - autoload :StringInquirer - autoload :TaggedLogging - autoload :XmlMini - autoload :ArrayInquirer - end - - autoload :Rescuable - autoload :SafeBuffer, "active_support/core_ext/string/output_safety" - autoload :TestCase - - def self.eager_load! - super - - NumberHelper.eager_load! - end - - cattr_accessor :test_order # :nodoc: - - def self.halt_callback_chains_on_return_false - ActiveSupport::Deprecation.warn(<<-MSG.squish) - ActiveSupport.halt_callback_chains_on_return_false is deprecated and will be removed in Rails 5.2. - MSG - end - - def self.halt_callback_chains_on_return_false=(value) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - ActiveSupport.halt_callback_chains_on_return_false= is deprecated and will be removed in Rails 5.2. - MSG - end - - def self.to_time_preserves_timezone - DateAndTime::Compatibility.preserve_timezone - end - - def self.to_time_preserves_timezone=(value) - DateAndTime::Compatibility.preserve_timezone = value - end -end - -autoload :I18n, "active_support/i18n" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/all.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/all.rb deleted file mode 100644 index 72a23075af..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/all.rb +++ /dev/null @@ -1,3 +0,0 @@ -require "active_support" -require "active_support/time" -require "active_support/core_ext" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/array_inquirer.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/array_inquirer.rb deleted file mode 100644 index befa1746c6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/array_inquirer.rb +++ /dev/null @@ -1,46 +0,0 @@ -module ActiveSupport - # Wrapping an array in an +ArrayInquirer+ gives a friendlier way to check - # its string-like contents: - # - # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet]) - # - # variants.phone? # => true - # variants.tablet? # => true - # variants.desktop? # => false - class ArrayInquirer < Array - # Passes each element of +candidates+ collection to ArrayInquirer collection. - # The method returns true if any element from the ArrayInquirer collection - # is equal to the stringified or symbolized form of any element in the +candidates+ collection. - # - # If +candidates+ collection is not given, method returns true. - # - # variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet]) - # - # variants.any? # => true - # variants.any?(:phone, :tablet) # => true - # variants.any?('phone', 'desktop') # => true - # variants.any?(:desktop, :watch) # => false - def any?(*candidates) - if candidates.none? - super - else - candidates.any? do |candidate| - include?(candidate.to_sym) || include?(candidate.to_s) - end - end - end - - private - def respond_to_missing?(name, include_private = false) - (name[-1] == "?") || super - end - - def method_missing(name, *args) - if name[-1] == "?" - any?(name[0..-2]) - else - super - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/backtrace_cleaner.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/backtrace_cleaner.rb deleted file mode 100644 index e47c90597f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/backtrace_cleaner.rb +++ /dev/null @@ -1,103 +0,0 @@ -module ActiveSupport - # Backtraces often include many lines that are not relevant for the context - # under review. This makes it hard to find the signal amongst the backtrace - # noise, and adds debugging time. With a BacktraceCleaner, filters and - # silencers are used to remove the noisy lines, so that only the most relevant - # lines remain. - # - # Filters are used to modify lines of data, while silencers are used to remove - # lines entirely. The typical filter use case is to remove lengthy path - # information from the start of each line, and view file paths relevant to the - # app directory instead of the file system root. The typical silencer use case - # is to exclude the output of a noisy library from the backtrace, so that you - # can focus on the rest. - # - # bc = ActiveSupport::BacktraceCleaner.new - # bc.add_filter { |line| line.gsub(Rails.root.to_s, '') } # strip the Rails.root prefix - # bc.add_silencer { |line| line =~ /puma|rubygems/ } # skip any lines from puma or rubygems - # bc.clean(exception.backtrace) # perform the cleanup - # - # To reconfigure an existing BacktraceCleaner (like the default one in Rails) - # and show as much data as possible, you can always call - # BacktraceCleaner#remove_silencers!, which will restore the - # backtrace to a pristine state. If you need to reconfigure an existing - # BacktraceCleaner so that it does not filter or modify the paths of any lines - # of the backtrace, you can call BacktraceCleaner#remove_filters! - # These two methods will give you a completely untouched backtrace. - # - # Inspired by the Quiet Backtrace gem by thoughtbot. - class BacktraceCleaner - def initialize - @filters, @silencers = [], [] - end - - # Returns the backtrace after all filters and silencers have been run - # against it. Filters run first, then silencers. - def clean(backtrace, kind = :silent) - filtered = filter_backtrace(backtrace) - - case kind - when :silent - silence(filtered) - when :noise - noise(filtered) - else - filtered - end - end - alias :filter :clean - - # Adds a filter from the block provided. Each line in the backtrace will be - # mapped against this filter. - # - # # Will turn "/my/rails/root/app/models/person.rb" into "/app/models/person.rb" - # backtrace_cleaner.add_filter { |line| line.gsub(Rails.root, '') } - def add_filter(&block) - @filters << block - end - - # Adds a silencer from the block provided. If the silencer returns +true+ - # for a given line, it will be excluded from the clean backtrace. - # - # # Will reject all lines that include the word "puma", like "/gems/puma/server.rb" or "/app/my_puma_server/rb" - # backtrace_cleaner.add_silencer { |line| line =~ /puma/ } - def add_silencer(&block) - @silencers << block - end - - # Removes all silencers, but leaves in the filters. Useful if your - # context of debugging suddenly expands as you suspect a bug in one of - # the libraries you use. - def remove_silencers! - @silencers = [] - end - - # Removes all filters, but leaves in the silencers. Useful if you suddenly - # need to see entire filepaths in the backtrace that you had already - # filtered out. - def remove_filters! - @filters = [] - end - - private - def filter_backtrace(backtrace) - @filters.each do |f| - backtrace = backtrace.map { |line| f.call(line) } - end - - backtrace - end - - def silence(backtrace) - @silencers.each do |s| - backtrace = backtrace.reject { |line| s.call(line) } - end - - backtrace - end - - def noise(backtrace) - backtrace - silence(backtrace) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/benchmarkable.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/benchmarkable.rb deleted file mode 100644 index 70493c8da7..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/benchmarkable.rb +++ /dev/null @@ -1,49 +0,0 @@ -require "active_support/core_ext/benchmark" -require "active_support/core_ext/hash/keys" - -module ActiveSupport - module Benchmarkable - # Allows you to measure the execution time of a block in a template and - # records the result to the log. Wrap this block around expensive operations - # or possible bottlenecks to get a time reading for the operation. For - # example, let's say you thought your file processing method was taking too - # long; you could wrap it in a benchmark block. - # - # <% benchmark 'Process data files' do %> - # <%= expensive_files_operation %> - # <% end %> - # - # That would add something like "Process data files (345.2ms)" to the log, - # which you can then use to compare timings when optimizing your code. - # - # You may give an optional logger level (:debug, :info, - # :warn, :error) as the :level option. The - # default logger level value is :info. - # - # <% benchmark 'Low-level files', level: :debug do %> - # <%= lowlevel_files_operation %> - # <% end %> - # - # Finally, you can pass true as the third argument to silence all log - # activity (other than the timing information) from inside the block. This - # is great for boiling down a noisy block to just a single statement that - # produces one log line: - # - # <% benchmark 'Process data files', level: :info, silence: true do %> - # <%= expensive_and_chatty_files_operation %> - # <% end %> - def benchmark(message = "Benchmarking", options = {}) - if logger - options.assert_valid_keys(:level, :silence) - options[:level] ||= :info - - result = nil - ms = Benchmark.ms { result = options[:silence] ? logger.silence { yield } : yield } - logger.send(options[:level], "%s (%.1fms)" % [ message, ms ]) - result - else - yield - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/builder.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/builder.rb deleted file mode 100644 index 0f010c5d96..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/builder.rb +++ /dev/null @@ -1,6 +0,0 @@ -begin - require "builder" -rescue LoadError => e - $stderr.puts "You don't have builder installed in your application. Please add it to your Gemfile and run bundle install" - raise e -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache.rb deleted file mode 100644 index 720d6655bc..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache.rb +++ /dev/null @@ -1,694 +0,0 @@ -require "zlib" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/array/wrap" -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/numeric/bytes" -require "active_support/core_ext/numeric/time" -require "active_support/core_ext/object/to_param" -require "active_support/core_ext/string/inflections" - -module ActiveSupport - # See ActiveSupport::Cache::Store for documentation. - module Cache - autoload :FileStore, "active_support/cache/file_store" - autoload :MemoryStore, "active_support/cache/memory_store" - autoload :MemCacheStore, "active_support/cache/mem_cache_store" - autoload :NullStore, "active_support/cache/null_store" - - # These options mean something to all cache implementations. Individual cache - # implementations may support additional options. - UNIVERSAL_OPTIONS = [:namespace, :compress, :compress_threshold, :expires_in, :race_condition_ttl] - - module Strategy - autoload :LocalCache, "active_support/cache/strategy/local_cache" - end - - class << self - # Creates a new Store object according to the given options. - # - # If no arguments are passed to this method, then a new - # ActiveSupport::Cache::MemoryStore object will be returned. - # - # If you pass a Symbol as the first argument, then a corresponding cache - # store class under the ActiveSupport::Cache namespace will be created. - # For example: - # - # ActiveSupport::Cache.lookup_store(:memory_store) - # # => returns a new ActiveSupport::Cache::MemoryStore object - # - # ActiveSupport::Cache.lookup_store(:mem_cache_store) - # # => returns a new ActiveSupport::Cache::MemCacheStore object - # - # Any additional arguments will be passed to the corresponding cache store - # class's constructor: - # - # ActiveSupport::Cache.lookup_store(:file_store, '/tmp/cache') - # # => same as: ActiveSupport::Cache::FileStore.new('/tmp/cache') - # - # If the first argument is not a Symbol, then it will simply be returned: - # - # ActiveSupport::Cache.lookup_store(MyOwnCacheStore.new) - # # => returns MyOwnCacheStore.new - def lookup_store(*store_option) - store, *parameters = *Array.wrap(store_option).flatten - - case store - when Symbol - retrieve_store_class(store).new(*parameters) - when nil - ActiveSupport::Cache::MemoryStore.new - else - store - end - end - - # Expands out the +key+ argument into a key that can be used for the - # cache store. Optionally accepts a namespace, and all keys will be - # scoped within that namespace. - # - # If the +key+ argument provided is an array, or responds to +to_a+, then - # each of elements in the array will be turned into parameters/keys and - # concatenated into a single key. For example: - # - # ActiveSupport::Cache.expand_cache_key([:foo, :bar]) # => "foo/bar" - # ActiveSupport::Cache.expand_cache_key([:foo, :bar], "namespace") # => "namespace/foo/bar" - # - # The +key+ argument can also respond to +cache_key+ or +to_param+. - def expand_cache_key(key, namespace = nil) - expanded_cache_key = namespace ? "#{namespace}/" : "" - - if prefix = ENV["RAILS_CACHE_ID"] || ENV["RAILS_APP_VERSION"] - expanded_cache_key << "#{prefix}/" - end - - expanded_cache_key << retrieve_cache_key(key) - expanded_cache_key - end - - private - def retrieve_cache_key(key) - case - when key.respond_to?(:cache_key) then key.cache_key - when key.is_a?(Array) then key.map { |element| retrieve_cache_key(element) }.to_param - when key.respond_to?(:to_a) then retrieve_cache_key(key.to_a) - else key.to_param - end.to_s - end - - # Obtains the specified cache store class, given the name of the +store+. - # Raises an error when the store class cannot be found. - def retrieve_store_class(store) - require "active_support/cache/#{store}" - rescue LoadError => e - raise "Could not find cache store adapter for #{store} (#{e})" - else - ActiveSupport::Cache.const_get(store.to_s.camelize) - end - end - - # An abstract cache store class. There are multiple cache store - # implementations, each having its own additional features. See the classes - # under the ActiveSupport::Cache module, e.g. - # ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most - # popular cache store for large production websites. - # - # Some implementations may not support all methods beyond the basic cache - # methods of +fetch+, +write+, +read+, +exist?+, and +delete+. - # - # ActiveSupport::Cache::Store can store any serializable Ruby object. - # - # cache = ActiveSupport::Cache::MemoryStore.new - # - # cache.read('city') # => nil - # cache.write('city', "Duckburgh") - # cache.read('city') # => "Duckburgh" - # - # Keys are always translated into Strings and are case sensitive. When an - # object is specified as a key and has a +cache_key+ method defined, this - # method will be called to define the key. Otherwise, the +to_param+ - # method will be called. Hashes and Arrays can also be used as keys. The - # elements will be delimited by slashes, and the elements within a Hash - # will be sorted by key so they are consistent. - # - # cache.read('city') == cache.read(:city) # => true - # - # Nil values can be cached. - # - # If your cache is on a shared infrastructure, you can define a namespace - # for your cache entries. If a namespace is defined, it will be prefixed on - # to every key. The namespace can be either a static value or a Proc. If it - # is a Proc, it will be invoked when each key is evaluated so that you can - # use application logic to invalidate keys. - # - # cache.namespace = -> { @last_mod_time } # Set the namespace to a variable - # @last_mod_time = Time.now # Invalidate the entire cache by changing namespace - # - # Caches can also store values in a compressed format to save space and - # reduce time spent sending data. Since there is overhead, values must be - # large enough to warrant compression. To turn on compression either pass - # compress: true in the initializer or as an option to +fetch+ - # or +write+. To specify the threshold at which to compress values, set the - # :compress_threshold option. The default threshold is 16K. - class Store - cattr_accessor :logger, instance_writer: true - - attr_reader :silence, :options - alias :silence? :silence - - # Creates a new cache. The options will be passed to any write method calls - # except for :namespace which can be used to set the global - # namespace for the cache. - def initialize(options = nil) - @options = options ? options.dup : {} - end - - # Silences the logger. - def silence! - @silence = true - self - end - - # Silences the logger within a block. - def mute - previous_silence, @silence = defined?(@silence) && @silence, true - yield - ensure - @silence = previous_silence - end - - # Fetches data from the cache, using the given key. If there is data in - # the cache with the given key, then that data is returned. - # - # If there is no such data in the cache (a cache miss), then +nil+ will be - # returned. However, if a block has been passed, that block will be passed - # the key and executed in the event of a cache miss. The return value of the - # block will be written to the cache under the given cache key, and that - # return value will be returned. - # - # cache.write('today', 'Monday') - # cache.fetch('today') # => "Monday" - # - # cache.fetch('city') # => nil - # cache.fetch('city') do - # 'Duckburgh' - # end - # cache.fetch('city') # => "Duckburgh" - # - # You may also specify additional options via the +options+ argument. - # Setting force: true forces a cache "miss," meaning we treat - # the cache value as missing even if it's present. Passing a block is - # required when +force+ is true so this always results in a cache write. - # - # cache.write('today', 'Monday') - # cache.fetch('today', force: true) { 'Tuesday' } # => 'Tuesday' - # cache.fetch('today', force: true) # => ArgumentError - # - # The +:force+ option is useful when you're calling some other method to - # ask whether you should force a cache write. Otherwise, it's clearer to - # just call Cache#write. - # - # Setting :compress will store a large cache entry set by the call - # in a compressed format. - # - # Setting :expires_in will set an expiration time on the cache. - # All caches support auto-expiring content after a specified number of - # seconds. This value can be specified as an option to the constructor - # (in which case all entries will be affected), or it can be supplied to - # the +fetch+ or +write+ method to effect just one entry. - # - # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes) - # cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry - # - # Setting :race_condition_ttl is very useful in situations where - # a cache entry is used very frequently and is under heavy load. If a - # cache expires and due to heavy load several different processes will try - # to read data natively and then they all will try to write to cache. To - # avoid that case the first process to find an expired cache entry will - # bump the cache expiration time by the value set in :race_condition_ttl. - # Yes, this process is extending the time for a stale value by another few - # seconds. Because of extended life of the previous cache, other processes - # will continue to use slightly stale data for a just a bit longer. In the - # meantime that first process will go ahead and will write into cache the - # new value. After that all the processes will start getting the new value. - # The key is to keep :race_condition_ttl small. - # - # If the process regenerating the entry errors out, the entry will be - # regenerated after the specified number of seconds. Also note that the - # life of stale cache is extended only if it expired recently. Otherwise - # a new value is generated and :race_condition_ttl does not play - # any role. - # - # # Set all values to expire after one minute. - # cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute) - # - # cache.write('foo', 'original value') - # val_1 = nil - # val_2 = nil - # sleep 60 - # - # Thread.new do - # val_1 = cache.fetch('foo', race_condition_ttl: 10.seconds) do - # sleep 1 - # 'new value 1' - # end - # end - # - # Thread.new do - # val_2 = cache.fetch('foo', race_condition_ttl: 10.seconds) do - # 'new value 2' - # end - # end - # - # cache.fetch('foo') # => "original value" - # sleep 10 # First thread extended the life of cache by another 10 seconds - # cache.fetch('foo') # => "new value 1" - # val_1 # => "new value 1" - # val_2 # => "original value" - # - # Other options will be handled by the specific cache store implementation. - # Internally, #fetch calls #read_entry, and calls #write_entry on a cache - # miss. +options+ will be passed to the #read and #write calls. - # - # For example, MemCacheStore's #write method supports the +:raw+ - # option, which tells the memcached server to store all values as strings. - # We can use this option with #fetch too: - # - # cache = ActiveSupport::Cache::MemCacheStore.new - # cache.fetch("foo", force: true, raw: true) do - # :bar - # end - # cache.fetch('foo') # => "bar" - def fetch(name, options = nil) - if block_given? - options = merged_options(options) - key = normalize_key(name, options) - - entry = nil - instrument(:read, name, options) do |payload| - cached_entry = read_entry(key, options) unless options[:force] - entry = handle_expired_entry(cached_entry, key, options) - payload[:super_operation] = :fetch if payload - payload[:hit] = !!entry if payload - end - - if entry - get_entry_value(entry, name, options) - else - save_block_result_to_cache(name, options) { |_name| yield _name } - end - elsif options && options[:force] - raise ArgumentError, "Missing block: Calling `Cache#fetch` with `force: true` requires a block." - else - read(name, options) - end - end - - # Fetches data from the cache, using the given key. If there is data in - # the cache with the given key, then that data is returned. Otherwise, - # +nil+ is returned. - # - # Options are passed to the underlying cache implementation. - def read(name, options = nil) - options = merged_options(options) - key = normalize_key(name, options) - instrument(:read, name, options) do |payload| - entry = read_entry(key, options) - if entry - if entry.expired? - delete_entry(key, options) - payload[:hit] = false if payload - nil - else - payload[:hit] = true if payload - entry.value - end - else - payload[:hit] = false if payload - nil - end - end - end - - # Reads multiple values at once from the cache. Options can be passed - # in the last argument. - # - # Some cache implementation may optimize this method. - # - # Returns a hash mapping the names provided to the values found. - def read_multi(*names) - options = names.extract_options! - options = merged_options(options) - - results = {} - names.each do |name| - key = normalize_key(name, options) - entry = read_entry(key, options) - if entry - if entry.expired? - delete_entry(key, options) - else - results[name] = entry.value - end - end - end - results - end - - # Fetches data from the cache, using the given keys. If there is data in - # the cache with the given keys, then that data is returned. Otherwise, - # the supplied block is called for each key for which there was no data, - # and the result will be written to the cache and returned. - # Therefore, you need to pass a block that returns the data to be written - # to the cache. If you do not want to write the cache when the cache is - # not found, use #read_multi. - # - # Options are passed to the underlying cache implementation. - # - # Returns a hash with the data for each of the names. For example: - # - # cache.write("bim", "bam") - # cache.fetch_multi("bim", "unknown_key") do |key| - # "Fallback value for key: #{key}" - # end - # # => { "bim" => "bam", - # # "unknown_key" => "Fallback value for key: unknown_key" } - # - def fetch_multi(*names) - raise ArgumentError, "Missing block: `Cache#fetch_multi` requires a block." unless block_given? - - options = names.extract_options! - options = merged_options(options) - results = read_multi(*names, options) - - names.each_with_object({}) do |name, memo| - memo[name] = results.fetch(name) do - value = yield name - write(name, value, options) - value - end - end - end - - # Writes the value to the cache, with the key. - # - # Options are passed to the underlying cache implementation. - def write(name, value, options = nil) - options = merged_options(options) - - instrument(:write, name, options) do - entry = Entry.new(value, options) - write_entry(normalize_key(name, options), entry, options) - end - end - - # Deletes an entry in the cache. Returns +true+ if an entry is deleted. - # - # Options are passed to the underlying cache implementation. - def delete(name, options = nil) - options = merged_options(options) - - instrument(:delete, name) do - delete_entry(normalize_key(name, options), options) - end - end - - # Returns +true+ if the cache contains an entry for the given key. - # - # Options are passed to the underlying cache implementation. - def exist?(name, options = nil) - options = merged_options(options) - - instrument(:exist?, name) do - entry = read_entry(normalize_key(name, options), options) - (entry && !entry.expired?) || false - end - end - - # Deletes all entries with keys matching the pattern. - # - # Options are passed to the underlying cache implementation. - # - # All implementations may not support this method. - def delete_matched(matcher, options = nil) - raise NotImplementedError.new("#{self.class.name} does not support delete_matched") - end - - # Increments an integer value in the cache. - # - # Options are passed to the underlying cache implementation. - # - # All implementations may not support this method. - def increment(name, amount = 1, options = nil) - raise NotImplementedError.new("#{self.class.name} does not support increment") - end - - # Decrements an integer value in the cache. - # - # Options are passed to the underlying cache implementation. - # - # All implementations may not support this method. - def decrement(name, amount = 1, options = nil) - raise NotImplementedError.new("#{self.class.name} does not support decrement") - end - - # Cleanups the cache by removing expired entries. - # - # Options are passed to the underlying cache implementation. - # - # All implementations may not support this method. - def cleanup(options = nil) - raise NotImplementedError.new("#{self.class.name} does not support cleanup") - end - - # Clears the entire cache. Be careful with this method since it could - # affect other processes if shared cache is being used. - # - # The options hash is passed to the underlying cache implementation. - # - # All implementations may not support this method. - def clear(options = nil) - raise NotImplementedError.new("#{self.class.name} does not support clear") - end - - private - # Adds the namespace defined in the options to a pattern designed to - # match keys. Implementations that support delete_matched should call - # this method to translate a pattern that matches names into one that - # matches namespaced keys. - def key_matcher(pattern, options) # :doc: - prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace] - if prefix - source = pattern.source - if source.start_with?("^") - source = source[1, source.length] - else - source = ".*#{source[0, source.length]}" - end - Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options) - else - pattern - end - end - - # Reads an entry from the cache implementation. Subclasses must implement - # this method. - def read_entry(key, options) - raise NotImplementedError.new - end - - # Writes an entry to the cache implementation. Subclasses must implement - # this method. - def write_entry(key, entry, options) - raise NotImplementedError.new - end - - # Deletes an entry from the cache implementation. Subclasses must - # implement this method. - def delete_entry(key, options) - raise NotImplementedError.new - end - - # Merges the default options with ones specific to a method call. - def merged_options(call_options) - if call_options - options.merge(call_options) - else - options.dup - end - end - - # Expands key to be a consistent string value. Invokes +cache_key+ if - # object responds to +cache_key+. Otherwise, +to_param+ method will be - # called. If the key is a Hash, then keys will be sorted alphabetically. - def expanded_key(key) - return key.cache_key.to_s if key.respond_to?(:cache_key) - - case key - when Array - if key.size > 1 - key = key.collect { |element| expanded_key(element) } - else - key = key.first - end - when Hash - key = key.sort_by { |k, _| k.to_s }.collect { |k, v| "#{k}=#{v}" } - end - - key.to_param - end - - # Prefixes a key with the namespace. Namespace and key will be delimited - # with a colon. - def normalize_key(key, options) - key = expanded_key(key) - namespace = options[:namespace] if options - prefix = namespace.is_a?(Proc) ? namespace.call : namespace - key = "#{prefix}:#{key}" if prefix - key - end - - def instrument(operation, key, options = nil) - log { "Cache #{operation}: #{normalize_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" } - - payload = { key: key } - payload.merge!(options) if options.is_a?(Hash) - ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload) { yield(payload) } - end - - def log - return unless logger && logger.debug? && !silence? - logger.debug(yield) - end - - def handle_expired_entry(entry, key, options) - if entry && entry.expired? - race_ttl = options[:race_condition_ttl].to_i - if (race_ttl > 0) && (Time.now.to_f - entry.expires_at <= race_ttl) - # When an entry has a positive :race_condition_ttl defined, put the stale entry back into the cache - # for a brief period while the entry is being recalculated. - entry.expires_at = Time.now + race_ttl - write_entry(key, entry, expires_in: race_ttl * 2) - else - delete_entry(key, options) - end - entry = nil - end - entry - end - - def get_entry_value(entry, name, options) - instrument(:fetch_hit, name, options) {} - entry.value - end - - def save_block_result_to_cache(name, options) - result = instrument(:generate, name, options) do - yield(name) - end - - write(name, result, options) - result - end - end - - # This class is used to represent cache entries. Cache entries have a value and an optional - # expiration time. The expiration time is used to support the :race_condition_ttl option - # on the cache. - # - # Since cache entries in most instances will be serialized, the internals of this class are highly optimized - # using short instance variable names that are lazily defined. - class Entry # :nodoc: - DEFAULT_COMPRESS_LIMIT = 16.kilobytes - - # Creates a new cache entry for the specified value. Options supported are - # +:compress+, +:compress_threshold+, and +:expires_in+. - def initialize(value, options = {}) - if should_compress?(value, options) - @value = compress(value) - @compressed = true - else - @value = value - end - - @created_at = Time.now.to_f - @expires_in = options[:expires_in] - @expires_in = @expires_in.to_f if @expires_in - end - - def value - compressed? ? uncompress(@value) : @value - end - - # Checks if the entry is expired. The +expires_in+ parameter can override - # the value set when the entry was created. - def expired? - @expires_in && @created_at + @expires_in <= Time.now.to_f - end - - def expires_at - @expires_in ? @created_at + @expires_in : nil - end - - def expires_at=(value) - if value - @expires_in = value.to_f - @created_at - else - @expires_in = nil - end - end - - # Returns the size of the cached value. This could be less than - # value.size if the data is compressed. - def size - if defined?(@s) - @s - else - case value - when NilClass - 0 - when String - @value.bytesize - else - @s = Marshal.dump(@value).bytesize - end - end - end - - # Duplicates the value in a class. This is used by cache implementations that don't natively - # serialize entries to protect against accidental cache modifications. - def dup_value! - if @value && !compressed? && !(@value.is_a?(Numeric) || @value == true || @value == false) - if @value.is_a?(String) - @value = @value.dup - else - @value = Marshal.load(Marshal.dump(@value)) - end - end - end - - private - def should_compress?(value, options) - if value && options[:compress] - compress_threshold = options[:compress_threshold] || DEFAULT_COMPRESS_LIMIT - serialized_value_size = (value.is_a?(String) ? value : Marshal.dump(value)).bytesize - - return true if serialized_value_size >= compress_threshold - end - - false - end - - def compressed? - defined?(@compressed) ? @compressed : false - end - - def compress(value) - Zlib::Deflate.deflate(Marshal.dump(value)) - end - - def uncompress(value) - Marshal.load(Zlib::Inflate.inflate(value)) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/file_store.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/file_store.rb deleted file mode 100644 index 945f50a56e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/file_store.rb +++ /dev/null @@ -1,195 +0,0 @@ -require "active_support/core_ext/marshal" -require "active_support/core_ext/file/atomic" -require "active_support/core_ext/string/conversions" -require "uri/common" - -module ActiveSupport - module Cache - # A cache store implementation which stores everything on the filesystem. - # - # FileStore implements the Strategy::LocalCache strategy which implements - # an in-memory cache inside of a block. - class FileStore < Store - prepend Strategy::LocalCache - attr_reader :cache_path - - DIR_FORMATTER = "%03X" - FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write) - FILEPATH_MAX_SIZE = 900 # max is 1024, plus some room - EXCLUDED_DIRS = [".", ".."].freeze - GITKEEP_FILES = [".gitkeep", ".keep"].freeze - - def initialize(cache_path, options = nil) - super(options) - @cache_path = cache_path.to_s - end - - # Deletes all items from the cache. In this case it deletes all the entries in the specified - # file store directory except for .keep or .gitkeep. Be careful which directory is specified in your - # config file when using +FileStore+ because everything in that directory will be deleted. - def clear(options = nil) - root_dirs = exclude_from(cache_path, EXCLUDED_DIRS + GITKEEP_FILES) - FileUtils.rm_r(root_dirs.collect { |f| File.join(cache_path, f) }) - rescue Errno::ENOENT - end - - # Preemptively iterates through all stored keys and removes the ones which have expired. - def cleanup(options = nil) - options = merged_options(options) - search_dir(cache_path) do |fname| - key = file_path_key(fname) - entry = read_entry(key, options) - delete_entry(key, options) if entry && entry.expired? - end - end - - # Increments an already existing integer value that is stored in the cache. - # If the key is not found nothing is done. - def increment(name, amount = 1, options = nil) - modify_value(name, amount, options) - end - - # Decrements an already existing integer value that is stored in the cache. - # If the key is not found nothing is done. - def decrement(name, amount = 1, options = nil) - modify_value(name, -amount, options) - end - - def delete_matched(matcher, options = nil) - options = merged_options(options) - instrument(:delete_matched, matcher.inspect) do - matcher = key_matcher(matcher, options) - search_dir(cache_path) do |path| - key = file_path_key(path) - delete_entry(path, options) if key.match(matcher) - end - end - end - - private - - def read_entry(key, options) - if File.exist?(key) - File.open(key) { |f| Marshal.load(f) } - end - rescue => e - logger.error("FileStoreError (#{e}): #{e.message}") if logger - nil - end - - def write_entry(key, entry, options) - return false if options[:unless_exist] && File.exist?(key) - ensure_cache_path(File.dirname(key)) - File.atomic_write(key, cache_path) { |f| Marshal.dump(entry, f) } - true - end - - def delete_entry(key, options) - if File.exist?(key) - begin - File.delete(key) - delete_empty_directories(File.dirname(key)) - true - rescue => e - # Just in case the error was caused by another process deleting the file first. - raise e if File.exist?(key) - false - end - end - end - - # Lock a file for a block so only one process can modify it at a time. - def lock_file(file_name, &block) - if File.exist?(file_name) - File.open(file_name, "r+") do |f| - begin - f.flock File::LOCK_EX - yield - ensure - f.flock File::LOCK_UN - end - end - else - yield - end - end - - # Translate a key into a file path. - def normalize_key(key, options) - key = super - fname = URI.encode_www_form_component(key) - - if fname.size > FILEPATH_MAX_SIZE - fname = Digest::MD5.hexdigest(key) - end - - hash = Zlib.adler32(fname) - hash, dir_1 = hash.divmod(0x1000) - dir_2 = hash.modulo(0x1000) - fname_paths = [] - - # Make sure file name doesn't exceed file system limits. - begin - fname_paths << fname[0, FILENAME_MAX_SIZE] - fname = fname[FILENAME_MAX_SIZE..-1] - end until fname.blank? - - File.join(cache_path, DIR_FORMATTER % dir_1, DIR_FORMATTER % dir_2, *fname_paths) - end - - # Translate a file path into a key. - def file_path_key(path) - fname = path[cache_path.to_s.size..-1].split(File::SEPARATOR, 4).last - URI.decode_www_form_component(fname, Encoding::UTF_8) - end - - # Delete empty directories in the cache. - def delete_empty_directories(dir) - return if File.realpath(dir) == File.realpath(cache_path) - if exclude_from(dir, EXCLUDED_DIRS).empty? - Dir.delete(dir) rescue nil - delete_empty_directories(File.dirname(dir)) - end - end - - # Make sure a file path's directories exist. - def ensure_cache_path(path) - FileUtils.makedirs(path) unless File.exist?(path) - end - - def search_dir(dir, &callback) - return if !File.exist?(dir) - Dir.foreach(dir) do |d| - next if EXCLUDED_DIRS.include?(d) - name = File.join(dir, d) - if File.directory?(name) - search_dir(name, &callback) - else - callback.call name - end - end - end - - # Modifies the amount of an already existing integer value that is stored in the cache. - # If the key is not found nothing is done. - def modify_value(name, amount, options) - file_name = normalize_key(name, options) - - lock_file(file_name) do - options = merged_options(options) - - if num = read(name, options) - num = num.to_i + amount - write(name, num, options) - num - end - end - end - - # Exclude entries from source directory - def exclude_from(source, excludes) - Dir.entries(source).reject { |f| excludes.include?(f) } - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/mem_cache_store.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/mem_cache_store.rb deleted file mode 100644 index e09cee3335..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/mem_cache_store.rb +++ /dev/null @@ -1,197 +0,0 @@ -begin - require "dalli" -rescue LoadError => e - $stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install" - raise e -end - -require "digest/md5" -require "active_support/core_ext/marshal" -require "active_support/core_ext/array/extract_options" - -module ActiveSupport - module Cache - # A cache store implementation which stores data in Memcached: - # http://memcached.org/ - # - # This is currently the most popular cache store for production websites. - # - # Special features: - # - Clustering and load balancing. One can specify multiple memcached servers, - # and MemCacheStore will load balance between all available servers. If a - # server goes down, then MemCacheStore will ignore it until it comes back up. - # - # MemCacheStore implements the Strategy::LocalCache strategy which implements - # an in-memory cache inside of a block. - class MemCacheStore < Store - # Provide support for raw values in the local cache strategy. - module LocalCacheWithRaw # :nodoc: - private - def read_entry(key, options) - entry = super - if options[:raw] && local_cache && entry - entry = deserialize_entry(entry.value) - end - entry - end - - def write_entry(key, entry, options) - if options[:raw] && local_cache - raw_entry = Entry.new(entry.value.to_s) - raw_entry.expires_at = entry.expires_at - super(key, raw_entry, options) - else - super - end - end - end - - prepend Strategy::LocalCache - prepend LocalCacheWithRaw - - ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n - - # Creates a new Dalli::Client instance with specified addresses and options. - # By default address is equal localhost:11211. - # - # ActiveSupport::Cache::MemCacheStore.build_mem_cache - # # => # - # ActiveSupport::Cache::MemCacheStore.build_mem_cache('localhost:10290') - # # => # - def self.build_mem_cache(*addresses) # :nodoc: - addresses = addresses.flatten - options = addresses.extract_options! - addresses = ["localhost:11211"] if addresses.empty? - Dalli::Client.new(addresses, options) - end - - # Creates a new MemCacheStore object, with the given memcached server - # addresses. Each address is either a host name, or a host-with-port string - # in the form of "host_name:port". For example: - # - # ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229") - # - # If no addresses are specified, then MemCacheStore will connect to - # localhost port 11211 (the default memcached port). - def initialize(*addresses) - addresses = addresses.flatten - options = addresses.extract_options! - super(options) - - unless [String, Dalli::Client, NilClass].include?(addresses.first.class) - raise ArgumentError, "First argument must be an empty array, an array of hosts or a Dalli::Client instance." - end - if addresses.first.is_a?(Dalli::Client) - @data = addresses.first - else - mem_cache_options = options.dup - UNIVERSAL_OPTIONS.each { |name| mem_cache_options.delete(name) } - @data = self.class.build_mem_cache(*(addresses + [mem_cache_options])) - end - end - - # Reads multiple values from the cache using a single call to the - # servers for all keys. Options can be passed in the last argument. - def read_multi(*names) - options = names.extract_options! - options = merged_options(options) - - keys_to_names = Hash[names.map { |name| [normalize_key(name, options), name] }] - raw_values = @data.get_multi(keys_to_names.keys) - values = {} - raw_values.each do |key, value| - entry = deserialize_entry(value) - values[keys_to_names[key]] = entry.value unless entry.expired? - end - values - end - - # Increment a cached value. This method uses the memcached incr atomic - # operator and can only be used on values written with the :raw option. - # Calling it on a value not stored with :raw will initialize that value - # to zero. - def increment(name, amount = 1, options = nil) - options = merged_options(options) - instrument(:increment, name, amount: amount) do - rescue_error_with nil do - @data.incr(normalize_key(name, options), amount) - end - end - end - - # Decrement a cached value. This method uses the memcached decr atomic - # operator and can only be used on values written with the :raw option. - # Calling it on a value not stored with :raw will initialize that value - # to zero. - def decrement(name, amount = 1, options = nil) - options = merged_options(options) - instrument(:decrement, name, amount: amount) do - rescue_error_with nil do - @data.decr(normalize_key(name, options), amount) - end - end - end - - # Clear the entire cache on all memcached servers. This method should - # be used with care when shared cache is being used. - def clear(options = nil) - rescue_error_with(nil) { @data.flush_all } - end - - # Get the statistics from the memcached servers. - def stats - @data.stats - end - - private - # Read an entry from the cache. - def read_entry(key, options) - rescue_error_with(nil) { deserialize_entry(@data.get(key, options)) } - end - - # Write an entry to the cache. - def write_entry(key, entry, options) - method = options && options[:unless_exist] ? :add : :set - value = options[:raw] ? entry.value.to_s : entry - expires_in = options[:expires_in].to_i - if expires_in > 0 && !options[:raw] - # Set the memcache expire a few minutes in the future to support race condition ttls on read - expires_in += 5.minutes - end - rescue_error_with false do - @data.send(method, key, value, expires_in, options) - end - end - - # Delete an entry from the cache. - def delete_entry(key, options) - rescue_error_with(false) { @data.delete(key) } - end - - # Memcache keys are binaries. So we need to force their encoding to binary - # before applying the regular expression to ensure we are escaping all - # characters properly. - def normalize_key(key, options) - key = super.dup - key = key.force_encoding(Encoding::ASCII_8BIT) - key = key.gsub(ESCAPE_KEY_CHARS) { |match| "%#{match.getbyte(0).to_s(16).upcase}" } - key = "#{key[0, 213]}:md5:#{Digest::MD5.hexdigest(key)}" if key.size > 250 - key - end - - def deserialize_entry(raw_value) - if raw_value - entry = Marshal.load(raw_value) rescue raw_value - entry.is_a?(Entry) ? entry : Entry.new(entry) - end - end - - def rescue_error_with(fallback) - yield - rescue Dalli::DalliError => e - logger.error("DalliError (#{e}): #{e.message}") if logger - fallback - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/memory_store.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/memory_store.rb deleted file mode 100644 index 56fe1457d0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/memory_store.rb +++ /dev/null @@ -1,167 +0,0 @@ -require "monitor" - -module ActiveSupport - module Cache - # A cache store implementation which stores everything into memory in the - # same process. If you're running multiple Ruby on Rails server processes - # (which is the case if you're using Phusion Passenger or puma clustered mode), - # then this means that Rails server process instances won't be able - # to share cache data with each other and this may not be the most - # appropriate cache in that scenario. - # - # This cache has a bounded size specified by the :size options to the - # initializer (default is 32Mb). When the cache exceeds the allotted size, - # a cleanup will occur which tries to prune the cache down to three quarters - # of the maximum size by removing the least recently used entries. - # - # MemoryStore is thread-safe. - class MemoryStore < Store - def initialize(options = nil) - options ||= {} - super(options) - @data = {} - @key_access = {} - @max_size = options[:size] || 32.megabytes - @max_prune_time = options[:max_prune_time] || 2 - @cache_size = 0 - @monitor = Monitor.new - @pruning = false - end - - # Delete all data stored in a given cache store. - def clear(options = nil) - synchronize do - @data.clear - @key_access.clear - @cache_size = 0 - end - end - - # Preemptively iterates through all stored keys and removes the ones which have expired. - def cleanup(options = nil) - options = merged_options(options) - instrument(:cleanup, size: @data.size) do - keys = synchronize { @data.keys } - keys.each do |key| - entry = @data[key] - delete_entry(key, options) if entry && entry.expired? - end - end - end - - # To ensure entries fit within the specified memory prune the cache by removing the least - # recently accessed entries. - def prune(target_size, max_time = nil) - return if pruning? - @pruning = true - begin - start_time = Time.now - cleanup - instrument(:prune, target_size, from: @cache_size) do - keys = synchronize { @key_access.keys.sort { |a, b| @key_access[a].to_f <=> @key_access[b].to_f } } - keys.each do |key| - delete_entry(key, options) - return if @cache_size <= target_size || (max_time && Time.now - start_time > max_time) - end - end - ensure - @pruning = false - end - end - - # Returns true if the cache is currently being pruned. - def pruning? - @pruning - end - - # Increment an integer value in the cache. - def increment(name, amount = 1, options = nil) - modify_value(name, amount, options) - end - - # Decrement an integer value in the cache. - def decrement(name, amount = 1, options = nil) - modify_value(name, -amount, options) - end - - # Deletes cache entries if the cache key matches a given pattern. - def delete_matched(matcher, options = nil) - options = merged_options(options) - instrument(:delete_matched, matcher.inspect) do - matcher = key_matcher(matcher, options) - keys = synchronize { @data.keys } - keys.each do |key| - delete_entry(key, options) if key.match(matcher) - end - end - end - - def inspect # :nodoc: - "<##{self.class.name} entries=#{@data.size}, size=#{@cache_size}, options=#{@options.inspect}>" - end - - # Synchronize calls to the cache. This should be called wherever the underlying cache implementation - # is not thread safe. - def synchronize(&block) # :nodoc: - @monitor.synchronize(&block) - end - - private - - PER_ENTRY_OVERHEAD = 240 - - def cached_size(key, entry) - key.to_s.bytesize + entry.size + PER_ENTRY_OVERHEAD - end - - def read_entry(key, options) - entry = @data[key] - synchronize do - if entry - @key_access[key] = Time.now.to_f - else - @key_access.delete(key) - end - end - entry - end - - def write_entry(key, entry, options) - entry.dup_value! - synchronize do - old_entry = @data[key] - return false if @data.key?(key) && options[:unless_exist] - if old_entry - @cache_size -= (old_entry.size - entry.size) - else - @cache_size += cached_size(key, entry) - end - @key_access[key] = Time.now.to_f - @data[key] = entry - prune(@max_size * 0.75, @max_prune_time) if @cache_size > @max_size - true - end - end - - def delete_entry(key, options) - synchronize do - @key_access.delete(key) - entry = @data.delete(key) - @cache_size -= cached_size(key, entry) if entry - !!entry - end - end - - def modify_value(name, amount, options) - synchronize do - options = merged_options(options) - if num = read(name, options) - num = num.to_i + amount - write(name, num, options) - num - end - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/null_store.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/null_store.rb deleted file mode 100644 index 550659fc56..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/null_store.rb +++ /dev/null @@ -1,41 +0,0 @@ -module ActiveSupport - module Cache - # A cache store implementation which doesn't actually store anything. Useful in - # development and test environments where you don't want caching turned on but - # need to go through the caching interface. - # - # This cache does implement the local cache strategy, so values will actually - # be cached inside blocks that utilize this strategy. See - # ActiveSupport::Cache::Strategy::LocalCache for more details. - class NullStore < Store - prepend Strategy::LocalCache - - def clear(options = nil) - end - - def cleanup(options = nil) - end - - def increment(name, amount = 1, options = nil) - end - - def decrement(name, amount = 1, options = nil) - end - - def delete_matched(matcher, options = nil) - end - - private - def read_entry(key, options) - end - - def write_entry(key, entry, options) - true - end - - def delete_entry(key, options) - false - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/strategy/local_cache.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/strategy/local_cache.rb deleted file mode 100644 index 0dc0b40430..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/strategy/local_cache.rb +++ /dev/null @@ -1,163 +0,0 @@ -require "active_support/core_ext/object/duplicable" -require "active_support/core_ext/string/inflections" -require "active_support/per_thread_registry" - -module ActiveSupport - module Cache - module Strategy - # Caches that implement LocalCache will be backed by an in-memory cache for the - # duration of a block. Repeated calls to the cache for the same key will hit the - # in-memory cache for faster access. - module LocalCache - autoload :Middleware, "active_support/cache/strategy/local_cache_middleware" - - # Class for storing and registering the local caches. - class LocalCacheRegistry # :nodoc: - extend ActiveSupport::PerThreadRegistry - - def initialize - @registry = {} - end - - def cache_for(local_cache_key) - @registry[local_cache_key] - end - - def set_cache_for(local_cache_key, value) - @registry[local_cache_key] = value - end - - def self.set_cache_for(l, v); instance.set_cache_for l, v; end - def self.cache_for(l); instance.cache_for l; end - end - - # Simple memory backed cache. This cache is not thread safe and is intended only - # for serving as a temporary memory cache for a single thread. - class LocalStore < Store - def initialize - super - @data = {} - end - - # Don't allow synchronizing since it isn't thread safe. - def synchronize # :nodoc: - yield - end - - def clear(options = nil) - @data.clear - end - - def read_entry(key, options) - @data[key] - end - - def write_entry(key, value, options) - @data[key] = value - true - end - - def delete_entry(key, options) - !!@data.delete(key) - end - - def fetch_entry(key, options = nil) # :nodoc: - @data.fetch(key) { @data[key] = yield } - end - end - - # Use a local cache for the duration of block. - def with_local_cache - use_temporary_local_cache(LocalStore.new) { yield } - end - - # Middleware class can be inserted as a Rack handler to be local cache for the - # duration of request. - def middleware - @middleware ||= Middleware.new( - "ActiveSupport::Cache::Strategy::LocalCache", - local_cache_key) - end - - def clear(options = nil) # :nodoc: - return super unless cache = local_cache - cache.clear(options) - super - end - - def cleanup(options = nil) # :nodoc: - return super unless cache = local_cache - cache.clear(options) - super - end - - def increment(name, amount = 1, options = nil) # :nodoc: - return super unless local_cache - value = bypass_local_cache { super } - write_cache_value(name, value, options) - value - end - - def decrement(name, amount = 1, options = nil) # :nodoc: - return super unless local_cache - value = bypass_local_cache { super } - write_cache_value(name, value, options) - value - end - - private - def read_entry(key, options) - if cache = local_cache - cache.fetch_entry(key) { super } - else - super - end - end - - def write_entry(key, entry, options) - local_cache.write_entry(key, entry, options) if local_cache - super - end - - def delete_entry(key, options) - local_cache.delete_entry(key, options) if local_cache - super - end - - def write_cache_value(name, value, options) - name = normalize_key(name, options) - cache = local_cache - cache.mute do - if value - cache.write(name, value, options) - else - cache.delete(name, options) - end - end - end - - def local_cache_key - @local_cache_key ||= "#{self.class.name.underscore}_local_cache_#{object_id}".gsub(/[\/-]/, "_").to_sym - end - - def local_cache - LocalCacheRegistry.cache_for(local_cache_key) - end - - def bypass_local_cache - use_temporary_local_cache(nil) { yield } - end - - def use_temporary_local_cache(temporary_cache) - save_cache = LocalCacheRegistry.cache_for(local_cache_key) - begin - LocalCacheRegistry.set_cache_for(local_cache_key, temporary_cache) - yield - ensure - LocalCacheRegistry.set_cache_for(local_cache_key, save_cache) - end - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/strategy/local_cache_middleware.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/strategy/local_cache_middleware.rb deleted file mode 100644 index 4c3679e4bf..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/cache/strategy/local_cache_middleware.rb +++ /dev/null @@ -1,43 +0,0 @@ -require "rack/body_proxy" -require "rack/utils" - -module ActiveSupport - module Cache - module Strategy - module LocalCache - #-- - # This class wraps up local storage for middlewares. Only the middleware method should - # construct them. - class Middleware # :nodoc: - attr_reader :name, :local_cache_key - - def initialize(name, local_cache_key) - @name = name - @local_cache_key = local_cache_key - @app = nil - end - - def new(app) - @app = app - self - end - - def call(env) - LocalCacheRegistry.set_cache_for(local_cache_key, LocalStore.new) - response = @app.call(env) - response[2] = ::Rack::BodyProxy.new(response[2]) do - LocalCacheRegistry.set_cache_for(local_cache_key, nil) - end - cleanup_on_body_close = true - response - rescue Rack::Utils::InvalidParameterError - [400, {}, []] - ensure - LocalCacheRegistry.set_cache_for(local_cache_key, nil) unless - cleanup_on_body_close - end - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/callbacks.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/callbacks.rb deleted file mode 100644 index e61844c5be..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/callbacks.rb +++ /dev/null @@ -1,856 +0,0 @@ -require "active_support/concern" -require "active_support/descendants_tracker" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/class/attribute" -require "active_support/core_ext/kernel/reporting" -require "active_support/core_ext/kernel/singleton_class" -require "active_support/core_ext/string/filters" -require "active_support/deprecation" -require "thread" - -module ActiveSupport - # Callbacks are code hooks that are run at key points in an object's life cycle. - # The typical use case is to have a base class define a set of callbacks - # relevant to the other functionality it supplies, so that subclasses can - # install callbacks that enhance or modify the base functionality without - # needing to override or redefine methods of the base class. - # - # Mixing in this module allows you to define the events in the object's - # life cycle that will support callbacks (via +ClassMethods.define_callbacks+), - # set the instance methods, procs, or callback objects to be called (via - # +ClassMethods.set_callback+), and run the installed callbacks at the - # appropriate times (via +run_callbacks+). - # - # Three kinds of callbacks are supported: before callbacks, run before a - # certain event; after callbacks, run after the event; and around callbacks, - # blocks that surround the event, triggering it when they yield. Callback code - # can be contained in instance methods, procs or lambdas, or callback objects - # that respond to certain predetermined methods. See +ClassMethods.set_callback+ - # for details. - # - # class Record - # include ActiveSupport::Callbacks - # define_callbacks :save - # - # def save - # run_callbacks :save do - # puts "- save" - # end - # end - # end - # - # class PersonRecord < Record - # set_callback :save, :before, :saving_message - # def saving_message - # puts "saving..." - # end - # - # set_callback :save, :after do |object| - # puts "saved" - # end - # end - # - # person = PersonRecord.new - # person.save - # - # Output: - # saving... - # - save - # saved - module Callbacks - extend Concern - - included do - extend ActiveSupport::DescendantsTracker - class_attribute :__callbacks, instance_writer: false - self.__callbacks ||= {} - end - - CALLBACK_FILTER_TYPES = [:before, :after, :around] - - # Runs the callbacks for the given event. - # - # Calls the before and around callbacks in the order they were set, yields - # the block (if given one), and then runs the after callbacks in reverse - # order. - # - # If the callback chain was halted, returns +false+. Otherwise returns the - # result of the block, +nil+ if no callbacks have been set, or +true+ - # if callbacks have been set but no block is given. - # - # run_callbacks :save do - # save - # end - # - #-- - # - # As this method is used in many places, and often wraps large portions of - # user code, it has an additional design goal of minimizing its impact on - # the visible call stack. An exception from inside a :before or :after - # callback can be as noisy as it likes -- but when control has passed - # smoothly through and into the supplied block, we want as little evidence - # as possible that we were here. - def run_callbacks(kind) - callbacks = __callbacks[kind.to_sym] - - if callbacks.empty? - yield if block_given? - else - env = Filters::Environment.new(self, false, nil) - next_sequence = callbacks.compile - - invoke_sequence = Proc.new do - skipped = nil - while true - current = next_sequence - current.invoke_before(env) - if current.final? - env.value = !env.halted && (!block_given? || yield) - elsif current.skip?(env) - (skipped ||= []) << current - next_sequence = next_sequence.nested - next - else - next_sequence = next_sequence.nested - begin - target, block, method, *arguments = current.expand_call_template(env, invoke_sequence) - target.send(method, *arguments, &block) - ensure - next_sequence = current - end - end - current.invoke_after(env) - skipped.pop.invoke_after(env) while skipped && skipped.first - break env.value - end - end - - # Common case: no 'around' callbacks defined - if next_sequence.final? - next_sequence.invoke_before(env) - env.value = !env.halted && (!block_given? || yield) - next_sequence.invoke_after(env) - env.value - else - invoke_sequence.call - end - end - end - - private - - # A hook invoked every time a before callback is halted. - # This can be overridden in ActiveSupport::Callbacks implementors in order - # to provide better debugging/logging. - def halted_callback_hook(filter) - end - - module Conditionals # :nodoc: - class Value - def initialize(&block) - @block = block - end - def call(target, value); @block.call(value); end - end - end - - module Filters - Environment = Struct.new(:target, :halted, :value) - - class Before - def self.build(callback_sequence, user_callback, user_conditions, chain_config, filter) - halted_lambda = chain_config[:terminator] - - if user_conditions.any? - halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter) - else - halting(callback_sequence, user_callback, halted_lambda, filter) - end - end - - def self.halting_and_conditional(callback_sequence, user_callback, user_conditions, halted_lambda, filter) - callback_sequence.before do |env| - target = env.target - value = env.value - halted = env.halted - - if !halted && user_conditions.all? { |c| c.call(target, value) } - result_lambda = -> { user_callback.call target, value } - env.halted = halted_lambda.call(target, result_lambda) - if env.halted - target.send :halted_callback_hook, filter - end - end - - env - end - end - private_class_method :halting_and_conditional - - def self.halting(callback_sequence, user_callback, halted_lambda, filter) - callback_sequence.before do |env| - target = env.target - value = env.value - halted = env.halted - - unless halted - result_lambda = -> { user_callback.call target, value } - env.halted = halted_lambda.call(target, result_lambda) - - if env.halted - target.send :halted_callback_hook, filter - end - end - - env - end - end - private_class_method :halting - end - - class After - def self.build(callback_sequence, user_callback, user_conditions, chain_config) - if chain_config[:skip_after_callbacks_if_terminated] - if user_conditions.any? - halting_and_conditional(callback_sequence, user_callback, user_conditions) - else - halting(callback_sequence, user_callback) - end - else - if user_conditions.any? - conditional callback_sequence, user_callback, user_conditions - else - simple callback_sequence, user_callback - end - end - end - - def self.halting_and_conditional(callback_sequence, user_callback, user_conditions) - callback_sequence.after do |env| - target = env.target - value = env.value - halted = env.halted - - if !halted && user_conditions.all? { |c| c.call(target, value) } - user_callback.call target, value - end - - env - end - end - private_class_method :halting_and_conditional - - def self.halting(callback_sequence, user_callback) - callback_sequence.after do |env| - unless env.halted - user_callback.call env.target, env.value - end - - env - end - end - private_class_method :halting - - def self.conditional(callback_sequence, user_callback, user_conditions) - callback_sequence.after do |env| - target = env.target - value = env.value - - if user_conditions.all? { |c| c.call(target, value) } - user_callback.call target, value - end - - env - end - end - private_class_method :conditional - - def self.simple(callback_sequence, user_callback) - callback_sequence.after do |env| - user_callback.call env.target, env.value - - env - end - end - private_class_method :simple - end - end - - class Callback #:nodoc:# - def self.build(chain, filter, kind, options) - if filter.is_a?(String) - raise ArgumentError, <<-MSG.squish - Passing string to define a callback is not supported. See the `.set_callback` - documentation to see supported values. - MSG - end - - new chain.name, filter, kind, options, chain.config - end - - attr_accessor :kind, :name - attr_reader :chain_config - - def initialize(name, filter, kind, options, chain_config) - @chain_config = chain_config - @name = name - @kind = kind - @filter = filter - @key = compute_identifier filter - @if = Array(options[:if]) - @unless = Array(options[:unless]) - end - - def filter; @key; end - def raw_filter; @filter; end - - def merge_conditional_options(chain, if_option:, unless_option:) - options = { - if: @if.dup, - unless: @unless.dup - } - - options[:if].concat Array(unless_option) - options[:unless].concat Array(if_option) - - self.class.build chain, @filter, @kind, options - end - - def matches?(_kind, _filter) - @kind == _kind && filter == _filter - end - - def duplicates?(other) - case @filter - when Symbol, String - matches?(other.kind, other.filter) - else - false - end - end - - # Wraps code with filter - def apply(callback_sequence) - user_conditions = conditions_lambdas - user_callback = CallTemplate.build(@filter, self) - - case kind - when :before - Filters::Before.build(callback_sequence, user_callback.make_lambda, user_conditions, chain_config, @filter) - when :after - Filters::After.build(callback_sequence, user_callback.make_lambda, user_conditions, chain_config) - when :around - callback_sequence.around(user_callback, user_conditions) - end - end - - def current_scopes - Array(chain_config[:scope]).map { |s| public_send(s) } - end - - private - def compute_identifier(filter) - case filter - when String, ::Proc - filter.object_id - else - filter - end - end - - def conditions_lambdas - @if.map { |c| CallTemplate.build(c, self).make_lambda } + - @unless.map { |c| CallTemplate.build(c, self).inverted_lambda } - end - end - - # A future invocation of user-supplied code (either as a callback, - # or a condition filter). - class CallTemplate # :nodoc: - def initialize(target, method, arguments, block) - @override_target = target - @method_name = method - @arguments = arguments - @override_block = block - end - - # Return the parts needed to make this call, with the given - # input values. - # - # Returns an array of the form: - # - # [target, block, method, *arguments] - # - # This array can be used as such: - # - # target.send(method, *arguments, &block) - # - # The actual invocation is left up to the caller to minimize - # call stack pollution. - def expand(target, value, block) - result = @arguments.map { |arg| - case arg - when :value; value - when :target; target - when :block; block || raise(ArgumentError) - end - } - - result.unshift @method_name - result.unshift @override_block || block - result.unshift @override_target || target - - # target, block, method, *arguments = result - # target.send(method, *arguments, &block) - result - end - - # Return a lambda that will make this call when given the input - # values. - def make_lambda - lambda do |target, value, &block| - target, block, method, *arguments = expand(target, value, block) - target.send(method, *arguments, &block) - end - end - - # Return a lambda that will make this call when given the input - # values, but then return the boolean inverse of that result. - def inverted_lambda - lambda do |target, value, &block| - target, block, method, *arguments = expand(target, value, block) - ! target.send(method, *arguments, &block) - end - end - - # Filters support: - # - # Symbols:: A method to call. - # Strings:: Some content to evaluate. - # Procs:: A proc to call with the object. - # Objects:: An object with a before_foo method on it to call. - # - # All of these objects are converted into a CallTemplate and handled - # the same after this point. - def self.build(filter, callback) - case filter - when Symbol - new(nil, filter, [], nil) - when String - new(nil, :instance_exec, [:value], compile_lambda(filter)) - when Conditionals::Value - new(filter, :call, [:target, :value], nil) - when ::Proc - if filter.arity > 1 - new(nil, :instance_exec, [:target, :block], filter) - elsif filter.arity > 0 - new(nil, :instance_exec, [:target], filter) - else - new(nil, :instance_exec, [], filter) - end - else - method_to_call = callback.current_scopes.join("_") - - new(filter, method_to_call, [:target], nil) - end - end - - def self.compile_lambda(filter) - eval("lambda { |value| #{filter} }") - end - end - - # Execute before and after filters in a sequence instead of - # chaining them with nested lambda calls, see: - # https://github.com/rails/rails/issues/18011 - class CallbackSequence # :nodoc: - def initialize(nested = nil, call_template = nil, user_conditions = nil) - @nested = nested - @call_template = call_template - @user_conditions = user_conditions - - @before = [] - @after = [] - end - - def before(&before) - @before.unshift(before) - self - end - - def after(&after) - @after.push(after) - self - end - - def around(call_template, user_conditions) - CallbackSequence.new(self, call_template, user_conditions) - end - - def skip?(arg) - arg.halted || !@user_conditions.all? { |c| c.call(arg.target, arg.value) } - end - - def nested - @nested - end - - def final? - !@call_template - end - - def expand_call_template(arg, block) - @call_template.expand(arg.target, arg.value, block) - end - - def invoke_before(arg) - @before.each { |b| b.call(arg) } - end - - def invoke_after(arg) - @after.each { |a| a.call(arg) } - end - end - - # An Array with a compile method. - class CallbackChain #:nodoc:# - include Enumerable - - attr_reader :name, :config - - def initialize(name, config) - @name = name - @config = { - scope: [:kind], - terminator: default_terminator - }.merge!(config) - @chain = [] - @callbacks = nil - @mutex = Mutex.new - end - - def each(&block); @chain.each(&block); end - def index(o); @chain.index(o); end - def empty?; @chain.empty?; end - - def insert(index, o) - @callbacks = nil - @chain.insert(index, o) - end - - def delete(o) - @callbacks = nil - @chain.delete(o) - end - - def clear - @callbacks = nil - @chain.clear - self - end - - def initialize_copy(other) - @callbacks = nil - @chain = other.chain.dup - @mutex = Mutex.new - end - - def compile - @callbacks || @mutex.synchronize do - final_sequence = CallbackSequence.new - @callbacks ||= @chain.reverse.inject(final_sequence) do |callback_sequence, callback| - callback.apply callback_sequence - end - end - end - - def append(*callbacks) - callbacks.each { |c| append_one(c) } - end - - def prepend(*callbacks) - callbacks.each { |c| prepend_one(c) } - end - - protected - def chain; @chain; end - - private - - def append_one(callback) - @callbacks = nil - remove_duplicates(callback) - @chain.push(callback) - end - - def prepend_one(callback) - @callbacks = nil - remove_duplicates(callback) - @chain.unshift(callback) - end - - def remove_duplicates(callback) - @callbacks = nil - @chain.delete_if { |c| callback.duplicates?(c) } - end - - def default_terminator - Proc.new do |target, result_lambda| - terminate = true - catch(:abort) do - result_lambda.call if result_lambda.is_a?(Proc) - terminate = false - end - terminate - end - end - end - - module ClassMethods - def normalize_callback_params(filters, block) # :nodoc: - type = CALLBACK_FILTER_TYPES.include?(filters.first) ? filters.shift : :before - options = filters.extract_options! - filters.unshift(block) if block - [type, filters, options.dup] - end - - # This is used internally to append, prepend and skip callbacks to the - # CallbackChain. - def __update_callbacks(name) #:nodoc: - ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target| - chain = target.get_callbacks name - yield target, chain.dup - end - end - - # Install a callback for the given event. - # - # set_callback :save, :before, :before_method - # set_callback :save, :after, :after_method, if: :condition - # set_callback :save, :around, ->(r, block) { stuff; result = block.call; stuff } - # - # The second argument indicates whether the callback is to be run +:before+, - # +:after+, or +:around+ the event. If omitted, +:before+ is assumed. This - # means the first example above can also be written as: - # - # set_callback :save, :before_method - # - # The callback can be specified as a symbol naming an instance method; as a - # proc, lambda, or block; or as an object that responds to a certain method - # determined by the :scope argument to +define_callbacks+. - # - # If a proc, lambda, or block is given, its body is evaluated in the context - # of the current object. It can also optionally accept the current object as - # an argument. - # - # Before and around callbacks are called in the order that they are set; - # after callbacks are called in the reverse order. - # - # Around callbacks can access the return value from the event, if it - # wasn't halted, from the +yield+ call. - # - # ===== Options - # - # * :if - A symbol, a string (deprecated) or an array of symbols, - # each naming an instance method or a proc; the callback will be called - # only when they all return a true value. - # * :unless - A symbol, a string (deprecated) or an array of symbols, - # each naming an instance method or a proc; the callback will be called - # only when they all return a false value. - # * :prepend - If +true+, the callback will be prepended to the - # existing chain rather than appended. - def set_callback(name, *filter_list, &block) - type, filters, options = normalize_callback_params(filter_list, block) - - if options[:if].is_a?(String) || options[:unless].is_a?(String) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing string to be evaluated in :if and :unless conditional - options is deprecated and will be removed in Rails 5.2 without - replacement. Pass a symbol for an instance method, or a lambda, - proc or block, instead. - MSG - end - - self_chain = get_callbacks name - mapped = filters.map do |filter| - Callback.build(self_chain, filter, type, options) - end - - __update_callbacks(name) do |target, chain| - options[:prepend] ? chain.prepend(*mapped) : chain.append(*mapped) - target.set_callbacks name, chain - end - end - - # Skip a previously set callback. Like +set_callback+, :if or - # :unless options may be passed in order to control when the - # callback is skipped. - # - # class Writer < Person - # skip_callback :validate, :before, :check_membership, if: -> { age > 18 } - # end - # - # An ArgumentError will be raised if the callback has not - # already been set (unless the :raise option is set to false). - def skip_callback(name, *filter_list, &block) - type, filters, options = normalize_callback_params(filter_list, block) - - if options[:if].is_a?(String) || options[:unless].is_a?(String) - ActiveSupport::Deprecation.warn(<<-MSG.squish) - Passing string to :if and :unless conditional options is deprecated - and will be removed in Rails 5.2 without replacement. - MSG - end - - options[:raise] = true unless options.key?(:raise) - - __update_callbacks(name) do |target, chain| - filters.each do |filter| - callback = chain.find { |c| c.matches?(type, filter) } - - if !callback && options[:raise] - raise ArgumentError, "#{type.to_s.capitalize} #{name} callback #{filter.inspect} has not been defined" - end - - if callback && (options.key?(:if) || options.key?(:unless)) - new_callback = callback.merge_conditional_options(chain, if_option: options[:if], unless_option: options[:unless]) - chain.insert(chain.index(callback), new_callback) - end - - chain.delete(callback) - end - target.set_callbacks name, chain - end - end - - # Remove all set callbacks for the given event. - def reset_callbacks(name) - callbacks = get_callbacks name - - ActiveSupport::DescendantsTracker.descendants(self).each do |target| - chain = target.get_callbacks(name).dup - callbacks.each { |c| chain.delete(c) } - target.set_callbacks name, chain - end - - set_callbacks(name, callbacks.dup.clear) - end - - # Define sets of events in the object life cycle that support callbacks. - # - # define_callbacks :validate - # define_callbacks :initialize, :save, :destroy - # - # ===== Options - # - # * :terminator - Determines when a before filter will halt the - # callback chain, preventing following before and around callbacks from - # being called and the event from being triggered. - # This should be a lambda to be executed. - # The current object and the result lambda of the callback will be provided - # to the terminator lambda. - # - # define_callbacks :validate, terminator: ->(target, result_lambda) { result_lambda.call == false } - # - # In this example, if any before validate callbacks returns +false+, - # any successive before and around callback is not executed. - # - # The default terminator halts the chain when a callback throws +:abort+. - # - # * :skip_after_callbacks_if_terminated - Determines if after - # callbacks should be terminated by the :terminator option. By - # default after callbacks are executed no matter if callback chain was - # terminated or not. This option makes sense only when :terminator - # option is specified. - # - # * :scope - Indicates which methods should be executed when an - # object is used as a callback. - # - # class Audit - # def before(caller) - # puts 'Audit: before is called' - # end - # - # def before_save(caller) - # puts 'Audit: before_save is called' - # end - # end - # - # class Account - # include ActiveSupport::Callbacks - # - # define_callbacks :save - # set_callback :save, :before, Audit.new - # - # def save - # run_callbacks :save do - # puts 'save in main' - # end - # end - # end - # - # In the above case whenever you save an account the method - # Audit#before will be called. On the other hand - # - # define_callbacks :save, scope: [:kind, :name] - # - # would trigger Audit#before_save instead. That's constructed - # by calling #{kind}_#{name} on the given instance. In this - # case "kind" is "before" and "name" is "save". In this context +:kind+ - # and +:name+ have special meanings: +:kind+ refers to the kind of - # callback (before/after/around) and +:name+ refers to the method on - # which callbacks are being defined. - # - # A declaration like - # - # define_callbacks :save, scope: [:name] - # - # would call Audit#save. - # - # ===== Notes - # - # +names+ passed to +define_callbacks+ must not end with - # !, ? or =. - # - # Calling +define_callbacks+ multiple times with the same +names+ will - # overwrite previous callbacks registered with +set_callback+. - def define_callbacks(*names) - options = names.extract_options! - - names.each do |name| - name = name.to_sym - - set_callbacks name, CallbackChain.new(name, options) - - module_eval <<-RUBY, __FILE__, __LINE__ + 1 - def _run_#{name}_callbacks(&block) - run_callbacks #{name.inspect}, &block - end - - def self._#{name}_callbacks - get_callbacks(#{name.inspect}) - end - - def self._#{name}_callbacks=(value) - set_callbacks(#{name.inspect}, value) - end - - def _#{name}_callbacks - __callbacks[#{name.inspect}] - end - RUBY - end - end - - protected - - def get_callbacks(name) # :nodoc: - __callbacks[name.to_sym] - end - - def set_callbacks(name, callbacks) # :nodoc: - self.__callbacks = __callbacks.merge(name.to_sym => callbacks) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/concern.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/concern.rb deleted file mode 100644 index 0403eb70ca..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/concern.rb +++ /dev/null @@ -1,142 +0,0 @@ -module ActiveSupport - # A typical module looks like this: - # - # module M - # def self.included(base) - # base.extend ClassMethods - # base.class_eval do - # scope :disabled, -> { where(disabled: true) } - # end - # end - # - # module ClassMethods - # ... - # end - # end - # - # By using ActiveSupport::Concern the above module could instead be - # written as: - # - # require 'active_support/concern' - # - # module M - # extend ActiveSupport::Concern - # - # included do - # scope :disabled, -> { where(disabled: true) } - # end - # - # class_methods do - # ... - # end - # end - # - # Moreover, it gracefully handles module dependencies. Given a +Foo+ module - # and a +Bar+ module which depends on the former, we would typically write the - # following: - # - # module Foo - # def self.included(base) - # base.class_eval do - # def self.method_injected_by_foo - # ... - # end - # end - # end - # end - # - # module Bar - # def self.included(base) - # base.method_injected_by_foo - # end - # end - # - # class Host - # include Foo # We need to include this dependency for Bar - # include Bar # Bar is the module that Host really needs - # end - # - # But why should +Host+ care about +Bar+'s dependencies, namely +Foo+? We - # could try to hide these from +Host+ directly including +Foo+ in +Bar+: - # - # module Bar - # include Foo - # def self.included(base) - # base.method_injected_by_foo - # end - # end - # - # class Host - # include Bar - # end - # - # Unfortunately this won't work, since when +Foo+ is included, its base - # is the +Bar+ module, not the +Host+ class. With ActiveSupport::Concern, - # module dependencies are properly resolved: - # - # require 'active_support/concern' - # - # module Foo - # extend ActiveSupport::Concern - # included do - # def self.method_injected_by_foo - # ... - # end - # end - # end - # - # module Bar - # extend ActiveSupport::Concern - # include Foo - # - # included do - # self.method_injected_by_foo - # end - # end - # - # class Host - # include Bar # It works, now Bar takes care of its dependencies - # end - module Concern - class MultipleIncludedBlocks < StandardError #:nodoc: - def initialize - super "Cannot define multiple 'included' blocks for a Concern" - end - end - - def self.extended(base) #:nodoc: - base.instance_variable_set(:@_dependencies, []) - end - - def append_features(base) - if base.instance_variable_defined?(:@_dependencies) - base.instance_variable_get(:@_dependencies) << self - return false - else - return false if base < self - @_dependencies.each { |dep| base.include(dep) } - super - base.extend const_get(:ClassMethods) if const_defined?(:ClassMethods) - base.class_eval(&@_included_block) if instance_variable_defined?(:@_included_block) - end - end - - def included(base = nil, &block) - if base.nil? - raise MultipleIncludedBlocks if instance_variable_defined?(:@_included_block) - - @_included_block = block - else - super - end - end - - def class_methods(&class_methods_module_definition) - mod = const_defined?(:ClassMethods, false) ? - const_get(:ClassMethods) : - const_set(:ClassMethods, Module.new) - - mod.module_eval(&class_methods_module_definition) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/concurrency/load_interlock_aware_monitor.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/concurrency/load_interlock_aware_monitor.rb deleted file mode 100644 index a8455c0048..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/concurrency/load_interlock_aware_monitor.rb +++ /dev/null @@ -1,17 +0,0 @@ -# frozen_string_literal: true - -require "monitor" - -module ActiveSupport - module Concurrency - # A monitor that will permit dependency loading while blocked waiting for - # the lock. - class LoadInterlockAwareMonitor < Monitor - # Enters an exclusive section, but allows dependency loading while blocked - def mon_enter - mon_try_enter || - ActiveSupport::Dependencies.interlock.permit_concurrent_loads { super } - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/concurrency/share_lock.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/concurrency/share_lock.rb deleted file mode 100644 index 4318523b07..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/concurrency/share_lock.rb +++ /dev/null @@ -1,225 +0,0 @@ -require "thread" -require "monitor" - -module ActiveSupport - module Concurrency - # A share/exclusive lock, otherwise known as a read/write lock. - # - # https://en.wikipedia.org/wiki/Readers%E2%80%93writer_lock - class ShareLock - include MonitorMixin - - # We track Thread objects, instead of just using counters, because - # we need exclusive locks to be reentrant, and we need to be able - # to upgrade share locks to exclusive. - - def raw_state # :nodoc: - synchronize do - threads = @sleeping.keys | @sharing.keys | @waiting.keys - threads |= [@exclusive_thread] if @exclusive_thread - - data = {} - - threads.each do |thread| - purpose, compatible = @waiting[thread] - - data[thread] = { - thread: thread, - sharing: @sharing[thread], - exclusive: @exclusive_thread == thread, - purpose: purpose, - compatible: compatible, - waiting: !!@waiting[thread], - sleeper: @sleeping[thread], - } - end - - # NB: Yields while holding our *internal* synchronize lock, - # which is supposed to be used only for a few instructions at - # a time. This allows the caller to inspect additional state - # without things changing out from underneath, but would have - # disastrous effects upon normal operation. Fortunately, this - # method is only intended to be called when things have - # already gone wrong. - yield data - end - end - - def initialize - super() - - @cv = new_cond - - @sharing = Hash.new(0) - @waiting = {} - @sleeping = {} - @exclusive_thread = nil - @exclusive_depth = 0 - end - - # Returns false if +no_wait+ is set and the lock is not - # immediately available. Otherwise, returns true after the lock - # has been acquired. - # - # +purpose+ and +compatible+ work together; while this thread is - # waiting for the exclusive lock, it will yield its share (if any) - # to any other attempt whose +purpose+ appears in this attempt's - # +compatible+ list. This allows a "loose" upgrade, which, being - # less strict, prevents some classes of deadlocks. - # - # For many resources, loose upgrades are sufficient: if a thread - # is awaiting a lock, it is not running any other code. With - # +purpose+ matching, it is possible to yield only to other - # threads whose activity will not interfere. - def start_exclusive(purpose: nil, compatible: [], no_wait: false) - synchronize do - unless @exclusive_thread == Thread.current - if busy_for_exclusive?(purpose) - return false if no_wait - - yield_shares(purpose: purpose, compatible: compatible, block_share: true) do - wait_for(:start_exclusive) { busy_for_exclusive?(purpose) } - end - end - @exclusive_thread = Thread.current - end - @exclusive_depth += 1 - - true - end - end - - # Relinquish the exclusive lock. Must only be called by the thread - # that called start_exclusive (and currently holds the lock). - def stop_exclusive(compatible: []) - synchronize do - raise "invalid unlock" if @exclusive_thread != Thread.current - - @exclusive_depth -= 1 - if @exclusive_depth == 0 - @exclusive_thread = nil - - if eligible_waiters?(compatible) - yield_shares(compatible: compatible, block_share: true) do - wait_for(:stop_exclusive) { @exclusive_thread || eligible_waiters?(compatible) } - end - end - @cv.broadcast - end - end - end - - def start_sharing - synchronize do - if @sharing[Thread.current] > 0 || @exclusive_thread == Thread.current - # We already hold a lock; nothing to wait for - elsif @waiting[Thread.current] - # We're nested inside a +yield_shares+ call: we'll resume as - # soon as there isn't an exclusive lock in our way - wait_for(:start_sharing) { @exclusive_thread } - else - # This is an initial / outermost share call: any outstanding - # requests for an exclusive lock get to go first - wait_for(:start_sharing) { busy_for_sharing?(false) } - end - @sharing[Thread.current] += 1 - end - end - - def stop_sharing - synchronize do - if @sharing[Thread.current] > 1 - @sharing[Thread.current] -= 1 - else - @sharing.delete Thread.current - @cv.broadcast - end - end - end - - # Execute the supplied block while holding the Exclusive lock. If - # +no_wait+ is set and the lock is not immediately available, - # returns +nil+ without yielding. Otherwise, returns the result of - # the block. - # - # See +start_exclusive+ for other options. - def exclusive(purpose: nil, compatible: [], after_compatible: [], no_wait: false) - if start_exclusive(purpose: purpose, compatible: compatible, no_wait: no_wait) - begin - yield - ensure - stop_exclusive(compatible: after_compatible) - end - end - end - - # Execute the supplied block while holding the Share lock. - def sharing - start_sharing - begin - yield - ensure - stop_sharing - end - end - - # Temporarily give up all held Share locks while executing the - # supplied block, allowing any +compatible+ exclusive lock request - # to proceed. - def yield_shares(purpose: nil, compatible: [], block_share: false) - loose_shares = previous_wait = nil - synchronize do - if loose_shares = @sharing.delete(Thread.current) - if previous_wait = @waiting[Thread.current] - purpose = nil unless purpose == previous_wait[0] - compatible &= previous_wait[1] - end - compatible |= [false] unless block_share - @waiting[Thread.current] = [purpose, compatible] - end - - @cv.broadcast - end - - begin - yield - ensure - synchronize do - wait_for(:yield_shares) { @exclusive_thread && @exclusive_thread != Thread.current } - - if previous_wait - @waiting[Thread.current] = previous_wait - else - @waiting.delete Thread.current - end - @sharing[Thread.current] = loose_shares if loose_shares - end - end - end - - private - - # Must be called within synchronize - def busy_for_exclusive?(purpose) - busy_for_sharing?(purpose) || - @sharing.size > (@sharing[Thread.current] > 0 ? 1 : 0) - end - - def busy_for_sharing?(purpose) - (@exclusive_thread && @exclusive_thread != Thread.current) || - @waiting.any? { |t, (_, c)| t != Thread.current && !c.include?(purpose) } - end - - def eligible_waiters?(compatible) - @waiting.any? { |t, (p, _)| compatible.include?(p) && @waiting.all? { |t2, (_, c2)| t == t2 || c2.include?(p) } } - end - - def wait_for(method) - @sleeping[Thread.current] = method - @cv.wait_while { yield } - ensure - @sleeping.delete Thread.current - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/configurable.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/configurable.rb deleted file mode 100644 index f72a893bcc..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/configurable.rb +++ /dev/null @@ -1,148 +0,0 @@ -require "active_support/concern" -require "active_support/ordered_options" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/regexp" - -module ActiveSupport - # Configurable provides a config method to store and retrieve - # configuration options as an OrderedHash. - module Configurable - extend ActiveSupport::Concern - - class Configuration < ActiveSupport::InheritableOptions - def compile_methods! - self.class.compile_methods!(keys) - end - - # Compiles reader methods so we don't have to go through method_missing. - def self.compile_methods!(keys) - keys.reject { |m| method_defined?(m) }.each do |key| - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{key}; _get(#{key.inspect}); end - RUBY - end - end - end - - module ClassMethods - def config - @_config ||= if respond_to?(:superclass) && superclass.respond_to?(:config) - superclass.config.inheritable_copy - else - # create a new "anonymous" class that will host the compiled reader methods - Class.new(Configuration).new - end - end - - def configure - yield config - end - - # Allows you to add shortcut so that you don't have to refer to attribute - # through config. Also look at the example for config to contrast. - # - # Defines both class and instance config accessors. - # - # class User - # include ActiveSupport::Configurable - # config_accessor :allowed_access - # end - # - # User.allowed_access # => nil - # User.allowed_access = false - # User.allowed_access # => false - # - # user = User.new - # user.allowed_access # => false - # user.allowed_access = true - # user.allowed_access # => true - # - # User.allowed_access # => false - # - # The attribute name must be a valid method name in Ruby. - # - # class User - # include ActiveSupport::Configurable - # config_accessor :"1_Badname" - # end - # # => NameError: invalid config attribute name - # - # To opt out of the instance writer method, pass instance_writer: false. - # To opt out of the instance reader method, pass instance_reader: false. - # - # class User - # include ActiveSupport::Configurable - # config_accessor :allowed_access, instance_reader: false, instance_writer: false - # end - # - # User.allowed_access = false - # User.allowed_access # => false - # - # User.new.allowed_access = true # => NoMethodError - # User.new.allowed_access # => NoMethodError - # - # Or pass instance_accessor: false, to opt out both instance methods. - # - # class User - # include ActiveSupport::Configurable - # config_accessor :allowed_access, instance_accessor: false - # end - # - # User.allowed_access = false - # User.allowed_access # => false - # - # User.new.allowed_access = true # => NoMethodError - # User.new.allowed_access # => NoMethodError - # - # Also you can pass a block to set up the attribute with a default value. - # - # class User - # include ActiveSupport::Configurable - # config_accessor :hair_colors do - # [:brown, :black, :blonde, :red] - # end - # end - # - # User.hair_colors # => [:brown, :black, :blonde, :red] - def config_accessor(*names) - options = names.extract_options! - - names.each do |name| - raise NameError.new("invalid config attribute name") unless /\A[_A-Za-z]\w*\z/.match?(name) - - reader, reader_line = "def #{name}; config.#{name}; end", __LINE__ - writer, writer_line = "def #{name}=(value); config.#{name} = value; end", __LINE__ - - singleton_class.class_eval reader, __FILE__, reader_line - singleton_class.class_eval writer, __FILE__, writer_line - - unless options[:instance_accessor] == false - class_eval reader, __FILE__, reader_line unless options[:instance_reader] == false - class_eval writer, __FILE__, writer_line unless options[:instance_writer] == false - end - send("#{name}=", yield) if block_given? - end - end - private :config_accessor - end - - # Reads and writes attributes from a configuration OrderedHash. - # - # require 'active_support/configurable' - # - # class User - # include ActiveSupport::Configurable - # end - # - # user = User.new - # - # user.config.allowed_access = true - # user.config.level = 1 - # - # user.config.allowed_access # => true - # user.config.level # => 1 - def config - @_config ||= self.class.config.inheritable_copy - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext.rb deleted file mode 100644 index f397f658f3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext.rb +++ /dev/null @@ -1,3 +0,0 @@ -(Dir["#{File.dirname(__FILE__)}/core_ext/*.rb"]).each do |path| - require path -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array.rb deleted file mode 100644 index e908386a1c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array.rb +++ /dev/null @@ -1,7 +0,0 @@ -require "active_support/core_ext/array/wrap" -require "active_support/core_ext/array/access" -require "active_support/core_ext/array/conversions" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/array/grouping" -require "active_support/core_ext/array/prepend_and_append" -require "active_support/core_ext/array/inquiry" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/access.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/access.rb deleted file mode 100644 index fca33c9d69..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/access.rb +++ /dev/null @@ -1,90 +0,0 @@ -class Array - # Returns the tail of the array from +position+. - # - # %w( a b c d ).from(0) # => ["a", "b", "c", "d"] - # %w( a b c d ).from(2) # => ["c", "d"] - # %w( a b c d ).from(10) # => [] - # %w().from(0) # => [] - # %w( a b c d ).from(-2) # => ["c", "d"] - # %w( a b c ).from(-10) # => [] - def from(position) - self[position, length] || [] - end - - # Returns the beginning of the array up to +position+. - # - # %w( a b c d ).to(0) # => ["a"] - # %w( a b c d ).to(2) # => ["a", "b", "c"] - # %w( a b c d ).to(10) # => ["a", "b", "c", "d"] - # %w().to(0) # => [] - # %w( a b c d ).to(-2) # => ["a", "b", "c"] - # %w( a b c ).to(-10) # => [] - def to(position) - if position >= 0 - take position + 1 - else - self[0..position] - end - end - - # Returns a copy of the Array without the specified elements. - # - # people = ["David", "Rafael", "Aaron", "Todd"] - # people.without "Aaron", "Todd" - # # => ["David", "Rafael"] - # - # Note: This is an optimization of `Enumerable#without` that uses `Array#-` - # instead of `Array#reject` for performance reasons. - def without(*elements) - self - elements - end - - # Equal to self[1]. - # - # %w( a b c d e ).second # => "b" - def second - self[1] - end - - # Equal to self[2]. - # - # %w( a b c d e ).third # => "c" - def third - self[2] - end - - # Equal to self[3]. - # - # %w( a b c d e ).fourth # => "d" - def fourth - self[3] - end - - # Equal to self[4]. - # - # %w( a b c d e ).fifth # => "e" - def fifth - self[4] - end - - # Equal to self[41]. Also known as accessing "the reddit". - # - # (1..42).to_a.forty_two # => 42 - def forty_two - self[41] - end - - # Equal to self[-3]. - # - # %w( a b c d e ).third_to_last # => "c" - def third_to_last - self[-3] - end - - # Equal to self[-2]. - # - # %w( a b c d e ).second_to_last # => "d" - def second_to_last - self[-2] - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/conversions.rb deleted file mode 100644 index cac15e1100..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/conversions.rb +++ /dev/null @@ -1,211 +0,0 @@ -require "active_support/xml_mini" -require "active_support/core_ext/hash/keys" -require "active_support/core_ext/string/inflections" -require "active_support/core_ext/object/to_param" -require "active_support/core_ext/object/to_query" - -class Array - # Converts the array to a comma-separated sentence where the last element is - # joined by the connector word. - # - # You can pass the following options to change the default behavior. If you - # pass an option key that doesn't exist in the list below, it will raise an - # ArgumentError. - # - # ==== Options - # - # * :words_connector - The sign or word used to join the elements - # in arrays with two or more elements (default: ", "). - # * :two_words_connector - The sign or word used to join the elements - # in arrays with two elements (default: " and "). - # * :last_word_connector - The sign or word used to join the last element - # in arrays with three or more elements (default: ", and "). - # * :locale - If +i18n+ is available, you can set a locale and use - # the connector options defined on the 'support.array' namespace in the - # corresponding dictionary file. - # - # ==== Examples - # - # [].to_sentence # => "" - # ['one'].to_sentence # => "one" - # ['one', 'two'].to_sentence # => "one and two" - # ['one', 'two', 'three'].to_sentence # => "one, two, and three" - # - # ['one', 'two'].to_sentence(passing: 'invalid option') - # # => ArgumentError: Unknown key: :passing. Valid keys are: :words_connector, :two_words_connector, :last_word_connector, :locale - # - # ['one', 'two'].to_sentence(two_words_connector: '-') - # # => "one-two" - # - # ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ') - # # => "one or two or at least three" - # - # Using :locale option: - # - # # Given this locale dictionary: - # # - # # es: - # # support: - # # array: - # # words_connector: " o " - # # two_words_connector: " y " - # # last_word_connector: " o al menos " - # - # ['uno', 'dos'].to_sentence(locale: :es) - # # => "uno y dos" - # - # ['uno', 'dos', 'tres'].to_sentence(locale: :es) - # # => "uno o dos o al menos tres" - def to_sentence(options = {}) - options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) - - default_connectors = { - words_connector: ", ", - two_words_connector: " and ", - last_word_connector: ", and " - } - if defined?(I18n) - i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {}) - default_connectors.merge!(i18n_connectors) - end - options = default_connectors.merge!(options) - - case length - when 0 - "" - when 1 - "#{self[0]}" - when 2 - "#{self[0]}#{options[:two_words_connector]}#{self[1]}" - else - "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}" - end - end - - # Extends Array#to_s to convert a collection of elements into a - # comma separated id list if :db argument is given as the format. - # - # Blog.all.to_formatted_s(:db) # => "1,2,3" - # Blog.none.to_formatted_s(:db) # => "null" - # [1,2].to_formatted_s # => "[1, 2]" - def to_formatted_s(format = :default) - case format - when :db - if empty? - "null" - else - collect(&:id).join(",") - end - else - to_default_s - end - end - alias_method :to_default_s, :to_s - alias_method :to_s, :to_formatted_s - - # Returns a string that represents the array in XML by invoking +to_xml+ - # on each element. Active Record collections delegate their representation - # in XML to this method. - # - # All elements are expected to respond to +to_xml+, if any of them does - # not then an exception is raised. - # - # The root node reflects the class name of the first element in plural - # if all elements belong to the same type and that's not Hash: - # - # customer.projects.to_xml - # - # - # - # - # 20000.0 - # 1567 - # 2008-04-09 - # ... - # - # - # 57230.0 - # 1567 - # 2008-04-15 - # ... - # - # - # - # Otherwise the root element is "objects": - # - # [{ foo: 1, bar: 2}, { baz: 3}].to_xml - # - # - # - # - # 2 - # 1 - # - # - # 3 - # - # - # - # If the collection is empty the root element is "nil-classes" by default: - # - # [].to_xml - # - # - # - # - # To ensure a meaningful root element use the :root option: - # - # customer_with_no_projects.projects.to_xml(root: 'projects') - # - # - # - # - # By default name of the node for the children of root is root.singularize. - # You can change it with the :children option. - # - # The +options+ hash is passed downwards: - # - # Message.all.to_xml(skip_types: true) - # - # - # - # - # 2008-03-07T09:58:18+01:00 - # 1 - # 1 - # 2008-03-07T09:58:18+01:00 - # 1 - # - # - # - def to_xml(options = {}) - require "active_support/builder" unless defined?(Builder) - - options = options.dup - options[:indent] ||= 2 - options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent]) - options[:root] ||= \ - if first.class != Hash && all? { |e| e.is_a?(first.class) } - underscored = ActiveSupport::Inflector.underscore(first.class.name) - ActiveSupport::Inflector.pluralize(underscored).tr("/", "_") - else - "objects" - end - - builder = options[:builder] - builder.instruct! unless options.delete(:skip_instruct) - - root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options) - children = options.delete(:children) || root.singularize - attributes = options[:skip_types] ? {} : { type: "array" } - - if empty? - builder.tag!(root, attributes) - else - builder.tag!(root, attributes) do - each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) } - yield builder if block_given? - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/extract_options.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/extract_options.rb deleted file mode 100644 index 9008a0df2a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/extract_options.rb +++ /dev/null @@ -1,29 +0,0 @@ -class Hash - # By default, only instances of Hash itself are extractable. - # Subclasses of Hash may implement this method and return - # true to declare themselves as extractable. If a Hash - # is extractable, Array#extract_options! pops it from - # the Array when it is the last element of the Array. - def extractable_options? - instance_of?(Hash) - end -end - -class Array - # Extracts options from a set of arguments. Removes and returns the last - # element in the array if it's a hash, otherwise returns a blank hash. - # - # def options(*args) - # args.extract_options! - # end - # - # options(1, 2) # => {} - # options(1, 2, a: :b) # => {:a=>:b} - def extract_options! - if last.is_a?(Hash) && last.extractable_options? - pop - else - {} - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/grouping.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/grouping.rb deleted file mode 100644 index 0d798e5c4e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/grouping.rb +++ /dev/null @@ -1,107 +0,0 @@ -class Array - # Splits or iterates over the array in groups of size +number+, - # padding any remaining slots with +fill_with+ unless it is +false+. - # - # %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group} - # ["1", "2", "3"] - # ["4", "5", "6"] - # ["7", "8", "9"] - # ["10", nil, nil] - # - # %w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group} - # ["1", "2"] - # ["3", "4"] - # ["5", " "] - # - # %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group} - # ["1", "2"] - # ["3", "4"] - # ["5"] - def in_groups_of(number, fill_with = nil) - if number.to_i <= 0 - raise ArgumentError, - "Group size must be a positive integer, was #{number.inspect}" - end - - if fill_with == false - collection = self - else - # size % number gives how many extra we have; - # subtracting from number gives how many to add; - # modulo number ensures we don't add group of just fill. - padding = (number - size % number) % number - collection = dup.concat(Array.new(padding, fill_with)) - end - - if block_given? - collection.each_slice(number) { |slice| yield(slice) } - else - collection.each_slice(number).to_a - end - end - - # Splits or iterates over the array in +number+ of groups, padding any - # remaining slots with +fill_with+ unless it is +false+. - # - # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group} - # ["1", "2", "3", "4"] - # ["5", "6", "7", nil] - # ["8", "9", "10", nil] - # - # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, ' ') {|group| p group} - # ["1", "2", "3", "4"] - # ["5", "6", "7", " "] - # ["8", "9", "10", " "] - # - # %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group} - # ["1", "2", "3"] - # ["4", "5"] - # ["6", "7"] - def in_groups(number, fill_with = nil) - # size.div number gives minor group size; - # size % number gives how many objects need extra accommodation; - # each group hold either division or division + 1 items. - division = size.div number - modulo = size % number - - # create a new array avoiding dup - groups = [] - start = 0 - - number.times do |index| - length = division + (modulo > 0 && modulo > index ? 1 : 0) - groups << last_group = slice(start, length) - last_group << fill_with if fill_with != false && - modulo > 0 && length == division - start += length - end - - if block_given? - groups.each { |g| yield(g) } - else - groups - end - end - - # Divides the array into one or more subarrays based on a delimiting +value+ - # or the result of an optional block. - # - # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]] - # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]] - def split(value = nil) - arr = dup - result = [] - if block_given? - while (idx = arr.index { |i| yield i }) - result << arr.shift(idx) - arr.shift - end - else - while (idx = arr.index(value)) - result << arr.shift(idx) - arr.shift - end - end - result << arr - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/inquiry.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/inquiry.rb deleted file mode 100644 index 66fa5fcd0c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/inquiry.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "active_support/array_inquirer" - -class Array - # Wraps the array in an +ArrayInquirer+ object, which gives a friendlier way - # to check its string-like contents. - # - # pets = [:cat, :dog].inquiry - # - # pets.cat? # => true - # pets.ferret? # => false - # - # pets.any?(:cat, :ferret) # => true - # pets.any?(:ferret, :alligator) # => false - def inquiry - ActiveSupport::ArrayInquirer.new(self) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/prepend_and_append.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/prepend_and_append.rb deleted file mode 100644 index 16a6789f8d..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/prepend_and_append.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Array - # The human way of thinking about adding stuff to the end of a list is with append. - alias_method :append, :<< - - # The human way of thinking about adding stuff to the beginning of a list is with prepend. - alias_method :prepend, :unshift -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/wrap.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/wrap.rb deleted file mode 100644 index b611d34c27..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/array/wrap.rb +++ /dev/null @@ -1,46 +0,0 @@ -class Array - # Wraps its argument in an array unless it is already an array (or array-like). - # - # Specifically: - # - # * If the argument is +nil+ an empty array is returned. - # * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned. - # * Otherwise, returns an array with the argument as its single element. - # - # Array.wrap(nil) # => [] - # Array.wrap([1, 2, 3]) # => [1, 2, 3] - # Array.wrap(0) # => [0] - # - # This method is similar in purpose to Kernel#Array, but there are some differences: - # - # * If the argument responds to +to_ary+ the method is invoked. Kernel#Array - # moves on to try +to_a+ if the returned value is +nil+, but Array.wrap returns - # an array with the argument as its single element right away. - # * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, Kernel#Array - # raises an exception, while Array.wrap does not, it just returns the value. - # * It does not call +to_a+ on the argument, if the argument does not respond to +to_ary+ - # it returns an array with the argument as its single element. - # - # The last point is easily explained with some enumerables: - # - # Array(foo: :bar) # => [[:foo, :bar]] - # Array.wrap(foo: :bar) # => [{:foo=>:bar}] - # - # There's also a related idiom that uses the splat operator: - # - # [*object] - # - # which returns [] for +nil+, but calls to Array(object) otherwise. - # - # The differences with Kernel#Array explained above - # apply to the rest of objects. - def self.wrap(object) - if object.nil? - [] - elsif object.respond_to?(:to_ary) - object.to_ary || [object] - else - [object] - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/benchmark.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/benchmark.rb deleted file mode 100644 index 2300953860..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/benchmark.rb +++ /dev/null @@ -1,14 +0,0 @@ -require "benchmark" - -class << Benchmark - # Benchmark realtime in milliseconds. - # - # Benchmark.realtime { User.all } - # # => 8.0e-05 - # - # Benchmark.ms { User.all } - # # => 0.074 - def ms - 1000 * realtime { yield } - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/big_decimal.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/big_decimal.rb deleted file mode 100644 index 7b4f87f10e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/big_decimal.rb +++ /dev/null @@ -1 +0,0 @@ -require "active_support/core_ext/big_decimal/conversions" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/big_decimal/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/big_decimal/conversions.rb deleted file mode 100644 index decd4e1699..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/big_decimal/conversions.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "bigdecimal" -require "bigdecimal/util" - -module ActiveSupport - module BigDecimalWithDefaultFormat #:nodoc: - def to_s(format = "F") - super(format) - end - end -end - -BigDecimal.prepend(ActiveSupport::BigDecimalWithDefaultFormat) diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class.rb deleted file mode 100644 index 6a19e862d0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class.rb +++ /dev/null @@ -1,2 +0,0 @@ -require "active_support/core_ext/class/attribute" -require "active_support/core_ext/class/subclasses" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/attribute.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/attribute.rb deleted file mode 100644 index ba422f9071..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/attribute.rb +++ /dev/null @@ -1,128 +0,0 @@ -require "active_support/core_ext/kernel/singleton_class" -require "active_support/core_ext/module/remove_method" -require "active_support/core_ext/array/extract_options" - -class Class - # Declare a class-level attribute whose value is inheritable by subclasses. - # Subclasses can change their own value and it will not impact parent class. - # - # class Base - # class_attribute :setting - # end - # - # class Subclass < Base - # end - # - # Base.setting = true - # Subclass.setting # => true - # Subclass.setting = false - # Subclass.setting # => false - # Base.setting # => true - # - # In the above case as long as Subclass does not assign a value to setting - # by performing Subclass.setting = _something_, Subclass.setting - # would read value assigned to parent class. Once Subclass assigns a value then - # the value assigned by Subclass would be returned. - # - # This matches normal Ruby method inheritance: think of writing an attribute - # on a subclass as overriding the reader method. However, you need to be aware - # when using +class_attribute+ with mutable structures as +Array+ or +Hash+. - # In such cases, you don't want to do changes in place. Instead use setters: - # - # Base.setting = [] - # Base.setting # => [] - # Subclass.setting # => [] - # - # # Appending in child changes both parent and child because it is the same object: - # Subclass.setting << :foo - # Base.setting # => [:foo] - # Subclass.setting # => [:foo] - # - # # Use setters to not propagate changes: - # Base.setting = [] - # Subclass.setting += [:foo] - # Base.setting # => [] - # Subclass.setting # => [:foo] - # - # For convenience, an instance predicate method is defined as well. - # To skip it, pass instance_predicate: false. - # - # Subclass.setting? # => false - # - # Instances may overwrite the class value in the same way: - # - # Base.setting = true - # object = Base.new - # object.setting # => true - # object.setting = false - # object.setting # => false - # Base.setting # => true - # - # To opt out of the instance reader method, pass instance_reader: false. - # - # object.setting # => NoMethodError - # object.setting? # => NoMethodError - # - # To opt out of the instance writer method, pass instance_writer: false. - # - # object.setting = false # => NoMethodError - # - # To opt out of both instance methods, pass instance_accessor: false. - def class_attribute(*attrs) - options = attrs.extract_options! - instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true) - instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true) - instance_predicate = options.fetch(:instance_predicate, true) - - attrs.each do |name| - remove_possible_singleton_method(name) - define_singleton_method(name) { nil } - - remove_possible_singleton_method("#{name}?") - define_singleton_method("#{name}?") { !!public_send(name) } if instance_predicate - - ivar = "@#{name}" - - remove_possible_singleton_method("#{name}=") - define_singleton_method("#{name}=") do |val| - singleton_class.class_eval do - remove_possible_method(name) - define_method(name) { val } - end - - if singleton_class? - class_eval do - remove_possible_method(name) - define_method(name) do - if instance_variable_defined? ivar - instance_variable_get ivar - else - singleton_class.send name - end - end - end - end - val - end - - if instance_reader - remove_possible_method name - define_method(name) do - if instance_variable_defined?(ivar) - instance_variable_get ivar - else - self.class.public_send name - end - end - - remove_possible_method "#{name}?" - define_method("#{name}?") { !!public_send(name) } if instance_predicate - end - - if instance_writer - remove_possible_method "#{name}=" - attr_writer name - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/attribute_accessors.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/attribute_accessors.rb deleted file mode 100644 index 0f767925ed..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/attribute_accessors.rb +++ /dev/null @@ -1,4 +0,0 @@ -# cattr_* became mattr_* aliases in 7dfbd91b0780fbd6a1dd9bfbc176e10894871d2d, -# but we keep this around for libraries that directly require it knowing they -# want cattr_*. No need to deprecate. -require "active_support/core_ext/module/attribute_accessors" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/subclasses.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/subclasses.rb deleted file mode 100644 index 62397d9508..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/class/subclasses.rb +++ /dev/null @@ -1,55 +0,0 @@ -require "active_support/core_ext/module/anonymous" -require "active_support/core_ext/module/reachable" - -class Class - begin - # Test if this Ruby supports each_object against singleton_class - ObjectSpace.each_object(Numeric.singleton_class) {} - - # Returns an array with all classes that are < than its receiver. - # - # class C; end - # C.descendants # => [] - # - # class B < C; end - # C.descendants # => [B] - # - # class A < B; end - # C.descendants # => [B, A] - # - # class D < C; end - # C.descendants # => [B, A, D] - def descendants - descendants = [] - ObjectSpace.each_object(singleton_class) do |k| - next if k.singleton_class? - descendants.unshift k unless k == self - end - descendants - end - rescue StandardError # JRuby 9.0.4.0 and earlier - def descendants - descendants = [] - ObjectSpace.each_object(Class) do |k| - descendants.unshift k if k < self - end - descendants.uniq! - descendants - end - end - - # Returns an array with the direct children of +self+. - # - # class Foo; end - # class Bar < Foo; end - # class Baz < Bar; end - # - # Foo.subclasses # => [Bar] - def subclasses - subclasses, chain = [], descendants - chain.each do |k| - subclasses << k unless chain.any? { |c| c > k } - end - subclasses - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date.rb deleted file mode 100644 index 4f66804da2..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "active_support/core_ext/date/acts_like" -require "active_support/core_ext/date/blank" -require "active_support/core_ext/date/calculations" -require "active_support/core_ext/date/conversions" -require "active_support/core_ext/date/zones" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/acts_like.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/acts_like.rb deleted file mode 100644 index 46fe99ad47..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/acts_like.rb +++ /dev/null @@ -1,8 +0,0 @@ -require "active_support/core_ext/object/acts_like" - -class Date - # Duck-types as a Date-like class. See Object#acts_like?. - def acts_like_date? - true - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/blank.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/blank.rb deleted file mode 100644 index edd2847126..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/blank.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "date" - -class Date #:nodoc: - # No Date is blank: - # - # Date.today.blank? # => false - # - # @return [false] - def blank? - false - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/calculations.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/calculations.rb deleted file mode 100644 index d6f60cac04..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/calculations.rb +++ /dev/null @@ -1,143 +0,0 @@ -require "date" -require "active_support/duration" -require "active_support/core_ext/object/acts_like" -require "active_support/core_ext/date/zones" -require "active_support/core_ext/time/zones" -require "active_support/core_ext/date_and_time/calculations" - -class Date - include DateAndTime::Calculations - - class << self - attr_accessor :beginning_of_week_default - - # Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=). - # If Date.beginning_of_week has not been set for the current request, returns the week start specified in config.beginning_of_week. - # If no config.beginning_of_week was specified, returns :monday. - def beginning_of_week - Thread.current[:beginning_of_week] || beginning_of_week_default || :monday - end - - # Sets Date.beginning_of_week to a week start (e.g. :monday) for current request/thread. - # - # This method accepts any of the following day symbols: - # :monday, :tuesday, :wednesday, :thursday, :friday, :saturday, :sunday - def beginning_of_week=(week_start) - Thread.current[:beginning_of_week] = find_beginning_of_week!(week_start) - end - - # Returns week start day symbol (e.g. :monday), or raises an +ArgumentError+ for invalid day symbol. - def find_beginning_of_week!(week_start) - raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start) - week_start - end - - # Returns a new Date representing the date 1 day ago (i.e. yesterday's date). - def yesterday - ::Date.current.yesterday - end - - # Returns a new Date representing the date 1 day after today (i.e. tomorrow's date). - def tomorrow - ::Date.current.tomorrow - end - - # Returns Time.zone.today when Time.zone or config.time_zone are set, otherwise just returns Date.today. - def current - ::Time.zone ? ::Time.zone.today : ::Date.today - end - end - - # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00) - # and then subtracts the specified number of seconds. - def ago(seconds) - in_time_zone.since(-seconds) - end - - # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00) - # and then adds the specified number of seconds - def since(seconds) - in_time_zone.since(seconds) - end - alias :in :since - - # Converts Date to a Time (or DateTime if necessary) with the time portion set to the beginning of the day (0:00) - def beginning_of_day - in_time_zone - end - alias :midnight :beginning_of_day - alias :at_midnight :beginning_of_day - alias :at_beginning_of_day :beginning_of_day - - # Converts Date to a Time (or DateTime if necessary) with the time portion set to the middle of the day (12:00) - def middle_of_day - in_time_zone.middle_of_day - end - alias :midday :middle_of_day - alias :noon :middle_of_day - alias :at_midday :middle_of_day - alias :at_noon :middle_of_day - alias :at_middle_of_day :middle_of_day - - # Converts Date to a Time (or DateTime if necessary) with the time portion set to the end of the day (23:59:59) - def end_of_day - in_time_zone.end_of_day - end - alias :at_end_of_day :end_of_day - - def plus_with_duration(other) #:nodoc: - if ActiveSupport::Duration === other - other.since(self) - else - plus_without_duration(other) - end - end - alias_method :plus_without_duration, :+ - alias_method :+, :plus_with_duration - - def minus_with_duration(other) #:nodoc: - if ActiveSupport::Duration === other - plus_with_duration(-other) - else - minus_without_duration(other) - end - end - alias_method :minus_without_duration, :- - alias_method :-, :minus_with_duration - - # Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with - # any of these keys: :years, :months, :weeks, :days. - def advance(options) - options = options.dup - d = self - d = d >> options.delete(:years) * 12 if options[:years] - d = d >> options.delete(:months) if options[:months] - d = d + options.delete(:weeks) * 7 if options[:weeks] - d = d + options.delete(:days) if options[:days] - d - end - - # Returns a new Date where one or more of the elements have been changed according to the +options+ parameter. - # The +options+ parameter is a hash with a combination of these keys: :year, :month, :day. - # - # Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1) - # Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12) - def change(options) - ::Date.new( - options.fetch(:year, year), - options.fetch(:month, month), - options.fetch(:day, day) - ) - end - - # Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there. - def compare_with_coercion(other) - if other.is_a?(Time) - to_datetime <=> other - else - compare_without_coercion(other) - end - end - alias_method :compare_without_coercion, :<=> - alias_method :<=>, :compare_with_coercion -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/conversions.rb deleted file mode 100644 index d553406dff..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/conversions.rb +++ /dev/null @@ -1,95 +0,0 @@ -require "date" -require "active_support/inflector/methods" -require "active_support/core_ext/date/zones" -require "active_support/core_ext/module/remove_method" - -class Date - DATE_FORMATS = { - short: "%d %b", - long: "%B %d, %Y", - db: "%Y-%m-%d", - number: "%Y%m%d", - long_ordinal: lambda { |date| - day_format = ActiveSupport::Inflector.ordinalize(date.day) - date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007" - }, - rfc822: "%d %b %Y", - iso8601: lambda { |date| date.iso8601 } - } - - # Ruby 1.9 has Date#to_time which converts to localtime only. - remove_method :to_time - - # Ruby 1.9 has Date#xmlschema which converts to a string without the time - # component. This removal may generate an issue on FreeBSD, that's why we - # need to use remove_possible_method here - remove_possible_method :xmlschema - - # Convert to a formatted string. See DATE_FORMATS for predefined formats. - # - # This method is aliased to to_s. - # - # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 - # - # date.to_formatted_s(:db) # => "2007-11-10" - # date.to_s(:db) # => "2007-11-10" - # - # date.to_formatted_s(:short) # => "10 Nov" - # date.to_formatted_s(:number) # => "20071110" - # date.to_formatted_s(:long) # => "November 10, 2007" - # date.to_formatted_s(:long_ordinal) # => "November 10th, 2007" - # date.to_formatted_s(:rfc822) # => "10 Nov 2007" - # date.to_formatted_s(:iso8601) # => "2007-11-10" - # - # == Adding your own date formats to to_formatted_s - # You can add your own formats to the Date::DATE_FORMATS hash. - # Use the format name as the hash key and either a strftime string - # or Proc instance that takes a date argument as the value. - # - # # config/initializers/date_formats.rb - # Date::DATE_FORMATS[:month_and_year] = '%B %Y' - # Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") } - def to_formatted_s(format = :default) - if formatter = DATE_FORMATS[format] - if formatter.respond_to?(:call) - formatter.call(self).to_s - else - strftime(formatter) - end - else - to_default_s - end - end - alias_method :to_default_s, :to_s - alias_method :to_s, :to_formatted_s - - # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005" - def readable_inspect - strftime("%a, %d %b %Y") - end - alias_method :default_inspect, :inspect - alias_method :inspect, :readable_inspect - - # Converts a Date instance to a Time, where the time is set to the beginning of the day. - # The timezone can be either :local or :utc (default :local). - # - # date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 - # - # date.to_time # => 2007-11-10 00:00:00 0800 - # date.to_time(:local) # => 2007-11-10 00:00:00 0800 - # - # date.to_time(:utc) # => 2007-11-10 00:00:00 UTC - def to_time(form = :local) - raise ArgumentError, "Expected :local or :utc, got #{form.inspect}." unless [:local, :utc].include?(form) - ::Time.send(form, year, month, day) - end - - # Returns a string which represents the time in used time zone as DateTime - # defined by XML Schema: - # - # date = Date.new(2015, 05, 23) # => Sat, 23 May 2015 - # date.xmlschema # => "2015-05-23T00:00:00+04:00" - def xmlschema - in_time_zone.xmlschema - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/zones.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/zones.rb deleted file mode 100644 index da23fe4892..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date/zones.rb +++ /dev/null @@ -1,6 +0,0 @@ -require "date" -require "active_support/core_ext/date_and_time/zones" - -class Date - include DateAndTime::Zones -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/calculations.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/calculations.rb deleted file mode 100644 index f2ba7fdda5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/calculations.rb +++ /dev/null @@ -1,340 +0,0 @@ -require "active_support/core_ext/object/try" - -module DateAndTime - module Calculations - DAYS_INTO_WEEK = { - monday: 0, - tuesday: 1, - wednesday: 2, - thursday: 3, - friday: 4, - saturday: 5, - sunday: 6 - } - WEEKEND_DAYS = [ 6, 0 ] - - # Returns a new date/time representing yesterday. - def yesterday - advance(days: -1) - end - - # Returns a new date/time representing the previous day. - def prev_day - advance(days: -1) - end - - # Returns a new date/time representing tomorrow. - def tomorrow - advance(days: 1) - end - - # Returns a new date/time representing the next day. - def next_day - advance(days: 1) - end - - # Returns true if the date/time is today. - def today? - to_date == ::Date.current - end - - # Returns true if the date/time is in the past. - def past? - self < self.class.current - end - - # Returns true if the date/time is in the future. - def future? - self > self.class.current - end - - # Returns true if the date/time falls on a Saturday or Sunday. - def on_weekend? - WEEKEND_DAYS.include?(wday) - end - - # Returns true if the date/time does not fall on a Saturday or Sunday. - def on_weekday? - !WEEKEND_DAYS.include?(wday) - end - - # Returns a new date/time the specified number of days ago. - def days_ago(days) - advance(days: -days) - end - - # Returns a new date/time the specified number of days in the future. - def days_since(days) - advance(days: days) - end - - # Returns a new date/time the specified number of weeks ago. - def weeks_ago(weeks) - advance(weeks: -weeks) - end - - # Returns a new date/time the specified number of weeks in the future. - def weeks_since(weeks) - advance(weeks: weeks) - end - - # Returns a new date/time the specified number of months ago. - def months_ago(months) - advance(months: -months) - end - - # Returns a new date/time the specified number of months in the future. - def months_since(months) - advance(months: months) - end - - # Returns a new date/time the specified number of years ago. - def years_ago(years) - advance(years: -years) - end - - # Returns a new date/time the specified number of years in the future. - def years_since(years) - advance(years: years) - end - - # Returns a new date/time at the start of the month. - # - # today = Date.today # => Thu, 18 Jun 2015 - # today.beginning_of_month # => Mon, 01 Jun 2015 - # - # +DateTime+ objects will have a time set to 0:00. - # - # now = DateTime.current # => Thu, 18 Jun 2015 15:23:13 +0000 - # now.beginning_of_month # => Mon, 01 Jun 2015 00:00:00 +0000 - def beginning_of_month - first_hour(change(day: 1)) - end - alias :at_beginning_of_month :beginning_of_month - - # Returns a new date/time at the start of the quarter. - # - # today = Date.today # => Fri, 10 Jul 2015 - # today.beginning_of_quarter # => Wed, 01 Jul 2015 - # - # +DateTime+ objects will have a time set to 0:00. - # - # now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000 - # now.beginning_of_quarter # => Wed, 01 Jul 2015 00:00:00 +0000 - def beginning_of_quarter - first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month } - beginning_of_month.change(month: first_quarter_month) - end - alias :at_beginning_of_quarter :beginning_of_quarter - - # Returns a new date/time at the end of the quarter. - # - # today = Date.today # => Fri, 10 Jul 2015 - # today.end_of_quarter # => Wed, 30 Sep 2015 - # - # +DateTime+ objects will have a time set to 23:59:59. - # - # now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000 - # now.end_of_quarter # => Wed, 30 Sep 2015 23:59:59 +0000 - def end_of_quarter - last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month } - beginning_of_month.change(month: last_quarter_month).end_of_month - end - alias :at_end_of_quarter :end_of_quarter - - # Returns a new date/time at the beginning of the year. - # - # today = Date.today # => Fri, 10 Jul 2015 - # today.beginning_of_year # => Thu, 01 Jan 2015 - # - # +DateTime+ objects will have a time set to 0:00. - # - # now = DateTime.current # => Fri, 10 Jul 2015 18:41:29 +0000 - # now.beginning_of_year # => Thu, 01 Jan 2015 00:00:00 +0000 - def beginning_of_year - change(month: 1).beginning_of_month - end - alias :at_beginning_of_year :beginning_of_year - - # Returns a new date/time representing the given day in the next week. - # - # today = Date.today # => Thu, 07 May 2015 - # today.next_week # => Mon, 11 May 2015 - # - # The +given_day_in_next_week+ defaults to the beginning of the week - # which is determined by +Date.beginning_of_week+ or +config.beginning_of_week+ - # when set. - # - # today = Date.today # => Thu, 07 May 2015 - # today.next_week(:friday) # => Fri, 15 May 2015 - # - # +DateTime+ objects have their time set to 0:00 unless +same_time+ is true. - # - # now = DateTime.current # => Thu, 07 May 2015 13:31:16 +0000 - # now.next_week # => Mon, 11 May 2015 00:00:00 +0000 - def next_week(given_day_in_next_week = Date.beginning_of_week, same_time: false) - result = first_hour(weeks_since(1).beginning_of_week.days_since(days_span(given_day_in_next_week))) - same_time ? copy_time_to(result) : result - end - - # Returns a new date/time representing the next weekday. - def next_weekday - if next_day.on_weekend? - next_week(:monday, same_time: true) - else - next_day - end - end - - # Short-hand for months_since(1). - def next_month - months_since(1) - end - - # Short-hand for months_since(3) - def next_quarter - months_since(3) - end - - # Short-hand for years_since(1). - def next_year - years_since(1) - end - - # Returns a new date/time representing the given day in the previous week. - # Week is assumed to start on +start_day+, default is - # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. - # DateTime objects have their time set to 0:00 unless +same_time+ is true. - def prev_week(start_day = Date.beginning_of_week, same_time: false) - result = first_hour(weeks_ago(1).beginning_of_week.days_since(days_span(start_day))) - same_time ? copy_time_to(result) : result - end - alias_method :last_week, :prev_week - - # Returns a new date/time representing the previous weekday. - def prev_weekday - if prev_day.on_weekend? - copy_time_to(beginning_of_week(:friday)) - else - prev_day - end - end - alias_method :last_weekday, :prev_weekday - - # Short-hand for months_ago(1). - def prev_month - months_ago(1) - end - alias_method :last_month, :prev_month - - # Short-hand for months_ago(3). - def prev_quarter - months_ago(3) - end - alias_method :last_quarter, :prev_quarter - - # Short-hand for years_ago(1). - def prev_year - years_ago(1) - end - alias_method :last_year, :prev_year - - # Returns the number of days to the start of the week on the given day. - # Week is assumed to start on +start_day+, default is - # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. - def days_to_week_start(start_day = Date.beginning_of_week) - start_day_number = DAYS_INTO_WEEK[start_day] - current_day_number = wday != 0 ? wday - 1 : 6 - (current_day_number - start_day_number) % 7 - end - - # Returns a new date/time representing the start of this week on the given day. - # Week is assumed to start on +start_day+, default is - # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. - # +DateTime+ objects have their time set to 0:00. - def beginning_of_week(start_day = Date.beginning_of_week) - result = days_ago(days_to_week_start(start_day)) - acts_like?(:time) ? result.midnight : result - end - alias :at_beginning_of_week :beginning_of_week - - # Returns Monday of this week assuming that week starts on Monday. - # +DateTime+ objects have their time set to 0:00. - def monday - beginning_of_week(:monday) - end - - # Returns a new date/time representing the end of this week on the given day. - # Week is assumed to start on +start_day+, default is - # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. - # DateTime objects have their time set to 23:59:59. - def end_of_week(start_day = Date.beginning_of_week) - last_hour(days_since(6 - days_to_week_start(start_day))) - end - alias :at_end_of_week :end_of_week - - # Returns Sunday of this week assuming that week starts on Monday. - # +DateTime+ objects have their time set to 23:59:59. - def sunday - end_of_week(:monday) - end - - # Returns a new date/time representing the end of the month. - # DateTime objects will have a time set to 23:59:59. - def end_of_month - last_day = ::Time.days_in_month(month, year) - last_hour(days_since(last_day - day)) - end - alias :at_end_of_month :end_of_month - - # Returns a new date/time representing the end of the year. - # DateTime objects will have a time set to 23:59:59. - def end_of_year - change(month: 12).end_of_month - end - alias :at_end_of_year :end_of_year - - # Returns a Range representing the whole day of the current date/time. - def all_day - beginning_of_day..end_of_day - end - - # Returns a Range representing the whole week of the current date/time. - # Week starts on start_day, default is Date.beginning_of_week or config.beginning_of_week when set. - def all_week(start_day = Date.beginning_of_week) - beginning_of_week(start_day)..end_of_week(start_day) - end - - # Returns a Range representing the whole month of the current date/time. - def all_month - beginning_of_month..end_of_month - end - - # Returns a Range representing the whole quarter of the current date/time. - def all_quarter - beginning_of_quarter..end_of_quarter - end - - # Returns a Range representing the whole year of the current date/time. - def all_year - beginning_of_year..end_of_year - end - - private - def first_hour(date_or_time) - date_or_time.acts_like?(:time) ? date_or_time.beginning_of_day : date_or_time - end - - def last_hour(date_or_time) - date_or_time.acts_like?(:time) ? date_or_time.end_of_day : date_or_time - end - - def days_span(day) - (DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7 - end - - def copy_time_to(other) - other.change(hour: hour, min: min, sec: sec, nsec: try(:nsec)) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/compatibility.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/compatibility.rb deleted file mode 100644 index ab80392460..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/compatibility.rb +++ /dev/null @@ -1,14 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" - -module DateAndTime - module Compatibility - # If true, +to_time+ preserves the timezone offset of receiver. - # - # NOTE: With Ruby 2.4+ the default for +to_time+ changed from - # converting to the local system time, to preserving the offset - # of the receiver. For backwards compatibility we're overriding - # this behavior, but new apps will have an initializer that sets - # this to true, because the new behavior is preferred. - mattr_accessor(:preserve_timezone, instance_writer: false) { false } - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/zones.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/zones.rb deleted file mode 100644 index edd724f1d0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_and_time/zones.rb +++ /dev/null @@ -1,39 +0,0 @@ -module DateAndTime - module Zones - # Returns the simultaneous time in Time.zone if a zone is given or - # if Time.zone_default is set. Otherwise, it returns the current time. - # - # Time.zone = 'Hawaii' # => 'Hawaii' - # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - # Date.new(2000).in_time_zone # => Sat, 01 Jan 2000 00:00:00 HST -10:00 - # - # This method is similar to Time#localtime, except that it uses Time.zone as the local zone - # instead of the operating system's time zone. - # - # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument, - # and the conversion will be based on that zone instead of Time.zone. - # - # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00 - # Date.new(2000).in_time_zone('Alaska') # => Sat, 01 Jan 2000 00:00:00 AKST -09:00 - def in_time_zone(zone = ::Time.zone) - time_zone = ::Time.find_zone! zone - time = acts_like?(:time) ? self : nil - - if time_zone - time_with_zone(time, time_zone) - else - time || to_time - end - end - - private - - def time_with_zone(time, zone) - if time - ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone) - else - ActiveSupport::TimeWithZone.new(nil, zone, to_time(:utc)) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time.rb deleted file mode 100644 index 6fd498f864..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "active_support/core_ext/date_time/acts_like" -require "active_support/core_ext/date_time/blank" -require "active_support/core_ext/date_time/calculations" -require "active_support/core_ext/date_time/compatibility" -require "active_support/core_ext/date_time/conversions" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/acts_like.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/acts_like.rb deleted file mode 100644 index 6f50f55a53..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/acts_like.rb +++ /dev/null @@ -1,14 +0,0 @@ -require "date" -require "active_support/core_ext/object/acts_like" - -class DateTime - # Duck-types as a Date-like class. See Object#acts_like?. - def acts_like_date? - true - end - - # Duck-types as a Time-like class. See Object#acts_like?. - def acts_like_time? - true - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/blank.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/blank.rb deleted file mode 100644 index b475fd926d..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/blank.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "date" - -class DateTime #:nodoc: - # No DateTime is ever blank: - # - # DateTime.now.blank? # => false - # - # @return [false] - def blank? - false - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/calculations.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/calculations.rb deleted file mode 100644 index 7a9eb8c266..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/calculations.rb +++ /dev/null @@ -1,209 +0,0 @@ -require "date" - -class DateTime - class << self - # Returns Time.zone.now.to_datetime when Time.zone or - # config.time_zone are set, otherwise returns - # Time.now.to_datetime. - def current - ::Time.zone ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime - end - end - - # Returns the number of seconds since 00:00:00. - # - # DateTime.new(2012, 8, 29, 0, 0, 0).seconds_since_midnight # => 0 - # DateTime.new(2012, 8, 29, 12, 34, 56).seconds_since_midnight # => 45296 - # DateTime.new(2012, 8, 29, 23, 59, 59).seconds_since_midnight # => 86399 - def seconds_since_midnight - sec + (min * 60) + (hour * 3600) - end - - # Returns the number of seconds until 23:59:59. - # - # DateTime.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399 - # DateTime.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103 - # DateTime.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0 - def seconds_until_end_of_day - end_of_day.to_i - to_i - end - - # Returns the fraction of a second as a +Rational+ - # - # DateTime.new(2012, 8, 29, 0, 0, 0.5).subsec # => (1/2) - def subsec - sec_fraction - end - - # Returns a new DateTime where one or more of the elements have been changed - # according to the +options+ parameter. The time options (:hour, - # :min, :sec) reset cascadingly, so if only the hour is - # passed, then minute and sec is set to 0. If the hour and minute is passed, - # then sec is set to 0. The +options+ parameter takes a hash with any of these - # keys: :year, :month, :day, :hour, - # :min, :sec, :offset, :start. - # - # DateTime.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => DateTime.new(2012, 8, 1, 22, 35, 0) - # DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => DateTime.new(1981, 8, 1, 22, 35, 0) - # DateTime.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => DateTime.new(1981, 8, 29, 0, 0, 0) - def change(options) - if new_nsec = options[:nsec] - raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec] - new_fraction = Rational(new_nsec, 1000000000) - else - new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000)) - new_fraction = Rational(new_usec, 1000000) - end - - raise ArgumentError, "argument out of range" if new_fraction >= 1 - - ::DateTime.civil( - options.fetch(:year, year), - options.fetch(:month, month), - options.fetch(:day, day), - options.fetch(:hour, hour), - options.fetch(:min, options[:hour] ? 0 : min), - options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) + new_fraction, - options.fetch(:offset, offset), - options.fetch(:start, start) - ) - end - - # Uses Date to provide precise Time calculations for years, months, and days. - # The +options+ parameter takes a hash with any of these keys: :years, - # :months, :weeks, :days, :hours, - # :minutes, :seconds. - def advance(options) - unless options[:weeks].nil? - options[:weeks], partial_weeks = options[:weeks].divmod(1) - options[:days] = options.fetch(:days, 0) + 7 * partial_weeks - end - - unless options[:days].nil? - options[:days], partial_days = options[:days].divmod(1) - options[:hours] = options.fetch(:hours, 0) + 24 * partial_days - end - - d = to_date.advance(options) - datetime_advanced_by_date = change(year: d.year, month: d.month, day: d.day) - seconds_to_advance = \ - options.fetch(:seconds, 0) + - options.fetch(:minutes, 0) * 60 + - options.fetch(:hours, 0) * 3600 - - if seconds_to_advance.zero? - datetime_advanced_by_date - else - datetime_advanced_by_date.since(seconds_to_advance) - end - end - - # Returns a new DateTime representing the time a number of seconds ago. - # Do not use this method in combination with x.months, use months_ago instead! - def ago(seconds) - since(-seconds) - end - - # Returns a new DateTime representing the time a number of seconds since the - # instance time. Do not use this method in combination with x.months, use - # months_since instead! - def since(seconds) - self + Rational(seconds.round, 86400) - end - alias :in :since - - # Returns a new DateTime representing the start of the day (0:00). - def beginning_of_day - change(hour: 0) - end - alias :midnight :beginning_of_day - alias :at_midnight :beginning_of_day - alias :at_beginning_of_day :beginning_of_day - - # Returns a new DateTime representing the middle of the day (12:00) - def middle_of_day - change(hour: 12) - end - alias :midday :middle_of_day - alias :noon :middle_of_day - alias :at_midday :middle_of_day - alias :at_noon :middle_of_day - alias :at_middle_of_day :middle_of_day - - # Returns a new DateTime representing the end of the day (23:59:59). - def end_of_day - change(hour: 23, min: 59, sec: 59, usec: Rational(999999999, 1000)) - end - alias :at_end_of_day :end_of_day - - # Returns a new DateTime representing the start of the hour (hh:00:00). - def beginning_of_hour - change(min: 0) - end - alias :at_beginning_of_hour :beginning_of_hour - - # Returns a new DateTime representing the end of the hour (hh:59:59). - def end_of_hour - change(min: 59, sec: 59, usec: Rational(999999999, 1000)) - end - alias :at_end_of_hour :end_of_hour - - # Returns a new DateTime representing the start of the minute (hh:mm:00). - def beginning_of_minute - change(sec: 0) - end - alias :at_beginning_of_minute :beginning_of_minute - - # Returns a new DateTime representing the end of the minute (hh:mm:59). - def end_of_minute - change(sec: 59, usec: Rational(999999999, 1000)) - end - alias :at_end_of_minute :end_of_minute - - # Returns a Time instance of the simultaneous time in the system timezone. - def localtime(utc_offset = nil) - utc = new_offset(0) - - Time.utc( - utc.year, utc.month, utc.day, - utc.hour, utc.min, utc.sec + utc.sec_fraction - ).getlocal(utc_offset) - end - alias_method :getlocal, :localtime - - # Returns a Time instance of the simultaneous time in the UTC timezone. - # - # DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600 - # DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 UTC - def utc - utc = new_offset(0) - - Time.utc( - utc.year, utc.month, utc.day, - utc.hour, utc.min, utc.sec + utc.sec_fraction - ) - end - alias_method :getgm, :utc - alias_method :getutc, :utc - alias_method :gmtime, :utc - - # Returns +true+ if offset == 0. - def utc? - offset == 0 - end - - # Returns the offset value in seconds. - def utc_offset - (offset * 86400).to_i - end - - # Layers additional behavior on DateTime#<=> so that Time and - # ActiveSupport::TimeWithZone instances can be compared with a DateTime. - def <=>(other) - if other.respond_to? :to_datetime - super other.to_datetime rescue nil - else - super - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/compatibility.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/compatibility.rb deleted file mode 100644 index 870391aeaa..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/compatibility.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "active_support/core_ext/date_and_time/compatibility" -require "active_support/core_ext/module/remove_method" - -class DateTime - include DateAndTime::Compatibility - - remove_possible_method :to_time - - # Either return an instance of `Time` with the same UTC offset - # as +self+ or an instance of `Time` representing the same time - # in the the local system timezone depending on the setting of - # on the setting of +ActiveSupport.to_time_preserves_timezone+. - def to_time - preserve_timezone ? getlocal(utc_offset) : getlocal - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/conversions.rb deleted file mode 100644 index d9b3743858..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/date_time/conversions.rb +++ /dev/null @@ -1,105 +0,0 @@ -require "date" -require "active_support/inflector/methods" -require "active_support/core_ext/time/conversions" -require "active_support/core_ext/date_time/calculations" -require "active_support/values/time_zone" - -class DateTime - # Convert to a formatted string. See Time::DATE_FORMATS for predefined formats. - # - # This method is aliased to to_s. - # - # === Examples - # datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000 - # - # datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00" - # datetime.to_s(:db) # => "2007-12-04 00:00:00" - # datetime.to_s(:number) # => "20071204000000" - # datetime.to_formatted_s(:short) # => "04 Dec 00:00" - # datetime.to_formatted_s(:long) # => "December 04, 2007 00:00" - # datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00" - # datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000" - # datetime.to_formatted_s(:iso8601) # => "2007-12-04T00:00:00+00:00" - # - # == Adding your own datetime formats to to_formatted_s - # DateTime formats are shared with Time. You can add your own to the - # Time::DATE_FORMATS hash. Use the format name as the hash key and - # either a strftime string or Proc instance that takes a time or - # datetime argument as the value. - # - # # config/initializers/time_formats.rb - # Time::DATE_FORMATS[:month_and_year] = '%B %Y' - # Time::DATE_FORMATS[:short_ordinal] = lambda { |time| time.strftime("%B #{time.day.ordinalize}") } - def to_formatted_s(format = :default) - if formatter = ::Time::DATE_FORMATS[format] - formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) - else - to_default_s - end - end - alias_method :to_default_s, :to_s if instance_methods(false).include?(:to_s) - alias_method :to_s, :to_formatted_s - - # Returns a formatted string of the offset from UTC, or an alternative - # string if the time zone is already UTC. - # - # datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24)) - # datetime.formatted_offset # => "-06:00" - # datetime.formatted_offset(false) # => "-0600" - def formatted_offset(colon = true, alternate_utc_string = nil) - utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon) - end - - # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000". - def readable_inspect - to_s(:rfc822) - end - alias_method :default_inspect, :inspect - alias_method :inspect, :readable_inspect - - # Returns DateTime with local offset for given year if format is local else - # offset is zero. - # - # DateTime.civil_from_format :local, 2012 - # # => Sun, 01 Jan 2012 00:00:00 +0300 - # DateTime.civil_from_format :local, 2012, 12, 17 - # # => Mon, 17 Dec 2012 00:00:00 +0000 - def self.civil_from_format(utc_or_local, year, month = 1, day = 1, hour = 0, min = 0, sec = 0) - if utc_or_local.to_sym == :local - offset = ::Time.local(year, month, day).utc_offset.to_r / 86400 - else - offset = 0 - end - civil(year, month, day, hour, min, sec, offset) - end - - # Converts +self+ to a floating-point number of seconds, including fractional microseconds, since the Unix epoch. - def to_f - seconds_since_unix_epoch.to_f + sec_fraction - end - - # Converts +self+ to an integer number of seconds since the Unix epoch. - def to_i - seconds_since_unix_epoch.to_i - end - - # Returns the fraction of a second as microseconds - def usec - (sec_fraction * 1_000_000).to_i - end - - # Returns the fraction of a second as nanoseconds - def nsec - (sec_fraction * 1_000_000_000).to_i - end - - private - - def offset_in_seconds - (offset * 86400).to_i - end - - def seconds_since_unix_epoch - (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/digest/uuid.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/digest/uuid.rb deleted file mode 100644 index e6d60e3267..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/digest/uuid.rb +++ /dev/null @@ -1,51 +0,0 @@ -require "securerandom" - -module Digest - module UUID - DNS_NAMESPACE = "k\xA7\xB8\x10\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: - URL_NAMESPACE = "k\xA7\xB8\x11\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: - OID_NAMESPACE = "k\xA7\xB8\x12\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: - X500_NAMESPACE = "k\xA7\xB8\x14\x9D\xAD\x11\xD1\x80\xB4\x00\xC0O\xD40\xC8" #:nodoc: - - # Generates a v5 non-random UUID (Universally Unique IDentifier). - # - # Using Digest::MD5 generates version 3 UUIDs; Digest::SHA1 generates version 5 UUIDs. - # uuid_from_hash always generates the same UUID for a given name and namespace combination. - # - # See RFC 4122 for details of UUID at: http://www.ietf.org/rfc/rfc4122.txt - def self.uuid_from_hash(hash_class, uuid_namespace, name) - if hash_class == Digest::MD5 - version = 3 - elsif hash_class == Digest::SHA1 - version = 5 - else - raise ArgumentError, "Expected Digest::SHA1 or Digest::MD5, got #{hash_class.name}." - end - - hash = hash_class.new - hash.update(uuid_namespace) - hash.update(name) - - ary = hash.digest.unpack("NnnnnN") - ary[2] = (ary[2] & 0x0FFF) | (version << 12) - ary[3] = (ary[3] & 0x3FFF) | 0x8000 - - "%08x-%04x-%04x-%04x-%04x%08x" % ary - end - - # Convenience method for uuid_from_hash using Digest::MD5. - def self.uuid_v3(uuid_namespace, name) - uuid_from_hash(Digest::MD5, uuid_namespace, name) - end - - # Convenience method for uuid_from_hash using Digest::SHA1. - def self.uuid_v5(uuid_namespace, name) - uuid_from_hash(Digest::SHA1, uuid_namespace, name) - end - - # Convenience method for SecureRandom.uuid. - def self.uuid_v4 - SecureRandom.uuid - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/enumerable.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/enumerable.rb deleted file mode 100644 index 4f120d4b45..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/enumerable.rb +++ /dev/null @@ -1,157 +0,0 @@ -module Enumerable - # Enumerable#sum was added in Ruby 2.4 but it only works with Numeric elements - # when we omit an identity. - # - # We tried shimming it to attempt the fast native method, rescue TypeError, - # and fall back to the compatible implementation, but that's much slower than - # just calling the compat method in the first place. - if Enumerable.instance_methods(false).include?(:sum) && !((?a..?b).sum rescue false) - # We can't use Refinements here because Refinements with Module which will be prepended - # doesn't work well https://bugs.ruby-lang.org/issues/13446 - alias :_original_sum_with_required_identity :sum - private :_original_sum_with_required_identity - # Calculates a sum from the elements. - # - # payments.sum { |p| p.price * p.tax_rate } - # payments.sum(&:price) - # - # The latter is a shortcut for: - # - # payments.inject(0) { |sum, p| sum + p.price } - # - # It can also calculate the sum without the use of a block. - # - # [5, 15, 10].sum # => 30 - # ['foo', 'bar'].sum # => "foobar" - # [[1, 2], [3, 1, 5]].sum # => [1, 2, 3, 1, 5] - # - # The default sum of an empty list is zero. You can override this default: - # - # [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0) - def sum(identity = nil, &block) - if identity - _original_sum_with_required_identity(identity, &block) - elsif block_given? - map(&block).sum(identity) - else - inject(:+) || 0 - end - end - else - def sum(identity = nil, &block) - if block_given? - map(&block).sum(identity) - else - sum = identity ? inject(identity, :+) : inject(:+) - sum || identity || 0 - end - end - end - - # Convert an enumerable to a hash. - # - # people.index_by(&:login) - # # => { "nextangle" => , "chade-" => , ...} - # people.index_by { |person| "#{person.first_name} #{person.last_name}" } - # # => { "Chade- Fowlersburg-e" => , "David Heinemeier Hansson" => , ...} - def index_by - if block_given? - result = {} - each { |elem| result[yield(elem)] = elem } - result - else - to_enum(:index_by) { size if respond_to?(:size) } - end - end - - # Returns +true+ if the enumerable has more than 1 element. Functionally - # equivalent to enum.to_a.size > 1. Can be called with a block too, - # much like any?, so people.many? { |p| p.age > 26 } returns +true+ - # if more than one person is over 26. - def many? - cnt = 0 - if block_given? - any? do |element| - cnt += 1 if yield element - cnt > 1 - end - else - any? { (cnt += 1) > 1 } - end - end - - # The negative of the Enumerable#include?. Returns +true+ if the - # collection does not include the object. - def exclude?(object) - !include?(object) - end - - # Returns a copy of the enumerable without the specified elements. - # - # ["David", "Rafael", "Aaron", "Todd"].without "Aaron", "Todd" - # # => ["David", "Rafael"] - # - # {foo: 1, bar: 2, baz: 3}.without :bar - # # => {foo: 1, baz: 3} - def without(*elements) - reject { |element| elements.include?(element) } - end - - # Convert an enumerable to an array based on the given key. - # - # [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) - # # => ["David", "Rafael", "Aaron"] - # - # [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name) - # # => [[1, "David"], [2, "Rafael"]] - def pluck(*keys) - if keys.many? - map { |element| keys.map { |key| element[key] } } - else - map { |element| element[keys.first] } - end - end -end - -class Range #:nodoc: - # Optimize range sum to use arithmetic progression if a block is not given and - # we have a range of numeric values. - def sum(identity = nil) - if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer)) - super - else - actual_last = exclude_end? ? (last - 1) : last - if actual_last >= first - sum = identity || 0 - sum + (actual_last - first + 1) * (actual_last + first) / 2 - else - identity || 0 - end - end - end -end - -# Array#sum was added in Ruby 2.4 but it only works with Numeric elements. -# -# We tried shimming it to attempt the fast native method, rescue TypeError, -# and fall back to the compatible implementation, but that's much slower than -# just calling the compat method in the first place. -if Array.instance_methods(false).include?(:sum) && !(%w[a].sum rescue false) - # Using Refinements here in order not to expose our internal method - using Module.new { - refine Array do - alias :orig_sum :sum - end - } - - class Array - def sum(init = nil, &block) #:nodoc: - if init.is_a?(Numeric) || first.is_a?(Numeric) - init ||= 0 - orig_sum(init, &block) - else - super - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/file.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/file.rb deleted file mode 100644 index 6d99bad2af..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/file.rb +++ /dev/null @@ -1 +0,0 @@ -require "active_support/core_ext/file/atomic" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/file/atomic.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/file/atomic.rb deleted file mode 100644 index 8d6c0d3685..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/file/atomic.rb +++ /dev/null @@ -1,68 +0,0 @@ -require "fileutils" - -class File - # Write to a file atomically. Useful for situations where you don't - # want other processes or threads to see half-written files. - # - # File.atomic_write('important.file') do |file| - # file.write('hello') - # end - # - # This method needs to create a temporary file. By default it will create it - # in the same directory as the destination file. If you don't like this - # behavior you can provide a different directory but it must be on the - # same physical filesystem as the file you're trying to write. - # - # File.atomic_write('/data/something.important', '/data/tmp') do |file| - # file.write('hello') - # end - def self.atomic_write(file_name, temp_dir = dirname(file_name)) - require "tempfile" unless defined?(Tempfile) - - Tempfile.open(".#{basename(file_name)}", temp_dir) do |temp_file| - temp_file.binmode - return_val = yield temp_file - temp_file.close - - old_stat = if exist?(file_name) - # Get original file permissions - stat(file_name) - elsif temp_dir != dirname(file_name) - # If not possible, probe which are the default permissions in the - # destination directory. - probe_stat_in(dirname(file_name)) - end - - if old_stat - # Set correct permissions on new file - begin - chown(old_stat.uid, old_stat.gid, temp_file.path) - # This operation will affect filesystem ACL's - chmod(old_stat.mode, temp_file.path) - rescue Errno::EPERM, Errno::EACCES - # Changing file ownership failed, moving on. - end - end - - # Overwrite original file with temp file - rename(temp_file.path, file_name) - return_val - end - end - - # Private utility method. - def self.probe_stat_in(dir) #:nodoc: - basename = [ - ".permissions_check", - Thread.current.object_id, - Process.pid, - rand(1000000) - ].join(".") - - file_name = join(dir, basename) - FileUtils.touch(file_name) - stat(file_name) - ensure - FileUtils.rm_f(file_name) if file_name - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash.rb deleted file mode 100644 index c819307e8a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash.rb +++ /dev/null @@ -1,9 +0,0 @@ -require "active_support/core_ext/hash/compact" -require "active_support/core_ext/hash/conversions" -require "active_support/core_ext/hash/deep_merge" -require "active_support/core_ext/hash/except" -require "active_support/core_ext/hash/indifferent_access" -require "active_support/core_ext/hash/keys" -require "active_support/core_ext/hash/reverse_merge" -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/hash/transform_values" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/compact.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/compact.rb deleted file mode 100644 index e357284be0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/compact.rb +++ /dev/null @@ -1,27 +0,0 @@ -class Hash - unless Hash.instance_methods(false).include?(:compact) - # Returns a hash with non +nil+ values. - # - # hash = { a: true, b: false, c: nil } - # hash.compact # => { a: true, b: false } - # hash # => { a: true, b: false, c: nil } - # { c: nil }.compact # => {} - # { c: true }.compact # => { c: true } - def compact - select { |_, value| !value.nil? } - end - end - - unless Hash.instance_methods(false).include?(:compact!) - # Replaces current hash with non +nil+ values. - # Returns +nil+ if no changes were made, otherwise returns the hash. - # - # hash = { a: true, b: false, c: nil } - # hash.compact! # => { a: true, b: false } - # hash # => { a: true, b: false } - # { c: true }.compact! # => nil - def compact! - reject! { |_, value| value.nil? } - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/conversions.rb deleted file mode 100644 index 2a58a7f1ca..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/conversions.rb +++ /dev/null @@ -1,261 +0,0 @@ -require "active_support/xml_mini" -require "active_support/time" -require "active_support/core_ext/object/blank" -require "active_support/core_ext/object/to_param" -require "active_support/core_ext/object/to_query" -require "active_support/core_ext/array/wrap" -require "active_support/core_ext/hash/reverse_merge" -require "active_support/core_ext/string/inflections" - -class Hash - # Returns a string containing an XML representation of its receiver: - # - # { foo: 1, bar: 2 }.to_xml - # # => - # # - # # - # # 1 - # # 2 - # # - # - # To do so, the method loops over the pairs and builds nodes that depend on - # the _values_. Given a pair +key+, +value+: - # - # * If +value+ is a hash there's a recursive call with +key+ as :root. - # - # * If +value+ is an array there's a recursive call with +key+ as :root, - # and +key+ singularized as :children. - # - # * If +value+ is a callable object it must expect one or two arguments. Depending - # on the arity, the callable is invoked with the +options+ hash as first argument - # with +key+ as :root, and +key+ singularized as second argument. The - # callable can add nodes by using options[:builder]. - # - # {foo: lambda { |options, key| options[:builder].b(key) }}.to_xml - # # => "foo" - # - # * If +value+ responds to +to_xml+ the method is invoked with +key+ as :root. - # - # class Foo - # def to_xml(options) - # options[:builder].bar 'fooing!' - # end - # end - # - # { foo: Foo.new }.to_xml(skip_instruct: true) - # # => - # # - # # fooing! - # # - # - # * Otherwise, a node with +key+ as tag is created with a string representation of - # +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. - # Unless the option :skip_types exists and is true, an attribute "type" is - # added as well according to the following mapping: - # - # XML_TYPE_NAMES = { - # "Symbol" => "symbol", - # "Integer" => "integer", - # "BigDecimal" => "decimal", - # "Float" => "float", - # "TrueClass" => "boolean", - # "FalseClass" => "boolean", - # "Date" => "date", - # "DateTime" => "dateTime", - # "Time" => "dateTime" - # } - # - # By default the root node is "hash", but that's configurable via the :root option. - # - # The default XML builder is a fresh instance of Builder::XmlMarkup. You can - # configure your own builder with the :builder option. The method also accepts - # options like :dasherize and friends, they are forwarded to the builder. - def to_xml(options = {}) - require "active_support/builder" unless defined?(Builder) - - options = options.dup - options[:indent] ||= 2 - options[:root] ||= "hash" - options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent]) - - builder = options[:builder] - builder.instruct! unless options.delete(:skip_instruct) - - root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options) - - builder.tag!(root) do - each { |key, value| ActiveSupport::XmlMini.to_tag(key, value, options) } - yield builder if block_given? - end - end - - class << self - # Returns a Hash containing a collection of pairs when the key is the node name and the value is - # its content - # - # xml = <<-XML - # - # - # 1 - # 2 - # - # XML - # - # hash = Hash.from_xml(xml) - # # => {"hash"=>{"foo"=>1, "bar"=>2}} - # - # +DisallowedType+ is raised if the XML contains attributes with type="yaml" or - # type="symbol". Use Hash.from_trusted_xml to - # parse this XML. - # - # Custom +disallowed_types+ can also be passed in the form of an - # array. - # - # xml = <<-XML - # - # - # 1 - # "David" - # - # XML - # - # hash = Hash.from_xml(xml, ['integer']) - # # => ActiveSupport::XMLConverter::DisallowedType: Disallowed type attribute: "integer" - # - # Note that passing custom disallowed types will override the default types, - # which are Symbol and YAML. - def from_xml(xml, disallowed_types = nil) - ActiveSupport::XMLConverter.new(xml, disallowed_types).to_h - end - - # Builds a Hash from XML just like Hash.from_xml, but also allows Symbol and YAML. - def from_trusted_xml(xml) - from_xml xml, [] - end - end -end - -module ActiveSupport - class XMLConverter # :nodoc: - # Raised if the XML contains attributes with type="yaml" or - # type="symbol". Read Hash#from_xml for more details. - class DisallowedType < StandardError - def initialize(type) - super "Disallowed type attribute: #{type.inspect}" - end - end - - DISALLOWED_TYPES = %w(symbol yaml) - - def initialize(xml, disallowed_types = nil) - @xml = normalize_keys(XmlMini.parse(xml)) - @disallowed_types = disallowed_types || DISALLOWED_TYPES - end - - def to_h - deep_to_h(@xml) - end - - private - def normalize_keys(params) - case params - when Hash - Hash[params.map { |k, v| [k.to_s.tr("-", "_"), normalize_keys(v)] } ] - when Array - params.map { |v| normalize_keys(v) } - else - params - end - end - - def deep_to_h(value) - case value - when Hash - process_hash(value) - when Array - process_array(value) - when String - value - else - raise "can't typecast #{value.class.name} - #{value.inspect}" - end - end - - def process_hash(value) - if value.include?("type") && !value["type"].is_a?(Hash) && @disallowed_types.include?(value["type"]) - raise DisallowedType, value["type"] - end - - if become_array?(value) - _, entries = Array.wrap(value.detect { |k, v| not v.is_a?(String) }) - if entries.nil? || value["__content__"].try(:empty?) - [] - else - case entries - when Array - entries.collect { |v| deep_to_h(v) } - when Hash - [deep_to_h(entries)] - else - raise "can't typecast #{entries.inspect}" - end - end - elsif become_content?(value) - process_content(value) - - elsif become_empty_string?(value) - "" - elsif become_hash?(value) - xml_value = Hash[value.map { |k, v| [k, deep_to_h(v)] }] - - # Turn { files: { file: # } } into { files: # } so it is compatible with - # how multipart uploaded files from HTML appear - xml_value["file"].is_a?(StringIO) ? xml_value["file"] : xml_value - end - end - - def become_content?(value) - value["type"] == "file" || (value["__content__"] && (value.keys.size == 1 || value["__content__"].present?)) - end - - def become_array?(value) - value["type"] == "array" - end - - def become_empty_string?(value) - # { "string" => true } - # No tests fail when the second term is removed. - value["type"] == "string" && value["nil"] != "true" - end - - def become_hash?(value) - !nothing?(value) && !garbage?(value) - end - - def nothing?(value) - # blank or nil parsed values are represented by nil - value.blank? || value["nil"] == "true" - end - - def garbage?(value) - # If the type is the only element which makes it then - # this still makes the value nil, except if type is - # an XML node(where type['value'] is a Hash) - value["type"] && !value["type"].is_a?(::Hash) && value.size == 1 - end - - def process_content(value) - content = value["__content__"] - if parser = ActiveSupport::XmlMini::PARSING[value["type"]] - parser.arity == 1 ? parser.call(content) : parser.call(content, value) - else - content - end - end - - def process_array(value) - value.map! { |i| deep_to_h(i) } - value.length > 1 ? value : value.first - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/deep_merge.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/deep_merge.rb deleted file mode 100644 index 9c9faf67ea..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/deep_merge.rb +++ /dev/null @@ -1,38 +0,0 @@ -class Hash - # Returns a new hash with +self+ and +other_hash+ merged recursively. - # - # h1 = { a: true, b: { c: [1, 2, 3] } } - # h2 = { a: false, b: { x: [3, 4, 5] } } - # - # h1.deep_merge(h2) # => { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } } - # - # Like with Hash#merge in the standard library, a block can be provided - # to merge values: - # - # h1 = { a: 100, b: 200, c: { c1: 100 } } - # h2 = { b: 250, c: { c1: 200 } } - # h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val } - # # => { a: 100, b: 450, c: { c1: 300 } } - def deep_merge(other_hash, &block) - dup.deep_merge!(other_hash, &block) - end - - # Same as +deep_merge+, but modifies +self+. - def deep_merge!(other_hash, &block) - other_hash.each_pair do |current_key, other_value| - this_value = self[current_key] - - self[current_key] = if this_value.is_a?(Hash) && other_value.is_a?(Hash) - this_value.deep_merge(other_value, &block) - else - if block_given? && key?(current_key) - block.call(current_key, this_value, other_value) - else - other_value - end - end - end - - self - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/except.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/except.rb deleted file mode 100644 index 2f6d38c1f6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/except.rb +++ /dev/null @@ -1,22 +0,0 @@ -class Hash - # Returns a hash that includes everything except given keys. - # hash = { a: true, b: false, c: nil } - # hash.except(:c) # => { a: true, b: false } - # hash.except(:a, :b) # => { c: nil } - # hash # => { a: true, b: false, c: nil } - # - # This is useful for limiting a set of parameters to everything but a few known toggles: - # @person.update(params[:person].except(:admin)) - def except(*keys) - dup.except!(*keys) - end - - # Removes the given keys from hash and returns it. - # hash = { a: true, b: false, c: nil } - # hash.except!(:c) # => { a: true, b: false } - # hash # => { a: true, b: false } - def except!(*keys) - keys.each { |key| delete(key) } - self - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/indifferent_access.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/indifferent_access.rb deleted file mode 100644 index 3e1ccecb6c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/indifferent_access.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "active_support/hash_with_indifferent_access" - -class Hash - # Returns an ActiveSupport::HashWithIndifferentAccess out of its receiver: - # - # { a: 1 }.with_indifferent_access['a'] # => 1 - def with_indifferent_access - ActiveSupport::HashWithIndifferentAccess.new(self) - end - - # Called when object is nested under an object that receives - # #with_indifferent_access. This method will be called on the current object - # by the enclosing object and is aliased to #with_indifferent_access by - # default. Subclasses of Hash may overwrite this method to return +self+ if - # converting to an ActiveSupport::HashWithIndifferentAccess would not be - # desirable. - # - # b = { b: 1 } - # { a: b }.with_indifferent_access['a'] # calls b.nested_under_indifferent_access - # # => {"b"=>1} - alias nested_under_indifferent_access with_indifferent_access -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/keys.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/keys.rb deleted file mode 100644 index 363bf55517..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/keys.rb +++ /dev/null @@ -1,170 +0,0 @@ -class Hash - # Returns a new hash with all keys converted using the +block+ operation. - # - # hash = { name: 'Rob', age: '28' } - # - # hash.transform_keys { |key| key.to_s.upcase } # => {"NAME"=>"Rob", "AGE"=>"28"} - # - # If you do not provide a +block+, it will return an Enumerator - # for chaining with other methods: - # - # hash.transform_keys.with_index { |k, i| [k, i].join } # => {"name0"=>"Rob", "age1"=>"28"} - def transform_keys - return enum_for(:transform_keys) { size } unless block_given? - result = {} - each_key do |key| - result[yield(key)] = self[key] - end - result - end unless method_defined? :transform_keys - - # Destructively converts all keys using the +block+ operations. - # Same as +transform_keys+ but modifies +self+. - def transform_keys! - return enum_for(:transform_keys!) { size } unless block_given? - keys.each do |key| - self[yield(key)] = delete(key) - end - self - end unless method_defined? :transform_keys! - - # Returns a new hash with all keys converted to strings. - # - # hash = { name: 'Rob', age: '28' } - # - # hash.stringify_keys - # # => {"name"=>"Rob", "age"=>"28"} - def stringify_keys - transform_keys(&:to_s) - end - - # Destructively converts all keys to strings. Same as - # +stringify_keys+, but modifies +self+. - def stringify_keys! - transform_keys!(&:to_s) - end - - # Returns a new hash with all keys converted to symbols, as long as - # they respond to +to_sym+. - # - # hash = { 'name' => 'Rob', 'age' => '28' } - # - # hash.symbolize_keys - # # => {:name=>"Rob", :age=>"28"} - def symbolize_keys - transform_keys { |key| key.to_sym rescue key } - end - alias_method :to_options, :symbolize_keys - - # Destructively converts all keys to symbols, as long as they respond - # to +to_sym+. Same as +symbolize_keys+, but modifies +self+. - def symbolize_keys! - transform_keys! { |key| key.to_sym rescue key } - end - alias_method :to_options!, :symbolize_keys! - - # Validates all keys in a hash match *valid_keys, raising - # +ArgumentError+ on a mismatch. - # - # Note that keys are treated differently than HashWithIndifferentAccess, - # meaning that string and symbol keys will not match. - # - # { name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age" - # { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'" - # { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing - def assert_valid_keys(*valid_keys) - valid_keys.flatten! - each_key do |k| - unless valid_keys.include?(k) - raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}") - end - end - end - - # Returns a new hash with all keys converted by the block operation. - # This includes the keys from the root hash and from all - # nested hashes and arrays. - # - # hash = { person: { name: 'Rob', age: '28' } } - # - # hash.deep_transform_keys{ |key| key.to_s.upcase } - # # => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}} - def deep_transform_keys(&block) - _deep_transform_keys_in_object(self, &block) - end - - # Destructively converts all keys by using the block operation. - # This includes the keys from the root hash and from all - # nested hashes and arrays. - def deep_transform_keys!(&block) - _deep_transform_keys_in_object!(self, &block) - end - - # Returns a new hash with all keys converted to strings. - # This includes the keys from the root hash and from all - # nested hashes and arrays. - # - # hash = { person: { name: 'Rob', age: '28' } } - # - # hash.deep_stringify_keys - # # => {"person"=>{"name"=>"Rob", "age"=>"28"}} - def deep_stringify_keys - deep_transform_keys(&:to_s) - end - - # Destructively converts all keys to strings. - # This includes the keys from the root hash and from all - # nested hashes and arrays. - def deep_stringify_keys! - deep_transform_keys!(&:to_s) - end - - # Returns a new hash with all keys converted to symbols, as long as - # they respond to +to_sym+. This includes the keys from the root hash - # and from all nested hashes and arrays. - # - # hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } } - # - # hash.deep_symbolize_keys - # # => {:person=>{:name=>"Rob", :age=>"28"}} - def deep_symbolize_keys - deep_transform_keys { |key| key.to_sym rescue key } - end - - # Destructively converts all keys to symbols, as long as they respond - # to +to_sym+. This includes the keys from the root hash and from all - # nested hashes and arrays. - def deep_symbolize_keys! - deep_transform_keys! { |key| key.to_sym rescue key } - end - - private - # support methods for deep transforming nested hashes and arrays - def _deep_transform_keys_in_object(object, &block) - case object - when Hash - object.each_with_object({}) do |(key, value), result| - result[yield(key)] = _deep_transform_keys_in_object(value, &block) - end - when Array - object.map { |e| _deep_transform_keys_in_object(e, &block) } - else - object - end - end - - def _deep_transform_keys_in_object!(object, &block) - case object - when Hash - object.keys.each do |key| - value = object.delete(key) - object[yield(key)] = _deep_transform_keys_in_object!(value, &block) - end - object - when Array - object.map! { |e| _deep_transform_keys_in_object!(e, &block) } - else - object - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/reverse_merge.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/reverse_merge.rb deleted file mode 100644 index efb9d1b8a0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/reverse_merge.rb +++ /dev/null @@ -1,22 +0,0 @@ -class Hash - # Merges the caller into +other_hash+. For example, - # - # options = options.reverse_merge(size: 25, velocity: 10) - # - # is equivalent to - # - # options = { size: 25, velocity: 10 }.merge(options) - # - # This is particularly useful for initializing an options hash - # with default values. - def reverse_merge(other_hash) - other_hash.merge(self) - end - - # Destructive +reverse_merge+. - def reverse_merge!(other_hash) - # right wins if there is no left - merge!(other_hash) { |key, left, right| left } - end - alias_method :reverse_update, :reverse_merge! -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/slice.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/slice.rb deleted file mode 100644 index 161b00dfb3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/slice.rb +++ /dev/null @@ -1,48 +0,0 @@ -class Hash - # Slices a hash to include only the given keys. Returns a hash containing - # the given keys. - # - # { a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b) - # # => {:a=>1, :b=>2} - # - # This is useful for limiting an options hash to valid keys before - # passing to a method: - # - # def search(criteria = {}) - # criteria.assert_valid_keys(:mass, :velocity, :time) - # end - # - # search(options.slice(:mass, :velocity, :time)) - # - # If you have an array of keys you want to limit to, you should splat them: - # - # valid_keys = [:mass, :velocity, :time] - # search(options.slice(*valid_keys)) - def slice(*keys) - keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true) - keys.each_with_object(self.class.new) { |k, hash| hash[k] = self[k] if has_key?(k) } - end - - # Replaces the hash with only the given keys. - # Returns a hash containing the removed key/value pairs. - # - # { a: 1, b: 2, c: 3, d: 4 }.slice!(:a, :b) - # # => {:c=>3, :d=>4} - def slice!(*keys) - keys.map! { |key| convert_key(key) } if respond_to?(:convert_key, true) - omit = slice(*self.keys - keys) - hash = slice(*keys) - hash.default = default - hash.default_proc = default_proc if default_proc - replace(hash) - omit - end - - # Removes and returns the key/value pairs matching the given keys. - # - # { a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2} - # { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1} - def extract!(*keys) - keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) } - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/transform_values.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/transform_values.rb deleted file mode 100644 index 2f693bff0c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/hash/transform_values.rb +++ /dev/null @@ -1,30 +0,0 @@ -class Hash - # Returns a new hash with the results of running +block+ once for every value. - # The keys are unchanged. - # - # { a: 1, b: 2, c: 3 }.transform_values { |x| x * 2 } # => { a: 2, b: 4, c: 6 } - # - # If you do not provide a +block+, it will return an Enumerator - # for chaining with other methods: - # - # { a: 1, b: 2 }.transform_values.with_index { |v, i| [v, i].join.to_i } # => { a: 10, b: 21 } - def transform_values - return enum_for(:transform_values) { size } unless block_given? - return {} if empty? - result = self.class.new - each do |key, value| - result[key] = yield(value) - end - result - end unless method_defined? :transform_values - - # Destructively converts all values using the +block+ operations. - # Same as +transform_values+ but modifies +self+. - def transform_values! - return enum_for(:transform_values!) { size } unless block_given? - each do |key, value| - self[key] = yield(value) - end - end unless method_defined? :transform_values! - # TODO: Remove this file when supporting only Ruby 2.4+. -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer.rb deleted file mode 100644 index 8f0c55f9d3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer.rb +++ /dev/null @@ -1,3 +0,0 @@ -require "active_support/core_ext/integer/multiple" -require "active_support/core_ext/integer/inflections" -require "active_support/core_ext/integer/time" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/inflections.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/inflections.rb deleted file mode 100644 index bc21b65533..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/inflections.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "active_support/inflector" - -class Integer - # Ordinalize turns a number into an ordinal string used to denote the - # position in an ordered sequence such as 1st, 2nd, 3rd, 4th. - # - # 1.ordinalize # => "1st" - # 2.ordinalize # => "2nd" - # 1002.ordinalize # => "1002nd" - # 1003.ordinalize # => "1003rd" - # -11.ordinalize # => "-11th" - # -1001.ordinalize # => "-1001st" - def ordinalize - ActiveSupport::Inflector.ordinalize(self) - end - - # Ordinal returns the suffix used to denote the position - # in an ordered sequence such as 1st, 2nd, 3rd, 4th. - # - # 1.ordinal # => "st" - # 2.ordinal # => "nd" - # 1002.ordinal # => "nd" - # 1003.ordinal # => "rd" - # -11.ordinal # => "th" - # -1001.ordinal # => "st" - def ordinal - ActiveSupport::Inflector.ordinal(self) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/multiple.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/multiple.rb deleted file mode 100644 index c668c7c2eb..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/multiple.rb +++ /dev/null @@ -1,10 +0,0 @@ -class Integer - # Check whether the integer is evenly divisible by the argument. - # - # 0.multiple_of?(0) # => true - # 6.multiple_of?(5) # => false - # 10.multiple_of?(2) # => true - def multiple_of?(number) - number != 0 ? self % number == 0 : zero? - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/time.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/time.rb deleted file mode 100644 index 74baae3639..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/integer/time.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "active_support/duration" -require "active_support/core_ext/numeric/time" - -class Integer - # Enables the use of time calculations and declarations, like 45.minutes + - # 2.hours + 4.years. - # - # These methods use Time#advance for precise date calculations when using - # from_now, +ago+, etc. as well as adding or subtracting their - # results from a Time object. - # - # # equivalent to Time.now.advance(months: 1) - # 1.month.from_now - # - # # equivalent to Time.now.advance(years: 2) - # 2.years.from_now - # - # # equivalent to Time.now.advance(months: 4, years: 5) - # (4.months + 5.years).from_now - def months - ActiveSupport::Duration.months(self) - end - alias :month :months - - def years - ActiveSupport::Duration.years(self) - end - alias :year :years -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel.rb deleted file mode 100644 index 3d41ff7876..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel.rb +++ /dev/null @@ -1,4 +0,0 @@ -require "active_support/core_ext/kernel/agnostics" -require "active_support/core_ext/kernel/concern" -require "active_support/core_ext/kernel/reporting" -require "active_support/core_ext/kernel/singleton_class" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/agnostics.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/agnostics.rb deleted file mode 100644 index 64837d87aa..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/agnostics.rb +++ /dev/null @@ -1,11 +0,0 @@ -class Object - # Makes backticks behave (somewhat more) similarly on all platforms. - # On win32 `nonexistent_command` raises Errno::ENOENT; on Unix, the - # spawned shell prints a message to stderr and sets $?. We emulate - # Unix on the former but not the latter. - def `(command) #:nodoc: - super - rescue Errno::ENOENT => e - STDERR.puts "#$0: #{e}" - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/concern.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/concern.rb deleted file mode 100644 index 307a7f7a63..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/concern.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "active_support/core_ext/module/concerning" - -module Kernel - module_function - - # A shortcut to define a toplevel concern, not within a module. - # - # See Module::Concerning for more. - def concern(topic, &module_definition) - Object.concern topic, &module_definition - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/reporting.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/reporting.rb deleted file mode 100644 index c02618d5f3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/reporting.rb +++ /dev/null @@ -1,43 +0,0 @@ -module Kernel - module_function - - # Sets $VERBOSE to +nil+ for the duration of the block and back to its original - # value afterwards. - # - # silence_warnings do - # value = noisy_call # no warning voiced - # end - # - # noisy_call # warning voiced - def silence_warnings - with_warnings(nil) { yield } - end - - # Sets $VERBOSE to +true+ for the duration of the block and back to its - # original value afterwards. - def enable_warnings - with_warnings(true) { yield } - end - - # Sets $VERBOSE for the duration of the block and back to its original - # value afterwards. - def with_warnings(flag) - old_verbose, $VERBOSE = $VERBOSE, flag - yield - ensure - $VERBOSE = old_verbose - end - - # Blocks and ignores any exception passed as argument if raised within the block. - # - # suppress(ZeroDivisionError) do - # 1/0 - # puts 'This code is NOT reached' - # end - # - # puts 'This code gets executed and nothing related to ZeroDivisionError was seen' - def suppress(*exception_classes) - yield - rescue *exception_classes - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/singleton_class.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/singleton_class.rb deleted file mode 100644 index 9bbf1bbd73..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/kernel/singleton_class.rb +++ /dev/null @@ -1,6 +0,0 @@ -module Kernel - # class_eval on an object acts like singleton_class.class_eval. - def class_eval(*args, &block) - singleton_class.class_eval(*args, &block) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/load_error.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/load_error.rb deleted file mode 100644 index d273487010..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/load_error.rb +++ /dev/null @@ -1,14 +0,0 @@ -class LoadError - REGEXPS = [ - /^no such file to load -- (.+)$/i, - /^Missing \w+ (?:file\s*)?([^\s]+.rb)$/i, - /^Missing API definition file in (.+)$/i, - /^cannot load such file -- (.+)$/i, - ] - - # Returns true if the given path name (except perhaps for the ".rb" - # extension) is the missing file which caused the exception to be raised. - def is_missing?(location) - location.sub(/\.rb$/, "".freeze) == path.sub(/\.rb$/, "".freeze) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/marshal.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/marshal.rb deleted file mode 100644 index bba2b3be2e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/marshal.rb +++ /dev/null @@ -1,22 +0,0 @@ -module ActiveSupport - module MarshalWithAutoloading # :nodoc: - def load(source, proc = nil) - super(source, proc) - rescue ArgumentError, NameError => exc - if exc.message.match(%r|undefined class/module (.+?)(?:::)?\z|) - # try loading the class/module - loaded = $1.constantize - - raise unless $1 == loaded.name - - # if it is an IO we need to go back to read the object - source.rewind if source.respond_to?(:rewind) - retry - else - raise exc - end - end - end -end - -Marshal.singleton_class.prepend(ActiveSupport::MarshalWithAutoloading) diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module.rb deleted file mode 100644 index 2930255557..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module.rb +++ /dev/null @@ -1,11 +0,0 @@ -require "active_support/core_ext/module/aliasing" -require "active_support/core_ext/module/introspection" -require "active_support/core_ext/module/anonymous" -require "active_support/core_ext/module/reachable" -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/module/attribute_accessors_per_thread" -require "active_support/core_ext/module/attr_internal" -require "active_support/core_ext/module/concerning" -require "active_support/core_ext/module/delegation" -require "active_support/core_ext/module/deprecation" -require "active_support/core_ext/module/remove_method" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/aliasing.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/aliasing.rb deleted file mode 100644 index c48bd3354a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/aliasing.rb +++ /dev/null @@ -1,29 +0,0 @@ -class Module - # Allows you to make aliases for attributes, which includes - # getter, setter, and a predicate. - # - # class Content < ActiveRecord::Base - # # has a title attribute - # end - # - # class Email < Content - # alias_attribute :subject, :title - # end - # - # e = Email.find(1) - # e.title # => "Superstars" - # e.subject # => "Superstars" - # e.subject? # => true - # e.subject = "Megastars" - # e.title # => "Megastars" - def alias_attribute(new_name, old_name) - # The following reader methods use an explicit `self` receiver in order to - # support aliases that start with an uppercase letter. Otherwise, they would - # be resolved as constants instead. - module_eval <<-STR, __FILE__, __LINE__ + 1 - def #{new_name}; self.#{old_name}; end # def subject; self.title; end - def #{new_name}?; self.#{old_name}?; end # def subject?; self.title?; end - def #{new_name}=(v); self.#{old_name} = v; end # def subject=(v); self.title = v; end - STR - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/anonymous.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/anonymous.rb deleted file mode 100644 index 510c9a5430..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/anonymous.rb +++ /dev/null @@ -1,28 +0,0 @@ -class Module - # A module may or may not have a name. - # - # module M; end - # M.name # => "M" - # - # m = Module.new - # m.name # => nil - # - # +anonymous?+ method returns true if module does not have a name, false otherwise: - # - # Module.new.anonymous? # => true - # - # module M; end - # M.anonymous? # => false - # - # A module gets a name when it is first assigned to a constant. Either - # via the +module+ or +class+ keyword or by an explicit assignment: - # - # m = Module.new # creates an anonymous module - # m.anonymous? # => true - # M = m # m gets a name here as a side-effect - # m.name # => "M" - # m.anonymous? # => false - def anonymous? - name.nil? - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attr_internal.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attr_internal.rb deleted file mode 100644 index 5081d5f7a3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attr_internal.rb +++ /dev/null @@ -1,36 +0,0 @@ -class Module - # Declares an attribute reader backed by an internally-named instance variable. - def attr_internal_reader(*attrs) - attrs.each { |attr_name| attr_internal_define(attr_name, :reader) } - end - - # Declares an attribute writer backed by an internally-named instance variable. - def attr_internal_writer(*attrs) - attrs.each { |attr_name| attr_internal_define(attr_name, :writer) } - end - - # Declares an attribute reader and writer backed by an internally-named instance - # variable. - def attr_internal_accessor(*attrs) - attr_internal_reader(*attrs) - attr_internal_writer(*attrs) - end - alias_method :attr_internal, :attr_internal_accessor - - class << self; attr_accessor :attr_internal_naming_format end - self.attr_internal_naming_format = "@_%s" - - private - def attr_internal_ivar_name(attr) - Module.attr_internal_naming_format % attr - end - - def attr_internal_define(attr_name, type) - internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, "") - # use native attr_* methods as they are faster on some Ruby implementations - send("attr_#{type}", internal_name) - attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer - alias_method attr_name, internal_name - remove_method internal_name - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attribute_accessors.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attribute_accessors.rb deleted file mode 100644 index 2c24081eb9..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attribute_accessors.rb +++ /dev/null @@ -1,218 +0,0 @@ -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/regexp" - -# Extends the module object with class/module and instance accessors for -# class/module attributes, just like the native attr* accessors for instance -# attributes. -class Module - # Defines a class attribute and creates a class and instance reader methods. - # The underlying class variable is set to +nil+, if it is not previously - # defined. All class and instance methods created will be public, even if - # this method is called with a private or protected access modifier. - # - # module HairColors - # mattr_reader :hair_colors - # end - # - # HairColors.hair_colors # => nil - # HairColors.class_variable_set("@@hair_colors", [:brown, :black]) - # HairColors.hair_colors # => [:brown, :black] - # - # The attribute name must be a valid method name in Ruby. - # - # module Foo - # mattr_reader :"1_Badname" - # end - # # => NameError: invalid attribute name: 1_Badname - # - # If you want to opt out the creation on the instance reader method, pass - # instance_reader: false or instance_accessor: false. - # - # module HairColors - # mattr_reader :hair_colors, instance_reader: false - # end - # - # class Person - # include HairColors - # end - # - # Person.new.hair_colors # => NoMethodError - # - # - # Also, you can pass a block to set up the attribute with a default value. - # - # module HairColors - # mattr_reader :hair_colors do - # [:brown, :black, :blonde, :red] - # end - # end - # - # class Person - # include HairColors - # end - # - # Person.new.hair_colors # => [:brown, :black, :blonde, :red] - def mattr_reader(*syms) - options = syms.extract_options! - syms.each do |sym| - raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - @@#{sym} = nil unless defined? @@#{sym} - - def self.#{sym} - @@#{sym} - end - EOS - - unless options[:instance_reader] == false || options[:instance_accessor] == false - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{sym} - @@#{sym} - end - EOS - end - class_variable_set("@@#{sym}", yield) if block_given? - end - end - alias :cattr_reader :mattr_reader - - # Defines a class attribute and creates a class and instance writer methods to - # allow assignment to the attribute. All class and instance methods created - # will be public, even if this method is called with a private or protected - # access modifier. - # - # module HairColors - # mattr_writer :hair_colors - # end - # - # class Person - # include HairColors - # end - # - # HairColors.hair_colors = [:brown, :black] - # Person.class_variable_get("@@hair_colors") # => [:brown, :black] - # Person.new.hair_colors = [:blonde, :red] - # HairColors.class_variable_get("@@hair_colors") # => [:blonde, :red] - # - # If you want to opt out the instance writer method, pass - # instance_writer: false or instance_accessor: false. - # - # module HairColors - # mattr_writer :hair_colors, instance_writer: false - # end - # - # class Person - # include HairColors - # end - # - # Person.new.hair_colors = [:blonde, :red] # => NoMethodError - # - # Also, you can pass a block to set up the attribute with a default value. - # - # module HairColors - # mattr_writer :hair_colors do - # [:brown, :black, :blonde, :red] - # end - # end - # - # class Person - # include HairColors - # end - # - # Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red] - def mattr_writer(*syms) - options = syms.extract_options! - syms.each do |sym| - raise NameError.new("invalid attribute name: #{sym}") unless /\A[_A-Za-z]\w*\z/.match?(sym) - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - @@#{sym} = nil unless defined? @@#{sym} - - def self.#{sym}=(obj) - @@#{sym} = obj - end - EOS - - unless options[:instance_writer] == false || options[:instance_accessor] == false - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{sym}=(obj) - @@#{sym} = obj - end - EOS - end - send("#{sym}=", yield) if block_given? - end - end - alias :cattr_writer :mattr_writer - - # Defines both class and instance accessors for class attributes. - # All class and instance methods created will be public, even if - # this method is called with a private or protected access modifier. - # - # module HairColors - # mattr_accessor :hair_colors - # end - # - # class Person - # include HairColors - # end - # - # HairColors.hair_colors = [:brown, :black, :blonde, :red] - # HairColors.hair_colors # => [:brown, :black, :blonde, :red] - # Person.new.hair_colors # => [:brown, :black, :blonde, :red] - # - # If a subclass changes the value then that would also change the value for - # parent class. Similarly if parent class changes the value then that would - # change the value of subclasses too. - # - # class Male < Person - # end - # - # Male.new.hair_colors << :blue - # Person.new.hair_colors # => [:brown, :black, :blonde, :red, :blue] - # - # To opt out of the instance writer method, pass instance_writer: false. - # To opt out of the instance reader method, pass instance_reader: false. - # - # module HairColors - # mattr_accessor :hair_colors, instance_writer: false, instance_reader: false - # end - # - # class Person - # include HairColors - # end - # - # Person.new.hair_colors = [:brown] # => NoMethodError - # Person.new.hair_colors # => NoMethodError - # - # Or pass instance_accessor: false, to opt out both instance methods. - # - # module HairColors - # mattr_accessor :hair_colors, instance_accessor: false - # end - # - # class Person - # include HairColors - # end - # - # Person.new.hair_colors = [:brown] # => NoMethodError - # Person.new.hair_colors # => NoMethodError - # - # Also you can pass a block to set up the attribute with a default value. - # - # module HairColors - # mattr_accessor :hair_colors do - # [:brown, :black, :blonde, :red] - # end - # end - # - # class Person - # include HairColors - # end - # - # Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red] - def mattr_accessor(*syms, &blk) - mattr_reader(*syms, &blk) - mattr_writer(*syms) - end - alias :cattr_accessor :mattr_accessor -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb deleted file mode 100644 index 1e82b4acc2..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/attribute_accessors_per_thread.rb +++ /dev/null @@ -1,148 +0,0 @@ -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/regexp" - -# Extends the module object with class/module and instance accessors for -# class/module attributes, just like the native attr* accessors for instance -# attributes, but does so on a per-thread basis. -# -# So the values are scoped within the Thread.current space under the class name -# of the module. -class Module - # Defines a per-thread class attribute and creates class and instance reader methods. - # The underlying per-thread class variable is set to +nil+, if it is not previously defined. - # - # module Current - # thread_mattr_reader :user - # end - # - # Current.user # => nil - # Thread.current[:attr_Current_user] = "DHH" - # Current.user # => "DHH" - # - # The attribute name must be a valid method name in Ruby. - # - # module Foo - # thread_mattr_reader :"1_Badname" - # end - # # => NameError: invalid attribute name: 1_Badname - # - # If you want to opt out of the creation of the instance reader method, pass - # instance_reader: false or instance_accessor: false. - # - # class Current - # thread_mattr_reader :user, instance_reader: false - # end - # - # Current.new.user # => NoMethodError - def thread_mattr_reader(*syms) # :nodoc: - options = syms.extract_options! - - syms.each do |sym| - raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym) - - # The following generated method concatenates `name` because we want it - # to work with inheritance via polymorphism. - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def self.#{sym} - Thread.current["attr_" + name + "_#{sym}"] - end - EOS - - unless options[:instance_reader] == false || options[:instance_accessor] == false - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{sym} - self.class.#{sym} - end - EOS - end - end - end - alias :thread_cattr_reader :thread_mattr_reader - - # Defines a per-thread class attribute and creates a class and instance writer methods to - # allow assignment to the attribute. - # - # module Current - # thread_mattr_writer :user - # end - # - # Current.user = "DHH" - # Thread.current[:attr_Current_user] # => "DHH" - # - # If you want to opt out of the creation of the instance writer method, pass - # instance_writer: false or instance_accessor: false. - # - # class Current - # thread_mattr_writer :user, instance_writer: false - # end - # - # Current.new.user = "DHH" # => NoMethodError - def thread_mattr_writer(*syms) # :nodoc: - options = syms.extract_options! - syms.each do |sym| - raise NameError.new("invalid attribute name: #{sym}") unless /^[_A-Za-z]\w*$/.match?(sym) - - # The following generated method concatenates `name` because we want it - # to work with inheritance via polymorphism. - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def self.#{sym}=(obj) - Thread.current["attr_" + name + "_#{sym}"] = obj - end - EOS - - unless options[:instance_writer] == false || options[:instance_accessor] == false - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{sym}=(obj) - self.class.#{sym} = obj - end - EOS - end - end - end - alias :thread_cattr_writer :thread_mattr_writer - - # Defines both class and instance accessors for class attributes. - # - # class Account - # thread_mattr_accessor :user - # end - # - # Account.user = "DHH" - # Account.user # => "DHH" - # Account.new.user # => "DHH" - # - # If a subclass changes the value, the parent class' value is not changed. - # Similarly, if the parent class changes the value, the value of subclasses - # is not changed. - # - # class Customer < Account - # end - # - # Customer.user = "Rafael" - # Customer.user # => "Rafael" - # Account.user # => "DHH" - # - # To opt out of the instance writer method, pass instance_writer: false. - # To opt out of the instance reader method, pass instance_reader: false. - # - # class Current - # thread_mattr_accessor :user, instance_writer: false, instance_reader: false - # end - # - # Current.new.user = "DHH" # => NoMethodError - # Current.new.user # => NoMethodError - # - # Or pass instance_accessor: false, to opt out both instance methods. - # - # class Current - # mattr_accessor :user, instance_accessor: false - # end - # - # Current.new.user = "DHH" # => NoMethodError - # Current.new.user # => NoMethodError - def thread_mattr_accessor(*syms) - thread_mattr_reader(*syms) - thread_mattr_writer(*syms) - end - alias :thread_cattr_accessor :thread_mattr_accessor -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/concerning.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/concerning.rb deleted file mode 100644 index 97b0a382ce..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/concerning.rb +++ /dev/null @@ -1,135 +0,0 @@ -require "active_support/concern" - -class Module - # = Bite-sized separation of concerns - # - # We often find ourselves with a medium-sized chunk of behavior that we'd - # like to extract, but only mix in to a single class. - # - # Extracting a plain old Ruby object to encapsulate it and collaborate or - # delegate to the original object is often a good choice, but when there's - # no additional state to encapsulate or we're making DSL-style declarations - # about the parent class, introducing new collaborators can obfuscate rather - # than simplify. - # - # The typical route is to just dump everything in a monolithic class, perhaps - # with a comment, as a least-bad alternative. Using modules in separate files - # means tedious sifting to get a big-picture view. - # - # = Dissatisfying ways to separate small concerns - # - # == Using comments: - # - # class Todo - # # Other todo implementation - # # ... - # - # ## Event tracking - # has_many :events - # - # before_create :track_creation - # after_destroy :track_deletion - # - # private - # def track_creation - # # ... - # end - # end - # - # == With an inline module: - # - # Noisy syntax. - # - # class Todo - # # Other todo implementation - # # ... - # - # module EventTracking - # extend ActiveSupport::Concern - # - # included do - # has_many :events - # before_create :track_creation - # after_destroy :track_deletion - # end - # - # private - # def track_creation - # # ... - # end - # end - # include EventTracking - # end - # - # == Mix-in noise exiled to its own file: - # - # Once our chunk of behavior starts pushing the scroll-to-understand-it - # boundary, we give in and move it to a separate file. At this size, the - # increased overhead can be a reasonable tradeoff even if it reduces our - # at-a-glance perception of how things work. - # - # class Todo - # # Other todo implementation - # # ... - # - # include TodoEventTracking - # end - # - # = Introducing Module#concerning - # - # By quieting the mix-in noise, we arrive at a natural, low-ceremony way to - # separate bite-sized concerns. - # - # class Todo - # # Other todo implementation - # # ... - # - # concerning :EventTracking do - # included do - # has_many :events - # before_create :track_creation - # after_destroy :track_deletion - # end - # - # private - # def track_creation - # # ... - # end - # end - # end - # - # Todo.ancestors - # # => [Todo, Todo::EventTracking, Object] - # - # This small step has some wonderful ripple effects. We can - # * grok the behavior of our class in one glance, - # * clean up monolithic junk-drawer classes by separating their concerns, and - # * stop leaning on protected/private for crude "this is internal stuff" modularity. - module Concerning - # Define a new concern and mix it in. - def concerning(topic, &block) - include concern(topic, &block) - end - - # A low-cruft shortcut to define a concern. - # - # concern :EventTracking do - # ... - # end - # - # is equivalent to - # - # module EventTracking - # extend ActiveSupport::Concern - # - # ... - # end - def concern(topic, &module_definition) - const_set topic, Module.new { - extend ::ActiveSupport::Concern - module_eval(&module_definition) - } - end - end - include Concerning -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/delegation.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/delegation.rb deleted file mode 100644 index 85ab739095..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/delegation.rb +++ /dev/null @@ -1,285 +0,0 @@ -require "set" -require "active_support/core_ext/regexp" - -class Module - # Error generated by +delegate+ when a method is called on +nil+ and +allow_nil+ - # option is not used. - class DelegationError < NoMethodError; end - - RUBY_RESERVED_KEYWORDS = %w(alias and BEGIN begin break case class def defined? do - else elsif END end ensure false for if in module next nil not or redo rescue retry - return self super then true undef unless until when while yield) - DELEGATION_RESERVED_KEYWORDS = %w(_ arg args block) - DELEGATION_RESERVED_METHOD_NAMES = Set.new( - RUBY_RESERVED_KEYWORDS + DELEGATION_RESERVED_KEYWORDS - ).freeze - - # Provides a +delegate+ class method to easily expose contained objects' - # public methods as your own. - # - # ==== Options - # * :to - Specifies the target object - # * :prefix - Prefixes the new method with the target name or a custom prefix - # * :allow_nil - if set to true, prevents a +Module::DelegationError+ - # from being raised - # - # The macro receives one or more method names (specified as symbols or - # strings) and the name of the target object via the :to option - # (also a symbol or string). - # - # Delegation is particularly useful with Active Record associations: - # - # class Greeter < ActiveRecord::Base - # def hello - # 'hello' - # end - # - # def goodbye - # 'goodbye' - # end - # end - # - # class Foo < ActiveRecord::Base - # belongs_to :greeter - # delegate :hello, to: :greeter - # end - # - # Foo.new.hello # => "hello" - # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for # - # - # Multiple delegates to the same target are allowed: - # - # class Foo < ActiveRecord::Base - # belongs_to :greeter - # delegate :hello, :goodbye, to: :greeter - # end - # - # Foo.new.goodbye # => "goodbye" - # - # Methods can be delegated to instance variables, class variables, or constants - # by providing them as a symbols: - # - # class Foo - # CONSTANT_ARRAY = [0,1,2,3] - # @@class_array = [4,5,6,7] - # - # def initialize - # @instance_array = [8,9,10,11] - # end - # delegate :sum, to: :CONSTANT_ARRAY - # delegate :min, to: :@@class_array - # delegate :max, to: :@instance_array - # end - # - # Foo.new.sum # => 6 - # Foo.new.min # => 4 - # Foo.new.max # => 11 - # - # It's also possible to delegate a method to the class by using +:class+: - # - # class Foo - # def self.hello - # "world" - # end - # - # delegate :hello, to: :class - # end - # - # Foo.new.hello # => "world" - # - # Delegates can optionally be prefixed using the :prefix option. If the value - # is true, the delegate methods are prefixed with the name of the object being - # delegated to. - # - # Person = Struct.new(:name, :address) - # - # class Invoice < Struct.new(:client) - # delegate :name, :address, to: :client, prefix: true - # end - # - # john_doe = Person.new('John Doe', 'Vimmersvej 13') - # invoice = Invoice.new(john_doe) - # invoice.client_name # => "John Doe" - # invoice.client_address # => "Vimmersvej 13" - # - # It is also possible to supply a custom prefix. - # - # class Invoice < Struct.new(:client) - # delegate :name, :address, to: :client, prefix: :customer - # end - # - # invoice = Invoice.new(john_doe) - # invoice.customer_name # => 'John Doe' - # invoice.customer_address # => 'Vimmersvej 13' - # - # If the target is +nil+ and does not respond to the delegated method a - # +Module::DelegationError+ is raised, as with any other value. Sometimes, - # however, it makes sense to be robust to that situation and that is the - # purpose of the :allow_nil option: If the target is not +nil+, or it - # is and responds to the method, everything works as usual. But if it is +nil+ - # and does not respond to the delegated method, +nil+ is returned. - # - # class User < ActiveRecord::Base - # has_one :profile - # delegate :age, to: :profile - # end - # - # User.new.age - # # => Module::DelegationError: User#age delegated to profile.age, but profile is nil - # - # But if not having a profile yet is fine and should not be an error - # condition: - # - # class User < ActiveRecord::Base - # has_one :profile - # delegate :age, to: :profile, allow_nil: true - # end - # - # User.new.age # nil - # - # Note that if the target is not +nil+ then the call is attempted regardless of the - # :allow_nil option, and thus an exception is still raised if said object - # does not respond to the method: - # - # class Foo - # def initialize(bar) - # @bar = bar - # end - # - # delegate :name, to: :@bar, allow_nil: true - # end - # - # Foo.new("Bar").name # raises NoMethodError: undefined method `name' - # - # The target method must be public, otherwise it will raise +NoMethodError+. - def delegate(*methods, to: nil, prefix: nil, allow_nil: nil) - unless to - raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter)." - end - - if prefix == true && /^[^a-z_]/.match?(to) - raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method." - end - - method_prefix = \ - if prefix - "#{prefix == true ? to : prefix}_" - else - "" - end - - location = caller_locations(1, 1).first - file, line = location.path, location.lineno - - to = to.to_s - to = "self.#{to}" if DELEGATION_RESERVED_METHOD_NAMES.include?(to) - - methods.each do |method| - # Attribute writer methods only accept one argument. Makes sure []= - # methods still accept two arguments. - definition = /[^\]]=$/.match?(method) ? "arg" : "*args, &block" - - # The following generated method calls the target exactly once, storing - # the returned value in a dummy variable. - # - # Reason is twofold: On one hand doing less calls is in general better. - # On the other hand it could be that the target has side-effects, - # whereas conceptually, from the user point of view, the delegator should - # be doing one call. - if allow_nil - method_def = [ - "def #{method_prefix}#{method}(#{definition})", - "_ = #{to}", - "if !_.nil? || nil.respond_to?(:#{method})", - " _.#{method}(#{definition})", - "end", - "end" - ].join ";" - else - exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}") - - method_def = [ - "def #{method_prefix}#{method}(#{definition})", - " _ = #{to}", - " _.#{method}(#{definition})", - "rescue NoMethodError => e", - " if _.nil? && e.name == :#{method}", - " #{exception}", - " else", - " raise", - " end", - "end" - ].join ";" - end - - module_eval(method_def, file, line) - end - end - - # When building decorators, a common pattern may emerge: - # - # class Partition - # def initialize(first_event) - # @events = [ first_event ] - # end - # - # def people - # if @events.first.detail.people.any? - # @events.collect { |e| Array(e.detail.people) }.flatten.uniq - # else - # @events.collect(&:creator).uniq - # end - # end - # - # private - # def respond_to_missing?(name, include_private = false) - # @events.respond_to?(name, include_private) - # end - # - # def method_missing(method, *args, &block) - # @events.send(method, *args, &block) - # end - # end - # - # With `Module#delegate_missing_to`, the above is condensed to: - # - # class Partition - # delegate_missing_to :@events - # - # def initialize(first_event) - # @events = [ first_event ] - # end - # - # def people - # if @events.first.detail.people.any? - # @events.collect { |e| Array(e.detail.people) }.flatten.uniq - # else - # @events.collect(&:creator).uniq - # end - # end - # end - # - # The target can be anything callable within the object. E.g. instance - # variables, methods, constants and the likes. - def delegate_missing_to(target) - target = target.to_s - target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target) - - module_eval <<-RUBY, __FILE__, __LINE__ + 1 - def respond_to_missing?(name, include_private = false) - # It may look like an oversight, but we deliberately do not pass - # +include_private+, because they do not get delegated. - - #{target}.respond_to?(name) || super - end - - def method_missing(method, *args, &block) - if #{target}.respond_to?(method) - #{target}.public_send(method, *args, &block) - else - super - end - end - RUBY - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/deprecation.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/deprecation.rb deleted file mode 100644 index f3f2e7f5fc..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/deprecation.rb +++ /dev/null @@ -1,23 +0,0 @@ -class Module - # deprecate :foo - # deprecate bar: 'message' - # deprecate :foo, :bar, baz: 'warning!', qux: 'gone!' - # - # You can also use custom deprecator instance: - # - # deprecate :foo, deprecator: MyLib::Deprecator.new - # deprecate :foo, bar: "warning!", deprecator: MyLib::Deprecator.new - # - # \Custom deprecators must respond to deprecation_warning(deprecated_method_name, message, caller_backtrace) - # method where you can implement your custom warning behavior. - # - # class MyLib::Deprecator - # def deprecation_warning(deprecated_method_name, message, caller_backtrace = nil) - # message = "#{deprecated_method_name} is deprecated and will be removed from MyLibrary | #{message}" - # Kernel.warn message - # end - # end - def deprecate(*method_names) - ActiveSupport::Deprecation.deprecate_methods(self, *method_names) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/introspection.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/introspection.rb deleted file mode 100644 index ca20a6d4c5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/introspection.rb +++ /dev/null @@ -1,60 +0,0 @@ -require "active_support/inflector" - -class Module - # Returns the name of the module containing this one. - # - # M::N.parent_name # => "M" - def parent_name - if defined?(@parent_name) - @parent_name - else - parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil - @parent_name = parent_name unless frozen? - parent_name - end - end - - # Returns the module which contains this one according to its name. - # - # module M - # module N - # end - # end - # X = M::N - # - # M::N.parent # => M - # X.parent # => M - # - # The parent of top-level and anonymous modules is Object. - # - # M.parent # => Object - # Module.new.parent # => Object - def parent - parent_name ? ActiveSupport::Inflector.constantize(parent_name) : Object - end - - # Returns all the parents of this module according to its name, ordered from - # nested outwards. The receiver is not contained within the result. - # - # module M - # module N - # end - # end - # X = M::N - # - # M.parents # => [Object] - # M::N.parents # => [M, Object] - # X.parents # => [M, Object] - def parents - parents = [] - if parent_name - parts = parent_name.split("::") - until parts.empty? - parents << ActiveSupport::Inflector.constantize(parts * "::") - parts.pop - end - end - parents << Object unless parents.include? Object - parents - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/reachable.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/reachable.rb deleted file mode 100644 index b89a38f26c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/reachable.rb +++ /dev/null @@ -1,8 +0,0 @@ -require "active_support/core_ext/module/anonymous" -require "active_support/core_ext/string/inflections" - -class Module - def reachable? #:nodoc: - !anonymous? && name.safe_constantize.equal?(self) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/remove_method.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/remove_method.rb deleted file mode 100644 index d5ec16d68a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/module/remove_method.rb +++ /dev/null @@ -1,35 +0,0 @@ -class Module - # Removes the named method, if it exists. - def remove_possible_method(method) - if method_defined?(method) || private_method_defined?(method) - undef_method(method) - end - end - - # Removes the named singleton method, if it exists. - def remove_possible_singleton_method(method) - singleton_class.instance_eval do - remove_possible_method(method) - end - end - - # Replaces the existing method definition, if there is one, with the passed - # block as its body. - def redefine_method(method, &block) - visibility = method_visibility(method) - remove_possible_method(method) - define_method(method, &block) - send(visibility, method) - end - - def method_visibility(method) # :nodoc: - case - when private_method_defined?(method) - :private - when protected_method_defined?(method) - :protected - else - :public - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/name_error.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/name_error.rb deleted file mode 100644 index 6b447d772b..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/name_error.rb +++ /dev/null @@ -1,31 +0,0 @@ -class NameError - # Extract the name of the missing constant from the exception message. - # - # begin - # HelloWorld - # rescue NameError => e - # e.missing_name - # end - # # => "HelloWorld" - def missing_name - if /undefined local variable or method/ !~ message - $1 if /((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/ =~ message - end - end - - # Was this exception raised because the given name was missing? - # - # begin - # HelloWorld - # rescue NameError => e - # e.missing_name?("HelloWorld") - # end - # # => true - def missing_name?(name) - if name.is_a? Symbol - self.name == name - else - missing_name == name.to_s - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric.rb deleted file mode 100644 index 6062f9e3a8..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric.rb +++ /dev/null @@ -1,4 +0,0 @@ -require "active_support/core_ext/numeric/bytes" -require "active_support/core_ext/numeric/time" -require "active_support/core_ext/numeric/inquiry" -require "active_support/core_ext/numeric/conversions" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/bytes.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/bytes.rb deleted file mode 100644 index dfbca32474..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/bytes.rb +++ /dev/null @@ -1,64 +0,0 @@ -class Numeric - KILOBYTE = 1024 - MEGABYTE = KILOBYTE * 1024 - GIGABYTE = MEGABYTE * 1024 - TERABYTE = GIGABYTE * 1024 - PETABYTE = TERABYTE * 1024 - EXABYTE = PETABYTE * 1024 - - # Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes - # - # 2.bytes # => 2 - def bytes - self - end - alias :byte :bytes - - # Returns the number of bytes equivalent to the kilobytes provided. - # - # 2.kilobytes # => 2048 - def kilobytes - self * KILOBYTE - end - alias :kilobyte :kilobytes - - # Returns the number of bytes equivalent to the megabytes provided. - # - # 2.megabytes # => 2_097_152 - def megabytes - self * MEGABYTE - end - alias :megabyte :megabytes - - # Returns the number of bytes equivalent to the gigabytes provided. - # - # 2.gigabytes # => 2_147_483_648 - def gigabytes - self * GIGABYTE - end - alias :gigabyte :gigabytes - - # Returns the number of bytes equivalent to the terabytes provided. - # - # 2.terabytes # => 2_199_023_255_552 - def terabytes - self * TERABYTE - end - alias :terabyte :terabytes - - # Returns the number of bytes equivalent to the petabytes provided. - # - # 2.petabytes # => 2_251_799_813_685_248 - def petabytes - self * PETABYTE - end - alias :petabyte :petabytes - - # Returns the number of bytes equivalent to the exabytes provided. - # - # 2.exabytes # => 2_305_843_009_213_693_952 - def exabytes - self * EXABYTE - end - alias :exabyte :exabytes -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/conversions.rb deleted file mode 100644 index 4f6621693e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/conversions.rb +++ /dev/null @@ -1,138 +0,0 @@ -require "active_support/core_ext/big_decimal/conversions" -require "active_support/number_helper" -require "active_support/core_ext/module/deprecation" - -module ActiveSupport::NumericWithFormat - # Provides options for converting numbers into formatted strings. - # Options are provided for phone numbers, currency, percentage, - # precision, positional notation, file size and pretty printing. - # - # ==== Options - # - # For details on which formats use which options, see ActiveSupport::NumberHelper - # - # ==== Examples - # - # Phone Numbers: - # 5551234.to_s(:phone) # => "555-1234" - # 1235551234.to_s(:phone) # => "123-555-1234" - # 1235551234.to_s(:phone, area_code: true) # => "(123) 555-1234" - # 1235551234.to_s(:phone, delimiter: ' ') # => "123 555 1234" - # 1235551234.to_s(:phone, area_code: true, extension: 555) # => "(123) 555-1234 x 555" - # 1235551234.to_s(:phone, country_code: 1) # => "+1-123-555-1234" - # 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.') - # # => "+1.123.555.1234 x 1343" - # - # Currency: - # 1234567890.50.to_s(:currency) # => "$1,234,567,890.50" - # 1234567890.506.to_s(:currency) # => "$1,234,567,890.51" - # 1234567890.506.to_s(:currency, precision: 3) # => "$1,234,567,890.506" - # 1234567890.506.to_s(:currency, locale: :fr) # => "1 234 567 890,51 €" - # -1234567890.50.to_s(:currency, negative_format: '(%u%n)') - # # => "($1,234,567,890.50)" - # 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '') - # # => "£1234567890,50" - # 1234567890.50.to_s(:currency, unit: '£', separator: ',', delimiter: '', format: '%n %u') - # # => "1234567890,50 £" - # - # Percentage: - # 100.to_s(:percentage) # => "100.000%" - # 100.to_s(:percentage, precision: 0) # => "100%" - # 1000.to_s(:percentage, delimiter: '.', separator: ',') # => "1.000,000%" - # 302.24398923423.to_s(:percentage, precision: 5) # => "302.24399%" - # 1000.to_s(:percentage, locale: :fr) # => "1 000,000%" - # 100.to_s(:percentage, format: '%n %') # => "100.000 %" - # - # Delimited: - # 12345678.to_s(:delimited) # => "12,345,678" - # 12345678.05.to_s(:delimited) # => "12,345,678.05" - # 12345678.to_s(:delimited, delimiter: '.') # => "12.345.678" - # 12345678.to_s(:delimited, delimiter: ',') # => "12,345,678" - # 12345678.05.to_s(:delimited, separator: ' ') # => "12,345,678 05" - # 12345678.05.to_s(:delimited, locale: :fr) # => "12 345 678,05" - # 98765432.98.to_s(:delimited, delimiter: ' ', separator: ',') - # # => "98 765 432,98" - # - # Rounded: - # 111.2345.to_s(:rounded) # => "111.235" - # 111.2345.to_s(:rounded, precision: 2) # => "111.23" - # 13.to_s(:rounded, precision: 5) # => "13.00000" - # 389.32314.to_s(:rounded, precision: 0) # => "389" - # 111.2345.to_s(:rounded, significant: true) # => "111" - # 111.2345.to_s(:rounded, precision: 1, significant: true) # => "100" - # 13.to_s(:rounded, precision: 5, significant: true) # => "13.000" - # 111.234.to_s(:rounded, locale: :fr) # => "111,234" - # 13.to_s(:rounded, precision: 5, significant: true, strip_insignificant_zeros: true) - # # => "13" - # 389.32314.to_s(:rounded, precision: 4, significant: true) # => "389.3" - # 1111.2345.to_s(:rounded, precision: 2, separator: ',', delimiter: '.') - # # => "1.111,23" - # - # Human-friendly size in Bytes: - # 123.to_s(:human_size) # => "123 Bytes" - # 1234.to_s(:human_size) # => "1.21 KB" - # 12345.to_s(:human_size) # => "12.1 KB" - # 1234567.to_s(:human_size) # => "1.18 MB" - # 1234567890.to_s(:human_size) # => "1.15 GB" - # 1234567890123.to_s(:human_size) # => "1.12 TB" - # 1234567890123456.to_s(:human_size) # => "1.1 PB" - # 1234567890123456789.to_s(:human_size) # => "1.07 EB" - # 1234567.to_s(:human_size, precision: 2) # => "1.2 MB" - # 483989.to_s(:human_size, precision: 2) # => "470 KB" - # 1234567.to_s(:human_size, precision: 2, separator: ',') # => "1,2 MB" - # 1234567890123.to_s(:human_size, precision: 5) # => "1.1228 TB" - # 524288000.to_s(:human_size, precision: 5) # => "500 MB" - # - # Human-friendly format: - # 123.to_s(:human) # => "123" - # 1234.to_s(:human) # => "1.23 Thousand" - # 12345.to_s(:human) # => "12.3 Thousand" - # 1234567.to_s(:human) # => "1.23 Million" - # 1234567890.to_s(:human) # => "1.23 Billion" - # 1234567890123.to_s(:human) # => "1.23 Trillion" - # 1234567890123456.to_s(:human) # => "1.23 Quadrillion" - # 1234567890123456789.to_s(:human) # => "1230 Quadrillion" - # 489939.to_s(:human, precision: 2) # => "490 Thousand" - # 489939.to_s(:human, precision: 4) # => "489.9 Thousand" - # 1234567.to_s(:human, precision: 4, - # significant: false) # => "1.2346 Million" - # 1234567.to_s(:human, precision: 1, - # separator: ',', - # significant: false) # => "1,2 Million" - def to_s(format = nil, options = nil) - case format - when nil - super() - when Integer, String - super(format) - when :phone - return ActiveSupport::NumberHelper.number_to_phone(self, options || {}) - when :currency - return ActiveSupport::NumberHelper.number_to_currency(self, options || {}) - when :percentage - return ActiveSupport::NumberHelper.number_to_percentage(self, options || {}) - when :delimited - return ActiveSupport::NumberHelper.number_to_delimited(self, options || {}) - when :rounded - return ActiveSupport::NumberHelper.number_to_rounded(self, options || {}) - when :human - return ActiveSupport::NumberHelper.number_to_human(self, options || {}) - when :human_size - return ActiveSupport::NumberHelper.number_to_human_size(self, options || {}) - when Symbol - super() - else - super(format) - end - end -end - -# Ruby 2.4+ unifies Fixnum & Bignum into Integer. -if 0.class == Integer - Integer.prepend ActiveSupport::NumericWithFormat -else - Fixnum.prepend ActiveSupport::NumericWithFormat - Bignum.prepend ActiveSupport::NumericWithFormat -end -Float.prepend ActiveSupport::NumericWithFormat -BigDecimal.prepend ActiveSupport::NumericWithFormat diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/inquiry.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/inquiry.rb deleted file mode 100644 index ec79701189..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/inquiry.rb +++ /dev/null @@ -1,26 +0,0 @@ -unless 1.respond_to?(:positive?) # TODO: Remove this file when we drop support to ruby < 2.3 - class Numeric - # Returns true if the number is positive. - # - # 1.positive? # => true - # 0.positive? # => false - # -1.positive? # => false - def positive? - self > 0 - end - - # Returns true if the number is negative. - # - # -1.negative? # => true - # 0.negative? # => false - # 1.negative? # => false - def negative? - self < 0 - end - end - - class Complex - undef :positive? - undef :negative? - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/time.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/time.rb deleted file mode 100644 index 2e6c70d418..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/numeric/time.rb +++ /dev/null @@ -1,74 +0,0 @@ -require "active_support/duration" -require "active_support/core_ext/time/calculations" -require "active_support/core_ext/time/acts_like" -require "active_support/core_ext/date/calculations" -require "active_support/core_ext/date/acts_like" - -class Numeric - # Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years. - # - # These methods use Time#advance for precise date calculations when using from_now, ago, etc. - # as well as adding or subtracting their results from a Time object. For example: - # - # # equivalent to Time.current.advance(months: 1) - # 1.month.from_now - # - # # equivalent to Time.current.advance(years: 2) - # 2.years.from_now - # - # # equivalent to Time.current.advance(months: 4, years: 5) - # (4.months + 5.years).from_now - def seconds - ActiveSupport::Duration.seconds(self) - end - alias :second :seconds - - # Returns a Duration instance matching the number of minutes provided. - # - # 2.minutes # => 2 minutes - def minutes - ActiveSupport::Duration.minutes(self) - end - alias :minute :minutes - - # Returns a Duration instance matching the number of hours provided. - # - # 2.hours # => 2 hours - def hours - ActiveSupport::Duration.hours(self) - end - alias :hour :hours - - # Returns a Duration instance matching the number of days provided. - # - # 2.days # => 2 days - def days - ActiveSupport::Duration.days(self) - end - alias :day :days - - # Returns a Duration instance matching the number of weeks provided. - # - # 2.weeks # => 2 weeks - def weeks - ActiveSupport::Duration.weeks(self) - end - alias :week :weeks - - # Returns a Duration instance matching the number of fortnights provided. - # - # 2.fortnights # => 4 weeks - def fortnights - ActiveSupport::Duration.weeks(self * 2) - end - alias :fortnight :fortnights - - # Returns the number of milliseconds equivalent to the seconds provided. - # Used with the standard time durations, like 1.hour.in_milliseconds -- - # so we can feed them to JavaScript functions like getTime(). - # - # 2.in_milliseconds # => 2_000 - def in_milliseconds - self * 1000 - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object.rb deleted file mode 100644 index 58bbf78601..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object.rb +++ /dev/null @@ -1,14 +0,0 @@ -require "active_support/core_ext/object/acts_like" -require "active_support/core_ext/object/blank" -require "active_support/core_ext/object/duplicable" -require "active_support/core_ext/object/deep_dup" -require "active_support/core_ext/object/try" -require "active_support/core_ext/object/inclusion" - -require "active_support/core_ext/object/conversions" -require "active_support/core_ext/object/instance_variables" - -require "active_support/core_ext/object/json" -require "active_support/core_ext/object/to_param" -require "active_support/core_ext/object/to_query" -require "active_support/core_ext/object/with_options" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/acts_like.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/acts_like.rb deleted file mode 100644 index 3912cc5ace..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/acts_like.rb +++ /dev/null @@ -1,10 +0,0 @@ -class Object - # A duck-type assistant method. For example, Active Support extends Date - # to define an acts_like_date? method, and extends Time to define - # acts_like_time?. As a result, we can do x.acts_like?(:time) and - # x.acts_like?(:date) to do duck-type-safe comparisons, since classes that - # we want to act like Time simply need to define an acts_like_time? method. - def acts_like?(duck) - respond_to? :"acts_like_#{duck}?" - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/blank.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/blank.rb deleted file mode 100644 index bdb50ee291..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/blank.rb +++ /dev/null @@ -1,145 +0,0 @@ -require "active_support/core_ext/regexp" - -class Object - # An object is blank if it's false, empty, or a whitespace string. - # For example, +false+, '', ' ', +nil+, [], and {} are all blank. - # - # This simplifies - # - # !address || address.empty? - # - # to - # - # address.blank? - # - # @return [true, false] - def blank? - respond_to?(:empty?) ? !!empty? : !self - end - - # An object is present if it's not blank. - # - # @return [true, false] - def present? - !blank? - end - - # Returns the receiver if it's present otherwise returns +nil+. - # object.presence is equivalent to - # - # object.present? ? object : nil - # - # For example, something like - # - # state = params[:state] if params[:state].present? - # country = params[:country] if params[:country].present? - # region = state || country || 'US' - # - # becomes - # - # region = params[:state].presence || params[:country].presence || 'US' - # - # @return [Object] - def presence - self if present? - end -end - -class NilClass - # +nil+ is blank: - # - # nil.blank? # => true - # - # @return [true] - def blank? - true - end -end - -class FalseClass - # +false+ is blank: - # - # false.blank? # => true - # - # @return [true] - def blank? - true - end -end - -class TrueClass - # +true+ is not blank: - # - # true.blank? # => false - # - # @return [false] - def blank? - false - end -end - -class Array - # An array is blank if it's empty: - # - # [].blank? # => true - # [1,2,3].blank? # => false - # - # @return [true, false] - alias_method :blank?, :empty? -end - -class Hash - # A hash is blank if it's empty: - # - # {}.blank? # => true - # { key: 'value' }.blank? # => false - # - # @return [true, false] - alias_method :blank?, :empty? -end - -class String - BLANK_RE = /\A[[:space:]]*\z/ - - # A string is blank if it's empty or contains whitespaces only: - # - # ''.blank? # => true - # ' '.blank? # => true - # "\t\n\r".blank? # => true - # ' blah '.blank? # => false - # - # Unicode whitespace is supported: - # - # "\u00a0".blank? # => true - # - # @return [true, false] - def blank? - # The regexp that matches blank strings is expensive. For the case of empty - # strings we can speed up this method (~3.5x) with an empty? call. The - # penalty for the rest of strings is marginal. - empty? || BLANK_RE.match?(self) - end -end - -class Numeric #:nodoc: - # No number is blank: - # - # 1.blank? # => false - # 0.blank? # => false - # - # @return [false] - def blank? - false - end -end - -class Time #:nodoc: - # No Time is blank: - # - # Time.now.blank? # => false - # - # @return [false] - def blank? - false - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/conversions.rb deleted file mode 100644 index 918ebcdc9f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/conversions.rb +++ /dev/null @@ -1,4 +0,0 @@ -require "active_support/core_ext/object/to_param" -require "active_support/core_ext/object/to_query" -require "active_support/core_ext/array/conversions" -require "active_support/core_ext/hash/conversions" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/deep_dup.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/deep_dup.rb deleted file mode 100644 index 5ac649e552..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/deep_dup.rb +++ /dev/null @@ -1,53 +0,0 @@ -require "active_support/core_ext/object/duplicable" - -class Object - # Returns a deep copy of object if it's duplicable. If it's - # not duplicable, returns +self+. - # - # object = Object.new - # dup = object.deep_dup - # dup.instance_variable_set(:@a, 1) - # - # object.instance_variable_defined?(:@a) # => false - # dup.instance_variable_defined?(:@a) # => true - def deep_dup - duplicable? ? dup : self - end -end - -class Array - # Returns a deep copy of array. - # - # array = [1, [2, 3]] - # dup = array.deep_dup - # dup[1][2] = 4 - # - # array[1][2] # => nil - # dup[1][2] # => 4 - def deep_dup - map(&:deep_dup) - end -end - -class Hash - # Returns a deep copy of hash. - # - # hash = { a: { b: 'b' } } - # dup = hash.deep_dup - # dup[:a][:c] = 'c' - # - # hash[:a][:c] # => nil - # dup[:a][:c] # => "c" - def deep_dup - hash = dup - each_pair do |key, value| - if key.frozen? && ::String === key - hash[key] = value.deep_dup - else - hash.delete(key) - hash[key.deep_dup] = value.deep_dup - end - end - hash - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/duplicable.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/duplicable.rb deleted file mode 100644 index c27fd4f792..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/duplicable.rb +++ /dev/null @@ -1,154 +0,0 @@ -#-- -# Most objects are cloneable, but not all. For example you can't dup methods: -# -# method(:puts).dup # => TypeError: allocator undefined for Method -# -# Classes may signal their instances are not duplicable removing +dup+/+clone+ -# or raising exceptions from them. So, to dup an arbitrary object you normally -# use an optimistic approach and are ready to catch an exception, say: -# -# arbitrary_object.dup rescue object -# -# Rails dups objects in a few critical spots where they are not that arbitrary. -# That rescue is very expensive (like 40 times slower than a predicate), and it -# is often triggered. -# -# That's why we hardcode the following cases and check duplicable? instead of -# using that rescue idiom. -#++ -class Object - # Can you safely dup this object? - # - # False for method objects; - # true otherwise. - def duplicable? - true - end -end - -class NilClass - begin - nil.dup - rescue TypeError - - # +nil+ is not duplicable: - # - # nil.duplicable? # => false - # nil.dup # => TypeError: can't dup NilClass - def duplicable? - false - end - end -end - -class FalseClass - begin - false.dup - rescue TypeError - - # +false+ is not duplicable: - # - # false.duplicable? # => false - # false.dup # => TypeError: can't dup FalseClass - def duplicable? - false - end - end -end - -class TrueClass - begin - true.dup - rescue TypeError - - # +true+ is not duplicable: - # - # true.duplicable? # => false - # true.dup # => TypeError: can't dup TrueClass - def duplicable? - false - end - end -end - -class Symbol - begin - :symbol.dup # Ruby 2.4.x. - "symbol_from_string".to_sym.dup # Some symbols can't `dup` in Ruby 2.4.0. - rescue TypeError - - # Symbols are not duplicable: - # - # :my_symbol.duplicable? # => false - # :my_symbol.dup # => TypeError: can't dup Symbol - def duplicable? - false - end - end -end - -class Numeric - begin - 1.dup - rescue TypeError - - # Numbers are not duplicable: - # - # 3.duplicable? # => false - # 3.dup # => TypeError: can't dup Integer - def duplicable? - false - end - end -end - -require "bigdecimal" -class BigDecimal - # BigDecimals are duplicable: - # - # BigDecimal.new("1.2").duplicable? # => true - # BigDecimal.new("1.2").dup # => # - def duplicable? - true - end -end - -class Method - # Methods are not duplicable: - # - # method(:puts).duplicable? # => false - # method(:puts).dup # => TypeError: allocator undefined for Method - def duplicable? - false - end -end - -class Complex - begin - Complex(1).dup - rescue TypeError - - # Complexes are not duplicable for RUBY_VERSION < 2.5.0: - # - # Complex(1).duplicable? # => false - # Complex(1).dup # => TypeError: can't copy Complex - def duplicable? - false - end - end -end - -class Rational - begin - Rational(1).dup - rescue TypeError - - # Rationals are not duplicable for RUBY_VERSION < 2.5.0: - # - # Rational(1).duplicable? # => false - # Rational(1).dup # => TypeError: can't copy Rational - def duplicable? - false - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/inclusion.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/inclusion.rb deleted file mode 100644 index 98bf820d36..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/inclusion.rb +++ /dev/null @@ -1,27 +0,0 @@ -class Object - # Returns true if this object is included in the argument. Argument must be - # any object which responds to +#include?+. Usage: - # - # characters = ["Konata", "Kagami", "Tsukasa"] - # "Konata".in?(characters) # => true - # - # This will throw an +ArgumentError+ if the argument doesn't respond - # to +#include?+. - def in?(another_object) - another_object.include?(self) - rescue NoMethodError - raise ArgumentError.new("The parameter passed to #in? must respond to #include?") - end - - # Returns the receiver if it's included in the argument otherwise returns +nil+. - # Argument must be any object which responds to +#include?+. Usage: - # - # params[:bucket_type].presence_in %w( project calendar ) - # - # This will throw an +ArgumentError+ if the argument doesn't respond to +#include?+. - # - # @return [Object] - def presence_in(another_object) - in?(another_object) ? self : nil - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/instance_variables.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/instance_variables.rb deleted file mode 100644 index 593a7a4940..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/instance_variables.rb +++ /dev/null @@ -1,28 +0,0 @@ -class Object - # Returns a hash with string keys that maps instance variable names without "@" to their - # corresponding values. - # - # class C - # def initialize(x, y) - # @x, @y = x, y - # end - # end - # - # C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} - def instance_values - Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }] - end - - # Returns an array of instance variable names as strings including "@". - # - # class C - # def initialize(x, y) - # @x, @y = x, y - # end - # end - # - # C.new(0, 1).instance_variable_names # => ["@y", "@x"] - def instance_variable_names - instance_variables.map(&:to_s) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/json.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/json.rb deleted file mode 100644 index 1c4d181443..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/json.rb +++ /dev/null @@ -1,219 +0,0 @@ -# Hack to load json gem first so we can overwrite its to_json. -require "json" -require "bigdecimal" -require "uri/generic" -require "pathname" -require "active_support/core_ext/big_decimal/conversions" # for #to_s -require "active_support/core_ext/hash/except" -require "active_support/core_ext/hash/slice" -require "active_support/core_ext/object/instance_variables" -require "time" -require "active_support/core_ext/time/conversions" -require "active_support/core_ext/date_time/conversions" -require "active_support/core_ext/date/conversions" - -# The JSON gem adds a few modules to Ruby core classes containing :to_json definition, overwriting -# their default behavior. That said, we need to define the basic to_json method in all of them, -# otherwise they will always use to_json gem implementation, which is backwards incompatible in -# several cases (for instance, the JSON implementation for Hash does not work) with inheritance -# and consequently classes as ActiveSupport::OrderedHash cannot be serialized to json. -# -# On the other hand, we should avoid conflict with ::JSON.{generate,dump}(obj). Unfortunately, the -# JSON gem's encoder relies on its own to_json implementation to encode objects. Since it always -# passes a ::JSON::State object as the only argument to to_json, we can detect that and forward the -# calls to the original to_json method. -# -# It should be noted that when using ::JSON.{generate,dump} directly, ActiveSupport's encoder is -# bypassed completely. This means that as_json won't be invoked and the JSON gem will simply -# ignore any options it does not natively understand. This also means that ::JSON.{generate,dump} -# should give exactly the same results with or without active support. - -module ActiveSupport - module ToJsonWithActiveSupportEncoder # :nodoc: - def to_json(options = nil) - if options.is_a?(::JSON::State) - # Called from JSON.{generate,dump}, forward it to JSON gem's to_json - super(options) - else - # to_json is being invoked directly, use ActiveSupport's encoder - ActiveSupport::JSON.encode(self, options) - end - end - end -end - -[Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass, Enumerable].reverse_each do |klass| - klass.prepend(ActiveSupport::ToJsonWithActiveSupportEncoder) -end - -class Object - def as_json(options = nil) #:nodoc: - if respond_to?(:to_hash) - to_hash.as_json(options) - else - instance_values.as_json(options) - end - end -end - -class Struct #:nodoc: - def as_json(options = nil) - Hash[members.zip(values)].as_json(options) - end -end - -class TrueClass - def as_json(options = nil) #:nodoc: - self - end -end - -class FalseClass - def as_json(options = nil) #:nodoc: - self - end -end - -class NilClass - def as_json(options = nil) #:nodoc: - self - end -end - -class String - def as_json(options = nil) #:nodoc: - self - end -end - -class Symbol - def as_json(options = nil) #:nodoc: - to_s - end -end - -class Numeric - def as_json(options = nil) #:nodoc: - self - end -end - -class Float - # Encoding Infinity or NaN to JSON should return "null". The default returns - # "Infinity" or "NaN" which are not valid JSON. - def as_json(options = nil) #:nodoc: - finite? ? self : nil - end -end - -class BigDecimal - # A BigDecimal would be naturally represented as a JSON number. Most libraries, - # however, parse non-integer JSON numbers directly as floats. Clients using - # those libraries would get in general a wrong number and no way to recover - # other than manually inspecting the string with the JSON code itself. - # - # That's why a JSON string is returned. The JSON literal is not numeric, but - # if the other end knows by contract that the data is supposed to be a - # BigDecimal, it still has the chance to post-process the string and get the - # real value. - def as_json(options = nil) #:nodoc: - finite? ? to_s : nil - end -end - -class Regexp - def as_json(options = nil) #:nodoc: - to_s - end -end - -module Enumerable - def as_json(options = nil) #:nodoc: - to_a.as_json(options) - end -end - -class Range - def as_json(options = nil) #:nodoc: - to_s - end -end - -class Array - def as_json(options = nil) #:nodoc: - map { |v| options ? v.as_json(options.dup) : v.as_json } - end -end - -class Hash - def as_json(options = nil) #:nodoc: - # create a subset of the hash by applying :only or :except - subset = if options - if attrs = options[:only] - slice(*Array(attrs)) - elsif attrs = options[:except] - except(*Array(attrs)) - else - self - end - else - self - end - - Hash[subset.map { |k, v| [k.to_s, options ? v.as_json(options.dup) : v.as_json] }] - end -end - -class Time - def as_json(options = nil) #:nodoc: - if ActiveSupport::JSON::Encoding.use_standard_json_time_format - xmlschema(ActiveSupport::JSON::Encoding.time_precision) - else - %(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) - end - end -end - -class Date - def as_json(options = nil) #:nodoc: - if ActiveSupport::JSON::Encoding.use_standard_json_time_format - strftime("%Y-%m-%d") - else - strftime("%Y/%m/%d") - end - end -end - -class DateTime - def as_json(options = nil) #:nodoc: - if ActiveSupport::JSON::Encoding.use_standard_json_time_format - xmlschema(ActiveSupport::JSON::Encoding.time_precision) - else - strftime("%Y/%m/%d %H:%M:%S %z") - end - end -end - -class URI::Generic #:nodoc: - def as_json(options = nil) - to_s - end -end - -class Pathname #:nodoc: - def as_json(options = nil) - to_s - end -end - -class Process::Status #:nodoc: - def as_json(options = nil) - { exitstatus: exitstatus, pid: pid } - end -end - -class Exception - def as_json(options = nil) - to_s - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/to_param.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/to_param.rb deleted file mode 100644 index 5eeaf03163..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/to_param.rb +++ /dev/null @@ -1 +0,0 @@ -require "active_support/core_ext/object/to_query" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/to_query.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/to_query.rb deleted file mode 100644 index c35c092810..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/to_query.rb +++ /dev/null @@ -1,87 +0,0 @@ -require "cgi" - -class Object - # Alias of to_s. - def to_param - to_s - end - - # Converts an object into a string suitable for use as a URL query string, - # using the given key as the param name. - def to_query(key) - "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}" - end -end - -class NilClass - # Returns +self+. - def to_param - self - end -end - -class TrueClass - # Returns +self+. - def to_param - self - end -end - -class FalseClass - # Returns +self+. - def to_param - self - end -end - -class Array - # Calls to_param on all its elements and joins the result with - # slashes. This is used by url_for in Action Pack. - def to_param - collect(&:to_param).join "/" - end - - # Converts an array into a string suitable for use as a URL query string, - # using the given +key+ as the param name. - # - # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" - def to_query(key) - prefix = "#{key}[]" - - if empty? - nil.to_query(prefix) - else - collect { |value| value.to_query(prefix) }.join "&" - end - end -end - -class Hash - # Returns a string representation of the receiver suitable for use as a URL - # query string: - # - # {name: 'David', nationality: 'Danish'}.to_query - # # => "name=David&nationality=Danish" - # - # An optional namespace can be passed to enclose key names: - # - # {name: 'David', nationality: 'Danish'}.to_query('user') - # # => "user%5Bname%5D=David&user%5Bnationality%5D=Danish" - # - # The string pairs "key=value" that conform the query string - # are sorted lexicographically in ascending order. - # - # This method is also aliased as +to_param+. - def to_query(namespace = nil) - query = collect do |key, value| - unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty? - value.to_query(namespace ? "#{namespace}[#{key}]" : key) - end - end.compact - - query.sort! unless namespace.to_s.include?("[]") - query.join("&") - end - - alias_method :to_param, :to_query -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/try.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/try.rb deleted file mode 100644 index b2be619b2d..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/try.rb +++ /dev/null @@ -1,146 +0,0 @@ -require "delegate" - -module ActiveSupport - module Tryable #:nodoc: - def try(*a, &b) - try!(*a, &b) if a.empty? || respond_to?(a.first) - end - - def try!(*a, &b) - if a.empty? && block_given? - if b.arity == 0 - instance_eval(&b) - else - yield self - end - else - public_send(*a, &b) - end - end - end -end - -class Object - include ActiveSupport::Tryable - - ## - # :method: try - # - # :call-seq: - # try(*a, &b) - # - # Invokes the public method whose name goes as first argument just like - # +public_send+ does, except that if the receiver does not respond to it the - # call returns +nil+ rather than raising an exception. - # - # This method is defined to be able to write - # - # @person.try(:name) - # - # instead of - # - # @person.name if @person - # - # +try+ calls can be chained: - # - # @person.try(:spouse).try(:name) - # - # instead of - # - # @person.spouse.name if @person && @person.spouse - # - # +try+ will also return +nil+ if the receiver does not respond to the method: - # - # @person.try(:non_existing_method) # => nil - # - # instead of - # - # @person.non_existing_method if @person.respond_to?(:non_existing_method) # => nil - # - # +try+ returns +nil+ when called on +nil+ regardless of whether it responds - # to the method: - # - # nil.try(:to_i) # => nil, rather than 0 - # - # Arguments and blocks are forwarded to the method if invoked: - # - # @posts.try(:each_slice, 2) do |a, b| - # ... - # end - # - # The number of arguments in the signature must match. If the object responds - # to the method the call is attempted and +ArgumentError+ is still raised - # in case of argument mismatch. - # - # If +try+ is called without arguments it yields the receiver to a given - # block unless it is +nil+: - # - # @person.try do |p| - # ... - # end - # - # You can also call try with a block without accepting an argument, and the block - # will be instance_eval'ed instead: - # - # @person.try { upcase.truncate(50) } - # - # Please also note that +try+ is defined on +Object+. Therefore, it won't work - # with instances of classes that do not have +Object+ among their ancestors, - # like direct subclasses of +BasicObject+. - - ## - # :method: try! - # - # :call-seq: - # try!(*a, &b) - # - # Same as #try, but raises a +NoMethodError+ exception if the receiver is - # not +nil+ and does not implement the tried method. - # - # "a".try!(:upcase) # => "A" - # nil.try!(:upcase) # => nil - # 123.try!(:upcase) # => NoMethodError: undefined method `upcase' for 123:Integer -end - -class Delegator - include ActiveSupport::Tryable - - ## - # :method: try - # - # :call-seq: - # try(a*, &b) - # - # See Object#try - - ## - # :method: try! - # - # :call-seq: - # try!(a*, &b) - # - # See Object#try! -end - -class NilClass - # Calling +try+ on +nil+ always returns +nil+. - # It becomes especially helpful when navigating through associations that may return +nil+. - # - # nil.try(:name) # => nil - # - # Without +try+ - # @person && @person.children.any? && @person.children.first.name - # - # With +try+ - # @person.try(:children).try(:first).try(:name) - def try(*args) - nil - end - - # Calling +try!+ on +nil+ always returns +nil+. - # - # nil.try!(:name) # => nil - def try!(*args) - nil - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/with_options.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/with_options.rb deleted file mode 100644 index 3a44e08630..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/object/with_options.rb +++ /dev/null @@ -1,80 +0,0 @@ -require "active_support/option_merger" - -class Object - # An elegant way to factor duplication out of options passed to a series of - # method calls. Each method called in the block, with the block variable as - # the receiver, will have its options merged with the default +options+ hash - # provided. Each method called on the block variable must take an options - # hash as its final argument. - # - # Without with_options, this code contains duplication: - # - # class Account < ActiveRecord::Base - # has_many :customers, dependent: :destroy - # has_many :products, dependent: :destroy - # has_many :invoices, dependent: :destroy - # has_many :expenses, dependent: :destroy - # end - # - # Using with_options, we can remove the duplication: - # - # class Account < ActiveRecord::Base - # with_options dependent: :destroy do |assoc| - # assoc.has_many :customers - # assoc.has_many :products - # assoc.has_many :invoices - # assoc.has_many :expenses - # end - # end - # - # It can also be used with an explicit receiver: - # - # I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n| - # subject i18n.t :subject - # body i18n.t :body, user_name: user.name - # end - # - # When you don't pass an explicit receiver, it executes the whole block - # in merging options context: - # - # class Account < ActiveRecord::Base - # with_options dependent: :destroy do - # has_many :customers - # has_many :products - # has_many :invoices - # has_many :expenses - # end - # end - # - # with_options can also be nested since the call is forwarded to its receiver. - # - # NOTE: Each nesting level will merge inherited defaults in addition to their own. - # - # class Post < ActiveRecord::Base - # with_options if: :persisted?, length: { minimum: 50 } do - # validates :content, if: -> { content.present? } - # end - # end - # - # The code is equivalent to: - # - # validates :content, length: { minimum: 50 }, if: -> { content.present? } - # - # Hence the inherited default for `if` key is ignored. - # - # NOTE: You cannot call class methods implicitly inside of with_options. - # You can access these methods using the class name instead: - # - # class Phone < ActiveRecord::Base - # enum phone_number_type: [home: 0, office: 1, mobile: 2] - # - # with_options presence: true do - # validates :phone_number_type, inclusion: { in: Phone.phone_number_types.keys } - # end - # end - # - def with_options(options, &block) - option_merger = ActiveSupport::OptionMerger.new(self, options) - block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range.rb deleted file mode 100644 index 3190e3ff76..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range.rb +++ /dev/null @@ -1,4 +0,0 @@ -require "active_support/core_ext/range/conversions" -require "active_support/core_ext/range/include_range" -require "active_support/core_ext/range/overlaps" -require "active_support/core_ext/range/each" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/conversions.rb deleted file mode 100644 index 69ea046cb6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/conversions.rb +++ /dev/null @@ -1,31 +0,0 @@ -module ActiveSupport::RangeWithFormat - RANGE_FORMATS = { - db: Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" } - } - - # Convert range to a formatted string. See RANGE_FORMATS for predefined formats. - # - # range = (1..100) # => 1..100 - # - # range.to_s # => "1..100" - # range.to_s(:db) # => "BETWEEN '1' AND '100'" - # - # == Adding your own range formats to to_s - # You can add your own formats to the Range::RANGE_FORMATS hash. - # Use the format name as the hash key and a Proc instance. - # - # # config/initializers/range_formats.rb - # Range::RANGE_FORMATS[:short] = ->(start, stop) { "Between #{start.to_s(:db)} and #{stop.to_s(:db)}" } - def to_s(format = :default) - if formatter = RANGE_FORMATS[format] - formatter.call(first, last) - else - super() - end - end - - alias_method :to_default_s, :to_s - alias_method :to_formatted_s, :to_s -end - -Range.prepend(ActiveSupport::RangeWithFormat) diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/each.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/each.rb deleted file mode 100644 index dc6dad5ced..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/each.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActiveSupport - module EachTimeWithZone #:nodoc: - def each(&block) - ensure_iteration_allowed - super - end - - def step(n = 1, &block) - ensure_iteration_allowed - super - end - - private - - def ensure_iteration_allowed - raise TypeError, "can't iterate from #{first.class}" if first.is_a?(Time) - end - end -end - -Range.prepend(ActiveSupport::EachTimeWithZone) diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/include_range.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/include_range.rb deleted file mode 100644 index c69e1e3fb9..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/include_range.rb +++ /dev/null @@ -1,23 +0,0 @@ -module ActiveSupport - module IncludeWithRange #:nodoc: - # Extends the default Range#include? to support range comparisons. - # (1..5).include?(1..5) # => true - # (1..5).include?(2..3) # => true - # (1..5).include?(2..6) # => false - # - # The native Range#include? behavior is untouched. - # ('a'..'f').include?('c') # => true - # (5..9).include?(11) # => false - def include?(value) - if value.is_a?(::Range) - # 1...10 includes 1..9 but it does not include 1..10. - operator = exclude_end? && !value.exclude_end? ? :< : :<= - super(value.first) && value.last.send(operator, last) - else - super - end - end - end -end - -Range.prepend(ActiveSupport::IncludeWithRange) diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/overlaps.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/overlaps.rb deleted file mode 100644 index 603657c180..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/range/overlaps.rb +++ /dev/null @@ -1,8 +0,0 @@ -class Range - # Compare two ranges and see if they overlap each other - # (1..5).overlaps?(4..6) # => true - # (1..5).overlaps?(7..9) # => false - def overlaps?(other) - cover?(other.first) || other.cover?(first) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/regexp.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/regexp.rb deleted file mode 100644 index d77d01bf42..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/regexp.rb +++ /dev/null @@ -1,9 +0,0 @@ -class Regexp #:nodoc: - def multiline? - options & MULTILINE == MULTILINE - end - - def match?(string, pos = 0) - !!match(string, pos) - end unless //.respond_to?(:match?) -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/securerandom.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/securerandom.rb deleted file mode 100644 index a57685bea1..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/securerandom.rb +++ /dev/null @@ -1,23 +0,0 @@ -require "securerandom" - -module SecureRandom - BASE58_ALPHABET = ("0".."9").to_a + ("A".."Z").to_a + ("a".."z").to_a - ["0", "O", "I", "l"] - # SecureRandom.base58 generates a random base58 string. - # - # The argument _n_ specifies the length, of the random string to be generated. - # - # If _n_ is not specified or is +nil+, 16 is assumed. It may be larger in the future. - # - # The result may contain alphanumeric characters except 0, O, I and l - # - # p SecureRandom.base58 # => "4kUgL2pdQMSCQtjE" - # p SecureRandom.base58(24) # => "77TMHrHJFvFDwodq8w7Ev2m7" - # - def self.base58(n = 16) - SecureRandom.random_bytes(n).unpack("C*").map do |byte| - idx = byte % 64 - idx = SecureRandom.random_number(58) if idx >= 58 - BASE58_ALPHABET[idx] - end.join - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string.rb deleted file mode 100644 index 4cb3200875..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "active_support/core_ext/string/conversions" -require "active_support/core_ext/string/filters" -require "active_support/core_ext/string/multibyte" -require "active_support/core_ext/string/starts_ends_with" -require "active_support/core_ext/string/inflections" -require "active_support/core_ext/string/access" -require "active_support/core_ext/string/behavior" -require "active_support/core_ext/string/output_safety" -require "active_support/core_ext/string/exclude" -require "active_support/core_ext/string/strip" -require "active_support/core_ext/string/inquiry" -require "active_support/core_ext/string/indent" -require "active_support/core_ext/string/zones" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/access.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/access.rb deleted file mode 100644 index 6133826f37..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/access.rb +++ /dev/null @@ -1,104 +0,0 @@ -class String - # If you pass a single integer, returns a substring of one character at that - # position. The first character of the string is at position 0, the next at - # position 1, and so on. If a range is supplied, a substring containing - # characters at offsets given by the range is returned. In both cases, if an - # offset is negative, it is counted from the end of the string. Returns +nil+ - # if the initial offset falls outside the string. Returns an empty string if - # the beginning of the range is greater than the end of the string. - # - # str = "hello" - # str.at(0) # => "h" - # str.at(1..3) # => "ell" - # str.at(-2) # => "l" - # str.at(-2..-1) # => "lo" - # str.at(5) # => nil - # str.at(5..-1) # => "" - # - # If a Regexp is given, the matching portion of the string is returned. - # If a String is given, that given string is returned if it occurs in - # the string. In both cases, +nil+ is returned if there is no match. - # - # str = "hello" - # str.at(/lo/) # => "lo" - # str.at(/ol/) # => nil - # str.at("lo") # => "lo" - # str.at("ol") # => nil - def at(position) - self[position] - end - - # Returns a substring from the given position to the end of the string. - # If the position is negative, it is counted from the end of the string. - # - # str = "hello" - # str.from(0) # => "hello" - # str.from(3) # => "lo" - # str.from(-2) # => "lo" - # - # You can mix it with +to+ method and do fun things like: - # - # str = "hello" - # str.from(0).to(-1) # => "hello" - # str.from(1).to(-2) # => "ell" - def from(position) - self[position..-1] - end - - # Returns a substring from the beginning of the string to the given position. - # If the position is negative, it is counted from the end of the string. - # - # str = "hello" - # str.to(0) # => "h" - # str.to(3) # => "hell" - # str.to(-2) # => "hell" - # - # You can mix it with +from+ method and do fun things like: - # - # str = "hello" - # str.from(0).to(-1) # => "hello" - # str.from(1).to(-2) # => "ell" - def to(position) - self[0..position] - end - - # Returns the first character. If a limit is supplied, returns a substring - # from the beginning of the string until it reaches the limit value. If the - # given limit is greater than or equal to the string length, returns a copy of self. - # - # str = "hello" - # str.first # => "h" - # str.first(1) # => "h" - # str.first(2) # => "he" - # str.first(0) # => "" - # str.first(6) # => "hello" - def first(limit = 1) - if limit == 0 - "" - elsif limit >= size - dup - else - to(limit - 1) - end - end - - # Returns the last character of the string. If a limit is supplied, returns a substring - # from the end of the string until it reaches the limit value (counting backwards). If - # the given limit is greater than or equal to the string length, returns a copy of self. - # - # str = "hello" - # str.last # => "o" - # str.last(1) # => "o" - # str.last(2) # => "lo" - # str.last(0) # => "" - # str.last(6) # => "hello" - def last(limit = 1) - if limit == 0 - "" - elsif limit >= size - dup - else - from(-limit) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/behavior.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/behavior.rb deleted file mode 100644 index 710f1f4670..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/behavior.rb +++ /dev/null @@ -1,6 +0,0 @@ -class String - # Enables more predictable duck-typing on String-like classes. See Object#acts_like?. - def acts_like_string? - true - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/conversions.rb deleted file mode 100644 index 221b4969cc..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/conversions.rb +++ /dev/null @@ -1,57 +0,0 @@ -require "date" -require "active_support/core_ext/time/calculations" - -class String - # Converts a string to a Time value. - # The +form+ can be either :utc or :local (default :local). - # - # The time is parsed using Time.parse method. - # If +form+ is :local, then the time is in the system timezone. - # If the date part is missing then the current date is used and if - # the time part is missing then it is assumed to be 00:00:00. - # - # "13-12-2012".to_time # => 2012-12-13 00:00:00 +0100 - # "06:12".to_time # => 2012-12-13 06:12:00 +0100 - # "2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100 - # "2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100 - # "2012-12-13T06:12".to_time(:utc) # => 2012-12-13 06:12:00 UTC - # "12/13/2012".to_time # => ArgumentError: argument out of range - def to_time(form = :local) - parts = Date._parse(self, false) - used_keys = %i(year mon mday hour min sec sec_fraction offset) - return if (parts.keys & used_keys).empty? - - now = Time.now - time = Time.new( - parts.fetch(:year, now.year), - parts.fetch(:mon, now.month), - parts.fetch(:mday, now.day), - parts.fetch(:hour, 0), - parts.fetch(:min, 0), - parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0), - parts.fetch(:offset, form == :utc ? 0 : nil) - ) - - form == :utc ? time.utc : time.to_time - end - - # Converts a string to a Date value. - # - # "1-1-2012".to_date # => Sun, 01 Jan 2012 - # "01/01/2012".to_date # => Sun, 01 Jan 2012 - # "2012-12-13".to_date # => Thu, 13 Dec 2012 - # "12/13/2012".to_date # => ArgumentError: invalid date - def to_date - ::Date.parse(self, false) unless blank? - end - - # Converts a string to a DateTime value. - # - # "1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000 - # "01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000 - # "2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000 - # "12/13/2012".to_datetime # => ArgumentError: invalid date - def to_datetime - ::DateTime.parse(self, false) unless blank? - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/exclude.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/exclude.rb deleted file mode 100644 index 0ac684f6ee..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/exclude.rb +++ /dev/null @@ -1,11 +0,0 @@ -class String - # The inverse of String#include?. Returns true if the string - # does not include the other string. - # - # "hello".exclude? "lo" # => false - # "hello".exclude? "ol" # => true - # "hello".exclude? ?h # => false - def exclude?(string) - !include?(string) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/filters.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/filters.rb deleted file mode 100644 index a9ec2eb842..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/filters.rb +++ /dev/null @@ -1,102 +0,0 @@ -class String - # Returns the string, first removing all whitespace on both ends of - # the string, and then changing remaining consecutive whitespace - # groups into one space each. - # - # Note that it handles both ASCII and Unicode whitespace. - # - # %{ Multi-line - # string }.squish # => "Multi-line string" - # " foo bar \n \t boo".squish # => "foo bar boo" - def squish - dup.squish! - end - - # Performs a destructive squish. See String#squish. - # str = " foo bar \n \t boo" - # str.squish! # => "foo bar boo" - # str # => "foo bar boo" - def squish! - gsub!(/[[:space:]]+/, " ") - strip! - self - end - - # Returns a new string with all occurrences of the patterns removed. - # str = "foo bar test" - # str.remove(" test") # => "foo bar" - # str.remove(" test", /bar/) # => "foo " - # str # => "foo bar test" - def remove(*patterns) - dup.remove!(*patterns) - end - - # Alters the string by removing all occurrences of the patterns. - # str = "foo bar test" - # str.remove!(" test", /bar/) # => "foo " - # str # => "foo " - def remove!(*patterns) - patterns.each do |pattern| - gsub! pattern, "" - end - - self - end - - # Truncates a given +text+ after a given length if +text+ is longer than length: - # - # 'Once upon a time in a world far far away'.truncate(27) - # # => "Once upon a time in a wo..." - # - # Pass a string or regexp :separator to truncate +text+ at a natural break: - # - # 'Once upon a time in a world far far away'.truncate(27, separator: ' ') - # # => "Once upon a time in a..." - # - # 'Once upon a time in a world far far away'.truncate(27, separator: /\s/) - # # => "Once upon a time in a..." - # - # The last characters will be replaced with the :omission string (defaults to "...") - # for a total length not exceeding length: - # - # 'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)') - # # => "And they f... (continued)" - def truncate(truncate_at, options = {}) - return dup unless length > truncate_at - - omission = options[:omission] || "..." - length_with_room_for_omission = truncate_at - omission.length - stop = \ - if options[:separator] - rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission - else - length_with_room_for_omission - end - - "#{self[0, stop]}#{omission}" - end - - # Truncates a given +text+ after a given number of words (words_count): - # - # 'Once upon a time in a world far far away'.truncate_words(4) - # # => "Once upon a time..." - # - # Pass a string or regexp :separator to specify a different separator of words: - # - # 'Once
    upon
    a
    time
    in
    a
    world'.truncate_words(5, separator: '
    ') - # # => "Once
    upon
    a
    time
    in..." - # - # The last characters will be replaced with the :omission string (defaults to "..."): - # - # 'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)') - # # => "And they found that many... (continued)" - def truncate_words(words_count, options = {}) - sep = options[:separator] || /\s+/ - sep = Regexp.escape(sep.to_s) unless Regexp === sep - if self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m - $1 + (options[:omission] || "...") - else - dup - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/indent.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/indent.rb deleted file mode 100644 index d7b58301d3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/indent.rb +++ /dev/null @@ -1,43 +0,0 @@ -class String - # Same as +indent+, except it indents the receiver in-place. - # - # Returns the indented string, or +nil+ if there was nothing to indent. - def indent!(amount, indent_string = nil, indent_empty_lines = false) - indent_string = indent_string || self[/^[ \t]/] || " " - re = indent_empty_lines ? /^/ : /^(?!$)/ - gsub!(re, indent_string * amount) - end - - # Indents the lines in the receiver: - # - # < - # def some_method - # some_code - # end - # - # The second argument, +indent_string+, specifies which indent string to - # use. The default is +nil+, which tells the method to make a guess by - # peeking at the first indented line, and fallback to a space if there is - # none. - # - # " foo".indent(2) # => " foo" - # "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar" - # "foo".indent(2, "\t") # => "\t\tfoo" - # - # While +indent_string+ is typically one space or tab, it may be any string. - # - # The third argument, +indent_empty_lines+, is a flag that says whether - # empty lines should be indented. Default is false. - # - # "foo\n\nbar".indent(2) # => " foo\n\n bar" - # "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar" - # - def indent(amount, indent_string = nil, indent_empty_lines = false) - dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) } - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/inflections.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/inflections.rb deleted file mode 100644 index 7a2fc5c1b5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/inflections.rb +++ /dev/null @@ -1,240 +0,0 @@ -require "active_support/inflector/methods" -require "active_support/inflector/transliterate" - -# String inflections define new methods on the String class to transform names for different purposes. -# For instance, you can figure out the name of a table from the name of a class. -# -# 'ScaleScore'.tableize # => "scale_scores" -# -class String - # Returns the plural form of the word in the string. - # - # If the optional parameter +count+ is specified, - # the singular form will be returned if count == 1. - # For any other value of +count+ the plural will be returned. - # - # If the optional parameter +locale+ is specified, - # the word will be pluralized as a word of that language. - # By default, this parameter is set to :en. - # You must define your own inflection rules for languages other than English. - # - # 'post'.pluralize # => "posts" - # 'octopus'.pluralize # => "octopi" - # 'sheep'.pluralize # => "sheep" - # 'words'.pluralize # => "words" - # 'the blue mailman'.pluralize # => "the blue mailmen" - # 'CamelOctopus'.pluralize # => "CamelOctopi" - # 'apple'.pluralize(1) # => "apple" - # 'apple'.pluralize(2) # => "apples" - # 'ley'.pluralize(:es) # => "leyes" - # 'ley'.pluralize(1, :es) # => "ley" - def pluralize(count = nil, locale = :en) - locale = count if count.is_a?(Symbol) - if count == 1 - dup - else - ActiveSupport::Inflector.pluralize(self, locale) - end - end - - # The reverse of +pluralize+, returns the singular form of a word in a string. - # - # If the optional parameter +locale+ is specified, - # the word will be singularized as a word of that language. - # By default, this parameter is set to :en. - # You must define your own inflection rules for languages other than English. - # - # 'posts'.singularize # => "post" - # 'octopi'.singularize # => "octopus" - # 'sheep'.singularize # => "sheep" - # 'word'.singularize # => "word" - # 'the blue mailmen'.singularize # => "the blue mailman" - # 'CamelOctopi'.singularize # => "CamelOctopus" - # 'leyes'.singularize(:es) # => "ley" - def singularize(locale = :en) - ActiveSupport::Inflector.singularize(self, locale) - end - - # +constantize+ tries to find a declared constant with the name specified - # in the string. It raises a NameError when the name is not in CamelCase - # or is not initialized. See ActiveSupport::Inflector.constantize - # - # 'Module'.constantize # => Module - # 'Class'.constantize # => Class - # 'blargle'.constantize # => NameError: wrong constant name blargle - def constantize - ActiveSupport::Inflector.constantize(self) - end - - # +safe_constantize+ tries to find a declared constant with the name specified - # in the string. It returns +nil+ when the name is not in CamelCase - # or is not initialized. See ActiveSupport::Inflector.safe_constantize - # - # 'Module'.safe_constantize # => Module - # 'Class'.safe_constantize # => Class - # 'blargle'.safe_constantize # => nil - def safe_constantize - ActiveSupport::Inflector.safe_constantize(self) - end - - # By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize - # is set to :lower then camelize produces lowerCamelCase. - # - # +camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces. - # - # 'active_record'.camelize # => "ActiveRecord" - # 'active_record'.camelize(:lower) # => "activeRecord" - # 'active_record/errors'.camelize # => "ActiveRecord::Errors" - # 'active_record/errors'.camelize(:lower) # => "activeRecord::Errors" - def camelize(first_letter = :upper) - case first_letter - when :upper - ActiveSupport::Inflector.camelize(self, true) - when :lower - ActiveSupport::Inflector.camelize(self, false) - end - end - alias_method :camelcase, :camelize - - # Capitalizes all the words and replaces some characters in the string to create - # a nicer looking title. +titleize+ is meant for creating pretty output. It is not - # used in the Rails internals. - # - # +titleize+ is also aliased as +titlecase+. - # - # 'man from the boondocks'.titleize # => "Man From The Boondocks" - # 'x-men: the last stand'.titleize # => "X Men: The Last Stand" - def titleize - ActiveSupport::Inflector.titleize(self) - end - alias_method :titlecase, :titleize - - # The reverse of +camelize+. Makes an underscored, lowercase form from the expression in the string. - # - # +underscore+ will also change '::' to '/' to convert namespaces to paths. - # - # 'ActiveModel'.underscore # => "active_model" - # 'ActiveModel::Errors'.underscore # => "active_model/errors" - def underscore - ActiveSupport::Inflector.underscore(self) - end - - # Replaces underscores with dashes in the string. - # - # 'puni_puni'.dasherize # => "puni-puni" - def dasherize - ActiveSupport::Inflector.dasherize(self) - end - - # Removes the module part from the constant expression in the string. - # - # 'ActiveSupport::Inflector::Inflections'.demodulize # => "Inflections" - # 'Inflections'.demodulize # => "Inflections" - # '::Inflections'.demodulize # => "Inflections" - # ''.demodulize # => '' - # - # See also +deconstantize+. - def demodulize - ActiveSupport::Inflector.demodulize(self) - end - - # Removes the rightmost segment from the constant expression in the string. - # - # 'Net::HTTP'.deconstantize # => "Net" - # '::Net::HTTP'.deconstantize # => "::Net" - # 'String'.deconstantize # => "" - # '::String'.deconstantize # => "" - # ''.deconstantize # => "" - # - # See also +demodulize+. - def deconstantize - ActiveSupport::Inflector.deconstantize(self) - end - - # Replaces special characters in a string so that it may be used as part of a 'pretty' URL. - # - # class Person - # def to_param - # "#{id}-#{name.parameterize}" - # end - # end - # - # @person = Person.find(1) - # # => # - # - # <%= link_to(@person.name, person_path) %> - # # => Donald E. Knuth - # - # To preserve the case of the characters in a string, use the `preserve_case` argument. - # - # class Person - # def to_param - # "#{id}-#{name.parameterize(preserve_case: true)}" - # end - # end - # - # @person = Person.find(1) - # # => # - # - # <%= link_to(@person.name, person_path) %> - # # => Donald E. Knuth - def parameterize(separator: "-", preserve_case: false) - ActiveSupport::Inflector.parameterize(self, separator: separator, preserve_case: preserve_case) - end - - # Creates the name of a table like Rails does for models to table names. This method - # uses the +pluralize+ method on the last word in the string. - # - # 'RawScaledScorer'.tableize # => "raw_scaled_scorers" - # 'ham_and_egg'.tableize # => "ham_and_eggs" - # 'fancyCategory'.tableize # => "fancy_categories" - def tableize - ActiveSupport::Inflector.tableize(self) - end - - # Creates a class name from a plural table name like Rails does for table names to models. - # Note that this returns a string and not a class. (To convert to an actual class - # follow +classify+ with +constantize+.) - # - # 'ham_and_eggs'.classify # => "HamAndEgg" - # 'posts'.classify # => "Post" - def classify - ActiveSupport::Inflector.classify(self) - end - - # Capitalizes the first word, turns underscores into spaces, and strips a - # trailing '_id' if present. - # Like +titleize+, this is meant for creating pretty output. - # - # The capitalization of the first word can be turned off by setting the - # optional parameter +capitalize+ to false. - # By default, this parameter is true. - # - # 'employee_salary'.humanize # => "Employee salary" - # 'author_id'.humanize # => "Author" - # 'author_id'.humanize(capitalize: false) # => "author" - # '_id'.humanize # => "Id" - def humanize(options = {}) - ActiveSupport::Inflector.humanize(self, options) - end - - # Converts just the first character to uppercase. - # - # 'what a Lovely Day'.upcase_first # => "What a Lovely Day" - # 'w'.upcase_first # => "W" - # ''.upcase_first # => "" - def upcase_first - ActiveSupport::Inflector.upcase_first(self) - end - - # Creates a foreign key name from a class name. - # +separate_class_name_and_id_with_underscore+ sets whether - # the method should put '_' between the name and 'id'. - # - # 'Message'.foreign_key # => "message_id" - # 'Message'.foreign_key(false) # => "messageid" - # 'Admin::Post'.foreign_key # => "post_id" - def foreign_key(separate_class_name_and_id_with_underscore = true) - ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/inquiry.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/inquiry.rb deleted file mode 100644 index c95d83beae..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/inquiry.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "active_support/string_inquirer" - -class String - # Wraps the current string in the ActiveSupport::StringInquirer class, - # which gives you a prettier way to test for equality. - # - # env = 'production'.inquiry - # env.production? # => true - # env.development? # => false - def inquiry - ActiveSupport::StringInquirer.new(self) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/multibyte.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/multibyte.rb deleted file mode 100644 index 1c73182259..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/multibyte.rb +++ /dev/null @@ -1,53 +0,0 @@ -require "active_support/multibyte" - -class String - # == Multibyte proxy - # - # +mb_chars+ is a multibyte safe proxy for string methods. - # - # It creates and returns an instance of the ActiveSupport::Multibyte::Chars class which - # encapsulates the original string. A Unicode safe version of all the String methods are defined on this proxy - # class. If the proxy class doesn't respond to a certain method, it's forwarded to the encapsulated string. - # - # >> "lj".upcase - # => "lj" - # >> "lj".mb_chars.upcase.to_s - # => "LJ" - # - # == Method chaining - # - # All the methods on the Chars proxy which normally return a string will return a Chars object. This allows - # method chaining on the result of any of these methods. - # - # name.mb_chars.reverse.length # => 12 - # - # == Interoperability and configuration - # - # The Chars object tries to be as interchangeable with String objects as possible: sorting and comparing between - # String and Char work like expected. The bang! methods change the internal string representation in the Chars - # object. Interoperability problems can be resolved easily with a +to_s+ call. - # - # For more information about the methods defined on the Chars proxy see ActiveSupport::Multibyte::Chars. For - # information about how to change the default Multibyte behavior see ActiveSupport::Multibyte. - def mb_chars - ActiveSupport::Multibyte.proxy_class.new(self) - end - - # Returns +true+ if string has utf_8 encoding. - # - # utf_8_str = "some string".encode "UTF-8" - # iso_str = "some string".encode "ISO-8859-1" - # - # utf_8_str.is_utf8? # => true - # iso_str.is_utf8? # => false - def is_utf8? - case encoding - when Encoding::UTF_8 - valid_encoding? - when Encoding::ASCII_8BIT, Encoding::US_ASCII - dup.force_encoding(Encoding::UTF_8).valid_encoding? - else - false - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/output_safety.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/output_safety.rb deleted file mode 100644 index 94ce3f6a61..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/output_safety.rb +++ /dev/null @@ -1,259 +0,0 @@ -require "erb" -require "active_support/core_ext/kernel/singleton_class" -require "active_support/multibyte/unicode" - -class ERB - module Util - HTML_ESCAPE = { "&" => "&", ">" => ">", "<" => "<", '"' => """, "'" => "'" } - JSON_ESCAPE = { "&" => '\u0026', ">" => '\u003e', "<" => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' } - HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+)|(#[xX][\dA-Fa-f]+));)/ - JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u - - # A utility method for escaping HTML tag characters. - # This method is also aliased as h. - # - # In your ERB templates, use this method to escape any unsafe content. For example: - # <%= h @person.name %> - # - # puts html_escape('is a > 0 & a < 10?') - # # => is a > 0 & a < 10? - def html_escape(s) - unwrapped_html_escape(s).html_safe - end - - # Aliasing twice issues a warning "discarding old...". Remove first to avoid it. - remove_method(:h) - alias h html_escape - - module_function :h - - singleton_class.send(:remove_method, :html_escape) - module_function :html_escape - - # HTML escapes strings but doesn't wrap them with an ActiveSupport::SafeBuffer. - # This method is not for public consumption! Seriously! - def unwrapped_html_escape(s) # :nodoc: - s = s.to_s - if s.html_safe? - s - else - CGI.escapeHTML(ActiveSupport::Multibyte::Unicode.tidy_bytes(s)) - end - end - module_function :unwrapped_html_escape - - # A utility method for escaping HTML without affecting existing escaped entities. - # - # html_escape_once('1 < 2 & 3') - # # => "1 < 2 & 3" - # - # html_escape_once('<< Accept & Checkout') - # # => "<< Accept & Checkout" - def html_escape_once(s) - result = ActiveSupport::Multibyte::Unicode.tidy_bytes(s.to_s).gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE) - s.html_safe? ? result.html_safe : result - end - - module_function :html_escape_once - - # A utility method for escaping HTML entities in JSON strings. Specifically, the - # &, > and < characters are replaced with their equivalent unicode escaped form - - # \u0026, \u003e, and \u003c. The Unicode sequences \u2028 and \u2029 are also - # escaped as they are treated as newline characters in some JavaScript engines. - # These sequences have identical meaning as the original characters inside the - # context of a JSON string, so assuming the input is a valid and well-formed - # JSON value, the output will have equivalent meaning when parsed: - # - # json = JSON.generate({ name: ""}) - # # => "{\"name\":\"\"}" - # - # json_escape(json) - # # => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}" - # - # JSON.parse(json) == JSON.parse(json_escape(json)) - # # => true - # - # The intended use case for this method is to escape JSON strings before including - # them inside a script tag to avoid XSS vulnerability: - # - # - # - # It is necessary to +raw+ the result of +json_escape+, so that quotation marks - # don't get converted to " entities. +json_escape+ doesn't - # automatically flag the result as HTML safe, since the raw value is unsafe to - # use inside HTML attributes. - # - # If your JSON is being used downstream for insertion into the DOM, be aware of - # whether or not it is being inserted via +html()+. Most jQuery plugins do this. - # If that is the case, be sure to +html_escape+ or +sanitize+ any user-generated - # content returned by your JSON. - # - # If you need to output JSON elsewhere in your HTML, you can just do something - # like this, as any unsafe characters (including quotation marks) will be - # automatically escaped for you: - # - #
    ...
    - # - # WARNING: this helper only works with valid JSON. Using this on non-JSON values - # will open up serious XSS vulnerabilities. For example, if you replace the - # +current_user.to_json+ in the example above with user input instead, the browser - # will happily eval() that string as JavaScript. - # - # The escaping performed in this method is identical to those performed in the - # Active Support JSON encoder when +ActiveSupport.escape_html_entities_in_json+ is - # set to true. Because this transformation is idempotent, this helper can be - # applied even if +ActiveSupport.escape_html_entities_in_json+ is already true. - # - # Therefore, when you are unsure if +ActiveSupport.escape_html_entities_in_json+ - # is enabled, or if you are unsure where your JSON string originated from, it - # is recommended that you always apply this helper (other libraries, such as the - # JSON gem, do not provide this kind of protection by default; also some gems - # might override +to_json+ to bypass Active Support's encoder). - def json_escape(s) - result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE) - s.html_safe? ? result.html_safe : result - end - - module_function :json_escape - end -end - -class Object - def html_safe? - false - end -end - -class Numeric - def html_safe? - true - end -end - -module ActiveSupport #:nodoc: - class SafeBuffer < String - UNSAFE_STRING_METHODS = %w( - capitalize chomp chop delete downcase gsub lstrip next reverse rstrip - slice squeeze strip sub succ swapcase tr tr_s upcase - ) - - alias_method :original_concat, :concat - private :original_concat - - # Raised when ActiveSupport::SafeBuffer#safe_concat is called on unsafe buffers. - class SafeConcatError < StandardError - def initialize - super "Could not concatenate to the buffer because it is not html safe." - end - end - - def [](*args) - if args.size < 2 - super - elsif html_safe? - new_safe_buffer = super - - if new_safe_buffer - new_safe_buffer.instance_variable_set :@html_safe, true - end - - new_safe_buffer - else - to_str[*args] - end - end - - def safe_concat(value) - raise SafeConcatError unless html_safe? - original_concat(value) - end - - def initialize(str = "") - @html_safe = true - super - end - - def initialize_copy(other) - super - @html_safe = other.html_safe? - end - - def clone_empty - self[0, 0] - end - - def concat(value) - super(html_escape_interpolated_argument(value)) - end - alias << concat - - def prepend(value) - super(html_escape_interpolated_argument(value)) - end - - def +(other) - dup.concat(other) - end - - def %(args) - case args - when Hash - escaped_args = Hash[args.map { |k, arg| [k, html_escape_interpolated_argument(arg)] }] - else - escaped_args = Array(args).map { |arg| html_escape_interpolated_argument(arg) } - end - - self.class.new(super(escaped_args)) - end - - def html_safe? - defined?(@html_safe) && @html_safe - end - - def to_s - self - end - - def to_param - to_str - end - - def encode_with(coder) - coder.represent_object nil, to_str - end - - UNSAFE_STRING_METHODS.each do |unsafe_method| - if unsafe_method.respond_to?(unsafe_method) - class_eval <<-EOT, __FILE__, __LINE__ + 1 - def #{unsafe_method}(*args, &block) # def capitalize(*args, &block) - to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block) - end # end - - def #{unsafe_method}!(*args) # def capitalize!(*args) - @html_safe = false # @html_safe = false - super # super - end # end - EOT - end - end - - private - - def html_escape_interpolated_argument(arg) - (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s) - end - end -end - -class String - # Marks a string as trusted safe. It will be inserted into HTML with no - # additional escaping performed. It is your responsibility to ensure that the - # string contains no malicious content. This method is equivalent to the - # `raw` helper in views. It is recommended that you use `sanitize` instead of - # this method. It should never be called on user input. - def html_safe - ActiveSupport::SafeBuffer.new(self) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/starts_ends_with.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/starts_ends_with.rb deleted file mode 100644 index 641acf62d0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/starts_ends_with.rb +++ /dev/null @@ -1,4 +0,0 @@ -class String - alias_method :starts_with?, :start_with? - alias_method :ends_with?, :end_with? -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/strip.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/strip.rb deleted file mode 100644 index bb62e6c0ba..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/strip.rb +++ /dev/null @@ -1,23 +0,0 @@ -class String - # Strips indentation in heredocs. - # - # For example in - # - # if options[:usage] - # puts <<-USAGE.strip_heredoc - # This command does such and such. - # - # Supported options are: - # -h This message - # ... - # USAGE - # end - # - # the user would see the usage message aligned against the left margin. - # - # Technically, it looks for the least indented non-empty line - # in the whole string, and removes that amount of leading whitespace. - def strip_heredoc - gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "".freeze) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/zones.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/zones.rb deleted file mode 100644 index de5a28e4f7..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/string/zones.rb +++ /dev/null @@ -1,14 +0,0 @@ -require "active_support/core_ext/string/conversions" -require "active_support/core_ext/time/zones" - -class String - # Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default - # is set, otherwise converts String to a Time via String#to_time - def in_time_zone(zone = ::Time.zone) - if zone - ::Time.find_zone!(zone).parse(self) - else - to_time - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time.rb deleted file mode 100644 index b1ae4a45d9..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "active_support/core_ext/time/acts_like" -require "active_support/core_ext/time/calculations" -require "active_support/core_ext/time/compatibility" -require "active_support/core_ext/time/conversions" -require "active_support/core_ext/time/zones" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/acts_like.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/acts_like.rb deleted file mode 100644 index cf4b2539c5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/acts_like.rb +++ /dev/null @@ -1,8 +0,0 @@ -require "active_support/core_ext/object/acts_like" - -class Time - # Duck-types as a Time-like class. See Object#acts_like?. - def acts_like_time? - true - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/calculations.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/calculations.rb deleted file mode 100644 index 7b7aeef25a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/calculations.rb +++ /dev/null @@ -1,307 +0,0 @@ -require "active_support/duration" -require "active_support/core_ext/time/conversions" -require "active_support/time_with_zone" -require "active_support/core_ext/time/zones" -require "active_support/core_ext/date_and_time/calculations" -require "active_support/core_ext/date/calculations" - -class Time - include DateAndTime::Calculations - - COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - - class << self - # Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances - def ===(other) - super || (self == Time && other.is_a?(ActiveSupport::TimeWithZone)) - end - - # Returns the number of days in the given month. - # If no year is specified, it will use the current year. - def days_in_month(month, year = current.year) - if month == 2 && ::Date.gregorian_leap?(year) - 29 - else - COMMON_YEAR_DAYS_IN_MONTH[month] - end - end - - # Returns the number of days in the given year. - # If no year is specified, it will use the current year. - def days_in_year(year = current.year) - days_in_month(2, year) + 337 - end - - # Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise just returns Time.now. - def current - ::Time.zone ? ::Time.zone.now : ::Time.now - end - - # Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime - # instances can be used when called with a single argument - def at_with_coercion(*args) - return at_without_coercion(*args) if args.size != 1 - - # Time.at can be called with a time or numerical value - time_or_number = args.first - - if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime) - at_without_coercion(time_or_number.to_f).getlocal - else - at_without_coercion(time_or_number) - end - end - alias_method :at_without_coercion, :at - alias_method :at, :at_with_coercion - - # Creates a +Time+ instance from an RFC 3339 string. - # - # Time.rfc3339('1999-12-31T14:00:00-10:00') # => 2000-01-01 00:00:00 -1000 - # - # If the time or offset components are missing then an +ArgumentError+ will be raised. - # - # Time.rfc3339('1999-12-31') # => ArgumentError: invalid date - def rfc3339(str) - parts = Date._rfc3339(str) - - raise ArgumentError, "invalid date" if parts.empty? - - Time.new( - parts.fetch(:year), - parts.fetch(:mon), - parts.fetch(:mday), - parts.fetch(:hour), - parts.fetch(:min), - parts.fetch(:sec) + parts.fetch(:sec_fraction, 0), - parts.fetch(:offset) - ) - end - end - - # Returns the number of seconds since 00:00:00. - # - # Time.new(2012, 8, 29, 0, 0, 0).seconds_since_midnight # => 0.0 - # Time.new(2012, 8, 29, 12, 34, 56).seconds_since_midnight # => 45296.0 - # Time.new(2012, 8, 29, 23, 59, 59).seconds_since_midnight # => 86399.0 - def seconds_since_midnight - to_i - change(hour: 0).to_i + (usec / 1.0e+6) - end - - # Returns the number of seconds until 23:59:59. - # - # Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399 - # Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103 - # Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0 - def seconds_until_end_of_day - end_of_day.to_i - to_i - end - - # Returns the fraction of a second as a +Rational+ - # - # Time.new(2012, 8, 29, 0, 0, 0.5).sec_fraction # => (1/2) - def sec_fraction - subsec - end - - # Returns a new Time where one or more of the elements have been changed according - # to the +options+ parameter. The time options (:hour, :min, - # :sec, :usec, :nsec) reset cascadingly, so if only - # the hour is passed, then minute, sec, usec and nsec is set to 0. If the hour - # and minute is passed, then sec, usec and nsec is set to 0. The +options+ - # parameter takes a hash with any of these keys: :year, :month, - # :day, :hour, :min, :sec, :usec - # :nsec. Pass either :usec or :nsec, not both. - # - # Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0) - # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0) - # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0) - def change(options) - new_year = options.fetch(:year, year) - new_month = options.fetch(:month, month) - new_day = options.fetch(:day, day) - new_hour = options.fetch(:hour, hour) - new_min = options.fetch(:min, options[:hour] ? 0 : min) - new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) - - if new_nsec = options[:nsec] - raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec] - new_usec = Rational(new_nsec, 1000) - else - new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000)) - end - - if utc? - ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec) - elsif zone - ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec) - else - raise ArgumentError, "argument out of range" if new_usec >= 1000000 - ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset) - end - end - - # Uses Date to provide precise Time calculations for years, months, and days - # according to the proleptic Gregorian calendar. The +options+ parameter - # takes a hash with any of these keys: :years, :months, - # :weeks, :days, :hours, :minutes, - # :seconds. - # - # Time.new(2015, 8, 1, 14, 35, 0).advance(seconds: 1) # => 2015-08-01 14:35:01 -0700 - # Time.new(2015, 8, 1, 14, 35, 0).advance(minutes: 1) # => 2015-08-01 14:36:00 -0700 - # Time.new(2015, 8, 1, 14, 35, 0).advance(hours: 1) # => 2015-08-01 15:35:00 -0700 - # Time.new(2015, 8, 1, 14, 35, 0).advance(days: 1) # => 2015-08-02 14:35:00 -0700 - # Time.new(2015, 8, 1, 14, 35, 0).advance(weeks: 1) # => 2015-08-08 14:35:00 -0700 - def advance(options) - unless options[:weeks].nil? - options[:weeks], partial_weeks = options[:weeks].divmod(1) - options[:days] = options.fetch(:days, 0) + 7 * partial_weeks - end - - unless options[:days].nil? - options[:days], partial_days = options[:days].divmod(1) - options[:hours] = options.fetch(:hours, 0) + 24 * partial_days - end - - d = to_date.advance(options) - d = d.gregorian if d.julian? - time_advanced_by_date = change(year: d.year, month: d.month, day: d.day) - seconds_to_advance = \ - options.fetch(:seconds, 0) + - options.fetch(:minutes, 0) * 60 + - options.fetch(:hours, 0) * 3600 - - if seconds_to_advance.zero? - time_advanced_by_date - else - time_advanced_by_date.since(seconds_to_advance) - end - end - - # Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension - def ago(seconds) - since(-seconds) - end - - # Returns a new Time representing the time a number of seconds since the instance time - def since(seconds) - self + seconds - rescue - to_datetime.since(seconds) - end - alias :in :since - - # Returns a new Time representing the start of the day (0:00) - def beginning_of_day - change(hour: 0) - end - alias :midnight :beginning_of_day - alias :at_midnight :beginning_of_day - alias :at_beginning_of_day :beginning_of_day - - # Returns a new Time representing the middle of the day (12:00) - def middle_of_day - change(hour: 12) - end - alias :midday :middle_of_day - alias :noon :middle_of_day - alias :at_midday :middle_of_day - alias :at_noon :middle_of_day - alias :at_middle_of_day :middle_of_day - - # Returns a new Time representing the end of the day, 23:59:59.999999 - def end_of_day - change( - hour: 23, - min: 59, - sec: 59, - usec: Rational(999999999, 1000) - ) - end - alias :at_end_of_day :end_of_day - - # Returns a new Time representing the start of the hour (x:00) - def beginning_of_hour - change(min: 0) - end - alias :at_beginning_of_hour :beginning_of_hour - - # Returns a new Time representing the end of the hour, x:59:59.999999 - def end_of_hour - change( - min: 59, - sec: 59, - usec: Rational(999999999, 1000) - ) - end - alias :at_end_of_hour :end_of_hour - - # Returns a new Time representing the start of the minute (x:xx:00) - def beginning_of_minute - change(sec: 0) - end - alias :at_beginning_of_minute :beginning_of_minute - - # Returns a new Time representing the end of the minute, x:xx:59.999999 - def end_of_minute - change( - sec: 59, - usec: Rational(999999999, 1000) - ) - end - alias :at_end_of_minute :end_of_minute - - def plus_with_duration(other) #:nodoc: - if ActiveSupport::Duration === other - other.since(self) - else - plus_without_duration(other) - end - end - alias_method :plus_without_duration, :+ - alias_method :+, :plus_with_duration - - def minus_with_duration(other) #:nodoc: - if ActiveSupport::Duration === other - other.until(self) - else - minus_without_duration(other) - end - end - alias_method :minus_without_duration, :- - alias_method :-, :minus_with_duration - - # Time#- can also be used to determine the number of seconds between two Time instances. - # We're layering on additional behavior so that ActiveSupport::TimeWithZone instances - # are coerced into values that Time#- will recognize - def minus_with_coercion(other) - other = other.comparable_time if other.respond_to?(:comparable_time) - other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other) - end - alias_method :minus_without_coercion, :- - alias_method :-, :minus_with_coercion - - # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances - # can be chronologically compared with a Time - def compare_with_coercion(other) - # we're avoiding Time#to_datetime and Time#to_time because they're expensive - if other.class == Time - compare_without_coercion(other) - elsif other.is_a?(Time) - compare_without_coercion(other.to_time) - else - to_datetime <=> other - end - end - alias_method :compare_without_coercion, :<=> - alias_method :<=>, :compare_with_coercion - - # Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances - # can be eql? to an equivalent Time - def eql_with_coercion(other) - # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison - other = other.comparable_time if other.respond_to?(:comparable_time) - eql_without_coercion(other) - end - alias_method :eql_without_coercion, :eql? - alias_method :eql?, :eql_with_coercion -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/compatibility.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/compatibility.rb deleted file mode 100644 index 45e86b77ce..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/compatibility.rb +++ /dev/null @@ -1,14 +0,0 @@ -require "active_support/core_ext/date_and_time/compatibility" -require "active_support/core_ext/module/remove_method" - -class Time - include DateAndTime::Compatibility - - remove_possible_method :to_time - - # Either return +self+ or the time in the local system timezone depending - # on the setting of +ActiveSupport.to_time_preserves_timezone+. - def to_time - preserve_timezone ? self : getlocal - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/conversions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/conversions.rb deleted file mode 100644 index 595bda6b4f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/conversions.rb +++ /dev/null @@ -1,70 +0,0 @@ -require "active_support/inflector/methods" -require "active_support/values/time_zone" - -class Time - DATE_FORMATS = { - db: "%Y-%m-%d %H:%M:%S", - number: "%Y%m%d%H%M%S", - nsec: "%Y%m%d%H%M%S%9N", - usec: "%Y%m%d%H%M%S%6N", - time: "%H:%M", - short: "%d %b %H:%M", - long: "%B %d, %Y %H:%M", - long_ordinal: lambda { |time| - day_format = ActiveSupport::Inflector.ordinalize(time.day) - time.strftime("%B #{day_format}, %Y %H:%M") - }, - rfc822: lambda { |time| - offset_format = time.formatted_offset(false) - time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}") - }, - iso8601: lambda { |time| time.iso8601 } - } - - # Converts to a formatted string. See DATE_FORMATS for built-in formats. - # - # This method is aliased to to_s. - # - # time = Time.now # => 2007-01-18 06:10:17 -06:00 - # - # time.to_formatted_s(:time) # => "06:10" - # time.to_s(:time) # => "06:10" - # - # time.to_formatted_s(:db) # => "2007-01-18 06:10:17" - # time.to_formatted_s(:number) # => "20070118061017" - # time.to_formatted_s(:short) # => "18 Jan 06:10" - # time.to_formatted_s(:long) # => "January 18, 2007 06:10" - # time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10" - # time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600" - # time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00" - # - # == Adding your own time formats to +to_formatted_s+ - # You can add your own formats to the Time::DATE_FORMATS hash. - # Use the format name as the hash key and either a strftime string - # or Proc instance that takes a time argument as the value. - # - # # config/initializers/time_formats.rb - # Time::DATE_FORMATS[:month_and_year] = '%B %Y' - # Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") } - def to_formatted_s(format = :default) - if formatter = DATE_FORMATS[format] - formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) - else - to_default_s - end - end - alias_method :to_default_s, :to_s - alias_method :to_s, :to_formatted_s - - # Returns a formatted string of the offset from UTC, or an alternative - # string if the time zone is already UTC. - # - # Time.local(2000).formatted_offset # => "-06:00" - # Time.local(2000).formatted_offset(false) # => "-0600" - def formatted_offset(colon = true, alternate_utc_string = nil) - utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon) - end - - # Aliased to +xmlschema+ for compatibility with +DateTime+ - alias_method :rfc3339, :xmlschema -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/zones.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/zones.rb deleted file mode 100644 index 87b5ad903a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/time/zones.rb +++ /dev/null @@ -1,111 +0,0 @@ -require "active_support/time_with_zone" -require "active_support/core_ext/time/acts_like" -require "active_support/core_ext/date_and_time/zones" - -class Time - include DateAndTime::Zones - class << self - attr_accessor :zone_default - - # Returns the TimeZone for the current request, if this has been set (via Time.zone=). - # If Time.zone has not been set for the current request, returns the TimeZone specified in config.time_zone. - def zone - Thread.current[:time_zone] || zone_default - end - - # Sets Time.zone to a TimeZone object for the current request/thread. - # - # This method accepts any of the following: - # - # * A Rails TimeZone object. - # * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", -5.hours). - # * A TZInfo::Timezone object. - # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York"). - # - # Here's an example of how you might set Time.zone on a per request basis and reset it when the request is done. - # current_user.time_zone just needs to return a string identifying the user's preferred time zone: - # - # class ApplicationController < ActionController::Base - # around_action :set_time_zone - # - # def set_time_zone - # if logged_in? - # Time.use_zone(current_user.time_zone) { yield } - # else - # yield - # end - # end - # end - def zone=(time_zone) - Thread.current[:time_zone] = find_zone!(time_zone) - end - - # Allows override of Time.zone locally inside supplied block; - # resets Time.zone to existing value when done. - # - # class ApplicationController < ActionController::Base - # around_action :set_time_zone - # - # private - # - # def set_time_zone - # Time.use_zone(current_user.timezone) { yield } - # end - # end - # - # NOTE: This won't affect any ActiveSupport::TimeWithZone - # objects that have already been created, e.g. any model timestamp - # attributes that have been read before the block will remain in - # the application's default timezone. - def use_zone(time_zone) - new_zone = find_zone!(time_zone) - begin - old_zone, ::Time.zone = ::Time.zone, new_zone - yield - ensure - ::Time.zone = old_zone - end - end - - # Returns a TimeZone instance matching the time zone provided. - # Accepts the time zone in any format supported by Time.zone=. - # Raises an +ArgumentError+ for invalid time zones. - # - # Time.find_zone! "America/New_York" # => # - # Time.find_zone! "EST" # => # - # Time.find_zone! -5.hours # => # - # Time.find_zone! nil # => nil - # Time.find_zone! false # => false - # Time.find_zone! "NOT-A-TIMEZONE" # => ArgumentError: Invalid Timezone: NOT-A-TIMEZONE - def find_zone!(time_zone) - if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone) - time_zone - else - # Look up the timezone based on the identifier (unless we've been - # passed a TZInfo::Timezone) - unless time_zone.respond_to?(:period_for_local) - time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone) - end - - # Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone - if time_zone.is_a?(ActiveSupport::TimeZone) - time_zone - else - ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone) - end - end - rescue TZInfo::InvalidTimezoneIdentifier - raise ArgumentError, "Invalid Timezone: #{time_zone}" - end - - # Returns a TimeZone instance matching the time zone provided. - # Accepts the time zone in any format supported by Time.zone=. - # Returns +nil+ for invalid time zones. - # - # Time.find_zone "America/New_York" # => # - # Time.find_zone "NOT-A-TIMEZONE" # => nil - def find_zone(time_zone) - find_zone!(time_zone) rescue nil - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/uri.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/uri.rb deleted file mode 100644 index 342a5fcd52..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/core_ext/uri.rb +++ /dev/null @@ -1,24 +0,0 @@ -require "uri" -str = "\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E" # Ni-ho-nn-go in UTF-8, means Japanese. -parser = URI::Parser.new - -unless str == parser.unescape(parser.escape(str)) - URI::Parser.class_eval do - remove_method :unescape - def unescape(str, escaped = /%[a-fA-F\d]{2}/) - # TODO: Are we actually sure that ASCII == UTF-8? - # YK: My initial experiments say yes, but let's be sure please - enc = str.encoding - enc = Encoding::UTF_8 if enc == Encoding::US_ASCII - str.gsub(escaped) { |match| [match[1, 2].hex].pack("C") }.force_encoding(enc) - end - end -end - -module URI - class << self - def parser - @parser ||= URI::Parser.new - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies.rb deleted file mode 100644 index 2e4c55e7b2..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies.rb +++ /dev/null @@ -1,754 +0,0 @@ -require "set" -require "thread" -require "concurrent/map" -require "pathname" -require "active_support/core_ext/module/aliasing" -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/module/introspection" -require "active_support/core_ext/module/anonymous" -require "active_support/core_ext/object/blank" -require "active_support/core_ext/kernel/reporting" -require "active_support/core_ext/load_error" -require "active_support/core_ext/name_error" -require "active_support/core_ext/string/starts_ends_with" -require "active_support/dependencies/interlock" -require "active_support/inflector" - -module ActiveSupport #:nodoc: - module Dependencies #:nodoc: - extend self - - mattr_accessor :interlock - self.interlock = Interlock.new - - # :doc: - - # Execute the supplied block without interference from any - # concurrent loads. - def self.run_interlock - Dependencies.interlock.running { yield } - end - - # Execute the supplied block while holding an exclusive lock, - # preventing any other thread from being inside a #run_interlock - # block at the same time. - def self.load_interlock - Dependencies.interlock.loading { yield } - end - - # Execute the supplied block while holding an exclusive lock, - # preventing any other thread from being inside a #run_interlock - # block at the same time. - def self.unload_interlock - Dependencies.interlock.unloading { yield } - end - - # :nodoc: - - # Should we turn on Ruby warnings on the first load of dependent files? - mattr_accessor :warnings_on_first_load - self.warnings_on_first_load = false - - # All files ever loaded. - mattr_accessor :history - self.history = Set.new - - # All files currently loaded. - mattr_accessor :loaded - self.loaded = Set.new - - # Stack of files being loaded. - mattr_accessor :loading - self.loading = [] - - # Should we load files or require them? - mattr_accessor :mechanism - self.mechanism = ENV["NO_RELOAD"] ? :require : :load - - # The set of directories from which we may automatically load files. Files - # under these directories will be reloaded on each request in development mode, - # unless the directory also appears in autoload_once_paths. - mattr_accessor :autoload_paths - self.autoload_paths = [] - - # The set of directories from which automatically loaded constants are loaded - # only once. All directories in this set must also be present in +autoload_paths+. - mattr_accessor :autoload_once_paths - self.autoload_once_paths = [] - - # An array of qualified constant names that have been loaded. Adding a name - # to this array will cause it to be unloaded the next time Dependencies are - # cleared. - mattr_accessor :autoloaded_constants - self.autoloaded_constants = [] - - # An array of constant names that need to be unloaded on every request. Used - # to allow arbitrary constants to be marked for unloading. - mattr_accessor :explicitly_unloadable_constants - self.explicitly_unloadable_constants = [] - - # The WatchStack keeps a stack of the modules being watched as files are - # loaded. If a file in the process of being loaded (parent.rb) triggers the - # load of another file (child.rb) the stack will ensure that child.rb - # handles the new constants. - # - # If child.rb is being autoloaded, its constants will be added to - # autoloaded_constants. If it was being `require`d, they will be discarded. - # - # This is handled by walking back up the watch stack and adding the constants - # found by child.rb to the list of original constants in parent.rb. - class WatchStack - include Enumerable - - # @watching is a stack of lists of constants being watched. For instance, - # if parent.rb is autoloaded, the stack will look like [[Object]]. If - # parent.rb then requires namespace/child.rb, the stack will look like - # [[Object], [Namespace]]. - - def initialize - @watching = [] - @stack = Hash.new { |h, k| h[k] = [] } - end - - def each(&block) - @stack.each(&block) - end - - def watching? - !@watching.empty? - end - - # Returns a list of new constants found since the last call to - # watch_namespaces. - def new_constants - constants = [] - - # Grab the list of namespaces that we're looking for new constants under - @watching.last.each do |namespace| - # Retrieve the constants that were present under the namespace when watch_namespaces - # was originally called - original_constants = @stack[namespace].last - - mod = Inflector.constantize(namespace) if Dependencies.qualified_const_defined?(namespace) - next unless mod.is_a?(Module) - - # Get a list of the constants that were added - new_constants = mod.constants(false) - original_constants - - # @stack[namespace] returns an Array of the constants that are being evaluated - # for that namespace. For instance, if parent.rb requires child.rb, the first - # element of @stack[Object] will be an Array of the constants that were present - # before parent.rb was required. The second element will be an Array of the - # constants that were present before child.rb was required. - @stack[namespace].each do |namespace_constants| - namespace_constants.concat(new_constants) - end - - # Normalize the list of new constants, and add them to the list we will return - new_constants.each do |suffix| - constants << ([namespace, suffix] - ["Object"]).join("::".freeze) - end - end - constants - ensure - # A call to new_constants is always called after a call to watch_namespaces - pop_modules(@watching.pop) - end - - # Add a set of modules to the watch stack, remembering the initial - # constants. - def watch_namespaces(namespaces) - @watching << namespaces.map do |namespace| - module_name = Dependencies.to_constant_name(namespace) - original_constants = Dependencies.qualified_const_defined?(module_name) ? - Inflector.constantize(module_name).constants(false) : [] - - @stack[module_name] << original_constants - module_name - end - end - - private - def pop_modules(modules) - modules.each { |mod| @stack[mod].pop } - end - end - - # An internal stack used to record which constants are loaded by any block. - mattr_accessor :constant_watch_stack - self.constant_watch_stack = WatchStack.new - - # Module includes this module. - module ModuleConstMissing #:nodoc: - def self.append_features(base) - base.class_eval do - # Emulate #exclude via an ivar - return if defined?(@_const_missing) && @_const_missing - @_const_missing = instance_method(:const_missing) - remove_method(:const_missing) - end - super - end - - def self.exclude_from(base) - base.class_eval do - define_method :const_missing, @_const_missing - @_const_missing = nil - end - end - - def const_missing(const_name) - from_mod = anonymous? ? guess_for_anonymous(const_name) : self - Dependencies.load_missing_constant(from_mod, const_name) - end - - # We assume that the name of the module reflects the nesting - # (unless it can be proven that is not the case) and the path to the file - # that defines the constant. Anonymous modules cannot follow these - # conventions and therefore we assume that the user wants to refer to a - # top-level constant. - def guess_for_anonymous(const_name) - if Object.const_defined?(const_name) - raise NameError.new "#{const_name} cannot be autoloaded from an anonymous class or module", const_name - else - Object - end - end - - def unloadable(const_desc = self) - super(const_desc) - end - end - - # Object includes this module. - module Loadable #:nodoc: - def self.exclude_from(base) - base.class_eval do - define_method(:load, Kernel.instance_method(:load)) - private :load - end - end - - def require_or_load(file_name) - Dependencies.require_or_load(file_name) - end - - # Interprets a file using mechanism and marks its defined - # constants as autoloaded. file_name can be either a string or - # respond to to_path. - # - # Use this method in code that absolutely needs a certain constant to be - # defined at that point. A typical use case is to make constant name - # resolution deterministic for constants with the same relative name in - # different namespaces whose evaluation would depend on load order - # otherwise. - def require_dependency(file_name, message = "No such file to load -- %s.rb") - file_name = file_name.to_path if file_name.respond_to?(:to_path) - unless file_name.is_a?(String) - raise ArgumentError, "the file name must either be a String or implement #to_path -- you passed #{file_name.inspect}" - end - - Dependencies.depend_on(file_name, message) - end - - def load_dependency(file) - if Dependencies.load? && Dependencies.constant_watch_stack.watching? - Dependencies.new_constants_in(Object) { yield } - else - yield - end - rescue Exception => exception # errors from loading file - exception.blame_file! file if exception.respond_to? :blame_file! - raise - end - - # Mark the given constant as unloadable. Unloadable constants are removed - # each time dependencies are cleared. - # - # Note that marking a constant for unloading need only be done once. Setup - # or init scripts may list each unloadable constant that may need unloading; - # each constant will be removed for every subsequent clear, as opposed to - # for the first clear. - # - # The provided constant descriptor may be a (non-anonymous) module or class, - # or a qualified constant name as a string or symbol. - # - # Returns +true+ if the constant was not previously marked for unloading, - # +false+ otherwise. - def unloadable(const_desc) - Dependencies.mark_for_unload const_desc - end - - private - - def load(file, wrap = false) - result = false - load_dependency(file) { result = super } - result - end - - def require(file) - result = false - load_dependency(file) { result = super } - result - end - end - - # Exception file-blaming. - module Blamable #:nodoc: - def blame_file!(file) - (@blamed_files ||= []).unshift file - end - - def blamed_files - @blamed_files ||= [] - end - - def describe_blame - return nil if blamed_files.empty? - "This error occurred while loading the following files:\n #{blamed_files.join "\n "}" - end - - def copy_blame!(exc) - @blamed_files = exc.blamed_files.clone - self - end - end - - def hook! - Object.class_eval { include Loadable } - Module.class_eval { include ModuleConstMissing } - Exception.class_eval { include Blamable } - end - - def unhook! - ModuleConstMissing.exclude_from(Module) - Loadable.exclude_from(Object) - end - - def load? - mechanism == :load - end - - def depend_on(file_name, message = "No such file to load -- %s.rb") - path = search_for_file(file_name) - require_or_load(path || file_name) - rescue LoadError => load_error - if file_name = load_error.message[/ -- (.*?)(\.rb)?$/, 1] - load_error.message.replace(message % file_name) - load_error.copy_blame!(load_error) - end - raise - end - - def clear - Dependencies.unload_interlock do - loaded.clear - loading.clear - remove_unloadable_constants! - end - end - - def require_or_load(file_name, const_path = nil) - file_name = $` if file_name =~ /\.rb\z/ - expanded = File.expand_path(file_name) - return if loaded.include?(expanded) - - Dependencies.load_interlock do - # Maybe it got loaded while we were waiting for our lock: - return if loaded.include?(expanded) - - # Record that we've seen this file *before* loading it to avoid an - # infinite loop with mutual dependencies. - loaded << expanded - loading << expanded - - begin - if load? - # Enable warnings if this file has not been loaded before and - # warnings_on_first_load is set. - load_args = ["#{file_name}.rb"] - load_args << const_path unless const_path.nil? - - if !warnings_on_first_load || history.include?(expanded) - result = load_file(*load_args) - else - enable_warnings { result = load_file(*load_args) } - end - else - result = require file_name - end - rescue Exception - loaded.delete expanded - raise - ensure - loading.pop - end - - # Record history *after* loading so first load gets warnings. - history << expanded - result - end - end - - # Is the provided constant path defined? - def qualified_const_defined?(path) - Object.const_defined?(path, false) - end - - # Given +path+, a filesystem path to a ruby file, return an array of - # constant paths which would cause Dependencies to attempt to load this - # file. - def loadable_constants_for_path(path, bases = autoload_paths) - path = $` if path =~ /\.rb\z/ - expanded_path = File.expand_path(path) - paths = [] - - bases.each do |root| - expanded_root = File.expand_path(root) - next unless expanded_path.start_with?(expanded_root) - - root_size = expanded_root.size - next if expanded_path[root_size] != ?/.freeze - - nesting = expanded_path[(root_size + 1)..-1] - paths << nesting.camelize unless nesting.blank? - end - - paths.uniq! - paths - end - - # Search for a file in autoload_paths matching the provided suffix. - def search_for_file(path_suffix) - path_suffix = path_suffix.sub(/(\.rb)?$/, ".rb".freeze) - - autoload_paths.each do |root| - path = File.join(root, path_suffix) - return path if File.file? path - end - nil # Gee, I sure wish we had first_match ;-) - end - - # Does the provided path_suffix correspond to an autoloadable module? - # Instead of returning a boolean, the autoload base for this module is - # returned. - def autoloadable_module?(path_suffix) - autoload_paths.each do |load_path| - return load_path if File.directory? File.join(load_path, path_suffix) - end - nil - end - - def load_once_path?(path) - # to_s works around a ruby issue where String#starts_with?(Pathname) - # will raise a TypeError: no implicit conversion of Pathname into String - autoload_once_paths.any? { |base| path.starts_with? base.to_s } - end - - # Attempt to autoload the provided module name by searching for a directory - # matching the expected path suffix. If found, the module is created and - # assigned to +into+'s constants with the name +const_name+. Provided that - # the directory was loaded from a reloadable base path, it is added to the - # set of constants that are to be unloaded. - def autoload_module!(into, const_name, qualified_name, path_suffix) - return nil unless base_path = autoloadable_module?(path_suffix) - mod = Module.new - into.const_set const_name, mod - autoloaded_constants << qualified_name unless autoload_once_paths.include?(base_path) - autoloaded_constants.uniq! - mod - end - - # Load the file at the provided path. +const_paths+ is a set of qualified - # constant names. When loading the file, Dependencies will watch for the - # addition of these constants. Each that is defined will be marked as - # autoloaded, and will be removed when Dependencies.clear is next called. - # - # If the second parameter is left off, then Dependencies will construct a - # set of names that the file at +path+ may define. See - # +loadable_constants_for_path+ for more details. - def load_file(path, const_paths = loadable_constants_for_path(path)) - const_paths = [const_paths].compact unless const_paths.is_a? Array - parent_paths = const_paths.collect { |const_path| const_path[/.*(?=::)/] || ::Object } - - result = nil - newly_defined_paths = new_constants_in(*parent_paths) do - result = Kernel.load path - end - - autoloaded_constants.concat newly_defined_paths unless load_once_path?(path) - autoloaded_constants.uniq! - result - end - - # Returns the constant path for the provided parent and constant name. - def qualified_name_for(mod, name) - mod_name = to_constant_name mod - mod_name == "Object" ? name.to_s : "#{mod_name}::#{name}" - end - - # Load the constant named +const_name+ which is missing from +from_mod+. If - # it is not possible to load the constant into from_mod, try its parent - # module using +const_missing+. - def load_missing_constant(from_mod, const_name) - unless qualified_const_defined?(from_mod.name) && Inflector.constantize(from_mod.name).equal?(from_mod) - raise ArgumentError, "A copy of #{from_mod} has been removed from the module tree but is still active!" - end - - qualified_name = qualified_name_for from_mod, const_name - path_suffix = qualified_name.underscore - - file_path = search_for_file(path_suffix) - - if file_path - expanded = File.expand_path(file_path) - expanded.sub!(/\.rb\z/, "".freeze) - - if loading.include?(expanded) - raise "Circular dependency detected while autoloading constant #{qualified_name}" - else - require_or_load(expanded, qualified_name) - raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false) - return from_mod.const_get(const_name) - end - elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix) - return mod - elsif (parent = from_mod.parent) && parent != from_mod && - ! from_mod.parents.any? { |p| p.const_defined?(const_name, false) } - # If our parents do not have a constant named +const_name+ then we are free - # to attempt to load upwards. If they do have such a constant, then this - # const_missing must be due to from_mod::const_name, which should not - # return constants from from_mod's parents. - begin - # Since Ruby does not pass the nesting at the point the unknown - # constant triggered the callback we cannot fully emulate constant - # name lookup and need to make a trade-off: we are going to assume - # that the nesting in the body of Foo::Bar is [Foo::Bar, Foo] even - # though it might not be. Counterexamples are - # - # class Foo::Bar - # Module.nesting # => [Foo::Bar] - # end - # - # or - # - # module M::N - # module S::T - # Module.nesting # => [S::T, M::N] - # end - # end - # - # for example. - return parent.const_missing(const_name) - rescue NameError => e - raise unless e.missing_name? qualified_name_for(parent, const_name) - end - end - - name_error = NameError.new("uninitialized constant #{qualified_name}", const_name) - name_error.set_backtrace(caller.reject { |l| l.starts_with? __FILE__ }) - raise name_error - end - - # Remove the constants that have been autoloaded, and those that have been - # marked for unloading. Before each constant is removed a callback is sent - # to its class/module if it implements +before_remove_const+. - # - # The callback implementation should be restricted to cleaning up caches, etc. - # as the environment will be in an inconsistent state, e.g. other constants - # may have already been unloaded and not accessible. - def remove_unloadable_constants! - autoloaded_constants.each { |const| remove_constant const } - autoloaded_constants.clear - Reference.clear! - explicitly_unloadable_constants.each { |const| remove_constant const } - end - - class ClassCache - def initialize - @store = Concurrent::Map.new - end - - def empty? - @store.empty? - end - - def key?(key) - @store.key?(key) - end - - def get(key) - key = key.name if key.respond_to?(:name) - @store[key] ||= Inflector.constantize(key) - end - alias :[] :get - - def safe_get(key) - key = key.name if key.respond_to?(:name) - @store[key] ||= Inflector.safe_constantize(key) - end - - def store(klass) - return self unless klass.respond_to?(:name) - raise(ArgumentError, "anonymous classes cannot be cached") if klass.name.empty? - @store[klass.name] = klass - self - end - - def clear! - @store.clear - end - end - - Reference = ClassCache.new - - # Store a reference to a class +klass+. - def reference(klass) - Reference.store klass - end - - # Get the reference for class named +name+. - # Raises an exception if referenced class does not exist. - def constantize(name) - Reference.get(name) - end - - # Get the reference for class named +name+ if one exists. - # Otherwise returns +nil+. - def safe_constantize(name) - Reference.safe_get(name) - end - - # Determine if the given constant has been automatically loaded. - def autoloaded?(desc) - return false if desc.is_a?(Module) && desc.anonymous? - name = to_constant_name desc - return false unless qualified_const_defined?(name) - return autoloaded_constants.include?(name) - end - - # Will the provided constant descriptor be unloaded? - def will_unload?(const_desc) - autoloaded?(const_desc) || - explicitly_unloadable_constants.include?(to_constant_name(const_desc)) - end - - # Mark the provided constant name for unloading. This constant will be - # unloaded on each request, not just the next one. - def mark_for_unload(const_desc) - name = to_constant_name const_desc - if explicitly_unloadable_constants.include? name - false - else - explicitly_unloadable_constants << name - true - end - end - - # Run the provided block and detect the new constants that were loaded during - # its execution. Constants may only be regarded as 'new' once -- so if the - # block calls +new_constants_in+ again, then the constants defined within the - # inner call will not be reported in this one. - # - # If the provided block does not run to completion, and instead raises an - # exception, any new constants are regarded as being only partially defined - # and will be removed immediately. - def new_constants_in(*descs) - constant_watch_stack.watch_namespaces(descs) - success = false - - begin - yield # Now yield to the code that is to define new constants. - success = true - ensure - new_constants = constant_watch_stack.new_constants - - return new_constants if success - - # Remove partially loaded constants. - new_constants.each { |c| remove_constant(c) } - end - end - - # Convert the provided const desc to a qualified constant name (as a string). - # A module, class, symbol, or string may be provided. - def to_constant_name(desc) #:nodoc: - case desc - when String then desc.sub(/^::/, "") - when Symbol then desc.to_s - when Module - desc.name || - raise(ArgumentError, "Anonymous modules have no name to be referenced by") - else raise TypeError, "Not a valid constant descriptor: #{desc.inspect}" - end - end - - def remove_constant(const) #:nodoc: - # Normalize ::Foo, ::Object::Foo, Object::Foo, Object::Object::Foo, etc. as Foo. - normalized = const.to_s.sub(/\A::/, "") - normalized.sub!(/\A(Object::)+/, "") - - constants = normalized.split("::") - to_remove = constants.pop - - # Remove the file path from the loaded list. - file_path = search_for_file(const.underscore) - if file_path - expanded = File.expand_path(file_path) - expanded.sub!(/\.rb\z/, "") - loaded.delete(expanded) - end - - if constants.empty? - parent = Object - else - # This method is robust to non-reachable constants. - # - # Non-reachable constants may be passed if some of the parents were - # autoloaded and already removed. It is easier to do a sanity check - # here than require the caller to be clever. We check the parent - # rather than the very const argument because we do not want to - # trigger Kernel#autoloads, see the comment below. - parent_name = constants.join("::") - return unless qualified_const_defined?(parent_name) - parent = constantize(parent_name) - end - - # In an autoloaded user.rb like this - # - # autoload :Foo, 'foo' - # - # class User < ActiveRecord::Base - # end - # - # we correctly register "Foo" as being autoloaded. But if the app does - # not use the "Foo" constant we need to be careful not to trigger - # loading "foo.rb" ourselves. While #const_defined? and #const_get? do - # require the file, #autoload? and #remove_const don't. - # - # We are going to remove the constant nonetheless ---which exists as - # far as Ruby is concerned--- because if the user removes the macro - # call from a class or module that were not autoloaded, as in the - # example above with Object, accessing to that constant must err. - unless parent.autoload?(to_remove) - begin - constantized = parent.const_get(to_remove, false) - rescue NameError - # The constant is no longer reachable, just skip it. - return - else - constantized.before_remove_const if constantized.respond_to?(:before_remove_const) - end - end - - begin - parent.instance_eval { remove_const to_remove } - rescue NameError - # The constant is no longer reachable, just skip it. - end - end - end -end - -ActiveSupport::Dependencies.hook! diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies/autoload.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies/autoload.rb deleted file mode 100644 index 13036d521d..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies/autoload.rb +++ /dev/null @@ -1,77 +0,0 @@ -require "active_support/inflector/methods" - -module ActiveSupport - # Autoload and eager load conveniences for your library. - # - # This module allows you to define autoloads based on - # Rails conventions (i.e. no need to define the path - # it is automatically guessed based on the filename) - # and also define a set of constants that needs to be - # eager loaded: - # - # module MyLib - # extend ActiveSupport::Autoload - # - # autoload :Model - # - # eager_autoload do - # autoload :Cache - # end - # end - # - # Then your library can be eager loaded by simply calling: - # - # MyLib.eager_load! - module Autoload - def self.extended(base) # :nodoc: - base.class_eval do - @_autoloads = {} - @_under_path = nil - @_at_path = nil - @_eager_autoload = false - end - end - - def autoload(const_name, path = @_at_path) - unless path - full = [name, @_under_path, const_name.to_s].compact.join("::") - path = Inflector.underscore(full) - end - - if @_eager_autoload - @_autoloads[const_name] = path - end - - super const_name, path - end - - def autoload_under(path) - @_under_path, old_path = path, @_under_path - yield - ensure - @_under_path = old_path - end - - def autoload_at(path) - @_at_path, old_path = path, @_at_path - yield - ensure - @_at_path = old_path - end - - def eager_autoload - old_eager, @_eager_autoload = @_eager_autoload, true - yield - ensure - @_eager_autoload = old_eager - end - - def eager_load! - @_autoloads.each_value { |file| require file } - end - - def autoloads - @_autoloads - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies/interlock.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies/interlock.rb deleted file mode 100644 index e4e18439c5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/dependencies/interlock.rb +++ /dev/null @@ -1,55 +0,0 @@ -require "active_support/concurrency/share_lock" - -module ActiveSupport #:nodoc: - module Dependencies #:nodoc: - class Interlock - def initialize # :nodoc: - @lock = ActiveSupport::Concurrency::ShareLock.new - end - - def loading - @lock.exclusive(purpose: :load, compatible: [:load], after_compatible: [:load]) do - yield - end - end - - def unloading - @lock.exclusive(purpose: :unload, compatible: [:load, :unload], after_compatible: [:load, :unload]) do - yield - end - end - - def start_unloading - @lock.start_exclusive(purpose: :unload, compatible: [:load, :unload]) - end - - def done_unloading - @lock.stop_exclusive(compatible: [:load, :unload]) - end - - def start_running - @lock.start_sharing - end - - def done_running - @lock.stop_sharing - end - - def running - @lock.sharing do - yield - end - end - - def permit_concurrent_loads - @lock.yield_shares(compatible: [:load]) do - yield - end - end - - def raw_state(&block) # :nodoc: - @lock.raw_state(&block) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation.rb deleted file mode 100644 index 71e6681b3f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation.rb +++ /dev/null @@ -1,44 +0,0 @@ -require "singleton" - -module ActiveSupport - # \Deprecation specifies the API used by Rails to deprecate methods, instance - # variables, objects and constants. - class Deprecation - # active_support.rb sets an autoload for ActiveSupport::Deprecation. - # - # If these requires were at the top of the file the constant would not be - # defined by the time their files were loaded. Since some of them reopen - # ActiveSupport::Deprecation its autoload would be triggered, resulting in - # a circular require warning for active_support/deprecation.rb. - # - # So, we define the constant first, and load dependencies later. - require "active_support/deprecation/instance_delegator" - require "active_support/deprecation/behaviors" - require "active_support/deprecation/reporting" - require "active_support/deprecation/constant_accessor" - require "active_support/deprecation/method_wrappers" - require "active_support/deprecation/proxy_wrappers" - require "active_support/core_ext/module/deprecation" - - include Singleton - include InstanceDelegator - include Behavior - include Reporting - include MethodWrapper - - # The version number in which the deprecated behavior will be removed, by default. - attr_accessor :deprecation_horizon - - # It accepts two parameters on initialization. The first is a version of library - # and the second is a library name - # - # ActiveSupport::Deprecation.new('2.0', 'MyLibrary') - def initialize(deprecation_horizon = "5.2", gem_name = "Rails") - self.gem_name = gem_name - self.deprecation_horizon = deprecation_horizon - # By default, warnings are not silenced and debugging is off. - self.silenced = false - self.debug = false - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/behaviors.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/behaviors.rb deleted file mode 100644 index 1d1354c23e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/behaviors.rb +++ /dev/null @@ -1,90 +0,0 @@ -require "active_support/notifications" - -module ActiveSupport - # Raised when ActiveSupport::Deprecation::Behavior#behavior is set with :raise. - # You would set :raise, as a behavior to raise errors and proactively report exceptions from deprecations. - class DeprecationException < StandardError - end - - class Deprecation - # Default warning behaviors per Rails.env. - DEFAULT_BEHAVIORS = { - raise: ->(message, callstack) { - e = DeprecationException.new(message) - e.set_backtrace(callstack.map(&:to_s)) - raise e - }, - - stderr: ->(message, callstack) { - $stderr.puts(message) - $stderr.puts callstack.join("\n ") if debug - }, - - log: ->(message, callstack) { - logger = - if defined?(Rails.logger) && Rails.logger - Rails.logger - else - require "active_support/logger" - ActiveSupport::Logger.new($stderr) - end - logger.warn message - logger.debug callstack.join("\n ") if debug - }, - - notify: ->(message, callstack) { - ActiveSupport::Notifications.instrument("deprecation.rails", - message: message, callstack: callstack) - }, - - silence: ->(message, callstack) {}, - } - - # Behavior module allows to determine how to display deprecation messages. - # You can create a custom behavior or set any from the +DEFAULT_BEHAVIORS+ - # constant. Available behaviors are: - # - # [+raise+] Raise ActiveSupport::DeprecationException. - # [+stderr+] Log all deprecation warnings to +$stderr+. - # [+log+] Log all deprecation warnings to +Rails.logger+. - # [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+. - # [+silence+] Do nothing. - # - # Setting behaviors only affects deprecations that happen after boot time. - # For more information you can read the documentation of the +behavior=+ method. - module Behavior - # Whether to print a backtrace along with the warning. - attr_accessor :debug - - # Returns the current behavior or if one isn't set, defaults to +:stderr+. - def behavior - @behavior ||= [DEFAULT_BEHAVIORS[:stderr]] - end - - # Sets the behavior to the specified value. Can be a single value, array, - # or an object that responds to +call+. - # - # Available behaviors: - # - # [+raise+] Raise ActiveSupport::DeprecationException. - # [+stderr+] Log all deprecation warnings to +$stderr+. - # [+log+] Log all deprecation warnings to +Rails.logger+. - # [+notify+] Use +ActiveSupport::Notifications+ to notify +deprecation.rails+. - # [+silence+] Do nothing. - # - # Setting behaviors only affects deprecations that happen after boot time. - # Deprecation warnings raised by gems are not affected by this setting - # because they happen before Rails boots up. - # - # ActiveSupport::Deprecation.behavior = :stderr - # ActiveSupport::Deprecation.behavior = [:stderr, :log] - # ActiveSupport::Deprecation.behavior = MyCustomHandler - # ActiveSupport::Deprecation.behavior = ->(message, callstack) { - # # custom stuff - # } - def behavior=(behavior) - @behavior = Array(behavior).map { |b| DEFAULT_BEHAVIORS[b] || b } - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/constant_accessor.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/constant_accessor.rb deleted file mode 100644 index 2b19de365f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/constant_accessor.rb +++ /dev/null @@ -1,50 +0,0 @@ -require "active_support/inflector/methods" - -module ActiveSupport - class Deprecation - # DeprecatedConstantAccessor transforms a constant into a deprecated one by - # hooking +const_missing+. - # - # It takes the names of an old (deprecated) constant and of a new constant - # (both in string form) and optionally a deprecator. The deprecator defaults - # to +ActiveSupport::Deprecator+ if none is specified. - # - # The deprecated constant now returns the same object as the new one rather - # than a proxy object, so it can be used transparently in +rescue+ blocks - # etc. - # - # PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto) - # - # (In a later update, the original implementation of `PLANETS` has been removed.) - # - # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune) - # include ActiveSupport::Deprecation::DeprecatedConstantAccessor - # deprecate_constant 'PLANETS', 'PLANETS_POST_2006' - # - # PLANETS.map { |planet| planet.capitalize } - # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead. - # (Backtrace information…) - # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] - module DeprecatedConstantAccessor - def self.included(base) - extension = Module.new do - def const_missing(missing_const_name) - if class_variable_defined?(:@@_deprecated_constants) - if (replacement = class_variable_get(:@@_deprecated_constants)[missing_const_name.to_s]) - replacement[:deprecator].warn(replacement[:message] || "#{name}::#{missing_const_name} is deprecated! Use #{replacement[:new]} instead.", caller_locations) - return ActiveSupport::Inflector.constantize(replacement[:new].to_s) - end - end - super - end - - def deprecate_constant(const_name, new_constant, message: nil, deprecator: ActiveSupport::Deprecation.instance) - class_variable_set(:@@_deprecated_constants, {}) unless class_variable_defined?(:@@_deprecated_constants) - class_variable_get(:@@_deprecated_constants)[const_name.to_s] = { new: new_constant, message: message, deprecator: deprecator } - end - end - base.singleton_class.prepend extension - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/instance_delegator.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/instance_delegator.rb deleted file mode 100644 index 6d390f3b37..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/instance_delegator.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "active_support/core_ext/kernel/singleton_class" -require "active_support/core_ext/module/delegation" - -module ActiveSupport - class Deprecation - module InstanceDelegator # :nodoc: - def self.included(base) - base.extend(ClassMethods) - base.singleton_class.prepend(OverrideDelegators) - base.public_class_method :new - end - - module ClassMethods # :nodoc: - def include(included_module) - included_module.instance_methods.each { |m| method_added(m) } - super - end - - def method_added(method_name) - singleton_class.delegate(method_name, to: :instance) - end - end - - module OverrideDelegators # :nodoc: - def warn(message = nil, callstack = nil) - callstack ||= caller_locations(2) - super - end - - def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil) - caller_backtrace ||= caller_locations(2) - super - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/method_wrappers.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/method_wrappers.rb deleted file mode 100644 index 15a73c1c90..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/method_wrappers.rb +++ /dev/null @@ -1,77 +0,0 @@ -require "active_support/core_ext/module/aliasing" -require "active_support/core_ext/array/extract_options" - -module ActiveSupport - class Deprecation - module MethodWrapper - # Declare that a method has been deprecated. - # - # module Fred - # extend self - # - # def aaa; end - # def bbb; end - # def ccc; end - # def ddd; end - # def eee; end - # end - # - # Using the default deprecator: - # ActiveSupport::Deprecation.deprecate_methods(Fred, :aaa, bbb: :zzz, ccc: 'use Bar#ccc instead') - # # => Fred - # - # Fred.aaa - # # DEPRECATION WARNING: aaa is deprecated and will be removed from Rails 5.1. (called from irb_binding at (irb):10) - # # => nil - # - # Fred.bbb - # # DEPRECATION WARNING: bbb is deprecated and will be removed from Rails 5.1 (use zzz instead). (called from irb_binding at (irb):11) - # # => nil - # - # Fred.ccc - # # DEPRECATION WARNING: ccc is deprecated and will be removed from Rails 5.1 (use Bar#ccc instead). (called from irb_binding at (irb):12) - # # => nil - # - # Passing in a custom deprecator: - # custom_deprecator = ActiveSupport::Deprecation.new('next-release', 'MyGem') - # ActiveSupport::Deprecation.deprecate_methods(Fred, ddd: :zzz, deprecator: custom_deprecator) - # # => [:ddd] - # - # Fred.ddd - # DEPRECATION WARNING: ddd is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):15) - # # => nil - # - # Using a custom deprecator directly: - # custom_deprecator = ActiveSupport::Deprecation.new('next-release', 'MyGem') - # custom_deprecator.deprecate_methods(Fred, eee: :zzz) - # # => [:eee] - # - # Fred.eee - # DEPRECATION WARNING: eee is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):18) - # # => nil - def deprecate_methods(target_module, *method_names) - options = method_names.extract_options! - deprecator = options.delete(:deprecator) || self - method_names += options.keys - - mod = Module.new do - method_names.each do |method_name| - define_method(method_name) do |*args, &block| - deprecator.deprecation_warning(method_name, options[method_name]) - super(*args, &block) - end - - case - when target_module.protected_method_defined?(method_name) - protected method_name - when target_module.private_method_defined?(method_name) - private method_name - end - end - end - - target_module.prepend(mod) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/proxy_wrappers.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/proxy_wrappers.rb deleted file mode 100644 index ce39e9a232..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/proxy_wrappers.rb +++ /dev/null @@ -1,151 +0,0 @@ -require "active_support/inflector/methods" -require "active_support/core_ext/regexp" - -module ActiveSupport - class Deprecation - class DeprecationProxy #:nodoc: - def self.new(*args, &block) - object = args.first - - return object unless object - super - end - - instance_methods.each { |m| undef_method m unless /^__|^object_id$/.match?(m) } - - # Don't give a deprecation warning on inspect since test/unit and error - # logs rely on it for diagnostics. - def inspect - target.inspect - end - - private - def method_missing(called, *args, &block) - warn caller_locations, called, args - target.__send__(called, *args, &block) - end - end - - # DeprecatedObjectProxy transforms an object into a deprecated one. It - # takes an object, a deprecation message and optionally a deprecator. The - # deprecator defaults to +ActiveSupport::Deprecator+ if none is specified. - # - # deprecated_object = ActiveSupport::Deprecation::DeprecatedObjectProxy.new(Object.new, "This object is now deprecated") - # # => # - # - # deprecated_object.to_s - # DEPRECATION WARNING: This object is now deprecated. - # (Backtrace) - # # => "#" - class DeprecatedObjectProxy < DeprecationProxy - def initialize(object, message, deprecator = ActiveSupport::Deprecation.instance) - @object = object - @message = message - @deprecator = deprecator - end - - private - def target - @object - end - - def warn(callstack, called, args) - @deprecator.warn(@message, callstack) - end - end - - # DeprecatedInstanceVariableProxy transforms an instance variable into a - # deprecated one. It takes an instance of a class, a method on that class - # and an instance variable. It optionally takes a deprecator as the last - # argument. The deprecator defaults to +ActiveSupport::Deprecator+ if none - # is specified. - # - # class Example - # def initialize - # @request = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new(self, :request, :@request) - # @_request = :special_request - # end - # - # def request - # @_request - # end - # - # def old_request - # @request - # end - # end - # - # example = Example.new - # # => # - # - # example.old_request.to_s - # # => DEPRECATION WARNING: @request is deprecated! Call request.to_s instead of - # @request.to_s - # (Backtrace information…) - # "special_request" - # - # example.request.to_s - # # => "special_request" - class DeprecatedInstanceVariableProxy < DeprecationProxy - def initialize(instance, method, var = "@#{method}", deprecator = ActiveSupport::Deprecation.instance) - @instance = instance - @method = method - @var = var - @deprecator = deprecator - end - - private - def target - @instance.__send__(@method) - end - - def warn(callstack, called, args) - @deprecator.warn("#{@var} is deprecated! Call #{@method}.#{called} instead of #{@var}.#{called}. Args: #{args.inspect}", callstack) - end - end - - # DeprecatedConstantProxy transforms a constant into a deprecated one. It - # takes the names of an old (deprecated) constant and of a new constant - # (both in string form) and optionally a deprecator. The deprecator defaults - # to +ActiveSupport::Deprecator+ if none is specified. The deprecated constant - # now returns the value of the new one. - # - # PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto) - # - # (In a later update, the original implementation of `PLANETS` has been removed.) - # - # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune) - # PLANETS = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('PLANETS', 'PLANETS_POST_2006') - # - # PLANETS.map { |planet| planet.capitalize } - # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead. - # (Backtrace information…) - # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] - class DeprecatedConstantProxy < DeprecationProxy - def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance, message: "#{old_const} is deprecated! Use #{new_const} instead.") - @old_const = old_const - @new_const = new_const - @deprecator = deprecator - @message = message - end - - # Returns the class of the new constant. - # - # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune) - # PLANETS = ActiveSupport::Deprecation::DeprecatedConstantProxy.new('PLANETS', 'PLANETS_POST_2006') - # PLANETS.class # => Array - def class - target.class - end - - private - def target - ActiveSupport::Inflector.constantize(@new_const.to_s) - end - - def warn(callstack, called, args) - @deprecator.warn(@message, callstack) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/reporting.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/reporting.rb deleted file mode 100644 index 58c5c50e30..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/deprecation/reporting.rb +++ /dev/null @@ -1,112 +0,0 @@ -require "rbconfig" - -module ActiveSupport - class Deprecation - module Reporting - # Whether to print a message (silent mode) - attr_accessor :silenced - # Name of gem where method is deprecated - attr_accessor :gem_name - - # Outputs a deprecation warning to the output configured by - # ActiveSupport::Deprecation.behavior. - # - # ActiveSupport::Deprecation.warn('something broke!') - # # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)" - def warn(message = nil, callstack = nil) - return if silenced - - callstack ||= caller_locations(2) - deprecation_message(callstack, message).tap do |m| - behavior.each { |b| b.call(m, callstack) } - end - end - - # Silence deprecation warnings within the block. - # - # ActiveSupport::Deprecation.warn('something broke!') - # # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)" - # - # ActiveSupport::Deprecation.silence do - # ActiveSupport::Deprecation.warn('something broke!') - # end - # # => nil - def silence - old_silenced, @silenced = @silenced, true - yield - ensure - @silenced = old_silenced - end - - def deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil) - caller_backtrace ||= caller_locations(2) - deprecated_method_warning(deprecated_method_name, message).tap do |msg| - warn(msg, caller_backtrace) - end - end - - private - # Outputs a deprecation warning message - # - # deprecated_method_warning(:method_name) - # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}" - # deprecated_method_warning(:method_name, :another_method) - # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)" - # deprecated_method_warning(:method_name, "Optional message") - # # => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)" - def deprecated_method_warning(method_name, message = nil) - warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}" - case message - when Symbol then "#{warning} (use #{message} instead)" - when String then "#{warning} (#{message})" - else warning - end - end - - def deprecation_message(callstack, message = nil) - message ||= "You are using deprecated behavior which will be removed from the next major or minor release." - "DEPRECATION WARNING: #{message} #{deprecation_caller_message(callstack)}" - end - - def deprecation_caller_message(callstack) - file, line, method = extract_callstack(callstack) - if file - if line && method - "(called from #{method} at #{file}:#{line})" - else - "(called from #{file}:#{line})" - end - end - end - - def extract_callstack(callstack) - return _extract_callstack(callstack) if callstack.first.is_a? String - - offending_line = callstack.find { |frame| - frame.absolute_path && !ignored_callstack(frame.absolute_path) - } || callstack.first - - [offending_line.path, offending_line.lineno, offending_line.label] - end - - def _extract_callstack(callstack) - warn "Please pass `caller_locations` to the deprecation API" if $VERBOSE - offending_line = callstack.find { |line| !ignored_callstack(line) } || callstack.first - - if offending_line - if md = offending_line.match(/^(.+?):(\d+)(?::in `(.*?)')?/) - md.captures - else - offending_line - end - end - end - - RAILS_GEM_ROOT = File.expand_path("../../../../..", __FILE__) + "/" - - def ignored_callstack(path) - path.start_with?(RAILS_GEM_ROOT) || path.start_with?(RbConfig::CONFIG["rubylibdir"]) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/descendants_tracker.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/descendants_tracker.rb deleted file mode 100644 index 27861e01d0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/descendants_tracker.rb +++ /dev/null @@ -1,60 +0,0 @@ -module ActiveSupport - # This module provides an internal implementation to track descendants - # which is faster than iterating through ObjectSpace. - module DescendantsTracker - @@direct_descendants = {} - - class << self - def direct_descendants(klass) - @@direct_descendants[klass] || [] - end - - def descendants(klass) - arr = [] - accumulate_descendants(klass, arr) - arr - end - - def clear - if defined? ActiveSupport::Dependencies - @@direct_descendants.each do |klass, descendants| - if ActiveSupport::Dependencies.autoloaded?(klass) - @@direct_descendants.delete(klass) - else - descendants.reject! { |v| ActiveSupport::Dependencies.autoloaded?(v) } - end - end - else - @@direct_descendants.clear - end - end - - # This is the only method that is not thread safe, but is only ever called - # during the eager loading phase. - def store_inherited(klass, descendant) - (@@direct_descendants[klass] ||= []) << descendant - end - - private - def accumulate_descendants(klass, acc) - if direct_descendants = @@direct_descendants[klass] - acc.concat(direct_descendants) - direct_descendants.each { |direct_descendant| accumulate_descendants(direct_descendant, acc) } - end - end - end - - def inherited(base) - DescendantsTracker.store_inherited(self, base) - super - end - - def direct_descendants - DescendantsTracker.direct_descendants(self) - end - - def descendants - DescendantsTracker.descendants(self) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration.rb deleted file mode 100644 index 76c9e01348..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration.rb +++ /dev/null @@ -1,428 +0,0 @@ -require "active_support/core_ext/array/conversions" -require "active_support/core_ext/module/delegation" -require "active_support/core_ext/object/acts_like" -require "active_support/core_ext/string/filters" -require "active_support/deprecation" - -module ActiveSupport - # Provides accurate date and time measurements using Date#advance and - # Time#advance, respectively. It mainly supports the methods on Numeric. - # - # 1.month.ago # equivalent to Time.now.advance(months: -1) - class Duration - class Scalar < Numeric #:nodoc: - attr_reader :value - delegate :to_i, :to_f, :to_s, to: :value - - def initialize(value) - @value = value - end - - def coerce(other) - [Scalar.new(other), self] - end - - def -@ - Scalar.new(-value) - end - - def <=>(other) - if Scalar === other || Duration === other - value <=> other.value - elsif Numeric === other - value <=> other - else - nil - end - end - - def +(other) - if Duration === other - seconds = value + other.parts[:seconds] - new_parts = other.parts.merge(seconds: seconds) - new_value = value + other.value - - Duration.new(new_value, new_parts) - else - calculate(:+, other) - end - end - - def -(other) - if Duration === other - seconds = value - other.parts[:seconds] - new_parts = other.parts.map { |part, other_value| [part, -other_value] }.to_h - new_parts = new_parts.merge(seconds: seconds) - new_value = value - other.value - - Duration.new(new_value, new_parts) - else - calculate(:-, other) - end - end - - def *(other) - if Duration === other - new_parts = other.parts.map { |part, other_value| [part, value * other_value] }.to_h - new_value = value * other.value - - Duration.new(new_value, new_parts) - else - calculate(:*, other) - end - end - - def /(other) - if Duration === other - value / other.value - else - calculate(:/, other) - end - end - - def %(other) - if Duration === other - Duration.build(value % other.value) - else - calculate(:%, other) - end - end - - private - def calculate(op, other) - if Scalar === other - Scalar.new(value.public_send(op, other.value)) - elsif Numeric === other - Scalar.new(value.public_send(op, other)) - else - raise_type_error(other) - end - end - - def raise_type_error(other) - raise TypeError, "no implicit conversion of #{other.class} into #{self.class}" - end - end - - SECONDS_PER_MINUTE = 60 - SECONDS_PER_HOUR = 3600 - SECONDS_PER_DAY = 86400 - SECONDS_PER_WEEK = 604800 - SECONDS_PER_MONTH = 2629746 # 1/12 of a gregorian year - SECONDS_PER_YEAR = 31556952 # length of a gregorian year (365.2425 days) - - PARTS_IN_SECONDS = { - seconds: 1, - minutes: SECONDS_PER_MINUTE, - hours: SECONDS_PER_HOUR, - days: SECONDS_PER_DAY, - weeks: SECONDS_PER_WEEK, - months: SECONDS_PER_MONTH, - years: SECONDS_PER_YEAR - }.freeze - - PARTS = [:years, :months, :weeks, :days, :hours, :minutes, :seconds].freeze - - attr_accessor :value, :parts - - autoload :ISO8601Parser, "active_support/duration/iso8601_parser" - autoload :ISO8601Serializer, "active_support/duration/iso8601_serializer" - - class << self - # Creates a new Duration from string formatted according to ISO 8601 Duration. - # - # See {ISO 8601}[http://en.wikipedia.org/wiki/ISO_8601#Durations] for more information. - # This method allows negative parts to be present in pattern. - # If invalid string is provided, it will raise +ActiveSupport::Duration::ISO8601Parser::ParsingError+. - def parse(iso8601duration) - parts = ISO8601Parser.new(iso8601duration).parse! - new(calculate_total_seconds(parts), parts) - end - - def ===(other) #:nodoc: - other.is_a?(Duration) - rescue ::NoMethodError - false - end - - def seconds(value) #:nodoc: - new(value, [[:seconds, value]]) - end - - def minutes(value) #:nodoc: - new(value * SECONDS_PER_MINUTE, [[:minutes, value]]) - end - - def hours(value) #:nodoc: - new(value * SECONDS_PER_HOUR, [[:hours, value]]) - end - - def days(value) #:nodoc: - new(value * SECONDS_PER_DAY, [[:days, value]]) - end - - def weeks(value) #:nodoc: - new(value * SECONDS_PER_WEEK, [[:weeks, value]]) - end - - def months(value) #:nodoc: - new(value * SECONDS_PER_MONTH, [[:months, value]]) - end - - def years(value) #:nodoc: - new(value * SECONDS_PER_YEAR, [[:years, value]]) - end - - # Creates a new Duration from a seconds value that is converted - # to the individual parts: - # - # ActiveSupport::Duration.build(31556952).parts # => {:years=>1} - # ActiveSupport::Duration.build(2716146).parts # => {:months=>1, :days=>1} - # - def build(value) - parts = {} - remainder = value.to_f - - PARTS.each do |part| - unless part == :seconds - part_in_seconds = PARTS_IN_SECONDS[part] - parts[part] = remainder.div(part_in_seconds) - remainder = (remainder % part_in_seconds).round(9) - end - end - - parts[:seconds] = remainder - parts.reject! { |k, v| v.zero? } - - new(value, parts) - end - - private - - def calculate_total_seconds(parts) - parts.inject(0) do |total, (part, value)| - total + value * PARTS_IN_SECONDS[part] - end - end - end - - def initialize(value, parts) #:nodoc: - @value, @parts = value, parts.to_h - @parts.default = 0 - end - - def coerce(other) #:nodoc: - if Scalar === other - [other, self] - else - [Scalar.new(other), self] - end - end - - # Compares one Duration with another or a Numeric to this Duration. - # Numeric values are treated as seconds. - def <=>(other) - if Duration === other - value <=> other.value - elsif Numeric === other - value <=> other - end - end - - # Adds another Duration or a Numeric to this Duration. Numeric values - # are treated as seconds. - def +(other) - if Duration === other - parts = @parts.dup - other.parts.each do |(key, value)| - parts[key] += value - end - Duration.new(value + other.value, parts) - else - seconds = @parts[:seconds] + other - Duration.new(value + other, @parts.merge(seconds: seconds)) - end - end - - # Subtracts another Duration or a Numeric from this Duration. Numeric - # values are treated as seconds. - def -(other) - self + (-other) - end - - # Multiplies this Duration by a Numeric and returns a new Duration. - def *(other) - if Scalar === other || Duration === other - Duration.new(value * other.value, parts.map { |type, number| [type, number * other.value] }) - elsif Numeric === other - Duration.new(value * other, parts.map { |type, number| [type, number * other] }) - else - raise_type_error(other) - end - end - - # Divides this Duration by a Numeric and returns a new Duration. - def /(other) - if Scalar === other - Duration.new(value / other.value, parts.map { |type, number| [type, number / other.value] }) - elsif Duration === other - value / other.value - elsif Numeric === other - Duration.new(value / other, parts.map { |type, number| [type, number / other] }) - else - raise_type_error(other) - end - end - - # Returns the modulo of this Duration by another Duration or Numeric. - # Numeric values are treated as seconds. - def %(other) - if Duration === other || Scalar === other - Duration.build(value % other.value) - elsif Numeric === other - Duration.build(value % other) - else - raise_type_error(other) - end - end - - def -@ #:nodoc: - Duration.new(-value, parts.map { |type, number| [type, -number] }) - end - - def is_a?(klass) #:nodoc: - Duration == klass || value.is_a?(klass) - end - alias :kind_of? :is_a? - - def instance_of?(klass) # :nodoc: - Duration == klass || value.instance_of?(klass) - end - - # Returns +true+ if +other+ is also a Duration instance with the - # same +value+, or if other == value. - def ==(other) - if Duration === other - other.value == value - else - other == value - end - end - - # Returns the amount of seconds a duration covers as a string. - # For more information check to_i method. - # - # 1.day.to_s # => "86400" - def to_s - @value.to_s - end - - # Returns the number of seconds that this Duration represents. - # - # 1.minute.to_i # => 60 - # 1.hour.to_i # => 3600 - # 1.day.to_i # => 86400 - # - # Note that this conversion makes some assumptions about the - # duration of some periods, e.g. months are always 1/12 of year - # and years are 365.2425 days: - # - # # equivalent to (1.year / 12).to_i - # 1.month.to_i # => 2629746 - # - # # equivalent to 365.2425.days.to_i - # 1.year.to_i # => 31556952 - # - # In such cases, Ruby's core - # Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and - # Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision - # date and time arithmetic. - def to_i - @value.to_i - end - - # Returns +true+ if +other+ is also a Duration instance, which has the - # same parts as this one. - def eql?(other) - Duration === other && other.value.eql?(value) - end - - def hash - @value.hash - end - - # Calculates a new Time or Date that is as far in the future - # as this Duration represents. - def since(time = ::Time.current) - sum(1, time) - end - alias :from_now :since - alias :after :since - - # Calculates a new Time or Date that is as far in the past - # as this Duration represents. - def ago(time = ::Time.current) - sum(-1, time) - end - alias :until :ago - alias :before :ago - - def inspect #:nodoc: - parts. - reduce(::Hash.new(0)) { |h, (l, r)| h[l] += r; h }. - sort_by { |unit, _ | PARTS.index(unit) }. - map { |unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}" }. - to_sentence(locale: ::I18n.default_locale) - end - - def as_json(options = nil) #:nodoc: - to_i - end - - def respond_to_missing?(method, include_private = false) #:nodoc: - @value.respond_to?(method, include_private) - end - - def init_with(coder) #:nodoc: - initialize(coder["value"], coder["parts"]) - end - - def encode_with(coder) #:nodoc: - coder.map = { "value" => @value, "parts" => @parts } - end - - # Build ISO 8601 Duration string for this duration. - # The +precision+ parameter can be used to limit seconds' precision of duration. - def iso8601(precision: nil) - ISO8601Serializer.new(self, precision: precision).serialize - end - - private - - def sum(sign, time = ::Time.current) - parts.inject(time) do |t, (type, number)| - if t.acts_like?(:time) || t.acts_like?(:date) - if type == :seconds - t.since(sign * number) - elsif type == :minutes - t.since(sign * number * 60) - elsif type == :hours - t.since(sign * number * 3600) - else - t.advance(type => sign * number) - end - else - raise ::ArgumentError, "expected a time or date, got #{time.inspect}" - end - end - end - - def method_missing(method, *args, &block) - value.send(method, *args, &block) - end - - def raise_type_error(other) - raise TypeError, "no implicit conversion of #{other.class} into #{self.class}" - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration/iso8601_parser.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration/iso8601_parser.rb deleted file mode 100644 index e96cb8e883..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration/iso8601_parser.rb +++ /dev/null @@ -1,123 +0,0 @@ -require "strscan" -require "active_support/core_ext/regexp" - -module ActiveSupport - class Duration - # Parses a string formatted according to ISO 8601 Duration into the hash. - # - # See {ISO 8601}[http://en.wikipedia.org/wiki/ISO_8601#Durations] for more information. - # - # This parser allows negative parts to be present in pattern. - class ISO8601Parser # :nodoc: - class ParsingError < ::ArgumentError; end - - PERIOD_OR_COMMA = /\.|,/ - PERIOD = ".".freeze - COMMA = ",".freeze - - SIGN_MARKER = /\A\-|\+|/ - DATE_MARKER = /P/ - TIME_MARKER = /T/ - DATE_COMPONENT = /(\-?\d+(?:[.,]\d+)?)(Y|M|D|W)/ - TIME_COMPONENT = /(\-?\d+(?:[.,]\d+)?)(H|M|S)/ - - DATE_TO_PART = { "Y" => :years, "M" => :months, "W" => :weeks, "D" => :days } - TIME_TO_PART = { "H" => :hours, "M" => :minutes, "S" => :seconds } - - DATE_COMPONENTS = [:years, :months, :days] - TIME_COMPONENTS = [:hours, :minutes, :seconds] - - attr_reader :parts, :scanner - attr_accessor :mode, :sign - - def initialize(string) - @scanner = StringScanner.new(string) - @parts = {} - @mode = :start - @sign = 1 - end - - def parse! - while !finished? - case mode - when :start - if scan(SIGN_MARKER) - self.sign = (scanner.matched == "-") ? -1 : 1 - self.mode = :sign - else - raise_parsing_error - end - - when :sign - if scan(DATE_MARKER) - self.mode = :date - else - raise_parsing_error - end - - when :date - if scan(TIME_MARKER) - self.mode = :time - elsif scan(DATE_COMPONENT) - parts[DATE_TO_PART[scanner[2]]] = number * sign - else - raise_parsing_error - end - - when :time - if scan(TIME_COMPONENT) - parts[TIME_TO_PART[scanner[2]]] = number * sign - else - raise_parsing_error - end - - end - end - - validate! - parts - end - - private - - def finished? - scanner.eos? - end - - # Parses number which can be a float with either comma or period. - def number - PERIOD_OR_COMMA.match?(scanner[1]) ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i - end - - def scan(pattern) - scanner.scan(pattern) - end - - def raise_parsing_error(reason = nil) - raise ParsingError, "Invalid ISO 8601 duration: #{scanner.string.inspect} #{reason}".strip - end - - # Checks for various semantic errors as stated in ISO 8601 standard. - def validate! - raise_parsing_error("is empty duration") if parts.empty? - - # Mixing any of Y, M, D with W is invalid. - if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any? - raise_parsing_error("mixing weeks with other date parts not allowed") - end - - # Specifying an empty T part is invalid. - if mode == :time && (parts.keys & TIME_COMPONENTS).empty? - raise_parsing_error("time part marker is present but time part is empty") - end - - fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 } - unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last) - raise_parsing_error "(only last part can be fractional)" - end - - return true - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration/iso8601_serializer.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration/iso8601_serializer.rb deleted file mode 100644 index e5d458b3ab..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/duration/iso8601_serializer.rb +++ /dev/null @@ -1,53 +0,0 @@ -require "active_support/core_ext/object/blank" -require "active_support/core_ext/hash/transform_values" - -module ActiveSupport - class Duration - # Serializes duration to string according to ISO 8601 Duration format. - class ISO8601Serializer # :nodoc: - def initialize(duration, precision: nil) - @duration = duration - @precision = precision - end - - # Builds and returns output string. - def serialize - parts, sign = normalize - return "PT0S".freeze if parts.empty? - - output = "P" - output << "#{parts[:years]}Y" if parts.key?(:years) - output << "#{parts[:months]}M" if parts.key?(:months) - output << "#{parts[:weeks]}W" if parts.key?(:weeks) - output << "#{parts[:days]}D" if parts.key?(:days) - time = "" - time << "#{parts[:hours]}H" if parts.key?(:hours) - time << "#{parts[:minutes]}M" if parts.key?(:minutes) - if parts.key?(:seconds) - time << "#{sprintf(@precision ? "%0.0#{@precision}f" : '%g', parts[:seconds])}S" - end - output << "T#{time}" unless time.empty? - "#{sign}#{output}" - end - - private - - # Return pair of duration's parts and whole duration sign. - # Parts are summarized (as they can become repetitive due to addition, etc). - # Zero parts are removed as not significant. - # If all parts are negative it will negate all of them and return minus as a sign. - def normalize - parts = @duration.parts.each_with_object(Hash.new(0)) do |(k, v), p| - p[k] += v unless v.zero? - end - # If all parts are negative - let's make a negative duration - sign = "" - if parts.values.all? { |v| v < 0 } - sign = "-" - parts.transform_values!(&:-@) - end - [parts, sign] - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/evented_file_update_checker.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/evented_file_update_checker.rb deleted file mode 100644 index f59f5d17dc..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/evented_file_update_checker.rb +++ /dev/null @@ -1,203 +0,0 @@ -require "set" -require "pathname" -require "concurrent/atomic/atomic_boolean" - -module ActiveSupport - # Allows you to "listen" to changes in a file system. - # The evented file updater does not hit disk when checking for updates - # instead it uses platform specific file system events to trigger a change - # in state. - # - # The file checker takes an array of files to watch or a hash specifying directories - # and file extensions to watch. It also takes a block that is called when - # EventedFileUpdateChecker#execute is run or when EventedFileUpdateChecker#execute_if_updated - # is run and there have been changes to the file system. - # - # Note: Forking will cause the first call to `updated?` to return `true`. - # - # Example: - # - # checker = ActiveSupport::EventedFileUpdateChecker.new(["/tmp/foo"]) { puts "changed" } - # checker.updated? - # # => false - # checker.execute_if_updated - # # => nil - # - # FileUtils.touch("/tmp/foo") - # - # checker.updated? - # # => true - # checker.execute_if_updated - # # => "changed" - # - class EventedFileUpdateChecker #:nodoc: all - def initialize(files, dirs = {}, &block) - unless block - raise ArgumentError, "A block is required to initialize an EventedFileUpdateChecker" - end - - @ph = PathHelper.new - @files = files.map { |f| @ph.xpath(f) }.to_set - - @dirs = {} - dirs.each do |dir, exts| - @dirs[@ph.xpath(dir)] = Array(exts).map { |ext| @ph.normalize_extension(ext) } - end - - @block = block - @updated = Concurrent::AtomicBoolean.new(false) - @lcsp = @ph.longest_common_subpath(@dirs.keys) - @pid = Process.pid - @boot_mutex = Mutex.new - - if (@dtw = directories_to_watch).any? - # Loading listen triggers warnings. These are originated by a legit - # usage of attr_* macros for private attributes, but adds a lot of noise - # to our test suite. Thus, we lazy load it and disable warnings locally. - silence_warnings do - begin - require "listen" - rescue LoadError => e - raise LoadError, "Could not load the 'listen' gem. Add `gem 'listen'` to the development group of your Gemfile", e.backtrace - end - end - end - boot! - end - - def updated? - @boot_mutex.synchronize do - if @pid != Process.pid - boot! - @pid = Process.pid - @updated.make_true - end - end - @updated.true? - end - - def execute - @updated.make_false - @block.call - end - - def execute_if_updated - if updated? - yield if block_given? - execute - true - end - end - - private - def boot! - Listen.to(*@dtw, &method(:changed)).start - end - - def changed(modified, added, removed) - unless updated? - @updated.make_true if (modified + added + removed).any? { |f| watching?(f) } - end - end - - def watching?(file) - file = @ph.xpath(file) - - if @files.member?(file) - true - elsif file.directory? - false - else - ext = @ph.normalize_extension(file.extname) - - file.dirname.ascend do |dir| - if @dirs.fetch(dir, []).include?(ext) - break true - elsif dir == @lcsp || dir.root? - break false - end - end - end - end - - def directories_to_watch - dtw = (@files + @dirs.keys).map { |f| @ph.existing_parent(f) } - dtw.compact! - dtw.uniq! - - normalized_gem_paths = Gem.path.map { |path| File.join path, "" } - dtw = dtw.reject do |path| - normalized_gem_paths.any? { |gem_path| path.to_s.start_with?(gem_path) } - end - - @ph.filter_out_descendants(dtw) - end - - class PathHelper - def xpath(path) - Pathname.new(path).expand_path - end - - def normalize_extension(ext) - ext.to_s.sub(/\A\./, "") - end - - # Given a collection of Pathname objects returns the longest subpath - # common to all of them, or +nil+ if there is none. - def longest_common_subpath(paths) - return if paths.empty? - - lcsp = Pathname.new(paths[0]) - - paths[1..-1].each do |path| - until ascendant_of?(lcsp, path) - if lcsp.root? - # If we get here a root directory is not an ascendant of path. - # This may happen if there are paths in different drives on - # Windows. - return - else - lcsp = lcsp.parent - end - end - end - - lcsp - end - - # Returns the deepest existing ascendant, which could be the argument itself. - def existing_parent(dir) - dir.ascend do |ascendant| - break ascendant if ascendant.directory? - end - end - - # Filters out directories which are descendants of others in the collection (stable). - def filter_out_descendants(dirs) - return dirs if dirs.length < 2 - - dirs_sorted_by_nparts = dirs.sort_by { |dir| dir.each_filename.to_a.length } - descendants = [] - - until dirs_sorted_by_nparts.empty? - dir = dirs_sorted_by_nparts.shift - - dirs_sorted_by_nparts.reject! do |possible_descendant| - ascendant_of?(dir, possible_descendant) && descendants << possible_descendant - end - end - - # Array#- preserves order. - dirs - descendants - end - - private - - def ascendant_of?(base, other) - base != other && other.ascend do |ascendant| - break true if base == ascendant - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/execution_wrapper.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/execution_wrapper.rb deleted file mode 100644 index ca88e7876b..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/execution_wrapper.rb +++ /dev/null @@ -1,126 +0,0 @@ -require "active_support/callbacks" - -module ActiveSupport - class ExecutionWrapper - include ActiveSupport::Callbacks - - Null = Object.new # :nodoc: - def Null.complete! # :nodoc: - end - - define_callbacks :run - define_callbacks :complete - - def self.to_run(*args, &block) - set_callback(:run, *args, &block) - end - - def self.to_complete(*args, &block) - set_callback(:complete, *args, &block) - end - - RunHook = Struct.new(:hook) do # :nodoc: - def before(target) - hook_state = target.send(:hook_state) - hook_state[hook] = hook.run - end - end - - CompleteHook = Struct.new(:hook) do # :nodoc: - def before(target) - hook_state = target.send(:hook_state) - if hook_state.key?(hook) - hook.complete hook_state[hook] - end - end - alias after before - end - - # Register an object to be invoked during both the +run+ and - # +complete+ steps. - # - # +hook.complete+ will be passed the value returned from +hook.run+, - # and will only be invoked if +run+ has previously been called. - # (Mostly, this means it won't be invoked if an exception occurs in - # a preceding +to_run+ block; all ordinary +to_complete+ blocks are - # invoked in that situation.) - def self.register_hook(hook, outer: false) - if outer - to_run RunHook.new(hook), prepend: true - to_complete :after, CompleteHook.new(hook) - else - to_run RunHook.new(hook) - to_complete CompleteHook.new(hook) - end - end - - # Run this execution. - # - # Returns an instance, whose +complete!+ method *must* be invoked - # after the work has been performed. - # - # Where possible, prefer +wrap+. - def self.run! - if active? - Null - else - new.tap do |instance| - success = nil - begin - instance.run! - success = true - ensure - instance.complete! unless success - end - end - end - end - - # Perform the work in the supplied block as an execution. - def self.wrap - return yield if active? - - instance = run! - begin - yield - ensure - instance.complete! - end - end - - class << self # :nodoc: - attr_accessor :active - end - - def self.inherited(other) # :nodoc: - super - other.active = Concurrent::Hash.new - end - - self.active = Concurrent::Hash.new - - def self.active? # :nodoc: - @active[Thread.current] - end - - def run! # :nodoc: - self.class.active[Thread.current] = true - run_callbacks(:run) - end - - # Complete this in-flight execution. This method *must* be called - # exactly once on the result of any call to +run!+. - # - # Where possible, prefer +wrap+. - def complete! - run_callbacks(:complete) - ensure - self.class.active.delete Thread.current - end - - private - def hook_state - @_hook_state ||= {} - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/executor.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/executor.rb deleted file mode 100644 index a6400cae0a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/executor.rb +++ /dev/null @@ -1,6 +0,0 @@ -require "active_support/execution_wrapper" - -module ActiveSupport - class Executor < ExecutionWrapper - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/file_update_checker.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/file_update_checker.rb deleted file mode 100644 index 2b5e3c1350..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/file_update_checker.rb +++ /dev/null @@ -1,161 +0,0 @@ -require "active_support/core_ext/time/calculations" - -module ActiveSupport - # FileUpdateChecker specifies the API used by Rails to watch files - # and control reloading. The API depends on four methods: - # - # * +initialize+ which expects two parameters and one block as - # described below. - # - # * +updated?+ which returns a boolean if there were updates in - # the filesystem or not. - # - # * +execute+ which executes the given block on initialization - # and updates the latest watched files and timestamp. - # - # * +execute_if_updated+ which just executes the block if it was updated. - # - # After initialization, a call to +execute_if_updated+ must execute - # the block only if there was really a change in the filesystem. - # - # This class is used by Rails to reload the I18n framework whenever - # they are changed upon a new request. - # - # i18n_reloader = ActiveSupport::FileUpdateChecker.new(paths) do - # I18n.reload! - # end - # - # ActiveSupport::Reloader.to_prepare do - # i18n_reloader.execute_if_updated - # end - class FileUpdateChecker - # It accepts two parameters on initialization. The first is an array - # of files and the second is an optional hash of directories. The hash must - # have directories as keys and the value is an array of extensions to be - # watched under that directory. - # - # This method must also receive a block that will be called once a path - # changes. The array of files and list of directories cannot be changed - # after FileUpdateChecker has been initialized. - def initialize(files, dirs = {}, &block) - unless block - raise ArgumentError, "A block is required to initialize a FileUpdateChecker" - end - - @files = files.freeze - @glob = compile_glob(dirs) - @block = block - - @watched = nil - @updated_at = nil - - @last_watched = watched - @last_update_at = updated_at(@last_watched) - end - - # Check if any of the entries were updated. If so, the watched and/or - # updated_at values are cached until the block is executed via +execute+ - # or +execute_if_updated+. - def updated? - current_watched = watched - if @last_watched.size != current_watched.size - @watched = current_watched - true - else - current_updated_at = updated_at(current_watched) - if @last_update_at < current_updated_at - @watched = current_watched - @updated_at = current_updated_at - true - else - false - end - end - end - - # Executes the given block and updates the latest watched files and - # timestamp. - def execute - @last_watched = watched - @last_update_at = updated_at(@last_watched) - @block.call - ensure - @watched = nil - @updated_at = nil - end - - # Execute the block given if updated. - def execute_if_updated - if updated? - yield if block_given? - execute - true - else - false - end - end - - private - - def watched - @watched || begin - all = @files.select { |f| File.exist?(f) } - all.concat(Dir[@glob]) if @glob - all - end - end - - def updated_at(paths) - @updated_at || max_mtime(paths) || Time.at(0) - end - - # This method returns the maximum mtime of the files in +paths+, or +nil+ - # if the array is empty. - # - # Files with a mtime in the future are ignored. Such abnormal situation - # can happen for example if the user changes the clock by hand. It is - # healthy to consider this edge case because with mtimes in the future - # reloading is not triggered. - def max_mtime(paths) - time_now = Time.now - max_mtime = nil - - # Time comparisons are performed with #compare_without_coercion because - # AS redefines these operators in a way that is much slower and does not - # bring any benefit in this particular code. - # - # Read t1.compare_without_coercion(t2) < 0 as t1 < t2. - paths.each do |path| - mtime = File.mtime(path) - - next if time_now.compare_without_coercion(mtime) < 0 - - if max_mtime.nil? || max_mtime.compare_without_coercion(mtime) < 0 - max_mtime = mtime - end - end - - max_mtime - end - - def compile_glob(hash) - hash.freeze # Freeze so changes aren't accidentally pushed - return if hash.empty? - - globs = hash.map do |key, value| - "#{escape(key)}/**/*#{compile_ext(value)}" - end - "{#{globs.join(",")}}" - end - - def escape(key) - key.gsub(",", '\,') - end - - def compile_ext(array) - array = Array(array) - return if array.empty? - ".{#{array.join(",")}}" - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/gem_version.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/gem_version.rb deleted file mode 100644 index 79491a116a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module ActiveSupport - # Returns the version of the currently loaded Active Support as a Gem::Version. - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/gzip.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/gzip.rb deleted file mode 100644 index 95a86889ec..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/gzip.rb +++ /dev/null @@ -1,36 +0,0 @@ -require "zlib" -require "stringio" - -module ActiveSupport - # A convenient wrapper for the zlib standard library that allows - # compression/decompression of strings with gzip. - # - # gzip = ActiveSupport::Gzip.compress('compress me!') - # # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00" - # - # ActiveSupport::Gzip.decompress(gzip) - # # => "compress me!" - module Gzip - class Stream < StringIO - def initialize(*) - super - set_encoding "BINARY" - end - def close; rewind; end - end - - # Decompresses a gzipped string. - def self.decompress(source) - Zlib::GzipReader.wrap(StringIO.new(source), &:read) - end - - # Compresses a string using gzip. - def self.compress(source, level = Zlib::DEFAULT_COMPRESSION, strategy = Zlib::DEFAULT_STRATEGY) - output = Stream.new - gz = Zlib::GzipWriter.new(output, level, strategy) - gz.write(source) - gz.close - output.string - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/hash_with_indifferent_access.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/hash_with_indifferent_access.rb deleted file mode 100644 index 770ec26423..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/hash_with_indifferent_access.rb +++ /dev/null @@ -1,341 +0,0 @@ -require "active_support/core_ext/hash/keys" -require "active_support/core_ext/hash/reverse_merge" - -module ActiveSupport - # Implements a hash where keys :foo and "foo" are considered - # to be the same. - # - # rgb = ActiveSupport::HashWithIndifferentAccess.new - # - # rgb[:black] = '#000000' - # rgb[:black] # => '#000000' - # rgb['black'] # => '#000000' - # - # rgb['white'] = '#FFFFFF' - # rgb[:white] # => '#FFFFFF' - # rgb['white'] # => '#FFFFFF' - # - # Internally symbols are mapped to strings when used as keys in the entire - # writing interface (calling []=, merge, etc). This - # mapping belongs to the public interface. For example, given: - # - # hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1) - # - # You are guaranteed that the key is returned as a string: - # - # hash.keys # => ["a"] - # - # Technically other types of keys are accepted: - # - # hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1) - # hash[0] = 0 - # hash # => {"a"=>1, 0=>0} - # - # but this class is intended for use cases where strings or symbols are the - # expected keys and it is convenient to understand both as the same. For - # example the +params+ hash in Ruby on Rails. - # - # Note that core extensions define Hash#with_indifferent_access: - # - # rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access - # - # which may be handy. - # - # To access this class outside of Rails, require the core extension with: - # - # require "active_support/core_ext/hash/indifferent_access" - # - # which will, in turn, require this file. - class HashWithIndifferentAccess < Hash - # Returns +true+ so that Array#extract_options! finds members of - # this class. - def extractable_options? - true - end - - def with_indifferent_access - dup - end - - def nested_under_indifferent_access - self - end - - def initialize(constructor = {}) - if constructor.respond_to?(:to_hash) - super() - update(constructor) - - hash = constructor.to_hash - self.default = hash.default if hash.default - self.default_proc = hash.default_proc if hash.default_proc - else - super(constructor) - end - end - - def self.[](*args) - new.merge!(Hash[*args]) - end - - alias_method :regular_writer, :[]= unless method_defined?(:regular_writer) - alias_method :regular_update, :update unless method_defined?(:regular_update) - - # Assigns a new value to the hash: - # - # hash = ActiveSupport::HashWithIndifferentAccess.new - # hash[:key] = 'value' - # - # This value can be later fetched using either +:key+ or 'key'. - def []=(key, value) - regular_writer(convert_key(key), convert_value(value, for: :assignment)) - end - - alias_method :store, :[]= - - # Updates the receiver in-place, merging in the hash passed as argument: - # - # hash_1 = ActiveSupport::HashWithIndifferentAccess.new - # hash_1[:key] = 'value' - # - # hash_2 = ActiveSupport::HashWithIndifferentAccess.new - # hash_2[:key] = 'New Value!' - # - # hash_1.update(hash_2) # => {"key"=>"New Value!"} - # - # The argument can be either an - # ActiveSupport::HashWithIndifferentAccess or a regular +Hash+. - # In either case the merge respects the semantics of indifferent access. - # - # If the argument is a regular hash with keys +:key+ and +"key"+ only one - # of the values end up in the receiver, but which one is unspecified. - # - # When given a block, the value for duplicated keys will be determined - # by the result of invoking the block with the duplicated key, the value - # in the receiver, and the value in +other_hash+. The rules for duplicated - # keys follow the semantics of indifferent access: - # - # hash_1[:key] = 10 - # hash_2['key'] = 12 - # hash_1.update(hash_2) { |key, old, new| old + new } # => {"key"=>22} - def update(other_hash) - if other_hash.is_a? HashWithIndifferentAccess - super(other_hash) - else - other_hash.to_hash.each_pair do |key, value| - if block_given? && key?(key) - value = yield(convert_key(key), self[key], value) - end - regular_writer(convert_key(key), convert_value(value)) - end - self - end - end - - alias_method :merge!, :update - - # Checks the hash for a key matching the argument passed in: - # - # hash = ActiveSupport::HashWithIndifferentAccess.new - # hash['key'] = 'value' - # hash.key?(:key) # => true - # hash.key?('key') # => true - def key?(key) - super(convert_key(key)) - end - - alias_method :include?, :key? - alias_method :has_key?, :key? - alias_method :member?, :key? - - # Same as Hash#[] where the key passed as argument can be - # either a string or a symbol: - # - # counters = ActiveSupport::HashWithIndifferentAccess.new - # counters[:foo] = 1 - # - # counters['foo'] # => 1 - # counters[:foo] # => 1 - # counters[:zoo] # => nil - def [](key) - super(convert_key(key)) - end - - # Same as Hash#fetch where the key passed as argument can be - # either a string or a symbol: - # - # counters = ActiveSupport::HashWithIndifferentAccess.new - # counters[:foo] = 1 - # - # counters.fetch('foo') # => 1 - # counters.fetch(:bar, 0) # => 0 - # counters.fetch(:bar) { |key| 0 } # => 0 - # counters.fetch(:zoo) # => KeyError: key not found: "zoo" - def fetch(key, *extras) - super(convert_key(key), *extras) - end - - if Hash.new.respond_to?(:dig) - # Same as Hash#dig where the key passed as argument can be - # either a string or a symbol: - # - # counters = ActiveSupport::HashWithIndifferentAccess.new - # counters[:foo] = { bar: 1 } - # - # counters.dig('foo', 'bar') # => 1 - # counters.dig(:foo, :bar) # => 1 - # counters.dig(:zoo) # => nil - def dig(*args) - args[0] = convert_key(args[0]) if args.size > 0 - super(*args) - end - end - - # Same as Hash#default where the key passed as argument can be - # either a string or a symbol: - # - # hash = ActiveSupport::HashWithIndifferentAccess.new(1) - # hash.default # => 1 - # - # hash = ActiveSupport::HashWithIndifferentAccess.new { |hash, key| key } - # hash.default # => nil - # hash.default('foo') # => 'foo' - # hash.default(:foo) # => 'foo' - def default(*args) - super(*args.map { |arg| convert_key(arg) }) - end - - # Returns an array of the values at the specified indices: - # - # hash = ActiveSupport::HashWithIndifferentAccess.new - # hash[:a] = 'x' - # hash[:b] = 'y' - # hash.values_at('a', 'b') # => ["x", "y"] - def values_at(*indices) - indices.collect { |key| self[convert_key(key)] } - end - - # Returns a shallow copy of the hash. - # - # hash = ActiveSupport::HashWithIndifferentAccess.new({ a: { b: 'b' } }) - # dup = hash.dup - # dup[:a][:c] = 'c' - # - # hash[:a][:c] # => "c" - # dup[:a][:c] # => "c" - def dup - self.class.new(self).tap do |new_hash| - set_defaults(new_hash) - end - end - - # This method has the same semantics of +update+, except it does not - # modify the receiver but rather returns a new hash with indifferent - # access with the result of the merge. - def merge(hash, &block) - dup.update(hash, &block) - end - - # Like +merge+ but the other way around: Merges the receiver into the - # argument and returns a new hash with indifferent access as result: - # - # hash = ActiveSupport::HashWithIndifferentAccess.new - # hash['a'] = nil - # hash.reverse_merge(a: 0, b: 1) # => {"a"=>nil, "b"=>1} - def reverse_merge(other_hash) - super(self.class.new(other_hash)) - end - - # Same semantics as +reverse_merge+ but modifies the receiver in-place. - def reverse_merge!(other_hash) - replace(reverse_merge(other_hash)) - end - - # Replaces the contents of this hash with other_hash. - # - # h = { "a" => 100, "b" => 200 } - # h.replace({ "c" => 300, "d" => 400 }) # => {"c"=>300, "d"=>400} - def replace(other_hash) - super(self.class.new(other_hash)) - end - - # Removes the specified key from the hash. - def delete(key) - super(convert_key(key)) - end - - def stringify_keys!; self end - def deep_stringify_keys!; self end - def stringify_keys; dup end - def deep_stringify_keys; dup end - undef :symbolize_keys! - undef :deep_symbolize_keys! - def symbolize_keys; to_hash.symbolize_keys! end - def deep_symbolize_keys; to_hash.deep_symbolize_keys! end - def to_options!; self end - - def select(*args, &block) - return to_enum(:select) unless block_given? - dup.tap { |hash| hash.select!(*args, &block) } - end - - def reject(*args, &block) - return to_enum(:reject) unless block_given? - dup.tap { |hash| hash.reject!(*args, &block) } - end - - def transform_values(*args, &block) - return to_enum(:transform_values) unless block_given? - dup.tap { |hash| hash.transform_values!(*args, &block) } - end - - def compact - dup.tap(&:compact!) - end - - # Convert to a regular hash with string keys. - def to_hash - _new_hash = Hash.new - set_defaults(_new_hash) - - each do |key, value| - _new_hash[key] = convert_value(value, for: :to_hash) - end - _new_hash - end - - private - def convert_key(key) # :doc: - key.kind_of?(Symbol) ? key.to_s : key - end - - def convert_value(value, options = {}) # :doc: - if value.is_a? Hash - if options[:for] == :to_hash - value.to_hash - else - value.nested_under_indifferent_access - end - elsif value.is_a?(Array) - if options[:for] != :assignment || value.frozen? - value = value.dup - end - value.map! { |e| convert_value(e, options) } - else - value - end - end - - def set_defaults(target) # :doc: - if default_proc - target.default_proc = default_proc.dup - else - target.default = default - end - end - end -end - -# :stopdoc: - -HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/i18n.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/i18n.rb deleted file mode 100644 index f0408f429c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/i18n.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "active_support/core_ext/hash/deep_merge" -require "active_support/core_ext/hash/except" -require "active_support/core_ext/hash/slice" -begin - require "i18n" -rescue LoadError => e - $stderr.puts "The i18n gem is not available. Please add it to your Gemfile and run bundle install" - raise e -end -require "active_support/lazy_load_hooks" - -ActiveSupport.run_load_hooks(:i18n) -I18n.load_path << "#{File.dirname(__FILE__)}/locale/en.yml" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/i18n_railtie.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/i18n_railtie.rb deleted file mode 100644 index f9e1937da5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/i18n_railtie.rb +++ /dev/null @@ -1,120 +0,0 @@ -require "active_support" -require "active_support/file_update_checker" -require "active_support/core_ext/array/wrap" - -# :enddoc: - -module I18n - class Railtie < Rails::Railtie - config.i18n = ActiveSupport::OrderedOptions.new - config.i18n.railties_load_path = [] - config.i18n.load_path = [] - config.i18n.fallbacks = ActiveSupport::OrderedOptions.new - - # Set the i18n configuration after initialization since a lot of - # configuration is still usually done in application initializers. - config.after_initialize do |app| - I18n::Railtie.initialize_i18n(app) - end - - # Trigger i18n config before any eager loading has happened - # so it's ready if any classes require it when eager loaded. - config.before_eager_load do |app| - I18n::Railtie.initialize_i18n(app) - end - - @i18n_inited = false - - # Setup i18n configuration. - def self.initialize_i18n(app) - return if @i18n_inited - - fallbacks = app.config.i18n.delete(:fallbacks) - - # Avoid issues with setting the default_locale by disabling available locales - # check while configuring. - enforce_available_locales = app.config.i18n.delete(:enforce_available_locales) - enforce_available_locales = I18n.enforce_available_locales if enforce_available_locales.nil? - I18n.enforce_available_locales = false - - reloadable_paths = [] - app.config.i18n.each do |setting, value| - case setting - when :railties_load_path - reloadable_paths = value - app.config.i18n.load_path.unshift(*value.map(&:existent).flatten) - when :load_path - I18n.load_path += value - else - I18n.send("#{setting}=", value) - end - end - - init_fallbacks(fallbacks) if fallbacks && validate_fallbacks(fallbacks) - - # Restore available locales check so it will take place from now on. - I18n.enforce_available_locales = enforce_available_locales - - directories = watched_dirs_with_extensions(reloadable_paths) - reloader = app.config.file_watcher.new(I18n.load_path.dup, directories) do - I18n.load_path.keep_if { |p| File.exist?(p) } - I18n.load_path |= reloadable_paths.map(&:existent).flatten - - I18n.reload! - end - - app.reloaders << reloader - app.reloader.to_run do - reloader.execute_if_updated { require_unload_lock! } - # TODO: remove the following line as soon as the return value of - # callbacks is ignored, that is, returning `false` does not - # display a deprecation warning or halts the callback chain. - true - end - reloader.execute - - @i18n_inited = true - end - - def self.include_fallbacks_module - I18n.backend.class.include(I18n::Backend::Fallbacks) - end - - def self.init_fallbacks(fallbacks) - include_fallbacks_module - - args = \ - case fallbacks - when ActiveSupport::OrderedOptions - [*(fallbacks[:defaults] || []) << fallbacks[:map]].compact - when Hash, Array - Array.wrap(fallbacks) - else # TrueClass - [I18n.default_locale] - end - - if args.empty? || args.first.is_a?(Hash) - args.unshift I18n.default_locale - end - - I18n.fallbacks = I18n::Locale::Fallbacks.new(*args) - end - - def self.validate_fallbacks(fallbacks) - case fallbacks - when ActiveSupport::OrderedOptions - !fallbacks.empty? - when TrueClass, Array, Hash - true - else - raise "Unexpected fallback type #{fallbacks.inspect}" - end - end - - def self.watched_dirs_with_extensions(paths) - paths.each_with_object({}) do |path, result| - result[path.absolute_current] = path.extensions - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflections.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflections.rb deleted file mode 100644 index afa7d1f325..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflections.rb +++ /dev/null @@ -1,70 +0,0 @@ -require "active_support/inflector/inflections" - -#-- -# Defines the standard inflection rules. These are the starting point for -# new projects and are not considered complete. The current set of inflection -# rules is frozen. This means, we do not change them to become more complete. -# This is a safety measure to keep existing applications from breaking. -#++ -module ActiveSupport - Inflector.inflections(:en) do |inflect| - inflect.plural(/$/, "s") - inflect.plural(/s$/i, "s") - inflect.plural(/^(ax|test)is$/i, '\1es') - inflect.plural(/(octop|vir)us$/i, '\1i') - inflect.plural(/(octop|vir)i$/i, '\1i') - inflect.plural(/(alias|status)$/i, '\1es') - inflect.plural(/(bu)s$/i, '\1ses') - inflect.plural(/(buffal|tomat)o$/i, '\1oes') - inflect.plural(/([ti])um$/i, '\1a') - inflect.plural(/([ti])a$/i, '\1a') - inflect.plural(/sis$/i, "ses") - inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves') - inflect.plural(/(hive)$/i, '\1s') - inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies') - inflect.plural(/(x|ch|ss|sh)$/i, '\1es') - inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices') - inflect.plural(/^(m|l)ouse$/i, '\1ice') - inflect.plural(/^(m|l)ice$/i, '\1ice') - inflect.plural(/^(ox)$/i, '\1en') - inflect.plural(/^(oxen)$/i, '\1') - inflect.plural(/(quiz)$/i, '\1zes') - - inflect.singular(/s$/i, "") - inflect.singular(/(ss)$/i, '\1') - inflect.singular(/(n)ews$/i, '\1ews') - inflect.singular(/([ti])a$/i, '\1um') - inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis') - inflect.singular(/(^analy)(sis|ses)$/i, '\1sis') - inflect.singular(/([^f])ves$/i, '\1fe') - inflect.singular(/(hive)s$/i, '\1') - inflect.singular(/(tive)s$/i, '\1') - inflect.singular(/([lr])ves$/i, '\1f') - inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y') - inflect.singular(/(s)eries$/i, '\1eries') - inflect.singular(/(m)ovies$/i, '\1ovie') - inflect.singular(/(x|ch|ss|sh)es$/i, '\1') - inflect.singular(/^(m|l)ice$/i, '\1ouse') - inflect.singular(/(bus)(es)?$/i, '\1') - inflect.singular(/(o)es$/i, '\1') - inflect.singular(/(shoe)s$/i, '\1') - inflect.singular(/(cris|test)(is|es)$/i, '\1is') - inflect.singular(/^(a)x[ie]s$/i, '\1xis') - inflect.singular(/(octop|vir)(us|i)$/i, '\1us') - inflect.singular(/(alias|status)(es)?$/i, '\1') - inflect.singular(/^(ox)en/i, '\1') - inflect.singular(/(vert|ind)ices$/i, '\1ex') - inflect.singular(/(matr)ices$/i, '\1ix') - inflect.singular(/(quiz)zes$/i, '\1') - inflect.singular(/(database)s$/i, '\1') - - inflect.irregular("person", "people") - inflect.irregular("man", "men") - inflect.irregular("child", "children") - inflect.irregular("sex", "sexes") - inflect.irregular("move", "moves") - inflect.irregular("zombie", "zombies") - - inflect.uncountable(%w(equipment information rice money species series fish sheep jeans police)) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector.rb deleted file mode 100644 index 48631b16a8..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector.rb +++ /dev/null @@ -1,7 +0,0 @@ -# in case active_support/inflector is required without the rest of active_support -require "active_support/inflector/inflections" -require "active_support/inflector/transliterate" -require "active_support/inflector/methods" - -require "active_support/inflections" -require "active_support/core_ext/string/inflections" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/inflections.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/inflections.rb deleted file mode 100644 index c47a2e34e1..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/inflections.rb +++ /dev/null @@ -1,244 +0,0 @@ -require "concurrent/map" -require "active_support/core_ext/array/prepend_and_append" -require "active_support/core_ext/regexp" -require "active_support/i18n" - -module ActiveSupport - module Inflector - extend self - - # A singleton instance of this class is yielded by Inflector.inflections, - # which can then be used to specify additional inflection rules. If passed - # an optional locale, rules for other languages can be specified. The - # default locale is :en. Only rules for English are provided. - # - # ActiveSupport::Inflector.inflections(:en) do |inflect| - # inflect.plural /^(ox)$/i, '\1\2en' - # inflect.singular /^(ox)en/i, '\1' - # - # inflect.irregular 'octopus', 'octopi' - # - # inflect.uncountable 'equipment' - # end - # - # New rules are added at the top. So in the example above, the irregular - # rule for octopus will now be the first of the pluralization and - # singularization rules that is runs. This guarantees that your rules run - # before any of the rules that may already have been loaded. - class Inflections - @__instance__ = Concurrent::Map.new - - class Uncountables < Array - def initialize - @regex_array = [] - super - end - - def delete(entry) - super entry - @regex_array.delete(to_regex(entry)) - end - - def <<(*word) - add(word) - end - - def add(words) - words = words.flatten.map(&:downcase) - concat(words) - @regex_array += words.map { |word| to_regex(word) } - self - end - - def uncountable?(str) - @regex_array.any? { |regex| regex.match? str } - end - - private - def to_regex(string) - /\b#{::Regexp.escape(string)}\Z/i - end - end - - def self.instance(locale = :en) - @__instance__[locale] ||= new - end - - attr_reader :plurals, :singulars, :uncountables, :humans, :acronyms, :acronym_regex - - def initialize - @plurals, @singulars, @uncountables, @humans, @acronyms, @acronym_regex = [], [], Uncountables.new, [], {}, /(?=a)b/ - end - - # Private, for the test suite. - def initialize_dup(orig) # :nodoc: - %w(plurals singulars uncountables humans acronyms acronym_regex).each do |scope| - instance_variable_set("@#{scope}", orig.send(scope).dup) - end - end - - # Specifies a new acronym. An acronym must be specified as it will appear - # in a camelized string. An underscore string that contains the acronym - # will retain the acronym when passed to +camelize+, +humanize+, or - # +titleize+. A camelized string that contains the acronym will maintain - # the acronym when titleized or humanized, and will convert the acronym - # into a non-delimited single lowercase word when passed to +underscore+. - # - # acronym 'HTML' - # titleize 'html' # => 'HTML' - # camelize 'html' # => 'HTML' - # underscore 'MyHTML' # => 'my_html' - # - # The acronym, however, must occur as a delimited unit and not be part of - # another word for conversions to recognize it: - # - # acronym 'HTTP' - # camelize 'my_http_delimited' # => 'MyHTTPDelimited' - # camelize 'https' # => 'Https', not 'HTTPs' - # underscore 'HTTPS' # => 'http_s', not 'https' - # - # acronym 'HTTPS' - # camelize 'https' # => 'HTTPS' - # underscore 'HTTPS' # => 'https' - # - # Note: Acronyms that are passed to +pluralize+ will no longer be - # recognized, since the acronym will not occur as a delimited unit in the - # pluralized result. To work around this, you must specify the pluralized - # form as an acronym as well: - # - # acronym 'API' - # camelize(pluralize('api')) # => 'Apis' - # - # acronym 'APIs' - # camelize(pluralize('api')) # => 'APIs' - # - # +acronym+ may be used to specify any word that contains an acronym or - # otherwise needs to maintain a non-standard capitalization. The only - # restriction is that the word must begin with a capital letter. - # - # acronym 'RESTful' - # underscore 'RESTful' # => 'restful' - # underscore 'RESTfulController' # => 'restful_controller' - # titleize 'RESTfulController' # => 'RESTful Controller' - # camelize 'restful' # => 'RESTful' - # camelize 'restful_controller' # => 'RESTfulController' - # - # acronym 'McDonald' - # underscore 'McDonald' # => 'mcdonald' - # camelize 'mcdonald' # => 'McDonald' - def acronym(word) - @acronyms[word.downcase] = word - @acronym_regex = /#{@acronyms.values.join("|")}/ - end - - # Specifies a new pluralization rule and its replacement. The rule can - # either be a string or a regular expression. The replacement should - # always be a string that may include references to the matched data from - # the rule. - def plural(rule, replacement) - @uncountables.delete(rule) if rule.is_a?(String) - @uncountables.delete(replacement) - @plurals.prepend([rule, replacement]) - end - - # Specifies a new singularization rule and its replacement. The rule can - # either be a string or a regular expression. The replacement should - # always be a string that may include references to the matched data from - # the rule. - def singular(rule, replacement) - @uncountables.delete(rule) if rule.is_a?(String) - @uncountables.delete(replacement) - @singulars.prepend([rule, replacement]) - end - - # Specifies a new irregular that applies to both pluralization and - # singularization at the same time. This can only be used for strings, not - # regular expressions. You simply pass the irregular in singular and - # plural form. - # - # irregular 'octopus', 'octopi' - # irregular 'person', 'people' - def irregular(singular, plural) - @uncountables.delete(singular) - @uncountables.delete(plural) - - s0 = singular[0] - srest = singular[1..-1] - - p0 = plural[0] - prest = plural[1..-1] - - if s0.upcase == p0.upcase - plural(/(#{s0})#{srest}$/i, '\1' + prest) - plural(/(#{p0})#{prest}$/i, '\1' + prest) - - singular(/(#{s0})#{srest}$/i, '\1' + srest) - singular(/(#{p0})#{prest}$/i, '\1' + srest) - else - plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest) - plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest) - plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest) - plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest) - - singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest) - singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest) - singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest) - singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest) - end - end - - # Specifies words that are uncountable and should not be inflected. - # - # uncountable 'money' - # uncountable 'money', 'information' - # uncountable %w( money information rice ) - def uncountable(*words) - @uncountables.add(words) - end - - # Specifies a humanized form of a string by a regular expression rule or - # by a string mapping. When using a regular expression based replacement, - # the normal humanize formatting is called after the replacement. When a - # string is used, the human form should be specified as desired (example: - # 'The name', not 'the_name'). - # - # human /_cnt$/i, '\1_count' - # human 'legacy_col_person_name', 'Name' - def human(rule, replacement) - @humans.prepend([rule, replacement]) - end - - # Clears the loaded inflections within a given scope (default is - # :all). Give the scope as a symbol of the inflection type, the - # options are: :plurals, :singulars, :uncountables, - # :humans. - # - # clear :all - # clear :plurals - def clear(scope = :all) - case scope - when :all - @plurals, @singulars, @uncountables, @humans = [], [], Uncountables.new, [] - else - instance_variable_set "@#{scope}", [] - end - end - end - - # Yields a singleton instance of Inflector::Inflections so you can specify - # additional inflector rules. If passed an optional locale, rules for other - # languages can be specified. If not specified, defaults to :en. - # Only rules for English are provided. - # - # ActiveSupport::Inflector.inflections(:en) do |inflect| - # inflect.uncountable 'rails' - # end - def inflections(locale = :en) - if block_given? - yield Inflections.instance(locale) - else - Inflections.instance(locale) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/methods.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/methods.rb deleted file mode 100644 index 51c221ac0e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/methods.rb +++ /dev/null @@ -1,391 +0,0 @@ -require "active_support/inflections" -require "active_support/core_ext/regexp" - -module ActiveSupport - # The Inflector transforms words from singular to plural, class names to table - # names, modularized class names to ones without, and class names to foreign - # keys. The default inflections for pluralization, singularization, and - # uncountable words are kept in inflections.rb. - # - # The Rails core team has stated patches for the inflections library will not - # be accepted in order to avoid breaking legacy applications which may be - # relying on errant inflections. If you discover an incorrect inflection and - # require it for your application or wish to define rules for languages other - # than English, please correct or add them yourself (explained below). - module Inflector - extend self - - # Returns the plural form of the word in the string. - # - # If passed an optional +locale+ parameter, the word will be - # pluralized using rules defined for that language. By default, - # this parameter is set to :en. - # - # pluralize('post') # => "posts" - # pluralize('octopus') # => "octopi" - # pluralize('sheep') # => "sheep" - # pluralize('words') # => "words" - # pluralize('CamelOctopus') # => "CamelOctopi" - # pluralize('ley', :es) # => "leyes" - def pluralize(word, locale = :en) - apply_inflections(word, inflections(locale).plurals) - end - - # The reverse of #pluralize, returns the singular form of a word in a - # string. - # - # If passed an optional +locale+ parameter, the word will be - # singularized using rules defined for that language. By default, - # this parameter is set to :en. - # - # singularize('posts') # => "post" - # singularize('octopi') # => "octopus" - # singularize('sheep') # => "sheep" - # singularize('word') # => "word" - # singularize('CamelOctopi') # => "CamelOctopus" - # singularize('leyes', :es) # => "ley" - def singularize(word, locale = :en) - apply_inflections(word, inflections(locale).singulars) - end - - # Converts strings to UpperCamelCase. - # If the +uppercase_first_letter+ parameter is set to false, then produces - # lowerCamelCase. - # - # Also converts '/' to '::' which is useful for converting - # paths to namespaces. - # - # camelize('active_model') # => "ActiveModel" - # camelize('active_model', false) # => "activeModel" - # camelize('active_model/errors') # => "ActiveModel::Errors" - # camelize('active_model/errors', false) # => "activeModel::Errors" - # - # As a rule of thumb you can think of +camelize+ as the inverse of - # #underscore, though there are cases where that does not hold: - # - # camelize(underscore('SSLError')) # => "SslError" - def camelize(term, uppercase_first_letter = true) - string = term.to_s - if uppercase_first_letter - string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize } - else - string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { |match| match.downcase } - end - string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" } - string.gsub!("/".freeze, "::".freeze) - string - end - - # Makes an underscored, lowercase form from the expression in the string. - # - # Changes '::' to '/' to convert namespaces to paths. - # - # underscore('ActiveModel') # => "active_model" - # underscore('ActiveModel::Errors') # => "active_model/errors" - # - # As a rule of thumb you can think of +underscore+ as the inverse of - # #camelize, though there are cases where that does not hold: - # - # camelize(underscore('SSLError')) # => "SslError" - def underscore(camel_cased_word) - return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word) - word = camel_cased_word.to_s.gsub("::".freeze, "/".freeze) - word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1 && '_'.freeze }#{$2.downcase}" } - word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2'.freeze) - word.gsub!(/([a-z\d])([A-Z])/, '\1_\2'.freeze) - word.tr!("-".freeze, "_".freeze) - word.downcase! - word - end - - # Tweaks an attribute name for display to end users. - # - # Specifically, performs these transformations: - # - # * Applies human inflection rules to the argument. - # * Deletes leading underscores, if any. - # * Removes a "_id" suffix if present. - # * Replaces underscores with spaces, if any. - # * Downcases all words except acronyms. - # * Capitalizes the first word. - # - # The capitalization of the first word can be turned off by setting the - # +:capitalize+ option to false (default is true). - # - # humanize('employee_salary') # => "Employee salary" - # humanize('author_id') # => "Author" - # humanize('author_id', capitalize: false) # => "author" - # humanize('_id') # => "Id" - # - # If "SSL" was defined to be an acronym: - # - # humanize('ssl_error') # => "SSL error" - # - def humanize(lower_case_and_underscored_word, options = {}) - result = lower_case_and_underscored_word.to_s.dup - - inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) } - - result.sub!(/\A_+/, "".freeze) - result.sub!(/_id\z/, "".freeze) - result.tr!("_".freeze, " ".freeze) - - result.gsub!(/([a-z\d]*)/i) do |match| - "#{inflections.acronyms[match] || match.downcase}" - end - - if options.fetch(:capitalize, true) - result.sub!(/\A\w/) { |match| match.upcase } - end - - result - end - - # Converts just the first character to uppercase. - # - # upcase_first('what a Lovely Day') # => "What a Lovely Day" - # upcase_first('w') # => "W" - # upcase_first('') # => "" - def upcase_first(string) - string.length > 0 ? string[0].upcase.concat(string[1..-1]) : "" - end - - # Capitalizes all the words and replaces some characters in the string to - # create a nicer looking title. +titleize+ is meant for creating pretty - # output. It is not used in the Rails internals. - # - # +titleize+ is also aliased as +titlecase+. - # - # titleize('man from the boondocks') # => "Man From The Boondocks" - # titleize('x-men: the last stand') # => "X Men: The Last Stand" - # titleize('TheManWithoutAPast') # => "The Man Without A Past" - # titleize('raiders_of_the_lost_ark') # => "Raiders Of The Lost Ark" - def titleize(word) - humanize(underscore(word)).gsub(/\b(? "raw_scaled_scorers" - # tableize('ham_and_egg') # => "ham_and_eggs" - # tableize('fancyCategory') # => "fancy_categories" - def tableize(class_name) - pluralize(underscore(class_name)) - end - - # Creates a class name from a plural table name like Rails does for table - # names to models. Note that this returns a string and not a Class (To - # convert to an actual class follow +classify+ with #constantize). - # - # classify('ham_and_eggs') # => "HamAndEgg" - # classify('posts') # => "Post" - # - # Singular names are not handled correctly: - # - # classify('calculus') # => "Calculus" - def classify(table_name) - # strip out any leading schema name - camelize(singularize(table_name.to_s.sub(/.*\./, "".freeze))) - end - - # Replaces underscores with dashes in the string. - # - # dasherize('puni_puni') # => "puni-puni" - def dasherize(underscored_word) - underscored_word.tr("_".freeze, "-".freeze) - end - - # Removes the module part from the expression in the string. - # - # demodulize('ActiveSupport::Inflector::Inflections') # => "Inflections" - # demodulize('Inflections') # => "Inflections" - # demodulize('::Inflections') # => "Inflections" - # demodulize('') # => "" - # - # See also #deconstantize. - def demodulize(path) - path = path.to_s - if i = path.rindex("::") - path[(i + 2)..-1] - else - path - end - end - - # Removes the rightmost segment from the constant expression in the string. - # - # deconstantize('Net::HTTP') # => "Net" - # deconstantize('::Net::HTTP') # => "::Net" - # deconstantize('String') # => "" - # deconstantize('::String') # => "" - # deconstantize('') # => "" - # - # See also #demodulize. - def deconstantize(path) - path.to_s[0, path.rindex("::") || 0] # implementation based on the one in facets' Module#spacename - end - - # Creates a foreign key name from a class name. - # +separate_class_name_and_id_with_underscore+ sets whether - # the method should put '_' between the name and 'id'. - # - # foreign_key('Message') # => "message_id" - # foreign_key('Message', false) # => "messageid" - # foreign_key('Admin::Post') # => "post_id" - def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) - underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id") - end - - # Tries to find a constant with the name specified in the argument string. - # - # constantize('Module') # => Module - # constantize('Foo::Bar') # => Foo::Bar - # - # The name is assumed to be the one of a top-level constant, no matter - # whether it starts with "::" or not. No lexical context is taken into - # account: - # - # C = 'outside' - # module M - # C = 'inside' - # C # => 'inside' - # constantize('C') # => 'outside', same as ::C - # end - # - # NameError is raised when the name is not in CamelCase or the constant is - # unknown. - def constantize(camel_cased_word) - names = camel_cased_word.split("::".freeze) - - # Trigger a built-in NameError exception including the ill-formed constant in the message. - Object.const_get(camel_cased_word) if names.empty? - - # Remove the first blank element in case of '::ClassName' notation. - names.shift if names.size > 1 && names.first.empty? - - names.inject(Object) do |constant, name| - if constant == Object - constant.const_get(name) - else - candidate = constant.const_get(name) - next candidate if constant.const_defined?(name, false) - next candidate unless Object.const_defined?(name) - - # Go down the ancestors to check if it is owned directly. The check - # stops when we reach Object or the end of ancestors tree. - constant = constant.ancestors.inject(constant) do |const, ancestor| - break const if ancestor == Object - break ancestor if ancestor.const_defined?(name, false) - const - end - - # owner is in Object, so raise - constant.const_get(name, false) - end - end - end - - # Tries to find a constant with the name specified in the argument string. - # - # safe_constantize('Module') # => Module - # safe_constantize('Foo::Bar') # => Foo::Bar - # - # The name is assumed to be the one of a top-level constant, no matter - # whether it starts with "::" or not. No lexical context is taken into - # account: - # - # C = 'outside' - # module M - # C = 'inside' - # C # => 'inside' - # safe_constantize('C') # => 'outside', same as ::C - # end - # - # +nil+ is returned when the name is not in CamelCase or the constant (or - # part of it) is unknown. - # - # safe_constantize('blargle') # => nil - # safe_constantize('UnknownModule') # => nil - # safe_constantize('UnknownModule::Foo::Bar') # => nil - def safe_constantize(camel_cased_word) - constantize(camel_cased_word) - rescue NameError => e - raise if e.name && !(camel_cased_word.to_s.split("::").include?(e.name.to_s) || - e.name.to_s == camel_cased_word.to_s) - rescue ArgumentError => e - raise unless /not missing constant #{const_regexp(camel_cased_word)}!$/.match?(e.message) - end - - # Returns the suffix that should be added to a number to denote the position - # in an ordered sequence such as 1st, 2nd, 3rd, 4th. - # - # ordinal(1) # => "st" - # ordinal(2) # => "nd" - # ordinal(1002) # => "nd" - # ordinal(1003) # => "rd" - # ordinal(-11) # => "th" - # ordinal(-1021) # => "st" - def ordinal(number) - abs_number = number.to_i.abs - - if (11..13).include?(abs_number % 100) - "th" - else - case abs_number % 10 - when 1; "st" - when 2; "nd" - when 3; "rd" - else "th" - end - end - end - - # Turns a number into an ordinal string used to denote the position in an - # ordered sequence such as 1st, 2nd, 3rd, 4th. - # - # ordinalize(1) # => "1st" - # ordinalize(2) # => "2nd" - # ordinalize(1002) # => "1002nd" - # ordinalize(1003) # => "1003rd" - # ordinalize(-11) # => "-11th" - # ordinalize(-1021) # => "-1021st" - def ordinalize(number) - "#{number}#{ordinal(number)}" - end - - private - - # Mounts a regular expression, returned as a string to ease interpolation, - # that will match part by part the given constant. - # - # const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?" - # const_regexp("::") # => "::" - def const_regexp(camel_cased_word) - parts = camel_cased_word.split("::".freeze) - - return Regexp.escape(camel_cased_word) if parts.blank? - - last = parts.pop - - parts.reverse.inject(last) do |acc, part| - part.empty? ? acc : "#{part}(::#{acc})?" - end - end - - # Applies inflection rules for +singularize+ and +pluralize+. - # - # apply_inflections('post', inflections.plurals) # => "posts" - # apply_inflections('posts', inflections.singulars) # => "post" - def apply_inflections(word, rules) - result = word.to_s.dup - - if word.empty? || inflections.uncountables.uncountable?(result) - result - else - rules.each { |(rule, replacement)| break if result.sub!(rule, replacement) } - result - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/transliterate.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/transliterate.rb deleted file mode 100644 index de6dd2720b..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/inflector/transliterate.rb +++ /dev/null @@ -1,109 +0,0 @@ -require "active_support/core_ext/string/multibyte" -require "active_support/i18n" - -module ActiveSupport - module Inflector - # Replaces non-ASCII characters with an ASCII approximation, or if none - # exists, a replacement character which defaults to "?". - # - # transliterate('Ærøskøbing') - # # => "AEroskobing" - # - # Default approximations are provided for Western/Latin characters, - # e.g, "ø", "ñ", "é", "ß", etc. - # - # This method is I18n aware, so you can set up custom approximations for a - # locale. This can be useful, for example, to transliterate German's "ü" - # and "ö" to "ue" and "oe", or to add support for transliterating Russian - # to ASCII. - # - # In order to make your custom transliterations available, you must set - # them as the i18n.transliterate.rule i18n key: - # - # # Store the transliterations in locales/de.yml - # i18n: - # transliterate: - # rule: - # ü: "ue" - # ö: "oe" - # - # # Or set them using Ruby - # I18n.backend.store_translations(:de, i18n: { - # transliterate: { - # rule: { - # 'ü' => 'ue', - # 'ö' => 'oe' - # } - # } - # }) - # - # The value for i18n.transliterate.rule can be a simple Hash that - # maps characters to ASCII approximations as shown above, or, for more - # complex requirements, a Proc: - # - # I18n.backend.store_translations(:de, i18n: { - # transliterate: { - # rule: ->(string) { MyTransliterator.transliterate(string) } - # } - # }) - # - # Now you can have different transliterations for each locale: - # - # I18n.locale = :en - # transliterate('Jürgen') - # # => "Jurgen" - # - # I18n.locale = :de - # transliterate('Jürgen') - # # => "Juergen" - def transliterate(string, replacement = "?".freeze) - raise ArgumentError, "Can only transliterate strings. Received #{string.class.name}" unless string.is_a?(String) - - I18n.transliterate(ActiveSupport::Multibyte::Unicode.normalize( - ActiveSupport::Multibyte::Unicode.tidy_bytes(string), :c), - replacement: replacement) - end - - # Replaces special characters in a string so that it may be used as part of - # a 'pretty' URL. - # - # parameterize("Donald E. Knuth") # => "donald-e-knuth" - # parameterize("^trés|Jolie-- ") # => "tres-jolie" - # - # To use a custom separator, override the `separator` argument. - # - # parameterize("Donald E. Knuth", separator: '_') # => "donald_e_knuth" - # parameterize("^trés|Jolie-- ", separator: '_') # => "tres_jolie" - # - # To preserve the case of the characters in a string, use the `preserve_case` argument. - # - # parameterize("Donald E. Knuth", preserve_case: true) # => "Donald-E-Knuth" - # parameterize("^trés|Jolie-- ", preserve_case: true) # => "tres-Jolie" - # - def parameterize(string, separator: "-", preserve_case: false) - # Replace accented chars with their ASCII equivalents. - parameterized_string = transliterate(string) - - # Turn unwanted chars into the separator. - parameterized_string.gsub!(/[^a-z0-9\-_]+/i, separator) - - unless separator.nil? || separator.empty? - if separator == "-".freeze - re_duplicate_separator = /-{2,}/ - re_leading_trailing_separator = /^-|-$/i - else - re_sep = Regexp.escape(separator) - re_duplicate_separator = /#{re_sep}{2,}/ - re_leading_trailing_separator = /^#{re_sep}|#{re_sep}$/i - end - # No more than one of the separator in a row. - parameterized_string.gsub!(re_duplicate_separator, separator) - # Remove leading/trailing separator. - parameterized_string.gsub!(re_leading_trailing_separator, "".freeze) - end - - parameterized_string.downcase! unless preserve_case - parameterized_string - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/json.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/json.rb deleted file mode 100644 index da938d1555..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/json.rb +++ /dev/null @@ -1,2 +0,0 @@ -require "active_support/json/decoding" -require "active_support/json/encoding" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/json/decoding.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/json/decoding.rb deleted file mode 100644 index f487fa0c65..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/json/decoding.rb +++ /dev/null @@ -1,74 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/module/delegation" -require "json" - -module ActiveSupport - # Look for and parse json strings that look like ISO 8601 times. - mattr_accessor :parse_json_times - - module JSON - # matches YAML-formatted dates - DATE_REGEX = /^\d{4}-\d{2}-\d{2}$/ - DATETIME_REGEX = /^(?:\d{4}-\d{2}-\d{2}|\d{4}-\d{1,2}-\d{1,2}[T \t]+\d{1,2}:\d{2}:\d{2}(\.[0-9]*)?(([ \t]*)Z|[-+]\d{2}?(:\d{2})?)?)$/ - - class << self - # Parses a JSON string (JavaScript Object Notation) into a hash. - # See http://www.json.org for more info. - # - # ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}") - # => {"team" => "rails", "players" => "36"} - def decode(json) - data = ::JSON.parse(json, quirks_mode: true) - - if ActiveSupport.parse_json_times - convert_dates_from(data) - else - data - end - end - - # Returns the class of the error that will be raised when there is an - # error in decoding JSON. Using this method means you won't directly - # depend on the ActiveSupport's JSON implementation, in case it changes - # in the future. - # - # begin - # obj = ActiveSupport::JSON.decode(some_string) - # rescue ActiveSupport::JSON.parse_error - # Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}") - # end - def parse_error - ::JSON::ParserError - end - - private - - def convert_dates_from(data) - case data - when nil - nil - when DATE_REGEX - begin - Date.parse(data) - rescue ArgumentError - data - end - when DATETIME_REGEX - begin - Time.zone.parse(data) - rescue ArgumentError - data - end - when Array - data.map! { |d| convert_dates_from(d) } - when Hash - data.each do |key, value| - data[key] = convert_dates_from(value) - end - else - data - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/json/encoding.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/json/encoding.rb deleted file mode 100644 index defaf3f395..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/json/encoding.rb +++ /dev/null @@ -1,128 +0,0 @@ -require "active_support/core_ext/object/json" -require "active_support/core_ext/module/delegation" - -module ActiveSupport - class << self - delegate :use_standard_json_time_format, :use_standard_json_time_format=, - :time_precision, :time_precision=, - :escape_html_entities_in_json, :escape_html_entities_in_json=, - :json_encoder, :json_encoder=, - to: :'ActiveSupport::JSON::Encoding' - end - - module JSON - # Dumps objects in JSON (JavaScript Object Notation). - # See http://www.json.org for more info. - # - # ActiveSupport::JSON.encode({ team: 'rails', players: '36' }) - # # => "{\"team\":\"rails\",\"players\":\"36\"}" - def self.encode(value, options = nil) - Encoding.json_encoder.new(options).encode(value) - end - - module Encoding #:nodoc: - class JSONGemEncoder #:nodoc: - attr_reader :options - - def initialize(options = nil) - @options = options || {} - end - - # Encode the given object into a JSON string - def encode(value) - stringify jsonify value.as_json(options.dup) - end - - private - # Rails does more escaping than the JSON gem natively does (we - # escape \u2028 and \u2029 and optionally >, <, & to work around - # certain browser problems). - ESCAPED_CHARS = { - "\u2028" => '\u2028', - "\u2029" => '\u2029', - ">" => '\u003e', - "<" => '\u003c', - "&" => '\u0026', - } - - ESCAPE_REGEX_WITH_HTML_ENTITIES = /[\u2028\u2029><&]/u - ESCAPE_REGEX_WITHOUT_HTML_ENTITIES = /[\u2028\u2029]/u - - # This class wraps all the strings we see and does the extra escaping - class EscapedString < String #:nodoc: - def to_json(*) - if Encoding.escape_html_entities_in_json - super.gsub ESCAPE_REGEX_WITH_HTML_ENTITIES, ESCAPED_CHARS - else - super.gsub ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, ESCAPED_CHARS - end - end - - def to_s - self - end - end - - # Mark these as private so we don't leak encoding-specific constructs - private_constant :ESCAPED_CHARS, :ESCAPE_REGEX_WITH_HTML_ENTITIES, - :ESCAPE_REGEX_WITHOUT_HTML_ENTITIES, :EscapedString - - # Convert an object into a "JSON-ready" representation composed of - # primitives like Hash, Array, String, Numeric, - # and +true+/+false+/+nil+. - # Recursively calls #as_json to the object to recursively build a - # fully JSON-ready object. - # - # This allows developers to implement #as_json without having to - # worry about what base types of objects they are allowed to return - # or having to remember to call #as_json recursively. - # - # Note: the +options+ hash passed to +object.to_json+ is only passed - # to +object.as_json+, not any of this method's recursive +#as_json+ - # calls. - def jsonify(value) - case value - when String - EscapedString.new(value) - when Numeric, NilClass, TrueClass, FalseClass - value.as_json - when Hash - Hash[value.map { |k, v| [jsonify(k), jsonify(v)] }] - when Array - value.map { |v| jsonify(v) } - else - jsonify value.as_json - end - end - - # Encode a "jsonified" Ruby data structure using the JSON gem - def stringify(jsonified) - ::JSON.generate(jsonified, quirks_mode: true, max_nesting: false) - end - end - - class << self - # If true, use ISO 8601 format for dates and times. Otherwise, fall back - # to the Active Support legacy format. - attr_accessor :use_standard_json_time_format - - # If true, encode >, <, & as escaped unicode sequences (e.g. > as \u003e) - # as a safety measure. - attr_accessor :escape_html_entities_in_json - - # Sets the precision of encoded time values. - # Defaults to 3 (equivalent to millisecond precision) - attr_accessor :time_precision - - # Sets the encoder used by Rails to encode Ruby objects into JSON strings - # in +Object#to_json+ and +ActiveSupport::JSON.encode+. - attr_accessor :json_encoder - end - - self.use_standard_json_time_format = true - self.escape_html_entities_in_json = true - self.json_encoder = JSONGemEncoder - self.time_precision = 3 - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/key_generator.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/key_generator.rb deleted file mode 100644 index 23ab804eb1..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/key_generator.rb +++ /dev/null @@ -1,71 +0,0 @@ -require "concurrent/map" -require "openssl" - -module ActiveSupport - # KeyGenerator is a simple wrapper around OpenSSL's implementation of PBKDF2. - # It can be used to derive a number of keys for various purposes from a given secret. - # This lets Rails applications have a single secure secret, but avoid reusing that - # key in multiple incompatible contexts. - class KeyGenerator - def initialize(secret, options = {}) - @secret = secret - # The default iterations are higher than required for our key derivation uses - # on the off chance someone uses this for password storage - @iterations = options[:iterations] || 2**16 - end - - # Returns a derived key suitable for use. The default key_size is chosen - # to be compatible with the default settings of ActiveSupport::MessageVerifier. - # i.e. OpenSSL::Digest::SHA1#block_length - def generate_key(salt, key_size = 64) - OpenSSL::PKCS5.pbkdf2_hmac_sha1(@secret, salt, @iterations, key_size) - end - end - - # CachingKeyGenerator is a wrapper around KeyGenerator which allows users to avoid - # re-executing the key generation process when it's called using the same salt and - # key_size. - class CachingKeyGenerator - def initialize(key_generator) - @key_generator = key_generator - @cache_keys = Concurrent::Map.new - end - - # Returns a derived key suitable for use. - def generate_key(*args) - @cache_keys[args.join] ||= @key_generator.generate_key(*args) - end - end - - class LegacyKeyGenerator # :nodoc: - SECRET_MIN_LENGTH = 30 # Characters - - def initialize(secret) - ensure_secret_secure(secret) - @secret = secret - end - - def generate_key(salt) - @secret - end - - private - - # To prevent users from using something insecure like "Password" we make sure that the - # secret they've provided is at least 30 characters in length. - def ensure_secret_secure(secret) - if secret.blank? - raise ArgumentError, "A secret is required to generate an integrity hash " \ - "for cookie session data. Set a secret_key_base of at least " \ - "#{SECRET_MIN_LENGTH} characters in config/secrets.yml." - end - - if secret.length < SECRET_MIN_LENGTH - raise ArgumentError, "Secret should be something secure, " \ - "like \"#{SecureRandom.hex(16)}\". The value you " \ - "provided, \"#{secret}\", is shorter than the minimum length " \ - "of #{SECRET_MIN_LENGTH} characters." - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/lazy_load_hooks.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/lazy_load_hooks.rb deleted file mode 100644 index 0f17b87987..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/lazy_load_hooks.rb +++ /dev/null @@ -1,76 +0,0 @@ -module ActiveSupport - # lazy_load_hooks allows Rails to lazily load a lot of components and thus - # making the app boot faster. Because of this feature now there is no need to - # require ActiveRecord::Base at boot time purely to apply - # configuration. Instead a hook is registered that applies configuration once - # ActiveRecord::Base is loaded. Here ActiveRecord::Base is - # used as example but this feature can be applied elsewhere too. - # - # Here is an example where +on_load+ method is called to register a hook. - # - # initializer 'active_record.initialize_timezone' do - # ActiveSupport.on_load(:active_record) do - # self.time_zone_aware_attributes = true - # self.default_timezone = :utc - # end - # end - # - # When the entirety of +ActiveRecord::Base+ has been - # evaluated then +run_load_hooks+ is invoked. The very last line of - # +ActiveRecord::Base+ is: - # - # ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base) - module LazyLoadHooks - def self.extended(base) # :nodoc: - base.class_eval do - @load_hooks = Hash.new { |h, k| h[k] = [] } - @loaded = Hash.new { |h, k| h[k] = [] } - @run_once = Hash.new { |h, k| h[k] = [] } - end - end - - # Declares a block that will be executed when a Rails component is fully - # loaded. - # - # Options: - # - # * :yield - Yields the object that run_load_hooks to +block+. - # * :run_once - Given +block+ will run only once. - def on_load(name, options = {}, &block) - @loaded[name].each do |base| - execute_hook(name, base, options, block) - end - - @load_hooks[name] << [block, options] - end - - def run_load_hooks(name, base = Object) - @loaded[name] << base - @load_hooks[name].each do |hook, options| - execute_hook(name, base, options, hook) - end - end - - private - - def with_execution_control(name, block, once) - unless @run_once[name].include?(block) - @run_once[name] << block if once - - yield - end - end - - def execute_hook(name, base, options, block) - with_execution_control(name, block, options[:run_once]) do - if options[:yield] - block.call(base) - else - base.instance_eval(&block) - end - end - end - end - - extend LazyLoadHooks -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/locale/en.yml b/debian/gems-compat/activesupport-5.1.7/lib/active_support/locale/en.yml deleted file mode 100644 index c64b7598ee..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/locale/en.yml +++ /dev/null @@ -1,135 +0,0 @@ -en: - date: - formats: - # Use the strftime parameters for formats. - # When no format has been given, it uses default. - # You can provide other formats here if you like! - default: "%Y-%m-%d" - short: "%b %d" - long: "%B %d, %Y" - - day_names: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday] - abbr_day_names: [Sun, Mon, Tue, Wed, Thu, Fri, Sat] - - # Don't forget the nil at the beginning; there's no such thing as a 0th month - month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December] - abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec] - # Used in date_select and datetime_select. - order: - - year - - month - - day - - time: - formats: - default: "%a, %d %b %Y %H:%M:%S %z" - short: "%d %b %H:%M" - long: "%B %d, %Y %H:%M" - am: "am" - pm: "pm" - -# Used in array.to_sentence. - support: - array: - words_connector: ", " - two_words_connector: " and " - last_word_connector: ", and " - number: - # Used in NumberHelper.number_to_delimited() - # These are also the defaults for 'currency', 'percentage', 'precision', and 'human' - format: - # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5) - separator: "." - # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three) - delimiter: "," - # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00) - precision: 3 - # If set to true, precision will mean the number of significant digits instead - # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2) - significant: false - # If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2) - strip_insignificant_zeros: false - - # Used in NumberHelper.number_to_currency() - currency: - format: - # Where is the currency sign? %u is the currency unit, %n the number (default: $5.00) - format: "%u%n" - unit: "$" - # These five are to override number.format and are optional - separator: "." - delimiter: "," - precision: 2 - significant: false - strip_insignificant_zeros: false - - # Used in NumberHelper.number_to_percentage() - percentage: - format: - # These five are to override number.format and are optional - # separator: - delimiter: "" - # precision: - # significant: false - # strip_insignificant_zeros: false - format: "%n%" - - # Used in NumberHelper.number_to_rounded() - precision: - format: - # These five are to override number.format and are optional - # separator: - delimiter: "" - # precision: - # significant: false - # strip_insignificant_zeros: false - - # Used in NumberHelper.number_to_human_size() and NumberHelper.number_to_human() - human: - format: - # These five are to override number.format and are optional - # separator: - delimiter: "" - precision: 3 - significant: true - strip_insignificant_zeros: true - # Used in number_to_human_size() - storage_units: - # Storage units output formatting. - # %u is the storage unit, %n is the number (default: 2 MB) - format: "%n %u" - units: - byte: - one: "Byte" - other: "Bytes" - kb: "KB" - mb: "MB" - gb: "GB" - tb: "TB" - pb: "PB" - eb: "EB" - # Used in NumberHelper.number_to_human() - decimal_units: - format: "%n %u" - # Decimal units output formatting - # By default we will only quantify some of the exponents - # but the commented ones might be defined or overridden - # by the user. - units: - # femto: Quadrillionth - # pico: Trillionth - # nano: Billionth - # micro: Millionth - # mili: Thousandth - # centi: Hundredth - # deci: Tenth - unit: "" - # ten: - # one: Ten - # other: Tens - # hundred: Hundred - thousand: Thousand - million: Million - billion: Billion - trillion: Trillion - quadrillion: Quadrillion diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/log_subscriber.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/log_subscriber.rb deleted file mode 100644 index e704e18fb9..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/log_subscriber.rb +++ /dev/null @@ -1,111 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/class/attribute" -require "active_support/subscriber" - -module ActiveSupport - # ActiveSupport::LogSubscriber is an object set to consume - # ActiveSupport::Notifications with the sole purpose of logging them. - # The log subscriber dispatches notifications to a registered object based - # on its given namespace. - # - # An example would be Active Record log subscriber responsible for logging - # queries: - # - # module ActiveRecord - # class LogSubscriber < ActiveSupport::LogSubscriber - # def sql(event) - # "#{event.payload[:name]} (#{event.duration}) #{event.payload[:sql]}" - # end - # end - # end - # - # And it's finally registered as: - # - # ActiveRecord::LogSubscriber.attach_to :active_record - # - # Since we need to know all instance methods before attaching the log - # subscriber, the line above should be called after your - # ActiveRecord::LogSubscriber definition. - # - # After configured, whenever a "sql.active_record" notification is published, - # it will properly dispatch the event (ActiveSupport::Notifications::Event) to - # the sql method. - # - # Log subscriber also has some helpers to deal with logging and automatically - # flushes all logs when the request finishes (via action_dispatch.callback - # notification) in a Rails environment. - class LogSubscriber < Subscriber - # Embed in a String to clear all previous ANSI sequences. - CLEAR = "\e[0m" - BOLD = "\e[1m" - - # Colors - BLACK = "\e[30m" - RED = "\e[31m" - GREEN = "\e[32m" - YELLOW = "\e[33m" - BLUE = "\e[34m" - MAGENTA = "\e[35m" - CYAN = "\e[36m" - WHITE = "\e[37m" - - mattr_accessor :colorize_logging - self.colorize_logging = true - - class << self - def logger - @logger ||= if defined?(Rails) && Rails.respond_to?(:logger) - Rails.logger - end - end - - attr_writer :logger - - def log_subscribers - subscribers - end - - # Flush all log_subscribers' logger. - def flush_all! - logger.flush if logger.respond_to?(:flush) - end - end - - def logger - LogSubscriber.logger - end - - def start(name, id, payload) - super if logger - end - - def finish(name, id, payload) - super if logger - rescue => e - if logger - logger.error "Could not log #{name.inspect} event. #{e.class}: #{e.message} #{e.backtrace}" - end - end - - private - - %w(info debug warn error fatal unknown).each do |level| - class_eval <<-METHOD, __FILE__, __LINE__ + 1 - def #{level}(progname = nil, &block) - logger.#{level}(progname, &block) if logger - end - METHOD - end - - # Set color by using a symbol or one of the defined constants. If a third - # option is set to +true+, it also adds bold to the string. This is based - # on the Highline implementation and will automatically append CLEAR to the - # end of the returned String. - def color(text, color, bold = false) # :doc: - return text unless colorize_logging - color = self.class.const_get(color.upcase) if color.is_a?(Symbol) - bold = bold ? BOLD : "" - "#{bold}#{color}#{text}#{CLEAR}" - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/log_subscriber/test_helper.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/log_subscriber/test_helper.rb deleted file mode 100644 index 953ee77c2a..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/log_subscriber/test_helper.rb +++ /dev/null @@ -1,104 +0,0 @@ -require "active_support/log_subscriber" -require "active_support/logger" -require "active_support/notifications" - -module ActiveSupport - class LogSubscriber - # Provides some helpers to deal with testing log subscribers by setting up - # notifications. Take for instance Active Record subscriber tests: - # - # class SyncLogSubscriberTest < ActiveSupport::TestCase - # include ActiveSupport::LogSubscriber::TestHelper - # - # setup do - # ActiveRecord::LogSubscriber.attach_to(:active_record) - # end - # - # def test_basic_query_logging - # Developer.all.to_a - # wait - # assert_equal 1, @logger.logged(:debug).size - # assert_match(/Developer Load/, @logger.logged(:debug).last) - # assert_match(/SELECT \* FROM "developers"/, @logger.logged(:debug).last) - # end - # end - # - # All you need to do is to ensure that your log subscriber is added to - # Rails::Subscriber, as in the second line of the code above. The test - # helpers are responsible for setting up the queue, subscriptions and - # turning colors in logs off. - # - # The messages are available in the @logger instance, which is a logger with - # limited powers (it actually does not send anything to your output), and - # you can collect them doing @logger.logged(level), where level is the level - # used in logging, like info, debug, warn and so on. - module TestHelper - def setup # :nodoc: - @logger = MockLogger.new - @notifier = ActiveSupport::Notifications::Fanout.new - - ActiveSupport::LogSubscriber.colorize_logging = false - - @old_notifier = ActiveSupport::Notifications.notifier - set_logger(@logger) - ActiveSupport::Notifications.notifier = @notifier - end - - def teardown # :nodoc: - set_logger(nil) - ActiveSupport::Notifications.notifier = @old_notifier - end - - class MockLogger - include ActiveSupport::Logger::Severity - - attr_reader :flush_count - attr_accessor :level - - def initialize(level = DEBUG) - @flush_count = 0 - @level = level - @logged = Hash.new { |h, k| h[k] = [] } - end - - def method_missing(level, message = nil) - if block_given? - @logged[level] << yield - else - @logged[level] << message - end - end - - def logged(level) - @logged[level].compact.map { |l| l.to_s.strip } - end - - def flush - @flush_count += 1 - end - - ActiveSupport::Logger::Severity.constants.each do |severity| - class_eval <<-EOT, __FILE__, __LINE__ + 1 - def #{severity.downcase}? - #{severity} >= @level - end - EOT - end - end - - # Wait notifications to be published. - def wait - @notifier.wait - end - - # Overwrite if you use another logger in your log subscriber. - # - # def logger - # ActiveRecord::Base.logger = @logger - # end - def set_logger(logger) - ActiveSupport::LogSubscriber.logger = logger - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger.rb deleted file mode 100644 index ea09d7d2df..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger.rb +++ /dev/null @@ -1,106 +0,0 @@ -require "active_support/logger_silence" -require "active_support/logger_thread_safe_level" -require "logger" - -module ActiveSupport - class Logger < ::Logger - include ActiveSupport::LoggerThreadSafeLevel - include LoggerSilence - - # Returns true if the logger destination matches one of the sources - # - # logger = Logger.new(STDOUT) - # ActiveSupport::Logger.logger_outputs_to?(logger, STDOUT) - # # => true - def self.logger_outputs_to?(logger, *sources) - logdev = logger.instance_variable_get("@logdev") - logger_source = logdev.dev if logdev.respond_to?(:dev) - sources.any? { |source| source == logger_source } - end - - # Broadcasts logs to multiple loggers. - def self.broadcast(logger) # :nodoc: - Module.new do - define_method(:add) do |*args, &block| - logger.add(*args, &block) - super(*args, &block) - end - - define_method(:<<) do |x| - logger << x - super(x) - end - - define_method(:close) do - logger.close - super() - end - - define_method(:progname=) do |name| - logger.progname = name - super(name) - end - - define_method(:formatter=) do |formatter| - logger.formatter = formatter - super(formatter) - end - - define_method(:level=) do |level| - logger.level = level - super(level) - end - - define_method(:local_level=) do |level| - logger.local_level = level if logger.respond_to?(:local_level=) - super(level) if respond_to?(:local_level=) - end - - define_method(:silence) do |level = Logger::ERROR, &block| - if logger.respond_to?(:silence) - logger.silence(level) do - if defined?(super) - super(level, &block) - else - block.call(self) - end - end - else - if defined?(super) - super(level, &block) - else - block.call(self) - end - end - end - end - end - - def initialize(*args) - super - @formatter = SimpleFormatter.new - after_initialize if respond_to? :after_initialize - end - - def add(severity, message = nil, progname = nil, &block) - return true if @logdev.nil? || (severity || UNKNOWN) < level - super - end - - Logger::Severity.constants.each do |severity| - class_eval(<<-EOT, __FILE__, __LINE__ + 1) - def #{severity.downcase}? # def debug? - Logger::#{severity} >= level # DEBUG >= level - end # end - EOT - end - - # Simple formatter which only displays the message. - class SimpleFormatter < ::Logger::Formatter - # This method is invoked when a log event occurs - def call(severity, timestamp, progname, msg) - "#{String === msg ? msg : msg.inspect}\n" - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger_silence.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger_silence.rb deleted file mode 100644 index 632994cf50..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger_silence.rb +++ /dev/null @@ -1,28 +0,0 @@ -require "active_support/concern" -require "active_support/core_ext/module/attribute_accessors" -require "concurrent" - -module LoggerSilence - extend ActiveSupport::Concern - - included do - cattr_accessor :silencer - self.silencer = true - end - - # Silences the logger for the duration of the block. - def silence(temporary_level = Logger::ERROR) - if silencer - begin - old_local_level = local_level - self.local_level = temporary_level - - yield self - ensure - self.local_level = old_local_level - end - else - yield self - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger_thread_safe_level.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger_thread_safe_level.rb deleted file mode 100644 index 7fb175dea6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/logger_thread_safe_level.rb +++ /dev/null @@ -1,31 +0,0 @@ -require "active_support/concern" - -module ActiveSupport - module LoggerThreadSafeLevel # :nodoc: - extend ActiveSupport::Concern - - def after_initialize - @local_levels = Concurrent::Map.new(initial_capacity: 2) - end - - def local_log_id - Thread.current.__id__ - end - - def local_level - @local_levels[local_log_id] - end - - def local_level=(level) - if level - @local_levels[local_log_id] = level - else - @local_levels.delete(local_log_id) - end - end - - def level - local_level || super - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/message_encryptor.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/message_encryptor.rb deleted file mode 100644 index 726e1464ad..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/message_encryptor.rb +++ /dev/null @@ -1,156 +0,0 @@ -require "openssl" -require "base64" -require "active_support/core_ext/array/extract_options" -require "active_support/message_verifier" - -module ActiveSupport - # MessageEncryptor is a simple way to encrypt values which get stored - # somewhere you don't trust. - # - # The cipher text and initialization vector are base64 encoded and returned - # to you. - # - # This can be used in situations similar to the MessageVerifier, but - # where you don't want users to be able to determine the value of the payload. - # - # salt = SecureRandom.random_bytes(64) - # key = ActiveSupport::KeyGenerator.new('password').generate_key(salt, 32) # => "\x89\xE0\x156\xAC..." - # crypt = ActiveSupport::MessageEncryptor.new(key) # => # - # encrypted_data = crypt.encrypt_and_sign('my secret data') # => "NlFBTTMwOUV5UlA1QlNEN2xkY2d6eThYWWh..." - # crypt.decrypt_and_verify(encrypted_data) # => "my secret data" - class MessageEncryptor - DEFAULT_CIPHER = "aes-256-cbc" - - module NullSerializer #:nodoc: - def self.load(value) - value - end - - def self.dump(value) - value - end - end - - module NullVerifier #:nodoc: - def self.verify(value) - value - end - - def self.generate(value) - value - end - end - - class InvalidMessage < StandardError; end - OpenSSLCipherError = OpenSSL::Cipher::CipherError - - # Initialize a new MessageEncryptor. +secret+ must be at least as long as - # the cipher key size. For the default 'aes-256-cbc' cipher, this is 256 - # bits. If you are using a user-entered secret, you can generate a suitable - # key by using ActiveSupport::KeyGenerator or a similar key - # derivation function. - # - # First additional parameter is used as the signature key for +MessageVerifier+. - # This allows you to specify keys to encrypt and sign data. - # - # ActiveSupport::MessageEncryptor.new('secret', 'signature_secret') - # - # Options: - # * :cipher - Cipher to use. Can be any cipher returned by - # OpenSSL::Cipher.ciphers. Default is 'aes-256-cbc'. - # * :digest - String of digest to use for signing. Default is - # +SHA1+. Ignored when using an AEAD cipher like 'aes-256-gcm'. - # * :serializer - Object serializer to use. Default is +Marshal+. - def initialize(secret, *signature_key_or_options) - options = signature_key_or_options.extract_options! - sign_secret = signature_key_or_options.first - @secret = secret - @sign_secret = sign_secret - @cipher = options[:cipher] || DEFAULT_CIPHER - @digest = options[:digest] || "SHA1" unless aead_mode? - @verifier = resolve_verifier - @serializer = options[:serializer] || Marshal - end - - # Encrypt and sign a message. We need to sign the message in order to avoid - # padding attacks. Reference: http://www.limited-entropy.com/padding-oracle-attacks. - def encrypt_and_sign(value) - verifier.generate(_encrypt(value)) - end - - # Decrypt and verify a message. We need to verify the message in order to - # avoid padding attacks. Reference: http://www.limited-entropy.com/padding-oracle-attacks. - def decrypt_and_verify(value) - _decrypt(verifier.verify(value)) - end - - # Given a cipher, returns the key length of the cipher to help generate the key of desired size - def self.key_len(cipher = DEFAULT_CIPHER) - OpenSSL::Cipher.new(cipher).key_len - end - - private - - def _encrypt(value) - cipher = new_cipher - cipher.encrypt - cipher.key = @secret - - # Rely on OpenSSL for the initialization vector - iv = cipher.random_iv - cipher.auth_data = "" if aead_mode? - - encrypted_data = cipher.update(@serializer.dump(value)) - encrypted_data << cipher.final - - blob = "#{::Base64.strict_encode64 encrypted_data}--#{::Base64.strict_encode64 iv}" - blob << "--#{::Base64.strict_encode64 cipher.auth_tag}" if aead_mode? - blob - end - - def _decrypt(encrypted_message) - cipher = new_cipher - encrypted_data, iv, auth_tag = encrypted_message.split("--".freeze).map { |v| ::Base64.strict_decode64(v) } - - # Currently the OpenSSL bindings do not raise an error if auth_tag is - # truncated, which would allow an attacker to easily forge it. See - # https://github.com/ruby/openssl/issues/63 - raise InvalidMessage if aead_mode? && (auth_tag.nil? || auth_tag.bytes.length != 16) - - cipher.decrypt - cipher.key = @secret - cipher.iv = iv - if aead_mode? - cipher.auth_tag = auth_tag - cipher.auth_data = "" - end - - decrypted_data = cipher.update(encrypted_data) - decrypted_data << cipher.final - - @serializer.load(decrypted_data) - rescue OpenSSLCipherError, TypeError, ArgumentError - raise InvalidMessage - end - - def new_cipher - OpenSSL::Cipher.new(@cipher) - end - - def verifier - @verifier - end - - def aead_mode? - @aead_mode ||= new_cipher.authenticated? - end - - def resolve_verifier - if aead_mode? - NullVerifier - else - MessageVerifier.new(@sign_secret || @secret, digest: @digest, serializer: NullSerializer) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/message_verifier.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/message_verifier.rb deleted file mode 100644 index 8419e858c6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/message_verifier.rb +++ /dev/null @@ -1,134 +0,0 @@ -require "base64" -require "active_support/core_ext/object/blank" -require "active_support/security_utils" - -module ActiveSupport - # +MessageVerifier+ makes it easy to generate and verify messages which are - # signed to prevent tampering. - # - # This is useful for cases like remember-me tokens and auto-unsubscribe links - # where the session store isn't suitable or available. - # - # Remember Me: - # cookies[:remember_me] = @verifier.generate([@user.id, 2.weeks.from_now]) - # - # In the authentication filter: - # - # id, time = @verifier.verify(cookies[:remember_me]) - # if Time.now < time - # self.current_user = User.find(id) - # end - # - # By default it uses Marshal to serialize the message. If you want to use - # another serialization method, you can set the serializer in the options - # hash upon initialization: - # - # @verifier = ActiveSupport::MessageVerifier.new('s3Krit', serializer: YAML) - # - # +MessageVerifier+ creates HMAC signatures using SHA1 hash algorithm by default. - # If you want to use a different hash algorithm, you can change it by providing - # `:digest` key as an option while initializing the verifier: - # - # @verifier = ActiveSupport::MessageVerifier.new('s3Krit', digest: 'SHA256') - class MessageVerifier - class InvalidSignature < StandardError; end - - def initialize(secret, options = {}) - raise ArgumentError, "Secret should not be nil." unless secret - @secret = secret - @digest = options[:digest] || "SHA1" - @serializer = options[:serializer] || Marshal - end - - # Checks if a signed message could have been generated by signing an object - # with the +MessageVerifier+'s secret. - # - # verifier = ActiveSupport::MessageVerifier.new 's3Krit' - # signed_message = verifier.generate 'a private message' - # verifier.valid_message?(signed_message) # => true - # - # tampered_message = signed_message.chop # editing the message invalidates the signature - # verifier.valid_message?(tampered_message) # => false - def valid_message?(signed_message) - return if signed_message.nil? || !signed_message.valid_encoding? || signed_message.blank? - - data, digest = signed_message.split("--".freeze) - data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data)) - end - - # Decodes the signed message using the +MessageVerifier+'s secret. - # - # verifier = ActiveSupport::MessageVerifier.new 's3Krit' - # - # signed_message = verifier.generate 'a private message' - # verifier.verified(signed_message) # => 'a private message' - # - # Returns +nil+ if the message was not signed with the same secret. - # - # other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit' - # other_verifier.verified(signed_message) # => nil - # - # Returns +nil+ if the message is not Base64-encoded. - # - # invalid_message = "f--46a0120593880c733a53b6dad75b42ddc1c8996d" - # verifier.verified(invalid_message) # => nil - # - # Raises any error raised while decoding the signed message. - # - # incompatible_message = "test--dad7b06c94abba8d46a15fafaef56c327665d5ff" - # verifier.verified(incompatible_message) # => TypeError: incompatible marshal file format - def verified(signed_message) - if valid_message?(signed_message) - begin - data = signed_message.split("--".freeze)[0] - @serializer.load(decode(data)) - rescue ArgumentError => argument_error - return if argument_error.message.include?("invalid base64") - raise - end - end - end - - # Decodes the signed message using the +MessageVerifier+'s secret. - # - # verifier = ActiveSupport::MessageVerifier.new 's3Krit' - # signed_message = verifier.generate 'a private message' - # - # verifier.verify(signed_message) # => 'a private message' - # - # Raises +InvalidSignature+ if the message was not signed with the same - # secret or was not Base64-encoded. - # - # other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit' - # other_verifier.verify(signed_message) # => ActiveSupport::MessageVerifier::InvalidSignature - def verify(signed_message) - verified(signed_message) || raise(InvalidSignature) - end - - # Generates a signed message for the provided value. - # - # The message is signed with the +MessageVerifier+'s secret. Without knowing - # the secret, the original value cannot be extracted from the message. - # - # verifier = ActiveSupport::MessageVerifier.new 's3Krit' - # verifier.generate 'a private message' # => "BAhJIhRwcml2YXRlLW1lc3NhZ2UGOgZFVA==--e2d724331ebdee96a10fb99b089508d1c72bd772" - def generate(value) - data = encode(@serializer.dump(value)) - "#{data}--#{generate_digest(data)}" - end - - private - def encode(data) - ::Base64.strict_encode64(data) - end - - def decode(data) - ::Base64.strict_decode64(data) - end - - def generate_digest(data) - require "openssl" unless defined?(OpenSSL) - OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte.rb deleted file mode 100644 index f7c7befee0..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte.rb +++ /dev/null @@ -1,21 +0,0 @@ -module ActiveSupport #:nodoc: - module Multibyte - autoload :Chars, "active_support/multibyte/chars" - autoload :Unicode, "active_support/multibyte/unicode" - - # The proxy class returned when calling mb_chars. You can use this accessor - # to configure your own proxy class so you can support other encodings. See - # the ActiveSupport::Multibyte::Chars implementation for an example how to - # do this. - # - # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 - def self.proxy_class=(klass) - @proxy_class = klass - end - - # Returns the current proxy class. - def self.proxy_class - @proxy_class ||= ActiveSupport::Multibyte::Chars - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte/chars.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte/chars.rb deleted file mode 100644 index 8c58466556..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte/chars.rb +++ /dev/null @@ -1,233 +0,0 @@ -require "active_support/json" -require "active_support/core_ext/string/access" -require "active_support/core_ext/string/behavior" -require "active_support/core_ext/module/delegation" -require "active_support/core_ext/regexp" - -module ActiveSupport #:nodoc: - module Multibyte #:nodoc: - # Chars enables you to work transparently with UTF-8 encoding in the Ruby - # String class without having extensive knowledge about the encoding. A - # Chars object accepts a string upon initialization and proxies String - # methods in an encoding safe manner. All the normal String methods are also - # implemented on the proxy. - # - # String methods are proxied through the Chars object, and can be accessed - # through the +mb_chars+ method. Methods which would normally return a - # String object now return a Chars object so methods can be chained. - # - # 'The Perfect String '.mb_chars.downcase.strip.normalize - # # => # - # - # Chars objects are perfectly interchangeable with String objects as long as - # no explicit class checks are made. If certain methods do explicitly check - # the class, call +to_s+ before you pass chars objects to them. - # - # bad.explicit_checking_method 'T'.mb_chars.downcase.to_s - # - # The default Chars implementation assumes that the encoding of the string - # is UTF-8, if you want to handle different encodings you can write your own - # multibyte string handler and configure it through - # ActiveSupport::Multibyte.proxy_class. - # - # class CharsForUTF32 - # def size - # @wrapped_string.size / 4 - # end - # - # def self.accepts?(string) - # string.length % 4 == 0 - # end - # end - # - # ActiveSupport::Multibyte.proxy_class = CharsForUTF32 - class Chars - include Comparable - attr_reader :wrapped_string - alias to_s wrapped_string - alias to_str wrapped_string - - delegate :<=>, :=~, :acts_like_string?, to: :wrapped_string - - # Creates a new Chars instance by wrapping _string_. - def initialize(string) - @wrapped_string = string - @wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen? - end - - # Forward all undefined methods to the wrapped string. - def method_missing(method, *args, &block) - result = @wrapped_string.__send__(method, *args, &block) - if /!$/.match?(method) - self if result - else - result.kind_of?(String) ? chars(result) : result - end - end - - # Returns +true+ if _obj_ responds to the given method. Private methods - # are included in the search only if the optional second parameter - # evaluates to +true+. - def respond_to_missing?(method, include_private) - @wrapped_string.respond_to?(method, include_private) - end - - # Returns +true+ when the proxy class can handle the string. Returns - # +false+ otherwise. - def self.consumes?(string) - string.encoding == Encoding::UTF_8 - end - - # Works just like String#split, with the exception that the items - # in the resulting list are Chars instances instead of String. This makes - # chaining methods easier. - # - # 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s } # => ["CAF", " P", "RIFERÔL"] - def split(*args) - @wrapped_string.split(*args).map { |i| self.class.new(i) } - end - - # Works like String#slice!, but returns an instance of - # Chars, or +nil+ if the string was not modified. The string will not be - # modified if the range given is out of bounds - # - # string = 'Welcome' - # string.mb_chars.slice!(3) # => # - # string # => 'Welome' - # string.mb_chars.slice!(0..3) # => # - # string # => 'me' - def slice!(*args) - string_sliced = @wrapped_string.slice!(*args) - if string_sliced - chars(string_sliced) - end - end - - # Reverses all characters in the string. - # - # 'Café'.mb_chars.reverse.to_s # => 'éfaC' - def reverse - chars(Unicode.unpack_graphemes(@wrapped_string).reverse.flatten.pack("U*")) - end - - # Limits the byte size of the string to a number of bytes without breaking - # characters. Usable when the storage for a string is limited for some - # reason. - # - # 'こんにちは'.mb_chars.limit(7).to_s # => "こん" - def limit(limit) - slice(0...translate_offset(limit)) - end - - # Converts characters in the string to uppercase. - # - # 'Laurent, où sont les tests ?'.mb_chars.upcase.to_s # => "LAURENT, OÙ SONT LES TESTS ?" - def upcase - chars Unicode.upcase(@wrapped_string) - end - - # Converts characters in the string to lowercase. - # - # 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s # => "věda a výzkum" - def downcase - chars Unicode.downcase(@wrapped_string) - end - - # Converts characters in the string to the opposite case. - # - # 'El Cañón'.mb_chars.swapcase.to_s # => "eL cAÑÓN" - def swapcase - chars Unicode.swapcase(@wrapped_string) - end - - # Converts the first character to uppercase and the remainder to lowercase. - # - # 'über'.mb_chars.capitalize.to_s # => "Über" - def capitalize - (slice(0) || chars("")).upcase + (slice(1..-1) || chars("")).downcase - end - - # Capitalizes the first letter of every word, when possible. - # - # "ÉL QUE SE ENTERÓ".mb_chars.titleize.to_s # => "Él Que Se Enteró" - # "日本語".mb_chars.titleize.to_s # => "日本語" - def titleize - chars(downcase.to_s.gsub(/\b('?\S)/u) { Unicode.upcase($1) }) - end - alias_method :titlecase, :titleize - - # Returns the KC normalization of the string by default. NFKC is - # considered the best normalization form for passing strings to databases - # and validations. - # - # * form - The form you want to normalize in. Should be one of the following: - # :c, :kc, :d, or :kd. Default is - # ActiveSupport::Multibyte::Unicode.default_normalization_form - def normalize(form = nil) - chars(Unicode.normalize(@wrapped_string, form)) - end - - # Performs canonical decomposition on all the characters. - # - # 'é'.length # => 2 - # 'é'.mb_chars.decompose.to_s.length # => 3 - def decompose - chars(Unicode.decompose(:canonical, @wrapped_string.codepoints.to_a).pack("U*")) - end - - # Performs composition on all the characters. - # - # 'é'.length # => 3 - # 'é'.mb_chars.compose.to_s.length # => 2 - def compose - chars(Unicode.compose(@wrapped_string.codepoints.to_a).pack("U*")) - end - - # Returns the number of grapheme clusters in the string. - # - # 'क्षि'.mb_chars.length # => 4 - # 'क्षि'.mb_chars.grapheme_length # => 3 - def grapheme_length - Unicode.unpack_graphemes(@wrapped_string).length - end - - # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent - # resulting in a valid UTF-8 string. - # - # Passing +true+ will forcibly tidy all bytes, assuming that the string's - # encoding is entirely CP1252 or ISO-8859-1. - def tidy_bytes(force = false) - chars(Unicode.tidy_bytes(@wrapped_string, force)) - end - - def as_json(options = nil) #:nodoc: - to_s.as_json(options) - end - - %w(capitalize downcase reverse tidy_bytes upcase).each do |method| - define_method("#{method}!") do |*args| - @wrapped_string = send(method, *args).to_s - self - end - end - - private - - def translate_offset(byte_offset) - return nil if byte_offset.nil? - return 0 if @wrapped_string == "" - - begin - @wrapped_string.byteslice(0...byte_offset).unpack("U*").length - rescue ArgumentError - byte_offset -= 1 - retry - end - end - - def chars(string) - self.class.new(string) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte/unicode.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte/unicode.rb deleted file mode 100644 index 0912912aba..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/multibyte/unicode.rb +++ /dev/null @@ -1,392 +0,0 @@ -module ActiveSupport - module Multibyte - module Unicode - extend self - - # A list of all available normalization forms. - # See http://www.unicode.org/reports/tr15/tr15-29.html for more - # information about normalization. - NORMALIZATION_FORMS = [:c, :kc, :d, :kd] - - # The Unicode version that is supported by the implementation - UNICODE_VERSION = "9.0.0" - - # The default normalization used for operations that require - # normalization. It can be set to any of the normalizations - # in NORMALIZATION_FORMS. - # - # ActiveSupport::Multibyte::Unicode.default_normalization_form = :c - attr_accessor :default_normalization_form - @default_normalization_form = :kc - - # Hangul character boundaries and properties - HANGUL_SBASE = 0xAC00 - HANGUL_LBASE = 0x1100 - HANGUL_VBASE = 0x1161 - HANGUL_TBASE = 0x11A7 - HANGUL_LCOUNT = 19 - HANGUL_VCOUNT = 21 - HANGUL_TCOUNT = 28 - HANGUL_NCOUNT = HANGUL_VCOUNT * HANGUL_TCOUNT - HANGUL_SCOUNT = 11172 - HANGUL_SLAST = HANGUL_SBASE + HANGUL_SCOUNT - - # Detect whether the codepoint is in a certain character class. Returns - # +true+ when it's in the specified character class and +false+ otherwise. - # Valid character classes are: :cr, :lf, :l, - # :v, :lv, :lvt and :t. - # - # Primarily used by the grapheme cluster support. - def in_char_class?(codepoint, classes) - classes.detect { |c| database.boundary[c] === codepoint } ? true : false - end - - # Unpack the string at grapheme boundaries. Returns a list of character - # lists. - # - # Unicode.unpack_graphemes('क्षि') # => [[2325, 2381], [2359], [2367]] - # Unicode.unpack_graphemes('Café') # => [[67], [97], [102], [233]] - def unpack_graphemes(string) - codepoints = string.codepoints.to_a - unpacked = [] - pos = 0 - marker = 0 - eoc = codepoints.length - while (pos < eoc) - pos += 1 - previous = codepoints[pos - 1] - current = codepoints[pos] - - # See http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundary_Rules - should_break = - if pos == eoc - true - # GB3. CR X LF - elsif previous == database.boundary[:cr] && current == database.boundary[:lf] - false - # GB4. (Control|CR|LF) ÷ - elsif previous && in_char_class?(previous, [:control, :cr, :lf]) - true - # GB5. ÷ (Control|CR|LF) - elsif in_char_class?(current, [:control, :cr, :lf]) - true - # GB6. L X (L|V|LV|LVT) - elsif database.boundary[:l] === previous && in_char_class?(current, [:l, :v, :lv, :lvt]) - false - # GB7. (LV|V) X (V|T) - elsif in_char_class?(previous, [:lv, :v]) && in_char_class?(current, [:v, :t]) - false - # GB8. (LVT|T) X (T) - elsif in_char_class?(previous, [:lvt, :t]) && database.boundary[:t] === current - false - # GB9. X (Extend | ZWJ) - elsif in_char_class?(current, [:extend, :zwj]) - false - # GB9a. X SpacingMark - elsif database.boundary[:spacingmark] === current - false - # GB9b. Prepend X - elsif database.boundary[:prepend] === previous - false - # GB10. (E_Base | EBG) Extend* X E_Modifier - elsif (marker...pos).any? { |i| in_char_class?(codepoints[i], [:e_base, :e_base_gaz]) && codepoints[i + 1...pos].all? { |c| database.boundary[:extend] === c } } && database.boundary[:e_modifier] === current - false - # GB11. ZWJ X (Glue_After_Zwj | EBG) - elsif database.boundary[:zwj] === previous && in_char_class?(current, [:glue_after_zwj, :e_base_gaz]) - false - # GB12. ^ (RI RI)* RI X RI - # GB13. [^RI] (RI RI)* RI X RI - elsif codepoints[marker..pos].all? { |c| database.boundary[:regional_indicator] === c } && codepoints[marker..pos].count { |c| database.boundary[:regional_indicator] === c }.even? - false - # GB999. Any ÷ Any - else - true - end - - if should_break - unpacked << codepoints[marker..pos - 1] - marker = pos - end - end - unpacked - end - - # Reverse operation of unpack_graphemes. - # - # Unicode.pack_graphemes(Unicode.unpack_graphemes('क्षि')) # => 'क्षि' - def pack_graphemes(unpacked) - unpacked.flatten.pack("U*") - end - - # Re-order codepoints so the string becomes canonical. - def reorder_characters(codepoints) - length = codepoints.length - 1 - pos = 0 - while pos < length do - cp1, cp2 = database.codepoints[codepoints[pos]], database.codepoints[codepoints[pos + 1]] - if (cp1.combining_class > cp2.combining_class) && (cp2.combining_class > 0) - codepoints[pos..pos + 1] = cp2.code, cp1.code - pos += (pos > 0 ? -1 : 1) - else - pos += 1 - end - end - codepoints - end - - # Decompose composed characters to the decomposed form. - def decompose(type, codepoints) - codepoints.inject([]) do |decomposed, cp| - # if it's a hangul syllable starter character - if HANGUL_SBASE <= cp && cp < HANGUL_SLAST - sindex = cp - HANGUL_SBASE - ncp = [] # new codepoints - ncp << HANGUL_LBASE + sindex / HANGUL_NCOUNT - ncp << HANGUL_VBASE + (sindex % HANGUL_NCOUNT) / HANGUL_TCOUNT - tindex = sindex % HANGUL_TCOUNT - ncp << (HANGUL_TBASE + tindex) unless tindex == 0 - decomposed.concat ncp - # if the codepoint is decomposable in with the current decomposition type - elsif (ncp = database.codepoints[cp].decomp_mapping) && (!database.codepoints[cp].decomp_type || type == :compatibility) - decomposed.concat decompose(type, ncp.dup) - else - decomposed << cp - end - end - end - - # Compose decomposed characters to the composed form. - def compose(codepoints) - pos = 0 - eoa = codepoints.length - 1 - starter_pos = 0 - starter_char = codepoints[0] - previous_combining_class = -1 - while pos < eoa - pos += 1 - lindex = starter_char - HANGUL_LBASE - # -- Hangul - if 0 <= lindex && lindex < HANGUL_LCOUNT - vindex = codepoints[starter_pos + 1] - HANGUL_VBASE rescue vindex = -1 - if 0 <= vindex && vindex < HANGUL_VCOUNT - tindex = codepoints[starter_pos + 2] - HANGUL_TBASE rescue tindex = -1 - if 0 <= tindex && tindex < HANGUL_TCOUNT - j = starter_pos + 2 - eoa -= 2 - else - tindex = 0 - j = starter_pos + 1 - eoa -= 1 - end - codepoints[starter_pos..j] = (lindex * HANGUL_VCOUNT + vindex) * HANGUL_TCOUNT + tindex + HANGUL_SBASE - end - starter_pos += 1 - starter_char = codepoints[starter_pos] - # -- Other characters - else - current_char = codepoints[pos] - current = database.codepoints[current_char] - if current.combining_class > previous_combining_class - if ref = database.composition_map[starter_char] - composition = ref[current_char] - else - composition = nil - end - unless composition.nil? - codepoints[starter_pos] = composition - starter_char = composition - codepoints.delete_at pos - eoa -= 1 - pos -= 1 - previous_combining_class = -1 - else - previous_combining_class = current.combining_class - end - else - previous_combining_class = current.combining_class - end - if current.combining_class == 0 - starter_pos = pos - starter_char = codepoints[pos] - end - end - end - codepoints - end - - # Rubinius' String#scrub, however, doesn't support ASCII-incompatible chars. - if !defined?(Rubinius) - # Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent - # resulting in a valid UTF-8 string. - # - # Passing +true+ will forcibly tidy all bytes, assuming that the string's - # encoding is entirely CP1252 or ISO-8859-1. - def tidy_bytes(string, force = false) - return string if string.empty? - return recode_windows1252_chars(string) if force - string.scrub { |bad| recode_windows1252_chars(bad) } - end - else - def tidy_bytes(string, force = false) - return string if string.empty? - return recode_windows1252_chars(string) if force - - # We can't transcode to the same format, so we choose a nearly-identical encoding. - # We're going to 'transcode' bytes from UTF-8 when possible, then fall back to - # CP1252 when we get errors. The final string will be 'converted' back to UTF-8 - # before returning. - reader = Encoding::Converter.new(Encoding::UTF_8, Encoding::UTF_16LE) - - source = string.dup - out = "".force_encoding(Encoding::UTF_16LE) - - loop do - reader.primitive_convert(source, out) - _, _, _, error_bytes, _ = reader.primitive_errinfo - break if error_bytes.nil? - out << error_bytes.encode(Encoding::UTF_16LE, Encoding::Windows_1252, invalid: :replace, undef: :replace) - end - - reader.finish - - out.encode!(Encoding::UTF_8) - end - end - - # Returns the KC normalization of the string by default. NFKC is - # considered the best normalization form for passing strings to databases - # and validations. - # - # * string - The string to perform normalization on. - # * form - The form you want to normalize in. Should be one of - # the following: :c, :kc, :d, or :kd. - # Default is ActiveSupport::Multibyte::Unicode.default_normalization_form. - def normalize(string, form = nil) - form ||= @default_normalization_form - # See http://www.unicode.org/reports/tr15, Table 1 - codepoints = string.codepoints.to_a - case form - when :d - reorder_characters(decompose(:canonical, codepoints)) - when :c - compose(reorder_characters(decompose(:canonical, codepoints))) - when :kd - reorder_characters(decompose(:compatibility, codepoints)) - when :kc - compose(reorder_characters(decompose(:compatibility, codepoints))) - else - raise ArgumentError, "#{form} is not a valid normalization variant", caller - end.pack("U*".freeze) - end - - def downcase(string) - apply_mapping string, :lowercase_mapping - end - - def upcase(string) - apply_mapping string, :uppercase_mapping - end - - def swapcase(string) - apply_mapping string, :swapcase_mapping - end - - # Holds data about a codepoint in the Unicode database. - class Codepoint - attr_accessor :code, :combining_class, :decomp_type, :decomp_mapping, :uppercase_mapping, :lowercase_mapping - - # Initializing Codepoint object with default values - def initialize - @combining_class = 0 - @uppercase_mapping = 0 - @lowercase_mapping = 0 - end - - def swapcase_mapping - uppercase_mapping > 0 ? uppercase_mapping : lowercase_mapping - end - end - - # Holds static data from the Unicode database. - class UnicodeDatabase - ATTRIBUTES = :codepoints, :composition_exclusion, :composition_map, :boundary, :cp1252 - - attr_writer(*ATTRIBUTES) - - def initialize - @codepoints = Hash.new(Codepoint.new) - @composition_exclusion = [] - @composition_map = {} - @boundary = {} - @cp1252 = {} - end - - # Lazy load the Unicode database so it's only loaded when it's actually used - ATTRIBUTES.each do |attr_name| - class_eval(<<-EOS, __FILE__, __LINE__ + 1) - def #{attr_name} # def codepoints - load # load - @#{attr_name} # @codepoints - end # end - EOS - end - - # Loads the Unicode database and returns all the internal objects of - # UnicodeDatabase. - def load - begin - @codepoints, @composition_exclusion, @composition_map, @boundary, @cp1252 = File.open(self.class.filename, "rb") { |f| Marshal.load f.read } - rescue => e - raise IOError.new("Couldn't load the Unicode tables for UTF8Handler (#{e.message}), ActiveSupport::Multibyte is unusable") - end - - # Redefine the === method so we can write shorter rules for grapheme cluster breaks - @boundary.each_key do |k| - @boundary[k].instance_eval do - def ===(other) - detect { |i| i === other } ? true : false - end - end if @boundary[k].kind_of?(Array) - end - - # define attr_reader methods for the instance variables - class << self - attr_reader(*ATTRIBUTES) - end - end - - # Returns the directory in which the data files are stored. - def self.dirname - File.dirname(__FILE__) + "/../values/" - end - - # Returns the filename for the data file for this version. - def self.filename - File.expand_path File.join(dirname, "unicode_tables.dat") - end - end - - private - - def apply_mapping(string, mapping) - database.codepoints - string.each_codepoint.map do |codepoint| - cp = database.codepoints[codepoint] - if cp && (ncp = cp.send(mapping)) && ncp > 0 - ncp - else - codepoint - end - end.pack("U*") - end - - def recode_windows1252_chars(string) - string.encode(Encoding::UTF_8, Encoding::Windows_1252, invalid: :replace, undef: :replace) - end - - def database - @database ||= UnicodeDatabase.new - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications.rb deleted file mode 100644 index 37dfdc0422..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications.rb +++ /dev/null @@ -1,214 +0,0 @@ -require "active_support/notifications/instrumenter" -require "active_support/notifications/fanout" -require "active_support/per_thread_registry" - -module ActiveSupport - # = Notifications - # - # ActiveSupport::Notifications provides an instrumentation API for - # Ruby. - # - # == Instrumenters - # - # To instrument an event you just need to do: - # - # ActiveSupport::Notifications.instrument('render', extra: :information) do - # render plain: 'Foo' - # end - # - # That first executes the block and then notifies all subscribers once done. - # - # In the example above +render+ is the name of the event, and the rest is called - # the _payload_. The payload is a mechanism that allows instrumenters to pass - # extra information to subscribers. Payloads consist of a hash whose contents - # are arbitrary and generally depend on the event. - # - # == Subscribers - # - # You can consume those events and the information they provide by registering - # a subscriber. - # - # ActiveSupport::Notifications.subscribe('render') do |name, start, finish, id, payload| - # name # => String, name of the event (such as 'render' from above) - # start # => Time, when the instrumented block started execution - # finish # => Time, when the instrumented block ended execution - # id # => String, unique ID for this notification - # payload # => Hash, the payload - # end - # - # For instance, let's store all "render" events in an array: - # - # events = [] - # - # ActiveSupport::Notifications.subscribe('render') do |*args| - # events << ActiveSupport::Notifications::Event.new(*args) - # end - # - # That code returns right away, you are just subscribing to "render" events. - # The block is saved and will be called whenever someone instruments "render": - # - # ActiveSupport::Notifications.instrument('render', extra: :information) do - # render plain: 'Foo' - # end - # - # event = events.first - # event.name # => "render" - # event.duration # => 10 (in milliseconds) - # event.payload # => { extra: :information } - # - # The block in the subscribe call gets the name of the event, start - # timestamp, end timestamp, a string with a unique identifier for that event - # (something like "535801666f04d0298cd6"), and a hash with the payload, in - # that order. - # - # If an exception happens during that particular instrumentation the payload will - # have a key :exception with an array of two elements as value: a string with - # the name of the exception class, and the exception message. - # The :exception_object key of the payload will have the exception - # itself as the value. - # - # As the previous example depicts, the class ActiveSupport::Notifications::Event - # is able to take the arguments as they come and provide an object-oriented - # interface to that data. - # - # It is also possible to pass an object which responds to call method - # as the second parameter to the subscribe method instead of a block: - # - # module ActionController - # class PageRequest - # def call(name, started, finished, unique_id, payload) - # Rails.logger.debug ['notification:', name, started, finished, unique_id, payload].join(' ') - # end - # end - # end - # - # ActiveSupport::Notifications.subscribe('process_action.action_controller', ActionController::PageRequest.new) - # - # resulting in the following output within the logs including a hash with the payload: - # - # notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 { - # controller: "Devise::SessionsController", - # action: "new", - # params: {"action"=>"new", "controller"=>"devise/sessions"}, - # format: :html, - # method: "GET", - # path: "/login/sign_in", - # status: 200, - # view_runtime: 279.3080806732178, - # db_runtime: 40.053 - # } - # - # You can also subscribe to all events whose name matches a certain regexp: - # - # ActiveSupport::Notifications.subscribe(/render/) do |*args| - # ... - # end - # - # and even pass no argument to subscribe, in which case you are subscribing - # to all events. - # - # == Temporary Subscriptions - # - # Sometimes you do not want to subscribe to an event for the entire life of - # the application. There are two ways to unsubscribe. - # - # WARNING: The instrumentation framework is designed for long-running subscribers, - # use this feature sparingly because it wipes some internal caches and that has - # a negative impact on performance. - # - # === Subscribe While a Block Runs - # - # You can subscribe to some event temporarily while some block runs. For - # example, in - # - # callback = lambda {|*args| ... } - # ActiveSupport::Notifications.subscribed(callback, "sql.active_record") do - # ... - # end - # - # the callback will be called for all "sql.active_record" events instrumented - # during the execution of the block. The callback is unsubscribed automatically - # after that. - # - # === Manual Unsubscription - # - # The +subscribe+ method returns a subscriber object: - # - # subscriber = ActiveSupport::Notifications.subscribe("render") do |*args| - # ... - # end - # - # To prevent that block from being called anymore, just unsubscribe passing - # that reference: - # - # ActiveSupport::Notifications.unsubscribe(subscriber) - # - # You can also unsubscribe by passing the name of the subscriber object. Note - # that this will unsubscribe all subscriptions with the given name: - # - # ActiveSupport::Notifications.unsubscribe("render") - # - # == Default Queue - # - # Notifications ships with a queue implementation that consumes and publishes events - # to all log subscribers. You can use any queue implementation you want. - # - module Notifications - class << self - attr_accessor :notifier - - def publish(name, *args) - notifier.publish(name, *args) - end - - def instrument(name, payload = {}) - if notifier.listening?(name) - instrumenter.instrument(name, payload) { yield payload if block_given? } - else - yield payload if block_given? - end - end - - def subscribe(*args, &block) - notifier.subscribe(*args, &block) - end - - def subscribed(callback, *args, &block) - subscriber = subscribe(*args, &callback) - yield - ensure - unsubscribe(subscriber) - end - - def unsubscribe(subscriber_or_name) - notifier.unsubscribe(subscriber_or_name) - end - - def instrumenter - InstrumentationRegistry.instance.instrumenter_for(notifier) - end - end - - # This class is a registry which holds all of the +Instrumenter+ objects - # in a particular thread local. To access the +Instrumenter+ object for a - # particular +notifier+, you can call the following method: - # - # InstrumentationRegistry.instrumenter_for(notifier) - # - # The instrumenters for multiple notifiers are held in a single instance of - # this class. - class InstrumentationRegistry # :nodoc: - extend ActiveSupport::PerThreadRegistry - - def initialize - @registry = {} - end - - def instrumenter_for(notifier) - @registry[notifier] ||= Instrumenter.new(notifier) - end - end - - self.notifier = Fanout.new - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications/fanout.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications/fanout.rb deleted file mode 100644 index 9da115f552..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications/fanout.rb +++ /dev/null @@ -1,157 +0,0 @@ -require "mutex_m" -require "concurrent/map" - -module ActiveSupport - module Notifications - # This is a default queue implementation that ships with Notifications. - # It just pushes events to all registered log subscribers. - # - # This class is thread safe. All methods are reentrant. - class Fanout - include Mutex_m - - def initialize - @subscribers = [] - @listeners_for = Concurrent::Map.new - super - end - - def subscribe(pattern = nil, block = Proc.new) - subscriber = Subscribers.new pattern, block - synchronize do - @subscribers << subscriber - @listeners_for.clear - end - subscriber - end - - def unsubscribe(subscriber_or_name) - synchronize do - case subscriber_or_name - when String - @subscribers.reject! { |s| s.matches?(subscriber_or_name) } - else - @subscribers.delete(subscriber_or_name) - end - - @listeners_for.clear - end - end - - def start(name, id, payload) - listeners_for(name).each { |s| s.start(name, id, payload) } - end - - def finish(name, id, payload, listeners = listeners_for(name)) - listeners.each { |s| s.finish(name, id, payload) } - end - - def publish(name, *args) - listeners_for(name).each { |s| s.publish(name, *args) } - end - - def listeners_for(name) - # this is correctly done double-checked locking (Concurrent::Map's lookups have volatile semantics) - @listeners_for[name] || synchronize do - # use synchronisation when accessing @subscribers - @listeners_for[name] ||= @subscribers.select { |s| s.subscribed_to?(name) } - end - end - - def listening?(name) - listeners_for(name).any? - end - - # This is a sync queue, so there is no waiting. - def wait - end - - module Subscribers # :nodoc: - def self.new(pattern, listener) - if listener.respond_to?(:start) && listener.respond_to?(:finish) - subscriber = Evented.new pattern, listener - else - subscriber = Timed.new pattern, listener - end - - unless pattern - AllMessages.new(subscriber) - else - subscriber - end - end - - class Evented #:nodoc: - def initialize(pattern, delegate) - @pattern = pattern - @delegate = delegate - @can_publish = delegate.respond_to?(:publish) - end - - def publish(name, *args) - if @can_publish - @delegate.publish name, *args - end - end - - def start(name, id, payload) - @delegate.start name, id, payload - end - - def finish(name, id, payload) - @delegate.finish name, id, payload - end - - def subscribed_to?(name) - @pattern === name - end - - def matches?(name) - @pattern && @pattern === name - end - end - - class Timed < Evented # :nodoc: - def publish(name, *args) - @delegate.call name, *args - end - - def start(name, id, payload) - timestack = Thread.current[:_timestack] ||= [] - timestack.push Time.now - end - - def finish(name, id, payload) - timestack = Thread.current[:_timestack] - started = timestack.pop - @delegate.call(name, started, Time.now, id, payload) - end - end - - class AllMessages # :nodoc: - def initialize(delegate) - @delegate = delegate - end - - def start(name, id, payload) - @delegate.start name, id, payload - end - - def finish(name, id, payload) - @delegate.finish name, id, payload - end - - def publish(name, *args) - @delegate.publish name, *args - end - - def subscribed_to?(name) - true - end - - alias :matches? :=== - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications/instrumenter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications/instrumenter.rb deleted file mode 100644 index e11e2e0689..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/notifications/instrumenter.rb +++ /dev/null @@ -1,91 +0,0 @@ -require "securerandom" - -module ActiveSupport - module Notifications - # Instrumenters are stored in a thread local. - class Instrumenter - attr_reader :id - - def initialize(notifier) - @id = unique_id - @notifier = notifier - end - - # Instrument the given block by measuring the time taken to execute it - # and publish it. Notice that events get sent even if an error occurs - # in the passed-in block. - def instrument(name, payload = {}) - # some of the listeners might have state - listeners_state = start name, payload - begin - yield payload - rescue Exception => e - payload[:exception] = [e.class.name, e.message] - payload[:exception_object] = e - raise e - ensure - finish_with_state listeners_state, name, payload - end - end - - # Send a start notification with +name+ and +payload+. - def start(name, payload) - @notifier.start name, @id, payload - end - - # Send a finish notification with +name+ and +payload+. - def finish(name, payload) - @notifier.finish name, @id, payload - end - - def finish_with_state(listeners_state, name, payload) - @notifier.finish name, @id, payload, listeners_state - end - - private - - def unique_id - SecureRandom.hex(10) - end - end - - class Event - attr_reader :name, :time, :transaction_id, :payload, :children - attr_accessor :end - - def initialize(name, start, ending, transaction_id, payload) - @name = name - @payload = payload.dup - @time = start - @transaction_id = transaction_id - @end = ending - @children = [] - @duration = nil - end - - # Returns the difference in milliseconds between when the execution of the - # event started and when it ended. - # - # ActiveSupport::Notifications.subscribe('wait') do |*args| - # @event = ActiveSupport::Notifications::Event.new(*args) - # end - # - # ActiveSupport::Notifications.instrument('wait') do - # sleep 1 - # end - # - # @event.duration # => 1000.138 - def duration - @duration ||= 1000.0 * (self.end - time) - end - - def <<(event) - @children << event - end - - def parent_of?(event) - @children.include? event - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper.rb deleted file mode 100644 index 9cb2821cb6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper.rb +++ /dev/null @@ -1,369 +0,0 @@ -module ActiveSupport - module NumberHelper - extend ActiveSupport::Autoload - - eager_autoload do - autoload :NumberConverter - autoload :RoundingHelper - autoload :NumberToRoundedConverter - autoload :NumberToDelimitedConverter - autoload :NumberToHumanConverter - autoload :NumberToHumanSizeConverter - autoload :NumberToPhoneConverter - autoload :NumberToCurrencyConverter - autoload :NumberToPercentageConverter - end - - extend self - - # Formats a +number+ into a phone number (US by default e.g., (555) - # 123-9876). You can customize the format in the +options+ hash. - # - # ==== Options - # - # * :area_code - Adds parentheses around the area code. - # * :delimiter - Specifies the delimiter to use - # (defaults to "-"). - # * :extension - Specifies an extension to add to the - # end of the generated number. - # * :country_code - Sets the country code for the phone - # number. - # * :pattern - Specifies how the number is divided into three - # groups with the custom regexp to override the default format. - # ==== Examples - # - # number_to_phone(5551234) # => "555-1234" - # number_to_phone('5551234') # => "555-1234" - # number_to_phone(1235551234) # => "123-555-1234" - # number_to_phone(1235551234, area_code: true) # => "(123) 555-1234" - # number_to_phone(1235551234, delimiter: ' ') # => "123 555 1234" - # number_to_phone(1235551234, area_code: true, extension: 555) # => "(123) 555-1234 x 555" - # number_to_phone(1235551234, country_code: 1) # => "+1-123-555-1234" - # number_to_phone('123a456') # => "123a456" - # - # number_to_phone(1235551234, country_code: 1, extension: 1343, delimiter: '.') - # # => "+1.123.555.1234 x 1343" - # - # number_to_phone(75561234567, pattern: /(\d{1,4})(\d{4})(\d{4})$/, area_code: true) - # # => "(755) 6123-4567" - # number_to_phone(13312345678, pattern: /(\d{3})(\d{4})(\d{4})$/) - # # => "133-1234-5678" - def number_to_phone(number, options = {}) - NumberToPhoneConverter.convert(number, options) - end - - # Formats a +number+ into a currency string (e.g., $13.65). You - # can customize the format in the +options+ hash. - # - # The currency unit and number formatting of the current locale will be used - # unless otherwise specified in the provided options. No currency conversion - # is performed. If the user is given a way to change their locale, they will - # also be able to change the relative value of the currency displayed with - # this helper. If your application will ever support multiple locales, you - # may want to specify a constant :locale option or consider - # using a library capable of currency conversion. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the level of precision (defaults - # to 2). - # * :unit - Sets the denomination of the currency - # (defaults to "$"). - # * :separator - Sets the separator between the units - # (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ","). - # * :format - Sets the format for non-negative numbers - # (defaults to "%u%n"). Fields are %u for the - # currency, and %n for the number. - # * :negative_format - Sets the format for negative - # numbers (defaults to prepending a hyphen to the formatted - # number given by :format). Accepts the same fields - # than :format, except %n is here the - # absolute value of the number. - # - # ==== Examples - # - # number_to_currency(1234567890.50) # => "$1,234,567,890.50" - # number_to_currency(1234567890.506) # => "$1,234,567,890.51" - # number_to_currency(1234567890.506, precision: 3) # => "$1,234,567,890.506" - # number_to_currency(1234567890.506, locale: :fr) # => "1 234 567 890,51 €" - # number_to_currency('123a456') # => "$123a456" - # - # number_to_currency(-1234567890.50, negative_format: '(%u%n)') - # # => "($1,234,567,890.50)" - # number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '') - # # => "£1234567890,50" - # number_to_currency(1234567890.50, unit: '£', separator: ',', delimiter: '', format: '%n %u') - # # => "1234567890,50 £" - def number_to_currency(number, options = {}) - NumberToCurrencyConverter.convert(number, options) - end - - # Formats a +number+ as a percentage string (e.g., 65%). You can - # customize the format in the +options+ hash. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). Keeps the number's precision if +nil+. - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +false+). - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +false+). - # * :format - Specifies the format of the percentage - # string The number field is %n (defaults to "%n%"). - # - # ==== Examples - # - # number_to_percentage(100) # => "100.000%" - # number_to_percentage('98') # => "98.000%" - # number_to_percentage(100, precision: 0) # => "100%" - # number_to_percentage(1000, delimiter: '.', separator: ',') # => "1.000,000%" - # number_to_percentage(302.24398923423, precision: 5) # => "302.24399%" - # number_to_percentage(1000, locale: :fr) # => "1000,000%" - # number_to_percentage(1000, precision: nil) # => "1000%" - # number_to_percentage('98a') # => "98a%" - # number_to_percentage(100, format: '%n %') # => "100.000 %" - def number_to_percentage(number, options = {}) - NumberToPercentageConverter.convert(number, options) - end - - # Formats a +number+ with grouped thousands using +delimiter+ - # (e.g., 12,324). You can customize the format in the +options+ - # hash. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :delimiter - Sets the thousands delimiter (defaults - # to ","). - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter_pattern - Sets a custom regular expression used for - # deriving the placement of delimiter. Helpful when using currency formats - # like INR. - # - # ==== Examples - # - # number_to_delimited(12345678) # => "12,345,678" - # number_to_delimited('123456') # => "123,456" - # number_to_delimited(12345678.05) # => "12,345,678.05" - # number_to_delimited(12345678, delimiter: '.') # => "12.345.678" - # number_to_delimited(12345678, delimiter: ',') # => "12,345,678" - # number_to_delimited(12345678.05, separator: ' ') # => "12,345,678 05" - # number_to_delimited(12345678.05, locale: :fr) # => "12 345 678,05" - # number_to_delimited('112a') # => "112a" - # number_to_delimited(98765432.98, delimiter: ' ', separator: ',') - # # => "98 765 432,98" - # number_to_delimited("123456.78", - # delimiter_pattern: /(\d+?)(?=(\d\d)+(\d)(?!\d))/) - # # => "1,23,456.78" - def number_to_delimited(number, options = {}) - NumberToDelimitedConverter.convert(number, options) - end - - # Formats a +number+ with the specified level of - # :precision (e.g., 112.32 has a precision of 2 if - # +:significant+ is +false+, and 5 if +:significant+ is +true+). - # You can customize the format in the +options+ hash. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). Keeps the number's precision if +nil+. - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +false+). - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +false+). - # - # ==== Examples - # - # number_to_rounded(111.2345) # => "111.235" - # number_to_rounded(111.2345, precision: 2) # => "111.23" - # number_to_rounded(13, precision: 5) # => "13.00000" - # number_to_rounded(389.32314, precision: 0) # => "389" - # number_to_rounded(111.2345, significant: true) # => "111" - # number_to_rounded(111.2345, precision: 1, significant: true) # => "100" - # number_to_rounded(13, precision: 5, significant: true) # => "13.000" - # number_to_rounded(13, precision: nil) # => "13" - # number_to_rounded(111.234, locale: :fr) # => "111,234" - # - # number_to_rounded(13, precision: 5, significant: true, strip_insignificant_zeros: true) - # # => "13" - # - # number_to_rounded(389.32314, precision: 4, significant: true) # => "389.3" - # number_to_rounded(1111.2345, precision: 2, separator: ',', delimiter: '.') - # # => "1.111,23" - def number_to_rounded(number, options = {}) - NumberToRoundedConverter.convert(number, options) - end - - # Formats the bytes in +number+ into a more understandable - # representation (e.g., giving it 1500 yields 1.5 KB). This - # method is useful for reporting file sizes to users. You can - # customize the format in the +options+ hash. - # - # See number_to_human if you want to pretty-print a - # generic number. - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +true+) - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +true+) - # - # ==== Examples - # - # number_to_human_size(123) # => "123 Bytes" - # number_to_human_size(1234) # => "1.21 KB" - # number_to_human_size(12345) # => "12.1 KB" - # number_to_human_size(1234567) # => "1.18 MB" - # number_to_human_size(1234567890) # => "1.15 GB" - # number_to_human_size(1234567890123) # => "1.12 TB" - # number_to_human_size(1234567890123456) # => "1.1 PB" - # number_to_human_size(1234567890123456789) # => "1.07 EB" - # number_to_human_size(1234567, precision: 2) # => "1.2 MB" - # number_to_human_size(483989, precision: 2) # => "470 KB" - # number_to_human_size(1234567, precision: 2, separator: ',') # => "1,2 MB" - # number_to_human_size(1234567890123, precision: 5) # => "1.1228 TB" - # number_to_human_size(524288000, precision: 5) # => "500 MB" - def number_to_human_size(number, options = {}) - NumberToHumanSizeConverter.convert(number, options) - end - - # Pretty prints (formats and approximates) a number in a way it - # is more readable by humans (eg.: 1200000000 becomes "1.2 - # Billion"). This is useful for numbers that can get very large - # (and too hard to read). - # - # See number_to_human_size if you want to print a file - # size. - # - # You can also define your own unit-quantifier names if you want - # to use other decimal units (eg.: 1500 becomes "1.5 - # kilometers", 0.150 becomes "150 milliliters", etc). You may - # define a wide range of unit quantifiers, even fractional ones - # (centi, deci, mili, etc). - # - # ==== Options - # - # * :locale - Sets the locale to be used for formatting - # (defaults to current locale). - # * :precision - Sets the precision of the number - # (defaults to 3). - # * :significant - If +true+, precision will be the number - # of significant_digits. If +false+, the number of fractional - # digits (defaults to +true+) - # * :separator - Sets the separator between the - # fractional and integer digits (defaults to "."). - # * :delimiter - Sets the thousands delimiter (defaults - # to ""). - # * :strip_insignificant_zeros - If +true+ removes - # insignificant zeros after the decimal separator (defaults to - # +true+) - # * :units - A Hash of unit quantifier names. Or a - # string containing an i18n scope where to find this hash. It - # might have the following keys: - # * *integers*: :unit, :ten, - # :hundred, :thousand, :million, - # :billion, :trillion, - # :quadrillion - # * *fractionals*: :deci, :centi, - # :mili, :micro, :nano, - # :pico, :femto - # * :format - Sets the format of the output string - # (defaults to "%n %u"). The field types are: - # * %u - The quantifier (ex.: 'thousand') - # * %n - The number - # - # ==== Examples - # - # number_to_human(123) # => "123" - # number_to_human(1234) # => "1.23 Thousand" - # number_to_human(12345) # => "12.3 Thousand" - # number_to_human(1234567) # => "1.23 Million" - # number_to_human(1234567890) # => "1.23 Billion" - # number_to_human(1234567890123) # => "1.23 Trillion" - # number_to_human(1234567890123456) # => "1.23 Quadrillion" - # number_to_human(1234567890123456789) # => "1230 Quadrillion" - # number_to_human(489939, precision: 2) # => "490 Thousand" - # number_to_human(489939, precision: 4) # => "489.9 Thousand" - # number_to_human(1234567, precision: 4, - # significant: false) # => "1.2346 Million" - # number_to_human(1234567, precision: 1, - # separator: ',', - # significant: false) # => "1,2 Million" - # - # number_to_human(500000000, precision: 5) # => "500 Million" - # number_to_human(12345012345, significant: false) # => "12.345 Billion" - # - # Non-significant zeros after the decimal separator are stripped - # out by default (set :strip_insignificant_zeros to - # +false+ to change that): - # - # number_to_human(12.00001) # => "12" - # number_to_human(12.00001, strip_insignificant_zeros: false) # => "12.0" - # - # ==== Custom Unit Quantifiers - # - # You can also use your own custom unit quantifiers: - # number_to_human(500000, units: { unit: 'ml', thousand: 'lt' }) # => "500 lt" - # - # If in your I18n locale you have: - # - # distance: - # centi: - # one: "centimeter" - # other: "centimeters" - # unit: - # one: "meter" - # other: "meters" - # thousand: - # one: "kilometer" - # other: "kilometers" - # billion: "gazillion-distance" - # - # Then you could do: - # - # number_to_human(543934, units: :distance) # => "544 kilometers" - # number_to_human(54393498, units: :distance) # => "54400 kilometers" - # number_to_human(54393498000, units: :distance) # => "54.4 gazillion-distance" - # number_to_human(343, units: :distance, precision: 1) # => "300 meters" - # number_to_human(1, units: :distance) # => "1 meter" - # number_to_human(0.34, units: :distance) # => "34 centimeters" - def number_to_human(number, options = {}) - NumberToHumanConverter.convert(number, options) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_converter.rb deleted file mode 100644 index ce363287cf..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_converter.rb +++ /dev/null @@ -1,182 +0,0 @@ -require "active_support/core_ext/big_decimal/conversions" -require "active_support/core_ext/object/blank" -require "active_support/core_ext/hash/keys" -require "active_support/i18n" -require "active_support/core_ext/class/attribute" - -module ActiveSupport - module NumberHelper - class NumberConverter # :nodoc: - # Default and i18n option namespace per class - class_attribute :namespace - - # Does the object need a number that is a valid float? - class_attribute :validate_float - - attr_reader :number, :opts - - DEFAULTS = { - # Used in number_to_delimited - # These are also the defaults for 'currency', 'percentage', 'precision', and 'human' - format: { - # Sets the separator between the units, for more precision (e.g. 1.0 / 2.0 == 0.5) - separator: ".", - # Delimits thousands (e.g. 1,000,000 is a million) (always in groups of three) - delimiter: ",", - # Number of decimals, behind the separator (the number 1 with a precision of 2 gives: 1.00) - precision: 3, - # If set to true, precision will mean the number of significant digits instead - # of the number of decimal digits (1234 with precision 2 becomes 1200, 1.23543 becomes 1.2) - significant: false, - # If set, the zeros after the decimal separator will always be stripped (eg.: 1.200 will be 1.2) - strip_insignificant_zeros: false - }, - - # Used in number_to_currency - currency: { - format: { - format: "%u%n", - negative_format: "-%u%n", - unit: "$", - # These five are to override number.format and are optional - separator: ".", - delimiter: ",", - precision: 2, - significant: false, - strip_insignificant_zeros: false - } - }, - - # Used in number_to_percentage - percentage: { - format: { - delimiter: "", - format: "%n%" - } - }, - - # Used in number_to_rounded - precision: { - format: { - delimiter: "" - } - }, - - # Used in number_to_human_size and number_to_human - human: { - format: { - # These five are to override number.format and are optional - delimiter: "", - precision: 3, - significant: true, - strip_insignificant_zeros: true - }, - # Used in number_to_human_size - storage_units: { - # Storage units output formatting. - # %u is the storage unit, %n is the number (default: 2 MB) - format: "%n %u", - units: { - byte: "Bytes", - kb: "KB", - mb: "MB", - gb: "GB", - tb: "TB" - } - }, - # Used in number_to_human - decimal_units: { - format: "%n %u", - # Decimal units output formatting - # By default we will only quantify some of the exponents - # but the commented ones might be defined or overridden - # by the user. - units: { - # femto: Quadrillionth - # pico: Trillionth - # nano: Billionth - # micro: Millionth - # mili: Thousandth - # centi: Hundredth - # deci: Tenth - unit: "", - # ten: - # one: Ten - # other: Tens - # hundred: Hundred - thousand: "Thousand", - million: "Million", - billion: "Billion", - trillion: "Trillion", - quadrillion: "Quadrillion" - } - } - } - } - - def self.convert(number, options) - new(number, options).execute - end - - def initialize(number, options) - @number = number - @opts = options.symbolize_keys - end - - def execute - if !number - nil - elsif validate_float? && !valid_float? - number - else - convert - end - end - - private - - def options - @options ||= format_options.merge(opts) - end - - def format_options - default_format_options.merge!(i18n_format_options) - end - - def default_format_options - options = DEFAULTS[:format].dup - options.merge!(DEFAULTS[namespace][:format]) if namespace - options - end - - def i18n_format_options - locale = opts[:locale] - options = I18n.translate(:'number.format', locale: locale, default: {}).dup - - if namespace - options.merge!(I18n.translate(:"number.#{namespace}.format", locale: locale, default: {})) - end - - options - end - - def translate_number_value_with_default(key, i18n_options = {}) - I18n.translate(key, { default: default_value(key), scope: :number }.merge!(i18n_options)) - end - - def translate_in_locale(key, i18n_options = {}) - translate_number_value_with_default(key, { locale: options[:locale] }.merge(i18n_options)) - end - - def default_value(key) - key.split(".").reduce(DEFAULTS) { |defaults, k| defaults[k.to_sym] } - end - - def valid_float? - Float(number) - rescue ArgumentError, TypeError - false - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_currency_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_currency_converter.rb deleted file mode 100644 index 0f9dce722f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_currency_converter.rb +++ /dev/null @@ -1,44 +0,0 @@ -require "active_support/core_ext/numeric/inquiry" - -module ActiveSupport - module NumberHelper - class NumberToCurrencyConverter < NumberConverter # :nodoc: - self.namespace = :currency - - def convert - number = self.number.to_s.strip - format = options[:format] - - if number.to_f.negative? - format = options[:negative_format] - number = absolute_value(number) - end - - rounded_number = NumberToRoundedConverter.convert(number, options) - format.gsub("%n".freeze, rounded_number).gsub("%u".freeze, options[:unit]) - end - - private - - def absolute_value(number) - number.respond_to?(:abs) ? number.abs : number.sub(/\A-/, "") - end - - def options - @options ||= begin - defaults = default_format_options.merge(i18n_opts) - # Override negative format if format options are given - defaults[:negative_format] = "-#{opts[:format]}" if opts[:format] - defaults.merge!(opts) - end - end - - def i18n_opts - # Set International negative format if it does not exist - i18n = i18n_format_options - i18n[:negative_format] ||= "-#{i18n[:format]}" if i18n[:format] - i18n - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_delimited_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_delimited_converter.rb deleted file mode 100644 index e3b35531b1..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_delimited_converter.rb +++ /dev/null @@ -1,27 +0,0 @@ -module ActiveSupport - module NumberHelper - class NumberToDelimitedConverter < NumberConverter #:nodoc: - self.validate_float = true - - DEFAULT_DELIMITER_REGEX = /(\d)(?=(\d\d\d)+(?!\d))/ - - def convert - parts.join(options[:separator]) - end - - private - - def parts - left, right = number.to_s.split(".".freeze) - left.gsub!(delimiter_pattern) do |digit_to_delimit| - "#{digit_to_delimit}#{options[:delimiter]}" - end - [left, right].compact - end - - def delimiter_pattern - options.fetch(:delimiter_pattern, DEFAULT_DELIMITER_REGEX) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_human_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_human_converter.rb deleted file mode 100644 index 040343b5dd..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_human_converter.rb +++ /dev/null @@ -1,66 +0,0 @@ -module ActiveSupport - module NumberHelper - class NumberToHumanConverter < NumberConverter # :nodoc: - DECIMAL_UNITS = { 0 => :unit, 1 => :ten, 2 => :hundred, 3 => :thousand, 6 => :million, 9 => :billion, 12 => :trillion, 15 => :quadrillion, - -1 => :deci, -2 => :centi, -3 => :mili, -6 => :micro, -9 => :nano, -12 => :pico, -15 => :femto } - INVERTED_DECIMAL_UNITS = DECIMAL_UNITS.invert - - self.namespace = :human - self.validate_float = true - - def convert # :nodoc: - @number = RoundingHelper.new(options).round(number) - @number = Float(number) - - # for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files - unless options.key?(:strip_insignificant_zeros) - options[:strip_insignificant_zeros] = true - end - - units = opts[:units] - exponent = calculate_exponent(units) - @number = number / (10**exponent) - - rounded_number = NumberToRoundedConverter.convert(number, options) - unit = determine_unit(units, exponent) - format.gsub("%n".freeze, rounded_number).gsub("%u".freeze, unit).strip - end - - private - - def format - options[:format] || translate_in_locale("human.decimal_units.format") - end - - def determine_unit(units, exponent) - exp = DECIMAL_UNITS[exponent] - case units - when Hash - units[exp] || "" - when String, Symbol - I18n.translate("#{units}.#{exp}", locale: options[:locale], count: number.to_i) - else - translate_in_locale("human.decimal_units.units.#{exp}", count: number.to_i) - end - end - - def calculate_exponent(units) - exponent = number != 0 ? Math.log10(number.abs).floor : 0 - unit_exponents(units).find { |e| exponent >= e } || 0 - end - - def unit_exponents(units) - case units - when Hash - units - when String, Symbol - I18n.translate(units.to_s, locale: options[:locale], raise: true) - when nil - translate_in_locale("human.decimal_units.units", raise: true) - else - raise ArgumentError, ":units must be a Hash or String translation scope." - end.keys.map { |e_name| INVERTED_DECIMAL_UNITS[e_name] }.sort_by(&:-@) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_human_size_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_human_size_converter.rb deleted file mode 100644 index f263dbe9f8..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_human_size_converter.rb +++ /dev/null @@ -1,57 +0,0 @@ -module ActiveSupport - module NumberHelper - class NumberToHumanSizeConverter < NumberConverter #:nodoc: - STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb, :pb, :eb] - - self.namespace = :human - self.validate_float = true - - def convert - @number = Float(number) - - # for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files - unless options.key?(:strip_insignificant_zeros) - options[:strip_insignificant_zeros] = true - end - - if smaller_than_base? - number_to_format = number.to_i.to_s - else - human_size = number / (base**exponent) - number_to_format = NumberToRoundedConverter.convert(human_size, options) - end - conversion_format.gsub("%n".freeze, number_to_format).gsub("%u".freeze, unit) - end - - private - - def conversion_format - translate_number_value_with_default("human.storage_units.format", locale: options[:locale], raise: true) - end - - def unit - translate_number_value_with_default(storage_unit_key, locale: options[:locale], count: number.to_i, raise: true) - end - - def storage_unit_key - key_end = smaller_than_base? ? "byte" : STORAGE_UNITS[exponent] - "human.storage_units.units.#{key_end}" - end - - def exponent - max = STORAGE_UNITS.size - 1 - exp = (Math.log(number) / Math.log(base)).to_i - exp = max if exp > max # avoid overflow for the highest unit - exp - end - - def smaller_than_base? - number.to_i < base - end - - def base - 1024 - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_percentage_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_percentage_converter.rb deleted file mode 100644 index ac647ca9b7..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_percentage_converter.rb +++ /dev/null @@ -1,12 +0,0 @@ -module ActiveSupport - module NumberHelper - class NumberToPercentageConverter < NumberConverter # :nodoc: - self.namespace = :percentage - - def convert - rounded_number = NumberToRoundedConverter.convert(number, options) - options[:format].gsub("%n".freeze, rounded_number) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_phone_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_phone_converter.rb deleted file mode 100644 index 1de9f50f34..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_phone_converter.rb +++ /dev/null @@ -1,56 +0,0 @@ -module ActiveSupport - module NumberHelper - class NumberToPhoneConverter < NumberConverter #:nodoc: - def convert - str = country_code(opts[:country_code]) - str << convert_to_phone_number(number.to_s.strip) - str << phone_ext(opts[:extension]) - end - - private - - def convert_to_phone_number(number) - if opts[:area_code] - convert_with_area_code(number) - else - convert_without_area_code(number) - end - end - - def convert_with_area_code(number) - default_pattern = /(\d{1,3})(\d{3})(\d{4}$)/ - number.gsub!(regexp_pattern(default_pattern), - "(\\1) \\2#{delimiter}\\3") - number - end - - def convert_without_area_code(number) - default_pattern = /(\d{0,3})(\d{3})(\d{4})$/ - number.gsub!(regexp_pattern(default_pattern), - "\\1#{delimiter}\\2#{delimiter}\\3") - number.slice!(0, 1) if start_with_delimiter?(number) - number - end - - def start_with_delimiter?(number) - delimiter.present? && number.start_with?(delimiter) - end - - def delimiter - opts[:delimiter] || "-" - end - - def country_code(code) - code.blank? ? "" : "+#{code}#{delimiter}" - end - - def phone_ext(ext) - ext.blank? ? "" : " x #{ext}" - end - - def regexp_pattern(default_pattern) - opts.fetch :pattern, default_pattern - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_rounded_converter.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_rounded_converter.rb deleted file mode 100644 index c32d85a45f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/number_to_rounded_converter.rb +++ /dev/null @@ -1,72 +0,0 @@ -module ActiveSupport - module NumberHelper - class NumberToRoundedConverter < NumberConverter # :nodoc: - self.namespace = :precision - self.validate_float = true - - def convert - helper = RoundingHelper.new(options) - rounded_number = helper.round(number) - - if precision = options[:precision] - if options[:significant] && precision > 0 - digits = helper.digit_count(rounded_number) - precision -= digits - precision = 0 if precision < 0 # don't let it be negative - end - - formatted_string = - if BigDecimal === rounded_number && rounded_number.finite? - s = rounded_number.to_s("F") - s << "0".freeze * precision - a, b = s.split(".".freeze, 2) - a << ".".freeze - a << b[0, precision] - else - "%00.#{precision}f" % rounded_number - end - else - formatted_string = rounded_number - end - - delimited_number = NumberToDelimitedConverter.convert(formatted_string, options) - format_number(delimited_number) - end - - private - - def digits_and_rounded_number(precision) - if zero? - [1, 0] - else - digits = digit_count(number) - multiplier = 10**(digits - precision) - rounded_number = calculate_rounded_number(multiplier) - digits = digit_count(rounded_number) # After rounding, the number of digits may have changed - [digits, rounded_number] - end - end - - def calculate_rounded_number(multiplier) - (number / BigDecimal.new(multiplier.to_f.to_s)).round * multiplier - end - - def digit_count(number) - number.zero? ? 1 : (Math.log10(absolute_number(number)) + 1).floor - end - - def strip_insignificant_zeros - options[:strip_insignificant_zeros] - end - - def format_number(number) - if strip_insignificant_zeros - escaped_separator = Regexp.escape(options[:separator]) - number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, "") - else - number - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/rounding_helper.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/rounding_helper.rb deleted file mode 100644 index d9644df17d..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/number_helper/rounding_helper.rb +++ /dev/null @@ -1,64 +0,0 @@ -module ActiveSupport - module NumberHelper - class RoundingHelper # :nodoc: - attr_reader :options - - def initialize(options) - @options = options - end - - def round(number) - return number unless precision - number = convert_to_decimal(number) - if significant && precision > 0 - round_significant(number) - else - round_without_significant(number) - end - end - - def digit_count(number) - return 1 if number.zero? - (Math.log10(absolute_number(number)) + 1).floor - end - - private - def round_without_significant(number) - number = number.round(precision) - number = number.to_i if precision == 0 && number.finite? - number = number.abs if number.zero? # prevent showing negative zeros - number - end - - def round_significant(number) - return 0 if number.zero? - digits = digit_count(number) - multiplier = 10**(digits - precision) - (number / BigDecimal.new(multiplier.to_f.to_s)).round * multiplier - end - - def convert_to_decimal(number) - case number - when Float, String - number = BigDecimal(number.to_s) - when Rational - number = BigDecimal(number, digit_count(number.to_i) + precision) - else - number = number.to_d - end - end - - def precision - options[:precision] - end - - def significant - options[:significant] - end - - def absolute_number(number) - number.respond_to?(:abs) ? number.abs : number.to_d.abs - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/option_merger.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/option_merger.rb deleted file mode 100644 index 0f2caa98f2..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/option_merger.rb +++ /dev/null @@ -1,25 +0,0 @@ -require "active_support/core_ext/hash/deep_merge" - -module ActiveSupport - class OptionMerger #:nodoc: - instance_methods.each do |method| - undef_method(method) if method !~ /^(__|instance_eval|class|object_id)/ - end - - def initialize(context, options) - @context, @options = context, options - end - - private - def method_missing(method, *arguments, &block) - if arguments.first.is_a?(Proc) - proc = arguments.pop - arguments << lambda { |*args| @options.deep_merge(proc.call(*args)) } - else - arguments << (arguments.last.respond_to?(:to_hash) ? @options.deep_merge(arguments.pop) : @options.dup) - end - - @context.__send__(method, *arguments, &block) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/ordered_hash.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/ordered_hash.rb deleted file mode 100644 index 3aa0a14f04..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/ordered_hash.rb +++ /dev/null @@ -1,48 +0,0 @@ -require "yaml" - -YAML.add_builtin_type("omap") do |type, val| - ActiveSupport::OrderedHash[val.map { |v| v.to_a.first }] -end - -module ActiveSupport - # DEPRECATED: ActiveSupport::OrderedHash implements a hash that preserves - # insertion order. - # - # oh = ActiveSupport::OrderedHash.new - # oh[:a] = 1 - # oh[:b] = 2 - # oh.keys # => [:a, :b], this order is guaranteed - # - # Also, maps the +omap+ feature for YAML files - # (See http://yaml.org/type/omap.html) to support ordered items - # when loading from yaml. - # - # ActiveSupport::OrderedHash is namespaced to prevent conflicts - # with other implementations. - class OrderedHash < ::Hash - def to_yaml_type - "!tag:yaml.org,2002:omap" - end - - def encode_with(coder) - coder.represent_seq "!omap", map { |k, v| { k => v } } - end - - def select(*args, &block) - dup.tap { |hash| hash.select!(*args, &block) } - end - - def reject(*args, &block) - dup.tap { |hash| hash.reject!(*args, &block) } - end - - def nested_under_indifferent_access - self - end - - # Returns true to make sure that this hash is extractable via Array#extract_options! - def extractable_options? - true - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/ordered_options.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/ordered_options.rb deleted file mode 100644 index 04d6dfaf9c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/ordered_options.rb +++ /dev/null @@ -1,83 +0,0 @@ -require "active_support/core_ext/object/blank" - -module ActiveSupport - # Usually key value pairs are handled something like this: - # - # h = {} - # h[:boy] = 'John' - # h[:girl] = 'Mary' - # h[:boy] # => 'John' - # h[:girl] # => 'Mary' - # h[:dog] # => nil - # - # Using +OrderedOptions+, the above code could be reduced to: - # - # h = ActiveSupport::OrderedOptions.new - # h.boy = 'John' - # h.girl = 'Mary' - # h.boy # => 'John' - # h.girl # => 'Mary' - # h.dog # => nil - # - # To raise an exception when the value is blank, append a - # bang to the key name, like: - # - # h.dog! # => raises KeyError: key not found: :dog - # - class OrderedOptions < Hash - alias_method :_get, :[] # preserve the original #[] method - protected :_get # make it protected - - def []=(key, value) - super(key.to_sym, value) - end - - def [](key) - super(key.to_sym) - end - - def method_missing(name, *args) - name_string = name.to_s - if name_string.chomp!("=") - self[name_string] = args.first - else - bangs = name_string.chomp!("!") - - if bangs - fetch(name_string.to_sym).presence || raise(KeyError.new("#{name_string} is blank.")) - else - self[name_string] - end - end - end - - def respond_to_missing?(name, include_private) - true - end - end - - # +InheritableOptions+ provides a constructor to build an +OrderedOptions+ - # hash inherited from another hash. - # - # Use this if you already have some hash and you want to create a new one based on it. - # - # h = ActiveSupport::InheritableOptions.new({ girl: 'Mary', boy: 'John' }) - # h.girl # => 'Mary' - # h.boy # => 'John' - class InheritableOptions < OrderedOptions - def initialize(parent = nil) - if parent.kind_of?(OrderedOptions) - # use the faster _get when dealing with OrderedOptions - super() { |h, k| parent._get(k) } - elsif parent - super() { |h, k| parent[k] } - else - super() - end - end - - def inheritable_copy - self.class.new(self) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/per_thread_registry.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/per_thread_registry.rb deleted file mode 100644 index 02431704d3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/per_thread_registry.rb +++ /dev/null @@ -1,58 +0,0 @@ -require "active_support/core_ext/module/delegation" - -module ActiveSupport - # NOTE: This approach has been deprecated for end-user code in favor of {thread_mattr_accessor}[rdoc-ref:Module#thread_mattr_accessor] and friends. - # Please use that approach instead. - # - # This module is used to encapsulate access to thread local variables. - # - # Instead of polluting the thread locals namespace: - # - # Thread.current[:connection_handler] - # - # you define a class that extends this module: - # - # module ActiveRecord - # class RuntimeRegistry - # extend ActiveSupport::PerThreadRegistry - # - # attr_accessor :connection_handler - # end - # end - # - # and invoke the declared instance accessors as class methods. So - # - # ActiveRecord::RuntimeRegistry.connection_handler = connection_handler - # - # sets a connection handler local to the current thread, and - # - # ActiveRecord::RuntimeRegistry.connection_handler - # - # returns a connection handler local to the current thread. - # - # This feature is accomplished by instantiating the class and storing the - # instance as a thread local keyed by the class name. In the example above - # a key "ActiveRecord::RuntimeRegistry" is stored in Thread.current. - # The class methods proxy to said thread local instance. - # - # If the class has an initializer, it must accept no arguments. - module PerThreadRegistry - def self.extended(object) - object.instance_variable_set "@per_thread_registry_key", object.name.freeze - end - - def instance - Thread.current[@per_thread_registry_key] ||= new - end - - private - def method_missing(name, *args, &block) - # Caches the method definition as a singleton method of the receiver. - # - # By letting #delegate handle it, we avoid an enclosure that'll capture args. - singleton_class.delegate name, to: :instance - - send(name, *args, &block) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/proxy_object.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/proxy_object.rb deleted file mode 100644 index 20a0fd8e62..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/proxy_object.rb +++ /dev/null @@ -1,13 +0,0 @@ -module ActiveSupport - # A class with no predefined methods that behaves similarly to Builder's - # BlankSlate. Used for proxy classes. - class ProxyObject < ::BasicObject - undef_method :== - undef_method :equal? - - # Let ActiveSupport::ProxyObject at least raise exceptions. - def raise(*args) - ::Object.send(:raise, *args) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/rails.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/rails.rb deleted file mode 100644 index f6b018f0d3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/rails.rb +++ /dev/null @@ -1,33 +0,0 @@ -# This is private interface. -# -# Rails components cherry pick from Active Support as needed, but there are a -# few features that are used for sure in some way or another and it is not worth -# putting individual requires absolutely everywhere. Think blank? for example. -# -# This file is loaded by every Rails component except Active Support itself, -# but it does not belong to the Rails public interface. It is internal to -# Rails and can change anytime. - -# Defines Object#blank? and Object#present?. -require "active_support/core_ext/object/blank" - -# Rails own autoload, eager_load, etc. -require "active_support/dependencies/autoload" - -# Support for ClassMethods and the included macro. -require "active_support/concern" - -# Defines Class#class_attribute. -require "active_support/core_ext/class/attribute" - -# Defines Module#delegate. -require "active_support/core_ext/module/delegation" - -# Defines ActiveSupport::Deprecation. -require "active_support/deprecation" - -# Defines Regexp#match?. -# -# This should be removed when Rails needs Ruby 2.4 or later, and the require -# added where other Regexp extensions are being used (easy to grep). -require "active_support/core_ext/regexp" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/railtie.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/railtie.rb deleted file mode 100644 index b875875afe..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/railtie.rb +++ /dev/null @@ -1,51 +0,0 @@ -require "active_support" -require "active_support/i18n_railtie" - -module ActiveSupport - class Railtie < Rails::Railtie # :nodoc: - config.active_support = ActiveSupport::OrderedOptions.new - - config.eager_load_namespaces << ActiveSupport - - initializer "active_support.deprecation_behavior" do |app| - if deprecation = app.config.active_support.deprecation - ActiveSupport::Deprecation.behavior = deprecation - end - end - - # Sets the default value for Time.zone - # If assigned value cannot be matched to a TimeZone, an exception will be raised. - initializer "active_support.initialize_time_zone" do |app| - begin - TZInfo::DataSource.get - rescue TZInfo::DataSourceNotFound => e - raise e.exception "tzinfo-data is not present. Please add gem 'tzinfo-data' to your Gemfile and run bundle install" - end - require "active_support/core_ext/time/zones" - zone_default = Time.find_zone!(app.config.time_zone) - - unless zone_default - raise "Value assigned to config.time_zone not recognized. " \ - 'Run "rake time:zones:all" for a time zone names list.' - end - - Time.zone_default = zone_default - end - - # Sets the default week start - # If assigned value is not a valid day symbol (e.g. :sunday, :monday, ...), an exception will be raised. - initializer "active_support.initialize_beginning_of_week" do |app| - require "active_support/core_ext/date/calculations" - beginning_of_week_default = Date.find_beginning_of_week!(app.config.beginning_of_week) - - Date.beginning_of_week_default = beginning_of_week_default - end - - initializer "active_support.set_configs" do |app| - app.config.active_support.each do |k, v| - k = "#{k}=" - ActiveSupport.send(k, v) if ActiveSupport.respond_to? k - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/reloader.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/reloader.rb deleted file mode 100644 index 121c621751..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/reloader.rb +++ /dev/null @@ -1,129 +0,0 @@ -require "active_support/execution_wrapper" - -module ActiveSupport - #-- - # This class defines several callbacks: - # - # to_prepare -- Run once at application startup, and also from - # +to_run+. - # - # to_run -- Run before a work run that is reloading. If - # +reload_classes_only_on_change+ is true (the default), the class - # unload will have already occurred. - # - # to_complete -- Run after a work run that has reloaded. If - # +reload_classes_only_on_change+ is false, the class unload will - # have occurred after the work run, but before this callback. - # - # before_class_unload -- Run immediately before the classes are - # unloaded. - # - # after_class_unload -- Run immediately after the classes are - # unloaded. - # - class Reloader < ExecutionWrapper - define_callbacks :prepare - - define_callbacks :class_unload - - def self.to_prepare(*args, &block) - set_callback(:prepare, *args, &block) - end - - def self.before_class_unload(*args, &block) - set_callback(:class_unload, *args, &block) - end - - def self.after_class_unload(*args, &block) - set_callback(:class_unload, :after, *args, &block) - end - - to_run(:after) { self.class.prepare! } - - # Initiate a manual reload - def self.reload! - executor.wrap do - new.tap do |instance| - begin - instance.run! - ensure - instance.complete! - end - end - end - prepare! - end - - def self.run! # :nodoc: - if check! - super - else - Null - end - end - - # Run the supplied block as a work unit, reloading code as needed - def self.wrap - executor.wrap do - super - end - end - - class_attribute :executor - class_attribute :check - - self.executor = Executor - self.check = lambda { false } - - def self.check! # :nodoc: - @should_reload ||= check.call - end - - def self.reloaded! # :nodoc: - @should_reload = false - end - - def self.prepare! # :nodoc: - new.run_callbacks(:prepare) - end - - def initialize - super - @locked = false - end - - # Acquire the ActiveSupport::Dependencies::Interlock unload lock, - # ensuring it will be released automatically - def require_unload_lock! - unless @locked - ActiveSupport::Dependencies.interlock.start_unloading - @locked = true - end - end - - # Release the unload lock if it has been previously obtained - def release_unload_lock! - if @locked - @locked = false - ActiveSupport::Dependencies.interlock.done_unloading - end - end - - def run! # :nodoc: - super - release_unload_lock! - end - - def class_unload!(&block) # :nodoc: - require_unload_lock! - run_callbacks(:class_unload, &block) - end - - def complete! # :nodoc: - super - self.class.reloaded! - ensure - release_unload_lock! - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/rescuable.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/rescuable.rb deleted file mode 100644 index 12ec8bf1b8..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/rescuable.rb +++ /dev/null @@ -1,173 +0,0 @@ -require "active_support/concern" -require "active_support/core_ext/class/attribute" -require "active_support/core_ext/string/inflections" - -module ActiveSupport - # Rescuable module adds support for easier exception handling. - module Rescuable - extend Concern - - included do - class_attribute :rescue_handlers - self.rescue_handlers = [] - end - - module ClassMethods - # Rescue exceptions raised in controller actions. - # - # rescue_from receives a series of exception classes or class - # names, and a trailing :with option with the name of a method - # or a Proc object to be called to handle them. Alternatively a block can - # be given. - # - # Handlers that take one argument will be called with the exception, so - # that the exception can be inspected when dealing with it. - # - # Handlers are inherited. They are searched from right to left, from - # bottom to top, and up the hierarchy. The handler of the first class for - # which exception.is_a?(klass) holds true is the one invoked, if - # any. - # - # class ApplicationController < ActionController::Base - # rescue_from User::NotAuthorized, with: :deny_access # self defined exception - # rescue_from ActiveRecord::RecordInvalid, with: :show_errors - # - # rescue_from 'MyAppError::Base' do |exception| - # render xml: exception, status: 500 - # end - # - # private - # def deny_access - # ... - # end - # - # def show_errors(exception) - # exception.record.new_record? ? ... - # end - # end - # - # Exceptions raised inside exception handlers are not propagated up. - def rescue_from(*klasses, with: nil, &block) - unless with - if block_given? - with = block - else - raise ArgumentError, "Need a handler. Pass the with: keyword argument or provide a block." - end - end - - klasses.each do |klass| - key = if klass.is_a?(Module) && klass.respond_to?(:===) - klass.name - elsif klass.is_a?(String) - klass - else - raise ArgumentError, "#{klass.inspect} must be an Exception class or a String referencing an Exception class" - end - - # Put the new handler at the end because the list is read in reverse. - self.rescue_handlers += [[key, with]] - end - end - - # Matches an exception to a handler based on the exception class. - # - # If no handler matches the exception, check for a handler matching the - # (optional) exception.cause. If no handler matches the exception or its - # cause, this returns +nil+, so you can deal with unhandled exceptions. - # Be sure to re-raise unhandled exceptions if this is what you expect. - # - # begin - # … - # rescue => exception - # rescue_with_handler(exception) || raise - # end - # - # Returns the exception if it was handled and +nil+ if it was not. - def rescue_with_handler(exception, object: self, visited_exceptions: []) - visited_exceptions << exception - - if handler = handler_for_rescue(exception, object: object) - handler.call exception - exception - elsif exception - if visited_exceptions.include?(exception.cause) - nil - else - rescue_with_handler(exception.cause, object: object, visited_exceptions: visited_exceptions) - end - end - end - - def handler_for_rescue(exception, object: self) #:nodoc: - case rescuer = find_rescue_handler(exception) - when Symbol - method = object.method(rescuer) - if method.arity == 0 - -> e { method.call } - else - method - end - when Proc - if rescuer.arity == 0 - -> e { object.instance_exec(&rescuer) } - else - -> e { object.instance_exec(e, &rescuer) } - end - end - end - - private - def find_rescue_handler(exception) - if exception - # Handlers are in order of declaration but the most recently declared - # is the highest priority match, so we search for matching handlers - # in reverse. - _, handler = rescue_handlers.reverse_each.detect do |class_or_name, _| - if klass = constantize_rescue_handler_class(class_or_name) - klass === exception - end - end - - handler - end - end - - def constantize_rescue_handler_class(class_or_name) - case class_or_name - when String, Symbol - begin - # Try a lexical lookup first since we support - # - # class Super - # rescue_from 'Error', with: … - # end - # - # class Sub - # class Error < StandardError; end - # end - # - # so an Error raised in Sub will hit the 'Error' handler. - const_get class_or_name - rescue NameError - class_or_name.safe_constantize - end - else - class_or_name - end - end - end - - # Delegates to the class method, but uses the instance as the subject for - # rescue_from handlers (method calls, instance_exec blocks). - def rescue_with_handler(exception) - self.class.rescue_with_handler exception, object: self - end - - # Internal handler lookup. Delegates to class method. Some libraries call - # this directly, so keeping it around for compatibility. - def handler_for_rescue(exception) #:nodoc: - self.class.handler_for_rescue exception, object: self - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/security_utils.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/security_utils.rb deleted file mode 100644 index b655d64449..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/security_utils.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "digest" - -module ActiveSupport - module SecurityUtils - # Constant time string comparison. - # - # The values compared should be of fixed length, such as strings - # that have already been processed by HMAC. This should not be used - # on variable length plaintext strings because it could leak length info - # via timing attacks. - def secure_compare(a, b) - return false unless a.bytesize == b.bytesize - - l = a.unpack "C#{a.bytesize}" - - res = 0 - b.each_byte { |byte| res |= byte ^ l.shift } - res == 0 - end - module_function :secure_compare - - def variable_size_secure_compare(a, b) # :nodoc: - secure_compare(::Digest::SHA256.hexdigest(a), ::Digest::SHA256.hexdigest(b)) - end - module_function :variable_size_secure_compare - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/string_inquirer.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/string_inquirer.rb deleted file mode 100644 index 90eac89c9e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/string_inquirer.rb +++ /dev/null @@ -1,32 +0,0 @@ -module ActiveSupport - # Wrapping a string in this class gives you a prettier way to test - # for equality. The value returned by Rails.env is wrapped - # in a StringInquirer object, so instead of calling this: - # - # Rails.env == 'production' - # - # you can call this: - # - # Rails.env.production? - # - # == Instantiating a new StringInquirer - # - # vehicle = ActiveSupport::StringInquirer.new('car') - # vehicle.car? # => true - # vehicle.bike? # => false - class StringInquirer < String - private - - def respond_to_missing?(method_name, include_private = false) - (method_name[-1] == "?") || super - end - - def method_missing(method_name, *arguments) - if method_name[-1] == "?" - self == method_name[0..-2] - else - super - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/subscriber.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/subscriber.rb deleted file mode 100644 index 2924139755..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/subscriber.rb +++ /dev/null @@ -1,124 +0,0 @@ -require "active_support/per_thread_registry" -require "active_support/notifications" - -module ActiveSupport - # ActiveSupport::Subscriber is an object set to consume - # ActiveSupport::Notifications. The subscriber dispatches notifications to - # a registered object based on its given namespace. - # - # An example would be an Active Record subscriber responsible for collecting - # statistics about queries: - # - # module ActiveRecord - # class StatsSubscriber < ActiveSupport::Subscriber - # attach_to :active_record - # - # def sql(event) - # Statsd.timing("sql.#{event.payload[:name]}", event.duration) - # end - # end - # end - # - # After configured, whenever a "sql.active_record" notification is published, - # it will properly dispatch the event (ActiveSupport::Notifications::Event) to - # the +sql+ method. - class Subscriber - class << self - # Attach the subscriber to a namespace. - def attach_to(namespace, subscriber = new, notifier = ActiveSupport::Notifications) - @namespace = namespace - @subscriber = subscriber - @notifier = notifier - - subscribers << subscriber - - # Add event subscribers for all existing methods on the class. - subscriber.public_methods(false).each do |event| - add_event_subscriber(event) - end - end - - # Adds event subscribers for all new methods added to the class. - def method_added(event) - # Only public methods are added as subscribers, and only if a notifier - # has been set up. This means that subscribers will only be set up for - # classes that call #attach_to. - if public_method_defined?(event) && notifier - add_event_subscriber(event) - end - end - - def subscribers - @@subscribers ||= [] - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :subscriber, :notifier, :namespace - - private - - def add_event_subscriber(event) # :doc: - return if %w{ start finish }.include?(event.to_s) - - pattern = "#{event}.#{namespace}" - - # Don't add multiple subscribers (eg. if methods are redefined). - return if subscriber.patterns.include?(pattern) - - subscriber.patterns << pattern - notifier.subscribe(pattern, subscriber) - end - end - - attr_reader :patterns # :nodoc: - - def initialize - @queue_key = [self.class.name, object_id].join "-" - @patterns = [] - super - end - - def start(name, id, payload) - e = ActiveSupport::Notifications::Event.new(name, Time.now, nil, id, payload) - parent = event_stack.last - parent << e if parent - - event_stack.push e - end - - def finish(name, id, payload) - finished = Time.now - event = event_stack.pop - event.end = finished - event.payload.merge!(payload) - - method = name.split(".".freeze).first - send(method, event) - end - - private - - def event_stack - SubscriberQueueRegistry.instance.get_queue(@queue_key) - end - end - - # This is a registry for all the event stacks kept for subscribers. - # - # See the documentation of ActiveSupport::PerThreadRegistry - # for further details. - class SubscriberQueueRegistry # :nodoc: - extend PerThreadRegistry - - def initialize - @registry = {} - end - - def get_queue(queue_key) - @registry[queue_key] ||= [] - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/tagged_logging.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/tagged_logging.rb deleted file mode 100644 index ad134c49b6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/tagged_logging.rb +++ /dev/null @@ -1,77 +0,0 @@ -require "active_support/core_ext/module/delegation" -require "active_support/core_ext/object/blank" -require "logger" -require "active_support/logger" - -module ActiveSupport - # Wraps any standard Logger object to provide tagging capabilities. - # - # logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) - # logger.tagged('BCX') { logger.info 'Stuff' } # Logs "[BCX] Stuff" - # logger.tagged('BCX', "Jason") { logger.info 'Stuff' } # Logs "[BCX] [Jason] Stuff" - # logger.tagged('BCX') { logger.tagged('Jason') { logger.info 'Stuff' } } # Logs "[BCX] [Jason] Stuff" - # - # This is used by the default Rails.logger as configured by Railties to make - # it easy to stamp log lines with subdomains, request ids, and anything else - # to aid debugging of multi-user production applications. - module TaggedLogging - module Formatter # :nodoc: - # This method is invoked when a log event occurs. - def call(severity, timestamp, progname, msg) - super(severity, timestamp, progname, "#{tags_text}#{msg}") - end - - def tagged(*tags) - new_tags = push_tags(*tags) - yield self - ensure - pop_tags(new_tags.size) - end - - def push_tags(*tags) - tags.flatten.reject(&:blank?).tap do |new_tags| - current_tags.concat new_tags - end - end - - def pop_tags(size = 1) - current_tags.pop size - end - - def clear_tags! - current_tags.clear - end - - def current_tags - # We use our object ID here to avoid conflicting with other instances - thread_key = @thread_key ||= "activesupport_tagged_logging_tags:#{object_id}".freeze - Thread.current[thread_key] ||= [] - end - - def tags_text - tags = current_tags - if tags.any? - tags.collect { |tag| "[#{tag}] " }.join - end - end - end - - def self.new(logger) - # Ensure we set a default formatter so we aren't extending nil! - logger.formatter ||= ActiveSupport::Logger::SimpleFormatter.new - logger.formatter.extend Formatter - logger.extend(self) - end - - delegate :push_tags, :pop_tags, :clear_tags!, to: :formatter - - def tagged(*tags) - formatter.tagged(*tags) { yield self } - end - - def flush - clear_tags! - super if defined?(super) - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/test_case.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/test_case.rb deleted file mode 100644 index 3de4ccc1da..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/test_case.rb +++ /dev/null @@ -1,71 +0,0 @@ -gem "minitest" # make sure we get the gem, not stdlib -require "minitest" -require "active_support/testing/tagged_logging" -require "active_support/testing/setup_and_teardown" -require "active_support/testing/assertions" -require "active_support/testing/deprecation" -require "active_support/testing/declarative" -require "active_support/testing/isolation" -require "active_support/testing/constant_lookup" -require "active_support/testing/time_helpers" -require "active_support/testing/file_fixtures" -require "active_support/core_ext/kernel/reporting" - -module ActiveSupport - class TestCase < ::Minitest::Test - Assertion = Minitest::Assertion - - class << self - # Sets the order in which test cases are run. - # - # ActiveSupport::TestCase.test_order = :random # => :random - # - # Valid values are: - # * +:random+ (to run tests in random order) - # * +:parallel+ (to run tests in parallel) - # * +:sorted+ (to run tests alphabetically by method name) - # * +:alpha+ (equivalent to +:sorted+) - def test_order=(new_order) - ActiveSupport.test_order = new_order - end - - # Returns the order in which test cases are run. - # - # ActiveSupport::TestCase.test_order # => :random - # - # Possible values are +:random+, +:parallel+, +:alpha+, +:sorted+. - # Defaults to +:random+. - def test_order - ActiveSupport.test_order ||= :random - end - end - - alias_method :method_name, :name - - include ActiveSupport::Testing::TaggedLogging - include ActiveSupport::Testing::SetupAndTeardown - include ActiveSupport::Testing::Assertions - include ActiveSupport::Testing::Deprecation - include ActiveSupport::Testing::TimeHelpers - include ActiveSupport::Testing::FileFixtures - extend ActiveSupport::Testing::Declarative - - # test/unit backwards compatibility methods - alias :assert_raise :assert_raises - alias :assert_not_empty :refute_empty - alias :assert_not_equal :refute_equal - alias :assert_not_in_delta :refute_in_delta - alias :assert_not_in_epsilon :refute_in_epsilon - alias :assert_not_includes :refute_includes - alias :assert_not_instance_of :refute_instance_of - alias :assert_not_kind_of :refute_kind_of - alias :assert_no_match :refute_match - alias :assert_not_nil :refute_nil - alias :assert_not_operator :refute_operator - alias :assert_not_predicate :refute_predicate - alias :assert_not_respond_to :refute_respond_to - alias :assert_not_same :refute_same - - ActiveSupport.run_load_hooks(:active_support_test_case, self) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/assertions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/assertions.rb deleted file mode 100644 index 28cf2953bf..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/assertions.rb +++ /dev/null @@ -1,197 +0,0 @@ -module ActiveSupport - module Testing - module Assertions - UNTRACKED = Object.new # :nodoc: - - # Asserts that an expression is not truthy. Passes if object is - # +nil+ or +false+. "Truthy" means "considered true in a conditional" - # like if foo. - # - # assert_not nil # => true - # assert_not false # => true - # assert_not 'foo' # => Expected "foo" to be nil or false - # - # An error message can be specified. - # - # assert_not foo, 'foo should be false' - def assert_not(object, message = nil) - message ||= "Expected #{mu_pp(object)} to be nil or false" - assert !object, message - end - - # Assertion that the block should not raise an exception. - # - # Passes if evaluated code in the yielded block raises no exception. - # - # assert_nothing_raised do - # perform_service(param: 'no_exception') - # end - def assert_nothing_raised - yield - end - - # Test numeric difference between the return value of an expression as a - # result of what is evaluated in the yielded block. - # - # assert_difference 'Article.count' do - # post :create, params: { article: {...} } - # end - # - # An arbitrary expression is passed in and evaluated. - # - # assert_difference 'Article.last.comments(:reload).size' do - # post :create, params: { comment: {...} } - # end - # - # An arbitrary positive or negative difference can be specified. - # The default is 1. - # - # assert_difference 'Article.count', -1 do - # post :delete, params: { id: ... } - # end - # - # An array of expressions can also be passed in and evaluated. - # - # assert_difference [ 'Article.count', 'Post.count' ], 2 do - # post :create, params: { article: {...} } - # end - # - # A lambda or a list of lambdas can be passed in and evaluated: - # - # assert_difference ->{ Article.count }, 2 do - # post :create, params: { article: {...} } - # end - # - # assert_difference [->{ Article.count }, ->{ Post.count }], 2 do - # post :create, params: { article: {...} } - # end - # - # An error message can be specified. - # - # assert_difference 'Article.count', -1, 'An Article should be destroyed' do - # post :delete, params: { id: ... } - # end - def assert_difference(expression, difference = 1, message = nil, &block) - expressions = Array(expression) - - exps = expressions.map { |e| - e.respond_to?(:call) ? e : lambda { eval(e, block.binding) } - } - before = exps.map(&:call) - - retval = yield - - expressions.zip(exps).each_with_index do |(code, e), i| - error = "#{code.inspect} didn't change by #{difference}" - error = "#{message}.\n#{error}" if message - assert_equal(before[i] + difference, e.call, error) - end - - retval - end - - # Assertion that the numeric result of evaluating an expression is not - # changed before and after invoking the passed in block. - # - # assert_no_difference 'Article.count' do - # post :create, params: { article: invalid_attributes } - # end - # - # An error message can be specified. - # - # assert_no_difference 'Article.count', 'An Article should not be created' do - # post :create, params: { article: invalid_attributes } - # end - def assert_no_difference(expression, message = nil, &block) - assert_difference expression, 0, message, &block - end - - # Assertion that the result of evaluating an expression is changed before - # and after invoking the passed in block. - # - # assert_changes 'Status.all_good?' do - # post :create, params: { status: { ok: false } } - # end - # - # You can pass the block as a string to be evaluated in the context of - # the block. A lambda can be passed for the block as well. - # - # assert_changes -> { Status.all_good? } do - # post :create, params: { status: { ok: false } } - # end - # - # The assertion is useful to test side effects. The passed block can be - # anything that can be converted to string with #to_s. - # - # assert_changes :@object do - # @object = 42 - # end - # - # The keyword arguments :from and :to can be given to specify the - # expected initial value and the expected value after the block was - # executed. - # - # assert_changes :@object, from: nil, to: :foo do - # @object = :foo - # end - # - # An error message can be specified. - # - # assert_changes -> { Status.all_good? }, 'Expected the status to be bad' do - # post :create, params: { status: { incident: true } } - # end - def assert_changes(expression, message = nil, from: UNTRACKED, to: UNTRACKED, &block) - exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) } - - before = exp.call - retval = yield - - unless from == UNTRACKED - error = "#{expression.inspect} isn't #{from.inspect}" - error = "#{message}.\n#{error}" if message - assert from === before, error - end - - after = exp.call - - if to == UNTRACKED - error = "#{expression.inspect} didn't changed" - error = "#{message}.\n#{error}" if message - assert_not_equal before, after, error - else - error = "#{expression.inspect} didn't change to #{to}" - error = "#{message}.\n#{error}" if message - assert to === after, error - end - - retval - end - - # Assertion that the result of evaluating an expression is changed before - # and after invoking the passed in block. - # - # assert_no_changes 'Status.all_good?' do - # post :create, params: { status: { ok: true } } - # end - # - # An error message can be specified. - # - # assert_no_changes -> { Status.all_good? }, 'Expected the status to be good' do - # post :create, params: { status: { ok: false } } - # end - def assert_no_changes(expression, message = nil, &block) - exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) } - - before = exp.call - retval = yield - after = exp.call - - error = "#{expression.inspect} did change to #{after}" - error = "#{message}.\n#{error}" if message - assert_equal before, after, error - - retval - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/autorun.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/autorun.rb deleted file mode 100644 index 0440077d6f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/autorun.rb +++ /dev/null @@ -1,5 +0,0 @@ -gem "minitest" - -require "minitest" - -Minitest.autorun diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/constant_lookup.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/constant_lookup.rb deleted file mode 100644 index 647395d2b3..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/constant_lookup.rb +++ /dev/null @@ -1,49 +0,0 @@ -require "active_support/concern" -require "active_support/inflector" - -module ActiveSupport - module Testing - # Resolves a constant from a minitest spec name. - # - # Given the following spec-style test: - # - # describe WidgetsController, :index do - # describe "authenticated user" do - # describe "returns widgets" do - # it "has a controller that exists" do - # assert_kind_of WidgetsController, @controller - # end - # end - # end - # end - # - # The test will have the following name: - # - # "WidgetsController::index::authenticated user::returns widgets" - # - # The constant WidgetsController can be resolved from the name. - # The following code will resolve the constant: - # - # controller = determine_constant_from_test_name(name) do |constant| - # Class === constant && constant < ::ActionController::Metal - # end - module ConstantLookup - extend ::ActiveSupport::Concern - - module ClassMethods # :nodoc: - def determine_constant_from_test_name(test_name) - names = test_name.split "::" - while names.size > 0 do - names.last.sub!(/Test$/, "") - begin - constant = names.join("::").safe_constantize - break(constant) if yield(constant) - ensure - names.pop - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/declarative.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/declarative.rb deleted file mode 100644 index 53ab3ebf78..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/declarative.rb +++ /dev/null @@ -1,26 +0,0 @@ -module ActiveSupport - module Testing - module Declarative - unless defined?(Spec) - # Helper to define a test method using a String. Under the hood, it replaces - # spaces with underscores and defines the test method. - # - # test "verify something" do - # ... - # end - def test(name, &block) - test_name = "test_#{name.gsub(/\s+/, '_')}".to_sym - defined = method_defined? test_name - raise "#{test_name} is already defined in #{self}" if defined - if block_given? - define_method(test_name, &block) - else - define_method(test_name) do - flunk "No implementation provided for #{name}" - end - end - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/deprecation.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/deprecation.rb deleted file mode 100644 index 58911570e8..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/deprecation.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "active_support/deprecation" -require "active_support/core_ext/regexp" - -module ActiveSupport - module Testing - module Deprecation #:nodoc: - def assert_deprecated(match = nil, deprecator = nil, &block) - result, warnings = collect_deprecations(deprecator, &block) - assert !warnings.empty?, "Expected a deprecation warning within the block but received none" - if match - match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp) - assert warnings.any? { |w| match.match?(w) }, "No deprecation warning matched #{match}: #{warnings.join(', ')}" - end - result - end - - def assert_not_deprecated(deprecator = nil, &block) - result, deprecations = collect_deprecations(deprecator, &block) - assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}" - result - end - - def collect_deprecations(deprecator = nil) - deprecator ||= ActiveSupport::Deprecation - old_behavior = deprecator.behavior - deprecations = [] - deprecator.behavior = Proc.new do |message, callstack| - deprecations << message - end - result = yield - [result, deprecations] - ensure - deprecator.behavior = old_behavior - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/file_fixtures.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/file_fixtures.rb deleted file mode 100644 index affb84cda5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/file_fixtures.rb +++ /dev/null @@ -1,34 +0,0 @@ -module ActiveSupport - module Testing - # Adds simple access to sample files called file fixtures. - # File fixtures are normal files stored in - # ActiveSupport::TestCase.file_fixture_path. - # - # File fixtures are represented as +Pathname+ objects. - # This makes it easy to extract specific information: - # - # file_fixture("example.txt").read # get the file's content - # file_fixture("example.mp3").size # get the file size - module FileFixtures - extend ActiveSupport::Concern - - included do - class_attribute :file_fixture_path, instance_writer: false - end - - # Returns a +Pathname+ to the fixture file named +fixture_name+. - # - # Raises +ArgumentError+ if +fixture_name+ can't be found. - def file_fixture(fixture_name) - path = Pathname.new(File.join(file_fixture_path, fixture_name)) - - if path.exist? - path - else - msg = "the directory '%s' does not contain a file named '%s'" - raise ArgumentError, msg % [file_fixture_path, fixture_name] - end - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/isolation.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/isolation.rb deleted file mode 100644 index afe58427a1..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/isolation.rb +++ /dev/null @@ -1,108 +0,0 @@ -module ActiveSupport - module Testing - module Isolation - require "thread" - - def self.included(klass) #:nodoc: - klass.class_eval do - parallelize_me! - end - end - - def self.forking_env? - !ENV["NO_FORK"] && Process.respond_to?(:fork) - end - - def run - serialized = run_in_isolation do - super - end - - Marshal.load(serialized) - end - - module Forking - def run_in_isolation(&blk) - read, write = IO.pipe - read.binmode - write.binmode - - pid = fork do - read.close - yield - begin - if error? - failures.map! { |e| - begin - Marshal.dump e - e - rescue TypeError - ex = Exception.new e.message - ex.set_backtrace e.backtrace - Minitest::UnexpectedError.new ex - end - } - end - test_result = defined?(Minitest::Result) ? Minitest::Result.from(self) : dup - result = Marshal.dump(test_result) - end - - write.puts [result].pack("m") - exit! - end - - write.close - result = read.read - Process.wait2(pid) - return result.unpack("m")[0] - end - end - - module Subprocess - ORIG_ARGV = ARGV.dup unless defined?(ORIG_ARGV) - - # Crazy H4X to get this working in windows / jruby with - # no forking. - def run_in_isolation(&blk) - require "tempfile" - - if ENV["ISOLATION_TEST"] - yield - test_result = defined?(Minitest::Result) ? Minitest::Result.from(self) : dup - File.open(ENV["ISOLATION_OUTPUT"], "w") do |file| - file.puts [Marshal.dump(test_result)].pack("m") - end - exit! - else - Tempfile.open("isolation") do |tmpfile| - env = { - "ISOLATION_TEST" => self.class.name, - "ISOLATION_OUTPUT" => tmpfile.path - } - - test_opts = "-n#{self.class.name}##{name}" - - load_path_args = [] - $-I.each do |p| - load_path_args << "-I" - load_path_args << File.expand_path(p) - end - - child = IO.popen([env, Gem.ruby, *load_path_args, $0, *ORIG_ARGV, test_opts]) - - begin - Process.wait(child.pid) - rescue Errno::ECHILD # The child process may exit before we wait - nil - end - - return tmpfile.read.unpack("m")[0] - end - end - end - end - - include forking_env? ? Forking : Subprocess - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/method_call_assertions.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/method_call_assertions.rb deleted file mode 100644 index 6b07416fdc..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/method_call_assertions.rb +++ /dev/null @@ -1,41 +0,0 @@ -require "minitest/mock" - -module ActiveSupport - module Testing - module MethodCallAssertions # :nodoc: - private - def assert_called(object, method_name, message = nil, times: 1, returns: nil) - times_called = 0 - - object.stub(method_name, proc { times_called += 1; returns }) { yield } - - error = "Expected #{method_name} to be called #{times} times, " \ - "but was called #{times_called} times" - error = "#{message}.\n#{error}" if message - assert_equal times, times_called, error - end - - def assert_called_with(object, method_name, args = [], returns: nil) - mock = Minitest::Mock.new - - if args.all? { |arg| arg.is_a?(Array) } - args.each { |arg| mock.expect(:call, returns, arg) } - else - mock.expect(:call, returns, args) - end - - object.stub(method_name, mock) { yield } - - mock.verify - end - - def assert_not_called(object, method_name, message = nil, &block) - assert_called(object, method_name, message, times: 0, &block) - end - - def stub_any_instance(klass, instance: klass.new) - klass.stub(:new, instance) { yield instance } - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/setup_and_teardown.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/setup_and_teardown.rb deleted file mode 100644 index 358c79c321..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/setup_and_teardown.rb +++ /dev/null @@ -1,50 +0,0 @@ -require "active_support/concern" -require "active_support/callbacks" - -module ActiveSupport - module Testing - # Adds support for +setup+ and +teardown+ callbacks. - # These callbacks serve as a replacement to overwriting the - # #setup and #teardown methods of your TestCase. - # - # class ExampleTest < ActiveSupport::TestCase - # setup do - # # ... - # end - # - # teardown do - # # ... - # end - # end - module SetupAndTeardown - extend ActiveSupport::Concern - - included do - include ActiveSupport::Callbacks - define_callbacks :setup, :teardown - end - - module ClassMethods - # Add a callback, which runs before TestCase#setup. - def setup(*args, &block) - set_callback(:setup, :before, *args, &block) - end - - # Add a callback, which runs after TestCase#teardown. - def teardown(*args, &block) - set_callback(:teardown, :after, *args, &block) - end - end - - def before_setup # :nodoc: - super - run_callbacks :setup - end - - def after_teardown # :nodoc: - run_callbacks :teardown - super - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/stream.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/stream.rb deleted file mode 100644 index 1d06b94559..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/stream.rb +++ /dev/null @@ -1,42 +0,0 @@ -module ActiveSupport - module Testing - module Stream #:nodoc: - private - - def silence_stream(stream) - old_stream = stream.dup - stream.reopen(IO::NULL) - stream.sync = true - yield - ensure - stream.reopen(old_stream) - old_stream.close - end - - def quietly - silence_stream(STDOUT) do - silence_stream(STDERR) do - yield - end - end - end - - def capture(stream) - stream = stream.to_s - captured_stream = Tempfile.new(stream) - stream_io = eval("$#{stream}") - origin_stream = stream_io.dup - stream_io.reopen(captured_stream) - - yield - - stream_io.rewind - return captured_stream.read - ensure - captured_stream.close - captured_stream.unlink - stream_io.reopen(origin_stream) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/tagged_logging.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/tagged_logging.rb deleted file mode 100644 index afdff87b45..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/tagged_logging.rb +++ /dev/null @@ -1,25 +0,0 @@ -module ActiveSupport - module Testing - # Logs a "PostsControllerTest: test name" heading before each test to - # make test.log easier to search and follow along with. - module TaggedLogging #:nodoc: - attr_writer :tagged_logger - - def before_setup - if tagged_logger && tagged_logger.info? - heading = "#{self.class}: #{name}" - divider = "-" * heading.size - tagged_logger.info divider - tagged_logger.info heading - tagged_logger.info divider - end - super - end - - private - def tagged_logger - @tagged_logger ||= (defined?(Rails.logger) && Rails.logger) - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/time_helpers.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/time_helpers.rb deleted file mode 100644 index 3d9ff99729..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/testing/time_helpers.rb +++ /dev/null @@ -1,170 +0,0 @@ -require "active_support/core_ext/string/strip" # for strip_heredoc -require "active_support/core_ext/time/calculations" -require "concurrent/map" - -module ActiveSupport - module Testing - class SimpleStubs # :nodoc: - Stub = Struct.new(:object, :method_name, :original_method) - - def initialize - @stubs = Concurrent::Map.new { |h, k| h[k] = {} } - end - - def stub_object(object, method_name, &block) - if stub = stubbing(object, method_name) - unstub_object(stub) - end - - new_name = "__simple_stub__#{method_name}" - - @stubs[object.object_id][method_name] = Stub.new(object, method_name, new_name) - - object.singleton_class.send :alias_method, new_name, method_name - object.define_singleton_method(method_name, &block) - end - - def unstub_all! - @stubs.each_value do |object_stubs| - object_stubs.each_value do |stub| - unstub_object(stub) - end - end - @stubs.clear - end - - def stubbing(object, method_name) - @stubs[object.object_id][method_name] - end - - private - - def unstub_object(stub) - singleton_class = stub.object.singleton_class - singleton_class.send :undef_method, stub.method_name - singleton_class.send :alias_method, stub.method_name, stub.original_method - singleton_class.send :undef_method, stub.original_method - end - end - - # Contains helpers that help you test passage of time. - module TimeHelpers - # Changes current time to the time in the future or in the past by a given time difference by - # stubbing +Time.now+, +Date.today+, and +DateTime.now+. - # - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - # travel 1.day - # Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00 - # Date.current # => Sun, 10 Nov 2013 - # DateTime.current # => Sun, 10 Nov 2013 15:34:49 -0500 - # - # This method also accepts a block, which will return the current time back to its original - # state at the end of the block: - # - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - # travel 1.day do - # User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00 - # end - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - def travel(duration, &block) - travel_to Time.now + duration, &block - end - - # Changes current time to the given time by stubbing +Time.now+, - # +Date.today+, and +DateTime.now+ to return the time or date passed into this method. - # - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - # travel_to Time.zone.local(2004, 11, 24, 01, 04, 44) - # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 - # Date.current # => Wed, 24 Nov 2004 - # DateTime.current # => Wed, 24 Nov 2004 01:04:44 -0500 - # - # Dates are taken as their timestamp at the beginning of the day in the - # application time zone. Time.current returns said timestamp, - # and Time.now its equivalent in the system time zone. Similarly, - # Date.current returns a date equal to the argument, and - # Date.today the date according to Time.now, which may - # be different. (Note that you rarely want to deal with Time.now, - # or Date.today, in order to honor the application time zone - # please always use Time.current and Date.current.) - # - # Note that the usec for the time passed will be set to 0 to prevent rounding - # errors with external services, like MySQL (which will round instead of floor, - # leading to off-by-one-second errors). - # - # This method also accepts a block, which will return the current time back to its original - # state at the end of the block: - # - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - # travel_to Time.zone.local(2004, 11, 24, 01, 04, 44) do - # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 - # end - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - def travel_to(date_or_time) - if block_given? && simple_stubs.stubbing(Time, :now) - travel_to_nested_block_call = <<-MSG.strip_heredoc - - Calling `travel_to` with a block, when we have previously already made a call to `travel_to`, can lead to confusing time stubbing. - - Instead of: - - travel_to 2.days.from_now do - # 2 days from today - travel_to 3.days.from_now do - # 5 days from today - end - end - - preferred way to achieve above is: - - travel 2.days do - # 2 days from today - end - - travel 5.days do - # 5 days from today - end - - MSG - raise travel_to_nested_block_call - end - - if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime) - now = date_or_time.midnight.to_time - else - now = date_or_time.to_time.change(usec: 0) - end - - simple_stubs.stub_object(Time, :now) { at(now.to_i) } - simple_stubs.stub_object(Date, :today) { jd(now.to_date.jd) } - simple_stubs.stub_object(DateTime, :now) { jd(now.to_date.jd, now.hour, now.min, now.sec, Rational(now.utc_offset, 86400)) } - - if block_given? - begin - yield - ensure - travel_back - end - end - end - - # Returns the current time back to its original state, by removing the stubs added by - # `travel` and `travel_to`. - # - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - # travel_to Time.zone.local(2004, 11, 24, 01, 04, 44) - # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 - # travel_back - # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - def travel_back - simple_stubs.unstub_all! - end - - private - - def simple_stubs - @simple_stubs ||= SimpleStubs.new - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/time.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/time.rb deleted file mode 100644 index 7658228ca6..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/time.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ActiveSupport - autoload :Duration, "active_support/duration" - autoload :TimeWithZone, "active_support/time_with_zone" - autoload :TimeZone, "active_support/values/time_zone" -end - -require "date" -require "time" - -require "active_support/core_ext/time" -require "active_support/core_ext/date" -require "active_support/core_ext/date_time" - -require "active_support/core_ext/integer/time" -require "active_support/core_ext/numeric/time" - -require "active_support/core_ext/string/conversions" -require "active_support/core_ext/string/zones" diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/time_with_zone.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/time_with_zone.rb deleted file mode 100644 index b0dd6b7e8c..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/time_with_zone.rb +++ /dev/null @@ -1,513 +0,0 @@ -require "active_support/duration" -require "active_support/values/time_zone" -require "active_support/core_ext/object/acts_like" -require "active_support/core_ext/date_and_time/compatibility" - -module ActiveSupport - # A Time-like class that can represent a time in any time zone. Necessary - # because standard Ruby Time instances are limited to UTC and the - # system's ENV['TZ'] zone. - # - # You shouldn't ever need to create a TimeWithZone instance directly via +new+. - # Instead use methods +local+, +parse+, +at+ and +now+ on TimeZone instances, - # and +in_time_zone+ on Time and DateTime instances. - # - # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' - # Time.zone.local(2007, 2, 10, 15, 30, 45) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 - # Time.zone.parse('2007-02-10 15:30:45') # => Sat, 10 Feb 2007 15:30:45 EST -05:00 - # Time.zone.at(1171139445) # => Sat, 10 Feb 2007 15:30:45 EST -05:00 - # Time.zone.now # => Sun, 18 May 2008 13:07:55 EDT -04:00 - # Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone # => Sat, 10 Feb 2007 15:30:45 EST -05:00 - # - # See Time and TimeZone for further documentation of these methods. - # - # TimeWithZone instances implement the same API as Ruby Time instances, so - # that Time and TimeWithZone instances are interchangeable. - # - # t = Time.zone.now # => Sun, 18 May 2008 13:27:25 EDT -04:00 - # t.hour # => 13 - # t.dst? # => true - # t.utc_offset # => -14400 - # t.zone # => "EDT" - # t.to_s(:rfc822) # => "Sun, 18 May 2008 13:27:25 -0400" - # t + 1.day # => Mon, 19 May 2008 13:27:25 EDT -04:00 - # t.beginning_of_year # => Tue, 01 Jan 2008 00:00:00 EST -05:00 - # t > Time.utc(1999) # => true - # t.is_a?(Time) # => true - # t.is_a?(ActiveSupport::TimeWithZone) # => true - class TimeWithZone - # Report class name as 'Time' to thwart type checking. - def self.name - "Time" - end - - PRECISIONS = Hash.new { |h, n| h[n] = "%FT%T.%#{n}N".freeze } - PRECISIONS[0] = "%FT%T".freeze - - include Comparable, DateAndTime::Compatibility - attr_reader :time_zone - - def initialize(utc_time, time_zone, local_time = nil, period = nil) - @utc = utc_time ? transfer_time_values_to_utc_constructor(utc_time) : nil - @time_zone, @time = time_zone, local_time - @period = @utc ? period : get_period_and_ensure_valid_local_time(period) - end - - # Returns a Time instance that represents the time in +time_zone+. - def time - @time ||= period.to_local(@utc) - end - - # Returns a Time instance of the simultaneous time in the UTC timezone. - def utc - @utc ||= period.to_utc(@time) - end - alias_method :comparable_time, :utc - alias_method :getgm, :utc - alias_method :getutc, :utc - alias_method :gmtime, :utc - - # Returns the underlying TZInfo::TimezonePeriod. - def period - @period ||= time_zone.period_for_utc(@utc) - end - - # Returns the simultaneous time in Time.zone, or the specified zone. - def in_time_zone(new_zone = ::Time.zone) - return self if time_zone == new_zone - utc.in_time_zone(new_zone) - end - - # Returns a Time instance of the simultaneous time in the system timezone. - def localtime(utc_offset = nil) - utc.getlocal(utc_offset) - end - alias_method :getlocal, :localtime - - # Returns true if the current time is within Daylight Savings Time for the - # specified time zone. - # - # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' - # Time.zone.parse("2012-5-30").dst? # => true - # Time.zone.parse("2012-11-30").dst? # => false - def dst? - period.dst? - end - alias_method :isdst, :dst? - - # Returns true if the current time zone is set to UTC. - # - # Time.zone = 'UTC' # => 'UTC' - # Time.zone.now.utc? # => true - # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' - # Time.zone.now.utc? # => false - def utc? - period.offset.abbreviation == :UTC || period.offset.abbreviation == :UCT - end - alias_method :gmt?, :utc? - - # Returns the offset from current time to UTC time in seconds. - def utc_offset - period.utc_total_offset - end - alias_method :gmt_offset, :utc_offset - alias_method :gmtoff, :utc_offset - - # Returns a formatted string of the offset from UTC, or an alternative - # string if the time zone is already UTC. - # - # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" - # Time.zone.now.formatted_offset(true) # => "-05:00" - # Time.zone.now.formatted_offset(false) # => "-0500" - # Time.zone = 'UTC' # => "UTC" - # Time.zone.now.formatted_offset(true, "0") # => "0" - def formatted_offset(colon = true, alternate_utc_string = nil) - utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon) - end - - # Returns the time zone abbreviation. - # - # Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" - # Time.zone.now.zone # => "EST" - def zone - period.zone_identifier.to_s - end - - # Returns a string of the object's date, time, zone, and offset from UTC. - # - # Time.zone.now.inspect # => "Thu, 04 Dec 2014 11:00:25 EST -05:00" - def inspect - "#{time.strftime('%a, %d %b %Y %H:%M:%S')} #{zone} #{formatted_offset}" - end - - # Returns a string of the object's date and time in the ISO 8601 standard - # format. - # - # Time.zone.now.xmlschema # => "2014-12-04T11:02:37-05:00" - def xmlschema(fraction_digits = 0) - "#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z'.freeze)}" - end - alias_method :iso8601, :xmlschema - alias_method :rfc3339, :xmlschema - - # Coerces time to a string for JSON encoding. The default format is ISO 8601. - # You can get %Y/%m/%d %H:%M:%S +offset style by setting - # ActiveSupport::JSON::Encoding.use_standard_json_time_format - # to +false+. - # - # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true - # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json - # # => "2005-02-01T05:15:10.000-10:00" - # - # # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false - # Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json - # # => "2005/02/01 05:15:10 -1000" - def as_json(options = nil) - if ActiveSupport::JSON::Encoding.use_standard_json_time_format - xmlschema(ActiveSupport::JSON::Encoding.time_precision) - else - %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) - end - end - - def init_with(coder) #:nodoc: - initialize(coder["utc"], coder["zone"], coder["time"]) - end - - def encode_with(coder) #:nodoc: - coder.tag = "!ruby/object:ActiveSupport::TimeWithZone" - coder.map = { "utc" => utc, "zone" => time_zone, "time" => time } - end - - # Returns a string of the object's date and time in the format used by - # HTTP requests. - # - # Time.zone.now.httpdate # => "Tue, 01 Jan 2013 04:39:43 GMT" - def httpdate - utc.httpdate - end - - # Returns a string of the object's date and time in the RFC 2822 standard - # format. - # - # Time.zone.now.rfc2822 # => "Tue, 01 Jan 2013 04:51:39 +0000" - def rfc2822 - to_s(:rfc822) - end - alias_method :rfc822, :rfc2822 - - # Returns a string of the object's date and time. - # Accepts an optional format: - # * :default - default value, mimics Ruby Time#to_s format. - # * :db - format outputs time in UTC :db time. See Time#to_formatted_s(:db). - # * Any key in Time::DATE_FORMATS can be used. See active_support/core_ext/time/conversions.rb. - def to_s(format = :default) - if format == :db - utc.to_s(format) - elsif formatter = ::Time::DATE_FORMATS[format] - formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) - else - "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby Time#to_s format - end - end - alias_method :to_formatted_s, :to_s - - # Replaces %Z directive with +zone before passing to Time#strftime, - # so that zone information is correct. - def strftime(format) - format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}") - getlocal(utc_offset).strftime(format) - end - - # Use the time in UTC for comparisons. - def <=>(other) - utc <=> other - end - - # Returns true if the current object's time is within the specified - # +min+ and +max+ time. - def between?(min, max) - utc.between?(min, max) - end - - # Returns true if the current object's time is in the past. - def past? - utc.past? - end - - # Returns true if the current object's time falls within - # the current day. - def today? - time.today? - end - - # Returns true if the current object's time is in the future. - def future? - utc.future? - end - - # Returns +true+ if +other+ is equal to current object. - def eql?(other) - other.eql?(utc) - end - - def hash - utc.hash - end - - # Adds an interval of time to the current object's time and returns that - # value as a new TimeWithZone object. - # - # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' - # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28 EDT -04:00 - # now + 1000 # => Sun, 02 Nov 2014 01:43:08 EDT -04:00 - # - # If we're adding a Duration of variable length (i.e., years, months, days), - # move forward from #time, otherwise move forward from #utc, for accuracy - # when moving across DST boundaries. - # - # For instance, a time + 24.hours will advance exactly 24 hours, while a - # time + 1.day will advance 23-25 hours, depending on the day. - # - # now + 24.hours # => Mon, 03 Nov 2014 00:26:28 EST -05:00 - # now + 1.day # => Mon, 03 Nov 2014 01:26:28 EST -05:00 - def +(other) - if duration_of_variable_length?(other) - method_missing(:+, other) - else - result = utc.acts_like?(:date) ? utc.since(other) : utc + other rescue utc.since(other) - result.in_time_zone(time_zone) - end - end - alias_method :since, :+ - alias_method :in, :+ - - # Returns a new TimeWithZone object that represents the difference between - # the current object's time and the +other+ time. - # - # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' - # now = Time.zone.now # => Mon, 03 Nov 2014 00:26:28 EST -05:00 - # now - 1000 # => Mon, 03 Nov 2014 00:09:48 EST -05:00 - # - # If subtracting a Duration of variable length (i.e., years, months, days), - # move backward from #time, otherwise move backward from #utc, for accuracy - # when moving across DST boundaries. - # - # For instance, a time - 24.hours will go subtract exactly 24 hours, while a - # time - 1.day will subtract 23-25 hours, depending on the day. - # - # now - 24.hours # => Sun, 02 Nov 2014 01:26:28 EDT -04:00 - # now - 1.day # => Sun, 02 Nov 2014 00:26:28 EDT -04:00 - def -(other) - if other.acts_like?(:time) - to_time - other.to_time - elsif duration_of_variable_length?(other) - method_missing(:-, other) - else - result = utc.acts_like?(:date) ? utc.ago(other) : utc - other rescue utc.ago(other) - result.in_time_zone(time_zone) - end - end - - # Subtracts an interval of time from the current object's time and returns - # the result as a new TimeWithZone object. - # - # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' - # now = Time.zone.now # => Mon, 03 Nov 2014 00:26:28 EST -05:00 - # now.ago(1000) # => Mon, 03 Nov 2014 00:09:48 EST -05:00 - # - # If we're subtracting a Duration of variable length (i.e., years, months, - # days), move backward from #time, otherwise move backward from #utc, for - # accuracy when moving across DST boundaries. - # - # For instance, time.ago(24.hours) will move back exactly 24 hours, - # while time.ago(1.day) will move back 23-25 hours, depending on - # the day. - # - # now.ago(24.hours) # => Sun, 02 Nov 2014 01:26:28 EDT -04:00 - # now.ago(1.day) # => Sun, 02 Nov 2014 00:26:28 EDT -04:00 - def ago(other) - since(-other) - end - - # Uses Date to provide precise Time calculations for years, months, and days - # according to the proleptic Gregorian calendar. The result is returned as a - # new TimeWithZone object. - # - # The +options+ parameter takes a hash with any of these keys: - # :years, :months, :weeks, :days, - # :hours, :minutes, :seconds. - # - # If advancing by a value of variable length (i.e., years, weeks, months, - # days), move forward from #time, otherwise move forward from #utc, for - # accuracy when moving across DST boundaries. - # - # Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' - # now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28 EDT -04:00 - # now.advance(seconds: 1) # => Sun, 02 Nov 2014 01:26:29 EDT -04:00 - # now.advance(minutes: 1) # => Sun, 02 Nov 2014 01:27:28 EDT -04:00 - # now.advance(hours: 1) # => Sun, 02 Nov 2014 01:26:28 EST -05:00 - # now.advance(days: 1) # => Mon, 03 Nov 2014 01:26:28 EST -05:00 - # now.advance(weeks: 1) # => Sun, 09 Nov 2014 01:26:28 EST -05:00 - # now.advance(months: 1) # => Tue, 02 Dec 2014 01:26:28 EST -05:00 - # now.advance(years: 1) # => Mon, 02 Nov 2015 01:26:28 EST -05:00 - def advance(options) - # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time, - # otherwise advance from #utc, for accuracy when moving across DST boundaries - if options.values_at(:years, :weeks, :months, :days).any? - method_missing(:advance, options) - else - utc.advance(options).in_time_zone(time_zone) - end - end - - %w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name| - class_eval <<-EOV, __FILE__, __LINE__ + 1 - def #{method_name} # def month - time.#{method_name} # time.month - end # end - EOV - end - - # Returns Array of parts of Time in sequence of - # [seconds, minutes, hours, day, month, year, weekday, yearday, dst?, zone]. - # - # now = Time.zone.now # => Tue, 18 Aug 2015 02:29:27 UTC +00:00 - # now.to_a # => [27, 29, 2, 18, 8, 2015, 2, 230, false, "UTC"] - def to_a - [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone] - end - - # Returns the object's date and time as a floating point number of seconds - # since the Epoch (January 1, 1970 00:00 UTC). - # - # Time.zone.now.to_f # => 1417709320.285418 - def to_f - utc.to_f - end - - # Returns the object's date and time as an integer number of seconds - # since the Epoch (January 1, 1970 00:00 UTC). - # - # Time.zone.now.to_i # => 1417709320 - def to_i - utc.to_i - end - alias_method :tv_sec, :to_i - - # Returns the object's date and time as a rational number of seconds - # since the Epoch (January 1, 1970 00:00 UTC). - # - # Time.zone.now.to_r # => (708854548642709/500000) - def to_r - utc.to_r - end - - # Returns an instance of DateTime with the timezone's UTC offset - # - # Time.zone.now.to_datetime # => Tue, 18 Aug 2015 02:32:20 +0000 - # Time.current.in_time_zone('Hawaii').to_datetime # => Mon, 17 Aug 2015 16:32:20 -1000 - def to_datetime - @to_datetime ||= utc.to_datetime.new_offset(Rational(utc_offset, 86_400)) - end - - # Returns an instance of +Time+, either with the same UTC offset - # as +self+ or in the local system timezone depending on the setting - # of +ActiveSupport.to_time_preserves_timezone+. - def to_time - if preserve_timezone - @to_time_with_instance_offset ||= getlocal(utc_offset) - else - @to_time_with_system_offset ||= getlocal - end - end - - # So that +self+ acts_like?(:time). - def acts_like_time? - true - end - - # Say we're a Time to thwart type checking. - def is_a?(klass) - klass == ::Time || super - end - alias_method :kind_of?, :is_a? - - # An instance of ActiveSupport::TimeWithZone is never blank - def blank? - false - end - - def freeze - # preload instance variables before freezing - period; utc; time; to_datetime; to_time - super - end - - def marshal_dump - [utc, time_zone.name, time] - end - - def marshal_load(variables) - initialize(variables[0].utc, ::Time.find_zone(variables[1]), variables[2].utc) - end - - # respond_to_missing? is not called in some cases, such as when type conversion is - # performed with Kernel#String - def respond_to?(sym, include_priv = false) - # ensure that we're not going to throw and rescue from NoMethodError in method_missing which is slow - return false if sym.to_sym == :to_str - super - end - - # Ensure proxy class responds to all methods that underlying time instance - # responds to. - def respond_to_missing?(sym, include_priv) - return false if sym.to_sym == :acts_like_date? - time.respond_to?(sym, include_priv) - end - - # Send the missing method to +time+ instance, and wrap result in a new - # TimeWithZone with the existing +time_zone+. - def method_missing(sym, *args, &block) - wrap_with_time_zone time.__send__(sym, *args, &block) - rescue NoMethodError => e - raise e, e.message.sub(time.inspect, inspect), e.backtrace - end - - private - def get_period_and_ensure_valid_local_time(period) - # we don't want a Time.local instance enforcing its own DST rules as well, - # so transfer time values to a utc constructor if necessary - @time = transfer_time_values_to_utc_constructor(@time) unless @time.utc? - begin - period || @time_zone.period_for_local(@time) - rescue ::TZInfo::PeriodNotFound - # time is in the "spring forward" hour gap, so we're moving the time forward one hour and trying again - @time += 1.hour - retry - end - end - - def transfer_time_values_to_utc_constructor(time) - # avoid creating another Time object if possible - return time if time.instance_of?(::Time) && time.utc? - ::Time.utc(time.year, time.month, time.day, time.hour, time.min, time.sec + time.subsec) - end - - def duration_of_variable_length?(obj) - ActiveSupport::Duration === obj && obj.parts.any? { |p| [:years, :months, :weeks, :days].include?(p[0]) } - end - - def wrap_with_time_zone(time) - if time.acts_like?(:time) - periods = time_zone.periods_for_local(time) - self.class.new(nil, time_zone, time, periods.include?(period) ? period : nil) - elsif time.is_a?(Range) - wrap_with_time_zone(time.begin)..wrap_with_time_zone(time.end) - else - time - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/values/time_zone.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/values/time_zone.rb deleted file mode 100644 index 5f4bd7075e..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/values/time_zone.rb +++ /dev/null @@ -1,553 +0,0 @@ -require "tzinfo" -require "concurrent/map" -require "active_support/core_ext/object/blank" - -module ActiveSupport - # The TimeZone class serves as a wrapper around TZInfo::Timezone instances. - # It allows us to do the following: - # - # * Limit the set of zones provided by TZInfo to a meaningful subset of 146 - # zones. - # * Retrieve and display zones with a friendlier name - # (e.g., "Eastern Time (US & Canada)" instead of "America/New_York"). - # * Lazily load TZInfo::Timezone instances only when they're needed. - # * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+, - # +parse+, +at+ and +now+ methods. - # - # If you set config.time_zone in the Rails Application, you can - # access this TimeZone object via Time.zone: - # - # # application.rb: - # class Application < Rails::Application - # config.time_zone = 'Eastern Time (US & Canada)' - # end - # - # Time.zone # => # - # Time.zone.name # => "Eastern Time (US & Canada)" - # Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00 - class TimeZone - # Keys are Rails TimeZone names, values are TZInfo identifiers. - MAPPING = { - "International Date Line West" => "Pacific/Midway", - "Midway Island" => "Pacific/Midway", - "American Samoa" => "Pacific/Pago_Pago", - "Hawaii" => "Pacific/Honolulu", - "Alaska" => "America/Juneau", - "Pacific Time (US & Canada)" => "America/Los_Angeles", - "Tijuana" => "America/Tijuana", - "Mountain Time (US & Canada)" => "America/Denver", - "Arizona" => "America/Phoenix", - "Chihuahua" => "America/Chihuahua", - "Mazatlan" => "America/Mazatlan", - "Central Time (US & Canada)" => "America/Chicago", - "Saskatchewan" => "America/Regina", - "Guadalajara" => "America/Mexico_City", - "Mexico City" => "America/Mexico_City", - "Monterrey" => "America/Monterrey", - "Central America" => "America/Guatemala", - "Eastern Time (US & Canada)" => "America/New_York", - "Indiana (East)" => "America/Indiana/Indianapolis", - "Bogota" => "America/Bogota", - "Lima" => "America/Lima", - "Quito" => "America/Lima", - "Atlantic Time (Canada)" => "America/Halifax", - "Caracas" => "America/Caracas", - "La Paz" => "America/La_Paz", - "Santiago" => "America/Santiago", - "Newfoundland" => "America/St_Johns", - "Brasilia" => "America/Sao_Paulo", - "Buenos Aires" => "America/Argentina/Buenos_Aires", - "Montevideo" => "America/Montevideo", - "Georgetown" => "America/Guyana", - "Greenland" => "America/Godthab", - "Mid-Atlantic" => "Atlantic/South_Georgia", - "Azores" => "Atlantic/Azores", - "Cape Verde Is." => "Atlantic/Cape_Verde", - "Dublin" => "Europe/Dublin", - "Edinburgh" => "Europe/London", - "Lisbon" => "Europe/Lisbon", - "London" => "Europe/London", - "Casablanca" => "Africa/Casablanca", - "Monrovia" => "Africa/Monrovia", - "UTC" => "Etc/UTC", - "Belgrade" => "Europe/Belgrade", - "Bratislava" => "Europe/Bratislava", - "Budapest" => "Europe/Budapest", - "Ljubljana" => "Europe/Ljubljana", - "Prague" => "Europe/Prague", - "Sarajevo" => "Europe/Sarajevo", - "Skopje" => "Europe/Skopje", - "Warsaw" => "Europe/Warsaw", - "Zagreb" => "Europe/Zagreb", - "Brussels" => "Europe/Brussels", - "Copenhagen" => "Europe/Copenhagen", - "Madrid" => "Europe/Madrid", - "Paris" => "Europe/Paris", - "Amsterdam" => "Europe/Amsterdam", - "Berlin" => "Europe/Berlin", - "Bern" => "Europe/Zurich", - "Zurich" => "Europe/Zurich", - "Rome" => "Europe/Rome", - "Stockholm" => "Europe/Stockholm", - "Vienna" => "Europe/Vienna", - "West Central Africa" => "Africa/Algiers", - "Bucharest" => "Europe/Bucharest", - "Cairo" => "Africa/Cairo", - "Helsinki" => "Europe/Helsinki", - "Kyiv" => "Europe/Kiev", - "Riga" => "Europe/Riga", - "Sofia" => "Europe/Sofia", - "Tallinn" => "Europe/Tallinn", - "Vilnius" => "Europe/Vilnius", - "Athens" => "Europe/Athens", - "Istanbul" => "Europe/Istanbul", - "Minsk" => "Europe/Minsk", - "Jerusalem" => "Asia/Jerusalem", - "Harare" => "Africa/Harare", - "Pretoria" => "Africa/Johannesburg", - "Kaliningrad" => "Europe/Kaliningrad", - "Moscow" => "Europe/Moscow", - "St. Petersburg" => "Europe/Moscow", - "Volgograd" => "Europe/Volgograd", - "Samara" => "Europe/Samara", - "Kuwait" => "Asia/Kuwait", - "Riyadh" => "Asia/Riyadh", - "Nairobi" => "Africa/Nairobi", - "Baghdad" => "Asia/Baghdad", - "Tehran" => "Asia/Tehran", - "Abu Dhabi" => "Asia/Muscat", - "Muscat" => "Asia/Muscat", - "Baku" => "Asia/Baku", - "Tbilisi" => "Asia/Tbilisi", - "Yerevan" => "Asia/Yerevan", - "Kabul" => "Asia/Kabul", - "Ekaterinburg" => "Asia/Yekaterinburg", - "Islamabad" => "Asia/Karachi", - "Karachi" => "Asia/Karachi", - "Tashkent" => "Asia/Tashkent", - "Chennai" => "Asia/Kolkata", - "Kolkata" => "Asia/Kolkata", - "Mumbai" => "Asia/Kolkata", - "New Delhi" => "Asia/Kolkata", - "Kathmandu" => "Asia/Kathmandu", - "Astana" => "Asia/Dhaka", - "Dhaka" => "Asia/Dhaka", - "Sri Jayawardenepura" => "Asia/Colombo", - "Almaty" => "Asia/Almaty", - "Novosibirsk" => "Asia/Novosibirsk", - "Rangoon" => "Asia/Rangoon", - "Bangkok" => "Asia/Bangkok", - "Hanoi" => "Asia/Bangkok", - "Jakarta" => "Asia/Jakarta", - "Krasnoyarsk" => "Asia/Krasnoyarsk", - "Beijing" => "Asia/Shanghai", - "Chongqing" => "Asia/Chongqing", - "Hong Kong" => "Asia/Hong_Kong", - "Urumqi" => "Asia/Urumqi", - "Kuala Lumpur" => "Asia/Kuala_Lumpur", - "Singapore" => "Asia/Singapore", - "Taipei" => "Asia/Taipei", - "Perth" => "Australia/Perth", - "Irkutsk" => "Asia/Irkutsk", - "Ulaanbaatar" => "Asia/Ulaanbaatar", - "Seoul" => "Asia/Seoul", - "Osaka" => "Asia/Tokyo", - "Sapporo" => "Asia/Tokyo", - "Tokyo" => "Asia/Tokyo", - "Yakutsk" => "Asia/Yakutsk", - "Darwin" => "Australia/Darwin", - "Adelaide" => "Australia/Adelaide", - "Canberra" => "Australia/Melbourne", - "Melbourne" => "Australia/Melbourne", - "Sydney" => "Australia/Sydney", - "Brisbane" => "Australia/Brisbane", - "Hobart" => "Australia/Hobart", - "Vladivostok" => "Asia/Vladivostok", - "Guam" => "Pacific/Guam", - "Port Moresby" => "Pacific/Port_Moresby", - "Magadan" => "Asia/Magadan", - "Srednekolymsk" => "Asia/Srednekolymsk", - "Solomon Is." => "Pacific/Guadalcanal", - "New Caledonia" => "Pacific/Noumea", - "Fiji" => "Pacific/Fiji", - "Kamchatka" => "Asia/Kamchatka", - "Marshall Is." => "Pacific/Majuro", - "Auckland" => "Pacific/Auckland", - "Wellington" => "Pacific/Auckland", - "Nuku'alofa" => "Pacific/Tongatapu", - "Tokelau Is." => "Pacific/Fakaofo", - "Chatham Is." => "Pacific/Chatham", - "Samoa" => "Pacific/Apia" - } - - UTC_OFFSET_WITH_COLON = "%s%02d:%02d" - UTC_OFFSET_WITHOUT_COLON = UTC_OFFSET_WITH_COLON.tr(":", "") - - @lazy_zones_map = Concurrent::Map.new - @country_zones = Concurrent::Map.new - - class << self - # Assumes self represents an offset from UTC in seconds (as returned from - # Time#utc_offset) and turns this into an +HH:MM formatted string. - # - # ActiveSupport::TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00" - def seconds_to_utc_offset(seconds, colon = true) - format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON - sign = (seconds < 0 ? "-" : "+") - hours = seconds.abs / 3600 - minutes = (seconds.abs % 3600) / 60 - format % [sign, hours, minutes] - end - - def find_tzinfo(name) - TZInfo::Timezone.new(MAPPING[name] || name) - end - - alias_method :create, :new - - # Returns a TimeZone instance with the given name, or +nil+ if no - # such TimeZone instance exists. (This exists to support the use of - # this class with the +composed_of+ macro.) - def new(name) - self[name] - end - - # Returns an array of all TimeZone objects. There are multiple - # TimeZone objects per time zone, in many cases, to make it easier - # for users to find their own time zone. - def all - @zones ||= zones_map.values.sort - end - - # Locate a specific time zone object. If the argument is a string, it - # is interpreted to mean the name of the timezone to locate. If it is a - # numeric value it is either the hour offset, or the second offset, of the - # timezone to find. (The first one with that offset will be returned.) - # Returns +nil+ if no such time zone is known to the system. - def [](arg) - case arg - when String - begin - @lazy_zones_map[arg] ||= create(arg) - rescue TZInfo::InvalidTimezoneIdentifier - nil - end - when Numeric, ActiveSupport::Duration - arg *= 3600 if arg.abs <= 13 - all.find { |z| z.utc_offset == arg.to_i } - else - raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}" - end - end - - # A convenience method for returning a collection of TimeZone objects - # for time zones in the USA. - def us_zones - country_zones(:us) - end - - # A convenience method for returning a collection of TimeZone objects - # for time zones in the country specified by its ISO 3166-1 Alpha2 code. - def country_zones(country_code) - code = country_code.to_s.upcase - @country_zones[code] ||= load_country_zones(code) - end - - private - def load_country_zones(code) - country = TZInfo::Country.get(code) - country.zone_identifiers.map do |tz_id| - if MAPPING.value?(tz_id) - MAPPING.inject([]) do |memo, (key, value)| - memo << self[key] if value == tz_id - memo - end - else - create(tz_id, nil, TZInfo::Timezone.new(tz_id)) - end - end.flatten(1).sort! - end - - def zones_map - @zones_map ||= begin - MAPPING.each_key { |place| self[place] } # load all the zones - @lazy_zones_map - end - end - end - - include Comparable - attr_reader :name - attr_reader :tzinfo - - # Create a new TimeZone object with the given name and offset. The - # offset is the number of seconds that this time zone is offset from UTC - # (GMT). Seconds were chosen as the offset unit because that is the unit - # that Ruby uses to represent time zone offsets (see Time#utc_offset). - def initialize(name, utc_offset = nil, tzinfo = nil) - @name = name - @utc_offset = utc_offset - @tzinfo = tzinfo || TimeZone.find_tzinfo(name) - end - - # Returns the offset of this time zone from UTC in seconds. - def utc_offset - if @utc_offset - @utc_offset - else - tzinfo.current_period.utc_offset if tzinfo && tzinfo.current_period - end - end - - # Returns a formatted string of the offset from UTC, or an alternative - # string if the time zone is already UTC. - # - # zone = ActiveSupport::TimeZone['Central Time (US & Canada)'] - # zone.formatted_offset # => "-06:00" - # zone.formatted_offset(false) # => "-0600" - def formatted_offset(colon = true, alternate_utc_string = nil) - utc_offset == 0 && alternate_utc_string || self.class.seconds_to_utc_offset(utc_offset, colon) - end - - # Compare this time zone to the parameter. The two are compared first on - # their offsets, and then by name. - def <=>(zone) - return unless zone.respond_to? :utc_offset - result = (utc_offset <=> zone.utc_offset) - result = (name <=> zone.name) if result == 0 - result - end - - # Compare #name and TZInfo identifier to a supplied regexp, returning +true+ - # if a match is found. - def =~(re) - re === name || re === MAPPING[name] - end - - # Returns a textual representation of this time zone. - def to_s - "(GMT#{formatted_offset}) #{name}" - end - - # Method for creating new ActiveSupport::TimeWithZone instance in time zone - # of +self+ from given values. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00 - def local(*args) - time = Time.utc(*args) - ActiveSupport::TimeWithZone.new(nil, self, time) - end - - # Method for creating new ActiveSupport::TimeWithZone instance in time zone - # of +self+ from number of seconds since the Unix epoch. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.utc(2000).to_f # => 946684800.0 - # Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - def at(secs) - Time.at(secs).utc.in_time_zone(self) - end - - # Method for creating new ActiveSupport::TimeWithZone instance in time zone - # of +self+ from an ISO 8601 string. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.iso8601('1999-12-31T14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - # - # If the time components are missing then they will be set to zero. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.iso8601('1999-12-31') # => Fri, 31 Dec 1999 00:00:00 HST -10:00 - # - # If the string is invalid then an +ArgumentError+ will be raised unlike +parse+ - # which returns +nil+ when given an invalid date string. - def iso8601(str) - parts = Date._iso8601(str) - - raise ArgumentError, "invalid date" if parts.empty? - - time = Time.new( - parts.fetch(:year), - parts.fetch(:mon), - parts.fetch(:mday), - parts.fetch(:hour, 0), - parts.fetch(:min, 0), - parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0), - parts.fetch(:offset, 0) - ) - - if parts[:offset] - TimeWithZone.new(time.utc, self) - else - TimeWithZone.new(nil, self, time) - end - end - - # Method for creating new ActiveSupport::TimeWithZone instance in time zone - # of +self+ from parsed string. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - # - # If upper components are missing from the string, they are supplied from - # TimeZone#now: - # - # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - # Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00 - # - # However, if the date component is not provided, but any other upper - # components are supplied, then the day of the month defaults to 1: - # - # Time.zone.parse('Mar 2000') # => Wed, 01 Mar 2000 00:00:00 HST -10:00 - def parse(str, now = now()) - parts_to_time(Date._parse(str, false), now) - end - - # Method for creating new ActiveSupport::TimeWithZone instance in time zone - # of +self+ from an RFC 3339 string. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.rfc3339('2000-01-01T00:00:00Z') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - # - # If the time or zone components are missing then an +ArgumentError+ will - # be raised. This is much stricter than either +parse+ or +iso8601+ which - # allow for missing components. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.rfc3339('1999-12-31') # => ArgumentError: invalid date - def rfc3339(str) - parts = Date._rfc3339(str) - - raise ArgumentError, "invalid date" if parts.empty? - - time = Time.new( - parts.fetch(:year), - parts.fetch(:mon), - parts.fetch(:mday), - parts.fetch(:hour), - parts.fetch(:min), - parts.fetch(:sec) + parts.fetch(:sec_fraction, 0), - parts.fetch(:offset) - ) - - TimeWithZone.new(time.utc, self) - end - - # Parses +str+ according to +format+ and returns an ActiveSupport::TimeWithZone. - # - # Assumes that +str+ is a time in the time zone +self+, - # unless +format+ includes an explicit time zone. - # (This is the same behavior as +parse+.) - # In either case, the returned TimeWithZone has the timezone of +self+. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.strptime('1999-12-31 14:00:00', '%Y-%m-%d %H:%M:%S') # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - # - # If upper components are missing from the string, they are supplied from - # TimeZone#now: - # - # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00 - # Time.zone.strptime('22:30:00', '%H:%M:%S') # => Fri, 31 Dec 1999 22:30:00 HST -10:00 - # - # However, if the date component is not provided, but any other upper - # components are supplied, then the day of the month defaults to 1: - # - # Time.zone.strptime('Mar 2000', '%b %Y') # => Wed, 01 Mar 2000 00:00:00 HST -10:00 - def strptime(str, format, now = now()) - parts_to_time(DateTime._strptime(str, format), now) - end - - # Returns an ActiveSupport::TimeWithZone instance representing the current - # time in the time zone represented by +self+. - # - # Time.zone = 'Hawaii' # => "Hawaii" - # Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00 - def now - time_now.utc.in_time_zone(self) - end - - # Returns the current date in this time zone. - def today - tzinfo.now.to_date - end - - # Returns the next date in this time zone. - def tomorrow - today + 1 - end - - # Returns the previous date in this time zone. - def yesterday - today - 1 - end - - # Adjust the given time to the simultaneous time in the time zone - # represented by +self+. Returns a Time.utc() instance -- if you want an - # ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead. - def utc_to_local(time) - tzinfo.utc_to_local(time) - end - - # Adjust the given time to the simultaneous time in UTC. Returns a - # Time.utc() instance. - def local_to_utc(time, dst = true) - tzinfo.local_to_utc(time, dst) - end - - # Available so that TimeZone instances respond like TZInfo::Timezone - # instances. - def period_for_utc(time) - tzinfo.period_for_utc(time) - end - - # Available so that TimeZone instances respond like TZInfo::Timezone - # instances. - def period_for_local(time, dst = true) - tzinfo.period_for_local(time, dst) - end - - def periods_for_local(time) #:nodoc: - tzinfo.periods_for_local(time) - end - - def init_with(coder) #:nodoc: - initialize(coder["name"]) - end - - def encode_with(coder) #:nodoc: - coder.tag = "!ruby/object:#{self.class}" - coder.map = { "name" => tzinfo.name } - end - - private - def parts_to_time(parts, now) - raise ArgumentError, "invalid date" if parts.nil? - return if parts.empty? - - if parts[:seconds] - time = Time.at(parts[:seconds]) - else - time = Time.new( - parts.fetch(:year, now.year), - parts.fetch(:mon, now.month), - parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day), - parts.fetch(:hour, 0), - parts.fetch(:min, 0), - parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0), - parts.fetch(:offset, 0) - ) - end - - if parts[:offset] || parts[:seconds] - TimeWithZone.new(time.utc, self) - else - TimeWithZone.new(nil, self, time) - end - end - - def time_now - Time.now - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/values/unicode_tables.dat b/debian/gems-compat/activesupport-5.1.7/lib/active_support/values/unicode_tables.dat deleted file mode 100644 index f7d9c48bbe..0000000000 Binary files a/debian/gems-compat/activesupport-5.1.7/lib/active_support/values/unicode_tables.dat and /dev/null differ diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/version.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/version.rb deleted file mode 100644 index 20b91ac911..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module ActiveSupport - # Returns the version of the currently loaded ActiveSupport as a Gem::Version - def self.version - gem_version - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini.rb deleted file mode 100644 index 782fb41288..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini.rb +++ /dev/null @@ -1,207 +0,0 @@ -require "time" -require "base64" -require "bigdecimal" -require "active_support/core_ext/module/delegation" -require "active_support/core_ext/string/inflections" -require "active_support/core_ext/date_time/calculations" - -module ActiveSupport - # = XmlMini - # - # To use the much faster libxml parser: - # gem 'libxml-ruby', '=0.9.7' - # XmlMini.backend = 'LibXML' - module XmlMini - extend self - - # This module decorates files deserialized using Hash.from_xml with - # the original_filename and content_type methods. - module FileLike #:nodoc: - attr_writer :original_filename, :content_type - - def original_filename - @original_filename || "untitled" - end - - def content_type - @content_type || "application/octet-stream" - end - end - - DEFAULT_ENCODINGS = { - "binary" => "base64" - } unless defined?(DEFAULT_ENCODINGS) - - unless defined?(TYPE_NAMES) - TYPE_NAMES = { - "Symbol" => "symbol", - "Integer" => "integer", - "BigDecimal" => "decimal", - "Float" => "float", - "TrueClass" => "boolean", - "FalseClass" => "boolean", - "Date" => "date", - "DateTime" => "dateTime", - "Time" => "dateTime", - "Array" => "array", - "Hash" => "hash" - } - - # No need to map these on Ruby 2.4+ - TYPE_NAMES["Fixnum"] = "integer" unless 0.class == Integer - TYPE_NAMES["Bignum"] = "integer" unless 0.class == Integer - end - - FORMATTING = { - "symbol" => Proc.new { |symbol| symbol.to_s }, - "date" => Proc.new { |date| date.to_s(:db) }, - "dateTime" => Proc.new { |time| time.xmlschema }, - "binary" => Proc.new { |binary| ::Base64.encode64(binary) }, - "yaml" => Proc.new { |yaml| yaml.to_yaml } - } unless defined?(FORMATTING) - - # TODO use regexp instead of Date.parse - unless defined?(PARSING) - PARSING = { - "symbol" => Proc.new { |symbol| symbol.to_s.to_sym }, - "date" => Proc.new { |date| ::Date.parse(date) }, - "datetime" => Proc.new { |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc }, - "integer" => Proc.new { |integer| integer.to_i }, - "float" => Proc.new { |float| float.to_f }, - "decimal" => Proc.new do |number| - if String === number - begin - BigDecimal(number) - rescue ArgumentError - BigDecimal("0") - end - else - BigDecimal(number) - end - end, - "boolean" => Proc.new { |boolean| %w(1 true).include?(boolean.to_s.strip) }, - "string" => Proc.new { |string| string.to_s }, - "yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml }, - "base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) }, - "binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) }, - "file" => Proc.new { |file, entity| _parse_file(file, entity) } - } - - PARSING.update( - "double" => PARSING["float"], - "dateTime" => PARSING["datetime"] - ) - end - - attr_accessor :depth - self.depth = 100 - - delegate :parse, to: :backend - - def backend - current_thread_backend || @backend - end - - def backend=(name) - backend = name && cast_backend_name_to_module(name) - self.current_thread_backend = backend if current_thread_backend - @backend = backend - end - - def with_backend(name) - old_backend = current_thread_backend - self.current_thread_backend = name && cast_backend_name_to_module(name) - yield - ensure - self.current_thread_backend = old_backend - end - - def to_tag(key, value, options) - type_name = options.delete(:type) - merged_options = options.merge(root: key, skip_instruct: true) - - if value.is_a?(::Method) || value.is_a?(::Proc) - if value.arity == 1 - value.call(merged_options) - else - value.call(merged_options, key.to_s.singularize) - end - elsif value.respond_to?(:to_xml) - value.to_xml(merged_options) - else - type_name ||= TYPE_NAMES[value.class.name] - type_name ||= value.class.name if value && !value.respond_to?(:to_str) - type_name = type_name.to_s if type_name - type_name = "dateTime" if type_name == "datetime" - - key = rename_key(key.to_s, options) - - attributes = options[:skip_types] || type_name.nil? ? {} : { type: type_name } - attributes[:nil] = true if value.nil? - - encoding = options[:encoding] || DEFAULT_ENCODINGS[type_name] - attributes[:encoding] = encoding if encoding - - formatted_value = FORMATTING[type_name] && !value.nil? ? - FORMATTING[type_name].call(value) : value - - options[:builder].tag!(key, formatted_value, attributes) - end - end - - def rename_key(key, options = {}) - camelize = options[:camelize] - dasherize = !options.has_key?(:dasherize) || options[:dasherize] - if camelize - key = true == camelize ? key.camelize : key.camelize(camelize) - end - key = _dasherize(key) if dasherize - key - end - - private - - def _dasherize(key) - # $2 must be a non-greedy regex for this to work - left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1, 3] - "#{left}#{middle.tr('_ ', '--')}#{right}" - end - - # TODO: Add support for other encodings - def _parse_binary(bin, entity) - case entity["encoding"] - when "base64" - ::Base64.decode64(bin) - else - bin - end - end - - def _parse_file(file, entity) - f = StringIO.new(::Base64.decode64(file)) - f.extend(FileLike) - f.original_filename = entity["name"] - f.content_type = entity["content_type"] - f - end - - def current_thread_backend - Thread.current[:xml_mini_backend] - end - - def current_thread_backend=(name) - Thread.current[:xml_mini_backend] = name && cast_backend_name_to_module(name) - end - - def cast_backend_name_to_module(name) - if name.is_a?(Module) - name - else - require "active_support/xml_mini/#{name.downcase}" - ActiveSupport.const_get("XmlMini_#{name}") - end - end - end - - XmlMini.backend = "REXML" -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/jdom.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/jdom.rb deleted file mode 100644 index a7939b3185..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/jdom.rb +++ /dev/null @@ -1,181 +0,0 @@ -raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFORM.include?("java") - -require "jruby" -include Java - -require "active_support/core_ext/object/blank" - -java_import javax.xml.parsers.DocumentBuilder unless defined? DocumentBuilder -java_import javax.xml.parsers.DocumentBuilderFactory unless defined? DocumentBuilderFactory -java_import java.io.StringReader unless defined? StringReader -java_import org.xml.sax.InputSource unless defined? InputSource -java_import org.xml.sax.Attributes unless defined? Attributes -java_import org.w3c.dom.Node unless defined? Node - -module ActiveSupport - module XmlMini_JDOM #:nodoc: - extend self - - CONTENT_KEY = "__content__".freeze - - NODE_TYPE_NAMES = %w{ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE - DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE - PROCESSING_INSTRUCTION_NODE TEXT_NODE} - - node_type_map = {} - NODE_TYPE_NAMES.each { |type| node_type_map[Node.send(type)] = type } - - # Parse an XML Document string or IO into a simple hash using Java's jdom. - # data:: - # XML Document string or IO to parse - def parse(data) - if data.respond_to?(:read) - data = data.read - end - - if data.blank? - {} - else - @dbf = DocumentBuilderFactory.new_instance - # secure processing of java xml - # http://www.ibm.com/developerworks/xml/library/x-tipcfsx/index.html - @dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false) - @dbf.setFeature("http://xml.org/sax/features/external-general-entities", false) - @dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false) - @dbf.setFeature(javax.xml.XMLConstants::FEATURE_SECURE_PROCESSING, true) - xml_string_reader = StringReader.new(data) - xml_input_source = InputSource.new(xml_string_reader) - doc = @dbf.new_document_builder.parse(xml_input_source) - merge_element!({ CONTENT_KEY => "" }, doc.document_element, XmlMini.depth) - end - end - - private - - # Convert an XML element and merge into the hash - # - # hash:: - # Hash to merge the converted element into. - # element:: - # XML element to merge into hash - def merge_element!(hash, element, depth) - raise "Document too deep!" if depth == 0 - delete_empty(hash) - merge!(hash, element.tag_name, collapse(element, depth)) - end - - def delete_empty(hash) - hash.delete(CONTENT_KEY) if hash[CONTENT_KEY] == "" - end - - # Actually converts an XML document element into a data structure. - # - # element:: - # The document element to be collapsed. - def collapse(element, depth) - hash = get_attributes(element) - - child_nodes = element.child_nodes - if child_nodes.length > 0 - (0...child_nodes.length).each do |i| - child = child_nodes.item(i) - merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE - end - merge_texts!(hash, element) unless empty_content?(element) - hash - else - merge_texts!(hash, element) - end - end - - # Merge all the texts of an element into the hash - # - # hash:: - # Hash to add the converted element to. - # element:: - # XML element whose texts are to me merged into the hash - def merge_texts!(hash, element) - delete_empty(hash) - text_children = texts(element) - if text_children.join.empty? - hash - else - # must use value to prevent double-escaping - merge!(hash, CONTENT_KEY, text_children.join) - end - end - - # Adds a new key/value pair to an existing Hash. If the key to be added - # already exists and the existing value associated with key is not - # an Array, it will be wrapped in an Array. Then the new value is - # appended to that Array. - # - # hash:: - # Hash to add key/value pair to. - # key:: - # Key to be added. - # value:: - # Value to be associated with key. - def merge!(hash, key, value) - if hash.has_key?(key) - if hash[key].instance_of?(Array) - hash[key] << value - else - hash[key] = [hash[key], value] - end - elsif value.instance_of?(Array) - hash[key] = [value] - else - hash[key] = value - end - hash - end - - # Converts the attributes array of an XML element into a hash. - # Returns an empty Hash if node has no attributes. - # - # element:: - # XML element to extract attributes from. - def get_attributes(element) - attribute_hash = {} - attributes = element.attributes - (0...attributes.length).each do |i| - attribute_hash[CONTENT_KEY] ||= "" - attribute_hash[attributes.item(i).name] = attributes.item(i).value - end - attribute_hash - end - - # Determines if a document element has text content - # - # element:: - # XML element to be checked. - def texts(element) - texts = [] - child_nodes = element.child_nodes - (0...child_nodes.length).each do |i| - item = child_nodes.item(i) - if item.node_type == Node.TEXT_NODE - texts << item.get_data - end - end - texts - end - - # Determines if a document element has text content - # - # element:: - # XML element to be checked. - def empty_content?(element) - text = "" - child_nodes = element.child_nodes - (0...child_nodes.length).each do |i| - item = child_nodes.item(i) - if item.node_type == Node.TEXT_NODE - text << item.get_data.strip - end - end - text.strip.length == 0 - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/libxml.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/libxml.rb deleted file mode 100644 index d849cdfa6b..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/libxml.rb +++ /dev/null @@ -1,78 +0,0 @@ -require "libxml" -require "active_support/core_ext/object/blank" -require "stringio" - -module ActiveSupport - module XmlMini_LibXML #:nodoc: - extend self - - # Parse an XML Document string or IO into a simple hash using libxml. - # data:: - # XML Document string or IO to parse - def parse(data) - if !data.respond_to?(:read) - data = StringIO.new(data || "") - end - - if data.eof? - {} - else - LibXML::XML::Parser.io(data).parse.to_hash - end - end - end -end - -module LibXML #:nodoc: - module Conversions #:nodoc: - module Document #:nodoc: - def to_hash - root.to_hash - end - end - - module Node #:nodoc: - CONTENT_ROOT = "__content__".freeze - - # Convert XML document to hash. - # - # hash:: - # Hash to merge the converted element into. - def to_hash(hash = {}) - node_hash = {} - - # Insert node hash into parent hash correctly. - case hash[name] - when Array then hash[name] << node_hash - when Hash then hash[name] = [hash[name], node_hash] - when nil then hash[name] = node_hash - end - - # Handle child elements - each_child do |c| - if c.element? - c.to_hash(node_hash) - elsif c.text? || c.cdata? - node_hash[CONTENT_ROOT] ||= "" - node_hash[CONTENT_ROOT] << c.content - end - end - - # Remove content node if it is blank - if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank? - node_hash.delete(CONTENT_ROOT) - end - - # Handle attributes - each_attr { |a| node_hash[a.name] = a.value } - - hash - end - end - end -end - -# :enddoc: - -LibXML::XML::Document.include(LibXML::Conversions::Document) -LibXML::XML::Node.include(LibXML::Conversions::Node) diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/libxmlsax.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/libxmlsax.rb deleted file mode 100644 index f3d485da2f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/libxmlsax.rb +++ /dev/null @@ -1,81 +0,0 @@ -require "libxml" -require "active_support/core_ext/object/blank" -require "stringio" - -module ActiveSupport - module XmlMini_LibXMLSAX #:nodoc: - extend self - - # Class that will build the hash while the XML document - # is being parsed using SAX events. - class HashBuilder - include LibXML::XML::SaxParser::Callbacks - - CONTENT_KEY = "__content__".freeze - HASH_SIZE_KEY = "__hash_size__".freeze - - attr_reader :hash - - def current_hash - @hash_stack.last - end - - def on_start_document - @hash = { CONTENT_KEY => "" } - @hash_stack = [@hash] - end - - def on_end_document - @hash = @hash_stack.pop - @hash.delete(CONTENT_KEY) - end - - def on_start_element(name, attrs = {}) - new_hash = { CONTENT_KEY => "" }.merge!(attrs) - new_hash[HASH_SIZE_KEY] = new_hash.size + 1 - - case current_hash[name] - when Array then current_hash[name] << new_hash - when Hash then current_hash[name] = [current_hash[name], new_hash] - when nil then current_hash[name] = new_hash - end - - @hash_stack.push(new_hash) - end - - def on_end_element(name) - if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == "" - current_hash.delete(CONTENT_KEY) - end - @hash_stack.pop - end - - def on_characters(string) - current_hash[CONTENT_KEY] << string - end - - alias_method :on_cdata_block, :on_characters - end - - attr_accessor :document_class - self.document_class = HashBuilder - - def parse(data) - if !data.respond_to?(:read) - data = StringIO.new(data || "") - end - - if data.eof? - {} - else - LibXML::XML::Error.set_handler(&LibXML::XML::Error::QUIET_HANDLER) - parser = LibXML::XML::SaxParser.io(data) - document = document_class.new - - parser.callbacks = document - parser.parse - document.hash - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/nokogiri.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/nokogiri.rb deleted file mode 100644 index 63466c08b2..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/nokogiri.rb +++ /dev/null @@ -1,81 +0,0 @@ -begin - require "nokogiri" -rescue LoadError => e - $stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install" - raise e -end -require "active_support/core_ext/object/blank" -require "stringio" - -module ActiveSupport - module XmlMini_Nokogiri #:nodoc: - extend self - - # Parse an XML Document string or IO into a simple hash using libxml / nokogiri. - # data:: - # XML Document string or IO to parse - def parse(data) - if !data.respond_to?(:read) - data = StringIO.new(data || "") - end - - if data.eof? - {} - else - doc = Nokogiri::XML(data) - raise doc.errors.first if doc.errors.length > 0 - doc.to_hash - end - end - - module Conversions #:nodoc: - module Document #:nodoc: - def to_hash - root.to_hash - end - end - - module Node #:nodoc: - CONTENT_ROOT = "__content__".freeze - - # Convert XML document to hash. - # - # hash:: - # Hash to merge the converted element into. - def to_hash(hash = {}) - node_hash = {} - - # Insert node hash into parent hash correctly. - case hash[name] - when Array then hash[name] << node_hash - when Hash then hash[name] = [hash[name], node_hash] - when nil then hash[name] = node_hash - end - - # Handle child elements - children.each do |c| - if c.element? - c.to_hash(node_hash) - elsif c.text? || c.cdata? - node_hash[CONTENT_ROOT] ||= "" - node_hash[CONTENT_ROOT] << c.content - end - end - - # Remove content node if it is blank and there are child tags - if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank? - node_hash.delete(CONTENT_ROOT) - end - - # Handle attributes - attribute_nodes.each { |a| node_hash[a.node_name] = a.value } - - hash - end - end - end - - Nokogiri::XML::Document.include(Conversions::Document) - Nokogiri::XML::Node.include(Conversions::Node) - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/nokogirisax.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/nokogirisax.rb deleted file mode 100644 index 54e15e6a5f..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/nokogirisax.rb +++ /dev/null @@ -1,84 +0,0 @@ -begin - require "nokogiri" -rescue LoadError => e - $stderr.puts "You don't have nokogiri installed in your application. Please add it to your Gemfile and run bundle install" - raise e -end -require "active_support/core_ext/object/blank" -require "stringio" - -module ActiveSupport - module XmlMini_NokogiriSAX #:nodoc: - extend self - - # Class that will build the hash while the XML document - # is being parsed using SAX events. - class HashBuilder < Nokogiri::XML::SAX::Document - CONTENT_KEY = "__content__".freeze - HASH_SIZE_KEY = "__hash_size__".freeze - - attr_reader :hash - - def current_hash - @hash_stack.last - end - - def start_document - @hash = {} - @hash_stack = [@hash] - end - - def end_document - raise "Parse stack not empty!" if @hash_stack.size > 1 - end - - def error(error_message) - raise error_message - end - - def start_element(name, attrs = []) - new_hash = { CONTENT_KEY => "" }.merge!(Hash[attrs]) - new_hash[HASH_SIZE_KEY] = new_hash.size + 1 - - case current_hash[name] - when Array then current_hash[name] << new_hash - when Hash then current_hash[name] = [current_hash[name], new_hash] - when nil then current_hash[name] = new_hash - end - - @hash_stack.push(new_hash) - end - - def end_element(name) - if current_hash.length > current_hash.delete(HASH_SIZE_KEY) && current_hash[CONTENT_KEY].blank? || current_hash[CONTENT_KEY] == "" - current_hash.delete(CONTENT_KEY) - end - @hash_stack.pop - end - - def characters(string) - current_hash[CONTENT_KEY] << string - end - - alias_method :cdata_block, :characters - end - - attr_accessor :document_class - self.document_class = HashBuilder - - def parse(data) - if !data.respond_to?(:read) - data = StringIO.new(data || "") - end - - if data.eof? - {} - else - document = document_class.new - parser = Nokogiri::XML::SAX::Parser.new(document) - parser.parse(data) - document.hash - end - end - end -end diff --git a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/rexml.rb b/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/rexml.rb deleted file mode 100644 index 03fa910fa5..0000000000 --- a/debian/gems-compat/activesupport-5.1.7/lib/active_support/xml_mini/rexml.rb +++ /dev/null @@ -1,128 +0,0 @@ -require "active_support/core_ext/kernel/reporting" -require "active_support/core_ext/object/blank" -require "stringio" - -module ActiveSupport - module XmlMini_REXML #:nodoc: - extend self - - CONTENT_KEY = "__content__".freeze - - # Parse an XML Document string or IO into a simple hash. - # - # Same as XmlSimple::xml_in but doesn't shoot itself in the foot, - # and uses the defaults from Active Support. - # - # data:: - # XML Document string or IO to parse - def parse(data) - if !data.respond_to?(:read) - data = StringIO.new(data || "") - end - - if data.eof? - {} - else - silence_warnings { require "rexml/document" } unless defined?(REXML::Document) - doc = REXML::Document.new(data) - - if doc.root - merge_element!({}, doc.root, XmlMini.depth) - else - raise REXML::ParseException, - "The document #{doc.to_s.inspect} does not have a valid root" - end - end - end - - private - # Convert an XML element and merge into the hash - # - # hash:: - # Hash to merge the converted element into. - # element:: - # XML element to merge into hash - def merge_element!(hash, element, depth) - raise REXML::ParseException, "The document is too deep" if depth == 0 - merge!(hash, element.name, collapse(element, depth)) - end - - # Actually converts an XML document element into a data structure. - # - # element:: - # The document element to be collapsed. - def collapse(element, depth) - hash = get_attributes(element) - - if element.has_elements? - element.each_element { |child| merge_element!(hash, child, depth - 1) } - merge_texts!(hash, element) unless empty_content?(element) - hash - else - merge_texts!(hash, element) - end - end - - # Merge all the texts of an element into the hash - # - # hash:: - # Hash to add the converted element to. - # element:: - # XML element whose texts are to me merged into the hash - def merge_texts!(hash, element) - unless element.has_text? - hash - else - # must use value to prevent double-escaping - texts = "" - element.texts.each { |t| texts << t.value } - merge!(hash, CONTENT_KEY, texts) - end - end - - # Adds a new key/value pair to an existing Hash. If the key to be added - # already exists and the existing value associated with key is not - # an Array, it will be wrapped in an Array. Then the new value is - # appended to that Array. - # - # hash:: - # Hash to add key/value pair to. - # key:: - # Key to be added. - # value:: - # Value to be associated with key. - def merge!(hash, key, value) - if hash.has_key?(key) - if hash[key].instance_of?(Array) - hash[key] << value - else - hash[key] = [hash[key], value] - end - elsif value.instance_of?(Array) - hash[key] = [value] - else - hash[key] = value - end - hash - end - - # Converts the attributes array of an XML element into a hash. - # Returns an empty Hash if node has no attributes. - # - # element:: - # XML element to extract attributes from. - def get_attributes(element) - attributes = {} - element.attributes.each { |n, v| attributes[n] = v } - attributes - end - - # Determines if a document element has text content - # - # element:: - # XML element to be checked. - def empty_content?(element) - element.texts.join.blank? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/History.txt b/debian/gems-compat/arel-8.0.0/History.txt deleted file mode 100644 index 6985da4f49..0000000000 --- a/debian/gems-compat/arel-8.0.0/History.txt +++ /dev/null @@ -1,326 +0,0 @@ -=== 8.0.0 / 2017-02-21 - -* Enhancements - - * Remove deprecated type casting support in Arel - * Frozen all string literals in Arel - -=== 7.1.1 / 2016-07-27 - -* Bug Fixes - - * Fix warning in `Casted#hash` - -=== 7.1.0 / 2016-07-19 - -* Enhancements - - * Support Ruby 2.4 unified Integer class - * Implement `CASE` conditional expression - * Support for Bitwise Operations as `InfixOperations` - -=== 7.0.0 / 2015-12-17 - -* Enhancements - - * Remove deprecated method `Table#primary_key` - * Remove engine from the constructor arguments `Arel::Table` - * Deprecate automatic type casting within Arel - -=== 6.0.0 / 2014-11-25 - -* Enhancements - - * Remove deprecated `Arel::Expression` - * Remove deprecated `Arel::SqlLiteral` - * Remove deprecated `SelectManager#joins` - * Remove deprecated `SelectManager#to_a` - * Remove deprecated `Arel::Sql::Engine` - * Remove deprecated `Arel::InnerJoin` constant - * Remove deprecated `Arel::OuterJoin` constant - -== 5.0.0 / 2013-12-04 - -* Enhancements - - * Remove deprecated code - -* Bug Fixes - - * Fix serializing a relation when calling `to_yaml` - -=== 4.0.2 / 2014-02-05 - - * Bug Fixes - - * Fix `SqlLiteral` YAML serialization - * PostgreSQL bugfix for invalid SQL in subqueries - -== 4.0.1 / 2013-10-22 - -* Enhancements - - * Cache visitor dispatch on a per-visitor basis - * Improve performance of #uniq across a large number of nodes - -* Bug Fixes - - * Make visitors threadsafe by removing @last_column - * Support `columns_for_distinct` with Oracle adapter - -== 3.0.3 / 2013-11-12 - -* Enhancements - - * Support ANSI 2003 window functions - -* Bug Fixes - - * Fix joins in Informix - -== 3.0.2 / 2012-02-21 - -* Enhancements - - * Added a module for visiting and transforming bind values - * Fix in [] to be false, not in [] to be true - -* Bug Fixes - - * Revert fix for LIMIT / OFFSET when query is ordered in Oracle - -== 3.0.1 / 2012-02-17 - -* Bug Fixes - - * Fixed LIMIT / OFFSET when query is ordered in Oracle - -== 3.0.0 / 2012-01-12 - -* Enhancements - - * Support connection pool and schema cache - -* Bug Fixes - - * Conditions with no column can be followed by other conditions in Postgres - -== 2.2.3 / 2012-02-21 - -* Enhancements - - * Added a module for visiting and transforming bind values - -== 2.2.2 / 2012-02-20 - -* Enhancements - - * Support LOCK - * Allow using non-table alias as a right-hand relation name - * Added SelectManager#distinct - -== 2.2.1 / 2011-09-15 - -* Enhancements - - * Added UpdateManager#key to access the key value - * Added SelectManager#projections= to override any existing projections - * Added SelectManager#source to get the source of the last select core in the AST - -== 2.2.0 / 2011-08-09 - -* Bug Fixes - - * The database connection caches visitors for generating SQL. - * FALSE and TRUE nodes can be constructed. - * Fixed ORDER BY / LIMIT clauses for UPDATE statements in Oracle. - -== 2.1.4 / 2011-07-25 - -* Bug Fixes - - * Fix depth-first traversal to understand ascending / descending nodes. - * Parenthesis are suppressed with nested unions in MySQL. Thanks jhtwong! - -== 2.1.3 / 2011-06-27 - -* Bug Fixes - - * Fixed broken gem build. - -== 2.1.2 / 2011-06-27 - -* Bug Fixes - - * Visitors can define their own cache strategy so caches are not shared. - Fixes #57 - * Informix support fixed. Thanks Khronos. - * Ordering nodes broken to subclasses. Thanks Ernie Miller! - * Reversal supported in ordering nodes. Thanks Ernie Miller! - -== 2.1.1 / 2011/05/14 - -* Bug fixes - - * Fixed thread safety bug in ToSql visitor. Thanks Damon McCormick and - Cameron Walters! - -== 2.1.0 / 2011/04/30 - -* Enhancements - - * AST is now Enumerable - * AND nodes are now n-ary nodes - * SQL Literals may be used as Attribute names - * Added Arel::Nodes::NamedFunction for representing generic SQL functions - * Add Arel::SelectManager#limit= - * Add Arel::SelectManager#offset - * Add Arel::SelectManager#offset= - * Added Arel::SelectManager#create_insert for building an insert manager. - * SQL Literals are allowed for values in INSERT statements. - * Math operations have been added to attributes, thanks to - Vladimir Meremyanin. - -* Bug fixes - - * MSSQL adds TOP to sub selects - * Assigning nil to take() removes LIMIT from statement. - * Assigning nil to offset() removes OFFSET from statement. - * TableAlias leg ordering fixed - -* Deprecations - - * Calls to `insert` are deprecated. Please use `compile_insert` then call - `to_sql` on the resulting object and execute that SQL. - - * Calls to `update` are deprecated. Please use `compile_update` then call - `to_sql` on the resulting object and execute that SQL. - - * Calls to `delete` are deprecated. Please use `compile_delete` then call - `to_sql` on the resulting object and execute that SQL. - - * Arel::Table#joins is deprecated and will be removed in 3.0.0 with no - replacement. - - * Arel::Table#columns is deprecated and will be removed in 3.0.0 with no - replacement. - - * Arel::Table.table_cache is deprecated and will be removed in 3.0.0 with no - replacement. - - * Arel::Nodes::And.new takes a single list instead of left and right. - - * Arel::Table#primary_key is deprecated and will be removed in 3.0.0 with no - replacement. - - * Arel::SelectManager#where_clauses is deprecated and will be removed in - 3.0.0 with no replacement. - - * Arel::SelectManager#wheres is deprecated and will be removed in - 3.0.0 with no replacement. - -== 2.0.9 / 2010/02/25 - -* Bug Fixes - - * Custom LOCK strings are allowed. Fixes LH # 6399 - https://rails.lighthouseapp.com/projects/8994/tickets/6399-allow-database-specific-locking-clauses-to-be-used - - * Strings passed to StringManager#on will be automatically tagged as SQL - literals. Fixes Rails LH #6384 - https://rails.lighthouseapp.com/projects/8994/tickets/6384-activerecord-303-and-3-0-stable-generate-invalid-sql-for-has_many-through-association-with-conditions - -== 2.0.8 / 2010/02/08 - -* Bug Fixes - - * Added set operation support - * Fixed problems with *_any / *_all methods. - -== 2.0.7 - -* Bug Fixes - - * Limit members are visited - * Fixing MSSQL TOP support - -== 2.0.6 12/01/2010 - -* Bug Fixes - - * Rails 3.0.x does not like that Node is Enumerable, so removing for now. - -== 2.0.5 11/30/2010 - -* Enhancements - - * Arel::Visitors::DepthFirst can walk your AST depth first - * Arel::Nodes::Node is enumerable, depth first - -* Bug fixes - - * #lock will lock SELECT statements "FOR UPDATE" on mysql - * Nodes::Node#not factory method added for creating Nodes::Not nodes - * Added an As node - -* Deprecations - - * Support for Subclasses of core classes will be removed in Arel version - 2.2.0 - -== 2.0.4 - -* Bug fixes - - * Speed improvements for Range queries. Thanks Rolf Timmermans! - -== 2.0.3 - -* Bug fixes - - * Fixing Oracle support - * Added a visitor for "Class" objects - -== 2.0.2 - -* Bug fixes - - * MySQL selects from DUAL on empty FROM - * Visitor translates nil to NULL - * Visitor translates Bignum properly - -== 2.0.1 - -* Bug fixes - -== 2.0.0 / 2010-08-01 -* Enhancements - - * Recreate library using the Visitor pattern. - http://en.wikipedia.org/wiki/Visitor_pattern - -== 0.3.0 / 2010-03-10 - -* Enhancements - - * Introduced "SQL compilers" for query generation. - * Added support for Oracle (Raimonds Simanovskis) and IBM/DB (Praveen Devarao). - * Improvements to give better support to Active Record. - -== 0.2.1 / 2010-02-05 - -* Enhancements - - * Bump dependency version of activesupport to 3.0.0.beta - -== 0.2.0 / 2010-01-31 - - * Ruby 1.9 compatibility - * Many improvements to support the Arel integration into Active Record (see `git log v0.1.0..v0.2.0`) - * Thanks to Emilio Tagua and Pratik Naik for many significant contributions! - -== 0.1.0 / 2009-08-06 - -* 1 major enhancement - - * Birthday! diff --git a/debian/gems-compat/arel-8.0.0/MIT-LICENSE.txt b/debian/gems-compat/arel-8.0.0/MIT-LICENSE.txt deleted file mode 100644 index f7a59c3c5f..0000000000 --- a/debian/gems-compat/arel-8.0.0/MIT-LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2007-2016 Nick Kallen, Bryan Helmkamp, Emilio Tagua, Aaron Patterson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - diff --git a/debian/gems-compat/arel-8.0.0/README.md b/debian/gems-compat/arel-8.0.0/README.md deleted file mode 100644 index 292b7fdbca..0000000000 --- a/debian/gems-compat/arel-8.0.0/README.md +++ /dev/null @@ -1,285 +0,0 @@ -# Arel - -* http://github.com/rails/arel -* [API Documentation](http://www.rubydoc.info/github/rails/arel) - -## DESCRIPTION - -Arel Really Exasperates Logicians - -Arel is a SQL AST manager for Ruby. It - -1. simplifies the generation of complex SQL queries, and -2. adapts to various RDBMSes. - -It is intended to be a framework framework; that is, you can build your own ORM -with it, focusing on innovative object and collection modeling as opposed to -database compatibility and query generation. - -## Status - -For the moment, Arel uses Active Record's connection adapters to connect to the various engines and perform connection pooling, quoting, and type conversion. - -## A Gentle Introduction - -Generating a query with Arel is simple. For example, in order to produce - -```sql -SELECT * FROM users -``` - -you construct a table relation and convert it to SQL: - -```ruby -users = Arel::Table.new(:users) -query = users.project(Arel.sql('*')) -query.to_sql -``` - -### More Sophisticated Queries - -Here is a whirlwind tour through the most common SQL operators. These will probably cover 80% of all interaction with the database. - -First is the 'restriction' operator, `where`: - -```ruby -users.where(users[:name].eq('amy')) -# => SELECT * FROM users WHERE users.name = 'amy' -``` - -What would, in SQL, be part of the `SELECT` clause is called in Arel a `projection`: - -```ruby -users.project(users[:id]) -# => SELECT users.id FROM users -``` - -Comparison operators `=`, `!=`, `<`, `>`, `<=`, `>=`, `IN`: - -```ruby -users.where(users[:age].eq(10)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE "users"."age" = 10 - -users.where(users[:age].not_eq(10)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE "users"."age" != 10 - -users.where(users[:age].lt(10)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE "users"."age" < 10 - -users.where(users[:age].gt(10)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE "users"."age" > 10 - -users.where(users[:age].lteq(10)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE "users"."age" <= 10 - -users.where(users[:age].gteq(10)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE "users"."age" >= 10 - -users.where(users[:age].in([20, 16, 17])).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE "users"."age" IN (20, 16, 17) -``` - -Bitwise operators `&`, `|`, `^`, `<<`, `>>`: - -```ruby -users.where((users[:bitmap] & 16).gt(0)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE ("users"."bitmap" & 16) > 0 - -users.where((users[:bitmap] | 16).gt(0)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE ("users"."bitmap" | 16) > 0 - -users.where((users[:bitmap] ^ 16).gt(0)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE ("users"."bitmap" ^ 16) > 0 - -users.where((users[:bitmap] << 1).gt(0)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE ("users"."bitmap" << 1) > 0 - -users.where((users[:bitmap] >> 1).gt(0)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE ("users"."bitmap" >> 1) > 0 - -users.where((~ users[:bitmap]).gt(0)).project(Arel.sql('*')) -# => SELECT * FROM "users" WHERE ~ "users"."bitmap" > 0 -``` - -Joins resemble SQL strongly: - -```ruby -users.join(photos).on(users[:id].eq(photos[:user_id])) -# => SELECT * FROM users INNER JOIN photos ON users.id = photos.user_id -``` - -Left joins: - -```ruby -users.join(photos, Arel::Nodes::OuterJoin).on(users[:id].eq(photos[:user_id])) -# => SELECT FROM users LEFT OUTER JOIN photos ON users.id = photos.user_id -``` - -What are called `LIMIT` and `OFFSET` in SQL are called `take` and `skip` in Arel: - -```ruby -users.take(5) # => SELECT * FROM users LIMIT 5 -users.skip(4) # => SELECT * FROM users OFFSET 4 -``` - -`GROUP BY` is called `group`: - -```ruby -users.project(users[:name]).group(users[:name]) -# => SELECT users.name FROM users GROUP BY users.name -``` - -The best property of Arel is its "composability," or closure under all operations. For example, to restrict AND project, just "chain" the method invocations: - -```ruby -users \ - .where(users[:name].eq('amy')) \ - .project(users[:id]) \ -# => SELECT users.id FROM users WHERE users.name = 'amy' -``` - -All operators are chainable in this way, and they are chainable any number of times, in any order. - -```ruby -users.where(users[:name].eq('bob')).where(users[:age].lt(25)) -``` - -The `OR` operator works like this: - -```ruby -users.where(users[:name].eq('bob').or(users[:age].lt(25))) -``` - -The `AND` operator behaves similarly. - -Aggregate functions `AVG`, `SUM`, `COUNT`, `MIN`, `MAX`, `HAVING`: - -```ruby -photos.group(photos[:user_id]).having(photos[:id].count.gt(5)) -# => SELECT FROM photos GROUP BY photos.user_id HAVING COUNT(photos.id) > 5 - -users.project(users[:age].sum) -# => SELECT SUM(users.age) FROM users - -users.project(users[:age].average) -# => SELECT AVG(users.age) FROM users - -users.project(users[:age].maximum) -# => SELECT MAX(users.age) FROM users - -users.project(users[:age].minimum) -# => SELECT MIN(users.age) FROM users - -users.project(users[:age].count) -# => SELECT COUNT(users.age) FROM users -``` - -Aliasing Aggregate Functions: - -```ruby -users.project(users[:age].average.as("mean_age")) -# => SELECT AVG(users.age) AS mean_age FROM users -``` - -### The Crazy Features - -The examples above are fairly simple and other libraries match or come close to matching the expressiveness of Arel (e.g. `Sequel` in Ruby). - -#### Inline math operations - -Suppose we have a table `products` with prices in different currencies. And we have a table `currency_rates`, of constantly changing currency rates. In Arel: - -```ruby -products = Arel::Table.new(:products) -# Attributes: [:id, :name, :price, :currency_id] - -currency_rates = Arel::Table.new(:currency_rates) -# Attributes: [:from_id, :to_id, :date, :rate] -``` - -Now, to order products by price in user preferred currency simply call: - -```ruby -products. - join(:currency_rates).on(products[:currency_id].eq(currency_rates[:from_id])). - where(currency_rates[:to_id].eq(user_preferred_currency), currency_rates[:date].eq(Date.today)). - order(products[:price] * currency_rates[:rate]) -``` - -#### Complex Joins - -Where Arel really shines is in its ability to handle complex joins and aggregations. As a first example, let's consider an "adjacency list", a tree represented in a table. Suppose we have a table `comments`, representing a threaded discussion: - -```ruby -comments = Arel::Table.new(:comments) -``` - -And this table has the following attributes: - -```ruby -# [:id, :body, :parent_id] -``` - -The `parent_id` column is a foreign key from the `comments` table to itself. -Joining a table to itself requires aliasing in SQL. This aliasing can be handled from Arel as below: - -```ruby -replies = comments.alias -comments_with_replies = \ - comments.join(replies).on(replies[:parent_id].eq(comments[:id])).where(comments[:id].eq(1)) -# => SELECT * FROM comments INNER JOIN comments AS comments_2 -# WHERE comments_2.parent_id = comments.id AND comments.id = 1 -``` - -This will return the reply for the first comment. - -[Common Table Expressions (CTE)](https://en.wikipedia.org/wiki/Common_table_expressions#Common_table_expression) support via: - -Create a `CTE` - -```ruby -cte_table = Arel::Table.new(:cte_table) -composed_cte = Arel::Nodes::As.new(cte_table, photos.where(photos[:created_at].gt(Date.current))) -``` - -Use the created `CTE`: - -```ruby -users. - join(cte_table).on(users[:id].eq(cte_table[:user_id])). - project(users[:id], cte_table[:click].sum). - with(composed_cte) - -# => WITH cte_table AS (SELECT FROM photos WHERE photos.created_at > '2014-05-02') -# SELECT users.id, SUM(cte_table.click) -# FROM users INNER JOIN cte_table ON users.id = cte_table.user_id -``` - -When your query is too complex for `Arel`, you can use `Arel::SqlLiteral`: - -```ruby -photo_clicks = Arel::Nodes::SqlLiteral.new(<<-SQL - CASE WHEN condition1 THEN calculation1 - WHEN condition2 THEN calculation2 - WHEN condition3 THEN calculation3 - ELSE default_calculation END -SQL -) - -photos.project(photo_clicks.as("photo_clicks")) -# => SELECT CASE WHEN condition1 THEN calculation1 -# WHEN condition2 THEN calculation2 -# WHEN condition3 THEN calculation3 -# ELSE default_calculation END -# FROM "photos" -``` - -## Contributing to Arel - -Arel is the work of many contributors. You're encouraged to submit pull requests, propose -features and discuss issues. - -See [CONTRIBUTING](CONTRIBUTING.md). - -## License -Arel is released under the [MIT License](http://www.opensource.org/licenses/MIT). diff --git a/debian/gems-compat/arel-8.0.0/arel.gemspec b/debian/gems-compat/arel-8.0.0/arel.gemspec deleted file mode 100644 index c80a5bd907..0000000000 --- a/debian/gems-compat/arel-8.0.0/arel.gemspec +++ /dev/null @@ -1,42 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: arel 8.0.0 ruby lib - -Gem::Specification.new do |s| - s.name = "arel".freeze - s.version = "8.0.0" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib".freeze] - s.authors = ["Aaron Patterson".freeze, "Bryan Helmkamp".freeze, "Emilio Tagua".freeze, "Nick Kallen".freeze] - s.date = "2017-02-21" - s.description = "Arel Really Exasperates Logicians\n\nArel is a SQL AST manager for Ruby. It\n\n1. Simplifies the generation of complex SQL queries\n2. Adapts to various RDBMSes\n\nIt is intended to be a framework framework; that is, you can build your own ORM\nwith it, focusing on innovative object and collection modeling as opposed to\ndatabase compatibility and query generation.".freeze - s.email = ["aaron@tenderlovemaking.com".freeze, "bryan@brynary.com".freeze, "miloops@gmail.com".freeze] - s.extra_rdoc_files = ["History.txt".freeze, "MIT-LICENSE.txt".freeze, "README.md".freeze] - s.files = ["History.txt".freeze, "MIT-LICENSE.txt".freeze, "README.md".freeze, "lib/arel.rb".freeze, "lib/arel/alias_predication.rb".freeze, "lib/arel/attributes.rb".freeze, "lib/arel/attributes/attribute.rb".freeze, "lib/arel/collectors/bind.rb".freeze, "lib/arel/collectors/plain_string.rb".freeze, "lib/arel/collectors/sql_string.rb".freeze, "lib/arel/compatibility/wheres.rb".freeze, "lib/arel/crud.rb".freeze, "lib/arel/delete_manager.rb".freeze, "lib/arel/errors.rb".freeze, "lib/arel/expressions.rb".freeze, "lib/arel/factory_methods.rb".freeze, "lib/arel/insert_manager.rb".freeze, "lib/arel/math.rb".freeze, "lib/arel/nodes.rb".freeze, "lib/arel/nodes/and.rb".freeze, "lib/arel/nodes/ascending.rb".freeze, "lib/arel/nodes/binary.rb".freeze, "lib/arel/nodes/bind_param.rb".freeze, "lib/arel/nodes/case.rb".freeze, "lib/arel/nodes/casted.rb".freeze, "lib/arel/nodes/count.rb".freeze, "lib/arel/nodes/delete_statement.rb".freeze, "lib/arel/nodes/descending.rb".freeze, "lib/arel/nodes/equality.rb".freeze, "lib/arel/nodes/extract.rb".freeze, "lib/arel/nodes/false.rb".freeze, "lib/arel/nodes/full_outer_join.rb".freeze, "lib/arel/nodes/function.rb".freeze, "lib/arel/nodes/grouping.rb".freeze, "lib/arel/nodes/in.rb".freeze, "lib/arel/nodes/infix_operation.rb".freeze, "lib/arel/nodes/inner_join.rb".freeze, "lib/arel/nodes/insert_statement.rb".freeze, "lib/arel/nodes/join_source.rb".freeze, "lib/arel/nodes/matches.rb".freeze, "lib/arel/nodes/named_function.rb".freeze, "lib/arel/nodes/node.rb".freeze, "lib/arel/nodes/outer_join.rb".freeze, "lib/arel/nodes/over.rb".freeze, "lib/arel/nodes/regexp.rb".freeze, "lib/arel/nodes/right_outer_join.rb".freeze, "lib/arel/nodes/select_core.rb".freeze, "lib/arel/nodes/select_statement.rb".freeze, "lib/arel/nodes/sql_literal.rb".freeze, "lib/arel/nodes/string_join.rb".freeze, "lib/arel/nodes/table_alias.rb".freeze, "lib/arel/nodes/terminal.rb".freeze, "lib/arel/nodes/true.rb".freeze, "lib/arel/nodes/unary.rb".freeze, "lib/arel/nodes/unary_operation.rb".freeze, "lib/arel/nodes/unqualified_column.rb".freeze, "lib/arel/nodes/update_statement.rb".freeze, "lib/arel/nodes/values.rb".freeze, "lib/arel/nodes/window.rb".freeze, "lib/arel/nodes/with.rb".freeze, "lib/arel/order_predications.rb".freeze, "lib/arel/predications.rb".freeze, "lib/arel/select_manager.rb".freeze, "lib/arel/table.rb".freeze, "lib/arel/tree_manager.rb".freeze, "lib/arel/update_manager.rb".freeze, "lib/arel/visitors.rb".freeze, "lib/arel/visitors/bind_substitute.rb".freeze, "lib/arel/visitors/bind_visitor.rb".freeze, "lib/arel/visitors/depth_first.rb".freeze, "lib/arel/visitors/dot.rb".freeze, "lib/arel/visitors/ibm_db.rb".freeze, "lib/arel/visitors/informix.rb".freeze, "lib/arel/visitors/mssql.rb".freeze, "lib/arel/visitors/mysql.rb".freeze, "lib/arel/visitors/oracle.rb".freeze, "lib/arel/visitors/oracle12.rb".freeze, "lib/arel/visitors/postgresql.rb".freeze, "lib/arel/visitors/reduce.rb".freeze, "lib/arel/visitors/sqlite.rb".freeze, "lib/arel/visitors/to_sql.rb".freeze, "lib/arel/visitors/visitor.rb".freeze, "lib/arel/visitors/where_sql.rb".freeze, "lib/arel/window_predications.rb".freeze] - s.homepage = "https://github.com/rails/arel".freeze - s.licenses = ["MIT".freeze] - s.rdoc_options = ["--main".freeze, "README.md".freeze] - s.rubygems_version = "2.7.6".freeze - s.summary = "Arel Really Exasperates Logicians Arel is a SQL AST manager for Ruby".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_development_dependency(%q.freeze, ["~> 5.4"]) - s.add_development_dependency(%q.freeze, [">= 0"]) - s.add_development_dependency(%q.freeze, ["~> 4.0"]) - else - s.add_dependency(%q.freeze, ["~> 5.4"]) - s.add_dependency(%q.freeze, [">= 0"]) - s.add_dependency(%q.freeze, ["~> 4.0"]) - end - else - s.add_dependency(%q.freeze, ["~> 5.4"]) - s.add_dependency(%q.freeze, [">= 0"]) - s.add_dependency(%q.freeze, ["~> 4.0"]) - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel.rb b/debian/gems-compat/arel-8.0.0/lib/arel.rb deleted file mode 100644 index f0d2bdce78..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel.rb +++ /dev/null @@ -1,38 +0,0 @@ -# frozen_string_literal: true -require 'arel/errors' - -require 'arel/crud' -require 'arel/factory_methods' - -require 'arel/expressions' -require 'arel/predications' -require 'arel/window_predications' -require 'arel/math' -require 'arel/alias_predication' -require 'arel/order_predications' -require 'arel/table' -require 'arel/attributes' -require 'arel/compatibility/wheres' - -require 'arel/visitors' - -require 'arel/tree_manager' -require 'arel/insert_manager' -require 'arel/select_manager' -require 'arel/update_manager' -require 'arel/delete_manager' -require 'arel/nodes' - -module Arel - VERSION = '8.0.0' - - def self.sql raw_sql - Arel::Nodes::SqlLiteral.new raw_sql - end - - def self.star - sql '*' - end - ## Convenience Alias - Node = Arel::Nodes::Node -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/alias_predication.rb b/debian/gems-compat/arel-8.0.0/lib/arel/alias_predication.rb deleted file mode 100644 index cb50fb95be..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/alias_predication.rb +++ /dev/null @@ -1,8 +0,0 @@ -# frozen_string_literal: true -module Arel - module AliasPredication - def as other - Nodes::As.new self, Nodes::SqlLiteral.new(other) - end - end -end \ No newline at end of file diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/attributes.rb b/debian/gems-compat/arel-8.0.0/lib/arel/attributes.rb deleted file mode 100644 index ed4739ebed..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/attributes.rb +++ /dev/null @@ -1,21 +0,0 @@ -# frozen_string_literal: true -require 'arel/attributes/attribute' - -module Arel - module Attributes - ### - # Factory method to wrap a raw database +column+ to an Arel Attribute. - def self.for column - case column.type - when :string, :text, :binary then String - when :integer then Integer - when :float then Float - when :decimal then Decimal - when :date, :datetime, :timestamp, :time then Time - when :boolean then Boolean - else - Undefined - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/attributes/attribute.rb b/debian/gems-compat/arel-8.0.0/lib/arel/attributes/attribute.rb deleted file mode 100644 index 41bc0c32c7..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/attributes/attribute.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true -module Arel - module Attributes - class Attribute < Struct.new :relation, :name - include Arel::Expressions - include Arel::Predications - include Arel::AliasPredication - include Arel::OrderPredications - include Arel::Math - - ### - # Create a node for lowering this attribute - def lower - relation.lower self - end - - def type_cast_for_database(value) - relation.type_cast_for_database(name, value) - end - - def able_to_type_cast? - relation.able_to_type_cast? - end - end - - class String < Attribute; end - class Time < Attribute; end - class Boolean < Attribute; end - class Decimal < Attribute; end - class Float < Attribute; end - class Integer < Attribute; end - class Undefined < Attribute; end - end - - Attribute = Attributes::Attribute -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/collectors/bind.rb b/debian/gems-compat/arel-8.0.0/lib/arel/collectors/bind.rb deleted file mode 100644 index dfa79d1001..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/collectors/bind.rb +++ /dev/null @@ -1,37 +0,0 @@ -# frozen_string_literal: true -module Arel - module Collectors - class Bind - def initialize - @parts = [] - end - - def << str - @parts << str - self - end - - def add_bind bind - @parts << bind - self - end - - def value; @parts; end - - def substitute_binds bvs - bvs = bvs.dup - @parts.map do |val| - if Arel::Nodes::BindParam === val - bvs.shift - else - val - end - end - end - - def compile bvs - substitute_binds(bvs).join - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/collectors/plain_string.rb b/debian/gems-compat/arel-8.0.0/lib/arel/collectors/plain_string.rb deleted file mode 100644 index 1e8d2a2152..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/collectors/plain_string.rb +++ /dev/null @@ -1,19 +0,0 @@ -# frozen_string_literal: true -module Arel - module Collectors - class PlainString - def initialize - @str = ''.dup - end - - def value - @str - end - - def << str - @str << str - self - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/collectors/sql_string.rb b/debian/gems-compat/arel-8.0.0/lib/arel/collectors/sql_string.rb deleted file mode 100644 index 5f42117331..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/collectors/sql_string.rb +++ /dev/null @@ -1,25 +0,0 @@ -# encoding: utf-8 -# frozen_string_literal: true - -require 'arel/collectors/plain_string' - -module Arel - module Collectors - class SQLString < PlainString - def initialize(*) - super - @bind_index = 1 - end - - def add_bind bind - self << yield(@bind_index) - @bind_index += 1 - self - end - - def compile bvs - value - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/compatibility/wheres.rb b/debian/gems-compat/arel-8.0.0/lib/arel/compatibility/wheres.rb deleted file mode 100644 index 3e60894bd8..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/compatibility/wheres.rb +++ /dev/null @@ -1,34 +0,0 @@ -# frozen_string_literal: true -module Arel - module Compatibility # :nodoc: - class Wheres # :nodoc: - include Enumerable - - module Value # :nodoc: - attr_accessor :visitor - def value - visitor.accept self - end - - def name - super.to_sym - end - end - - def initialize engine, collection - @engine = engine - @collection = collection - end - - def each - to_sql = Visitors::ToSql.new @engine - - @collection.each { |c| - c.extend(Value) - c.visitor = to_sql - yield c - } - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/crud.rb b/debian/gems-compat/arel-8.0.0/lib/arel/crud.rb deleted file mode 100644 index 2d10432205..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/crud.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true -module Arel - ### - # FIXME hopefully we can remove this - module Crud - def compile_update values, pk - um = UpdateManager.new - - if Nodes::SqlLiteral === values - relation = @ctx.from - else - relation = values.first.first.relation - end - um.key = pk - um.table relation - um.set values - um.take @ast.limit.expr if @ast.limit - um.order(*@ast.orders) - um.wheres = @ctx.wheres - um - end - - def compile_insert values - im = create_insert - im.insert values - im - end - - def create_insert - InsertManager.new - end - - def compile_delete - dm = DeleteManager.new - dm.take @ast.limit.expr if @ast.limit - dm.wheres = @ctx.wheres - dm.from @ctx.froms - dm - end - - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/delete_manager.rb b/debian/gems-compat/arel-8.0.0/lib/arel/delete_manager.rb deleted file mode 100644 index aee4511249..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/delete_manager.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true -module Arel - class DeleteManager < Arel::TreeManager - def initialize - super - @ast = Nodes::DeleteStatement.new - @ctx = @ast - end - - def from relation - @ast.relation = relation - self - end - - def take limit - @ast.limit = Nodes::Limit.new(Nodes.build_quoted(limit)) if limit - self - end - - def wheres= list - @ast.wheres = list - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/errors.rb b/debian/gems-compat/arel-8.0.0/lib/arel/errors.rb deleted file mode 100644 index 86fbb80461..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/errors.rb +++ /dev/null @@ -1,8 +0,0 @@ -# frozen_string_literal: true -module Arel - class ArelError < StandardError - end - - class EmptyJoinError < ArelError - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/expressions.rb b/debian/gems-compat/arel-8.0.0/lib/arel/expressions.rb deleted file mode 100644 index 612a0942f1..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/expressions.rb +++ /dev/null @@ -1,29 +0,0 @@ -# frozen_string_literal: true -module Arel - module Expressions - def count distinct = false - Nodes::Count.new [self], distinct - end - - def sum - Nodes::Sum.new [self] - end - - def maximum - Nodes::Max.new [self] - end - - def minimum - Nodes::Min.new [self] - end - - def average - Nodes::Avg.new [self] - end - - def extract field - Nodes::Extract.new [self], field - end - - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/factory_methods.rb b/debian/gems-compat/arel-8.0.0/lib/arel/factory_methods.rb deleted file mode 100644 index 6647c5ac44..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/factory_methods.rb +++ /dev/null @@ -1,44 +0,0 @@ -# frozen_string_literal: true -module Arel - ### - # Methods for creating various nodes - module FactoryMethods - def create_true - Arel::Nodes::True.new - end - - def create_false - Arel::Nodes::False.new - end - - def create_table_alias relation, name - Nodes::TableAlias.new(relation, name) - end - - def create_join to, constraint = nil, klass = Nodes::InnerJoin - klass.new(to, constraint) - end - - def create_string_join to - create_join to, nil, Nodes::StringJoin - end - - def create_and clauses - Nodes::And.new clauses - end - - def create_on expr - Nodes::On.new expr - end - - def grouping expr - Nodes::Grouping.new expr - end - - ### - # Create a LOWER() function - def lower column - Nodes::NamedFunction.new 'LOWER', [Nodes.build_quoted(column)] - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/insert_manager.rb b/debian/gems-compat/arel-8.0.0/lib/arel/insert_manager.rb deleted file mode 100644 index d0a49842de..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/insert_manager.rb +++ /dev/null @@ -1,43 +0,0 @@ -# frozen_string_literal: true -module Arel - class InsertManager < Arel::TreeManager - def initialize - super - @ast = Nodes::InsertStatement.new - end - - def into table - @ast.relation = table - self - end - - def columns; @ast.columns end - def values= val; @ast.values = val; end - - def select select - @ast.select = select - end - - def insert fields - return if fields.empty? - - if String === fields - @ast.values = Nodes::SqlLiteral.new(fields) - else - @ast.relation ||= fields.first.first.relation - - values = [] - - fields.each do |column, value| - @ast.columns << column - values << value - end - @ast.values = create_values values, @ast.columns - end - end - - def create_values values, columns - Nodes::Values.new values, columns - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/math.rb b/debian/gems-compat/arel-8.0.0/lib/arel/math.rb deleted file mode 100644 index 9e6549b58f..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/math.rb +++ /dev/null @@ -1,44 +0,0 @@ -# frozen_string_literal: true -module Arel - module Math - def *(other) - Arel::Nodes::Multiplication.new(self, other) - end - - def +(other) - Arel::Nodes::Grouping.new(Arel::Nodes::Addition.new(self, other)) - end - - def -(other) - Arel::Nodes::Grouping.new(Arel::Nodes::Subtraction.new(self, other)) - end - - def /(other) - Arel::Nodes::Division.new(self, other) - end - - def &(other) - Arel::Nodes::Grouping.new(Arel::Nodes::BitwiseAnd.new(self, other)) - end - - def |(other) - Arel::Nodes::Grouping.new(Arel::Nodes::BitwiseOr.new(self, other)) - end - - def ^(other) - Arel::Nodes::Grouping.new(Arel::Nodes::BitwiseXor.new(self, other)) - end - - def <<(other) - Arel::Nodes::Grouping.new(Arel::Nodes::BitwiseShiftLeft.new(self, other)) - end - - def >>(other) - Arel::Nodes::Grouping.new(Arel::Nodes::BitwiseShiftRight.new(self, other)) - end - - def ~@ - Arel::Nodes::BitwiseNot.new(self) - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes.rb deleted file mode 100644 index 8c9815a96b..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes.rb +++ /dev/null @@ -1,64 +0,0 @@ -# frozen_string_literal: true -# node -require 'arel/nodes/node' -require 'arel/nodes/select_statement' -require 'arel/nodes/select_core' -require 'arel/nodes/insert_statement' -require 'arel/nodes/update_statement' -require 'arel/nodes/bind_param' - -# terminal - -require 'arel/nodes/terminal' -require 'arel/nodes/true' -require 'arel/nodes/false' - -# unary -require 'arel/nodes/unary' -require 'arel/nodes/grouping' -require 'arel/nodes/ascending' -require 'arel/nodes/descending' -require 'arel/nodes/unqualified_column' -require 'arel/nodes/with' - -# binary -require 'arel/nodes/binary' -require 'arel/nodes/equality' -require 'arel/nodes/in' # Why is this subclassed from equality? -require 'arel/nodes/join_source' -require 'arel/nodes/delete_statement' -require 'arel/nodes/table_alias' -require 'arel/nodes/infix_operation' -require 'arel/nodes/unary_operation' -require 'arel/nodes/over' -require 'arel/nodes/matches' -require 'arel/nodes/regexp' - -# nary -require 'arel/nodes/and' - -# function -# FIXME: Function + Alias can be rewritten as a Function and Alias node. -# We should make Function a Unary node and deprecate the use of "aliaz" -require 'arel/nodes/function' -require 'arel/nodes/count' -require 'arel/nodes/extract' -require 'arel/nodes/values' -require 'arel/nodes/named_function' - -# windows -require 'arel/nodes/window' - -# conditional expressions -require 'arel/nodes/case' - -# joins -require 'arel/nodes/full_outer_join' -require 'arel/nodes/inner_join' -require 'arel/nodes/outer_join' -require 'arel/nodes/right_outer_join' -require 'arel/nodes/string_join' - -require 'arel/nodes/sql_literal' - -require 'arel/nodes/casted' diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/and.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/and.rb deleted file mode 100644 index 1e2f61cf43..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/and.rb +++ /dev/null @@ -1,31 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class And < Arel::Nodes::Node - attr_reader :children - - def initialize children - super() - @children = children - end - - def left - children.first - end - - def right - children[1] - end - - def hash - children.hash - end - - def eql? other - self.class == other.class && - self.children == other.children - end - alias :== :eql? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/ascending.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/ascending.rb deleted file mode 100644 index adadab55e4..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/ascending.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Ascending < Ordering - - def reverse - Descending.new(expr) - end - - def direction - :asc - end - - def ascending? - true - end - - def descending? - false - end - - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/binary.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/binary.rb deleted file mode 100644 index 3001788774..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/binary.rb +++ /dev/null @@ -1,51 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Binary < Arel::Nodes::Node - attr_accessor :left, :right - - def initialize left, right - super() - @left = left - @right = right - end - - def initialize_copy other - super - @left = @left.clone if @left - @right = @right.clone if @right - end - - def hash - [self.class, @left, @right].hash - end - - def eql? other - self.class == other.class && - self.left == other.left && - self.right == other.right - end - alias :== :eql? - end - - %w{ - As - Assignment - Between - GreaterThan - GreaterThanOrEqual - Join - LessThan - LessThanOrEqual - NotEqual - NotIn - Or - Union - UnionAll - Intersect - Except - }.each do |name| - const_set name, Class.new(Binary) - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/bind_param.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/bind_param.rb deleted file mode 100644 index 9e297831cd..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/bind_param.rb +++ /dev/null @@ -1,10 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class BindParam < Node - def ==(other) - other.is_a?(BindParam) - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/case.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/case.rb deleted file mode 100644 index 1edca40001..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/case.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Case < Arel::Nodes::Node - include Arel::OrderPredications - include Arel::Predications - include Arel::AliasPredication - - attr_accessor :case, :conditions, :default - - def initialize expression = nil, default = nil - @case = expression - @conditions = [] - @default = default - end - - def when condition, expression = nil - @conditions << When.new(Nodes.build_quoted(condition), expression) - self - end - - def then expression - @conditions.last.right = Nodes.build_quoted(expression) - self - end - - def else expression - @default = Else.new Nodes.build_quoted(expression) - self - end - - def initialize_copy other - super - @case = @case.clone if @case - @conditions = @conditions.map { |x| x.clone } - @default = @default.clone if @default - end - - def hash - [@case, @conditions, @default].hash - end - - def eql? other - self.class == other.class && - self.case == other.case && - self.conditions == other.conditions && - self.default == other.default - end - alias :== :eql? - end - - class When < Binary # :nodoc: - end - - class Else < Unary # :nodoc: - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/casted.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/casted.rb deleted file mode 100644 index 290e4dd38c..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/casted.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Casted < Arel::Nodes::Node # :nodoc: - attr_reader :val, :attribute - def initialize val, attribute - @val = val - @attribute = attribute - super() - end - - def nil?; @val.nil?; end - - def hash - [self.class, val, attribute].hash - end - - def eql? other - self.class == other.class && - self.val == other.val && - self.attribute == other.attribute - end - alias :== :eql? - end - - class Quoted < Arel::Nodes::Unary # :nodoc: - alias :val :value - def nil?; val.nil?; end - end - - def self.build_quoted other, attribute = nil - case other - when Arel::Nodes::Node, Arel::Attributes::Attribute, Arel::Table, Arel::Nodes::BindParam, Arel::SelectManager, Arel::Nodes::Quoted - other - else - case attribute - when Arel::Attributes::Attribute - Casted.new other, attribute - else - Quoted.new other - end - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/count.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/count.rb deleted file mode 100644 index a7c6236a22..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/count.rb +++ /dev/null @@ -1,11 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Count < Arel::Nodes::Function - def initialize expr, distinct = false, aliaz = nil - super(expr, aliaz) - @distinct = distinct - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/delete_statement.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/delete_statement.rb deleted file mode 100644 index 593ce9bddf..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/delete_statement.rb +++ /dev/null @@ -1,22 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class DeleteStatement < Arel::Nodes::Binary - attr_accessor :limit - - alias :relation :left - alias :relation= :left= - alias :wheres :right - alias :wheres= :right= - - def initialize relation = nil, wheres = [] - super - end - - def initialize_copy other - super - @right = @right.clone - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/descending.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/descending.rb deleted file mode 100644 index d7261ab583..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/descending.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Descending < Ordering - - def reverse - Ascending.new(expr) - end - - def direction - :desc - end - - def ascending? - false - end - - def descending? - true - end - - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/equality.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/equality.rb deleted file mode 100644 index ef44725e24..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/equality.rb +++ /dev/null @@ -1,10 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Equality < Arel::Nodes::Binary - def operator; :== end - alias :operand1 :left - alias :operand2 :right - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/extract.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/extract.rb deleted file mode 100644 index 4e797b6770..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/extract.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Extract < Arel::Nodes::Unary - include Arel::AliasPredication - include Arel::Predications - - attr_accessor :field - - def initialize expr, field - super(expr) - @field = field - end - - def hash - super ^ @field.hash - end - - def eql? other - super && - self.field == other.field - end - alias :== :eql? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/false.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/false.rb deleted file mode 100644 index 26b4e5db97..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/false.rb +++ /dev/null @@ -1,14 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class False < Arel::Nodes::Node - def hash - self.class.hash - end - - def eql? other - self.class == other.class - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/full_outer_join.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/full_outer_join.rb deleted file mode 100644 index 12a02d8cd9..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/full_outer_join.rb +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class FullOuterJoin < Arel::Nodes::Join - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/function.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/function.rb deleted file mode 100644 index 28a394e9f3..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/function.rb +++ /dev/null @@ -1,44 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Function < Arel::Nodes::Node - include Arel::Predications - include Arel::WindowPredications - include Arel::OrderPredications - attr_accessor :expressions, :alias, :distinct - - def initialize expr, aliaz = nil - super() - @expressions = expr - @alias = aliaz && SqlLiteral.new(aliaz) - @distinct = false - end - - def as aliaz - self.alias = SqlLiteral.new(aliaz) - self - end - - def hash - [@expressions, @alias, @distinct].hash - end - - def eql? other - self.class == other.class && - self.expressions == other.expressions && - self.alias == other.alias && - self.distinct == other.distinct - end - end - - %w{ - Sum - Exists - Max - Min - Avg - }.each do |name| - const_set(name, Class.new(Function)) - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/grouping.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/grouping.rb deleted file mode 100644 index 16911eb3b6..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/grouping.rb +++ /dev/null @@ -1,8 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Grouping < Unary - include Arel::Predications - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/in.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/in.rb deleted file mode 100644 index 30cd771c40..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/in.rb +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class In < Equality - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/infix_operation.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/infix_operation.rb deleted file mode 100644 index 4eb7c5356f..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/infix_operation.rb +++ /dev/null @@ -1,80 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - - class InfixOperation < Binary - include Arel::Expressions - include Arel::Predications - include Arel::OrderPredications - include Arel::AliasPredication - include Arel::Math - - attr_reader :operator - - def initialize operator, left, right - super(left, right) - @operator = operator - end - end - - class Multiplication < InfixOperation - def initialize left, right - super(:*, left, right) - end - end - - class Division < InfixOperation - def initialize left, right - super(:/, left, right) - end - end - - class Addition < InfixOperation - def initialize left, right - super(:+, left, right) - end - end - - class Subtraction < InfixOperation - def initialize left, right - super(:-, left, right) - end - end - - class Concat < InfixOperation - def initialize left, right - super('||', left, right) - end - end - - class BitwiseAnd < InfixOperation - def initialize left, right - super(:&, left, right) - end - end - - class BitwiseOr < InfixOperation - def initialize left, right - super(:|, left, right) - end - end - - class BitwiseXor < InfixOperation - def initialize left, right - super(:^, left, right) - end - end - - class BitwiseShiftLeft < InfixOperation - def initialize left, right - super(:<<, left, right) - end - end - - class BitwiseShiftRight < InfixOperation - def initialize left, right - super(:>>, left, right) - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/inner_join.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/inner_join.rb deleted file mode 100644 index 4e398267c3..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/inner_join.rb +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class InnerJoin < Arel::Nodes::Join - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/insert_statement.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/insert_statement.rb deleted file mode 100644 index 72793bc1ad..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/insert_statement.rb +++ /dev/null @@ -1,36 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class InsertStatement < Arel::Nodes::Node - attr_accessor :relation, :columns, :values, :select - - def initialize - super() - @relation = nil - @columns = [] - @values = nil - @select = nil - end - - def initialize_copy other - super - @columns = @columns.clone - @values = @values.clone if @values - @select = @select.clone if @select - end - - def hash - [@relation, @columns, @values, @select].hash - end - - def eql? other - self.class == other.class && - self.relation == other.relation && - self.columns == other.columns && - self.select == other.select && - self.values == other.values - end - alias :== :eql? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/join_source.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/join_source.rb deleted file mode 100644 index 428ce8183e..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/join_source.rb +++ /dev/null @@ -1,19 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - ### - # Class that represents a join source - # - # http://www.sqlite.org/syntaxdiagrams.html#join-source - - class JoinSource < Arel::Nodes::Binary - def initialize single_source, joinop = [] - super - end - - def empty? - !left && right.empty? - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/matches.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/matches.rb deleted file mode 100644 index 3ad3850a8e..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/matches.rb +++ /dev/null @@ -1,17 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Matches < Binary - attr_reader :escape - attr_accessor :case_sensitive - - def initialize(left, right, escape = nil, case_sensitive = false) - super(left, right) - @escape = escape && Nodes.build_quoted(escape) - @case_sensitive = case_sensitive - end - end - - class DoesNotMatch < Matches; end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/named_function.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/named_function.rb deleted file mode 100644 index 173838a7fd..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/named_function.rb +++ /dev/null @@ -1,22 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class NamedFunction < Arel::Nodes::Function - attr_accessor :name - - def initialize name, expr, aliaz = nil - super(expr, aliaz) - @name = name - end - - def hash - super ^ @name.hash - end - - def eql? other - super && self.name == other.name - end - alias :== :eql? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/node.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/node.rb deleted file mode 100644 index 34e71063af..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/node.rb +++ /dev/null @@ -1,61 +0,0 @@ -# frozen_string_literal: true -require 'arel/collectors/sql_string' - -module Arel - module Nodes - ### - # Abstract base class for all AST nodes - class Node - include Arel::FactoryMethods - include Enumerable - - if $DEBUG - def _caller - @caller - end - - def initialize - @caller = caller.dup - end - end - - ### - # Factory method to create a Nodes::Not node that has the recipient of - # the caller as a child. - def not - Nodes::Not.new self - end - - ### - # Factory method to create a Nodes::Grouping node that has an Nodes::Or - # node as a child. - def or right - Nodes::Grouping.new Nodes::Or.new(self, right) - end - - ### - # Factory method to create an Nodes::And node. - def and right - Nodes::And.new [self, right] - end - - # FIXME: this method should go away. I don't like people calling - # to_sql on non-head nodes. This forces us to walk the AST until we - # can find a node that has a "relation" member. - # - # Maybe we should just use `Table.engine`? :'( - def to_sql engine = Table.engine - collector = Arel::Collectors::SQLString.new - collector = engine.connection.visitor.accept self, collector - collector.value - end - - # Iterate through AST, nodes will be yielded depth-first - def each &block - return enum_for(:each) unless block_given? - - ::Arel::Visitors::DepthFirst.new(block).accept self - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/outer_join.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/outer_join.rb deleted file mode 100644 index c568655fe6..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/outer_join.rb +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class OuterJoin < Arel::Nodes::Join - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/over.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/over.rb deleted file mode 100644 index 47a34e69ea..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/over.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - - class Over < Binary - include Arel::AliasPredication - - def initialize(left, right = nil) - super(left, right) - end - - def operator; 'OVER' end - end - - end -end \ No newline at end of file diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/regexp.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/regexp.rb deleted file mode 100644 index 8a76185ef0..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/regexp.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Regexp < Binary - attr_accessor :case_sensitive - - def initialize(left, right, case_sensitive = true) - super(left, right) - @case_sensitive = case_sensitive - end - end - - class NotRegexp < Regexp; end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/right_outer_join.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/right_outer_join.rb deleted file mode 100644 index 04ab31ebf0..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/right_outer_join.rb +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class RightOuterJoin < Arel::Nodes::Join - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/select_core.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/select_core.rb deleted file mode 100644 index 264fa46591..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/select_core.rb +++ /dev/null @@ -1,64 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class SelectCore < Arel::Nodes::Node - attr_accessor :top, :projections, :wheres, :groups, :windows - attr_accessor :havings, :source, :set_quantifier - - def initialize - super() - @source = JoinSource.new nil - @top = nil - - # http://savage.net.au/SQL/sql-92.bnf.html#set%20quantifier - @set_quantifier = nil - @projections = [] - @wheres = [] - @groups = [] - @havings = [] - @windows = [] - end - - def from - @source.left - end - - def from= value - @source.left = value - end - - alias :froms= :from= - alias :froms :from - - def initialize_copy other - super - @source = @source.clone if @source - @projections = @projections.clone - @wheres = @wheres.clone - @groups = @groups.clone - @havings = @havings.clone - @windows = @windows.clone - end - - def hash - [ - @source, @top, @set_quantifier, @projections, - @wheres, @groups, @havings, @windows - ].hash - end - - def eql? other - self.class == other.class && - self.source == other.source && - self.top == other.top && - self.set_quantifier == other.set_quantifier && - self.projections == other.projections && - self.wheres == other.wheres && - self.groups == other.groups && - self.havings == other.havings && - self.windows == other.windows - end - alias :== :eql? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/select_statement.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/select_statement.rb deleted file mode 100644 index 641a08405d..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/select_statement.rb +++ /dev/null @@ -1,40 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class SelectStatement < Arel::Nodes::Node - attr_reader :cores - attr_accessor :limit, :orders, :lock, :offset, :with - - def initialize cores = [SelectCore.new] - super() - @cores = cores - @orders = [] - @limit = nil - @lock = nil - @offset = nil - @with = nil - end - - def initialize_copy other - super - @cores = @cores.map { |x| x.clone } - @orders = @orders.map { |x| x.clone } - end - - def hash - [@cores, @orders, @limit, @lock, @offset, @with].hash - end - - def eql? other - self.class == other.class && - self.cores == other.cores && - self.orders == other.orders && - self.limit == other.limit && - self.lock == other.lock && - self.offset == other.offset && - self.with == other.with - end - alias :== :eql? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/sql_literal.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/sql_literal.rb deleted file mode 100644 index 73575a7d49..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/sql_literal.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class SqlLiteral < String - include Arel::Expressions - include Arel::Predications - include Arel::AliasPredication - include Arel::OrderPredications - - def encode_with(coder) - coder.scalar = self.to_s - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/string_join.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/string_join.rb deleted file mode 100644 index 21d6845c45..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/string_join.rb +++ /dev/null @@ -1,10 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class StringJoin < Arel::Nodes::Join - def initialize left, right = nil - super - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/table_alias.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/table_alias.rb deleted file mode 100644 index 78deb175b6..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/table_alias.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class TableAlias < Arel::Nodes::Binary - alias :name :right - alias :relation :left - alias :table_alias :name - - def [] name - Attribute.new(self, name) - end - - def table_name - relation.respond_to?(:name) ? relation.name : name - end - - def type_cast_for_database(*args) - relation.type_cast_for_database(*args) - end - - def able_to_type_cast? - relation.respond_to?(:able_to_type_cast?) && relation.able_to_type_cast? - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/terminal.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/terminal.rb deleted file mode 100644 index 6f60fe006f..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/terminal.rb +++ /dev/null @@ -1,14 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Distinct < Arel::Nodes::Node - def hash - self.class.hash - end - - def eql? other - self.class == other.class - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/true.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/true.rb deleted file mode 100644 index 796b5b9348..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/true.rb +++ /dev/null @@ -1,14 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class True < Arel::Nodes::Node - def hash - self.class.hash - end - - def eql? other - self.class == other.class - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unary.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unary.rb deleted file mode 100644 index a42744b1d5..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unary.rb +++ /dev/null @@ -1,43 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Unary < Arel::Nodes::Node - attr_accessor :expr - alias :value :expr - - def initialize expr - super() - @expr = expr - end - - def hash - @expr.hash - end - - def eql? other - self.class == other.class && - self.expr == other.expr - end - alias :== :eql? - end - - %w{ - Bin - Cube - DistinctOn - Group - GroupingElement - GroupingSet - Limit - Lock - Not - Offset - On - Ordering - RollUp - Top - }.each do |name| - const_set(name, Class.new(Unary)) - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unary_operation.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unary_operation.rb deleted file mode 100644 index 3c56ef2026..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unary_operation.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - - class UnaryOperation < Unary - include Arel::Expressions - include Arel::Predications - include Arel::OrderPredications - include Arel::AliasPredication - include Arel::Math - - attr_reader :operator - - def initialize operator, operand - super(operand) - @operator = operator - end - end - - class BitwiseNot < UnaryOperation - def initialize operand - super(:~, operand) - end - end - end -end \ No newline at end of file diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unqualified_column.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unqualified_column.rb deleted file mode 100644 index f9017238c8..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/unqualified_column.rb +++ /dev/null @@ -1,21 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class UnqualifiedColumn < Arel::Nodes::Unary - alias :attribute :expr - alias :attribute= :expr= - - def relation - @expr.relation - end - - def column - @expr.column - end - - def name - @expr.name - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/update_statement.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/update_statement.rb deleted file mode 100644 index 286f0bd3ce..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/update_statement.rb +++ /dev/null @@ -1,39 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class UpdateStatement < Arel::Nodes::Node - attr_accessor :relation, :wheres, :values, :orders, :limit - attr_accessor :key - - def initialize - @relation = nil - @wheres = [] - @values = [] - @orders = [] - @limit = nil - @key = nil - end - - def initialize_copy other - super - @wheres = @wheres.clone - @values = @values.clone - end - - def hash - [@relation, @wheres, @values, @orders, @limit, @key].hash - end - - def eql? other - self.class == other.class && - self.relation == other.relation && - self.wheres == other.wheres && - self.values == other.values && - self.orders == other.orders && - self.limit == other.limit && - self.key == other.key - end - alias :== :eql? - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/values.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/values.rb deleted file mode 100644 index b32d5063a2..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/values.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Values < Arel::Nodes::Binary - alias :expressions :left - alias :expressions= :left= - alias :columns :right - alias :columns= :right= - - def initialize exprs, columns = [] - super - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/window.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/window.rb deleted file mode 100644 index 535c0c6238..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/window.rb +++ /dev/null @@ -1,124 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class Window < Arel::Nodes::Node - attr_accessor :orders, :framing, :partitions - - def initialize - @orders = [] - @partitions = [] - @framing = nil - end - - def order *expr - # FIXME: We SHOULD NOT be converting these to SqlLiteral automatically - @orders.concat expr.map { |x| - String === x || Symbol === x ? Nodes::SqlLiteral.new(x.to_s) : x - } - self - end - - def partition *expr - # FIXME: We SHOULD NOT be converting these to SqlLiteral automatically - @partitions.concat expr.map { |x| - String === x || Symbol === x ? Nodes::SqlLiteral.new(x.to_s) : x - } - self - end - - def frame(expr) - @framing = expr - end - - def rows(expr = nil) - if @framing - Rows.new(expr) - else - frame(Rows.new(expr)) - end - end - - def range(expr = nil) - if @framing - Range.new(expr) - else - frame(Range.new(expr)) - end - end - - def initialize_copy other - super - @orders = @orders.map { |x| x.clone } - end - - def hash - [@orders, @framing].hash - end - - def eql? other - self.class == other.class && - self.orders == other.orders && - self.framing == other.framing && - self.partitions == other.partitions - end - alias :== :eql? - end - - class NamedWindow < Window - attr_accessor :name - - def initialize name - super() - @name = name - end - - def initialize_copy other - super - @name = other.name.clone - end - - def hash - super ^ @name.hash - end - - def eql? other - super && self.name == other.name - end - alias :== :eql? - end - - class Rows < Unary - def initialize(expr = nil) - super(expr) - end - end - - class Range < Unary - def initialize(expr = nil) - super(expr) - end - end - - class CurrentRow < Node - def hash - self.class.hash - end - - def eql? other - self.class == other.class - end - end - - class Preceding < Unary - def initialize(expr = nil) - super(expr) - end - end - - class Following < Unary - def initialize(expr = nil) - super(expr) - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/with.rb b/debian/gems-compat/arel-8.0.0/lib/arel/nodes/with.rb deleted file mode 100644 index def7840ea3..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/nodes/with.rb +++ /dev/null @@ -1,11 +0,0 @@ -# frozen_string_literal: true -module Arel - module Nodes - class With < Arel::Nodes::Unary - alias children expr - end - - class WithRecursive < With; end - end -end - diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/order_predications.rb b/debian/gems-compat/arel-8.0.0/lib/arel/order_predications.rb deleted file mode 100644 index d84be82bb6..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/order_predications.rb +++ /dev/null @@ -1,14 +0,0 @@ -# frozen_string_literal: true -module Arel - module OrderPredications - - def asc - Nodes::Ascending.new self - end - - def desc - Nodes::Descending.new self - end - - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/predications.rb b/debian/gems-compat/arel-8.0.0/lib/arel/predications.rb deleted file mode 100644 index 799c7c67b8..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/predications.rb +++ /dev/null @@ -1,240 +0,0 @@ -# frozen_string_literal: true -module Arel - module Predications - def not_eq other - Nodes::NotEqual.new self, quoted_node(other) - end - - def not_eq_any others - grouping_any :not_eq, others - end - - def not_eq_all others - grouping_all :not_eq, others - end - - def eq other - Nodes::Equality.new self, quoted_node(other) - end - - def eq_any others - grouping_any :eq, others - end - - def eq_all others - grouping_all :eq, quoted_array(others) - end - - def between other - if equals_quoted?(other.begin, -Float::INFINITY) - if equals_quoted?(other.end, Float::INFINITY) - not_in([]) - elsif other.exclude_end? - lt(other.end) - else - lteq(other.end) - end - elsif equals_quoted?(other.end, Float::INFINITY) - gteq(other.begin) - elsif other.exclude_end? - gteq(other.begin).and(lt(other.end)) - else - left = quoted_node(other.begin) - right = quoted_node(other.end) - Nodes::Between.new(self, left.and(right)) - end - end - - def in other - case other - when Arel::SelectManager - Arel::Nodes::In.new(self, other.ast) - when Range - if $VERBOSE - warn <<-eowarn -Passing a range to `#in` is deprecated. Call `#between`, instead. - eowarn - end - between(other) - when Enumerable - Nodes::In.new self, quoted_array(other) - else - Nodes::In.new self, quoted_node(other) - end - end - - def in_any others - grouping_any :in, others - end - - def in_all others - grouping_all :in, others - end - - def not_between other - if equals_quoted?(other.begin, -Float::INFINITY) - if equals_quoted?(other.end, Float::INFINITY) - self.in([]) - elsif other.exclude_end? - gteq(other.end) - else - gt(other.end) - end - elsif equals_quoted?(other.end, Float::INFINITY) - lt(other.begin) - else - left = lt(other.begin) - right = if other.exclude_end? - gteq(other.end) - else - gt(other.end) - end - left.or(right) - end - end - - def not_in other - case other - when Arel::SelectManager - Arel::Nodes::NotIn.new(self, other.ast) - when Range - if $VERBOSE - warn <<-eowarn -Passing a range to `#not_in` is deprecated. Call `#not_between`, instead. - eowarn - end - not_between(other) - when Enumerable - Nodes::NotIn.new self, quoted_array(other) - else - Nodes::NotIn.new self, quoted_node(other) - end - end - - def not_in_any others - grouping_any :not_in, others - end - - def not_in_all others - grouping_all :not_in, others - end - - def matches other, escape = nil, case_sensitive = false - Nodes::Matches.new self, quoted_node(other), escape, case_sensitive - end - - def matches_regexp other, case_sensitive = true - Nodes::Regexp.new self, quoted_node(other), case_sensitive - end - - def matches_any others, escape = nil, case_sensitive = false - grouping_any :matches, others, escape, case_sensitive - end - - def matches_all others, escape = nil, case_sensitive = false - grouping_all :matches, others, escape, case_sensitive - end - - def does_not_match other, escape = nil, case_sensitive = false - Nodes::DoesNotMatch.new self, quoted_node(other), escape, case_sensitive - end - - def does_not_match_regexp other, case_sensitive = true - Nodes::NotRegexp.new self, quoted_node(other), case_sensitive - end - - def does_not_match_any others, escape = nil - grouping_any :does_not_match, others, escape - end - - def does_not_match_all others, escape = nil - grouping_all :does_not_match, others, escape - end - - def gteq right - Nodes::GreaterThanOrEqual.new self, quoted_node(right) - end - - def gteq_any others - grouping_any :gteq, others - end - - def gteq_all others - grouping_all :gteq, others - end - - def gt right - Nodes::GreaterThan.new self, quoted_node(right) - end - - def gt_any others - grouping_any :gt, others - end - - def gt_all others - grouping_all :gt, others - end - - def lt right - Nodes::LessThan.new self, quoted_node(right) - end - - def lt_any others - grouping_any :lt, others - end - - def lt_all others - grouping_all :lt, others - end - - def lteq right - Nodes::LessThanOrEqual.new self, quoted_node(right) - end - - def lteq_any others - grouping_any :lteq, others - end - - def lteq_all others - grouping_all :lteq, others - end - - def when right - Nodes::Case.new(self).when quoted_node(right) - end - - def concat other - Nodes::Concat.new self, other - end - - private - - def grouping_any method_id, others, *extras - nodes = others.map {|expr| send(method_id, expr, *extras)} - Nodes::Grouping.new nodes.inject { |memo,node| - Nodes::Or.new(memo, node) - } - end - - def grouping_all method_id, others, *extras - nodes = others.map {|expr| send(method_id, expr, *extras)} - Nodes::Grouping.new Nodes::And.new(nodes) - end - - def quoted_node(other) - Nodes.build_quoted(other, self) - end - - def quoted_array(others) - others.map { |v| quoted_node(v) } - end - - def equals_quoted?(maybe_quoted, value) - if maybe_quoted.is_a?(Nodes::Quoted) - maybe_quoted.val == value - else - maybe_quoted == value - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/select_manager.rb b/debian/gems-compat/arel-8.0.0/lib/arel/select_manager.rb deleted file mode 100644 index 0b35176842..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/select_manager.rb +++ /dev/null @@ -1,269 +0,0 @@ -# frozen_string_literal: true -require 'arel/collectors/sql_string' - -module Arel - class SelectManager < Arel::TreeManager - include Arel::Crud - - STRING_OR_SYMBOL_CLASS = [Symbol, String] - - def initialize table = nil - super() - @ast = Nodes::SelectStatement.new - @ctx = @ast.cores.last - from table - end - - def initialize_copy other - super - @ctx = @ast.cores.last - end - - def limit - @ast.limit && @ast.limit.expr - end - alias :taken :limit - - def constraints - @ctx.wheres - end - - def offset - @ast.offset && @ast.offset.expr - end - - def skip amount - if amount - @ast.offset = Nodes::Offset.new(amount) - else - @ast.offset = nil - end - self - end - alias :offset= :skip - - ### - # Produces an Arel::Nodes::Exists node - def exists - Arel::Nodes::Exists.new @ast - end - - def as other - create_table_alias grouping(@ast), Nodes::SqlLiteral.new(other) - end - - def lock locking = Arel.sql('FOR UPDATE') - case locking - when true - locking = Arel.sql('FOR UPDATE') - when Arel::Nodes::SqlLiteral - when String - locking = Arel.sql locking - end - - @ast.lock = Nodes::Lock.new(locking) - self - end - - def locked - @ast.lock - end - - def on *exprs - @ctx.source.right.last.right = Nodes::On.new(collapse(exprs)) - self - end - - def group *columns - columns.each do |column| - # FIXME: backwards compat - column = Nodes::SqlLiteral.new(column) if String === column - column = Nodes::SqlLiteral.new(column.to_s) if Symbol === column - - @ctx.groups.push Nodes::Group.new column - end - self - end - - def from table - table = Nodes::SqlLiteral.new(table) if String === table - - case table - when Nodes::Join - @ctx.source.right << table - else - @ctx.source.left = table - end - - self - end - - def froms - @ast.cores.map { |x| x.from }.compact - end - - def join relation, klass = Nodes::InnerJoin - return self unless relation - - case relation - when String, Nodes::SqlLiteral - raise EmptyJoinError if relation.empty? - klass = Nodes::StringJoin - end - - @ctx.source.right << create_join(relation, nil, klass) - self - end - - def outer_join relation - join(relation, Nodes::OuterJoin) - end - - def having expr - @ctx.havings << expr - self - end - - def window name - window = Nodes::NamedWindow.new(name) - @ctx.windows.push window - window - end - - def project *projections - # FIXME: converting these to SQLLiterals is probably not good, but - # rails tests require it. - @ctx.projections.concat projections.map { |x| - STRING_OR_SYMBOL_CLASS.include?(x.class) ? Nodes::SqlLiteral.new(x.to_s) : x - } - self - end - - def projections - @ctx.projections - end - - def projections= projections - @ctx.projections = projections - end - - def distinct(value = true) - if value - @ctx.set_quantifier = Arel::Nodes::Distinct.new - else - @ctx.set_quantifier = nil - end - self - end - - def distinct_on(value) - if value - @ctx.set_quantifier = Arel::Nodes::DistinctOn.new(value) - else - @ctx.set_quantifier = nil - end - self - end - - def order *expr - # FIXME: We SHOULD NOT be converting these to SqlLiteral automatically - @ast.orders.concat expr.map { |x| - STRING_OR_SYMBOL_CLASS.include?(x.class) ? Nodes::SqlLiteral.new(x.to_s) : x - } - self - end - - def orders - @ast.orders - end - - def where_sql engine = Table.engine - return if @ctx.wheres.empty? - - viz = Visitors::WhereSql.new(engine.connection.visitor, engine.connection) - Nodes::SqlLiteral.new viz.accept(@ctx, Collectors::SQLString.new).value - end - - def union operation, other = nil - if other - node_class = Nodes.const_get("Union#{operation.to_s.capitalize}") - else - other = operation - node_class = Nodes::Union - end - - node_class.new self.ast, other.ast - end - - def intersect other - Nodes::Intersect.new ast, other.ast - end - - def except other - Nodes::Except.new ast, other.ast - end - alias :minus :except - - def with *subqueries - if subqueries.first.is_a? Symbol - node_class = Nodes.const_get("With#{subqueries.shift.to_s.capitalize}") - else - node_class = Nodes::With - end - @ast.with = node_class.new(subqueries.flatten) - - self - end - - def take limit - if limit - @ast.limit = Nodes::Limit.new(limit) - @ctx.top = Nodes::Top.new(limit) - else - @ast.limit = nil - @ctx.top = nil - end - self - end - alias limit= take - - def join_sources - @ctx.source.right - end - - def source - @ctx.source - end - - class Row < Struct.new(:data) # :nodoc: - def id - data['id'] - end - - def method_missing(name, *args) - name = name.to_s - return data[name] if data.key?(name) - super - end - end - - private - def collapse exprs, existing = nil - exprs = exprs.unshift(existing.expr) if existing - exprs = exprs.compact.map { |expr| - if String === expr - # FIXME: Don't do this automatically - Arel.sql(expr) - else - expr - end - } - - if exprs.length == 1 - exprs.first - else - create_and exprs - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/table.rb b/debian/gems-compat/arel-8.0.0/lib/arel/table.rb deleted file mode 100644 index b3f2d79e5f..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/table.rb +++ /dev/null @@ -1,110 +0,0 @@ -# frozen_string_literal: true -module Arel - class Table - include Arel::Crud - include Arel::FactoryMethods - - @engine = nil - class << self; attr_accessor :engine; end - - attr_accessor :name, :table_alias - - # TableAlias and Table both have a #table_name which is the name of the underlying table - alias :table_name :name - - def initialize(name, as: nil, type_caster: nil) - @name = name.to_s - @type_caster = type_caster - - # Sometime AR sends an :as parameter to table, to let the table know - # that it is an Alias. We may want to override new, and return a - # TableAlias node? - if as.to_s == @name - as = nil - end - @table_alias = as - end - - def alias name = "#{self.name}_2" - Nodes::TableAlias.new(self, name) - end - - def from - SelectManager.new(self) - end - - def join relation, klass = Nodes::InnerJoin - return from unless relation - - case relation - when String, Nodes::SqlLiteral - raise EmptyJoinError if relation.empty? - klass = Nodes::StringJoin - end - - from.join(relation, klass) - end - - def outer_join relation - join(relation, Nodes::OuterJoin) - end - - def group *columns - from.group(*columns) - end - - def order *expr - from.order(*expr) - end - - def where condition - from.where condition - end - - def project *things - from.project(*things) - end - - def take amount - from.take amount - end - - def skip amount - from.skip amount - end - - def having expr - from.having expr - end - - def [] name - ::Arel::Attribute.new self, name - end - - def hash - # Perf note: aliases and table alias is excluded from the hash - # aliases can have a loop back to this table breaking hashes in parent - # relations, for the vast majority of cases @name is unique to a query - @name.hash - end - - def eql? other - self.class == other.class && - self.name == other.name && - self.table_alias == other.table_alias - end - alias :== :eql? - - def type_cast_for_database(attribute_name, value) - type_caster.type_cast_for_database(attribute_name, value) - end - - def able_to_type_cast? - !type_caster.nil? - end - - protected - - attr_reader :type_caster - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/tree_manager.rb b/debian/gems-compat/arel-8.0.0/lib/arel/tree_manager.rb deleted file mode 100644 index cc3f1eeee4..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/tree_manager.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true -require 'arel/collectors/sql_string' - -module Arel - class TreeManager - include Arel::FactoryMethods - - attr_reader :ast, :engine - - attr_accessor :bind_values - - def initialize - @ctx = nil - @bind_values = [] - end - - def to_dot - collector = Arel::Collectors::PlainString.new - collector = Visitors::Dot.new.accept @ast, collector - collector.value - end - - def to_sql engine = Table.engine - collector = Arel::Collectors::SQLString.new - collector = engine.connection.visitor.accept @ast, collector - collector.value - end - - def initialize_copy other - super - @ast = @ast.clone - end - - def where expr - if Arel::TreeManager === expr - expr = expr.ast - end - @ctx.wheres << expr - self - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/update_manager.rb b/debian/gems-compat/arel-8.0.0/lib/arel/update_manager.rb deleted file mode 100644 index eac414eafb..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/update_manager.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true -module Arel - class UpdateManager < Arel::TreeManager - def initialize - super - @ast = Nodes::UpdateStatement.new - @ctx = @ast - end - - def take limit - @ast.limit = Nodes::Limit.new(Nodes.build_quoted(limit)) if limit - self - end - - def key= key - @ast.key = Nodes.build_quoted(key) - end - - def key - @ast.key - end - - def order *expr - @ast.orders = expr - self - end - - ### - # UPDATE +table+ - def table table - @ast.relation = table - self - end - - def wheres= exprs - @ast.wheres = exprs - end - - def where expr - @ast.wheres << expr - self - end - - def set values - if String === values - @ast.values = [values] - else - @ast.values = values.map { |column,value| - Nodes::Assignment.new( - Nodes::UnqualifiedColumn.new(column), - value - ) - } - end - self - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors.rb deleted file mode 100644 index a3404cf992..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors.rb +++ /dev/null @@ -1,19 +0,0 @@ -# frozen_string_literal: true -require 'arel/visitors/visitor' -require 'arel/visitors/depth_first' -require 'arel/visitors/to_sql' -require 'arel/visitors/sqlite' -require 'arel/visitors/postgresql' -require 'arel/visitors/mysql' -require 'arel/visitors/mssql' -require 'arel/visitors/oracle' -require 'arel/visitors/oracle12' -require 'arel/visitors/where_sql' -require 'arel/visitors/dot' -require 'arel/visitors/ibm_db' -require 'arel/visitors/informix' - -module Arel - module Visitors - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/bind_substitute.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/bind_substitute.rb deleted file mode 100644 index 52c96b0d72..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/bind_substitute.rb +++ /dev/null @@ -1,10 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class BindSubstitute - def initialize delegate - @delegate = delegate - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/bind_visitor.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/bind_visitor.rb deleted file mode 100644 index 8a5570cf5c..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/bind_visitor.rb +++ /dev/null @@ -1,40 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - module BindVisitor - def initialize target - @block = nil - super - end - - def accept node, collector, &block - @block = block if block_given? - super - end - - private - - def visit_Arel_Nodes_Assignment o, collector - if o.right.is_a? Arel::Nodes::BindParam - collector = visit o.left, collector - collector << " = " - visit o.right, collector - else - super - end - end - - def visit_Arel_Nodes_BindParam o, collector - if @block - val = @block.call - if String === val - collector << val - end - else - super - end - end - - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/depth_first.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/depth_first.rb deleted file mode 100644 index 5416a285f5..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/depth_first.rb +++ /dev/null @@ -1,198 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class DepthFirst < Arel::Visitors::Visitor - def initialize block = nil - @block = block || Proc.new - super() - end - - private - - def visit o - super - @block.call o - end - - def unary o - visit o.expr - end - alias :visit_Arel_Nodes_Else :unary - alias :visit_Arel_Nodes_Group :unary - alias :visit_Arel_Nodes_Cube :unary - alias :visit_Arel_Nodes_RollUp :unary - alias :visit_Arel_Nodes_GroupingSet :unary - alias :visit_Arel_Nodes_GroupingElement :unary - alias :visit_Arel_Nodes_Grouping :unary - alias :visit_Arel_Nodes_Having :unary - alias :visit_Arel_Nodes_Limit :unary - alias :visit_Arel_Nodes_Not :unary - alias :visit_Arel_Nodes_Offset :unary - alias :visit_Arel_Nodes_On :unary - alias :visit_Arel_Nodes_Ordering :unary - alias :visit_Arel_Nodes_Ascending :unary - alias :visit_Arel_Nodes_Descending :unary - alias :visit_Arel_Nodes_Top :unary - alias :visit_Arel_Nodes_UnqualifiedColumn :unary - - def function o - visit o.expressions - visit o.alias - visit o.distinct - end - alias :visit_Arel_Nodes_Avg :function - alias :visit_Arel_Nodes_Exists :function - alias :visit_Arel_Nodes_Max :function - alias :visit_Arel_Nodes_Min :function - alias :visit_Arel_Nodes_Sum :function - - def visit_Arel_Nodes_NamedFunction o - visit o.name - visit o.expressions - visit o.distinct - visit o.alias - end - - def visit_Arel_Nodes_Count o - visit o.expressions - visit o.alias - visit o.distinct - end - - def visit_Arel_Nodes_Case o - visit o.case - visit o.conditions - visit o.default - end - - def nary o - o.children.each { |child| visit child} - end - alias :visit_Arel_Nodes_And :nary - - def binary o - visit o.left - visit o.right - end - alias :visit_Arel_Nodes_As :binary - alias :visit_Arel_Nodes_Assignment :binary - alias :visit_Arel_Nodes_Between :binary - alias :visit_Arel_Nodes_Concat :binary - alias :visit_Arel_Nodes_DeleteStatement :binary - alias :visit_Arel_Nodes_DoesNotMatch :binary - alias :visit_Arel_Nodes_Equality :binary - alias :visit_Arel_Nodes_FullOuterJoin :binary - alias :visit_Arel_Nodes_GreaterThan :binary - alias :visit_Arel_Nodes_GreaterThanOrEqual :binary - alias :visit_Arel_Nodes_In :binary - alias :visit_Arel_Nodes_InfixOperation :binary - alias :visit_Arel_Nodes_JoinSource :binary - alias :visit_Arel_Nodes_InnerJoin :binary - alias :visit_Arel_Nodes_LessThan :binary - alias :visit_Arel_Nodes_LessThanOrEqual :binary - alias :visit_Arel_Nodes_Matches :binary - alias :visit_Arel_Nodes_NotEqual :binary - alias :visit_Arel_Nodes_NotIn :binary - alias :visit_Arel_Nodes_NotRegexp :binary - alias :visit_Arel_Nodes_Or :binary - alias :visit_Arel_Nodes_OuterJoin :binary - alias :visit_Arel_Nodes_Regexp :binary - alias :visit_Arel_Nodes_RightOuterJoin :binary - alias :visit_Arel_Nodes_TableAlias :binary - alias :visit_Arel_Nodes_Values :binary - alias :visit_Arel_Nodes_When :binary - - def visit_Arel_Nodes_StringJoin o - visit o.left - end - - def visit_Arel_Attribute o - visit o.relation - visit o.name - end - alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute - alias :visit_Arel_Attributes_Float :visit_Arel_Attribute - alias :visit_Arel_Attributes_String :visit_Arel_Attribute - alias :visit_Arel_Attributes_Time :visit_Arel_Attribute - alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute - alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute - alias :visit_Arel_Attributes_Decimal :visit_Arel_Attribute - - def visit_Arel_Table o - visit o.name - end - - def terminal o - end - alias :visit_ActiveSupport_Multibyte_Chars :terminal - alias :visit_ActiveSupport_StringInquirer :terminal - alias :visit_Arel_Nodes_Lock :terminal - alias :visit_Arel_Nodes_Node :terminal - alias :visit_Arel_Nodes_SqlLiteral :terminal - alias :visit_Arel_Nodes_BindParam :terminal - alias :visit_Arel_Nodes_Window :terminal - alias :visit_Arel_Nodes_True :terminal - alias :visit_Arel_Nodes_False :terminal - alias :visit_BigDecimal :terminal - alias :visit_Bignum :terminal - alias :visit_Class :terminal - alias :visit_Date :terminal - alias :visit_DateTime :terminal - alias :visit_FalseClass :terminal - alias :visit_Fixnum :terminal - alias :visit_Float :terminal - alias :visit_Integer :terminal - alias :visit_NilClass :terminal - alias :visit_String :terminal - alias :visit_Symbol :terminal - alias :visit_Time :terminal - alias :visit_TrueClass :terminal - - def visit_Arel_Nodes_InsertStatement o - visit o.relation - visit o.columns - visit o.values - end - - def visit_Arel_Nodes_SelectCore o - visit o.projections - visit o.source - visit o.wheres - visit o.groups - visit o.windows - visit o.havings - end - - def visit_Arel_Nodes_SelectStatement o - visit o.cores - visit o.orders - visit o.limit - visit o.lock - visit o.offset - end - - def visit_Arel_Nodes_UpdateStatement o - visit o.relation - visit o.values - visit o.wheres - visit o.orders - visit o.limit - end - - def visit_Array o - o.each { |i| visit i } - end - alias :visit_Set :visit_Array - - def visit_Hash o - o.each { |k,v| visit(k); visit(v) } - end - - DISPATCH = dispatch_cache - - def get_dispatch_cache - DISPATCH - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/dot.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/dot.rb deleted file mode 100644 index 9aa22d33f6..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/dot.rb +++ /dev/null @@ -1,291 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class Dot < Arel::Visitors::Visitor - class Node # :nodoc: - attr_accessor :name, :id, :fields - - def initialize name, id, fields = [] - @name = name - @id = id - @fields = fields - end - end - - class Edge < Struct.new :name, :from, :to # :nodoc: - end - - def initialize - super() - @nodes = [] - @edges = [] - @node_stack = [] - @edge_stack = [] - @seen = {} - end - - def accept object, collector - visit object - collector << to_dot - end - - private - - def visit_Arel_Nodes_Ordering o - visit_edge o, "expr" - end - - def visit_Arel_Nodes_TableAlias o - visit_edge o, "name" - visit_edge o, "relation" - end - - def visit_Arel_Nodes_Count o - visit_edge o, "expressions" - visit_edge o, "distinct" - end - - def visit_Arel_Nodes_Values o - visit_edge o, "expressions" - end - - def visit_Arel_Nodes_StringJoin o - visit_edge o, "left" - end - - def visit_Arel_Nodes_InnerJoin o - visit_edge o, "left" - visit_edge o, "right" - end - alias :visit_Arel_Nodes_FullOuterJoin :visit_Arel_Nodes_InnerJoin - alias :visit_Arel_Nodes_OuterJoin :visit_Arel_Nodes_InnerJoin - alias :visit_Arel_Nodes_RightOuterJoin :visit_Arel_Nodes_InnerJoin - - def visit_Arel_Nodes_DeleteStatement o - visit_edge o, "relation" - visit_edge o, "wheres" - end - - def unary o - visit_edge o, "expr" - end - alias :visit_Arel_Nodes_Group :unary - alias :visit_Arel_Nodes_Cube :unary - alias :visit_Arel_Nodes_RollUp :unary - alias :visit_Arel_Nodes_GroupingSet :unary - alias :visit_Arel_Nodes_GroupingElement :unary - alias :visit_Arel_Nodes_Grouping :unary - alias :visit_Arel_Nodes_Having :unary - alias :visit_Arel_Nodes_Limit :unary - alias :visit_Arel_Nodes_Not :unary - alias :visit_Arel_Nodes_Offset :unary - alias :visit_Arel_Nodes_On :unary - alias :visit_Arel_Nodes_Top :unary - alias :visit_Arel_Nodes_UnqualifiedColumn :unary - alias :visit_Arel_Nodes_Preceding :unary - alias :visit_Arel_Nodes_Following :unary - alias :visit_Arel_Nodes_Rows :unary - alias :visit_Arel_Nodes_Range :unary - - def window o - visit_edge o, "partitions" - visit_edge o, "orders" - visit_edge o, "framing" - end - alias :visit_Arel_Nodes_Window :window - - def named_window o - visit_edge o, "partitions" - visit_edge o, "orders" - visit_edge o, "framing" - visit_edge o, "name" - end - alias :visit_Arel_Nodes_NamedWindow :named_window - - def function o - visit_edge o, "expressions" - visit_edge o, "distinct" - visit_edge o, "alias" - end - alias :visit_Arel_Nodes_Exists :function - alias :visit_Arel_Nodes_Min :function - alias :visit_Arel_Nodes_Max :function - alias :visit_Arel_Nodes_Avg :function - alias :visit_Arel_Nodes_Sum :function - - def extract o - visit_edge o, "expressions" - visit_edge o, "alias" - end - alias :visit_Arel_Nodes_Extract :extract - - def visit_Arel_Nodes_NamedFunction o - visit_edge o, "name" - visit_edge o, "expressions" - visit_edge o, "distinct" - visit_edge o, "alias" - end - - def visit_Arel_Nodes_InsertStatement o - visit_edge o, "relation" - visit_edge o, "columns" - visit_edge o, "values" - end - - def visit_Arel_Nodes_SelectCore o - visit_edge o, "source" - visit_edge o, "projections" - visit_edge o, "wheres" - visit_edge o, "windows" - end - - def visit_Arel_Nodes_SelectStatement o - visit_edge o, "cores" - visit_edge o, "limit" - visit_edge o, "orders" - visit_edge o, "offset" - end - - def visit_Arel_Nodes_UpdateStatement o - visit_edge o, "relation" - visit_edge o, "wheres" - visit_edge o, "values" - end - - def visit_Arel_Table o - visit_edge o, "name" - end - - def visit_Arel_Nodes_Casted o - visit_edge o, 'val' - visit_edge o, 'attribute' - end - - def visit_Arel_Attribute o - visit_edge o, "relation" - visit_edge o, "name" - end - alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute - alias :visit_Arel_Attributes_Float :visit_Arel_Attribute - alias :visit_Arel_Attributes_String :visit_Arel_Attribute - alias :visit_Arel_Attributes_Time :visit_Arel_Attribute - alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute - alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute - - def nary o - o.children.each_with_index do |x,i| - edge(i) { visit x } - end - end - alias :visit_Arel_Nodes_And :nary - - def binary o - visit_edge o, "left" - visit_edge o, "right" - end - alias :visit_Arel_Nodes_As :binary - alias :visit_Arel_Nodes_Assignment :binary - alias :visit_Arel_Nodes_Between :binary - alias :visit_Arel_Nodes_Concat :binary - alias :visit_Arel_Nodes_DoesNotMatch :binary - alias :visit_Arel_Nodes_Equality :binary - alias :visit_Arel_Nodes_GreaterThan :binary - alias :visit_Arel_Nodes_GreaterThanOrEqual :binary - alias :visit_Arel_Nodes_In :binary - alias :visit_Arel_Nodes_JoinSource :binary - alias :visit_Arel_Nodes_LessThan :binary - alias :visit_Arel_Nodes_LessThanOrEqual :binary - alias :visit_Arel_Nodes_Matches :binary - alias :visit_Arel_Nodes_NotEqual :binary - alias :visit_Arel_Nodes_NotIn :binary - alias :visit_Arel_Nodes_Or :binary - alias :visit_Arel_Nodes_Over :binary - - def visit_String o - @node_stack.last.fields << o - end - alias :visit_Time :visit_String - alias :visit_Date :visit_String - alias :visit_DateTime :visit_String - alias :visit_NilClass :visit_String - alias :visit_TrueClass :visit_String - alias :visit_FalseClass :visit_String - alias :visit_Integer :visit_String - alias :visit_Fixnum :visit_String - alias :visit_BigDecimal :visit_String - alias :visit_Float :visit_String - alias :visit_Symbol :visit_String - alias :visit_Arel_Nodes_SqlLiteral :visit_String - - def visit_Arel_Nodes_BindParam o; end - - def visit_Hash o - o.each_with_index do |pair, i| - edge("pair_#{i}") { visit pair } - end - end - - def visit_Array o - o.each_with_index do |x,i| - edge(i) { visit x } - end - end - alias :visit_Set :visit_Array - - def visit_edge o, method - edge(method) { visit o.send(method) } - end - - def visit o - if node = @seen[o.object_id] - @edge_stack.last.to = node - return - end - - node = Node.new(o.class.name, o.object_id) - @seen[node.id] = node - @nodes << node - with_node node do - super - end - end - - def edge name - edge = Edge.new(name, @node_stack.last) - @edge_stack.push edge - @edges << edge - yield - @edge_stack.pop - end - - def with_node node - if edge = @edge_stack.last - edge.to = node - end - - @node_stack.push node - yield - @node_stack.pop - end - - def quote string - string.to_s.gsub('"', '\"') - end - - def to_dot - "digraph \"Arel\" {\nnode [width=0.375,height=0.25,shape=record];\n" + - @nodes.map { |node| - label = "#{node.name}" - - node.fields.each_with_index do |field, i| - label += "|#{quote field}" - end - - "#{node.id} [label=\"#{label}\"];" - }.join("\n") + "\n" + @edges.map { |edge| - "#{edge.from.id} -> #{edge.to.id} [label=\"#{edge.name}\"];" - }.join("\n") + "\n}" - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/ibm_db.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/ibm_db.rb deleted file mode 100644 index e85a5a08a7..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/ibm_db.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class IBM_DB < Arel::Visitors::ToSql - private - - def visit_Arel_Nodes_Limit o, collector - collector << "FETCH FIRST " - collector = visit o.expr, collector - collector << " ROWS ONLY" - end - - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/informix.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/informix.rb deleted file mode 100644 index b53ab18b82..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/informix.rb +++ /dev/null @@ -1,57 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class Informix < Arel::Visitors::ToSql - private - def visit_Arel_Nodes_SelectStatement o, collector - collector << "SELECT " - collector = maybe_visit o.offset, collector - collector = maybe_visit o.limit, collector - collector = o.cores.inject(collector) { |c,x| - visit_Arel_Nodes_SelectCore x, c - } - if o.orders.any? - collector << "ORDER BY " - collector = inject_join o.orders, collector, ", " - end - collector = maybe_visit o.lock, collector - end - def visit_Arel_Nodes_SelectCore o, collector - collector = inject_join o.projections, collector, ", " - froms = false - if o.source && !o.source.empty? - froms = true - collector << " FROM " - collector = visit o.source, collector - end - - if o.wheres.any? - collector << " WHERE " - collector = inject_join o.wheres, collector, " AND " - end - - if o.groups.any? - collector << "GROUP BY " - collector = inject_join o.groups, collector, ", " - end - - if o.havings.any? - collector << " HAVING " - collector = inject_join o.havings, collector, " AND " - end - collector - end - - def visit_Arel_Nodes_Offset o, collector - collector << "SKIP " - visit o.expr, collector - end - def visit_Arel_Nodes_Limit o, collector - collector << "FIRST " - visit o.expr, collector - collector << " " - end - end - end -end - diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/mssql.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/mssql.rb deleted file mode 100644 index 8347d05d06..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/mssql.rb +++ /dev/null @@ -1,124 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class MSSQL < Arel::Visitors::ToSql - RowNumber = Struct.new :children - - def initialize(*) - @primary_keys = {} - super - end - - private - - # `top` wouldn't really work here. I.e. User.select("distinct first_name").limit(10) would generate - # "select top 10 distinct first_name from users", which is invalid query! it should be - # "select distinct top 10 first_name from users" - def visit_Arel_Nodes_Top o - "" - end - - def visit_Arel_Visitors_MSSQL_RowNumber o, collector - collector << "ROW_NUMBER() OVER (ORDER BY " - inject_join(o.children, collector, ', ') << ") as _row_num" - end - - def visit_Arel_Nodes_SelectStatement o, collector - if !o.limit && !o.offset - return super - end - - is_select_count = false - o.cores.each { |x| - core_order_by = row_num_literal determine_order_by(o.orders, x) - if select_count? x - x.projections = [core_order_by] - is_select_count = true - else - x.projections << core_order_by - end - } - - if is_select_count - # fixme count distinct wouldn't work with limit or offset - collector << "SELECT COUNT(1) as count_id FROM (" - end - - collector << "SELECT _t.* FROM (" - collector = o.cores.inject(collector) { |c,x| - visit_Arel_Nodes_SelectCore x, c - } - collector << ") as _t WHERE #{get_offset_limit_clause(o)}" - - if is_select_count - collector << ") AS subquery" - else - collector - end - end - - def get_offset_limit_clause o - first_row = o.offset ? o.offset.expr.to_i + 1 : 1 - last_row = o.limit ? o.limit.expr.to_i - 1 + first_row : nil - if last_row - " _row_num BETWEEN #{first_row} AND #{last_row}" - else - " _row_num >= #{first_row}" - end - end - - def visit_Arel_Nodes_DeleteStatement o, collector - collector << 'DELETE ' - if o.limit - collector << 'TOP (' - visit o.limit.expr, collector - collector << ') ' - end - collector << 'FROM ' - collector = visit o.relation, collector - if o.wheres.any? - collector << ' WHERE ' - inject_join o.wheres, collector, AND - else - collector - end - end - - def determine_order_by orders, x - if orders.any? - orders - elsif x.groups.any? - x.groups - else - pk = find_left_table_pk(x.froms) - pk ? [pk] : [] - end - end - - def row_num_literal order_by - RowNumber.new order_by - end - - def select_count? x - x.projections.length == 1 && Arel::Nodes::Count === x.projections.first - end - - # FIXME raise exception of there is no pk? - def find_left_table_pk o - if o.kind_of?(Arel::Nodes::Join) - find_left_table_pk(o.left) - elsif o.instance_of?(Arel::Table) - find_primary_key(o) - end - end - - def find_primary_key(o) - @primary_keys[o.name] ||= begin - primary_key_name = @connection.primary_key(o.name) - # some tables might be without primary key - primary_key_name && o[primary_key_name] - end - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/mysql.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/mysql.rb deleted file mode 100644 index 4c734f6292..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/mysql.rb +++ /dev/null @@ -1,86 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class MySQL < Arel::Visitors::ToSql - private - def visit_Arel_Nodes_Union o, collector, suppress_parens = false - unless suppress_parens - collector << "( " - end - - collector = case o.left - when Arel::Nodes::Union - visit_Arel_Nodes_Union o.left, collector, true - else - visit o.left, collector - end - - collector << " UNION " - - collector = case o.right - when Arel::Nodes::Union - visit_Arel_Nodes_Union o.right, collector, true - else - visit o.right, collector - end - - if suppress_parens - collector - else - collector << " )" - end - end - - def visit_Arel_Nodes_Bin o, collector - collector << "BINARY " - visit o.expr, collector - end - - ### - # :'( - # http://dev.mysql.com/doc/refman/5.0/en/select.html#id3482214 - def visit_Arel_Nodes_SelectStatement o, collector - if o.offset && !o.limit - o.limit = Arel::Nodes::Limit.new(18446744073709551615) - end - super - end - - def visit_Arel_Nodes_SelectCore o, collector - o.froms ||= Arel.sql('DUAL') - super - end - - def visit_Arel_Nodes_UpdateStatement o, collector - collector << "UPDATE " - collector = visit o.relation, collector - - unless o.values.empty? - collector << " SET " - collector = inject_join o.values, collector, ', ' - end - - unless o.wheres.empty? - collector << " WHERE " - collector = inject_join o.wheres, collector, ' AND ' - end - - unless o.orders.empty? - collector << " ORDER BY " - collector = inject_join o.orders, collector, ', ' - end - - maybe_visit o.limit, collector - end - - def visit_Arel_Nodes_Concat o, collector - collector << " CONCAT(" - visit o.left, collector - collector << ", " - visit o.right, collector - collector << ") " - collector - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/oracle.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/oracle.rb deleted file mode 100644 index 3b452836db..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/oracle.rb +++ /dev/null @@ -1,153 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class Oracle < Arel::Visitors::ToSql - private - - def visit_Arel_Nodes_SelectStatement o, collector - o = order_hacks(o) - - # if need to select first records without ORDER BY and GROUP BY and without DISTINCT - # then can use simple ROWNUM in WHERE clause - if o.limit && o.orders.empty? && o.cores.first.groups.empty? && !o.offset && o.cores.first.set_quantifier.class.to_s !~ /Distinct/ - o.cores.last.wheres.push Nodes::LessThanOrEqual.new( - Nodes::SqlLiteral.new('ROWNUM'), o.limit.expr - ) - return super - end - - if o.limit && o.offset - o = o.dup - limit = o.limit.expr - offset = o.offset - o.offset = nil - collector << " - SELECT * FROM ( - SELECT raw_sql_.*, rownum raw_rnum_ - FROM (" - - collector = super(o, collector) - - if offset.expr.is_a? Nodes::BindParam - offset_bind = nil - collector << ') raw_sql_ WHERE rownum <= (' - collector.add_bind(offset.expr) { |i| offset_bind = ":a#{i}" } - collector << ' + ' - collector.add_bind(limit) { |i| ":a#{i}" } - collector << ") ) WHERE raw_rnum_ > #{offset_bind}" - return collector - else - collector << ") raw_sql_ - WHERE rownum <= #{offset.expr.to_i + limit} - ) - WHERE " - return visit(offset, collector) - end - end - - if o.limit - o = o.dup - limit = o.limit.expr - collector << "SELECT * FROM (" - collector = super(o, collector) - collector << ") WHERE ROWNUM <= " - return visit limit, collector - end - - if o.offset - o = o.dup - offset = o.offset - o.offset = nil - collector << "SELECT * FROM ( - SELECT raw_sql_.*, rownum raw_rnum_ - FROM (" - collector = super(o, collector) - collector << ") raw_sql_ - ) - WHERE " - return visit offset, collector - end - - super - end - - def visit_Arel_Nodes_Limit o, collector - collector - end - - def visit_Arel_Nodes_Offset o, collector - collector << "raw_rnum_ > " - visit o.expr, collector - end - - def visit_Arel_Nodes_Except o, collector - collector << "( " - collector = infix_value o, collector, " MINUS " - collector << " )" - end - - def visit_Arel_Nodes_UpdateStatement o, collector - # Oracle does not allow ORDER BY/LIMIT in UPDATEs. - if o.orders.any? && o.limit.nil? - # However, there is no harm in silently eating the ORDER BY clause if no LIMIT has been provided, - # otherwise let the user deal with the error - o = o.dup - o.orders = [] - end - - super - end - - ### - # Hacks for the order clauses specific to Oracle - def order_hacks o - return o if o.orders.empty? - return o unless o.cores.any? do |core| - core.projections.any? do |projection| - /FIRST_VALUE/ === projection - end - end - # Previous version with join and split broke ORDER BY clause - # if it contained functions with several arguments (separated by ','). - # - # orders = o.orders.map { |x| visit x }.join(', ').split(',') - orders = o.orders.map do |x| - string = visit(x, Arel::Collectors::SQLString.new).value - if string.include?(',') - split_order_string(string) - else - string - end - end.flatten - o.orders = [] - orders.each_with_index do |order, i| - o.orders << - Nodes::SqlLiteral.new("alias_#{i}__#{' DESC' if /\bdesc$/i === order}") - end - o - end - - # Split string by commas but count opening and closing brackets - # and ignore commas inside brackets. - def split_order_string(string) - array = [] - i = 0 - string.split(',').each do |part| - if array[i] - array[i] << ',' << part - else - # to ensure that array[i] will be String and not Arel::Nodes::SqlLiteral - array[i] = part.to_s - end - i += 1 if array[i].count('(') == array[i].count(')') - end - array - end - - def visit_Arel_Nodes_BindParam o, collector - collector.add_bind(o) { |i| ":a#{i}" } - end - - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/oracle12.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/oracle12.rb deleted file mode 100644 index ce90e994ae..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/oracle12.rb +++ /dev/null @@ -1,60 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class Oracle12 < Arel::Visitors::ToSql - private - - def visit_Arel_Nodes_SelectStatement o, collector - # Oracle does not allow LIMIT clause with select for update - if o.limit && o.lock - raise ArgumentError, <<-MSG - 'Combination of limit and lock is not supported. - because generated SQL statements - `SELECT FOR UPDATE and FETCH FIRST n ROWS` generates ORA-02014.` - MSG - end - super - end - - def visit_Arel_Nodes_SelectOptions o, collector - collector = maybe_visit o.offset, collector - collector = maybe_visit o.limit, collector - collector = maybe_visit o.lock, collector - end - - def visit_Arel_Nodes_Limit o, collector - collector << "FETCH FIRST " - collector = visit o.expr, collector - collector << " ROWS ONLY" - end - - def visit_Arel_Nodes_Offset o, collector - collector << "OFFSET " - visit o.expr, collector - collector << " ROWS" - end - - def visit_Arel_Nodes_Except o, collector - collector << "( " - collector = infix_value o, collector, " MINUS " - collector << " )" - end - - def visit_Arel_Nodes_UpdateStatement o, collector - # Oracle does not allow ORDER BY/LIMIT in UPDATEs. - if o.orders.any? && o.limit.nil? - # However, there is no harm in silently eating the ORDER BY clause if no LIMIT has been provided, - # otherwise let the user deal with the error - o = o.dup - o.orders = [] - end - - super - end - - def visit_Arel_Nodes_BindParam o, collector - collector.add_bind(o) { |i| ":a#{i}" } - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/postgresql.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/postgresql.rb deleted file mode 100644 index f0991a2f11..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/postgresql.rb +++ /dev/null @@ -1,85 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class PostgreSQL < Arel::Visitors::ToSql - CUBE = 'CUBE' - ROLLUP = 'ROLLUP' - GROUPING_SET = 'GROUPING SET' - - private - - def visit_Arel_Nodes_Matches o, collector - op = o.case_sensitive ? ' LIKE ' : ' ILIKE ' - collector = infix_value o, collector, op - if o.escape - collector << ' ESCAPE ' - visit o.escape, collector - else - collector - end - end - - def visit_Arel_Nodes_DoesNotMatch o, collector - op = o.case_sensitive ? ' NOT LIKE ' : ' NOT ILIKE ' - collector = infix_value o, collector, op - if o.escape - collector << ' ESCAPE ' - visit o.escape, collector - else - collector - end - end - - def visit_Arel_Nodes_Regexp o, collector - op = o.case_sensitive ? ' ~ ' : ' ~* ' - infix_value o, collector, op - end - - def visit_Arel_Nodes_NotRegexp o, collector - op = o.case_sensitive ? ' !~ ' : ' !~* ' - infix_value o, collector, op - end - - def visit_Arel_Nodes_DistinctOn o, collector - collector << "DISTINCT ON ( " - visit(o.expr, collector) << " )" - end - - def visit_Arel_Nodes_BindParam o, collector - collector.add_bind(o) { |i| "$#{i}" } - end - - def visit_Arel_Nodes_GroupingElement o, collector - collector << "( " - visit(o.expr, collector) << " )" - end - - def visit_Arel_Nodes_Cube o, collector - collector << CUBE - grouping_array_or_grouping_element o, collector - end - - def visit_Arel_Nodes_RollUp o, collector - collector << ROLLUP - grouping_array_or_grouping_element o, collector - end - - def visit_Arel_Nodes_GroupingSet o, collector - collector << GROUPING_SET - grouping_array_or_grouping_element o, collector - end - - # Utilized by GroupingSet, Cube & RollUp visitors to - # handle grouping aggregation semantics - def grouping_array_or_grouping_element o, collector - if o.expr.is_a? Array - collector << "( " - visit o.expr, collector - collector << " )" - else - visit o.expr, collector - end - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/reduce.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/reduce.rb deleted file mode 100644 index 7948758e2f..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/reduce.rb +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true -require 'arel/visitors/visitor' - -module Arel - module Visitors - class Reduce < Arel::Visitors::Visitor - def accept object, collector - visit object, collector - end - - private - - def visit object, collector - send dispatch[object.class], object, collector - rescue NoMethodError => e - raise e if respond_to?(dispatch[object.class], true) - superklass = object.class.ancestors.find { |klass| - respond_to?(dispatch[klass], true) - } - raise(TypeError, "Cannot visit #{object.class}") unless superklass - dispatch[object.class] = dispatch[superklass] - retry - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/sqlite.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/sqlite.rb deleted file mode 100644 index 4ae093968b..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/sqlite.rb +++ /dev/null @@ -1,27 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class SQLite < Arel::Visitors::ToSql - private - - # Locks are not supported in SQLite - def visit_Arel_Nodes_Lock o, collector - collector - end - - def visit_Arel_Nodes_SelectStatement o, collector - o.limit = Arel::Nodes::Limit.new(-1) if o.offset && !o.limit - super - end - - def visit_Arel_Nodes_True o, collector - collector << "1" - end - - def visit_Arel_Nodes_False o, collector - collector << "0" - end - - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/to_sql.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/to_sql.rb deleted file mode 100644 index 486c51a183..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/to_sql.rb +++ /dev/null @@ -1,827 +0,0 @@ -# frozen_string_literal: true -require 'bigdecimal' -require 'date' -require 'arel/visitors/reduce' - -module Arel - module Visitors - class UnsupportedVisitError < StandardError - def initialize(object) - super "Unsupported argument type: #{object.class.name}. Construct an Arel node instead." - end - end - - class ToSql < Arel::Visitors::Reduce - ## - # This is some roflscale crazy stuff. I'm roflscaling this because - # building SQL queries is a hotspot. I will explain the roflscale so that - # others will not rm this code. - # - # In YARV, string literals in a method body will get duped when the byte - # code is executed. Let's take a look: - # - # > puts RubyVM::InstructionSequence.new('def foo; "bar"; end').disasm - # - # == disasm: >===== - # 0000 trace 8 - # 0002 trace 1 - # 0004 putstring "bar" - # 0006 trace 16 - # 0008 leave - # - # The `putstring` bytecode will dup the string and push it on the stack. - # In many cases in our SQL visitor, that string is never mutated, so there - # is no need to dup the literal. - # - # If we change to a constant lookup, the string will not be duped, and we - # can reduce the objects in our system: - # - # > puts RubyVM::InstructionSequence.new('BAR = "bar"; def foo; BAR; end').disasm - # - # == disasm: >======== - # 0000 trace 8 - # 0002 trace 1 - # 0004 getinlinecache 11, - # 0007 getconstant :BAR - # 0009 setinlinecache - # 0011 trace 16 - # 0013 leave - # - # `getconstant` should be a hash lookup, and no object is duped when the - # value of the constant is pushed on the stack. Hence the crazy - # constants below. - # - # `matches` and `doesNotMatch` operate case-insensitively via Visitor subclasses - # specialized for specific databases when necessary. - # - - WHERE = ' WHERE ' # :nodoc: - SPACE = ' ' # :nodoc: - COMMA = ', ' # :nodoc: - GROUP_BY = ' GROUP BY ' # :nodoc: - ORDER_BY = ' ORDER BY ' # :nodoc: - WINDOW = ' WINDOW ' # :nodoc: - AND = ' AND ' # :nodoc: - - DISTINCT = 'DISTINCT' # :nodoc: - - def initialize connection - super() - @connection = connection - end - - def compile node, &block - accept(node, Arel::Collectors::SQLString.new, &block).value - end - - private - - def visit_Arel_Nodes_DeleteStatement o, collector - collector << 'DELETE FROM ' - collector = visit o.relation, collector - if o.wheres.any? - collector << WHERE - collector = inject_join o.wheres, collector, AND - end - - maybe_visit o.limit, collector - end - - # FIXME: we should probably have a 2-pass visitor for this - def build_subselect key, o - stmt = Nodes::SelectStatement.new - core = stmt.cores.first - core.froms = o.relation - core.wheres = o.wheres - core.projections = [key] - stmt.limit = o.limit - stmt.orders = o.orders - stmt - end - - def visit_Arel_Nodes_UpdateStatement o, collector - if o.orders.empty? && o.limit.nil? - wheres = o.wheres - else - wheres = [Nodes::In.new(o.key, [build_subselect(o.key, o)])] - end - - collector << "UPDATE " - collector = visit o.relation, collector - unless o.values.empty? - collector << " SET " - collector = inject_join o.values, collector, ", " - end - - unless wheres.empty? - collector << " WHERE " - collector = inject_join wheres, collector, " AND " - end - - collector - end - - def visit_Arel_Nodes_InsertStatement o, collector - collector << "INSERT INTO " - collector = visit o.relation, collector - if o.columns.any? - collector << " (#{o.columns.map { |x| - quote_column_name x.name - }.join ', '})" - end - - if o.values - maybe_visit o.values, collector - elsif o.select - maybe_visit o.select, collector - else - collector - end - end - - def visit_Arel_Nodes_Exists o, collector - collector << "EXISTS (" - collector = visit(o.expressions, collector) << ")" - if o.alias - collector << " AS " - visit o.alias, collector - else - collector - end - end - - def visit_Arel_Nodes_Casted o, collector - collector << quoted(o.val, o.attribute).to_s - end - - def visit_Arel_Nodes_Quoted o, collector - collector << quoted(o.expr, nil).to_s - end - - def visit_Arel_Nodes_True o, collector - collector << "TRUE" - end - - def visit_Arel_Nodes_False o, collector - collector << "FALSE" - end - - def visit_Arel_Nodes_Values o, collector - collector << "VALUES (" - - len = o.expressions.length - 1 - o.expressions.each_with_index { |value, i| - case value - when Nodes::SqlLiteral, Nodes::BindParam - collector = visit value, collector - else - collector << quote(value).to_s - end - unless i == len - collector << COMMA - end - } - - collector << ")" - end - - def visit_Arel_Nodes_SelectStatement o, collector - if o.with - collector = visit o.with, collector - collector << SPACE - end - - collector = o.cores.inject(collector) { |c,x| - visit_Arel_Nodes_SelectCore(x, c) - } - - unless o.orders.empty? - collector << ORDER_BY - len = o.orders.length - 1 - o.orders.each_with_index { |x, i| - collector = visit(x, collector) - collector << COMMA unless len == i - } - end - - visit_Arel_Nodes_SelectOptions(o, collector) - - collector - end - - def visit_Arel_Nodes_SelectOptions o, collector - collector = maybe_visit o.limit, collector - collector = maybe_visit o.offset, collector - collector = maybe_visit o.lock, collector - end - - def visit_Arel_Nodes_SelectCore o, collector - collector << "SELECT" - - collector = maybe_visit o.top, collector - - collector = maybe_visit o.set_quantifier, collector - - collect_nodes_for o.projections, collector, SPACE - - if o.source && !o.source.empty? - collector << " FROM " - collector = visit o.source, collector - end - - collect_nodes_for o.wheres, collector, WHERE, AND - collect_nodes_for o.groups, collector, GROUP_BY - unless o.havings.empty? - collector << " HAVING " - inject_join o.havings, collector, AND - end - collect_nodes_for o.windows, collector, WINDOW - - collector - end - - def collect_nodes_for nodes, collector, spacer, connector = COMMA - unless nodes.empty? - collector << spacer - len = nodes.length - 1 - nodes.each_with_index do |x, i| - collector = visit(x, collector) - collector << connector unless len == i - end - end - end - - def visit_Arel_Nodes_Bin o, collector - visit o.expr, collector - end - - def visit_Arel_Nodes_Distinct o, collector - collector << DISTINCT - end - - def visit_Arel_Nodes_DistinctOn o, collector - raise NotImplementedError, 'DISTINCT ON not implemented for this db' - end - - def visit_Arel_Nodes_With o, collector - collector << "WITH " - inject_join o.children, collector, COMMA - end - - def visit_Arel_Nodes_WithRecursive o, collector - collector << "WITH RECURSIVE " - inject_join o.children, collector, COMMA - end - - def visit_Arel_Nodes_Union o, collector - collector << "( " - infix_value(o, collector, " UNION ") << " )" - end - - def visit_Arel_Nodes_UnionAll o, collector - collector << "( " - infix_value(o, collector, " UNION ALL ") << " )" - end - - def visit_Arel_Nodes_Intersect o, collector - collector << "( " - infix_value(o, collector, " INTERSECT ") << " )" - end - - def visit_Arel_Nodes_Except o, collector - collector << "( " - infix_value(o, collector, " EXCEPT ") << " )" - end - - def visit_Arel_Nodes_NamedWindow o, collector - collector << quote_column_name(o.name) - collector << " AS " - visit_Arel_Nodes_Window o, collector - end - - def visit_Arel_Nodes_Window o, collector - collector << "(" - - if o.partitions.any? - collector << "PARTITION BY " - collector = inject_join o.partitions, collector, ", " - end - - if o.orders.any? - collector << SPACE if o.partitions.any? - collector << "ORDER BY " - collector = inject_join o.orders, collector, ", " - end - - if o.framing - collector << SPACE if o.partitions.any? or o.orders.any? - collector = visit o.framing, collector - end - - collector << ")" - end - - def visit_Arel_Nodes_Rows o, collector - if o.expr - collector << "ROWS " - visit o.expr, collector - else - collector << "ROWS" - end - end - - def visit_Arel_Nodes_Range o, collector - if o.expr - collector << "RANGE " - visit o.expr, collector - else - collector << "RANGE" - end - end - - def visit_Arel_Nodes_Preceding o, collector - collector = if o.expr - visit o.expr, collector - else - collector << "UNBOUNDED" - end - - collector << " PRECEDING" - end - - def visit_Arel_Nodes_Following o, collector - collector = if o.expr - visit o.expr, collector - else - collector << "UNBOUNDED" - end - - collector << " FOLLOWING" - end - - def visit_Arel_Nodes_CurrentRow o, collector - collector << "CURRENT ROW" - end - - def visit_Arel_Nodes_Over o, collector - case o.right - when nil - visit(o.left, collector) << " OVER ()" - when Arel::Nodes::SqlLiteral - infix_value o, collector, " OVER " - when String, Symbol - visit(o.left, collector) << " OVER #{quote_column_name o.right.to_s}" - else - infix_value o, collector, " OVER " - end - end - - def visit_Arel_Nodes_Offset o, collector - collector << "OFFSET " - visit o.expr, collector - end - - def visit_Arel_Nodes_Limit o, collector - collector << "LIMIT " - visit o.expr, collector - end - - # FIXME: this does nothing on most databases, but does on MSSQL - def visit_Arel_Nodes_Top o, collector - collector - end - - def visit_Arel_Nodes_Lock o, collector - visit o.expr, collector - end - - def visit_Arel_Nodes_Grouping o, collector - if o.expr.is_a? Nodes::Grouping - visit(o.expr, collector) - else - collector << "(" - visit(o.expr, collector) << ")" - end - end - - def visit_Arel_SelectManager o, collector - collector << "(#{o.to_sql.rstrip})" - end - - def visit_Arel_Nodes_Ascending o, collector - visit(o.expr, collector) << " ASC" - end - - def visit_Arel_Nodes_Descending o, collector - visit(o.expr, collector) << " DESC" - end - - def visit_Arel_Nodes_Group o, collector - visit o.expr, collector - end - - def visit_Arel_Nodes_NamedFunction o, collector - collector << o.name - collector << "(" - collector << "DISTINCT " if o.distinct - collector = inject_join(o.expressions, collector, ", ") << ")" - if o.alias - collector << " AS " - visit o.alias, collector - else - collector - end - end - - def visit_Arel_Nodes_Extract o, collector - collector << "EXTRACT(#{o.field.to_s.upcase} FROM " - visit(o.expr, collector) << ")" - end - - def visit_Arel_Nodes_Count o, collector - aggregate "COUNT", o, collector - end - - def visit_Arel_Nodes_Sum o, collector - aggregate "SUM", o, collector - end - - def visit_Arel_Nodes_Max o, collector - aggregate "MAX", o, collector - end - - def visit_Arel_Nodes_Min o, collector - aggregate "MIN", o, collector - end - - def visit_Arel_Nodes_Avg o, collector - aggregate "AVG", o, collector - end - - def visit_Arel_Nodes_TableAlias o, collector - collector = visit o.relation, collector - collector << " " - collector << quote_table_name(o.name) - end - - def visit_Arel_Nodes_Between o, collector - collector = visit o.left, collector - collector << " BETWEEN " - visit o.right, collector - end - - def visit_Arel_Nodes_GreaterThanOrEqual o, collector - collector = visit o.left, collector - collector << " >= " - visit o.right, collector - end - - def visit_Arel_Nodes_GreaterThan o, collector - collector = visit o.left, collector - collector << " > " - visit o.right, collector - end - - def visit_Arel_Nodes_LessThanOrEqual o, collector - collector = visit o.left, collector - collector << " <= " - visit o.right, collector - end - - def visit_Arel_Nodes_LessThan o, collector - collector = visit o.left, collector - collector << " < " - visit o.right, collector - end - - def visit_Arel_Nodes_Matches o, collector - collector = visit o.left, collector - collector << " LIKE " - collector = visit o.right, collector - if o.escape - collector << ' ESCAPE ' - visit o.escape, collector - else - collector - end - end - - def visit_Arel_Nodes_DoesNotMatch o, collector - collector = visit o.left, collector - collector << " NOT LIKE " - collector = visit o.right, collector - if o.escape - collector << ' ESCAPE ' - visit o.escape, collector - else - collector - end - end - - def visit_Arel_Nodes_JoinSource o, collector - if o.left - collector = visit o.left, collector - end - if o.right.any? - collector << SPACE if o.left - collector = inject_join o.right, collector, SPACE - end - collector - end - - def visit_Arel_Nodes_Regexp o, collector - raise NotImplementedError, '~ not implemented for this db' - end - - def visit_Arel_Nodes_NotRegexp o, collector - raise NotImplementedError, '!~ not implemented for this db' - end - - def visit_Arel_Nodes_StringJoin o, collector - visit o.left, collector - end - - def visit_Arel_Nodes_FullOuterJoin o, collector - collector << "FULL OUTER JOIN " - collector = visit o.left, collector - collector << SPACE - visit o.right, collector - end - - def visit_Arel_Nodes_OuterJoin o, collector - collector << "LEFT OUTER JOIN " - collector = visit o.left, collector - collector << " " - visit o.right, collector - end - - def visit_Arel_Nodes_RightOuterJoin o, collector - collector << "RIGHT OUTER JOIN " - collector = visit o.left, collector - collector << SPACE - visit o.right, collector - end - - def visit_Arel_Nodes_InnerJoin o, collector - collector << "INNER JOIN " - collector = visit o.left, collector - if o.right - collector << SPACE - visit(o.right, collector) - else - collector - end - end - - def visit_Arel_Nodes_On o, collector - collector << "ON " - visit o.expr, collector - end - - def visit_Arel_Nodes_Not o, collector - collector << "NOT (" - visit(o.expr, collector) << ")" - end - - def visit_Arel_Table o, collector - if o.table_alias - collector << "#{quote_table_name o.name} #{quote_table_name o.table_alias}" - else - collector << quote_table_name(o.name) - end - end - - def visit_Arel_Nodes_In o, collector - if Array === o.right && o.right.empty? - collector << '1=0' - else - collector = visit o.left, collector - collector << " IN (" - visit(o.right, collector) << ")" - end - end - - def visit_Arel_Nodes_NotIn o, collector - if Array === o.right && o.right.empty? - collector << '1=1' - else - collector = visit o.left, collector - collector << " NOT IN (" - collector = visit o.right, collector - collector << ")" - end - end - - def visit_Arel_Nodes_And o, collector - inject_join o.children, collector, " AND " - end - - def visit_Arel_Nodes_Or o, collector - collector = visit o.left, collector - collector << " OR " - visit o.right, collector - end - - def visit_Arel_Nodes_Assignment o, collector - case o.right - when Arel::Nodes::UnqualifiedColumn, Arel::Attributes::Attribute, Arel::Nodes::BindParam - collector = visit o.left, collector - collector << " = " - visit o.right, collector - else - collector = visit o.left, collector - collector << " = " - collector << quote(o.right).to_s - end - end - - def visit_Arel_Nodes_Equality o, collector - right = o.right - - collector = visit o.left, collector - - if right.nil? - collector << " IS NULL" - else - collector << " = " - visit right, collector - end - end - - def visit_Arel_Nodes_NotEqual o, collector - right = o.right - - collector = visit o.left, collector - - if right.nil? - collector << " IS NOT NULL" - else - collector << " != " - visit right, collector - end - end - - def visit_Arel_Nodes_As o, collector - collector = visit o.left, collector - collector << " AS " - visit o.right, collector - end - - def visit_Arel_Nodes_Case o, collector - collector << "CASE " - if o.case - visit o.case, collector - collector << " " - end - o.conditions.each do |condition| - visit condition, collector - collector << " " - end - if o.default - visit o.default, collector - collector << " " - end - collector << "END" - end - - def visit_Arel_Nodes_When o, collector - collector << "WHEN " - visit o.left, collector - collector << " THEN " - visit o.right, collector - end - - def visit_Arel_Nodes_Else o, collector - collector << "ELSE " - visit o.expr, collector - end - - def visit_Arel_Nodes_UnqualifiedColumn o, collector - collector << "#{quote_column_name o.name}" - collector - end - - def visit_Arel_Attributes_Attribute o, collector - join_name = o.relation.table_alias || o.relation.name - collector << "#{quote_table_name join_name}.#{quote_column_name o.name}" - end - alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute - - def literal o, collector; collector << o.to_s; end - - def visit_Arel_Nodes_BindParam o, collector - collector.add_bind(o) { "?" } - end - - alias :visit_Arel_Nodes_SqlLiteral :literal - alias :visit_Bignum :literal - alias :visit_Fixnum :literal - alias :visit_Integer :literal - - def quoted o, a - if a && a.able_to_type_cast? - quote(a.type_cast_for_database(o)) - else - quote(o) - end - end - - def unsupported o, collector - raise UnsupportedVisitError.new(o) - end - - alias :visit_ActiveSupport_Multibyte_Chars :unsupported - alias :visit_ActiveSupport_StringInquirer :unsupported - alias :visit_BigDecimal :unsupported - alias :visit_Class :unsupported - alias :visit_Date :unsupported - alias :visit_DateTime :unsupported - alias :visit_FalseClass :unsupported - alias :visit_Float :unsupported - alias :visit_Hash :unsupported - alias :visit_NilClass :unsupported - alias :visit_String :unsupported - alias :visit_Symbol :unsupported - alias :visit_Time :unsupported - alias :visit_TrueClass :unsupported - - def visit_Arel_Nodes_InfixOperation o, collector - collector = visit o.left, collector - collector << " #{o.operator} " - visit o.right, collector - end - - alias :visit_Arel_Nodes_Addition :visit_Arel_Nodes_InfixOperation - alias :visit_Arel_Nodes_Subtraction :visit_Arel_Nodes_InfixOperation - alias :visit_Arel_Nodes_Multiplication :visit_Arel_Nodes_InfixOperation - alias :visit_Arel_Nodes_Division :visit_Arel_Nodes_InfixOperation - - def visit_Arel_Nodes_UnaryOperation o, collector - collector << " #{o.operator} " - visit o.expr, collector - end - - def visit_Array o, collector - inject_join o, collector, ", " - end - alias :visit_Set :visit_Array - - def quote value - return value if Arel::Nodes::SqlLiteral === value - @connection.quote value - end - - def quote_table_name name - return name if Arel::Nodes::SqlLiteral === name - @connection.quote_table_name(name) - end - - def quote_column_name name - return name if Arel::Nodes::SqlLiteral === name - @connection.quote_column_name(name) - end - - def maybe_visit thing, collector - return collector unless thing - collector << " " - visit thing, collector - end - - def inject_join list, collector, join_str - len = list.length - 1 - list.each_with_index.inject(collector) { |c, (x,i)| - if i == len - visit x, c - else - visit(x, c) << join_str - end - } - end - - def infix_value o, collector, value - collector = visit o.left, collector - collector << value - visit o.right, collector - end - - def aggregate name, o, collector - collector << "#{name}(" - if o.distinct - collector << "DISTINCT " - end - collector = inject_join(o.expressions, collector, ", ") << ")" - if o.alias - collector << " AS " - visit o.alias, collector - else - collector - end - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/visitor.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/visitor.rb deleted file mode 100644 index b96b8238a7..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/visitor.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class Visitor - def initialize - @dispatch = get_dispatch_cache - end - - def accept object - visit object - end - - private - - def self.dispatch_cache - Hash.new do |hash, klass| - hash[klass] = "visit_#{(klass.name || '').gsub('::', '_')}" - end - end - - def get_dispatch_cache - self.class.dispatch_cache - end - - def dispatch - @dispatch - end - - def visit object - send dispatch[object.class], object - rescue NoMethodError => e - raise e if respond_to?(dispatch[object.class], true) - superklass = object.class.ancestors.find { |klass| - respond_to?(dispatch[klass], true) - } - raise(TypeError, "Cannot visit #{object.class}") unless superklass - dispatch[object.class] = dispatch[superklass] - retry - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/where_sql.rb b/debian/gems-compat/arel-8.0.0/lib/arel/visitors/where_sql.rb deleted file mode 100644 index 55e6ca9a21..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/visitors/where_sql.rb +++ /dev/null @@ -1,22 +0,0 @@ -# frozen_string_literal: true -module Arel - module Visitors - class WhereSql < Arel::Visitors::ToSql - def initialize(inner_visitor, *args, &block) - @inner_visitor = inner_visitor - super(*args, &block) - end - - private - - def visit_Arel_Nodes_SelectCore o, collector - collector << "WHERE " - wheres = o.wheres.map do |where| - Nodes::SqlLiteral.new(@inner_visitor.accept(where, collector.class.new).value) - end - - inject_join wheres, collector, ' AND ' - end - end - end -end diff --git a/debian/gems-compat/arel-8.0.0/lib/arel/window_predications.rb b/debian/gems-compat/arel-8.0.0/lib/arel/window_predications.rb deleted file mode 100644 index f93dede036..0000000000 --- a/debian/gems-compat/arel-8.0.0/lib/arel/window_predications.rb +++ /dev/null @@ -1,10 +0,0 @@ -# frozen_string_literal: true -module Arel - module WindowPredications - - def over(expr = nil) - Nodes::Over.new(self, expr) - end - - end -end \ No newline at end of file diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/.gitignore b/debian/gems-compat/gitlab-labkit-0.2.0/.gitignore deleted file mode 100644 index f8051c1313..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -Gemfile.lock -*.gem -node_modules diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/.gitlab-ci.yml b/debian/gems-compat/gitlab-labkit-0.2.0/.gitlab-ci.yml deleted file mode 100644 index 6175b791f3..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/.gitlab-ci.yml +++ /dev/null @@ -1,24 +0,0 @@ -.test_template: &test_definition - stage: test - script: - - bundle install - - bundle exec rake verify build install - -test:2.6: - image: ruby:2.6 - <<: *test_definition - -test:2.5: - image: ruby:2.5 - <<: *test_definition - -test:2.4: - image: ruby:2.4 - <<: *test_definition - -deploy: - stage: deploy - script: - - tools/deploy-rubygem.sh - only: - - tags diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/.rspec b/debian/gems-compat/gitlab-labkit-0.2.0/.rspec deleted file mode 100644 index 9fba4148ee..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/.rspec +++ /dev/null @@ -1,2 +0,0 @@ ---color ---require ./spec/spec_helper diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/.rubocop.yml b/debian/gems-compat/gitlab-labkit-0.2.0/.rubocop.yml deleted file mode 100644 index 177fe98beb..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/.rubocop.yml +++ /dev/null @@ -1,173 +0,0 @@ -AllCops: - TargetRubyVersion: 2.4 - -require: - - rubocop-rspec - -Style/HashSyntax: - EnforcedStyle: no_mixed_keys - -Style/SymbolLiteral: - Enabled: No - -Style/TrailingCommaInArguments: - Enabled: No # Delegated to rufo - -Style/TrailingCommaInHashLiteral: - Enabled: No # Delegated to rufo - -Style/FrozenStringLiteralComment: - EnforcedStyle: always - -Style/TrailingCommaInArrayLiteral: - EnforcedStyleForMultiline: comma - -Style/StringLiterals: - EnforcedStyle: double_quotes - -Style/StringLiteralsInInterpolation: - EnforcedStyle: double_quotes - -Layout/MultilineMethodCallIndentation: - Enabled: No - -Layout/SpaceInLambdaLiteral: - Enabled: No - -Layout/SpaceInsideBlockBraces: - Enabled: No - -Layout/FirstParameterIndentation: - Enabled: No - -Metrics/AbcSize: - Enabled: true - Max: 54.28 - -Metrics/BlockLength: - Enabled: false - -Metrics/BlockNesting: - Enabled: true - Max: 4 - -Metrics/ClassLength: - Enabled: false - -Metrics/CyclomaticComplexity: - Enabled: true - Max: 13 - -Metrics/LineLength: - Enabled: false - -Metrics/MethodLength: - Enabled: false - -Metrics/ModuleLength: - Enabled: false - -Metrics/ParameterLists: - Enabled: true - Max: 8 - -Metrics/PerceivedComplexity: - Enabled: true - Max: 14 - -RSpec/AnyInstance: - Enabled: false - -RSpec/BeEql: - Enabled: true - -RSpec/BeforeAfterAll: - Enabled: false - -RSpec/DescribeClass: - Enabled: false - -RSpec/DescribeMethod: - Enabled: false - -RSpec/DescribeSymbol: - Enabled: true - -RSpec/DescribedClass: - Enabled: true - -RSpec/EmptyExampleGroup: - Enabled: true - -RSpec/ExampleLength: - Enabled: false - Max: 5 - -RSpec/ExampleWording: - Enabled: false - CustomTransform: - be: is - have: has - not: does not - IgnoredWords: [] - -RSpec/ExpectActual: - Enabled: true - -RSpec/ExpectOutput: - Enabled: true - -RSpec/FilePath: - Enabled: true - IgnoreMethods: true - -RSpec/Focus: - Enabled: true - -RSpec/HookArgument: - Enabled: true - EnforcedStyle: implicit - -RSpec/ImplicitExpect: - Enabled: true - EnforcedStyle: is_expected - -RSpec/InstanceVariable: - Enabled: false - -RSpec/LeadingSubject: - Enabled: false - -RSpec/LetSetup: - Enabled: false - -RSpec/MessageChain: - Enabled: false - -RSpec/MessageSpies: - Enabled: false - -RSpec/MultipleDescribes: - Enabled: false - -RSpec/MultipleExpectations: - Enabled: false - -RSpec/NamedSubject: - Enabled: false - -RSpec/NestedGroups: - Enabled: false - -RSpec/NotToNot: - EnforcedStyle: not_to - Enabled: true - -RSpec/RepeatedDescription: - Enabled: false - -RSpec/SubjectStub: - Enabled: false - -RSpec/VerifiedDoubles: - Enabled: false diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/.ruby-version b/debian/gems-compat/gitlab-labkit-0.2.0/.ruby-version deleted file mode 100644 index d4bcea9584..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/.ruby-version +++ /dev/null @@ -1 +0,0 @@ -ruby-2.5.3 diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/.rufo b/debian/gems-compat/gitlab-labkit-0.2.0/.rufo deleted file mode 100644 index 84b926d98f..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/.rufo +++ /dev/null @@ -1,3 +0,0 @@ -align_chained_calls true -parens_in_def :dynamic -trailing_commas true diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/Gemfile b/debian/gems-compat/gitlab-labkit-0.2.0/Gemfile deleted file mode 100644 index be173b205f..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/Gemfile +++ /dev/null @@ -1,5 +0,0 @@ -# frozen_string_literal: true - -source "https://rubygems.org" - -gemspec diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/LICENSE b/debian/gems-compat/gitlab-labkit-0.2.0/LICENSE deleted file mode 100644 index 662504449b..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016-2019 GitLab B.V. - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/README.md b/debian/gems-compat/gitlab-labkit-0.2.0/README.md deleted file mode 100644 index 4a7d809612..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# LabKit-Ruby 🔬🔬🔬🔬🔬 - -LabKit-Ruby is minimalist library to provide functionality for Ruby services at GitLab. - -LabKit-Ruby is the Ruby companion for [LabKit](https://gitlab.com/gitlab-org/labkit), a minimalist library to provide functionality for Go services at GitLab. - -LabKit-Ruby and LabKit are intended to provide similar functionality, but use the semantics of their respective languages, so are not intended to provide identical APIS. - -## Documentation - -API Documentation is available at [the Rubydoc site](https://www.rubydoc.info/gems/gitlab-labkit/). - -## Functionality - -LabKit-Ruby provides functionality in three areas: - -1. `Labkit::Correlation` for handling and propagating Correlation-IDs. -1. `Labkit::Logging` for sanitizing log messages. -1. `Labkit::Tracing` for handling and propagating distributed traces. - -## Developing - -Anyone can contribute! - -```console -$ git clone git@gitlab.com:gitlab-org/labkit-ruby.git -$ cd labkit-ruby -$ bundle install - -$ # Autoformat code and auto-correct linters -$ bundle exec rake fix - -$ # Run tests, linters -$ bundle exec rake verify -``` - -Note that LabKit-Ruby uses the [`rufo`](https://github.com/ruby-formatter/rufo) for auto-formatting. Please run `bundle exec rake fix` to auto-format your code before pushing. - -Please also review the [development section of the LabKit (go) README](https://gitlab.com/gitlab-org/labkit#developing-labkit) for details of the LabKit architectural philosophy. diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/Rakefile b/debian/gems-compat/gitlab-labkit-0.2.0/Rakefile deleted file mode 100644 index 9a7206715f..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/Rakefile +++ /dev/null @@ -1,41 +0,0 @@ -# frozen_string_literal: true - -require "bundler/gem_tasks" -require "rufo" - -begin - require "rspec/core/rake_task" - RSpec::Core::RakeTask.new(:spec) -end - -require "rubocop/rake_task" -RuboCop::RakeTask.new - -desc "Alias for `rake rufo:run`" -task :format => ["rufo:run"] - -namespace :rufo do - require "rufo" - - def rufo_command(*switches, rake_args) - files_or_dirs = rake_args[:files_or_dirs] || "." - args = switches + files_or_dirs.split(" ") - Rufo::Command.run(args) - end - - desc "Format Ruby code in current directory" - task :run, [:files_or_dirs] do |_task, rake_args| - rufo_command(rake_args) - end - - desc "Check that no formatting changes are produced" - task :check, [:files_or_dirs] do |_task, rake_args| - rufo_command("--check", rake_args) - end -end - -task :fix => %w[rufo:run rubocop:auto_correct] - -task :verify => %w[spec rufo:check rubocop] - -task :default => %w[verify build] diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/gitlab-labkit.gemspec b/debian/gems-compat/gitlab-labkit-0.2.0/gitlab-labkit.gemspec deleted file mode 100644 index 10392ca162..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/gitlab-labkit.gemspec +++ /dev/null @@ -1,33 +0,0 @@ -# frozen_string_literal: true - -lib = File.expand_path("lib", __dir__) -$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) - -Gem::Specification.new do |spec| - spec.name = "gitlab-labkit" - spec.version = "0.2.0" - spec.authors = ["Andrew Newdigate"] - spec.email = ["andrew@gitlab.com"] - - spec.summary = "Instrumentation for GitLab" - spec.homepage = "http://about.gitlab.com" - spec.license = "MIT" - - spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec|tools)/}) } - spec.require_paths = ["lib"] - spec.required_ruby_version = ">= 2.4.0" - - spec.add_runtime_dependency "actionpack", "~> 5" - spec.add_runtime_dependency "activesupport", "~> 5" - spec.add_runtime_dependency "grpc", "~> 1.15" - spec.add_runtime_dependency "jaeger-client", "~> 0.10" - spec.add_runtime_dependency "opentracing", "~> 0.4" - - spec.add_development_dependency "rack", "~> 2.0" - spec.add_development_dependency "rake", "~> 12.3" - spec.add_development_dependency "rspec", "~> 3.6.0" - spec.add_development_dependency "rspec-parameterized", "~> 0.4" - spec.add_development_dependency "rubocop", "~> 0.65.0" - spec.add_development_dependency "rubocop-rspec", "~> 1.22.1" - spec.add_development_dependency "rufo", "~> 0.6" -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/gitlab-labkit.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/gitlab-labkit.rb deleted file mode 100644 index 975c0aa931..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/gitlab-labkit.rb +++ /dev/null @@ -1,15 +0,0 @@ -# rubocop:disable Naming/FileName -# frozen_string_literal: true - -require "active_support/all" - -# LabKit is a module for handling cross-project -# infrastructural concerns, partcularly related to -# observability. -module Labkit - autoload :Correlation, "labkit/correlation" - autoload :Tracing, "labkit/tracing" - autoload :Logging, "labkit/logging" -end - -# rubocop:enable Naming/FileName diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/correlation.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/correlation.rb deleted file mode 100644 index 3e0bc20e10..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/correlation.rb +++ /dev/null @@ -1,8 +0,0 @@ -# frozen_string_literal: true - -module Labkit - # Correlation provides correlation functionality - module Correlation - autoload :CorrelationId, "labkit/correlation/correlation_id" - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/correlation/correlation_id.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/correlation/correlation_id.rb deleted file mode 100644 index f993537518..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/correlation/correlation_id.rb +++ /dev/null @@ -1,44 +0,0 @@ -# frozen_string_literal: true - -module Labkit - module Correlation - # CorrelationId module provides access the Correlation-ID - # of the current request - module CorrelationId - LOG_KEY = "correlation_id" - - class << self - def use_id(correlation_id, &_blk) - # always generate a id if null is passed - correlation_id ||= new_id - - ids.push(correlation_id || new_id) - - begin - yield(current_id) - ensure - ids.pop - end - end - - def current_id - ids.last - end - - def current_or_new_id - current_id || new_id - end - - private - - def ids - Thread.current[:correlation_id] ||= [] - end - - def new_id - SecureRandom.uuid - end - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/logging.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/logging.rb deleted file mode 100644 index 97a2146966..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/logging.rb +++ /dev/null @@ -1,9 +0,0 @@ -# frozen_string_literal: true - -module Labkit - # Logging provides functionality for logging, such as - # sanitization - module Logging - autoload :Sanitizer, "labkit/logging/sanitizer" - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/logging/sanitizer.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/logging/sanitizer.rb deleted file mode 100644 index 9b03300710..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/logging/sanitizer.rb +++ /dev/null @@ -1,54 +0,0 @@ -# frozen_string_literal: true - -module Labkit - module Logging - # Sanitizer provides log message sanitization, removing - # confidential information from log messages - class Sanitizer - SCP_URL_REGEXP = %r{ - (?:((?:[\-_.!~*()a-zA-Z\d;&=+$,]|%[a-fA-F\d]{2})+)(:(?:(?:[\-_.!~*()a-zA-Z\d;:&=+$,]|%[a-fA-F\d]{2})*))?@) (?# 1: username, 2: password) - (?:((?:(?:[a-zA-Z0-9\-._])+|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[(?:(?:[a-fA-F\d]{1,4}:)*(?:[a-fA-F\d]{1,4}|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|(?:(?:[a-fA-F\d]{1,4}:)*[a-fA-F\d]{1,4})?::(?:(?:[a-fA-F\d]{1,4}:)*(?:[a-fA-F\d]{1,4}|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))?)\]))) (?# 3: host) - : - ((?:[\-_.!~*'()a-zA-Z\d:@&=+$,]|%[a-fA-F\d]{2})*(?:;(?:[\-_.!~*'()a-zA-Z\d:@&=+$,]|%[a-fA-F\d]{2})*)*(?:\/(?:[\-_.!~*'()a-zA-Z\d:@&=+$,]|%[a-fA-F\d]{2})*(?:;(?:[\-_.!~*'()a-zA-Z\d:@&=+$,]|%[a-fA-F\d]{2})*)*)*)? (?# 4: path) - }x.freeze - SCP_ANCHORED_URL_REGEXP = /^#{SCP_URL_REGEXP}$/x.freeze - ALLOWED_SCHEMES = %w[http https ssh git].freeze - URL_REGEXP = URI::DEFAULT_PARSER.make_regexp(ALLOWED_SCHEMES).freeze - - def self.sanitize_field(content) - content = content.gsub(URL_REGEXP) { |url| mask_url(url) } - content = content.gsub(SCP_URL_REGEXP) { |scp_url| mask_scp_url(scp_url) } - - content - end - - # Ensures that URLS are sanitized to hide credentials - def self.mask_url(url) - url = url.to_s.strip - p = URI::DEFAULT_PARSER.parse(url) - - p.password = "*****" if p.password.present? - p.user = "*****" if p.user.present? - p.to_s - rescue URI::InvalidURIError - "" - end - - # Ensures that URLs of the form user:password@hostname:project.git are - # sanitized to hide credentials - def self.mask_scp_url(scp_url) - scp_url = scp_url.to_s.strip - m = SCP_ANCHORED_URL_REGEXP.match(scp_url) - return "" unless m - - password = m[2] - host = m[3] - path = m[4] - - return "*****@#{host}:#{path}" unless password.present? - - "*****:*****@#{host}:#{path}" - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing.rb deleted file mode 100644 index ab34bf0d9b..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing.rb +++ /dev/null @@ -1,57 +0,0 @@ -# frozen_string_literal: true - -require "active_support/all" - -module Labkit - # Tracing provides distributed tracing functionality - module Tracing - autoload :Factory, "labkit/tracing/factory" - autoload :GRPCInterceptor, "labkit/tracing/grpc_interceptor" - autoload :JaegerFactory, "labkit/tracing/jaeger_factory" - autoload :RackMiddleware, "labkit/tracing/rack_middleware" - autoload :Rails, "labkit/tracing/rails" - autoload :Sidekiq, "labkit/tracing/sidekiq" - autoload :TracingUtils, "labkit/tracing/tracing_utils" - - # Tracing is only enabled when the `GITLAB_TRACING` env var is configured. - def self.enabled? - connection_string.present? - end - - def self.connection_string - ENV["GITLAB_TRACING"] - end - - def self.tracing_url_template - ENV["GITLAB_TRACING_URL"] - end - - def self.tracing_url_enabled? - enabled? && tracing_url_template.present? - end - - # This will provide a link into the distributed tracing for the current trace, - # if it has been captured. - def self.tracing_url(service_name) - return unless tracing_url_enabled? - - correlation_id = Labkit::Correlation::CorrelationId.current_id.to_s - - # Avoid using `format` since it can throw TypeErrors - # which we want to avoid on unsanitised env var input - tracing_url_template.to_s - .gsub("{{ correlation_id }}", correlation_id) - .gsub("{{ service }}", service_name) - end - - # This will run a block with a span - # @param operation_name [String] The operation name for the span - # @param tags [Hash] Tags to assign to the span - # @param child_of [SpanContext, Span] SpanContext that acts as a parent to - # the newly-started span. If a span instance is provided, its - # context is automatically substituted. - def self.with_tracing(**kwargs, &block) - TracingUtils.with_tracing(**kwargs, &block) - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/factory.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/factory.rb deleted file mode 100644 index 81f39ecfec..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/factory.rb +++ /dev/null @@ -1,58 +0,0 @@ -# frozen_string_literal: true - -require "cgi" - -module Labkit - module Tracing - # Factory provides tools for setting up and configuring the - # distributed tracing system within the process, given the - # tracing connection string - class Factory - OPENTRACING_SCHEME = "opentracing" - - def self.create_tracer(service_name, connection_string) - return unless connection_string.present? - - begin - opentracing_details = parse_connection_string(connection_string) - driver_name = opentracing_details[:driver_name] - - case driver_name - when "jaeger" - JaegerFactory.create_tracer(service_name, opentracing_details[:options]) - else - raise "Unknown driver: #{driver_name}" - end - - # Can't create the tracer? Warn and continue sans tracer - rescue StandardError => e - warn "Unable to instantiate tracer: #{e}" - nil - end - end - - def self.parse_connection_string(connection_string) - parsed = URI.parse(connection_string) - - raise "Invalid tracing connection string" unless valid_uri?(parsed) - - { driver_name: parsed.host, options: parse_query(parsed.query) } - end - private_class_method :parse_connection_string - - def self.parse_query(query) - return {} unless query - - CGI.parse(query).symbolize_keys.transform_values(&:first) - end - private_class_method :parse_query - - def self.valid_uri?(uri) - return false unless uri - - uri.scheme == OPENTRACING_SCHEME && uri.host.to_s =~ /^[a-z0-9_]+$/ && uri.path.empty? - end - private_class_method :valid_uri? - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/grpc_interceptor.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/grpc_interceptor.rb deleted file mode 100644 index d6d0f45535..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/grpc_interceptor.rb +++ /dev/null @@ -1,45 +0,0 @@ -# frozen_string_literal: true - -# rubocop:disable Lint/UnusedMethodArgument -require "opentracing" -require "grpc" - -module Labkit - module Tracing - # GRPCInterceptor is a client-side GRPC interceptor - # for instrumenting GRPC calls with distributed tracing - class GRPCInterceptor < GRPC::ClientInterceptor - include Singleton - - def request_response(request:, call:, method:, metadata:) - wrap_with_tracing(method, "unary", metadata) { yield } - end - - def client_streamer(requests:, call:, method:, metadata:) - wrap_with_tracing(method, "client_stream", metadata) { yield } - end - - def server_streamer(request:, call:, method:, metadata:) - wrap_with_tracing(method, "server_stream", metadata) { yield } - end - - def bidi_streamer(requests:, call:, method:, metadata:) - wrap_with_tracing(method, "bidi_stream", metadata) { yield } - end - - private - - def wrap_with_tracing(method, grpc_type, metadata) - tags = { "component" => "grpc", "span.kind" => "client", "grpc.method" => method, "grpc.type" => grpc_type } - - TracingUtils.with_tracing(operation_name: "grpc:#{method}", tags: tags) do |span| - OpenTracing.inject(span.context, OpenTracing::FORMAT_TEXT_MAP, metadata) - - yield - end - end - end - end -end - -# rubocop:enable Lint/UnusedMethodArgument diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/jaeger_factory.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/jaeger_factory.rb deleted file mode 100644 index e5bf500bfa..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/jaeger_factory.rb +++ /dev/null @@ -1,82 +0,0 @@ -# frozen_string_literal: true - -require "jaeger/client" - -module Labkit - module Tracing - # JaegerFactory will configure Jaeger distributed tracing - class JaegerFactory - # When the probabilistic sampler is used, by default 0.1% of requests will be traced - DEFAULT_PROBABILISTIC_RATE = 0.001 - - # The default port for the Jaeger agent UDP listener - DEFAULT_UDP_PORT = 6831 - - # Reduce this from default of 10 seconds as the Ruby jaeger - # client doesn't have overflow control, leading to very large - # messages which fail to send over UDP (max packet = 64k) - # Flush more often, with smaller packets - FLUSH_INTERVAL = 5 - - def self.create_tracer(service_name, options) - kwargs = { - service_name: service_name, - sampler: get_sampler(options[:sampler], options[:sampler_param]), - reporter: get_reporter(service_name, options[:http_endpoint], options[:udp_endpoint]), - }.compact - - extra_params = options.except(:sampler, :sampler_param, :http_endpoint, :udp_endpoint, :strict_parsing, :debug) - if extra_params.present? - message = "jaeger tracer: invalid option: #{extra_params.keys.join(", ")}" - - raise message if options[:strict_parsing] - - warn message - end - - Jaeger::Client.build(kwargs) - end - - def self.get_sampler(sampler_type, sampler_param) - case sampler_type - when "probabilistic" - sampler_rate = sampler_param ? sampler_param.to_f : DEFAULT_PROBABILISTIC_RATE - Jaeger::Samplers::Probabilistic.new(rate: sampler_rate) - when "const" - const_value = sampler_param == "1" - Jaeger::Samplers::Const.new(const_value) - end - end - private_class_method :get_sampler - - def self.get_reporter(service_name, http_endpoint, udp_endpoint) - encoder = Jaeger::Encoders::ThriftEncoder.new(service_name: service_name) - - if http_endpoint.present? - sender = get_http_sender(encoder, http_endpoint) - elsif udp_endpoint.present? - sender = get_udp_sender(encoder, udp_endpoint) - else - return nil - end - - Jaeger::Reporters::RemoteReporter.new(sender: sender, flush_interval: FLUSH_INTERVAL) - end - private_class_method :get_reporter - - def self.get_http_sender(encoder, address) - Jaeger::HttpSender.new(url: address, encoder: encoder, logger: Logger.new(STDOUT)) - end - private_class_method :get_http_sender - - def self.get_udp_sender(encoder, address) - pair = address.split(":", 2) - host = pair[0] - port = pair[1] ? pair[1].to_i : DEFAULT_UDP_PORT - - Jaeger::UdpSender.new(host: host, port: port, encoder: encoder, logger: Logger.new(STDOUT)) - end - private_class_method :get_udp_sender - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rack_middleware.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rack_middleware.rb deleted file mode 100644 index b8ae410c9d..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rack_middleware.rb +++ /dev/null @@ -1,42 +0,0 @@ -# frozen_string_literal: true - -require "opentracing" -require "active_support/all" -require "action_dispatch" - -module Labkit - module Tracing - # RackMiddleware is a rack middleware component for - # instrumenting incoming http requests into a Rails/Rack - # server - class RackMiddleware - REQUEST_METHOD = "REQUEST_METHOD" - - def initialize(app) - @app = app - end - - def call(env) - method = env[REQUEST_METHOD] - - context = TracingUtils.tracer.extract(OpenTracing::FORMAT_RACK, env) - tags = { "component" => "rack", "span.kind" => "server", "http.method" => method, "http.url" => self.class.build_sanitized_url_from_env(env) } - - TracingUtils.with_tracing(operation_name: "http:#{method}", child_of: context, tags: tags) do |span| - @app.call(env).tap { |status_code, _headers, _body| span.set_tag("http.status_code", status_code) } - end - end - - # Generate a sanitized (safe) request URL from the rack environment - def self.build_sanitized_url_from_env(env) - request = ::ActionDispatch::Request.new(env) - - original_url = request.original_url - uri = URI.parse(original_url) - uri.query = request.filtered_parameters.to_query if uri.query.present? - - uri.to_s - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails.rb deleted file mode 100644 index 860011e59b..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails.rb +++ /dev/null @@ -1,12 +0,0 @@ -# frozen_string_literal: true - -module Labkit - module Tracing - # Rails provides classes for instrumenting Rails events - module Rails - autoload :ActionViewSubscriber, "labkit/tracing/rails/action_view_subscriber" - autoload :ActiveRecordSubscriber, "labkit/tracing/rails/active_record_subscriber" - autoload :RailsCommon, "labkit/tracing/rails/rails_common" - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/action_view_subscriber.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/action_view_subscriber.rb deleted file mode 100644 index 9eb69d5845..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/action_view_subscriber.rb +++ /dev/null @@ -1,70 +0,0 @@ -# frozen_string_literal: true - -module Labkit - module Tracing - module Rails - # ActionViewSubscriber bridges action view notifications to - # the distributed tracing subsystem - class ActionViewSubscriber - include RailsCommon - - COMPONENT_TAG = "ActionView" - RENDER_TEMPLATE_NOTIFICATION_TOPIC = "render_template.action_view" - RENDER_COLLECTION_NOTIFICATION_TOPIC = "render_collection.action_view" - RENDER_PARTIAL_NOTIFICATION_TOPIC = "render_partial.action_view" - - # Instruments Rails ActionView events for opentracing. - # Returns a lambda, which, when called will unsubscribe from the notifications - def self.instrument - subscriber = new - - subscriptions = [ - ActiveSupport::Notifications.subscribe(RENDER_TEMPLATE_NOTIFICATION_TOPIC) do |_, start, finish, _, payload| - subscriber.notify_render_template(start, finish, payload) - end, - ActiveSupport::Notifications.subscribe(RENDER_COLLECTION_NOTIFICATION_TOPIC) do |_, start, finish, _, payload| - subscriber.notify_render_collection(start, finish, payload) - end, - ActiveSupport::Notifications.subscribe(RENDER_PARTIAL_NOTIFICATION_TOPIC) do |_, start, finish, _, payload| - subscriber.notify_render_partial(start, finish, payload) - end, - ] - - create_unsubscriber subscriptions - end - - # For more information on the payloads: https://guides.rubyonrails.org/active_support_instrumentation.html - def notify_render_template(start, finish, payload) - generate_span_for_notification("render_template", start, finish, payload, tags_for_render_template(payload)) - end - - def notify_render_collection(start, finish, payload) - generate_span_for_notification("render_collection", start, finish, payload, tags_for_render_collection(payload)) - end - - def notify_render_partial(start, finish, payload) - generate_span_for_notification("render_partial", start, finish, payload, tags_for_render_partial(payload)) - end - - private - - def tags_for_render_template(payload) - { "component" => COMPONENT_TAG, "template.id" => payload[:identifier], "template.layout" => payload[:layout] } - end - - def tags_for_render_collection(payload) - { - "component" => COMPONENT_TAG, - "template.id" => payload[:identifier], - "template.count" => payload[:count] || 0, - "template.cache.hits" => payload[:cache_hits] || 0, - } - end - - def tags_for_render_partial(payload) - { "component" => COMPONENT_TAG, "template.id" => payload[:identifier] } - end - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/active_record_subscriber.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/active_record_subscriber.rb deleted file mode 100644 index f4cd04b0c9..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/active_record_subscriber.rb +++ /dev/null @@ -1,52 +0,0 @@ -# frozen_string_literal: true - -module Labkit - module Tracing - module Rails - # ActiveRecordSubscriber bridges active record notifications to - # the distributed tracing subsystem - class ActiveRecordSubscriber - include RailsCommon - - ACTIVE_RECORD_NOTIFICATION_TOPIC = "sql.active_record" - OPERATION_NAME_PREFIX = "active_record:" - DEFAULT_OPERATION_NAME = "sqlquery" - - # Instruments Rails ActiveRecord events for opentracing. - # Returns a lambda, which, when called will unsubscribe from the notifications - def self.instrument - subscriber = new - - subscription = - ActiveSupport::Notifications.subscribe(ACTIVE_RECORD_NOTIFICATION_TOPIC) do |_, start, finish, _, payload| - subscriber.notify(start, finish, payload) - end - - create_unsubscriber [subscription] - end - - # For more information on the payloads: https://guides.rubyonrails.org/active_support_instrumentation.html - def notify(start, finish, payload) - generate_span_for_notification(notification_name(payload), start, finish, payload, tags_for_notification(payload)) - end - - private - - def notification_name(payload) - OPERATION_NAME_PREFIX + (payload[:name].presence || DEFAULT_OPERATION_NAME) - end - - def tags_for_notification(payload) - { - "component" => "ActiveRecord", - "span.kind" => "client", - "db.type" => "sql", - "db.connection_id" => payload[:connection_id], - "db.cached" => payload[:cached] || false, - "db.statement" => payload[:sql], - } - end - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/rails_common.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/rails_common.rb deleted file mode 100644 index bb6c56e4ab..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/rails/rails_common.rb +++ /dev/null @@ -1,27 +0,0 @@ -# frozen_string_literal: true - -require "active_support/all" - -module Labkit - module Tracing - module Rails - # RailsCommon is a mixin for providing instrumentation - # functionality for the rails instrumentation classes - module RailsCommon - extend ActiveSupport::Concern - - class_methods do - def create_unsubscriber(subscriptions) - -> { subscriptions.each { |subscriber| ActiveSupport::Notifications.unsubscribe(subscriber) } } - end - end - - def generate_span_for_notification(operation_name, start, finish, payload, tags) - exception = payload[:exception] - - TracingUtils.postnotify_span(operation_name, start, finish, tags: tags, exception: exception) - end - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq.rb deleted file mode 100644 index 32bf32f8b1..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq.rb +++ /dev/null @@ -1,13 +0,0 @@ -# frozen_string_literal: true - -module Labkit - module Tracing - # Sidekiq provides classes for instrumenting Sidekiq client and server - # functionality - module Sidekiq - autoload :ClientMiddleware, "labkit/tracing/sidekiq/client_middleware" - autoload :ServerMiddleware, "labkit/tracing/sidekiq/server_middleware" - autoload :SidekiqCommon, "labkit/tracing/sidekiq/sidekiq_common" - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/client_middleware.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/client_middleware.rb deleted file mode 100644 index af34c9c29b..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/client_middleware.rb +++ /dev/null @@ -1,27 +0,0 @@ -# frozen_string_literal: true - -require "opentracing" - -module Labkit - module Tracing - module Sidekiq - # ClientMiddleware provides a sidekiq client middleware for - # instrumenting distributed tracing calls made from the client - # application - class ClientMiddleware - include SidekiqCommon - - SPAN_KIND = "client" - - def call(_worker_class, job, _queue, _redis_pool) - TracingUtils.with_tracing(operation_name: "sidekiq:#{job["class"]}", tags: tags_from_job(job, SPAN_KIND)) do |span| - # Inject the details directly into the job - TracingUtils.tracer.inject(span.context, OpenTracing::FORMAT_TEXT_MAP, job) - - yield - end - end - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/server_middleware.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/server_middleware.rb deleted file mode 100644 index 94eb807ddd..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/server_middleware.rb +++ /dev/null @@ -1,24 +0,0 @@ -# frozen_string_literal: true - -require "opentracing" - -module Labkit - module Tracing - module Sidekiq - # ServerMiddleware provides a sidekiq server middleware for - # instrumenting distributed tracing calls when they are - # executed by the Sidekiq server - class ServerMiddleware - include SidekiqCommon - - SPAN_KIND = "server" - - def call(_worker, job, _queue) - context = TracingUtils.tracer.extract(OpenTracing::FORMAT_TEXT_MAP, job) - - TracingUtils.with_tracing(operation_name: "sidekiq:#{job["class"]}", child_of: context, tags: tags_from_job(job, SPAN_KIND)) { |_span| yield } - end - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/sidekiq_common.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/sidekiq_common.rb deleted file mode 100644 index 18e8e38eb2..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/sidekiq/sidekiq_common.rb +++ /dev/null @@ -1,21 +0,0 @@ -# frozen_string_literal: true - -module Labkit - module Tracing - module Sidekiq - # SidekiqCommon is a mixin for the sidekiq middleware components - module SidekiqCommon - def tags_from_job(job, kind) - { - "component" => "sidekiq", - "span.kind" => kind, - "sidekiq.queue" => job["queue"], - "sidekiq.jid" => job["jid"], - "sidekiq.retry" => job["retry"].to_s, - "sidekiq.args" => job["args"]&.join(", "), - } - end - end - end - end -end diff --git a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/tracing_utils.rb b/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/tracing_utils.rb deleted file mode 100644 index 3538c4aa8b..0000000000 --- a/debian/gems-compat/gitlab-labkit-0.2.0/lib/labkit/tracing/tracing_utils.rb +++ /dev/null @@ -1,65 +0,0 @@ -# frozen_string_literal: true - -require "opentracing" - -module Labkit - module Tracing - # Internal methods for tracing. This is not part of the LabKit public API. - # For internal usage only - class TracingUtils - # Convience method for running a block with a span - def self.with_tracing(operation_name:, tags:, child_of: nil) - scope = tracer.start_active_span(operation_name, child_of: child_of, tags: tags) - span = scope.span - - # Add correlation details to the span if we have them - correlation_id = Labkit::Correlation::CorrelationId.current_id - span.set_tag("correlation_id", correlation_id) if correlation_id - - begin - yield span - rescue StandardError => e - log_exception_on_span(span, e) - raise e - ensure - scope.close - end - end - - # Obtain a tracer instance - def self.tracer - OpenTracing.global_tracer - end - - # Generate a span retrospectively - def self.postnotify_span(operation_name, start_time, end_time, tags: nil, child_of: nil, exception: nil) - span = OpenTracing.start_span(operation_name, start_time: start_time, tags: tags, child_of: child_of) - - log_exception_on_span(span, exception) if exception - - span.finish(end_time: end_time) - end - - # Add exception logging to a span - def self.log_exception_on_span(span, exception) - span.set_tag("error", true) - span.log_kv(kv_tags_for_exception(exception)) - end - - # Generate key-value tags for an exception - def self.kv_tags_for_exception(exception) - case exception - when Exception - { - :"event" => "error", - :"error.kind" => exception.class.to_s, - :"message" => Labkit::Logging::Sanitizer.sanitize_field(exception.message), - :"stack" => exception.backtrace&.join('\n'), - } - else - { :"event" => "error", :"error.kind" => exception.class.to_s, :"error.object" => Labkit::Logging::Sanitizer.sanitize_field(exception.to_s) } - end - end - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/.codeclimate.yml b/debian/gems-compat/jwt-2.1.0/.codeclimate.yml deleted file mode 100644 index c652722d2a..0000000000 --- a/debian/gems-compat/jwt-2.1.0/.codeclimate.yml +++ /dev/null @@ -1,20 +0,0 @@ -engines: - rubocop: - enabled: true - golint: - enabled: false - gofmt: - enabled: false - eslint: - enabled: false - csslint: - enabled: false - -ratings: - paths: - - lib/** - - "**.rb" - -exclude_paths: - - spec/**/* - - vendor/**/* diff --git a/debian/gems-compat/jwt-2.1.0/.ebert.yml b/debian/gems-compat/jwt-2.1.0/.ebert.yml deleted file mode 100644 index 25e7a3448b..0000000000 --- a/debian/gems-compat/jwt-2.1.0/.ebert.yml +++ /dev/null @@ -1,18 +0,0 @@ -styleguide: excpt/linters -engines: - reek: - enabled: true - fixme: - enabled: true - rubocop: - enabled: true - channel: rubocop-0-49 - duplication: - config: - languages: - - ruby - enabled: true - remark-lint: - enabled: true -exclude_paths: -- spec diff --git a/debian/gems-compat/jwt-2.1.0/.gitignore b/debian/gems-compat/jwt-2.1.0/.gitignore deleted file mode 100644 index 6976ec1988..0000000000 --- a/debian/gems-compat/jwt-2.1.0/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -.idea/ -jwt.gemspec -pkg -Gemfile.lock -coverage/ -.DS_Store -.rbenv-gemsets -.ruby-version -.vscode/ -.bundle -bin/ \ No newline at end of file diff --git a/debian/gems-compat/jwt-2.1.0/.reek.yml b/debian/gems-compat/jwt-2.1.0/.reek.yml deleted file mode 100644 index 5ee5309876..0000000000 --- a/debian/gems-compat/jwt-2.1.0/.reek.yml +++ /dev/null @@ -1,40 +0,0 @@ ---- -TooManyStatements: - max_statements: 10 -UncommunicativeMethodName: - reject: - - !ruby/regexp /^[a-z]$/ - - !ruby/regexp /[0-9]$/ -UncommunicativeParameterName: - reject: - - !ruby/regexp /^.$/ - - !ruby/regexp /[0-9]$/ - - !ruby/regexp /^_/ -UncommunicativeVariableName: - reject: - - !ruby/regexp /^.$/ - - !ruby/regexp /[0-9]$/ -UtilityFunction: - enabled: false -LongParameterList: - enabled: false -DuplicateMethodCall: - max_calls: 2 -IrresponsibleModule: - enabled: false -NestedIterators: - max_allowed_nesting: 2 -PrimaDonnaMethod: - enabled: false -UnusedParameters: - enabled: false -FeatureEnvy: - enabled: false -ControlParameter: - enabled: false -UnusedPrivateMethod: - enabled: false -InstanceVariableAssumption: - exclude: - - !ruby/regexp /Controller$/ - - !ruby/regexp /Mailer$/s \ No newline at end of file diff --git a/debian/gems-compat/jwt-2.1.0/.rspec b/debian/gems-compat/jwt-2.1.0/.rspec deleted file mode 100644 index 4e1e0d2f72..0000000000 --- a/debian/gems-compat/jwt-2.1.0/.rspec +++ /dev/null @@ -1 +0,0 @@ ---color diff --git a/debian/gems-compat/jwt-2.1.0/.rubocop.yml b/debian/gems-compat/jwt-2.1.0/.rubocop.yml deleted file mode 100644 index 943b7208ad..0000000000 --- a/debian/gems-compat/jwt-2.1.0/.rubocop.yml +++ /dev/null @@ -1,98 +0,0 @@ -AllCops: - Exclude: - - 'bin/**/*' - - 'db/**/*' - - 'config/**/*' - - 'script/**/*' - -Rails: - Enabled: true - -Style/AlignParameters: - EnforcedStyle: with_fixed_indentation - -Style/CaseIndentation: - EnforcedStyle: end - -Style/AsciiComments: - Enabled: false - -Style/IndentHash: - Enabled: false - -Style/CollectionMethods: - Enabled: true - PreferredMethods: - inject: 'inject' - -Style/Documentation: - Enabled: false - -Style/BlockDelimiters: - Exclude: - - spec/**/*_spec.rb - -Style/BracesAroundHashParameters: - Exclude: - - spec/**/*_spec.rb - -Style/GuardClause: - Enabled: false - -Style/IfUnlessModifier: - Enabled: false - -Style/SpaceInsideHashLiteralBraces: - Enabled: false - -Style/Lambda: - Enabled: false - -Style/RaiseArgs: - Enabled: false - -Style/SignalException: - Enabled: false - -Metrics/AbcSize: - Max: 20 - -Metrics/ClassLength: - Max: 100 - -Metrics/ModuleLength: - Max: 100 - -Metrics/LineLength: - Enabled: false - -Metrics/MethodLength: - Max: 15 - -Style/SingleLineBlockParams: - Enabled: false - -Lint/EndAlignment: - EnforcedStyleAlignWith: variable - -Style/FormatString: - Enabled: false - -Style/MultilineMethodCallIndentation: - EnforcedStyle: indented - -Style/MultilineOperationIndentation: - EnforcedStyle: indented - -Style/WordArray: - Enabled: false - -Style/RedundantSelf: - Enabled: false - -Style/AlignHash: - Enabled: true - EnforcedLastArgumentHashStyle: always_ignore - -Style/TrivialAccessors: - AllowPredicates: true \ No newline at end of file diff --git a/debian/gems-compat/jwt-2.1.0/.travis.yml b/debian/gems-compat/jwt-2.1.0/.travis.yml deleted file mode 100644 index d53fb18efa..0000000000 --- a/debian/gems-compat/jwt-2.1.0/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -sudo: required -cache: bundler -dist: trusty -language: ruby -rvm: - - 2.2.0 - - 2.3.0 - - 2.4.0 -script: "bundle exec rspec && bundle exec codeclimate-test-reporter" -before_install: - - sudo add-apt-repository ppa:chris-lea/libsodium -y - - sudo apt-get update -q - - sudo apt-get install libsodium-dev -y - - gem install bundler diff --git a/debian/gems-compat/jwt-2.1.0/CHANGELOG.md b/debian/gems-compat/jwt-2.1.0/CHANGELOG.md deleted file mode 100644 index 5c69bec2f5..0000000000 --- a/debian/gems-compat/jwt-2.1.0/CHANGELOG.md +++ /dev/null @@ -1,476 +0,0 @@ -# Change Log - -## [2.1.0](https://github.com/jwt/ruby-jwt/tree/2.1.0) (2017-10-06) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.0.0...2.1.0) - -**Implemented enhancements:** - -- Ed25519 support planned? [\#217](https://github.com/jwt/ruby-jwt/issues/217) -- Verify JTI Proc [\#207](https://github.com/jwt/ruby-jwt/issues/207) -- Allow a list of algorithms for decode [\#241](https://github.com/jwt/ruby-jwt/pull/241) ([lautis](https://github.com/lautis)) -- verify takes 2 params, second being payload closes: \#207 [\#238](https://github.com/jwt/ruby-jwt/pull/238) ([ab320012](https://github.com/ab320012)) -- simplified logic for keyfinder [\#237](https://github.com/jwt/ruby-jwt/pull/237) ([ab320012](https://github.com/ab320012)) -- Show backtrace if rbnacl-libsodium not loaded [\#231](https://github.com/jwt/ruby-jwt/pull/231) ([buzztaiki](https://github.com/buzztaiki)) -- Support for ED25519 [\#229](https://github.com/jwt/ruby-jwt/pull/229) ([ab320012](https://github.com/ab320012)) - -**Fixed bugs:** - -- JWT.encode failing on encode for string [\#235](https://github.com/jwt/ruby-jwt/issues/235) -- The README says it uses an algorithm by default [\#226](https://github.com/jwt/ruby-jwt/issues/226) -- Fix string payload issue [\#236](https://github.com/jwt/ruby-jwt/pull/236) ([excpt](https://github.com/excpt)) - -**Closed issues:** - -- Change from 1.5.6 to 2.0.0 and appears a "Completed 401 Unauthorized" [\#240](https://github.com/jwt/ruby-jwt/issues/240) -- Why doesn't the decode function use a default algorithm? [\#227](https://github.com/jwt/ruby-jwt/issues/227) - -**Merged pull requests:** - -- Update README.md [\#242](https://github.com/jwt/ruby-jwt/pull/242) ([excpt](https://github.com/excpt)) -- Update ebert configuration [\#232](https://github.com/jwt/ruby-jwt/pull/232) ([excpt](https://github.com/excpt)) -- added algos/strategy classes + structs for inputs [\#230](https://github.com/jwt/ruby-jwt/pull/230) ([ab320012](https://github.com/ab320012)) -- Add HS256 algorithm to decode default options [\#228](https://github.com/jwt/ruby-jwt/pull/228) ([madkin10](https://github.com/madkin10)) - -## [v2.0.0](https://github.com/jwt/ruby-jwt/tree/v2.0.0) (2017-09-03) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/v2.0.0.beta1...v2.0.0) - -**Fixed bugs:** - -- Support versions outside 2.1 [\#209](https://github.com/jwt/ruby-jwt/issues/209) -- Verifying expiration without leeway throws exception [\#206](https://github.com/jwt/ruby-jwt/issues/206) -- Ruby interpreter warning [\#200](https://github.com/jwt/ruby-jwt/issues/200) -- TypeError: no implicit conversion of String into Integer [\#188](https://github.com/jwt/ruby-jwt/issues/188) -- Fix JWT.encode\(nil\) [\#203](https://github.com/jwt/ruby-jwt/pull/203) ([tmm1](https://github.com/tmm1)) - -**Closed issues:** - -- Possibility to disable claim verifications [\#222](https://github.com/jwt/ruby-jwt/issues/222) -- Proper way to verify Firebase id tokens [\#216](https://github.com/jwt/ruby-jwt/issues/216) - -**Merged pull requests:** - -- Release 2.0.0 preparations :\) [\#225](https://github.com/jwt/ruby-jwt/pull/225) ([excpt](https://github.com/excpt)) -- Skip 'exp' claim validation for array payloads [\#224](https://github.com/jwt/ruby-jwt/pull/224) ([excpt](https://github.com/excpt)) -- Use a default leeway of 0 [\#223](https://github.com/jwt/ruby-jwt/pull/223) ([travisofthenorth](https://github.com/travisofthenorth)) -- Fix reported codesmells [\#221](https://github.com/jwt/ruby-jwt/pull/221) ([excpt](https://github.com/excpt)) -- Add fancy gem version badge [\#220](https://github.com/jwt/ruby-jwt/pull/220) ([excpt](https://github.com/excpt)) -- Add missing dist option to .travis.yml [\#219](https://github.com/jwt/ruby-jwt/pull/219) ([excpt](https://github.com/excpt)) -- Fix ruby version requirements in gemspec file [\#218](https://github.com/jwt/ruby-jwt/pull/218) ([excpt](https://github.com/excpt)) -- Fix a little typo in the readme [\#214](https://github.com/jwt/ruby-jwt/pull/214) ([RyanBrushett](https://github.com/RyanBrushett)) -- Update README.md [\#212](https://github.com/jwt/ruby-jwt/pull/212) ([zuzannast](https://github.com/zuzannast)) -- Fix typo in HS512256 algorithm description [\#211](https://github.com/jwt/ruby-jwt/pull/211) ([ojab](https://github.com/ojab)) -- Allow configuration of multiple acceptable issuers [\#210](https://github.com/jwt/ruby-jwt/pull/210) ([ojab](https://github.com/ojab)) -- Enforce `exp` to be an `Integer` [\#205](https://github.com/jwt/ruby-jwt/pull/205) ([lucasmazza](https://github.com/lucasmazza)) -- ruby 1.9.3 support message upd [\#204](https://github.com/jwt/ruby-jwt/pull/204) ([maokomioko](https://github.com/maokomioko)) -- Guard against partially loaded RbNaCl when failing to load libsodium [\#202](https://github.com/jwt/ruby-jwt/pull/202) ([Dorian](https://github.com/Dorian)) - -## [v2.0.0.beta1](https://github.com/jwt/ruby-jwt/tree/v2.0.0.beta1) (2017-02-27) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.6...v2.0.0.beta1) - -**Implemented enhancements:** - -- Error with method sign for String [\#171](https://github.com/jwt/ruby-jwt/issues/171) -- Refactor the encondig code [\#121](https://github.com/jwt/ruby-jwt/issues/121) -- Refactor [\#196](https://github.com/jwt/ruby-jwt/pull/196) ([EmilioCristalli](https://github.com/EmilioCristalli)) -- Move signature logic to its own module [\#195](https://github.com/jwt/ruby-jwt/pull/195) ([EmilioCristalli](https://github.com/EmilioCristalli)) -- Add options for claim-specific leeway [\#187](https://github.com/jwt/ruby-jwt/pull/187) ([EmilioCristalli](https://github.com/EmilioCristalli)) -- Add user friendly encode error if private key is a String, \#171 [\#176](https://github.com/jwt/ruby-jwt/pull/176) ([xamenrax](https://github.com/xamenrax)) -- Return empty string if signature less than byte\_size \#155 [\#175](https://github.com/jwt/ruby-jwt/pull/175) ([xamenrax](https://github.com/xamenrax)) -- Remove 'typ' optional parameter [\#174](https://github.com/jwt/ruby-jwt/pull/174) ([xamenrax](https://github.com/xamenrax)) -- Pass payload to keyfinder [\#172](https://github.com/jwt/ruby-jwt/pull/172) ([CodeMonkeySteve](https://github.com/CodeMonkeySteve)) -- Use RbNaCl for HMAC if available with fallback to OpenSSL [\#149](https://github.com/jwt/ruby-jwt/pull/149) ([mwpastore](https://github.com/mwpastore)) - -**Fixed bugs:** - -- ruby-jwt::raw\_to\_asn1: Fails for signatures less than byte\_size [\#155](https://github.com/jwt/ruby-jwt/issues/155) -- The leeway parameter is applies to all time based verifications [\#129](https://github.com/jwt/ruby-jwt/issues/129) -- Add options for claim-specific leeway [\#187](https://github.com/jwt/ruby-jwt/pull/187) ([EmilioCristalli](https://github.com/EmilioCristalli)) -- Make algorithm option required to verify signature [\#184](https://github.com/jwt/ruby-jwt/pull/184) ([EmilioCristalli](https://github.com/EmilioCristalli)) -- Validate audience when payload is a scalar and options is an array [\#183](https://github.com/jwt/ruby-jwt/pull/183) ([steti](https://github.com/steti)) - -**Closed issues:** - -- Different encoded value between servers with same password [\#197](https://github.com/jwt/ruby-jwt/issues/197) -- Signature is different at each run [\#190](https://github.com/jwt/ruby-jwt/issues/190) -- Include custom headers with password [\#189](https://github.com/jwt/ruby-jwt/issues/189) -- can't create token - 'NotImplementedError: Unsupported signing method' [\#186](https://github.com/jwt/ruby-jwt/issues/186) -- Why jwt depends on json \< 2.0 ? [\#179](https://github.com/jwt/ruby-jwt/issues/179) -- Cannot verify JWT at all?? [\#177](https://github.com/jwt/ruby-jwt/issues/177) -- verify\_iss: true is raising JWT::DecodeError instead of JWT::InvalidIssuerError [\#170](https://github.com/jwt/ruby-jwt/issues/170) - -**Merged pull requests:** - -- Version bump 2.0.0.beta1 [\#199](https://github.com/jwt/ruby-jwt/pull/199) ([excpt](https://github.com/excpt)) -- Update CHANGELOG.md and minor fixes [\#198](https://github.com/jwt/ruby-jwt/pull/198) ([excpt](https://github.com/excpt)) -- Add Codacy coverage reporter [\#194](https://github.com/jwt/ruby-jwt/pull/194) ([excpt](https://github.com/excpt)) -- Add minimum required ruby version to gemspec [\#193](https://github.com/jwt/ruby-jwt/pull/193) ([excpt](https://github.com/excpt)) -- Code smell fixes [\#192](https://github.com/jwt/ruby-jwt/pull/192) ([excpt](https://github.com/excpt)) -- Version bump to 2.0.0.dev [\#191](https://github.com/jwt/ruby-jwt/pull/191) ([excpt](https://github.com/excpt)) -- Basic encode module refactoring \#121 [\#182](https://github.com/jwt/ruby-jwt/pull/182) ([xamenrax](https://github.com/xamenrax)) -- Fix travis ci build configuration [\#181](https://github.com/jwt/ruby-jwt/pull/181) ([excpt](https://github.com/excpt)) -- Fix travis ci build configuration [\#180](https://github.com/jwt/ruby-jwt/pull/180) ([excpt](https://github.com/excpt)) -- Fix typo in README [\#178](https://github.com/jwt/ruby-jwt/pull/178) ([tomeduarte](https://github.com/tomeduarte)) -- Fix code style [\#173](https://github.com/jwt/ruby-jwt/pull/173) ([excpt](https://github.com/excpt)) -- Fixed a typo in a spec name [\#169](https://github.com/jwt/ruby-jwt/pull/169) ([Mingan](https://github.com/Mingan)) - -## [v1.5.6](https://github.com/jwt/ruby-jwt/tree/v1.5.6) (2016-09-19) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.5...v1.5.6) - -**Fixed bugs:** - -- Fix missing symbol handling in aud verify code [\#166](https://github.com/jwt/ruby-jwt/pull/166) ([excpt](https://github.com/excpt)) - -**Merged pull requests:** - -- Update changelog [\#168](https://github.com/jwt/ruby-jwt/pull/168) ([excpt](https://github.com/excpt)) -- Fix rubocop code smells [\#167](https://github.com/jwt/ruby-jwt/pull/167) ([excpt](https://github.com/excpt)) - -## [v1.5.5](https://github.com/jwt/ruby-jwt/tree/v1.5.5) (2016-09-16) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.4...v1.5.5) - -**Implemented enhancements:** - -- JWT.decode always raises JWT::ExpiredSignature for tokens created with Time objects passed as the `exp` parameter [\#148](https://github.com/jwt/ruby-jwt/issues/148) - -**Fixed bugs:** - -- expiration check does not give "Signature has expired" error for the exact time of expiration [\#157](https://github.com/jwt/ruby-jwt/issues/157) -- JTI claim broken? [\#152](https://github.com/jwt/ruby-jwt/issues/152) -- Audience Claim broken? [\#151](https://github.com/jwt/ruby-jwt/issues/151) -- 1.5.3 breaks compatibility with 1.5.2 [\#133](https://github.com/jwt/ruby-jwt/issues/133) -- Version 1.5.3 breaks 1.9.3 compatibility, but not documented as such [\#132](https://github.com/jwt/ruby-jwt/issues/132) -- Fix: exp claim check [\#161](https://github.com/jwt/ruby-jwt/pull/161) ([excpt](https://github.com/excpt)) - -**Closed issues:** - -- Rendering Json Results in JWT::DecodeError [\#162](https://github.com/jwt/ruby-jwt/issues/162) -- PHP Libraries [\#154](https://github.com/jwt/ruby-jwt/issues/154) -- \[security\] Signature verified after expiration/sub/iss checks [\#153](https://github.com/jwt/ruby-jwt/issues/153) -- Is ruby-jwt thread-safe? [\#150](https://github.com/jwt/ruby-jwt/issues/150) -- JWT 1.5.3 [\#143](https://github.com/jwt/ruby-jwt/issues/143) -- gem install v 1.5.3 returns error [\#141](https://github.com/jwt/ruby-jwt/issues/141) -- Adding a CHANGELOG [\#140](https://github.com/jwt/ruby-jwt/issues/140) - -**Merged pull requests:** - -- Bump version [\#165](https://github.com/jwt/ruby-jwt/pull/165) ([excpt](https://github.com/excpt)) -- Improve error message for exp claim in payload [\#164](https://github.com/jwt/ruby-jwt/pull/164) ([excpt](https://github.com/excpt)) -- Fix \#151 and code refactoring [\#163](https://github.com/jwt/ruby-jwt/pull/163) ([excpt](https://github.com/excpt)) -- Signature validation before claim verification [\#160](https://github.com/jwt/ruby-jwt/pull/160) ([excpt](https://github.com/excpt)) -- Create specs for README.md examples [\#159](https://github.com/jwt/ruby-jwt/pull/159) ([excpt](https://github.com/excpt)) -- Tiny Readme Improvement [\#156](https://github.com/jwt/ruby-jwt/pull/156) ([b264](https://github.com/b264)) -- Added test execution to Rakefile [\#147](https://github.com/jwt/ruby-jwt/pull/147) ([jabbrwcky](https://github.com/jabbrwcky)) -- Add more bling bling to the site [\#146](https://github.com/jwt/ruby-jwt/pull/146) ([excpt](https://github.com/excpt)) -- Bump version [\#145](https://github.com/jwt/ruby-jwt/pull/145) ([excpt](https://github.com/excpt)) -- Add first content and basic layout [\#144](https://github.com/jwt/ruby-jwt/pull/144) ([excpt](https://github.com/excpt)) -- Add a changelog file [\#142](https://github.com/jwt/ruby-jwt/pull/142) ([excpt](https://github.com/excpt)) -- Return decoded\_segments [\#139](https://github.com/jwt/ruby-jwt/pull/139) ([akostrikov](https://github.com/akostrikov)) - -## [v1.5.4](https://github.com/jwt/ruby-jwt/tree/v1.5.4) (2016-03-24) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/v1.5.3...v1.5.4) - -**Closed issues:** - -- 404 at https://rubygems.global.ssl.fastly.net/gems/jwt-1.5.3.gem [\#137](https://github.com/jwt/ruby-jwt/issues/137) - -**Merged pull requests:** - -- Update README.md [\#138](https://github.com/jwt/ruby-jwt/pull/138) ([excpt](https://github.com/excpt)) -- Fix base64url\_decode [\#136](https://github.com/jwt/ruby-jwt/pull/136) ([excpt](https://github.com/excpt)) -- Fix ruby 1.9.3 compatibility [\#135](https://github.com/jwt/ruby-jwt/pull/135) ([excpt](https://github.com/excpt)) -- iat can be a float value [\#134](https://github.com/jwt/ruby-jwt/pull/134) ([llimllib](https://github.com/llimllib)) - -## [v1.5.3](https://github.com/jwt/ruby-jwt/tree/v1.5.3) (2016-02-24) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.5.2...v1.5.3) - -**Implemented enhancements:** - -- Refactor obsolete code for ruby 1.8 support [\#120](https://github.com/jwt/ruby-jwt/issues/120) -- Fix "Rubocop/Metrics/CyclomaticComplexity" issue in lib/jwt.rb [\#106](https://github.com/jwt/ruby-jwt/issues/106) -- Fix "Rubocop/Metrics/CyclomaticComplexity" issue in lib/jwt.rb [\#105](https://github.com/jwt/ruby-jwt/issues/105) -- Allow a proc to be passed for JTI verification [\#126](https://github.com/jwt/ruby-jwt/pull/126) ([yahooguntu](https://github.com/yahooguntu)) -- Relax restrictions on "jti" claim verification [\#113](https://github.com/jwt/ruby-jwt/pull/113) ([lwe](https://github.com/lwe)) - -**Closed issues:** - -- Verifications not functioning in latest release [\#128](https://github.com/jwt/ruby-jwt/issues/128) -- Base64 is generating invalid length base64 strings - cross language interop [\#127](https://github.com/jwt/ruby-jwt/issues/127) -- Digest::Digest is deprecated; use Digest [\#119](https://github.com/jwt/ruby-jwt/issues/119) -- verify\_rsa no method 'verify' for class String [\#115](https://github.com/jwt/ruby-jwt/issues/115) -- Add a changelog [\#111](https://github.com/jwt/ruby-jwt/issues/111) - -**Merged pull requests:** - -- Drop ruby 1.9.3 support [\#131](https://github.com/jwt/ruby-jwt/pull/131) ([excpt](https://github.com/excpt)) -- Allow string hash keys in validation configurations [\#130](https://github.com/jwt/ruby-jwt/pull/130) ([tpickett66](https://github.com/tpickett66)) -- Add ruby 2.3.0 for travis ci testing [\#123](https://github.com/jwt/ruby-jwt/pull/123) ([excpt](https://github.com/excpt)) -- Remove obsolete json code [\#122](https://github.com/jwt/ruby-jwt/pull/122) ([excpt](https://github.com/excpt)) -- Add fancy badges to README.md [\#118](https://github.com/jwt/ruby-jwt/pull/118) ([excpt](https://github.com/excpt)) -- Refactor decode and verify functionality [\#117](https://github.com/jwt/ruby-jwt/pull/117) ([excpt](https://github.com/excpt)) -- Drop echoe dependency for gem releases [\#116](https://github.com/jwt/ruby-jwt/pull/116) ([excpt](https://github.com/excpt)) -- Updated readme for iss/aud options [\#114](https://github.com/jwt/ruby-jwt/pull/114) ([ryanmcilmoyl](https://github.com/ryanmcilmoyl)) -- Fix error misspelling [\#112](https://github.com/jwt/ruby-jwt/pull/112) ([kat3kasper](https://github.com/kat3kasper)) - -## [jwt-1.5.2](https://github.com/jwt/ruby-jwt/tree/jwt-1.5.2) (2015-10-27) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.5.1...jwt-1.5.2) - -**Implemented enhancements:** - -- Must we specify algorithm when calling decode to avoid vulnerabilities? [\#107](https://github.com/jwt/ruby-jwt/issues/107) -- Code review: Rspec test refactoring [\#85](https://github.com/jwt/ruby-jwt/pull/85) ([excpt](https://github.com/excpt)) - -**Fixed bugs:** - -- aud verifies if aud is passed in, :sub does not [\#102](https://github.com/jwt/ruby-jwt/issues/102) -- iat check does not use leeway so nbf could pass, but iat fail [\#83](https://github.com/jwt/ruby-jwt/issues/83) - -**Closed issues:** - -- Test ticket from Code Climate [\#104](https://github.com/jwt/ruby-jwt/issues/104) -- Test ticket from Code Climate [\#100](https://github.com/jwt/ruby-jwt/issues/100) -- Is it possible to decode the payload without validating the signature? [\#97](https://github.com/jwt/ruby-jwt/issues/97) -- What is audience? [\#96](https://github.com/jwt/ruby-jwt/issues/96) -- Options hash uses both symbols and strings as keys. [\#95](https://github.com/jwt/ruby-jwt/issues/95) - -**Merged pull requests:** - -- Fix incorrect `iat` examples [\#109](https://github.com/jwt/ruby-jwt/pull/109) ([kjwierenga](https://github.com/kjwierenga)) -- Update docs to include instructions for the algorithm parameter. [\#108](https://github.com/jwt/ruby-jwt/pull/108) ([aarongray](https://github.com/aarongray)) -- make sure :sub check behaves like :aud check [\#103](https://github.com/jwt/ruby-jwt/pull/103) ([skippy](https://github.com/skippy)) -- Change hash syntax [\#101](https://github.com/jwt/ruby-jwt/pull/101) ([excpt](https://github.com/excpt)) -- Include LICENSE and README.md in gem [\#99](https://github.com/jwt/ruby-jwt/pull/99) ([bkeepers](https://github.com/bkeepers)) -- Remove unused variable in the sample code. [\#98](https://github.com/jwt/ruby-jwt/pull/98) ([hypermkt](https://github.com/hypermkt)) -- Fix iat claim example [\#94](https://github.com/jwt/ruby-jwt/pull/94) ([larrylv](https://github.com/larrylv)) -- Fix wrong description in README.md [\#93](https://github.com/jwt/ruby-jwt/pull/93) ([larrylv](https://github.com/larrylv)) -- JWT and JWA are now RFC. [\#92](https://github.com/jwt/ruby-jwt/pull/92) ([aj-michael](https://github.com/aj-michael)) -- Update README.md [\#91](https://github.com/jwt/ruby-jwt/pull/91) ([nsarno](https://github.com/nsarno)) -- Fix missing verify parameter in docs [\#90](https://github.com/jwt/ruby-jwt/pull/90) ([ernie](https://github.com/ernie)) -- Iat check uses leeway. [\#89](https://github.com/jwt/ruby-jwt/pull/89) ([aj-michael](https://github.com/aj-michael)) -- nbf check allows exact time matches. [\#88](https://github.com/jwt/ruby-jwt/pull/88) ([aj-michael](https://github.com/aj-michael)) - -## [jwt-1.5.1](https://github.com/jwt/ruby-jwt/tree/jwt-1.5.1) (2015-06-22) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.5.0...jwt-1.5.1) - -**Implemented enhancements:** - -- Fix either README or source code [\#78](https://github.com/jwt/ruby-jwt/issues/78) -- Validate against draft 20 [\#38](https://github.com/jwt/ruby-jwt/issues/38) - -**Fixed bugs:** - -- ECDSA signature verification fails for valid tokens [\#84](https://github.com/jwt/ruby-jwt/issues/84) -- Shouldn't verification of additional claims, like iss, aud etc. be enforced when in options? [\#81](https://github.com/jwt/ruby-jwt/issues/81) -- Fix either README or source code [\#78](https://github.com/jwt/ruby-jwt/issues/78) -- decode fails with 'none' algorithm and verify [\#75](https://github.com/jwt/ruby-jwt/issues/75) - -**Closed issues:** - -- Doc mismatch: uninitialized constant JWT::ExpiredSignature [\#79](https://github.com/jwt/ruby-jwt/issues/79) -- TypeError when specifying a wrong algorithm [\#77](https://github.com/jwt/ruby-jwt/issues/77) -- jti verification doesn't prevent replays [\#73](https://github.com/jwt/ruby-jwt/issues/73) - -**Merged pull requests:** - -- Correctly sign ECDSA JWTs [\#87](https://github.com/jwt/ruby-jwt/pull/87) ([jurriaan](https://github.com/jurriaan)) -- fixed results of decoded tokens in readme [\#86](https://github.com/jwt/ruby-jwt/pull/86) ([piscolomo](https://github.com/piscolomo)) -- Force verification of "iss" and "aud" claims [\#82](https://github.com/jwt/ruby-jwt/pull/82) ([lwe](https://github.com/lwe)) - -## [jwt-1.5.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.5.0) (2015-05-09) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.4.1...jwt-1.5.0) - -**Implemented enhancements:** - -- Needs to support asymmetric key signatures over shared secrets [\#46](https://github.com/jwt/ruby-jwt/issues/46) -- Implement Elliptic Curve Crypto Signatures [\#74](https://github.com/jwt/ruby-jwt/pull/74) ([jtdowney](https://github.com/jtdowney)) -- Add an option to verify the signature on decode [\#71](https://github.com/jwt/ruby-jwt/pull/71) ([javawizard](https://github.com/javawizard)) - -**Closed issues:** - -- Check JWT vulnerability [\#76](https://github.com/jwt/ruby-jwt/issues/76) - -**Merged pull requests:** - -- Fixed some examples to make them copy-pastable [\#72](https://github.com/jwt/ruby-jwt/pull/72) ([jer](https://github.com/jer)) - -## [jwt-1.4.1](https://github.com/jwt/ruby-jwt/tree/jwt-1.4.1) (2015-03-12) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.4.0...jwt-1.4.1) - -**Fixed bugs:** - -- jti verification not working per the spec [\#68](https://github.com/jwt/ruby-jwt/issues/68) -- Verify ISS should be off by default [\#66](https://github.com/jwt/ruby-jwt/issues/66) - -**Merged pull requests:** - -- Fix \#66 \#68 [\#69](https://github.com/jwt/ruby-jwt/pull/69) ([excpt](https://github.com/excpt)) -- When throwing errors, mention expected/received values [\#65](https://github.com/jwt/ruby-jwt/pull/65) ([rolodato](https://github.com/rolodato)) - -## [jwt-1.4.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.4.0) (2015-03-10) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.3.0...jwt-1.4.0) - -**Closed issues:** - -- The behavior using 'json' differs from 'multi\_json' [\#41](https://github.com/jwt/ruby-jwt/issues/41) - -**Merged pull requests:** - -- Release 1.4.0 [\#64](https://github.com/jwt/ruby-jwt/pull/64) ([excpt](https://github.com/excpt)) -- Update README.md and remove dead code [\#63](https://github.com/jwt/ruby-jwt/pull/63) ([excpt](https://github.com/excpt)) -- Add 'iat/ aud/ sub/ jti' support for ruby-jwt [\#62](https://github.com/jwt/ruby-jwt/pull/62) ([ZhangHanDong](https://github.com/ZhangHanDong)) -- Add 'iss' support for ruby-jwt [\#61](https://github.com/jwt/ruby-jwt/pull/61) ([ZhangHanDong](https://github.com/ZhangHanDong)) -- Clarify .encode API in README [\#60](https://github.com/jwt/ruby-jwt/pull/60) ([jbodah](https://github.com/jbodah)) - -## [jwt-1.3.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.3.0) (2015-02-24) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.2.1...jwt-1.3.0) - -**Closed issues:** - -- Signature Verification to Return Verification Error rather than decode error [\#57](https://github.com/jwt/ruby-jwt/issues/57) -- Incorrect readme for leeway [\#55](https://github.com/jwt/ruby-jwt/issues/55) -- What is the reason behind stripping the = in base64 encoding? [\#54](https://github.com/jwt/ruby-jwt/issues/54) -- Preperations for version 2.x [\#50](https://github.com/jwt/ruby-jwt/issues/50) -- Release a new version [\#47](https://github.com/jwt/ruby-jwt/issues/47) -- Catch up for ActiveWhatever 4.1.1 series [\#40](https://github.com/jwt/ruby-jwt/issues/40) - -**Merged pull requests:** - -- raise verification error for signiture verification [\#58](https://github.com/jwt/ruby-jwt/pull/58) ([punkle](https://github.com/punkle)) -- Added support for not before claim verification [\#56](https://github.com/jwt/ruby-jwt/pull/56) ([punkle](https://github.com/punkle)) -- Preperations for version 2.x [\#49](https://github.com/jwt/ruby-jwt/pull/49) ([excpt](https://github.com/excpt)) - -## [jwt-1.2.1](https://github.com/jwt/ruby-jwt/tree/jwt-1.2.1) (2015-01-22) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.2.0...jwt-1.2.1) - -**Closed issues:** - -- JWT.encode\({"exp": 10}, "secret"\) [\#52](https://github.com/jwt/ruby-jwt/issues/52) -- JWT.encode\({"exp": 10}, "secret"\) [\#51](https://github.com/jwt/ruby-jwt/issues/51) - -**Merged pull requests:** - -- Accept expiration claims as string [\#53](https://github.com/jwt/ruby-jwt/pull/53) ([yarmand](https://github.com/yarmand)) - -## [jwt-1.2.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.2.0) (2014-11-24) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.13...jwt-1.2.0) - -**Closed issues:** - -- set token to expire [\#42](https://github.com/jwt/ruby-jwt/issues/42) - -**Merged pull requests:** - -- Added support for `exp` claim [\#45](https://github.com/jwt/ruby-jwt/pull/45) ([zshannon](https://github.com/zshannon)) -- rspec 3 breaks passing tests [\#44](https://github.com/jwt/ruby-jwt/pull/44) ([zshannon](https://github.com/zshannon)) - -## [jwt-0.1.13](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.13) (2014-05-08) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-1.0.0...jwt-0.1.13) - -**Closed issues:** - -- Semantic versioning [\#37](https://github.com/jwt/ruby-jwt/issues/37) -- Update gem to get latest changes [\#36](https://github.com/jwt/ruby-jwt/issues/36) - -## [jwt-1.0.0](https://github.com/jwt/ruby-jwt/tree/jwt-1.0.0) (2014-05-07) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.11...jwt-1.0.0) - -**Closed issues:** - -- API request - JWT::decoded\_header\(\) [\#26](https://github.com/jwt/ruby-jwt/issues/26) - -**Merged pull requests:** - -- return header along with playload after decoding [\#35](https://github.com/jwt/ruby-jwt/pull/35) ([sawyerzhang](https://github.com/sawyerzhang)) -- Raise JWT::DecodeError on nil token [\#34](https://github.com/jwt/ruby-jwt/pull/34) ([tjmw](https://github.com/tjmw)) -- Make MultiJson optional for Ruby 1.9+ [\#33](https://github.com/jwt/ruby-jwt/pull/33) ([petergoldstein](https://github.com/petergoldstein)) -- Allow access to header and payload without signature verification [\#32](https://github.com/jwt/ruby-jwt/pull/32) ([petergoldstein](https://github.com/petergoldstein)) -- Update specs to use RSpec 3.0.x syntax [\#31](https://github.com/jwt/ruby-jwt/pull/31) ([petergoldstein](https://github.com/petergoldstein)) -- Travis - Add Ruby 2.0.0, 2.1.0, Rubinius [\#30](https://github.com/jwt/ruby-jwt/pull/30) ([petergoldstein](https://github.com/petergoldstein)) - -## [jwt-0.1.11](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.11) (2014-01-17) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.10...jwt-0.1.11) - -**Closed issues:** - -- url safe encode and decode [\#28](https://github.com/jwt/ruby-jwt/issues/28) -- Release [\#27](https://github.com/jwt/ruby-jwt/issues/27) - -**Merged pull requests:** - -- fixed urlsafe base64 encoding [\#29](https://github.com/jwt/ruby-jwt/pull/29) ([tobscher](https://github.com/tobscher)) - -## [jwt-0.1.10](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.10) (2014-01-10) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.8...jwt-0.1.10) - -**Closed issues:** - -- change to signature of JWT.decode method [\#14](https://github.com/jwt/ruby-jwt/issues/14) - -**Merged pull requests:** - -- Fix warning: assigned but unused variable - e [\#25](https://github.com/jwt/ruby-jwt/pull/25) ([sferik](https://github.com/sferik)) -- Echoe doesn't define a license= method [\#24](https://github.com/jwt/ruby-jwt/pull/24) ([sferik](https://github.com/sferik)) -- Use OpenSSL::Digest instead of deprecated OpenSSL::Digest::Digest [\#23](https://github.com/jwt/ruby-jwt/pull/23) ([JuanitoFatas](https://github.com/JuanitoFatas)) -- Handle some invalid JWTs [\#22](https://github.com/jwt/ruby-jwt/pull/22) ([steved](https://github.com/steved)) -- Add MIT license to gemspec [\#21](https://github.com/jwt/ruby-jwt/pull/21) ([nycvotes-dev](https://github.com/nycvotes-dev)) -- Tweaks and improvements [\#20](https://github.com/jwt/ruby-jwt/pull/20) ([threedaymonk](https://github.com/threedaymonk)) -- Don't leave errors in OpenSSL.errors when there is a decoding error. [\#19](https://github.com/jwt/ruby-jwt/pull/19) ([lowellk](https://github.com/lowellk)) - -## [jwt-0.1.8](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.8) (2013-03-14) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.7...jwt-0.1.8) - -**Merged pull requests:** - -- Contrib and update [\#18](https://github.com/jwt/ruby-jwt/pull/18) ([threedaymonk](https://github.com/threedaymonk)) -- Verify if verify is truthy \(not just true\) [\#17](https://github.com/jwt/ruby-jwt/pull/17) ([threedaymonk](https://github.com/threedaymonk)) - -## [jwt-0.1.7](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.7) (2013-03-07) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.6...jwt-0.1.7) - -**Merged pull requests:** - -- Catch MultiJson::LoadError and reraise as JWT::DecodeError [\#16](https://github.com/jwt/ruby-jwt/pull/16) ([rwygand](https://github.com/rwygand)) - -## [jwt-0.1.6](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.6) (2013-03-05) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.5...jwt-0.1.6) - -**Merged pull requests:** - -- Fixes a theoretical timing attack [\#15](https://github.com/jwt/ruby-jwt/pull/15) ([mgates](https://github.com/mgates)) -- Use StandardError as parent for DecodeError [\#13](https://github.com/jwt/ruby-jwt/pull/13) ([Oscil8](https://github.com/Oscil8)) - -## [jwt-0.1.5](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.5) (2012-07-20) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.4...jwt-0.1.5) - -**Closed issues:** - -- Unable to specify signature header fields [\#7](https://github.com/jwt/ruby-jwt/issues/7) - -**Merged pull requests:** - -- MultiJson dependency uses ~\> but should be \>= [\#12](https://github.com/jwt/ruby-jwt/pull/12) ([sporkmonger](https://github.com/sporkmonger)) -- Oops. :-\) [\#11](https://github.com/jwt/ruby-jwt/pull/11) ([sporkmonger](https://github.com/sporkmonger)) -- Fix issue with signature verification in JRuby [\#10](https://github.com/jwt/ruby-jwt/pull/10) ([sporkmonger](https://github.com/sporkmonger)) -- Depend on MultiJson [\#9](https://github.com/jwt/ruby-jwt/pull/9) ([lautis](https://github.com/lautis)) -- Allow for custom headers on encode and decode [\#8](https://github.com/jwt/ruby-jwt/pull/8) ([dgrijalva](https://github.com/dgrijalva)) -- Missing development dependency for echoe gem. [\#6](https://github.com/jwt/ruby-jwt/pull/6) ([sporkmonger](https://github.com/sporkmonger)) - -## [jwt-0.1.4](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.4) (2011-11-11) -[Full Changelog](https://github.com/jwt/ruby-jwt/compare/jwt-0.1.3...jwt-0.1.4) - -**Merged pull requests:** - -- Fix for RSA verification [\#5](https://github.com/jwt/ruby-jwt/pull/5) ([jordan-brough](https://github.com/jordan-brough)) - -## [jwt-0.1.3](https://github.com/jwt/ruby-jwt/tree/jwt-0.1.3) (2011-06-30) -**Closed issues:** - -- signatures calculated incorrectly \(hexdigest instead of digest\) [\#1](https://github.com/jwt/ruby-jwt/issues/1) - -**Merged pull requests:** - -- Bumped a version and added a .gemspec using rake build\_gemspec [\#3](https://github.com/jwt/ruby-jwt/pull/3) ([zhitomirskiyi](https://github.com/zhitomirskiyi)) -- Added RSA support [\#2](https://github.com/jwt/ruby-jwt/pull/2) ([zhitomirskiyi](https://github.com/zhitomirskiyi)) - - - -\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* \ No newline at end of file diff --git a/debian/gems-compat/jwt-2.1.0/Gemfile b/debian/gems-compat/jwt-2.1.0/Gemfile deleted file mode 100644 index fa75df1563..0000000000 --- a/debian/gems-compat/jwt-2.1.0/Gemfile +++ /dev/null @@ -1,3 +0,0 @@ -source 'https://rubygems.org' - -gemspec diff --git a/debian/gems-compat/jwt-2.1.0/LICENSE b/debian/gems-compat/jwt-2.1.0/LICENSE deleted file mode 100644 index 927c375f49..0000000000 --- a/debian/gems-compat/jwt-2.1.0/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2011 Jeff Lindsay - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/jwt-2.1.0/Manifest b/debian/gems-compat/jwt-2.1.0/Manifest deleted file mode 100644 index c2e11dcbbe..0000000000 --- a/debian/gems-compat/jwt-2.1.0/Manifest +++ /dev/null @@ -1,8 +0,0 @@ -Rakefile -README.md -LICENSE -lib/jwt.rb -lib/jwt/json.rb -spec/spec_helper.rb -spec/jwt_spec.rb -Manifest diff --git a/debian/gems-compat/jwt-2.1.0/README.md b/debian/gems-compat/jwt-2.1.0/README.md deleted file mode 100644 index 7c81cfd834..0000000000 --- a/debian/gems-compat/jwt-2.1.0/README.md +++ /dev/null @@ -1,478 +0,0 @@ -# JWT - -[![Gem Version](https://badge.fury.io/rb/jwt.svg)](https://badge.fury.io/rb/jwt) -[![Build Status](https://travis-ci.org/jwt/ruby-jwt.svg)](https://travis-ci.org/jwt/ruby-jwt) -[![Code Climate](https://codeclimate.com/github/jwt/ruby-jwt/badges/gpa.svg)](https://codeclimate.com/github/jwt/ruby-jwt) -[![Test Coverage](https://codeclimate.com/github/jwt/ruby-jwt/badges/coverage.svg)](https://codeclimate.com/github/jwt/ruby-jwt/coverage) -[![Issue Count](https://codeclimate.com/github/jwt/ruby-jwt/badges/issue_count.svg)](https://codeclimate.com/github/jwt/ruby-jwt) - -A pure ruby implementation of the [RFC 7519 OAuth JSON Web Token (JWT)](https://tools.ietf.org/html/rfc7519) standard. - -If you have further questions related to development or usage, join us: [ruby-jwt google group](https://groups.google.com/forum/#!forum/ruby-jwt). - -## Announcements - -* Ruby 1.9.3 support was dropped at December 31st, 2016. -* Version 1.5.3 yanked. See: [#132](https://github.com/jwt/ruby-jwt/issues/132) and [#133](https://github.com/jwt/ruby-jwt/issues/133) - -## Installing - -### Using Rubygems: -```bash -sudo gem install jwt -``` - -### Using Bundler: -Add the following to your Gemfile -``` -gem 'jwt' -``` -And run `bundle install` - -## Algorithms and Usage - -The JWT spec supports NONE, HMAC, RSASSA, ECDSA and RSASSA-PSS algorithms for cryptographic signing. Currently the jwt gem supports NONE, HMAC, RSASSA and ECDSA. If you are using cryptographic signing, you need to specify the algorithm in the options hash whenever you call JWT.decode to ensure that an attacker [cannot bypass the algorithm verification step](https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/). - -See: [ JSON Web Algorithms (JWA) 3.1. "alg" (Algorithm) Header Parameter Values for JWS](https://tools.ietf.org/html/rfc7518#section-3.1) - -**NONE** - -* none - unsigned token - -```ruby -require 'jwt' - -payload = {:data => 'test'} - -# IMPORTANT: set nil as password parameter -token = JWT.encode payload, nil, 'none' - -# eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9. -puts token - -# Set password to nil and validation to false otherwise this won't work -decoded_token = JWT.decode token, nil, false - -# Array -# [ -# {"data"=>"test"}, # payload -# {"alg"=>"none"} # header -# ] -puts decoded_token -``` - -**HMAC** - -* HS256 - HMAC using SHA-256 hash algorithm -* HS512256 - HMAC using SHA-512-256 hash algorithm (only available with RbNaCl; see note below) -* HS384 - HMAC using SHA-384 hash algorithm -* HS512 - HMAC using SHA-512 hash algorithm - -```ruby -hmac_secret = 'my$ecretK3y' - -token = JWT.encode payload, hmac_secret, 'HS256' - -# eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.ZxW8go9hz3ETCSfxFxpwSkYg_602gOPKearsf6DsxgY -puts token - -decoded_token = JWT.decode token, hmac_secret, true, { :algorithm => 'HS256' } - -# Array -# [ -# {"data"=>"test"}, # payload -# {"alg"=>"HS256"} # header -# ] -puts decoded_token -``` - -Note: If [RbNaCl](https://github.com/cryptosphere/rbnacl) is loadable, ruby-jwt will use it for HMAC-SHA256, HMAC-SHA512-256, and HMAC-SHA512. RbNaCl enforces a maximum key size of 32 bytes for these algorithms. - -[RbNaCl](https://github.com/cryptosphere/rbnacl) requires -[libsodium](https://github.com/jedisct1/libsodium), it can be installed -on MacOS with `brew install libsodium`. - -**RSA** - -* RS256 - RSA using SHA-256 hash algorithm -* RS384 - RSA using SHA-384 hash algorithm -* RS512 - RSA using SHA-512 hash algorithm - -```ruby -rsa_private = OpenSSL::PKey::RSA.generate 2048 -rsa_public = rsa_private.public_key - -token = JWT.encode payload, rsa_private, 'RS256' - -# eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ0ZXN0IjoiZGF0YSJ9.c2FynXNyi6_PeKxrDGxfS3OLwQ8lTDbWBWdq7oMviCy2ZfFpzvW2E_odCWJrbLof-eplHCsKzW7MGAntHMALXgclm_Cs9i2Exi6BZHzpr9suYkrhIjwqV1tCgMBCQpdeMwIq6SyKVjgH3L51ivIt0-GDDPDH1Rcut3jRQzp3Q35bg3tcI2iVg7t3Msvl9QrxXAdYNFiS5KXH22aJZ8X_O2HgqVYBXfSB1ygTYUmKTIIyLbntPQ7R22rFko1knGWOgQCoYXwbtpuKRZVFrxX958L2gUWgb4jEQNf3fhOtkBm1mJpj-7BGst00o8g_3P2zHy-3aKgpPo1XlKQGjRrrxA -puts token - -decoded_token = JWT.decode token, rsa_public, true, { :algorithm => 'RS256' } - -# Array -# [ -# {"data"=>"test"}, # payload -# {"alg"=>"RS256"} # header -# ] -puts decoded_token -``` - -**ECDSA** - -* ES256 - ECDSA using P-256 and SHA-256 -* ES384 - ECDSA using P-384 and SHA-384 -* ES512 - ECDSA using P-521 and SHA-512 - -```ruby -ecdsa_key = OpenSSL::PKey::EC.new 'prime256v1' -ecdsa_key.generate_key -ecdsa_public = OpenSSL::PKey::EC.new ecdsa_key -ecdsa_public.private_key = nil - -token = JWT.encode payload, ecdsa_key, 'ES256' - -# eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJ0ZXN0IjoiZGF0YSJ9.MEQCIAtShrxRwP1L9SapqaT4f7hajDJH4t_rfm-YlZcNDsBNAiB64M4-JRfyS8nRMlywtQ9lHbvvec9U54KznzOe1YxTyA -puts token - -decoded_token = JWT.decode token, ecdsa_public, true, { :algorithm => 'ES256' } - -# Array -# [ -# {"test"=>"data"}, # payload -# {"alg"=>"ES256"} # header -# ] -puts decoded_token -``` - -**EDDSA** - -In order to use this algorithm you need to add the `RbNaCl` gem to you `Gemfile`. - -```ruby -gem 'rbnacl' -``` - -For more detailed installation instruction check the official [repository](https://github.com/cryptosphere/rbnacl) on GitHub. - -* ED25519 - -```ruby -private_key = RbNaCl::Signatures::Ed25519::SigningKey.new("abcdefghijklmnopqrstuvwxyzABCDEF") -public_key = private_key.verify_key -token = JWT.encode payload, private_key, 'ED25519' - -# eyJhbGciOiJFRDI1NTE5In0.eyJ0ZXN0IjoiZGF0YSJ9.-Ki0vxVOlsPXovPsYRT_9OXrLSgQd4RDAgCLY_PLmcP4q32RYy-yUUmX82ycegdekR9wo26me1wOzjmSU5nTCQ -puts token - -decoded_token = JWT.decode token, public_key, true, {:algorithm => 'ED25519' } -# Array -# [ -# {"test"=>"data"}, # payload -# {"alg"=>"ED25519"} # header -# ] - -``` - -**RSASSA-PSS** - -Not implemented. - -## Support for reserved claim names -JSON Web Token defines some reserved claim names and defines how they should be -used. JWT supports these reserved claim names: - - - 'exp' (Expiration Time) Claim - - 'nbf' (Not Before Time) Claim - - 'iss' (Issuer) Claim - - 'aud' (Audience) Claim - - 'jti' (JWT ID) Claim - - 'iat' (Issued At) Claim - - 'sub' (Subject) Claim - -## Add custom header fields -Ruby-jwt gem supports custom [header fields] (https://tools.ietf.org/html/rfc7519#section-5) -To add custom header fields you need to pass `header_fields` parameter - -```ruby -token = JWT.encode payload, key, algorithm='HS256', header_fields={} -``` - -**Example:** - -```ruby -require 'jwt' - -payload = {:data => 'test'} - -# IMPORTANT: set nil as password parameter -token = JWT.encode payload, nil, 'none', { :typ => "JWT" } - -# eyJ0eXAiOiJKV1QiLCJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9. -puts token - -# Set password to nil and validation to false otherwise this won't work -decoded_token = JWT.decode token, nil, false - -# Array -# [ -# {"data"=>"test"}, # payload -# {"typ"=>"JWT", "alg"=>"none"} # header -# ] -puts decoded_token -``` - -### Expiration Time Claim - -From [Oauth JSON Web Token 4.1.4. "exp" (Expiration Time) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.4): - -> The `exp` (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the `exp` claim requires that the current date/time MUST be before the expiration date/time listed in the `exp` claim. Implementers MAY provide for some small `leeway`, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a ***NumericDate*** value. Use of this claim is OPTIONAL. - -**Handle Expiration Claim** - -```ruby -exp = Time.now.to_i + 4 * 3600 -exp_payload = { :data => 'data', :exp => exp } - -token = JWT.encode exp_payload, hmac_secret, 'HS256' - -begin - decoded_token = JWT.decode token, hmac_secret, true, { :algorithm => 'HS256' } -rescue JWT::ExpiredSignature - # Handle expired token, e.g. logout user or deny access -end -``` - -**Adding Leeway** - -```ruby -exp = Time.now.to_i - 10 -leeway = 30 # seconds - -exp_payload = { :data => 'data', :exp => exp } - -# build expired token -token = JWT.encode exp_payload, hmac_secret, 'HS256' - -begin - # add leeway to ensure the token is still accepted - decoded_token = JWT.decode token, hmac_secret, true, { :exp_leeway => leeway, :algorithm => 'HS256' } -rescue JWT::ExpiredSignature - # Handle expired token, e.g. logout user or deny access -end -``` - -### Not Before Time Claim - -From [Oauth JSON Web Token 4.1.5. "nbf" (Not Before) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.5): - -> The `nbf` (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the `nbf` claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the `nbf` claim. Implementers MAY provide for some small `leeway`, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a ***NumericDate*** value. Use of this claim is OPTIONAL. - -**Handle Not Before Claim** - -```ruby -nbf = Time.now.to_i - 3600 -nbf_payload = { :data => 'data', :nbf => nbf } - -token = JWT.encode nbf_payload, hmac_secret, 'HS256' - -begin - decoded_token = JWT.decode token, hmac_secret, true, { :algorithm => 'HS256' } -rescue JWT::ImmatureSignature - # Handle invalid token, e.g. logout user or deny access -end -``` - -**Adding Leeway** - -```ruby -nbf = Time.now.to_i + 10 -leeway = 30 - -nbf_payload = { :data => 'data', :nbf => nbf } - -# build expired token -token = JWT.encode nbf_payload, hmac_secret, 'HS256' - -begin - # add leeway to ensure the token is valid - decoded_token = JWT.decode token, hmac_secret, true, { :nbf_leeway => leeway, :algorithm => 'HS256' } -rescue JWT::ImmatureSignature - # Handle invalid token, e.g. logout user or deny access -end -``` - -### Issuer Claim - -From [Oauth JSON Web Token 4.1.1. "iss" (Issuer) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.1): - -> The `iss` (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The `iss` value is a case-sensitive string containing a ***StringOrURI*** value. Use of this claim is OPTIONAL. - -You can pass multiple allowed issuers as an Array, verification will pass if one of them matches the `iss` value in the payload. - -```ruby -iss = 'My Awesome Company Inc. or https://my.awesome.website/' -iss_payload = { :data => 'data', :iss => iss } - -token = JWT.encode iss_payload, hmac_secret, 'HS256' - -begin - # Add iss to the validation to check if the token has been manipulated - decoded_token = JWT.decode token, hmac_secret, true, { :iss => iss, :verify_iss => true, :algorithm => 'HS256' } -rescue JWT::InvalidIssuerError - # Handle invalid token, e.g. logout user or deny access -end -``` - -### Audience Claim - -From [Oauth JSON Web Token 4.1.3. "aud" (Audience) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.3): - -> The `aud` (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the `aud` claim when this claim is present, then the JWT MUST be rejected. In the general case, the `aud` value is an array of case-sensitive strings, each containing a ***StringOrURI*** value. In the special case when the JWT has one audience, the `aud` value MAY be a single case-sensitive string containing a ***StringOrURI*** value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL. - -```ruby -aud = ['Young', 'Old'] -aud_payload = { :data => 'data', :aud => aud } - -token = JWT.encode aud_payload, hmac_secret, 'HS256' - -begin - # Add aud to the validation to check if the token has been manipulated - decoded_token = JWT.decode token, hmac_secret, true, { :aud => aud, :verify_aud => true, :algorithm => 'HS256' } -rescue JWT::InvalidAudError - # Handle invalid token, e.g. logout user or deny access - puts 'Audience Error' -end -``` - -### JWT ID Claim - -From [Oauth JSON Web Token 4.1.7. "jti" (JWT ID) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.7): - -> The `jti` (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The `jti` claim can be used to prevent the JWT from being replayed. The `jti` value is a case-sensitive string. Use of this claim is OPTIONAL. - -```ruby -# Use the secret and iat to create a unique key per request to prevent replay attacks -jti_raw = [hmac_secret, iat].join(':').to_s -jti = Digest::MD5.hexdigest(jti_raw) -jti_payload = { :data => 'data', :iat => iat, :jti => jti } - -token = JWT.encode jti_payload, hmac_secret, 'HS256' - -begin - # If :verify_jti is true, validation will pass if a JTI is present - #decoded_token = JWT.decode token, hmac_secret, true, { :verify_jti => true, :algorithm => 'HS256' } - # Alternatively, pass a proc with your own code to check if the JTI has already been used - decoded_token = JWT.decode token, hmac_secret, true, { :verify_jti => proc { |jti| my_validation_method(jti) }, :algorithm => 'HS256' } -rescue JWT::InvalidJtiError - # Handle invalid token, e.g. logout user or deny access - puts 'Error' -end - -``` - -### Issued At Claim - -From [Oauth JSON Web Token 4.1.6. "iat" (Issued At) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.6): - -> The `iat` (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a ***NumericDate*** value. Use of this claim is OPTIONAL. - -**Handle Issued At Claim** - -```ruby -iat = Time.now.to_i -iat_payload = { :data => 'data', :iat => iat } - -token = JWT.encode iat_payload, hmac_secret, 'HS256' - -begin - # Add iat to the validation to check if the token has been manipulated - decoded_token = JWT.decode token, hmac_secret, true, { :verify_iat => true, :algorithm => 'HS256' } -rescue JWT::InvalidIatError - # Handle invalid token, e.g. logout user or deny access -end -``` - -**Adding Leeway** - -```ruby -iat = Time.now.to_i + 10 -leeway = 30 # seconds - -iat_payload = { :data => 'data', :iat => iat } - -# build token issued in the future -token = JWT.encode iat_payload, hmac_secret, 'HS256' - -begin - # add leeway to ensure the token is accepted - decoded_token = JWT.decode token, hmac_secret, true, { :iat_leeway => leeway, :verify_iat => true, :algorithm => 'HS256' } -rescue JWT::InvalidIatError - # Handle invalid token, e.g. logout user or deny access -end -``` - -### Subject Claim - -From [Oauth JSON Web Token 4.1.2. "sub" (Subject) Claim](https://tools.ietf.org/html/rfc7519#section-4.1.2): - -> The `sub` (subject) claim identifies the principal that is the subject of the JWT. The Claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The sub value is a case-sensitive string containing a ***StringOrURI*** value. Use of this claim is OPTIONAL. - -```ruby -sub = 'Subject' -sub_payload = { :data => 'data', :sub => sub } - -token = JWT.encode sub_payload, hmac_secret, 'HS256' - -begin - # Add sub to the validation to check if the token has been manipulated - decoded_token = JWT.decode token, hmac_secret, true, { 'sub' => sub, :verify_sub => true, :algorithm => 'HS256' } -rescue JWT::InvalidSubError - # Handle invalid token, e.g. logout user or deny access -end -``` - -# Development and Tests - -We depend on [Bundler](http://rubygems.org/gems/bundler) for defining gemspec and performing releases to rubygems.org, which can be done with - -```bash -rake release -``` - -The tests are written with rspec. Given you have installed the dependencies via bundler, you can run tests with - -```bash -bundle exec rspec -``` - -**If you want a release cut with your PR, please include a version bump according to [Semantic Versioning](http://semver.org/)** - -## Contributors - - * Jordan Brough - * Ilya Zhitomirskiy - * Daniel Grippi - * Jeff Lindsay - * Bob Aman - * Micah Gates - * Rob Wygand - * Ariel Salomon (Oscil8) - * Paul Battley - * Zane Shannon [@zshannon](https://github.com/zshannon) - * Brian Fletcher [@punkle](https://github.com/punkle) - * Alex [@ZhangHanDong](https://github.com/ZhangHanDong) - * John Downey [@jtdowney](https://github.com/jtdowney) - * Adam Greene [@skippy](https://github.com/skippy) - * Tim Rudat [@excpt](https://github.com/excpt) - Maintainer - -## License - -MIT - -Copyright (c) 2011 Jeff Lindsay - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/jwt-2.1.0/Rakefile b/debian/gems-compat/jwt-2.1.0/Rakefile deleted file mode 100644 index 727c38a949..0000000000 --- a/debian/gems-compat/jwt-2.1.0/Rakefile +++ /dev/null @@ -1,11 +0,0 @@ -require 'bundler/gem_tasks' - -begin - require 'rspec/core/rake_task' - - RSpec::Core::RakeTask.new(:test) - - task default: :test -rescue LoadError - puts 'RSpec rake tasks not available. Please run "bundle install" to install missing dependencies.' -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt.rb deleted file mode 100644 index 730a28cd08..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt.rb +++ /dev/null @@ -1,63 +0,0 @@ -# frozen_string_literal: true - -require 'base64' -require 'jwt/decode' -require 'jwt/default_options' -require 'jwt/encode' -require 'jwt/error' -require 'jwt/signature' -require 'jwt/verify' - -# JSON Web Token implementation -# -# Should be up to date with the latest spec: -# https://tools.ietf.org/html/rfc7519 -module JWT - include JWT::DefaultOptions - - module_function - - def encode(payload, key, algorithm = 'HS256', header_fields = {}) - encoder = Encode.new payload, key, algorithm, header_fields - encoder.segments - end - - def decode(jwt, key = nil, verify = true, custom_options = {}, &keyfinder) - raise(JWT::DecodeError, 'Nil JSON web token') unless jwt - - merged_options = DEFAULT_OPTIONS.merge(custom_options) - - decoder = Decode.new jwt, verify - header, payload, signature, signing_input = decoder.decode_segments - decode_verify_signature(key, header, payload, signature, signing_input, merged_options, &keyfinder) if verify - - Verify.verify_claims(payload, merged_options) if verify - - raise(JWT::DecodeError, 'Not enough or too many segments') unless header && payload - - [payload, header] - end - - def decode_verify_signature(key, header, payload, signature, signing_input, options, &keyfinder) - algo, key = signature_algorithm_and_key(header, payload, key, &keyfinder) - - raise(JWT::IncorrectAlgorithm, 'An algorithm must be specified') if allowed_algorithms(options).empty? - raise(JWT::IncorrectAlgorithm, 'Expected a different algorithm') unless allowed_algorithms(options).include?(algo) - - Signature.verify(algo, key, signing_input, signature) - end - - def signature_algorithm_and_key(header, payload, key, &keyfinder) - key = (keyfinder.arity == 2 ? yield(header, payload) : yield(header)) if keyfinder - raise JWT::DecodeError, 'No verification key available' unless key - [header['alg'], key] - end - - def allowed_algorithms(options) - if options.key?(:algorithm) - [options[:algorithm]] - else - options[:algorithms] || [] - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/ecdsa.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/ecdsa.rb deleted file mode 100644 index d7a5ea7593..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/ecdsa.rb +++ /dev/null @@ -1,35 +0,0 @@ -module JWT - module Algos - module Ecdsa - module_function - - SUPPORTED = %(ES256 ES384 ES512).freeze - NAMED_CURVES = { - 'prime256v1' => 'ES256', - 'secp384r1' => 'ES384', - 'secp521r1' => 'ES512' - }.freeze - - def sign(to_sign) - algorithm, msg, key = to_sign.values - key_algorithm = NAMED_CURVES[key.group.curve_name] - if algorithm != key_algorithm - raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{key_algorithm} signing key was provided" - end - - digest = OpenSSL::Digest.new(algorithm.sub('ES', 'sha')) - SecurityUtils.asn1_to_raw(key.dsa_sign_asn1(digest.digest(msg)), key) - end - - def verify(to_verify) - algorithm, public_key, signing_input, signature = to_verify.values - key_algorithm = NAMED_CURVES[public_key.group.curve_name] - if algorithm != key_algorithm - raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{key_algorithm} verification key was provided" - end - digest = OpenSSL::Digest.new(algorithm.sub('ES', 'sha')) - public_key.dsa_verify_asn1(digest.digest(signing_input), SecurityUtils.raw_to_asn1(signature, public_key)) - end - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/eddsa.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/eddsa.rb deleted file mode 100644 index aec8b75774..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/eddsa.rb +++ /dev/null @@ -1,23 +0,0 @@ -module JWT - module Algos - module Eddsa - module_function - - SUPPORTED = %w[ED25519].freeze - - def sign(to_sign) - algorithm, msg, key = to_sign.values - raise EncodeError, "Key given is a #{key.class} but has to be an RbNaCl::Signatures::Ed25519::SigningKey" if key.class != RbNaCl::Signatures::Ed25519::SigningKey - raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{key.primitive} signing key was provided" if algorithm.downcase.to_sym != key.primitive - key.sign(msg) - end - - def verify(to_verify) - algorithm, public_key, signing_input, signature = to_verify.values - raise IncorrectAlgorithm, "payload algorithm is #{algorithm} but #{public_key.primitive} verification key was provided" if algorithm.downcase.to_sym != public_key.primitive - raise DecodeError, "key given is a #{public_key.class} but has to be a RbNaCl::Signatures::Ed25519::VerifyKey" if public_key.class != RbNaCl::Signatures::Ed25519::VerifyKey - public_key.verify(signature, signing_input) - end - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/hmac.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/hmac.rb deleted file mode 100644 index d4b02b8239..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/hmac.rb +++ /dev/null @@ -1,33 +0,0 @@ -module JWT - module Algos - module Hmac - module_function - - SUPPORTED = %w[HS256 HS512256 HS384 HS512].freeze - - def sign(to_sign) - algorithm, msg, key = to_sign.values - authenticator, padded_key = SecurityUtils.rbnacl_fixup(algorithm, key) - if authenticator && padded_key - authenticator.auth(padded_key, msg.encode('binary')) - else - OpenSSL::HMAC.digest(OpenSSL::Digest.new(algorithm.sub('HS', 'sha')), key, msg) - end - end - - def verify(to_verify) - algorithm, public_key, signing_input, signature = to_verify.values - authenticator, padded_key = SecurityUtils.rbnacl_fixup(algorithm, public_key) - if authenticator && padded_key - begin - authenticator.verify(padded_key, signature.encode('binary'), signing_input.encode('binary')) - rescue RbNaCl::BadAuthenticatorError - false - end - else - SecurityUtils.secure_compare(signature, sign(JWT::Signature::ToSign.new(algorithm, signing_input, public_key))) - end - end - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/rsa.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/rsa.rb deleted file mode 100644 index c6621bc794..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/rsa.rb +++ /dev/null @@ -1,19 +0,0 @@ -module JWT - module Algos - module Rsa - module_function - - SUPPORTED = %w[RS256 RS384 RS512].freeze - - def sign(to_sign) - algorithm, msg, key = to_sign.values - raise EncodeError, "The given key is a #{key.class}. It has to be an OpenSSL::PKey::RSA instance." if key.class == String - key.sign(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), msg) - end - - def verify(to_verify) - SecurityUtils.verify_rsa(to_verify.algorithm, to_verify.public_key, to_verify.signing_input, to_verify.signature) - end - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/unsupported.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/unsupported.rb deleted file mode 100644 index 99ddcb71c8..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/algos/unsupported.rb +++ /dev/null @@ -1,16 +0,0 @@ -module JWT - module Algos - module Unsupported - module_function - - SUPPORTED = Object.new.tap { |object| object.define_singleton_method(:include?) { |*| true } } - def verify(*) - raise JWT::VerificationError, 'Algorithm not supported' - end - - def sign(*) - raise NotImplementedError, 'Unsupported signing method' - end - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/decode.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/decode.rb deleted file mode 100644 index 770a8aa97f..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/decode.rb +++ /dev/null @@ -1,49 +0,0 @@ -# frozen_string_literal: true - -require 'json' - -# JWT::Decode module -module JWT - # Decoding logic for JWT - class Decode - attr_reader :header, :payload, :signature - - def self.base64url_decode(str) - str += '=' * (4 - str.length.modulo(4)) - Base64.decode64(str.tr('-_', '+/')) - end - - def initialize(jwt, verify) - @jwt = jwt - @verify = verify - @header = '' - @payload = '' - @signature = '' - end - - def decode_segments - header_segment, payload_segment, crypto_segment = raw_segments - @header, @payload = decode_header_and_payload(header_segment, payload_segment) - @signature = Decode.base64url_decode(crypto_segment.to_s) if @verify - signing_input = [header_segment, payload_segment].join('.') - [@header, @payload, @signature, signing_input] - end - - private - - def raw_segments - segments = @jwt.split('.') - required_num_segments = @verify ? [3] : [2, 3] - raise(JWT::DecodeError, 'Not enough or too many segments') unless required_num_segments.include? segments.length - segments - end - - def decode_header_and_payload(header_segment, payload_segment) - header = JSON.parse(Decode.base64url_decode(header_segment)) - payload = JSON.parse(Decode.base64url_decode(payload_segment)) - [header, payload] - rescue JSON::ParserError - raise JWT::DecodeError, 'Invalid segment encoding' - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/default_options.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/default_options.rb deleted file mode 100644 index 0cf0e3dec9..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/default_options.rb +++ /dev/null @@ -1,15 +0,0 @@ -module JWT - module DefaultOptions - DEFAULT_OPTIONS = { - verify_expiration: true, - verify_not_before: true, - verify_iss: false, - verify_iat: false, - verify_jti: false, - verify_aud: false, - verify_sub: false, - leeway: 0, - algorithms: ['HS256'] - }.freeze - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/encode.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/encode.rb deleted file mode 100644 index 7e8f07d405..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/encode.rb +++ /dev/null @@ -1,51 +0,0 @@ -# frozen_string_literal: true - -require 'json' - -# JWT::Encode module -module JWT - # Encoding logic for JWT - class Encode - attr_reader :payload, :key, :algorithm, :header_fields, :segments - - def self.base64url_encode(str) - Base64.encode64(str).tr('+/', '-_').gsub(/[\n=]/, '') - end - - def initialize(payload, key, algorithm, header_fields) - @payload = payload - @key = key - @algorithm = algorithm - @header_fields = header_fields - @segments = encode_segments - end - - private - - def encoded_header - header = { 'alg' => @algorithm }.merge(@header_fields) - Encode.base64url_encode(JSON.generate(header)) - end - - def encoded_payload - raise InvalidPayload, 'exp claim must be an integer' if @payload && @payload.is_a?(Hash) && @payload.key?('exp') && !@payload['exp'].is_a?(Integer) - Encode.base64url_encode(JSON.generate(@payload)) - end - - def encoded_signature(signing_input) - if @algorithm == 'none' - '' - else - signature = JWT::Signature.sign(@algorithm, signing_input, @key) - Encode.base64url_encode(signature) - end - end - - def encode_segments - header = encoded_header - payload = encoded_payload - signature = encoded_signature([header, payload].join('.')) - [header, payload, signature].join('.') - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/error.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/error.rb deleted file mode 100644 index d6dca94017..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/error.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true - -module JWT - class EncodeError < StandardError; end - class DecodeError < StandardError; end - class VerificationError < DecodeError; end - class ExpiredSignature < DecodeError; end - class IncorrectAlgorithm < DecodeError; end - class ImmatureSignature < DecodeError; end - class InvalidIssuerError < DecodeError; end - class InvalidIatError < DecodeError; end - class InvalidAudError < DecodeError; end - class InvalidSubError < DecodeError; end - class InvalidJtiError < DecodeError; end - class InvalidPayload < DecodeError; end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/security_utils.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/security_utils.rb deleted file mode 100644 index 7193dc2621..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/security_utils.rb +++ /dev/null @@ -1,51 +0,0 @@ -module JWT - # Collection of security methods - # - # @see: https://github.com/rails/rails/blob/master/activesupport/lib/active_support/security_utils.rb - module SecurityUtils - module_function - - def secure_compare(left, right) - left_bytesize = left.bytesize - - return false unless left_bytesize == right.bytesize - - unpacked_left = left.unpack "C#{left_bytesize}" - result = 0 - right.each_byte { |byte| result |= byte ^ unpacked_left.shift } - result.zero? - end - - def verify_rsa(algorithm, public_key, signing_input, signature) - public_key.verify(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), signature, signing_input) - end - - def asn1_to_raw(signature, public_key) - byte_size = (public_key.group.degree + 7) / 8 - OpenSSL::ASN1.decode(signature).value.map { |value| value.value.to_s(2).rjust(byte_size, "\x00") }.join - end - - def raw_to_asn1(signature, private_key) - byte_size = (private_key.group.degree + 7) / 8 - sig_bytes = signature[0..(byte_size - 1)] - sig_char = signature[byte_size..-1] || '' - OpenSSL::ASN1::Sequence.new([sig_bytes, sig_char].map { |int| OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(int, 2)) }).to_der - end - - def rbnacl_fixup(algorithm, key) - algorithm = algorithm.sub('HS', 'SHA').to_sym - - return [] unless defined?(RbNaCl) && RbNaCl::HMAC.constants(false).include?(algorithm) - - authenticator = RbNaCl::HMAC.const_get(algorithm) - - # Fall back to OpenSSL for keys larger than 32 bytes. - return [] if key.bytesize > authenticator.key_bytes - - [ - authenticator, - key.bytes.fill(0, key.bytesize...authenticator.key_bytes).pack('C*') - ] - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/signature.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/signature.rb deleted file mode 100644 index 8bc296da1a..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/signature.rb +++ /dev/null @@ -1,50 +0,0 @@ -# frozen_string_literal: true - -require 'jwt/security_utils' -require 'openssl' -require 'jwt/algos/hmac' -require 'jwt/algos/eddsa' -require 'jwt/algos/ecdsa' -require 'jwt/algos/rsa' -require 'jwt/algos/unsupported' -begin - require 'rbnacl' -rescue LoadError - raise if defined?(RbNaCl) -end - -# JWT::Signature module -module JWT - # Signature logic for JWT - module Signature - extend self - ALGOS = [ - Algos::Hmac, - Algos::Ecdsa, - Algos::Rsa, - Algos::Eddsa, - Algos::Unsupported - ].freeze - ToSign = Struct.new(:algorithm, :msg, :key) - ToVerify = Struct.new(:algorithm, :public_key, :signing_input, :signature) - - def sign(algorithm, msg, key) - algo = ALGOS.find do |alg| - alg.const_get(:SUPPORTED).include? algorithm - end - algo.sign ToSign.new(algorithm, msg, key) - end - - def verify(algorithm, key, signing_input, signature) - algo = ALGOS.find do |alg| - alg.const_get(:SUPPORTED).include? algorithm - end - verified = algo.verify(ToVerify.new(algorithm, key, signing_input, signature)) - raise(JWT::VerificationError, 'Signature verification raised') unless verified - rescue OpenSSL::PKey::PKeyError - raise JWT::VerificationError, 'Signature verification raised' - ensure - OpenSSL.errors.clear - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/verify.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/verify.rb deleted file mode 100644 index 79789389de..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/verify.rb +++ /dev/null @@ -1,102 +0,0 @@ -# frozen_string_literal: true - -require 'jwt/error' - -module JWT - # JWT verify methods - class Verify - DEFAULTS = { - leeway: 0 - }.freeze - - class << self - %w[verify_aud verify_expiration verify_iat verify_iss verify_jti verify_not_before verify_sub].each do |method_name| - define_method method_name do |payload, options| - new(payload, options).send(method_name) - end - end - - def verify_claims(payload, options) - options.each do |key, val| - next unless key.to_s =~ /verify/ - Verify.send(key, payload, options) if val - end - end - end - - def initialize(payload, options) - @payload = payload - @options = DEFAULTS.merge(options) - end - - def verify_aud - return unless (options_aud = @options[:aud]) - - aud = @payload['aud'] - raise(JWT::InvalidAudError, "Invalid audience. Expected #{options_aud}, received #{aud || ''}") if ([*aud] & [*options_aud]).empty? - end - - def verify_expiration - return unless @payload.include?('exp') - raise(JWT::ExpiredSignature, 'Signature has expired') if @payload['exp'].to_i <= (Time.now.to_i - exp_leeway) - end - - def verify_iat - return unless @payload.include?('iat') - - iat = @payload['iat'] - raise(JWT::InvalidIatError, 'Invalid iat') if !iat.is_a?(Numeric) || iat.to_f > (Time.now.to_f + iat_leeway) - end - - def verify_iss - return unless (options_iss = @options[:iss]) - - iss = @payload['iss'] - - return if Array(options_iss).map(&:to_s).include?(iss.to_s) - - raise(JWT::InvalidIssuerError, "Invalid issuer. Expected #{options_iss}, received #{iss || ''}") - end - - def verify_jti - options_verify_jti = @options[:verify_jti] - jti = @payload['jti'] - - if options_verify_jti.respond_to?(:call) - verified = options_verify_jti.arity == 2 ? options_verify_jti.call(jti, @payload) : options_verify_jti.call(jti) - raise(JWT::InvalidJtiError, 'Invalid jti') unless verified - elsif jti.to_s.strip.empty? - raise(JWT::InvalidJtiError, 'Missing jti') - end - end - - def verify_not_before - return unless @payload.include?('nbf') - raise(JWT::ImmatureSignature, 'Signature nbf has not been reached') if @payload['nbf'].to_i > (Time.now.to_i + nbf_leeway) - end - - def verify_sub - return unless (options_sub = @options[:sub]) - sub = @payload['sub'] - raise(JWT::InvalidSubError, "Invalid subject. Expected #{options_sub}, received #{sub || ''}") unless sub.to_s == options_sub.to_s - end - - private - - def global_leeway - @options[:leeway] - end - - def exp_leeway - @options[:exp_leeway] || global_leeway - end - - def iat_leeway - @options[:iat_leeway] || global_leeway - end - - def nbf_leeway - @options[:nbf_leeway] || global_leeway - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/lib/jwt/version.rb b/debian/gems-compat/jwt-2.1.0/lib/jwt/version.rb deleted file mode 100644 index 0185f470e8..0000000000 --- a/debian/gems-compat/jwt-2.1.0/lib/jwt/version.rb +++ /dev/null @@ -1,24 +0,0 @@ -# encoding: utf-8 -# frozen_string_literal: true - -# Moments version builder module -module JWT - def self.gem_version - Gem::Version.new VERSION::STRING - end - - # Moments version builder module - module VERSION - # major version - MAJOR = 2 - # minor version - MINOR = 1 - # tiny version - TINY = 0 - # alpha, beta, etc. tag - PRE = nil - - # Build version string - STRING = [MAJOR, MINOR, TINY, PRE].compact.join('.') - end -end diff --git a/debian/gems-compat/jwt-2.1.0/ruby-jwt.gemspec b/debian/gems-compat/jwt-2.1.0/ruby-jwt.gemspec deleted file mode 100644 index e2c9183104..0000000000 --- a/debian/gems-compat/jwt-2.1.0/ruby-jwt.gemspec +++ /dev/null @@ -1,31 +0,0 @@ -lib = File.expand_path('../lib/', __FILE__) -$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'jwt/version' - -Gem::Specification.new do |spec| - spec.name = 'jwt' - spec.version = JWT.gem_version - spec.authors = [ - 'Tim Rudat' - ] - spec.email = 'timrudat@gmail.com' - spec.summary = 'JSON Web Token implementation in Ruby' - spec.description = 'A pure ruby implementation of the RFC 7519 OAuth JSON Web Token (JWT) standard.' - spec.homepage = 'http://github.com/jwt/ruby-jwt' - spec.license = 'MIT' - spec.required_ruby_version = '>= 2.1' - - spec.files = `git ls-files -z`.split("\x0") - spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } - spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) - spec.require_paths = %w[lib] - - spec.add_development_dependency 'bundler' - spec.add_development_dependency 'rake' - spec.add_development_dependency 'rspec' - spec.add_development_dependency 'simplecov' - spec.add_development_dependency 'simplecov-json' - spec.add_development_dependency 'codeclimate-test-reporter' - spec.add_development_dependency 'codacy-coverage' - spec.add_development_dependency 'rbnacl' -end diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-private.pem deleted file mode 100644 index 40c7a8f635..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-private.pem +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN EC PARAMETERS----- -BggqhkjOPQMBBw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MHcCAQEEIJmVse5uPfj6B4TcXrUAvf9/8pJh+KrKKYLNcmOnp/vPoAoGCCqGSM49 -AwEHoUQDQgAEAr+WbDE5VtIDGhtYMxvEc6cMsDBc/DX1wuhIMu8dQzOLSt0tpqK9 -MVfXbVfrKdayVFgoWzs8MilcYq0QIhKx/w== ------END EC PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-public.pem deleted file mode 100644 index e6f22827d3..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-public.pem +++ /dev/null @@ -1,4 +0,0 @@ ------BEGIN PUBLIC KEY----- -MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEAr+WbDE5VtIDGhtYMxvEc6cMsDBc -/DX1wuhIMu8dQzOLSt0tpqK9MVfXbVfrKdayVFgoWzs8MilcYq0QIhKx/w== ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-wrong-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-wrong-private.pem deleted file mode 100644 index 260df0b623..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-wrong-private.pem +++ /dev/null @@ -1,8 +0,0 @@ ------BEGIN EC PARAMETERS----- -BgUrgQQACg== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MHQCAQEEICfA4AaomONdmPTzeyrx5U/jugYXTERyb5U3ETTv7Hx7oAcGBSuBBAAK -oUQDQgAEPmuXZT3jpJnEMVPOW6RMsmxeGLOCE1PN6fwvUwOsxv7YnyoQ5/bpo64n -+Jp4slSl1aUNoCBF2oz9bS0iyBo3jg== ------END EC PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-wrong-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-wrong-public.pem deleted file mode 100644 index 511a0def9b..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec256-wrong-public.pem +++ /dev/null @@ -1,4 +0,0 @@ ------BEGIN PUBLIC KEY----- -MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAEPmuXZT3jpJnEMVPOW6RMsmxeGLOCE1PN -6fwvUwOsxv7YnyoQ5/bpo64n+Jp4slSl1aUNoCBF2oz9bS0iyBo3jg== ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-private.pem deleted file mode 100644 index 553f27c1da..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-private.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN EC PARAMETERS----- -BgUrgQQAIg== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MIGkAgEBBDDxOljqUKw9YNhkluSJIBAYO1YXcNtS+vckd5hpTZ5toxsOlwbmyrnU -Tn+D5Xma1m2gBwYFK4EEACKhZANiAASQwYTiRvXu1hMHceSosMs/8uf50sJI3jvK -kdSkvuRAPxSzhtrUvCQDnVsThFq4aOdZZY1qh2ErJGtzmrx+pEsJvJnvfOTG3NGU -KRalek+LQfVqAUSvDMKlxdkz2e67tso= ------END EC PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-public.pem deleted file mode 100644 index 6b7638d4a6..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-public.pem +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN PUBLIC KEY----- -MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEkMGE4kb17tYTB3HkqLDLP/Ln+dLCSN47 -ypHUpL7kQD8Us4ba1LwkA51bE4RauGjnWWWNaodhKyRrc5q8fqRLCbyZ73zkxtzR -lCkWpXpPi0H1agFErwzCpcXZM9nuu7bK ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-wrong-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-wrong-private.pem deleted file mode 100644 index 1cc5f0d8db..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-wrong-private.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN EC PARAMETERS----- -BgUrgQQAIg== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MIGkAgEBBDAfZW47dSKnC5JkSVOk1ERxCIi/IJ1p1WBnVGx4hnrNHy+dxtaZJaF+ -YLInFQ/QbYegBwYFK4EEACKhZANiAAQwXkx4BFBGLXbzl5yVrfxK7er8hSi38iDE -K2+7cdrR137Wn5JUnL4WTwXTzkyUgfBOL3sHNozwfgU03GD/EOUEKqzsIJiz2cbP -bFALd4hS+8T4szDLVC9Jl1W6k0CAtmM= ------END EC PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-wrong-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-wrong-public.pem deleted file mode 100644 index 693bd019e0..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec384-wrong-public.pem +++ /dev/null @@ -1,5 +0,0 @@ ------BEGIN PUBLIC KEY----- -MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEMF5MeARQRi1285ecla38Su3q/IUot/Ig -xCtvu3Ha0dd+1p+SVJy+Fk8F085MlIHwTi97BzaM8H4FNNxg/xDlBCqs7CCYs9nG -z2xQC3eIUvvE+LMwy1QvSZdVupNAgLZj ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-private.pem deleted file mode 100644 index fddd88894e..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-private.pem +++ /dev/null @@ -1,10 +0,0 @@ ------BEGIN EC PARAMETERS----- -BgUrgQQAIw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MIHcAgEBBEIB0/+ffxEj7j62xvGaB5pvzk888e412ESO/EK/K0QlS9dSF8+Rj1rG -zqpRB8fvDnoe8xdmkW/W5GKzojMyv7YQYumgBwYFK4EEACOhgYkDgYYABAEw74Yw -aTbPY6TtWmxx6LJDzCX2nKWCPnKdZcEH9Ncu8g5RjRBRq2yacja3OoS6nA2YeDng -reBJxZr376P6Ns6XcQFWDA6K/MCTrEBCsPxXZNxd8KR9vMGWhgNtWRrcKzwJfQkr -suyehZkbbYyFnAWyARKHZuV7VUXmeEmRS/f93MPqVA== ------END EC PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-public.pem deleted file mode 100644 index a74a57b073..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-public.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBMO+GMGk2z2Ok7VpsceiyQ8wl9pyl -gj5ynWXBB/TXLvIOUY0QUatsmnI2tzqEupwNmHg54K3gScWa9++j+jbOl3EBVgwO -ivzAk6xAQrD8V2TcXfCkfbzBloYDbVka3Cs8CX0JK7LsnoWZG22MhZwFsgESh2bl -e1VF5nhJkUv3/dzD6lQ= ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-wrong-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-wrong-private.pem deleted file mode 100644 index b6ec7b7310..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-wrong-private.pem +++ /dev/null @@ -1,10 +0,0 @@ ------BEGIN EC PARAMETERS----- -BgUrgQQAIw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MIHbAgEBBEG/KbA2oCbiCT6L3V8XSz2WKBy0XhGvIFbl/ZkXIXnkYt+1B7wViSVo -KCHuMFsi6xU/5nE1EuDG2UsQJmKeAMkIOKAHBgUrgQQAI6GBiQOBhgAEAG0TFWe5 -cZ5DZIyfuysrCoQySTNxd+aT8sPIxsx7mW6YBTsuO6rEgxyegd2Auy4xtikxpzKv -soMXR02999Aaus2jAAt/wxrhhr41BDP4MV0b6Zngb72hna0pcGqit5OyU8AbOJUZ -+rdyowRGsOY+aPbOyVhdNcsEdxYC8GdIyCQLBC1H ------END EC PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-wrong-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-wrong-public.pem deleted file mode 100644 index a84be38c34..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/ec512-wrong-public.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAbRMVZ7lxnkNkjJ+7KysKhDJJM3F3 -5pPyw8jGzHuZbpgFOy47qsSDHJ6B3YC7LjG2KTGnMq+ygxdHTb330Bq6zaMAC3/D -GuGGvjUEM/gxXRvpmeBvvaGdrSlwaqK3k7JTwBs4lRn6t3KjBEaw5j5o9s7JWF01 -ywR3FgLwZ0jIJAsELUc= ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-1024-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-1024-private.pem deleted file mode 100644 index 7f01c00261..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-1024-private.pem +++ /dev/null @@ -1,15 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIICXgIBAAKBgQDO/ahgFDvniFoQ1dm+MdnkBi+Ts5W9AtQNgw4ZHIdPnqEzSgW7 -0opKEu8hnlLqsIyU2BC2op/xOanipdbXObuFlA6bth1cYRI+YJlR3BbPGOIL6YbJ -ud9m0gIsBlCDLm4e/E45ZS+emudISP7/SF7zxvxZlnr1z7HTm7nIIVBvuQIDAQAB -AoGBAMzFQAccvU6GI6O4C5sOsiHUxMh3xtCftaxQVGgfQvVPVuXoeteep1Q0ewFl -IV4vnkO5pH8pTtVTWG9x5KIy6QCql4qvr2jkOm4mo9uogrpNklvBl2lN4Lxubj0N -mGRXaM3hckZl8+JT6uzfBfjy+pd8AOigJGPQCOZn4gmANW7pAkEA82Nh4wpj6ZRU -NBiBq3ONZuH4xJm59MI2FWRJsGUFUYdSaFwyKKim52/13d8iUb7v9utWQFRatCXz -Lqw9fQyVrwJBANm3dBOVxpUPrYEQsG0q2rdP+u6U3woylxwtQgJxImZKZmmJlPr8 -9v23rhydvCe1ERPYe7EjF4RGWVPN3KLdExcCQDdzNfL3BApMS97OkoRQQC/nXbjU -2SPlN1MqVQuGCG8pqGG0V40h11y1CkvxMS10ldEojq77SOrwFnZUsXGS82sCQQC6 -XdO7QCaxSq5XIRYlHN4EtS40NLOIYy3/LK6osHel4GIyTVd+UjSLk0QzssJxqwln -V5TqWQO0cxPcLQiFUYEZAkEA2G84ilb9QXOgbNyoE1VifNk49hhodbSskLb86uwY -Vgtzq1ZsqoPBCasr4WRiXt270n+mo5dNYRlZwiUn9lH78Q== ------END RSA PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-1024-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-1024-public.pem deleted file mode 100644 index 7bec6ef05a..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-1024-public.pem +++ /dev/null @@ -1,6 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO/ahgFDvniFoQ1dm+MdnkBi+T -s5W9AtQNgw4ZHIdPnqEzSgW70opKEu8hnlLqsIyU2BC2op/xOanipdbXObuFlA6b -th1cYRI+YJlR3BbPGOIL6YbJud9m0gIsBlCDLm4e/E45ZS+emudISP7/SF7zxvxZ -lnr1z7HTm7nIIVBvuQIDAQAB ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-private.pem deleted file mode 100644 index dab50df27b..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-private.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEA4GzZTLU48c4WbyvHi+QKrB71x+T0eq5hqDbQqnlYjhD1Ika7 -io1iplsdJWJuyxfYbUkb2Ol0fj4koZ/GS6lgCZr4+8UHbr1qf0Eu5HZSpszs2YxY -8U5RHnrpw67co7hlgAR9HbyNf5XIYgLV9ldHH/eazwnc3F/hgNsV0xjScVilejgo -cJ4zcsyymvW8t42lteM7bI867ZuJhGop/V+Y0HFyrMsPoQyLuCUpr6ulOfrkr7ZO -dhAIG8r1HcjOp/AUjM15vfXcbUZjkM/VloifX1YitU3upMGJ8/DpFGffMOImrn5r -6BT494V8rRyN2qvQoAkLJpqZ0avLxwiR2lgVQQIDAQABAoIBAEH0Ozgr2fxWEInD -V/VooypKPvjr9F1JejGxSkmPN9MocKIOH3dsbZ1uEXa3ItBUxan4XlK06SNgp+tH -xULfF/Y6sQlsse59hBq50Uoa69dRShn1AP6JgZVvkduMPBNxUYL5zrs6emsQXb9Q -DglDRQfEAJ7vyxSIqQDxYcyT8uSUF70dqFe+E9B2VE3D6ccHc98k41pJrAFAUFH1 -wwvDhfyYr7/Ultut9wzpZvU1meF3Vna3GOUHfxrG6wu1G+WIWHGjouzThsc1qiVI -BtMCJxuCt5fOXRbU4STbMqhB6sZHiOh6J/dZU6JwRYt+IS8FB6kCNFSEWZWQledJ -XqtYSQECgYEA9nmnFTRj3fTBq9zMXfCRujkSy6X2bOb39ftNXzHFuc+I6xmv/3Bs -P9tDdjueP/SnCb7i/9hXkpEIcxjrjiqgcvD2ym1hE4q+odMzRAXYMdnmzI34SVZE -U5hYJcYsXNKrTTleba7QgqdORmyJ9FwqLO40udvmrZMY223XDwgRkOkCgYEA6RkO -5wjjrWWp/G1YN3KXZTS1m2/eGrUThohXKAfAjbWWiouNLW2msXrxEWsPRL6xKiHu -X9cwZwzi3MstAgk+bphUGUVUkGKNDjWHJA25tDYjbPtkd6xbL4eCHsKpNL3HNYr9 -N0CIvgn7qjaHRBem0iK7T6keY4axaSVddEwYapkCgYEA13K5qaB1F4Smcpt8DTWH -vPe8xUUaZlFzOJLmLCsuwmB2N8Ppg2j7RspcaxJsH021YaB5ftjWm+ipMSr8ZPY/ -8JlPsNzxuYpTXtNmAbT2KYVm6THEch61dTk6/DIBf1YrpUJbl5by7vJeStL/uBmE -SGgksL5XIyzs0opuLdaIvFkCgYAyBLWE8AxjFfCvAQuwAj/ocLITo6KmWnrRIIqL -RXaVMgUWv7FQsTnW1cnK8g05tC2yG8vZ9wQk6Mf5lwOWb0NdWgSZ0528ydj41pWk -L+nMeN2LMjqxz2NVxJ8wWJcUgTCxFZ0WcRumo9/D+6V1ABpE9zz4cBLcSnfhVypB -nV6T6QKBgQCSZNCQ9HPxjAgYcsqc5sjNwuN1GHQZSav3Tye3k6zHENe1lsteT9K8 -xciGIuhybKZBvB4yImIIHCtnH+AS+mHAGqHarjNDMfvjOq0dMibPx4+bkIiHdBIH -Xz+j5kmntvFiUnzr0Z/Tcqo+r8FvyCo1YWgwqGP8XoFrswD7gy7cZw== ------END RSA PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-public.pem deleted file mode 100644 index c80a9523c7..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-public.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4GzZTLU48c4WbyvHi+QK -rB71x+T0eq5hqDbQqnlYjhD1Ika7io1iplsdJWJuyxfYbUkb2Ol0fj4koZ/GS6lg -CZr4+8UHbr1qf0Eu5HZSpszs2YxY8U5RHnrpw67co7hlgAR9HbyNf5XIYgLV9ldH -H/eazwnc3F/hgNsV0xjScVilejgocJ4zcsyymvW8t42lteM7bI867ZuJhGop/V+Y -0HFyrMsPoQyLuCUpr6ulOfrkr7ZOdhAIG8r1HcjOp/AUjM15vfXcbUZjkM/Vloif -X1YitU3upMGJ8/DpFGffMOImrn5r6BT494V8rRyN2qvQoAkLJpqZ0avLxwiR2lgV -QQIDAQAB ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-wrong-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-wrong-private.pem deleted file mode 100644 index 7cae44c660..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-wrong-private.pem +++ /dev/null @@ -1,27 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIEpAIBAAKCAQEAzHAVGaW9j4l3/b4ngcjjoIoIcnsQEWOMqErb5VhLZMGIq1gE -O5qxPDAwooKsNotzcAOB3ZyLn7p5D+dmOrNUYkYWgYITNGeSifrnVqQugd5Fh1L8 -K7zOGltUo2UtjbN4uJ56tzxBMZp2wejs2/Qu0eu0xZK3To+YkDcWOk92rmNgmUSQ -C/kNyIOj+yBvOo3wTk6HvbhoIarCgJ6Lay1v/hMLyQLzwRY/Qfty1FTIDyTv2dch -47FsfkZ1KAL+MbUnHuCBPzGxRjXa8Iy9Z7YGxrYasUt1b0um64bscxoIiCu8yLL8 -jlg01Rwrjr/MTwKRhwXlMp8B7HTonwtaG6arJwIDAQABAoIBAGFR4dmJusl/qW1T -fj8cQLAFxaupxaZhe24J5NAyzgEy2Dqo9ariIwkB78UM66ozjEqAgOvcP+NTw5m8 -kD/VapA1yTTxlO7XdzzUAhiOo80S4IphCMZRZNPLMmluGtdf3lIUr1pXBrn0TCBX -H5o9jaREzpNXGof9d6T/dEdh2J9+uE/p1xE5GSxQfaPheZzCG7636La/DcArg/UR -+TusPqp62BEmk96pE/KKJRmEeH+WnPfSh6sMpLxi3hkEU7AynpliGT6Z6xV4csBI -S/rdpkcj5DWpbnQzkwdrnL2Q+POEq/vlx5/NlezvtQPNLvQWDyY4yBCoMKGb3EbX -xrxP7MECgYEA/kwe4P0Mqk+087IyhjDBGPfcMt8gfYc9nzNfIYSWdSwuSag/hqHq -I4GwHQzUV9ix3iM6w5hin10yAzWxCYZg9hquV+lSvNNpGB76FX6oOqwuAhyQMRwv -eW+VUyfFXeJugwL5JuIaNTvwPpQVDHYtELLifie+uzJ5HC6dhg/XchcCgYEAzc5/ -+IXjOlExd/mBgFk/5Y87ifA0ZOgbaJXifYgU0aNSgz1piHxU3n2p4jJ9lSdwwCl2 -Fb5EN7666t20PL5QcXJ5ZdaTRLzRlYiqTWzfYHBgttbB1Jl3Ed9GsKuzRgaRqGFC -ANJSqZlKG0NZ3keRtuKdFwq+IVOnsQr9g0TZiXECgYEAqUgtCiMKCloTIGMQpSnR -cXiWWjsUmturls4Q1vQ3YHrvuVLKLyqb/dT4Uu5WcMAs765OESThCit0/pQAbVHK -PCpYwubskAzAGjGM00BEZwJ1gixXhIm5xMIWCowgI7Z3ULlq+IptXeCvtkjHlksZ -BtO+WLLGkkEwRCV38WWcSzMCgYA/Xxqgl/mD94RYAQgTUWgPc69Nph08BQyLg7ue -E8z1UGkT6FEaqc4oRGGPOSTaTK63PQ0TXOb8k0pTD7l0CtYSWMFwzkXCoLGYbeCi -vqd5tqDRLAe7QxYa9rl5pSUqptMrGeeNATZa6sya4H5Hp5oCyny8n54z/OJh7ZRq -W0TwwQKBgQDDP7ksm2pcqadaVAmODdOlaDHbaEcxp8wN7YVz0lM3UpJth96ukbj7 -S39eJhXYWOn6oJQb/lN9fGOYqjg3y6IchGZDp67ATvWYvn/NY0R7mt4K4oHx5TuN -rSQlP3WmOGv8Kemw892uRfW/jZyBEHhsfS213WDttVPn9F635GdNWw== ------END RSA PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-wrong-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-wrong-public.pem deleted file mode 100644 index 8d49601410..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-2048-wrong-public.pem +++ /dev/null @@ -1,9 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzHAVGaW9j4l3/b4ngcjj -oIoIcnsQEWOMqErb5VhLZMGIq1gEO5qxPDAwooKsNotzcAOB3ZyLn7p5D+dmOrNU -YkYWgYITNGeSifrnVqQugd5Fh1L8K7zOGltUo2UtjbN4uJ56tzxBMZp2wejs2/Qu -0eu0xZK3To+YkDcWOk92rmNgmUSQC/kNyIOj+yBvOo3wTk6HvbhoIarCgJ6Lay1v -/hMLyQLzwRY/Qfty1FTIDyTv2dch47FsfkZ1KAL+MbUnHuCBPzGxRjXa8Iy9Z7YG -xrYasUt1b0um64bscxoIiCu8yLL8jlg01Rwrjr/MTwKRhwXlMp8B7HTonwtaG6ar -JwIDAQAB ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-4096-private.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-4096-private.pem deleted file mode 100644 index ddee07317d..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-4096-private.pem +++ /dev/null @@ -1,51 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -MIIJJwIBAAKCAgEAqETmgWBi5rCmb7euJplA/9xs65+bncc9Yvs5zjyycXSW82Jf -RuyguGm0OvA2wog24dR4N2kT/87DcGtp5JqJWADVFNr+2V2r6i57/OMLruRpn3p2 -r95dmo0COE+BxPFl7XEBT8JbH57ZtpgcB3/xkS14nLOWFf96hrXPlXJC+VMVKVZm -A8k2LRh42vT5wUf4U0Doy/p7yFNSFFa6Q8wwe4TBy/z/f+rhFD1w8rxlYjallee/ -ocm7bjZCwbJGMm7orLViqWfsFX3O35PeoJ5h/7uJ7iRwvTFERkTdwWP/0BeKBeIt -BR3YFc2mut+V9W+WKRkMSL6Crc+oVSx3p8aB7j9SZFzQiRtes4BYETpX1xl2mgIq -5hvsFbLw7ESrlIodiwUMTrSIid2DQ6q80kv1zXPr4+Id6L0sJLxPCaXnTmNtasSw -yedJJYxLjwhHJwtzFAeaq18H3O791YKhjAJ6YxK3zJ59jTE6Pkvqjq183f2PGHVR -vgSN7aCmI6MBUUB5wDP2K8zX2sh40/uPDVSd6ei1vl3DpPk+h8iExx6AzbohfqZ+ -5RUUNx127L3MaQvOVC5TxV+R99gwKW++wzcVuO3m2KqVUj+K1uYBy3KBCUMBbckp -EWGbN++jcdV5oJX6fsC66nOmKlntYwCL/pRww+oLsbzF8J3dxeDbKNF9JDsCAwEA -AQKCAgBJF8TZJjlP5CQoGy227pNhkSpvH6HFY6qyuFZf09XfmrmHd4/Tiy41bRUx -FO90iR7t8hFWYHqjf/k9eCtDdi164MGukYJqgVoQG6kYLLgCfI21DMlJk9otLFtu -gnroRcP05EWhk9dpYONJgcGLMHSKj6n4x7nGTHe41HkbfcrB6ukiT7l4o4q5BAxb -cFadMtoXr/ZvxJrIZgkddJ7snGHjBcP5DCkgM7MZy6aoilWv1/UNrOF9MdgNA9zz -rrD3b136x7/XvqC6pS+bxuvJ8YK4R4qeu42NYT07GOcK/pk8lz0JWTodIt2eevqV -6lGFj7c2mv7PCpJRVgbVGL/RTVVap/+jbcRVLdnYKsII/dANG7iXnfwRgkLWet5D -OOsPuvIuyiSaJIwcdRE3SSO+tZhKLt+gh/oLxBPw5Ex0FwsVTtYn3Q/X3EAx+Wph -eFcRr3TVkDg0MfdWWkgk16DvYB5cWc29coTaH1g+2juadNHbtVAigwJorKc6sxH3 -QGsW0WQJ8ZRZgJkSUuu3nr7QD3ZrgHptONQAh1RWGnIWi6OlMfaPdMo+SDnnL5SG -mpOPjWadDc1XvMFnKQYMYB5GWU/ZNmnZmDLyg1Pc0Y+qRUc0s83nZFHN60KnUrSz -0MZDspSFtr0fMx0b2/EB4EbuXd3QjQURF6P6HtWBu6oFnzu1AQKCAQEA2R9BKJgJ -vNP+DUu8NBzwmi0cKlAiaxt+w90i5DWq1XWPKgi+RVLkaQSJqHoYQVNgEwL/cWxp -s2r3GCMNIdOrGdcm8dX/6UYFpRaFcViTycVEA7cwZOMppgqr2Q+ZYX42K7HObUVL -JGvdEWWWfSsynUGsrG87DC1gl94ANxCdqkZdbW5d3X0w5v7M/1tlrmAeskZSZpeT -8BwwM6REb0U/B4/i8TLtLi/PGmMTOIxW41uKS/S6kq/gwyv+jNNO0ljhPt25iSbV -K5ZHS4YuPKLl0tZMaOkPco9s6t4ES/Y317zQoTzUkAAkkFO4QPzRZL0ESqVBNR0h -Ao7FLmFZzFHpoQKCAQEAxmZBn0UrJLXkD7bw66y4RwzjQYmxLlkEl3uvjrvVSuL1 -mAHDW58aGIpFFZ8QSTtNewIBQYNifp/cdFHAagqtl/iMGEegaOpJAKu/ykrkfZUp -7mYDNng4ZWpypeKaGMAQoNzZiUpF+BDnqbeb/kgYu6sNlh9gRHR79rgAuZQxZ/1B -tE8WcUFi4CnTq2QLqX4LwMuZHWXAJQoMoW3K5av+J544lIM6GdMJuIONtBBkKVQD -ErrJ0bqYeykrFS6pKl/NBCZLGo5xFFRiYEdZ1GlA3uW3EGKppz6PS7194+x5UVts -xZPUfkgdFjWCczkl4JDoWfaNn5sgXtiVbGh1n3gYWwKCAQB7vHEg1kyuXU4qe5/d -PyTraIvlnVeQHNJIgy0QS3l5Pw8A0IzG6y+anehpqHNMP1zAWPQEytkOVAZPriIc -xgl7p37dUa0PX0V2SPhxmR5YXeCeEXc197PTmb9H67jos8nhauqOoW/qaMJK2M9D -tCubLUNf3eAT14R16CHNP93qnUE/TSeXQ3JsIofne0neb47u4F6zcuzvaNEbjSEn -HJqID7sw5GoA6WQo0I+yqWAXICMXmHf/gtYfxGHEFeSUwexULH5BKG1R8sncw7J0 -Ag3h8xkGrNON4SkcTLy8Iay/eS6YxRcKndo4mk2mU65tr77TX4xi3Z/jWkQLY5WO -eJwhAoIBABO17wkSxyGDjJ/fDfpsE3bDmgRV2KuBHoqqOBvXH26sM7ghXLZKjT4o -5ooqXmTYJm91GIjYs71exnkr8hDW9L4nbEuxOgeSVyRg69H+NMshOaQ8sE8GDJxO -wgsnAyY4Vq6UomwYW/E0RL/AxRezM/nZGaVzgo3qgLJXP4MwbOQm7hMq1FD2LQuW -PDhH3Ty+kA5ca97W0Asd/3k+Pi0pNDvdZUOj8e7E369cKoTcKAdPGGsQ8aILhsCd -q3EUTKwwDl8+KrH9utBJPejQzeTjfBVo/xH6q145QeVFcy9ku/zQN3M9p5vQMEuX -j1lBMTkpTFw7uYBE2idyHw5BJoZsWQcCggEADfZTChqnOncItSflzGoaAACrr4/x -KyT/4A+cPMCs11JN9J+EWsCezya2o1l/NF7YPcBR4qjCmFMEiq5GxH5fGLQp0aa7 -V13mHA8XBQ25OW2K7BGJhMHdbuvTnl6jsOfC4+t7P2bUAYxoP6/ncxTzZ5OlBN5k -aMv9firWl1kSKK75ww9DWn6j0rQ4dBetwX45EMcs+iKIdydg0fmJxR2EJ+uQsCFy -xcWBEDqV7qLUi6UrAPL3v/DXUv9wKcKOTbKw/aNE8+YTWMUO330GCJ5cVU1eTL5t -UrcNKOJkFIj7jJUCzv6vcy++hMJEbNXnnTVRnky6e9C2vwzMl33njntapg== ------END RSA PRIVATE KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-4096-public.pem b/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-4096-public.pem deleted file mode 100644 index 01055eb081..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/fixtures/certs/rsa-4096-public.pem +++ /dev/null @@ -1,14 +0,0 @@ ------BEGIN PUBLIC KEY----- -MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAqETmgWBi5rCmb7euJplA -/9xs65+bncc9Yvs5zjyycXSW82JfRuyguGm0OvA2wog24dR4N2kT/87DcGtp5JqJ -WADVFNr+2V2r6i57/OMLruRpn3p2r95dmo0COE+BxPFl7XEBT8JbH57ZtpgcB3/x -kS14nLOWFf96hrXPlXJC+VMVKVZmA8k2LRh42vT5wUf4U0Doy/p7yFNSFFa6Q8ww -e4TBy/z/f+rhFD1w8rxlYjallee/ocm7bjZCwbJGMm7orLViqWfsFX3O35PeoJ5h -/7uJ7iRwvTFERkTdwWP/0BeKBeItBR3YFc2mut+V9W+WKRkMSL6Crc+oVSx3p8aB -7j9SZFzQiRtes4BYETpX1xl2mgIq5hvsFbLw7ESrlIodiwUMTrSIid2DQ6q80kv1 -zXPr4+Id6L0sJLxPCaXnTmNtasSwyedJJYxLjwhHJwtzFAeaq18H3O791YKhjAJ6 -YxK3zJ59jTE6Pkvqjq183f2PGHVRvgSN7aCmI6MBUUB5wDP2K8zX2sh40/uPDVSd -6ei1vl3DpPk+h8iExx6AzbohfqZ+5RUUNx127L3MaQvOVC5TxV+R99gwKW++wzcV -uO3m2KqVUj+K1uYBy3KBCUMBbckpEWGbN++jcdV5oJX6fsC66nOmKlntYwCL/pRw -w+oLsbzF8J3dxeDbKNF9JDsCAwEAAQ== ------END PUBLIC KEY----- diff --git a/debian/gems-compat/jwt-2.1.0/spec/integration/readme_examples_spec.rb b/debian/gems-compat/jwt-2.1.0/spec/integration/readme_examples_spec.rb deleted file mode 100644 index 52341e0088..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/integration/readme_examples_spec.rb +++ /dev/null @@ -1,202 +0,0 @@ -# frozen_string_literal: true - -require_relative '../spec_helper' -require 'jwt' - -describe 'README.md code test' do - context 'algorithm usage' do - let(:payload) { { data: 'test' } } - - it 'NONE' do - token = JWT.encode payload, nil, 'none' - decoded_token = JWT.decode token, nil, false - - expect(token).to eq 'eyJhbGciOiJub25lIn0.eyJkYXRhIjoidGVzdCJ9.' - expect(decoded_token).to eq [ - { 'data' => 'test' }, - { 'alg' => 'none' } - ] - end - - it 'HMAC' do - token = JWT.encode payload, 'my$ecretK3y', 'HS256' - decoded_token = JWT.decode token, 'my$ecretK3y', false - - expect(token).to eq 'eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pNIWIL34Jo13LViZAJACzK6Yf0qnvT_BuwOxiMCPE-Y' - expect(decoded_token).to eq [ - { 'data' => 'test' }, - { 'alg' => 'HS256' } - ] - end - - it 'RSA' do - rsa_private = OpenSSL::PKey::RSA.generate 2048 - rsa_public = rsa_private.public_key - - token = JWT.encode payload, rsa_private, 'RS256' - decoded_token = JWT.decode token, rsa_public, true, algorithm: 'RS256' - - expect(decoded_token).to eq [ - { 'data' => 'test' }, - { 'alg' => 'RS256' } - ] - end - - it 'ECDSA' do - ecdsa_key = OpenSSL::PKey::EC.new 'prime256v1' - ecdsa_key.generate_key - ecdsa_public = OpenSSL::PKey::EC.new ecdsa_key - ecdsa_public.private_key = nil - - token = JWT.encode payload, ecdsa_key, 'ES256' - decoded_token = JWT.decode token, ecdsa_public, true, algorithm: 'ES256' - - expect(decoded_token).to eq [ - { 'data' => 'test' }, - { 'alg' => 'ES256' } - ] - end - end - - context 'claims' do - let(:hmac_secret) { 'MyP4ssW0rD' } - - context 'exp' do - it 'without leeway' do - exp = Time.now.to_i + 4 * 3600 - exp_payload = { data: 'data', exp: exp } - - token = JWT.encode exp_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, algorithm: 'HS256' - end.not_to raise_error - end - - it 'with leeway' do - exp = Time.now.to_i - 10 - leeway = 30 # seconds - - exp_payload = { data: 'data', exp: exp } - - token = JWT.encode exp_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, leeway: leeway, algorithm: 'HS256' - end.not_to raise_error - end - end - - context 'nbf' do - it 'without leeway' do - nbf = Time.now.to_i - 3600 - nbf_payload = { data: 'data', nbf: nbf } - token = JWT.encode nbf_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, algorithm: 'HS256' - end.not_to raise_error - end - - it 'with leeway' do - nbf = Time.now.to_i + 10 - leeway = 30 - nbf_payload = { data: 'data', nbf: nbf } - token = JWT.encode nbf_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, leeway: leeway, algorithm: 'HS256' - end.not_to raise_error - end - end - - it 'iss' do - iss = 'My Awesome Company Inc. or https://my.awesome.website/' - iss_payload = { data: 'data', iss: iss } - - token = JWT.encode iss_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, iss: iss, algorithm: 'HS256' - end.not_to raise_error - end - - context 'aud' do - it 'array' do - aud = %w[Young Old] - aud_payload = { data: 'data', aud: aud } - - token = JWT.encode aud_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, aud: %w[Old Young], verify_aud: true, algorithm: 'HS256' - end.not_to raise_error - end - - it 'string' do - expect do - end.not_to raise_error - end - end - - it 'jti' do - iat = Time.now.to_i - hmac_secret = 'test' - jti_raw = [hmac_secret, iat].join(':').to_s - jti = Digest::MD5.hexdigest(jti_raw) - jti_payload = { data: 'data', iat: iat, jti: jti } - - token = JWT.encode jti_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, verify_jti: true, algorithm: 'HS256' - end.not_to raise_error - end - - context 'iat' do - it 'without leeway' do - iat = Time.now.to_i - iat_payload = { data: 'data', iat: iat } - - token = JWT.encode iat_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, verify_iat: true, algorithm: 'HS256' - end.not_to raise_error - end - - it 'with leeway' do - iat = Time.now.to_i - 7 - iat_payload = { data: 'data', iat: iat, leeway: 10 } - - token = JWT.encode iat_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, verify_iat: true, algorithm: 'HS256' - end.not_to raise_error - end - end - - context 'custom header fields' do - it 'with custom field' do - payload = { data: 'test' } - - token = JWT.encode payload, nil, 'none', typ: 'JWT' - _, header = JWT.decode token, nil, false - - expect(header['typ']).to eq 'JWT' - end - end - - it 'sub' do - sub = 'Subject' - sub_payload = { data: 'data', sub: sub } - - token = JWT.encode sub_payload, hmac_secret, 'HS256' - - expect do - JWT.decode token, hmac_secret, true, 'sub' => sub, :verify_sub => true, :algorithm => 'HS256' - end.not_to raise_error - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/spec/jwt/verify_spec.rb b/debian/gems-compat/jwt-2.1.0/spec/jwt/verify_spec.rb deleted file mode 100644 index 02528eea05..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/jwt/verify_spec.rb +++ /dev/null @@ -1,232 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' -require 'jwt/verify' - -module JWT - RSpec.describe Verify do - let(:base_payload) { { 'user_id' => 'some@user.tld' } } - let(:options) { { leeway: 0 } } - - context '.verify_aud(payload, options)' do - let(:scalar_aud) { 'ruby-jwt-aud' } - let(:array_aud) { %w[ruby-jwt-aud test-aud ruby-ruby-ruby] } - let(:scalar_payload) { base_payload.merge('aud' => scalar_aud) } - let(:array_payload) { base_payload.merge('aud' => array_aud) } - - it 'must raise JWT::InvalidAudError when the singular audience does not match' do - expect do - Verify.verify_aud(scalar_payload, options.merge(aud: 'no-match')) - end.to raise_error JWT::InvalidAudError - end - - it 'must raise JWT::InvalidAudError when the payload has an array and none match the supplied value' do - expect do - Verify.verify_aud(array_payload, options.merge(aud: 'no-match')) - end.to raise_error JWT::InvalidAudError - end - - it 'must allow a matching singular audience to pass' do - Verify.verify_aud(scalar_payload, options.merge(aud: scalar_aud)) - end - - it 'must allow an array with any value matching the one in the options' do - Verify.verify_aud(array_payload, options.merge(aud: array_aud.first)) - end - - it 'must allow an array with any value matching any value in the options array' do - Verify.verify_aud(array_payload, options.merge(aud: array_aud)) - end - - it 'must allow a singular audience payload matching any value in the options array' do - Verify.verify_aud(scalar_payload, options.merge(aud: array_aud)) - end - end - - context '.verify_expiration(payload, options)' do - let(:payload) { base_payload.merge('exp' => (Time.now.to_i - 5)) } - - it 'must raise JWT::ExpiredSignature when the token has expired' do - expect do - Verify.verify_expiration(payload, options) - end.to raise_error JWT::ExpiredSignature - end - - it 'must allow some leeway in the expiration when global leeway is configured' do - Verify.verify_expiration(payload, options.merge(leeway: 10)) - end - - it 'must allow some leeway in the expiration when exp_leeway is configured' do - Verify.verify_expiration(payload, options.merge(exp_leeway: 10)) - end - - it 'must be expired if the exp claim equals the current time' do - payload['exp'] = Time.now.to_i - - expect do - Verify.verify_expiration(payload, options) - end.to raise_error JWT::ExpiredSignature - end - - context 'when leeway is not specified' do - let(:options) { {} } - - it 'used a default leeway of 0' do - expect do - Verify.verify_expiration(payload, options) - end.to raise_error JWT::ExpiredSignature - end - end - end - - context '.verify_iat(payload, options)' do - let(:iat) { Time.now.to_f } - let(:payload) { base_payload.merge('iat' => iat) } - - it 'must allow a valid iat' do - Verify.verify_iat(payload, options) - end - - it 'must allow configured leeway' do - Verify.verify_iat(payload.merge('iat' => (iat + 60)), options.merge(leeway: 70)) - end - - it 'must allow configured iat_leeway' do - Verify.verify_iat(payload.merge('iat' => (iat + 60)), options.merge(iat_leeway: 70)) - end - - it 'must properly handle integer times' do - Verify.verify_iat(payload.merge('iat' => Time.now.to_i), options) - end - - it 'must raise JWT::InvalidIatError when the iat value is not Numeric' do - expect do - Verify.verify_iat(payload.merge('iat' => 'not a number'), options) - end.to raise_error JWT::InvalidIatError - end - - it 'must raise JWT::InvalidIatError when the iat value is in the future' do - expect do - Verify.verify_iat(payload.merge('iat' => (iat + 120)), options) - end.to raise_error JWT::InvalidIatError - end - end - - context '.verify_iss(payload, options)' do - let(:iss) { 'ruby-jwt-gem' } - let(:payload) { base_payload.merge('iss' => iss) } - - let(:invalid_token) { JWT.encode base_payload, payload[:secret] } - - context 'when iss is a String' do - it 'must raise JWT::InvalidIssuerError when the configured issuer does not match the payload issuer' do - expect do - Verify.verify_iss(payload, options.merge(iss: 'mismatched-issuer')) - end.to raise_error JWT::InvalidIssuerError - end - - it 'must raise JWT::InvalidIssuerError when the payload does not include an issuer' do - expect do - Verify.verify_iss(base_payload, options.merge(iss: iss)) - end.to raise_error(JWT::InvalidIssuerError, /received /) - end - - it 'must allow a matching issuer to pass' do - Verify.verify_iss(payload, options.merge(iss: iss)) - end - end - context 'when iss is an Array' do - it 'must raise JWT::InvalidIssuerError when no matching issuers in array' do - expect do - Verify.verify_iss(payload, options.merge(iss: %w[first second])) - end.to raise_error JWT::InvalidIssuerError - end - - it 'must raise JWT::InvalidIssuerError when the payload does not include an issuer' do - expect do - Verify.verify_iss(base_payload, options.merge(iss: %w[first second])) - end.to raise_error(JWT::InvalidIssuerError, /received /) - end - - it 'must allow an array with matching issuer to pass' do - Verify.verify_iss(payload, options.merge(iss: ['first', iss, 'third'])) - end - end - end - - context '.verify_jti(payload, options)' do - let(:payload) { base_payload.merge('jti' => 'some-random-uuid-or-whatever') } - - it 'must allow any jti when the verfy_jti key in the options is truthy but not a proc' do - Verify.verify_jti(payload, options.merge(verify_jti: true)) - end - - it 'must raise JWT::InvalidJtiError when the jti is missing' do - expect do - Verify.verify_jti(base_payload, options) - end.to raise_error JWT::InvalidJtiError, /missing/i - end - - it 'must raise JWT::InvalidJtiError when the jti is an empty string' do - expect do - Verify.verify_jti(base_payload.merge('jti' => ' '), options) - end.to raise_error JWT::InvalidJtiError, /missing/i - end - - it 'must raise JWT::InvalidJtiError when verify_jti proc returns false' do - expect do - Verify.verify_jti(payload, options.merge(verify_jti: ->(_jti) { false })) - end.to raise_error JWT::InvalidJtiError, /invalid/i - end - - it 'true proc should not raise JWT::InvalidJtiError' do - Verify.verify_jti(payload, options.merge(verify_jti: ->(_jti) { true })) - end - - it 'it should not throw arguement error with 2 args' do - expect do - Verify.verify_jti(payload, options.merge(verify_jti: ->(_jti, pl) { - true - })) - end.to_not raise_error - end - it 'should have payload as second param in proc' do - Verify.verify_jti(payload, options.merge(verify_jti: ->(_jti, pl) { - expect(pl).to eq(payload) - })) - end - end - - context '.verify_not_before(payload, options)' do - let(:payload) { base_payload.merge('nbf' => (Time.now.to_i + 5)) } - - it 'must raise JWT::ImmatureSignature when the nbf in the payload is in the future' do - expect do - Verify.verify_not_before(payload, options) - end.to raise_error JWT::ImmatureSignature - end - - it 'must allow some leeway in the token age when global leeway is configured' do - Verify.verify_not_before(payload, options.merge(leeway: 10)) - end - - it 'must allow some leeway in the token age when nbf_leeway is configured' do - Verify.verify_not_before(payload, options.merge(nbf_leeway: 10)) - end - end - - context '.verify_sub(payload, options)' do - let(:sub) { 'ruby jwt subject' } - - it 'must raise JWT::InvalidSubError when the subjects do not match' do - expect do - Verify.verify_sub(base_payload.merge('sub' => 'not-a-match'), options.merge(sub: sub)) - end.to raise_error JWT::InvalidSubError - end - - it 'must allow a matching sub' do - Verify.verify_sub(base_payload.merge('sub' => sub), options.merge(sub: sub)) - end - end - end -end diff --git a/debian/gems-compat/jwt-2.1.0/spec/jwt_spec.rb b/debian/gems-compat/jwt-2.1.0/spec/jwt_spec.rb deleted file mode 100644 index fbade515e6..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/jwt_spec.rb +++ /dev/null @@ -1,315 +0,0 @@ -require 'spec_helper' -require 'jwt' -require 'jwt/encode' -require 'jwt/decode' - -describe JWT do - let(:payload) { { 'user_id' => 'some@user.tld' } } - - let :data do - { - :secret => 'My$ecretK3y', - :rsa_private => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-private.pem'))), - :rsa_public => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-public.pem'))), - :wrong_rsa_private => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem'))), - :wrong_rsa_public => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem'))), - 'ES256_private' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-private.pem'))), - 'ES256_public' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-public.pem'))), - 'ES384_private' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec384-private.pem'))), - 'ES384_public' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec384-public.pem'))), - 'ES512_private' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec512-private.pem'))), - 'ES512_public' => OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec512-public.pem'))), - 'ED25519_private' => RbNaCl::Signatures::Ed25519::SigningKey.new('abcdefghijklmnopqrstuvwxyzABCDEF'), - 'ED25519_public' => RbNaCl::Signatures::Ed25519::SigningKey.new('abcdefghijklmnopqrstuvwxyzABCDEF').verify_key, - 'NONE' => 'eyJhbGciOiJub25lIn0.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.', - 'HS256' => 'eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.kWOVtIOpWcG7JnyJG0qOkTDbOy636XrrQhMm_8JrRQ8', - 'HS512256' => 'eyJhbGciOiJIUzUxMjI1NiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.Ds_4ibvf7z4QOBoKntEjDfthy3WJ-3rKMspTEcHE2bA', - 'HS384' => 'eyJhbGciOiJIUzM4NCJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.VuV4j4A1HKhWxCNzEcwc9qVF3frrEu-BRLzvYPkbWO0LENRGy5dOiBQ34remM3XH', - 'HS512' => 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.8zNtCBTJIZTHpZ-BkhR-6sZY1K85Nm5YCKqV3AxRdsBJDt_RR-REH2db4T3Y0uQwNknhrCnZGvhNHrvhDwV1kA', - 'RS256' => 'eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.eSXvWP4GViiwUALj_-qTxU68I1oM0XjgDsCZBBUri2Ghh9d75QkVDoZ_v872GaqunN5A5xcnBK0-cOq-CR6OwibgJWfOt69GNzw5RrOfQ2mz3QI3NYEq080nF69h8BeqkiaXhI24Q51joEgfa9aj5Y-oitLAmtDPYTm7vTcdGufd6AwD3_3jajKBwkh0LPSeMtbe_5EyS94nFoEF9OQuhJYjUmp7agsBVa8FFEjVw5jEgVqkvERSj5hSY4nEiCAomdVxIKBfykyi0d12cgjhI7mBFwWkPku8XIPGZ7N8vpiSLdM68BnUqIK5qR7NAhtvT7iyLFgOqhZNUQ6Ret5VpQ', - 'RS384' => 'eyJhbGciOiJSUzM4NCJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.Sfgk56moPghtsjaP4so6tOy3I553mgwX-5gByMC6dX8lpeWgsxSeAd_K8IyO7u4lwYOL0DSftnqO1HEOuN1AKyBbDvaTXz3u2xNA2x4NYLdW4AZA6ritbYcKLO5BHTXw5ueMbtA1jjGXP0zI_aK2iJTMBmB8SCF88RYBUH01Tyf4PlLj98pGL-v3prZd6kZkIeRJ3326h04hslcB5HQKmgeBk24QNLIoIC-CD329HPjJ7TtGx01lj-ehTBnwVbBGzYFAyoalV5KgvL_MDOfWPr1OYHnR5s_Fm6_3Vg4u6lBljvHOrmv4Nfx7d8HLgbo8CwH4qn1wm6VQCtuDd-uhRg', - 'RS512' => 'eyJhbGciOiJSUzUxMiJ9.eyJ1c2VyX2lkIjoic29tZUB1c2VyLnRsZCJ9.LIIAUEuCkGNdpYguOO5LoW4rZ7ED2POJrB0pmEAAchyTdIK4HKh1jcLxc6KyGwZv40njCgub3y72q6vcQTn7oD0zWFCVQRIDW1911Ii2hRNHuigiPUnrnZh1OQ6z65VZRU6GKs8omoBGU9vrClBU0ODqYE16KxYmE_0n4Xw2h3D_L1LF0IAOtDWKBRDa3QHwZRM9sHsHNsBuD5ye9KzDYN1YALXj64LBfA-DoCKfpVAm9NkRPOyzjR2X2C3TomOSJgqWIVHJucudKDDAZyEbO4RA5pI-UFYy1370p9bRajvtDyoBuLDCzoSkMyQ4L2DnLhx5CbWcnD7Cd3GUmnjjTA', - 'ES256' => '', - 'ES384' => '', - 'ES512' => '' - } - end - - after(:each) do - expect(OpenSSL.errors).to be_empty - end - - context 'alg: NONE' do - let(:alg) { 'none' } - - it 'should generate a valid token' do - token = JWT.encode payload, nil, alg - - expect(token).to eq data['NONE'] - end - - it 'should decode a valid token' do - jwt_payload, header = JWT.decode data['NONE'], nil, false - - expect(header['alg']).to eq alg - expect(jwt_payload).to eq payload - end - - it 'should display a better error message if payload exp is_a?(Time)' do - payload['exp'] = Time.now - - expect do - JWT.encode payload, nil, alg - end.to raise_error JWT::InvalidPayload - end - - it 'should display a better error message if payload exp is not an Integer' do - payload['exp'] = Time.now.to_i.to_s - - expect do - JWT.encode payload, nil, alg - end.to raise_error JWT::InvalidPayload - end - end - - %w[HS256 HS512256 HS384 HS512].each do |alg| - context "alg: #{alg}" do - it 'should generate a valid token' do - token = JWT.encode payload, data[:secret], alg - - expect(token).to eq data[alg] - end - - it 'should decode a valid token' do - jwt_payload, header = JWT.decode data[alg], data[:secret], true, algorithm: alg - - expect(header['alg']).to eq alg - expect(jwt_payload).to eq payload - end - - it 'wrong secret should raise JWT::DecodeError' do - expect do - JWT.decode data[alg], 'wrong_secret', true, algorithm: alg - end.to raise_error JWT::VerificationError - end - - it 'wrong secret and verify = false should not raise JWT::DecodeError' do - expect do - JWT.decode data[alg], 'wrong_secret', false - end.not_to raise_error - end - end - end - - %w[RS256 RS384 RS512].each do |alg| - context "alg: #{alg}" do - it 'should generate a valid token' do - token = JWT.encode payload, data[:rsa_private], alg - - expect(token).to eq data[alg] - end - - it 'should decode a valid token' do - jwt_payload, header = JWT.decode data[alg], data[:rsa_public], true, algorithm: alg - - expect(header['alg']).to eq alg - expect(jwt_payload).to eq payload - end - - it 'wrong key should raise JWT::DecodeError' do - key = OpenSSL::PKey.read File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem')) - - expect do - JWT.decode data[alg], key, true, algorithm: alg - end.to raise_error JWT::DecodeError - end - - it 'wrong key and verify = false should not raise JWT::DecodeError' do - key = OpenSSL::PKey.read File.read(File.join(CERT_PATH, 'rsa-2048-wrong-public.pem')) - - expect do - JWT.decode data[alg], key, false - end.not_to raise_error - end - end - end - - %w[ED25519].each do |alg| - context "alg: #{alg}" do - before(:each) do - data[alg] = JWT.encode payload, data["#{alg}_private"], alg - end - - let(:wrong_key) { OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-wrong-public.pem'))) } - - it 'should generate a valid token' do - jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg - - expect(header['alg']).to eq alg - expect(jwt_payload).to eq payload - end - - it 'should decode a valid token' do - jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg - - expect(header['alg']).to eq alg - expect(jwt_payload).to eq payload - end - - it 'wrong key should raise JWT::DecodeError' do - expect do - JWT.decode data[alg], wrong_key - end.to raise_error JWT::DecodeError - end - - it 'wrong key and verify = false should not raise JWT::DecodeError' do - expect do - JWT.decode data[alg], wrong_key, false - end.not_to raise_error - end - end - end - %w[ES256 ES384 ES512].each do |alg| - context "alg: #{alg}" do - before(:each) do - data[alg] = JWT.encode payload, data["#{alg}_private"], alg - end - - let(:wrong_key) { OpenSSL::PKey.read(File.read(File.join(CERT_PATH, 'ec256-wrong-public.pem'))) } - - it 'should generate a valid token' do - jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg - - expect(header['alg']).to eq alg - expect(jwt_payload).to eq payload - end - - it 'should decode a valid token' do - jwt_payload, header = JWT.decode data[alg], data["#{alg}_public"], true, algorithm: alg - - expect(header['alg']).to eq alg - expect(jwt_payload).to eq payload - end - - it 'wrong key should raise JWT::DecodeError' do - expect do - JWT.decode data[alg], wrong_key - end.to raise_error JWT::DecodeError - end - - it 'wrong key and verify = false should not raise JWT::DecodeError' do - expect do - JWT.decode data[alg], wrong_key, false - end.not_to raise_error - end - end - end - - context 'Invalid' do - it 'algorithm should raise NotImplementedError' do - expect do - JWT.encode payload, 'secret', 'HS255' - end.to raise_error NotImplementedError - end - - it 'ECDSA curve_name should raise JWT::IncorrectAlgorithm' do - key = OpenSSL::PKey::EC.new 'secp256k1' - key.generate_key - - expect do - JWT.encode payload, key, 'ES256' - end.to raise_error JWT::IncorrectAlgorithm - - token = JWT.encode payload, data['ES256_private'], 'ES256' - key.private_key = nil - - expect do - JWT.decode token, key - end.to raise_error JWT::IncorrectAlgorithm - end - end - - context 'Verify' do - context 'algorithm' do - it 'should raise JWT::IncorrectAlgorithm on mismatch' do - token = JWT.encode payload, data[:secret], 'HS256' - - expect do - JWT.decode token, data[:secret], true, algorithm: 'HS384' - end.to raise_error JWT::IncorrectAlgorithm - - expect do - JWT.decode token, data[:secret], true, algorithm: 'HS256' - end.not_to raise_error - end - - it 'should raise JWT::IncorrectAlgorithm when algorithms array does not contain algorithm' do - token = JWT.encode payload, data[:secret], 'HS512' - - expect do - JWT.decode token, data[:secret], true, algorithms: ['HS384'] - end.to raise_error JWT::IncorrectAlgorithm - - expect do - JWT.decode token, data[:secret], true, algorithms: ['HS512', 'HS384'] - end.not_to raise_error - end - - context 'no algorithm provided' do - it 'should use the default decode algorithm' do - token = JWT.encode payload, data[:rsa_public].to_s - - jwt_payload, header = JWT.decode token, data[:rsa_public].to_s - - expect(header['alg']).to eq 'HS256' - expect(jwt_payload).to eq payload - end - end - end - - context 'issuer claim' do - let(:iss) { 'ruby-jwt-gem' } - let(:invalid_token) { JWT.encode payload, data[:secret] } - - let :token do - iss_payload = payload.merge(iss: iss) - JWT.encode iss_payload, data[:secret] - end - - it 'if verify_iss is set to false (default option) should not raise JWT::InvalidIssuerError' do - expect do - JWT.decode token, data[:secret], true, iss: iss, algorithm: 'HS256' - end.not_to raise_error - end - end - end - - context 'Base64' do - it 'urlsafe replace + / with - _' do - allow(Base64).to receive(:encode64) { 'string+with/non+url-safe/characters_' } - expect(JWT::Encode.base64url_encode('foo')).to eq('string-with_non-url-safe_characters_') - end - end - - it 'should not verify token even if the payload has claims' do - head = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9' - load = 'eyJ1c2VyX2lkIjo1NCwiZXhwIjoxNTA0MzkwODA0fQ' - sign = 'Skpi6FfYMbZ-DwW9ocyRIosNMdPMAIWRLYxRO68GTQk' - - expect do - JWT.decode([head, load, sign].join('.'), '', false) - end.not_to raise_error - end - - it 'should not raise InvalidPayload exception if payload is an array' do - expect do - JWT.encode(['my', 'payload'], 'secret') - end.not_to raise_error - end - - it 'should encode string payloads' do - expect do - JWT.encode 'Hello World', 'secret' - end.not_to raise_error - end -end diff --git a/debian/gems-compat/jwt-2.1.0/spec/spec_helper.rb b/debian/gems-compat/jwt-2.1.0/spec/spec_helper.rb deleted file mode 100644 index a6ecae86df..0000000000 --- a/debian/gems-compat/jwt-2.1.0/spec/spec_helper.rb +++ /dev/null @@ -1,28 +0,0 @@ -require 'rspec' -require 'simplecov' -require 'simplecov-json' -require 'codeclimate-test-reporter' -require 'codacy-coverage' - -Codacy::Reporter.start - -SimpleCov.configure do - root File.join(File.dirname(__FILE__), '..') - project_name 'Ruby JWT - Ruby JSON Web Token implementation' - add_filter 'spec' -end - -SimpleCov.start if ENV['COVERAGE'] - -CERT_PATH = File.join(File.dirname(__FILE__), 'fixtures', 'certs') - -RSpec.configure do |config| - config.expect_with :rspec do |c| - c.syntax = %i[should expect] - end - - config.run_all_when_everything_filtered = true - config.filter_run :focus - - config.order = 'random' -end diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/.gitignore b/debian/gems-compat/omniauth-google-oauth2-0.6.1/.gitignore deleted file mode 100644 index 6eabdf28a3..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -*.gem -*.rbc -.bundle -.config -.yardoc -.ruby-gemset -.ruby-version -.rvmrc -Gemfile.lock -InstalledFiles -_yardoc -coverage -doc/ -lib/bundler/man -pkg -rdoc -spec/reports -test/tmp -test/version_tmp -tmp -.powenv -.idea/ diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/.rubocop.yml b/debian/gems-compat/omniauth-google-oauth2-0.6.1/.rubocop.yml deleted file mode 100644 index 82e572a464..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/.rubocop.yml +++ /dev/null @@ -1,23 +0,0 @@ -ClassLength: - Enabled: false -Layout/IndentHeredoc: - Enabled: false -Metrics/AbcSize: - Enabled: false -Metrics/BlockLength: - ExcludedMethods: ['describe', 'context'] -Metrics/CyclomaticComplexity: - Enabled: false -Metrics/LineLength: - Enabled: false -Metrics/MethodLength: - Enabled: false -Metrics/PerceivedComplexity: - Enabled: false -Naming: - Enabled: false -Style/MutableConstant: - Enabled: false -Gemspec/RequiredRubyVersion: - Enabled: false - diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/.travis.yml b/debian/gems-compat/omniauth-google-oauth2-0.6.1/.travis.yml deleted file mode 100644 index bcaeff9897..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: ruby -rvm: - - '2.1.10' - - '2.2.7' - - '2.3.4' - - '2.4.1' - - '2.5.0' diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/CHANGELOG.md b/debian/gems-compat/omniauth-google-oauth2-0.6.1/CHANGELOG.md deleted file mode 100644 index d01d3f11e5..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/CHANGELOG.md +++ /dev/null @@ -1,268 +0,0 @@ -# Changelog -All notable changes to this project will be documented in this file. - -## 0.6.1 - 2019-03-07 - -### Added -- Return `email` and `email_verified` keys in response. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Nothing. - -## 0.6.0 - 2018-12-28 - -### Added -- Support for JWT 2.x. - -### Deprecated -- Nothing. - -### Removed -- Support for JWT 1.x. -- Support for `raw_friend_info` and `raw_image_info`. -- Stop using Google+ API endpoints. - -### Fixed -- Nothing. - -## 0.5.4 - 2018-12-07 - -### Added -- New recommended endpoints for Google OAuth. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Nothing. - -## 0.5.3 - 2018-01-25 - -### Added -- Added support for the JWT 2.x gem. -- Now fully qualifies the `JWT` class to prevent conflicts with the `Omniauth::JWT` strategy. - -### Deprecated -- Nothing. - -### Removed -- Removed the `multijson` dependency. -- Support for versions of `omniauth-oauth2` < 1.5. - -### Fixed -- Nothing. - -## 0.5.2 - 2017-07-30 - -### Added -- Nothing. - -### Deprecated -- Nothing. - -### Removed -- New `authorize_url` and `token_url` endpoints are reverted until JWT 2.0 ships. - -### Fixed -- Nothing. - -## 0.5.1 - 2017-07-19 - -### Added -- *Breaking* JWT iss verification can be enabled/disabled with the `verify_iss` flag - see the README for more details. -- Authorize options now includes `device_id` and `device_name` for private ip ranges. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Updated `authorize_url` and `token_url` to new endpoints. - -## 0.5.0 - 2017-05-29 - -### Added -- Rubocop checks to specs. -- Defaulted dev environment to ruby 2.3.4. - -### Deprecated -- Nothing. - -### Removed -- Testing support for older versions of ruby not supported by OmniAuth 1.5. -- Key `[:urls]['Google']` no longer exists, it has been renamed to `[:urls][:google]`. - -### Fixed -- Updated all code to rubocop conventions. This includes the Ruby 1.9 hash syntax when appropriate. -- Example javascript flow now picks up ENV vars for google key and secret. - -## 0.4.1 - 2016-03-14 - -### Added -- Nothing. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Fixed JWT iat leeway by requiring ruby-jwt 1.5.2 - -## 0.4.0 - 2016-03-11 - -### Added -- Addedd ability to specify multiple hosted domains. -- Added a default leeway of 1 minute to JWT token validation. -- Now requires ruby-jwt 1.5.x. - -### Deprecated -- Nothing. - -### Removed -- Removed support for ruby 1.9.3 as ruby-jwt 1.5.x does not support it. - -### Fixed -- Nothing. - -## 0.3.1 - 2016-01-28 - -### Added -- Verify Hosted Domain if hd is set in options. - -### Deprecated -- Nothing. - -### Removed -- Dependency on addressable. - -### Fixed -- Nothing. - -## 0.3.0 - 2016-01-09 - -### Added -- Updated verify_token to use the v3 tokeninfo endpoint. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Compatibility with omniauth-oauth2 1.4.0 - -## 0.2.10 - 2015-11-05 - -### Added -- Nothing. - -### Deprecated -- Nothing. - -### Removed -- Removed some checks on the id_token. Now only parses the id_token in the JWT processing. - -### Fixed -- Nothing. - -## 0.2.9 - 2015-10-29 - -### Added -- Nothing. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Issue with omniauth-oauth2 where redirect_uri was handled improperly. We now lock the dependency to ~> 1.3.1 - -## 0.2.8 - 2015-10-01 - -### Added -- Added skip_jwt option to bypass JWT decoding in case you get decoding errors. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Resolved JWT::InvalidIatError. https://github.com/zquestz/omniauth-google-oauth2/issues/195 - -## 0.2.7 - 2015-09-25 - -### Added -- Now strips out the 'sz' parameter from profile image urls. -- Now uses 'addressable' gem for URI actions. -- Added image data to extras hash. -- Override validation on JWT token for open_id token. -- Handle authorization codes coming from an installed applications. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Fixes double slashes in google image urls. - -## 0.2.6 - 2014-10-26 - -### Added -- Nothing. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Hybrid authorization issues due to bad method alias. - -## 0.2.5 - 2014-07-09 - -### Added -- Support for versions of omniauth past 1.0.x. - -### Deprecated -- Nothing. - -### Removed -- Nothing. - -### Fixed -- Nothing. - -## 0.2.4 - 2014-04-25 - -### Added -- Now requiring the "Contacts API" and "Google+ API" to be enabled in your Google API console. - -### Deprecated -- The old Google OAuth API support was removed without deprecation. - -### Removed -- Support for the old Google OAuth API. `OAuth2::Error` will be thrown and state that access is not configured when you attempt to authenticate using the old API. See Added section for this release. - -### Fixed -- Nothing. diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/Gemfile b/debian/gems-compat/omniauth-google-oauth2-0.6.1/Gemfile deleted file mode 100644 index 7f4f5e950d..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/Gemfile +++ /dev/null @@ -1,5 +0,0 @@ -# frozen_string_literal: true - -source 'https://rubygems.org' - -gemspec diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/README.md b/debian/gems-compat/omniauth-google-oauth2-0.6.1/README.md deleted file mode 100644 index 5d811693a6..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/README.md +++ /dev/null @@ -1,300 +0,0 @@ -[![Gem Version](https://badge.fury.io/rb/omniauth-google-oauth2.svg)](https://badge.fury.io/rb/omniauth-google-oauth2) -[![Build Status](https://travis-ci.org/zquestz/omniauth-google-oauth2.svg)](https://travis-ci.org/zquestz/omniauth-google-oauth2) - -# OmniAuth Google OAuth2 Strategy - -Strategy to authenticate with Google via OAuth2 in OmniAuth. - -Get your API key at: https://code.google.com/apis/console/ Note the Client ID and the Client Secret. - -For more details, read the Google docs: https://developers.google.com/accounts/docs/OAuth2 - -## Installation - -Add to your `Gemfile`: - -```ruby -gem 'omniauth-google-oauth2' -``` - -Then `bundle install`. - -## Google API Setup - -* Go to 'https://console.developers.google.com' -* Select your project. -* Go to Credentials, then select the "OAuth consent screen" tab on top, and provide an 'EMAIL ADDRESS' and a 'PRODUCT NAME' -* Wait 10 minutes for changes to take effect. - -## Usage - -Here's an example for adding the middleware to a Rails app in `config/initializers/omniauth.rb`: - -```ruby -Rails.application.config.middleware.use OmniAuth::Builder do - provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'] -end -``` - -You can now access the OmniAuth Google OAuth2 URL: `/auth/google_oauth2` - -For more examples please check out `examples/omni_auth.rb` - -NOTE: While developing your application, if you change the scope in the initializer you will need to restart your app server. Remember that either the 'email' or 'profile' scope is required! - -## Configuration - -You can configure several options, which you pass in to the `provider` method via a hash: - -* `scope`: A comma-separated list of permissions you want to request from the user. See the [Google OAuth 2.0 Playground](https://developers.google.com/oauthplayground/) for a full list of available permissions. Caveats: - * The `email` and `profile` scopes are used by default. By defining your own `scope`, you override these defaults, but Google requires at least one of `email` or `profile`, so make sure to add at least one of them to your scope! - * Scopes starting with `https://www.googleapis.com/auth/` do not need that prefix specified. So while you can use the smaller scope `books` since that permission starts with the mentioned prefix, you should use the full scope URL `https://docs.google.com/feeds/` to access a user's docs, for example. - -* `redirect_uri`: Override the redirect_uri used by the gem. - -* `prompt`: A space-delimited list of string values that determines whether the user is re-prompted for authentication and/or consent. Possible values are: - * `none`: No authentication or consent pages will be displayed; it will return an error if the user is not already authenticated and has not pre-configured consent for the requested scopes. This can be used as a method to check for existing authentication and/or consent. - * `consent`: The user will always be prompted for consent, even if he has previously allowed access a given set of scopes. - * `select_account`: The user will always be prompted to select a user account. This allows a user who has multiple current account sessions to select one amongst them. - - If no value is specified, the user only sees the authentication page if he is not logged in and only sees the consent page the first time he authorizes a given set of scopes. - -* `image_aspect_ratio`: The shape of the user's profile picture. Possible values are: - * `original`: Picture maintains its original aspect ratio. - * `square`: Picture presents equal width and height. - - Defaults to `original`. - -* `image_size`: The size of the user's profile picture. The image returned will have width equal to the given value and variable height, according to the `image_aspect_ratio` chosen. Additionally, a picture with specific width and height can be requested by setting this option to a hash with `width` and `height` as keys. If only `width` or `height` is specified, a picture whose width or height is closest to the requested size and requested aspect ratio will be returned. Defaults to the original width and height of the picture. - -* `name`: The name of the strategy. The default name is `google_oauth2` but it can be changed to any value, for example `google`. The OmniAuth URL will thus change to `/auth/google` and the `provider` key in the auth hash will then return `google`. - -* `access_type`: Defaults to `offline`, so a refresh token is sent to be used when the user is not present at the browser. Can be set to `online`. More about [offline access](https://developers.google.com/identity/protocols/OAuth2WebServer#offline) - -* `hd`: (Optional) Limit sign-in to a particular Google Apps hosted domain. This can be simply string `'domain.com'` or an array `%w(domain.com domain.co)`. More information at: https://developers.google.com/accounts/docs/OpenIDConnect#hd-param - -* `jwt_leeway`: Number of seconds passed to the JWT library as leeway. Defaults to 60 seconds. - -* `skip_jwt`: Skip JWT processing. This is for users who are seeing JWT decoding errors with the `iat` field. Always try adjusting the leeway before disabling JWT processing. - -* `login_hint`: When your app knows which user it is trying to authenticate, it can provide this parameter as a hint to the authentication server. Passing this hint suppresses the account chooser and either pre-fill the email box on the sign-in form, or select the proper session (if the user is using multiple sign-in), which can help you avoid problems that occur if your app logs in the wrong user account. The value can be either an email address or the sub string, which is equivalent to the user's Google+ ID. - -* `include_granted_scopes`: If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes. See Google's [Incremental Authorization](https://developers.google.com/accounts/docs/OAuth2WebServer#incrementalAuth) for additional details. - -* `openid_realm`: Set the OpenID realm value, to allow upgrading from OpenID based authentication to OAuth 2 based authentication. When this is set correctly an `openid_id` value will be set in `[:extra][:id_info]` in the authentication hash with the value of the user's OpenID ID URL. - -Here's an example of a possible configuration where the strategy name is changed, the user is asked for extra permissions, the user is always prompted to select his account when logging in and the user's profile picture is returned as a thumbnail: - -```ruby -Rails.application.config.middleware.use OmniAuth::Builder do - provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], - { - scope: 'userinfo.email, userinfo.profile, http://gdata.youtube.com', - prompt: 'select_account', - image_aspect_ratio: 'square', - image_size: 50 - } -end -``` - -## Auth Hash - -Here's an example of an authentication hash available in the callback by accessing `request.env['omniauth.auth']`: - -```ruby -{ - "provider" => "google_oauth2", - "uid" => "100000000000000000000", - "info" => { - "name" => "John Smith", - "email" => "john@example.com", - "first_name" => "John", - "last_name" => "Smith", - "image" => "https://lh4.googleusercontent.com/photo.jpg", - "urls" => { - "google" => "https://plus.google.com/+JohnSmith" - } - }, - "credentials" => { - "token" => "TOKEN", - "refresh_token" => "REFRESH_TOKEN", - "expires_at" => 1496120719, - "expires" => true - }, - "extra" => { - "id_token" => "ID_TOKEN", - "id_info" => { - "azp" => "APP_ID", - "aud" => "APP_ID", - "sub" => "100000000000000000000", - "email" => "john@example.com", - "email_verified" => true, - "at_hash" => "HK6E_P6Dh8Y93mRNtsDB1Q", - "iss" => "accounts.google.com", - "iat" => 1496117119, - "exp" => 1496120719 - }, - "raw_info" => { - "sub" => "100000000000000000000", - "name" => "John Smith", - "given_name" => "John", - "family_name" => "Smith", - "profile" => "https://plus.google.com/+JohnSmith", - "picture" => "https://lh4.googleusercontent.com/photo.jpg?sz=50", - "email" => "john@example.com", - "email_verified" => "true", - "locale" => "en", - "hd" => "company.com" - } - } -} -``` - -### Devise - -First define your application id and secret in `config/initializers/devise.rb`. Do not use the snippet mentioned in the [Usage](https://github.com/zquestz/omniauth-google-oauth2#usage) section. - -Configuration options can be passed as the last parameter here as key/value pairs. - -```ruby -config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', {} -``` -NOTE: If you are using this gem with devise with above snippet in `config/initializers/devise.rb` then do not create `config/initializers/omniauth.rb` which will conflict with devise configurations. - -Then add the following to 'config/routes.rb' so the callback routes are defined. - -```ruby -devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' } -``` - -Make sure your model is omniauthable. Generally this is "/app/models/user.rb" - -```ruby -devise :omniauthable, omniauth_providers: [:google_oauth2] -``` - -Then make sure your callbacks controller is setup. - -```ruby -class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController - def google_oauth2 - # You need to implement the method below in your model (e.g. app/models/user.rb) - @user = User.from_omniauth(request.env['omniauth.auth']) - - if @user.persisted? - flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google' - sign_in_and_redirect @user, event: :authentication - else - session['devise.google_data'] = request.env['omniauth.auth'].except(:extra) # Removing extra as it can overflow some session stores - redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n") - end - end -end -``` - -and bind to or create the user - -```ruby -def self.from_omniauth(access_token) - data = access_token.info - user = User.where(email: data['email']).first - - # Uncomment the section below if you want users to be created if they don't exist - # unless user - # user = User.create(name: data['name'], - # email: data['email'], - # password: Devise.friendly_token[0,20] - # ) - # end - user -end -``` - -For your views you can login using: - -```erb -<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %> - -<%# Devise prior 4.1.0: %> -<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %> -``` - -An overview is available at https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview - -### One-time Code Flow (Hybrid Authentication) - -Google describes the One-time Code Flow [here](https://developers.google.com/+/web/signin/server-side-flow). This hybrid authentication flow has significant functional and security advantages over a pure server-side or pure client-side flow. The following steps occur in this flow: - -1. The client (web browser) authenticates the user directly via Google's JS API. During this process assorted modals may be rendered by Google. -2. On successful authentication, Google returns a one-time use code, which requires the Google client secret (which is only available server-side). -3. Using a AJAX request, the code is POSTed to the Omniauth Google OAuth2 callback. -4. The Omniauth Google OAuth2 gem will validate the code via a server-side request to Google. If the code is valid, then Google will return an access token and, if this is the first time this user is authenticating against this application, a refresh token. Both of these should be stored on the server. The response to the AJAX request indicates the success or failure of this process. - -This flow is immune to replay attacks, and conveys no useful information to a man in the middle. - -The omniauth-google-oauth2 gem supports this mode of operation out of the box. Implementors simply need to add the appropriate JavaScript to their web page, and they can take advantage of this flow. An example JavaScript snippet follows. - -```javascript -// Basic hybrid auth example following the pattern at: -// https://developers.google.com/identity/sign-in/web/reference - - - -... - -function init() { - gapi.load('auth2', function() { - // Ready. - $('.google-login-button').click(function(e) { - e.preventDefault(); - - gapi.auth2.authorize({ - client_id: 'YOUR_CLIENT_ID', - cookie_policy: 'single_host_origin', - scope: 'email profile', - response_type: 'code' - }, function(response) { - if (response && !response.error) { - // google authentication succeed, now post data to server. - jQuery.ajax({type: 'POST', url: '/auth/google_oauth2/callback', data: response, - success: function(data) { - // response from server - } - }); - } else { - // google authentication failed - } - }); - }); - }); -}; -``` - -#### Note about mobile clients (iOS, Android) - -The documentation at https://developers.google.com/identity/sign-in/ios/offline-access specifies the _REDIRECT_URI_ to be either a set value or an EMPTY string for mobile logins to work. Else, you will run into _redirect_uri_mismatch_ errors. - -In that case, ensure to send an additional parameter `redirect_uri=` (empty string) to the `/auth/google_oauth2/callback` URL from your mobile device. - -#### Note about CORS - -If you're making POST requests to `/auth/google_oauth2/callback` from another domain, then you need to make sure `'X-Requested-With': 'XMLHttpRequest'` header is included with your request, otherwise your server might respond with `OAuth2::Error, : Invalid Value` error. - -## Fixing Protocol Mismatch for `redirect_uri` in Rails - -Just set the `full_host` in OmniAuth based on the Rails.env. - -``` -# config/initializers/omniauth.rb -OmniAuth.config.full_host = Rails.env.production? ? 'https://domain.com' : 'http://localhost:3000' -``` - -## License - -Copyright (c) 2018 by Josh Ellithorpe - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/Rakefile b/debian/gems-compat/omniauth-google-oauth2-0.6.1/Rakefile deleted file mode 100644 index db36369bc1..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/Rakefile +++ /dev/null @@ -1,8 +0,0 @@ -# frozen_string_literal: true - -require File.join('bundler', 'gem_tasks') -require File.join('rspec', 'core', 'rake_task') - -RSpec::Core::RakeTask.new(:spec) - -task default: :spec diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/Gemfile b/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/Gemfile deleted file mode 100644 index f3ce8d55a1..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/Gemfile +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true - -source 'https://rubygems.org' - -gem 'omniauth-google-oauth2', '~> 0.6' -gem 'rubocop' -gem 'sinatra', '~> 1.4' diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/config.ru b/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/config.ru deleted file mode 100644 index ee17929094..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/config.ru +++ /dev/null @@ -1,120 +0,0 @@ -# frozen_string_literal: true - -# Sample app for Google OAuth2 Strategy -# Make sure to setup the ENV variables GOOGLE_KEY and GOOGLE_SECRET -# Run with "bundle exec rackup" - -require 'rubygems' -require 'bundler' -require 'sinatra' -require 'omniauth' -require 'omniauth-google-oauth2' - -# Do not use for production code. -# This is only to make setup easier when running through the sample. -# -# If you do have issues with certs in production code, this could help: -# http://railsapps.github.io/openssl-certificate-verify-failed.html -OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE - -# Main example app for omniauth-google-oauth2 -class App < Sinatra::Base - get '/' do - <<-HTML - - - - Google OAuth2 Example - - - - - - - - HTML - end - - post '/auth/:provider/callback' do - content_type 'text/plain' - begin - request.env['omniauth.auth'].to_hash.inspect - rescue StandardError - 'No Data' - end - end - - get '/auth/:provider/callback' do - content_type 'text/plain' - begin - request.env['omniauth.auth'].to_hash.inspect - rescue StandardError - 'No Data' - end - end - - get '/auth/failure' do - content_type 'text/plain' - begin - request.env['omniauth.auth'].to_hash.inspect - rescue StandardError - 'No Data' - end - end -end - -use Rack::Session::Cookie, secret: ENV['RACK_COOKIE_SECRET'] - -use OmniAuth::Builder do - # For additional provider examples please look at 'omni_auth.rb' - # The key provider_ignores_state is only for AJAX flows. It is not recommended for normal logins. - provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline', prompt: 'consent', provider_ignores_state: true, scope: 'email,profile,calendar' -end - -run App.new diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/omni_auth.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/omni_auth.rb deleted file mode 100644 index 127b62a9aa..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/examples/omni_auth.rb +++ /dev/null @@ -1,33 +0,0 @@ -# frozen_string_literal: true - -# Google's OAuth2 docs. Make sure you are familiar with all the options -# before attempting to configure this gem. -# https://developers.google.com/accounts/docs/OAuth2Login - -Rails.application.config.middleware.use OmniAuth::Builder do - # Default usage, this will give you offline access and a refresh token - # using default scopes 'email' and 'profile' - # - provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'email,profile' - - # Manual setup for offline access with a refresh token. - # - # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'offline' - - # Custom scope supporting youtube. If you are customizing scopes, remember - # to include the default scopes 'email' and 'profile' - # - # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], scope: 'http://gdata.youtube.com,email,profile,plus.me' - - # Custom scope for users only using Google for account creation/auth and do not require a refresh token. - # - # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], access_type: 'online', prompt: '' - - # To include information about people in your circles you must include the 'plus.login' scope. - # - # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], skip_friends: false, scope: 'email,profile,plus.login' - - # If you need to acquire whether user picture is a default one or uploaded by user. - # - # provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], skip_image_info: false -end diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth-google-oauth2.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth-google-oauth2.rb deleted file mode 100644 index a5cc57ab4c..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth-google-oauth2.rb +++ /dev/null @@ -1,3 +0,0 @@ -# frozen_string_literal: true - -require 'omniauth/google_oauth2' diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/google_oauth2.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/google_oauth2.rb deleted file mode 100644 index 594c9a4eed..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/google_oauth2.rb +++ /dev/null @@ -1,3 +0,0 @@ -# frozen_string_literal: true - -require 'omniauth/strategies/google_oauth2' diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/google_oauth2/version.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/google_oauth2/version.rb deleted file mode 100644 index 54d4667810..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/google_oauth2/version.rb +++ /dev/null @@ -1,7 +0,0 @@ -# frozen_string_literal: true - -module OmniAuth - module GoogleOauth2 - VERSION = '0.6.1' - end -end diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/strategies/google_oauth2.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/strategies/google_oauth2.rb deleted file mode 100644 index 30b2c041e9..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/lib/omniauth/strategies/google_oauth2.rb +++ /dev/null @@ -1,209 +0,0 @@ -# frozen_string_literal: true - -require 'jwt' -require 'omniauth/strategies/oauth2' -require 'uri' - -module OmniAuth - module Strategies - # Main class for Google OAuth2 strategy. - class GoogleOauth2 < OmniAuth::Strategies::OAuth2 - ALLOWED_ISSUERS = ['accounts.google.com', 'https://accounts.google.com'].freeze - BASE_SCOPE_URL = 'https://www.googleapis.com/auth/' - BASE_SCOPES = %w[profile email openid].freeze - DEFAULT_SCOPE = 'email,profile' - USER_INFO_URL = 'https://www.googleapis.com/oauth2/v3/userinfo' - - option :name, 'google_oauth2' - option :skip_friends, true - option :skip_image_info, true - option :skip_jwt, false - option :jwt_leeway, 60 - option :authorize_options, %i[access_type hd login_hint prompt request_visible_actions scope state redirect_uri include_granted_scopes openid_realm device_id device_name] - option :authorized_client_ids, [] - - option :client_options, - site: 'https://oauth2.googleapis.com', - authorize_url: 'https://accounts.google.com/o/oauth2/auth', - token_url: '/token' - - def authorize_params - super.tap do |params| - options[:authorize_options].each do |k| - params[k] = request.params[k.to_s] unless [nil, ''].include?(request.params[k.to_s]) - end - - params[:scope] = get_scope(params) - params[:access_type] = 'offline' if params[:access_type].nil? - params['openid.realm'] = params.delete(:openid_realm) unless params[:openid_realm].nil? - - session['omniauth.state'] = params[:state] if params[:state] - end - end - - uid { raw_info['sub'] } - - info do - prune!( - name: raw_info['name'], - email: raw_info['email'], - email_verified: raw_info['email_verified'], - first_name: raw_info['given_name'], - last_name: raw_info['family_name'], - image: image_url, - urls: { - google: raw_info['profile'] - } - ) - end - - extra do - hash = {} - hash[:id_token] = access_token['id_token'] - if !options[:skip_jwt] && !access_token['id_token'].nil? - decoded = ::JWT.decode(access_token['id_token'], nil, false).first - - # We have to manually verify the claims because the third parameter to - # JWT.decode is false since no verification key is provided. - ::JWT::Verify.verify_claims(decoded, - verify_iss: true, - iss: ALLOWED_ISSUERS, - verify_aud: true, - aud: options.client_id, - verify_sub: false, - verify_expiration: true, - verify_not_before: true, - verify_iat: true, - verify_jti: false, - leeway: options[:jwt_leeway]) - - hash[:id_info] = decoded - end - hash[:raw_info] = raw_info unless skip_info? - prune! hash - end - - def raw_info - @raw_info ||= access_token.get(USER_INFO_URL).parsed - end - - def custom_build_access_token - access_token = get_access_token(request) - - verify_hd(access_token) - access_token - end - alias build_access_token custom_build_access_token - - private - - def callback_url - options[:redirect_uri] || (full_host + script_name + callback_path) - end - - def get_access_token(request) - if request.xhr? && request.params['code'] - verifier = request.params['code'] - redirect_uri = request.params['redirect_uri'] || 'postmessage' - client.auth_code.get_token(verifier, get_token_options(redirect_uri), deep_symbolize(options.auth_token_params || {})) - elsif request.params['code'] && request.params['redirect_uri'] - verifier = request.params['code'] - redirect_uri = request.params['redirect_uri'] - client.auth_code.get_token(verifier, get_token_options(redirect_uri), deep_symbolize(options.auth_token_params || {})) - elsif verify_token(request.params['access_token']) - ::OAuth2::AccessToken.from_hash(client, request.params.dup) - else - verifier = request.params['code'] - client.auth_code.get_token(verifier, get_token_options(callback_url), deep_symbolize(options.auth_token_params)) - end - end - - def get_scope(params) - raw_scope = params[:scope] || DEFAULT_SCOPE - scope_list = raw_scope.split(' ').map { |item| item.split(',') }.flatten - scope_list.map! { |s| s =~ %r{^https?://} || BASE_SCOPES.include?(s) ? s : "#{BASE_SCOPE_URL}#{s}" } - scope_list.join(' ') - end - - def get_token_options(redirect_uri) - { redirect_uri: redirect_uri }.merge(token_params.to_hash(symbolize_keys: true)) - end - - def prune!(hash) - hash.delete_if do |_, v| - prune!(v) if v.is_a?(Hash) - v.nil? || (v.respond_to?(:empty?) && v.empty?) - end - end - - def image_url - return nil unless raw_info['picture'] - - u = URI.parse(raw_info['picture'].gsub('https:https', 'https')) - - path_index = u.path.to_s.index('/photo.jpg') - - if path_index && image_size_opts_passed? - u.path.insert(path_index, image_params) - u.path = u.path.gsub('//', '/') - end - - u.query = strip_unnecessary_query_parameters(u.query) - - u.to_s - end - - def image_size_opts_passed? - options[:image_size] || options[:image_aspect_ratio] - end - - def image_params - image_params = [] - if options[:image_size].is_a?(Integer) - image_params << "s#{options[:image_size]}" - elsif options[:image_size].is_a?(Hash) - image_params << "w#{options[:image_size][:width]}" if options[:image_size][:width] - image_params << "h#{options[:image_size][:height]}" if options[:image_size][:height] - end - image_params << 'c' if options[:image_aspect_ratio] == 'square' - - '/' + image_params.join('-') - end - - def strip_unnecessary_query_parameters(query_parameters) - # strip `sz` parameter (defaults to sz=50) which overrides `image_size` options - return nil if query_parameters.nil? - - params = CGI.parse(query_parameters) - stripped_params = params.delete_if { |key| key == 'sz' } - - # don't return an empty Hash since that would result - # in URLs with a trailing ? character: http://image.url? - return nil if stripped_params.empty? - - URI.encode_www_form(stripped_params) - end - - def verify_token(access_token) - return false unless access_token - - raw_response = client.request(:get, 'https://www.googleapis.com/oauth2/v3/tokeninfo', - params: { access_token: access_token }).parsed - raw_response['aud'] == options.client_id || options.authorized_client_ids.include?(raw_response['aud']) - end - - def verify_hd(access_token) - return true unless options.hd - - @raw_info ||= access_token.get(USER_INFO_URL).parsed - - options.hd = options.hd.call if options.hd.is_a? Proc - allowed_hosted_domains = Array(options.hd) - - raise CallbackError.new(:invalid_hd, 'Invalid Hosted Domain') unless allowed_hosted_domains.include?(@raw_info['hd']) || options.hd == '*' - - true - end - end - end -end diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/omniauth-google-oauth2.gemspec b/debian/gems-compat/omniauth-google-oauth2-0.6.1/omniauth-google-oauth2.gemspec deleted file mode 100644 index 74fd1473de..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/omniauth-google-oauth2.gemspec +++ /dev/null @@ -1,30 +0,0 @@ -# frozen_string_literal: true - -require File.expand_path( - File.join('..', 'lib', 'omniauth', 'google_oauth2', 'version'), - __FILE__ -) - -Gem::Specification.new do |gem| - gem.name = 'omniauth-google-oauth2' - gem.version = OmniAuth::GoogleOauth2::VERSION - gem.license = 'MIT' - gem.summary = %(A Google OAuth2 strategy for OmniAuth 1.x) - gem.description = %(A Google OAuth2 strategy for OmniAuth 1.x. This allows you to login to Google with your ruby app.) - gem.authors = ['Josh Ellithorpe', 'Yury Korolev'] - gem.email = ['quest@mac.com'] - gem.homepage = 'https://github.com/zquestz/omniauth-google-oauth2' - - gem.files = `git ls-files`.split("\n") - gem.require_paths = ['lib'] - - gem.required_ruby_version = '>= 2.1' - - gem.add_runtime_dependency 'jwt', '>= 2.0' - gem.add_runtime_dependency 'omniauth', '>= 1.1.1' - gem.add_runtime_dependency 'omniauth-oauth2', '>= 1.5' - - gem.add_development_dependency 'rake', '~> 12.0' - gem.add_development_dependency 'rspec', '~> 3.6' - gem.add_development_dependency 'rubocop', '~> 0.49' -end diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/omniauth/strategies/google_oauth2_spec.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/omniauth/strategies/google_oauth2_spec.rb deleted file mode 100644 index 78265fe73a..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/omniauth/strategies/google_oauth2_spec.rb +++ /dev/null @@ -1,692 +0,0 @@ -# frozen_string_literal: true - -require 'spec_helper' -require 'json' -require 'omniauth-google-oauth2' - -describe OmniAuth::Strategies::GoogleOauth2 do - let(:request) { double('Request', params: {}, cookies: {}, env: {}) } - let(:app) do - lambda do - [200, {}, ['Hello.']] - end - end - - subject do - OmniAuth::Strategies::GoogleOauth2.new(app, 'appid', 'secret', @options || {}).tap do |strategy| - allow(strategy).to receive(:request) do - request - end - end - end - - before do - OmniAuth.config.test_mode = true - end - - after do - OmniAuth.config.test_mode = false - end - - describe '#client_options' do - it 'has correct site' do - expect(subject.client.site).to eq('https://oauth2.googleapis.com') - end - - it 'has correct authorize_url' do - expect(subject.client.options[:authorize_url]).to eq('https://accounts.google.com/o/oauth2/auth') - end - - it 'has correct token_url' do - expect(subject.client.options[:token_url]).to eq('/token') - end - - describe 'overrides' do - context 'as strings' do - it 'should allow overriding the site' do - @options = { client_options: { 'site' => 'https://example.com' } } - expect(subject.client.site).to eq('https://example.com') - end - - it 'should allow overriding the authorize_url' do - @options = { client_options: { 'authorize_url' => 'https://example.com' } } - expect(subject.client.options[:authorize_url]).to eq('https://example.com') - end - - it 'should allow overriding the token_url' do - @options = { client_options: { 'token_url' => 'https://example.com' } } - expect(subject.client.options[:token_url]).to eq('https://example.com') - end - end - - context 'as symbols' do - it 'should allow overriding the site' do - @options = { client_options: { site: 'https://example.com' } } - expect(subject.client.site).to eq('https://example.com') - end - - it 'should allow overriding the authorize_url' do - @options = { client_options: { authorize_url: 'https://example.com' } } - expect(subject.client.options[:authorize_url]).to eq('https://example.com') - end - - it 'should allow overriding the token_url' do - @options = { client_options: { token_url: 'https://example.com' } } - expect(subject.client.options[:token_url]).to eq('https://example.com') - end - end - end - end - - describe '#authorize_options' do - %i[access_type hd login_hint prompt scope state device_id device_name].each do |k| - it "should support #{k}" do - @options = { k => 'http://someval' } - expect(subject.authorize_params[k.to_s]).to eq('http://someval') - end - end - - describe 'redirect_uri' do - it 'should default to nil' do - @options = {} - expect(subject.authorize_params['redirect_uri']).to eq(nil) - end - - it 'should set the redirect_uri parameter if present' do - @options = { redirect_uri: 'https://example.com' } - expect(subject.authorize_params['redirect_uri']).to eq('https://example.com') - end - end - - describe 'access_type' do - it 'should default to "offline"' do - @options = {} - expect(subject.authorize_params['access_type']).to eq('offline') - end - - it 'should set the access_type parameter if present' do - @options = { access_type: 'online' } - expect(subject.authorize_params['access_type']).to eq('online') - end - end - - describe 'hd' do - it 'should default to nil' do - expect(subject.authorize_params['hd']).to eq(nil) - end - - it 'should set the hd (hosted domain) parameter if present' do - @options = { hd: 'example.com' } - expect(subject.authorize_params['hd']).to eq('example.com') - end - - it 'should set the hd parameter and work with nil hd (gmail)' do - @options = { hd: nil } - expect(subject.authorize_params['hd']).to eq(nil) - end - - it 'should set the hd parameter to * if set (only allows G Suite emails)' do - @options = { hd: '*' } - expect(subject.authorize_params['hd']).to eq('*') - end - end - - describe 'login_hint' do - it 'should default to nil' do - expect(subject.authorize_params['login_hint']).to eq(nil) - end - - it 'should set the login_hint parameter if present' do - @options = { login_hint: 'john@example.com' } - expect(subject.authorize_params['login_hint']).to eq('john@example.com') - end - end - - describe 'prompt' do - it 'should default to nil' do - expect(subject.authorize_params['prompt']).to eq(nil) - end - - it 'should set the prompt parameter if present' do - @options = { prompt: 'consent select_account' } - expect(subject.authorize_params['prompt']).to eq('consent select_account') - end - end - - describe 'request_visible_actions' do - it 'should default to nil' do - expect(subject.authorize_params['request_visible_actions']).to eq(nil) - end - - it 'should set the request_visible_actions parameter if present' do - @options = { request_visible_actions: 'something' } - expect(subject.authorize_params['request_visible_actions']).to eq('something') - end - end - - describe 'include_granted_scopes' do - it 'should default to nil' do - expect(subject.authorize_params['include_granted_scopes']).to eq(nil) - end - - it 'should set the include_granted_scopes parameter if present' do - @options = { include_granted_scopes: 'true' } - expect(subject.authorize_params['include_granted_scopes']).to eq('true') - end - end - - describe 'scope' do - it 'should expand scope shortcuts' do - @options = { scope: 'calendar' } - expect(subject.authorize_params['scope']).to eq('https://www.googleapis.com/auth/calendar') - end - - it 'should leave base scopes as is' do - @options = { scope: 'profile' } - expect(subject.authorize_params['scope']).to eq('profile') - end - - it 'should join scopes' do - @options = { scope: 'profile,email' } - expect(subject.authorize_params['scope']).to eq('profile email') - end - - it 'should deal with whitespace when joining scopes' do - @options = { scope: 'profile, email' } - expect(subject.authorize_params['scope']).to eq('profile email') - end - - it 'should set default scope to email,profile' do - expect(subject.authorize_params['scope']).to eq('email profile') - end - - it 'should support space delimited scopes' do - @options = { scope: 'profile email' } - expect(subject.authorize_params['scope']).to eq('profile email') - end - - it 'should support extremely badly formed scopes' do - @options = { scope: 'profile email,foo,steve yeah http://example.com' } - expect(subject.authorize_params['scope']).to eq('profile email https://www.googleapis.com/auth/foo https://www.googleapis.com/auth/steve https://www.googleapis.com/auth/yeah http://example.com') - end - end - - describe 'state' do - it 'should set the state parameter' do - @options = { state: 'some_state' } - expect(subject.authorize_params['state']).to eq('some_state') - expect(subject.authorize_params[:state]).to eq('some_state') - expect(subject.session['omniauth.state']).to eq('some_state') - end - - it 'should set the omniauth.state dynamically' do - allow(subject).to receive(:request) { double('Request', params: { 'state' => 'some_state' }, env: {}) } - expect(subject.authorize_params['state']).to eq('some_state') - expect(subject.authorize_params[:state]).to eq('some_state') - expect(subject.session['omniauth.state']).to eq('some_state') - end - end - - describe 'overrides' do - it 'should include top-level options that are marked as :authorize_options' do - @options = { authorize_options: %i[scope foo request_visible_actions], scope: 'http://bar', foo: 'baz', hd: 'wow', request_visible_actions: 'something' } - expect(subject.authorize_params['scope']).to eq('http://bar') - expect(subject.authorize_params['foo']).to eq('baz') - expect(subject.authorize_params['hd']).to eq(nil) - expect(subject.authorize_params['request_visible_actions']).to eq('something') - end - - describe 'request overrides' do - %i[access_type hd login_hint prompt scope state].each do |k| - context "authorize option #{k}" do - let(:request) { double('Request', params: { k.to_s => 'http://example.com' }, cookies: {}, env: {}) } - - it "should set the #{k} authorize option dynamically in the request" do - @options = { k: '' } - expect(subject.authorize_params[k.to_s]).to eq('http://example.com') - end - end - end - - describe 'custom authorize_options' do - let(:request) { double('Request', params: { 'foo' => 'something' }, cookies: {}, env: {}) } - - it 'should support request overrides from custom authorize_options' do - @options = { authorize_options: [:foo], foo: '' } - expect(subject.authorize_params['foo']).to eq('something') - end - end - end - end - end - - describe '#authorize_params' do - it 'should include any authorize params passed in the :authorize_params option' do - @options = { authorize_params: { request_visible_actions: 'something', foo: 'bar', baz: 'zip' }, hd: 'wow', bad: 'not_included' } - expect(subject.authorize_params['request_visible_actions']).to eq('something') - expect(subject.authorize_params['foo']).to eq('bar') - expect(subject.authorize_params['baz']).to eq('zip') - expect(subject.authorize_params['hd']).to eq('wow') - expect(subject.authorize_params['bad']).to eq(nil) - end - end - - describe '#token_params' do - it 'should include any token params passed in the :token_params option' do - @options = { token_params: { foo: 'bar', baz: 'zip' } } - expect(subject.token_params['foo']).to eq('bar') - expect(subject.token_params['baz']).to eq('zip') - end - end - - describe '#token_options' do - it 'should include top-level options that are marked as :token_options' do - @options = { token_options: %i[scope foo], scope: 'bar', foo: 'baz', bad: 'not_included' } - expect(subject.token_params['scope']).to eq('bar') - expect(subject.token_params['foo']).to eq('baz') - expect(subject.token_params['bad']).to eq(nil) - end - end - - describe '#callback_path' do - it 'has the correct default callback path' do - expect(subject.callback_path).to eq('/auth/google_oauth2/callback') - end - - it 'should set the callback_path parameter if present' do - @options = { callback_path: '/auth/foo/callback' } - expect(subject.callback_path).to eq('/auth/foo/callback') - end - end - - describe '#extra' do - let(:client) do - OAuth2::Client.new('abc', 'def') do |builder| - builder.request :url_encoded - builder.adapter :test do |stub| - stub.get('/oauth2/v3/userinfo') { [200, { 'content-type' => 'application/json' }, '{"sub": "12345"}'] } - end - end - end - let(:access_token) { OAuth2::AccessToken.from_hash(client, {}) } - - before { allow(subject).to receive(:access_token).and_return(access_token) } - - describe 'id_token' do - shared_examples 'id_token issued by valid issuer' do |issuer| # rubocop:disable Metrics/BlockLength - context 'when the id_token is passed into the access token' do - let(:token_info) do - { - 'abc' => 'xyz', - 'exp' => Time.now.to_i + 3600, - 'nbf' => Time.now.to_i - 60, - 'iat' => Time.now.to_i, - 'aud' => 'appid', - 'iss' => issuer - } - end - let(:id_token) { JWT.encode(token_info, 'secret') } - let(:access_token) { OAuth2::AccessToken.from_hash(client, 'id_token' => id_token) } - - it 'should include id_token when set on the access_token' do - expect(subject.extra).to include(id_token: id_token) - end - - it 'should include id_info when id_token is set on the access_token and skip_jwt is false' do - subject.options[:skip_jwt] = false - expect(subject.extra).to include(id_info: token_info) - end - - it 'should not include id_info when id_token is set on the access_token and skip_jwt is true' do - subject.options[:skip_jwt] = true - expect(subject.extra).not_to have_key(:id_info) - end - - it 'should include id_info when id_token is set on the access_token by default' do - expect(subject.extra).to include(id_info: token_info) - end - end - end - - it_behaves_like 'id_token issued by valid issuer', 'accounts.google.com' - it_behaves_like 'id_token issued by valid issuer', 'https://accounts.google.com' - - context 'when the id_token is issued by an invalid issuer' do - let(:token_info) do - { - 'abc' => 'xyz', - 'exp' => Time.now.to_i + 3600, - 'nbf' => Time.now.to_i - 60, - 'iat' => Time.now.to_i, - 'aud' => 'appid', - 'iss' => 'fake.google.com' - } - end - let(:id_token) { JWT.encode(token_info, 'secret') } - let(:access_token) { OAuth2::AccessToken.from_hash(client, 'id_token' => id_token) } - - it 'raises JWT::InvalidIssuerError' do - expect { subject.extra }.to raise_error(JWT::InvalidIssuerError) - end - end - - context 'when the id_token is missing' do - it 'should not include id_token' do - expect(subject.extra).not_to have_key(:id_token) - end - - it 'should not include id_info' do - expect(subject.extra).not_to have_key(:id_info) - end - end - end - - describe 'raw_info' do - context 'when skip_info is true' do - before { subject.options[:skip_info] = true } - - it 'should not include raw_info' do - expect(subject.extra).not_to have_key(:raw_info) - end - end - - context 'when skip_info is false' do - before { subject.options[:skip_info] = false } - - it 'should include raw_info' do - expect(subject.extra[:raw_info]).to eq('sub' => '12345') - end - end - end - end - - describe 'populate auth hash urls' do - it 'should populate url map in auth hash if link present in raw_info' do - allow(subject).to receive(:raw_info) { { 'name' => 'Foo', 'profile' => 'https://plus.google.com/123456' } } - expect(subject.info[:urls][:google]).to eq('https://plus.google.com/123456') - end - - it 'should not populate url map in auth hash if no link present in raw_info' do - allow(subject).to receive(:raw_info) { { 'name' => 'Foo' } } - expect(subject.info).not_to have_key(:urls) - end - end - - describe 'image options' do - it 'should have no image if a picture is not present' do - @options = { image_aspect_ratio: 'square' } - allow(subject).to receive(:raw_info) { { 'name' => 'User Without Pic' } } - expect(subject.info[:image]).to be_nil - end - - describe 'when a picture is returned from google' do - it 'should return the image with size specified in the `image_size` option' do - @options = { image_size: 50 } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg') - end - - it 'should handle a picture with too many slashes correctly' do - @options = { image_size: 50 } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url//photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg') - end - - it 'should handle a picture with a size query parameter correctly' do - @options = { image_size: 50 } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?sz=50' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg') - end - - it 'should handle a picture with a size query parameter and other valid query parameters correctly' do - @options = { image_size: 50 } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?sz=50&hello=true&life=42' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg?hello=true&life=42') - end - - it 'should handle a picture with other valid query parameters correctly' do - @options = { image_size: 50 } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg?hello=true&life=42' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50/photo.jpg?hello=true&life=42') - end - - it 'should return the image with width and height specified in the `image_size` option' do - @options = { image_size: { width: 50, height: 40 } } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40/photo.jpg') - end - - it 'should return square image when `image_aspect_ratio` is specified' do - @options = { image_aspect_ratio: 'square' } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/c/photo.jpg') - end - - it 'should return square sized image when `image_aspect_ratio` and `image_size` is set' do - @options = { image_aspect_ratio: 'square', image_size: 50 } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/s50-c/photo.jpg') - end - - it 'should return square sized image when `image_aspect_ratio` and `image_size` has height and width' do - @options = { image_aspect_ratio: 'square', image_size: { width: 50, height: 40 } } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/w50-h40-c/photo.jpg') - end - - it 'should return original image if image url does not end in `photo.jpg`' do - @options = { image_size: 50 } - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photograph.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photograph.jpg') - end - end - - it 'should return original image if no options are provided' do - allow(subject).to receive(:raw_info) { { 'picture' => 'https://lh3.googleusercontent.com/url/photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg') - end - - it 'should return correct image if google image url has double https' do - allow(subject).to receive(:raw_info) { { 'picture' => 'https:https://lh3.googleusercontent.com/url/photo.jpg' } } - expect(subject.info[:image]).to eq('https://lh3.googleusercontent.com/url/photo.jpg') - end - end - - describe 'build_access_token' do - it 'should use a hybrid authorization request_uri if this is an AJAX request with a code parameter' do - allow(request).to receive(:xhr?).and_return(true) - allow(request).to receive(:params).and_return('code' => 'valid_code') - - client = double(:client) - auth_code = double(:auth_code) - allow(client).to receive(:auth_code).and_return(auth_code) - expect(subject).to receive(:client).and_return(client) - expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'postmessage' }, {}) - - expect(subject).not_to receive(:orig_build_access_token) - subject.build_access_token - end - - it 'should use a hybrid authorization request_uri if this is an AJAX request (mobile) with a code parameter' do - allow(request).to receive(:xhr?).and_return(true) - allow(request).to receive(:params).and_return('code' => 'valid_code', 'redirect_uri' => '') - - client = double(:client) - auth_code = double(:auth_code) - allow(client).to receive(:auth_code).and_return(auth_code) - expect(subject).to receive(:client).and_return(client) - expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: '' }, {}) - - expect(subject).not_to receive(:orig_build_access_token) - subject.build_access_token - end - - it 'should use the request_uri from params if this not an AJAX request (request from installed app) with a code parameter' do - allow(request).to receive(:xhr?).and_return(false) - allow(request).to receive(:params).and_return('code' => 'valid_code', 'redirect_uri' => 'redirect_uri') - - client = double(:client) - auth_code = double(:auth_code) - allow(client).to receive(:auth_code).and_return(auth_code) - expect(subject).to receive(:client).and_return(client) - expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'redirect_uri' }, {}) - - expect(subject).not_to receive(:orig_build_access_token) - subject.build_access_token - end - - it 'should read access_token from hash if this is not an AJAX request with a code parameter' do - allow(request).to receive(:xhr?).and_return(false) - allow(request).to receive(:params).and_return('access_token' => 'valid_access_token') - expect(subject).to receive(:verify_token).with('valid_access_token').and_return true - expect(subject).to receive(:client).and_return(:client) - - token = subject.build_access_token - expect(token).to be_instance_of(::OAuth2::AccessToken) - expect(token.token).to eq('valid_access_token') - expect(token.client).to eq(:client) - end - - it 'should use callback_url without query_string if this is not an AJAX request' do - allow(request).to receive(:xhr?).and_return(false) - allow(request).to receive(:params).and_return('code' => 'valid_code') - - client = double(:client) - auth_code = double(:auth_code) - allow(client).to receive(:auth_code).and_return(auth_code) - allow(subject).to receive(:callback_url).and_return('redirect_uri_without_query_string') - - expect(subject).to receive(:client).and_return(client) - expect(auth_code).to receive(:get_token).with('valid_code', { redirect_uri: 'redirect_uri_without_query_string' }, {}) - subject.build_access_token - end - end - - describe 'verify_token' do - before(:each) do - subject.options.client_options[:connection_build] = proc do |builder| - builder.request :url_encoded - builder.adapter :test do |stub| - stub.get('/oauth2/v3/tokeninfo?access_token=valid_access_token') do - [200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump( - aud: '000000000000.apps.googleusercontent.com', - sub: '123456789', - email_verified: 'true', - email: 'example@example.com', - access_type: 'offline', - scope: 'profile email', - expires_in: 436 - )] - end - stub.get('/oauth2/v3/tokeninfo?access_token=invalid_access_token') do - [400, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump(error_description: 'Invalid Value')] - end - end - end - end - - it 'should verify token if access_token is valid and app_id equals' do - subject.options.client_id = '000000000000.apps.googleusercontent.com' - expect(subject.send(:verify_token, 'valid_access_token')).to eq(true) - end - - it 'should verify token if access_token is valid and app_id authorized' do - subject.options.authorized_client_ids = ['000000000000.apps.googleusercontent.com'] - expect(subject.send(:verify_token, 'valid_access_token')).to eq(true) - end - - it 'should not verify token if access_token is valid but app_id is false' do - expect(subject.send(:verify_token, 'valid_access_token')).to eq(false) - end - - it 'should raise error if access_token is invalid' do - expect do - subject.send(:verify_token, 'invalid_access_token') - end.to raise_error(OAuth2::Error) - end - end - - describe 'verify_hd' do - let(:client) do - OAuth2::Client.new('abc', 'def') do |builder| - builder.request :url_encoded - builder.adapter :test do |stub| - stub.get('/oauth2/v3/userinfo') do - [200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump( - hd: 'example.com' - )] - end - end - end - end - let(:access_token) { OAuth2::AccessToken.from_hash(client, {}) } - - context 'when domain is nil' do - let(:client) do - OAuth2::Client.new('abc', 'def') do |builder| - builder.request :url_encoded - builder.adapter :test do |stub| - stub.get('/oauth2/v3/userinfo') do - [200, { 'Content-Type' => 'application/json; charset=UTF-8' }, JSON.dump({})] - end - end - end - end - - it 'should verify hd if options hd is set and correct' do - subject.options.hd = nil - expect(subject.send(:verify_hd, access_token)).to eq(true) - end - - it 'should verify hd if options hd is set as an array and is correct' do - subject.options.hd = ['example.com', 'example.co', nil] - expect(subject.send(:verify_hd, access_token)).to eq(true) - end - - it 'should raise an exception if nil is not included' do - subject.options.hd = ['example.com', 'example.co'] - expect do - subject.send(:verify_hd, access_token) - end.to raise_error(OmniAuth::Strategies::OAuth2::CallbackError) - end - end - - it 'should verify hd if options hd is not set' do - expect(subject.send(:verify_hd, access_token)).to eq(true) - end - - it 'should verify hd if options hd is set and correct' do - subject.options.hd = 'example.com' - expect(subject.send(:verify_hd, access_token)).to eq(true) - end - - it 'should verify hd if options hd is set as an array and is correct' do - subject.options.hd = ['example.com', 'example.co', nil] - expect(subject.send(:verify_hd, access_token)).to eq(true) - end - - it 'should verify hd if options hd is set as an Proc and is correct' do - subject.options.hd = proc { 'example.com' } - expect(subject.send(:verify_hd, access_token)).to eq(true) - end - - it 'should verify hd if options hd is set as an Proc returning an array and is correct' do - subject.options.hd = proc { ['example.com', 'example.co'] } - expect(subject.send(:verify_hd, access_token)).to eq(true) - end - - it 'should raise error if options hd is set and wrong' do - subject.options.hd = 'invalid.com' - expect do - subject.send(:verify_hd, access_token) - end.to raise_error(OmniAuth::Strategies::GoogleOauth2::CallbackError) - end - - it 'should raise error if options hd is set as an array and is not correct' do - subject.options.hd = ['invalid.com', 'invalid.co'] - expect do - subject.send(:verify_hd, access_token) - end.to raise_error(OmniAuth::Strategies::GoogleOauth2::CallbackError) - end - end -end diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/rubocop_spec.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/rubocop_spec.rb deleted file mode 100644 index eca9b450e6..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/rubocop_spec.rb +++ /dev/null @@ -1,9 +0,0 @@ -# frozen_string_literal: true - -require_relative 'spec_helper' - -describe 'Rubocop' do - it 'should pass with no offenses detected' do - expect(`rubocop`).to include('no offenses detected') - end -end diff --git a/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/spec_helper.rb b/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/spec_helper.rb deleted file mode 100644 index 3c2325389c..0000000000 --- a/debian/gems-compat/omniauth-google-oauth2-0.6.1/spec/spec_helper.rb +++ /dev/null @@ -1,4 +0,0 @@ -# frozen_string_literal: true - -require File.join('bundler', 'setup') -require 'rspec' diff --git a/debian/gems-compat/rails-5.1.7/README.md b/debian/gems-compat/rails-5.1.7/README.md deleted file mode 100644 index 7e25a0c8f1..0000000000 --- a/debian/gems-compat/rails-5.1.7/README.md +++ /dev/null @@ -1,93 +0,0 @@ -# Welcome to Rails - -Rails is a web-application framework that includes everything needed to -create database-backed web applications according to the -[Model-View-Controller (MVC)](http://en.wikipedia.org/wiki/Model-view-controller) -pattern. - -Understanding the MVC pattern is key to understanding Rails. MVC divides your -application into three layers, each with a specific responsibility. - -The _Model layer_ represents your domain model (such as Account, Product, -Person, Post, etc.) and encapsulates the business logic that is specific to -your application. In Rails, database-backed model classes are derived from -`ActiveRecord::Base`. Active Record allows you to present the data from -database rows as objects and embellish these data objects with business logic -methods. You can read more about Active Record in its [README](activerecord/README.rdoc). -Although most Rails models are backed by a database, models can also be ordinary -Ruby classes, or Ruby classes that implement a set of interfaces as provided by -the Active Model module. You can read more about Active Model in its [README](activemodel/README.rdoc). - -The _Controller layer_ is responsible for handling incoming HTTP requests and -providing a suitable response. Usually this means returning HTML, but Rails controllers -can also generate XML, JSON, PDFs, mobile-specific views, and more. Controllers load and -manipulate models, and render view templates in order to generate the appropriate HTTP response. -In Rails, incoming requests are routed by Action Dispatch to an appropriate controller, and -controller classes are derived from `ActionController::Base`. Action Dispatch and Action Controller -are bundled together in Action Pack. You can read more about Action Pack in its -[README](actionpack/README.rdoc). - -The _View layer_ is composed of "templates" that are responsible for providing -appropriate representations of your application's resources. Templates can -come in a variety of formats, but most view templates are HTML with embedded -Ruby code (ERB files). Views are typically rendered to generate a controller response, -or to generate the body of an email. In Rails, View generation is handled by Action View. -You can read more about Action View in its [README](actionview/README.rdoc). - -Active Record, Active Model, Action Pack, and Action View can each be used independently outside Rails. -In addition to that, Rails also comes with Action Mailer ([README](actionmailer/README.rdoc)), a library -to generate and send emails; Active Job ([README](activejob/README.md)), a -framework for declaring jobs and making them run on a variety of queueing -backends; Action Cable ([README](actioncable/README.md)), a framework to -integrate WebSockets with a Rails application; -and Active Support ([README](activesupport/README.rdoc)), a collection -of utility classes and standard library extensions that are useful for Rails, -and may also be used independently outside Rails. - -## Getting Started - -1. Install Rails at the command prompt if you haven't yet: - - $ gem install rails - -2. At the command prompt, create a new Rails application: - - $ rails new myapp - - where "myapp" is the application name. - -3. Change directory to `myapp` and start the web server: - - $ cd myapp - $ rails server - - Run with `--help` or `-h` for options. - -4. Using a browser, go to `http://localhost:3000` and you'll see: -"Yay! You’re on Rails!" - -5. Follow the guidelines to start developing your application. You may find - the following resources handy: - * [Getting Started with Rails](http://guides.rubyonrails.org/getting_started.html) - * [Ruby on Rails Guides](http://guides.rubyonrails.org) - * [The API Documentation](http://api.rubyonrails.org) - * [Ruby on Rails Tutorial](https://www.railstutorial.org/book) - -## Contributing - -We encourage you to contribute to Ruby on Rails! Please check out the -[Contributing to Ruby on Rails guide](http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html) for guidelines about how to proceed. [Join us!](http://contributors.rubyonrails.org) - -Trying to report a possible security vulnerability in Rails? Please -check out our [security policy](http://rubyonrails.org/security/) for -guidelines about how to proceed. - -Everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](http://rubyonrails.org/conduct/). - -## Code Status - -[![Build Status](https://travis-ci.org/rails/rails.svg?branch=master)](https://travis-ci.org/rails/rails) - -## License - -Ruby on Rails is released under the [MIT License](http://www.opensource.org/licenses/MIT). diff --git a/debian/gems-compat/rails-5.1.7/rails.gemspec b/debian/gems-compat/rails-5.1.7/rails.gemspec deleted file mode 100644 index 6423732e3c..0000000000 --- a/debian/gems-compat/rails-5.1.7/rails.gemspec +++ /dev/null @@ -1,65 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: rails 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "rails".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 1.8.11".freeze) if s.respond_to? :required_rubygems_version= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.date = "2019-03-28" - s.description = "Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.".freeze - s.email = "david@loudthinking.com".freeze - s.files = ["README.md".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.rubygems_version = "2.7.6.2".freeze - s.summary = "Full-stack web application framework.".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, [">= 1.3.0"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, [">= 2.0.0"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 1.3.0"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 2.0.0"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 1.3.0"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 2.0.0"]) - end -end diff --git a/debian/gems-compat/railties-5.1.7/CHANGELOG.md b/debian/gems-compat/railties-5.1.7/CHANGELOG.md deleted file mode 100644 index 005e8517a4..0000000000 --- a/debian/gems-compat/railties-5.1.7/CHANGELOG.md +++ /dev/null @@ -1,323 +0,0 @@ -## Rails 5.1.7 (March 27, 2019) ## - -* No changes. - - -## Rails 5.1.6.2 (March 11, 2019) ## - -* No changes. - - -## Rails 5.1.6.1 (November 27, 2018) ## - -* No changes. - - -## Rails 5.1.6 (March 29, 2018) ## - -* Fix check for minimum Ruby version to correctly identify Ruby 2.2.10. - - *shia* - -* Fix minitest rails plugin. - - The custom reporters are added only if needed. - - This will fix conflicts with others plugins. - - *Kevin Robatel* - - -## Rails 5.1.5 (February 14, 2018) ## - -* Gemfile for new apps: upgrade redis-rb from ~> 3.0 to 4.0. - - *Jeremy Daer* - - -## Rails 5.1.4 (September 07, 2017) ## - -* No changes. - - -## Rails 5.1.4.rc1 (August 24, 2017) ## - -* Allow irb options to be passed from `rails console` command. - - Fixes #28988. - - *Yuji Yaginuma* - -## Rails 5.1.3 (August 03, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc3 (July 31, 2017) ## - -* No changes. - - -## Rails 5.1.3.rc2 (July 25, 2017) ## - -* Regression fix: Allow `bin/rails test` to take absolute paths to tests. - - *Pawan Dubey* - -## Rails 5.1.3.rc1 (July 19, 2017) ## - -* Make Rails' test runner work better with minitest plugins. - - By demoting the Rails test runner to just another minitest plugin — - and thereby not eager loading it — we can co-exist much better with - other minitest plugins such as pride and minitest-focus. - - *Kasper Timm Hansen* - -* Load environment file in `dbconsole` command. - - Fixes #29717 - - *Yuji Yaginuma* - -* Allow mounting the same engine several times in different locations. - - Fixes #20204. - - *David Rodríguez* - - -## Rails 5.1.2 (June 26, 2017) ## - -* Add Windows support to `rails secrets:edit`. - - *Kasper Timm Hansen* - -## Rails 5.1.1 (May 12, 2017) ## - -* No changes. - - -## Rails 5.1.0 (April 27, 2017) ## - -* Namespace error pages' CSS selectors to stop the styles from bleeding into other pages - when using Turbolinks. - - *Jan Krutisch* - -* Raise a error when using a bad symlink - - Previously bad symlinks (where the link destination doesn't exist) - would be silent ignored and lead to hard to diagnose problems as - the non-existence isn't readily apparent. - - *Richard Schneeman* - -* Remove -j (--javascript) option from `rails new` command. - - *claudiob* - -* Specify form field ids when generating a scaffold. - - This makes sure that the labels are linked up with the fields. The - regression was introduced when the template was switched to - `form_with`. - - *Yves Senn* - -* Add `app:update` task to engines. - - *Yuji Yaginuma* - -* Avoid running system tests by default with the `bin/rails test` - and `bin/rake test` commands since they may be expensive. - - Fixes #28286. - - *Robin Dupret* - -* Improve encryption for encrypted secrets. - - Switch to aes-128-gcm authenticated encryption. Also generate a random - initialization vector for each encryption so the same input and key can - generate different encrypted data. - - Double the encryption key entropy by properly extracting the underlying - bytes from the hexadecimal seed key. - - NOTE: Since the encryption mechanism has been switched, you need to run - this script to upgrade: - - https://gist.github.com/kaspth/bc37989c2f39a5642112f28b1d93f343 - - *Stephen Touset* - -* Add encrypted secrets in `config/secrets.yml.enc`. - - Allow storing production secrets straight in the revision control system by - encrypting them. - - Use `bin/rails secrets:setup` to opt-in by generating `config/secrets.yml.enc` - for the secrets themselves and `config/secrets.yml.key` for the encryption key. - - Edit secrets with `bin/rails secrets:edit`. - - See `bin/rails secrets:setup --help` for more. - - *Kasper Timm Hansen* - -* Fix running multiple tests in one `rake` command - - e.g. `bin/rake test:models test:controllers` - - *Dominic Cleal* - -* Add option to configure Ruby's warning behaviour to test runner. - - *Yuji Yaginuma* - -* Initialize git repo when generating new app, if option `--skip-git` - is not provided. - - *Dino Maric* - -* Install Byebug gem as default in Windows (mingw and x64_mingw) platform. - - *Junichi Ito* - -* Make every Rails command work within engines. - - *Sean Collins*, *Yuji Yaginuma* - -* Don't generate HTML/ERB templates for scaffold controller with `--api` flag. - - Fixes #27591. - - *Prathamesh Sonpatki* - -* Make `Rails.env` fall back to `development` when `RAILS_ENV` and `RACK_ENV` is an empty string. - - *Daniel Deng* - -* Remove deprecated `CONTROLLER` environment variable for `routes` task. - - *Rafael Mendonça França* - -* Remove deprecated tasks: `rails:update`, `rails:template`, `rails:template:copy`, - `rails:update:configs` and `rails:update:bin`. - - *Rafael Mendonça França* - -* Remove deprecated file `rails/rack/debugger`. - - *Rafael Mendonça França* - -* Remove deprecated `config.serve_static_files`. - - *Rafael Mendonça França* - -* Remove deprecated `config.static_cache_control`. - - *Rafael Mendonça França* - -* The `log:clear` task clear all environments log files by default. - - *Yuji Yaginuma* - -* Add Webpack support in new apps via the --webpack option, which will delegate to the rails/webpacker gem. - - To generate a new app that has Webpack dependencies configured and binstubs for webpack and webpack-watcher: - - `rails new myapp --webpack` - - To generate a new app that has Webpack + React configured and an example intalled: - - `rails new myapp --webpack=react` - - *DHH* - -* Add Yarn support in new apps with a yarn binstub and package.json. Skippable via --skip-yarn option. - - *Liceth Ovalles*, *Guillermo Iguaran*, *DHH* - -* Removed jquery-rails from default stack, instead rails-ujs that is shipped - with Action View is included as default UJS adapter. - - *Guillermo Iguaran* - -* The config file `secrets.yml` is now loaded in with all keys as symbols. - This allows secrets files to contain more complex information without all - child keys being strings while parent keys are symbols. - - *Isaac Sloan* - -* Add `:skip_sprockets` to `Rails::PluginBuilder::PASSTHROUGH_OPTIONS` - - *Tsukuru Tanimichi* - -* Add `--skip-coffee` option to `rails new` - - *Seunghwan Oh* - -* Allow the use of listen's 3.1.x branch - - *Esteban Santana Santana* - -* Run `Minitest.after_run` hooks when running `rails test`. - - *Michael Grosser* - -* Run `before_configuration` callbacks as soon as application constant - inherits from `Rails::Application`. - - Fixes #19880. - - *Yuji Yaginuma* - -* A generated app should not include Uglifier with `--skip-javascript` option. - - *Ben Pickles* - -* Set session store to cookie store internally and remove the initializer from - the generated app. - - *Prathamesh Sonpatki* - -* Set the server host using the `HOST` environment variable. - - *mahnunchik* - -* Add public API to register new folders for `rake notes`: - - config.annotations.register_directories('spec', 'features') - - *John Meehan* - -* Display name of the class defining the initializer along with the initializer - name in the output of `rails initializers`. - - Before: - disable_dependency_loading - - After: - DemoApp::Application.disable_dependency_loading - - *ta1kt0me* - -* Do not run `bundle install` when generating a new plugin. - - Since bundler 1.12.0, the gemspec is validated so the `bundle install` - command will fail just after the gem is created causing confusion to the - users. This change was a bug fix to correctly validate gemspecs. - - *Rafael Mendonça França* - -* Ensure `/rails/info` routes match in development for apps with a catch-all globbing route. - - *Nicholas Firth-McCoy* - -* Added a shared section to `config/secrets.yml` that will be loaded for all environments. - - *DHH* - -Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/railties/CHANGELOG.md) for previous changes. diff --git a/debian/gems-compat/railties-5.1.7/MIT-LICENSE b/debian/gems-compat/railties-5.1.7/MIT-LICENSE deleted file mode 100644 index f9e4444f07..0000000000 --- a/debian/gems-compat/railties-5.1.7/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2004-2017 David Heinemeier Hansson - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/railties-5.1.7/RDOC_MAIN.rdoc b/debian/gems-compat/railties-5.1.7/RDOC_MAIN.rdoc deleted file mode 100644 index 654c7bae57..0000000000 --- a/debian/gems-compat/railties-5.1.7/RDOC_MAIN.rdoc +++ /dev/null @@ -1,73 +0,0 @@ -== Welcome to \Rails - -\Rails is a web-application framework that includes everything needed to create -database-backed web applications according to the {Model-View-Controller (MVC)}[http://en.wikipedia.org/wiki/Model-view-controller] pattern. - -Understanding the MVC pattern is key to understanding \Rails. MVC divides your application -into three layers, each with a specific responsibility. - -The View layer is composed of "templates" that are responsible for providing -appropriate representations of your application's resources. Templates -can come in a variety of formats, but most view templates are \HTML with embedded Ruby -code (.erb files). - -The Model layer represents your domain model (such as Account, Product, Person, Post) -and encapsulates the business logic that is specific to your application. In \Rails, -database-backed model classes are derived from ActiveRecord::Base. Active Record allows -you to present the data from database rows as objects and embellish these data objects -with business logic methods. Although most \Rails models are backed by a database, models -can also be ordinary Ruby classes, or Ruby classes that implement a set of interfaces as -provided by the ActiveModel module. You can read more about Active Record in its -{README}[link:files/activerecord/README_rdoc.html]. - -The Controller layer is responsible for handling incoming HTTP requests and providing a -suitable response. Usually this means returning \HTML, but \Rails controllers can also -generate XML, JSON, PDFs, mobile-specific views, and more. Controllers manipulate models -and render view templates in order to generate the appropriate HTTP response. - -In \Rails, the Controller and View layers are handled together by Action Pack. -These two layers are bundled in a single package due to their heavy interdependence. -This is unlike the relationship between Active Record and Action Pack, which are -independent. Each of these packages can be used independently outside of \Rails. You -can read more about Action Pack in its {README}[link:files/actionpack/README_rdoc.html]. - -== Getting Started - -1. Install \Rails at the command prompt if you haven't yet: - - $ gem install rails - -2. At the command prompt, create a new \Rails application: - - $ rails new myapp - - where "myapp" is the application name. - -3. Change directory to +myapp+ and start the web server: - - $ cd myapp; rails server - - Run with --help or -h for options. - -4. Go to http://localhost:3000 and you'll see: - - "Yay! You’re on Rails!" - -5. Follow the guidelines to start developing your application. You may find the following resources handy: - -* The \README file created within your application. -* {Getting Started with \Rails}[http://guides.rubyonrails.org/getting_started.html]. -* {Ruby on \Rails Tutorial}[https://www.railstutorial.org/book]. -* {Ruby on \Rails Guides}[http://guides.rubyonrails.org]. -* {The API Documentation}[http://api.rubyonrails.org]. - -== Contributing - -We encourage you to contribute to Ruby on \Rails! Please check out the {Contributing to Rails -guide}[http://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html] for guidelines about how -to proceed. {Join us}[http://contributors.rubyonrails.org]! - - -== License - -Ruby on \Rails is released under the {MIT License}[http://www.opensource.org/licenses/MIT]. diff --git a/debian/gems-compat/railties-5.1.7/README.rdoc b/debian/gems-compat/railties-5.1.7/README.rdoc deleted file mode 100644 index a25658668c..0000000000 --- a/debian/gems-compat/railties-5.1.7/README.rdoc +++ /dev/null @@ -1,41 +0,0 @@ -= Railties -- Gluing the Engine to the Rails - -Railties is responsible for gluing all frameworks together. Overall, it: - -* handles the bootstrapping process for a Rails application; - -* manages the +rails+ command line interface; - -* and provides the Rails generators core. - - -== Download - -The latest version of Railties can be installed with RubyGems: - -* gem install railties - -Source code can be downloaded as part of the Rails project on GitHub - -* https://github.com/rails/rails/tree/master/railties - -== License - -Railties is released under the MIT license: - -* http://www.opensource.org/licenses/MIT - -== Support - -API documentation is at - -* http://api.rubyonrails.org - -Bug reports can be filed for the Ruby on Rails project here: - -* https://github.com/rails/rails/issues - -Feature requests should be discussed on the rails-core mailing list here: - -* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core - diff --git a/debian/gems-compat/railties-5.1.7/exe/rails b/debian/gems-compat/railties-5.1.7/exe/rails deleted file mode 100755 index 7e791c1f99..0000000000 --- a/debian/gems-compat/railties-5.1.7/exe/rails +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env ruby - -git_path = File.expand_path("../../../.git", __FILE__) - -if File.exist?(git_path) - railties_path = File.expand_path("../../lib", __FILE__) - $:.unshift(railties_path) -end -require "rails/cli" diff --git a/debian/gems-compat/railties-5.1.7/lib/minitest/rails_plugin.rb b/debian/gems-compat/railties-5.1.7/lib/minitest/rails_plugin.rb deleted file mode 100644 index b893041f3e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/minitest/rails_plugin.rb +++ /dev/null @@ -1,58 +0,0 @@ -require "active_support/core_ext/module/attribute_accessors" -require "rails/test_unit/reporter" - -module Minitest - class SuppressedSummaryReporter < SummaryReporter - # Disable extra failure output after a run if output is inline. - def aggregated_results(*) - super unless options[:output_inline] - end - end - - def self.plugin_rails_options(opts, options) - opts.on("-b", "--backtrace", "Show the complete backtrace") do - options[:full_backtrace] = true - end - - opts.on("-d", "--defer-output", "Output test failures and errors after the test run") do - options[:output_inline] = false - end - - opts.on("-f", "--fail-fast", "Abort test run on first failure or error") do - options[:fail_fast] = true - end - - opts.on("-c", "--[no-]color", "Enable color in the output") do |value| - options[:color] = value - end - - options[:color] = true - options[:output_inline] = true - end - - # Owes great inspiration to test runner trailblazers like RSpec, - # minitest-reporters, maxitest and others. - def self.plugin_rails_init(options) - unless options[:full_backtrace] || ENV["BACKTRACE"] - # Plugin can run without Rails loaded, check before filtering. - Minitest.backtrace_filter = ::Rails.backtrace_cleaner if ::Rails.respond_to?(:backtrace_cleaner) - end - - self.plugin_rails_replace_reporters(reporter, options) - end - - def self.plugin_rails_replace_reporters(minitest_reporter, options) - return unless minitest_reporter.kind_of?(Minitest::CompositeReporter) - - # Replace progress reporter for colors. - if minitest_reporter.reporters.reject! { |reporter| reporter.kind_of?(SummaryReporter) } != nil - minitest_reporter << SuppressedSummaryReporter.new(options[:io], options) - end - if minitest_reporter.reporters.reject! { |reporter| reporter.kind_of?(ProgressReporter) } != nil - minitest_reporter << ::Rails::TestUnitReporter.new(options[:io], options) - end - end - - # Backwardscompatibility with Rails 5.0 generated plugin test scripts - mattr_reader(:run_via) { Hash.new } -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails.rb b/debian/gems-compat/railties-5.1.7/lib/rails.rb deleted file mode 100644 index 00add5829d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails.rb +++ /dev/null @@ -1,112 +0,0 @@ -require "rails/ruby_version_check" - -require "pathname" - -require "active_support" -require "active_support/dependencies/autoload" -require "active_support/core_ext/kernel/reporting" -require "active_support/core_ext/module/delegation" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/object/blank" - -require "rails/application" -require "rails/version" - -require "active_support/railtie" -require "action_dispatch/railtie" - -# UTF-8 is the default internal and external encoding. -silence_warnings do - Encoding.default_external = Encoding::UTF_8 - Encoding.default_internal = Encoding::UTF_8 -end - -module Rails - extend ActiveSupport::Autoload - - autoload :Info - autoload :InfoController - autoload :MailersController - autoload :WelcomeController - - class << self - @application = @app_class = nil - - attr_writer :application - attr_accessor :app_class, :cache, :logger - def application - @application ||= (app_class.instance if app_class) - end - - delegate :initialize!, :initialized?, to: :application - - # The Configuration instance used to configure the Rails environment - def configuration - application.config - end - - def backtrace_cleaner - @backtrace_cleaner ||= begin - # Relies on Active Support, so we have to lazy load to postpone definition until Active Support has been loaded - require "rails/backtrace_cleaner" - Rails::BacktraceCleaner.new - end - end - - # Returns a Pathname object of the current Rails project, - # otherwise it returns +nil+ if there is no project: - # - # Rails.root - # # => # - def root - application && application.config.root - end - - # Returns the current Rails environment. - # - # Rails.env # => "development" - # Rails.env.development? # => true - # Rails.env.production? # => false - def env - @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "development") - end - - # Sets the Rails environment. - # - # Rails.env = "staging" # => "staging" - def env=(environment) - @_env = ActiveSupport::StringInquirer.new(environment) - end - - # Returns all Rails groups for loading based on: - # - # * The Rails environment; - # * The environment variable RAILS_GROUPS; - # * The optional envs given as argument and the hash with group dependencies; - # - # groups assets: [:development, :test] - # - # # Returns - # # => [:default, :development, :assets] for Rails.env == "development" - # # => [:default, :production] for Rails.env == "production" - def groups(*groups) - hash = groups.extract_options! - env = Rails.env - groups.unshift(:default, env) - groups.concat ENV["RAILS_GROUPS"].to_s.split(",") - groups.concat hash.map { |k, v| k if v.map(&:to_s).include?(env) } - groups.compact! - groups.uniq! - groups - end - - # Returns a Pathname object of the public folder of the current - # Rails project, otherwise it returns +nil+ if there is no project: - # - # Rails.public_path - # # => # - def public_path - application && Pathname.new(application.paths["public"].first) - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/all.rb b/debian/gems-compat/railties-5.1.7/lib/rails/all.rb deleted file mode 100644 index 7606ea0e46..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/all.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "rails" - -%w( - active_record/railtie - action_controller/railtie - action_view/railtie - action_mailer/railtie - active_job/railtie - action_cable/engine - rails/test_unit/railtie - sprockets/railtie -).each do |railtie| - begin - require railtie - rescue LoadError - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/api/generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/api/generator.rb deleted file mode 100644 index dcc491783c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/api/generator.rb +++ /dev/null @@ -1,28 +0,0 @@ -require "sdoc" - -class RDoc::Generator::API < RDoc::Generator::SDoc # :nodoc: - RDoc::RDoc.add_generator self - - def generate_class_tree_level(classes, visited = {}) - # Only process core extensions on the first visit. - if visited.empty? - core_exts, classes = classes.partition { |klass| core_extension?(klass) } - - super.unshift([ "Core extensions", "", "", build_core_ext_subtree(core_exts, visited) ]) - else - super - end - end - - private - def build_core_ext_subtree(classes, visited) - classes.map do |klass| - [ klass.name, klass.document_self_or_methods ? klass.path : "", "", - generate_class_tree_level(klass.classes_and_modules, visited) ] - end - end - - def core_extension?(klass) - klass.name != "ActiveSupport" && klass.in_files.any? { |file| file.absolute_name.include?("core_ext") } - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/api/task.rb b/debian/gems-compat/railties-5.1.7/lib/rails/api/task.rb deleted file mode 100644 index 49267c2329..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/api/task.rb +++ /dev/null @@ -1,175 +0,0 @@ -require "rdoc/task" -require_relative "generator" - -module Rails - module API - class Task < RDoc::Task - RDOC_FILES = { - "activesupport" => { - include: %w( - README.rdoc - lib/active_support/**/*.rb - ) - }, - - "activerecord" => { - include: %w( - README.rdoc - lib/active_record/**/*.rb - ) - }, - - "activemodel" => { - include: %w( - README.rdoc - lib/active_model/**/*.rb - ) - }, - - "actionpack" => { - include: %w( - README.rdoc - lib/abstract_controller/**/*.rb - lib/action_controller/**/*.rb - lib/action_dispatch/**/*.rb - ) - }, - - "actionview" => { - include: %w( - README.rdoc - lib/action_view/**/*.rb - ), - exclude: "lib/action_view/vendor/*" - }, - - "actionmailer" => { - include: %w( - README.rdoc - lib/action_mailer/**/*.rb - ) - }, - - "activejob" => { - include: %w( - README.md - lib/active_job/**/*.rb - ) - }, - - "actioncable" => { - include: %w( - README.md - lib/action_cable/**/*.rb - ) - }, - - "railties" => { - include: %w( - README.rdoc - lib/**/*.rb - ), - exclude: %w( - lib/rails/generators/**/templates/**/*.rb - lib/rails/test_unit/* - lib/rails/api/generator.rb - ) - } - } - - def initialize(name) - super - - # Every time rake runs this task is instantiated as all the rest. - # Be lazy computing stuff to have as light impact as possible to - # the rest of tasks. - before_running_rdoc do - configure_sdoc - configure_rdoc_files - setup_horo_variables - end - end - - # Hack, ignore the desc calls performed by the original initializer. - def desc(description) - # no-op - end - - def configure_sdoc - self.title = "Ruby on Rails API" - self.rdoc_dir = api_dir - - options << "-m" << api_main - options << "-e" << "UTF-8" - - options << "-f" << "api" - options << "-T" << "rails" - end - - def configure_rdoc_files - rdoc_files.include(api_main) - - RDOC_FILES.each do |component, cfg| - cdr = component_root_dir(component) - - Array(cfg[:include]).each do |pattern| - rdoc_files.include("#{cdr}/#{pattern}") - end - - Array(cfg[:exclude]).each do |pattern| - rdoc_files.exclude("#{cdr}/#{pattern}") - end - end - - # Only generate documentation for files that have been - # changed since the API was generated. - if Dir.exist?("doc/rdoc") && !ENV["ALL"] - last_generation = DateTime.rfc2822(File.open("doc/rdoc/created.rid", &:readline)) - - rdoc_files.keep_if do |file| - File.mtime(file).to_datetime > last_generation - end - - # Nothing to do - exit(0) if rdoc_files.empty? - end - end - - def setup_horo_variables - ENV["HORO_PROJECT_NAME"] = "Ruby on Rails" - ENV["HORO_PROJECT_VERSION"] = rails_version - end - - def api_main - component_root_dir("railties") + "/RDOC_MAIN.rdoc" - end - end - - class RepoTask < Task - def configure_sdoc - super - options << "-g" # link to GitHub, SDoc flag - end - - def component_root_dir(component) - component - end - - def api_dir - "doc/rdoc" - end - end - - class EdgeTask < RepoTask - def rails_version - "master@#{`git rev-parse HEAD`[0, 7]}" - end - end - - class StableTask < RepoTask - def rails_version - File.read("RAILS_VERSION").strip - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/app_loader.rb b/debian/gems-compat/railties-5.1.7/lib/rails/app_loader.rb deleted file mode 100644 index 525d5f0161..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/app_loader.rb +++ /dev/null @@ -1,64 +0,0 @@ -require "pathname" -require "rails/version" - -module Rails - module AppLoader # :nodoc: - extend self - - RUBY = Gem.ruby - EXECUTABLES = ["bin/rails", "script/rails"] - BUNDLER_WARNING = < 'my sensible data' - # - # See the +ActiveSupport::MessageVerifier+ documentation for more information. - def message_verifier(verifier_name) - @message_verifiers[verifier_name] ||= begin - secret = key_generator.generate_key(verifier_name.to_s) - ActiveSupport::MessageVerifier.new(secret) - end - end - - # Convenience for loading config/foo.yml for the current Rails env. - # - # Example: - # - # # config/exception_notification.yml: - # production: - # url: http://127.0.0.1:8080 - # namespace: my_app_production - # development: - # url: http://localhost:3001 - # namespace: my_app_development - # - # # config/environments/production.rb - # Rails.application.configure do - # config.middleware.use ExceptionNotifier, config_for(:exception_notification) - # end - def config_for(name, env: Rails.env) - if name.is_a?(Pathname) - yaml = name - else - yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml") - end - - if yaml.exist? - require "erb" - (YAML.load(ERB.new(yaml.read).result) || {})[env] || {} - else - raise "Could not load configuration. No such file - #{yaml}" - end - rescue Psych::SyntaxError => e - raise "YAML syntax error occurred while parsing #{yaml}. " \ - "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ - "Error: #{e.message}" - end - - # Stores some of the Rails initial environment parameters which - # will be used by middlewares and engines to configure themselves. - def env_config - @app_env_config ||= begin - validate_secret_key_config! - - super.merge( - "action_dispatch.parameter_filter" => config.filter_parameters, - "action_dispatch.redirect_filter" => config.filter_redirect, - "action_dispatch.secret_token" => secrets.secret_token, - "action_dispatch.secret_key_base" => secrets.secret_key_base, - "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions, - "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local, - "action_dispatch.logger" => Rails.logger, - "action_dispatch.backtrace_cleaner" => Rails.backtrace_cleaner, - "action_dispatch.key_generator" => key_generator, - "action_dispatch.http_auth_salt" => config.action_dispatch.http_auth_salt, - "action_dispatch.signed_cookie_salt" => config.action_dispatch.signed_cookie_salt, - "action_dispatch.encrypted_cookie_salt" => config.action_dispatch.encrypted_cookie_salt, - "action_dispatch.encrypted_signed_cookie_salt" => config.action_dispatch.encrypted_signed_cookie_salt, - "action_dispatch.cookies_serializer" => config.action_dispatch.cookies_serializer, - "action_dispatch.cookies_digest" => config.action_dispatch.cookies_digest - ) - end - end - - # If you try to define a set of Rake tasks on the instance, these will get - # passed up to the Rake tasks defined on the application's class. - def rake_tasks(&block) - self.class.rake_tasks(&block) - end - - # Sends the initializers to the +initializer+ method defined in the - # Rails::Initializable module. Each Rails::Application class has its own - # set of initializers, as defined by the Initializable module. - def initializer(name, opts = {}, &block) - self.class.initializer(name, opts, &block) - end - - # Sends any runner called in the instance of a new application up - # to the +runner+ method defined in Rails::Railtie. - def runner(&blk) - self.class.runner(&blk) - end - - # Sends any console called in the instance of a new application up - # to the +console+ method defined in Rails::Railtie. - def console(&blk) - self.class.console(&blk) - end - - # Sends any generators called in the instance of a new application up - # to the +generators+ method defined in Rails::Railtie. - def generators(&blk) - self.class.generators(&blk) - end - - # Sends the +isolate_namespace+ method up to the class method. - def isolate_namespace(mod) - self.class.isolate_namespace(mod) - end - - ## Rails internal API - - # This method is called just after an application inherits from Rails::Application, - # allowing the developer to load classes in lib and use them during application - # configuration. - # - # class MyApplication < Rails::Application - # require "my_backend" # in lib/my_backend - # config.i18n.backend = MyBackend - # end - # - # Notice this method takes into consideration the default root path. So if you - # are changing config.root inside your application definition or having a custom - # Rails application, you will need to add lib to $LOAD_PATH on your own in case - # you need to load files in lib/ during the application configuration as well. - def self.add_lib_to_load_path!(root) #:nodoc: - path = File.join root, "lib" - if File.exist?(path) && !$LOAD_PATH.include?(path) - $LOAD_PATH.unshift(path) - end - end - - def require_environment! #:nodoc: - environment = paths["config/environment"].existent.first - require environment if environment - end - - def routes_reloader #:nodoc: - @routes_reloader ||= RoutesReloader.new - end - - # Returns an array of file paths appended with a hash of - # directories-extensions suitable for ActiveSupport::FileUpdateChecker - # API. - def watchable_args #:nodoc: - files, dirs = config.watchable_files.dup, config.watchable_dirs.dup - - ActiveSupport::Dependencies.autoload_paths.each do |path| - dirs[path.to_s] = [:rb] - end - - [files, dirs] - end - - # Initialize the application passing the given group. By default, the - # group is :default - def initialize!(group = :default) #:nodoc: - raise "Application has been already initialized." if @initialized - run_initializers(group, self) - @initialized = true - self - end - - def initializers #:nodoc: - Bootstrap.initializers_for(self) + - railties_initializers(super) + - Finisher.initializers_for(self) - end - - def config #:nodoc: - @config ||= Application::Configuration.new(self.class.find_root(self.class.called_from)) - end - - def config=(configuration) #:nodoc: - @config = configuration - end - - # Returns secrets added to config/secrets.yml. - # - # Example: - # - # development: - # secret_key_base: 836fa3665997a860728bcb9e9a1e704d427cfc920e79d847d79c8a9a907b9e965defa4154b2b86bdec6930adbe33f21364523a6f6ce363865724549fdfc08553 - # test: - # secret_key_base: 5a37811464e7d378488b0f073e2193b093682e4e21f5d6f3ae0a4e1781e61a351fdc878a843424e81c73fb484a40d23f92c8dafac4870e74ede6e5e174423010 - # production: - # secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> - # namespace: my_app_production - # - # +Rails.application.secrets.namespace+ returns +my_app_production+ in the - # production environment. - def secrets - @secrets ||= begin - secrets = ActiveSupport::OrderedOptions.new - files = config.paths["config/secrets"].existent - files = files.reject { |path| path.end_with?(".enc") } unless config.read_encrypted_secrets - secrets.merge! Rails::Secrets.parse(files, env: Rails.env) - - # Fallback to config.secret_key_base if secrets.secret_key_base isn't set - secrets.secret_key_base ||= config.secret_key_base - # Fallback to config.secret_token if secrets.secret_token isn't set - secrets.secret_token ||= config.secret_token - - secrets - end - end - - def secrets=(secrets) #:nodoc: - @secrets = secrets - end - - def to_app #:nodoc: - self - end - - def helpers_paths #:nodoc: - config.helpers_paths - end - - console do - require "pp" - end - - console do - unless ::Kernel.private_method_defined?(:y) - require "psych/y" - end - end - - # Return an array of railties respecting the order they're loaded - # and the order specified by the +railties_order+ config. - # - # While running initializers we need engines in reverse order here when - # copying migrations from railties ; we need them in the order given by - # +railties_order+. - def migration_railties # :nodoc: - ordered_railties.flatten - [self] - end - - protected - - alias :build_middleware_stack :app - - def run_tasks_blocks(app) #:nodoc: - railties.each { |r| r.run_tasks_blocks(app) } - super - require "rails/tasks" - task :environment do - ActiveSupport.on_load(:before_initialize) { config.eager_load = false } - - require_environment! - end - end - - def run_generators_blocks(app) #:nodoc: - railties.each { |r| r.run_generators_blocks(app) } - super - end - - def run_runner_blocks(app) #:nodoc: - railties.each { |r| r.run_runner_blocks(app) } - super - end - - def run_console_blocks(app) #:nodoc: - railties.each { |r| r.run_console_blocks(app) } - super - end - - # Returns the ordered railties for this application considering railties_order. - def ordered_railties #:nodoc: - @ordered_railties ||= begin - order = config.railties_order.map do |railtie| - if railtie == :main_app - self - elsif railtie.respond_to?(:instance) - railtie.instance - else - railtie - end - end - - all = (railties - order) - all.push(self) unless (all + order).include?(self) - order.push(:all) unless order.include?(:all) - - index = order.index(:all) - order[index] = all - order - end - end - - def railties_initializers(current) #:nodoc: - initializers = [] - ordered_railties.reverse.flatten.each do |r| - if r == self - initializers += current - else - initializers += r.initializers - end - end - initializers - end - - def default_middleware_stack #:nodoc: - default_stack = DefaultMiddlewareStack.new(self, config, paths) - default_stack.build_stack - end - - def validate_secret_key_config! #:nodoc: - if secrets.secret_key_base.blank? - ActiveSupport::Deprecation.warn "You didn't set `secret_key_base`. " \ - "Read the upgrade documentation to learn more about this new config option." - - if secrets.secret_token.blank? - raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`" - end - end - end - - private - - def build_request(env) - req = super - env["ORIGINAL_FULLPATH"] = req.fullpath - env["ORIGINAL_SCRIPT_NAME"] = req.script_name - req - end - - def build_middleware - config.app_middleware + super - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/application/bootstrap.rb b/debian/gems-compat/railties-5.1.7/lib/rails/application/bootstrap.rb deleted file mode 100644 index dc0491035d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/application/bootstrap.rb +++ /dev/null @@ -1,87 +0,0 @@ -require "fileutils" -require "active_support/notifications" -require "active_support/dependencies" -require "active_support/descendants_tracker" -require "rails/secrets" - -module Rails - class Application - module Bootstrap - include Initializable - - initializer :load_environment_hook, group: :all do end - - initializer :load_active_support, group: :all do - require "active_support/all" unless config.active_support.bare - end - - initializer :set_eager_load, group: :all do - if config.eager_load.nil? - warn <<-INFO -config.eager_load is set to nil. Please update your config/environments/*.rb files accordingly: - - * development - set it to false - * test - set it to false (unless you use a tool that preloads your test environment) - * production - set it to true - -INFO - config.eager_load = config.cache_classes - end - end - - # Initialize the logger early in the stack in case we need to log some deprecation. - initializer :initialize_logger, group: :all do - Rails.logger ||= config.logger || begin - path = config.paths["log"].first - unless File.exist? File.dirname path - FileUtils.mkdir_p File.dirname path - end - - f = File.open path, "a" - f.binmode - f.sync = config.autoflush_log # if true make sure every write flushes - - logger = ActiveSupport::Logger.new f - logger.formatter = config.log_formatter - logger = ActiveSupport::TaggedLogging.new(logger) - logger - rescue StandardError - logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR)) - logger.level = ActiveSupport::Logger::WARN - logger.warn( - "Rails Error: Unable to access log file. Please ensure that #{path} exists and is writable " \ - "(ie, make it writable for user and group: chmod 0664 #{path}). " \ - "The log level has been raised to WARN and the output directed to STDERR until the problem is fixed." - ) - logger - end - - Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase) - end - - # Initialize cache early in the stack so railties can make use of it. - initializer :initialize_cache, group: :all do - unless Rails.cache - Rails.cache = ActiveSupport::Cache.lookup_store(config.cache_store) - - if Rails.cache.respond_to?(:middleware) - config.middleware.insert_before(::Rack::Runtime, Rails.cache.middleware) - end - end - end - - # Sets the dependency loading mechanism. - initializer :initialize_dependency_mechanism, group: :all do - ActiveSupport::Dependencies.mechanism = config.cache_classes ? :require : :load - end - - initializer :bootstrap_hook, group: :all do |app| - ActiveSupport.run_load_hooks(:before_initialize, app) - end - - initializer :set_secrets_root, group: :all do - Rails::Secrets.root = root - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/application/configuration.rb b/debian/gems-compat/railties-5.1.7/lib/rails/application/configuration.rb deleted file mode 100644 index abcac0b320..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/application/configuration.rb +++ /dev/null @@ -1,216 +0,0 @@ -require "active_support/core_ext/kernel/reporting" -require "active_support/file_update_checker" -require "rails/engine/configuration" -require "rails/source_annotation_extractor" - -module Rails - class Application - class Configuration < ::Rails::Engine::Configuration - attr_accessor :allow_concurrency, :asset_host, :autoflush_log, - :cache_classes, :cache_store, :consider_all_requests_local, :console, - :eager_load, :exceptions_app, :file_watcher, :filter_parameters, - :force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags, - :railties_order, :relative_url_root, :secret_key_base, :secret_token, - :ssl_options, :public_file_server, - :session_options, :time_zone, :reload_classes_only_on_change, - :beginning_of_week, :filter_redirect, :x, :enable_dependency_loading, - :read_encrypted_secrets, :log_level - - attr_reader :encoding, :api_only - - def initialize(*) - super - self.encoding = Encoding::UTF_8 - @allow_concurrency = nil - @consider_all_requests_local = false - @filter_parameters = [] - @filter_redirect = [] - @helpers_paths = [] - @public_file_server = ActiveSupport::OrderedOptions.new - @public_file_server.enabled = true - @public_file_server.index_name = "index" - @force_ssl = false - @ssl_options = {} - @session_store = nil - @time_zone = "UTC" - @beginning_of_week = :monday - @log_level = :debug - @generators = app_generators - @cache_store = [ :file_store, "#{root}/tmp/cache/" ] - @railties_order = [:all] - @relative_url_root = ENV["RAILS_RELATIVE_URL_ROOT"] - @reload_classes_only_on_change = true - @file_watcher = ActiveSupport::FileUpdateChecker - @exceptions_app = nil - @autoflush_log = true - @log_formatter = ActiveSupport::Logger::SimpleFormatter.new - @eager_load = nil - @secret_token = nil - @secret_key_base = nil - @api_only = false - @debug_exception_response_format = nil - @x = Custom.new - @enable_dependency_loading = false - @read_encrypted_secrets = false - end - - def load_defaults(target_version) - case target_version.to_s - when "5.0" - if respond_to?(:action_controller) - action_controller.per_form_csrf_tokens = true - action_controller.forgery_protection_origin_check = true - end - - ActiveSupport.to_time_preserves_timezone = true - - if respond_to?(:active_record) - active_record.belongs_to_required_by_default = true - end - - self.ssl_options = { hsts: { subdomains: true } } - - when "5.1" - load_defaults "5.0" - - if respond_to?(:assets) - assets.unknown_asset_fallback = false - end - - else - raise "Unknown version #{target_version.to_s.inspect}" - end - end - - def encoding=(value) - @encoding = value - silence_warnings do - Encoding.default_external = value - Encoding.default_internal = value - end - end - - def api_only=(value) - @api_only = value - generators.api_only = value - - @debug_exception_response_format ||= :api - end - - def debug_exception_response_format - @debug_exception_response_format || :default - end - - def debug_exception_response_format=(value) - @debug_exception_response_format = value - end - - def paths - @paths ||= begin - paths = super - paths.add "config/database", with: "config/database.yml" - paths.add "config/secrets", with: "config", glob: "secrets.yml{,.enc}" - paths.add "config/environment", with: "config/environment.rb" - paths.add "lib/templates" - paths.add "log", with: "log/#{Rails.env}.log" - paths.add "public" - paths.add "public/javascripts" - paths.add "public/stylesheets" - paths.add "tmp" - paths - end - end - - # Loads and returns the entire raw configuration of database from - # values stored in `config/database.yml`. - def database_configuration - path = paths["config/database"].existent.first - yaml = Pathname.new(path) if path - - config = if yaml && yaml.exist? - require "yaml" - require "erb" - YAML.load(ERB.new(yaml.read).result) || {} - elsif ENV["DATABASE_URL"] - # Value from ENV['DATABASE_URL'] is set to default database connection - # by Active Record. - {} - else - raise "Could not load database configuration. No such file - #{paths["config/database"].instance_variable_get(:@paths)}" - end - - config - rescue Psych::SyntaxError => e - raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \ - "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ - "Error: #{e.message}" - rescue => e - raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace - end - - def colorize_logging - ActiveSupport::LogSubscriber.colorize_logging - end - - def colorize_logging=(val) - ActiveSupport::LogSubscriber.colorize_logging = val - generators.colorize_logging = val - end - - def session_store(new_session_store = nil, **options) - if new_session_store - if new_session_store == :active_record_store - begin - ActionDispatch::Session::ActiveRecordStore - rescue NameError - raise "`ActiveRecord::SessionStore` is extracted out of Rails into a gem. " \ - "Please add `activerecord-session_store` to your Gemfile to use it." - end - end - - @session_store = new_session_store - @session_options = options || {} - else - case @session_store - when :disabled - nil - when :active_record_store - ActionDispatch::Session::ActiveRecordStore - when Symbol - ActionDispatch::Session.const_get(@session_store.to_s.camelize) - else - @session_store - end - end - end - - def session_store? #:nodoc: - @session_store - end - - def annotations - SourceAnnotationExtractor::Annotation - end - - class Custom #:nodoc: - def initialize - @configurations = Hash.new - end - - def method_missing(method, *args) - if method =~ /=$/ - @configurations[$`.to_sym] = args.first - else - @configurations.fetch(method) { - @configurations[method] = ActiveSupport::OrderedOptions.new - } - end - end - - def respond_to_missing?(symbol, *) - true - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/application/default_middleware_stack.rb b/debian/gems-compat/railties-5.1.7/lib/rails/application/default_middleware_stack.rb deleted file mode 100644 index 8fe48feefb..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/application/default_middleware_stack.rb +++ /dev/null @@ -1,99 +0,0 @@ -module Rails - class Application - class DefaultMiddlewareStack - attr_reader :config, :paths, :app - - def initialize(app, config, paths) - @app = app - @config = config - @paths = paths - end - - def build_stack - ActionDispatch::MiddlewareStack.new.tap do |middleware| - if config.force_ssl - middleware.use ::ActionDispatch::SSL, config.ssl_options - end - - middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header - - if config.public_file_server.enabled - headers = config.public_file_server.headers || {} - - middleware.use ::ActionDispatch::Static, paths["public"].first, index: config.public_file_server.index_name, headers: headers - end - - if rack_cache = load_rack_cache - require "action_dispatch/http/rack_cache" - middleware.use ::Rack::Cache, rack_cache - end - - if config.allow_concurrency == false - # User has explicitly opted out of concurrent request - # handling: presumably their code is not threadsafe - - middleware.use ::Rack::Lock - end - - middleware.use ::ActionDispatch::Executor, app.executor - - middleware.use ::Rack::Runtime - middleware.use ::Rack::MethodOverride unless config.api_only - middleware.use ::ActionDispatch::RequestId - middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies - - middleware.use ::Rails::Rack::Logger, config.log_tags - middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app - middleware.use ::ActionDispatch::DebugExceptions, app, config.debug_exception_response_format - - unless config.cache_classes - middleware.use ::ActionDispatch::Reloader, app.reloader - end - - middleware.use ::ActionDispatch::Callbacks - middleware.use ::ActionDispatch::Cookies unless config.api_only - - if !config.api_only && config.session_store - if config.force_ssl && config.ssl_options.fetch(:secure_cookies, true) && !config.session_options.key?(:secure) - config.session_options[:secure] = true - end - middleware.use config.session_store, config.session_options - middleware.use ::ActionDispatch::Flash - end - - middleware.use ::Rack::Head - middleware.use ::Rack::ConditionalGet - middleware.use ::Rack::ETag, "no-cache" - end - end - - private - - def load_rack_cache - rack_cache = config.action_dispatch.rack_cache - return unless rack_cache - - begin - require "rack/cache" - rescue LoadError => error - error.message << " Be sure to add rack-cache to your Gemfile" - raise - end - - if rack_cache == true - { - metastore: "rails:/", - entitystore: "rails:/", - verbose: false - } - else - rack_cache - end - end - - def show_exceptions_app - config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/application/finisher.rb b/debian/gems-compat/railties-5.1.7/lib/rails/application/finisher.rb deleted file mode 100644 index d1f79fccad..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/application/finisher.rb +++ /dev/null @@ -1,194 +0,0 @@ -module Rails - class Application - module Finisher - include Initializable - - initializer :add_generator_templates do - config.generators.templates.unshift(*paths["lib/templates"].existent) - end - - initializer :ensure_autoload_once_paths_as_subset do - extra = ActiveSupport::Dependencies.autoload_once_paths - - ActiveSupport::Dependencies.autoload_paths - - unless extra.empty? - abort <<-end_error - autoload_once_paths must be a subset of the autoload_paths. - Extra items in autoload_once_paths: #{extra * ','} - end_error - end - end - - initializer :add_builtin_route do |app| - if Rails.env.development? - app.routes.prepend do - get "/rails/info/properties" => "rails/info#properties", internal: true - get "/rails/info/routes" => "rails/info#routes", internal: true - get "/rails/info" => "rails/info#index", internal: true - end - - app.routes.append do - get "/" => "rails/welcome#index", internal: true - end - end - end - - # Setup default session store if not already set in config/application.rb - initializer :setup_default_session_store, before: :build_middleware_stack do |app| - unless app.config.session_store? - app_name = app.class.name ? app.railtie_name.chomp("_application") : "" - app.config.session_store :cookie_store, key: "_#{app_name}_session" - end - end - - initializer :build_middleware_stack do - build_middleware_stack - end - - initializer :define_main_app_helper do |app| - app.routes.define_mounted_helper(:main_app) - end - - initializer :add_to_prepare_blocks do |app| - config.to_prepare_blocks.each do |block| - app.reloader.to_prepare(&block) - end - end - - # This needs to happen before eager load so it happens - # in exactly the same point regardless of config.cache_classes - initializer :run_prepare_callbacks do |app| - app.reloader.prepare! - end - - initializer :eager_load! do - if config.eager_load - ActiveSupport.run_load_hooks(:before_eager_load, self) - config.eager_load_namespaces.each(&:eager_load!) - end - end - - # All initialization is done, including eager loading in production - initializer :finisher_hook do - ActiveSupport.run_load_hooks(:after_initialize, self) - end - - class MutexHook - def initialize(mutex = Mutex.new) - @mutex = mutex - end - - def run - @mutex.lock - end - - def complete(_state) - @mutex.unlock - end - end - - module InterlockHook - def self.run - ActiveSupport::Dependencies.interlock.start_running - end - - def self.complete(_state) - ActiveSupport::Dependencies.interlock.done_running - end - end - - initializer :configure_executor_for_concurrency do |app| - if config.allow_concurrency == false - # User has explicitly opted out of concurrent request - # handling: presumably their code is not threadsafe - - app.executor.register_hook(MutexHook.new, outer: true) - - elsif config.allow_concurrency == :unsafe - # Do nothing, even if we know this is dangerous. This is the - # historical behavior for true. - - else - # Default concurrency setting: enabled, but safe - - unless config.cache_classes && config.eager_load - # Without cache_classes + eager_load, the load interlock - # is required for proper operation - - app.executor.register_hook(InterlockHook, outer: true) - end - end - end - - # Set routes reload after the finisher hook to ensure routes added in - # the hook are taken into account. - initializer :set_routes_reloader_hook do |app| - reloader = routes_reloader - reloader.eager_load = app.config.eager_load - reloader.execute - reloaders << reloader - app.reloader.to_run do - # We configure #execute rather than #execute_if_updated because if - # autoloaded constants are cleared we need to reload routes also in - # case any was used there, as in - # - # mount MailPreview => 'mail_view' - # - # This means routes are also reloaded if i18n is updated, which - # might not be necessary, but in order to be more precise we need - # some sort of reloaders dependency support, to be added. - require_unload_lock! - reloader.execute - end - end - - # Set clearing dependencies after the finisher hook to ensure paths - # added in the hook are taken into account. - initializer :set_clear_dependencies_hook, group: :all do |app| - callback = lambda do - ActiveSupport::DescendantsTracker.clear - ActiveSupport::Dependencies.clear - end - - if config.cache_classes - app.reloader.check = lambda { false } - elsif config.reload_classes_only_on_change - app.reloader.check = lambda do - app.reloaders.map(&:updated?).any? - end - else - app.reloader.check = lambda { true } - end - - if config.reload_classes_only_on_change - reloader = config.file_watcher.new(*watchable_args, &callback) - reloaders << reloader - - # Prepend this callback to have autoloaded constants cleared before - # any other possible reloading, in case they need to autoload fresh - # constants. - app.reloader.to_run(prepend: true) do - # In addition to changes detected by the file watcher, if routes - # or i18n have been updated we also need to clear constants, - # that's why we run #execute rather than #execute_if_updated, this - # callback has to clear autoloaded constants after any update. - class_unload! do - reloader.execute - end - end - else - app.reloader.to_complete do - class_unload!(&callback) - end - end - end - - # Disable dependency loading during request cycle - initializer :disable_dependency_loading do - if config.eager_load && config.cache_classes && !config.enable_dependency_loading - ActiveSupport::Dependencies.unhook! - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/application/routes_reloader.rb b/debian/gems-compat/railties-5.1.7/lib/rails/application/routes_reloader.rb deleted file mode 100644 index 6c89f18f8c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/application/routes_reloader.rb +++ /dev/null @@ -1,53 +0,0 @@ -require "active_support/core_ext/module/delegation" - -module Rails - class Application - class RoutesReloader - attr_reader :route_sets, :paths - attr_accessor :eager_load - delegate :execute_if_updated, :execute, :updated?, to: :updater - - def initialize - @paths = [] - @route_sets = [] - @eager_load = false - end - - def reload! - clear! - load_paths - finalize! - route_sets.each(&:eager_load!) if eager_load - ensure - revert - end - - private - - def updater - @updater ||= ActiveSupport::FileUpdateChecker.new(paths) { reload! } - end - - def clear! - route_sets.each do |routes| - routes.disable_clear_and_finalize = true - routes.clear! - end - end - - def load_paths - paths.each { |path| load(path) } - end - - def finalize! - route_sets.each(&:finalize!) - end - - def revert - route_sets.each do |routes| - routes.disable_clear_and_finalize = false - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/application_controller.rb b/debian/gems-compat/railties-5.1.7/lib/rails/application_controller.rb deleted file mode 100644 index a98e51fd28..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/application_controller.rb +++ /dev/null @@ -1,16 +0,0 @@ -class Rails::ApplicationController < ActionController::Base # :nodoc: - self.view_paths = File.expand_path("../templates", __FILE__) - layout "application" - - private - - def require_local! - unless local_request? - render html: "

    For security purposes, this information is only available to local requests.

    ".html_safe, status: :forbidden - end - end - - def local_request? - Rails.application.config.consider_all_requests_local || request.local? - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/backtrace_cleaner.rb b/debian/gems-compat/railties-5.1.7/lib/rails/backtrace_cleaner.rb deleted file mode 100644 index 5c833e12ba..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/backtrace_cleaner.rb +++ /dev/null @@ -1,32 +0,0 @@ -require "active_support/backtrace_cleaner" - -module Rails - class BacktraceCleaner < ActiveSupport::BacktraceCleaner - APP_DIRS_PATTERN = /^\/?(app|config|lib|test|\(\w*\))/ - RENDER_TEMPLATE_PATTERN = /:in `_render_template_\w*'/ - EMPTY_STRING = "".freeze - SLASH = "/".freeze - DOT_SLASH = "./".freeze - - def initialize - super - @root = "#{Rails.root}/".freeze - add_filter { |line| line.sub(@root, EMPTY_STRING) } - add_filter { |line| line.sub(RENDER_TEMPLATE_PATTERN, EMPTY_STRING) } - add_filter { |line| line.sub(DOT_SLASH, SLASH) } # for tests - - add_gem_filters - add_silencer { |line| line !~ APP_DIRS_PATTERN } - end - - private - def add_gem_filters - gems_paths = (Gem.path | [Gem.default_dir]).map { |p| Regexp.escape(p) } - return if gems_paths.empty? - - gems_regexp = %r{(#{gems_paths.join('|')})/gems/([^/]+)-([\w.]+)/(.*)} - gems_result = '\2 (\3) \4'.freeze - add_filter { |line| line.sub(gems_regexp, gems_result) } - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/cli.rb b/debian/gems-compat/railties-5.1.7/lib/rails/cli.rb deleted file mode 100644 index 973b746068..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/cli.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "rails/app_loader" - -# If we are inside a Rails application this method performs an exec and thus -# the rest of this script is not run. -Rails::AppLoader.exec_app - -require "rails/ruby_version_check" -Signal.trap("INT") { puts; exit(1) } - -require "rails/command" - -if ARGV.first == "plugin" - ARGV.shift - Rails::Command.invoke :plugin, ARGV -else - Rails::Command.invoke :application, ARGV -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/code_statistics.rb b/debian/gems-compat/railties-5.1.7/lib/rails/code_statistics.rb deleted file mode 100644 index 70dce268f1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/code_statistics.rb +++ /dev/null @@ -1,113 +0,0 @@ -require "rails/code_statistics_calculator" -require "active_support/core_ext/enumerable" - -class CodeStatistics #:nodoc: - TEST_TYPES = ["Controller tests", - "Helper tests", - "Model tests", - "Mailer tests", - "Job tests", - "Integration tests", - "System tests"] - - HEADERS = { lines: " Lines", code_lines: " LOC", classes: "Classes", methods: "Methods" } - - def initialize(*pairs) - @pairs = pairs - @statistics = calculate_statistics - @total = calculate_total if pairs.length > 1 - end - - def to_s - print_header - @pairs.each { |pair| print_line(pair.first, @statistics[pair.first]) } - print_splitter - - if @total - print_line("Total", @total) - print_splitter - end - - print_code_test_stats - end - - private - def calculate_statistics - Hash[@pairs.map { |pair| [pair.first, calculate_directory_statistics(pair.last)] }] - end - - def calculate_directory_statistics(directory, pattern = /^(?!\.).*?\.(rb|js|coffee|rake)$/) - stats = CodeStatisticsCalculator.new - - Dir.foreach(directory) do |file_name| - path = "#{directory}/#{file_name}" - - if File.directory?(path) && (/^\./ !~ file_name) - stats.add(calculate_directory_statistics(path, pattern)) - elsif file_name =~ pattern - stats.add_by_file_path(path) - end - end - - stats - end - - def calculate_total - @statistics.each_with_object(CodeStatisticsCalculator.new) do |pair, total| - total.add(pair.last) - end - end - - def calculate_code - code_loc = 0 - @statistics.each { |k, v| code_loc += v.code_lines unless TEST_TYPES.include? k } - code_loc - end - - def calculate_tests - test_loc = 0 - @statistics.each { |k, v| test_loc += v.code_lines if TEST_TYPES.include? k } - test_loc - end - - def width_for(label) - [@statistics.values.sum { |s| s.send(label) }.to_s.size, HEADERS[label].length].max - end - - def print_header - print_splitter - print "| Name " - HEADERS.each do |k, v| - print " | #{v.rjust(width_for(k))}" - end - puts " | M/C | LOC/M |" - print_splitter - end - - def print_splitter - print "+----------------------" - HEADERS.each_key do |k| - print "+#{'-' * (width_for(k) + 2)}" - end - puts "+-----+-------+" - end - - def print_line(name, statistics) - m_over_c = (statistics.methods / statistics.classes) rescue m_over_c = 0 - loc_over_m = (statistics.code_lines / statistics.methods) - 2 rescue loc_over_m = 0 - - print "| #{name.ljust(20)} " - HEADERS.each_key do |k| - print "| #{statistics.send(k).to_s.rjust(width_for(k))} " - end - puts "| #{m_over_c.to_s.rjust(3)} | #{loc_over_m.to_s.rjust(5)} |" - end - - def print_code_test_stats - code = calculate_code - tests = calculate_tests - - puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f / code)}" - puts "" - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/code_statistics_calculator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/code_statistics_calculator.rb deleted file mode 100644 index d0194af197..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/code_statistics_calculator.rb +++ /dev/null @@ -1,86 +0,0 @@ -class CodeStatisticsCalculator #:nodoc: - attr_reader :lines, :code_lines, :classes, :methods - - PATTERNS = { - rb: { - line_comment: /^\s*#/, - begin_block_comment: /^=begin/, - end_block_comment: /^=end/, - class: /^\s*class\s+[_A-Z]/, - method: /^\s*def\s+[_a-z]/, - }, - js: { - line_comment: %r{^\s*//}, - begin_block_comment: %r{^\s*/\*}, - end_block_comment: %r{\*/}, - method: /function(\s+[_a-zA-Z][\da-zA-Z]*)?\s*\(/, - }, - coffee: { - line_comment: /^\s*#/, - begin_block_comment: /^\s*###/, - end_block_comment: /^\s*###/, - class: /^\s*class\s+[_A-Z]/, - method: /[-=]>/, - } - } - - PATTERNS[:minitest] = PATTERNS[:rb].merge method: /^\s*(def|test)\s+['"_a-z]/ - PATTERNS[:rake] = PATTERNS[:rb] - - def initialize(lines = 0, code_lines = 0, classes = 0, methods = 0) - @lines = lines - @code_lines = code_lines - @classes = classes - @methods = methods - end - - def add(code_statistics_calculator) - @lines += code_statistics_calculator.lines - @code_lines += code_statistics_calculator.code_lines - @classes += code_statistics_calculator.classes - @methods += code_statistics_calculator.methods - end - - def add_by_file_path(file_path) - File.open(file_path) do |f| - add_by_io(f, file_type(file_path)) - end - end - - def add_by_io(io, file_type) - patterns = PATTERNS[file_type] || {} - - comment_started = false - - while line = io.gets - @lines += 1 - - if comment_started - if patterns[:end_block_comment] && line =~ patterns[:end_block_comment] - comment_started = false - end - next - else - if patterns[:begin_block_comment] && line =~ patterns[:begin_block_comment] - comment_started = true - next - end - end - - @classes += 1 if patterns[:class] && line =~ patterns[:class] - @methods += 1 if patterns[:method] && line =~ patterns[:method] - if line !~ /^\s*$/ && (patterns[:line_comment].nil? || line !~ patterns[:line_comment]) - @code_lines += 1 - end - end - end - - private - def file_type(file_path) - if file_path.end_with? "_test.rb" - :minitest - else - File.extname(file_path).sub(/\A\./, "").downcase.to_sym - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/command.rb deleted file mode 100644 index 0d4e6dc5a1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/command.rb +++ /dev/null @@ -1,111 +0,0 @@ -require "active_support" -require "active_support/dependencies/autoload" -require "active_support/core_ext/enumerable" -require "active_support/core_ext/object/blank" -require "active_support/core_ext/hash/transform_values" - -require "thor" - -module Rails - module Command - extend ActiveSupport::Autoload - - autoload :Behavior - autoload :Base - - include Behavior - - HELP_MAPPINGS = %w(-h -? --help) - - class << self - def hidden_commands # :nodoc: - @hidden_commands ||= [] - end - - def environment # :nodoc: - ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" - end - - # Receives a namespace, arguments and the behavior to invoke the command. - def invoke(full_namespace, args = [], **config) - namespace = full_namespace = full_namespace.to_s - - if char = namespace =~ /:(\w+)$/ - command_name, namespace = $1, namespace.slice(0, char) - else - command_name = namespace - end - - command_name, namespace = "help", "help" if command_name.blank? || HELP_MAPPINGS.include?(command_name) - command_name, namespace = "version", "version" if %w( -v --version ).include?(command_name) - - command = find_by_namespace(namespace, command_name) - if command && command.all_commands[command_name] - command.perform(command_name, args, config) - else - find_by_namespace("rake").perform(full_namespace, args, config) - end - end - - # Rails finds namespaces similar to Thor, it only adds one rule: - # - # Command names must end with "_command.rb". This is required because Rails - # looks in load paths and loads the command just before it's going to be used. - # - # find_by_namespace :webrat, :rails, :integration - # - # Will search for the following commands: - # - # "rails:webrat", "webrat:integration", "webrat" - # - # Notice that "rails:commands:webrat" could be loaded as well, what - # Rails looks for is the first and last parts of the namespace. - def find_by_namespace(namespace, command_name = nil) # :nodoc: - lookups = [ namespace ] - lookups << "#{namespace}:#{command_name}" if command_name - lookups.concat lookups.map { |lookup| "rails:#{lookup}" } - - lookup(lookups) - - namespaces = subclasses.index_by(&:namespace) - namespaces[(lookups & namespaces.keys).first] - end - - # Returns the root of the Rails engine or app running the command. - def root - if defined?(ENGINE_ROOT) - Pathname.new(ENGINE_ROOT) - elsif defined?(APP_PATH) - Pathname.new(File.expand_path("../..", APP_PATH)) - end - end - - def print_commands # :nodoc: - sorted_groups.each { |b, n| print_list(b, n) } - end - - def sorted_groups # :nodoc: - lookup! - - groups = (subclasses - hidden_commands).group_by { |c| c.namespace.split(":").first } - groups.transform_values! { |commands| commands.flat_map(&:printing_commands).sort } - - rails = groups.delete("rails") - [[ "rails", rails ]] + groups.sort.to_a - end - - private - def command_type # :doc: - @command_type ||= "command" - end - - def lookup_paths # :doc: - @lookup_paths ||= %w( rails/commands commands ) - end - - def file_lookup_paths # :doc: - @file_lookup_paths ||= [ "{#{lookup_paths.join(',')}}", "**", "*_command.rb" ] - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/command/actions.rb b/debian/gems-compat/railties-5.1.7/lib/rails/command/actions.rb deleted file mode 100644 index 8fda1c87c6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/command/actions.rb +++ /dev/null @@ -1,42 +0,0 @@ -module Rails - module Command - module Actions - # Change to the application's path if there is no config.ru file in current directory. - # This allows us to run `rails server` from other directories, but still get - # the main config.ru and properly set the tmp directory. - def set_application_directory! - Dir.chdir(File.expand_path("../../", APP_PATH)) unless File.exist?(File.expand_path("config.ru")) - end - - def require_application_and_environment! - require ENGINE_PATH if defined?(ENGINE_PATH) - - if defined?(APP_PATH) - require APP_PATH - Rails.application.require_environment! - end - end - - if defined?(ENGINE_PATH) - def load_tasks - Rake.application.init("rails") - Rake.application.load_rakefile - end - - def load_generators - engine = ::Rails::Engine.find(ENGINE_ROOT) - Rails::Generators.namespace = engine.railtie_namespace - engine.load_generators - end - else - def load_tasks - Rails.application.load_tasks - end - - def load_generators - Rails.application.load_generators - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/command/base.rb b/debian/gems-compat/railties-5.1.7/lib/rails/command/base.rb deleted file mode 100644 index 4f074df473..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/command/base.rb +++ /dev/null @@ -1,155 +0,0 @@ -require "thor" -require "erb" - -require "active_support/core_ext/string/filters" -require "active_support/core_ext/string/inflections" - -require "rails/command/actions" - -module Rails - module Command - class Base < Thor - class Error < Thor::Error # :nodoc: - end - - include Actions - - class << self - # Returns true when the app is a Rails engine. - def engine? - defined?(ENGINE_ROOT) - end - - # Tries to get the description from a USAGE file one folder above the command - # root. - def desc(usage = nil, description = nil, options = {}) - if usage - super - else - @desc ||= ERB.new(File.read(usage_path)).result(binding) if usage_path - end - end - - # Convenience method to get the namespace from the class name. It's the - # same as Thor default except that the Command at the end of the class - # is removed. - def namespace(name = nil) - if name - super - else - @namespace ||= super.chomp("_command").sub(/:command:/, ":") - end - end - - # Convenience method to hide this command from the available ones when - # running rails command. - def hide_command! - Rails::Command.hidden_commands << self - end - - def inherited(base) #:nodoc: - super - - if base.name && base.name !~ /Base$/ - Rails::Command.subclasses << base - end - end - - def perform(command, args, config) # :nodoc: - if Rails::Command::HELP_MAPPINGS.include?(args.first) - command, args = "help", [] - end - - dispatch(command, args.dup, nil, config) - end - - def printing_commands - namespaced_commands - end - - def executable - "bin/rails #{command_name}" - end - - # Use Rails' default banner. - def banner(*) - "#{executable} #{arguments.map(&:usage).join(' ')} [options]".squish! - end - - # Sets the base_name taking into account the current class namespace. - # - # Rails::Command::TestCommand.base_name # => 'rails' - def base_name - @base_name ||= begin - if base = name.to_s.split("::").first - base.underscore - end - end - end - - # Return command name without namespaces. - # - # Rails::Command::TestCommand.command_name # => 'test' - def command_name - @command_name ||= begin - if command = name.to_s.split("::").last - command.chomp!("Command") - command.underscore - end - end - end - - # Path to lookup a USAGE description in a file. - def usage_path - if default_command_root - path = File.join(default_command_root, "USAGE") - path if File.exist?(path) - end - end - - # Default file root to place extra files a command might need, placed - # one folder above the command file. - # - # For a `Rails::Command::TestCommand` placed in `rails/command/test_command.rb` - # would return `rails/test`. - def default_command_root - path = File.expand_path(File.join("../commands", command_root_namespace), __dir__) - path if File.exist?(path) - end - - private - # Allow the command method to be called perform. - def create_command(meth) - if meth == "perform" - alias_method command_name, meth - else - # Prevent exception about command without usage. - # Some commands define their documentation differently. - @usage ||= "" - @desc ||= "" - - super - end - end - - def command_root_namespace - (namespace.split(":") - %w( rails )).first - end - - def namespaced_commands - commands.keys.map do |key| - key == command_root_namespace ? key : "#{command_root_namespace}:#{key}" - end - end - end - - def help - if command_name = self.class.command_name - self.class.command_help(shell, command_name) - else - super - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/command/behavior.rb b/debian/gems-compat/railties-5.1.7/lib/rails/command/behavior.rb deleted file mode 100644 index 4a92f72f16..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/command/behavior.rb +++ /dev/null @@ -1,123 +0,0 @@ -require "active_support" - -module Rails - module Command - module Behavior #:nodoc: - extend ActiveSupport::Concern - - class_methods do - # Remove the color from output. - def no_color! - Thor::Base.shell = Thor::Shell::Basic - end - - # Track all command subclasses. - def subclasses - @subclasses ||= [] - end - - private - - # This code is based directly on the Text gem implementation. - # Copyright (c) 2006-2013 Paul Battley, Michael Neumann, Tim Fletcher. - # - # Returns a value representing the "cost" of transforming str1 into str2. - def levenshtein_distance(str1, str2) # :doc: - s = str1 - t = str2 - n = s.length - m = t.length - - return m if (0 == n) - return n if (0 == m) - - d = (0..m).to_a - x = nil - - # avoid duplicating an enumerable object in the loop - str2_codepoint_enumerable = str2.each_codepoint - - str1.each_codepoint.with_index do |char1, i| - e = i + 1 - - str2_codepoint_enumerable.with_index do |char2, j| - cost = (char1 == char2) ? 0 : 1 - x = [ - d[j + 1] + 1, # insertion - e + 1, # deletion - d[j] + cost # substitution - ].min - d[j] = e - e = x - end - - d[m] = x - end - - x - end - - # Prints a list of generators. - def print_list(base, namespaces) - return if namespaces.empty? - puts "#{base.camelize}:" - - namespaces.each do |namespace| - puts(" #{namespace}") - end - - puts - end - - # Receives namespaces in an array and tries to find matching generators - # in the load path. - def lookup(namespaces) - paths = namespaces_to_paths(namespaces) - - paths.each do |raw_path| - lookup_paths.each do |base| - path = "#{base}/#{raw_path}_#{command_type}" - - begin - require path - return - rescue LoadError => e - raise unless e.message =~ /#{Regexp.escape(path)}$/ - rescue Exception => e - warn "[WARNING] Could not load #{command_type} #{path.inspect}. Error: #{e.message}.\n#{e.backtrace.join("\n")}" - end - end - end - end - - # This will try to load any command in the load path to show in help. - def lookup! - $LOAD_PATH.each do |base| - Dir[File.join(base, *file_lookup_paths)].each do |path| - begin - path = path.sub("#{base}/", "") - require path - rescue Exception - # No problem - end - end - end - end - - # Convert namespaces to paths by replacing ":" for "/" and adding - # an extra lookup. For example, "rails:model" should be searched - # in both: "rails/model/model_generator" and "rails/model_generator". - def namespaces_to_paths(namespaces) - paths = [] - namespaces.each do |namespace| - pieces = namespace.split(":") - paths << pieces.dup.push(pieces.last).join("/") - paths << pieces.join("/") - end - paths.uniq! - paths - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/command/environment_argument.rb b/debian/gems-compat/railties-5.1.7/lib/rails/command/environment_argument.rb deleted file mode 100644 index 05eac34155..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/command/environment_argument.rb +++ /dev/null @@ -1,34 +0,0 @@ -require "active_support" - -module Rails - module Command - module EnvironmentArgument #:nodoc: - extend ActiveSupport::Concern - - included do - argument :environment, optional: true, banner: "environment" - end - - private - def extract_environment_option_from_argument - if environment - self.options = options.merge(environment: acceptable_environment(environment)) - elsif !options[:environment] - self.options = options.merge(environment: Rails::Command.environment) - end - end - - def acceptable_environment(env = nil) - if available_environments.include? env - env - else - %w( production development test ).detect { |e| e =~ /^#{env}/ } || env - end - end - - def available_environments - Dir["config/environments/*.rb"].map { |fname| File.basename(fname, ".*") } - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands.rb deleted file mode 100644 index fff0119c65..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "rails/command" - -aliases = { - "g" => "generate", - "d" => "destroy", - "c" => "console", - "s" => "server", - "db" => "dbconsole", - "r" => "runner", - "t" => "test" -} - -command = ARGV.shift -command = aliases[command] || command - -Rails::Command.invoke command, ARGV diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/application/application_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/application/application_command.rb deleted file mode 100644 index 7675d3b3d1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/application/application_command.rb +++ /dev/null @@ -1,29 +0,0 @@ -require "rails/generators" -require "rails/generators/rails/app/app_generator" - -module Rails - module Generators - class AppGenerator # :nodoc: - # We want to exit on failure to be kind to other libraries - # This is only when accessing via CLI - def self.exit_on_failure? - true - end - end - end - - module Command - class ApplicationCommand < Base # :nodoc: - hide_command! - - def help - perform # Punt help output to the generator. - end - - def perform(*args) - Rails::Generators::AppGenerator.start \ - Rails::Generators::ARGVScrubber.new(args).prepare! - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/console/console_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/console/console_command.rb deleted file mode 100644 index ec58540923..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/console/console_command.rb +++ /dev/null @@ -1,101 +0,0 @@ -require "irb" -require "irb/completion" - -require "rails/command/environment_argument" - -module Rails - class Console - module BacktraceCleaner - def filter_backtrace(bt) - if result = super - Rails.backtrace_cleaner.filter([result]).first - end - end - end - - def self.start(*args) - new(*args).start - end - - attr_reader :options, :app, :console - - def initialize(app, options = {}) - @app = app - @options = options - - app.sandbox = sandbox? - app.load_console - - @console = app.config.console || IRB - - if @console == IRB - IRB::WorkSpace.prepend(BacktraceCleaner) - end - end - - def sandbox? - options[:sandbox] - end - - def environment - options[:environment] - end - alias_method :environment?, :environment - - def set_environment! - Rails.env = environment - end - - def start - set_environment! if environment? - - if sandbox? - puts "Loading #{Rails.env} environment in sandbox (Rails #{Rails.version})" - puts "Any modifications you make will be rolled back on exit" - else - puts "Loading #{Rails.env} environment (Rails #{Rails.version})" - end - - if defined?(console::ExtendCommandBundle) - console::ExtendCommandBundle.include(Rails::ConsoleMethods) - end - console.start - end - end - - module Command - class ConsoleCommand < Base # :nodoc: - include EnvironmentArgument - - class_option :sandbox, aliases: "-s", type: :boolean, default: false, - desc: "Rollback database modifications on exit." - - class_option :environment, aliases: "-e", type: :string, - desc: "Specifies the environment to run this console under (test/development/production)." - - def initialize(args = [], local_options = {}, config = {}) - console_options = [] - - # For the same behavior as OptionParser, leave only options after "--" in ARGV. - termination = local_options.find_index("--") - if termination - console_options = local_options[termination + 1..-1] - local_options = local_options[0...termination] - end - - ARGV.replace(console_options) - super(args, local_options, config) - end - - def perform - extract_environment_option_from_argument - - # RAILS_ENV needs to be set before config/application is required. - ENV["RAILS_ENV"] = options[:environment] - - require_application_and_environment! - Rails::Console.start(Rails.application, options) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/dbconsole/dbconsole_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/dbconsole/dbconsole_command.rb deleted file mode 100644 index 627b00cce4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/dbconsole/dbconsole_command.rb +++ /dev/null @@ -1,159 +0,0 @@ -require "rails/command/environment_argument" - -module Rails - class DBConsole - def self.start(*args) - new(*args).start - end - - def initialize(options = {}) - @options = options - end - - def start - ENV["RAILS_ENV"] ||= @options[:environment] || environment - - case config["adapter"] - when /^(jdbc)?mysql/ - args = { - "host" => "--host", - "port" => "--port", - "socket" => "--socket", - "username" => "--user", - "encoding" => "--default-character-set", - "sslca" => "--ssl-ca", - "sslcert" => "--ssl-cert", - "sslcapath" => "--ssl-capath", - "sslcipher" => "--ssl-cipher", - "sslkey" => "--ssl-key" - }.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact - - if config["password"] && @options["include_password"] - args << "--password=#{config['password']}" - elsif config["password"] && !config["password"].to_s.empty? - args << "-p" - end - - args << config["database"] - - find_cmd_and_exec(["mysql", "mysql5"], *args) - - when /^postgres|^postgis/ - ENV["PGUSER"] = config["username"] if config["username"] - ENV["PGHOST"] = config["host"] if config["host"] - ENV["PGPORT"] = config["port"].to_s if config["port"] - ENV["PGPASSWORD"] = config["password"].to_s if config["password"] && @options["include_password"] - find_cmd_and_exec("psql", config["database"]) - - when "sqlite3" - args = [] - - args << "-#{@options['mode']}" if @options["mode"] - args << "-header" if @options["header"] - args << File.expand_path(config["database"], Rails.respond_to?(:root) ? Rails.root : nil) - - find_cmd_and_exec("sqlite3", *args) - - when "oracle", "oracle_enhanced" - logon = "" - - if config["username"] - logon = config["username"] - logon << "/#{config['password']}" if config["password"] && @options["include_password"] - logon << "@#{config['database']}" if config["database"] - end - - find_cmd_and_exec("sqlplus", logon) - - when "sqlserver" - args = [] - - args += ["-D", "#{config['database']}"] if config["database"] - args += ["-U", "#{config['username']}"] if config["username"] - args += ["-P", "#{config['password']}"] if config["password"] - - if config["host"] - host_arg = "#{config['host']}" - host_arg << ":#{config['port']}" if config["port"] - args += ["-S", host_arg] - end - - find_cmd_and_exec("sqsh", *args) - - else - abort "Unknown command-line client for #{config['database']}." - end - end - - def config - @config ||= begin - if configurations[environment].blank? - raise ActiveRecord::AdapterNotSpecified, "'#{environment}' database is not configured. Available configuration: #{configurations.inspect}" - else - configurations[environment] - end - end - end - - def environment - Rails.respond_to?(:env) ? Rails.env : Rails::Command.environment - end - - private - def configurations # :doc: - require APP_PATH - ActiveRecord::Base.configurations = Rails.application.config.database_configuration - ActiveRecord::Base.configurations - end - - def find_cmd_and_exec(commands, *args) # :doc: - commands = Array(commands) - - dirs_on_path = ENV["PATH"].to_s.split(File::PATH_SEPARATOR) - unless (ext = RbConfig::CONFIG["EXEEXT"]).empty? - commands = commands.map { |cmd| "#{cmd}#{ext}" } - end - - full_path_command = nil - found = commands.detect do |cmd| - dirs_on_path.detect do |path| - full_path_command = File.join(path, cmd) - File.file?(full_path_command) && File.executable?(full_path_command) - end - end - - if found - exec full_path_command, *args - else - abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.") - end - end - end - - module Command - class DbconsoleCommand < Base # :nodoc: - include EnvironmentArgument - - class_option :include_password, aliases: "-p", type: :boolean, - desc: "Automatically provide the password from database.yml" - - class_option :mode, enum: %w( html list line column ), type: :string, - desc: "Automatically put the sqlite3 database in the specified mode (html, list, line, column)." - - class_option :header, type: :string - - class_option :environment, aliases: "-e", type: :string, - desc: "Specifies the environment to run this console under (test/development/production)." - - def perform - extract_environment_option_from_argument - - # RAILS_ENV needs to be set before config/application is required. - ENV["RAILS_ENV"] = options[:environment] - - require_application_and_environment! - Rails::DBConsole.start(options) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/destroy/destroy_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/destroy/destroy_command.rb deleted file mode 100644 index 281732a936..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/destroy/destroy_command.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "rails/generators" - -module Rails - module Command - class DestroyCommand < Base # :nodoc: - no_commands do - def help - require_application_and_environment! - load_generators - - Rails::Generators.help self.class.command_name - end - end - - def perform(*) - generator = args.shift - return help unless generator - - require_application_and_environment! - load_generators - - Rails::Generators.invoke generator, args, behavior: :revoke, destination_root: Rails::Command.root - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/generate/generate_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/generate/generate_command.rb deleted file mode 100644 index 9dd7ad1012..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/generate/generate_command.rb +++ /dev/null @@ -1,28 +0,0 @@ -require "rails/generators" - -module Rails - module Command - class GenerateCommand < Base # :nodoc: - no_commands do - def help - require_application_and_environment! - load_generators - - Rails::Generators.help self.class.command_name - end - end - - def perform(*) - generator = args.shift - return help unless generator - - require_application_and_environment! - load_generators - - ARGV.shift - - Rails::Generators.invoke generator, args, behavior: :invoke, destination_root: Rails::Command.root - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/help/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/commands/help/USAGE deleted file mode 100644 index 8eb98319d2..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/help/USAGE +++ /dev/null @@ -1,16 +0,0 @@ -The most common rails commands are: - generate Generate new code (short-cut alias: "g") - console Start the Rails console (short-cut alias: "c") - server Start the Rails server (short-cut alias: "s") - test Run tests except system tests (short-cut alias: "t") - test:system Run system tests - dbconsole Start a console for the database specified in config/database.yml - (short-cut alias: "db") -<% unless engine? %> - new Create a new Rails application. "rails new my_app" creates a - new application called MyApp in "./my_app" -<% end %> - -All commands can be run with -h (or --help) for more information. -In addition to those commands, there are: - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/help/help_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/help/help_command.rb deleted file mode 100644 index 90d37217fc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/help/help_command.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Rails - module Command - class HelpCommand < Base # :nodoc: - hide_command! - - def help(*) - puts self.class.desc - - Rails::Command.print_commands - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/new/new_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/new/new_command.rb deleted file mode 100644 index 207dd5d995..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/new/new_command.rb +++ /dev/null @@ -1,17 +0,0 @@ -module Rails - module Command - class NewCommand < Base # :nodoc: - no_commands do - def help - Rails::Command.invoke :application, [ "--help" ] - end - end - - def perform(*) - puts "Can't initialize a new Rails application within the directory of another, please change to a non-Rails directory first.\n" - puts "Type 'rails' for help." - exit 1 - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/plugin/plugin_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/plugin/plugin_command.rb deleted file mode 100644 index b40ab006af..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/plugin/plugin_command.rb +++ /dev/null @@ -1,43 +0,0 @@ -module Rails - module Command - class PluginCommand < Base # :nodoc: - hide_command! - - def help - run_plugin_generator %w( --help ) - end - - def self.banner(*) # :nodoc: - "#{executable} new [options]" - end - - class_option :rc, type: :string, default: File.join("~", ".railsrc"), - desc: "Initialize the plugin command with previous defaults. Uses .railsrc in your home directory by default." - - class_option :no_rc, desc: "Skip evaluating .railsrc." - - def perform(type = nil, *plugin_args) - plugin_args << "--help" unless type == "new" - - unless options.key?("no_rc") # Thor's not so indifferent access hash. - railsrc = File.expand_path(options[:rc]) - - if File.exist?(railsrc) - extra_args = File.read(railsrc).split(/\n+/).flat_map(&:split) - puts "Using #{extra_args.join(" ")} from #{railsrc}" - plugin_args.insert(1, *extra_args) - end - end - - run_plugin_generator plugin_args - end - - private - def run_plugin_generator(plugin_args) - require "rails/generators" - require "rails/generators/rails/plugin/plugin_generator" - Rails::Generators::PluginGenerator.start plugin_args - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/rake/rake_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/rake/rake_command.rb deleted file mode 100644 index 075b1fd23d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/rake/rake_command.rb +++ /dev/null @@ -1,49 +0,0 @@ -module Rails - module Command - class RakeCommand < Base # :nodoc: - extend Rails::Command::Actions - - namespace "rake" - - class << self - def printing_commands - formatted_rake_tasks.map(&:first) - end - - def perform(task, *) - require_rake - - ARGV.unshift(task) # Prepend the task, so Rake knows how to run it. - - Rake.application.standard_exception_handling do - Rake.application.init("rails") - Rake.application.load_rakefile - Rake.application.top_level - end - end - - private - def rake_tasks - require_rake - - return @rake_tasks if defined?(@rake_tasks) - - require_application_and_environment! - - Rake::TaskManager.record_task_metadata = true - Rake.application.instance_variable_set(:@name, "rails") - load_tasks - @rake_tasks = Rake.application.tasks.select(&:comment) - end - - def formatted_rake_tasks - rake_tasks.map { |t| [ t.name_with_args, t.comment ] } - end - - def require_rake - require "rake" # Defer booting Rake until we know it's needed. - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/runner/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/commands/runner/USAGE deleted file mode 100644 index b2a6e8493d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/runner/USAGE +++ /dev/null @@ -1,17 +0,0 @@ -Examples: - -Run `puts Rails.env` after loading the app: - - <%= executable %> 'puts Rails.env' - -Run the Ruby file located at `path/to/filename.rb` after loading the app: - - <%= executable %> path/to/filename.rb - -<% unless Gem.win_platform? %> -You can also use the runner command as a shebang line for your executables: - - #!/usr/bin/env <%= File.expand_path(executable) %> - - Product.all.each { |p| p.price *= 2 ; p.save! } -<% end %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/runner/runner_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/runner/runner_command.rb deleted file mode 100644 index 6864a9726b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/runner/runner_command.rb +++ /dev/null @@ -1,49 +0,0 @@ -module Rails - module Command - class RunnerCommand < Base # :nodoc: - class_option :environment, aliases: "-e", type: :string, - default: Rails::Command.environment.dup, - desc: "The environment for the runner to operate under (test/development/production)" - - no_commands do - def help - super - puts self.class.desc - end - end - - def self.banner(*) - "#{super} [<'Some.ruby(code)'> | ]" - end - - def perform(code_or_file = nil, *command_argv) - unless code_or_file - help - exit 1 - end - - ENV["RAILS_ENV"] = options[:environment] - - require_application_and_environment! - Rails.application.load_runner - - ARGV.replace(command_argv) - - if File.exist?(code_or_file) - $0 = code_or_file - Kernel.load code_or_file - else - begin - eval(code_or_file, binding, __FILE__, __LINE__) - rescue SyntaxError, NameError => error - $stderr.puts "Please specify a valid ruby command or the path of a script to run." - $stderr.puts "Run '#{self.class.executable} -h' for help." - $stderr.puts - $stderr.puts error - exit 1 - end - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/secrets/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/commands/secrets/USAGE deleted file mode 100644 index 96e322fe91..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/secrets/USAGE +++ /dev/null @@ -1,60 +0,0 @@ -=== Storing Encrypted Secrets in Source Control - -The Rails `secrets` commands helps encrypting secrets to slim a production -environment's `ENV` hash. It's also useful for atomic deploys: no need to -coordinate key changes to get everything working as the keys are shipped -with the code. - -=== Setup - -Run `bin/rails secrets:setup` to opt in and generate the `config/secrets.yml.key` -and `config/secrets.yml.enc` files. - -The latter contains all the keys to be encrypted while the former holds the -encryption key. - -Don't lose the key! Put it in a password manager your team can access. -Should you lose it no one, including you, will be able to access any encrypted -secrets. -Don't commit the key! Add `config/secrets.yml.key` to your source control's -ignore file. If you use Git, Rails handles this for you. - -Rails also looks for the key in `ENV["RAILS_MASTER_KEY"]` if that's easier to -manage. - -You could prepend that to your server's start command like this: - - RAILS_MASTER_KEY="im-the-master-now-hahaha" server.start - - -The `config/secrets.yml.enc` has much the same format as `config/secrets.yml`: - - production: - secret_key_base: so-secret-very-hidden-wow - payment_processing_gateway_key: much-safe-very-gaedwey-wow - -But that's where the similarities between `secrets.yml` and `secrets.yml.enc` -end, e.g. no keys from `secrets.yml` will be moved to `secrets.yml.enc` and -be encrypted. - -A `shared:` top level key is also supported such that any keys there is merged -into the other environments. - -Additionally, Rails won't read encrypted secrets out of the box even if you have -the key. Add this: - - config.read_encrypted_secrets = true - -to the environment you'd like to read encrypted secrets. `bin/rails secrets:setup` -inserts this into the production environment by default. - -=== Editing Secrets - -After `bin/rails secrets:setup`, run `bin/rails secrets:edit`. - -That command opens a temporary file in `$EDITOR` with the decrypted contents of -`config/secrets.yml.enc` to edit the encrypted secrets. - -When the temporary file is next saved the contents are encrypted and written to -`config/secrets.yml.enc` while the file itself is destroyed to prevent secrets -from leaking. diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/secrets/secrets_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/secrets/secrets_command.rb deleted file mode 100644 index 5f077a5bcb..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/secrets/secrets_command.rb +++ /dev/null @@ -1,60 +0,0 @@ -require "active_support" -require "rails/secrets" - -module Rails - module Command - class SecretsCommand < Rails::Command::Base # :nodoc: - no_commands do - def help - say "Usage:\n #{self.class.banner}" - say "" - say self.class.desc - end - end - - def setup - generator.start - end - - def edit - if ENV["EDITOR"].to_s.empty? - say "No $EDITOR to open decrypted secrets in. Assign one like this:" - say "" - say %(EDITOR="mate --wait" bin/rails secrets:edit) - say "" - say "For editors that fork and exit immediately, it's important to pass a wait flag," - say "otherwise the secrets will be saved immediately with no chance to edit." - - return - end - - require_application_and_environment! - - Rails::Secrets.read_for_editing do |tmp_path| - system("#{ENV["EDITOR"]} #{tmp_path}") - end - - say "New secrets encrypted and saved." - rescue Interrupt - say "Aborted changing encrypted secrets: nothing saved." - rescue Rails::Secrets::MissingKeyError => error - say error.message - rescue Errno::ENOENT => error - raise unless error.message =~ /secrets\.yml\.enc/ - - Rails::Secrets.read_template_for_editing do |tmp_path| - system("#{ENV["EDITOR"]} #{tmp_path}") - generator.skip_secrets_file { setup } - end - end - - private - def generator - require "rails/generators" - require "rails/generators/rails/encrypted_secrets/encrypted_secrets_generator" - - Rails::Generators::EncryptedSecretsGenerator - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/server/server_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/server/server_command.rb deleted file mode 100644 index 423e1595db..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/server/server_command.rb +++ /dev/null @@ -1,228 +0,0 @@ -require "fileutils" -require "optparse" -require "action_dispatch" -require "rails" -require "rails/dev_caching" - -module Rails - class Server < ::Rack::Server - class Options - def parse!(args) - Rails::Command::ServerCommand.new([], args).server_options - end - end - - def initialize(options = nil) - @default_options = options || {} - super(@default_options) - set_environment - end - - # TODO: this is no longer required but we keep it for the moment to support older config.ru files. - def app - @app ||= begin - app = super - app.respond_to?(:to_app) ? app.to_app : app - end - end - - def opt_parser - Options.new - end - - def set_environment - ENV["RAILS_ENV"] ||= options[:environment] - end - - def start - print_boot_information - trap(:INT) { exit } - create_tmp_directories - setup_dev_caching - log_to_stdout if options[:log_stdout] - - super - ensure - # The '-h' option calls exit before @options is set. - # If we call 'options' with it unset, we get double help banners. - puts "Exiting" unless @options && options[:daemonize] - end - - def middleware - Hash.new([]) - end - - def default_options - super.merge(@default_options) - end - - private - def setup_dev_caching - if options[:environment] == "development" - Rails::DevCaching.enable_by_argument(options[:caching]) - end - end - - def print_boot_information - url = "on #{options[:SSLEnable] ? 'https' : 'http'}://#{options[:Host]}:#{options[:Port]}" unless use_puma? - puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" - puts "=> Rails #{Rails.version} application starting in #{Rails.env} #{url}" - puts "=> Run `rails server -h` for more startup options" - end - - def create_tmp_directories - %w(cache pids sockets).each do |dir_to_make| - FileUtils.mkdir_p(File.join(Rails.root, "tmp", dir_to_make)) - end - end - - def log_to_stdout - wrapped_app # touch the app so the logger is set up - - console = ActiveSupport::Logger.new(STDOUT) - console.formatter = Rails.logger.formatter - console.level = Rails.logger.level - - unless ActiveSupport::Logger.logger_outputs_to?(Rails.logger, STDOUT) - Rails.logger.extend(ActiveSupport::Logger.broadcast(console)) - end - end - - def restart_command - "bin/rails server #{ARGV.join(' ')}" - end - - def use_puma? - server.to_s == "Rack::Handler::Puma" - end - end - - module Command - class ServerCommand < Base # :nodoc: - DEFAULT_PORT = 3000 - DEFAULT_PID_PATH = "tmp/pids/server.pid".freeze - - class_option :port, aliases: "-p", type: :numeric, - desc: "Runs Rails on the specified port - defaults to 3000.", banner: :port - class_option :binding, aliases: "-b", type: :string, - desc: "Binds Rails to the specified IP - defaults to 'localhost' in development and '0.0.0.0' in other environments'.", - banner: :IP - class_option :config, aliases: "-c", type: :string, default: "config.ru", - desc: "Uses a custom rackup configuration.", banner: :file - class_option :daemon, aliases: "-d", type: :boolean, default: false, - desc: "Runs server as a Daemon." - class_option :environment, aliases: "-e", type: :string, - desc: "Specifies the environment to run this server under (development/test/production).", banner: :name - class_option :pid, aliases: "-P", type: :string, default: DEFAULT_PID_PATH, - desc: "Specifies the PID file." - class_option "dev-caching", aliases: "-C", type: :boolean, default: nil, - desc: "Specifies whether to perform caching in development." - - def initialize(args = [], local_options = {}, config = {}) - @original_options = local_options - super - @server = self.args.shift - @log_stdout = options[:daemon].blank? && (options[:environment] || Rails.env) == "development" - end - - def perform - set_application_directory! - Rails::Server.new(server_options).tap do |server| - # Require application after server sets environment to propagate - # the --environment option. - require APP_PATH - Dir.chdir(Rails.application.root) - server.start - end - end - - no_commands do - def server_options - { - user_supplied_options: user_supplied_options, - server: @server, - log_stdout: @log_stdout, - Port: port, - Host: host, - DoNotReverseLookup: true, - config: options[:config], - environment: environment, - daemonize: options[:daemon], - pid: pid, - caching: options["dev-caching"], - restart_cmd: restart_command - } - end - end - - private - def user_supplied_options - @user_supplied_options ||= begin - # Convert incoming options array to a hash of flags - # ["-p3001", "-C", "--binding", "127.0.0.1"] # => {"-p"=>true, "-C"=>true, "--binding"=>true} - user_flag = {} - @original_options.each do |command| - if command.to_s.start_with?("--") - option = command.split("=")[0] - user_flag[option] = true - elsif command =~ /\A(-.)/ - user_flag[Regexp.last_match[0]] = true - end - end - - # Collect all options that the user has explicitly defined so we can - # differentiate them from defaults - user_supplied_options = [] - self.class.class_options.select do |key, option| - if option.aliases.any? { |name| user_flag[name] } || user_flag["--#{option.name}"] - name = option.name.to_sym - case name - when :port - name = :Port - when :binding - name = :Host - when :"dev-caching" - name = :caching - when :daemonize - name = :daemon - end - user_supplied_options << name - end - end - user_supplied_options << :Host if ENV["HOST"] - user_supplied_options << :Port if ENV["PORT"] - user_supplied_options.uniq - end - end - - def port - options[:port] || ENV.fetch("PORT", DEFAULT_PORT).to_i - end - - def host - if options[:binding] - options[:binding] - else - default_host = environment == "development" ? "localhost" : "0.0.0.0" - ENV.fetch("HOST", default_host) - end - end - - def environment - options[:environment] || Rails::Command.environment - end - - def restart_command - "bin/rails server #{@server} #{@original_options.join(" ")}" - end - - def pid - File.expand_path(options[:pid]) - end - - def self.banner(*) - "rails server [puma, thin etc] [options]" - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/test/test_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/test/test_command.rb deleted file mode 100644 index 5852f51a62..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/test/test_command.rb +++ /dev/null @@ -1,42 +0,0 @@ -require_relative "../../command" -require_relative "../../test_unit/runner" - -module Rails - module Command - class TestCommand < Base # :nodoc: - no_commands do - def help - require "optparse" - require "minitest/rails_plugin" - - opts = OptionParser.new - opts.banner = "Usage: #{Rails::TestUnitReporter.executable} [options] [files or directories]" - opts.separator "" - opts.separator "You can run a single test by appending a line number to a filename:" - opts.separator "" - opts.separator " #{Rails::TestUnitReporter.executable} test/models/user_test.rb:27" - opts.separator "" - opts.separator "You can run multiple files and directories at the same time:" - opts.separator "" - opts.separator " #{Rails::TestUnitReporter.executable} test/controllers test/integration/login_test.rb" - opts.separator "" - opts.separator "By default test failures and errors are reported inline during a run." - opts.separator "" - - opts.separator "Rails options:" - Rails::TestUnit::Runner.options(opts) - Minitest.plugin_rails_options(opts, {}) - - say opts - end - end - - def perform(*) - $LOAD_PATH << Rails::Command.root.join("test").to_s - - Rails::TestUnit::Runner.parse_options(ARGV) - Rails::TestUnit::Runner.run(ARGV) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/commands/version/version_command.rb b/debian/gems-compat/railties-5.1.7/lib/rails/commands/version/version_command.rb deleted file mode 100644 index ac745594ee..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/commands/version/version_command.rb +++ /dev/null @@ -1,9 +0,0 @@ -module Rails - module Command - class VersionCommand < Base # :nodoc: - def perform - Rails::Command.invoke :application, [ "--version" ] - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/configuration.rb b/debian/gems-compat/railties-5.1.7/lib/rails/configuration.rb deleted file mode 100644 index fc7d4909f6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/configuration.rb +++ /dev/null @@ -1,135 +0,0 @@ -require "active_support/ordered_options" -require "active_support/core_ext/object" -require "rails/paths" -require "rails/rack" - -module Rails - module Configuration - # MiddlewareStackProxy is a proxy for the Rails middleware stack that allows - # you to configure middlewares in your application. It works basically as a - # command recorder, saving each command to be applied after initialization - # over the default middleware stack, so you can add, swap, or remove any - # middleware in Rails. - # - # You can add your own middlewares by using the +config.middleware.use+ method: - # - # config.middleware.use Magical::Unicorns - # - # This will put the Magical::Unicorns middleware on the end of the stack. - # You can use +insert_before+ if you wish to add a middleware before another: - # - # config.middleware.insert_before Rack::Head, Magical::Unicorns - # - # There's also +insert_after+ which will insert a middleware after another: - # - # config.middleware.insert_after Rack::Head, Magical::Unicorns - # - # Middlewares can also be completely swapped out and replaced with others: - # - # config.middleware.swap ActionDispatch::Flash, Magical::Unicorns - # - # And finally they can also be removed from the stack completely: - # - # config.middleware.delete ActionDispatch::Flash - # - class MiddlewareStackProxy - def initialize(operations = [], delete_operations = []) - @operations = operations - @delete_operations = delete_operations - end - - def insert_before(*args, &block) - @operations << [__method__, args, block] - end - - alias :insert :insert_before - - def insert_after(*args, &block) - @operations << [__method__, args, block] - end - - def swap(*args, &block) - @operations << [__method__, args, block] - end - - def use(*args, &block) - @operations << [__method__, args, block] - end - - def delete(*args, &block) - @delete_operations << [__method__, args, block] - end - - def unshift(*args, &block) - @operations << [__method__, args, block] - end - - def merge_into(other) #:nodoc: - (@operations + @delete_operations).each do |operation, args, block| - other.send(operation, *args, &block) - end - - other - end - - def +(other) # :nodoc: - MiddlewareStackProxy.new(@operations + other.operations, @delete_operations + other.delete_operations) - end - - protected - def operations - @operations - end - - def delete_operations - @delete_operations - end - end - - class Generators #:nodoc: - attr_accessor :aliases, :options, :templates, :fallbacks, :colorize_logging, :api_only - attr_reader :hidden_namespaces - - def initialize - @aliases = Hash.new { |h, k| h[k] = {} } - @options = Hash.new { |h, k| h[k] = {} } - @fallbacks = {} - @templates = [] - @colorize_logging = true - @api_only = false - @hidden_namespaces = [] - end - - def initialize_copy(source) - @aliases = @aliases.deep_dup - @options = @options.deep_dup - @fallbacks = @fallbacks.deep_dup - @templates = @templates.dup - end - - def hide_namespace(namespace) - @hidden_namespaces << namespace - end - - def method_missing(method, *args) - method = method.to_s.sub(/=$/, "").to_sym - - return @options[method] if args.empty? - - if method == :rails || args.first.is_a?(Hash) - namespace, configuration = method, args.shift - else - namespace, configuration = args.shift, args.shift - namespace = namespace.to_sym if namespace.respond_to?(:to_sym) - @options[:rails][method] = namespace - end - - if configuration - aliases = configuration.delete(:aliases) - @aliases[namespace].merge!(aliases) if aliases - @options[namespace].merge!(configuration) - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/console/app.rb b/debian/gems-compat/railties-5.1.7/lib/rails/console/app.rb deleted file mode 100644 index affadc8e09..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/console/app.rb +++ /dev/null @@ -1,36 +0,0 @@ -require "active_support/all" -require "action_controller" - -module Rails - module ConsoleMethods - # reference the global "app" instance, created on demand. To recreate the - # instance, pass a non-false value as the parameter. - def app(create = false) - @app_integration_instance = nil if create - @app_integration_instance ||= new_session do |sess| - sess.host! "www.example.com" - end - end - - # create a new session. If a block is given, the new session will be yielded - # to the block before being returned. - def new_session - app = Rails.application - session = ActionDispatch::Integration::Session.new(app) - yield session if block_given? - - # This makes app.url_for and app.foo_path available in the console - session.extend(app.routes.url_helpers) - session.extend(app.routes.mounted_helpers) - - session - end - - # reloads the environment - def reload!(print = true) - puts "Reloading..." if print - Rails.application.reloader.reload! - true - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/console/helpers.rb b/debian/gems-compat/railties-5.1.7/lib/rails/console/helpers.rb deleted file mode 100644 index a33f71dc5b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/console/helpers.rb +++ /dev/null @@ -1,17 +0,0 @@ -module Rails - module ConsoleMethods - # Gets the helper methods available to the controller. - # - # This method assumes an +ApplicationController+ exists, and it extends +ActionController::Base+ - def helper - ApplicationController.helpers - end - - # Gets a new instance of a controller object. - # - # This method assumes an +ApplicationController+ exists, and it extends +ActionController::Base+ - def controller - @controller ||= ApplicationController.new - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/dev_caching.rb b/debian/gems-compat/railties-5.1.7/lib/rails/dev_caching.rb deleted file mode 100644 index f69275a34a..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/dev_caching.rb +++ /dev/null @@ -1,43 +0,0 @@ -require "fileutils" - -module Rails - module DevCaching # :nodoc: - class << self - FILE = "tmp/caching-dev.txt" - - def enable_by_file - FileUtils.mkdir_p("tmp") - - if File.exist?(FILE) - delete_cache_file - puts "Development mode is no longer being cached." - else - create_cache_file - puts "Development mode is now being cached." - end - - FileUtils.touch "tmp/restart.txt" - FileUtils.rm_f("tmp/pids/server.pid") - end - - def enable_by_argument(caching) - FileUtils.mkdir_p("tmp") - - if caching - create_cache_file - elsif caching == false && File.exist?(FILE) - delete_cache_file - end - end - - private - def create_cache_file - FileUtils.touch FILE - end - - def delete_cache_file - File.delete FILE - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/engine.rb b/debian/gems-compat/railties-5.1.7/lib/rails/engine.rb deleted file mode 100644 index dc0b158bd4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/engine.rb +++ /dev/null @@ -1,703 +0,0 @@ -require "rails/railtie" -require "rails/engine/railties" -require "active_support/core_ext/module/delegation" -require "pathname" -require "thread" - -module Rails - # Rails::Engine allows you to wrap a specific Rails application or subset of - # functionality and share it with other applications or within a larger packaged application. - # Every Rails::Application is just an engine, which allows for simple - # feature and application sharing. - # - # Any Rails::Engine is also a Rails::Railtie, so the same - # methods (like rake_tasks and +generators+) and configuration - # options that are available in railties can also be used in engines. - # - # == Creating an Engine - # - # If you want a gem to behave as an engine, you have to specify an +Engine+ - # for it somewhere inside your plugin's +lib+ folder (similar to how we - # specify a +Railtie+): - # - # # lib/my_engine.rb - # module MyEngine - # class Engine < Rails::Engine - # end - # end - # - # Then ensure that this file is loaded at the top of your config/application.rb - # (or in your +Gemfile+) and it will automatically load models, controllers and helpers - # inside +app+, load routes at config/routes.rb, load locales at - # config/locales/*, and load tasks at lib/tasks/*. - # - # == Configuration - # - # Besides the +Railtie+ configuration which is shared across the application, in a - # Rails::Engine you can access autoload_paths, eager_load_paths - # and autoload_once_paths, which, differently from a Railtie, are scoped to - # the current engine. - # - # class MyEngine < Rails::Engine - # # Add a load path for this specific Engine - # config.autoload_paths << File.expand_path("../lib/some/path", __FILE__) - # - # initializer "my_engine.add_middleware" do |app| - # app.middleware.use MyEngine::Middleware - # end - # end - # - # == Generators - # - # You can set up generators for engines with config.generators method: - # - # class MyEngine < Rails::Engine - # config.generators do |g| - # g.orm :active_record - # g.template_engine :erb - # g.test_framework :test_unit - # end - # end - # - # You can also set generators for an application by using config.app_generators: - # - # class MyEngine < Rails::Engine - # # note that you can also pass block to app_generators in the same way you - # # can pass it to generators method - # config.app_generators.orm :datamapper - # end - # - # == Paths - # - # Applications and engines have flexible path configuration, meaning that you - # are not required to place your controllers at app/controllers, but - # in any place which you find convenient. - # - # For example, let's suppose you want to place your controllers in lib/controllers. - # You can set that as an option: - # - # class MyEngine < Rails::Engine - # paths["app/controllers"] = "lib/controllers" - # end - # - # You can also have your controllers loaded from both app/controllers and - # lib/controllers: - # - # class MyEngine < Rails::Engine - # paths["app/controllers"] << "lib/controllers" - # end - # - # The available paths in an engine are: - # - # class MyEngine < Rails::Engine - # paths["app"] # => ["app"] - # paths["app/controllers"] # => ["app/controllers"] - # paths["app/helpers"] # => ["app/helpers"] - # paths["app/models"] # => ["app/models"] - # paths["app/views"] # => ["app/views"] - # paths["lib"] # => ["lib"] - # paths["lib/tasks"] # => ["lib/tasks"] - # paths["config"] # => ["config"] - # paths["config/initializers"] # => ["config/initializers"] - # paths["config/locales"] # => ["config/locales"] - # paths["config/routes.rb"] # => ["config/routes.rb"] - # end - # - # The Application class adds a couple more paths to this set. And as in your - # Application, all folders under +app+ are automatically added to the load path. - # If you have an app/services folder for example, it will be added by default. - # - # == Endpoint - # - # An engine can also be a Rack application. It can be useful if you have a Rack application that - # you would like to wrap with +Engine+ and provide with some of the +Engine+'s features. - # - # To do that, use the +endpoint+ method: - # - # module MyEngine - # class Engine < Rails::Engine - # endpoint MyRackApplication - # end - # end - # - # Now you can mount your engine in application's routes just like that: - # - # Rails.application.routes.draw do - # mount MyEngine::Engine => "/engine" - # end - # - # == Middleware stack - # - # As an engine can now be a Rack endpoint, it can also have a middleware - # stack. The usage is exactly the same as in Application: - # - # module MyEngine - # class Engine < Rails::Engine - # middleware.use SomeMiddleware - # end - # end - # - # == Routes - # - # If you don't specify an endpoint, routes will be used as the default - # endpoint. You can use them just like you use an application's routes: - # - # # ENGINE/config/routes.rb - # MyEngine::Engine.routes.draw do - # get "/" => "posts#index" - # end - # - # == Mount priority - # - # Note that now there can be more than one router in your application, and it's better to avoid - # passing requests through many routers. Consider this situation: - # - # Rails.application.routes.draw do - # mount MyEngine::Engine => "/blog" - # get "/blog/omg" => "main#omg" - # end - # - # +MyEngine+ is mounted at /blog, and /blog/omg points to application's - # controller. In such a situation, requests to /blog/omg will go through +MyEngine+, - # and if there is no such route in +Engine+'s routes, it will be dispatched to main#omg. - # It's much better to swap that: - # - # Rails.application.routes.draw do - # get "/blog/omg" => "main#omg" - # mount MyEngine::Engine => "/blog" - # end - # - # Now, +Engine+ will get only requests that were not handled by +Application+. - # - # == Engine name - # - # There are some places where an Engine's name is used: - # - # * routes: when you mount an Engine with mount(MyEngine::Engine => '/my_engine'), - # it's used as default :as option - # * rake task for installing migrations my_engine:install:migrations - # - # Engine name is set by default based on class name. For MyEngine::Engine it will be - # my_engine_engine. You can change it manually using the engine_name method: - # - # module MyEngine - # class Engine < Rails::Engine - # engine_name "my_engine" - # end - # end - # - # == Isolated Engine - # - # Normally when you create controllers, helpers and models inside an engine, they are treated - # as if they were created inside the application itself. This means that all helpers and - # named routes from the application will be available to your engine's controllers as well. - # - # However, sometimes you want to isolate your engine from the application, especially if your engine - # has its own router. To do that, you simply need to call +isolate_namespace+. This method requires - # you to pass a module where all your controllers, helpers and models should be nested to: - # - # module MyEngine - # class Engine < Rails::Engine - # isolate_namespace MyEngine - # end - # end - # - # With such an engine, everything that is inside the +MyEngine+ module will be isolated from - # the application. - # - # Consider this controller: - # - # module MyEngine - # class FooController < ActionController::Base - # end - # end - # - # If the +MyEngine+ engine is marked as isolated, +FooController+ only has - # access to helpers from +MyEngine+, and url_helpers from - # MyEngine::Engine.routes. - # - # The next thing that changes in isolated engines is the behavior of routes. - # Normally, when you namespace your controllers, you also need to namespace - # the related routes. With an isolated engine, the engine's namespace is - # automatically applied, so you don't need to specify it explicitly in your - # routes: - # - # MyEngine::Engine.routes.draw do - # resources :articles - # end - # - # If +MyEngine+ is isolated, The routes above will point to - # MyEngine::ArticlesController. You also don't need to use longer - # url helpers like +my_engine_articles_path+. Instead, you should simply use - # +articles_path+, like you would do with your main application. - # - # To make this behavior consistent with other parts of the framework, - # isolated engines also have an effect on ActiveModel::Naming. In a - # normal Rails app, when you use a namespaced model such as - # Namespace::Article, ActiveModel::Naming will generate - # names with the prefix "namespace". In an isolated engine, the prefix will - # be omitted in url helpers and form fields, for convenience. - # - # polymorphic_url(MyEngine::Article.new) - # # => "articles_path" # not "my_engine_articles_path" - # - # form_for(MyEngine::Article.new) do - # text_field :title # => - # end - # - # Additionally, an isolated engine will set its own name according to its - # namespace, so MyEngine::Engine.engine_name will return - # "my_engine". It will also set +MyEngine.table_name_prefix+ to "my_engine_", - # meaning for example that MyEngine::Article will use the - # +my_engine_articles+ database table by default. - # - # == Using Engine's routes outside Engine - # - # Since you can now mount an engine inside application's routes, you do not have direct access to +Engine+'s - # url_helpers inside +Application+. When you mount an engine in an application's routes, a special helper is - # created to allow you to do that. Consider such a scenario: - # - # # config/routes.rb - # Rails.application.routes.draw do - # mount MyEngine::Engine => "/my_engine", as: "my_engine" - # get "/foo" => "foo#index" - # end - # - # Now, you can use the my_engine helper inside your application: - # - # class FooController < ApplicationController - # def index - # my_engine.root_url # => /my_engine/ - # end - # end - # - # There is also a main_app helper that gives you access to application's routes inside Engine: - # - # module MyEngine - # class BarController - # def index - # main_app.foo_path # => /foo - # end - # end - # end - # - # Note that the :as option given to mount takes the engine_name as default, so most of the time - # you can simply omit it. - # - # Finally, if you want to generate a url to an engine's route using - # polymorphic_url, you also need to pass the engine helper. Let's - # say that you want to create a form pointing to one of the engine's routes. - # All you need to do is pass the helper as the first element in array with - # attributes for url: - # - # form_for([my_engine, @user]) - # - # This code will use my_engine.user_path(@user) to generate the proper route. - # - # == Isolated engine's helpers - # - # Sometimes you may want to isolate engine, but use helpers that are defined for it. - # If you want to share just a few specific helpers you can add them to application's - # helpers in ApplicationController: - # - # class ApplicationController < ActionController::Base - # helper MyEngine::SharedEngineHelper - # end - # - # If you want to include all of the engine's helpers, you can use the #helper method on an engine's - # instance: - # - # class ApplicationController < ActionController::Base - # helper MyEngine::Engine.helpers - # end - # - # It will include all of the helpers from engine's directory. Take into account that this does - # not include helpers defined in controllers with helper_method or other similar solutions, - # only helpers defined in the helpers directory will be included. - # - # == Migrations & seed data - # - # Engines can have their own migrations. The default path for migrations is exactly the same - # as in application: db/migrate - # - # To use engine's migrations in application you can use the rake task below, which copies them to - # application's dir: - # - # rake ENGINE_NAME:install:migrations - # - # Note that some of the migrations may be skipped if a migration with the same name already exists - # in application. In such a situation you must decide whether to leave that migration or rename the - # migration in the application and rerun copying migrations. - # - # If your engine has migrations, you may also want to prepare data for the database in - # the db/seeds.rb file. You can load that data using the load_seed method, e.g. - # - # MyEngine::Engine.load_seed - # - # == Loading priority - # - # In order to change engine's priority you can use +config.railties_order+ in the main application. - # It will affect the priority of loading views, helpers, assets, and all the other files - # related to engine or application. - # - # # load Blog::Engine with highest priority, followed by application and other railties - # config.railties_order = [Blog::Engine, :main_app, :all] - class Engine < Railtie - autoload :Configuration, "rails/engine/configuration" - - class << self - attr_accessor :called_from, :isolated - - alias :isolated? :isolated - alias :engine_name :railtie_name - - delegate :eager_load!, to: :instance - - def inherited(base) - unless base.abstract_railtie? - Rails::Railtie::Configuration.eager_load_namespaces << base - - base.called_from = begin - call_stack = caller_locations.map { |l| l.absolute_path || l.path } - - File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] }) - end - end - - super - end - - def find_root(from) - find_root_with_flag "lib", from - end - - def endpoint(endpoint = nil) - @endpoint ||= nil - @endpoint = endpoint if endpoint - @endpoint - end - - def isolate_namespace(mod) - engine_name(generate_railtie_name(mod.name)) - - routes.default_scope = { module: ActiveSupport::Inflector.underscore(mod.name) } - self.isolated = true - - unless mod.respond_to?(:railtie_namespace) - name, railtie = engine_name, self - - mod.singleton_class.instance_eval do - define_method(:railtie_namespace) { railtie } - - unless mod.respond_to?(:table_name_prefix) - define_method(:table_name_prefix) { "#{name}_" } - end - - unless mod.respond_to?(:use_relative_model_naming?) - class_eval "def use_relative_model_naming?; true; end", __FILE__, __LINE__ - end - - unless mod.respond_to?(:railtie_helpers_paths) - define_method(:railtie_helpers_paths) { railtie.helpers_paths } - end - - unless mod.respond_to?(:railtie_routes_url_helpers) - define_method(:railtie_routes_url_helpers) { |include_path_helpers = true| railtie.routes.url_helpers(include_path_helpers) } - end - end - end - end - - # Finds engine with given path. - def find(path) - expanded_path = File.expand_path path - Rails::Engine.subclasses.each do |klass| - engine = klass.instance - return engine if File.expand_path(engine.root) == expanded_path - end - nil - end - end - - delegate :middleware, :root, :paths, to: :config - delegate :engine_name, :isolated?, to: :class - - def initialize - @_all_autoload_paths = nil - @_all_load_paths = nil - @app = nil - @config = nil - @env_config = nil - @helpers = nil - @routes = nil - @app_build_lock = Mutex.new - super - end - - # Load console and invoke the registered hooks. - # Check Rails::Railtie.console for more info. - def load_console(app = self) - require "rails/console/app" - require "rails/console/helpers" - run_console_blocks(app) - self - end - - # Load Rails runner and invoke the registered hooks. - # Check Rails::Railtie.runner for more info. - def load_runner(app = self) - run_runner_blocks(app) - self - end - - # Load Rake, railties tasks and invoke the registered hooks. - # Check Rails::Railtie.rake_tasks for more info. - def load_tasks(app = self) - require "rake" - run_tasks_blocks(app) - self - end - - # Load Rails generators and invoke the registered hooks. - # Check Rails::Railtie.generators for more info. - def load_generators(app = self) - require "rails/generators" - run_generators_blocks(app) - Rails::Generators.configure!(app.config.generators) - self - end - - # Eager load the application by loading all ruby - # files inside eager_load paths. - def eager_load! - config.eager_load_paths.each do |load_path| - matcher = /\A#{Regexp.escape(load_path.to_s)}\/(.*)\.rb\Z/ - Dir.glob("#{load_path}/**/*.rb").sort.each do |file| - require_dependency file.sub(matcher, '\1') - end - end - end - - def railties - @railties ||= Railties.new - end - - # Returns a module with all the helpers defined for the engine. - def helpers - @helpers ||= begin - helpers = Module.new - all = ActionController::Base.all_helpers_from_path(helpers_paths) - ActionController::Base.modules_for_helpers(all).each do |mod| - helpers.include(mod) - end - helpers - end - end - - # Returns all registered helpers paths. - def helpers_paths - paths["app/helpers"].existent - end - - # Returns the underlying Rack application for this engine. - def app - @app || @app_build_lock.synchronize { - @app ||= begin - stack = default_middleware_stack - config.middleware = build_middleware.merge_into(stack) - config.middleware.build(endpoint) - end - } - end - - # Returns the endpoint for this engine. If none is registered, - # defaults to an ActionDispatch::Routing::RouteSet. - def endpoint - self.class.endpoint || routes - end - - # Define the Rack API for this engine. - def call(env) - req = build_request env - app.call req.env - end - - # Defines additional Rack env configuration that is added on each call. - def env_config - @env_config ||= {} - end - - # Defines the routes for this engine. If a block is given to - # routes, it is appended to the engine. - def routes - @routes ||= ActionDispatch::Routing::RouteSet.new_with_config(config) - @routes.append(&Proc.new) if block_given? - @routes - end - - # Define the configuration object for the engine. - def config - @config ||= Engine::Configuration.new(self.class.find_root(self.class.called_from)) - end - - # Load data from db/seeds.rb file. It can be used in to load engines' - # seeds, e.g.: - # - # Blog::Engine.load_seed - def load_seed - seed_file = paths["db/seeds.rb"].existent.first - load(seed_file) if seed_file - end - - # Add configured load paths to Ruby's load path, and remove duplicate entries. - initializer :set_load_path, before: :bootstrap_hook do - _all_load_paths.reverse_each do |path| - $LOAD_PATH.unshift(path) if File.directory?(path) - end - $LOAD_PATH.uniq! - end - - # Set the paths from which Rails will automatically load source files, - # and the load_once paths. - # - # This needs to be an initializer, since it needs to run once - # per engine and get the engine as a block parameter. - initializer :set_autoload_paths, before: :bootstrap_hook do - ActiveSupport::Dependencies.autoload_paths.unshift(*_all_autoload_paths) - ActiveSupport::Dependencies.autoload_once_paths.unshift(*_all_autoload_once_paths) - - # Freeze so future modifications will fail rather than do nothing mysteriously - config.autoload_paths.freeze - config.eager_load_paths.freeze - config.autoload_once_paths.freeze - end - - initializer :add_routing_paths do |app| - routing_paths = paths["config/routes.rb"].existent - - if routes? || routing_paths.any? - app.routes_reloader.paths.unshift(*routing_paths) - app.routes_reloader.route_sets << routes - end - end - - # I18n load paths are a special case since the ones added - # later have higher priority. - initializer :add_locales do - config.i18n.railties_load_path << paths["config/locales"] - end - - initializer :add_view_paths do - views = paths["app/views"].existent - unless views.empty? - ActiveSupport.on_load(:action_controller) { prepend_view_path(views) if respond_to?(:prepend_view_path) } - ActiveSupport.on_load(:action_mailer) { prepend_view_path(views) } - end - end - - initializer :load_environment_config, before: :load_environment_hook, group: :all do - paths["config/environments"].existent.each do |environment| - require environment - end - end - - initializer :prepend_helpers_path do |app| - if !isolated? || (app == self) - app.config.helpers_paths.unshift(*paths["app/helpers"].existent) - end - end - - initializer :load_config_initializers do - config.paths["config/initializers"].existent.sort.each do |initializer| - load_config_initializer(initializer) - end - end - - initializer :engines_blank_point do - # We need this initializer so all extra initializers added in engines are - # consistently executed after all the initializers above across all engines. - end - - rake_tasks do - next if is_a?(Rails::Application) - next unless has_migrations? - - namespace railtie_name do - namespace :install do - desc "Copy migrations from #{railtie_name} to application" - task :migrations do - ENV["FROM"] = railtie_name - if Rake::Task.task_defined?("railties:install:migrations") - Rake::Task["railties:install:migrations"].invoke - else - Rake::Task["app:railties:install:migrations"].invoke - end - end - end - end - end - - def routes? #:nodoc: - @routes - end - - protected - - def run_tasks_blocks(*) #:nodoc: - super - paths["lib/tasks"].existent.sort.each { |ext| load(ext) } - end - - private - - def load_config_initializer(initializer) # :doc: - ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do - load(initializer) - end - end - - def has_migrations? - paths["db/migrate"].existent.any? - end - - def self.find_root_with_flag(flag, root_path, default = nil) #:nodoc: - while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") - parent = File.dirname(root_path) - root_path = parent != root_path && parent - end - - root = File.exist?("#{root_path}/#{flag}") ? root_path : default - raise "Could not find root path for #{self}" unless root - - Pathname.new File.realpath root - end - - def default_middleware_stack - ActionDispatch::MiddlewareStack.new - end - - def _all_autoload_once_paths - config.autoload_once_paths - end - - def _all_autoload_paths - @_all_autoload_paths ||= (config.autoload_paths + config.eager_load_paths + config.autoload_once_paths).uniq - end - - def _all_load_paths - @_all_load_paths ||= (config.paths.load_paths + _all_autoload_paths).uniq - end - - def build_request(env) - env.merge!(env_config) - req = ActionDispatch::Request.new env - req.routes = routes - req.engine_script_name = req.script_name - req - end - - def build_middleware - config.middleware - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/engine/commands.rb b/debian/gems-compat/railties-5.1.7/lib/rails/engine/commands.rb deleted file mode 100644 index b9ef63243a..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/engine/commands.rb +++ /dev/null @@ -1,7 +0,0 @@ -unless defined?(APP_PATH) - if File.exist?(File.expand_path("test/dummy/config/application.rb", ENGINE_ROOT)) - APP_PATH = File.expand_path("test/dummy/config/application", ENGINE_ROOT) - end -end - -require "rails/commands" diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/engine/configuration.rb b/debian/gems-compat/railties-5.1.7/lib/rails/engine/configuration.rb deleted file mode 100644 index 0c40173c38..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/engine/configuration.rb +++ /dev/null @@ -1,86 +0,0 @@ -require "rails/railtie/configuration" - -module Rails - class Engine - class Configuration < ::Rails::Railtie::Configuration - attr_reader :root - attr_accessor :middleware - attr_writer :eager_load_paths, :autoload_once_paths, :autoload_paths - - def initialize(root = nil) - super() - @root = root - @generators = app_generators.dup - @middleware = Rails::Configuration::MiddlewareStackProxy.new - end - - # Holds generators configuration: - # - # config.generators do |g| - # g.orm :data_mapper, migration: true - # g.template_engine :haml - # g.test_framework :rspec - # end - # - # If you want to disable color in console, do: - # - # config.generators.colorize_logging = false - # - def generators - @generators ||= Rails::Configuration::Generators.new - yield(@generators) if block_given? - @generators - end - - def paths - @paths ||= begin - paths = Rails::Paths::Root.new(@root) - - paths.add "app", eager_load: true, glob: "{*,*/concerns}" - paths.add "app/assets", glob: "*" - paths.add "app/controllers", eager_load: true - paths.add "app/channels", eager_load: true, glob: "**/*_channel.rb" - paths.add "app/helpers", eager_load: true - paths.add "app/models", eager_load: true - paths.add "app/mailers", eager_load: true - paths.add "app/views" - - paths.add "lib", load_path: true - paths.add "lib/assets", glob: "*" - paths.add "lib/tasks", glob: "**/*.rake" - - paths.add "config" - paths.add "config/environments", glob: "#{Rails.env}.rb" - paths.add "config/initializers", glob: "**/*.rb" - paths.add "config/locales", glob: "*.{rb,yml}" - paths.add "config/routes.rb" - - paths.add "db" - paths.add "db/migrate" - paths.add "db/seeds.rb" - - paths.add "vendor", load_path: true - paths.add "vendor/assets", glob: "*" - - paths - end - end - - def root=(value) - @root = paths.path = Pathname.new(value).expand_path - end - - def eager_load_paths - @eager_load_paths ||= paths.eager_load - end - - def autoload_once_paths - @autoload_once_paths ||= paths.autoload_once - end - - def autoload_paths - @autoload_paths ||= paths.autoload_paths - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/engine/railties.rb b/debian/gems-compat/railties-5.1.7/lib/rails/engine/railties.rb deleted file mode 100644 index 9969a1475d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/engine/railties.rb +++ /dev/null @@ -1,21 +0,0 @@ -module Rails - class Engine < Railtie - class Railties - include Enumerable - attr_reader :_all - - def initialize - @_all ||= ::Rails::Railtie.subclasses.map(&:instance) + - ::Rails::Engine.subclasses.map(&:instance) - end - - def each(*args, &block) - _all.each(*args, &block) - end - - def -(others) - _all - others - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/engine/updater.rb b/debian/gems-compat/railties-5.1.7/lib/rails/engine/updater.rb deleted file mode 100644 index 2ecf994a5c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/engine/updater.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "rails/generators" -require "rails/generators/rails/plugin/plugin_generator" - -module Rails - class Engine - class Updater - class << self - def generator - @generator ||= Rails::Generators::PluginGenerator.new ["plugin"], - { engine: true }, destination_root: ENGINE_ROOT - end - - def run(action) - generator.send(action) - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/gem_version.rb b/debian/gems-compat/railties-5.1.7/lib/rails/gem_version.rb deleted file mode 100644 index e5d65847f7..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/gem_version.rb +++ /dev/null @@ -1,15 +0,0 @@ -module Rails - # Returns the version of the currently loaded Rails as a Gem::Version - def self.gem_version - Gem::Version.new VERSION::STRING - end - - module VERSION - MAJOR = 5 - MINOR = 1 - TINY = 7 - PRE = nil - - STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators.rb deleted file mode 100644 index 8ec805370b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators.rb +++ /dev/null @@ -1,316 +0,0 @@ -activesupport_path = File.expand_path("../../../../activesupport/lib", __FILE__) -$:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.include?(activesupport_path) - -require "thor/group" -require "rails/command" - -require "active_support" -require "active_support/core_ext/object/blank" -require "active_support/core_ext/kernel/singleton_class" -require "active_support/core_ext/array/extract_options" -require "active_support/core_ext/hash/deep_merge" -require "active_support/core_ext/module/attribute_accessors" -require "active_support/core_ext/string/inflections" - -module Rails - module Generators - include Rails::Command::Behavior - - autoload :Actions, "rails/generators/actions" - autoload :ActiveModel, "rails/generators/active_model" - autoload :Base, "rails/generators/base" - autoload :Migration, "rails/generators/migration" - autoload :NamedBase, "rails/generators/named_base" - autoload :ResourceHelpers, "rails/generators/resource_helpers" - autoload :TestCase, "rails/generators/test_case" - - mattr_accessor :namespace - - DEFAULT_ALIASES = { - rails: { - actions: "-a", - orm: "-o", - javascripts: "-j", - javascript_engine: "-je", - resource_controller: "-c", - scaffold_controller: "-c", - stylesheets: "-y", - stylesheet_engine: "-se", - scaffold_stylesheet: "-ss", - template_engine: "-e", - test_framework: "-t" - }, - - test_unit: { - fixture_replacement: "-r", - } - } - - DEFAULT_OPTIONS = { - rails: { - api: false, - assets: true, - force_plural: false, - helper: true, - integration_tool: nil, - javascripts: true, - javascript_engine: :js, - orm: false, - resource_controller: :controller, - resource_route: true, - scaffold_controller: :scaffold_controller, - stylesheets: true, - stylesheet_engine: :css, - scaffold_stylesheet: true, - system_tests: nil, - test_framework: nil, - template_engine: :erb - } - } - - class << self - def configure!(config) #:nodoc: - api_only! if config.api_only - no_color! unless config.colorize_logging - aliases.deep_merge! config.aliases - options.deep_merge! config.options - fallbacks.merge! config.fallbacks - templates_path.concat config.templates - templates_path.uniq! - hide_namespaces(*config.hidden_namespaces) - end - - def templates_path #:nodoc: - @templates_path ||= [] - end - - def aliases #:nodoc: - @aliases ||= DEFAULT_ALIASES.dup - end - - def options #:nodoc: - @options ||= DEFAULT_OPTIONS.dup - end - - # Hold configured generators fallbacks. If a plugin developer wants a - # generator group to fallback to another group in case of missing generators, - # they can add a fallback. - # - # For example, shoulda is considered a test_framework and is an extension - # of test_unit. However, most part of shoulda generators are similar to - # test_unit ones. - # - # Shoulda then can tell generators to search for test_unit generators when - # some of them are not available by adding a fallback: - # - # Rails::Generators.fallbacks[:shoulda] = :test_unit - def fallbacks - @fallbacks ||= {} - end - - # Configure generators for API only applications. It basically hides - # everything that is usually browser related, such as assets and session - # migration generators, and completely disable helpers and assets - # so generators such as scaffold won't create them. - def api_only! - hide_namespaces "assets", "helper", "css", "js" - - options[:rails].merge!( - api: true, - assets: false, - helper: false, - template_engine: nil - ) - - if ARGV.first == "mailer" - options[:rails].merge!(template_engine: :erb) - end - end - - # Remove the color from output. - def no_color! - Thor::Base.shell = Thor::Shell::Basic - end - - # Returns an array of generator namespaces that are hidden. - # Generator namespaces may be hidden for a variety of reasons. - # Some are aliased such as "rails:migration" and can be - # invoked with the shorter "migration", others are private to other generators - # such as "css:scaffold". - def hidden_namespaces - @hidden_namespaces ||= begin - orm = options[:rails][:orm] - test = options[:rails][:test_framework] - template = options[:rails][:template_engine] - css = options[:rails][:stylesheet_engine] - - [ - "rails", - "resource_route", - "#{orm}:migration", - "#{orm}:model", - "#{test}:controller", - "#{test}:helper", - "#{test}:integration", - "#{test}:system", - "#{test}:mailer", - "#{test}:model", - "#{test}:scaffold", - "#{test}:view", - "#{test}:job", - "#{template}:controller", - "#{template}:scaffold", - "#{template}:mailer", - "#{css}:scaffold", - "#{css}:assets", - "css:assets", - "css:scaffold" - ] - end - end - - def hide_namespaces(*namespaces) - hidden_namespaces.concat(namespaces) - end - alias hide_namespace hide_namespaces - - # Show help message with available generators. - def help(command = "generate") - puts "Usage: rails #{command} GENERATOR [args] [options]" - puts - puts "General options:" - puts " -h, [--help] # Print generator's options and usage" - puts " -p, [--pretend] # Run but do not make any changes" - puts " -f, [--force] # Overwrite files that already exist" - puts " -s, [--skip] # Skip files that already exist" - puts " -q, [--quiet] # Suppress status output" - puts - puts "Please choose a generator below." - puts - - print_generators - end - - def public_namespaces - lookup! - subclasses.map(&:namespace) - end - - def print_generators - sorted_groups.each { |b, n| print_list(b, n) } - end - - def sorted_groups - namespaces = public_namespaces - namespaces.sort! - - groups = Hash.new { |h, k| h[k] = [] } - namespaces.each do |namespace| - base = namespace.split(":").first - groups[base] << namespace - end - - rails = groups.delete("rails") - rails.map! { |n| n.sub(/^rails:/, "") } - rails.delete("app") - rails.delete("plugin") - rails.delete("encrypted_secrets") - - hidden_namespaces.each { |n| groups.delete(n.to_s) } - - [[ "rails", rails ]] + groups.sort.to_a - end - - # Rails finds namespaces similar to Thor, it only adds one rule: - # - # Generators names must end with "_generator.rb". This is required because Rails - # looks in load paths and loads the generator just before it's going to be used. - # - # find_by_namespace :webrat, :rails, :integration - # - # Will search for the following generators: - # - # "rails:webrat", "webrat:integration", "webrat" - # - # Notice that "rails:generators:webrat" could be loaded as well, what - # Rails looks for is the first and last parts of the namespace. - def find_by_namespace(name, base = nil, context = nil) #:nodoc: - lookups = [] - lookups << "#{base}:#{name}" if base - lookups << "#{name}:#{context}" if context - - unless base || context - unless name.to_s.include?(?:) - lookups << "#{name}:#{name}" - lookups << "rails:#{name}" - end - lookups << "#{name}" - end - - lookup(lookups) - - namespaces = Hash[subclasses.map { |klass| [klass.namespace, klass] }] - lookups.each do |namespace| - - klass = namespaces[namespace] - return klass if klass - end - - invoke_fallbacks_for(name, base) || invoke_fallbacks_for(context, name) - end - - # Receives a namespace, arguments and the behavior to invoke the generator. - # It's used as the default entry point for generate, destroy and update - # commands. - def invoke(namespace, args = ARGV, config = {}) - names = namespace.to_s.split(":") - if klass = find_by_namespace(names.pop, names.any? && names.join(":")) - args << "--help" if args.empty? && klass.arguments.any?(&:required?) - klass.start(args, config) - else - options = sorted_groups.flat_map(&:last) - suggestions = options.sort_by { |suggested| levenshtein_distance(namespace.to_s, suggested) }.first(3) - msg = "Could not find generator '#{namespace}'. " - msg << "Maybe you meant #{ suggestions.map { |s| "'#{s}'" }.to_sentence(last_word_connector: " or ", locale: :en) }\n" - msg << "Run `rails generate --help` for more options." - puts msg - end - end - - private - - def print_list(base, namespaces) # :doc: - namespaces = namespaces.reject { |n| hidden_namespaces.include?(n) } - super - end - - # Try fallbacks for the given base. - def invoke_fallbacks_for(name, base) - return nil unless base && fallbacks[base.to_sym] - invoked_fallbacks = [] - - Array(fallbacks[base.to_sym]).each do |fallback| - next if invoked_fallbacks.include?(fallback) - invoked_fallbacks << fallback - - klass = find_by_namespace(name, fallback) - return klass if klass - end - - nil - end - - def command_type # :doc: - @command_type ||= "generator" - end - - def lookup_paths # :doc: - @lookup_paths ||= %w( rails/generators generators ) - end - - def file_lookup_paths # :doc: - @file_lookup_paths ||= [ "{#{lookup_paths.join(',')}}", "**", "*_generator.rb" ] - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/actions.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/actions.rb deleted file mode 100644 index 0bd0615b7e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/actions.rb +++ /dev/null @@ -1,308 +0,0 @@ -module Rails - module Generators - module Actions - def initialize(*) # :nodoc: - super - @in_group = nil - @after_bundle_callbacks = [] - end - - # Adds an entry into +Gemfile+ for the supplied gem. - # - # gem "rspec", group: :test - # gem "technoweenie-restful-authentication", lib: "restful-authentication", source: "http://gems.github.com/" - # gem "rails", "3.0", git: "git://github.com/rails/rails" - def gem(*args) - options = args.extract_options! - name, version = args - - # Set the message to be shown in logs. Uses the git repo if one is given, - # otherwise use name (version). - parts, message = [ quote(name) ], name.dup - if version ||= options.delete(:version) - parts << quote(version) - message << " (#{version})" - end - message = options[:git] if options[:git] - - log :gemfile, message - - options.each do |option, value| - parts << "#{option}: #{quote(value)}" - end - - in_root do - str = "gem #{parts.join(", ")}" - str = " " + str if @in_group - str = "\n" + str - append_file "Gemfile", str, verbose: false - end - end - - # Wraps gem entries inside a group. - # - # gem_group :development, :test do - # gem "rspec-rails" - # end - def gem_group(*names, &block) - name = names.map(&:inspect).join(", ") - log :gemfile, "group #{name}" - - in_root do - append_file "Gemfile", "\ngroup #{name} do", force: true - - @in_group = true - instance_eval(&block) - @in_group = false - - append_file "Gemfile", "\nend\n", force: true - end - end - - # Add the given source to +Gemfile+ - # - # If block is given, gem entries in block are wrapped into the source group. - # - # add_source "http://gems.github.com/" - # - # add_source "http://gems.github.com/" do - # gem "rspec-rails" - # end - def add_source(source, options = {}, &block) - log :source, source - - in_root do - if block - append_file "Gemfile", "\nsource #{quote(source)} do", force: true - @in_group = true - instance_eval(&block) - @in_group = false - append_file "Gemfile", "\nend\n", force: true - else - prepend_file "Gemfile", "source #{quote(source)}\n", verbose: false - end - end - end - - # Adds a line inside the Application class for config/application.rb. - # - # If options :env is specified, the line is appended to the corresponding - # file in config/environments. - # - # environment do - # "config.action_controller.asset_host = 'cdn.provider.com'" - # end - # - # environment(nil, env: "development") do - # "config.action_controller.asset_host = 'localhost:3000'" - # end - def environment(data = nil, options = {}) - sentinel = /class [a-z_:]+ < Rails::Application/i - env_file_sentinel = /Rails\.application\.configure do/ - data = yield if !data && block_given? - - in_root do - if options[:env].nil? - inject_into_file "config/application.rb", "\n #{data}", after: sentinel, verbose: false - else - Array(options[:env]).each do |env| - inject_into_file "config/environments/#{env}.rb", "\n #{data}", after: env_file_sentinel, verbose: false - end - end - end - end - alias :application :environment - - # Run a command in git. - # - # git :init - # git add: "this.file that.rb" - # git add: "onefile.rb", rm: "badfile.cxx" - def git(commands = {}) - if commands.is_a?(Symbol) - run "git #{commands}" - else - commands.each do |cmd, options| - run "git #{cmd} #{options}" - end - end - end - - # Create a new file in the vendor/ directory. Code can be specified - # in a block or a data string can be given. - # - # vendor("sekrit.rb") do - # sekrit_salt = "#{Time.now}--#{3.years.ago}--#{rand}--" - # "salt = '#{sekrit_salt}'" - # end - # - # vendor("foreign.rb", "# Foreign code is fun") - def vendor(filename, data = nil, &block) - log :vendor, filename - create_file("vendor/#{filename}", data, verbose: false, &block) - end - - # Create a new file in the lib/ directory. Code can be specified - # in a block or a data string can be given. - # - # lib("crypto.rb") do - # "crypted_special_value = '#{rand}--#{Time.now}--#{rand(1337)}--'" - # end - # - # lib("foreign.rb", "# Foreign code is fun") - def lib(filename, data = nil, &block) - log :lib, filename - create_file("lib/#{filename}", data, verbose: false, &block) - end - - # Create a new +Rakefile+ with the provided code (either in a block or a string). - # - # rakefile("bootstrap.rake") do - # project = ask("What is the UNIX name of your project?") - # - # <<-TASK - # namespace :#{project} do - # task :bootstrap do - # puts "I like boots!" - # end - # end - # TASK - # end - # - # rakefile('seed.rake', 'puts "Planting seeds"') - def rakefile(filename, data = nil, &block) - log :rakefile, filename - create_file("lib/tasks/#{filename}", data, verbose: false, &block) - end - - # Create a new initializer with the provided code (either in a block or a string). - # - # initializer("globals.rb") do - # data = "" - # - # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do |const| - # data << "#{const} = :entp\n" - # end - # - # data - # end - # - # initializer("api.rb", "API_KEY = '123456'") - def initializer(filename, data = nil, &block) - log :initializer, filename - create_file("config/initializers/#{filename}", data, verbose: false, &block) - end - - # Generate something using a generator from Rails or a plugin. - # The second parameter is the argument string that is passed to - # the generator or an Array that is joined. - # - # generate(:authenticated, "user session") - def generate(what, *args) - log :generate, what - argument = args.flat_map(&:to_s).join(" ") - - in_root { run_ruby_script("bin/rails generate #{what} #{argument}", verbose: false) } - end - - # Runs the supplied rake task (invoked with 'rake ...') - # - # rake("db:migrate") - # rake("db:migrate", env: "production") - # rake("gems:install", sudo: true) - def rake(command, options = {}) - execute_command :rake, command, options - end - - # Runs the supplied rake task (invoked with 'rails ...') - # - # rails("db:migrate") - # rails("db:migrate", env: "production") - # rails("gems:install", sudo: true) - def rails_command(command, options = {}) - execute_command :rails, command, options - end - - # Just run the capify command in root - # - # capify! - def capify! - log :capify, "" - in_root { run("#{extify(:capify)} .", verbose: false) } - end - - # Make an entry in Rails routing file config/routes.rb - # - # route "root 'welcome#index'" - def route(routing_code) - log :route, routing_code - sentinel = /\.routes\.draw do\s*\n/m - - in_root do - inject_into_file "config/routes.rb", " #{routing_code}\n", after: sentinel, verbose: false, force: false - end - end - - # Reads the given file at the source root and prints it in the console. - # - # readme "README" - def readme(path) - log File.read(find_in_source_paths(path)) - end - - # Registers a callback to be executed after bundle and spring binstubs - # have run. - # - # after_bundle do - # git add: '.' - # end - def after_bundle(&block) - @after_bundle_callbacks << block - end - - private - - # Define log for backwards compatibility. If just one argument is sent, - # invoke say, otherwise invoke say_status. Differently from say and - # similarly to say_status, this method respects the quiet? option given. - def log(*args) # :doc: - if args.size == 1 - say args.first.to_s unless options.quiet? - else - args << (behavior == :invoke ? :green : :red) - say_status(*args) - end - end - - # Runs the supplied command using either "rake ..." or "rails ..." - # based on the executor parameter provided. - def execute_command(executor, command, options = {}) # :doc: - log executor, command - env = options[:env] || ENV["RAILS_ENV"] || "development" - sudo = options[:sudo] && !Gem.win_platform? ? "sudo " : "" - in_root { run("#{sudo}#{extify(executor)} #{command} RAILS_ENV=#{env}", verbose: false) } - end - - # Add an extension to the given name based on the platform. - def extify(name) # :doc: - if Gem.win_platform? - "#{name}.bat" - else - name - end - end - - # Surround string with single quotes if there is no quotes. - # Otherwise fall back to double quotes - def quote(value) # :doc: - return value.inspect unless value.is_a? String - - if value.include?("'") - value.inspect - else - "'#{value}'" - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/actions/create_migration.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/actions/create_migration.rb deleted file mode 100644 index d06609e91e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/actions/create_migration.rb +++ /dev/null @@ -1,69 +0,0 @@ -require "fileutils" -require "thor/actions" - -module Rails - module Generators - module Actions - class CreateMigration < Thor::Actions::CreateFile #:nodoc: - def migration_dir - File.dirname(@destination) - end - - def migration_file_name - @base.migration_file_name - end - - def identical? - exists? && File.binread(existing_migration) == render - end - - def revoke! - say_destination = exists? ? relative_existing_migration : relative_destination - say_status :remove, :red, say_destination - return unless exists? - ::FileUtils.rm_rf(existing_migration) unless pretend? - existing_migration - end - - def relative_existing_migration - base.relative_to_original_destination_root(existing_migration) - end - - def existing_migration - @existing_migration ||= begin - @base.class.migration_exists?(migration_dir, migration_file_name) || - File.exist?(@destination) && @destination - end - end - alias :exists? :existing_migration - - private - - def on_conflict_behavior # :doc: - options = base.options.merge(config) - if identical? - say_status :identical, :blue, relative_existing_migration - elsif options[:force] - say_status :remove, :green, relative_existing_migration - say_status :create, :green - unless pretend? - ::FileUtils.rm_rf(existing_migration) - yield - end - elsif options[:skip] - say_status :skip, :yellow - else - say_status :conflict, :red - raise Error, "Another migration is already named #{migration_file_name}: " \ - "#{existing_migration}. Use --force to replace this migration " \ - "or --skip to ignore conflicted file." - end - end - - def say_status(status, color, message = relative_destination) # :doc: - base.shell.say_status(status, message, color) if config[:verbose] - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/active_model.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/active_model.rb deleted file mode 100644 index 2679d06fe4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/active_model.rb +++ /dev/null @@ -1,78 +0,0 @@ -module Rails - module Generators - # ActiveModel is a class to be implemented by each ORM to allow Rails to - # generate customized controller code. - # - # The API has the same methods as ActiveRecord, but each method returns a - # string that matches the ORM API. - # - # For example: - # - # ActiveRecord::Generators::ActiveModel.find(Foo, "params[:id]") - # # => "Foo.find(params[:id])" - # - # DataMapper::Generators::ActiveModel.find(Foo, "params[:id]") - # # => "Foo.get(params[:id])" - # - # On initialization, the ActiveModel accepts the instance name that will - # receive the calls: - # - # builder = ActiveRecord::Generators::ActiveModel.new "@foo" - # builder.save # => "@foo.save" - # - # The only exception in ActiveModel for ActiveRecord is the use of self.build - # instead of self.new. - # - class ActiveModel - attr_reader :name - - def initialize(name) - @name = name - end - - # GET index - def self.all(klass) - "#{klass}.all" - end - - # GET show - # GET edit - # PATCH/PUT update - # DELETE destroy - def self.find(klass, params = nil) - "#{klass}.find(#{params})" - end - - # GET new - # POST create - def self.build(klass, params = nil) - if params - "#{klass}.new(#{params})" - else - "#{klass}.new" - end - end - - # POST create - def save - "#{name}.save" - end - - # PATCH/PUT update - def update(params = nil) - "#{name}.update(#{params})" - end - - # POST create - # PATCH/PUT update - def errors - "#{name}.errors" - end - - # DELETE destroy - def destroy - "#{name}.destroy" - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/app_base.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/app_base.rb deleted file mode 100644 index d8cef56072..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/app_base.rb +++ /dev/null @@ -1,442 +0,0 @@ -require "fileutils" -require "digest/md5" -require "active_support/core_ext/string/strip" -require "rails/version" unless defined?(Rails::VERSION) -require "open-uri" -require "uri" -require "rails/generators" -require "active_support/core_ext/array/extract_options" - -module Rails - module Generators - class AppBase < Base # :nodoc: - DATABASES = %w( mysql postgresql sqlite3 oracle frontbase ibm_db sqlserver ) - JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc ) - DATABASES.concat(JDBC_DATABASES) - - attr_accessor :rails_template - add_shebang_option! - - argument :app_path, type: :string - - def self.strict_args_position - false - end - - def self.add_shared_options_for(name) - class_option :template, type: :string, aliases: "-m", - desc: "Path to some #{name} template (can be a filesystem path or URL)" - - class_option :database, type: :string, aliases: "-d", default: "sqlite3", - desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})" - - class_option :skip_yarn, type: :boolean, default: false, - desc: "Don't use Yarn for managing JavaScript dependencies" - - class_option :skip_gemfile, type: :boolean, default: false, - desc: "Don't create a Gemfile" - - class_option :skip_git, type: :boolean, aliases: "-G", default: false, - desc: "Skip .gitignore file" - - class_option :skip_keeps, type: :boolean, default: false, - desc: "Skip source control .keep files" - - class_option :skip_action_mailer, type: :boolean, aliases: "-M", - default: false, - desc: "Skip Action Mailer files" - - class_option :skip_active_record, type: :boolean, aliases: "-O", default: false, - desc: "Skip Active Record files" - - class_option :skip_puma, type: :boolean, aliases: "-P", default: false, - desc: "Skip Puma related files" - - class_option :skip_action_cable, type: :boolean, aliases: "-C", default: false, - desc: "Skip Action Cable files" - - class_option :skip_sprockets, type: :boolean, aliases: "-S", default: false, - desc: "Skip Sprockets files" - - class_option :skip_spring, type: :boolean, default: false, - desc: "Don't install Spring application preloader" - - class_option :skip_listen, type: :boolean, default: false, - desc: "Don't generate configuration that depends on the listen gem" - - class_option :skip_coffee, type: :boolean, default: false, - desc: "Don't use CoffeeScript" - - class_option :skip_javascript, type: :boolean, aliases: "-J", default: false, - desc: "Skip JavaScript files" - - class_option :skip_turbolinks, type: :boolean, default: false, - desc: "Skip turbolinks gem" - - class_option :skip_test, type: :boolean, aliases: "-T", default: false, - desc: "Skip test files" - - class_option :skip_system_test, type: :boolean, default: false, - desc: "Skip system test files" - - class_option :dev, type: :boolean, default: false, - desc: "Setup the #{name} with Gemfile pointing to your Rails checkout" - - class_option :edge, type: :boolean, default: false, - desc: "Setup the #{name} with Gemfile pointing to Rails repository" - - class_option :rc, type: :string, default: nil, - desc: "Path to file containing extra configuration options for rails command" - - class_option :no_rc, type: :boolean, default: false, - desc: "Skip loading of extra configuration options from .railsrc file" - - class_option :help, type: :boolean, aliases: "-h", group: :rails, - desc: "Show this help message and quit" - end - - def initialize(*args) - @gem_filter = lambda { |gem| true } - @extra_entries = [] - super - convert_database_option_for_jruby - end - - private - - def gemfile_entry(name, *args) # :doc: - options = args.extract_options! - version = args.first - github = options[:github] - path = options[:path] - - if github - @extra_entries << GemfileEntry.github(name, github) - elsif path - @extra_entries << GemfileEntry.path(name, path) - else - @extra_entries << GemfileEntry.version(name, version) - end - self - end - - def gemfile_entries # :doc: - [rails_gemfile_entry, - database_gemfile_entry, - webserver_gemfile_entry, - assets_gemfile_entry, - webpacker_gemfile_entry, - javascript_gemfile_entry, - jbuilder_gemfile_entry, - psych_gemfile_entry, - cable_gemfile_entry, - @extra_entries].flatten.find_all(&@gem_filter) - end - - def add_gem_entry_filter # :doc: - @gem_filter = lambda { |next_filter, entry| - yield(entry) && next_filter.call(entry) - }.curry[@gem_filter] - end - - def builder # :doc: - @builder ||= begin - builder_class = get_builder_class - builder_class.include(ActionMethods) - builder_class.new(self) - end - end - - def build(meth, *args) # :doc: - builder.send(meth, *args) if builder.respond_to?(meth) - end - - def create_root # :doc: - valid_const? - - empty_directory "." - FileUtils.cd(destination_root) unless options[:pretend] - end - - def apply_rails_template # :doc: - apply rails_template if rails_template - rescue Thor::Error, LoadError, Errno::ENOENT => e - raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}" - end - - def set_default_accessors! # :doc: - self.destination_root = File.expand_path(app_path, destination_root) - self.rails_template = \ - case options[:template] - when /^https?:\/\// - options[:template] - when String - File.expand_path(options[:template], Dir.pwd) - else - options[:template] - end - end - - def database_gemfile_entry # :doc: - return [] if options[:skip_active_record] - gem_name, gem_version = gem_for_database - GemfileEntry.version gem_name, gem_version, - "Use #{options[:database]} as the database for Active Record" - end - - def webserver_gemfile_entry # :doc: - return [] if options[:skip_puma] - comment = "Use Puma as the app server" - GemfileEntry.new("puma", "~> 3.7", comment) - end - - def include_all_railties? # :doc: - options.values_at(:skip_active_record, :skip_action_mailer, :skip_test, :skip_sprockets, :skip_action_cable).none? - end - - def comment_if(value) # :doc: - options[value] ? "# " : "" - end - - def keeps? # :doc: - !options[:skip_keeps] - end - - def sqlite3? # :doc: - !options[:skip_active_record] && options[:database] == "sqlite3" - end - - class GemfileEntry < Struct.new(:name, :version, :comment, :options, :commented_out) - def initialize(name, version, comment, options = {}, commented_out = false) - super - end - - def self.github(name, github, branch = nil, comment = nil) - if branch - new(name, nil, comment, github: github, branch: branch) - else - new(name, nil, comment, github: github) - end - end - - def self.version(name, version, comment = nil) - new(name, version, comment) - end - - def self.path(name, path, comment = nil) - new(name, nil, comment, path: path) - end - - def version - version = super - - if version.is_a?(Array) - version.join("', '") - else - version - end - end - end - - def rails_gemfile_entry - dev_edge_common = [ - ] - if options.dev? - [ - GemfileEntry.path("rails", Rails::Generators::RAILS_DEV_PATH) - ] + dev_edge_common - elsif options.edge? - [ - GemfileEntry.github("rails", "rails/rails") - ] + dev_edge_common - else - [GemfileEntry.version("rails", - rails_version_specifier, - "Bundle edge Rails instead: gem 'rails', github: 'rails/rails'")] - end - end - - def rails_version_specifier(gem_version = Rails.gem_version) - if gem_version.segments.size == 3 || gem_version.release.segments.size == 3 - # ~> 1.2.3 - # ~> 1.2.3.pre4 - "~> #{gem_version}" - else - # ~> 1.2.3, >= 1.2.3.4 - # ~> 1.2.3, >= 1.2.3.4.pre5 - patch = gem_version.segments[0, 3].join(".") - ["~> #{patch}", ">= #{gem_version}"] - end - end - - def gem_for_database - # %w( mysql postgresql sqlite3 oracle frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql ) - case options[:database] - when "mysql" then ["mysql2", [">= 0.3.18", "< 0.6.0"]] - when "postgresql" then ["pg", [">= 0.18", "< 2.0"]] - when "oracle" then ["activerecord-oracle_enhanced-adapter", nil] - when "frontbase" then ["ruby-frontbase", nil] - when "sqlserver" then ["activerecord-sqlserver-adapter", nil] - when "jdbcmysql" then ["activerecord-jdbcmysql-adapter", nil] - when "jdbcsqlite3" then ["activerecord-jdbcsqlite3-adapter", nil] - when "jdbcpostgresql" then ["activerecord-jdbcpostgresql-adapter", nil] - when "jdbc" then ["activerecord-jdbc-adapter", nil] - else [options[:database], nil] - end - end - - def convert_database_option_for_jruby - if defined?(JRUBY_VERSION) - case options[:database] - when "postgresql" then options[:database].replace "jdbcpostgresql" - when "mysql" then options[:database].replace "jdbcmysql" - when "sqlite3" then options[:database].replace "jdbcsqlite3" - end - end - end - - def assets_gemfile_entry - return [] if options[:skip_sprockets] - - gems = [] - gems << GemfileEntry.version("sass-rails", "~> 5.0", - "Use SCSS for stylesheets") - - if !options[:skip_javascript] - gems << GemfileEntry.version("uglifier", - ">= 1.3.0", - "Use Uglifier as compressor for JavaScript assets") - end - - gems - end - - def webpacker_gemfile_entry - return [] unless options[:webpack] - - comment = "Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker" - GemfileEntry.new "webpacker", nil, comment - end - - def jbuilder_gemfile_entry - comment = "Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder" - GemfileEntry.new "jbuilder", "~> 2.5", comment, {}, options[:api] - end - - def coffee_gemfile_entry - GemfileEntry.version "coffee-rails", "~> 4.2", "Use CoffeeScript for .coffee assets and views" - end - - def javascript_gemfile_entry - if options[:skip_javascript] || options[:skip_sprockets] - [] - else - gems = [javascript_runtime_gemfile_entry] - gems << coffee_gemfile_entry unless options[:skip_coffee] - - unless options[:skip_turbolinks] - gems << GemfileEntry.version("turbolinks", "~> 5", - "Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks") - end - - gems - end - end - - def javascript_runtime_gemfile_entry - comment = "See https://github.com/rails/execjs#readme for more supported runtimes" - if defined?(JRUBY_VERSION) - GemfileEntry.version "therubyrhino", nil, comment - else - GemfileEntry.new "therubyracer", nil, comment, { platforms: :ruby }, true - end - end - - def psych_gemfile_entry - return [] unless defined?(Rubinius) - - comment = "Use Psych as the YAML engine, instead of Syck, so serialized " \ - "data can be read safely from different rubies (see http://git.io/uuLVag)" - GemfileEntry.new("psych", "~> 2.0", comment, platforms: :rbx) - end - - def cable_gemfile_entry - return [] if options[:skip_action_cable] - comment = "Use Redis adapter to run Action Cable in production" - gems = [] - gems << GemfileEntry.new("redis", "~> 4.0", comment, {}, true) - gems - end - - def bundle_command(command) - say_status :run, "bundle #{command}" - - # We are going to shell out rather than invoking Bundler::CLI.new(command) - # because `rails new` loads the Thor gem and on the other hand bundler uses - # its own vendored Thor, which could be a different version. Running both - # things in the same process is a recipe for a night with paracetamol. - # - # We unset temporary bundler variables to load proper bundler and Gemfile. - # - # Thanks to James Tucker for the Gem tricks involved in this call. - _bundle_command = Gem.bin_path("bundler", "bundle") - - require "bundler" - Bundler.with_clean_env do - full_command = %Q["#{Gem.ruby}" "#{_bundle_command}" #{command}] - if options[:quiet] - system(full_command, out: File::NULL) - else - system(full_command) - end - end - end - - def bundle_install? - !(options[:skip_gemfile] || options[:skip_bundle] || options[:pretend]) - end - - def spring_install? - !options[:skip_spring] && !options.dev? && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin") - end - - def depends_on_system_test? - !(options[:skip_system_test] || options[:skip_test] || options[:api]) - end - - def depend_on_listen? - !options[:skip_listen] && os_supports_listen_out_of_the_box? - end - - def os_supports_listen_out_of_the_box? - RbConfig::CONFIG["host_os"] =~ /darwin|linux/ - end - - def run_bundle - bundle_command("install") if bundle_install? - end - - def run_webpack - if !(webpack = options[:webpack]).nil? - rails_command "webpacker:install" - rails_command "webpacker:install:#{webpack}" unless webpack == "webpack" - end - end - - def generate_spring_binstubs - if bundle_install? && spring_install? - bundle_command("exec spring binstub --all") - end - end - - def empty_directory_with_keep_file(destination, config = {}) - empty_directory(destination, config) - keep_file(destination) - end - - def keep_file(destination) - create_file("#{destination}/.keep") if keeps? - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/base.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/base.rb deleted file mode 100644 index a650c52626..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/base.rb +++ /dev/null @@ -1,378 +0,0 @@ -begin - require "thor/group" -rescue LoadError - puts "Thor is not available.\nIf you ran this command from a git checkout " \ - "of Rails, please make sure thor is installed,\nand run this command " \ - "as `ruby #{$0} #{(ARGV | ['--dev']).join(" ")}`" - exit -end - -module Rails - module Generators - class Error < Thor::Error # :nodoc: - end - - class Base < Thor::Group - include Thor::Actions - include Rails::Generators::Actions - - add_runtime_options! - strict_args_position! - - # Returns the source root for this generator using default_source_root as default. - def self.source_root(path = nil) - @_source_root = path if path - @_source_root ||= default_source_root - end - - # Tries to get the description from a USAGE file one folder above the source - # root otherwise uses a default description. - def self.desc(description = nil) - return super if description - - @desc ||= if usage_path - ERB.new(File.read(usage_path)).result(binding) - else - "Description:\n Create #{base_name.humanize.downcase} files for #{generator_name} generator." - end - end - - # Convenience method to get the namespace from the class name. It's the - # same as Thor default except that the Generator at the end of the class - # is removed. - def self.namespace(name = nil) - return super if name - @namespace ||= super.sub(/_generator$/, "").sub(/:generators:/, ":") - end - - # Convenience method to hide this generator from the available ones when - # running rails generator command. - def self.hide! - Rails::Generators.hide_namespace(namespace) - end - - # Invoke a generator based on the value supplied by the user to the - # given option named "name". A class option is created when this method - # is invoked and you can set a hash to customize it. - # - # ==== Examples - # - # module Rails::Generators - # class ControllerGenerator < Base - # hook_for :test_framework, aliases: "-t" - # end - # end - # - # The example above will create a test framework option and will invoke - # a generator based on the user supplied value. - # - # For example, if the user invoke the controller generator as: - # - # rails generate controller Account --test-framework=test_unit - # - # The controller generator will then try to invoke the following generators: - # - # "rails:test_unit", "test_unit:controller", "test_unit" - # - # Notice that "rails:generators:test_unit" could be loaded as well, what - # Rails looks for is the first and last parts of the namespace. This is what - # allows any test framework to hook into Rails as long as it provides any - # of the hooks above. - # - # ==== Options - # - # The first and last part used to find the generator to be invoked are - # guessed based on class invokes hook_for, as noticed in the example above. - # This can be customized with two options: :in and :as. - # - # Let's suppose you are creating a generator that needs to invoke the - # controller generator from test unit. Your first attempt is: - # - # class AwesomeGenerator < Rails::Generators::Base - # hook_for :test_framework - # end - # - # The lookup in this case for test_unit as input is: - # - # "test_unit:awesome", "test_unit" - # - # Which is not the desired lookup. You can change it by providing the - # :as option: - # - # class AwesomeGenerator < Rails::Generators::Base - # hook_for :test_framework, as: :controller - # end - # - # And now it will look up at: - # - # "test_unit:controller", "test_unit" - # - # Similarly, if you want it to also look up in the rails namespace, you - # just need to provide the :in value: - # - # class AwesomeGenerator < Rails::Generators::Base - # hook_for :test_framework, in: :rails, as: :controller - # end - # - # And the lookup is exactly the same as previously: - # - # "rails:test_unit", "test_unit:controller", "test_unit" - # - # ==== Switches - # - # All hooks come with switches for user interface. If you do not want - # to use any test framework, you can do: - # - # rails generate controller Account --skip-test-framework - # - # Or similarly: - # - # rails generate controller Account --no-test-framework - # - # ==== Boolean hooks - # - # In some cases, you may want to provide a boolean hook. For example, webrat - # developers might want to have webrat available on controller generator. - # This can be achieved as: - # - # Rails::Generators::ControllerGenerator.hook_for :webrat, type: :boolean - # - # Then, if you want webrat to be invoked, just supply: - # - # rails generate controller Account --webrat - # - # The hooks lookup is similar as above: - # - # "rails:generators:webrat", "webrat:generators:controller", "webrat" - # - # ==== Custom invocations - # - # You can also supply a block to hook_for to customize how the hook is - # going to be invoked. The block receives two arguments, an instance - # of the current class and the class to be invoked. - # - # For example, in the resource generator, the controller should be invoked - # with a pluralized class name. But by default it is invoked with the same - # name as the resource generator, which is singular. To change this, we - # can give a block to customize how the controller can be invoked. - # - # hook_for :resource_controller do |instance, controller| - # instance.invoke controller, [ instance.name.pluralize ] - # end - # - def self.hook_for(*names, &block) - options = names.extract_options! - in_base = options.delete(:in) || base_name - as_hook = options.delete(:as) || generator_name - - names.each do |name| - unless class_options.key?(name) - defaults = if options[:type] == :boolean - {} - elsif [true, false].include?(default_value_for_option(name, options)) - { banner: "" } - else - { desc: "#{name.to_s.humanize} to be invoked", banner: "NAME" } - end - - class_option(name, defaults.merge!(options)) - end - - hooks[name] = [ in_base, as_hook ] - invoke_from_option(name, options, &block) - end - end - - # Remove a previously added hook. - # - # remove_hook_for :orm - def self.remove_hook_for(*names) - remove_invocation(*names) - - names.each do |name| - hooks.delete(name) - end - end - - # Make class option aware of Rails::Generators.options and Rails::Generators.aliases. - def self.class_option(name, options = {}) #:nodoc: - options[:desc] = "Indicates when to generate #{name.to_s.humanize.downcase}" unless options.key?(:desc) - options[:aliases] = default_aliases_for_option(name, options) - options[:default] = default_value_for_option(name, options) - super(name, options) - end - - # Returns the default source root for a given generator. This is used internally - # by rails to set its generators source root. If you want to customize your source - # root, you should use source_root. - def self.default_source_root - return unless base_name && generator_name - return unless default_generator_root - path = File.join(default_generator_root, "templates") - path if File.exist?(path) - end - - # Returns the base root for a common set of generators. This is used to dynamically - # guess the default source root. - def self.base_root - File.dirname(__FILE__) - end - - # Cache source root and add lib/generators/base/generator/templates to - # source paths. - def self.inherited(base) #:nodoc: - super - - # Invoke source_root so the default_source_root is set. - base.source_root - - if base.name && base.name !~ /Base$/ - Rails::Generators.subclasses << base - - Rails::Generators.templates_path.each do |path| - if base.name.include?("::") - base.source_paths << File.join(path, base.base_name, base.generator_name) - else - base.source_paths << File.join(path, base.generator_name) - end - end - end - end - - private - - # Check whether the given class names are already taken by user - # application or Ruby on Rails. - def class_collisions(*class_names) - return unless behavior == :invoke - - class_names.flatten.each do |class_name| - class_name = class_name.to_s - next if class_name.strip.empty? - - # Split the class from its module nesting - nesting = class_name.split("::") - last_name = nesting.pop - last = extract_last_module(nesting) - - if last && last.const_defined?(last_name.camelize, false) - raise Error, "The name '#{class_name}' is either already used in your application " \ - "or reserved by Ruby on Rails. Please choose an alternative and run " \ - "this generator again." - end - end - end - - # Takes in an array of nested modules and extracts the last module - def extract_last_module(nesting) # :doc: - nesting.inject(Object) do |last_module, nest| - break unless last_module.const_defined?(nest, false) - last_module.const_get(nest) - end - end - - # Use Rails default banner. - def self.banner # :doc: - "rails generate #{namespace.sub(/^rails:/, '')} #{arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, " ") - end - - # Sets the base_name taking into account the current class namespace. - def self.base_name # :doc: - @base_name ||= begin - if base = name.to_s.split("::").first - base.underscore - end - end - end - - # Removes the namespaces and get the generator name. For example, - # Rails::Generators::ModelGenerator will return "model" as generator name. - def self.generator_name # :doc: - @generator_name ||= begin - if generator = name.to_s.split("::").last - generator.sub!(/Generator$/, "") - generator.underscore - end - end - end - - # Returns the default value for the option name given doing a lookup in - # Rails::Generators.options. - def self.default_value_for_option(name, options) # :doc: - default_for_option(Rails::Generators.options, name, options, options[:default]) - end - - # Returns default aliases for the option name given doing a lookup in - # Rails::Generators.aliases. - def self.default_aliases_for_option(name, options) # :doc: - default_for_option(Rails::Generators.aliases, name, options, options[:aliases]) - end - - # Returns default for the option name given doing a lookup in config. - def self.default_for_option(config, name, options, default) # :doc: - if generator_name && (c = config[generator_name.to_sym]) && c.key?(name) - c[name] - elsif base_name && (c = config[base_name.to_sym]) && c.key?(name) - c[name] - elsif config[:rails].key?(name) - config[:rails][name] - else - default - end - end - - # Keep hooks configuration that are used on prepare_for_invocation. - def self.hooks #:nodoc: - @hooks ||= from_superclass(:hooks, {}) - end - - # Prepare class invocation to search on Rails namespace if a previous - # added hook is being used. - def self.prepare_for_invocation(name, value) #:nodoc: - return super unless value.is_a?(String) || value.is_a?(Symbol) - - if value && constants = hooks[name] - value = name if TrueClass === value - Rails::Generators.find_by_namespace(value, *constants) - elsif klass = Rails::Generators.find_by_namespace(value) - klass - else - super - end - end - - # Small macro to add ruby as an option to the generator with proper - # default value plus an instance helper method called shebang. - def self.add_shebang_option! # :doc: - class_option :ruby, type: :string, aliases: "-r", default: Thor::Util.ruby_command, - desc: "Path to the Ruby binary of your choice", banner: "PATH" - - no_tasks { - define_method :shebang do - @shebang ||= begin - command = if options[:ruby] == Thor::Util.ruby_command - "/usr/bin/env #{File.basename(Thor::Util.ruby_command)}" - else - options[:ruby] - end - "#!#{command}" - end - end - } - end - - def self.usage_path # :doc: - paths = [ - source_root && File.expand_path("../USAGE", source_root), - default_generator_root && File.join(default_generator_root, "USAGE") - ] - paths.compact.detect { |path| File.exist? path } - end - - def self.default_generator_root # :doc: - path = File.expand_path(File.join(base_name, generator_name), base_root) - path if File.exist?(path) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/assets/assets_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/assets/assets_generator.rb deleted file mode 100644 index 20baf31a34..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/assets/assets_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "rails/generators/named_base" - -module Css # :nodoc: - module Generators # :nodoc: - class AssetsGenerator < Rails::Generators::NamedBase # :nodoc: - source_root File.expand_path("../templates", __FILE__) - - def copy_stylesheet - copy_file "stylesheet.css", File.join("app/assets/stylesheets", class_path, "#{file_name}.css") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/assets/templates/stylesheet.css b/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/assets/templates/stylesheet.css deleted file mode 100644 index afad32db02..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/assets/templates/stylesheet.css +++ /dev/null @@ -1,4 +0,0 @@ -/* - Place all the styles related to the matching controller here. - They will automatically be included in application.css. -*/ diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/scaffold/scaffold_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/scaffold/scaffold_generator.rb deleted file mode 100644 index cf534030f9..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/css/scaffold/scaffold_generator.rb +++ /dev/null @@ -1,16 +0,0 @@ -require "rails/generators/named_base" - -module Css # :nodoc: - module Generators # :nodoc: - class ScaffoldGenerator < Rails::Generators::NamedBase # :nodoc: - # In order to allow the Sass generators to pick up the default Rails CSS and - # transform it, we leave it in a standard location for the CSS stylesheet - # generators to handle. For the simple, default case, just copy it over. - def copy_stylesheet - dir = Rails::Generators::ScaffoldGenerator.source_root - file = File.join(dir, "scaffold.css") - create_file "app/assets/stylesheets/scaffold.css", File.read(file) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb.rb deleted file mode 100644 index 97d9ab29d4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb.rb +++ /dev/null @@ -1,25 +0,0 @@ -require "rails/generators/named_base" - -module Erb # :nodoc: - module Generators # :nodoc: - class Base < Rails::Generators::NamedBase #:nodoc: - private - - def formats - [format] - end - - def format - :html - end - - def handler - :erb - end - - def filename_with_extensions(name, file_format = format) - [name, file_format, handler].compact.join(".") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/controller/controller_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/controller/controller_generator.rb deleted file mode 100644 index 36ecfea09b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/controller/controller_generator.rb +++ /dev/null @@ -1,22 +0,0 @@ -require "rails/generators/erb" - -module Erb # :nodoc: - module Generators # :nodoc: - class ControllerGenerator < Base # :nodoc: - argument :actions, type: :array, default: [], banner: "action action" - - def copy_view_files - base_path = File.join("app/views", class_path, file_name) - empty_directory base_path - - actions.each do |action| - @action = action - formats.each do |format| - @path = File.join(base_path, filename_with_extensions(action, format)) - template filename_with_extensions(:view, format), @path - end - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/controller/templates/view.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/controller/templates/view.html.erb deleted file mode 100644 index cd54d13d83..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/controller/templates/view.html.erb +++ /dev/null @@ -1,2 +0,0 @@ -

    <%= class_name %>#<%= @action %>

    -

    Find me in <%= @path %>

    diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/mailer_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/mailer_generator.rb deleted file mode 100644 index 3f1d9932f6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/mailer_generator.rb +++ /dev/null @@ -1,40 +0,0 @@ -require "rails/generators/erb" - -module Erb # :nodoc: - module Generators # :nodoc: - class MailerGenerator < Base # :nodoc: - argument :actions, type: :array, default: [], banner: "method method" - - def copy_view_files - view_base_path = File.join("app/views", class_path, file_name + "_mailer") - empty_directory view_base_path - - if behavior == :invoke - formats.each do |format| - layout_path = File.join("app/views/layouts", class_path, filename_with_extensions("mailer", format)) - template filename_with_extensions(:layout, format), layout_path unless File.exist?(layout_path) - end - end - - actions.each do |action| - @action = action - - formats.each do |format| - @path = File.join(view_base_path, filename_with_extensions(action, format)) - template filename_with_extensions(:view, format), @path - end - end - end - - private - - def formats - [:text, :html] - end - - def file_name - @_file_name ||= super.gsub(/_mailer/i, "") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/layout.html.erb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/layout.html.erb.tt deleted file mode 100644 index 55f3675d49..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/layout.html.erb.tt +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - <%%= yield %> - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/layout.text.erb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/layout.text.erb.tt deleted file mode 100644 index 6363733e6e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/layout.text.erb.tt +++ /dev/null @@ -1 +0,0 @@ -<%%= yield %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/view.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/view.html.erb deleted file mode 100644 index b5045671b3..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/view.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -

    <%= class_name %>#<%= @action %>

    - -

    - <%%= @greeting %>, find me in <%= @path %> -

    diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/view.text.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/view.text.erb deleted file mode 100644 index 342285df19..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/mailer/templates/view.text.erb +++ /dev/null @@ -1,3 +0,0 @@ -<%= class_name %>#<%= @action %> - -<%%= @greeting %>, find me in <%= @path %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/scaffold_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/scaffold_generator.rb deleted file mode 100644 index 0d77ef21da..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/scaffold_generator.rb +++ /dev/null @@ -1,31 +0,0 @@ -require "rails/generators/erb" -require "rails/generators/resource_helpers" - -module Erb # :nodoc: - module Generators # :nodoc: - class ScaffoldGenerator < Base # :nodoc: - include Rails::Generators::ResourceHelpers - - argument :attributes, type: :array, default: [], banner: "field:type field:type" - - def create_root_folder - empty_directory File.join("app/views", controller_file_path) - end - - def copy_view_files - available_views.each do |view| - formats.each do |format| - filename = filename_with_extensions(view, format) - template filename, File.join("app/views", controller_file_path, filename) - end - end - end - - private - - def available_views - %w(index edit show new _form) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/_form.html.erb deleted file mode 100644 index 4f2e84f924..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/_form.html.erb +++ /dev/null @@ -1,34 +0,0 @@ -<%%= form_with(model: <%= singular_table_name %>, local: true) do |form| %> - <%% if <%= singular_table_name %>.errors.any? %> -
    -

    <%%= pluralize(<%= singular_table_name %>.errors.count, "error") %> prohibited this <%= singular_table_name %> from being saved:

    - -
      - <%% <%= singular_table_name %>.errors.full_messages.each do |message| %> -
    • <%%= message %>
    • - <%% end %> -
    -
    - <%% end %> - -<% attributes.each do |attribute| -%> -
    -<% if attribute.password_digest? -%> - <%%= form.label :password %> - <%%= form.password_field :password, id: :<%= field_id(:password) %> %> -
    - -
    - <%%= form.label :password_confirmation %> - <%%= form.password_field :password_confirmation, id: :<%= field_id(:password_confirmation) %> %> -<% else -%> - <%%= form.label :<%= attribute.column_name %> %> - <%%= form.<%= attribute.field_type %> :<%= attribute.column_name %>, id: :<%= field_id(attribute.column_name) %> %> -<% end -%> -
    - -<% end -%> -
    - <%%= form.submit %> -
    -<%% end %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/edit.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/edit.html.erb deleted file mode 100644 index 81329473d9..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/edit.html.erb +++ /dev/null @@ -1,6 +0,0 @@ -

    Editing <%= singular_table_name.titleize %>

    - -<%%= render 'form', <%= singular_table_name %>: @<%= singular_table_name %> %> - -<%%= link_to 'Show', @<%= singular_table_name %> %> | -<%%= link_to 'Back', <%= index_helper %>_path %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/index.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/index.html.erb deleted file mode 100644 index 5f4904fee1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/index.html.erb +++ /dev/null @@ -1,31 +0,0 @@ -

    <%%= notice %>

    - -

    <%= plural_table_name.titleize %>

    - -
    - - -<% attributes.reject(&:password_digest?).each do |attribute| -%> - -<% end -%> - - - - - - <%% @<%= plural_table_name %>.each do |<%= singular_table_name %>| %> - -<% attributes.reject(&:password_digest?).each do |attribute| -%> - -<% end -%> - - - - - <%% end %> - -
    <%= attribute.human_name %>
    <%%= <%= singular_table_name %>.<%= attribute.name %> %><%%= link_to 'Show', <%= singular_table_name %> %><%%= link_to 'Edit', edit_<%= singular_table_name %>_path(<%= singular_table_name %>) %><%%= link_to 'Destroy', <%= singular_table_name %>, method: :delete, data: { confirm: 'Are you sure?' } %>
    - -
    - -<%%= link_to 'New <%= singular_table_name.titleize %>', new_<%= singular_table_name %>_path %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/new.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/new.html.erb deleted file mode 100644 index 9b2b2f4875..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/new.html.erb +++ /dev/null @@ -1,5 +0,0 @@ -

    New <%= singular_table_name.titleize %>

    - -<%%= render 'form', <%= singular_table_name %>: @<%= singular_table_name %> %> - -<%%= link_to 'Back', <%= index_helper %>_path %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/show.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/show.html.erb deleted file mode 100644 index 5e634153be..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/erb/scaffold/templates/show.html.erb +++ /dev/null @@ -1,11 +0,0 @@ -

    <%%= notice %>

    - -<% attributes.reject(&:password_digest?).each do |attribute| -%> -

    - <%= attribute.human_name %>: - <%%= @<%= singular_table_name %>.<%= attribute.name %> %> -

    - -<% end -%> -<%%= link_to 'Edit', edit_<%= singular_table_name %>_path(@<%= singular_table_name %>) %> | -<%%= link_to 'Back', <%= index_helper %>_path %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/generated_attribute.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/generated_attribute.rb deleted file mode 100644 index baed7bf1e3..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/generated_attribute.rb +++ /dev/null @@ -1,175 +0,0 @@ -require "active_support/time" - -module Rails - module Generators - class GeneratedAttribute # :nodoc: - INDEX_OPTIONS = %w(index uniq) - UNIQ_INDEX_OPTIONS = %w(uniq) - - attr_accessor :name, :type - attr_reader :attr_options - attr_writer :index_name - - class << self - def parse(column_definition) - name, type, has_index = column_definition.split(":") - - # if user provided "name:index" instead of "name:string:index" - # type should be set blank so GeneratedAttribute's constructor - # could set it to :string - has_index, type = type, nil if INDEX_OPTIONS.include?(type) - - type, attr_options = *parse_type_and_options(type) - type = type.to_sym if type - - if type && reference?(type) - if UNIQ_INDEX_OPTIONS.include?(has_index) - attr_options[:index] = { unique: true } - end - end - - new(name, type, has_index, attr_options) - end - - def reference?(type) - [:references, :belongs_to].include? type - end - - private - - # parse possible attribute options like :limit for string/text/binary/integer, :precision/:scale for decimals or :polymorphic for references/belongs_to - # when declaring options curly brackets should be used - def parse_type_and_options(type) - case type - when /(string|text|binary|integer)\{(\d+)\}/ - return $1, limit: $2.to_i - when /decimal\{(\d+)[,.-](\d+)\}/ - return :decimal, precision: $1.to_i, scale: $2.to_i - when /(references|belongs_to)\{(.+)\}/ - type = $1 - provided_options = $2.split(/[,.-]/) - options = Hash[provided_options.map { |opt| [opt.to_sym, true] }] - return type, options - else - return type, {} - end - end - end - - def initialize(name, type = nil, index_type = false, attr_options = {}) - @name = name - @type = type || :string - @has_index = INDEX_OPTIONS.include?(index_type) - @has_uniq_index = UNIQ_INDEX_OPTIONS.include?(index_type) - @attr_options = attr_options - end - - def field_type - @field_type ||= case type - when :integer then :number_field - when :float, :decimal then :text_field - when :time then :time_select - when :datetime, :timestamp then :datetime_select - when :date then :date_select - when :text then :text_area - when :boolean then :check_box - else - :text_field - end - end - - def default - @default ||= case type - when :integer then 1 - when :float then 1.5 - when :decimal then "9.99" - when :datetime, :timestamp, :time then Time.now.to_s(:db) - when :date then Date.today.to_s(:db) - when :string then name == "type" ? "" : "MyString" - when :text then "MyText" - when :boolean then false - when :references, :belongs_to then nil - else - "" - end - end - - def plural_name - name.sub(/_id$/, "").pluralize - end - - def singular_name - name.sub(/_id$/, "").singularize - end - - def human_name - name.humanize - end - - def index_name - @index_name ||= if polymorphic? - %w(id type).map { |t| "#{name}_#{t}" } - else - column_name - end - end - - def column_name - @column_name ||= reference? ? "#{name}_id" : name - end - - def foreign_key? - !!(name =~ /_id$/) - end - - def reference? - self.class.reference?(type) - end - - def polymorphic? - attr_options[:polymorphic] - end - - def required? - attr_options[:required] - end - - def has_index? - @has_index - end - - def has_uniq_index? - @has_uniq_index - end - - def password_digest? - name == "password" && type == :digest - end - - def token? - type == :token - end - - def inject_options - "".tap { |s| options_for_migration.each { |k, v| s << ", #{k}: #{v.inspect}" } } - end - - def inject_index_options - has_uniq_index? ? ", unique: true" : "" - end - - def options_for_migration - @attr_options.dup.tap do |options| - if required? - options.delete(:required) - options[:null] = false - end - - if reference? && !polymorphic? - options[:foreign_key] = true - end - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/js/assets/assets_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/js/assets/assets_generator.rb deleted file mode 100644 index 64d706ec91..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/js/assets/assets_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "rails/generators/named_base" - -module Js # :nodoc: - module Generators # :nodoc: - class AssetsGenerator < Rails::Generators::NamedBase # :nodoc: - source_root File.expand_path("../templates", __FILE__) - - def copy_javascript - copy_file "javascript.js", File.join("app/assets/javascripts", class_path, "#{file_name}.js") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/js/assets/templates/javascript.js b/debian/gems-compat/railties-5.1.7/lib/rails/generators/js/assets/templates/javascript.js deleted file mode 100644 index dee720facd..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/js/assets/templates/javascript.js +++ /dev/null @@ -1,2 +0,0 @@ -// Place all the behaviors and hooks related to the matching controller here. -// All this logic will automatically be available in application.js. diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/migration.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/migration.rb deleted file mode 100644 index 82481169c3..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/migration.rb +++ /dev/null @@ -1,69 +0,0 @@ -require "active_support/concern" -require "rails/generators/actions/create_migration" - -module Rails - module Generators - # Holds common methods for migrations. It assumes that migrations have the - # [0-9]*_name format and can be used by other frameworks (like Sequel) - # just by implementing the next migration version method. - module Migration - extend ActiveSupport::Concern - attr_reader :migration_number, :migration_file_name, :migration_class_name - - module ClassMethods #:nodoc: - def migration_lookup_at(dirname) - Dir.glob("#{dirname}/[0-9]*_*.rb") - end - - def migration_exists?(dirname, file_name) - migration_lookup_at(dirname).grep(/\d+_#{file_name}.rb$/).first - end - - def current_migration_number(dirname) - migration_lookup_at(dirname).collect do |file| - File.basename(file).split("_").first.to_i - end.max.to_i - end - - def next_migration_number(dirname) - raise NotImplementedError - end - end - - def create_migration(destination, data, config = {}, &block) - action Rails::Generators::Actions::CreateMigration.new(self, destination, block || data.to_s, config) - end - - def set_migration_assigns!(destination) - destination = File.expand_path(destination, destination_root) - - migration_dir = File.dirname(destination) - @migration_number = self.class.next_migration_number(migration_dir) - @migration_file_name = File.basename(destination, ".rb") - @migration_class_name = @migration_file_name.camelize - end - - # Creates a migration template at the given destination. The difference - # to the default template method is that the migration version is appended - # to the destination file name. - # - # The migration version, migration file name, migration class name are - # available as instance variables in the template to be rendered. - # - # migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb" - def migration_template(source, destination, config = {}) - source = File.expand_path(find_in_source_paths(source.to_s)) - - set_migration_assigns!(destination) - context = instance_eval("binding") - - dir, base = File.split(destination) - numbered_destination = File.join(dir, ["%migration_number%", base].join("_")) - - create_migration numbered_destination, nil, config do - ERB.new(::File.binread(source), nil, "-", "@output_buffer").result(context) - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/model_helpers.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/model_helpers.rb deleted file mode 100644 index 6f87a18660..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/model_helpers.rb +++ /dev/null @@ -1,28 +0,0 @@ -require "rails/generators/active_model" - -module Rails - module Generators - module ModelHelpers # :nodoc: - PLURAL_MODEL_NAME_WARN_MESSAGE = "[WARNING] The model name '%s' was recognized as a plural, using the singular '%s' instead. " \ - "Override with --force-plural or setup custom inflection rules for this noun before running the generator." - mattr_accessor :skip_warn - - def self.included(base) #:nodoc: - base.class_option :force_plural, type: :boolean, default: false, desc: "Forces the use of the given model name" - end - - def initialize(args, *_options) - super - if name == name.pluralize && name.singularize != name.pluralize && !options[:force_plural] - singular = name.singularize - unless ModelHelpers.skip_warn - say PLURAL_MODEL_NAME_WARN_MESSAGE % [name, singular] - ModelHelpers.skip_warn = true - end - name.replace singular - assign_names!(name) - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/named_base.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/named_base.rb deleted file mode 100644 index aef66adb64..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/named_base.rb +++ /dev/null @@ -1,241 +0,0 @@ -require "active_support/core_ext/module/introspection" -require "rails/generators/base" -require "rails/generators/generated_attribute" - -module Rails - module Generators - class NamedBase < Base - argument :name, type: :string - class_option :skip_namespace, type: :boolean, default: false, - desc: "Skip namespace (affects only isolated applications)" - - def initialize(args, *options) #:nodoc: - @inside_template = nil - # Unfreeze name in case it's given as a frozen string - args[0] = args[0].dup if args[0].is_a?(String) && args[0].frozen? - super - assign_names!(name) - parse_attributes! if respond_to?(:attributes) - end - - # Overrides Thor::Actions#template so it can tell if - # a template is currently being created. - no_tasks do - def template(source, *args, &block) - inside_template do - super - end - end - - def js_template(source, destination) - template(source + ".js", destination + ".js") - end - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - attr_reader :file_name - - private - - # FIXME: We are avoiding to use alias because a bug on thor that make - # this method public and add it to the task list. - def singular_name # :doc: - file_name - end - - # Wrap block with namespace of current application - # if namespace exists and is not skipped - def module_namespacing(&block) # :doc: - content = capture(&block) - content = wrap_with_namespace(content) if namespaced? - concat(content) - end - - def indent(content, multiplier = 2) # :doc: - spaces = " " * multiplier - content.each_line.map { |line| line.blank? ? line : "#{spaces}#{line}" }.join - end - - def wrap_with_namespace(content) # :doc: - content = indent(content).chomp - "module #{namespace.name}\n#{content}\nend\n" - end - - def inside_template # :doc: - @inside_template = true - yield - ensure - @inside_template = false - end - - def inside_template? # :doc: - @inside_template - end - - def namespace # :doc: - Rails::Generators.namespace - end - - def namespaced? # :doc: - !options[:skip_namespace] && namespace - end - - def namespace_dirs - @namespace_dirs ||= namespace.name.split("::").map(&:underscore) - end - - def file_path # :doc: - @file_path ||= (class_path + [file_name]).join("/") - end - - def class_path # :doc: - inside_template? || !namespaced? ? regular_class_path : namespaced_class_path - end - - def regular_class_path # :doc: - @class_path - end - - def namespaced_class_path # :doc: - @namespaced_class_path ||= namespace_dirs + @class_path - end - - def namespaced_path # :doc: - @namespaced_path ||= namespace_dirs.join("/") - end - - def class_name # :doc: - (class_path + [file_name]).map!(&:camelize).join("::") - end - - def human_name # :doc: - @human_name ||= singular_name.humanize - end - - def plural_name # :doc: - @plural_name ||= singular_name.pluralize - end - - def i18n_scope # :doc: - @i18n_scope ||= file_path.tr("/", ".") - end - - def table_name # :doc: - @table_name ||= begin - base = pluralize_table_names? ? plural_name : singular_name - (class_path + [base]).join("_") - end - end - - def uncountable? # :doc: - singular_name == plural_name - end - - def index_helper # :doc: - uncountable? ? "#{plural_table_name}_index" : plural_table_name - end - - def show_helper # :doc: - "#{singular_table_name}_url(@#{singular_table_name})" - end - - def edit_helper # :doc: - "edit_#{show_helper}" - end - - def new_helper # :doc: - "new_#{singular_table_name}_url" - end - - def field_id(attribute_name) - [singular_table_name, attribute_name].join("_") - end - - def singular_table_name # :doc: - @singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name) - end - - def plural_table_name # :doc: - @plural_table_name ||= (pluralize_table_names? ? table_name : table_name.pluralize) - end - - def plural_file_name # :doc: - @plural_file_name ||= file_name.pluralize - end - - def fixture_file_name # :doc: - @fixture_file_name ||= (pluralize_table_names? ? plural_file_name : file_name) - end - - def route_url # :doc: - @route_url ||= class_path.collect { |dname| "/" + dname }.join + "/" + plural_file_name - end - - def url_helper_prefix # :doc: - @url_helper_prefix ||= (class_path + [file_name]).join("_") - end - - # Tries to retrieve the application name or simply return application. - def application_name # :doc: - if defined?(Rails) && Rails.application - Rails.application.class.name.split("::").first.underscore - else - "application" - end - end - - def assign_names!(name) - @class_path = name.include?("/") ? name.split("/") : name.split("::") - @class_path.map!(&:underscore) - @file_name = @class_path.pop - end - - # Convert attributes array into GeneratedAttribute objects. - def parse_attributes! - self.attributes = (attributes || []).map do |attr| - Rails::Generators::GeneratedAttribute.parse(attr) - end - end - - def attributes_names # :doc: - @attributes_names ||= attributes.each_with_object([]) do |a, names| - names << a.column_name - names << "password_confirmation" if a.password_digest? - names << "#{a.name}_type" if a.polymorphic? - end - end - - def pluralize_table_names? # :doc: - !defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names - end - - def mountable_engine? # :doc: - defined?(ENGINE_ROOT) && namespaced? - end - - # Add a class collisions name to be checked on class initialization. You - # can supply a hash with a :prefix or :suffix to be tested. - # - # ==== Examples - # - # check_class_collision suffix: "Decorator" - # - # If the generator is invoked with class name Admin, it will check for - # the presence of "AdminDecorator". - # - def self.check_class_collision(options = {}) # :doc: - define_method :check_class_collision do - name = if respond_to?(:controller_class_name) # for ScaffoldBase - controller_class_name - else - class_name - end - - class_collisions "#{options[:prefix]}#{name}#{options[:suffix]}" - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/USAGE deleted file mode 100644 index 28df6ebf44..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/USAGE +++ /dev/null @@ -1,14 +0,0 @@ -Description: - The 'rails new' command creates a new Rails application with a default - directory structure and configuration at the path you specify. - - You can specify extra command-line arguments to be used every time - 'rails new' runs in the .railsrc configuration file in your home directory. - - Note that the arguments specified in the .railsrc file don't affect the - defaults values shown above in this help message. - -Example: - rails new ~/Code/Ruby/weblog - - This generates a skeletal Rails installation in ~/Code/Ruby/weblog. diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/app_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/app_generator.rb deleted file mode 100644 index f6a9e00779..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/app_generator.rb +++ /dev/null @@ -1,568 +0,0 @@ -require "rails/generators/app_base" - -module Rails - module ActionMethods # :nodoc: - attr_reader :options - - def initialize(generator) - @generator = generator - @options = generator.options - end - - private - %w(template copy_file directory empty_directory inside - empty_directory_with_keep_file create_file chmod shebang).each do |method| - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{method}(*args, &block) - @generator.send(:#{method}, *args, &block) - end - RUBY - end - - # TODO: Remove once this is fully in place - def method_missing(meth, *args, &block) - @generator.send(meth, *args, &block) - end - end - - # The application builder allows you to override elements of the application - # generator without being forced to reverse the operations of the default - # generator. - # - # This allows you to override entire operations, like the creation of the - # Gemfile, README, or JavaScript files, without needing to know exactly - # what those operations do so you can create another template action. - # - # class CustomAppBuilder < Rails::AppBuilder - # def test - # @generator.gem "rspec-rails", group: [:development, :test] - # run "bundle install" - # generate "rspec:install" - # end - # end - class AppBuilder - def rakefile - template "Rakefile" - end - - def readme - copy_file "README.md", "README.md" - end - - def gemfile - template "Gemfile" - end - - def configru - template "config.ru" - end - - def gitignore - template "gitignore", ".gitignore" - end - - def version_control - if !options[:skip_git] && !options[:pretend] - run "git init" - end - end - - def app - directory "app" - - keep_file "app/assets/images" - empty_directory_with_keep_file "app/assets/javascripts/channels" unless options[:skip_action_cable] - - keep_file "app/controllers/concerns" - keep_file "app/models/concerns" - end - - def bin - directory "bin" do |content| - "#{shebang}\n" + content - end - chmod "bin", 0755 & ~File.umask, verbose: false - end - - def bin_when_updating - bin_yarn_exist = File.exist?("bin/yarn") - - bin - - if options[:api] && !bin_yarn_exist - remove_file "bin/yarn" - end - end - - def config - empty_directory "config" - - inside "config" do - template "routes.rb" - template "application.rb" - template "environment.rb" - template "secrets.yml" - template "cable.yml" unless options[:skip_action_cable] - template "puma.rb" unless options[:skip_puma] - template "spring.rb" if spring_install? - - directory "environments" - directory "initializers" - directory "locales" - end - end - - def config_when_updating - cookie_serializer_config_exist = File.exist?("config/initializers/cookies_serializer.rb") - action_cable_config_exist = File.exist?("config/cable.yml") - rack_cors_config_exist = File.exist?("config/initializers/cors.rb") - assets_config_exist = File.exist?("config/initializers/assets.rb") - new_framework_defaults_5_1_exist = File.exist?("config/initializers/new_framework_defaults_5_1.rb") - - config - - unless cookie_serializer_config_exist - gsub_file "config/initializers/cookies_serializer.rb", /json(?!,)/, "marshal" - end - - unless action_cable_config_exist - template "config/cable.yml" - end - - unless rack_cors_config_exist - remove_file "config/initializers/cors.rb" - end - - if options[:api] - unless cookie_serializer_config_exist - remove_file "config/initializers/cookies_serializer.rb" - end - - unless assets_config_exist - remove_file "config/initializers/assets.rb" - end - - # Sprockets owns the only new default for 5.1: - # In API-only Applications, we don't want the file. - unless new_framework_defaults_5_1_exist - remove_file "config/initializers/new_framework_defaults_5_1.rb" - end - end - end - - def database_yml - template "config/databases/#{options[:database]}.yml", "config/database.yml" - end - - def db - directory "db" - end - - def lib - empty_directory "lib" - empty_directory_with_keep_file "lib/tasks" - empty_directory_with_keep_file "lib/assets" - end - - def log - empty_directory_with_keep_file "log" - end - - def public_directory - directory "public", "public", recursive: false - end - - def test - empty_directory_with_keep_file "test/fixtures" - empty_directory_with_keep_file "test/fixtures/files" - empty_directory_with_keep_file "test/controllers" - empty_directory_with_keep_file "test/mailers" - empty_directory_with_keep_file "test/models" - empty_directory_with_keep_file "test/helpers" - empty_directory_with_keep_file "test/integration" - - template "test/test_helper.rb" - end - - def system_test - empty_directory_with_keep_file "test/system" - - template "test/application_system_test_case.rb" - end - - def tmp - empty_directory_with_keep_file "tmp" - empty_directory "tmp/cache" - empty_directory "tmp/cache/assets" - end - - def vendor - empty_directory_with_keep_file "vendor" - - unless options[:skip_yarn] - template "package.json" - end - end - end - - module Generators - # We need to store the RAILS_DEV_PATH in a constant, otherwise the path - # can change in Ruby 1.8.7 when we FileUtils.cd. - RAILS_DEV_PATH = File.expand_path("../../../../../..", File.dirname(__FILE__)) - RESERVED_NAMES = %w[application destroy plugin runner test] - - class AppGenerator < AppBase # :nodoc: - WEBPACKS = %w( react vue angular ) - - add_shared_options_for "application" - - # Add bin/rails options - class_option :version, type: :boolean, aliases: "-v", group: :rails, - desc: "Show Rails version number and quit" - - class_option :api, type: :boolean, - desc: "Preconfigure smaller stack for API only apps" - - class_option :skip_bundle, type: :boolean, aliases: "-B", default: false, - desc: "Don't run bundle install" - - class_option :webpack, type: :string, default: nil, - desc: "Preconfigure for app-like JavaScript with Webpack (options: #{WEBPACKS.join('/')})" - - def initialize(*args) - super - - if !options[:skip_active_record] && !DATABASES.include?(options[:database]) - raise Error, "Invalid value for --database option. Supported for preconfiguration are: #{DATABASES.join(", ")}." - end - - # Force sprockets and yarn to be skipped when generating API only apps. - # Can't modify options hash as it's frozen by default. - if options[:api] - self.options = options.merge(skip_sprockets: true, skip_javascript: true, skip_yarn: true).freeze - end - end - - public_task :set_default_accessors! - public_task :create_root - - def create_root_files - build(:readme) - build(:rakefile) - build(:configru) - build(:gitignore) unless options[:skip_git] - build(:gemfile) unless options[:skip_gemfile] - build(:version_control) - end - - def create_app_files - build(:app) - end - - def create_bin_files - build(:bin) - end - - def update_bin_files - build(:bin_when_updating) - end - remove_task :update_bin_files - - def create_config_files - build(:config) - end - - def update_config_files - build(:config_when_updating) - end - remove_task :update_config_files - - def display_upgrade_guide_info - say "\nAfter this, check Rails upgrade guide at http://guides.rubyonrails.org/upgrading_ruby_on_rails.html for more details about upgrading your app." - end - remove_task :display_upgrade_guide_info - - def create_boot_file - template "config/boot.rb" - end - - def create_active_record_files - return if options[:skip_active_record] - build(:database_yml) - end - - def create_db_files - return if options[:skip_active_record] - build(:db) - end - - def create_lib_files - build(:lib) - end - - def create_log_files - build(:log) - end - - def create_public_files - build(:public_directory) - end - - def create_test_files - build(:test) unless options[:skip_test] - end - - def create_system_test_files - build(:system_test) if depends_on_system_test? - end - - def create_tmp_files - build(:tmp) - end - - def create_vendor_files - build(:vendor) - end - - def delete_app_assets_if_api_option - if options[:api] - remove_dir "app/assets" - remove_dir "lib/assets" - remove_dir "tmp/cache/assets" - end - end - - def delete_app_helpers_if_api_option - if options[:api] - remove_dir "app/helpers" - remove_dir "test/helpers" - end - end - - def delete_application_layout_file_if_api_option - if options[:api] - remove_file "app/views/layouts/application.html.erb" - end - end - - def delete_public_files_if_api_option - if options[:api] - remove_file "public/404.html" - remove_file "public/422.html" - remove_file "public/500.html" - remove_file "public/apple-touch-icon-precomposed.png" - remove_file "public/apple-touch-icon.png" - remove_file "public/favicon.ico" - end - end - - def delete_js_folder_skipping_javascript - if options[:skip_javascript] - remove_dir "app/assets/javascripts" - end - end - - def delete_assets_initializer_skipping_sprockets - if options[:skip_sprockets] - remove_file "config/initializers/assets.rb" - end - end - - def delete_application_record_skipping_active_record - if options[:skip_active_record] - remove_file "app/models/application_record.rb" - end - end - - def delete_action_mailer_files_skipping_action_mailer - if options[:skip_action_mailer] - remove_file "app/views/layouts/mailer.html.erb" - remove_file "app/views/layouts/mailer.text.erb" - remove_dir "app/mailers" - remove_dir "test/mailers" - end - end - - def delete_action_cable_files_skipping_action_cable - if options[:skip_action_cable] - remove_file "config/cable.yml" - remove_file "app/assets/javascripts/cable.js" - remove_dir "app/channels" - end - end - - def delete_non_api_initializers_if_api_option - if options[:api] - remove_file "config/initializers/cookies_serializer.rb" - end - end - - def delete_api_initializers - unless options[:api] - remove_file "config/initializers/cors.rb" - end - end - - def delete_new_framework_defaults - unless options[:update] - remove_file "config/initializers/new_framework_defaults_5_1.rb" - end - end - - def delete_bin_yarn_if_skip_yarn_option - remove_file "bin/yarn" if options[:skip_yarn] - end - - def finish_template - build(:leftovers) - end - - public_task :apply_rails_template, :run_bundle - public_task :run_webpack, :generate_spring_binstubs - - def run_after_bundle_callbacks - @after_bundle_callbacks.each(&:call) - end - - def self.banner - "rails new #{arguments.map(&:usage).join(' ')} [options]" - end - - private - - # Define file as an alias to create_file for backwards compatibility. - def file(*args, &block) - create_file(*args, &block) - end - - def app_name - @app_name ||= (defined_app_const_base? ? defined_app_name : File.basename(destination_root)).tr('\\', "").tr(". ", "_") - end - - def defined_app_name - defined_app_const_base.underscore - end - - def defined_app_const_base - Rails.respond_to?(:application) && defined?(Rails::Application) && - Rails.application.is_a?(Rails::Application) && Rails.application.class.name.sub(/::Application$/, "") - end - - alias :defined_app_const_base? :defined_app_const_base - - def app_const_base - @app_const_base ||= defined_app_const_base || app_name.gsub(/\W/, "_").squeeze("_").camelize - end - alias :camelized :app_const_base - - def app_const - @app_const ||= "#{app_const_base}::Application" - end - - def valid_const? - if app_const =~ /^\d/ - raise Error, "Invalid application name #{app_name}. Please give a name which does not start with numbers." - elsif RESERVED_NAMES.include?(app_name) - raise Error, "Invalid application name #{app_name}. Please give a " \ - "name which does not match one of the reserved rails " \ - "words: #{RESERVED_NAMES.join(", ")}" - elsif Object.const_defined?(app_const_base) - raise Error, "Invalid application name #{app_name}, constant #{app_const_base} is already in use. Please choose another application name." - end - end - - def app_secret - SecureRandom.hex(64) - end - - def mysql_socket - @mysql_socket ||= [ - "/tmp/mysql.sock", # default - "/var/run/mysqld/mysqld.sock", # debian/gentoo - "/var/tmp/mysql.sock", # freebsd - "/var/lib/mysql/mysql.sock", # fedora - "/opt/local/lib/mysql/mysql.sock", # fedora - "/opt/local/var/run/mysqld/mysqld.sock", # mac + darwinports + mysql - "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4 - "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5 - "/opt/lampp/var/mysql/mysql.sock" # xampp for linux - ].find { |f| File.exist?(f) } unless Gem.win_platform? - end - - def get_builder_class - defined?(::AppBuilder) ? ::AppBuilder : Rails::AppBuilder - end - end - - # This class handles preparation of the arguments before the AppGenerator is - # called. The class provides version or help information if they were - # requested, and also constructs the railsrc file (used for extra configuration - # options). - # - # This class should be called before the AppGenerator is required and started - # since it configures and mutates ARGV correctly. - class ARGVScrubber # :nodoc: - def initialize(argv = ARGV) - @argv = argv - end - - def prepare! - handle_version_request!(@argv.first) - handle_invalid_command!(@argv.first, @argv) do - handle_rails_rc!(@argv.drop(1)) - end - end - - def self.default_rc_file - File.expand_path("~/.railsrc") - end - - private - - def handle_version_request!(argument) - if ["--version", "-v"].include?(argument) - require "rails/version" - puts "Rails #{Rails::VERSION::STRING}" - exit(0) - end - end - - def handle_invalid_command!(argument, argv) - if argument == "new" - yield - else - ["--help"] + argv.drop(1) - end - end - - def handle_rails_rc!(argv) - if argv.find { |arg| arg == "--no-rc" } - argv.reject { |arg| arg == "--no-rc" } - else - railsrc(argv) { |rc_argv, rc| insert_railsrc_into_argv!(rc_argv, rc) } - end - end - - def railsrc(argv) - if (customrc = argv.index { |x| x.include?("--rc=") }) - fname = File.expand_path(argv[customrc].gsub(/--rc=/, "")) - yield(argv.take(customrc) + argv.drop(customrc + 1), fname) - else - yield argv, self.class.default_rc_file - end - end - - def read_rc_file(railsrc) - extra_args = File.readlines(railsrc).flat_map(&:split) - puts "Using #{extra_args.join(" ")} from #{railsrc}" - extra_args - end - - def insert_railsrc_into_argv!(argv, railsrc) - return argv unless File.exist?(railsrc) - extra_args = read_rc_file railsrc - argv.take(1) + extra_args + argv.drop(1) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/Gemfile b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/Gemfile deleted file mode 100644 index 3753bcc25a..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/Gemfile +++ /dev/null @@ -1,65 +0,0 @@ -source 'https://rubygems.org' - -git_source(:github) do |repo_name| - repo_name = "#{repo_name}/#{repo_name}" unless repo_name.include?("/") - "https://github.com/#{repo_name}.git" -end - -<% gemfile_entries.each do |gem| -%> -<% if gem.comment -%> - -# <%= gem.comment %> -<% end -%> -<%= gem.commented_out ? '# ' : '' %>gem '<%= gem.name %>'<%= %(, '#{gem.version}') if gem.version -%> -<% if gem.options.any? -%> -, <%= gem.options.map { |k,v| - "#{k}: #{v.inspect}" }.join(', ') %> -<% end -%> -<% end -%> - -# Use ActiveModel has_secure_password -# gem 'bcrypt', '~> 3.1.7' - -# Use Capistrano for deployment -# gem 'capistrano-rails', group: :development - -<%- if options.api? -%> -# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible -# gem 'rack-cors' - -<%- end -%> -<% if RUBY_ENGINE == 'ruby' -%> -group :development, :test do - # Call 'byebug' anywhere in the code to stop execution and get a debugger console - gem 'byebug', platforms: [:mri, :mingw, :x64_mingw] - <%- if depends_on_system_test? -%> - # Adds support for Capybara system testing and selenium driver - gem 'capybara', '>= 2.15' - gem 'selenium-webdriver' - <%- end -%> -end - -group :development do -<%- unless options.api? -%> - # Access an IRB console on exception pages or by using <%%= console %> anywhere in the code. - <%- if options.dev? || options.edge? -%> - gem 'web-console', github: 'rails/web-console' - <%- else -%> - gem 'web-console', '>= 3.3.0' - <%- end -%> -<%- end -%> -<% if depend_on_listen? -%> - gem 'listen', '>= 3.0.5', '< 3.2' -<% end -%> -<% if spring_install? -%> - # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring - gem 'spring' -<% if depend_on_listen? -%> - gem 'spring-watcher-listen', '~> 2.0.0' -<% end -%> -<% end -%> -end -<% end -%> - -# Windows does not include zoneinfo files, so bundle the tzinfo-data gem -gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/README.md b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/README.md deleted file mode 100644 index 7db80e4ca1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# README - -This README would normally document whatever steps are necessary to get the -application up and running. - -Things you may want to cover: - -* Ruby version - -* System dependencies - -* Configuration - -* Database creation - -* Database initialization - -* How to run the test suite - -* Services (job queues, cache servers, search engines, etc.) - -* Deployment instructions - -* ... diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/Rakefile b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/Rakefile deleted file mode 100644 index e85f913914..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/Rakefile +++ /dev/null @@ -1,6 +0,0 @@ -# Add your own tasks in files placed in lib/tasks ending in .rake, -# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. - -require_relative 'config/application' - -Rails.application.load_tasks diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt deleted file mode 100644 index 70b579d10e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt +++ /dev/null @@ -1,5 +0,0 @@ -//= link_tree ../images -<% unless options.skip_javascript -%> -//= link_directory ../javascripts .js -<% end -%> -//= link_directory ../stylesheets .css diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt deleted file mode 100644 index 4206002a1b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +++ /dev/null @@ -1,19 +0,0 @@ -// This is a manifest file that'll be compiled into application.js, which will include all the files -// listed below. -// -// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's -// vendor/assets/javascripts directory can be referenced here using a relative path. -// -// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the -// compiled file. JavaScript code in this file should be added after the last require_* statement. -// -// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details -// about supported directives. -// -<% unless options[:skip_javascript] -%> -//= require rails-ujs -<% unless options[:skip_turbolinks] -%> -//= require turbolinks -<% end -%> -<% end -%> -//= require_tree . diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js deleted file mode 100644 index 739aa5f022..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js +++ /dev/null @@ -1,13 +0,0 @@ -// Action Cable provides the framework to deal with WebSockets in Rails. -// You can generate new channels where WebSocket features live using the `rails generate channel` command. -// -//= require action_cable -//= require_self -//= require_tree ./channels - -(function() { - this.App || (this.App = {}); - - App.cable = ActionCable.createConsumer(); - -}).call(this); diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css deleted file mode 100644 index d05ea0f511..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css +++ /dev/null @@ -1,15 +0,0 @@ -/* - * This is a manifest file that'll be compiled into application.css, which will include all the files - * listed below. - * - * Any CSS and SCSS file within this directory, lib/assets/stylesheets, or any plugin's - * vendor/assets/stylesheets directory can be referenced here using a relative path. - * - * You're free to add application-wide styles to this file and they'll appear at the bottom of the - * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS - * files in this directory. Styles in this file should be added after the last require_* statement. - * It is generally better to create a new file per style scope. - * - *= require_tree . - *= require_self - */ diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb deleted file mode 100644 index d672697283..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb +++ /dev/null @@ -1,4 +0,0 @@ -module ApplicationCable - class Channel < ActionCable::Channel::Base - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb deleted file mode 100644 index 0ff5442f47..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb +++ /dev/null @@ -1,4 +0,0 @@ -module ApplicationCable - class Connection < ActionCable::Connection::Base - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt deleted file mode 100644 index 413354186d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt +++ /dev/null @@ -1,5 +0,0 @@ -class ApplicationController < ActionController::<%= options[:api] ? "API" : "Base" %> -<%- unless options[:api] -%> - protect_from_forgery with: :exception -<%- end -%> -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb deleted file mode 100644 index de6be7945c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -module ApplicationHelper -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb deleted file mode 100644 index a009ace51c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/jobs/application_job.rb +++ /dev/null @@ -1,2 +0,0 @@ -class ApplicationJob < ActiveJob::Base -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb deleted file mode 100644 index 286b2239d1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb +++ /dev/null @@ -1,4 +0,0 @@ -class ApplicationMailer < ActionMailer::Base - default from: 'from@example.com' - layout 'mailer' -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/models/application_record.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/models/application_record.rb deleted file mode 100644 index 10a4cba84d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/models/application_record.rb +++ /dev/null @@ -1,3 +0,0 @@ -class ApplicationRecord < ActiveRecord::Base - self.abstract_class = true -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt deleted file mode 100644 index 5460155b3e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt +++ /dev/null @@ -1,23 +0,0 @@ - - - - <%= camelized %> - <%%= csrf_meta_tags %> - - <%- if options[:skip_javascript] -%> - <%%= stylesheet_link_tag 'application', media: 'all' %> - <%- else -%> - <%- unless options[:skip_turbolinks] -%> - <%%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %> - <%%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> - <%- else -%> - <%%= stylesheet_link_tag 'application', media: 'all' %> - <%%= javascript_include_tag 'application' %> - <%- end -%> - <%- end -%> - - - - <%%= yield %> - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt deleted file mode 100644 index 55f3675d49..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - <%%= yield %> - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt deleted file mode 100644 index 6363733e6e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt +++ /dev/null @@ -1 +0,0 @@ -<%%= yield %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/bundle b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/bundle deleted file mode 100644 index 1123dcf501..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/bundle +++ /dev/null @@ -1,2 +0,0 @@ -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) -load Gem.bin_path('bundler', 'bundle') diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/rails b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/rails deleted file mode 100644 index 513a2e0183..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/rails +++ /dev/null @@ -1,3 +0,0 @@ -APP_PATH = File.expand_path('../config/application', __dir__) -require_relative '../config/boot' -require 'rails/commands' diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/rake b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/rake deleted file mode 100644 index d14fc8395b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/rake +++ /dev/null @@ -1,3 +0,0 @@ -require_relative '../config/boot' -require 'rake' -Rake.application.run diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/setup.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/setup.tt deleted file mode 100644 index 52b3de5ee5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/setup.tt +++ /dev/null @@ -1,39 +0,0 @@ -require 'pathname' -require 'fileutils' -include FileUtils - -# path to your application root. -APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) - -def system!(*args) - system(*args) || abort("\n== Command #{args} failed ==") -end - -chdir APP_ROOT do - # This script is a starting point to setup your application. - # Add necessary setup steps to this file. - - puts '== Installing dependencies ==' - system! 'gem install bundler --conservative' - system('bundle check') || system!('bundle install') -<% unless options[:skip_yarn] %> - # Install JavaScript dependencies if using Yarn - # system('bin/yarn') -<% end %> -<% unless options.skip_active_record -%> - - # puts "\n== Copying sample files ==" - # unless File.exist?('config/database.yml') - # cp 'config/database.yml.sample', 'config/database.yml' - # end - - puts "\n== Preparing database ==" - system! 'bin/rails db:setup' -<% end -%> - - puts "\n== Removing old logs and tempfiles ==" - system! 'bin/rails log:clear tmp:clear' - - puts "\n== Restarting application server ==" - system! 'bin/rails restart' -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/update.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/update.tt deleted file mode 100644 index d385b363c6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/update.tt +++ /dev/null @@ -1,30 +0,0 @@ -require 'pathname' -require 'fileutils' -include FileUtils - -# path to your application root. -APP_ROOT = Pathname.new File.expand_path('../../', __FILE__) - -def system!(*args) - system(*args) || abort("\n== Command #{args} failed ==") -end - -chdir APP_ROOT do - # This script is a way to update your development environment automatically. - # Add necessary update steps to this file. - - puts '== Installing dependencies ==' - system! 'gem install bundler --conservative' - system('bundle check') || system!('bundle install') -<% unless options.skip_active_record -%> - - puts "\n== Updating database ==" - system! 'bin/rails db:migrate' -<% end -%> - - puts "\n== Removing old logs and tempfiles ==" - system! 'bin/rails log:clear tmp:clear' - - puts "\n== Restarting application server ==" - system! 'bin/rails restart' -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/yarn b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/yarn deleted file mode 100644 index 44f75c22a4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/bin/yarn +++ /dev/null @@ -1,10 +0,0 @@ -VENDOR_PATH = File.expand_path('..', __dir__) -Dir.chdir(VENDOR_PATH) do - begin - exec "yarnpkg #{ARGV.join(" ")}" - rescue Errno::ENOENT - $stderr.puts "Yarn executable was not detected in the system." - $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" - exit 1 - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config.ru b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config.ru deleted file mode 100644 index f7ba0b527b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config.ru +++ /dev/null @@ -1,5 +0,0 @@ -# This file is used by Rack-based servers to start the application. - -require_relative 'config/environment' - -run Rails.application diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/application.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/application.rb deleted file mode 100644 index 0b1d22228e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/application.rb +++ /dev/null @@ -1,43 +0,0 @@ -require_relative 'boot' - -<% if include_all_railties? -%> -require 'rails/all' -<% else -%> -require "rails" -# Pick the frameworks you want: -require "active_model/railtie" -require "active_job/railtie" -<%= comment_if :skip_active_record %>require "active_record/railtie" -require "action_controller/railtie" -<%= comment_if :skip_action_mailer %>require "action_mailer/railtie" -require "action_view/railtie" -<%= comment_if :skip_action_cable %>require "action_cable/engine" -<%= comment_if :skip_sprockets %>require "sprockets/railtie" -<%= comment_if :skip_test %>require "rails/test_unit/railtie" -<% end -%> - -# Require the gems listed in Gemfile, including any gems -# you've limited to :test, :development, or :production. -Bundler.require(*Rails.groups) - -module <%= app_const_base %> - class Application < Rails::Application - # Initialize configuration defaults for originally generated Rails version. - config.load_defaults <%= Rails::VERSION::STRING.to_f %> - - # Settings in config/environments/* take precedence over those specified here. - # Application configuration should go into files in config/initializers - # -- all .rb files in that directory are automatically loaded. -<%- if options[:api] -%> - - # Only loads a smaller set of middleware suitable for API only apps. - # Middleware like session, flash, cookies can be added back manually. - # Skip views, helpers and assets when generating a new resource. - config.api_only = true -<%- elsif !depends_on_system_test? -%> - - # Don't generate system test files. - config.generators.system_tests = nil -<%- end -%> - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/boot.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/boot.rb deleted file mode 100644 index 30f5120df6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/boot.rb +++ /dev/null @@ -1,3 +0,0 @@ -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) - -require 'bundler/setup' # Set up gems listed in the Gemfile. diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/cable.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/cable.yml deleted file mode 100644 index 1da4913082..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/cable.yml +++ /dev/null @@ -1,10 +0,0 @@ -development: - adapter: async - -test: - adapter: async - -production: - adapter: redis - url: redis://localhost:6379/1 - channel_prefix: <%= app_name %>_production diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml deleted file mode 100644 index 917b52e535..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/frontbase.yml +++ /dev/null @@ -1,50 +0,0 @@ -# FrontBase versions 4.x -# -# Get the bindings: -# gem install ruby-frontbase -# -# Configure Using Gemfile -# gem 'ruby-frontbase' -# -default: &default - adapter: frontbase - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - host: localhost - username: <%= app_name %> - password: '' - -development: - <<: *default - database: <%= app_name %>_development - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="frontbase://myuser:mypass@localhost/somedatabase" -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml deleted file mode 100644 index d40117a27f..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml +++ /dev/null @@ -1,86 +0,0 @@ -# IBM Dataservers -# -# Home Page -# https://github.com/dparnell/ibm_db -# -# To install the ibm_db gem: -# -# On Linux: -# . /home/db2inst1/sqllib/db2profile -# export IBM_DB_INCLUDE=/opt/ibm/db2/V9.7/include -# export IBM_DB_LIB=/opt/ibm/db2/V9.7/lib32 -# gem install ibm_db -# -# On Mac OS X 10.5: -# . /home/db2inst1/sqllib/db2profile -# export IBM_DB_INCLUDE=/opt/ibm/db2/V9.7/include -# export IBM_DB_LIB=/opt/ibm/db2/V9.7/lib32 -# export ARCHFLAGS="-arch i386" -# gem install ibm_db -# -# On Mac OS X 10.6: -# . /home/db2inst1/sqllib/db2profile -# export IBM_DB_INCLUDE=/opt/ibm/db2/V9.7/include -# export IBM_DB_LIB=/opt/ibm/db2/V9.7/lib64 -# export ARCHFLAGS="-arch x86_64" -# gem install ibm_db -# -# On Windows: -# Issue the command: gem install ibm_db -# -# Configure Using Gemfile -# gem 'ibm_db' -# -# -default: &default - adapter: ibm_db - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - username: db2inst1 - password: - #schema: db2inst1 - #host: localhost - #port: 50000 - #account: my_account - #app_user: my_app_user - #application: my_application - #workstation: my_workstation - #security: SSL - #timeout: 10 - #authentication: SERVER - #parameterized: false - -development: - <<: *default - database: <%= app_name[0,4] %>_dev - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name[0,4] %>_tst - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="ibm-db://myuser:mypass@localhost/somedatabase" -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml deleted file mode 100644 index 563be77710..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbc.yml +++ /dev/null @@ -1,69 +0,0 @@ -# If you are using mssql, derby, hsqldb, or h2 with one of the -# ActiveRecord JDBC adapters, install the appropriate driver, e.g.,: -# gem install activerecord-jdbcmssql-adapter -# -# Configure using Gemfile: -# gem 'activerecord-jdbcmssql-adapter' -# -# development: -# adapter: mssql -# username: <%= app_name %> -# password: -# host: localhost -# database: <%= app_name %>_development -# -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -# -# test: -# adapter: mssql -# username: <%= app_name %> -# password: -# host: localhost -# database: <%= app_name %>_test -# -# production: -# adapter: mssql -# username: <%= app_name %> -# password: -# host: localhost -# database: <%= app_name %>_production - -# If you are using oracle, db2, sybase, informix or prefer to use the plain -# JDBC adapter, configure your database setting as the example below (requires -# you to download and manually install the database vendor's JDBC driver .jar -# file). See your driver documentation for the appropriate driver class and -# connection string: - -default: &default - adapter: jdbc - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - username: <%= app_name %> - password: - driver: - -development: - <<: *default - url: jdbc:db://localhost/<%= app_name %>_development - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - url: jdbc:db://localhost/<%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -production: - url: jdbc:db://localhost/<%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml deleted file mode 100644 index 8bc8735a8e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml +++ /dev/null @@ -1,53 +0,0 @@ -# MySQL. Versions 5.1.10 and up are supported. -# -# Install the MySQL driver: -# gem install activerecord-jdbcmysql-adapter -# -# Configure Using Gemfile -# gem 'activerecord-jdbcmysql-adapter' -# -# And be sure to use new-style password hashing: -# http://dev.mysql.com/doc/refman/5.7/en/old-client.html -# -default: &default - adapter: mysql - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - username: root - password: - host: localhost - -development: - <<: *default - database: <%= app_name %>_development - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="mysql://myuser:mypass@localhost/somedatabase" -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml deleted file mode 100644 index 70df04079d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml +++ /dev/null @@ -1,69 +0,0 @@ -# PostgreSQL. Versions 9.1 and up are supported. -# -# Configure Using Gemfile -# gem 'activerecord-jdbcpostgresql-adapter' -# -default: &default - adapter: postgresql - encoding: unicode - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - -development: - <<: *default - database: <%= app_name %>_development - - # The specified database role being used to connect to postgres. - # To create additional roles in postgres see `$ createuser --help`. - # When left blank, postgres will use the default role. This is - # the same name as the operating system user that initialized the database. - #username: <%= app_name %> - - # The password associated with the postgres role (username). - #password: - - # Connect on a TCP socket. Omitted by default since the client uses a - # domain socket that doesn't need configuration. Windows does not have - # domain sockets, so uncomment these lines. - #host: localhost - #port: 5432 - - # Schema search path. The server defaults to $user,public - #schema_search_path: myapp,sharedapp,public - - # Minimum log levels, in increasing order: - # debug5, debug4, debug3, debug2, debug1, - # log, notice, warning, error, fatal, and panic - # Defaults to warning. - #min_messages: notice - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml deleted file mode 100644 index 371415e6a8..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml +++ /dev/null @@ -1,24 +0,0 @@ -# SQLite version 3.x -# gem 'activerecord-jdbcsqlite3-adapter' -# -# Configure Using Gemfile -# gem 'activerecord-jdbcsqlite3-adapter' -# -default: &default - adapter: sqlite3 - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - -development: - <<: *default - database: db/development.sqlite3 - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: db/test.sqlite3 - -production: - <<: *default - database: db/production.sqlite3 diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/mysql.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/mysql.yml deleted file mode 100644 index 269af1470d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/mysql.yml +++ /dev/null @@ -1,58 +0,0 @@ -# MySQL. Versions 5.1.10 and up are supported. -# -# Install the MySQL driver -# gem install mysql2 -# -# Ensure the MySQL gem is defined in your Gemfile -# gem 'mysql2' -# -# And be sure to use new-style password hashing: -# http://dev.mysql.com/doc/refman/5.7/en/old-client.html -# -default: &default - adapter: mysql2 - encoding: utf8 - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - username: root - password: -<% if mysql_socket -%> - socket: <%= mysql_socket %> -<% else -%> - host: localhost -<% end -%> - -development: - <<: *default - database: <%= app_name %>_development - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="mysql2://myuser:mypass@localhost/somedatabase" -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/oracle.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/oracle.yml deleted file mode 100644 index 6da0601b24..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/oracle.yml +++ /dev/null @@ -1,61 +0,0 @@ -# Oracle/OCI 11g or higher recommended -# -# Requires Ruby/OCI8: -# https://github.com/kubo/ruby-oci8 -# -# Specify your database using any valid connection syntax, such as a -# tnsnames.ora service name, or an SQL connect string of the form: -# -# //host:[port][/service name] -# -# By default prefetch_rows (OCI_ATTR_PREFETCH_ROWS) is set to 100. And -# until true bind variables are supported, cursor_sharing is set by default -# to 'similar'. Both can be changed in the configuration below; the defaults -# are equivalent to specifying: -# -# prefetch_rows: 100 -# cursor_sharing: similar -# -default: &default - adapter: oracle_enhanced - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - username: <%= app_name %> - password: - -development: - <<: *default - database: <%= app_name %>_development - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="oracle-enhanced://myuser:mypass@localhost/somedatabase" -# -# Note that the adapter name uses a dash instead of an underscore. -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml deleted file mode 100644 index 145cfb7f74..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/postgresql.yml +++ /dev/null @@ -1,85 +0,0 @@ -# PostgreSQL. Versions 9.1 and up are supported. -# -# Install the pg driver: -# gem install pg -# On OS X with Homebrew: -# gem install pg -- --with-pg-config=/usr/local/bin/pg_config -# On OS X with MacPorts: -# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config -# On Windows: -# gem install pg -# Choose the win32 build. -# Install PostgreSQL and put its /bin directory on your path. -# -# Configure Using Gemfile -# gem 'pg' -# -default: &default - adapter: postgresql - encoding: unicode - # For details on connection pooling, see Rails configuration guide - # http://guides.rubyonrails.org/configuring.html#database-pooling - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - -development: - <<: *default - database: <%= app_name %>_development - - # The specified database role being used to connect to postgres. - # To create additional roles in postgres see `$ createuser --help`. - # When left blank, postgres will use the default role. This is - # the same name as the operating system user that initialized the database. - #username: <%= app_name %> - - # The password associated with the postgres role (username). - #password: - - # Connect on a TCP socket. Omitted by default since the client uses a - # domain socket that doesn't need configuration. Windows does not have - # domain sockets, so uncomment these lines. - #host: localhost - - # The TCP port the server listens on. Defaults to 5432. - # If your server runs on a different port number, change accordingly. - #port: 5432 - - # Schema search path. The server defaults to $user,public - #schema_search_path: myapp,sharedapp,public - - # Minimum log levels, in increasing order: - # debug5, debug4, debug3, debug2, debug1, - # log, notice, warning, error, fatal, and panic - # Defaults to warning. - #min_messages: notice - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml deleted file mode 100644 index 9510568124..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml +++ /dev/null @@ -1,25 +0,0 @@ -# SQLite version 3.x -# gem install sqlite3 -# -# Ensure the SQLite 3 gem is defined in your Gemfile -# gem 'sqlite3' -# -default: &default - adapter: sqlite3 - pool: <%%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> - timeout: 5000 - -development: - <<: *default - database: db/development.sqlite3 - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: db/test.sqlite3 - -production: - <<: *default - database: db/production.sqlite3 diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml deleted file mode 100644 index a21555e573..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml +++ /dev/null @@ -1,52 +0,0 @@ -# SQL Server (2012 or higher recommended) -# -# Install the adapters and driver -# gem install tiny_tds -# gem install activerecord-sqlserver-adapter -# -# Ensure the activerecord adapter and db driver gems are defined in your Gemfile -# gem 'tiny_tds' -# gem 'activerecord-sqlserver-adapter' -# -default: &default - adapter: sqlserver - encoding: utf8 - username: sa - password: <%= ENV['SA_PASSWORD'] %> - host: localhost - -development: - <<: *default - database: <%= app_name %>_development - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: <%= app_name %>_test - -# As with config/secrets.yml, you never want to store sensitive information, -# like your database password, in your source code. If your source code is -# ever seen by anyone, they now have access to your database. -# -# Instead, provide the password as a unix environment variable when you boot -# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database -# for a full rundown on how to provide these environment variables in a -# production deployment. -# -# On Heroku and other platform providers, you may have a full connection URL -# available as an environment variable. For example: -# -# DATABASE_URL="sqlserver://myuser:mypass@localhost/somedatabase" -# -# You can use this database configuration with: -# -# production: -# url: <%%= ENV['DATABASE_URL'] %> -# -production: - <<: *default - database: <%= app_name %>_production - username: <%= app_name %> - password: <%%= ENV['<%= app_name.upcase %>_DATABASE_PASSWORD'] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environment.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environment.rb deleted file mode 100644 index 426333bb46..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environment.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Load the Rails application. -require_relative 'application' - -# Initialize the Rails application. -Rails.application.initialize! diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt deleted file mode 100644 index 511b4a82eb..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt +++ /dev/null @@ -1,60 +0,0 @@ -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # In the development environment your application's code is reloaded on - # every request. This slows down response time but is perfect for development - # since you don't have to restart the web server when you make code changes. - config.cache_classes = false - - # Do not eager load code on boot. - config.eager_load = false - - # Show full error reports. - config.consider_all_requests_local = true - - # Enable/disable caching. By default caching is disabled. - if Rails.root.join('tmp/caching-dev.txt').exist? - config.action_controller.perform_caching = true - - config.cache_store = :memory_store - config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" - } - else - config.action_controller.perform_caching = false - - config.cache_store = :null_store - end - <%- unless options.skip_action_mailer? -%> - - # Don't care if the mailer can't send. - config.action_mailer.raise_delivery_errors = false - - config.action_mailer.perform_caching = false - <%- end -%> - - # Print deprecation notices to the Rails logger. - config.active_support.deprecation = :log - - <%- unless options.skip_active_record? -%> - # Raise an error on page load if there are pending migrations. - config.active_record.migration_error = :page_load - - <%- end -%> - <%- unless options.skip_sprockets? -%> - # Debug mode disables concatenation and preprocessing of assets. - # This option may cause significant delays in view rendering with a large - # number of complex assets. - config.assets.debug = true - - # Suppress logger output for asset requests. - config.assets.quiet = true - <%- end -%> - - # Raises error for missing translations - # config.action_view.raise_on_missing_translations = true - - # Use an evented file watcher to asynchronously detect changes in source code, - # routes, locales, etc. This feature depends on the listen gem. - <%= '# ' unless depend_on_listen? %>config.file_watcher = ActiveSupport::EventedFileUpdateChecker -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt deleted file mode 100644 index 9c4a77fd1d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +++ /dev/null @@ -1,103 +0,0 @@ -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # Code is not reloaded between requests. - config.cache_classes = true - - # Eager load code on boot. This eager loads most of Rails and - # your application in memory, allowing both threaded web servers - # and those relying on copy on write to perform better. - # Rake tasks automatically ignore this option for performance. - config.eager_load = true - - # Full error reports are disabled and caching is turned on. - config.consider_all_requests_local = false - config.action_controller.perform_caching = true - - # Attempt to read encrypted secrets from `config/secrets.yml.enc`. - # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or - # `config/secrets.yml.key`. - config.read_encrypted_secrets = true - - # Disable serving static files from the `/public` folder by default since - # Apache or NGINX already handles this. - config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? - - <%- unless options.skip_sprockets? -%> - <%- if options.skip_javascript? -%> - # Compress CSS. - <%- else -%> - # Compress JavaScripts and CSS. - config.assets.js_compressor = :uglifier - <%- end -%> - # config.assets.css_compressor = :sass - - # Do not fallback to assets pipeline if a precompiled asset is missed. - config.assets.compile = false - - # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb - <%- end -%> - - # Enable serving of images, stylesheets, and JavaScripts from an asset server. - # config.action_controller.asset_host = 'http://assets.example.com' - - # Specifies the header that your server uses for sending files. - # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache - # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX - - <%- unless options[:skip_action_cable] -%> - # Mount Action Cable outside main process or domain - # config.action_cable.mount_path = nil - # config.action_cable.url = 'wss://example.com/cable' - # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] - <%- end -%> - - # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. - # config.force_ssl = true - - # Use the lowest log level to ensure availability of diagnostic information - # when problems arise. - config.log_level = :debug - - # Prepend all log lines with the following tags. - config.log_tags = [ :request_id ] - - # Use a different cache store in production. - # config.cache_store = :mem_cache_store - - # Use a real queuing backend for Active Job (and separate queues per environment) - # config.active_job.queue_adapter = :resque - # config.active_job.queue_name_prefix = "<%= app_name %>_#{Rails.env}" - <%- unless options.skip_action_mailer? -%> - config.action_mailer.perform_caching = false - - # Ignore bad email addresses and do not raise email delivery errors. - # Set this to true and configure the email server for immediate delivery to raise delivery errors. - # config.action_mailer.raise_delivery_errors = false - <%- end -%> - - # Enable locale fallbacks for I18n (makes lookups for any locale fall back to - # the I18n.default_locale when a translation cannot be found). - config.i18n.fallbacks = true - - # Send deprecation notices to registered listeners. - config.active_support.deprecation = :notify - - # Use default logging formatter so that PID and timestamp are not suppressed. - config.log_formatter = ::Logger::Formatter.new - - # Use a different logger for distributed setups. - # require 'syslog/logger' - # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') - - if ENV["RAILS_LOG_TO_STDOUT"].present? - logger = ActiveSupport::Logger.new(STDOUT) - logger.formatter = config.log_formatter - config.logger = ActiveSupport::TaggedLogging.new(logger) - end - <%- unless options.skip_active_record? -%> - - # Do not dump schema after migrations. - config.active_record.dump_schema_after_migration = false - <%- end -%> -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt deleted file mode 100644 index 56416b3075..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +++ /dev/null @@ -1,44 +0,0 @@ -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # The test environment is used exclusively to run your application's - # test suite. You never need to work with it otherwise. Remember that - # your test database is "scratch space" for the test suite and is wiped - # and recreated between test runs. Don't rely on the data there! - config.cache_classes = true - - # Do not eager load code on boot. This avoids loading your whole application - # just for the purpose of running a single test. If you are using a tool that - # preloads Rails for running tests, you may have to set it to true. - config.eager_load = false - - # Configure public file server for tests with Cache-Control for performance. - config.public_file_server.enabled = true - config.public_file_server.headers = { - 'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}" - } - - # Show full error reports and disable caching. - config.consider_all_requests_local = true - config.action_controller.perform_caching = false - - # Raise exceptions instead of rendering exception templates. - config.action_dispatch.show_exceptions = false - - # Disable request forgery protection in test environment. - config.action_controller.allow_forgery_protection = false - <%- unless options.skip_action_mailer? -%> - config.action_mailer.perform_caching = false - - # Tell Action Mailer not to deliver emails to the real world. - # The :test delivery method accumulates sent emails in the - # ActionMailer::Base.deliveries array. - config.action_mailer.delivery_method = :test - <%- end -%> - - # Print deprecation notices to the stderr. - config.active_support.deprecation = :stderr - - # Raises error for missing translations - # config.action_view.raise_on_missing_translations = true -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb deleted file mode 100644 index 89d2efab2b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb +++ /dev/null @@ -1,8 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# ActiveSupport::Reloader.to_prepare do -# ApplicationController.renderer.defaults.merge!( -# http_host: 'example.org', -# https: false -# ) -# end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt deleted file mode 100644 index 51196ae743..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt +++ /dev/null @@ -1,16 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Version of your assets, change this if you want to expire all your assets. -Rails.application.config.assets.version = '1.0' - -# Add additional assets to the asset load path. -# Rails.application.config.assets.paths << Emoji.images_path -<%- unless options[:skip_yarn] -%> -# Add Yarn node_modules folder to the asset load path. -Rails.application.config.assets.paths << Rails.root.join('node_modules') -<%- end -%> - -# Precompile additional assets. -# application.js, application.css, and all non-JS/CSS in the app/assets -# folder are already added. -# Rails.application.config.assets.precompile += %w( admin.js admin.css ) diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/backtrace_silencers.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/backtrace_silencers.rb deleted file mode 100644 index 59385cdf37..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/backtrace_silencers.rb +++ /dev/null @@ -1,7 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. -# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } - -# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. -# Rails.backtrace_cleaner.remove_silencers! diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb deleted file mode 100644 index 5a6a32d371..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Specify a serializer for the signed and encrypted cookie jars. -# Valid options are :json, :marshal, and :hybrid. -Rails.application.config.action_dispatch.cookies_serializer = :json diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/cors.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/cors.rb deleted file mode 100644 index 3b1c1b5ed1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/cors.rb +++ /dev/null @@ -1,16 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Avoid CORS issues when API is called from the frontend app. -# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. - -# Read more: https://github.com/cyu/rack-cors - -# Rails.application.config.middleware.insert_before 0, Rack::Cors do -# allow do -# origins 'example.com' -# -# resource '*', -# headers: :any, -# methods: [:get, :post, :put, :patch, :delete, :options, :head] -# end -# end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb deleted file mode 100644 index 4a994e1e7b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb +++ /dev/null @@ -1,4 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Configure sensitive parameters which will be filtered from the log file. -Rails.application.config.filter_parameters += [:password] diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb deleted file mode 100644 index ac033bf9dc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/inflections.rb +++ /dev/null @@ -1,16 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Add new inflection rules using the following format. Inflections -# are locale specific, and you may define rules for as many different -# locales as you wish. All of these examples are active by default: -# ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.plural /^(ox)$/i, '\1en' -# inflect.singular /^(ox)en/i, '\1' -# inflect.irregular 'person', 'people' -# inflect.uncountable %w( fish sheep ) -# end - -# These inflection rules are supported but not enabled by default: -# ActiveSupport::Inflector.inflections(:en) do |inflect| -# inflect.acronym 'RESTful' -# end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/mime_types.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/mime_types.rb deleted file mode 100644 index dc1899682b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/mime_types.rb +++ /dev/null @@ -1,4 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Add new mime types for use in respond_to blocks: -# Mime::Type.register "text/richtext", :rtf diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_5_1.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_5_1.rb.tt deleted file mode 100644 index a0c7f44b60..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_5_1.rb.tt +++ /dev/null @@ -1,16 +0,0 @@ -# Be sure to restart your server when you modify this file. -# -# This file contains migration options to ease your Rails 5.1 upgrade. -# -# Once upgraded flip defaults one by one to migrate to the new default. -# -# Read the Guide for Upgrading Ruby on Rails for more info on each option. - -# Make `form_with` generate non-remote forms. -Rails.application.config.action_view.form_with_generates_remote_forms = false -<%- unless options[:skip_sprockets] -%> - -# Unknown asset fallback will return the path passed in when the given -# asset is not present in the asset pipeline. -# Rails.application.config.assets.unknown_asset_fallback = false -<%- end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt deleted file mode 100644 index cadc85cfac..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt +++ /dev/null @@ -1,16 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# This file contains settings for ActionController::ParamsWrapper which -# is enabled by default. - -# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. -ActiveSupport.on_load(:action_controller) do - wrap_parameters format: [:json] -end -<%- unless options.skip_active_record? -%> - -# To enable root element in JSON for ActiveRecord objects. -# ActiveSupport.on_load(:active_record) do -# self.include_root_in_json = true -# end -<%- end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/locales/en.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/locales/en.yml deleted file mode 100644 index decc5a8573..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/locales/en.yml +++ /dev/null @@ -1,33 +0,0 @@ -# Files in the config/locales directory are used for internationalization -# and are automatically loaded by Rails. If you want to use locales other -# than English, add the necessary files in this directory. -# -# To use the locales, use `I18n.t`: -# -# I18n.t 'hello' -# -# In views, this is aliased to just `t`: -# -# <%= t('hello') %> -# -# To use a different locale, set it with `I18n.locale`: -# -# I18n.locale = :es -# -# This would use the information in config/locales/es.yml. -# -# The following keys must be escaped otherwise they will not be retrieved by -# the default I18n backend: -# -# true, false, on, off, yes, no -# -# Instead, surround them with single quotes. -# -# en: -# 'true': 'foo' -# -# To learn more, please read the Rails Internationalization guide -# available at http://guides.rubyonrails.org/i18n.html. - -en: - hello: "Hello world" diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/puma.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/puma.rb deleted file mode 100644 index 1e19380dcb..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/puma.rb +++ /dev/null @@ -1,56 +0,0 @@ -# Puma can serve each request in a thread from an internal thread pool. -# The `threads` method setting takes two numbers: a minimum and maximum. -# Any libraries that use thread pools should be configured to match -# the maximum value specified for Puma. Default is set to 5 threads for minimum -# and maximum; this matches the default thread size of Active Record. -# -threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } -threads threads_count, threads_count - -# Specifies the `port` that Puma will listen on to receive requests; default is 3000. -# -port ENV.fetch("PORT") { 3000 } - -# Specifies the `environment` that Puma will run in. -# -environment ENV.fetch("RAILS_ENV") { "development" } - -# Specifies the number of `workers` to boot in clustered mode. -# Workers are forked webserver processes. If using threads and workers together -# the concurrency of the application would be max `threads` * `workers`. -# Workers do not work on JRuby or Windows (both of which do not support -# processes). -# -# workers ENV.fetch("WEB_CONCURRENCY") { 2 } - -# Use the `preload_app!` method when specifying a `workers` number. -# This directive tells Puma to first boot the application and load code -# before forking the application. This takes advantage of Copy On Write -# process behavior so workers use less memory. If you use this option -# you need to make sure to reconnect any threads in the `on_worker_boot` -# block. -# -# preload_app! - -# If you are preloading your application and using Active Record, it's -# recommended that you close any connections to the database before workers -# are forked to prevent connection leakage. -# -# before_fork do -# ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord) -# end - -# The code in the `on_worker_boot` will be called if you are using -# clustered mode by specifying a number of `workers`. After each worker -# process is booted, this block will be run. If you are using the `preload_app!` -# option, you will want to use this block to reconnect to any threads -# or connections that may have been created at application boot, as Ruby -# cannot share connections between processes. -# -# on_worker_boot do -# ActiveRecord::Base.establish_connection if defined?(ActiveRecord) -# end -# - -# Allow puma to be restarted by `rails restart` command. -plugin :tmp_restart diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/routes.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/routes.rb deleted file mode 100644 index 787824f888..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/routes.rb +++ /dev/null @@ -1,3 +0,0 @@ -Rails.application.routes.draw do - # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/secrets.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/secrets.yml deleted file mode 100644 index ea9d47396c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/secrets.yml +++ /dev/null @@ -1,32 +0,0 @@ -# Be sure to restart your server when you modify this file. - -# Your secret key is used for verifying the integrity of signed cookies. -# If you change this key, all old signed cookies will become invalid! - -# Make sure the secret is at least 30 characters and all random, -# no regular words or you'll be exposed to dictionary attacks. -# You can use `rails secret` to generate a secure secret key. - -# Make sure the secrets in this file are kept private -# if you're sharing your code publicly. - -# Shared secrets are available across all environments. - -# shared: -# api_key: a1B2c3D4e5F6 - -# Environmental secrets are only available for that specific environment. - -development: - secret_key_base: <%= app_secret %> - -test: - secret_key_base: <%= app_secret %> - -# Do not keep production secrets in the unencrypted secrets file. -# Instead, either read values from the environment. -# Or, use `bin/rails secrets:setup` to configure encrypted secrets -# and move the `production:` environment over there. - -production: - secret_key_base: <%%= ENV["SECRET_KEY_BASE"] %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/spring.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/spring.rb deleted file mode 100644 index c9119b40c0..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/config/spring.rb +++ /dev/null @@ -1,6 +0,0 @@ -%w( - .ruby-version - .rbenv-vars - tmp/restart.txt - tmp/caching-dev.txt -).each { |path| Spring.watch(path) } diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/db/seeds.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/db/seeds.rb.tt deleted file mode 100644 index 1beea2accd..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/db/seeds.rb.tt +++ /dev/null @@ -1,7 +0,0 @@ -# This file should contain all the record creation needed to seed the database with its default values. -# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). -# -# Examples: -# -# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) -# Character.create(name: 'Luke', movie: movies.first) diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/gitignore b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/gitignore deleted file mode 100644 index 7221c26729..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/gitignore +++ /dev/null @@ -1,29 +0,0 @@ -# See https://help.github.com/articles/ignoring-files for more about ignoring files. -# -# If you find yourself ignoring temporary files generated by your text editor -# or operating system, you probably want to add a global ignore instead: -# git config --global core.excludesfile '~/.gitignore_global' - -# Ignore bundler config. -/.bundle - -<% if sqlite3? -%> -# Ignore the default SQLite database. -/db/*.sqlite3 -/db/*.sqlite3-journal - -<% end -%> -# Ignore all logfiles and tempfiles. -/log/* -/tmp/* -<% if keeps? -%> -!/log/.keep -!/tmp/.keep -<% end -%> - -<% unless options[:skip_yarn] -%> -/node_modules -/yarn-error.log - -<% end -%> -.byebug_history diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/package.json b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/package.json deleted file mode 100644 index 46db57dcbe..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/package.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name": "<%= app_name %>", - "private": true, - "dependencies": {} -} diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/404.html b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/404.html deleted file mode 100644 index 2be3af26fc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/404.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - The page you were looking for doesn't exist (404) - - - - - - -
    -
    -

    The page you were looking for doesn't exist.

    -

    You may have mistyped the address or the page may have moved.

    -
    -

    If you are the application owner check the logs for more information.

    -
    - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/422.html b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/422.html deleted file mode 100644 index c08eac0d1d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/422.html +++ /dev/null @@ -1,67 +0,0 @@ - - - - The change you wanted was rejected (422) - - - - - - -
    -
    -

    The change you wanted was rejected.

    -

    Maybe you tried to change something you didn't have access to.

    -
    -

    If you are the application owner check the logs for more information.

    -
    - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/500.html b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/500.html deleted file mode 100644 index 78a030af22..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/500.html +++ /dev/null @@ -1,66 +0,0 @@ - - - - We're sorry, but something went wrong (500) - - - - - - -
    -
    -

    We're sorry, but something went wrong.

    -
    -

    If you are the application owner check the logs for more information.

    -
    - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/apple-touch-icon-precomposed.png b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/apple-touch-icon-precomposed.png deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/apple-touch-icon.png b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/apple-touch-icon.png deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/favicon.ico b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/favicon.ico deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/robots.txt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/robots.txt deleted file mode 100644 index 37b576a4a0..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/public/robots.txt +++ /dev/null @@ -1 +0,0 @@ -# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/test/application_system_test_case.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/test/application_system_test_case.rb deleted file mode 100644 index d19212abd5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/test/application_system_test_case.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "test_helper" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :chrome, screen_size: [1400, 1400] -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/test/test_helper.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/test/test_helper.rb deleted file mode 100644 index 87b8fe3516..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/app/templates/test/test_helper.rb +++ /dev/null @@ -1,12 +0,0 @@ -ENV['RAILS_ENV'] ||= 'test' -require File.expand_path('../../config/environment', __FILE__) -require 'rails/test_help' - -class ActiveSupport::TestCase -<% unless options[:skip_active_record] -%> - # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. - fixtures :all - -<% end -%> - # Add more helper methods to be used by all tests here... -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/USAGE deleted file mode 100644 index d2e5ed4482..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/USAGE +++ /dev/null @@ -1,20 +0,0 @@ -Description: - Stubs out new asset placeholders. Pass the asset name, either CamelCased - or under_scored. - - To create an asset within a folder, specify the asset's name as a - path like 'parent/name'. - - This generates a JavaScript stub in app/assets/javascripts and a stylesheet - stub in app/assets/stylesheets. - - If CoffeeScript is available, JavaScripts will be generated with the .coffee extension. - If Sass 3 is available, stylesheets will be generated with the .scss extension. - -Example: - `rails generate assets posts` - - Posts assets. - JavaScript: app/assets/javascripts/posts.js - Stylesheet: app/assets/stylesheets/posts.css - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/assets_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/assets_generator.rb deleted file mode 100644 index 95d00c2d39..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/assets_generator.rb +++ /dev/null @@ -1,25 +0,0 @@ -module Rails - module Generators - class AssetsGenerator < NamedBase # :nodoc: - class_option :javascripts, type: :boolean, desc: "Generate JavaScripts" - class_option :stylesheets, type: :boolean, desc: "Generate Stylesheets" - - class_option :javascript_engine, desc: "Engine for JavaScripts" - class_option :stylesheet_engine, desc: "Engine for Stylesheets" - - private - - def asset_name - file_name - end - - hook_for :javascript_engine do |javascript_engine| - invoke javascript_engine, [name] if options[:javascripts] - end - - hook_for :stylesheet_engine do |stylesheet_engine| - invoke stylesheet_engine, [name] if options[:stylesheets] - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/templates/javascript.js b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/templates/javascript.js deleted file mode 100644 index dee720facd..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/templates/javascript.js +++ /dev/null @@ -1,2 +0,0 @@ -// Place all the behaviors and hooks related to the matching controller here. -// All this logic will automatically be available in application.js. diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/templates/stylesheet.css b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/templates/stylesheet.css deleted file mode 100644 index 7594abf268..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/assets/templates/stylesheet.css +++ /dev/null @@ -1,4 +0,0 @@ -/* - Place all the styles related to the matching controller here. - They will automatically be included in application.css. -*/ diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/USAGE deleted file mode 100644 index 64239ad599..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/USAGE +++ /dev/null @@ -1,18 +0,0 @@ -Description: - Stubs out a new controller and its views. Pass the controller name, either - CamelCased or under_scored, and a list of views as arguments. - - To create a controller within a module, specify the controller name as a - path like 'parent_module/controller_name'. - - This generates a controller class in app/controllers and invokes helper, - template engine, assets, and test framework generators. - -Example: - `rails generate controller CreditCards open debit credit close` - - CreditCards controller with URLs like /credit_cards/debit. - Controller: app/controllers/credit_cards_controller.rb - Test: test/controllers/credit_cards_controller_test.rb - Views: app/views/credit_cards/debit.html.erb [...] - Helper: app/helpers/credit_cards_helper.rb diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/controller_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/controller_generator.rb deleted file mode 100644 index 06bdb8b5ce..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/controller_generator.rb +++ /dev/null @@ -1,64 +0,0 @@ -module Rails - module Generators - class ControllerGenerator < NamedBase # :nodoc: - argument :actions, type: :array, default: [], banner: "action action" - class_option :skip_routes, type: :boolean, desc: "Don't add routes to config/routes.rb." - class_option :helper, type: :boolean - class_option :assets, type: :boolean - - check_class_collision suffix: "Controller" - - def create_controller_files - template "controller.rb", File.join("app/controllers", class_path, "#{file_name}_controller.rb") - end - - def add_routes - unless options[:skip_routes] - actions.reverse_each do |action| - # route prepends two spaces onto the front of the string that is passed, this corrects that. - route indent(generate_routing_code(action), 2)[2..-1] - end - end - end - - hook_for :template_engine, :test_framework, :helper, :assets - - private - - # This method creates nested route entry for namespaced resources. - # For eg. rails g controller foo/bar/baz index - # Will generate - - # namespace :foo do - # namespace :bar do - # get 'baz/index' - # end - # end - def generate_routing_code(action) - depth = 0 - lines = [] - - # Create 'namespace' ladder - # namespace :foo do - # namespace :bar do - regular_class_path.each do |ns| - lines << indent("namespace :#{ns} do\n", depth * 2) - depth += 1 - end - - # Create route - # get 'baz/index' - lines << indent(%{get '#{file_name}/#{action}'\n}, depth * 2) - - # Create `end` ladder - # end - # end - until depth.zero? - depth -= 1 - lines << indent("end\n", depth * 2) - end - - lines.join - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/templates/controller.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/templates/controller.rb deleted file mode 100644 index 633e0b3177..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/controller/templates/controller.rb +++ /dev/null @@ -1,13 +0,0 @@ -<% if namespaced? -%> -require_dependency "<%= namespaced_path %>/application_controller" - -<% end -%> -<% module_namespacing do -%> -class <%= class_name %>Controller < ApplicationController -<% actions.each do |action| -%> - def <%= action %> - end -<%= "\n" unless action == actions.last -%> -<% end -%> -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/encrypted_secrets/encrypted_secrets_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/encrypted_secrets/encrypted_secrets_generator.rb deleted file mode 100644 index 1da2fbc1a5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/encrypted_secrets/encrypted_secrets_generator.rb +++ /dev/null @@ -1,70 +0,0 @@ -require "rails/generators/base" -require "rails/secrets" - -module Rails - module Generators - class EncryptedSecretsGenerator < Base - def add_secrets_key_file - unless File.exist?("config/secrets.yml.key") || File.exist?("config/secrets.yml.enc") - key = Rails::Secrets.generate_key - - say "Adding config/secrets.yml.key to store the encryption key: #{key}" - say "" - say "Save this in a password manager your team can access." - say "" - say "If you lose the key, no one, including you, can access any encrypted secrets." - - say "" - create_file "config/secrets.yml.key", key - say "" - end - end - - def ignore_key_file - if File.exist?(".gitignore") - unless File.read(".gitignore").include?(key_ignore) - say "Ignoring config/secrets.yml.key so it won't end up in Git history:" - say "" - append_to_file ".gitignore", key_ignore - say "" - end - else - say "IMPORTANT: Don't commit config/secrets.yml.key. Add this to your ignore file:" - say key_ignore, :on_green - say "" - end - end - - def add_encrypted_secrets_file - unless (defined?(@@skip_secrets_file) && @@skip_secrets_file) || File.exist?("config/secrets.yml.enc") - say "Adding config/secrets.yml.enc to store secrets that needs to be encrypted." - say "" - say "For now the file contains this but it's been encrypted with the generated key:" - say "" - say Secrets.template, :on_green - say "" - - Secrets.write(Secrets.template) - - say "You can edit encrypted secrets with `bin/rails secrets:edit`." - say "" - end - - say "Add this to your config/environments/production.rb:" - say "config.read_encrypted_secrets = true" - end - - def self.skip_secrets_file - @@skip_secrets_file = true - yield - ensure - @@skip_secrets_file = false - end - - private - def key_ignore - [ "", "# Ignore encrypted secrets key file.", "config/secrets.yml.key", "" ].join("\n") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/USAGE deleted file mode 100644 index 799383050c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/USAGE +++ /dev/null @@ -1,13 +0,0 @@ -Description: - Stubs out a new generator at lib/generators. Pass the generator name as an argument, - either CamelCased or snake_cased. - -Example: - `rails generate generator Awesome` - - creates a standard awesome generator: - lib/generators/awesome/ - lib/generators/awesome/awesome_generator.rb - lib/generators/awesome/USAGE - lib/generators/awesome/templates/ - test/lib/generators/awesome_generator_test.rb diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/generator_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/generator_generator.rb deleted file mode 100644 index 299a7da5f1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/generator_generator.rb +++ /dev/null @@ -1,26 +0,0 @@ -module Rails - module Generators - class GeneratorGenerator < NamedBase # :nodoc: - check_class_collision suffix: "Generator" - - class_option :namespace, type: :boolean, default: true, - desc: "Namespace generator under lib/generators/name" - - def create_generator_files - directory ".", generator_dir - end - - hook_for :test_framework - - private - - def generator_dir - if options[:namespace] - File.join("lib", "generators", regular_class_path, file_name) - else - File.join("lib", "generators", regular_class_path) - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt deleted file mode 100644 index d0575772bc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt +++ /dev/null @@ -1,3 +0,0 @@ -class <%= class_name %>Generator < Rails::Generators::NamedBase - source_root File.expand_path('../templates', __FILE__) -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/USAGE.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/USAGE.tt deleted file mode 100644 index 1bb8df840d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/USAGE.tt +++ /dev/null @@ -1,8 +0,0 @@ -Description: - Explain the generator - -Example: - rails generate <%= file_name %> Thing - - This will create: - what/will/it/create diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/templates/.empty_directory b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/generator/templates/templates/.empty_directory deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/USAGE deleted file mode 100644 index 8855ef3b01..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/USAGE +++ /dev/null @@ -1,13 +0,0 @@ -Description: - Stubs out a new helper. Pass the helper name, either CamelCased - or under_scored. - - To create a helper within a module, specify the helper name as a - path like 'parent_module/helper_name'. - -Example: - `rails generate helper CreditCard` - - Credit card helper. - Helper: app/helpers/credit_card_helper.rb - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/helper_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/helper_generator.rb deleted file mode 100644 index e48b1b6fb3..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/helper_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -module Rails - module Generators - class HelperGenerator < NamedBase # :nodoc: - check_class_collision suffix: "Helper" - - def create_helper_files - template "helper.rb", File.join("app/helpers", class_path, "#{file_name}_helper.rb") - end - - hook_for :test_framework - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/templates/helper.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/templates/helper.rb deleted file mode 100644 index b4173151b4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/helper/templates/helper.rb +++ /dev/null @@ -1,4 +0,0 @@ -<% module_namespacing do -%> -module <%= class_name %>Helper -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/integration_test/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/integration_test/USAGE deleted file mode 100644 index 57ee3543e6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/integration_test/USAGE +++ /dev/null @@ -1,10 +0,0 @@ -Description: - Stubs out a new integration test. Pass the name of the test, either - CamelCased or under_scored, as an argument. - - This generator invokes the current integration tool, which defaults to - TestUnit. - -Example: - `rails generate integration_test GeneralStories` creates a GeneralStories - integration test in test/integration/general_stories_test.rb diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/integration_test/integration_test_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/integration_test/integration_test_generator.rb deleted file mode 100644 index 70770ddcb8..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/integration_test/integration_test_generator.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Rails - module Generators - class IntegrationTestGenerator < NamedBase # :nodoc: - hook_for :integration_tool, as: :integration - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/migration/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/migration/USAGE deleted file mode 100644 index baf3d9894f..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/migration/USAGE +++ /dev/null @@ -1,35 +0,0 @@ -Description: - Stubs out a new database migration. Pass the migration name, either - CamelCased or under_scored, and an optional list of attribute pairs as arguments. - - A migration class is generated in db/migrate prefixed by a timestamp of the current date and time. - - You can name your migration in either of these formats to generate add/remove - column lines from supplied attributes: AddColumnsToTable or RemoveColumnsFromTable - -Example: - `rails generate migration AddSslFlag` - - If the current date is May 14, 2008 and the current time 09:09:12, this creates the AddSslFlag migration - db/migrate/20080514090912_add_ssl_flag.rb - - `rails generate migration AddTitleBodyToPost title:string body:text published:boolean` - - This will create the AddTitleBodyToPost in db/migrate/20080514090912_add_title_body_to_post.rb with this in the Change migration: - - add_column :posts, :title, :string - add_column :posts, :body, :text - add_column :posts, :published, :boolean - -Migration names containing JoinTable will generate join tables for use with -has_and_belongs_to_many associations. - -Example: - `rails g migration CreateMediaJoinTable artists musics:uniq` - - will create the migration - - create_join_table :artists, :musics do |t| - # t.index [:artist_id, :music_id] - t.index [:music_id, :artist_id], unique: true - end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/migration/migration_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/migration/migration_generator.rb deleted file mode 100644 index fca2a8fef4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/migration/migration_generator.rb +++ /dev/null @@ -1,8 +0,0 @@ -module Rails - module Generators - class MigrationGenerator < NamedBase # :nodoc: - argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" - hook_for :orm, required: true, desc: "ORM to be invoked" - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/model/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/model/USAGE deleted file mode 100644 index 025bcf4774..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/model/USAGE +++ /dev/null @@ -1,114 +0,0 @@ -Description: - Stubs out a new model. Pass the model name, either CamelCased or - under_scored, and an optional list of attribute pairs as arguments. - - Attribute pairs are field:type arguments specifying the - model's attributes. Timestamps are added by default, so you don't have to - specify them by hand as 'created_at:datetime updated_at:datetime'. - - As a special case, specifying 'password:digest' will generate a - password_digest field of string type, and configure your generated model and - tests for use with Active Model has_secure_password (assuming the default ORM - and test framework are being used). - - You don't have to think up every attribute up front, but it helps to - sketch out a few so you can start working with the model immediately. - - This generator invokes your configured ORM and test framework, which - defaults to Active Record and TestUnit. - - Finally, if --parent option is given, it's used as superclass of the - created model. This allows you create Single Table Inheritance models. - - If you pass a namespaced model name (e.g. admin/account or Admin::Account) - then the generator will create a module with a table_name_prefix method - to prefix the model's table name with the module name (e.g. admin_accounts) - -Available field types: - - Just after the field name you can specify a type like text or boolean. - It will generate the column with the associated SQL type. For instance: - - `rails generate model post title:string body:text` - - will generate a title column with a varchar type and a body column with a text - type. If no type is specified the string type will be used by default. - You can use the following types: - - integer - primary_key - decimal - float - boolean - binary - string - text - date - time - datetime - - You can also consider `references` as a kind of type. For instance, if you run: - - `rails generate model photo title:string album:references` - - It will generate an `album_id` column. You should generate these kinds of fields when - you will use a `belongs_to` association, for instance. `references` also supports - polymorphism, you can enable polymorphism like this: - - `rails generate model product supplier:references{polymorphic}` - - For integer, string, text and binary fields, an integer in curly braces will - be set as the limit: - - `rails generate model user pseudo:string{30}` - - For decimal, two integers separated by a comma in curly braces will be used - for precision and scale: - - `rails generate model product 'price:decimal{10,2}'` - - You can add a `:uniq` or `:index` suffix for unique or standard indexes - respectively: - - `rails generate model user pseudo:string:uniq` - `rails generate model user pseudo:string:index` - - You can combine any single curly brace option with the index options: - - `rails generate model user username:string{30}:uniq` - `rails generate model product supplier:references{polymorphic}:index` - - If you require a `password_digest` string column for use with - has_secure_password, you can specify `password:digest`: - - `rails generate model user password:digest` - - If you require a `token` string column for use with - has_secure_token, you can specify `auth_token:token`: - - `rails generate model user auth_token:token` - -Examples: - `rails generate model account` - - For Active Record and TestUnit it creates: - - Model: app/models/account.rb - Test: test/models/account_test.rb - Fixtures: test/fixtures/accounts.yml - Migration: db/migrate/XXX_create_accounts.rb - - `rails generate model post title:string body:text published:boolean` - - Creates a Post model with a string title, text body, and published flag. - - `rails generate model admin/account` - - For Active Record and TestUnit it creates: - - Module: app/models/admin.rb - Model: app/models/admin/account.rb - Test: test/models/admin/account_test.rb - Fixtures: test/fixtures/admin/accounts.yml - Migration: db/migrate/XXX_create_admin_accounts.rb - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/model/model_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/model/model_generator.rb deleted file mode 100644 index c32a8a079a..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/model/model_generator.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "rails/generators/model_helpers" - -module Rails - module Generators - class ModelGenerator < NamedBase # :nodoc: - include Rails::Generators::ModelHelpers - - argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" - hook_for :orm, required: true, desc: "ORM to be invoked" - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/USAGE deleted file mode 100644 index 9a7bf9f396..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/USAGE +++ /dev/null @@ -1,10 +0,0 @@ -Description: - The 'rails plugin new' command creates a skeleton for developing any - kind of Rails extension with ability to run tests using dummy Rails - application. - -Example: - rails plugin new ~/Code/Ruby/blog - - This generates a skeletal Rails plugin in ~/Code/Ruby/blog. - See the README in the newly created plugin to get going. diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/plugin_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/plugin_generator.rb deleted file mode 100644 index 118e44d9d0..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/plugin_generator.rb +++ /dev/null @@ -1,445 +0,0 @@ -require "active_support/core_ext/hash/slice" -require "rails/generators/rails/app/app_generator" -require "date" - -module Rails - # The plugin builder allows you to override elements of the plugin - # generator without being forced to reverse the operations of the default - # generator. - # - # This allows you to override entire operations, like the creation of the - # Gemfile, \README, or JavaScript files, without needing to know exactly - # what those operations do so you can create another template action. - class PluginBuilder - def rakefile - template "Rakefile" - end - - def app - if mountable? - if api? - directory "app", exclude_pattern: %r{app/(views|helpers)} - else - directory "app" - empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" - end - elsif full? - empty_directory_with_keep_file "app/models" - empty_directory_with_keep_file "app/controllers" - empty_directory_with_keep_file "app/mailers" - - unless api? - empty_directory_with_keep_file "app/assets/images/#{namespaced_name}" - empty_directory_with_keep_file "app/helpers" - empty_directory_with_keep_file "app/views" - end - end - end - - def readme - template "README.md" - end - - def gemfile - template "Gemfile" - end - - def license - template "MIT-LICENSE" - end - - def gemspec - template "%name%.gemspec" - end - - def gitignore - template "gitignore", ".gitignore" - end - - def lib - template "lib/%namespaced_name%.rb" - template "lib/tasks/%namespaced_name%_tasks.rake" - template "lib/%namespaced_name%/version.rb" - template "lib/%namespaced_name%/engine.rb" if engine? - end - - def config - template "config/routes.rb" if engine? - end - - def test - template "test/test_helper.rb" - template "test/%namespaced_name%_test.rb" - append_file "Rakefile", <<-EOF -#{rakefile_test_tasks} - -task default: :test - EOF - if engine? - template "test/integration/navigation_test.rb" - end - end - - PASSTHROUGH_OPTIONS = [ - :skip_active_record, :skip_action_mailer, :skip_javascript, :skip_sprockets, :database, - :javascript, :quiet, :pretend, :force, :skip - ] - - def generate_test_dummy(force = false) - opts = (options || {}).slice(*PASSTHROUGH_OPTIONS) - opts[:force] = force - opts[:skip_bundle] = true - opts[:api] = options.api? - opts[:skip_listen] = true - opts[:skip_git] = true - opts[:skip_turbolinks] = true - - invoke Rails::Generators::AppGenerator, - [ File.expand_path(dummy_path, destination_root) ], opts - end - - def test_dummy_config - template "rails/boot.rb", "#{dummy_path}/config/boot.rb", force: true - template "rails/application.rb", "#{dummy_path}/config/application.rb", force: true - if mountable? - template "rails/routes.rb", "#{dummy_path}/config/routes.rb", force: true - end - end - - def test_dummy_assets - template "rails/javascripts.js", "#{dummy_path}/app/assets/javascripts/application.js", force: true - template "rails/stylesheets.css", "#{dummy_path}/app/assets/stylesheets/application.css", force: true - template "rails/dummy_manifest.js", "#{dummy_path}/app/assets/config/manifest.js", force: true - end - - def test_dummy_clean - inside dummy_path do - remove_file "db/seeds.rb" - remove_file "doc" - remove_file "Gemfile" - remove_file "lib/tasks" - remove_file "public/robots.txt" - remove_file "README.md" - remove_file "test" - remove_file "vendor" - end - end - - def assets_manifest - template "rails/engine_manifest.js", "app/assets/config/#{underscored_name}_manifest.js" - end - - def stylesheets - if mountable? - copy_file "rails/stylesheets.css", - "app/assets/stylesheets/#{namespaced_name}/application.css" - elsif full? - empty_directory_with_keep_file "app/assets/stylesheets/#{namespaced_name}" - end - end - - def javascripts - return if options.skip_javascript? - - if mountable? - template "rails/javascripts.js", - "app/assets/javascripts/#{namespaced_name}/application.js" - elsif full? - empty_directory_with_keep_file "app/assets/javascripts/#{namespaced_name}" - end - end - - def bin(force = false) - bin_file = engine? ? "bin/rails.tt" : "bin/test.tt" - template bin_file, force: force do |content| - "#{shebang}\n" + content - end - chmod "bin", 0755, verbose: false - end - - def gemfile_entry - return unless inside_application? - - gemfile_in_app_path = File.join(rails_app_path, "Gemfile") - if File.exist? gemfile_in_app_path - entry = "gem '#{name}', path: '#{relative_path}'" - append_file gemfile_in_app_path, entry - end - end - end - - module Generators - class PluginGenerator < AppBase # :nodoc: - add_shared_options_for "plugin" - - alias_method :plugin_path, :app_path - - class_option :dummy_path, type: :string, default: "test/dummy", - desc: "Create dummy application at given path" - - class_option :full, type: :boolean, default: false, - desc: "Generate a rails engine with bundled Rails application for testing" - - class_option :mountable, type: :boolean, default: false, - desc: "Generate mountable isolated application" - - class_option :skip_gemspec, type: :boolean, default: false, - desc: "Skip gemspec file" - - class_option :skip_gemfile_entry, type: :boolean, default: false, - desc: "If creating plugin in application's directory " \ - "skip adding entry to Gemfile" - - class_option :api, type: :boolean, default: false, - desc: "Generate a smaller stack for API application plugins" - - def initialize(*args) - @dummy_path = nil - super - end - - public_task :set_default_accessors! - public_task :create_root - - def create_root_files - build(:readme) - build(:rakefile) - build(:gemspec) unless options[:skip_gemspec] - build(:license) - build(:gitignore) unless options[:skip_git] - build(:gemfile) unless options[:skip_gemfile] - end - - def create_app_files - build(:app) - end - - def create_config_files - build(:config) - end - - def create_lib_files - build(:lib) - end - - def create_assets_manifest_file - build(:assets_manifest) if !api? && engine? - end - - def create_public_stylesheets_files - build(:stylesheets) unless api? - end - - def create_javascript_files - build(:javascripts) unless api? - end - - def create_bin_files - build(:bin) - end - - def create_test_files - build(:test) unless options[:skip_test] - end - - def create_test_dummy_files - return unless with_dummy_app? - create_dummy_app - end - - def update_gemfile - build(:gemfile_entry) unless options[:skip_gemfile_entry] - end - - def finish_template - build(:leftovers) - end - - public_task :apply_rails_template - - def run_after_bundle_callbacks - @after_bundle_callbacks.each do |callback| - callback.call - end - end - - def name - @name ||= begin - # same as ActiveSupport::Inflector#underscore except not replacing '-' - underscored = original_name.dup - underscored.gsub!(/([A-Z]+)([A-Z][a-z])/, '\1_\2') - underscored.gsub!(/([a-z\d])([A-Z])/, '\1_\2') - underscored.downcase! - - underscored - end - end - - def underscored_name - @underscored_name ||= original_name.underscore - end - - def namespaced_name - @namespaced_name ||= name.tr("-", "/") - end - - private - - def create_dummy_app(path = nil) - dummy_path(path) if path - - say_status :vendor_app, dummy_path - mute do - build(:generate_test_dummy) - store_application_definition! - build(:test_dummy_config) - build(:test_dummy_assets) - build(:test_dummy_clean) - # ensure that bin/rails has proper dummy_path - build(:bin, true) - end - end - - def engine? - full? || mountable? || options[:engine] - end - - def full? - options[:full] - end - - def mountable? - options[:mountable] - end - - def skip_git? - options[:skip_git] - end - - def with_dummy_app? - options[:skip_test].blank? || options[:dummy_path] != "test/dummy" - end - - def api? - options[:api] - end - - def self.banner - "rails plugin new #{arguments.map(&:usage).join(' ')} [options]" - end - - def original_name - @original_name ||= File.basename(destination_root) - end - - def modules - @modules ||= namespaced_name.camelize.split("::") - end - - def wrap_in_modules(unwrapped_code) - unwrapped_code = "#{unwrapped_code}".strip.gsub(/\s$\n/, "") - modules.reverse.inject(unwrapped_code) do |content, mod| - str = "module #{mod}\n" - str += content.lines.map { |line| " #{line}" }.join - str += content.present? ? "\nend" : "end" - end - end - - def camelized_modules - @camelized_modules ||= namespaced_name.camelize - end - - def humanized - @humanized ||= original_name.underscore.humanize - end - - def camelized - @camelized ||= name.gsub(/\W/, "_").squeeze("_").camelize - end - - def author - default = "TODO: Write your name" - if skip_git? - @author = default - else - @author = `git config user.name`.chomp rescue default - end - end - - def email - default = "TODO: Write your email address" - if skip_git? - @email = default - else - @email = `git config user.email`.chomp rescue default - end - end - - def valid_const? - if original_name =~ /-\d/ - raise Error, "Invalid plugin name #{original_name}. Please give a name which does not contain a namespace starting with numeric characters." - elsif original_name =~ /[^\w-]+/ - raise Error, "Invalid plugin name #{original_name}. Please give a name which uses only alphabetic, numeric, \"_\" or \"-\" characters." - elsif camelized =~ /^\d/ - raise Error, "Invalid plugin name #{original_name}. Please give a name which does not start with numbers." - elsif RESERVED_NAMES.include?(name) - raise Error, "Invalid plugin name #{original_name}. Please give a " \ - "name which does not match one of the reserved rails " \ - "words: #{RESERVED_NAMES.join(", ")}" - elsif Object.const_defined?(camelized) - raise Error, "Invalid plugin name #{original_name}, constant #{camelized} is already in use. Please choose another plugin name." - end - end - - def application_definition - @application_definition ||= begin - - dummy_application_path = File.expand_path("#{dummy_path}/config/application.rb", destination_root) - unless options[:pretend] || !File.exist?(dummy_application_path) - contents = File.read(dummy_application_path) - contents[(contents.index(/module ([\w]+)\n(.*)class Application/m))..-1] - end - end - end - alias :store_application_definition! :application_definition - - def get_builder_class - defined?(::PluginBuilder) ? ::PluginBuilder : Rails::PluginBuilder - end - - def rakefile_test_tasks - <<-RUBY -require 'rake/testtask' - -Rake::TestTask.new(:test) do |t| - t.libs << 'test' - t.pattern = 'test/**/*_test.rb' - t.verbose = false -end - RUBY - end - - def dummy_path(path = nil) - @dummy_path = path if path - @dummy_path || options[:dummy_path] - end - - def mute(&block) - shell.mute(&block) - end - - def rails_app_path - APP_PATH.sub("/config/application", "") if defined?(APP_PATH) - end - - def inside_application? - rails_app_path && destination_root.start_with?(rails_app_path.to_s) - end - - def relative_path - return unless inside_application? - app_path.sub(/^#{rails_app_path}\//, "") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/%name%.gemspec b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/%name%.gemspec deleted file mode 100644 index 3cd44c87a8..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/%name%.gemspec +++ /dev/null @@ -1,33 +0,0 @@ -$:.push File.expand_path("../lib", __FILE__) - -# Maintain your gem's version: -require "<%= namespaced_name %>/version" - -# Describe your gem and declare its dependencies: -Gem::Specification.new do |spec| - spec.name = "<%= name %>" - spec.version = <%= camelized_modules %>::VERSION - spec.authors = ["<%= author %>"] - spec.email = ["<%= email %>"] - spec.homepage = "TODO" - spec.summary = "TODO: Summary of <%= camelized_modules %>." - spec.description = "TODO: Description of <%= camelized_modules %>." - spec.license = "MIT" - - # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host' - # to allow pushing to a single host or delete this section to allow pushing to any host. - if spec.respond_to?(:metadata) - spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" - else - raise "RubyGems 2.0 or newer is required to protect against " \ - "public gem pushes." - end - - spec.files = Dir["{app,config,db,lib}/**/*", "MIT-LICENSE", "Rakefile", "README.md"] - - <%= '# ' if options.dev? || options.edge? -%>spec.add_dependency "rails", "<%= Array(rails_version_specifier).join('", "') %>" -<% unless options[:skip_active_record] -%> - - spec.add_development_dependency "<%= gem_for_database[0] %>" -<% end -%> -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/Gemfile b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/Gemfile deleted file mode 100644 index 22a4548ff2..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/Gemfile +++ /dev/null @@ -1,47 +0,0 @@ -source 'https://rubygems.org' - -<% if options[:skip_gemspec] -%> -<%= '# ' if options.dev? || options.edge? -%>gem 'rails', '<%= Array(rails_version_specifier).join("', '") %>' -<% else -%> -# Declare your gem's dependencies in <%= name %>.gemspec. -# Bundler will treat runtime dependencies like base dependencies, and -# development dependencies will be added by default to the :development group. -gemspec -<% end -%> - -<% if options[:skip_gemspec] -%> -group :development do - gem '<%= gem_for_database[0] %>' -end -<% else -%> -# Declare any dependencies that are still in development here instead of in -# your gemspec. These might include edge Rails or gems from your path or -# Git. Remember to move these dependencies to your gemspec before releasing -# your gem to rubygems.org. -<% end -%> - -<% if options.dev? || options.edge? -%> -# Your gem is dependent on dev or edge Rails. Once you can lock this -# dependency down to a specific version, move it to your gemspec. -<% max_width = gemfile_entries.map { |g| g.name.length }.max -%> -<% gemfile_entries.each do |gem| -%> -<% if gem.comment -%> - -# <%= gem.comment %> -<% end -%> -<%= gem.commented_out ? '# ' : '' %>gem '<%= gem.name %>'<%= %(, '#{gem.version}') if gem.version -%> -<% if gem.options.any? -%> -, <%= gem.options.map { |k,v| - "#{k}: #{v.inspect}" }.join(', ') %> -<% end -%> -<% end -%> - -<% end -%> -<% if RUBY_ENGINE == 'ruby' -%> -# To use a debugger -# gem 'byebug', group: [:development, :test] -<% end -%> -<% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince|java/) -%> - -gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/MIT-LICENSE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/MIT-LICENSE deleted file mode 100644 index ff2fb3ba4e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/MIT-LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright <%= Date.today.year %> <%= author %> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/README.md b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/README.md deleted file mode 100644 index 9d2b74416e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/README.md +++ /dev/null @@ -1,28 +0,0 @@ -# <%= camelized_modules %> -Short description and motivation. - -## Usage -How to use my plugin. - -## Installation -Add this line to your application's Gemfile: - -```ruby -gem '<%= name %>' -``` - -And then execute: -```bash -$ bundle -``` - -Or install it yourself as: -```bash -$ gem install <%= name %> -``` - -## Contributing -Contribution directions go here. - -## License -The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT). diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/Rakefile b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/Rakefile deleted file mode 100644 index 383d2fb2d1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/Rakefile +++ /dev/null @@ -1,29 +0,0 @@ -begin - require 'bundler/setup' -rescue LoadError - puts 'You must `gem install bundler` and `bundle install` to run rake tasks' -end - -require 'rdoc/task' - -RDoc::Task.new(:rdoc) do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = '<%= camelized_modules %>' - rdoc.options << '--line-numbers' - rdoc.rdoc_files.include('README.md') - rdoc.rdoc_files.include('lib/**/*.rb') -end - -<% if engine? && !options[:skip_active_record] && with_dummy_app? -%> -APP_RAKEFILE = File.expand_path("../<%= dummy_path -%>/Rakefile", __FILE__) -load 'rails/tasks/engine.rake' -<% end %> - -<% if engine? -%> -load 'rails/tasks/statistics.rake' -<% end %> - -<% unless options[:skip_gemspec] -%> - -require 'bundler/gem_tasks' -<% end %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt deleted file mode 100644 index abbacd9bec..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt +++ /dev/null @@ -1,6 +0,0 @@ -<%= wrap_in_modules <<-rb.strip_heredoc - class ApplicationController < ActionController::#{api? ? "API" : "Base"} - #{ api? ? '# ' : '' }protect_from_forgery with: :exception - end -rb -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/helpers/%namespaced_name%/application_helper.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/helpers/%namespaced_name%/application_helper.rb.tt deleted file mode 100644 index 25d692732d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/helpers/%namespaced_name%/application_helper.rb.tt +++ /dev/null @@ -1,5 +0,0 @@ -<%= wrap_in_modules <<-rb.strip_heredoc - module ApplicationHelper - end -rb -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/jobs/%namespaced_name%/application_job.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/jobs/%namespaced_name%/application_job.rb.tt deleted file mode 100644 index bad1ff2d16..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/jobs/%namespaced_name%/application_job.rb.tt +++ /dev/null @@ -1,5 +0,0 @@ -<%= wrap_in_modules <<-rb.strip_heredoc - class ApplicationJob < ActiveJob::Base - end -rb -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/mailers/%namespaced_name%/application_mailer.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/mailers/%namespaced_name%/application_mailer.rb.tt deleted file mode 100644 index 09aac13f42..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/mailers/%namespaced_name%/application_mailer.rb.tt +++ /dev/null @@ -1,7 +0,0 @@ -<%= wrap_in_modules <<-rb.strip_heredoc - class ApplicationMailer < ActionMailer::Base - default from: 'from@example.com' - layout 'mailer' - end -rb -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/models/%namespaced_name%/application_record.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/models/%namespaced_name%/application_record.rb.tt deleted file mode 100644 index 8aa3de78f1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/models/%namespaced_name%/application_record.rb.tt +++ /dev/null @@ -1,6 +0,0 @@ -<%= wrap_in_modules <<-rb.strip_heredoc - class ApplicationRecord < ActiveRecord::Base - self.abstract_class = true - end -rb -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/views/layouts/%namespaced_name%/application.html.erb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/views/layouts/%namespaced_name%/application.html.erb.tt deleted file mode 100644 index 6bc480161d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/app/views/layouts/%namespaced_name%/application.html.erb.tt +++ /dev/null @@ -1,14 +0,0 @@ - - - - <%= humanized %> - <%%= stylesheet_link_tag "<%= namespaced_name %>/application", media: "all" %> - <%%= javascript_include_tag "<%= namespaced_name %>/application" %> - <%%= csrf_meta_tags %> - - - -<%%= yield %> - - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/bin/rails.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/bin/rails.tt deleted file mode 100644 index c03d9953d4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/bin/rails.tt +++ /dev/null @@ -1,13 +0,0 @@ -# This command will automatically be run when you run "rails" with Rails gems -# installed from the root of your application. - -ENGINE_ROOT = File.expand_path('../..', __FILE__) -ENGINE_PATH = File.expand_path('../../lib/<%= namespaced_name -%>/engine', __FILE__) -APP_PATH = File.expand_path('../../<%= dummy_path -%>/config/application', __FILE__) - -# Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) - -require 'rails/all' -require 'rails/engine/commands' diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/bin/test.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/bin/test.tt deleted file mode 100644 index 8385e6a8a2..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/bin/test.tt +++ /dev/null @@ -1,4 +0,0 @@ -$: << File.expand_path(File.expand_path("../../test", __FILE__)) - -require "bundler/setup" -require "rails/plugin/test" diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/config/routes.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/config/routes.rb deleted file mode 100644 index 154452bfe5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/config/routes.rb +++ /dev/null @@ -1,6 +0,0 @@ -<% if mountable? -%> -<%= camelized_modules %>::Engine.routes.draw do -<% else -%> -Rails.application.routes.draw do -<% end -%> -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/gitignore b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/gitignore deleted file mode 100644 index 54c78d7927..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/gitignore +++ /dev/null @@ -1,9 +0,0 @@ -.bundle/ -log/*.log -pkg/ -<% unless options[:skip_test] && options[:dummy_path] == 'test/dummy' -%> -<%= dummy_path %>/db/*.sqlite3 -<%= dummy_path %>/db/*.sqlite3-journal -<%= dummy_path %>/log/*.log -<%= dummy_path %>/tmp/ -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%.rb deleted file mode 100644 index 40b1c4cee7..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%.rb +++ /dev/null @@ -1,5 +0,0 @@ -<% if engine? -%> -require "<%= namespaced_name %>/engine" - -<% end -%> -<%= wrap_in_modules "# Your code goes here..." %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb deleted file mode 100644 index 8938770fc4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb +++ /dev/null @@ -1,7 +0,0 @@ -<%= wrap_in_modules <<-rb.strip_heredoc - class Engine < ::Rails::Engine - #{mountable? ? ' isolate_namespace ' + camelized_modules : ' '} - #{api? ? " config.generators.api_only = true" : ' '} - end -rb -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb deleted file mode 100644 index b08f4ef9ae..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb +++ /dev/null @@ -1 +0,0 @@ -<%= wrap_in_modules "VERSION = '0.1.0'" %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/tasks/%namespaced_name%_tasks.rake b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/tasks/%namespaced_name%_tasks.rake deleted file mode 100644 index 88a2c4120f..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/lib/tasks/%namespaced_name%_tasks.rake +++ /dev/null @@ -1,4 +0,0 @@ -# desc "Explaining what the task does" -# task :<%= underscored_name %> do -# # Task goes here -# end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/application.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/application.rb deleted file mode 100644 index d03b1be878..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/application.rb +++ /dev/null @@ -1,20 +0,0 @@ -require_relative 'boot' - -<% if include_all_railties? -%> -require 'rails/all' -<% else -%> -# Pick the frameworks you want: -<%= comment_if :skip_active_record %>require "active_record/railtie" -require "action_controller/railtie" -require "action_view/railtie" -<%= comment_if :skip_action_mailer %>require "action_mailer/railtie" -require "active_job/railtie" -<%= comment_if :skip_action_cable %>require "action_cable/engine" -<%= comment_if :skip_test %>require "rails/test_unit/railtie" -<%= comment_if :skip_sprockets %>require "sprockets/railtie" -<% end -%> - -Bundler.require(*Rails.groups) -require "<%= namespaced_name %>" - -<%= application_definition %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/boot.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/boot.rb deleted file mode 100644 index c9aef85d40..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/boot.rb +++ /dev/null @@ -1,5 +0,0 @@ -# Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) - -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) -$LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/dummy_manifest.js b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/dummy_manifest.js deleted file mode 100644 index 8d21b2b6fb..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/dummy_manifest.js +++ /dev/null @@ -1,11 +0,0 @@ - -<% unless api? -%> -//= link_tree ../images -<% end -%> -<% unless options.skip_javascript -%> -//= link_directory ../javascripts .js -<% end -%> -//= link_directory ../stylesheets .css -<% if mountable? && !api? -%> -//= link <%= underscored_name %>_manifest.js -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/engine_manifest.js b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/engine_manifest.js deleted file mode 100644 index 2f23844f5e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/engine_manifest.js +++ /dev/null @@ -1,6 +0,0 @@ -<% if mountable? -%> -<% if !options.skip_javascript -%> -//= link_directory ../javascripts/<%= namespaced_name %> .js -<% end -%> -//= link_directory ../stylesheets/<%= namespaced_name %> .css -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/javascripts.js b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/javascripts.js deleted file mode 100644 index e54c6461cc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/javascripts.js +++ /dev/null @@ -1,13 +0,0 @@ -// This is a manifest file that'll be compiled into application.js, which will include all the files -// listed below. -// -// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, -// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. -// -// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the -// compiled file. JavaScript code in this file should be added after the last require_* statement. -// -// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details -// about supported directives. -// -//= require_tree . diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/routes.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/routes.rb deleted file mode 100644 index 694510edc0..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/routes.rb +++ /dev/null @@ -1,3 +0,0 @@ -Rails.application.routes.draw do - mount <%= camelized_modules %>::Engine => "/<%= name %>" -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css deleted file mode 100644 index 0ebd7fe829..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css +++ /dev/null @@ -1,15 +0,0 @@ -/* - * This is a manifest file that'll be compiled into application.css, which will include all the files - * listed below. - * - * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, - * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. - * - * You're free to add application-wide styles to this file and they'll appear at the bottom of the - * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS - * files in this directory. Styles in this file should be added after the last require_* statement. - * It is generally better to create a new file per style scope. - * - *= require_tree . - *= require_self - */ diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/%namespaced_name%_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/%namespaced_name%_test.rb deleted file mode 100644 index 1ee05d7871..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/%namespaced_name%_test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class <%= camelized_modules %>::Test < ActiveSupport::TestCase - test "truth" do - assert_kind_of Module, <%= camelized_modules %> - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/application_system_test_case.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/application_system_test_case.rb deleted file mode 100644 index d19212abd5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/application_system_test_case.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "test_helper" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :chrome, screen_size: [1400, 1400] -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb deleted file mode 100644 index f5d1ec2046..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'test_helper' - -class NavigationTest < ActionDispatch::IntegrationTest - # test "the truth" do - # assert true - # end -end - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/test_helper.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/test_helper.rb deleted file mode 100644 index ac6bd23273..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/plugin/templates/test/test_helper.rb +++ /dev/null @@ -1,26 +0,0 @@ -# Configure Rails Environment -ENV["RAILS_ENV"] = "test" -require File.expand_path("../../<%= options[:dummy_path] -%>/config/environment.rb", __FILE__) -<% unless options[:skip_active_record] -%> -ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../<%= options[:dummy_path] -%>/db/migrate", __FILE__)] -<% if options[:mountable] -%> -ActiveRecord::Migrator.migrations_paths << File.expand_path('../../db/migrate', __FILE__) -<% end -%> -<% end -%> -require "rails/test_help" - -# Filter out Minitest backtrace while allowing backtrace from other libraries -# to be shown. -Minitest.backtrace_filter = Minitest::BacktraceFilter.new - -<% unless engine? -%> -Rails::TestUnitReporter.executable = 'bin/test' -<% end -%> - -# Load fixtures from the engine -if ActiveSupport::TestCase.respond_to?(:fixture_path=) - ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__) - ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path - ActiveSupport::TestCase.file_fixture_path = ActiveSupport::TestCase.fixture_path + "/files" - ActiveSupport::TestCase.fixtures :all -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource/USAGE deleted file mode 100644 index e359cd574f..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource/USAGE +++ /dev/null @@ -1,23 +0,0 @@ -Description: - Stubs out a new resource including an empty model and controller suitable - for a restful, resource-oriented application. Pass the singular model name, - either CamelCased or under_scored, as the first argument, and an optional - list of attribute pairs. - - Attribute pairs are field:type arguments specifying the - model's attributes. Timestamps are added by default, so you don't have to - specify them by hand as 'created_at:datetime updated_at:datetime'. - - You don't have to think up every attribute up front, but it helps to - sketch out a few so you can start working with the model immediately. - - This generator invokes your configured ORM and test framework, besides - creating helpers and add routes to config/routes.rb. - - Unlike the scaffold generator, the resource generator does not create - views or add any methods to the generated controller. - -Examples: - `rails generate resource post` # no attributes - `rails generate resource post title:string body:text published:boolean` - `rails generate resource purchase order_id:integer amount:decimal` diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource/resource_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource/resource_generator.rb deleted file mode 100644 index 5ac5164af0..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource/resource_generator.rb +++ /dev/null @@ -1,19 +0,0 @@ -require "rails/generators/resource_helpers" -require "rails/generators/rails/model/model_generator" - -module Rails - module Generators - class ResourceGenerator < ModelGenerator # :nodoc: - include ResourceHelpers - - hook_for :resource_controller, required: true do |controller| - invoke controller, [ controller_name, options[:actions] ] - end - - class_option :actions, type: :array, banner: "ACTION ACTION", default: [], - desc: "Actions for the resource controller" - - hook_for :resource_route, required: true - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource_route/resource_route_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource_route/resource_route_generator.rb deleted file mode 100644 index 42705107ae..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/resource_route/resource_route_generator.rb +++ /dev/null @@ -1,51 +0,0 @@ -module Rails - module Generators - class ResourceRouteGenerator < NamedBase # :nodoc: - # Properly nests namespaces passed into a generator - # - # $ rails generate resource admin/users/products - # - # should give you - # - # namespace :admin do - # namespace :users do - # resources :products - # end - # end - def add_resource_route - return if options[:actions].present? - - # iterates over all namespaces and opens up blocks - regular_class_path.each_with_index do |namespace, index| - write("namespace :#{namespace} do", index + 1) - end - - # inserts the primary resource - write("resources :#{file_name.pluralize}", route_length + 1) - - # ends blocks - regular_class_path.each_index do |index| - write("end", route_length - index) - end - - # route prepends two spaces onto the front of the string that is passed, this corrects that. - # Also it adds a \n to the end of each line, as route already adds that - # we need to correct that too. - route route_string[2..-2] - end - - private - def route_string - @route_string ||= "" - end - - def write(str, indent) - route_string << "#{" " * indent}#{str}\n" - end - - def route_length - regular_class_path.length - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/USAGE deleted file mode 100644 index c9283eda87..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/USAGE +++ /dev/null @@ -1,41 +0,0 @@ -Description: - Scaffolds an entire resource, from model and migration to controller and - views, along with a full test suite. The resource is ready to use as a - starting point for your RESTful, resource-oriented application. - - Pass the name of the model (in singular form), either CamelCased or - under_scored, as the first argument, and an optional list of attribute - pairs. - - Attributes are field arguments specifying the model's attributes. You can - optionally pass the type and an index to each field. For instance: - 'title body:text tracking_id:integer:uniq' will generate a title field of - string type, a body with text type and a tracking_id as an integer with an - unique index. "index" could also be given instead of "uniq" if one desires - a non unique index. - - As a special case, specifying 'password:digest' will generate a - password_digest field of string type, and configure your generated model, - controller, views, and test suite for use with Active Model - has_secure_password (assuming they are using Rails defaults). - - Timestamps are added by default, so you don't have to specify them by hand - as 'created_at:datetime updated_at:datetime'. - - You don't have to think up every attribute up front, but it helps to - sketch out a few so you can start working with the resource immediately. - - For example, 'scaffold post title body:text published:boolean' gives - you a model with those three attributes, a controller that handles - the create/show/update/destroy, forms to create and edit your posts, and - an index that lists them all, as well as a resources :posts declaration - in config/routes.rb. - - If you want to remove all the generated files, run - 'rails destroy scaffold ModelName'. - -Examples: - `rails generate scaffold post` - `rails generate scaffold post title:string body:text published:boolean` - `rails generate scaffold purchase amount:decimal tracking_id:integer:uniq` - `rails generate scaffold user email:uniq password:digest` diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/scaffold_generator.rb deleted file mode 100644 index 12d6bc85b2..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/scaffold_generator.rb +++ /dev/null @@ -1,37 +0,0 @@ -require "rails/generators/rails/resource/resource_generator" - -module Rails - module Generators - class ScaffoldGenerator < ResourceGenerator # :nodoc: - remove_hook_for :resource_controller - remove_class_option :actions - - class_option :api, type: :boolean - class_option :stylesheets, type: :boolean, desc: "Generate Stylesheets" - class_option :stylesheet_engine, desc: "Engine for Stylesheets" - class_option :assets, type: :boolean - class_option :resource_route, type: :boolean - class_option :scaffold_stylesheet, type: :boolean - - def handle_skip - @options = @options.merge(stylesheets: false) unless options[:assets] - @options = @options.merge(stylesheet_engine: false) unless options[:stylesheets] && options[:scaffold_stylesheet] - @options = @options.merge(system_tests: false) if options[:api] - end - - hook_for :scaffold_controller, required: true - - hook_for :system_tests, as: :system - - hook_for :assets do |assets| - invoke assets, [controller_name] - end - - hook_for :stylesheet_engine do |stylesheet_engine| - if behavior == :invoke - invoke stylesheet_engine, [controller_name] - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/templates/scaffold.css b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/templates/scaffold.css deleted file mode 100644 index cd4f3de38d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold/templates/scaffold.css +++ /dev/null @@ -1,80 +0,0 @@ -body { - background-color: #fff; - color: #333; - margin: 33px; -} - -body, p, ol, ul, td { - font-family: verdana, arial, helvetica, sans-serif; - font-size: 13px; - line-height: 18px; -} - -pre { - background-color: #eee; - padding: 10px; - font-size: 11px; -} - -a { - color: #000; -} - -a:visited { - color: #666; -} - -a:hover { - color: #fff; - background-color: #000; -} - -th { - padding-bottom: 5px; -} - -td { - padding: 0 5px 7px; -} - -div.field, -div.actions { - margin-bottom: 10px; -} - -#notice { - color: green; -} - -.field_with_errors { - padding: 2px; - background-color: red; - display: table; -} - -#error_explanation { - width: 450px; - border: 2px solid red; - padding: 7px 7px 0; - margin-bottom: 20px; - background-color: #f0f0f0; -} - -#error_explanation h2 { - text-align: left; - font-weight: bold; - padding: 5px 5px 5px 15px; - font-size: 12px; - margin: -7px -7px 0; - background-color: #c00; - color: #fff; -} - -#error_explanation ul li { - font-size: 12px; - list-style: square; -} - -label { - display: block; -} diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/USAGE deleted file mode 100644 index 8ba4c5ccbc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/USAGE +++ /dev/null @@ -1,19 +0,0 @@ -Description: - Stubs out a scaffolded controller, its seven RESTful actions and related - views. Pass the model name, either CamelCased or under_scored. The - controller name is retrieved as a pluralized version of the model name. - - To create a controller within a module, specify the model name as a - path like 'parent_module/controller_name'. - - This generates a controller class in app/controllers and invokes helper, - template engine and test framework generators. - -Example: - `rails generate scaffold_controller CreditCard` - - Credit card controller with URLs like /credit_card/debit. - Controller: app/controllers/credit_cards_controller.rb - Test: test/controllers/credit_cards_controller_test.rb - Views: app/views/credit_cards/index.html.erb [...] - Helper: app/helpers/credit_cards_helper.rb diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb deleted file mode 100644 index cf97c22160..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb +++ /dev/null @@ -1,35 +0,0 @@ -require "rails/generators/resource_helpers" - -module Rails - module Generators - class ScaffoldControllerGenerator < NamedBase # :nodoc: - include ResourceHelpers - - check_class_collision suffix: "Controller" - - class_option :helper, type: :boolean - class_option :orm, banner: "NAME", type: :string, required: true, - desc: "ORM to generate the controller for" - class_option :api, type: :boolean, - desc: "Generates API controller" - - argument :attributes, type: :array, default: [], banner: "field:type field:type" - - def create_controller_files - template_file = options.api? ? "api_controller.rb" : "controller.rb" - template template_file, File.join("app/controllers", controller_class_path, "#{controller_file_name}_controller.rb") - end - - hook_for :template_engine, as: :scaffold do |template_engine| - invoke template_engine unless options.api? - end - - hook_for :test_framework, as: :scaffold - - # Invoke the helper using the controller name (pluralized) - hook_for :helper, as: :scaffold do |invoked| - invoke invoked, [ controller_name ] - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb deleted file mode 100644 index 400afec6dc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb +++ /dev/null @@ -1,61 +0,0 @@ -<% if namespaced? -%> -require_dependency "<%= namespaced_path %>/application_controller" - -<% end -%> -<% module_namespacing do -%> -class <%= controller_class_name %>Controller < ApplicationController - before_action :set_<%= singular_table_name %>, only: [:show, :update, :destroy] - - # GET <%= route_url %> - def index - @<%= plural_table_name %> = <%= orm_class.all(class_name) %> - - render json: <%= "@#{plural_table_name}" %> - end - - # GET <%= route_url %>/1 - def show - render json: <%= "@#{singular_table_name}" %> - end - - # POST <%= route_url %> - def create - @<%= singular_table_name %> = <%= orm_class.build(class_name, "#{singular_table_name}_params") %> - - if @<%= orm_instance.save %> - render json: <%= "@#{singular_table_name}" %>, status: :created, location: <%= "@#{singular_table_name}" %> - else - render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity - end - end - - # PATCH/PUT <%= route_url %>/1 - def update - if @<%= orm_instance.update("#{singular_table_name}_params") %> - render json: <%= "@#{singular_table_name}" %> - else - render json: <%= "@#{orm_instance.errors}" %>, status: :unprocessable_entity - end - end - - # DELETE <%= route_url %>/1 - def destroy - @<%= orm_instance.destroy %> - end - - private - # Use callbacks to share common setup or constraints between actions. - def set_<%= singular_table_name %> - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> - end - - # Only allow a trusted parameter "white list" through. - def <%= "#{singular_table_name}_params" %> - <%- if attributes_names.empty? -%> - params.fetch(:<%= singular_table_name %>, {}) - <%- else -%> - params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>) - <%- end -%> - end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/templates/controller.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/templates/controller.rb deleted file mode 100644 index 42b9e34274..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/scaffold_controller/templates/controller.rb +++ /dev/null @@ -1,68 +0,0 @@ -<% if namespaced? -%> -require_dependency "<%= namespaced_path %>/application_controller" - -<% end -%> -<% module_namespacing do -%> -class <%= controller_class_name %>Controller < ApplicationController - before_action :set_<%= singular_table_name %>, only: [:show, :edit, :update, :destroy] - - # GET <%= route_url %> - def index - @<%= plural_table_name %> = <%= orm_class.all(class_name) %> - end - - # GET <%= route_url %>/1 - def show - end - - # GET <%= route_url %>/new - def new - @<%= singular_table_name %> = <%= orm_class.build(class_name) %> - end - - # GET <%= route_url %>/1/edit - def edit - end - - # POST <%= route_url %> - def create - @<%= singular_table_name %> = <%= orm_class.build(class_name, "#{singular_table_name}_params") %> - - if @<%= orm_instance.save %> - redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully created.'" %> - else - render :new - end - end - - # PATCH/PUT <%= route_url %>/1 - def update - if @<%= orm_instance.update("#{singular_table_name}_params") %> - redirect_to @<%= singular_table_name %>, notice: <%= "'#{human_name} was successfully updated.'" %> - else - render :edit - end - end - - # DELETE <%= route_url %>/1 - def destroy - @<%= orm_instance.destroy %> - redirect_to <%= index_helper %>_url, notice: <%= "'#{human_name} was successfully destroyed.'" %> - end - - private - # Use callbacks to share common setup or constraints between actions. - def set_<%= singular_table_name %> - @<%= singular_table_name %> = <%= orm_class.find(class_name, "params[:id]") %> - end - - # Only allow a trusted parameter "white list" through. - def <%= "#{singular_table_name}_params" %> - <%- if attributes_names.empty? -%> - params.fetch(:<%= singular_table_name %>, {}) - <%- else -%> - params.require(:<%= singular_table_name %>).permit(<%= attributes_names.map { |name| ":#{name}" }.join(', ') %>) - <%- end -%> - end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/system_test/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/system_test/USAGE deleted file mode 100644 index f11a99e008..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/system_test/USAGE +++ /dev/null @@ -1,10 +0,0 @@ -Description: - Stubs out a new system test. Pass the name of the test, either - CamelCased or under_scored, as an argument. - - This generator invokes the current system tool, which defaults to - TestUnit. - -Example: - `rails generate system_test GeneralStories` creates a GeneralStories - system test in test/system/general_stories_test.rb diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/system_test/system_test_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/system_test/system_test_generator.rb deleted file mode 100644 index 901120e892..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/system_test/system_test_generator.rb +++ /dev/null @@ -1,7 +0,0 @@ -module Rails - module Generators - class SystemTestGenerator < NamedBase # :nodoc: - hook_for :system_tests, as: :system - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/USAGE b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/USAGE deleted file mode 100644 index dbe9bbaf08..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/USAGE +++ /dev/null @@ -1,9 +0,0 @@ -Description: - Stubs out a new Rake task. Pass the namespace name, and a list of tasks as arguments. - - This generates a task file in lib/tasks. - -Example: - `rails generate task feeds fetch erase add` - - Task: lib/tasks/feeds.rake \ No newline at end of file diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/task_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/task_generator.rb deleted file mode 100644 index bb96bdf0dd..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/task_generator.rb +++ /dev/null @@ -1,11 +0,0 @@ -module Rails - module Generators - class TaskGenerator < NamedBase # :nodoc: - argument :actions, type: :array, default: [], banner: "action action" - - def create_task_files - template "task.rb", File.join("lib/tasks", "#{file_name}.rake") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/templates/task.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/templates/task.rb deleted file mode 100644 index 1e3ed5f158..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/rails/task/templates/task.rb +++ /dev/null @@ -1,8 +0,0 @@ -namespace :<%= file_name %> do -<% actions.each do |action| -%> - desc "TODO" - task <%= action %>: :environment do - end - -<% end -%> -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/resource_helpers.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/resource_helpers.rb deleted file mode 100644 index e7cb722473..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/resource_helpers.rb +++ /dev/null @@ -1,85 +0,0 @@ -require "rails/generators/active_model" -require "rails/generators/model_helpers" - -module Rails - module Generators - # Deal with controller names on scaffold and add some helpers to deal with - # ActiveModel. - module ResourceHelpers # :nodoc: - def self.included(base) #:nodoc: - base.include(Rails::Generators::ModelHelpers) - base.class_option :model_name, type: :string, desc: "ModelName to be used" - end - - # Set controller variables on initialization. - def initialize(*args) #:nodoc: - super - controller_name = name - if options[:model_name] - self.name = options[:model_name] - assign_names!(name) - end - - assign_controller_names!(controller_name.pluralize) - end - - # TODO Change this to private once we've dropped Ruby 2.2 support. - # Workaround for Ruby 2.2 "private attribute?" warning. - protected - - attr_reader :controller_name, :controller_file_name - - private - - def controller_class_path - if options[:model_name] - @controller_class_path - else - class_path - end - end - - def assign_controller_names!(name) - @controller_name = name - @controller_class_path = name.include?("/") ? name.split("/") : name.split("::") - @controller_class_path.map!(&:underscore) - @controller_file_name = @controller_class_path.pop - end - - def controller_file_path - @controller_file_path ||= (controller_class_path + [controller_file_name]).join("/") - end - - def controller_class_name - (controller_class_path + [controller_file_name]).map!(&:camelize).join("::") - end - - def controller_i18n_scope - @controller_i18n_scope ||= controller_file_path.tr("/", ".") - end - - # Loads the ORM::Generators::ActiveModel class. This class is responsible - # to tell scaffold entities how to generate a specific method for the - # ORM. Check Rails::Generators::ActiveModel for more information. - def orm_class - @orm_class ||= begin - # Raise an error if the class_option :orm was not defined. - unless self.class.class_options[:orm] - raise "You need to have :orm as class option to invoke orm_class and orm_instance" - end - - begin - "#{options[:orm].to_s.camelize}::Generators::ActiveModel".constantize - rescue NameError - Rails::Generators::ActiveModel - end - end - end - - # Initialize ORM::Generators::ActiveModel to access instance methods. - def orm_instance(name = singular_table_name) - @orm_instance ||= orm_class.new(name) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_case.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_case.rb deleted file mode 100644 index 3eec929aeb..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_case.rb +++ /dev/null @@ -1,35 +0,0 @@ -require "rails/generators" -require "rails/generators/testing/behaviour" -require "rails/generators/testing/setup_and_teardown" -require "rails/generators/testing/assertions" -require "fileutils" - -module Rails - module Generators - # Disable color in output. Easier to debug. - no_color! - - # This class provides a TestCase for testing generators. To setup, you need - # just to configure the destination and set which generator is being tested: - # - # class AppGeneratorTest < Rails::Generators::TestCase - # tests AppGenerator - # destination File.expand_path("../tmp", File.dirname(__FILE__)) - # end - # - # If you want to ensure your destination root is clean before running each test, - # you can set a setup callback: - # - # class AppGeneratorTest < Rails::Generators::TestCase - # tests AppGenerator - # destination File.expand_path("../tmp", File.dirname(__FILE__)) - # setup :prepare_destination - # end - class TestCase < ActiveSupport::TestCase - include Rails::Generators::Testing::Behaviour - include Rails::Generators::Testing::SetupAndTeardown - include Rails::Generators::Testing::Assertions - include FileUtils - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit.rb deleted file mode 100644 index 722efcf492..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit.rb +++ /dev/null @@ -1,8 +0,0 @@ -require "rails/generators/named_base" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class Base < Rails::Generators::NamedBase # :nodoc: - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/controller/controller_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/controller/controller_generator.rb deleted file mode 100644 index ac528d94f1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/controller/controller_generator.rb +++ /dev/null @@ -1,15 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class ControllerGenerator < Base # :nodoc: - argument :actions, type: :array, default: [], banner: "action action" - check_class_collision suffix: "ControllerTest" - - def create_test_files - template "functional_test.rb", - File.join("test/controllers", class_path, "#{file_name}_controller_test.rb") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/controller/templates/functional_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/controller/templates/functional_test.rb deleted file mode 100644 index ff41fef9e9..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/controller/templates/functional_test.rb +++ /dev/null @@ -1,23 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= class_name %>ControllerTest < ActionDispatch::IntegrationTest -<% if mountable_engine? -%> - include Engine.routes.url_helpers - -<% end -%> -<% if actions.empty? -%> - # test "the truth" do - # assert true - # end -<% else -%> -<% actions.each do |action| -%> - test "should get <%= action %>" do - get <%= url_helper_prefix %>_<%= action %>_url - assert_response :success - end - -<% end -%> -<% end -%> -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/generator/generator_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/generator/generator_generator.rb deleted file mode 100644 index 6b6e094453..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/generator/generator_generator.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class GeneratorGenerator < Base # :nodoc: - check_class_collision suffix: "GeneratorTest" - - class_option :namespace, type: :boolean, default: true, - desc: "Namespace generator under lib/generators/name" - - def create_generator_files - template "generator_test.rb", File.join("test/lib/generators", class_path, "#{file_name}_generator_test.rb") - end - - private - - def generator_path - if options[:namespace] - File.join("generators", regular_class_path, file_name, "#{file_name}_generator") - else - File.join("generators", regular_class_path, "#{file_name}_generator") - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/generator/templates/generator_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/generator/templates/generator_test.rb deleted file mode 100644 index a7f1fc4fba..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/generator/templates/generator_test.rb +++ /dev/null @@ -1,16 +0,0 @@ -require 'test_helper' -require '<%= generator_path %>' - -<% module_namespacing do -%> -class <%= class_name %>GeneratorTest < Rails::Generators::TestCase - tests <%= class_name %>Generator - destination Rails.root.join('tmp/generators') - setup :prepare_destination - - # test "generator runs without errors" do - # assert_nothing_raised do - # run_generator ["arguments"] - # end - # end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/helper/helper_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/helper/helper_generator.rb deleted file mode 100644 index 6674a15fa3..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/helper/helper_generator.rb +++ /dev/null @@ -1,9 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class HelperGenerator < Base # :nodoc: - # Rails does not generate anything here. - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/integration/integration_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/integration/integration_generator.rb deleted file mode 100644 index 9d065c1297..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/integration/integration_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class IntegrationGenerator < Base # :nodoc: - check_class_collision suffix: "Test" - - def create_test_files - template "integration_test.rb", File.join("test/integration", class_path, "#{file_name}_test.rb") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/integration/templates/integration_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/integration/templates/integration_test.rb deleted file mode 100644 index 118e0f1271..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/integration/templates/integration_test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= class_name %>Test < ActionDispatch::IntegrationTest - # test "the truth" do - # assert true - # end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/job/job_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/job/job_generator.rb deleted file mode 100644 index 6975252b99..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/job/job_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class JobGenerator < Base # :nodoc: - check_class_collision suffix: "JobTest" - - def create_test_file - template "unit_test.rb.erb", File.join("test/jobs", class_path, "#{file_name}_job_test.rb") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/job/templates/unit_test.rb.erb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/job/templates/unit_test.rb.erb deleted file mode 100644 index f5351d0ec6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/job/templates/unit_test.rb.erb +++ /dev/null @@ -1,9 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= class_name %>JobTest < ActiveJob::TestCase - # test "the truth" do - # assert true - # end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/mailer_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/mailer_generator.rb deleted file mode 100644 index 67bff8e4f9..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/mailer_generator.rb +++ /dev/null @@ -1,26 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class MailerGenerator < Base # :nodoc: - argument :actions, type: :array, default: [], banner: "method method" - - def check_class_collision - class_collisions "#{class_name}MailerTest", "#{class_name}MailerPreview" - end - - def create_test_files - template "functional_test.rb", File.join("test/mailers", class_path, "#{file_name}_mailer_test.rb") - end - - def create_preview_files - template "preview.rb", File.join("test/mailers/previews", class_path, "#{file_name}_mailer_preview.rb") - end - - private - def file_name - @_file_name ||= super.gsub(/_mailer/i, "") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/templates/functional_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/templates/functional_test.rb deleted file mode 100644 index a2f2d30de5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/templates/functional_test.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= class_name %>MailerTest < ActionMailer::TestCase -<% actions.each do |action| -%> - test "<%= action %>" do - mail = <%= class_name %>Mailer.<%= action %> - assert_equal <%= action.to_s.humanize.inspect %>, mail.subject - assert_equal ["to@example.org"], mail.to - assert_equal ["from@example.com"], mail.from - assert_match "Hi", mail.body.encoded - end - -<% end -%> -<% if actions.blank? -%> - # test "the truth" do - # assert true - # end -<% end -%> -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/templates/preview.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/templates/preview.rb deleted file mode 100644 index b063cbc47b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/mailer/templates/preview.rb +++ /dev/null @@ -1,13 +0,0 @@ -<% module_namespacing do -%> -# Preview all emails at http://localhost:3000/rails/mailers/<%= file_path %>_mailer -class <%= class_name %>MailerPreview < ActionMailer::Preview -<% actions.each do |action| -%> - - # Preview this email at http://localhost:3000/rails/mailers/<%= file_path %>_mailer/<%= action %> - def <%= action %> - <%= class_name %>Mailer.<%= action %> - end -<% end -%> - -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/model_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/model_generator.rb deleted file mode 100644 index 99495d5247..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/model_generator.rb +++ /dev/null @@ -1,35 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class ModelGenerator < Base # :nodoc: - RESERVED_YAML_KEYWORDS = %w(y yes n no true false on off null) - - argument :attributes, type: :array, default: [], banner: "field:type field:type" - class_option :fixture, type: :boolean - - check_class_collision suffix: "Test" - - def create_test_file - template "unit_test.rb", File.join("test/models", class_path, "#{file_name}_test.rb") - end - - hook_for :fixture_replacement - - def create_fixture_file - if options[:fixture] && options[:fixture_replacement].nil? - template "fixtures.yml", File.join("test/fixtures", class_path, "#{fixture_file_name}.yml") - end - end - - private - def yaml_key_value(key, value) - if RESERVED_YAML_KEYWORDS.include?(key.downcase) - "'#{key}': #{value}" - else - "#{key}: #{value}" - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/templates/fixtures.yml b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/templates/fixtures.yml deleted file mode 100644 index 0681780c97..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/templates/fixtures.yml +++ /dev/null @@ -1,29 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html -<% unless attributes.empty? -%> -<% %w(one two).each do |name| %> -<%= name %>: -<% attributes.each do |attribute| -%> - <%- if attribute.password_digest? -%> - password_digest: <%%= BCrypt::Password.create('secret') %> - <%- elsif attribute.reference? -%> - <%= yaml_key_value(attribute.column_name.sub(/_id$/, ''), attribute.default || name) %> - <%- else -%> - <%= yaml_key_value(attribute.column_name, attribute.default) %> - <%- end -%> - <%- if attribute.polymorphic? -%> - <%= yaml_key_value("#{attribute.name}_type", attribute.human_name) %> - <%- end -%> -<% end -%> -<% end -%> -<% else -%> - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/templates/unit_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/templates/unit_test.rb deleted file mode 100644 index c9bc7d5b90..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/model/templates/unit_test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= class_name %>Test < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/plugin_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/plugin_generator.rb deleted file mode 100644 index f1c9b6da5b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/plugin_generator.rb +++ /dev/null @@ -1,13 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class PluginGenerator < Base # :nodoc: - check_class_collision suffix: "Test" - - def create_test_files - directory ".", "test" - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt deleted file mode 100644 index 0cbae1120e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt +++ /dev/null @@ -1,7 +0,0 @@ -require 'test_helper' - -class <%= class_name %>Test < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/templates/test_helper.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/templates/test_helper.rb deleted file mode 100644 index 30a861f09d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/plugin/templates/test_helper.rb +++ /dev/null @@ -1,2 +0,0 @@ -require 'active_support/testing/autorun' -require 'active_support' diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb deleted file mode 100644 index 292db35121..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +++ /dev/null @@ -1,46 +0,0 @@ -require "rails/generators/test_unit" -require "rails/generators/resource_helpers" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class ScaffoldGenerator < Base # :nodoc: - include Rails::Generators::ResourceHelpers - - check_class_collision suffix: "ControllerTest" - - class_option :api, type: :boolean, - desc: "Generates API functional tests" - - argument :attributes, type: :array, default: [], banner: "field:type field:type" - - def create_test_files - template_file = options.api? ? "api_functional_test.rb" : "functional_test.rb" - template template_file, - File.join("test/controllers", controller_class_path, "#{controller_file_name}_controller_test.rb") - end - - def fixture_name - @fixture_name ||= - if mountable_engine? - (namespace_dirs + [table_name]).join("_") - else - table_name - end - end - - private - - def attributes_hash - return if attributes_names.empty? - - attributes_names.map do |name| - if %w(password password_confirmation).include?(name) && attributes.any?(&:password_digest?) - "#{name}: 'secret'" - else - "#{name}: @#{singular_table_name}.#{name}" - end - end.sort.join(", ") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb deleted file mode 100644 index c469c188e6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb +++ /dev/null @@ -1,44 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTest - <%- if mountable_engine? -%> - include Engine.routes.url_helpers - - <%- end -%> - setup do - @<%= singular_table_name %> = <%= fixture_name %>(:one) - end - - test "should get index" do - get <%= index_helper %>_url, as: :json - assert_response :success - end - - test "should create <%= singular_table_name %>" do - assert_difference('<%= class_name %>.count') do - post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }, as: :json - end - - assert_response 201 - end - - test "should show <%= singular_table_name %>" do - get <%= show_helper %>, as: :json - assert_response :success - end - - test "should update <%= singular_table_name %>" do - patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> }, as: :json - assert_response 200 - end - - test "should destroy <%= singular_table_name %>" do - assert_difference('<%= class_name %>.count', -1) do - delete <%= show_helper %>, as: :json - end - - assert_response 204 - end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb deleted file mode 100644 index c33375b7b4..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/scaffold/templates/functional_test.rb +++ /dev/null @@ -1,54 +0,0 @@ -require 'test_helper' - -<% module_namespacing do -%> -class <%= controller_class_name %>ControllerTest < ActionDispatch::IntegrationTest - <%- if mountable_engine? -%> - include Engine.routes.url_helpers - - <%- end -%> - setup do - @<%= singular_table_name %> = <%= fixture_name %>(:one) - end - - test "should get index" do - get <%= index_helper %>_url - assert_response :success - end - - test "should get new" do - get <%= new_helper %> - assert_response :success - end - - test "should create <%= singular_table_name %>" do - assert_difference('<%= class_name %>.count') do - post <%= index_helper %>_url, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } - end - - assert_redirected_to <%= singular_table_name %>_url(<%= class_name %>.last) - end - - test "should show <%= singular_table_name %>" do - get <%= show_helper %> - assert_response :success - end - - test "should get edit" do - get <%= edit_helper %> - assert_response :success - end - - test "should update <%= singular_table_name %>" do - patch <%= show_helper %>, params: { <%= "#{singular_table_name}: { #{attributes_hash} }" %> } - assert_redirected_to <%= singular_table_name %>_url(<%= "@#{singular_table_name}" %>) - end - - test "should destroy <%= singular_table_name %>" do - assert_difference('<%= class_name %>.count', -1) do - delete <%= show_helper %> - end - - assert_redirected_to <%= index_helper %>_url - end -end -<% end -%> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/system_generator.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/system_generator.rb deleted file mode 100644 index aec415a4e5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/system_generator.rb +++ /dev/null @@ -1,17 +0,0 @@ -require "rails/generators/test_unit" - -module TestUnit # :nodoc: - module Generators # :nodoc: - class SystemGenerator < Base # :nodoc: - check_class_collision suffix: "Test" - - def create_test_files - if !File.exist?(File.join("test/application_system_test_case.rb")) - template "application_system_test_case.rb", File.join("test", "application_system_test_case.rb") - end - - template "system_test.rb", File.join("test/system", "#{file_name.pluralize}_test.rb") - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/templates/application_system_test_case.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/templates/application_system_test_case.rb deleted file mode 100644 index d19212abd5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/templates/application_system_test_case.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "test_helper" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :chrome, screen_size: [1400, 1400] -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/templates/system_test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/templates/system_test.rb deleted file mode 100644 index b5ce2ba5c8..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/test_unit/system/templates/system_test.rb +++ /dev/null @@ -1,9 +0,0 @@ -require "application_system_test_case" - -class <%= class_name.pluralize %>Test < ApplicationSystemTestCase - # test "visiting the index" do - # visit <%= plural_table_name %>_url - # - # assert_selector "h1", text: "<%= class_name %>" - # end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/assertions.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/assertions.rb deleted file mode 100644 index 1cabf4e28c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/assertions.rb +++ /dev/null @@ -1,121 +0,0 @@ -module Rails - module Generators - module Testing - module Assertions - # Asserts a given file exists. You need to supply an absolute path or a path relative - # to the configured destination: - # - # assert_file "config/environment.rb" - # - # You can also give extra arguments. If the argument is a regexp, it will check if the - # regular expression matches the given file content. If it's a string, it compares the - # file with the given string: - # - # assert_file "config/environment.rb", /initialize/ - # - # Finally, when a block is given, it yields the file content: - # - # assert_file "app/controllers/products_controller.rb" do |controller| - # assert_instance_method :index, controller do |index| - # assert_match(/Product\.all/, index) - # end - # end - def assert_file(relative, *contents) - absolute = File.expand_path(relative, destination_root) - assert File.exist?(absolute), "Expected file #{relative.inspect} to exist, but does not" - - read = File.read(absolute) if block_given? || !contents.empty? - yield read if block_given? - - contents.each do |content| - case content - when String - assert_equal content, read - when Regexp - assert_match content, read - end - end - end - alias :assert_directory :assert_file - - # Asserts a given file does not exist. You need to supply an absolute path or a - # path relative to the configured destination: - # - # assert_no_file "config/random.rb" - def assert_no_file(relative) - absolute = File.expand_path(relative, destination_root) - assert !File.exist?(absolute), "Expected file #{relative.inspect} to not exist, but does" - end - alias :assert_no_directory :assert_no_file - - # Asserts a given migration exists. You need to supply an absolute path or a - # path relative to the configured destination: - # - # assert_migration "db/migrate/create_products.rb" - # - # This method manipulates the given path and tries to find any migration which - # matches the migration name. For example, the call above is converted to: - # - # assert_file "db/migrate/003_create_products.rb" - # - # Consequently, assert_migration accepts the same arguments has assert_file. - def assert_migration(relative, *contents, &block) - file_name = migration_file_name(relative) - assert file_name, "Expected migration #{relative} to exist, but was not found" - assert_file file_name, *contents, &block - end - - # Asserts a given migration does not exist. You need to supply an absolute path or a - # path relative to the configured destination: - # - # assert_no_migration "db/migrate/create_products.rb" - def assert_no_migration(relative) - file_name = migration_file_name(relative) - assert_nil file_name, "Expected migration #{relative} to not exist, but found #{file_name}" - end - - # Asserts the given class method exists in the given content. This method does not detect - # class methods inside (class << self), only class methods which starts with "self.". - # When a block is given, it yields the content of the method. - # - # assert_migration "db/migrate/create_products.rb" do |migration| - # assert_class_method :up, migration do |up| - # assert_match(/create_table/, up) - # end - # end - def assert_class_method(method, content, &block) - assert_instance_method "self.#{method}", content, &block - end - - # Asserts the given method exists in the given content. When a block is given, - # it yields the content of the method. - # - # assert_file "app/controllers/products_controller.rb" do |controller| - # assert_instance_method :index, controller do |index| - # assert_match(/Product\.all/, index) - # end - # end - def assert_instance_method(method, content) - assert content =~ /(\s+)def #{method}(\(.+\))?(.*?)\n\1end/m, "Expected to have method #{method}" - yield $3.strip if block_given? - end - alias :assert_method :assert_instance_method - - # Asserts the given attribute type gets translated to a field type - # properly: - # - # assert_field_type :date, :date_select - def assert_field_type(attribute_type, field_type) - assert_equal(field_type, create_generated_attribute(attribute_type).field_type) - end - - # Asserts the given attribute type gets a proper default value: - # - # assert_field_default_value :string, "MyString" - def assert_field_default_value(attribute_type, value) - assert_equal(value, create_generated_attribute(attribute_type).default) - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/behaviour.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/behaviour.rb deleted file mode 100644 index 64d641d096..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/behaviour.rb +++ /dev/null @@ -1,109 +0,0 @@ -require "active_support/core_ext/class/attribute" -require "active_support/core_ext/module/delegation" -require "active_support/core_ext/hash/reverse_merge" -require "active_support/core_ext/kernel/reporting" -require "active_support/testing/stream" -require "active_support/concern" -require "rails/generators" - -module Rails - module Generators - module Testing - module Behaviour - extend ActiveSupport::Concern - include ActiveSupport::Testing::Stream - - included do - class_attribute :destination_root, :current_path, :generator_class, :default_arguments - - # Generators frequently change the current path using +FileUtils.cd+. - # So we need to store the path at file load and revert back to it after each test. - self.current_path = File.expand_path(Dir.pwd) - self.default_arguments = [] - end - - module ClassMethods - # Sets which generator should be tested: - # - # tests AppGenerator - def tests(klass) - self.generator_class = klass - end - - # Sets default arguments on generator invocation. This can be overwritten when - # invoking it. - # - # arguments %w(app_name --skip-active-record) - def arguments(array) - self.default_arguments = array - end - - # Sets the destination of generator files: - # - # destination File.expand_path("../tmp", File.dirname(__FILE__)) - def destination(path) - self.destination_root = path - end - end - - # Runs the generator configured for this class. The first argument is an array like - # command line arguments: - # - # class AppGeneratorTest < Rails::Generators::TestCase - # tests AppGenerator - # destination File.expand_path("../tmp", File.dirname(__FILE__)) - # setup :prepare_destination - # - # test "database.yml is not created when skipping Active Record" do - # run_generator %w(myapp --skip-active-record) - # assert_no_file "config/database.yml" - # end - # end - # - # You can provide a configuration hash as second argument. This method returns the output - # printed by the generator. - def run_generator(args = default_arguments, config = {}) - capture(:stdout) do - args += ["--skip-bundle"] unless args.include? "--dev" - generator_class.start(args, config.reverse_merge(destination_root: destination_root)) - end - end - - # Instantiate the generator. - def generator(args = default_arguments, options = {}, config = {}) - @generator ||= generator_class.new(args, options, config.reverse_merge(destination_root: destination_root)) - end - - # Create a Rails::Generators::GeneratedAttribute by supplying the - # attribute type and, optionally, the attribute name: - # - # create_generated_attribute(:string, 'name') - def create_generated_attribute(attribute_type, name = "test", index = nil) - Rails::Generators::GeneratedAttribute.parse([name, attribute_type, index].compact.join(":")) - end - - private - - def destination_root_is_set? - raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root - end - - def ensure_current_path - cd current_path - end - - # Clears all files and directories in destination. - def prepare_destination # :doc: - rm_rf(destination_root) - mkdir_p(destination_root) - end - - def migration_file_name(relative) - absolute = File.expand_path(relative, destination_root) - dirname, file_name = File.dirname(absolute), File.basename(absolute).sub(/\.rb$/, "") - Dir.glob("#{dirname}/[0-9]*_*.rb").grep(/\d+_#{file_name}.rb$/).first - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/setup_and_teardown.rb b/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/setup_and_teardown.rb deleted file mode 100644 index 73102a283f..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/generators/testing/setup_and_teardown.rb +++ /dev/null @@ -1,18 +0,0 @@ -module Rails - module Generators - module Testing - module SetupAndTeardown - def setup # :nodoc: - destination_root_is_set? - ensure_current_path - super - end - - def teardown # :nodoc: - ensure_current_path - super - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/info.rb b/debian/gems-compat/railties-5.1.7/lib/rails/info.rb deleted file mode 100644 index fc064dac32..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/info.rb +++ /dev/null @@ -1,102 +0,0 @@ -require "cgi" - -module Rails - # This module helps build the runtime properties that are displayed in - # Rails::InfoController responses. These include the active Rails version, - # Ruby version, Rack version, and so on. - module Info - mattr_accessor :properties - class << (@@properties = []) - def names - map(&:first) - end - - def value_for(property_name) - if property = assoc(property_name) - property.last - end - end - end - - class << self #:nodoc: - def property(name, value = nil) - value ||= yield - properties << [name, value] if value - rescue Exception - end - - def to_s - column_width = properties.names.map(&:length).max - info = properties.map do |name, value| - value = value.join(", ") if value.is_a?(Array) - "%-#{column_width}s %s" % [name, value] - end - info.unshift "About your application's environment" - info * "\n" - end - - alias inspect to_s - - def to_html - "".tap do |table| - properties.each do |(name, value)| - table << %() - formatted_value = if value.kind_of?(Array) - "
      " + value.map { |v| "
    • #{CGI.escapeHTML(v.to_s)}
    • " }.join + "
    " - else - CGI.escapeHTML(value.to_s) - end - table << %() - end - table << "
    #{CGI.escapeHTML(name.to_s)}#{formatted_value}
    " - end - end - end - - # The Rails version. - property "Rails version" do - Rails.version.to_s - end - - # The Ruby version and platform, e.g. "2.0.0-p247 (x86_64-darwin12.4.0)". - property "Ruby version" do - "#{RUBY_VERSION}-p#{RUBY_PATCHLEVEL} (#{RUBY_PLATFORM})" - end - - # The RubyGems version, if it's installed. - property "RubyGems version" do - Gem::RubyGemsVersion - end - - property "Rack version" do - ::Rack.release - end - - property "JavaScript Runtime" do - ExecJS.runtime.name - end - - property "Middleware" do - Rails.configuration.middleware.map(&:inspect) - end - - # The application's location on the filesystem. - property "Application root" do - File.expand_path(Rails.root) - end - - # The current Rails environment (development, test, or production). - property "Environment" do - Rails.env - end - - # The name of the database adapter for the current environment. - property "Database adapter" do - ActiveRecord::Base.configurations[Rails.env]["adapter"] - end - - property "Database schema version" do - ActiveRecord::Migrator.current_version rescue nil - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/info_controller.rb b/debian/gems-compat/railties-5.1.7/lib/rails/info_controller.rb deleted file mode 100644 index 8b553aea79..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/info_controller.rb +++ /dev/null @@ -1,44 +0,0 @@ -require "rails/application_controller" -require "action_dispatch/routing/inspector" - -class Rails::InfoController < Rails::ApplicationController # :nodoc: - prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH - layout -> { request.xhr? ? false : "application" } - - before_action :require_local! - - def index - redirect_to action: :routes - end - - def properties - @info = Rails::Info.to_html - @page_title = "Properties" - end - - def routes - if path = params[:path] - path = URI.parser.escape path - normalized_path = with_leading_slash path - render json: { - exact: match_route { |it| it.match normalized_path }, - fuzzy: match_route { |it| it.spec.to_s.match path } - } - else - @routes_inspector = ActionDispatch::Routing::RoutesInspector.new(_routes.routes) - @page_title = "Routes" - end - end - - private - - def match_route - _routes.routes.select { |route| - yield route.path - }.map { |route| route.path.spec.to_s } - end - - def with_leading_slash(path) - ("/" + path).squeeze("/") - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/initializable.rb b/debian/gems-compat/railties-5.1.7/lib/rails/initializable.rb deleted file mode 100644 index a2615d5efd..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/initializable.rb +++ /dev/null @@ -1,93 +0,0 @@ -require "tsort" - -module Rails - module Initializable - def self.included(base) #:nodoc: - base.extend ClassMethods - end - - class Initializer - attr_reader :name, :block - - def initialize(name, context, options, &block) - options[:group] ||= :default - @name, @context, @options, @block = name, context, options, block - end - - def before - @options[:before] - end - - def after - @options[:after] - end - - def belongs_to?(group) - @options[:group] == group || @options[:group] == :all - end - - def run(*args) - @context.instance_exec(*args, &block) - end - - def bind(context) - return self if @context - Initializer.new(@name, context, @options, &block) - end - - def context_class - @context.class - end - end - - class Collection < Array - include TSort - - alias :tsort_each_node :each - def tsort_each_child(initializer, &block) - select { |i| i.before == initializer.name || i.name == initializer.after }.each(&block) - end - - def +(other) - Collection.new(to_a + other.to_a) - end - end - - def run_initializers(group = :default, *args) - return if instance_variable_defined?(:@ran) - initializers.tsort_each do |initializer| - initializer.run(*args) if initializer.belongs_to?(group) - end - @ran = true - end - - def initializers - @initializers ||= self.class.initializers_for(self) - end - - module ClassMethods - def initializers - @initializers ||= Collection.new - end - - def initializers_chain - initializers = Collection.new - ancestors.reverse_each do |klass| - next unless klass.respond_to?(:initializers) - initializers = initializers + klass.initializers - end - initializers - end - - def initializers_for(binding) - Collection.new(initializers_chain.map { |i| i.bind(binding) }) - end - - def initializer(name, opts = {}, &blk) - raise ArgumentError, "A block must be passed when defining an initializer" unless blk - opts[:after] ||= initializers.last.name unless initializers.empty? || initializers.find { |i| i.name == opts[:before] } - initializers << Initializer.new(name, nil, opts, &blk) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/mailers_controller.rb b/debian/gems-compat/railties-5.1.7/lib/rails/mailers_controller.rb deleted file mode 100644 index 000ce40fbc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/mailers_controller.rb +++ /dev/null @@ -1,79 +0,0 @@ -require "rails/application_controller" - -class Rails::MailersController < Rails::ApplicationController # :nodoc: - prepend_view_path ActionDispatch::DebugExceptions::RESCUES_TEMPLATE_PATH - - before_action :require_local!, unless: :show_previews? - before_action :find_preview, only: :preview - - def index - @previews = ActionMailer::Preview.all - @page_title = "Mailer Previews" - end - - def preview - if params[:path] == @preview.preview_name - @page_title = "Mailer Previews for #{@preview.preview_name}" - render action: "mailer" - else - @email_action = File.basename(params[:path]) - - if @preview.email_exists?(@email_action) - @email = @preview.call(@email_action) - - if params[:part] - part_type = Mime::Type.lookup(params[:part]) - - if part = find_part(part_type) - response.content_type = part_type - render plain: part.respond_to?(:decoded) ? part.decoded : part - else - raise AbstractController::ActionNotFound, "Email part '#{part_type}' not found in #{@preview.name}##{@email_action}" - end - else - @part = find_preferred_part(request.format, Mime[:html], Mime[:text]) - render action: "email", layout: false, formats: %w[html] - end - else - raise AbstractController::ActionNotFound, "Email '#{@email_action}' not found in #{@preview.name}" - end - end - end - - private - def show_previews? # :doc: - ActionMailer::Base.show_previews - end - - def find_preview # :doc: - candidates = [] - params[:path].to_s.scan(%r{/|$}) { candidates << $` } - preview = candidates.detect { |candidate| ActionMailer::Preview.exists?(candidate) } - - if preview - @preview = ActionMailer::Preview.find(preview) - else - raise AbstractController::ActionNotFound, "Mailer preview '#{params[:path]}' not found" - end - end - - def find_preferred_part(*formats) # :doc: - formats.each do |format| - if part = @email.find_first_mime_type(format) - return part - end - end - - if formats.any? { |f| @email.mime_type == f } - @email - end - end - - def find_part(format) # :doc: - if part = @email.find_first_mime_type(format) - part - elsif @email.mime_type == format - @email - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/paths.rb b/debian/gems-compat/railties-5.1.7/lib/rails/paths.rb deleted file mode 100644 index 6bdb673215..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/paths.rb +++ /dev/null @@ -1,225 +0,0 @@ -module Rails - module Paths - # This object is an extended hash that behaves as root of the Rails::Paths system. - # It allows you to collect information about how you want to structure your application - # paths through a Hash-like API. It requires you to give a physical path on initialization. - # - # root = Root.new "/rails" - # root.add "app/controllers", eager_load: true - # - # The above command creates a new root object and adds "app/controllers" as a path. - # This means we can get a Rails::Paths::Path object back like below: - # - # path = root["app/controllers"] - # path.eager_load? # => true - # path.is_a?(Rails::Paths::Path) # => true - # - # The +Path+ object is simply an enumerable and allows you to easily add extra paths: - # - # path.is_a?(Enumerable) # => true - # path.to_ary.inspect # => ["app/controllers"] - # - # path << "lib/controllers" - # path.to_ary.inspect # => ["app/controllers", "lib/controllers"] - # - # Notice that when you add a path using +add+, the path object created already - # contains the path with the same path value given to +add+. In some situations, - # you may not want this behavior, so you can give :with as option. - # - # root.add "config/routes", with: "config/routes.rb" - # root["config/routes"].inspect # => ["config/routes.rb"] - # - # The +add+ method accepts the following options as arguments: - # eager_load, autoload, autoload_once, and glob. - # - # Finally, the +Path+ object also provides a few helpers: - # - # root = Root.new "/rails" - # root.add "app/controllers" - # - # root["app/controllers"].expanded # => ["/rails/app/controllers"] - # root["app/controllers"].existent # => ["/rails/app/controllers"] - # - # Check the Rails::Paths::Path documentation for more information. - class Root - attr_accessor :path - - def initialize(path) - @path = path - @root = {} - end - - def []=(path, value) - glob = self[path] ? self[path].glob : nil - add(path, with: value, glob: glob) - end - - def add(path, options = {}) - with = Array(options.fetch(:with, path)) - @root[path] = Path.new(self, path, with, options) - end - - def [](path) - @root[path] - end - - def values - @root.values - end - - def keys - @root.keys - end - - def values_at(*list) - @root.values_at(*list) - end - - def all_paths - values.tap(&:uniq!) - end - - def autoload_once - filter_by(&:autoload_once?) - end - - def eager_load - filter_by(&:eager_load?) - end - - def autoload_paths - filter_by(&:autoload?) - end - - def load_paths - filter_by(&:load_path?) - end - - private - - def filter_by(&block) - all_paths.find_all(&block).flat_map { |path| - paths = path.existent - paths - path.children.flat_map { |p| yield(p) ? [] : p.existent } - }.uniq - end - end - - class Path - include Enumerable - - attr_accessor :glob - - def initialize(root, current, paths, options = {}) - @paths = paths - @current = current - @root = root - @glob = options[:glob] - - options[:autoload_once] ? autoload_once! : skip_autoload_once! - options[:eager_load] ? eager_load! : skip_eager_load! - options[:autoload] ? autoload! : skip_autoload! - options[:load_path] ? load_path! : skip_load_path! - end - - def absolute_current # :nodoc: - File.expand_path(@current, @root.path) - end - - def children - keys = @root.keys.find_all { |k| - k.start_with?(@current) && k != @current - } - @root.values_at(*keys.sort) - end - - def first - expanded.first - end - - def last - expanded.last - end - - %w(autoload_once eager_load autoload load_path).each do |m| - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{m}! # def eager_load! - @#{m} = true # @eager_load = true - end # end - # - def skip_#{m}! # def skip_eager_load! - @#{m} = false # @eager_load = false - end # end - # - def #{m}? # def eager_load? - @#{m} # @eager_load - end # end - RUBY - end - - def each(&block) - @paths.each(&block) - end - - def <<(path) - @paths << path - end - alias :push :<< - - def concat(paths) - @paths.concat paths - end - - def unshift(*paths) - @paths.unshift(*paths) - end - - def to_ary - @paths - end - - def extensions # :nodoc: - $1.split(",") if @glob =~ /\{([\S]+)\}/ - end - - # Expands all paths against the root and return all unique values. - def expanded - raise "You need to set a path root" unless @root.path - result = [] - - each do |p| - path = File.expand_path(p, @root.path) - - if @glob && File.directory?(path) - Dir.chdir(path) do - result.concat(Dir.glob(@glob).map { |file| File.join path, file }.sort) - end - else - result << path - end - end - - result.uniq! - result - end - - # Returns all expanded paths but only if they exist in the filesystem. - def existent - expanded.select do |f| - does_exist = File.exist?(f) - - if !does_exist && File.symlink?(f) - raise "File #{f.inspect} is a symlink that does not point to a valid file" - end - does_exist - end - end - - def existent_directories - expanded.select { |d| File.directory?(d) } - end - - alias to_a expanded - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/plugin/test.rb b/debian/gems-compat/railties-5.1.7/lib/rails/plugin/test.rb deleted file mode 100644 index 40070c0eb3..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/plugin/test.rb +++ /dev/null @@ -1,7 +0,0 @@ -require_relative "../test_unit/runner" -require_relative "../test_unit/reporter" - -Rails::TestUnitReporter.executable = "bin/test" - -Rails::TestUnit::Runner.parse_options(ARGV) -Rails::TestUnit::Runner.run(ARGV) diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/rack.rb b/debian/gems-compat/railties-5.1.7/lib/rails/rack.rb deleted file mode 100644 index a4c4527a72..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/rack.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Rails - module Rack - autoload :Logger, "rails/rack/logger" - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/rack/logger.rb b/debian/gems-compat/railties-5.1.7/lib/rails/rack/logger.rb deleted file mode 100644 index 9e3e5fcf4d..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/rack/logger.rb +++ /dev/null @@ -1,78 +0,0 @@ -require "active_support/core_ext/time/conversions" -require "active_support/core_ext/object/blank" -require "active_support/log_subscriber" -require "action_dispatch/http/request" -require "rack/body_proxy" - -module Rails - module Rack - # Sets log tags, logs the request, calls the app, and flushes the logs. - # - # Log tags (+taggers+) can be an Array containing: methods that the +request+ - # object responds to, objects that respond to +to_s+ or Proc objects that accept - # an instance of the +request+ object. - class Logger < ActiveSupport::LogSubscriber - def initialize(app, taggers = nil) - @app = app - @taggers = taggers || [] - end - - def call(env) - request = ActionDispatch::Request.new(env) - - if logger.respond_to?(:tagged) - logger.tagged(compute_tags(request)) { call_app(request, env) } - else - call_app(request, env) - end - end - - private - - def call_app(request, env) # :doc: - instrumenter = ActiveSupport::Notifications.instrumenter - instrumenter.start "request.action_dispatch", request: request - logger.info { started_request_message(request) } - status, headers, body = @app.call(env) - body = ::Rack::BodyProxy.new(body) { finish(request) } - [status, headers, body] - rescue Exception - finish(request) - raise - ensure - ActiveSupport::LogSubscriber.flush_all! - end - - # Started GET "/session/new" for 127.0.0.1 at 2012-09-26 14:51:42 -0700 - def started_request_message(request) # :doc: - 'Started %s "%s" for %s at %s' % [ - request.request_method, - request.filtered_path, - request.ip, - Time.now.to_default_s ] - end - - def compute_tags(request) # :doc: - @taggers.collect do |tag| - case tag - when Proc - tag.call(request) - when Symbol - request.send(tag) - else - tag - end - end - end - - def finish(request) - instrumenter = ActiveSupport::Notifications.instrumenter - instrumenter.finish "request.action_dispatch", request: request - end - - def logger - Rails.logger - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/railtie.rb b/debian/gems-compat/railties-5.1.7/lib/rails/railtie.rb deleted file mode 100644 index 474118c0a9..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/railtie.rb +++ /dev/null @@ -1,255 +0,0 @@ -require "rails/initializable" -require "active_support/inflector" -require "active_support/core_ext/module/introspection" -require "active_support/core_ext/module/delegation" - -module Rails - # Rails::Railtie is the core of the Rails framework and provides - # several hooks to extend Rails and/or modify the initialization process. - # - # Every major component of Rails (Action Mailer, Action Controller, Active - # Record, etc.) implements a railtie. Each of them is responsible for their - # own initialization. This makes Rails itself absent of any component hooks, - # allowing other components to be used in place of any of the Rails defaults. - # - # Developing a Rails extension does _not_ require implementing a railtie, but - # if you need to interact with the Rails framework during or after boot, then - # a railtie is needed. - # - # For example, an extension doing any of the following would need a railtie: - # - # * creating initializers - # * configuring a Rails framework for the application, like setting a generator - # * adding config.* keys to the environment - # * setting up a subscriber with ActiveSupport::Notifications - # * adding Rake tasks - # - # == Creating a Railtie - # - # To extend Rails using a railtie, create a subclass of Rails::Railtie. - # This class must be loaded during the Rails boot process, and is conventionally - # called MyNamespace::Railtie. - # - # The following example demonstrates an extension which can be used with or - # without Rails. - # - # # lib/my_gem/railtie.rb - # module MyGem - # class Railtie < Rails::Railtie - # end - # end - # - # # lib/my_gem.rb - # require 'my_gem/railtie' if defined?(Rails) - # - # == Initializers - # - # To add an initialization step to the Rails boot process from your railtie, just - # define the initialization code with the +initializer+ macro: - # - # class MyRailtie < Rails::Railtie - # initializer "my_railtie.configure_rails_initialization" do - # # some initialization behavior - # end - # end - # - # If specified, the block can also receive the application object, in case you - # need to access some application-specific configuration, like middleware: - # - # class MyRailtie < Rails::Railtie - # initializer "my_railtie.configure_rails_initialization" do |app| - # app.middleware.use MyRailtie::Middleware - # end - # end - # - # Finally, you can also pass :before and :after as options to - # +initializer+, in case you want to couple it with a specific step in the - # initialization process. - # - # == Configuration - # - # Railties can access a config object which contains configuration shared by all - # railties and the application: - # - # class MyRailtie < Rails::Railtie - # # Customize the ORM - # config.app_generators.orm :my_railtie_orm - # - # # Add a to_prepare block which is executed once in production - # # and before each request in development. - # config.to_prepare do - # MyRailtie.setup! - # end - # end - # - # == Loading Rake Tasks and Generators - # - # If your railtie has Rake tasks, you can tell Rails to load them through the method - # +rake_tasks+: - # - # class MyRailtie < Rails::Railtie - # rake_tasks do - # load 'path/to/my_railtie.tasks' - # end - # end - # - # By default, Rails loads generators from your load path. However, if you want to place - # your generators at a different location, you can specify in your railtie a block which - # will load them during normal generators lookup: - # - # class MyRailtie < Rails::Railtie - # generators do - # require 'path/to/my_railtie_generator' - # end - # end - # - # == Application and Engine - # - # An engine is nothing more than a railtie with some initializers already set. And since - # Rails::Application is an engine, the same configuration described here can be - # used in both. - # - # Be sure to look at the documentation of those specific classes for more information. - class Railtie - autoload :Configuration, "rails/railtie/configuration" - - include Initializable - - ABSTRACT_RAILTIES = %w(Rails::Railtie Rails::Engine Rails::Application) - - class << self - private :new - delegate :config, to: :instance - - def subclasses - @subclasses ||= [] - end - - def inherited(base) - unless base.abstract_railtie? - subclasses << base - end - end - - def rake_tasks(&blk) - register_block_for(:rake_tasks, &blk) - end - - def console(&blk) - register_block_for(:load_console, &blk) - end - - def runner(&blk) - register_block_for(:runner, &blk) - end - - def generators(&blk) - register_block_for(:generators, &blk) - end - - def abstract_railtie? - ABSTRACT_RAILTIES.include?(name) - end - - def railtie_name(name = nil) - @railtie_name = name.to_s if name - @railtie_name ||= generate_railtie_name(self.name) - end - - # Since Rails::Railtie cannot be instantiated, any methods that call - # +instance+ are intended to be called only on subclasses of a Railtie. - def instance - @instance ||= new - end - - def respond_to_missing?(*args) - instance.respond_to?(*args) || super - end - - # Allows you to configure the railtie. This is the same method seen in - # Railtie::Configurable, but this module is no longer required for all - # subclasses of Railtie so we provide the class method here. - def configure(&block) - instance.configure(&block) - end - - private - def generate_railtie_name(string) - ActiveSupport::Inflector.underscore(string).tr("/", "_") - end - - # If the class method does not have a method, then send the method call - # to the Railtie instance. - def method_missing(name, *args, &block) - if instance.respond_to?(name) - instance.public_send(name, *args, &block) - else - super - end - end - - # receives an instance variable identifier, set the variable value if is - # blank and append given block to value, which will be used later in - # `#each_registered_block(type, &block)` - def register_block_for(type, &blk) - var_name = "@#{type}" - blocks = instance_variable_defined?(var_name) ? instance_variable_get(var_name) : instance_variable_set(var_name, []) - blocks << blk if blk - blocks - end - end - - delegate :railtie_name, to: :class - - def initialize #:nodoc: - if self.class.abstract_railtie? - raise "#{self.class.name} is abstract, you cannot instantiate it directly." - end - end - - def configure(&block) #:nodoc: - instance_eval(&block) - end - - # This is used to create the config object on Railties, an instance of - # Railtie::Configuration, that is used by Railties and Application to store - # related configuration. - def config - @config ||= Railtie::Configuration.new - end - - def railtie_namespace #:nodoc: - @railtie_namespace ||= self.class.parents.detect { |n| n.respond_to?(:railtie_namespace) } - end - - protected - - def run_console_blocks(app) #:nodoc: - each_registered_block(:console) { |block| block.call(app) } - end - - def run_generators_blocks(app) #:nodoc: - each_registered_block(:generators) { |block| block.call(app) } - end - - def run_runner_blocks(app) #:nodoc: - each_registered_block(:runner) { |block| block.call(app) } - end - - def run_tasks_blocks(app) #:nodoc: - extend Rake::DSL - each_registered_block(:rake_tasks) { |block| instance_exec(app, &block) } - end - - private - - # run `&block` in every registered block in `#register_block_for` - def each_registered_block(type, &block) - klass = self.class - while klass.respond_to?(type) - klass.public_send(type).each(&block) - klass = klass.superclass - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/railtie/configurable.rb b/debian/gems-compat/railties-5.1.7/lib/rails/railtie/configurable.rb deleted file mode 100644 index 2a8295426e..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/railtie/configurable.rb +++ /dev/null @@ -1,35 +0,0 @@ -require "active_support/concern" - -module Rails - class Railtie - module Configurable - extend ActiveSupport::Concern - - module ClassMethods - delegate :config, to: :instance - - def inherited(base) - raise "You cannot inherit from a #{superclass.name} child" - end - - def instance - @instance ||= new - end - - def respond_to?(*args) - super || instance.respond_to?(*args) - end - - def configure(&block) - class_eval(&block) - end - - private - - def method_missing(*args, &block) - instance.send(*args, &block) - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/railtie/configuration.rb b/debian/gems-compat/railties-5.1.7/lib/rails/railtie/configuration.rb deleted file mode 100644 index aecc81c491..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/railtie/configuration.rb +++ /dev/null @@ -1,100 +0,0 @@ -require "rails/configuration" - -module Rails - class Railtie - class Configuration - def initialize - @@options ||= {} - end - - # Expose the eager_load_namespaces at "module" level for convenience. - def self.eager_load_namespaces #:nodoc: - @@eager_load_namespaces ||= [] - end - - # All namespaces that are eager loaded - def eager_load_namespaces - @@eager_load_namespaces ||= [] - end - - # Add files that should be watched for change. - def watchable_files - @@watchable_files ||= [] - end - - # Add directories that should be watched for change. - # The key of the hashes should be directories and the values should - # be an array of extensions to match in each directory. - def watchable_dirs - @@watchable_dirs ||= {} - end - - # This allows you to modify the application's middlewares from Engines. - # - # All operations you run on the app_middleware will be replayed on the - # application once it is defined and the default_middlewares are - # created - def app_middleware - @@app_middleware ||= Rails::Configuration::MiddlewareStackProxy.new - end - - # This allows you to modify application's generators from Railties. - # - # Values set on app_generators will become defaults for application, unless - # application overwrites them. - def app_generators - @@app_generators ||= Rails::Configuration::Generators.new - yield(@@app_generators) if block_given? - @@app_generators - end - - # First configurable block to run. Called before any initializers are run. - def before_configuration(&block) - ActiveSupport.on_load(:before_configuration, yield: true, &block) - end - - # Third configurable block to run. Does not run if +config.cache_classes+ - # set to false. - def before_eager_load(&block) - ActiveSupport.on_load(:before_eager_load, yield: true, &block) - end - - # Second configurable block to run. Called before frameworks initialize. - def before_initialize(&block) - ActiveSupport.on_load(:before_initialize, yield: true, &block) - end - - # Last configurable block to run. Called after frameworks initialize. - def after_initialize(&block) - ActiveSupport.on_load(:after_initialize, yield: true, &block) - end - - # Array of callbacks defined by #to_prepare. - def to_prepare_blocks - @@to_prepare_blocks ||= [] - end - - # Defines generic callbacks to run before #after_initialize. Useful for - # Rails::Railtie subclasses. - def to_prepare(&blk) - to_prepare_blocks << blk if blk - end - - def respond_to?(name, include_private = false) - super || @@options.key?(name.to_sym) - end - - private - - def method_missing(name, *args, &blk) - if name.to_s =~ /=$/ - @@options[$`.to_sym] = args.first - elsif @@options.key?(name) - @@options[name] - else - super - end - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/ruby_version_check.rb b/debian/gems-compat/railties-5.1.7/lib/rails/ruby_version_check.rb deleted file mode 100644 index 1f763c4f98..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/ruby_version_check.rb +++ /dev/null @@ -1,13 +0,0 @@ -if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.2.2") && RUBY_ENGINE == "ruby" - desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})" - abort <<-end_message - - Rails 5 requires Ruby 2.2.2 or newer. - - You're running - #{desc} - - Please upgrade to Ruby 2.2.2 or newer to continue. - - end_message -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/secrets.rb b/debian/gems-compat/railties-5.1.7/lib/rails/secrets.rb deleted file mode 100644 index 0883857c55..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/secrets.rb +++ /dev/null @@ -1,121 +0,0 @@ -require "yaml" -require "active_support/message_encryptor" -require "active_support/core_ext/string/strip" - -module Rails - # Greatly inspired by Ara T. Howard's magnificent sekrets gem. 😘 - class Secrets # :nodoc: - class MissingKeyError < RuntimeError - def initialize - super(<<-end_of_message.squish) - Missing encryption key to decrypt secrets with. - Ask your team for your master key and put it in ENV["RAILS_MASTER_KEY"] - end_of_message - end - end - - @cipher = "aes-128-gcm" - @root = File # Wonky, but ensures `join` uses the current directory. - - class << self - attr_writer :root - - def parse(paths, env:) - paths.each_with_object(Hash.new) do |path, all_secrets| - require "erb" - - secrets = YAML.load(ERB.new(preprocess(path)).result) || {} - all_secrets.merge!(secrets["shared"].deep_symbolize_keys) if secrets["shared"] - all_secrets.merge!(secrets[env].deep_symbolize_keys) if secrets[env] - end - end - - def generate_key - SecureRandom.hex(OpenSSL::Cipher.new(@cipher).key_len) - end - - def key - ENV["RAILS_MASTER_KEY"] || read_key_file || handle_missing_key - end - - def template - <<-end_of_template.strip_heredoc - # See `secrets.yml` for tips on generating suitable keys. - # production: - # external_api_key: 1466aac22e6a869134be3d09b9e89232fc2c2289 - - end_of_template - end - - def encrypt(data) - encryptor.encrypt_and_sign(data) - end - - def decrypt(data) - encryptor.decrypt_and_verify(data) - end - - def read - decrypt(IO.binread(path)) - end - - def write(contents) - IO.binwrite("#{path}.tmp", encrypt(contents)) - FileUtils.mv("#{path}.tmp", path) - end - - def read_for_editing(&block) - writing(read, &block) - end - - def read_template_for_editing(&block) - writing(template, &block) - end - - private - def handle_missing_key - raise MissingKeyError - end - - def read_key_file - if File.exist?(key_path) - IO.binread(key_path).strip - end - end - - def key_path - @root.join("config", "secrets.yml.key") - end - - def path - @root.join("config", "secrets.yml.enc").to_s - end - - def preprocess(path) - if path.end_with?(".enc") - decrypt(IO.binread(path)) - else - IO.read(path) - end - end - - def writing(contents) - tmp_file = "#{File.basename(path)}.#{Process.pid}" - tmp_path = File.join(Dir.tmpdir, tmp_file) - IO.binwrite(tmp_path, contents) - - yield tmp_path - - updated_contents = IO.binread(tmp_path) - - write(updated_contents) if updated_contents != contents - ensure - FileUtils.rm(tmp_path) if File.exist?(tmp_path) - end - - def encryptor - @encryptor ||= ActiveSupport::MessageEncryptor.new([ key ].pack("H*"), cipher: @cipher) - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/source_annotation_extractor.rb b/debian/gems-compat/railties-5.1.7/lib/rails/source_annotation_extractor.rb deleted file mode 100644 index e9088c44ce..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/source_annotation_extractor.rb +++ /dev/null @@ -1,139 +0,0 @@ -# Implements the logic behind the rake tasks for annotations like -# -# rails notes -# rails notes:optimize -# -# and friends. See rails -T notes and railties/lib/rails/tasks/annotations.rake. -# -# Annotation objects are triplets :line, :tag, :text that -# represent the line where the annotation lives, its tag, and its text. Note -# the filename is not stored. -# -# Annotations are looked for in comments and modulus whitespace they have to -# start with the tag optionally followed by a colon. Everything up to the end -# of the line (or closing ERB comment tag) is considered to be their text. -class SourceAnnotationExtractor - Annotation = Struct.new(:line, :tag, :text) do - def self.directories - @@directories ||= %w(app config db lib test) + (ENV["SOURCE_ANNOTATION_DIRECTORIES"] || "").split(",") - end - - # Registers additional directories to be included - # SourceAnnotationExtractor::Annotation.register_directories("spec","another") - def self.register_directories(*dirs) - directories.push(*dirs) - end - - def self.extensions - @@extensions ||= {} - end - - # Registers new Annotations File Extensions - # SourceAnnotationExtractor::Annotation.register_extensions("css", "scss", "sass", "less", "js") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ } - def self.register_extensions(*exts, &block) - extensions[/\.(#{exts.join("|")})$/] = block - end - - register_extensions("builder", "rb", "rake", "yml", "yaml", "ruby") { |tag| /#\s*(#{tag}):?\s*(.*)$/ } - register_extensions("css", "js") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ } - register_extensions("erb") { |tag| /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/ } - - # Returns a representation of the annotation that looks like this: - # - # [126] [TODO] This algorithm is simple and clearly correct, make it faster. - # - # If +options+ has a flag :tag the tag is shown as in the example above. - # Otherwise the string contains just line and text. - def to_s(options = {}) - s = "[#{line.to_s.rjust(options[:indent])}] " - s << "[#{tag}] " if options[:tag] - s << text - end - end - - # Prints all annotations with tag +tag+ under the root directories +app+, - # +config+, +db+, +lib+, and +test+ (recursively). - # - # Additional directories may be added using a comma-delimited list set using - # ENV['SOURCE_ANNOTATION_DIRECTORIES']. - # - # Directories may also be explicitly set using the :dirs key in +options+. - # - # SourceAnnotationExtractor.enumerate 'TODO|FIXME', dirs: %w(app lib), tag: true - # - # If +options+ has a :tag flag, it will be passed to each annotation's +to_s+. - # - # See #find_in for a list of file extensions that will be taken into account. - # - # This class method is the single entry point for the rake tasks. - def self.enumerate(tag, options = {}) - extractor = new(tag) - dirs = options.delete(:dirs) || Annotation.directories - extractor.display(extractor.find(dirs), options) - end - - attr_reader :tag - - def initialize(tag) - @tag = tag - end - - # Returns a hash that maps filenames under +dirs+ (recursively) to arrays - # with their annotations. - def find(dirs) - dirs.inject({}) { |h, dir| h.update(find_in(dir)) } - end - - # Returns a hash that maps filenames under +dir+ (recursively) to arrays - # with their annotations. Only files with annotations are included. Files - # with extension +.builder+, +.rb+, +.rake+, +.yml+, +.yaml+, +.ruby+, - # +.css+, +.js+ and +.erb+ are taken into account. - def find_in(dir) - results = {} - - Dir.glob("#{dir}/*") do |item| - next if File.basename(item)[0] == ?. - - if File.directory?(item) - results.update(find_in(item)) - else - extension = Annotation.extensions.detect do |regexp, _block| - regexp.match(item) - end - - if extension - pattern = extension.last.call(tag) - results.update(extract_annotations_from(item, pattern)) if pattern - end - end - end - - results - end - - # If +file+ is the filename of a file that contains annotations this method returns - # a hash with a single entry that maps +file+ to an array of its annotations. - # Otherwise it returns an empty hash. - def extract_annotations_from(file, pattern) - lineno = 0 - result = File.readlines(file, encoding: Encoding::BINARY).inject([]) do |list, line| - lineno += 1 - next list unless line =~ pattern - list << Annotation.new(lineno, $1, $2) - end - result.empty? ? {} : { file => result } - end - - # Prints the mapping from filenames to annotations in +results+ ordered by filename. - # The +options+ hash is passed to each annotation's +to_s+. - def display(results, options = {}) - options[:indent] = results.flat_map { |f, a| a.map(&:line) }.max.to_s.size - results.keys.sort.each do |file| - puts "#{file}:" - results[file].each do |note| - puts " * #{note.to_s(options)}" - end - puts - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks.rb b/debian/gems-compat/railties-5.1.7/lib/rails/tasks.rb deleted file mode 100644 index c0a50e5bda..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks.rb +++ /dev/null @@ -1,20 +0,0 @@ -require "rake" - -# Load Rails Rakefile extensions -%w( - annotations - dev - framework - initializers - log - middleware - misc - restart - routes - tmp - yarn -).tap { |arr| - arr << "statistics" if Rake.application.current_scope.empty? -}.each do |task| - load "rails/tasks/#{task}.rake" -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/annotations.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/annotations.rake deleted file mode 100644 index 9a69eb9934..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/annotations.rake +++ /dev/null @@ -1,20 +0,0 @@ -require "rails/source_annotation_extractor" - -desc "Enumerate all annotations (use notes:optimize, :fixme, :todo for focus)" -task :notes do - SourceAnnotationExtractor.enumerate "OPTIMIZE|FIXME|TODO", tag: true -end - -namespace :notes do - ["OPTIMIZE", "FIXME", "TODO"].each do |annotation| - # desc "Enumerate all #{annotation} annotations" - task annotation.downcase.intern do - SourceAnnotationExtractor.enumerate annotation - end - end - - desc "Enumerate a custom annotation, specify with ANNOTATION=CUSTOM" - task :custom do - SourceAnnotationExtractor.enumerate ENV["ANNOTATION"] - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/dev.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/dev.rake deleted file mode 100644 index 334e968123..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/dev.rake +++ /dev/null @@ -1,8 +0,0 @@ -require "rails/dev_caching" - -namespace :dev do - desc "Toggle development mode caching on/off" - task :cache do - Rails::DevCaching.enable_by_file - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/engine.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/engine.rake deleted file mode 100644 index 177b138090..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/engine.rake +++ /dev/null @@ -1,83 +0,0 @@ -task "load_app" do - namespace :app do - load APP_RAKEFILE - - desc "Update some initially generated files" - task update: [ "update:bin" ] - - namespace :update do - require "rails/engine/updater" - # desc "Adds new executables to the engine bin/ directory" - task :bin do - Rails::Engine::Updater.run(:create_bin_files) - end - end - end - task environment: "app:environment" - - if !defined?(ENGINE_ROOT) || !ENGINE_ROOT - ENGINE_ROOT = find_engine_path(APP_RAKEFILE) - end -end - -def app_task(name) - task name => [:load_app, "app:db:#{name}"] -end - -namespace :db do - app_task "reset" - - desc "Migrate the database (options: VERSION=x, VERBOSE=false)." - app_task "migrate" - app_task "migrate:up" - app_task "migrate:down" - app_task "migrate:redo" - app_task "migrate:reset" - - desc "Display status of migrations" - app_task "migrate:status" - - desc "Create the database from config/database.yml for the current Rails.env (use db:create:all to create all databases in the config)" - app_task "create" - app_task "create:all" - - desc "Drops the database for the current Rails.env (use db:drop:all to drop all databases)" - app_task "drop" - app_task "drop:all" - - desc "Load fixtures into the current environment's database." - app_task "fixtures:load" - - desc "Rolls the schema back to the previous version (specify steps w/ STEP=n)." - app_task "rollback" - - desc "Create a db/schema.rb file that can be portably used against any DB supported by Active Record" - app_task "schema:dump" - - desc "Load a schema.rb file into the database" - app_task "schema:load" - - desc "Load the seed data from db/seeds.rb" - app_task "seed" - - desc "Create the database, load the schema, and initialize with the seed data (use db:reset to also drop the db first)" - app_task "setup" - - desc "Dump the database structure to an SQL file" - app_task "structure:dump" - - desc "Retrieves the current schema version number" - app_task "version" -end - -def find_engine_path(path) - return File.expand_path(Dir.pwd) if path == "/" - - if Rails::Engine.find(path) - path - else - find_engine_path(File.expand_path("..", path)) - end -end - -Rake.application.invoke_task(:load_app) diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/framework.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/framework.rake deleted file mode 100644 index 32a6b109bc..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/framework.rake +++ /dev/null @@ -1,73 +0,0 @@ -namespace :app do - desc "Update configs and some other initially generated files (or use just update:configs or update:bin)" - task update: [ "update:configs", "update:bin", "update:upgrade_guide_info" ] - - desc "Applies the template supplied by LOCATION=(/path/to/template) or URL" - task template: :environment do - template = ENV["LOCATION"] - raise "No LOCATION value given. Please set LOCATION either as path to a file or a URL" if template.blank? - template = File.expand_path(template) if template !~ %r{\A[A-Za-z][A-Za-z0-9+\-\.]*://} - require "rails/generators" - require "rails/generators/rails/app/app_generator" - generator = Rails::Generators::AppGenerator.new [Rails.root], {}, destination_root: Rails.root - generator.apply template, verbose: false - end - - namespace :templates do - # desc "Copy all the templates from rails to the application directory for customization. Already existing local copies will be overwritten" - task :copy do - generators_lib = File.expand_path("../../generators", __FILE__) - project_templates = "#{Rails.root}/lib/templates" - - default_templates = { "erb" => %w{controller mailer scaffold}, - "rails" => %w{controller helper scaffold_controller assets} } - - default_templates.each do |type, names| - local_template_type_dir = File.join(project_templates, type) - mkdir_p local_template_type_dir, verbose: false - - names.each do |name| - dst_name = File.join(local_template_type_dir, name) - src_name = File.join(generators_lib, type, name, "templates") - cp_r src_name, dst_name, verbose: false - end - end - end - end - - namespace :update do - class RailsUpdate - def self.invoke_from_app_generator(method) - app_generator.send(method) - end - - def self.app_generator - @app_generator ||= begin - require "rails/generators" - require "rails/generators/rails/app/app_generator" - gen = Rails::Generators::AppGenerator.new ["rails"], - { api: !!Rails.application.config.api_only, update: true }, - destination_root: Rails.root - File.exist?(Rails.root.join("config", "application.rb")) ? - gen.send(:app_const) : gen.send(:valid_const?) - gen - end - end - end - - # desc "Update config/boot.rb from your current rails install" - task :configs do - RailsUpdate.invoke_from_app_generator :create_boot_file - RailsUpdate.invoke_from_app_generator :update_config_files - end - - # desc "Adds new executables to the application bin/ directory" - task :bin do - RailsUpdate.invoke_from_app_generator :update_bin_files - end - - task :upgrade_guide_info do - RailsUpdate.invoke_from_app_generator :display_upgrade_guide_info - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/initializers.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/initializers.rake deleted file mode 100644 index 6522f2ae5a..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/initializers.rake +++ /dev/null @@ -1,6 +0,0 @@ -desc "Print out all defined initializers in the order they are invoked by Rails." -task initializers: :environment do - Rails.application.initializers.tsort_each do |initializer| - puts "#{initializer.context_class}.#{initializer.name}" - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/log.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/log.rake deleted file mode 100644 index ba796845d7..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/log.rake +++ /dev/null @@ -1,40 +0,0 @@ -namespace :log do - - ## - # Truncates all/specified log files - # ENV['LOGS'] - # - defaults to all environments log files i.e. 'development,test,production' - # - ENV['LOGS']=all truncates all files i.e. log/*.log - # - ENV['LOGS']='test,development' truncates only specified files - desc "Truncates all/specified *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)" - task :clear do - log_files.each do |file| - clear_log_file(file) - end - end - - def log_files - if ENV["LOGS"] == "all" - FileList["log/*.log"] - elsif ENV["LOGS"] - log_files_to_truncate(ENV["LOGS"]) - else - log_files_to_truncate(all_environments.join(",")) - end - end - - def log_files_to_truncate(envs) - envs.split(",") - .map { |file| "log/#{file.strip}.log" } - .select { |file| File.exist?(file) } - end - - def clear_log_file(file) - f = File.open(file, "w") - f.close - end - - def all_environments - Dir["config/environments/*.rb"].map { |fname| File.basename(fname, ".*") } - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/middleware.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/middleware.rake deleted file mode 100644 index fd98be1ea9..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/middleware.rake +++ /dev/null @@ -1,7 +0,0 @@ -desc "Prints out your Rack middleware stack" -task middleware: :environment do - Rails.configuration.middleware.each do |middleware| - puts "use #{middleware.inspect}" - end - puts "run #{Rails.application.class.name}.routes" -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/misc.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/misc.rake deleted file mode 100644 index 29ea0ff804..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/misc.rake +++ /dev/null @@ -1,77 +0,0 @@ -desc "Generate a cryptographically secure secret key (this is typically used to generate a secret for cookie sessions)." -task :secret do - require "securerandom" - puts SecureRandom.hex(64) -end - -desc "List versions of all Rails frameworks and the environment" -task about: :environment do - puts Rails::Info -end - -namespace :time do - desc "List all time zones, list by two-letter country code (`rails time:zones[US]`), or list by UTC offset (`rails time:zones[-8]`)" - task :zones, :country_or_offset do |t, args| - zones, offset = ActiveSupport::TimeZone.all, nil - - if country_or_offset = args[:country_or_offset] - begin - zones = ActiveSupport::TimeZone.country_zones(country_or_offset) - rescue TZInfo::InvalidCountryCode - offset = country_or_offset - end - end - - build_time_zone_list zones, offset - end - - namespace :zones do - # desc 'Displays all time zones, also available: time:zones:us, time:zones:local -- filter with OFFSET parameter, e.g., OFFSET=-6' - task :all do - build_time_zone_list ActiveSupport::TimeZone.all - end - - # desc 'Displays names of US time zones recognized by the Rails TimeZone class, grouped by offset. Results can be filtered with optional OFFSET parameter, e.g., OFFSET=-6' - task :us do - build_time_zone_list ActiveSupport::TimeZone.us_zones - end - - # desc 'Displays names of time zones recognized by the Rails TimeZone class with the same offset as the system local time' - task :local do - require "active_support" - require "active_support/time" - - jan_offset = Time.now.beginning_of_year.utc_offset - jul_offset = Time.now.beginning_of_year.change(month: 7).utc_offset - offset = jan_offset < jul_offset ? jan_offset : jul_offset - - build_time_zone_list(ActiveSupport::TimeZone.all, offset) - end - - # to find UTC -06:00 zones, OFFSET can be set to either -6, -6:00 or 21600 - def build_time_zone_list(zones, offset = ENV["OFFSET"]) - require "active_support" - require "active_support/time" - if offset - offset = if offset.to_s.match(/(\+|-)?(\d+):(\d+)/) - sign = $1 == "-" ? -1 : 1 - hours, minutes = $2.to_f, $3.to_f - ((hours * 3600) + (minutes.to_f * 60)) * sign - elsif offset.to_f.abs <= 13 - offset.to_f * 3600 - else - offset.to_f - end - end - previous_offset = nil - zones.each do |zone| - if offset.nil? || offset == zone.utc_offset - puts "\n* UTC #{zone.formatted_offset} *" unless zone.utc_offset == previous_offset - puts zone.name - previous_offset = zone.utc_offset - end - end - puts "\n" - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/restart.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/restart.rake deleted file mode 100644 index 03177d9954..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/restart.rake +++ /dev/null @@ -1,8 +0,0 @@ -desc "Restart app by touching tmp/restart.txt" -task :restart do - verbose(false) do - mkdir_p "tmp" - touch "tmp/restart.txt" - rm_f "tmp/pids/server.pid" - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/routes.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/routes.rake deleted file mode 100644 index 215fb2ceb5..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/routes.rake +++ /dev/null @@ -1,29 +0,0 @@ -require "optparse" - -desc "Print out all defined routes in match order, with names. Target specific controller with -c option, or grep routes using -g option" -task routes: :environment do - all_routes = Rails.application.routes.routes - require "action_dispatch/routing/inspector" - inspector = ActionDispatch::Routing::RoutesInspector.new(all_routes) - - routes_filter = nil - - OptionParser.new do |opts| - opts.banner = "Usage: rails routes [options]" - - Rake.application.standard_rake_options.each { |args| opts.on(*args) } - - opts.on("-c CONTROLLER") do |controller| - routes_filter = { controller: controller } - end - - opts.on("-g PATTERN") do |pattern| - routes_filter = pattern - end - - end.parse!(ARGV.reject { |x| x == "routes" }) - - puts inspector.format(ActionDispatch::Routing::ConsoleFormatter.new, routes_filter) - - exit 0 # ensure extra arguments aren't interpreted as Rake tasks -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/statistics.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/statistics.rake deleted file mode 100644 index cb569be58b..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/statistics.rake +++ /dev/null @@ -1,29 +0,0 @@ -# While global constants are bad, many 3rd party tools depend on this one (e.g -# rspec-rails & cucumber-rails). So a deprecation warning is needed if we want -# to remove it. -STATS_DIRECTORIES = [ - %w(Controllers app/controllers), - %w(Helpers app/helpers), - %w(Jobs app/jobs), - %w(Models app/models), - %w(Mailers app/mailers), - %w(Channels app/channels), - %w(JavaScripts app/assets/javascripts), - %w(Libraries lib/), - %w(APIs app/apis), - %w(Controller\ tests test/controllers), - %w(Helper\ tests test/helpers), - %w(Model\ tests test/models), - %w(Mailer\ tests test/mailers), - %w(Job\ tests test/jobs), - %w(Integration\ tests test/integration), - %w(System\ tests test/system), -].collect do |name, dir| - [ name, "#{File.dirname(Rake.application.rakefile_location)}/#{dir}" ] -end.select { |name, dir| File.directory?(dir) } - -desc "Report code statistics (KLOCs, etc) from the application or engine" -task :stats do - require "rails/code_statistics" - CodeStatistics.new(*STATS_DIRECTORIES).to_s -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/tmp.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/tmp.rake deleted file mode 100644 index d42a890cb6..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/tmp.rake +++ /dev/null @@ -1,35 +0,0 @@ -namespace :tmp do - desc "Clear cache and socket files from tmp/ (narrow w/ tmp:cache:clear, tmp:sockets:clear)" - task clear: ["tmp:cache:clear", "tmp:sockets:clear"] - - tmp_dirs = [ "tmp/cache", - "tmp/sockets", - "tmp/pids", - "tmp/cache/assets" ] - - tmp_dirs.each { |d| directory d } - - desc "Creates tmp directories for cache, sockets, and pids" - task create: tmp_dirs - - namespace :cache do - # desc "Clears all files and directories in tmp/cache" - task :clear do - rm_rf Dir["tmp/cache/[^.]*"], verbose: false - end - end - - namespace :sockets do - # desc "Clears all files in tmp/sockets" - task :clear do - rm Dir["tmp/sockets/[^.]*"], verbose: false - end - end - - namespace :pids do - # desc "Clears all files in tmp/pids" - task :clear do - rm Dir["tmp/pids/[^.]*"], verbose: false - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/yarn.rake b/debian/gems-compat/railties-5.1.7/lib/rails/tasks/yarn.rake deleted file mode 100644 index 87476b1b8c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/tasks/yarn.rake +++ /dev/null @@ -1,11 +0,0 @@ -namespace :yarn do - desc "Install all JavaScript dependencies as specified via Yarn" - task :install do - system("./bin/yarn install --no-progress") - end -end - -# Run Yarn prior to Sprockets assets precompilation, so dependencies are available for use. -if Rake::Task.task_defined?("assets:precompile") - Rake::Task["assets:precompile"].enhance [ "yarn:install" ] -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/templates/layouts/application.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/templates/layouts/application.html.erb deleted file mode 100644 index 5aecaa712a..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/templates/layouts/application.html.erb +++ /dev/null @@ -1,36 +0,0 @@ - - - - - <%= @page_title %> - - - - -<%= yield %> - - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/info/properties.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/info/properties.html.erb deleted file mode 100644 index d47cbab202..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/info/properties.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= @info.html_safe %> \ No newline at end of file diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/info/routes.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/info/routes.html.erb deleted file mode 100644 index 2d8a190986..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/info/routes.html.erb +++ /dev/null @@ -1,9 +0,0 @@ -

    - Routes -

    - -

    - Routes match in priority from top to bottom -

    - -<%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/email.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/email.html.erb deleted file mode 100644 index c63781ed0c..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/email.html.erb +++ /dev/null @@ -1,133 +0,0 @@ - - - - - - - -
    -
    - <% if @email.respond_to?(:smtp_envelope_from) && Array(@email.from) != Array(@email.smtp_envelope_from) %> -
    SMTP-From:
    -
    <%= @email.smtp_envelope_from %>
    - <% end %> - - <% if @email.respond_to?(:smtp_envelope_to) && @email.to != @email.smtp_envelope_to %> -
    SMTP-To:
    -
    <%= @email.smtp_envelope_to %>
    - <% end %> - -
    From:
    -
    <%= @email.header['from'] %>
    - - <% if @email.reply_to %> -
    Reply-To:
    -
    <%= @email.header['reply-to'] %>
    - <% end %> - -
    To:
    -
    <%= @email.header['to'] %>
    - - <% if @email.cc %> -
    CC:
    -
    <%= @email.header['cc'] %>
    - <% end %> - -
    Date:
    -
    <%= Time.current.rfc2822 %>
    - -
    Subject:
    -
    <%= @email.subject %>
    - - <% unless @email.attachments.nil? || @email.attachments.empty? %> -
    Attachments:
    -
    - <% @email.attachments.each do |a| %> - <% filename = a.respond_to?(:original_filename) ? a.original_filename : a.filename %> - <%= link_to filename, "data:application/octet-stream;charset=utf-8;base64,#{Base64.encode64(a.body.to_s)}", download: filename %> - <% end %> -
    - <% end %> - - <% if @email.multipart? %> -
    - -
    - <% end %> -
    -
    - -<% if @part && @part.mime_type %> - -<% else %> -

    - You are trying to preview an email that does not have any content. - This is probably because the mail method has not been called in <%= @preview.preview_name %>#<%= @email_action %>. -

    -<% end %> - - - - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/index.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/index.html.erb deleted file mode 100644 index 000930c039..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/index.html.erb +++ /dev/null @@ -1,8 +0,0 @@ -<% @previews.each do |preview| %> -

    <%= link_to preview.preview_name.titleize, url_for(controller: "rails/mailers", action: "preview", path: preview.preview_name) %>

    -
      -<% preview.emails.each do |email| %> -
    • <%= link_to email, url_for(controller: "rails/mailers", action: "preview", path: "#{preview.preview_name}/#{email}") %>
    • -<% end %> -
    -<% end %> diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/mailer.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/mailer.html.erb deleted file mode 100644 index c12ead0f90..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/mailers/mailer.html.erb +++ /dev/null @@ -1,6 +0,0 @@ -

    <%= @preview.preview_name.titleize %>

    -
      -<% @preview.emails.each do |email| %> -
    • <%= link_to email, url_for(controller: "rails/mailers", action: "preview", path: "#{@preview.preview_name}/#{email}") %>
    • -<% end %> -
    diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/welcome/index.html.erb b/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/welcome/index.html.erb deleted file mode 100644 index 5cdb7e6a20..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/templates/rails/welcome/index.html.erb +++ /dev/null @@ -1,64 +0,0 @@ - - - - Ruby on Rails - - - - - - -
    -
    -

    - - Ruby on Rails - -

    - -

    Yay! You’re on Rails!

    - - Welcome - -

    - Rails version: <%= Rails.version %>
    - Ruby version: <%= RUBY_VERSION %> (<%= RUBY_PLATFORM %>) -

    -
    -
    - - diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/test_help.rb b/debian/gems-compat/railties-5.1.7/lib/rails/test_help.rb deleted file mode 100644 index 6826622ee7..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/test_help.rb +++ /dev/null @@ -1,50 +0,0 @@ -# Make double-sure the RAILS_ENV is not set to production, -# so fixtures aren't loaded into that environment -abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production? - -require "active_support/test_case" -require "action_controller" -require "action_controller/test_case" -require "action_dispatch/testing/integration" -require "rails/generators/test_case" - -require "active_support/testing/autorun" - -if defined?(ActiveRecord::Base) - begin - ActiveRecord::Migration.maintain_test_schema! - rescue ActiveRecord::PendingMigrationError => e - puts e.to_s.strip - exit 1 - end - - module ActiveSupport - class TestCase - include ActiveRecord::TestFixtures - self.fixture_path = "#{Rails.root}/test/fixtures/" - self.file_fixture_path = fixture_path + "files" - end - end - - ActionDispatch::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path - - def create_fixtures(*fixture_set_names, &block) - FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, {}, &block) - end -end - -# :enddoc: - -class ActionController::TestCase - def before_setup # :nodoc: - @routes = Rails.application.routes - super - end -end - -class ActionDispatch::IntegrationTest - def before_setup # :nodoc: - @routes = Rails.application.routes - super - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/line_filtering.rb b/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/line_filtering.rb deleted file mode 100644 index 289afae331..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/line_filtering.rb +++ /dev/null @@ -1,12 +0,0 @@ -require "method_source" -require "rails/test_unit/runner" - -module Rails - module LineFiltering # :nodoc: - def run(reporter, options = {}) - options[:filter] = Rails::TestUnit::Runner.compose_filter(self, options[:filter]) - - super - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/railtie.rb b/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/railtie.rb deleted file mode 100644 index 443e743421..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/railtie.rb +++ /dev/null @@ -1,27 +0,0 @@ -require "rails/test_unit/line_filtering" - -if defined?(Rake.application) && Rake.application.top_level_tasks.grep(/^(default$|test(:|$))/).any? - ENV["RAILS_ENV"] ||= Rake.application.options.show_tasks ? "development" : "test" -end - -module Rails - class TestUnitRailtie < Rails::Railtie - config.app_generators do |c| - c.test_framework :test_unit, fixture: true, - fixture_replacement: nil - - c.integration_tool :test_unit - c.system_tests :test_unit - end - - initializer "test_unit.line_filtering" do - ActiveSupport.on_load(:active_support_test_case) { - ActiveSupport::TestCase.extend Rails::LineFiltering - } - end - - rake_tasks do - load "rails/test_unit/testing.rake" - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/reporter.rb b/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/reporter.rb deleted file mode 100644 index ecd2a348aa..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/reporter.rb +++ /dev/null @@ -1,109 +0,0 @@ -require "active_support/core_ext/class/attribute" -require "minitest" - -module Rails - class TestUnitReporter < Minitest::StatisticsReporter - class_attribute :executable - self.executable = "bin/rails test" - - def record(result) - super - - if options[:verbose] - io.puts color_output(format_line(result), by: result) - else - io.print color_output(result.result_code, by: result) - end - - if output_inline? && result.failure && (!result.skipped? || options[:verbose]) - io.puts - io.puts - io.puts color_output(result, by: result) - io.puts - io.puts format_rerun_snippet(result) - io.puts - end - - if fail_fast? && result.failure && !result.skipped? - raise Interrupt - end - end - - def report - return if output_inline? || filtered_results.empty? - io.puts - io.puts "Failed tests:" - io.puts - io.puts aggregated_results - end - - def aggregated_results # :nodoc: - filtered_results.map { |result| format_rerun_snippet(result) }.join "\n" - end - - def filtered_results - if options[:verbose] - results - else - results.reject(&:skipped?) - end - end - - def relative_path_for(file) - file.sub(/^#{app_root}\/?/, "") - end - - private - def output_inline? - options[:output_inline] - end - - def fail_fast? - options[:fail_fast] - end - - def format_line(result) - klass = result.respond_to?(:klass) ? result.klass : result.class - "%s#%s = %.2f s = %s" % [klass, result.name, result.time, result.result_code] - end - - def format_rerun_snippet(result) - location, line = if result.respond_to?(:source_location) - result.source_location - else - result.method(result.name).source_location - end - - "#{executable} #{relative_path_for(location)}:#{line}" - end - - def app_root - @app_root ||= - if defined?(ENGINE_ROOT) - ENGINE_ROOT - elsif Rails.respond_to?(:root) - Rails.root - end - end - - def colored_output? - options[:color] && io.respond_to?(:tty?) && io.tty? - end - - codes = { red: 31, green: 32, yellow: 33 } - COLOR_BY_RESULT_CODE = { - "." => codes[:green], - "E" => codes[:red], - "F" => codes[:red], - "S" => codes[:yellow] - } - - def color_output(string, by:) - if colored_output? - "\e[#{COLOR_BY_RESULT_CODE[by.result_code]}m#{string}\e[0m" - else - string - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/runner.rb b/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/runner.rb deleted file mode 100644 index bdddbdc389..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/runner.rb +++ /dev/null @@ -1,143 +0,0 @@ -# frozen_string_literal: true - -require "shellwords" -require "method_source" -require "rake/file_list" -require "active_support/core_ext/module/attribute_accessors" - -module Rails - module TestUnit - class Runner - mattr_reader(:filters) { [] } - - class << self - def options(opts) - opts.on("--warnings", "-w", "Run with Ruby warnings enabled") {} - opts.on("-e", "--environment ENV", "Run tests in the ENV environment") {} - end - - def parse_options(argv) - # Perform manual parsing and cleanup since option parser raises on unknown options. - env_index = argv.index("--environment") || argv.index("-e") - if env_index - argv.delete_at(env_index) - environment = argv.delete_at(env_index).strip - end - ENV["RAILS_ENV"] = environment || "test" - - w_index = argv.index("--warnings") || argv.index("-w") - $VERBOSE = argv.delete_at(w_index) if w_index - end - - def rake_run(argv = []) - ARGV.replace Shellwords.split(ENV["TESTOPTS"] || "") - - run(argv) - end - - def run(argv = []) - load_tests(argv) - - require "active_support/testing/autorun" - end - - def load_tests(argv) - patterns = extract_filters(argv) - - tests = Rake::FileList[patterns.any? ? patterns : "test/**/*_test.rb"] - tests.exclude("test/system/**/*") if patterns.empty? - - tests.to_a.each { |path| require File.expand_path(path) } - end - - def compose_filter(runnable, filter) - if filters.any? { |_, lines| lines.any? } - CompositeFilter.new(runnable, filter, filters) - else - filter - end - end - - private - def extract_filters(argv) - # Extract absolute and relative paths but skip -n /.*/ regexp filters. - argv.select { |arg| arg =~ %r%^/?\w+/% && !arg.end_with?("/") }.map do |path| - case - when path =~ /(:\d+)+$/ - file, *lines = path.split(":") - filters << [ file, lines ] - file - when Dir.exist?(path) - "#{path}/**/*_test.rb" - else - filters << [ path, [] ] - path - end - end - end - end - end - - class CompositeFilter # :nodoc: - attr_reader :named_filter - - def initialize(runnable, filter, patterns) - @runnable = runnable - @named_filter = derive_named_filter(filter) - @filters = [ @named_filter, *derive_line_filters(patterns) ].compact - end - - # Minitest uses === to find matching filters. - def ===(method) - @filters.any? { |filter| filter === method } - end - - private - def derive_named_filter(filter) - if filter.respond_to?(:named_filter) - filter.named_filter - elsif filter =~ %r%/(.*)/% # Regexp filtering copied from Minitest. - Regexp.new $1 - elsif filter.is_a?(String) - filter - end - end - - def derive_line_filters(patterns) - patterns.flat_map do |file, lines| - if lines.empty? - Filter.new(@runnable, file, nil) if file - else - lines.map { |line| Filter.new(@runnable, file, line) } - end - end - end - end - - class Filter # :nodoc: - def initialize(runnable, file, line) - @runnable, @file = runnable, File.expand_path(file) - @line = line.to_i if line - end - - def ===(method) - return unless @runnable.method_defined?(method) - - if @line - test_file, test_range = definition_for(@runnable.instance_method(method)) - test_file == @file && test_range.include?(@line) - else - @runnable.instance_method(method).source_location.first == @file - end - end - - private - def definition_for(method) - file, start_line = method.source_location - end_line = method.source.count("\n") + start_line - 1 - - return file, start_line..end_line - end - end - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/testing.rake b/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/testing.rake deleted file mode 100644 index 97dd5cef10..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/test_unit/testing.rake +++ /dev/null @@ -1,56 +0,0 @@ -gem "minitest" -require "minitest" -require_relative "runner" - -task default: :test - -desc "Runs all tests in test folder except system ones" -task :test do - $: << "test" - - if ENV.key?("TEST") - Rails::TestUnit::Runner.rake_run([ENV["TEST"]]) - else - Rails::TestUnit::Runner.rake_run - end -end - -namespace :test do - task :prepare do - # Placeholder task for other Railtie and plugins to enhance. - # If used with Active Record, this task runs before the database schema is synchronized. - end - - task run: %w[test] - - desc "Run tests quickly, but also reset db" - task db: %w[db:test:prepare test] - - ["models", "helpers", "controllers", "mailers", "integration", "jobs"].each do |name| - task name => "test:prepare" do - $: << "test" - Rails::TestUnit::Runner.rake_run(["test/#{name}"]) - end - end - - task generators: "test:prepare" do - $: << "test" - Rails::TestUnit::Runner.rake_run(["test/lib/generators"]) - end - - task units: "test:prepare" do - $: << "test" - Rails::TestUnit::Runner.rake_run(["test/models", "test/helpers", "test/unit"]) - end - - task functionals: "test:prepare" do - $: << "test" - Rails::TestUnit::Runner.rake_run(["test/controllers", "test/mailers", "test/functional"]) - end - - desc "Run system tests only" - task system: "test:prepare" do - $: << "test" - Rails::TestUnit::Runner.rake_run(["test/system"]) - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/version.rb b/debian/gems-compat/railties-5.1.7/lib/rails/version.rb deleted file mode 100644 index 3d8e8291d1..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/version.rb +++ /dev/null @@ -1,8 +0,0 @@ -require_relative "gem_version" - -module Rails - # Returns the version of the currently loaded Rails as a string. - def self.version - VERSION::STRING - end -end diff --git a/debian/gems-compat/railties-5.1.7/lib/rails/welcome_controller.rb b/debian/gems-compat/railties-5.1.7/lib/rails/welcome_controller.rb deleted file mode 100644 index b757dc72ef..0000000000 --- a/debian/gems-compat/railties-5.1.7/lib/rails/welcome_controller.rb +++ /dev/null @@ -1,8 +0,0 @@ -require "rails/application_controller" - -class Rails::WelcomeController < Rails::ApplicationController # :nodoc: - layout false - - def index - end -end diff --git a/debian/gems-compat/railties-5.1.7/railties.gemspec b/debian/gems-compat/railties-5.1.7/railties.gemspec deleted file mode 100644 index e3db6db9ea..0000000000 --- a/debian/gems-compat/railties-5.1.7/railties.gemspec +++ /dev/null @@ -1,54 +0,0 @@ -######################################################### -# This file has been automatically generated by gem2tgz # -######################################################### -# -*- encoding: utf-8 -*- -# stub: railties 5.1.7 ruby lib - -Gem::Specification.new do |s| - s.name = "railties".freeze - s.version = "5.1.7" - - s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= - s.metadata = { "changelog_uri" => "https://github.com/rails/rails/blob/v5.1.7/railties/CHANGELOG.md", "source_code_uri" => "https://github.com/rails/rails/tree/v5.1.7/railties" } if s.respond_to? :metadata= - s.require_paths = ["lib".freeze] - s.authors = ["David Heinemeier Hansson".freeze] - s.bindir = "exe".freeze - s.date = "2019-03-28" - s.description = "Rails internals: application bootup, plugins, generators, and rake tasks.".freeze - s.email = "david@loudthinking.com".freeze - s.executables = ["rails".freeze] - s.files = ["CHANGELOG.md".freeze, "MIT-LICENSE".freeze, "RDOC_MAIN.rdoc".freeze, "README.rdoc".freeze, "exe/rails".freeze, "lib/minitest/rails_plugin.rb".freeze, "lib/rails.rb".freeze, "lib/rails/all.rb".freeze, "lib/rails/api/generator.rb".freeze, "lib/rails/api/task.rb".freeze, "lib/rails/app_loader.rb".freeze, "lib/rails/application.rb".freeze, "lib/rails/application/bootstrap.rb".freeze, "lib/rails/application/configuration.rb".freeze, "lib/rails/application/default_middleware_stack.rb".freeze, "lib/rails/application/finisher.rb".freeze, "lib/rails/application/routes_reloader.rb".freeze, "lib/rails/application_controller.rb".freeze, "lib/rails/backtrace_cleaner.rb".freeze, "lib/rails/cli.rb".freeze, "lib/rails/code_statistics.rb".freeze, "lib/rails/code_statistics_calculator.rb".freeze, "lib/rails/command.rb".freeze, "lib/rails/command/actions.rb".freeze, "lib/rails/command/base.rb".freeze, "lib/rails/command/behavior.rb".freeze, "lib/rails/command/environment_argument.rb".freeze, "lib/rails/commands.rb".freeze, "lib/rails/commands/application/application_command.rb".freeze, "lib/rails/commands/console/console_command.rb".freeze, "lib/rails/commands/dbconsole/dbconsole_command.rb".freeze, "lib/rails/commands/destroy/destroy_command.rb".freeze, "lib/rails/commands/generate/generate_command.rb".freeze, "lib/rails/commands/help/USAGE".freeze, "lib/rails/commands/help/help_command.rb".freeze, "lib/rails/commands/new/new_command.rb".freeze, "lib/rails/commands/plugin/plugin_command.rb".freeze, "lib/rails/commands/rake/rake_command.rb".freeze, "lib/rails/commands/runner/USAGE".freeze, "lib/rails/commands/runner/runner_command.rb".freeze, "lib/rails/commands/secrets/USAGE".freeze, "lib/rails/commands/secrets/secrets_command.rb".freeze, "lib/rails/commands/server/server_command.rb".freeze, "lib/rails/commands/test/test_command.rb".freeze, "lib/rails/commands/version/version_command.rb".freeze, "lib/rails/configuration.rb".freeze, "lib/rails/console/app.rb".freeze, "lib/rails/console/helpers.rb".freeze, "lib/rails/dev_caching.rb".freeze, "lib/rails/engine.rb".freeze, "lib/rails/engine/commands.rb".freeze, "lib/rails/engine/configuration.rb".freeze, "lib/rails/engine/railties.rb".freeze, "lib/rails/engine/updater.rb".freeze, "lib/rails/gem_version.rb".freeze, "lib/rails/generators.rb".freeze, "lib/rails/generators/actions.rb".freeze, "lib/rails/generators/actions/create_migration.rb".freeze, "lib/rails/generators/active_model.rb".freeze, "lib/rails/generators/app_base.rb".freeze, "lib/rails/generators/base.rb".freeze, "lib/rails/generators/css/assets/assets_generator.rb".freeze, "lib/rails/generators/css/assets/templates/stylesheet.css".freeze, "lib/rails/generators/css/scaffold/scaffold_generator.rb".freeze, "lib/rails/generators/erb.rb".freeze, "lib/rails/generators/erb/controller/controller_generator.rb".freeze, "lib/rails/generators/erb/controller/templates/view.html.erb".freeze, "lib/rails/generators/erb/mailer/mailer_generator.rb".freeze, "lib/rails/generators/erb/mailer/templates/layout.html.erb.tt".freeze, "lib/rails/generators/erb/mailer/templates/layout.text.erb.tt".freeze, "lib/rails/generators/erb/mailer/templates/view.html.erb".freeze, "lib/rails/generators/erb/mailer/templates/view.text.erb".freeze, "lib/rails/generators/erb/scaffold/scaffold_generator.rb".freeze, "lib/rails/generators/erb/scaffold/templates/_form.html.erb".freeze, "lib/rails/generators/erb/scaffold/templates/edit.html.erb".freeze, "lib/rails/generators/erb/scaffold/templates/index.html.erb".freeze, "lib/rails/generators/erb/scaffold/templates/new.html.erb".freeze, "lib/rails/generators/erb/scaffold/templates/show.html.erb".freeze, "lib/rails/generators/generated_attribute.rb".freeze, "lib/rails/generators/js/assets/assets_generator.rb".freeze, "lib/rails/generators/js/assets/templates/javascript.js".freeze, "lib/rails/generators/migration.rb".freeze, "lib/rails/generators/model_helpers.rb".freeze, "lib/rails/generators/named_base.rb".freeze, "lib/rails/generators/rails/app/USAGE".freeze, "lib/rails/generators/rails/app/app_generator.rb".freeze, "lib/rails/generators/rails/app/templates/Gemfile".freeze, "lib/rails/generators/rails/app/templates/README.md".freeze, "lib/rails/generators/rails/app/templates/Rakefile".freeze, "lib/rails/generators/rails/app/templates/app/assets/config/manifest.js.tt".freeze, "lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt".freeze, "lib/rails/generators/rails/app/templates/app/assets/javascripts/cable.js".freeze, "lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css".freeze, "lib/rails/generators/rails/app/templates/app/channels/application_cable/channel.rb".freeze, "lib/rails/generators/rails/app/templates/app/channels/application_cable/connection.rb".freeze, "lib/rails/generators/rails/app/templates/app/controllers/application_controller.rb.tt".freeze, "lib/rails/generators/rails/app/templates/app/helpers/application_helper.rb".freeze, "lib/rails/generators/rails/app/templates/app/jobs/application_job.rb".freeze, "lib/rails/generators/rails/app/templates/app/mailers/application_mailer.rb".freeze, "lib/rails/generators/rails/app/templates/app/models/application_record.rb".freeze, "lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt".freeze, "lib/rails/generators/rails/app/templates/app/views/layouts/mailer.html.erb.tt".freeze, "lib/rails/generators/rails/app/templates/app/views/layouts/mailer.text.erb.tt".freeze, "lib/rails/generators/rails/app/templates/bin/bundle".freeze, "lib/rails/generators/rails/app/templates/bin/rails".freeze, "lib/rails/generators/rails/app/templates/bin/rake".freeze, "lib/rails/generators/rails/app/templates/bin/setup.tt".freeze, "lib/rails/generators/rails/app/templates/bin/update.tt".freeze, "lib/rails/generators/rails/app/templates/bin/yarn".freeze, "lib/rails/generators/rails/app/templates/config.ru".freeze, "lib/rails/generators/rails/app/templates/config/application.rb".freeze, "lib/rails/generators/rails/app/templates/config/boot.rb".freeze, "lib/rails/generators/rails/app/templates/config/cable.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/frontbase.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/ibm_db.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/jdbc.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/jdbcmysql.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/jdbcpostgresql.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/jdbcsqlite3.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/mysql.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/oracle.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/postgresql.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/sqlite3.yml".freeze, "lib/rails/generators/rails/app/templates/config/databases/sqlserver.yml".freeze, "lib/rails/generators/rails/app/templates/config/environment.rb".freeze, "lib/rails/generators/rails/app/templates/config/environments/development.rb.tt".freeze, "lib/rails/generators/rails/app/templates/config/environments/production.rb.tt".freeze, "lib/rails/generators/rails/app/templates/config/environments/test.rb.tt".freeze, "lib/rails/generators/rails/app/templates/config/initializers/application_controller_renderer.rb".freeze, "lib/rails/generators/rails/app/templates/config/initializers/assets.rb.tt".freeze, "lib/rails/generators/rails/app/templates/config/initializers/backtrace_silencers.rb".freeze, "lib/rails/generators/rails/app/templates/config/initializers/cookies_serializer.rb".freeze, "lib/rails/generators/rails/app/templates/config/initializers/cors.rb".freeze, "lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb".freeze, "lib/rails/generators/rails/app/templates/config/initializers/inflections.rb".freeze, "lib/rails/generators/rails/app/templates/config/initializers/mime_types.rb".freeze, "lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_5_1.rb.tt".freeze, "lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt".freeze, "lib/rails/generators/rails/app/templates/config/locales/en.yml".freeze, "lib/rails/generators/rails/app/templates/config/puma.rb".freeze, "lib/rails/generators/rails/app/templates/config/routes.rb".freeze, "lib/rails/generators/rails/app/templates/config/secrets.yml".freeze, "lib/rails/generators/rails/app/templates/config/spring.rb".freeze, "lib/rails/generators/rails/app/templates/db/seeds.rb.tt".freeze, "lib/rails/generators/rails/app/templates/gitignore".freeze, "lib/rails/generators/rails/app/templates/package.json".freeze, "lib/rails/generators/rails/app/templates/public/404.html".freeze, "lib/rails/generators/rails/app/templates/public/422.html".freeze, "lib/rails/generators/rails/app/templates/public/500.html".freeze, "lib/rails/generators/rails/app/templates/public/apple-touch-icon-precomposed.png".freeze, "lib/rails/generators/rails/app/templates/public/apple-touch-icon.png".freeze, "lib/rails/generators/rails/app/templates/public/favicon.ico".freeze, "lib/rails/generators/rails/app/templates/public/robots.txt".freeze, "lib/rails/generators/rails/app/templates/test/application_system_test_case.rb".freeze, "lib/rails/generators/rails/app/templates/test/test_helper.rb".freeze, "lib/rails/generators/rails/assets/USAGE".freeze, "lib/rails/generators/rails/assets/assets_generator.rb".freeze, "lib/rails/generators/rails/assets/templates/javascript.js".freeze, "lib/rails/generators/rails/assets/templates/stylesheet.css".freeze, "lib/rails/generators/rails/controller/USAGE".freeze, "lib/rails/generators/rails/controller/controller_generator.rb".freeze, "lib/rails/generators/rails/controller/templates/controller.rb".freeze, "lib/rails/generators/rails/encrypted_secrets/encrypted_secrets_generator.rb".freeze, "lib/rails/generators/rails/generator/USAGE".freeze, "lib/rails/generators/rails/generator/generator_generator.rb".freeze, "lib/rails/generators/rails/generator/templates/%file_name%_generator.rb.tt".freeze, "lib/rails/generators/rails/generator/templates/USAGE.tt".freeze, "lib/rails/generators/rails/generator/templates/templates/.empty_directory".freeze, "lib/rails/generators/rails/helper/USAGE".freeze, "lib/rails/generators/rails/helper/helper_generator.rb".freeze, "lib/rails/generators/rails/helper/templates/helper.rb".freeze, "lib/rails/generators/rails/integration_test/USAGE".freeze, "lib/rails/generators/rails/integration_test/integration_test_generator.rb".freeze, "lib/rails/generators/rails/migration/USAGE".freeze, "lib/rails/generators/rails/migration/migration_generator.rb".freeze, "lib/rails/generators/rails/model/USAGE".freeze, "lib/rails/generators/rails/model/model_generator.rb".freeze, "lib/rails/generators/rails/plugin/USAGE".freeze, "lib/rails/generators/rails/plugin/plugin_generator.rb".freeze, "lib/rails/generators/rails/plugin/templates/%name%.gemspec".freeze, "lib/rails/generators/rails/plugin/templates/Gemfile".freeze, "lib/rails/generators/rails/plugin/templates/MIT-LICENSE".freeze, "lib/rails/generators/rails/plugin/templates/README.md".freeze, "lib/rails/generators/rails/plugin/templates/Rakefile".freeze, "lib/rails/generators/rails/plugin/templates/app/controllers/%namespaced_name%/application_controller.rb.tt".freeze, "lib/rails/generators/rails/plugin/templates/app/helpers/%namespaced_name%/application_helper.rb.tt".freeze, "lib/rails/generators/rails/plugin/templates/app/jobs/%namespaced_name%/application_job.rb.tt".freeze, "lib/rails/generators/rails/plugin/templates/app/mailers/%namespaced_name%/application_mailer.rb.tt".freeze, "lib/rails/generators/rails/plugin/templates/app/models/%namespaced_name%/application_record.rb.tt".freeze, "lib/rails/generators/rails/plugin/templates/app/views/layouts/%namespaced_name%/application.html.erb.tt".freeze, "lib/rails/generators/rails/plugin/templates/bin/rails.tt".freeze, "lib/rails/generators/rails/plugin/templates/bin/test.tt".freeze, "lib/rails/generators/rails/plugin/templates/config/routes.rb".freeze, "lib/rails/generators/rails/plugin/templates/gitignore".freeze, "lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%.rb".freeze, "lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/engine.rb".freeze, "lib/rails/generators/rails/plugin/templates/lib/%namespaced_name%/version.rb".freeze, "lib/rails/generators/rails/plugin/templates/lib/tasks/%namespaced_name%_tasks.rake".freeze, "lib/rails/generators/rails/plugin/templates/rails/application.rb".freeze, "lib/rails/generators/rails/plugin/templates/rails/boot.rb".freeze, "lib/rails/generators/rails/plugin/templates/rails/dummy_manifest.js".freeze, "lib/rails/generators/rails/plugin/templates/rails/engine_manifest.js".freeze, "lib/rails/generators/rails/plugin/templates/rails/javascripts.js".freeze, "lib/rails/generators/rails/plugin/templates/rails/routes.rb".freeze, "lib/rails/generators/rails/plugin/templates/rails/stylesheets.css".freeze, "lib/rails/generators/rails/plugin/templates/test/%namespaced_name%_test.rb".freeze, "lib/rails/generators/rails/plugin/templates/test/application_system_test_case.rb".freeze, "lib/rails/generators/rails/plugin/templates/test/integration/navigation_test.rb".freeze, "lib/rails/generators/rails/plugin/templates/test/test_helper.rb".freeze, "lib/rails/generators/rails/resource/USAGE".freeze, "lib/rails/generators/rails/resource/resource_generator.rb".freeze, "lib/rails/generators/rails/resource_route/resource_route_generator.rb".freeze, "lib/rails/generators/rails/scaffold/USAGE".freeze, "lib/rails/generators/rails/scaffold/scaffold_generator.rb".freeze, "lib/rails/generators/rails/scaffold/templates/scaffold.css".freeze, "lib/rails/generators/rails/scaffold_controller/USAGE".freeze, "lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb".freeze, "lib/rails/generators/rails/scaffold_controller/templates/api_controller.rb".freeze, "lib/rails/generators/rails/scaffold_controller/templates/controller.rb".freeze, "lib/rails/generators/rails/system_test/USAGE".freeze, "lib/rails/generators/rails/system_test/system_test_generator.rb".freeze, "lib/rails/generators/rails/task/USAGE".freeze, "lib/rails/generators/rails/task/task_generator.rb".freeze, "lib/rails/generators/rails/task/templates/task.rb".freeze, "lib/rails/generators/resource_helpers.rb".freeze, "lib/rails/generators/test_case.rb".freeze, "lib/rails/generators/test_unit.rb".freeze, "lib/rails/generators/test_unit/controller/controller_generator.rb".freeze, "lib/rails/generators/test_unit/controller/templates/functional_test.rb".freeze, "lib/rails/generators/test_unit/generator/generator_generator.rb".freeze, "lib/rails/generators/test_unit/generator/templates/generator_test.rb".freeze, "lib/rails/generators/test_unit/helper/helper_generator.rb".freeze, "lib/rails/generators/test_unit/integration/integration_generator.rb".freeze, "lib/rails/generators/test_unit/integration/templates/integration_test.rb".freeze, "lib/rails/generators/test_unit/job/job_generator.rb".freeze, "lib/rails/generators/test_unit/job/templates/unit_test.rb.erb".freeze, "lib/rails/generators/test_unit/mailer/mailer_generator.rb".freeze, "lib/rails/generators/test_unit/mailer/templates/functional_test.rb".freeze, "lib/rails/generators/test_unit/mailer/templates/preview.rb".freeze, "lib/rails/generators/test_unit/model/model_generator.rb".freeze, "lib/rails/generators/test_unit/model/templates/fixtures.yml".freeze, "lib/rails/generators/test_unit/model/templates/unit_test.rb".freeze, "lib/rails/generators/test_unit/plugin/plugin_generator.rb".freeze, "lib/rails/generators/test_unit/plugin/templates/%file_name%_test.rb.tt".freeze, "lib/rails/generators/test_unit/plugin/templates/test_helper.rb".freeze, "lib/rails/generators/test_unit/scaffold/scaffold_generator.rb".freeze, "lib/rails/generators/test_unit/scaffold/templates/api_functional_test.rb".freeze, "lib/rails/generators/test_unit/scaffold/templates/functional_test.rb".freeze, "lib/rails/generators/test_unit/system/system_generator.rb".freeze, "lib/rails/generators/test_unit/system/templates/application_system_test_case.rb".freeze, "lib/rails/generators/test_unit/system/templates/system_test.rb".freeze, "lib/rails/generators/testing/assertions.rb".freeze, "lib/rails/generators/testing/behaviour.rb".freeze, "lib/rails/generators/testing/setup_and_teardown.rb".freeze, "lib/rails/info.rb".freeze, "lib/rails/info_controller.rb".freeze, "lib/rails/initializable.rb".freeze, "lib/rails/mailers_controller.rb".freeze, "lib/rails/paths.rb".freeze, "lib/rails/plugin/test.rb".freeze, "lib/rails/rack.rb".freeze, "lib/rails/rack/logger.rb".freeze, "lib/rails/railtie.rb".freeze, "lib/rails/railtie/configurable.rb".freeze, "lib/rails/railtie/configuration.rb".freeze, "lib/rails/ruby_version_check.rb".freeze, "lib/rails/secrets.rb".freeze, "lib/rails/source_annotation_extractor.rb".freeze, "lib/rails/tasks.rb".freeze, "lib/rails/tasks/annotations.rake".freeze, "lib/rails/tasks/dev.rake".freeze, "lib/rails/tasks/engine.rake".freeze, "lib/rails/tasks/framework.rake".freeze, "lib/rails/tasks/initializers.rake".freeze, "lib/rails/tasks/log.rake".freeze, "lib/rails/tasks/middleware.rake".freeze, "lib/rails/tasks/misc.rake".freeze, "lib/rails/tasks/restart.rake".freeze, "lib/rails/tasks/routes.rake".freeze, "lib/rails/tasks/statistics.rake".freeze, "lib/rails/tasks/tmp.rake".freeze, "lib/rails/tasks/yarn.rake".freeze, "lib/rails/templates/layouts/application.html.erb".freeze, "lib/rails/templates/rails/info/properties.html.erb".freeze, "lib/rails/templates/rails/info/routes.html.erb".freeze, "lib/rails/templates/rails/mailers/email.html.erb".freeze, "lib/rails/templates/rails/mailers/index.html.erb".freeze, "lib/rails/templates/rails/mailers/mailer.html.erb".freeze, "lib/rails/templates/rails/welcome/index.html.erb".freeze, "lib/rails/test_help.rb".freeze, "lib/rails/test_unit/line_filtering.rb".freeze, "lib/rails/test_unit/railtie.rb".freeze, "lib/rails/test_unit/reporter.rb".freeze, "lib/rails/test_unit/runner.rb".freeze, "lib/rails/test_unit/testing.rake".freeze, "lib/rails/version.rb".freeze, "lib/rails/welcome_controller.rb".freeze] - s.homepage = "http://rubyonrails.org".freeze - s.licenses = ["MIT".freeze] - s.rdoc_options = ["--exclude".freeze, ".".freeze] - s.required_ruby_version = Gem::Requirement.new(">= 2.2.2".freeze) - s.rubygems_version = "2.7.6.2".freeze - s.summary = "Tools for creating, working with, and running Rails applications.".freeze - - if s.respond_to? :specification_version then - s.specification_version = 4 - - if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_development_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, ["= 5.1.7"]) - s.add_runtime_dependency(%q.freeze, [">= 0"]) - s.add_runtime_dependency(%q.freeze, [">= 0.8.7"]) - s.add_runtime_dependency(%q.freeze, ["< 2.0", ">= 0.18.1"]) - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 0"]) - s.add_dependency(%q.freeze, [">= 0.8.7"]) - s.add_dependency(%q.freeze, ["< 2.0", ">= 0.18.1"]) - end - else - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, ["= 5.1.7"]) - s.add_dependency(%q.freeze, [">= 0"]) - s.add_dependency(%q.freeze, [">= 0.8.7"]) - s.add_dependency(%q.freeze, ["< 2.0", ">= 0.18.1"]) - end -end diff --git a/debian/gitlab.install b/debian/gitlab.install index 73a2aa3a66..90274c4ad4 100644 --- a/debian/gitlab.install +++ b/debian/gitlab.install @@ -9,7 +9,6 @@ debian/conf/smtp_settings.rb etc/gitlab/initializers debian/conf/tmpfiles.d/gitlab.conf /usr/lib/tmpfiles.d/ debian/conf/nginx.conf.example usr/lib/gitlab/templates debian/conf/nginx.ssl.conf.example usr/lib/gitlab/templates -debian/gems-compat/* usr/share/gitlab/vendor/gems debian/rake-tasks.sh usr/lib/gitlab/scripts debian/gitlab-rake.sh usr/lib/gitlab/scripts babel.config.js usr/share/gitlab