Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Upgrade to Rails 3

  • Loading branch information...
commit 1233fcdd0e98485feeb2965262dde25d7bf53156 1 parent 4e124f4
@nertzy authored
Showing with 4,525 additions and 2,524 deletions.
  1. +5 −3 .gitignore
  2. +2 −4 Gemfile
  3. +71 −36 Gemfile.lock
  4. +142 −129 README
  5. +2 −5 Rakefile
  6. +0 −1  app/helpers/application_helper.rb
  7. +5 −7 app/models/status.rb
  8. +1 −1  app/views/statuses/show.html.erb
  9. +1 −7 app/views/users/show.html.erb
  10. +1 −1  app/views/welcome/index.html.erb
  11. +4 −0 config.ru
  12. +42 −0 config/application.rb
  13. +4 −122 config/boot.rb
  14. +4 −40 config/environment.rb
  15. +21 −14 config/environments/development.rb
  16. +41 −21 config/environments/production.rb
  17. +35 −28 config/environments/test.rb
  18. +2 −2 config/initializers/backtrace_silencers.rb
  19. +1 −1  config/initializers/inflections.rb
  20. +0 −21 config/initializers/new_rails_defaults.rb
  21. +7 −0 config/initializers/secret_token.rb
  22. +7 −6 config/initializers/session_store.rb
  23. +1 −1  config/locales/en.yml
  24. +5 −47 config/routes.rb
  25. +2 −2 db/seeds.rb
  26. +2 −0  doc/README_FOR_APP
  27. 0  lib/tasks/.gitkeep
  28. +15 −19 public/404.html
  29. +15 −19 public/422.html
  30. +14 −18 public/500.html
  31. +5 −3 public/javascripts/controls.js
  32. +7 −6 public/javascripts/dragdrop.js
  33. +8 −13 public/javascripts/effects.js
  34. +3,381 −1,700 public/javascripts/prototype.js
  35. +191 −0 public/javascripts/rails.js
  36. 0  public/stylesheets/.gitkeep
  37. +6 −0 script/rails
  38. +2 −2 test/performance/browsing_test.rb
  39. +2 −27 test/test_helper.rb
  40. +0 −90 vendor/plugins/rails_xss/README.markdown
  41. +0 −14 vendor/plugins/rails_xss/init.rb
  42. +0 −1  vendor/plugins/rails_xss/install.rb
  43. +0 −17 vendor/plugins/rails_xss/lib/av_patch.rb
  44. +0 −39 vendor/plugins/rails_xss/lib/rails_xss.rb
  45. +0 −20 vendor/plugins/rails_xss/lib/rails_xss_escaping.rb
  46. +0 −4 vendor/plugins/rails_xss/tasks/rails_xss_tasks.rake
  47. +0 −24 vendor/plugins/rails_xss/test/rails_xss_test.rb
  48. +0 −3  vendor/plugins/rails_xss/test/test_helper.rb
  49. +0 −1  vendor/plugins/rails_xss/uninstall.rb
  50. +1 −1  vendor/plugins/{rails_xss → verification}/MIT-LICENSE
  51. +34 −0 vendor/plugins/verification/README
  52. +3 −4 vendor/plugins/{rails_xss → verification}/Rakefile
  53. +3 −0  vendor/plugins/verification/init.rb
  54. +132 −0 vendor/plugins/verification/lib/action_controller/verification.rb
  55. +20 −0 vendor/plugins/verification/test/test_helper.rb
  56. +278 −0 vendor/plugins/verification/test/verification_test.rb
