New upstream version 12.1.13

This commit is contained in:
Sruthi Chandran 2019-10-03 14:02:42 +05:30
parent 73951b7177
commit dbce0600c5
84 changed files with 12743 additions and 0 deletions

8
derailed-benchmarks/.gitignore vendored Normal file
View file

@ -0,0 +1,8 @@
.DS_Store
*.gem
/test/rails_app/tmp/*
/test/rails_app/log/*
*.sqlite3
Gemfile.lock
gemfiles/*.lock

View file

@ -0,0 +1,18 @@
language: ruby
rvm:
- 2.5.5
- 2.6.3
- ruby-head
gemfile:
- gemfiles/rails_5_1.gemfile
- gemfiles/rails_5_2.gemfile
- gemfiles/rails_6_0.gemfile
- gemfiles/rails_git.gemfile
before_install:
- gem install bundler
matrix:
allow_failures:
- rvm: ruby-head

View file

@ -0,0 +1,26 @@
# -*- mode: ruby -*-
# vi: set ft=ruby :
appraise "rails-3-2" do
gem "rails", "~> 3.2.0"
end
appraise "rails-4-0" do
gem "rails", "~> 4.0.0"
end
appraise "rails-4-1" do
gem "rails", "~> 4.1.0"
end
appraise "rails-4-2" do
gem "rails", "~> 4.2.0"
end
appraise "rails-5-0" do
gem "rails", "~> 5.0.0"
end
appraise "rails-5-1" do
gem "rails", "~> 5.1.0"
end

View file

@ -0,0 +1,76 @@
# A Log of Changes!
## 1.4.0
- Allow configuration of `perf:ips` benchmark.
- Fix bug with `require_relative` [#142](https://github.com/schneems/derailed_benchmarks/pull/142)
- Introduce `perf:library` to profile patches to libraries (like Rails) [#135](https://github.com/schneems/derailed_benchmarks/pull/135), [#139](https://github.com/schneems/derailed_benchmarks/pull/139), [#140](https://github.com/schneems/derailed_benchmarks/pull/140), [#141](https://github.com/schneems/derailed_benchmarks/pull/141)
## 1.3.6
- `require_relative` is now measured [commit](https://github.com/schneems/derailed_benchmarks/commit/af11bcc46a4fa24f79e4897a51034927a56e077e)
- Fix bug preventing a specific Rails 6 file from being loaded (https://github.com/schneems/derailed_benchmarks/pull/134)
- `exit(1)` is called instead of raise (https://github.com/schneems/derailed_benchmarks/pull/127)
## [1.3.5]
- Output of `test` now emits the word "derailed" for easier grepping.
- Fix "already initialized constant" warning
## [1.3.4]
- Allow for "warming up tasks" via WARM_COUNT env var #119
## [1.3.3]
- Make all paths added to $LOAD_PATH absolute instead of relative to allow for use with apps that use bootsnap.
## [1.3.2]
- Allow for use with Rack 11.
## [1.3.1]
- Allow for use with Rack 11.
## [1.3.0] - 2015-01-07
- Allow environment variable to skip Active Record setup.
- Allow Rack 2 to work with Derailed.
## [1.1.3] - 2015-10-15
- Update docs
## [1.1.2] - 2015-10-05
- Added ability to use TEST_COUNT environment variable with `perf:heap`.
## [1.1.1] - 2015-10-01
- Added ability to create a heap dump `perf:heap`.
## [1.1.0] - 2015-09-09
- Set custom auth user using a lambda in perf.rake
- Changed `perf:ram_over_time` changed to `perf:mem_over_time`
- Fixed gem warnings
## [1.0.1] - 2015-06-20
- `bundle:mem` and similar tasks now keep track of duplicate requires and display them along side of memory requirements. This makes it easier to identify where components are used by multiple libraries
- Add rake to gemspec which gets rid of `Unresolved specs during Gem::Specification.reset:` warning
- Outputs of memory are now done in [mebibytes](https://en.wikipedia.org/wiki/Mebibyte), a more accurate unit for the value we're measuring (hint: it's what you think MB is).
## [1.0.0] - 2015-05-14
- Added `derailed` command line utility. Can be used with just a Gemfile using command `$ derailed bundle:mem` and `$ derailed bundle:objects`. All existing Rake tasks can now be called with `$ derailed exec` such as `$ derailed exec perf:mem`.
- Changed memory_profiler task to be `perf:objects` instead of `perf:mem`.
- Changed boot time memory measurement to `perf:mem` instead of `perf:require_bench`
- Released seperate [derailed](https://github.com/schneems/derailed) gem that is a wrapper for this gem. I.e. installing that gem installs this one. Easier to remember, less words to type. Also means there's no colision using the `derailed` namespace for executables inside of the `derailed_benchmarks`.
## [0.0.0] - 2014-08-15
- Initial release

View file

@ -0,0 +1,9 @@
source 'https://rubygems.org'
gemspec
group :development, :test do
gem "sqlite3", :platform => [:ruby, :mswin, :mingw]
gem "activerecord-jdbcsqlite3-adapter", '~> 1.3.13', :platform => :jruby
gem "test-unit", "~> 3.0"
end

View file

@ -0,0 +1,683 @@
## Derailed Benchmarks
A series of things you can use to benchmark a Rails or Ruby app.
![](http://media.giphy.com/media/lfbxexWy71b6U/giphy.gif)
[![Build Status](https://travis-ci.org/schneems/derailed_benchmarks.svg)](https://travis-ci.org/schneems/derailed_benchmarks)
[![Help Contribute to Open Source](https://www.codetriage.com/schneems/derailed_benchmarks/badges/users.svg)](https://www.codetriage.com/schneems/derailed_benchmarks)
## Compatibility/Requirements
This gem has been tested and is known to work with Rails 3.2+ using Ruby
2.1+. Some commands __may__ work on older versions of Ruby, but not all commands are supported.
For some benchmarks, not all, you'll need to verify you have a working version of curl on your OS:
```
$ which curl
/usr/bin/curl
$ curl -V
curl 7.37.1 #...
```
## Install
Put this in your gemfile:
```ruby
gem 'derailed_benchmarks', group: :development
```
Then run `$ bundle install`.
While executing your commands you may need to use `bundle exec` before typing the command.
To use all profiling methods available also add:
```ruby
gem 'stackprof', group: :development
```
You must be using Ruby 2.1+ to install these libraries. If you're on an older version of Ruby, what are you waiting for?
## Use
There are two ways to benchmark an app. Derailed can either try to boot your web app and run requests against it while benchmarking, or it can statically give you more information about the dependencies that are in your Gemfile. Booting your app will always be more accurate, but if you cannot get your app to run in production locally, you'll still find the static information useful.
## Static Benchmarking
This section covers how to get memory information from your Gemfile without having to boot your app.
All commands in this section will begin with `$ derailed bundle:`
For more information on the relationship between memory and performance please read/watch [How Ruby Uses Memory](http://www.schneems.com/2015/05/11/how-ruby-uses-memory.html).
### Memory used at Require time
Each gem you add to your project can increase your memory at boot. You can get visibility into the total memory used by each gem in your Gemfile by running:
```
$ bundle exec derailed bundle:mem
```
This will load each of your gems in your Gemfile and see how much memory they consume when they are required. For example if you're using the `mail` gem. The output might look like this
```
$ bundle exec derailed bundle:mem
TOP: 54.1836 MiB
mail: 18.9688 MiB
mime/types: 17.4453 MiB
mail/field: 0.4023 MiB
mail/message: 0.3906 MiB
action_view/view_paths: 0.4453 MiB
action_view/base: 0.4336 MiB
```
_Aside: A "MiB", which is the [IEEE] and [IEC] symbol for Mebibyte, is 2<sup>20</sup> bytes / 1024 Kibibytes (which are in turn 1024 bytes)._
[IEEE]: https://en.wikipedia.org/wiki/IEEE_1541-2002
[IEC]: https://en.wikipedia.org/wiki/IEC_80000-13
Here we can see that `mail` uses 18MiB, with the majority coming from `mime/types`. You can use this information to prune out large dependencies you don't need. Also if you see a large memory use by a gem that you do need, please open up an issue with that library to let them know (be sure to include reproduction instructions). Hopefully as a community we can identify memory hotspots and reduce their impact. Before we can fix performance problems, we need to know where those problems exist.
By default this task will only return results from the `:default` and `"production"` groups. If you want a different group you can run with.
```
$ bundle exec derailed bundle:mem development
```
You can use `CUT_OFF=0.3` to only show files that have above a certain memory usage, this can be used to help eliminate noise.
Note: This method won't include files in your own app, only items in your Gemfile. For that you'll need to use `bundle exec derailed exec mem`. See below for more info.
The same file may be required by several libraries, since Ruby only requires files once, the cost is only associated with the first library to require a file. To make this more visible duplicate entries will list all the parents they belong to. For example both `mail` and `fog` require `mime/types. So it may show up something like this in your app:
```
$ bundle exec derailed bundle:mem
TOP: 54.1836 MiB
mail: 18.9688 MiB
mime/types: 17.4453 MiB (Also required by: fog/storage)
mail/field: 0.4023 MiB
mail/message: 0.3906 MiB
```
That way you'll know that simply removing the top level library (mail) would not result in a memory reduction. The output is truncated after the first two entries:
```
fog/core: 0.9844 MiB (Also required by: fog/xml, fog/json, and 48 others)
fog/rackspace: 0.957 MiB
fog/joyent: 0.7227 MiB
fog/joyent/compute: 0.7227 MiB
```
If you want to see everything that requires `fog/core` you can run `CUT_OFF=0 bundle exec derailed bundle:mem` to get the full output that you can then grep through manually.
Update: While `mime/types` looks horrible in these examples, it's been fixed. You can add this to the top of your gemfile for free memory:
```ruby
gem 'mime-types', [ '~> 2.6', '>= 2.6.1' ], require: 'mime/types/columnar'
```
### Objects created at Require time
To get more info about the objects, using [memory_profiler](https://github.com/SamSaffron/memory_profiler), created when your dependencies are required you can run:
```
$ bundle exec derailed bundle:objects
```
This will output detailed information about objects created while your dependencies are loaded
```
Measuring objects created by gems in groups [:default, "production"]
Total allocated 433895
Total retained 100556
allocated memory by gem
-----------------------------------
24369241 activesupport-4.2.1
15560550 mime-types-2.4.3
8103432 json-1.8.2
```
Once you identify a gem that creates a large amount of memory using `$ bundle exec derailed bundle:mem` you can pull that gem into it's own Gemfile and run `$ bundle exec derailed bundle:objects` to get detailed information about it. This information can be used by contributors and library authors to identify and eliminate object creation hotspots.
By default this task will only return results from the `:default` and `"production"` groups. If you want a different group you can run with.
```
$ bundle exec derailed bundle:objects development
```
Note: This method won't include files in your own app, only items in your Gemfile. For that you'll need to use `bundle exec derailed exec objects`. See below for more info.
## Dynamic app Benchmarking
This benchmarking will attempt to boot your Rails app and run benchmarks against it. Unlike the static benchmarking with `$ bundle exec derailed bundle:*` these will include information about your specific app. The pro is you'll get more information and potentially identify problems in your app code, the con is that it requires you to be able to boot and run your application in a `production` environment locally, which for some apps is non-trivial.
You may want to check out [mini-profiler](https://github.com/MiniProfiler/rack-mini-profiler), here's a [mini-profiler walkthrough](http://www.justinweiss.com/articles/a-new-way-to-understand-your-rails-apps-performance/). It's great and does slightly different benchmarking than what you'll find here.
### Running in Production Locally.
Before you want to attempt any dynamic benchmarks, you'll need to boot your app in `production` mode. We benchmark using `production` because it is close to your deployed performance. This section is more a collection of tips rather than a de-facto tutorial.
For starters try booting into a console:
```
$ RAILS_ENV=production rails console
```
You may get errors, complaining about not being able to connect to the `production` database. For this, you can either create a local database with the name of your production database, or you can copy the info from your `development` group to your `production` group in your `database.yml`.
You may be missing environment variables expected in `production` such as `SECRET_KEY_BASE`. For those you can either commit them to your `.env` file (if you're using one). Or add them directly to the command:
```
$ SECRET_KEY_BASE=foo RAILS_ENV=production rails console
```
Once you can boot a console in production, you'll need to be able to boot a server in production
```
$ RAILS_ENV=production rails server
```
You may need to disable enforcing SSL or other domain restrictions temporarily. If you do these, don't forget to add them back in before deploying any code (eek!).
You can get information from STDOUT if you're using `rails_12factor` gem, or from `log/production.log` by running
```
$ tail -f log/production.log
```
Once you've fixed all errors and you can run a server in production, you're almost there.
### Running Derailed Exec
You can run commands against your app by running `$ derailed exec`. There are sections on setting up Rack and using authenticated requests below. You can see what commands are available by running:
```
$ bundle exec derailed exec --help
$ derailed exec perf:allocated_objects # outputs allocated object diff after app is called TEST_COUNT times
$ derailed exec perf:gc # outputs GC::Profiler.report data while app is called TEST_COUNT times
$ derailed exec perf:ips # iterations per second
$ derailed exec perf:mem # show memory usage caused by invoking require per gem
$ derailed exec perf:objects # profiles ruby allocation
$ derailed exec perf:mem_over_time # outputs memory usage over time
$ derailed exec perf:test # hits the url TEST_COUNT times
```
Instead of going over each command we'll look at common problems and which commands are best used to diagnose them. Later on we'll cover all of the environment variables you can use to configure derailed benchmarks in it's own section.
### Is my app leaking memory?
If your app appears to be leaking ever increasing amounts of memory, you'll want to first verify if it's an actual unbound "leak" or if it's just using more memory than you want. A true memory leak will increase memory use forever, most apps will increase memory use until they hit a "plateau". To diagnose this you can run:
```
$ bundle exec derailed exec perf:mem_over_time
```
This will boot your app and hit it with requests and output the memory to stdout (and a file under ./tmp). It may look like this:
```
$ bundle exec derailed exec perf:mem_over_time
Booting: production
Endpoint: "/"
PID: 78675
103.55078125
178.45703125
179.140625
180.3671875
182.1875
182.55859375
# ...
183.65234375
183.26171875
183.62109375
```
Here we can see that while the memory use is increasing, it levels off around 183 MiB. You'll want to run this task using ever increasing values of `TEST_COUNT=` for example
```
$ TEST_COUNT=5000 bundle exec derailed exec perf:mem_over_time
$ TEST_COUNT=10_000 bundle exec derailed exec perf:mem_over_time
$ TEST_COUNT=20_000 bundle exec derailed exec perf:mem_over_time
```
Adjust your counts appropriately so you can get results in a reasonable amount of time. If your memory never levels off, congrats! You've got a memory leak! I recommend copying and pasting values from the file generated into google docs and graphing it so you can get a better sense of the slope of your line.
If you don't want it to generate a tmp file with results run with `SKIP_FILE_WRITE=1`.
If you're pretty sure that there's a memory leak, but you can't confirm it using this method. Look at the environment variable options below, you can try hitting a different endpoint etc.
## Dissecting a Memory Leak
If you've identified a memory leak, or you simply want to see where your memory use is coming from you'll want to use
```
$ bundle exec derailed exec perf:objects
```
This task hits your app and uses memory_profiler to see where objects are created. You'll likely want to run once, then run it with a higher `TEST_COUNT` so that you can see hotspots where objects are created on __EVERY__ request versus just maybe on the first.
```
$ TEST_COUNT=10 bundle exec derailed exec perf:objects
```
This is an expensive operation, so you likely want to keep the count lowish. Once you've identified a hotspot read [how ruby uses memory](http://www.sitepoint.com/ruby-uses-memory/) for some tips on reducing object allocations.
This is similar to `$ bundle exec derailed bundle:objects` however it includes objects created at runtime. It's much more useful for actual production performance debugging, the other is more useful for library authors to debug.
## I want a Heap Dump
If you're still struggling with runtime memory you can generate a heap dump that can later be analyzed using [heap_inspect](https://github.com/schneems/heapy).
```
$ bundle exec derailed exec perf:heap
Booting: production
Heap file generated: "tmp/2015-10-01T12:31:03-05:00-heap.dump"
Analyzing Heap
==============
Generation: 0 object count: 209307
Generation: 35 object count: 31236
Generation: 36 object count: 36705
Generation: 37 object count: 1301
Generation: 38 object count: 8
Try uploading "tmp/2015-10-01T12:31:03-05:00-heap.dump" to http://tenderlove.github.io/heap-analyzer/
```
For more help on getting data from a heap dump see
```
$ heapy --help
```
### Memory Is large at boot.
Ruby memory typically goes in one direction, up. If your memory is large when you boot the application it will likely only increase. In addition to debugging memory retained from dependencies obtained while running `$ derailed bundle:mem` you'll likely want to see how your own files contribute to memory use.
This task does essentially the same thing, however it hits your app with one request to ensure that any last minute `require`-s have been called. To execute you can run:
```
$ bundle exec derailed exec perf:mem
TOP: 54.1836 MiB
mail: 18.9688 MiB
mime/types: 17.4453 MiB
mail/field: 0.4023 MiB
mail/message: 0.3906 MiB
action_view/view_paths: 0.4453 MiB
action_view/base: 0.4336 MiB
```
You can use `CUT_OFF=0.3` to only show files that have above a certain memory usage, this can be used to help eliminate noise.
If your application code is extremely large at boot consider using `$ derailed exec perf:objects` to debug low level object creation.
## My app is Slow
Well...aren't they all. If you've already looked into decreasing object allocations, you'll want to look at where your app is spending the most amount of code. Once you know that, you'll know where to spend your time optimising.
One technique is to use a "sampling" stack profiler. This type of profiling looks at what method is being executed at a given interval and records it. At the end of execution it counts all the times a given method was being called and shows you the percent of time spent in each method. This is a very low overhead method to looking into execution time. Ruby 2.1+ has this available in gem form it's called [stackprof](https://github.com/tmm1/stackprof). As you guessed you can run this with derailed benchmarks, first add it to your gemfile `gem "stackprof", group: :development` then execute:
```
$ bundle exec derailed exec perf:stackprof
==================================
Mode: cpu(1000)
Samples: 16067 (1.07% miss rate)
GC: 2651 (16.50%)
==================================
TOTAL (pct) SAMPLES (pct) FRAME
1293 (8.0%) 1293 (8.0%) block in ActionDispatch::Journey::Formatter#missing_keys
872 (5.4%) 872 (5.4%) block in ActiveSupport::Inflector#apply_inflections
935 (5.8%) 802 (5.0%) ActiveSupport::SafeBuffer#safe_concat
688 (4.3%) 688 (4.3%) Temple::Utils#escape_html
578 (3.6%) 578 (3.6%) ActiveRecord::Attribute#initialize
3541 (22.0%) 401 (2.5%) ActionDispatch::Routing::RouteSet#url_for
346 (2.2%) 346 (2.2%) ActiveSupport::SafeBuffer#initialize
298 (1.9%) 298 (1.9%) ThreadSafe::NonConcurrentCacheBackend#[]
227 (1.4%) 227 (1.4%) block in ActiveRecord::ConnectionAdapters::PostgreSQLAdapter#exec_no_cache
218 (1.4%) 218 (1.4%) NewRelic::Agent::Instrumentation::Event#initialize
1102 (6.9%) 213 (1.3%) ActiveSupport::Inflector#apply_inflections
193 (1.2%) 193 (1.2%) ActionDispatch::Routing::RouteSet::NamedRouteCollection::UrlHelper#deprecate_string_options
173 (1.1%) 173 (1.1%) ActiveSupport::SafeBuffer#html_safe?
308 (1.9%) 171 (1.1%) NewRelic::Agent::Instrumentation::ActionViewSubscriber::RenderEvent#metric_name
159 (1.0%) 159 (1.0%) block in ActiveRecord::Result#hash_rows
358 (2.2%) 153 (1.0%) ActionDispatch::Routing::RouteSet::Generator#initialize
153 (1.0%) 153 (1.0%) ActiveRecord::Type::String#cast_value
192 (1.2%) 143 (0.9%) ActionController::UrlFor#url_options
808 (5.0%) 127 (0.8%) ActiveRecord::LazyAttributeHash#[]
121 (0.8%) 121 (0.8%) PG::Result#values
120 (0.7%) 120 (0.7%) ActionDispatch::Journey::Router::Utils::UriEncoder#escape
2478 (15.4%) 117 (0.7%) ActionDispatch::Journey::Formatter#generate
115 (0.7%) 115 (0.7%) NewRelic::Agent::Instrumentation::EventedSubscriber#event_stack
114 (0.7%) 114 (0.7%) ActiveRecord::Core#init_internals
263 (1.6%) 110 (0.7%) ActiveRecord::Type::Value#type_cast
8520 (53.0%) 102 (0.6%) ActionView::CompiledTemplates#_app_views_repos__repo_html_slim__2939326833298152184_70365772737940
```
From here you can dig into individual methods.
## Is this perf change faster?
Micro benchmarks might tell you at the code level how much faster something is, but what about the overall application speed. If you're trying to figure out how effective a performance change is to your application, it is useful to compare it to your existing app performance. To help you with that you can use:
```
$ bundle exec derailed exec perf:ips
Endpoint: "/"
Calculating -------------------------------------
ips 1.000 i/100ms
-------------------------------------------------
ips 3.306 (± 0.0%) i/s - 17.000
```
This will hit an endpoint in your application using [benchmark-ips](https://github.com/evanphx/benchmark-ips). In "iterations per second" a higher value is always better. You can run your code change several times using this method, and then run your "baseline" codebase (without your changes) to see how it affects your overall performance. You'll want to run and record the results several times (including the std deviation) so you can help eliminate noise. Benchmarking is hard, this technique isn't perfect but it's definitely better than nothing.
If you care you can also run pure benchmark (without ips):
```
$ bundle exec derailed exec perf:test
```
But I wouldn't, benchmark-ips is a better measure.
### Configuring `benchmark-ips`
The `benchmark-ips` gem allows for a number of test run customizations, and `derailed_benchmarks` exposes a few of them via environment variables.
- `IPS_WARMUP`: number of seconds spent warming up the app, defaullt is `2`
- `IPS_TIME`: number of seconds to run ips benchmark for after warm up, defaullt is `5`
- `IPS_SUITE`: custom suite to use to run test
- `IPS_ITERATIONS`: number of times to run the test, displaying that last result, defaullt is `1`
## I made a patch to to Rails how can I tell if it made my Rails app faster and test for statistical significance
When you're trying to submit a performance patch to rails/rails then they'll likely ask you for a benchmark. While you can sometimes provide a microbenchmark, a real world full stack request/response test is the gold standard.
That's what this section is about. You'll need a rails app, ideally one you can open source (see [example apps](http://codetriage.com/example_app) if you need inspiration for extracting your private code into something external).
Then you'll need to fork rails and make a branch. Then point your rails app to your branch in your gemfile
```
gem 'rails', github: "<github username>/rails", branch: "<your branch name>"
```
or point it at your local copy:
```
gem 'rails', path: "<path/to/your/local/copy/rails>"
```
To run your test:
```
$ bundle exec derailed exec perf:library
```
This will automatically test the two latest commits of Rails (or the library you've specified). If you would like to compare against different SHAs you can manually specify them:
```
$ SHAS_TO_TEST="7b4d80cb373e,13d6aa3a7b70" bundle exec derailed exec perf:library
```
Use a comma to seperate your branch names with the `SHAS_TO_TEST` env var, or omit the env var to use the last 2 git commits.
If you only include one SHA, then derailed will grab the latest commit and compare it to that SHA.
These tests might take a along time to run so the output is stored on disk incase you want to see them in the future, they're at `tmp/library_branches/<timestamp>` and labeled with the same names as your commits.
When the test is done it will output which commit "won" and by how much:
```
❤️ ❤️ ❤️ (Statistically Significant) ❤️ ❤️ ❤️
[7b4d80cb37] "1.8x Faster Partial Caching - Faster Cache Keys" - (10.9711965 seconds)
FASTER by:
1.0870x [older/newer]
8.0026% [(older - newer) / older * 100]
[13d6aa3a7b] "Merge pull request #36284 from kamipo/fix_eager_loading_with_string_joins" - (11.9255485 seconds)
P-value: 4.635595463712749e-05
Is significant? (P-value < 0.05): true
```
You can provide this to the Rails team along with the example app you used to benchmark (so they can independently verify if needed).
Generally performance patches have to be weighted in terms of how much they help versus how large/difficult/gnarly the patch is. If the above example was a really tiny patch and it was in a common component, then half a percent might be a justafiable increase. If it was a huge re-write then it's likely going to be closed. In general I tend to not submit patches unless I'm seeing `>= 1%` performance increases.
You can use this to test changes in other libraries that aren't rails, you just have to tell it the path to the library you want to test against with the `DERAILED_PATH_TO_LIBRARY` env var.
> To get the best results before running tests you should close all programs on your laptop, turn on a program to prevent your laptop from going to sleep (or increase your sleep timer). Make sure it's plugged into a power outlet and go grab a cup of coffee. If you do anything on your laptop while this test is running you risk the chance of skewing your results.
By default derailed will stop once statistical signficance has been detected, you can tune this behavior by setting `DERAILED_STOP_VALID_COUNT` env var. Setting this to a positive number, will increase the number of iterations required that are detected to be statistically significant. For example setting it to 100 might result in 120 runs if it takes 20 runs to detect significance. Generally the more runs you have, the more accurate your averages will be. You can disable this all together by setting `DERAILED_STOP_VALID_COUNT=0` which will force derailed to run all iterations.
## Environment Variables
All the tasks accept configuration in the form of environment variables.
### Increasing or decreasing test count `TEST_COUNT`
For tasks that are run a number of times you can set the number using `TEST_COUNT` for example:
```
$ TEST_COUNT=100_000 bundle exec derailed exec perf:test
```
### Warming up your app before measuring with `WARM_COUNT`
When you are measuring the long term performance of an application, especially if you're using jit you may want to let the application "warm up" without measuring this time. To allow for this you can specify `WARM_COUNT` and the application will be called that number of times before any measurements are taken.
```
$ WARM_COUNT=5_000 bundle exec derailed exec perf:test
Warming up app: 5000 times
# ...
```
### Hitting a different endpoint with `PATH_TO_HIT`
By default tasks will hit your homepage `/`. If you want to hit a different url use `PATH_TO_HIT` for example if you wanted to go to `users/new` you can execute:
```
$ PATH_TO_HIT=/users/new bundle exec derailed exec perf:mem
```
This method accepts a full uri. For example, allowing you to hit a subdomain endpoint:
```
$ PATH_TO_HIT=http://subdomain.lvh.me:3000/users/new bundle exec derailed exec perf:mem
```
Beware that you cannot combine a full uri with `USE_SERVER`.
### Setting HTTP headers
You can specify HTTP headers by setting `HTTP_<header name>` variables. Example:
```
$ HTTP_AUTHORIZATION="Basic YWRtaW46c2VjcmV0\n" \
HTTP_USER_AGENT="Mozilla/5.0" \
PATH_TO_HIT=/foo_secret bundle exec derailed exec perf:ips
```
### Using a real web server with `USE_SERVER`
All tests are run without a webserver (directly using `Rack::Mock` by default), if you want to use a webserver set `USE_SERVER` to a Rack::Server compliant server, such as `webrick`.
```
$ USE_SERVER=webrick bundle exec derailed exec perf:mem
```
Or
```
$ USE_SERVER=puma bundle exec derailed exec perf:mem
```
This boots a webserver and hits it using `curl` instead of in memory. This is useful if you think the performance issue is related to your webserver.
Note: this plugs in the given webserver directly into rack, it doesn't use any `puma.config` file etc. that you have set-up. If you want to do this, i'm open to suggestions on how (and pull requests)
### Excluding ActiveRecord
By default, derailed will load ActiveRecord if the gem is included as a dependency. It is included by default, if you just include the `rails` gem. If you are using a different ORM, you will either need to only include the `railties` gem, or set the `DERAILED_SKIP_ACTIVE_RECORD` flag.
```
$ DERAILED_SKIP_ACTIVE_RECORD=true
```
### Running in a different environment
Tests run against the production environment by default, but it's easy to
change this if your app doesn't run locally with `RAILS_ENV` set to
`production`. For example:
```
$ RAILS_ENV=development bundle exec derailed exec perf:mem
```
## perf.rake
If you want to customize derailed, you'll need to create a `perf.rake` file at the root of the directory you're trying to benchmark.
It is possible to run benchmarks directly using rake
```
$ cat << EOF > perf.rake
require 'bundler'
Bundler.setup
require 'derailed_benchmarks'
require 'derailed_benchmarks/tasks'
EOF
```
The file should look like this:
```
$ cat perf.rake
require 'bundler'
Bundler.setup
require 'derailed_benchmarks'
require 'derailed_benchmarks/tasks'
```
This is done so the benchmarks will be loaded before your application, this is important for some benchmarks and less for others. This also prevents you from accidentally loading these benchmarks when you don't need them.
Then you can execute your commands via rake.
To find out the tasks available you can use `$ rake -f perf.rake -T` which essentially says use the file `perf.rake` and list all the tasks.
```
$ rake -f perf.rake -T
```
## Rack Setup
Using Rails? You don't need to do anything special. If you're using Rack, you need to tell us how to boot your app. In your `perf.rake` file add a task:
```ruby
namespace :perf do
task :rack_load do
DERAILED_APP = # your code here
end
end
```
Set the constant `DERAILED_APP` to your Rack app. See [schneems/derailed_benchmarks#1](https://github.com/schneems/derailed_benchmarks/pull/1) for more info.
An example of setting this up could look like:
```ruby
# perf.rake
require 'bundler'
Bundler.setup
require 'derailed_benchmarks'
require 'derailed_benchmarks/tasks'
namespace :perf do
task :rack_load do
require_relative 'lib/application'
DERAILED_APP = MyApplication::Routes
end
end
```
## Authentication
If you're trying to test an endpoint that has authentication you'll need to tell your task how to bypass that authentication. Authentication is controlled by the `DerailedBenchmarks.auth` object. There is a built in support for Devise. If you're using some other authentication method, you can write your own authentication strategy.
To enable authentication in a test run with:
```
$ USE_AUTH=true bundle exec derailed exec perf:mem
```
See below how to customize authentication.
### Authentication with Devise
If you're using devise, there is a built in auth helper that will detect the presence of the devise gem and load automatically.
Create a `perf.rake` file at your root.
```
$ cat perf.rake
```
If you want you can customize the user that is logged in by setting that value in your `perf.rake` file.
```ruby
DerailedBenchmarks.auth.user = -> { User.find_or_create!(twitter: "schneems") }
```
You will need to provide a valid user, so depending on the validations you have in your `user.rb`, you may need to provide different parameters.
If you're trying to authenticate a non-user model, you'll need to write your own custom auth strategy.
### Custom Authentication Strategy
To implement your own authentication strategy You will need to create a class that [inherits from auth_helper.rb](lib/derailed_benchmarks/auth_helper.rb). You will need to implement a `setup` and a `call` method. You can see an example of [how the devise auth helper was written](lib/derailed_benchmarks/auth_helpers/devise.rb) and [how it can be done for Clearance](https://gist.github.com/zavan/f4d34dd86bf825db549a0ac28c7e10d5). You can put this code in your `perf.rake` file.
```ruby
class MyCustomAuth < DerailedBenchmarks::AuthHelper
def setup
# initialize code here
end
def call(env)
# log something in on each request
app.call(env)
end
end
```
The devise strategy works by enabling test mode inside of the Rack request and inserting a stub user. You'll need to duplicate that logic for your own authentication scheme if you're not using devise.
Once you have your class, you'll need to set `DerailedBenchmarks.auth` to a new instance of your class. In your `perf.rake` file add:
```ruby
DerailedBenchmarks.auth = MyCustomAuth.new
```
Now on every request that is made with the `USE_AUTH` environment variable set, the `MyCustomAuth#call` method will be invoked.
## License
MIT
## Acknowledgements
Most of the commands are wrappers around other libraries, go check them out. Also thanks to [@tenderlove](https://twitter.com/tenderlove) as I cribbed some of the Rails init code in `$ rake perf:setup` from one of his projects.
kthksbye [@schneems](https://twitter.com/schneems)

View file

@ -0,0 +1,29 @@
# encoding: UTF-8
# frozen_string_literal: true
require 'rubygems'
require 'bundler'
require "bundler/gem_tasks"
begin
Bundler.setup(:default, :development, :test)
rescue Bundler::BundlerError => e
$stderr.puts e.message
$stderr.puts "Run `bundle install` to install missing gems"
exit e.status_code
end
require 'rake'
require 'rake/testtask'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = false
end
task default: :test

View file

@ -0,0 +1,93 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
unless File.respond_to? :realpath
class File #:nodoc:
def self.realpath path
return realpath(File.readlink(path)) if symlink?(path)
path
end
end
end
lib = File.expand_path(File.dirname(File.realpath(__FILE__)) + '/../lib')
$: << lib
require File.join(lib, 'derailed_benchmarks.rb')
Bundler.setup
require 'thor'
class DerailedBenchmarkCLI < Thor
desc "exec", "executes given derailed benchmark"
def exec(task = nil)
setup_bundler!
require 'derailed_benchmarks'
require 'rake'
Rake::TaskManager.record_task_metadata = true
require 'derailed_benchmarks/tasks'
perf_rakefile = File.expand_path(".", "perf.rake")
load perf_rakefile if File.exist?(perf_rakefile)
if task.nil? || task == "--help"
Rake.application.tasks.map do |task, n|
next unless task.comment
puts " $ derailed exec #{task.name} # #{task.comment}"
end
else
task = "perf:#{task}" unless Rake::Task.task_defined?(task)
Rake::Task[task].invoke
end
end
desc "bundle:objects", "measures objects created by gems"
define_method(:"bundle:objects") do |env = "production"|
setup_bundler!
env = [:default] + env.split(",")
puts "Measuring objects created by gems in groups #{ env.inspect }"
require 'memory_profiler'
report = MemoryProfiler.report do
Bundler.require(*env)
end
report.pretty_print
end
map :"bundler:objects" => :"bundle:objects"
desc "bundle:mem", "measures memory used by gems at boot time"
define_method(:"bundle:mem") do |env = "production"|
env = [:default] + env.split(",")
require 'get_process_mem'
mem = GetProcessMem.new
require 'derailed_benchmarks/core_ext/kernel_require'
before = mem.mb
setup_bundler!
Bundler.require(*env)
after = mem.mb
TOP_REQUIRE.print_sorted_children
end
map :"bundler:mem" => :"bundle:mem"
private
def setup_bundler!
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
require 'bundler/setup'
begin
if ENV["DERAILED_SKIP_ACTIVE_RECORD"]
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
else
require 'rails/all'
end
rescue LoadError
end
end
end
DerailedBenchmarkCLI.start(ARGV)

View file

@ -0,0 +1,39 @@
# -*- encoding: utf-8 -*-
# frozen_string_literal: true
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'derailed_benchmarks/version'
Gem::Specification.new do |gem|
gem.name = "derailed_benchmarks"
gem.version = DerailedBenchmarks::VERSION
gem.authors = ["Richard Schneeman"]
gem.email = ["richard.schneeman+rubygems@gmail.com"]
gem.description = %q{ Go faster, off the Rails }
gem.summary = %q{ Benchmarks designed to performance test your ENTIRE site }
gem.homepage = "https://github.com/schneems/derailed_benchmarks"
gem.license = "MIT"
gem.files = `git ls-files`.split($/)
gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
gem.require_paths = ["lib"]
gem.required_ruby_version = ">= 2.1.0"
gem.add_dependency "heapy", "~> 0"
gem.add_dependency "memory_profiler", "~> 0"
gem.add_dependency "get_process_mem", "~> 0"
gem.add_dependency "benchmark-ips", "~> 2"
gem.add_dependency "rack", ">= 1"
gem.add_dependency "rake", "> 10", "< 13"
gem.add_dependency "thor", "~> 0.19"
gem.add_dependency "ruby-statistics", ">= 2.1"
gem.add_development_dependency "capybara", "~> 2"
gem.add_development_dependency "m"
gem.add_development_dependency "rails", "> 3", "<= 6"
gem.add_development_dependency "devise", "> 3", "< 6"
gem.add_development_dependency "appraisal", "2.2.0"
end

View file

@ -0,0 +1,2 @@
---
BUNDLE_RETRY: "1"

View file

@ -0,0 +1,15 @@
# frozen_string_literal: true
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 5.1.0"
group :development, :test do
gem "sqlite3", platform: [:ruby, :mswin, :mingw]
gem "activerecord-jdbcsqlite3-adapter", "~> 1.3.13", platform: :jruby
gem "test-unit", "~> 3.0"
end
gemspec path: "../"

View file

@ -0,0 +1,15 @@
# frozen_string_literal: true
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 5.2.0"
group :development, :test do
gem "sqlite3", platform: [:ruby, :mswin, :mingw]
gem "activerecord-jdbcsqlite3-adapter", "~> 1.3.13", platform: :jruby
gem "test-unit", "~> 3.0"
end
gemspec path: "../"

View file

@ -0,0 +1,15 @@
# frozen_string_literal: true
# This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "6.0.0.rc1"
group :development, :test do
gem "sqlite3", platform: [:ruby, :mswin, :mingw]
gem "activerecord-jdbcsqlite3-adapter", "~> 1.3.13", platform: :jruby
gem "test-unit", "~> 3.0"
end
gemspec path: "../"

View file

@ -0,0 +1,19 @@
# frozen_string_literal: true
# $ BUNDLE_GEMFILE="$(pwd)/gemfiles/rails_git.gemfile" bundle exec m test/integration/tasks_test.rb:30
source "https://rubygems.org"
gem "rails", github: "rails/rails", ref: "3054e1d584e7eca110c69a1f8423f2e0866abbf9"
gem 'devise', github: "plataformatec/devise"
group :development, :test do
gem "sqlite3", platform: [:ruby, :mswin, :mingw]
gem "activerecord-jdbcsqlite3-adapter", "~> 1.3.13", platform: :jruby
gem "test-unit", "~> 3.0"
end
gemspec path: "../"
ENV['USING_RAILS_GIT'] = "1"

View file

@ -0,0 +1,51 @@
# frozen_string_literal: true
require 'time'
require 'bundler'
require 'get_process_mem'
module DerailedBenchmarks
def self.gem_is_bundled?(name)
specs = ::Bundler.locked_gems.specs.each_with_object({}) {|spec, hash| hash[spec.name] = spec }
specs[name]
end
class << self
attr_accessor :auth
end
def self.rails_path_on_disk
require 'rails/version'
rails_version_file = Rails.method(:version).source_location[0]
path = Pathname.new(rails_version_file).expand_path.parent.parent
while path != Pathname.new("/")
basename = path.expand_path.basename.to_s
break if basename.start_with?("rails") && basename != "railties"
path = path.parent
end
raise "Could not find rails folder on a folder in #{rails_version_file}" if path == Pathname.new("/")
path.expand_path
end
def self.add_auth(app)
if use_auth = ENV['USE_AUTH']
puts "Auth: #{use_auth}"
auth.add_app(app)
else
app
end
end
end
require 'derailed_benchmarks/require_tree'
require 'derailed_benchmarks/auth_helper'
require 'derailed_benchmarks/stats_in_file'
require 'derailed_benchmarks/stats_from_dir'
if DerailedBenchmarks.gem_is_bundled?("devise")
DerailedBenchmarks.auth = DerailedBenchmarks::AuthHelpers::Devise.new
end

View file

@ -0,0 +1,34 @@
# frozen_string_literal: true
require 'securerandom'
module DerailedBenchmarks
# Base helper class. Can be used to authenticate different strategies
# The root app will be wrapped by an authentication action
class AuthHelper
attr_reader :app
# Put any coded needed to set up or initialize your authentication module here
def setup
raise "Must subclass"
end
# Gets called for every request. Place all auth logic here.
# Return value is expected to be an valid Rack response array.
# If you do not manually `app.call(env)` here, the client app
# will never be called.
def call(env)
raise "Must subclass"
end
# Returns self and sets the target app
def add_app(app)
raise "App is required argument" unless app
@app = app
setup
self
end
end
end
require 'derailed_benchmarks/auth_helpers/devise'

View file

@ -0,0 +1,41 @@
# frozen_string_literal: true
module DerailedBenchmarks
class AuthHelpers
# Devise helper for authenticating requests
# Setup adds necessarry test methods, user provides a sample user.
# The authenticate method is called on every request when authentication is enabled
class Devise < AuthHelper
attr_writer :user
# Include devise test helpers and turn on test mode
# We need to do this on the class level
def setup
# self.class.instance_eval do
require 'devise'
require 'warden'
extend ::Warden::Test::Helpers
extend ::Devise::TestHelpers
Warden.test_mode!
# end
end
def user
if @user
@user = @user.call if @user.is_a?(Proc)
@user
else
password = SecureRandom.hex
@user = User.first_or_create!(email: "#{SecureRandom.hex}@example.com", password: password, password_confirmation: password)
end
end
# Logs the user in, then call the parent app
def call(env)
login_as(user)
app.call(env)
end
end
end
end

View file

@ -0,0 +1,86 @@
# frozen_string_literal: true
require 'get_process_mem'
require 'derailed_benchmarks/require_tree'
ENV['CUT_OFF'] ||= "0.3"
# This file contains classes and monkey patches to measure the amount of memory
# useage requiring an individual file adds.
# Monkey patch kernel to ensure that all `require` calls call the same
# method
module Kernel
private
alias :original_require :require
REQUIRE_STACK = []
def require(file)
Kernel.require(file)
end
def require_relative(file)
if Pathname.new(file).absolute?
require file
else
require File.expand_path("../#{file}", caller_locations(1, 1)[0].absolute_path)
end
end
class << self
alias :original_require :require
alias :original_require_relative :require_relative
end
# The core extension we use to measure require time of all requires
# When a file is required we create a tree node with its file name.
# We then push it onto a stack, this is because requiring a file can
# require other files before it is finished.
#
# When a child file is required, a tree node is created and the child file
# is pushed onto the parents tree. We then repeat the process as child
# files may require additional files.
#
# When a require returns we remove it from the require stack so we don't
# accidentally push additional children nodes to it. We then store the
# memory cost of the require in the tree node.
def self.measure_memory_impact(file, &block)
mem = GetProcessMem.new
node = DerailedBenchmarks::RequireTree.new(file)
parent = REQUIRE_STACK.last
parent << node
REQUIRE_STACK.push(node)
begin
before = mem.mb
block.call file
ensure
REQUIRE_STACK.pop # node
after = mem.mb
end
node.cost = after - before
end
end
# Top level node that will store all require information for the entire app
TOP_REQUIRE = DerailedBenchmarks::RequireTree.new("TOP")
REQUIRE_STACK.push(TOP_REQUIRE)
Kernel.define_singleton_method(:require) do |file|
measure_memory_impact(file) do |file|
# "source_annotation_extractor" is deprecated in Rails 6
# # if we don't skip the library it leads to a crash
# next if file == "rails/source_annotation_extractor" && Rails.version >= '6.0'
original_require(file)
end
end
# Don't forget to assign a cost to the top level
cost_before_requiring_anything = GetProcessMem.new.mb
TOP_REQUIRE.cost = cost_before_requiring_anything
def TOP_REQUIRE.print_sorted_children(*args)
self.cost = GetProcessMem.new.mb - self.cost
super
end

View file

@ -0,0 +1,138 @@
# frozen_string_literal: true
namespace :perf do
task :rails_load do
ENV["RAILS_ENV"] ||= "production"
ENV['RACK_ENV'] = ENV["RAILS_ENV"]
ENV["DISABLE_SPRING"] = "true"
ENV["SECRET_KEY_BASE"] ||= "foofoofoo"
ENV['LOG_LEVEL'] ||= "FATAL"
require 'rails'
puts "Booting: #{Rails.env}"
%W{ . lib test config }.each do |file|
$LOAD_PATH << File.expand_path(file)
end
require 'application'
Rails.env = ENV["RAILS_ENV"]
DERAILED_APP = Rails.application
if DERAILED_APP.respond_to?(:initialized?)
DERAILED_APP.initialize! unless DERAILED_APP.initialized?
else
DERAILED_APP.initialize! unless DERAILED_APP.instance_variable_get(:@initialized)
end
if ENV["DERAILED_SKIP_ACTIVE_RECORD"] && defined? ActiveRecord
if defined? ActiveRecord::Tasks::DatabaseTasks
ActiveRecord::Tasks::DatabaseTasks.create_current
else # Rails 3.2
raise "No valid database for #{ENV['RAILS_ENV']}, please create one" unless ActiveRecord::Base.connection.active?.inspect
end
ActiveRecord::Migrator.migrations_paths = DERAILED_APP.paths['db/migrate'].to_a
ActiveRecord::Migration.verbose = true
ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, nil)
end
DERAILED_APP.config.consider_all_requests_local = true
end
task :rack_load do
puts "You're not using Rails"
puts "You need to tell derailed how to boot your app"
puts "In your perf.rake add:"
puts
puts "namespace :perf do"
puts " task :rack_load do"
puts " # DERAILED_APP = your code here"
puts " end"
puts "end"
end
task :setup do
if DerailedBenchmarks.gem_is_bundled?("railties")
Rake::Task["perf:rails_load"].invoke
else
Rake::Task["perf:rack_load"].invoke
end
WARM_COUNT = (ENV['WARM_COUNT'] || 0).to_i
TEST_COUNT = (ENV['TEST_COUNT'] || ENV['CNT'] || 1_000).to_i
PATH_TO_HIT = ENV["PATH_TO_HIT"] || ENV['ENDPOINT'] || "/"
puts "Endpoint: #{ PATH_TO_HIT.inspect }"
HTTP_HEADER_PREFIX = "HTTP_".freeze
RACK_HTTP_HEADERS = ENV.select { |key| key.start_with?(HTTP_HEADER_PREFIX) }
HTTP_HEADERS = RACK_HTTP_HEADERS.keys.inject({}) do |hash, rack_header_name|
# e.g. "HTTP_ACCEPT_CHARSET" -> "Accept-Charset"
header_name = rack_header_name[HTTP_HEADER_PREFIX.size..-1].split("_").map(&:downcase).map(&:capitalize).join("-")
hash[header_name] = RACK_HTTP_HEADERS[rack_header_name]
hash
end
puts "HTTP headers: #{HTTP_HEADERS}" unless HTTP_HEADERS.empty?
CURL_HTTP_HEADER_ARGS = HTTP_HEADERS.map { |http_header_name, value| "-H \"#{http_header_name}: #{value}\"" }.join(" ")
require 'rack/test'
require 'rack/file'
DERAILED_APP = DerailedBenchmarks.add_auth(Object.class_eval { remove_const(:DERAILED_APP) })
if server = ENV["USE_SERVER"]
@port = (3000..3900).to_a.sample
puts "Port: #{ @port.inspect }"
puts "Server: #{ server.inspect }"
thread = Thread.new do
Rack::Server.start(app: DERAILED_APP, :Port => @port, environment: "none", server: server)
end
sleep 1
def call_app(path = File.join("/", PATH_TO_HIT))
cmd = "curl #{CURL_HTTP_HEADER_ARGS} 'http://localhost:#{@port}#{path}' -s --fail 2>&1"
response = `#{cmd}`
unless $?.success?
STDERR.puts "Couldn't call app."
STDERR.puts "Bad request to #{cmd.inspect} \n\n***RESPONSE***:\n\n#{ response.inspect }"
FileUtils.mkdir_p("tmp")
File.open("tmp/fail.html", "w+") {|f| f.write response.body }
`open #{File.expand_path("tmp/fail.html")}` if ENV["DERAILED_DEBUG"]
exit(1)
end
end
else
@app = Rack::MockRequest.new(DERAILED_APP)
def call_app
response = @app.get(PATH_TO_HIT, RACK_HTTP_HEADERS)
if response.status != 200
STDERR.puts "Couldn't call app. Bad request to #{PATH_TO_HIT}! Resulted in #{response.status} status."
STDERR.puts "\n\n***RESPONSE BODY***\n\n"
STDERR.puts response.body
FileUtils.mkdir_p("tmp")
File.open("tmp/fail.html", "w+") {|f| f.write response.body }
`open #{File.expand_path("tmp/fail.html")}` if ENV["DERAILED_DEBUG"]
exit(1)
end
response
end
end
if WARM_COUNT > 0
puts "Warming up app: #{WARM_COUNT} times"
WARM_COUNT.times { call_app }
end
end
end

View file

@ -0,0 +1,65 @@
# frozen_string_literal: true
# Tree structure used to store and sort require memory costs
# RequireTree.new('get_process_mem')
module DerailedBenchmarks
class RequireTree
REQUIRED_BY = {}
attr_reader :name
attr_writer :cost
attr_accessor :parent
def initialize(name)
@name = name
@children = {}
end
def <<(tree)
@children[tree.name.to_s] = tree
tree.parent = self
(REQUIRED_BY[tree.name.to_s] ||= []) << self.name
end
def [](name)
@children[name.to_s]
end
# Returns array of child nodes
def children
@children.values
end
def cost
@cost || 0
end
# Returns sorted array of child nodes from Largest to Smallest
def sorted_children
children.sort { |c1, c2| c2.cost <=> c1.cost }
end
def to_string
str = +"#{name}: #{cost.round(4)} MiB"
if parent && REQUIRED_BY[self.name.to_s]
names = REQUIRED_BY[self.name.to_s].uniq - [parent.name.to_s]
if names.any?
str << " (Also required by: #{ names.first(2).join(", ") }"
str << ", and #{names.count - 2} others" if names.count > 3
str << ")"
end
end
str
end
# Recursively prints all child nodes
def print_sorted_children(level = 0, out = STDOUT)
return if cost < ENV['CUT_OFF'].to_f
out.puts " " * level + self.to_string
level += 1
sorted_children.each do |child|
child.print_sorted_children(level, out)
end
end
end
end

View file

@ -0,0 +1,99 @@
# frozen_string_literal: true
require 'bigdecimal'
require 'statistics'
module DerailedBenchmarks
# A class used to read several benchmark files
# it will parse each file, then sort by average
# time of benchmarks. It can be used to find
# the fastest and slowest examples and give information
# about them such as what the percent difference is
# and if the results are statistically significant
#
# Example:
#
# branch_info = {}
# branch_info["loser"] = { desc: "Old commit", time: Time.now, file: dir.join("loser.bench.txt"), name: "loser" }
# branch_info["winner"] = { desc: "I am the new commit", time: Time.now + 1, file: dir.join("winner.bench.txt"), name: "winner" }
# stats = DerailedBenchmarks::StatsFromDir.new(branch_info)
#
# stats.newest.average # => 10.5
# stats.oldest.average # => 11.0
# stats.significant? # => true
# stats.x_faster # => "1.0476"
class StatsFromDir
FORMAT = "%0.4f"
attr_reader :stats, :oldest, :newest
def initialize(hash)
@files = []
hash.each do |branch, info_hash|
file = info_hash.fetch(:file)
desc = info_hash.fetch(:desc)
time = info_hash.fetch(:time)
@files << StatsForFile.new(file: file, desc: desc, time: time, name: branch)
end
@files.sort_by! { |f| f.time }
@oldest = @files.first
@newest = @files.last
end
def call
@files.each(&:call)
@stats = students_t_test
self
end
def students_t_test(series_1=oldest.values, series_2=newest.values)
StatisticalTest::TTest.perform(
alpha = 0.05,
:two_tail,
series_1,
series_2
)
end
def significant?
@stats[:alternative]
end
def p_value
@stats[:p_value].to_f
end
def x_faster
FORMAT % (oldest.average/newest.average).to_f
end
def percent_faster
FORMAT % (((oldest.average - newest.average) / oldest.average).to_f * 100)
end
def change_direction
newest.average < oldest.average ? "FASTER" : "SLOWER"
end
def banner(io = Kernel)
io.puts
if significant?
io.puts "❤️ ❤️ ❤️ (Statistically Significant) ❤️ ❤️ ❤️"
else
io.puts "👎👎👎(NOT Statistically Significant) 👎👎👎"
end
io.puts
io.puts "[#{newest.name}] #{newest.desc.inspect} - (#{newest.average} seconds)"
io.puts " #{change_direction} by:"
io.puts " #{x_faster}x [older/newer]"
io.puts " #{percent_faster}\% [(older - newer) / older * 100]"
io.puts "[#{oldest.name}] #{oldest.desc.inspect} - (#{oldest.average} seconds)"
io.puts
io.puts "Iterations per sample: #{ENV["TEST_COUNT"]}"
io.puts "Samples: #{newest.values.length}"
io.puts "P-value: #{p_value}"
io.puts "Is significant? (P-value < 0.05): #{significant?}"
io.puts
end
end
end

View file

@ -0,0 +1,53 @@
# frozen_string_literal: true
module DerailedBenchmarks
# A class for reading in benchmark results
# and converting them to numbers for comparison
#
# Example:
#
# puts `cat muhfile.bench.txt`
#
# 9.590142 0.831269 10.457801 ( 10.0)
# 9.836019 0.837319 10.728024 ( 11.0)
#
# x = StatsForFile.new(name: "muhcommit", file: "muhfile.bench.txt", desc: "I made it faster", time: Time.now)
# x.values #=> [11.437769, 11.792425]
# x.average # => 10.5
# x.name # => "muhfile"
class StatsForFile
attr_reader :name, :values, :desc, :time
def initialize(file:, name:, desc: "", time: )
@file = Pathname.new(file)
FileUtils.touch(@file)
@name = name
@desc = desc
@time = time
end
def call
load_file!
@average = values.inject(:+) / values.length
end
def average
@average.to_f
end
private def load_file!
@values = []
@file.each_line do |line|
line.match(/\( +(\d+\.\d+)\)/)
begin
values << BigDecimal($1)
rescue => e
raise e, "Problem with file #{@file.inspect}:\n#{@file.read}\n#{e.message}"
end
end
values.freeze
end
end
end

View file

@ -0,0 +1,256 @@
require_relative 'load_tasks'
namespace :perf do
desc "runs the same test against two different branches for statistical comparison"
task :library do
DERAILED_SCRIPT_COUNT = (ENV["DERAILED_SCRIPT_COUNT"] ||= "200").to_i
ENV["TEST_COUNT"] ||= "200"
raise "test count must be at least 2, is set to #{DERAILED_SCRIPT_COUNT}" if DERAILED_SCRIPT_COUNT < 2
script = ENV["DERAILED_SCRIPT"] || "bundle exec derailed exec perf:test"
if ENV["DERAILED_PATH_TO_LIBRARY"]
library_dir = ENV["DERAILED_PATH_TO_LIBRARY"]
else
library_dir = DerailedBenchmarks.rails_path_on_disk
end
raise "Must be a path with a .git directory '#{library_dir}'" unless File.exist?(File.join(library_dir, ".git"))
# Use either the explicit SHAs when present or grab last two SHAs from commit history
# if only one SHA is given, then use it and the last SHA from commit history
branch_names = []
branch_names = ENV.fetch("SHAS_TO_TEST").split(",") if ENV["SHAS_TO_TEST"]
if branch_names.length < 2
Dir.chdir(library_dir) do
branches = run!('git log --format="%H" -n 2').chomp.split($INPUT_RECORD_SEPARATOR)
if branch_names.empty?
branch_names = branches
else
branch_names << branches.shift
end
end
end
current_library_branch = ""
Dir.chdir(library_dir) { current_library_branch = run!('git describe --contains --all HEAD').chomp }
out_dir = Pathname.new("tmp/library_branches/#{Time.now.strftime('%Y-%m-%d-%H-%M-%s-%N')}")
out_dir.mkpath
branches_to_test = branch_names.each_with_object({}) {|elem, hash| hash[elem] = out_dir + "#{elem.gsub('/', ':')}.bench.txt" }
branch_info = {}
branches_to_test.each do |branch, file|
Dir.chdir(library_dir) do
run!("git checkout '#{branch}'")
description = run!("git log --oneline --format=%B -n 1 HEAD | head -n 1").strip
time_stamp = run!("git log -n 1 --pretty=format:%ci").strip # https://stackoverflow.com/a/25921837/147390
name = run!("git rev-parse --short HEAD").strip
branch_info[name] = { desc: description, time: DateTime.parse(time_stamp), file: file }
end
run!("#{script}")
end
stats = DerailedBenchmarks::StatsFromDir.new(branch_info)
ENV["DERAILED_STOP_VALID_COUNT"] ||= "10"
stop_valid_count = Integer(ENV["DERAILED_STOP_VALID_COUNT"])
times_significant = 0
DERAILED_SCRIPT_COUNT.times do |i|
puts "Sample: #{i.next}/#{DERAILED_SCRIPT_COUNT} iterations per sample: #{ENV['TEST_COUNT']}"
branches_to_test.each do |branch, file|
Dir.chdir(library_dir) { run!("git checkout '#{branch}'") }
run!(" #{script} 2>&1 | tail -n 1 >> '#{file}'")
end
times_significant += 1 if i >= 2 && stats.call.significant?
break if stop_valid_count != 0 && times_significant == stop_valid_count
end
ensure
if library_dir && current_library_branch
puts "Resetting git dir of #{library_dir.inspect} to #{current_library_branch.inspect}"
Dir.chdir(library_dir) do
run!("git checkout '#{current_library_branch}'")
end
end
stats.call.banner if stats
end
desc "hits the url TEST_COUNT times"
task :test => [:setup] do
require 'benchmark'
Benchmark.bm { |x|
x.report("#{TEST_COUNT} derailed requests") {
TEST_COUNT.times {
call_app
}
}
}
end
desc "stackprof"
task :stackprof => [:setup] do
# [:wall, :cpu, :object]
begin
require 'stackprof'
rescue LoadError
raise "Add stackprof to your gemfile to continue `gem 'stackprof', group: :development`"
end
TEST_COUNT = (ENV["TEST_COUNT"] ||= "100").to_i
file = "tmp/#{Time.now.iso8601}-stackprof-cpu-myapp.dump"
StackProf.run(mode: :cpu, out: file) do
Rake::Task["perf:test"].invoke
end
cmd = "stackprof #{file}"
puts "Running `#{cmd}`. Execute `stackprof --help` for more info"
puts `#{cmd}`
end
task :kernel_require_patch do
require 'derailed_benchmarks/core_ext/kernel_require.rb'
end
desc "show memory usage caused by invoking require per gem"
task :mem => [:kernel_require_patch, :setup] do
puts "## Impact of `require <file>` on RAM"
puts
puts "Showing all `require <file>` calls that consume #{ENV['CUT_OFF']} MiB or more of RSS"
puts "Configure with `CUT_OFF=0` for all entries or `CUT_OFF=5` for few entries"
puts "Note: Files only count against RAM on their first load."
puts " If multiple libraries require the same file, then"
puts " the 'cost' only shows up under the first library"
puts
call_app
TOP_REQUIRE.print_sorted_children
end
desc "outputs memory usage over time"
task :mem_over_time => [:setup] do
require 'get_process_mem'
puts "PID: #{Process.pid}"
ram = GetProcessMem.new
@keep_going = true
begin
unless ENV["SKIP_FILE_WRITE"]
ruby = `ruby -v`.chomp
FileUtils.mkdir_p("tmp")
file = File.open("tmp/#{Time.now.iso8601}-#{ruby}-memory-#{TEST_COUNT}-times.txt", 'w')
file.sync = true
end
ram_thread = Thread.new do
while @keep_going
mb = ram.mb
STDOUT.puts mb
file.puts mb unless ENV["SKIP_FILE_WRITE"]
sleep 5
end
end
TEST_COUNT.times {
call_app
}
ensure
@keep_going = false
ram_thread.join
file.close unless ENV["SKIP_FILE_WRITE"]
end
end
task :ram_over_time do
raise "Use mem_over_time"
end
desc "iterations per second"
task :ips => [:setup] do
require 'benchmark/ips'
Benchmark.ips do |x|
x.warmup = Float(ENV["IPS_WARMUP"] || 2)
x.time = Float(ENV["IPS_TIME"] || 5)
x.suite = ENV["IPS_SUITE"] if ENV["IPS_SUITE"]
x.iterations = Integer(ENV["IPS_ITERATIONS"] || 1)
x.report("ips") { call_app }
end
end
desc "outputs GC::Profiler.report data while app is called TEST_COUNT times"
task :gc => [:setup] do
GC::Profiler.enable
TEST_COUNT.times { call_app }
GC::Profiler.report
GC::Profiler.disable
end
desc "outputs allocated object diff after app is called TEST_COUNT times"
task :allocated_objects => [:setup] do
call_app
GC.start
GC.disable
start = ObjectSpace.count_objects
TEST_COUNT.times { call_app }
finish = ObjectSpace.count_objects
GC.enable
finish.each do |k,v|
puts k => (v - start[k]) / TEST_COUNT.to_f
end
end
desc "profiles ruby allocation"
task :objects => [:setup] do
require 'memory_profiler'
call_app
GC.start
num = Integer(ENV["TEST_COUNT"] || 1)
opts = {}
opts[:ignore_files] = /#{ENV['IGNORE_FILES_REGEXP']}/ if ENV['IGNORE_FILES_REGEXP']
opts[:allow_files] = "#{ENV['ALLOW_FILES']}" if ENV['ALLOW_FILES']
puts "Running #{num} times"
report = MemoryProfiler.report(opts) do
num.times { call_app }
end
report.pretty_print
end
desc "heap analyzer"
task :heap => [:setup] do
require 'objspace'
file_name = "tmp/#{Time.now.iso8601}-heap.dump"
FileUtils.mkdir_p("tmp")
ObjectSpace.trace_object_allocations_start
puts "Running #{ TEST_COUNT } times"
TEST_COUNT.times {
call_app
}
GC.start
puts "Heap file generated: #{ file_name.inspect }"
ObjectSpace.dump_all(output: File.open(file_name, 'w'))
require 'heapy'
Heapy::Analyzer.new(file_name).analyze
puts ""
puts "Run `$ heapy --help` for more options"
puts ""
puts "Also try uploading #{file_name.inspect} to http://tenderlove.github.io/heap-analyzer/"
end
def run!(cmd)
out = `#{cmd}`
raise "Error while running #{cmd.inspect}: #{out}" unless $?.success?
out
end
end

View file

@ -0,0 +1,5 @@
# frozen_string_literal: true
module DerailedBenchmarks
VERSION = "1.4.0"
end

View file

@ -0,0 +1,33 @@
# frozen_string_literal: true
require 'test_helper'
class KernelRequireTest < ActiveSupport::TestCase
setup do
require 'derailed_benchmarks/core_ext/kernel_require'
GC.disable
end
teardown do
GC.enable
end
def assert_node_in_parent(file_name, parent)
file = fixtures_dir(File.join("require", file_name))
node = parent[file]
assert node, "Expected:\n#{parent.children}\nto include:\n#{file.inspect}"
assert node.cost < parent.cost, "Expected:\n#{node.inspect}\nto cost less than:\n#{parent.inspect}" unless parent == TOP_REQUIRE
node
end
test "core extension profiles useage" do
require fixtures_dir("require/parent_one.rb")
parent = assert_node_in_parent("parent_one.rb", TOP_REQUIRE)
assert_node_in_parent("child_one.rb", parent)
child_two = assert_node_in_parent("child_two.rb", parent)
assert_node_in_parent("relative_child", parent)
assert_node_in_parent("relative_child_two", parent)
assert_node_in_parent("raise_child.rb", child_two)
end
end

View file

@ -0,0 +1,95 @@
# frozen_string_literal: true
require 'test_helper'
class RequireTree < ActiveSupport::TestCase
def tree(name)
DerailedBenchmarks::RequireTree.new(name)
end
def teardown
DerailedBenchmarks::RequireTree.const_set("REQUIRED_BY", {})
end
test "default_cost" do
parent = tree("parent")
assert_equal 0, parent.cost
value = rand(0..100)
parent.cost = value
assert_equal value, parent.cost
end
test "stores child" do
parent = tree("parent")
child = tree("child")
parent << child
# [](name)
assert_equal child, parent["child"]
# children
assert_equal [child], parent.children
assert_equal [child], parent.sorted_children
end
test "sorts children" do
parent = tree("parent")
parent.cost = rand(5..10)
small = tree("small")
small.cost = rand(10..100)
large = tree("large")
large.cost = small.cost + 1
parent << small
parent << large
expected = [large, small]
assert_equal expected, parent.sorted_children
expected = <<-OUT
parent: #{ parent.cost.round(4) } MiB
large: #{ large.cost.round(4) } MiB
small: #{ small.cost.round(4) } MiB
OUT
capture = StringIO.new
parent.print_sorted_children(0, capture)
assert_equal expected, capture.string
end
test "attributes duplicate children" do
parent = tree("parent")
parent.cost = rand(5..10)
small = tree("small")
small.cost = rand(10..100)
large = tree("large")
large.cost = small.cost + 1
dup = tree("large")
dup.cost = 0.4
small << dup
parent << small
parent << large
expected = [large, small]
assert_equal expected, parent.sorted_children
expected = [dup]
assert_equal expected, small.sorted_children
expected = <<-OUT
parent: #{ parent.cost.round(4) } MiB
large: #{ large.cost.round(4) } MiB (Also required by: small)
small: #{ small.cost.round(4) } MiB
large: #{ dup.cost.round(4) } MiB (Also required by: parent)
OUT
capture = StringIO.new
parent.print_sorted_children(0, capture)
assert_equal expected, capture.string
end
end

View file

@ -0,0 +1,101 @@
# frozen_string_literal: true
require 'test_helper'
class StatsFromDirTest < ActiveSupport::TestCase
test "that it works" do
dir = fixtures_dir("stats/significant")
branch_info = {}
branch_info["loser"] = { desc: "Old commit", time: Time.now, file: dir.join("loser.bench.txt"), name: "loser" }
branch_info["winner"] = { desc: "I am the new commit", time: Time.now + 1, file: dir.join("winner.bench.txt"), name: "winner" }
stats = DerailedBenchmarks::StatsFromDir.new(branch_info).call
newest = stats.newest
oldest = stats.oldest
assert newest.average < oldest.average
assert_equal "winner", newest.name
assert_equal "loser", oldest.name
assert 3.6e-05 < stats.p_value
assert 3.8e-05 > stats.p_value
assert_equal true, stats.significant?
assert_equal "1.0062", stats.x_faster
assert_equal "0.6131", stats.percent_faster
end
test "banner faster" do
dir = fixtures_dir("stats/significant")
branch_info = {}
branch_info["loser"] = { desc: "Old commit", time: Time.now, file: dir.join("loser.bench.txt"), name: "loser" }
branch_info["winner"] = { desc: "I am the new commit", time: Time.now + 1, file: dir.join("winner.bench.txt"), name: "winner" }
stats = DerailedBenchmarks::StatsFromDir.new(branch_info).call
newest = stats.newest
oldest = stats.oldest
# Test fixture for banner
def stats.p_value
"0.000037"
end
def newest.average
10.5
end
def oldest.average
11.0
end
expected = <<-EOM
[winner] "I am the new commit" - (10.5 seconds)
FASTER by:
1.0476x [older/newer]
4.5455% [(older - newer) / older * 100]
[loser] "Old commit" - (11.0 seconds)
EOM
actual = StringIO.new
stats.banner(actual)
assert_match expected, actual.string
end
test "banner slower" do
dir = fixtures_dir("stats/significant")
branch_info = {}
branch_info["loser"] = { desc: "I am the new commit", time: Time.now, file: dir.join("loser.bench.txt"), name: "loser" }
branch_info["winner"] = { desc: "Old commit", time: Time.now - 10, file: dir.join("winner.bench.txt"), name: "winner" }
stats = DerailedBenchmarks::StatsFromDir.new(branch_info).call
newest = stats.newest
oldest = stats.oldest
def oldest.average
10.5
end
def newest.average
11.0
end
expected = <<-EOM
[loser] "I am the new commit" - (11.0 seconds)
SLOWER by:
0.9545x [older/newer]
-4.7619% [(older - newer) / older * 100]
[winner] "Old commit" - (10.5 seconds)
EOM
actual = StringIO.new
stats.banner(actual)
assert_match expected, actual.string
end
test "stats from samples with slightly different sizes" do
stats = DerailedBenchmarks::StatsFromDir.new({})
out = stats.students_t_test([100,101,102], [1,3])
assert out[:alternative]
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
require 'test_helper'
class DerailedBenchmarksTest < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, DerailedBenchmarks
end
test "gem_is_bundled?" do
assert DerailedBenchmarks.gem_is_bundled?("rack")
refute DerailedBenchmarks.gem_is_bundled?("wicked")
end
end

View file

@ -0,0 +1,4 @@
class ChildOne
@retained = +""
50_000.times.map { @retained << "A" }
end

View file

@ -0,0 +1,9 @@
class ChildTwo
@retained = +""
200_000.times.map { @retained << "A" }
end
begin
require File.expand_path('../raise_child.rb', __FILE__)
rescue
end

View file

@ -0,0 +1,8 @@
class ParentOne
@retained = +""
1_000_000.times.map { @retained << "A" }
end
require File.expand_path('../child_one.rb', __FILE__)
require File.expand_path('../child_two.rb', __FILE__)
require_relative 'relative_child'
require_relative File.expand_path('relative_child_two', __dir__)

View file

@ -0,0 +1,6 @@
# frozen_string_literal: true
class RaiseChild
end
raise "Ohno"

View file

@ -0,0 +1,4 @@
# frozen_string_literal: true
class RelativeChild
end

View file

@ -0,0 +1,4 @@
# frozen_string_literal: true
class RelativeChildTwo
end

View file

@ -0,0 +1,100 @@
9.590142 0.831269 10.457801 ( 11.437769)
9.836019 0.837319 10.728024 ( 11.792425)
9.889497 0.837097 10.762795 ( 11.747066)
9.532349 0.835770 10.407767 ( 11.343758)
9.498824 0.821246 10.366225 ( 11.282013)
9.531201 0.834812 10.412715 ( 11.330127)
9.583804 0.830178 10.449280 ( 11.384867)
9.681340 0.834776 10.553697 ( 11.496842)
9.629079 0.820234 10.487276 ( 11.406677)
9.616845 0.818370 10.481193 ( 11.395825)
9.738706 0.825397 10.600923 ( 11.541978)
9.613132 0.827242 10.477559 ( 11.406065)
9.486763 0.818159 10.342470 ( 11.305299)
9.590618 0.833308 10.468615 ( 11.428548)
9.725126 0.842955 10.604727 ( 11.580922)
9.598757 0.846951 10.491222 ( 11.462324)
9.484803 0.836242 10.366269 ( 11.328111)
9.591107 0.818305 10.455931 ( 11.381660)
9.745620 0.841107 10.623715 ( 11.572584)
9.670502 0.826673 10.535566 ( 11.464770)
9.573957 0.825235 10.439166 ( 11.358507)
9.468308 0.817744 10.330541 ( 11.240717)
9.799312 0.833922 10.670213 ( 11.645225)
9.575413 0.828039 10.444712 ( 11.366111)
9.632808 0.828399 10.506581 ( 11.439761)
9.599766 0.829294 10.467003 ( 11.427869)
9.521930 0.828257 10.388242 ( 11.347915)
9.842608 0.815513 10.694427 ( 11.667158)
9.590377 0.837459 10.467418 ( 11.433524)
9.729984 0.819101 10.587020 ( 11.539660)
9.540025 0.819396 10.396442 ( 11.314444)
9.615953 0.827258 10.479946 ( 11.414527)
9.572009 0.824862 10.438432 ( 11.362800)
9.612657 0.818645 10.476568 ( 11.385235)
9.755889 0.823267 10.615302 ( 11.545301)
9.493372 0.813202 10.345646 ( 11.254617)
9.529610 0.816457 10.391484 ( 11.305237)
9.575646 0.828898 10.449636 ( 11.374993)
9.533278 0.828915 10.405592 ( 11.347798)
9.692731 0.845925 10.577313 ( 11.545701)
9.662406 0.835481 10.543032 ( 11.511367)
9.588803 0.834782 10.468166 ( 11.427231)
9.696038 0.832612 10.573877 ( 11.545533)
9.612567 0.833363 10.491381 ( 11.410244)
9.471584 0.836005 10.352883 ( 11.303213)
9.682906 0.829932 10.558423 ( 11.466843)
9.676123 0.825750 10.548111 ( 11.468789)
9.509686 0.826678 10.380435 ( 11.290658)
9.552683 0.826631 10.421387 ( 11.337799)
9.579964 0.829423 10.447095 ( 11.358198)
9.506519 0.812635 10.357147 ( 11.313867)
9.654363 0.839408 10.531093 ( 11.515562)
9.576167 0.833579 10.447897 ( 11.421267)
9.498507 0.826285 10.370417 ( 11.336780)
9.758637 0.842156 10.645638 ( 11.595915)
9.635031 0.836329 10.516094 ( 11.475492)
9.934052 0.825471 10.794286 ( 11.812346)
9.652537 0.821982 10.520060 ( 11.434903)
9.526788 0.820300 10.384780 ( 11.306397)
9.473180 0.812507 10.329689 ( 11.233813)
9.862016 0.841529 10.757393 ( 11.734586)
9.534627 0.821267 10.392666 ( 11.313970)
9.640884 0.837997 10.515254 ( 11.489616)
9.535812 0.826216 10.407273 ( 11.318032)
9.588703 0.851935 10.476997 ( 11.462256)
9.574569 0.834756 10.454909 ( 11.404434)
9.650073 0.839516 10.535755 ( 11.488113)
9.551275 0.822510 10.415396 ( 11.378195)
9.627255 0.829954 10.500136 ( 11.458503)
9.560385 0.814457 10.419578 ( 11.333235)
9.572809 0.819290 10.438854 ( 11.349594)
9.660163 0.824722 10.530198 ( 11.443437)
9.661319 0.837408 10.550881 ( 11.512634)
9.637423 0.837322 10.520727 ( 11.432594)
9.664915 0.825478 10.526599 ( 11.464716)
9.644935 0.814938 10.505644 ( 11.424535)
9.799771 0.835598 10.671993 ( 11.613622)
9.791496 0.840368 10.676233 ( 11.643770)
9.760101 0.850254 10.648067 ( 11.619884)
9.784358 0.829651 10.658058 ( 11.632889)
9.727932 0.844568 10.616464 ( 11.578881)
9.776381 0.847439 10.663001 ( 11.648257)
9.839221 0.835333 10.714699 ( 11.670378)
9.697873 0.836432 10.570815 ( 11.541265)
9.867105 0.836122 10.741859 ( 11.681261)
9.675377 0.826509 10.539536 ( 11.465271)
9.703541 0.830895 10.578611 ( 11.502074)
9.717583 0.832110 10.586737 ( 11.531415)
9.784151 0.842351 10.662311 ( 11.647167)
9.741646 0.832834 10.612608 ( 11.580701)
9.687384 0.798745 10.525026 ( 11.493736)
9.698579 0.851183 10.586010 ( 11.588731)
9.712651 0.823867 10.573837 ( 11.540969)
9.657543 0.829349 10.524768 ( 11.443846)
9.675987 0.807980 10.521943 ( 11.451106)
9.744757 0.817850 10.600094 ( 11.535379)
9.683474 0.836913 10.557015 ( 11.525771)
9.922540 0.843157 10.805096 ( 11.808377)
9.696813 0.821768 10.554695 ( 11.464342)
9.760965 0.836511 10.636968 ( 11.594082)

View file

@ -0,0 +1,100 @@
9.558387 0.795543 10.392696 ( 11.309311)
9.524045 0.803011 10.364301 ( 11.318477)
9.534609 0.804759 10.383564 ( 11.340585)
9.535700 0.800444 10.373048 ( 11.289682)
9.532372 0.794646 10.371722 ( 11.287656)
9.556350 0.822103 10.425949 ( 11.413659)
9.586525 0.824110 10.456246 ( 11.429651)
9.551907 0.830509 10.428443 ( 11.411978)
9.518711 0.834491 10.398652 ( 11.376422)
9.569772 0.827570 10.442956 ( 11.413585)
9.618950 0.829319 10.485139 ( 11.440848)
9.556727 0.807981 10.401758 ( 11.328267)
9.480701 0.804683 10.322360 ( 11.245781)
9.563369 0.801410 10.409686 ( 11.334188)
9.493082 0.805298 10.335983 ( 11.248441)
9.681861 0.803602 10.524930 ( 11.456107)
9.614529 0.781155 10.444055 ( 11.364476)
9.597825 0.806409 10.442217 ( 11.365743)
9.538346 0.813941 10.388972 ( 11.346084)
9.538091 0.808328 10.391165 ( 11.346197)
9.502600 0.812638 10.360783 ( 11.306602)
9.571149 0.826238 10.449697 ( 11.411387)
9.531260 0.821429 10.390722 ( 11.532200)
9.611447 0.783734 10.431579 ( 11.351863)
9.533522 0.806067 10.384192 ( 11.296454)
9.586843 0.820340 10.444013 ( 11.383357)
9.615441 0.804255 10.456321 ( 11.385184)
9.462530 0.803438 10.302507 ( 11.223665)
9.676985 0.789649 10.511461 ( 11.427901)
9.574692 0.816601 10.427670 ( 11.374204)
9.596892 0.803796 10.437442 ( 11.362358)
9.562942 0.815001 10.415687 ( 11.383593)
9.622502 0.804110 10.470848 ( 11.488275)
9.766782 0.828892 10.632272 ( 11.635267)
9.612909 0.804247 10.455650 ( 11.421374)
9.537415 0.805782 10.390754 ( 11.294518)
9.763286 0.805568 10.614687 ( 11.533764)
9.507627 0.806313 10.350967 ( 11.299277)
9.469710 0.803944 10.312100 ( 11.232190)
9.535007 0.795200 10.371960 ( 11.292289)
9.530755 0.797043 10.372644 ( 11.289316)
9.588961 0.806621 10.431681 ( 11.368492)
9.592512 0.808849 10.446866 ( 11.359820)
9.653610 0.803463 10.501491 ( 11.419194)
9.547770 0.812003 10.405405 ( 11.368690)
9.682181 0.812963 10.530854 ( 11.485025)
9.491677 0.807396 10.344595 ( 11.281067)
9.587365 0.813596 10.442915 ( 11.394766)
9.569528 0.814968 10.421925 ( 11.395829)
9.499610 0.806958 10.342308 ( 11.266410)
9.470981 0.802210 10.311858 ( 11.228286)
9.562924 0.794929 10.395599 ( 11.322258)
9.601453 0.810256 10.456259 ( 11.374217)
9.505371 0.799272 10.354669 ( 11.279456)
9.457992 0.795362 10.289520 ( 11.205184)
9.628120 0.787671 10.453407 ( 11.377989)
9.627611 0.805838 10.470388 ( 11.399739)
9.675034 0.812966 10.532779 ( 11.515440)
9.612906 0.807182 10.457964 ( 11.434272)
9.480996 0.803877 10.325013 ( 11.265876)
9.717399 0.823376 10.577638 ( 11.569749)
9.665028 0.809491 10.511645 ( 11.488256)
9.512832 0.805858 10.363675 ( 11.339722)
9.654066 0.807307 10.506755 ( 11.426100)
9.865550 0.794908 10.703626 ( 11.618194)
9.652618 0.793610 10.493186 ( 11.419415)
9.499487 0.796346 10.341364 ( 11.250758)
9.544258 0.797515 10.385862 ( 11.284281)
9.739863 0.794279 10.570723 ( 11.509588)
9.487554 0.785309 10.316760 ( 11.233325)
9.481721 0.803731 10.329705 ( 11.255686)
9.466643 0.802025 10.313663 ( 11.234516)
9.565479 0.798706 10.406513 ( 11.374955)
9.546849 0.818211 10.409684 ( 11.368566)
9.559145 0.813582 10.418666 ( 11.401304)
9.547626 0.787676 10.380384 ( 11.305801)
9.731920 0.806463 10.576084 ( 11.499545)
9.634309 0.804944 10.477565 ( 11.398455)
9.663389 0.797418 10.499369 ( 11.418504)
9.741374 0.818880 10.597056 ( 11.575796)
9.683985 0.804469 10.527844 ( 11.457434)
9.739006 0.808335 10.587852 ( 11.513780)
9.761998 0.818945 10.618427 ( 11.614032)
9.737508 0.819736 10.593885 ( 11.588014)
9.735949 0.821038 10.595284 ( 11.552597)
9.750022 0.814069 10.601283 ( 11.567239)
9.700983 0.801116 10.542112 ( 11.471005)
9.720313 0.798207 10.555314 ( 11.473235)
9.685407 0.811225 10.534452 ( 11.467112)
9.677940 0.809071 10.526291 ( 11.447495)
9.609120 0.813429 10.467227 ( 11.372680)
9.712403 0.810281 10.560867 ( 11.485852)
9.748022 0.817132 10.603028 ( 11.522460)
9.737389 0.801790 10.576720 ( 11.522855)
9.709541 0.795349 10.542238 ( 11.544047)
9.658660 0.819237 10.515718 ( 11.520783)
9.765426 0.829642 10.632481 ( 11.615062)
9.731822 0.809695 10.578871 ( 11.558062)
9.575340 0.800450 10.421430 ( 11.318465)
9.682845 0.796365 10.515529 ( 11.435012)

View file

@ -0,0 +1,118 @@
# frozen_string_literal: true
require 'test_helper'
require 'shellwords'
class TasksTest < ActiveSupport::TestCase
def setup
FileUtils.mkdir_p(rails_app_path('tmp'))
end
def teardown
FileUtils.remove_entry_secure(rails_app_path('tmp'))
end
def rake(cmd, options = {})
assert_success = options.key?(:assert_success) ? options[:assert_success] : true
env = options[:env] || {}
env_string = env.map {|key, value| "#{key.shellescape}=#{value.to_s.shellescape}" }.join(" ")
cmd = "env #{env_string} bundle exec rake -f perf.rake #{cmd} --trace"
puts "Running: #{cmd}"
result = `cd '#{rails_app_path}' && #{cmd}`
if assert_success
assert $?.success?, "Expected '#{cmd}' to return a success status.\nOutput: #{result}"
end
result
end
test 'library_branches' do
skip unless ENV['USING_RAILS_GIT']
env = { "TEST_COUNT" => 10, "DERAILED_SCRIPT_COUNT" => 2, "SHAS_TO_TEST" => "3054e1d584e7eca110c69a1f8423f2e0866abbf9,80f989aecece1a2b1830e9c953e5887421b52d3c"}
puts rake "perf:library", { env: env }
end
test 'hitting authenticated devise apps' do
env = { "PATH_TO_HIT" => "authenticated", "USE_AUTH" => "true", "TEST_COUNT" => "2" }
result = rake 'perf:test', env: env
assert_match 'Auth: true', result
env["USE_SERVER"] = "webrick"
result = rake 'perf:test', env: env
assert_match 'Auth: true', result
assert_match 'Server: "webrick"', result
end
test 'authenticate with a custom user' do
env = { "AUTH_CUSTOM_USER" => "true", "PATH_TO_HIT" => "authenticated", "USE_AUTH" => "true", "TEST_COUNT" => "2" }
result = rake 'perf:test', env: env
assert_match 'Auth: true', result
end
test 'test' do
rake "perf:test"
end
test 'TEST_COUNT' do
result = rake "perf:test", env: { "TEST_COUNT" => 1 }
assert_match "1 derailed requests", result
end
test 'WARM_COUNT' do
result = rake "perf:test", env: { "WARM_COUNT" => 1 }
assert_match "Warming up app:", result
end
test 'PATH_TO_HIT' do
env = { "PATH_TO_HIT" => 'foo', "TEST_COUNT" => "2" }
result = rake "perf:test", env: env
assert_match 'Endpoint: "foo"', result
env["USE_SERVER"] = "webrick"
result = rake "perf:test", env: env
assert_match 'Endpoint: "foo"', result
assert_match 'Server: "webrick"', result
end
test 'HTTP headers' do
env = {
"PATH_TO_HIT" => 'foo_secret',
"TEST_COUNT" => "2",
"HTTP_AUTHORIZATION" => "Basic #{Base64.encode64("admin:secret")}",
"HTTP_CACHE_CONTROL" => "no-cache"
}
result = rake "perf:test", env: env
assert_match 'Endpoint: "foo_secret"', result
assert_match 'HTTP headers: {"Authorization"=>"Basic YWRtaW46c2VjcmV0\n", "Cache-Control"=>"no-cache"}', result
env["USE_SERVER"] = "webrick"
result = rake "perf:test", env: env
assert_match 'HTTP headers: {"Authorization"=>"Basic YWRtaW46c2VjcmV0\n", "Cache-Control"=>"no-cache"}', result
end
test 'USE_SERVER' do
result = rake "perf:test", env: { "USE_SERVER" => 'webrick', "TEST_COUNT" => "2" }
assert_match 'Server: "webrick"', result
end
test '' do
end
test 'objects' do
rake "perf:objects"
end
test 'mem' do
rake "perf:mem"
end
test 'mem_over_time' do
rake "perf:mem_over_time"
end
test 'ips' do
rake "perf:mem_over_time"
end
end

View file

@ -0,0 +1,9 @@
# frozen_string_literal: true
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require 'rake'
Dummy::Application.load_tasks

View file

@ -0,0 +1,2 @@
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.

View file

@ -0,0 +1,4 @@
/*
Place all the styles related to the matching controller here.
They will automatically be included in application.css.
*/

