aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib
diff options
context:
space:
mode:
authorrick <technoweenie@gmail.com>2008-09-20 13:00:20 -0700
committerrick <technoweenie@gmail.com>2008-09-20 13:00:20 -0700
commit22e830f883af0b56de81186c184751b6398d0141 (patch)
tree0de20fad9f3a7ce2e49d660d1243b5b02a32e290 /railties/lib
parent0aef9d1a2651fa0acd2adcd2de308eeb0ec8cdd2 (diff)
parenta3b7fa78bfdc33e45e39c095b67e02d50a2c7bea (diff)
downloadrails-22e830f883af0b56de81186c184751b6398d0141.tar.gz
rails-22e830f883af0b56de81186c184751b6398d0141.tar.bz2
rails-22e830f883af0b56de81186c184751b6398d0141.zip
Merge branch 'master' of git@github.com:rails/rails
Diffstat (limited to 'railties/lib')
-rw-r--r--railties/lib/commands/console.rb13
-rw-r--r--railties/lib/commands/dbconsole.rb2
-rw-r--r--railties/lib/commands/plugin.rb18
-rw-r--r--railties/lib/commands/process/spawner.rb4
-rw-r--r--railties/lib/initializer.rb3
-rw-r--r--railties/lib/rails_generator/generators/applications/app/app_generator.rb3
-rw-r--r--railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb1
-rw-r--r--railties/lib/rails_generator/secret_key_generator.rb152
-rw-r--r--railties/lib/tasks/databases.rake36
-rw-r--r--railties/lib/tasks/documentation.rake4
-rw-r--r--railties/lib/tasks/misc.rake7
11 files changed, 65 insertions, 178 deletions
diff --git a/railties/lib/commands/console.rb b/railties/lib/commands/console.rb
index 2b9d92f647..63df834639 100644
--- a/railties/lib/commands/console.rb
+++ b/railties/lib/commands/console.rb
@@ -1,11 +1,13 @@
irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'
require 'optparse'
+
options = { :sandbox => false, :irb => irb }
OptionParser.new do |opt|
opt.banner = "Usage: console [environment] [options]"
opt.on('-s', '--sandbox', 'Rollback database modifications on exit.') { |v| options[:sandbox] = v }
opt.on("--irb=[#{irb}]", 'Invoke a different irb.') { |v| options[:irb] = v }
+ opt.on("--debugger", 'Enable ruby-debugging for the console.') { |v| options[:debugger] = v }
opt.parse!(ARGV)
end
@@ -15,6 +17,17 @@ libs << " -r console_app"
libs << " -r console_sandbox" if options[:sandbox]
libs << " -r console_with_helpers"
+if options[:debugger]
+ begin
+ require 'ruby-debug'
+ libs << " -r ruby-debug"
+ puts "=> Debugger enabled"
+ rescue Exception
+ puts "You need to install ruby-debug to run the console in debugging mode. With gems, use 'gem install ruby-debug'"
+ exit
+ end
+end
+
ENV['RAILS_ENV'] = case ARGV.first
when "p"; "production"
when "d"; "development"
diff --git a/railties/lib/commands/dbconsole.rb b/railties/lib/commands/dbconsole.rb
index 5be3b5dd8e..6ff895aa30 100644
--- a/railties/lib/commands/dbconsole.rb
+++ b/railties/lib/commands/dbconsole.rb
@@ -6,7 +6,7 @@ include_password = false
OptionParser.new do |opt|
opt.banner = "Usage: dbconsole [options] [environment]"
- opt.on("-p", "--include-password", "Automatically provide the database from database.yml") do |v|
+ opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
include_password = true
end
opt.parse!(ARGV)
diff --git a/railties/lib/commands/plugin.rb b/railties/lib/commands/plugin.rb
index 980244a71b..9ff4739562 100644
--- a/railties/lib/commands/plugin.rb
+++ b/railties/lib/commands/plugin.rb
@@ -461,11 +461,11 @@ module Commands
o.on("-r", "--root=DIR", String,
"Set an explicit rails app directory.",
- "Default: #{@rails_root}") { |@rails_root| self.environment = RailsEnvironment.new(@rails_root) }
+ "Default: #{@rails_root}") { |rails_root| @rails_root = rails_root; self.environment = RailsEnvironment.new(@rails_root) }
o.on("-s", "--source=URL1,URL2", Array,
- "Use the specified plugin repositories instead of the defaults.") { |@sources|}
+ "Use the specified plugin repositories instead of the defaults.") { |sources| @sources = sources}
- o.on("-v", "--verbose", "Turn on verbose output.") { |$verbose| }
+ o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
o.on("-h", "--help", "Show this help message.") { puts o; exit }
o.separator ""
@@ -552,12 +552,12 @@ module Commands
o.separator "Options:"
o.separator ""
o.on( "-s", "--source=URL1,URL2", Array,
- "Use the specified plugin repositories.") {|@sources|}
+ "Use the specified plugin repositories.") {|sources| @sources = sources}
o.on( "--local",
- "List locally installed plugins.") {|@local| @remote = false}
+ "List locally installed plugins.") {|local| @local, @remote = local, false}
o.on( "--remote",
"List remotely available plugins. This is the default behavior",
- "unless --local is provided.") {|@remote|}
+ "unless --local is provided.") {|remote| @remote = remote}
end
end
@@ -598,7 +598,7 @@ module Commands
o.separator "Options:"
o.separator ""
o.on( "-c", "--check",
- "Report status of repository.") { |@sources|}
+ "Report status of repository.") { |sources| @sources = sources}
end
end
@@ -689,7 +689,7 @@ module Commands
o.separator "Options:"
o.separator ""
o.on( "-l", "--list",
- "List but don't prompt or add discovered repositories.") { |@list| @prompt = !@list }
+ "List but don't prompt or add discovered repositories.") { |list| @list, @prompt = list, !@list }
o.on( "-n", "--no-prompt",
"Add all new repositories without prompting.") { |v| @prompt = !v }
end
@@ -901,7 +901,7 @@ class RecursiveHTTPFetcher
def initialize(urls_to_fetch, level = 1, cwd = ".")
@level = level
@cwd = cwd
- @urls_to_fetch = urls_to_fetch.to_a
+ @urls_to_fetch = RUBY_VERSION >= '1.9' ? urls_to_fetch.lines : urls_to_fetch.to_a
@quiet = false
end
diff --git a/railties/lib/commands/process/spawner.rb b/railties/lib/commands/process/spawner.rb
index dc0008698a..8bf47abb75 100644
--- a/railties/lib/commands/process/spawner.rb
+++ b/railties/lib/commands/process/spawner.rb
@@ -181,10 +181,10 @@ ARGV.options do |opts|
opts.on(" Options:")
- opts.on("-p", "--port=number", Integer, "Starting port number (default: #{OPTIONS[:port]})") { |OPTIONS[:port]| }
+ opts.on("-p", "--port=number", Integer, "Starting port number (default: #{OPTIONS[:port]})") { |v| OPTIONS[:port] = v }
if spawner_class.can_bind_to_custom_address?
- opts.on("-a", "--address=ip", String, "Bind to IP address (default: #{OPTIONS[:address]})") { |OPTIONS[:address]| }
+ opts.on("-a", "--address=ip", String, "Bind to IP address (default: #{OPTIONS[:address]})") { |v| OPTIONS[:address] = v }
end
opts.on("-p", "--port=number", Integer, "Starting port number (default: #{OPTIONS[:port]})") { |v| OPTIONS[:port] = v }
diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb
index 008f1de8fa..74d2daa34b 100644
--- a/railties/lib/initializer.rb
+++ b/railties/lib/initializer.rb
@@ -488,7 +488,7 @@ Run `rake gems:install` to install the missing gems.
# If assigned value cannot be matched to a TimeZone, an exception will be raised.
def initialize_time_zone
if configuration.time_zone
- zone_default = Time.send!(:get_zone, configuration.time_zone)
+ zone_default = Time.__send__(:get_zone, configuration.time_zone)
unless zone_default
raise %{Value assigned to config.time_zone not recognized. Run "rake -D time" for a list of tasks for finding appropriate time zone names.}
end
@@ -784,7 +784,6 @@ Run `rake gems:install` to install the missing gems.
def threadsafe!
self.cache_classes = true
self.dependency_loading = false
- self.active_record.allow_concurrency = true
self.action_controller.allow_concurrency = true
self
end
diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb
index 80e8eabfd3..9849948339 100644
--- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb
+++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb
@@ -1,6 +1,5 @@
require 'rbconfig'
require 'digest/md5'
-require 'rails_generator/secret_key_generator'
class AppGenerator < Rails::Generator::Base
DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'],
@@ -36,7 +35,7 @@ class AppGenerator < Rails::Generator::Base
md5 << @app_name
# Do our best to generate a secure secret key for CookieStore
- secret = Rails::SecretKeyGenerator.new(@app_name).generate_secret
+ secret = ActiveSupport::SecureRandom.hex(64)
record do |m|
# Root directory and all subdirectories.
diff --git a/railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb b/railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb
index 1b7bcfef08..4de94076e9 100644
--- a/railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb
+++ b/railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb
@@ -1,7 +1,6 @@
require 'test_helper'
class <%= class_name %>Test < ActionMailer::TestCase
- tests <%= class_name %>
<% for action in actions -%>
test "<%= action %>" do
@expected.subject = '<%= class_name %>#<%= action %>'
diff --git a/railties/lib/rails_generator/secret_key_generator.rb b/railties/lib/rails_generator/secret_key_generator.rb
index 5ae492312e..553811d35d 100644
--- a/railties/lib/rails_generator/secret_key_generator.rb
+++ b/railties/lib/rails_generator/secret_key_generator.rb
@@ -5,160 +5,18 @@ module Rails
#
# generator = Rails::SecretKeyGenerator("some unique identifier, such as the application name")
# generator.generate_secret # => "f3f1be90053fa851... (some long string)"
+ #
+ # This class is *deprecated* in Rails 2.2 in favor of ActiveSupport::SecureRandom.
+ # It is currently a wrapper around ActiveSupport::SecureRandom.
class SecretKeyGenerator
- GENERATORS = [ :secure_random, :win32_api, :urandom, :openssl, :prng ].freeze
-
def initialize(identifier)
- @identifier = identifier
end
# Generate a random secret key with the best possible method available on
# the current platform.
def generate_secret
- generator = GENERATORS.find do |g|
- self.class.send("supports_#{g}?")
- end
- send("generate_secret_with_#{generator}")
- end
-
- # Generate a random secret key by using the Win32 API. Raises LoadError
- # if the current platform cannot make use of the Win32 API. Raises
- # SystemCallError if some other error occurred.
- def generate_secret_with_win32_api
- # Following code is based on David Garamond's GUID library for Ruby.
- require 'Win32API'
-
- crypt_acquire_context = Win32API.new("advapi32", "CryptAcquireContext",
- 'PPPII', 'L')
- crypt_gen_random = Win32API.new("advapi32", "CryptGenRandom",
- 'LIP', 'L')
- crypt_release_context = Win32API.new("advapi32", "CryptReleaseContext",
- 'LI', 'L')
- prov_rsa_full = 1
- crypt_verifycontext = 0xF0000000
-
- hProvStr = " " * 4
- if crypt_acquire_context.call(hProvStr, nil, nil, prov_rsa_full,
- crypt_verifycontext) == 0
- raise SystemCallError, "CryptAcquireContext failed: #{lastWin32ErrorMessage}"
- end
- hProv, = hProvStr.unpack('L')
- bytes = " " * 64
- if crypt_gen_random.call(hProv, bytes.size, bytes) == 0
- raise SystemCallError, "CryptGenRandom failed: #{lastWin32ErrorMessage}"
- end
- if crypt_release_context.call(hProv, 0) == 0
- raise SystemCallError, "CryptReleaseContext failed: #{lastWin32ErrorMessage}"
- end
- bytes.unpack("H*")[0]
- end
-
- # Generate a random secret key with Ruby 1.9's SecureRandom module.
- # Raises LoadError if the current Ruby version does not support
- # SecureRandom.
- def generate_secret_with_secure_random
- require 'securerandom'
- return SecureRandom.hex(64)
- end
-
- # Generate a random secret key with OpenSSL. If OpenSSL is not
- # already loaded, then this method will attempt to load it.
- # LoadError will be raised if that fails.
- def generate_secret_with_openssl
- require 'openssl'
- if !File.exist?("/dev/urandom")
- # OpenSSL transparently seeds the random number generator with
- # data from /dev/urandom. On platforms where that is not
- # available, such as Windows, we have to provide OpenSSL with
- # our own seed. Unfortunately there's no way to provide a
- # secure seed without OS support, so we'll have to do with
- # rand() and Time.now.usec().
- OpenSSL::Random.seed(rand(0).to_s + Time.now.usec.to_s)
- end
- data = OpenSSL::BN.rand(2048, -1, false).to_s
-
- if OpenSSL::OPENSSL_VERSION_NUMBER > 0x00908000
- OpenSSL::Digest::SHA512.new(data).hexdigest
- else
- generate_secret_with_prng
- end
+ ActiveSupport::SecureRandom.hex(64)
end
-
- # Generate a random secret key with /dev/urandom.
- # Raises SystemCallError on failure.
- def generate_secret_with_urandom
- return File.read("/dev/urandom", 64).unpack("H*")[0]
- end
-
- # Generate a random secret key with Ruby's pseudo random number generator,
- # as well as some environment information.
- #
- # This is the least cryptographically secure way to generate a secret key,
- # and should be avoided whenever possible.
- def generate_secret_with_prng
- require 'digest/sha2'
- sha = Digest::SHA2.new(512)
- now = Time.now
- sha << now.to_s
- sha << String(now.usec)
- sha << String(rand(0))
- sha << String($$)
- sha << @identifier
- return sha.hexdigest
- end
-
- private
- def lastWin32ErrorMessage
- # Following code is based on David Garamond's GUID library for Ruby.
- get_last_error = Win32API.new("kernel32", "GetLastError", '', 'L')
- format_message = Win32API.new("kernel32", "FormatMessageA",
- 'LPLLPLPPPPPPPP', 'L')
- format_message_ignore_inserts = 0x00000200
- format_message_from_system = 0x00001000
-
- code = get_last_error.call
- msg = "\0" * 1024
- len = format_message.call(format_message_ignore_inserts +
- format_message_from_system, 0,
- code, 0, msg, 1024, nil, nil,
- nil, nil, nil, nil, nil, nil)
- msg[0, len].tr("\r", '').chomp
- end
-
- def self.supports_secure_random?
- begin
- require 'securerandom'
- true
- rescue LoadError
- false
- end
- end
-
- def self.supports_win32_api?
- return false unless RUBY_PLATFORM =~ /(:?mswin|mingw)/
- begin
- require 'Win32API'
- true
- rescue LoadError
- false
- end
- end
-
- def self.supports_urandom?
- File.exist?('/dev/urandom')
- end
-
- def self.supports_openssl?
- begin
- require 'openssl'
- true
- rescue LoadError
- false
- end
- end
-
- def self.supports_prng?
- true
- end
+ deprecate :generate_secret=>"You should use ActiveSupport::SecureRandom.hex(64)"
end
end
diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake
index 21c81b3fb5..1431aa6944 100644
--- a/railties/lib/tasks/databases.rake
+++ b/railties/lib/tasks/databases.rake
@@ -28,8 +28,24 @@ namespace :db do
def create_database(config)
begin
- ActiveRecord::Base.establish_connection(config)
- ActiveRecord::Base.connection
+ if config['adapter'] =~ /sqlite/
+ if File.exist?(config['database'])
+ $stderr.puts "#{config['database']} already exists"
+ else
+ begin
+ # Create the SQLite database
+ ActiveRecord::Base.establish_connection(config)
+ ActiveRecord::Base.connection
+ rescue
+ $stderr.puts $!, *($!.backtrace)
+ $stderr.puts "Couldn't create database for #{config.inspect}"
+ end
+ end
+ return # Skip the else clause of begin/rescue
+ else
+ ActiveRecord::Base.establish_connection(config)
+ ActiveRecord::Base.connection
+ end
rescue
case config['adapter']
when 'mysql'
@@ -52,10 +68,6 @@ namespace :db do
$stderr.puts $!, *($!.backtrace)
$stderr.puts "Couldn't create database for #{config.inspect}"
end
- when 'sqlite'
- `sqlite "#{config['database']}"`
- when 'sqlite3'
- `sqlite3 "#{config['database']}"`
end
else
$stderr.puts "#{config['database']} already exists"
@@ -101,8 +113,16 @@ namespace :db do
end
namespace :migrate do
- desc 'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x'
- task :redo => [ 'db:rollback', 'db:migrate' ]
+ desc 'Rollbacks the database one migration and re migrate up. If you want to rollback more than one step, define STEP=x. Target specific version with VERSION=x.'
+ task :redo => :environment do
+ if ENV["VERSION"]
+ Rake::Task["db:migrate:down"].invoke
+ Rake::Task["db:migrate:up"].invoke
+ else
+ Rake::Task["db:rollback"].invoke
+ Rake::Task["db:migrate"].invoke
+ end
+ end
desc 'Resets your database using your migrations for the current environment'
task :reset => ["db:drop", "db:create", "db:migrate"]
diff --git a/railties/lib/tasks/documentation.rake b/railties/lib/tasks/documentation.rake
index f4927a0ef1..4ef838626a 100644
--- a/railties/lib/tasks/documentation.rake
+++ b/railties/lib/tasks/documentation.rake
@@ -1,9 +1,9 @@
namespace :doc do
- desc "Generate documentation for the application. Set custom template with TEMPLATE=/path/to/rdoc/template.rb"
+ desc "Generate documentation for the application. Set custom template with TEMPLATE=/path/to/rdoc/template.rb or title with TITLE=\"Custom Title\""
Rake::RDocTask.new("app") { |rdoc|
rdoc.rdoc_dir = 'doc/app'
rdoc.template = ENV['template'] if ENV['template']
- rdoc.title = "Rails Application Documentation"
+ rdoc.title = ENV['title'] || "Rails Application Documentation"
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.options << '--charset' << 'utf-8'
rdoc.rdoc_files.include('doc/README_FOR_APP')
diff --git a/railties/lib/tasks/misc.rake b/railties/lib/tasks/misc.rake
index 33bbba1101..5c99725203 100644
--- a/railties/lib/tasks/misc.rake
+++ b/railties/lib/tasks/misc.rake
@@ -3,10 +3,9 @@ task :environment do
require(File.join(RAILS_ROOT, 'config', 'environment'))
end
-require 'rails_generator/secret_key_generator'
-desc 'Generate a crytographically secure secret key. This is typically used to generate a secret for cookie sessions. Pass a unique identifier to the generator using ID="some unique identifier" for greater security.'
+desc 'Generate a crytographically secure secret key. This is typically used to generate a secret for cookie sessions.'
task :secret do
- puts Rails::SecretKeyGenerator.new(ENV['ID']).generate_secret
+ puts ActiveSupport::SecureRandom.hex(64)
end
require 'active_support'
@@ -54,4 +53,4 @@ namespace :time do
puts "\n"
end
end
-end \ No newline at end of file
+end