View
8 .gitignore
@@ -1,10 +1,12 @@
-.DS_Store
+.bundle
+db/*.sqlite3
log/*.log
-tmp/**/*
+tmp/
+.DS_Store
tmp/restart.txt
config/database.yml
config/initializers/fleakr.rb
config/initializers/yahoo.rb
db/*.sqlite3
bin/*
-public/statuses/*
+public/statuses/*
View
6 Gemfile
@@ -1,15 +1,13 @@
source :rubygems
-gem "rails", "2.3.5"
+gem "rails", "3.0.4"
gem "dalli"
gem "system_timer"
-gem "RubyInline"
-gem "erubis"
gem "pg"
gem "grackle"
gem "addressable"
gem "term_extraction", "0.1.4"
-gem "fleakr", "0.6.3"
+gem "fleakr"
group :test do
gem "ruby-debug"
View
107 Gemfile.lock
@@ -1,83 +1,118 @@
GEM
remote: http://rubygems.org/
specs:
- RubyInline (3.8.6)
- ZenTest (~> 4.3)
- ZenTest (4.4.0)
+ ZenTest (4.4.2)
abstract (1.0.0)
- actionmailer (2.3.5)
- actionpack (= 2.3.5)
- actionpack (2.3.5)
- activesupport (= 2.3.5)
- rack (~> 1.0.0)
- activerecord (2.3.5)
- activesupport (= 2.3.5)
- activeresource (2.3.5)
- activesupport (= 2.3.5)
- activesupport (2.3.5)
- addressable (2.2.2)
- columnize (0.3.1)
+ actionmailer (3.0.4)
+ actionpack (= 3.0.4)
+ mail (~> 2.2.15)
+ actionpack (3.0.4)
+ activemodel (= 3.0.4)
+ activesupport (= 3.0.4)
+ builder (~> 2.1.2)
+ erubis (~> 2.6.6)
+ i18n (~> 0.4)
+ rack (~> 1.2.1)
+ rack-mount (~> 0.6.13)
+ rack-test (~> 0.5.7)
+ tzinfo (~> 0.3.23)
+ activemodel (3.0.4)
+ activesupport (= 3.0.4)
+ builder (~> 2.1.2)
+ i18n (~> 0.4)
+ activerecord (3.0.4)
+ activemodel (= 3.0.4)
+ activesupport (= 3.0.4)
+ arel (~> 2.0.2)
+ tzinfo (~> 0.3.23)
+ activeresource (3.0.4)
+ activemodel (= 3.0.4)
+ activesupport (= 3.0.4)
+ activesupport (3.0.4)
+ addressable (2.2.4)
+ arel (2.0.8)
+ builder (2.1.2)
+ columnize (0.3.2)
configuration (1.2.0)
dalli (1.0.2)
erubis (2.6.6)
abstract (>= 1.0.0)
- fleakr (0.6.3)
- activesupport (>= 2.0)
+ fleakr (0.7.1)
hpricot (>= 0.6.164)
loggable (>= 0.2.0)
grackle (0.1.10)
json
mime-types
oauth
- heroku (1.17.10)
- json (~> 1.4.6)
+ heroku (1.16.2)
+ json_pure (>= 1.2.0, < 1.5.0)
launchy (~> 0.3.2)
rest-client (>= 1.4.0, < 1.7.0)
- hpricot (0.8.2)
- json (1.4.6)
+ hpricot (0.8.3)
+ i18n (0.5.0)
+ json (1.5.1)
+ json_pure (1.4.6)
launchy (0.3.7)
configuration (>= 0.0.5)
rake (>= 0.8.1)
linecache (0.43)
loggable (0.3.0)
+ mail (2.2.15)
+ activesupport (>= 2.3.6)
+ i18n (>= 0.4.0)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
mime-types (1.16)
nokogiri (1.4.4)
oauth (0.4.4)
pg (0.10.1)
- rack (1.0.1)
- rails (2.3.5)
- actionmailer (= 2.3.5)
- actionpack (= 2.3.5)
- activerecord (= 2.3.5)
- activeresource (= 2.3.5)
- activesupport (= 2.3.5)
- rake (>= 0.8.3)
+ polyglot (0.3.1)
+ rack (1.2.1)
+ rack-mount (0.6.13)
+ rack (>= 1.0.0)
+ rack-test (0.5.7)
+ rack (>= 1.0)
+ rails (3.0.4)
+ actionmailer (= 3.0.4)
+ actionpack (= 3.0.4)
+ activerecord (= 3.0.4)
+ activeresource (= 3.0.4)
+ activesupport (= 3.0.4)
+ bundler (~> 1.0)
+ railties (= 3.0.4)
+ railties (3.0.4)
+ actionpack (= 3.0.4)
+ activesupport (= 3.0.4)
+ rake (>= 0.8.7)
+ thor (~> 0.14.4)
rake (0.8.7)
rest-client (1.6.1)
mime-types (>= 1.16)
- ruby-debug (0.10.3)
+ ruby-debug (0.10.4)
columnize (>= 0.1)
- ruby-debug-base (~> 0.10.3.0)
- ruby-debug-base (0.10.3)
+ ruby-debug-base (~> 0.10.4.0)
+ ruby-debug-base (0.10.4)
linecache (>= 0.3)
system_timer (1.0)
term_extraction (0.1.4)
nokogiri (>= 1.0.7)
+ thor (0.14.6)
+ treetop (1.4.9)
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.24)
PLATFORMS
ruby
DEPENDENCIES
- RubyInline
ZenTest
addressable
dalli
- erubis
- fleakr (= 0.6.3)
+ fleakr
grackle
heroku
pg
- rails (= 2.3.5)
+ rails (= 3.0.4)
ruby-debug
system_timer
term_extraction (= 0.1.4)
View
271 README
@@ -1,14 +1,15 @@
== Welcome to Rails
-Rails is a web-application framework that includes everything needed to create
-database-backed web applications according to the Model-View-Control pattern.
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
-This pattern splits the view (also called the presentation) into "dumb" templates
-that are primarily responsible for inserting pre-built data in between HTML tags.
-The model contains the "smart" domain objects (such as Account, Product, Person,
-Post) that holds all the business logic and knows how to persist themselves to
-a database. The controller handles the incoming requests (such as Save New Account,
-Update Product, Show Post) by manipulating the model and directing data to the view.
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
@@ -21,89 +22,40 @@ layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
-Rails. You can read more about Action Pack in
+Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
-1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
- and your application name. Ex: rails myapp
-2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
-3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
-4. Follow the guidelines to start developing your application
+1. At the command prompt, create a new Rails application:
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
-== Web Servers
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding Ruby on Rails!"
-By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
-with a variety of other web servers.
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
-Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
-suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
-getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
-More info at: http://mongrel.rubyforge.org
-
-Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
-Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
-FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
-
-== Apache .htaccess example for FCGI/CGI
-
-# General Apache options
-AddHandler fastcgi-script .fcgi
-AddHandler cgi-script .cgi
-Options +FollowSymLinks +ExecCGI
-
-# If you don't want Rails to look in certain directories,
-# use the following rewrite rules so that Apache won't rewrite certain requests
-#
-# Example:
-# RewriteCond %{REQUEST_URI} ^/notrails.*
-# RewriteRule .* - [L]
-
-# Redirect all requests not available on the filesystem to Rails
-# By default the cgi dispatcher is used which is very slow
-#
-# For better performance replace the dispatcher with the fastcgi one
-#
-# Example:
-# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
-RewriteEngine On
-
-# If your Rails application is accessed via an Alias directive,
-# then you MUST also set the RewriteBase in this htaccess file.
-#
-# Example:
-# Alias /myrailsapp /path/to/myrailsapp/public
-# RewriteBase /myrailsapp
-
-RewriteRule ^$ index.html [QSA]
-RewriteRule ^([^.]+)$ $1.html [QSA]
-RewriteCond %{REQUEST_FILENAME} !-f
-RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
-
-# In case Rails experiences terminal errors
-# Instead of displaying this message you can supply a file here which will be rendered instead
-#
-# Example:
-# ErrorDocument 500 /500.html
-
-ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
== Debugging Rails
-Sometimes your application goes wrong. Fortunately there are a lot of tools that
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
-First area to check is the application log files. Have "tail -f" commands running
-on the server.log and development.log. Rails will automatically display debugging
-and runtime information to these files. Debugging info will also be shown in the
-browser on requests from 127.0.0.1.
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
-You can also log your own messages directly into the log file from your code using
-the Ruby logger class from inside your controllers. Example:
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@@ -115,26 +67,27 @@ the Ruby logger class from inside your controllers. Example:
The result will be a message in your log file along the lines of:
- Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
More information on how to use the logger is at http://www.ruby-doc.org/core/
-Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
-* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
-* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
-These two online (and free) books will bring you up to speed on the Ruby language
-and also on programming in general.
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
== Debugger
-Debugger support is available through the debugger command when you start your Mongrel or
-Webrick server with --debugger. This means that you can break out of execution at any point
-in the code, investigate and change the model, AND then resume execution!
-You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'
-Example:
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
class WeblogController < ActionController::Base
def index
@@ -147,97 +100,157 @@ So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
- => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
- #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
-...and even better is that you can examine how your runtime objects actually work:
+...and even better, you can examine how your runtime objects actually work:
>> f = @posts.first
=> #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
-Finally, when you're ready to resume execution, you enter "cont"
+Finally, when you're ready to resume execution, you can enter "cont".
== Console
-You can interact with the domain model by starting the console through <tt>script/console</tt>.
-Here you'll have all parts of the application configured, just like it is when the
-application is running. You can inspect domain models, change values, and save to the
-database. Starting the script without arguments will launch it in the development environment.
-Passing an argument will specify a different environment, like <tt>script/console production</tt>.
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+To reload your controllers and models after launching the console run
+<tt>reload!</tt>
+
+More information about irb can be found at:
+link:http://www.rubycentral.com/pickaxe/irb.html
-To reload your controllers and models after launching the console run <tt>reload!</tt>
== dbconsole
-You can go to the command line of your database directly through <tt>script/dbconsole</tt>.
-You would be connected to the database with the credentials defined in database.yml.
-Starting the script without arguments will connect you to the development database. Passing an
-argument will connect you to a different database, like <tt>script/dbconsole production</tt>.
-Currently works for mysql, postgresql and sqlite.
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
== Description of Contents
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- controllers
+ | |-- helpers
+ | |-- mailers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ |-- script
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ `-- plugins
+
app
Holds all the code that's specific to this particular application.
app/controllers
Holds controllers that should be named like weblogs_controller.rb for
- automated URL mapping. All controllers should descend from ApplicationController
- which itself descends from ActionController::Base.
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
app/models
- Holds models that should be named like post.rb.
- Most models will descend from ActiveRecord::Base.
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
app/views
Holds the template files for the view that should be named like
- weblogs/index.html.erb for the WeblogsController#index action. All views use eRuby
- syntax.
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
app/views/layouts
- Holds the template files for layouts to be used with views. This models the common
- header/footer method of wrapping views. In your views, define a layout using the
- <tt>layout :default</tt> and create a file named default.html.erb. Inside default.html.erb,
- call <% yield %> to render the view using this layout.
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
app/helpers
- Holds view helpers that should be named like weblogs_helper.rb. These are generated
- for you automatically when using script/generate for controllers. Helpers can be used to
- wrap functionality for your views into methods.
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
config
- Configuration files for the Rails environment, the routing map, the database, and other dependencies.
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
db
- Contains the database schema in schema.rb. db/migrate contains all
- the sequence of Migrations for your schema.
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
doc
- This directory is where your application documentation will be stored when generated
- using <tt>rake doc:app</tt>
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
lib
- Application specific libraries. Basically, any kind of custom code that doesn't
- belong under controllers, models, or helpers. This directory is in the load path.
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
public
- The directory available for the web server. Contains subdirectories for images, stylesheets,
- and javascripts. Also contains the dispatchers and the default HTML files. This should be
- set as the DOCUMENT_ROOT of your web server.
+ The directory available for the web server. Contains subdirectories for
+ images, stylesheets, and javascripts. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
script
Helper scripts for automation and generation.
test
- Unit and functional tests along with fixtures. When using the script/generate scripts, template
- test files will be generated for you and placed in this directory.
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
vendor
- External libraries that the application depends on. Also includes the plugins subdirectory.
- If the app has frozen rails, those gems also go here, under vendor/rails/.
- This directory is in the load path.
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
View
7 Rakefile
@@ -1,10 +1,7 @@
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
-require(File.join(File.dirname(__FILE__), 'config', 'boot'))
-
+require File.expand_path('../config/application', __FILE__)
require 'rake'
-require 'rake/testtask'
-require 'rake/rdoctask'
-require 'tasks/rails'
+Flittr::Application.load_tasks
View
1  app/helpers/application_helper.rb
@@ -1,3 +1,2 @@
-# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
end
View
12 app/models/status.rb
@@ -43,13 +43,11 @@ def photo
end
def flickr_photo
- Rails.cache.fetch("#{cache_key}/flickr_photo", :raw => true) do
- query = terms.join
- photos = Fleakr.search(query.blank? ? 'lolcats' : query)
- photos = Fleakr.search(terms.first) if photos.empty? && terms.length > 1
- photos = Fleakr.search('lolcats') if photos.empty?
- photos.rand
- end
+ query = terms.join
+ photos = Fleakr.search(query.blank? ? 'lolcats' : query)
+ photos = Fleakr.search(terms.first) if photos.empty? && terms.length > 1
+ photos = Fleakr.search('lolcats') if photos.empty?
+ photos.sample
end
def cache_key
View
2  app/views/statuses/show.html.erb
@@ -6,7 +6,7 @@
background-color: #<%= @status.user.profile_background_color %>;
<% end -%>
-<%= render @status %>
+<%= render :partial => "statuses/status", :object => @status %>
<% if Rails.env.development? -%>
<%= raw debug(@status.terms) %>
View
8 app/views/users/show.html.erb
@@ -1,9 +1,3 @@
<% @page_title = "@#{@user.formatted_screen_name}" %>
<h1>@<%= @user.formatted_screen_name %></h1>
-<%= render @user.statuses %>
-
-<% if Rails.env.development? -%>
- <%= raw debug @user %>
- <%= raw debug @user.statuses.first %>
- <%= raw debug @user.record %>
-<% end -%>
+<%= render :partial => "statuses/status", :collection => @user.statuses %>
View
2  app/views/welcome/index.html.erb
@@ -4,7 +4,7 @@
<p>Welcome to Flittr! Flittr looks at publicly available Twitter statuses and tries to guess a good Flickr picture for it. This picture will permanently be associated with the status.</p>
<p>Right now, if it can't make a good guess, it will show you a lolcat instead.</p>
<p>It's slow due to the number of external API calls it makes, so expect to wait about a minute on the first load. After your page is generated, it will load much more quickly.</p>
- <% form_tag(search_path, {:class => 'search', :id => 'welcome_search_form'}) do -%>
+ <%= form_tag(search_path, {:class => 'search', :id => 'welcome_search_form'}) do -%>
<label>@<%= text_field_tag :screen_name, params[:screen_name] %></label>
<button type="submit">Look up by Twitter name</button>
<% if flash[:search_form_message] -%>
View
4 config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Flittr::Application
View
42 config/application.rb
@@ -0,0 +1,42 @@
+require File.expand_path('../boot', __FILE__)
+
+require 'rails/all'
+
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module Flittr
+ class Application < Rails::Application
+ # 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]
+ end
+end
View
126 config/boot.rb
@@ -1,124 +1,6 @@
-# Don't change this file!
-# Configure your app in config/environment.rb and config/environments/*.rb
+require 'rubygems'
-RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
-module Rails
- class << self
- def boot!
- unless booted?
- preinitialize
- pick_boot.run
- end
- end
-
- def booted?
- defined? Rails::Initializer
- end
-
- def pick_boot
- (vendor_rails? ? VendorBoot : GemBoot).new
- end
-
- def vendor_rails?
- File.exist?("#{RAILS_ROOT}/vendor/rails")
- end
-
- def preinitialize
- load(preinitializer_path) if File.exist?(preinitializer_path)
- end
-
- def preinitializer_path
- "#{RAILS_ROOT}/config/preinitializer.rb"
- end
- end
-
- class Boot
- def run
- load_initializer
- Rails::Initializer.run(:set_load_path)
- end
- end
-
- class VendorBoot < Boot
- def load_initializer
- require "#{RAILS_ROOT}/vendor/rails/railties/lib/initializer"
- Rails::Initializer.run(:install_gem_spec_stubs)
- Rails::GemDependency.add_frozen_gem_path
- end
- end
-
- class GemBoot < Boot
- def load_initializer
- self.class.load_rubygems
- load_rails_gem
- require 'initializer'
- end
-
- def load_rails_gem
- if version = self.class.gem_version
- gem 'rails', version
- else
- gem 'rails'
- end
- rescue Gem::LoadError => load_error
- $stderr.puts %(Missing the Rails #{version} gem. Please `gem install -v=#{version} rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.)
- exit 1
- end
-
- class << self
- def rubygems_version
- Gem::RubyGemsVersion rescue nil
- end
-
- def gem_version
- if defined? RAILS_GEM_VERSION
- RAILS_GEM_VERSION
- elsif ENV.include?('RAILS_GEM_VERSION')
- ENV['RAILS_GEM_VERSION']
- else
- parse_gem_version(read_environment_rb)
- end
- end
-
- def load_rubygems
- min_version = '1.3.2'
- require 'rubygems'
- unless rubygems_version >= min_version
- $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.)
- exit 1
- end
-
- rescue LoadError
- $stderr.puts %Q(Rails requires RubyGems >= #{min_version}. Please install RubyGems and try again: http://rubygems.rubyforge.org)
- exit 1
- end
-
- def parse_gem_version(text)
- $1 if text =~ /^[^#]*RAILS_GEM_VERSION\s*=\s*["']([!~<>=]*\s*[\d.]+)["']/
- end
-
- private
- def read_environment_rb
- File.read("#{RAILS_ROOT}/config/environment.rb")
- end
- end
- end
-end
-
-class Rails::Boot
- def run
- load_initializer
-
- Rails::Initializer.class_eval do
- def load_gems
- @bundler_loaded ||= Bundler.require :default, Rails.env
- end
- end
-
- Rails::Initializer.run(:set_load_path)
- end
-end
-
-# All that for this:
-Rails.boot!
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
View
44 config/environment.rb
@@ -1,41 +1,5 @@
-# Be sure to restart your server when you modify this file
+# Load the rails application
+require File.expand_path('../application', __FILE__)
-# Specifies gem version of Rails to use when vendor/rails is not present
-RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
-
-# Bootstrap the Rails environment, frameworks, and default configuration
-require File.join(File.dirname(__FILE__), 'boot')
-
-Rails::Initializer.run do |config|
- # Settings in config/environments/* take precedence over those specified here.
- # Application configuration should go into files in config/initializers
- # -- all .rb files in that directory are automatically loaded.
-
- # Add additional load paths for your own custom dirs
- # config.load_paths += %W( #{RAILS_ROOT}/extras )
-
- # Specify gems that this application depends on and have them installed with rake gems:install
- # config.gem "bj"
- # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
- # config.gem "sqlite3-ruby", :lib => "sqlite3"
- # config.gem "aws-s3", :lib => "aws/s3"
-
- # Only load the plugins named here, in the order given (default is alphabetical).
- # :all can be used as a placeholder for all plugins not explicitly named
- # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
-
- # Skip frameworks you're not going to use. To use Rails without a database,
- # you must remove the Active Record framework.
- # config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
-
- # Activate observers that should always be running
- # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
-
- # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
- # Run "rake -D time" for a list of tasks for finding time zone names.
- config.time_zone = 'UTC'
-
- # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
- # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')]
- # config.i18n.default_locale = :de
-end
+# Initialize the rails application
+Flittr::Application.initialize!
View
35 config/environments/development.rb
@@ -1,19 +1,26 @@
-# Settings specified here will take precedence over those in config/environment.rb
+Flittr::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
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the webserver when you make code changes.
+ config.cache_classes = false
-# Log error messages when you accidentally call methods on nil.
-config.whiny_nils = true
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
-# Show full error reports and disable caching
-config.action_controller.consider_all_requests_local = true
-config.action_view.debug_rjs = true
-config.action_controller.perform_caching = false
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_view.debug_rjs = true
+ config.action_controller.perform_caching = false
-# Don't care if the mailer can't send
-config.action_mailer.raise_delivery_errors = false
+ # 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
-config.cache_store = :mem_cache_store
View
62 config/environments/production.rb
@@ -1,29 +1,49 @@
-# Settings specified here will take precedence over those in config/environment.rb
+Flittr::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
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
-# Full error reports are disabled and caching is turned on
-config.action_controller.consider_all_requests_local = false
-config.action_controller.perform_caching = true
-config.action_view.cache_template_loading = true
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
-# See everything in the log (default is :info)
-# config.log_level = :debug
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
-# Use a different logger for distributed setups
-# config.logger = SyslogLogger.new
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
-# Use a different cache store in production
-require 'active_support/cache/dalli_store23'
-config.cache_store = :dalli_store
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
-# Enable serving of images, stylesheets, and javascripts from an asset server
-# config.action_controller.asset_host = "http://assets.example.com"
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
-# Disable delivery errors, bad email addresses will be ignored
-# config.action_mailer.raise_delivery_errors = false
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
-# Enable threaded mode
-# config.threadsafe!
+ # 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
63 config/environments/test.rb
@@ -1,28 +1,35 @@
-# Settings specified here will take precedence over those in config/environment.rb
-
-# The test environment is used exclusively to run your application's
-# test suite. You never need to work with it otherwise. Remember that
-# your test database is "scratch space" for the test suite and is wiped
-# and recreated between test runs. Don't rely on the data there!
-config.cache_classes = true
-
-# Log error messages when you accidentally call methods on nil.
-config.whiny_nils = true
-
-# Show full error reports and disable caching
-config.action_controller.consider_all_requests_local = true
-config.action_controller.perform_caching = false
-config.action_view.cache_template_loading = true
-
-# Disable request forgery protection in test environment
-config.action_controller.allow_forgery_protection = false
-
-# Tell Action Mailer not to deliver emails to the real world.
-# The :test delivery method accumulates sent emails in the
-# ActionMailer::Base.deliveries array.
-config.action_mailer.delivery_method = :test
-
-# Use SQL instead of Active Record's schema dumper when creating the test database.
-# This is necessary if your schema can't be completely dumped by the schema dumper,
-# like if you have constraints or database-specific column types
-# config.active_record.schema_format = :sql
+Flittr::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
4 config/initializers/backtrace_silencers.rb
@@ -3,5 +3,5 @@
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
-# You can also remove all the silencers if you're trying do debug a problem that might steem from framework code.
-# Rails.backtrace_cleaner.remove_silencers!
+# 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
2  config/initializers/inflections.rb
@@ -1,6 +1,6 @@
# Be sure to restart your server when you modify this file.
-# Add new inflection rules using the following format
+# 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'
View
21 config/initializers/new_rails_defaults.rb
@@ -1,21 +0,0 @@
-# Be sure to restart your server when you modify this file.
-
-# These settings change the behavior of Rails 2 apps and will be defaults
-# for Rails 3. You can remove this initializer when Rails 3 is released.
-
-if defined?(ActiveRecord)
- # Include Active Record class name as root for JSON serialized output.
- ActiveRecord::Base.include_root_in_json = true
-
- # Store the full class name (including module namespace) in STI type column.
- ActiveRecord::Base.store_full_sti_class = true
-end
-
-ActionController::Routing.generate_best_match = false
-
-# Use ISO 8601 format for JSON serialized times and dates.
-ActiveSupport.use_standard_json_time_format = true
-
-# Don't escape HTML entities in JSON, leave that for the #json_escape helper.
-# if you're including raw json in an HTML page.
-ActiveSupport.escape_html_entities_in_json = false
View
7 config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+Flittr::Application.config.secret_token = '3dd35145dc749b629e8a748eff4999e01c5e539eb1f578689dbef988a41f8e54ebf732e7c0655a5f415b43771687b4f7d0e387c82f9f82971207856bafc32266'
View
13 config/initializers/session_store.rb
@@ -1,7 +1,8 @@
-ActionController::Base.session = {
- :namespace => '_dalli-rails2_session',
- :secret => 'a9d5b3645da8e334cef0decf5fbf9537a31abf6818852f158a97e7b224fd8c812454d026623a6f5cc90dac28c856a91efca0ce02f91e7e29a62eee7a2a021514'
-}
+# Be sure to restart your server when you modify this file.
-require 'action_controller/session/dalli_store'
-ActionController::Base.session_store = :dalli_store
+Flittr::Application.config.session_store :cookie_store, :key => '_flittr_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")
+# Flittr::Application.config.session_store :active_record_store
View
2  config/locales/en.yml
@@ -2,4 +2,4 @@
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
- hello: "Hello world"
+ hello: "Hello world"
View
52 config/routes.rb
@@ -1,48 +1,6 @@
-ActionController::Routing::Routes.draw do |map|
- map.resources :users
-
- map.resources :statuses
-
- map.search 'search', :controller => 'search', :action => 'index'
- # The priority is based upon order of creation: first created -> highest priority.
-
- # Sample of regular route:
- # map.connect 'products/:id', :controller => 'catalog', :action => 'view'
- # Keep in mind you can assign values other than :controller and :action
-
- # Sample of named route:
- # map.purchase 'products/:id/purchase', :controller => 'catalog', :action => 'purchase'
- # This route can be invoked with purchase_url(:id => product.id)
-
- # Sample resource route (maps HTTP verbs to controller actions automatically):
- # map.resources :products
-
- # Sample resource route with options:
- # map.resources :products, :member => { :short => :get, :toggle => :post }, :collection => { :sold => :get }
-
- # Sample resource route with sub-resources:
- # map.resources :products, :has_many => [ :comments, :sales ], :has_one => :seller
-
- # Sample resource route with more complex sub-resources
- # map.resources :products do |products|
- # products.resources :comments
- # products.resources :sales, :collection => { :recent => :get }
- # end
-
- # Sample resource route within a namespace:
- # map.namespace :admin do |admin|
- # # Directs /admin/products/* to Admin::ProductsController (app/controllers/admin/products_controller.rb)
- # admin.resources :products
- # end
-
- # You can have the root of your site routed with map.root -- just remember to delete public/index.html.
- map.root :controller => "welcome"
-
- # See how all your routes lay out with "rake routes"
-
- # Install the default routes as the lowest priority.
- # Note: These default routes make all actions in every controller accessible via GET requests. You should
- # consider removing or commenting them out if you're using named routes and resources.
- # map.connect ':controller/:action/:id'
- # map.connect ':controller/:action/:id.:format'
+Flittr::Application.routes.draw do
+ resources :users
+ resources :statuses
+ post "search", :to => "search#index"
+ root :to => "welcome#index"
end
View
4 db/seeds.rb
@@ -2,6 +2,6 @@
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
-#
+#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
-# Major.create(:name => 'Daley', :city => cities.first)
+# Mayor.create(:name => 'Daley', :city => cities.first)
View
2  doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
View
0  lib/tasks/.gitkeep
No changes.
View
34 public/404.html
@@ -1,23 +1,19 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
+<!DOCTYPE html>
+<html>
<head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<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>
+ <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>
@@ -27,4 +23,4 @@
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
-</html>
+</html>
View
34 public/422.html
@@ -1,23 +1,19 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
+<!DOCTYPE html>
+<html>
<head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<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>
+ <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>
@@ -27,4 +23,4 @@
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
</body>
-</html>
+</html>
View
32 public/500.html
@@ -1,23 +1,19 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-
-<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
-
+<!DOCTYPE html>
+<html>
<head>
- <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<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>
+ <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>
View
8 public/javascripts/controls.js
@@ -1,6 +1,8 @@
-// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
-// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com)
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
// Contributors:
// Richard Livsey
// Rahul Bhargava
View
13 public/javascripts/dragdrop.js
@@ -1,5 +1,6 @@
-// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
-// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
+// script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//
// script.aculo.us is freely distributable under the terms of an MIT-style license.
// For details, see the script.aculo.us web site: http://script.aculo.us/
@@ -311,7 +312,7 @@ var Draggable = Class.create({
tag_name=='TEXTAREA')) return;
var pointer = [Event.pointerX(event), Event.pointerY(event)];
- var pos = Position.cumulativeOffset(this.element);
+ var pos = this.element.cumulativeOffset();
this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });
Draggables.activate(this);
@@ -454,7 +455,7 @@ var Draggable = Class.create({
},
draw: function(point) {
- var pos = Position.cumulativeOffset(this.element);
+ var pos = this.element.cumulativeOffset();
if(this.options.ghosting) {
var r = Position.realOffset(this.element);
pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
@@ -730,7 +731,7 @@ var Sortable = {
}
// keep reference
- this.sortables[element.id] = options;
+ this.sortables[element.identify()] = options;
// for onupdate
Draggables.addObserver(new SortableObserver(element, options.onUpdate));
@@ -825,7 +826,7 @@ var Sortable = {
hide().addClassName('dropmarker').setStyle({position:'absolute'});
document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
}
- var offsets = Position.cumulativeOffset(dropon);
+ var offsets = dropon.cumulativeOffset();
Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
if(position=='after')
View
21 public/javascripts/effects.js
@@ -1,4 +1,6 @@
-// Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// script.aculo.us effects.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
// Justin Palmer (http://encytemedia.com/)
// Mark Pilgrim (http://diveintomark.org/)
@@ -145,14 +147,13 @@ var Effect = {
'blind': ['BlindDown','BlindUp'],
'appear': ['Appear','Fade']
},
- toggle: function(element, effect) {
+ toggle: function(element, effect, options) {
element = $(element);
- effect = (effect || 'appear').toLowerCase();
- var options = Object.extend({
+ effect = (effect || 'appear').toLowerCase();
+
+ return Effect[ Effect.PAIRS[ effect ][ element.visible() ? 1 : 0 ] ](element, Object.extend({
queue: { position:'end', scope:(element.id || 'global'), limit: 1 }
- }, arguments[2] || { });
- Effect[element.visible() ?
- Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
+ }, options || {}));
}
};
@@ -228,12 +229,6 @@ Effect.Queue = Effect.Queues.get('global');
Effect.Base = Class.create({
position: null,
start: function(options) {
- function codeForEvent(options,eventName){
- return (
- (options[eventName+'Internal'] ? 'this.options.'+eventName+'Internal(this);' : '') +
- (options[eventName] ? 'this.options.'+eventName+'(this);' : '')
- );
- }
if (options && options.transition === false) options.transition = Effect.Transitions.linear;
this.options = Object.extend(Object.extend({ },Effect.DefaultOptions), options || { });
this.currentFrame = 0;
View
5,081 public/javascripts/prototype.js
3,381 additions, 1,700 deletions not shown
View
191 public/javascripts/rails.js
@@ -0,0 +1,191 @@
+(function() {
+ // 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, texarea', 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');
+ params = element.serialize();
+ } else {
+ method = element.readAttribute('data-method') || 'get';
+ url = element.readAttribute('href');
+ params = {};
+ }
+
+ new Ajax.Request(url, {
+ method: method,
+ parameters: params,
+ evalScripts: true,
+
+ onComplete: function(request) { element.fire("ajax:complete", request); },
+ onSuccess: function(request) { element.fire("ajax:success", request); },
+ onFailure: function(request) { element.fire("ajax:failure", request); }
+ });
+
+ element.fire("ajax:after");
+ }
+
+ 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') {
+ var field = new Element('input', { type: 'hidden', name: '_method', value: method });
+ form.insert(field);
+ }
+
+ if (csrf_param) {
+ var param = csrf_param.readAttribute('content'),
+ token = csrf_token.readAttribute('content'),
+ field = new Element('input', { type: 'hidden', name: param, value: token });
+ form.insert(field);
+ }
+
+ form.submit();
+ }
+
+
+ document.on("click", "*[data-confirm]", function(event, element) {
+ var message = element.readAttribute('data-confirm');
+ if (!confirm(message)) event.stop();
+ });
+
+ document.on("click", "a[data-remote]", function(event, element) {
+ if (event.stopped) return;
+ handleRemote(element);
+ event.stop();
+ });
+
+ document.on("click", "a[data-method]", function(event, element) {
+ if (event.stopped) return;
+ handleMethod(element);
+ event.stop();
+ });
+
+ document.on("submit", function(event) {
+ var element = event.findElement(),
+ message = element.readAttribute('data-confirm');
+ if (message && !confirm(message)) {
+ event.stop();
+ return false;
+ }
+
+ var inputs = element.select("input[type=submit][data-disable-with]");
+ inputs.each(function(input) {
+ input.disabled = true;
+ input.writeAttribute('data-original-value', input.value);
+ input.value = input.readAttribute('data-disable-with');
+ });
+
+ var element = event.findElement("form[data-remote]");
+ if (element) {
+ handleRemote(element);
+ event.stop();
+ }
+ });
+
+ document.on("ajax:after", "form", function(event, element) {
+ var inputs = element.select("input[type=submit][disabled=true][data-disable-with]");
+ inputs.each(function(input) {
+ input.value = input.readAttribute('data-original-value');
+ input.removeAttribute('data-original-value');
+ input.disabled = false;
+ });
+ });
+
+ Ajax.Responders.register({
+ onCreate: function(request) {
+ var csrf_meta_tag = $$('meta[name=csrf-token]')[0];
+
+ if (csrf_meta_tag) {
+ var header = 'X-CSRF-Token',
+ token = csrf_meta_tag.readAttribute('content');
+
+ if (!request.options.requestHeaders) {
+ request.options.requestHeaders = {};
+ }
+ request.options.requestHeaders[header] = token;
+ }
+ }
+ });
+})();
View
0  public/stylesheets/.gitkeep
No changes.
View
6 script/rails
@@ -0,0 +1,6 @@
+#!/usr/bin/env ruby
+# 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
4 test/performance/browsing_test.rb
@@ -1,8 +1,8 @@
require 'test_helper'
-require 'performance_test_help'
+require 'rails/performance_test_help'
# Profiling results for each test method are written to tmp/performance.
-class BrowsingTest < ActionController::PerformanceTest
+class BrowsingTest < ActionDispatch::PerformanceTest
def test_homepage
get '/'
end
View
29 test/test_helper.rb
@@ -1,33 +1,8 @@
ENV["RAILS_ENV"] = "test"
-require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
-require 'test_help'
+require File.expand_path('../../config/environment', __FILE__)
+require 'rails/test_help'
class ActiveSupport::TestCase
- # Transactional fixtures accelerate your tests by wrapping each test method
- # in a transaction that's rolled back on completion. This ensures that the
- # test database remains unchanged so your fixtures don't have to be reloaded
- # between every test method. Fewer database queries means faster tests.
- #
- # Read Mike Clark's excellent walkthrough at
- # http://clarkware.com/cgi/blosxom/2005/10/24#Rails10FastTesting
- #
- # Every Active Record database supports transactions except MyISAM tables
- # in MySQL. Turn off transactional fixtures in this case; however, if you
- # don't care one way or the other, switching from MyISAM to InnoDB tables
- # is recommended.
- #
- # The only drawback to using transactional fixtures is when you actually
- # need to test transactions. Since your test is bracketed by a transaction,
- # any transactions started in your code will be automatically rolled back.
- self.use_transactional_fixtures = true
-
- # Instantiated fixtures are slow, but give you @david where otherwise you
- # would need people(:david). If you don't want to migrate your existing
- # test cases which use the @david style and don't mind the speed hit (each
- # instantiated fixtures translates to a database query per test method),
- # then set this back to true.
- self.use_instantiated_fixtures = false
-
# Setup all fixtures in test/fixtures/*.(yml|csv) for all tests in alphabetical order.
#
# Note: You'll currently still have to declare fixtures explicitly in integration tests
View
90 vendor/plugins/rails_xss/README.markdown
@@ -1,90 +0,0 @@
-RailsXss
-========
-
-This plugin replaces the default ERB template handlers with erubis, and switches the behaviour to escape by default rather than requiring you to escape. This is consistent with the behaviour in Rails 3.0.
-
-Strings now have a notion of "html safe", which is false by default. Whenever rails copies a string into the response body it checks whether or not the string is safe, safe strings are copied verbatim into the response body, but unsafe strings are escaped first.
-
-All the XSS-proof helpers like link_to and form_tag now return safe strings, and will continue to work unmodified. If you have your own helpers which return strings you *know* are safe, you will need to explicitly tell rails that they're safe. For an example, take the following helper.
-
-
- def some_helper
- (1..5).map do |i|
- "<li>#{i}</li>"
- end.join("\n")
- end
-
-With this plugin installed, the html will be escaped. So you will need to do one of the following:
-
-1) Use the raw helper in your template. raw will ensure that your string is copied verbatim into the response body.
-
- <%= raw some_helper %>
-
-2) Mark the string as safe in the helper itself:
-
- def some_helper
- (1..5).map do |i|
- "<li>#{i}</li>"
- end.join("\n").html_safe!
- end
-
-3) Use the safe_helper meta programming method:
-
- module ApplicationHelper
- def some_helper
- #...
- end
- safe_helper :some_helper
- end
-
-Example
--------
-
-BEFORE:
-
- <%= params[:own_me] %> => XSS attack
- <%=h params[:own_me] %> => No XSS
- <%= @blog_post.content %> => Displays the HTML
-
-AFTER:
-
- <%= params[:own_me] %> => No XSS
- <%=h params[:own_me] %> => No XSS (same result)
- <%= @blog_post.content %> => *escapes* the HTML
- <%= raw @blog_post.content %> => Displays the HTML
-
-
-Gotchas
----
-
-#### textilize and simple_format do *not* return safe strings
-
-Both these methods support arbitrary HTML and are *not* safe to embed directly in your document. You'll need to do something like:
-
- <%= sanitize(textilize(@blog_post.content_textile)) %>
-
-#### Safe strings aren't magic.
-
-Once a string has been marked as safe, the only operations which will maintain that HTML safety are String#<<, String#concat and String#+. All other operations are safety ignorant so it's still probably possible to break your app if you're doing something like
-
- value = something_safe
- value.gsub!(/a/, params[:own_me])
-
-Don't do that.
-
-#### String interpolation won't be safe, even when it 'should' be
-
- value = "#{something_safe}#{something_else_safe}"
- value.html_safe? # => false
-
-This is intended functionality and can't be fixed.
-
-Getting Started
-===============
-
-1. Install rails 2.3.5 or higher, or freeze rails from 2-3-stable.
-2. Install erubis (gem install erubis)
-3. Install this plugin (ruby script/plugin install git://github.com/NZKoz/rails_xss.git)
-4. Report anything that breaks.
-
-Copyright (c) 2009 Koziarski Software Ltd, released under the MIT license. For full details see MIT-LICENSE included in this distribution.
View
14 vendor/plugins/rails_xss/init.rb
@@ -1,14 +0,0 @@
-# Include hook code here
-unless $gems_rake_task
- require 'erubis/helpers/rails_helper'
- require 'rails_xss'
-
- Erubis::Helpers::RailsHelper.engine_class = RailsXss::Erubis
-
- Module.class_eval do
- include RailsXss::SafeHelpers
- end
-
- require 'rails_xss_escaping'
- require 'av_patch'
-end
View
1  vendor/plugins/rails_xss/install.rb
@@ -1 +0,0 @@
-# Install hook code here
View
17 vendor/plugins/rails_xss/lib/av_patch.rb
@@ -1,17 +0,0 @@
-module AvPatch
- # Rails version of with_output_buffer uses '' as the default buf
- def with_output_buffer(buf = ActionView::SafeBuffer.new) #:nodoc:
- super(buf)
- end
-end
-
-ActionView::Base.send :include, AvPatch
-
-
-module ActionView
- class Base
- def self.xss_safe?
- true
- end
- end
-end
View
39 vendor/plugins/rails_xss/lib/rails_xss.rb
@@ -1,39 +0,0 @@
-# RailsXss
-module RailsXss
- class Erubis < ::Erubis::Eruby
- def add_preamble(src)
- src << "@output_buffer = ActionView::SafeBuffer.new;\n"
- end
-
- def add_text(src, text)
- src << "@output_buffer << ('" << escape_text(text) << "'.html_safe!);"
- end
-
- def add_expr_literal(src, code)
- src << '@output_buffer << ((' << code << ').to_s);'
- end
-
- def add_expr_escaped(src, code)
- src << '@output_buffer << ' << escaped_expr(code) << ';'
- end
-
- def add_postamble(src)
- src << '@output_buffer.to_s'
- end
-
- end
-
- module SafeHelpers
- def safe_helper(*names)
- names.each do |helper_method_name|
- aliased_target, punctuation = helper_method_name.to_s.sub(/([?!=])$/, ''), $1
- module_eval <<-END
- def #{aliased_target}_with_xss_safety#{punctuation}(*args, &block)
- raw(#{aliased_target}_without_xss_safety#{punctuation}(*args, &block))
- end
- END
- alias_method_chain helper_method_name, :xss_safety
- end
- end
- end
-end
View
20 vendor/plugins/rails_xss/lib/rails_xss_escaping.rb
@@ -1,20 +0,0 @@
-
-
-ERB::Util.module_eval do # :nodoc:
-
- def html_escape_with_output_safety(value)
- # Values which don't respond to html_safe, should be checked
- if value.respond_to?(:html_safe?) && value.html_safe?
- value
- else
- html_escape_without_output_safety(value).html_safe!
- end
- end
-
- alias_method_chain :html_escape, :output_safety
- alias h html_escape
-
- module_function :html_escape
- module_function :html_escape_without_output_safety
- module_function :h
-end
View
4 vendor/plugins/rails_xss/tasks/rails_xss_tasks.rake
@@ -1,4 +0,0 @@
-# desc "Explaining what the task does"
-# task :rails_xss do
-# # Task goes here
-# end
View
24 vendor/plugins/rails_xss/test/rails_xss_test.rb
@@ -1,24 +0,0 @@
-require 'test_helper'
-require 'rails_xss_escaping'
-
-class RailsXssTest < ActiveSupport::TestCase
- test "ERB::Util.h should mark its return value as safe and escape it" do
- escaped = ERB::Util.h("<p>")
- assert_equal "&lt;p&gt;", escaped
- assert escaped.html_safe?
- end
-
- test "ERB::Util.h should leave previously safe strings alone " do
- # TODO this seems easier to compose and reason about, but
- # this should be verified
- escaped = ERB::Util.h("<p>".html_safe!)
- assert_equal "<p>", escaped
- assert escaped.html_safe?
- end
-
- test "ERB::Util.h should not implode when passed a non-string" do
- assert_nothing_raised do
- assert_equal "1", ERB::Util.h(1)
- end
- end
-end
View
3  vendor/plugins/rails_xss/test/test_helper.rb
@@ -1,3 +0,0 @@
-require 'rubygems'
-require 'active_support'
-require 'active_support/test_case'
View
1  vendor/plugins/rails_xss/uninstall.rb
@@ -1 +0,0 @@
-# Uninstall hook code here
View
2  vendor/plugins/rails_xss/MIT-LICENSE → vendor/plugins/verification/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2009 Koziarski Software Ltd.
+Copyright (c) 2010 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
View
34 vendor/plugins/verification/README
@@ -0,0 +1,34 @@
+This module provides a class-level method for specifying that certain
+actions are guarded against being called without certain prerequisites
+being met. This is essentially a special kind of before_filter.
+
+An action may be guarded against being invoked without certain request
+parameters being set, or without certain session values existing.
+
+When a verification is violated, values may be inserted into the flash, and
+a specified redirection is triggered. If no specific action is configured,
+verification failures will by default result in a 400 Bad Request response.
+
+Usage:
+
+ class GlobalController < ActionController::Base
+ # Prevent the #update_settings action from being invoked unless
+ # the 'admin_privileges' request parameter exists. The
+ # settings action will be redirected to in current controller
+ # if verification fails.
+ verify :params => "admin_privileges", :only => :update_post,
+ :redirect_to => { :action => "settings" }
+
+ # Disallow a post from being updated if there was no information
+ # submitted with the post, and if there is no active post in the
+ # session, and if there is no "note" key in the flash. The route
+ # named category_url will be redirected to if verification fails.
+
+ verify :params => "post", :session => "post", "flash" => "note",
+ :only => :update_post,
+ :add_flash => { "alert" => "Failed to create your message" },
+ :redirect_to => :category_url
+
+Note that these prerequisites are not business rules. They do not examine
+the content of the session or the parameters. That level of validation should
+be encapsulated by your domain model or helper methods in the controller.
View
7 vendor/plugins/rails_xss/Rakefile → vendor/plugins/verification/Rakefile
@@ -5,18 +5,17 @@ require 'rake/rdoctask'
desc 'Default: run unit tests.'
task :default => :test
-desc 'Test the rails_xss plugin.'
+desc 'Test the verification plugin.'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
- t.verbose = true
end
-desc 'Generate documentation for the rails_xss plugin.'
+desc 'Generate documentation for the verification plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
- rdoc.title = 'RailsXss'
+ rdoc.title = 'Verification'
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.rdoc_files.include('README')
rdoc.rdoc_files.include('lib/**/*.rb')
View
3  vendor/plugins/verification/init.rb
@@ -0,0 +1,3 @@
+# Include hook code here
+
+require 'action_controller/verification'
View
132 vendor/plugins/verification/lib/action_controller/verification.rb
@@ -0,0 +1,132 @@
+module ActionController #:nodoc:
+ module Verification #:nodoc:
+ extend ActiveSupport::Concern
+
+ include AbstractController::Callbacks, Flash, Rendering
+
+ # This module provides a class-level method for specifying that certain
+ # actions are guarded against being called without certain prerequisites
+ # being met. This is essentially a special kind of before_filter.
+ #
+ # An action may be guarded against being invoked without certain request
+ # parameters being set, or without certain session values existing.
+ #
+ # When a verification is violated, values may be inserted into the flash, and
+ # a specified redirection is triggered. If no specific action is configured,
+ # verification failures will by default result in a 400 Bad Request response.
+ #
+ # Usage:
+ #
+ # class GlobalController < ActionController::Base
+ # # Prevent the #update_settings action from being invoked unless
+ # # the 'admin_privileges' request parameter exists. The
+ # # settings action will be redirected to in current controller
+ # # if verification fails.
+ # verify :params => "admin_privileges", :only => :update_post,
+ # :redirect_to => { :action => "settings" }
+ #
+ # # Disallow a post from being updated if there was no information
+ # # submitted with the post, and if there is no active post in the
+ # # session, and if there is no "note" key in the flash. The route
+ # # named category_url will be redirected to if verification fails.
+ #
+ # verify :params => "post", :session => "post", "flash" => "note",
+ # :only => :update_post,
+ # :add_flash => { "alert" => "Failed to create your message" },
+ # :redirect_to => :category_url
+ #
+ # Note that these prerequisites are not business rules. They do not examine
+ # the content of the session or the parameters. That level of validation should
+ # be encapsulated by your domain model or helper methods in the controller.
+ module ClassMethods
+ # Verify the given actions so that if certain prerequisites are not met,
+ # the user is redirected to a different action. The +options+ parameter
+ # is a hash consisting of the following key/value pairs:
+ #
+ # <tt>:params</tt>::
+ # a single key or an array of keys that must be in the <tt>params</tt>
+ # hash in order for the action(s) to be safely called.
+ # <tt>:session</tt>::
+ # a single key or an array of keys that must be in the <tt>session</tt>
+ # in order for the action(s) to be safely called.
+ # <tt>:flash</tt>::
+ # a single key or an array of keys that must be in the flash in order
+ # for the action(s) to be safely called.
+ # <tt>:method</tt>::
+ # a single key or an array of keys--any one of which must match the
+ # current request method in order for the action(s) to be safely called.
+ # (The key should be a symbol: <tt>:get</tt> or <tt>:post</tt>, for
+ # example.)
+ # <tt>:xhr</tt>::
+ # true/false option to ensure that the request is coming from an Ajax
+ # call or not.
+ # <tt>:add_flash</tt>::
+ # a hash of name/value pairs that should be merged into the session's
+ # flash if the prerequisites cannot be satisfied.
+ # <tt>:add_headers</tt>::
+ # a hash of name/value pairs that should be merged into the response's
+ # headers hash if the prerequisites cannot be satisfied.
+ # <tt>:redirect_to</tt>::
+ # the redirection parameters to be used when redirecting if the
+ # prerequisites cannot be satisfied. You can redirect either to named
+ # route or to the action in some controller.
+ # <tt>:render</tt>::
+ # the render parameters to be used when the prerequisites cannot be satisfied.
+ # <tt>:only</tt>::
+ # only apply this verification to the actions specified in the associated
+ # array (may also be a single value).
+ # <tt>:except</tt>::
+ # do not apply this verification to the actions specified in the associated
+ # array (may also be a single value).
+ def verify(options={})
+ before_filter :only => options[:only], :except => options[:except] do
+ verify_action options
+ end
+ end
+ end
+
+ private
+
+ def verify_action(options) #:nodoc:
+ if prereqs_invalid?(options)
+ flash.update(options[:add_flash]) if options[:add_flash]
+ response.headers.merge!(options[:add_headers]) if options[:add_headers]
+ apply_remaining_actions(options) unless performed?
+ end
+ end
+
+ def prereqs_invalid?(options) # :nodoc:
+ verify_presence_of_keys_in_hash_flash_or_params(options) ||
+ verify_method(options) ||
+ verify_request_xhr_status(options)
+ end
+
+ def verify_presence_of_keys_in_hash_flash_or_params(options) # :nodoc:
+ [*options[:params] ].find { |v| v && params[v.to_sym].nil? } ||
+ [*options[:session]].find { |v| session[v].nil? } ||
+ [*options[:flash] ].find { |v| flash[v].nil? }
+ end
+
+ def verify_method(options) # :nodoc:
+ [*options[:method]].all? { |v| request.request_method_symbol != v.to_sym } if options[:method]
+ end
+
+ def verify_request_xhr_status(options) # :nodoc:
+ request.xhr? != options[:xhr] unless options[:xhr].nil?
+ end
+
+ def apply_redirect_to(redirect_to_option) # :nodoc:
+ (redirect_to_option.is_a?(Symbol) && redirect_to_option != :back) ? self.__send__(redirect_to_option) : redirect_to_option
+ end
+
+ def apply_remaining_actions(options) # :nodoc:
+ case
+ when options[:render] ; render(options[:render])
+ when options[:redirect_to] ; redirect_to(apply_redirect_to(options[:redirect_to]))
+ else head(:bad_request)
+ end