View file

@ -0,0 +1,17 @@
# frozen_string_literal: true
class ApplicationController < ActionController::Base
if respond_to?(:before_filter) && !respond_to?(:before_action)
class << self
alias :before_action :before_filter
end
end
protect_from_forgery
before_action :pull_out_locale
def pull_out_locale
I18n.locale = params[:locale] if params[:locale].present?
end
end

View file

@ -0,0 +1,8 @@
# frozen_string_literal: true
class AuthenticatedController < ApplicationController
before_action :authenticate_user!
def index
end
end

View file

@ -0,0 +1,14 @@
# frozen_string_literal: true
class PagesController < ApplicationController
http_basic_authenticate_with name: "admin", password: "secret", only: :secret
def index
end
def secret
render action: 'index'
end
private
end

View file

@ -0,0 +1,4 @@
# frozen_string_literal: true
module ApplicationHelper
end

View file

@ -0,0 +1,4 @@
# frozen_string_literal: true
module AuthenticatedHelper
end

View file

@ -0,0 +1,13 @@
# frozen_string_literal: true
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable,
:registerable, :rememberable, :timeoutable,
:trackable, :validatable
# Setup accessible (or protected) attributes for your model
# attr_accessible :email, :password, :password_confirmation, :remember_me
# attr_accessible :title, :body
end

View file

@ -0,0 +1,14 @@
<!DOCTYPE html>
<html>
<head>
<title>Dummy</title>
<%# stylesheet_link_tag :all %>
<%# javascript_include_tag :defaults %>
<%= csrf_meta_tag %>
</head>
<body>
<%= yield %>
</body>
</html>

View file

@ -0,0 +1 @@
ohai

View file

@ -0,0 +1,6 @@
# frozen_string_literal: true
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Dummy::Application

View file

@ -0,0 +1,50 @@
# frozen_string_literal: true
require File.expand_path('../boot', __FILE__)
require "active_model/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_view/railtie"
require "action_mailer/railtie"
Bundler.require :default
require 'devise'
module Dummy
class Application < Rails::Application
config.action_mailer.default_url_options = { host: 'localhost:3000' }
# 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.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# JavaScript files you want as :defaults (application.js is always included).
# config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
config.serve_static_assets = true
end
end

View file

@ -0,0 +1,12 @@
# frozen_string_literal: true
require 'rubygems'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)
if File.exist?(gemfile)
ENV['BUNDLE_GEMFILE'] ||= gemfile
require 'bundler'
Bundler.setup
end
$:.unshift File.expand_path('../../../../lib', __FILE__)

View file

@ -0,0 +1,22 @@
# SQLite version 3.x
# gem install sqlite3
default: &default
adapter: sqlite3
pool: 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

View file

@ -0,0 +1,9 @@
# frozen_string_literal: true
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Rails.application.config.active_record.sqlite3.represent_boolean_as_integer = true
Dummy::Application.initialize!

View file

@ -0,0 +1,27 @@
# frozen_string_literal: true
Dummy::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 webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
end

View file

@ -0,0 +1,51 @@
# frozen_string_literal: true
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The production environment is meant for finished, "live" apps.
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Specifies the header that your server uses for sending files
config.action_dispatch.x_sendfile_header = "X-Sendfile"
# For nginx:
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# If you have no front-end server that supports something like X-Sendfile,
# just comment this out and Rails will serve the files
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Disable Rails's static asset server
# In production, Apache or nginx will already do this
config.serve_static_assets = false
# Enable serving of images, stylesheets, and javascripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end

View file

@ -0,0 +1,37 @@
# frozen_string_literal: true
Dummy::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
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# 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
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
end

View file

@ -0,0 +1,9 @@
# frozen_string_literal: true
# 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!

View file

@ -0,0 +1,258 @@
# frozen_string_literal: true
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = '527617f417a15170a26737856777918ab0e2665b59d41a183160eba6b038aaf81a3ebde5b5a8463cd2de1455462e40a37bcae057d580fbc4b251ceba3e85be84'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# encryptor), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = '5cecc5d3d942e712c236b7f2b0ebda84c47642864d58b5ff4c76b7f6f5523d5d6ffdeed82ea742792889393527f67f684c00aa72ef1530d81b84713ee8fecca8'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = false
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
end

View file

@ -0,0 +1,12 @@
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end

View file

@ -0,0 +1,7 @@
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone

View file

@ -0,0 +1,13 @@
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
if Dummy::Application.config.respond_to?(:secret_key_base)
Dummy::Application.config.secret_key_base = 'bedc31c5fff702ea808045bbbc5123455f1c00ecd005a1f667a5f04332100a6abf22cfcee2b3d39b8f677c03bb6503cf1c3b65c1287b9e13bd0d20c6431ec6ab'
else
Dummy::Application.config.secret_token = 'bedc31c5fff702ea808045bbbc5123455f1c00ecd005a1f667a5f04332100a6abf22cfcee2b3d39b8f677c03bb6503cf1c3b65c1287b9e13bd0d20c6431ec6ab'
end

View file

@ -0,0 +1,10 @@
# frozen_string_literal: true
# Be sure to restart your server when you modify this file.
Dummy::Application.config.session_store :cookie_store, :key => '_dummy_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Dummy::Application.config.session_store :active_record_store

View file

@ -0,0 +1,59 @@
# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
en:
devise:
confirmations:
confirmed: "Your account was successfully confirmed."
send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
failure:
already_authenticated: "You are already signed in."
inactive: "Your account is not activated yet."
invalid: "Invalid email or password."
locked: "Your account is locked."
last_attempt: "You have one more attempt before your account will be locked."
not_found_in_database: "Invalid email or password."
timeout: "Your session expired. Please sign in again to continue."
unauthenticated: "You need to sign in or sign up before continuing."
unconfirmed: "You have to confirm your account before continuing."
mailer:
confirmation_instructions:
subject: "Confirmation instructions"
reset_password_instructions:
subject: "Reset password instructions"
unlock_instructions:
subject: "Unlock Instructions"
omniauth_callbacks:
failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
success: "Successfully authenticated from %{kind} account."
passwords:
no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
updated: "Your password was changed successfully. You are now signed in."
updated_not_active: "Your password was changed successfully."
registrations:
destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon."
signed_up: "Welcome! You have signed up successfully."
signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated."
signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked."
signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account."
update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address."
updated: "You updated your account successfully."
sessions:
signed_in: "Signed in successfully."
signed_out: "Signed out successfully."
unlocks:
send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes."
send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes."
unlocked: "Your account has been unlocked successfully. Please sign in to continue."
errors:
messages:
already_confirmed: "was already confirmed, please try signing in"
confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
expired: "has expired, please request a new one"
not_found: "not found"
not_locked: "was not locked"
not_saved:
one: "1 error prohibited this %{resource} from being saved:"
other: "%{count} errors prohibited this %{resource} from being saved:"

View file

@ -0,0 +1,9 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
hello: "Hello world"
wicked:
first: "first"
second: "second"
last_step: "last_step"

View file

@ -0,0 +1,10 @@
# Sample localization file for Spanish. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
es:
hello: "hola mundo"
wicked:
first: "uno"
second: "dos"
last_step: "último_paso"

View file

@ -0,0 +1,67 @@
# frozen_string_literal: true
Dummy::Application.routes.draw do
devise_for :users
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
root to: "pages#index"
get "foo", to: "pages#index"
get "foo_secret", to: "pages#secret"
get "authenticated", to: "authenticated#index"
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id(.:format)))'
end

View file

@ -0,0 +1,45 @@
# frozen_string_literal: true
inherited_class = Rails.version < "5" ? ActiveRecord::Migration : ActiveRecord::Migration[4.2]
class DeviseCreateUsers < inherited_class
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end

View file

@ -0,0 +1,36 @@
# encoding: UTF-8
# frozen_string_literal: true
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20141210070547) do
create_table "users", force: true do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at"
t.datetime "updated_at"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end

View file

@ -0,0 +1,10 @@
# frozen_string_literal: true
$LOAD_PATH << File.expand_path("../../../lib", __FILE__)
require 'derailed_benchmarks'
require 'derailed_benchmarks/tasks'
if ENV['AUTH_CUSTOM_USER']
DerailedBenchmarks.auth.user = -> { User.first_or_create!(email: "user@example.com", password: 'password') }
end

View file

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<title>The page you were looking for doesn't exist (404)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/404.html -->
<div class="dialog">
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
</html>

View file

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<title>The change you wanted was rejected (422)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/422.html -->
<div class="dialog">
<h1>The change you wanted was rejected.</h1>
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
</body>
</html>

View file

@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<title>We're sorry, but something went wrong (500)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/500.html -->
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
<p>We've been notified about this issue and we'll take a look at it shortly.</p>
</div>
</body>
</html>

View file

@ -0,0 +1,2 @@
// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

View file

@ -0,0 +1,965 @@
// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
// Rob Wills
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
// Autocompleter.Base handles all the autocompletion functionality
// that's independent of the data source for autocompletion. This
// includes drawing the autocompletion menu, observing keyboard
// and mouse events, and similar.
//
// Specific autocompleters need to provide, at the very least,
// a getUpdatedChoices function that will be invoked every time
// the text inside the monitored textbox changes. This method
// should get the text for which to provide autocompletion by
// invoking this.getToken(), NOT by directly accessing
// this.element.value. This is to allow incremental tokenized
// autocompletion. Specific auto-completion logic (AJAX, etc)
// belongs in getUpdatedChoices.
//
// Tokenized incremental autocompletion is enabled automatically
// when an autocompleter is instantiated with the 'tokens' option
// in the options parameter, e.g.:
// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
// will incrementally autocomplete with a comma as the token.
// Additionally, ',' in the above example can be replaced with
// a token array, e.g. { tokens: [',', '\n'] } which
// enables autocompletion on multiple tokens. This is most
// useful when one of the tokens is \n (a newline), as it
// allows smart autocompletion after linebreaks.
if(typeof Effect == 'undefined')
throw("controls.js requires including script.aculo.us' effects.js library");
var Autocompleter = { };
Autocompleter.Base = Class.create({
baseInitialize: function(element, update, options) {
element = $(element);
this.element = element;
this.update = $(update);
this.hasFocus = false;
this.changed = false;
this.active = false;
this.index = 0;
this.entryCount = 0;
this.oldElementValue = this.element.value;
if(this.setOptions)
this.setOptions(options);
else
this.options = options || { };
this.options.paramName = this.options.paramName || this.element.name;
this.options.tokens = this.options.tokens || [];
this.options.frequency = this.options.frequency || 0.4;
this.options.minChars = this.options.minChars || 1;
this.options.onShow = this.options.onShow ||
function(element, update){
if(!update.style.position || update.style.position=='absolute') {
update.style.position = 'absolute';
Position.clone(element, update, {
setHeight: false,
offsetTop: element.offsetHeight
});
}
Effect.Appear(update,{duration:0.15});
};
this.options.onHide = this.options.onHide ||
function(element, update){ new Effect.Fade(update,{duration:0.15}) };
if(typeof(this.options.tokens) == 'string')
this.options.tokens = new Array(this.options.tokens);
// Force carriage returns as token delimiters anyway
if (!this.options.tokens.include('\n'))
this.options.tokens.push('\n');
this.observer = null;
this.element.setAttribute('autocomplete','off');
Element.hide(this.update);
Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
},
show: function() {
if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
if(!this.iefix &&
(Prototype.Browser.IE) &&
(Element.getStyle(this.update, 'position')=='absolute')) {
new Insertion.After(this.update,
'<iframe id="' + this.update.id + '_iefix" '+
'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
this.iefix = $(this.update.id+'_iefix');
}
if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
},
fixIEOverlapping: function() {
Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
this.iefix.style.zIndex = 1;
this.update.style.zIndex = 2;
Element.show(this.iefix);
},
hide: function() {
this.stopIndicator();
if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
if(this.iefix) Element.hide(this.iefix);
},
startIndicator: function() {
if(this.options.indicator) Element.show(this.options.indicator);
},
stopIndicator: function() {
if(this.options.indicator) Element.hide(this.options.indicator);
},
onKeyPress: function(event) {
if(this.active)
switch(event.keyCode) {
case Event.KEY_TAB:
case Event.KEY_RETURN:
this.selectEntry();
Event.stop(event);
case Event.KEY_ESC:
this.hide();
this.active = false;
Event.stop(event);
return;
case Event.KEY_LEFT:
case Event.KEY_RIGHT:
return;
case Event.KEY_UP:
this.markPrevious();
this.render();
Event.stop(event);
return;
case Event.KEY_DOWN:
this.markNext();
this.render();
Event.stop(event);
return;
}
else
if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
(Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
this.changed = true;
this.hasFocus = true;
if(this.observer) clearTimeout(this.observer);
this.observer =
setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
},
activate: function() {
this.changed = false;
this.hasFocus = true;
this.getUpdatedChoices();
},
onHover: function(event) {
var element = Event.findElement(event, 'LI');
if(this.index != element.autocompleteIndex)
{
this.index = element.autocompleteIndex;
this.render();
}
Event.stop(event);
},
onClick: function(event) {
var element = Event.findElement(event, 'LI');
this.index = element.autocompleteIndex;
this.selectEntry();
this.hide();
},
onBlur: function(event) {
// needed to make click events working
setTimeout(this.hide.bind(this), 250);
this.hasFocus = false;
this.active = false;
},
render: function() {
if(this.entryCount > 0) {
for (var i = 0; i < this.entryCount; i++)
this.index==i ?
Element.addClassName(this.getEntry(i),"selected") :
Element.removeClassName(this.getEntry(i),"selected");
if(this.hasFocus) {
this.show();
this.active = true;
}
} else {
this.active = false;
this.hide();
}
},
markPrevious: function() {
if(this.index > 0) this.index--;
else this.index = this.entryCount-1;
this.getEntry(this.index).scrollIntoView(true);
},
markNext: function() {
if(this.index < this.entryCount-1) this.index++;
else this.index = 0;
this.getEntry(this.index).scrollIntoView(false);
},
getEntry: function(index) {
return this.update.firstChild.childNodes[index];
},
getCurrentEntry: function() {
return this.getEntry(this.index);
},
selectEntry: function() {
this.active = false;
this.updateElement(this.getCurrentEntry());
},
updateElement: function(selectedElement) {
if (this.options.updateElement) {
this.options.updateElement(selectedElement);
return;
}
var value = '';
if (this.options.select) {
var nodes = $(selectedElement).select('.' + this.options.select) || [];
if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
} else
value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
var bounds = this.getTokenBounds();
if (bounds[0] != -1) {
var newValue = this.element.value.substr(0, bounds[0]);
var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
if (whitespace)
newValue += whitespace[0];
this.element.value = newValue + value + this.element.value.substr(bounds[1]);
} else {
this.element.value = value;
}
this.oldElementValue = this.element.value;
this.element.focus();
if (this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element, selectedElement);
},
updateChoices: function(choices) {
if(!this.changed && this.hasFocus) {
this.update.innerHTML = choices;
Element.cleanWhitespace(this.update);
Element.cleanWhitespace(this.update.down());
if(this.update.firstChild && this.update.down().childNodes) {
this.entryCount =
this.update.down().childNodes.length;
for (var i = 0; i < this.entryCount; i++) {
var entry = this.getEntry(i);
entry.autocompleteIndex = i;
this.addObservers(entry);
}
} else {
this.entryCount = 0;
}
this.stopIndicator();
this.index = 0;
if(this.entryCount==1 && this.options.autoSelect) {
this.selectEntry();
this.hide();
} else {
this.render();
}
}
},
addObservers: function(element) {
Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
Event.observe(element, "click", this.onClick.bindAsEventListener(this));
},
onObserverEvent: function() {
this.changed = false;
this.tokenBounds = null;
if(this.getToken().length>=this.options.minChars) {
this.getUpdatedChoices();
} else {
this.active = false;
this.hide();
}
this.oldElementValue = this.element.value;
},
getToken: function() {
var bounds = this.getTokenBounds();
return this.element.value.substring(bounds[0], bounds[1]).strip();
},
getTokenBounds: function() {
if (null != this.tokenBounds) return this.tokenBounds;
var value = this.element.value;
if (value.strip().empty()) return [-1, 0];
var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
var offset = (diff == this.oldElementValue.length ? 1 : 0);
var prevTokenPos = -1, nextTokenPos = value.length;
var tp;
for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
if (tp > prevTokenPos) prevTokenPos = tp;
tp = value.indexOf(this.options.tokens[index], diff + offset);
if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
}
return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
}
});
Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
var boundary = Math.min(newS.length, oldS.length);
for (var index = 0; index < boundary; ++index)
if (newS[index] != oldS[index])
return index;
return boundary;
};
Ajax.Autocompleter = Class.create(Autocompleter.Base, {
initialize: function(element, update, url, options) {
this.baseInitialize(element, update, options);
this.options.asynchronous = true;
this.options.onComplete = this.onComplete.bind(this);
this.options.defaultParams = this.options.parameters || null;
this.url = url;
},
getUpdatedChoices: function() {
this.startIndicator();
var entry = encodeURIComponent(this.options.paramName) + '=' +
encodeURIComponent(this.getToken());
this.options.parameters = this.options.callback ?
this.options.callback(this.element, entry) : entry;
if(this.options.defaultParams)
this.options.parameters += '&' + this.options.defaultParams;
new Ajax.Request(this.url, this.options);
},
onComplete: function(request) {
this.updateChoices(request.responseText);
}
});
// The local array autocompleter. Used when you'd prefer to
// inject an array of autocompletion options into the page, rather
// than sending out Ajax queries, which can be quite slow sometimes.
//
// The constructor takes four parameters. The first two are, as usual,
// the id of the monitored textbox, and id of the autocompletion menu.
// The third is the array you want to autocomplete from, and the fourth
// is the options block.
//
// Extra local autocompletion options:
// - choices - How many autocompletion choices to offer
//
// - partialSearch - If false, the autocompleter will match entered
// text only at the beginning of strings in the
// autocomplete array. Defaults to true, which will
// match text at the beginning of any *word* in the
// strings in the autocomplete array. If you want to
// search anywhere in the string, additionally set
// the option fullSearch to true (default: off).
//
// - fullSsearch - Search anywhere in autocomplete array strings.
//
// - partialChars - How many characters to enter before triggering
// a partial match (unlike minChars, which defines
// how many characters are required to do any match
// at all). Defaults to 2.
//
// - ignoreCase - Whether to ignore case when autocompleting.
// Defaults to true.
//
// It's possible to pass in a custom function as the 'selector'
// option, if you prefer to write your own autocompletion logic.
// In that case, the other options above will not apply unless
// you support them.
Autocompleter.Local = Class.create(Autocompleter.Base, {
initialize: function(element, update, array, options) {
this.baseInitialize(element, update, options);
this.options.array = array;
},
getUpdatedChoices: function() {
this.updateChoices(this.options.selector(this));
},
setOptions: function(options) {
this.options = Object.extend({
choices: 10,
partialSearch: true,
partialChars: 2,
ignoreCase: true,
fullSearch: false,
selector: function(instance) {
var ret = []; // Beginning matches
var partial = []; // Inside matches
var entry = instance.getToken();
var count = 0;
for (var i = 0; i < instance.options.array.length &&
ret.length < instance.options.choices ; i++) {
var elem = instance.options.array[i];
var foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase()) :
elem.indexOf(entry);
while (foundPos != -1) {
if (foundPos == 0 && elem.length != entry.length) {
ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
elem.substr(entry.length) + "</li>");
break;
} else if (entry.length >= instance.options.partialChars &&
instance.options.partialSearch && foundPos != -1) {
if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
foundPos + entry.length) + "</li>");
break;
}
}
foundPos = instance.options.ignoreCase ?
elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
elem.indexOf(entry, foundPos + 1);
}
}
if (partial.length)
ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
return "<ul>" + ret.join('') + "</ul>";
}
}, options || { });
}
});
// AJAX in-place editor and collection editor
// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
// Use this if you notice weird scrolling problems on some browsers,
// the DOM might be a bit confused when this gets called so do this
// waits 1 ms (with setTimeout) until it does the activation
Field.scrollFreeActivate = function(field) {
setTimeout(function() {
Field.activate(field);
}, 1);
};
Ajax.InPlaceEditor = Class.create({
initialize: function(element, url, options) {
this.url = url;
this.element = element = $(element);
this.prepareOptions();
this._controls = { };
arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
Object.extend(this.options, options || { });
if (!this.options.formId && this.element.id) {
this.options.formId = this.element.id + '-inplaceeditor';
if ($(this.options.formId))
this.options.formId = '';
}
if (this.options.externalControl)
this.options.externalControl = $(this.options.externalControl);
if (!this.options.externalControl)
this.options.externalControlOnly = false;
this._originalBackground = this.element.getStyle('background-color') || 'transparent';
this.element.title = this.options.clickToEditText;
this._boundCancelHandler = this.handleFormCancellation.bind(this);
this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
this._boundFailureHandler = this.handleAJAXFailure.bind(this);
this._boundSubmitHandler = this.handleFormSubmission.bind(this);
this._boundWrapperHandler = this.wrapUp.bind(this);
this.registerListeners();
},
checkForEscapeOrReturn: function(e) {
if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
if (Event.KEY_ESC == e.keyCode)
this.handleFormCancellation(e);
else if (Event.KEY_RETURN == e.keyCode)
this.handleFormSubmission(e);
},
createControl: function(mode, handler, extraClasses) {
var control = this.options[mode + 'Control'];
var text = this.options[mode + 'Text'];
if ('button' == control) {
var btn = document.createElement('input');
btn.type = 'submit';
btn.value = text;
btn.className = 'editor_' + mode + '_button';
if ('cancel' == mode)
btn.onclick = this._boundCancelHandler;
this._form.appendChild(btn);
this._controls[mode] = btn;
} else if ('link' == control) {
var link = document.createElement('a');
link.href = '#';
link.appendChild(document.createTextNode(text));
link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
link.className = 'editor_' + mode + '_link';
if (extraClasses)
link.className += ' ' + extraClasses;
this._form.appendChild(link);
this._controls[mode] = link;
}
},
createEditField: function() {
var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
var fld;
if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
fld = document.createElement('input');
fld.type = 'text';
var size = this.options.size || this.options.cols || 0;
if (0 < size) fld.size = size;
} else {
fld = document.createElement('textarea');
fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
fld.cols = this.options.cols || 40;
}
fld.name = this.options.paramName;
fld.value = text; // No HTML breaks conversion anymore
fld.className = 'editor_field';
if (this.options.submitOnBlur)
fld.onblur = this._boundSubmitHandler;
this._controls.editor = fld;
if (this.options.loadTextURL)
this.loadExternalText();
this._form.appendChild(this._controls.editor);
},
createForm: function() {
var ipe = this;
function addText(mode, condition) {
var text = ipe.options['text' + mode + 'Controls'];
if (!text || condition === false) return;
ipe._form.appendChild(document.createTextNode(text));
};
this._form = $(document.createElement('form'));
this._form.id = this.options.formId;
this._form.addClassName(this.options.formClassName);
this._form.onsubmit = this._boundSubmitHandler;
this.createEditField();
if ('textarea' == this._controls.editor.tagName.toLowerCase())
this._form.appendChild(document.createElement('br'));
if (this.options.onFormCustomization)
this.options.onFormCustomization(this, this._form);
addText('Before', this.options.okControl || this.options.cancelControl);
this.createControl('ok', this._boundSubmitHandler);
addText('Between', this.options.okControl && this.options.cancelControl);
this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
addText('After', this.options.okControl || this.options.cancelControl);
},
destroy: function() {
if (this._oldInnerHTML)
this.element.innerHTML = this._oldInnerHTML;
this.leaveEditMode();
this.unregisterListeners();
},
enterEditMode: function(e) {
if (this._saving || this._editing) return;
this._editing = true;
this.triggerCallback('onEnterEditMode');
if (this.options.externalControl)
this.options.externalControl.hide();
this.element.hide();
this.createForm();
this.element.parentNode.insertBefore(this._form, this.element);
if (!this.options.loadTextURL)
this.postProcessEditField();
if (e) Event.stop(e);
},
enterHover: function(e) {
if (this.options.hoverClassName)
this.element.addClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onEnterHover');
},
getText: function() {
return this.element.innerHTML.unescapeHTML();
},
handleAJAXFailure: function(transport) {
this.triggerCallback('onFailure', transport);
if (this._oldInnerHTML) {
this.element.innerHTML = this._oldInnerHTML;
this._oldInnerHTML = null;
}
},
handleFormCancellation: function(e) {
this.wrapUp();
if (e) Event.stop(e);
},
handleFormSubmission: function(e) {
var form = this._form;
var value = $F(this._controls.editor);
this.prepareSubmission();
var params = this.options.callback(form, value) || '';
if (Object.isString(params))
params = params.toQueryParams();
params.editorId = this.element.id;
if (this.options.htmlResponse) {
var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Updater({ success: this.element }, this.url, options);
} else {
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: params,
onComplete: this._boundWrapperHandler,
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.url, options);
}
if (e) Event.stop(e);
},
leaveEditMode: function() {
this.element.removeClassName(this.options.savingClassName);
this.removeForm();
this.leaveHover();
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
if (this.options.externalControl)
this.options.externalControl.show();
this._saving = false;
this._editing = false;
this._oldInnerHTML = null;
this.triggerCallback('onLeaveEditMode');
},
leaveHover: function(e) {
if (this.options.hoverClassName)
this.element.removeClassName(this.options.hoverClassName);
if (this._saving) return;
this.triggerCallback('onLeaveHover');
},
loadExternalText: function() {
this._form.addClassName(this.options.loadingClassName);
this._controls.editor.disabled = true;
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._form.removeClassName(this.options.loadingClassName);
var text = transport.responseText;
if (this.options.stripLoadedTextTags)
text = text.stripTags();
this._controls.editor.value = text;
this._controls.editor.disabled = false;
this.postProcessEditField();
}.bind(this),
onFailure: this._boundFailureHandler
});
new Ajax.Request(this.options.loadTextURL, options);
},
postProcessEditField: function() {
var fpc = this.options.fieldPostCreation;
if (fpc)
$(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
},
prepareOptions: function() {
this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
[this._extraDefaultOptions].flatten().compact().each(function(defs) {
Object.extend(this.options, defs);
}.bind(this));
},
prepareSubmission: function() {
this._saving = true;
this.removeForm();
this.leaveHover();
this.showSaving();
},
registerListeners: function() {
this._listeners = { };
var listener;
$H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
listener = this[pair.value].bind(this);
this._listeners[pair.key] = listener;
if (!this.options.externalControlOnly)
this.element.observe(pair.key, listener);
if (this.options.externalControl)
this.options.externalControl.observe(pair.key, listener);
}.bind(this));
},
removeForm: function() {
if (!this._form) return;
this._form.remove();
this._form = null;
this._controls = { };
},
showSaving: function() {
this._oldInnerHTML = this.element.innerHTML;
this.element.innerHTML = this.options.savingText;
this.element.addClassName(this.options.savingClassName);
this.element.style.backgroundColor = this._originalBackground;
this.element.show();
},
triggerCallback: function(cbName, arg) {
if ('function' == typeof this.options[cbName]) {
this.options[cbName](this, arg);
}
},
unregisterListeners: function() {
$H(this._listeners).each(function(pair) {
if (!this.options.externalControlOnly)
this.element.stopObserving(pair.key, pair.value);
if (this.options.externalControl)
this.options.externalControl.stopObserving(pair.key, pair.value);
}.bind(this));
},
wrapUp: function(transport) {
this.leaveEditMode();
// Can't use triggerCallback due to backward compatibility: requires
// binding + direct element
this._boundComplete(transport, this.element);
}
});
Object.extend(Ajax.InPlaceEditor.prototype, {
dispose: Ajax.InPlaceEditor.prototype.destroy
});
Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
initialize: function($super, element, url, options) {
this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
$super(element, url, options);
},
createEditField: function() {
var list = document.createElement('select');
list.name = this.options.paramName;
list.size = 1;
this._controls.editor = list;
this._collection = this.options.collection || [];
if (this.options.loadCollectionURL)
this.loadCollection();
else
this.checkForExternalText();
this._form.appendChild(this._controls.editor);
},
loadCollection: function() {
this._form.addClassName(this.options.loadingClassName);
this.showLoadingText(this.options.loadingCollectionText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
var js = transport.responseText.strip();
if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
throw('Server returned an invalid collection representation.');
this._collection = eval(js);
this.checkForExternalText();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadCollectionURL, options);
},
showLoadingText: function(text) {
this._controls.editor.disabled = true;
var tempOption = this._controls.editor.firstChild;
if (!tempOption) {
tempOption = document.createElement('option');
tempOption.value = '';
this._controls.editor.appendChild(tempOption);
tempOption.selected = true;
}
tempOption.update((text || '').stripScripts().stripTags());
},
checkForExternalText: function() {
this._text = this.getText();
if (this.options.loadTextURL)
this.loadExternalText();
else
this.buildOptionList();
},
loadExternalText: function() {
this.showLoadingText(this.options.loadingText);
var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
Object.extend(options, {
parameters: 'editorId=' + encodeURIComponent(this.element.id),
onComplete: Prototype.emptyFunction,
onSuccess: function(transport) {
this._text = transport.responseText.strip();
this.buildOptionList();
}.bind(this),
onFailure: this.onFailure
});
new Ajax.Request(this.options.loadTextURL, options);
},
buildOptionList: function() {
this._form.removeClassName(this.options.loadingClassName);
this._collection = this._collection.map(function(entry) {
return 2 === entry.length ? entry : [entry, entry].flatten();
});
var marker = ('value' in this.options) ? this.options.value : this._text;
var textFound = this._collection.any(function(entry) {
return entry[0] == marker;
}.bind(this));
this._controls.editor.update('');
var option;
this._collection.each(function(entry, index) {
option = document.createElement('option');
option.value = entry[0];
option.selected = textFound ? entry[0] == marker : 0 == index;
option.appendChild(document.createTextNode(entry[1]));
this._controls.editor.appendChild(option);
}.bind(this));
this._controls.editor.disabled = false;
Field.scrollFreeActivate(this._controls.editor);
}
});
//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
//**** This only exists for a while, in order to let ****
//**** users adapt to the new API. Read up on the new ****
//**** API and convert your code to it ASAP! ****
Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
if (!options) return;
function fallback(name, expr) {
if (name in options || expr === undefined) return;
options[name] = expr;
};
fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
options.cancelLink == options.cancelButton == false ? false : undefined)));
fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
options.okLink == options.okButton == false ? false : undefined)));
fallback('highlightColor', options.highlightcolor);
fallback('highlightEndColor', options.highlightendcolor);
};
Object.extend(Ajax.InPlaceEditor, {
DefaultOptions: {
ajaxOptions: { },
autoRows: 3, // Use when multi-line w/ rows == 1
cancelControl: 'link', // 'link'|'button'|false
cancelText: 'cancel',
clickToEditText: 'Click to edit',
externalControl: null, // id|elt
externalControlOnly: false,
fieldPostCreation: 'activate', // 'activate'|'focus'|false
formClassName: 'inplaceeditor-form',
formId: null, // id|elt
highlightColor: '#ffff99',
highlightEndColor: '#ffffff',
hoverClassName: '',
htmlResponse: true,
loadingClassName: 'inplaceeditor-loading',
loadingText: 'Loading...',
okControl: 'button', // 'link'|'button'|false
okText: 'ok',
paramName: 'value',
rows: 1, // If 1 and multi-line, uses autoRows
savingClassName: 'inplaceeditor-saving',
savingText: 'Saving...',
size: 0,
stripLoadedTextTags: false,
submitOnBlur: false,
textAfterControls: '',
textBeforeControls: '',
textBetweenControls: ''
},
DefaultCallbacks: {
callback: function(form) {
return Form.serialize(form);
},
onComplete: function(transport, element) {
// For backward compatibility, this one is bound to the IPE, and passes
// the element directly. It was too often customized, so we don't break it.
new Effect.Highlight(element, {
startcolor: this.options.highlightColor, keepBackgroundImage: true });
},
onEnterEditMode: null,
onEnterHover: function(ipe) {
ipe.element.style.backgroundColor = ipe.options.highlightColor;
if (ipe._effect)
ipe._effect.cancel();
},
onFailure: function(transport, ipe) {
alert('Error communication with the server: ' + transport.responseText.stripTags());
},
onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls.
onLeaveEditMode: null,
onLeaveHover: function(ipe) {
ipe._effect = new Effect.Highlight(ipe.element, {
startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor,
restorecolor: ipe._originalBackground, keepBackgroundImage: true
});
}
},
Listeners: {
click: 'enterEditMode',
keydown: 'checkForEscapeOrReturn',
mouseover: 'enterHover',
mouseout: 'leaveHover'
}
});
Ajax.InPlaceCollectionEditor.DefaultOptions = {
loadingCollectionText: 'Loading options...'
};
// Delayed observer, like Form.Element.Observer,
// but waits for delay after last key input
// Ideal for live-search fields
Form.Element.DelayedObserver = Class.create({
initialize: function(element, delay, callback) {
this.delay = delay || 0.5;
this.element = $(element);
this.callback = callback;
this.timer = null;
this.lastValue = $F(this.element);
Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));
},
delayedListener: function(event) {
if(this.lastValue == $F(this.element)) return;
if(this.timer) clearTimeout(this.timer);
this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000);
this.lastValue = $F(this.element);
},
onTimerEvent: function() {
this.timer = null;
this.callback(this.element, $F(this.element));
}
});

View file

@ -0,0 +1,974 @@
// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
if(Object.isUndefined(Effect))
throw("dragdrop.js requires including script.aculo.us' effects.js library");
var Droppables = {
drops: [],
remove: function(element) {
this.drops = this.drops.reject(function(d) { return d.element==$(element) });
},
add: function(element) {
element = $(element);
var options = Object.extend({
greedy: true,
hoverclass: null,
tree: false
}, arguments[1] || { });
// cache containers
if(options.containment) {
options._containers = [];
var containment = options.containment;
if(Object.isArray(containment)) {
containment.each( function(c) { options._containers.push($(c)) });
} else {
options._containers.push($(containment));
}
}
if(options.accept) options.accept = [options.accept].flatten();
Element.makePositioned(element); // fix IE
options.element = element;
this.drops.push(options);
},
findDeepestChild: function(drops) {
deepest = drops[0];
for (i = 1; i < drops.length; ++i)
if (Element.isParent(drops[i].element, deepest.element))
deepest = drops[i];
return deepest;
},
isContained: function(element, drop) {
var containmentNode;
if(drop.tree) {
containmentNode = element.treeNode;
} else {
containmentNode = element.parentNode;
}
return drop._containers.detect(function(c) { return containmentNode == c });
},
isAffected: function(point, element, drop) {
return (
(drop.element!=element) &&
((!drop._containers) ||
this.isContained(element, drop)) &&
((!drop.accept) ||
(Element.classNames(element).detect(
function(v) { return drop.accept.include(v) } ) )) &&
Position.within(drop.element, point[0], point[1]) );
},
deactivate: function(drop) {
if(drop.hoverclass)
Element.removeClassName(drop.element, drop.hoverclass);
this.last_active = null;
},
activate: function(drop) {
if(drop.hoverclass)
Element.addClassName(drop.element, drop.hoverclass);
this.last_active = drop;
},
show: function(point, element) {
if(!this.drops.length) return;
var drop, affected = [];
this.drops.each( function(drop) {
if(Droppables.isAffected(point, element, drop))
affected.push(drop);
});
if(affected.length>0)
drop = Droppables.findDeepestChild(affected);
if(this.last_active && this.last_active != drop) this.deactivate(this.last_active);
if (drop) {
Position.within(drop.element, point[0], point[1]);
if(drop.onHover)
drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
if (drop != this.last_active) Droppables.activate(drop);
}
},
fire: function(event, element) {
if(!this.last_active) return;
Position.prepare();
if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
if (this.last_active.onDrop) {
this.last_active.onDrop(element, this.last_active.element, event);
return true;
}
},
reset: function() {
if(this.last_active)
this.deactivate(this.last_active);
}
};
var Draggables = {
drags: [],
observers: [],
register: function(draggable) {
if(this.drags.length == 0) {
this.eventMouseUp = this.endDrag.bindAsEventListener(this);
this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
this.eventKeypress = this.keyPress.bindAsEventListener(this);
Event.observe(document, "mouseup", this.eventMouseUp);
Event.observe(document, "mousemove", this.eventMouseMove);
Event.observe(document, "keypress", this.eventKeypress);
}
this.drags.push(draggable);
},
unregister: function(draggable) {
this.drags = this.drags.reject(function(d) { return d==draggable });
if(this.drags.length == 0) {
Event.stopObserving(document, "mouseup", this.eventMouseUp);
Event.stopObserving(document, "mousemove", this.eventMouseMove);
Event.stopObserving(document, "keypress", this.eventKeypress);
}
},
activate: function(draggable) {
if(draggable.options.delay) {
this._timeout = setTimeout(function() {
Draggables._timeout = null;
window.focus();
Draggables.activeDraggable = draggable;
}.bind(this), draggable.options.delay);
} else {
window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
this.activeDraggable = draggable;
}
},
deactivate: function() {
this.activeDraggable = null;
},
updateDrag: function(event) {
if(!this.activeDraggable) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
// Mozilla-based browsers fire successive mousemove events with
// the same coordinates, prevent needless redrawing (moz bug?)
if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
this._lastPointer = pointer;
this.activeDraggable.updateDrag(event, pointer);
},
endDrag: function(event) {
if(this._timeout) {
clearTimeout(this._timeout);
this._timeout = null;
}
if(!this.activeDraggable) return;
this._lastPointer = null;
this.activeDraggable.endDrag(event);
this.activeDraggable = null;
},
keyPress: function(event) {
if(this.activeDraggable)
this.activeDraggable.keyPress(event);
},
addObserver: function(observer) {
this.observers.push(observer);
this._cacheObserverCallbacks();
},
removeObserver: function(element) { // element instead of observer fixes mem leaks
this.observers = this.observers.reject( function(o) { return o.element==element });
this._cacheObserverCallbacks();
},
notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag'
if(this[eventName+'Count'] > 0)
this.observers.each( function(o) {
if(o[eventName]) o[eventName](eventName, draggable, event);
});
if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
},
_cacheObserverCallbacks: function() {
['onStart','onEnd','onDrag'].each( function(eventName) {
Draggables[eventName+'Count'] = Draggables.observers.select(
function(o) { return o[eventName]; }
).length;
});
}
};
/*--------------------------------------------------------------------------*/
var Draggable = Class.create({
initialize: function(element) {
var defaults = {
handle: false,
reverteffect: function(element, top_offset, left_offset) {
var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
queue: {scope:'_draggable', position:'end'}
});
},
endeffect: function(element) {
var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0;
new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
queue: {scope:'_draggable', position:'end'},
afterFinish: function(){
Draggable._dragging[element] = false
}
});
},
zindex: 1000,
revert: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] }
delay: 0
};
if(!arguments[1] || Object.isUndefined(arguments[1].endeffect))
Object.extend(defaults, {
starteffect: function(element) {
element._opacity = Element.getOpacity(element);
Draggable._dragging[element] = true;
new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
}
});
var options = Object.extend(defaults, arguments[1] || { });
this.element = $(element);
if(options.handle && Object.isString(options.handle))
this.handle = this.element.down('.'+options.handle, 0);
if(!this.handle) this.handle = $(options.handle);
if(!this.handle) this.handle = this.element;
if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
options.scroll = $(options.scroll);
this._isScrollChild = Element.childOf(this.element, options.scroll);
}
Element.makePositioned(this.element); // fix IE
this.options = options;
this.dragging = false;
this.eventMouseDown = this.initDrag.bindAsEventListener(this);
Event.observe(this.handle, "mousedown", this.eventMouseDown);
Draggables.register(this);
},
destroy: function() {
Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
Draggables.unregister(this);
},
currentDelta: function() {
return([
parseInt(Element.getStyle(this.element,'left') || '0'),
parseInt(Element.getStyle(this.element,'top') || '0')]);
},
initDrag: function(event) {
if(!Object.isUndefined(Draggable._dragging[this.element]) &&
Draggable._dragging[this.element]) return;
if(Event.isLeftClick(event)) {
// abort on form elements, fixes a Firefox issue
var src = Event.element(event);
if((tag_name = src.tagName.toUpperCase()) && (
tag_name=='INPUT' ||
tag_name=='SELECT' ||
tag_name=='OPTION' ||
tag_name=='BUTTON' ||
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
var pos = this.element.cumulativeOffset();
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
Event.stop(event);
}
},
startDrag: function(event) {
this.dragging = true;
if(!this.delta)
this.delta = this.currentDelta();
if(this.options.zindex) {
this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
this.element.style.zIndex = this.options.zindex;
}
if(this.options.ghosting) {
this._clone = this.element.cloneNode(true);
this._originallyAbsolute = (this.element.getStyle('position') == 'absolute');
if (!this._originallyAbsolute)
Position.absolutize(this.element);
this.element.parentNode.insertBefore(this._clone, this.element);
}
if(this.options.scroll) {
if (this.options.scroll == window) {
var where = this._getWindowScroll(this.options.scroll);
this.originalScrollLeft = where.left;
this.originalScrollTop = where.top;
} else {
this.originalScrollLeft = this.options.scroll.scrollLeft;
this.originalScrollTop = this.options.scroll.scrollTop;
}
}
Draggables.notify('onStart', this, event);
if(this.options.starteffect) this.options.starteffect(this.element);
},
updateDrag: function(event, pointer) {
if(!this.dragging) this.startDrag(event);
if(!this.options.quiet){
Position.prepare();
Droppables.show(pointer, this.element);
}
Draggables.notify('onDrag', this, event);
this.draw(pointer);
if(this.options.change) this.options.change(this);
if(this.options.scroll) {
this.stopScrolling();
var p;
if (this.options.scroll == window) {
with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
} else {
p = Position.page(this.options.scroll);
p[0] += this.options.scroll.scrollLeft + Position.deltaX;
p[1] += this.options.scroll.scrollTop + Position.deltaY;
p.push(p[0]+this.options.scroll.offsetWidth);
p.push(p[1]+this.options.scroll.offsetHeight);
}
var speed = [0,0];
if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
this.startScrolling(speed);
}
// fix AppleWebKit rendering
if(Prototype.Browser.WebKit) window.scrollBy(0,0);
Event.stop(event);
},
finishDrag: function(event, success) {
this.dragging = false;
if(this.options.quiet){
Position.prepare();
var pointer = [Event.pointerX(event), Event.pointerY(event)];
Droppables.show(pointer, this.element);
}
if(this.options.ghosting) {
if (!this._originallyAbsolute)
Position.relativize(this.element);
delete this._originallyAbsolute;
Element.remove(this._clone);
this._clone = null;
}
var dropped = false;
if(success) {
dropped = Droppables.fire(event, this.element);
if (!dropped) dropped = false;
}
if(dropped && this.options.onDropped) this.options.onDropped(this.element);
Draggables.notify('onEnd', this, event);
var revert = this.options.revert;
if(revert && Object.isFunction(revert)) revert = revert(this.element);
var d = this.currentDelta();
if(revert && this.options.reverteffect) {
if (dropped == 0 || revert != 'failure')
this.options.reverteffect(this.element,
d[1]-this.delta[1], d[0]-this.delta[0]);
} else {
this.delta = d;
}
if(this.options.zindex)
this.element.style.zIndex = this.originalZ;
if(this.options.endeffect)
this.options.endeffect(this.element);
Draggables.deactivate(this);
Droppables.reset();
},
keyPress: function(event) {
if(event.keyCode!=Event.KEY_ESC) return;
this.finishDrag(event, false);
Event.stop(event);
},
endDrag: function(event) {
if(!this.dragging) return;
this.stopScrolling();
this.finishDrag(event, true);
Event.stop(event);
},
draw: function(point) {
var pos = this.element.cumulativeOffset();
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
}
var d = this.currentDelta();
pos[0] -= d[0]; pos[1] -= d[1];
if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
}
var p = [0,1].map(function(i){
return (point[i]-pos[i]-this.offset[i])
}.bind(this));
if(this.options.snap) {
if(Object.isFunction(this.options.snap)) {
p = this.options.snap(p[0],p[1],this);
} else {
if(Object.isArray(this.options.snap)) {
p = p.map( function(v, i) {
return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this));
} else {
p = p.map( function(v) {
return (v/this.options.snap).round()*this.options.snap }.bind(this));
}
}}
var style = this.element.style;
if((!this.options.constraint) || (this.options.constraint=='horizontal'))
style.left = p[0] + "px";
if((!this.options.constraint) || (this.options.constraint=='vertical'))
style.top = p[1] + "px";
if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
},
stopScrolling: function() {
if(this.scrollInterval) {
clearInterval(this.scrollInterval);
this.scrollInterval = null;
Draggables._lastScrollPointer = null;
}
},
startScrolling: function(speed) {
if(!(speed[0] || speed[1])) return;
this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
this.lastScrolled = new Date();
this.scrollInterval = setInterval(this.scroll.bind(this), 10);
},
scroll: function() {
var current = new Date();
var delta = current - this.lastScrolled;
this.lastScrolled = current;
if(this.options.scroll == window) {
with (this._getWindowScroll(this.options.scroll)) {
if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
var d = delta / 1000;
this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
}
}
} else {
this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000;
}
Position.prepare();
Droppables.show(Draggables._lastPointer, this.element);
Draggables.notify('onDrag', this);
if (this._isScrollChild) {
Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
if (Draggables._lastScrollPointer[0] < 0)
Draggables._lastScrollPointer[0] = 0;
if (Draggables._lastScrollPointer[1] < 0)
Draggables._lastScrollPointer[1] = 0;
this.draw(Draggables._lastScrollPointer);
}
if(this.options.change) this.options.change(this);
},
_getWindowScroll: function(w) {
var T, L, W, H;
with (w.document) {
if (w.document.documentElement && documentElement.scrollTop) {
T = documentElement.scrollTop;
L = documentElement.scrollLeft;
} else if (w.document.body) {
T = body.scrollTop;
L = body.scrollLeft;
}
if (w.innerWidth) {
W = w.innerWidth;
H = w.innerHeight;
} else if (w.document.documentElement && documentElement.clientWidth) {
W = documentElement.clientWidth;
H = documentElement.clientHeight;
} else {
W = body.offsetWidth;
H = body.offsetHeight;
}
}
return { top: T, left: L, width: W, height: H };
}
});
Draggable._dragging = { };
/*--------------------------------------------------------------------------*/
var SortableObserver = Class.create({
initialize: function(element, observer) {
this.element = $(element);
this.observer = observer;
this.lastValue = Sortable.serialize(this.element);
},
onStart: function() {
this.lastValue = Sortable.serialize(this.element);
},
onEnd: function() {
Sortable.unmark();
if(this.lastValue != Sortable.serialize(this.element))
this.observer(this.element)
}
});
var Sortable = {
SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
sortables: { },
_findRootElement: function(element) {
while (element.tagName.toUpperCase() != "BODY") {
if(element.id && Sortable.sortables[element.id]) return element;
element = element.parentNode;
}
},
options: function(element) {
element = Sortable._findRootElement($(element));
if(!element) return;
return Sortable.sortables[element.id];
},
destroy: function(element){
element = $(element);
var s = Sortable.sortables[element.id];
if(s) {
Draggables.removeObserver(s.element);
s.droppables.each(function(d){ Droppables.remove(d) });
s.draggables.invoke('destroy');
delete Sortable.sortables[s.element.id];
}
},
create: function(element) {
element = $(element);
var options = Object.extend({
element: element,
tag: 'li', // assumes li children, override with tag: 'tagname'
dropOnEmpty: false,
tree: false,
treeTag: 'ul',
overlap: 'vertical', // one of 'vertical', 'horizontal'
constraint: 'vertical', // one of 'vertical', 'horizontal', false
containment: element, // also takes array of elements (or id's); or false
handle: false, // or a CSS class
only: false,
delay: 0,
hoverclass: null,
ghosting: false,
quiet: false,
scroll: false,
scrollSensitivity: 20,
scrollSpeed: 15,
format: this.SERIALIZE_RULE,
// these take arrays of elements or ids and can be
// used for better initialization performance
elements: false,
handles: false,
onChange: Prototype.emptyFunction,
onUpdate: Prototype.emptyFunction
}, arguments[1] || { });
// clear any old sortable with same element
this.destroy(element);
// build options for the draggables
var options_for_draggable = {
revert: true,
quiet: options.quiet,
scroll: options.scroll,
scrollSpeed: options.scrollSpeed,
scrollSensitivity: options.scrollSensitivity,
delay: options.delay,
ghosting: options.ghosting,
constraint: options.constraint,
handle: options.handle };
if(options.starteffect)
options_for_draggable.starteffect = options.starteffect;
if(options.reverteffect)
options_for_draggable.reverteffect = options.reverteffect;
else
if(options.ghosting) options_for_draggable.reverteffect = function(element) {
element.style.top = 0;
element.style.left = 0;
};
if(options.endeffect)
options_for_draggable.endeffect = options.endeffect;
if(options.zindex)
options_for_draggable.zindex = options.zindex;
// build options for the droppables
var options_for_droppable = {
overlap: options.overlap,
containment: options.containment,
tree: options.tree,
hoverclass: options.hoverclass,
onHover: Sortable.onHover
};
var options_for_tree = {
onHover: Sortable.onEmptyHover,
overlap: options.overlap,
containment: options.containment,
hoverclass: options.hoverclass
};
// fix for gecko engine
Element.cleanWhitespace(element);
options.draggables = [];
options.droppables = [];
// drop on empty handling
if(options.dropOnEmpty || options.tree) {
Droppables.add(element, options_for_tree);
options.droppables.push(element);
}
(options.elements || this.findElements(element, options) || []).each( function(e,i) {
var handle = options.handles ? $(options.handles[i]) :
(options.handle ? $(e).select('.' + options.handle)[0] : e);
options.draggables.push(
new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
Droppables.add(e, options_for_droppable);
if(options.tree) e.treeNode = element;
options.droppables.push(e);
});
if(options.tree) {
(Sortable.findTreeElements(element, options) || []).each( function(e) {
Droppables.add(e, options_for_tree);
e.treeNode = element;
options.droppables.push(e);
});
}
// keep reference
this.sortables[element.identify()] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
},
// return all suitable-for-sortable elements in a guaranteed order
findElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.tag);
},
findTreeElements: function(element, options) {
return Element.findChildren(
element, options.only, options.tree ? true : false, options.treeTag);
},
onHover: function(element, dropon, overlap) {
if(Element.isParent(dropon, element)) return;
if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
return;
} else if(overlap>0.5) {
Sortable.mark(dropon, 'before');
if(dropon.previousSibling != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, dropon);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
} else {
Sortable.mark(dropon, 'after');
var nextElement = dropon.nextSibling || null;
if(nextElement != element) {
var oldParentNode = element.parentNode;
element.style.visibility = "hidden"; // fix gecko rendering
dropon.parentNode.insertBefore(element, nextElement);
if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);
Sortable.options(dropon.parentNode).onChange(element);
}
}
},
onEmptyHover: function(element, dropon, overlap) {
var oldParentNode = element.parentNode;
var droponOptions = Sortable.options(dropon);
if(!Element.isParent(dropon, element)) {
var index;
var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
var child = null;
if(children) {
var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
for (index = 0; index < children.length; index += 1) {
if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
offset -= Element.offsetSize (children[index], droponOptions.overlap);
} else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
child = index + 1 < children.length ? children[index + 1] : null;
break;
} else {
child = children[index];
break;
}
}
}
dropon.insertBefore(element, child);
Sortable.options(oldParentNode).onChange(element);
droponOptions.onChange(element);
}
},
unmark: function() {
if(Sortable._marker) Sortable._marker.hide();
},
mark: function(dropon, position) {
// mark on ghosting only
var sortable = Sortable.options(dropon.parentNode);
if(sortable && !sortable.ghosting) return;
if(!Sortable._marker) {
Sortable._marker =
($('dropmarker') || Element.extend(document.createElement('DIV'))).
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
var offsets = dropon.cumulativeOffset();
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
if(sortable.overlap == 'horizontal')
Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
else
Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
Sortable._marker.show();
},
_tree: function(element, options, parent) {
var children = Sortable.findElements(element, options) || [];
for (var i = 0; i < children.length; ++i) {
var match = children[i].id.match(options.format);
if (!match) continue;
var child = {
id: encodeURIComponent(match ? match[1] : null),
element: element,
parent: parent,
children: [],
position: parent.children.length,
container: $(children[i]).down(options.treeTag)
};
/* Get the element containing the children and recurse over it */
if (child.container)
this._tree(child.container, options, child);
parent.children.push (child);
}
return parent;
},
tree: function(element) {
element = $(element);
var sortableOptions = this.options(element);
var options = Object.extend({
tag: sortableOptions.tag,
treeTag: sortableOptions.treeTag,
only: sortableOptions.only,
name: element.id,
format: sortableOptions.format
}, arguments[1] || { });
var root = {
id: null,
parent: null,
children: [],
container: element,
position: 0
};
return Sortable._tree(element, options, root);
},
/* Construct a [i] index for a particular node */
_constructIndex: function(node) {
var index = '';
do {
if (node.id) index = '[' + node.position + ']' + index;
} while ((node = node.parent) != null);
return index;
},
sequence: function(element) {
element = $(element);
var options = Object.extend(this.options(element), arguments[1] || { });
return $(this.findElements(element, options) || []).map( function(item) {
return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
});
},
setSequence: function(element, new_sequence) {
element = $(element);
var options = Object.extend(this.options(element), arguments[2] || { });
var nodeMap = { };
this.findElements(element, options).each( function(n) {
if (n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
n.parentNode.removeChild(n);
});
new_sequence.each(function(ident) {
var n = nodeMap[ident];
if (n) {
n[1].appendChild(n[0]);
delete nodeMap[ident];
}
});
},
serialize: function(element) {
element = $(element);
var options = Object.extend(Sortable.options(element), arguments[1] || { });
var name = encodeURIComponent(
(arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
if (options.tree) {
return Sortable.tree(element, arguments[1]).children.map( function (item) {
return [name + Sortable._constructIndex(item) + "[id]=" +
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
}).flatten().join('&');
} else {
return Sortable.sequence(element, arguments[1]).map( function(item) {
return name + "[]=" + encodeURIComponent(item);
}).join('&');
}
}
};
// Returns true if child is contained within element
Element.isParent = function(child, element) {
if (!child.parentNode || child == element) return false;
if (child.parentNode == element) return true;
return Element.isParent(child.parentNode, element);
};
Element.findChildren = function(element, only, recursive, tagName) {
if(!element.hasChildNodes()) return null;
tagName = tagName.toUpperCase();
if(only) only = [only].flatten();
var elements = [];
$A(element.childNodes).each( function(e) {
if(e.tagName && e.tagName.toUpperCase()==tagName &&
(!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
elements.push(e);
if(recursive) {
var grandchildren = Element.findChildren(e, only, recursive, tagName);
if(grandchildren) elements.push(grandchildren);
}
});
return (elements.length>0 ? elements.flatten() : []);
};
Element.offsetSize = function (element, type) {
return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
};

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,202 @@
(function() {
Ajax.Responders.register({
onCreate: function(request) {
var token = $$('meta[name=csrf-token]')[0];
if (token) {
if (!request.options.requestHeaders) request.options.requestHeaders = {};
request.options.requestHeaders['X-CSRF-Token'] = token.readAttribute('content');
}
}
});
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
function isEventSupported(eventName) {
var el = document.createElement('div');
eventName = 'on' + eventName;
var isSupported = (eventName in el);
if (!isSupported) {
el.setAttribute(eventName, 'return;');
isSupported = typeof el[eventName] == 'function';
}
el = null;
return isSupported;
}
function isForm(element) {
return Object.isElement(element) && element.nodeName.toUpperCase() == 'FORM';
}
function isInput(element) {
if (Object.isElement(element)) {
var name = element.nodeName.toUpperCase();
return name == 'INPUT' || name == 'SELECT' || name == 'TEXTAREA';
}
else return false;
}
var submitBubbles = isEventSupported('submit'),
changeBubbles = isEventSupported('change');
if (!submitBubbles || !changeBubbles) {
// augment the Event.Handler class to observe custom events when needed
Event.Handler.prototype.initialize = Event.Handler.prototype.initialize.wrap(
function(init, element, eventName, selector, callback) {
init(element, eventName, selector, callback);
// is the handler being attached to an element that doesn't support this event?
if ( (!submitBubbles && this.eventName == 'submit' && !isForm(this.element)) ||
(!changeBubbles && this.eventName == 'change' && !isInput(this.element)) ) {
// "submit" => "emulated:submit"
this.eventName = 'emulated:' + this.eventName;
}
}
);
}
if (!submitBubbles) {
// discover forms on the page by observing focus events which always bubble
document.on('focusin', 'form', function(focusEvent, form) {
// special handler for the real "submit" event (one-time operation)
if (!form.retrieve('emulated:submit')) {
form.on('submit', function(submitEvent) {
var emulated = form.fire('emulated:submit', submitEvent, true);
// if custom event received preventDefault, cancel the real one too
if (emulated.returnValue === false) submitEvent.preventDefault();
});
form.store('emulated:submit', true);
}
});
}
if (!changeBubbles) {
// discover form inputs on the page
document.on('focusin', 'input, select, textarea', function(focusEvent, input) {
// special handler for real "change" events
if (!input.retrieve('emulated:change')) {
input.on('change', function(changeEvent) {
input.fire('emulated:change', changeEvent, true);
});
input.store('emulated:change', true);
}
});
}
function handleRemote(element) {
var method, url, params;
var event = element.fire("ajax:before");
if (event.stopped) return false;
if (element.tagName.toLowerCase() === 'form') {
method = element.readAttribute('method') || 'post';
url = element.readAttribute('action');
// serialize the form with respect to the submit button that was pressed
params = element.serialize({ submit: element.retrieve('rails:submit-button') });
// clear the pressed submit button information
element.store('rails:submit-button', null);
} else {
method = element.readAttribute('data-method') || 'get';
url = element.readAttribute('href');
params = {};
}
new Ajax.Request(url, {
method: method,
parameters: params,
evalScripts: true,
onCreate: function(response) { element.fire("ajax:create", response); },
onComplete: function(response) { element.fire("ajax:complete", response); },
onSuccess: function(response) { element.fire("ajax:success", response); },
onFailure: function(response) { element.fire("ajax:failure", response); }
});
element.fire("ajax:after");
}
function insertHiddenField(form, name, value) {
form.insert(new Element('input', { type: 'hidden', name: name, value: value }));
}
function handleMethod(element) {
var method = element.readAttribute('data-method'),
url = element.readAttribute('href'),
csrf_param = $$('meta[name=csrf-param]')[0],
csrf_token = $$('meta[name=csrf-token]')[0];
var form = new Element('form', { method: "POST", action: url, style: "display: none;" });
$(element.parentNode).insert(form);
if (method !== 'post') {
insertHiddenField(form, '_method', method);
}
if (csrf_param) {
insertHiddenField(form, csrf_param.readAttribute('content'), csrf_token.readAttribute('content'));
}
form.submit();
}
function disableFormElements(form) {
form.select('input[type=submit][data-disable-with]').each(function(input) {
input.store('rails:original-value', input.getValue());
input.setValue(input.readAttribute('data-disable-with')).disable();
});
}
function enableFormElements(form) {
form.select('input[type=submit][data-disable-with]').each(function(input) {
input.setValue(input.retrieve('rails:original-value')).enable();
});
}
function allowAction(element) {
var message = element.readAttribute('data-confirm');
return !message || confirm(message);
}
document.on('click', 'a[data-confirm], a[data-remote], a[data-method]', function(event, link) {
if (!allowAction(link)) {
event.stop();
return false;
}
if (link.readAttribute('data-remote')) {
handleRemote(link);
event.stop();
} else if (link.readAttribute('data-method')) {
handleMethod(link);
event.stop();
}
});
document.on("click", "form input[type=submit], form button[type=submit], form button:not([type])", function(event, button) {
// register the pressed submit button
event.findElement('form').store('rails:submit-button', button.name || false);
});
document.on("submit", function(event) {
var form = event.findElement();
if (!allowAction(form)) {
event.stop();
return false;
}
if (form.readAttribute('data-remote')) {
handleRemote(form);
event.stop();
} else {
disableFormElements(form);
}
});
document.on('ajax:create', 'form', function(event, form) {
if (form == event.findElement()) disableFormElements(form);
});
document.on('ajax:complete', 'form', function(event, form) {
if (form == event.findElement()) enableFormElements(form);
});
})();

View file

@ -0,0 +1,8 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
APP_PATH = File.expand_path('../../config/application', __FILE__)
require File.expand_path('../../config/boot', __FILE__)
require 'rails/commands'

View file

@ -0,0 +1,7 @@
# frozen_string_literal: true
# Define a bare test case to use with Capybara
class ActiveSupport::IntegrationCase < ActiveSupport::TestCase
# include Capybara::DSL
include Rails.application.routes.url_helpers
end

View file

@ -0,0 +1,62 @@
# frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
# Configure Rails Envinronment
ENV["RAILS_ENV"] = "test"
require 'rails'
require 'rails/test_help'
require 'stringio'
require 'pathname'
require 'derailed_benchmarks'
require File.expand_path("../rails_app/config/environment.rb", __FILE__)
require "rails/test_help"
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.default_url_options[:host] = "test.com"
Rails.backtrace_cleaner.remove_silencers!
# Configure capybara for integration testing
require "capybara/rails"
Capybara.default_driver = :rack_test
Capybara.default_selector = :css
require_relative "rails_app/config/environment"
ActiveRecord::Migrator.migrations_paths = [File.expand_path("../rails_app/db/migrate", __dir__)]
if Rails.gem_version >= Gem::Version.new('5.2.0')
ActiveRecord::MigrationContext
.new(File.expand_path("../rails_app/db/migrate/", __FILE__))
.migrate
else
ActiveRecord::Migrator.migrate(File.expand_path("../rails_app/db/migrate/", __FILE__))
end
# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
class ActiveSupport::IntegrationCase
def assert_has_content?(content)
assert has_content?(content), "Expected #{page.body} to include #{content.inspect}"
end
end
def fixtures_dir(name = "")
root_path("test/fixtures").join(name)
end
def root_path(name = "")
Pathname.new(File.expand_path("../..", __FILE__)).join(name)
end
def rails_app_path(name = "")
root_path("test/rails_app").join(name)
end