repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/core_ext/date_time/calculations.rb | provider/vendor/rails/activesupport/lib/active_support/core_ext/date_time/calculations.rb | require 'rational'
module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module DateTime #:nodoc:
# Enables the use of time calculations within DateTime itself
module Calculations
def self.included(base) #:nodoc:
base.extend ClassMethods
base.class_eval do
alias_method :compare_without_coercion, :<=>
alias_method :<=>, :compare_with_coercion
end
end
module ClassMethods
# DateTimes aren't aware of DST rules, so use a consistent non-DST offset when creating a DateTime with an offset in the local zone
def local_offset
::Time.local(2007).utc_offset.to_r / 86400
end
def current
::Time.zone_default ? ::Time.zone.now.to_datetime : ::Time.now.to_datetime
end
end
# Tells whether the DateTime object's datetime lies in the past
def past?
self < ::DateTime.current
end
# Tells whether the DateTime object's datetime lies in the future
def future?
self > ::DateTime.current
end
# Seconds since midnight: DateTime.now.seconds_since_midnight
def seconds_since_midnight
self.sec + (self.min * 60) + (self.hour * 3600)
end
# Returns a new DateTime where one or more of the elements have been changed according to the +options+ parameter. The time options
# (hour, minute, sec) reset cascadingly, so if only the hour is passed, then minute and sec is set to 0. If the hour and
# minute is passed, then sec is set to 0.
def change(options)
::DateTime.civil(
options[:year] || self.year,
options[:month] || self.month,
options[:day] || self.day,
options[:hour] || self.hour,
options[:min] || (options[:hour] ? 0 : self.min),
options[:sec] || ((options[:hour] || options[:min]) ? 0 : self.sec),
options[:offset] || self.offset,
options[:start] || self.start
)
end
# Uses Date to provide precise Time calculations for years, months, and days.
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
# <tt>:minutes</tt>, <tt>:seconds</tt>.
def advance(options)
d = to_date.advance(options)
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)
seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600
seconds_to_advance == 0 ? datetime_advanced_by_date : datetime_advanced_by_date.since(seconds_to_advance)
end
# Returns a new DateTime representing the time a number of seconds ago
# Do not use this method in combination with x.months, use months_ago instead!
def ago(seconds)
self.since(-seconds)
end
# Returns a new DateTime representing the time a number of seconds since the instance time
# Do not use this method in combination with x.months, use months_since instead!
def since(seconds)
self + Rational(seconds.round, 86400)
end
alias :in :since
# Returns a new DateTime representing the start of the day (0:00)
def beginning_of_day
change(:hour => 0)
end
alias :midnight :beginning_of_day
alias :at_midnight :beginning_of_day
alias :at_beginning_of_day :beginning_of_day
# Returns a new DateTime representing the end of the day (23:59:59)
def end_of_day
change(:hour => 23, :min => 59, :sec => 59)
end
# Adjusts DateTime to UTC by adding its offset value; offset is set to 0
#
# Example:
#
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)) # => Mon, 21 Feb 2005 10:11:12 -0600
# DateTime.civil(2005, 2, 21, 10, 11, 12, Rational(-6, 24)).utc # => Mon, 21 Feb 2005 16:11:12 +0000
def utc
new_offset(0)
end
alias_method :getutc, :utc
# Returns true if offset == 0
def utc?
offset == 0
end
# Returns the offset value in seconds
def utc_offset
(offset * 86400).to_i
end
# Layers additional behavior on DateTime#<=> so that Time and ActiveSupport::TimeWithZone instances can be compared with a DateTime
def compare_with_coercion(other)
other = other.comparable_time if other.respond_to?(:comparable_time)
other = other.to_datetime unless other.acts_like?(:date)
compare_without_coercion(other)
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/core_ext/numeric/time.rb | provider/vendor/rails/activesupport/lib/active_support/core_ext/numeric/time.rb | module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Numeric #:nodoc:
# Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years.
#
# These methods use Time#advance for precise date calculations when using from_now, ago, etc.
# as well as adding or subtracting their results from a Time object. For example:
#
# # equivalent to Time.now.advance(:months => 1)
# 1.month.from_now
#
# # equivalent to Time.now.advance(:years => 2)
# 2.years.from_now
#
# # equivalent to Time.now.advance(:months => 4, :years => 5)
# (4.months + 5.years).from_now
#
# While these methods provide precise calculation when used as in the examples above, care
# should be taken to note that this is not true if the result of `months', `years', etc is
# converted before use:
#
# # equivalent to 30.days.to_i.from_now
# 1.month.to_i.from_now
#
# # equivalent to 365.25.days.to_f.from_now
# 1.year.to_f.from_now
#
# In such cases, Ruby's core
# Date[http://stdlib.rubyonrails.org/libdoc/date/rdoc/index.html] and
# Time[http://stdlib.rubyonrails.org/libdoc/time/rdoc/index.html] should be used for precision
# date and time arithmetic
module Time
def seconds
ActiveSupport::Duration.new(self, [[:seconds, self]])
end
alias :second :seconds
def minutes
ActiveSupport::Duration.new(self * 60, [[:seconds, self * 60]])
end
alias :minute :minutes
def hours
ActiveSupport::Duration.new(self * 3600, [[:seconds, self * 3600]])
end
alias :hour :hours
def days
ActiveSupport::Duration.new(self * 24.hours, [[:days, self]])
end
alias :day :days
def weeks
ActiveSupport::Duration.new(self * 7.days, [[:days, self * 7]])
end
alias :week :weeks
def fortnights
ActiveSupport::Duration.new(self * 2.weeks, [[:days, self * 14]])
end
alias :fortnight :fortnights
# Reads best without arguments: 10.minutes.ago
def ago(time = ::Time.now)
time - self
end
# Reads best with argument: 10.minutes.until(time)
alias :until :ago
# Reads best with argument: 10.minutes.since(time)
def since(time = ::Time.now)
time + self
end
# Reads best without arguments: 10.minutes.from_now
alias :from_now :since
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/core_ext/numeric/conversions.rb | provider/vendor/rails/activesupport/lib/active_support/core_ext/numeric/conversions.rb | module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Numeric #:nodoc:
module Conversions
# Assumes self represents an offset from UTC in seconds (as returned from Time#utc_offset)
# and turns this into an +HH:MM formatted string. Example:
#
# -21_600.to_utc_offset_s # => "-06:00"
def to_utc_offset_s(colon=true)
seconds = self
sign = (seconds < 0 ? -1 : 1)
hours = seconds.abs / 3600
minutes = (seconds.abs % 3600) / 60
"%+03d%s%02d" % [ hours * sign, colon ? ":" : "", minutes ]
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/core_ext/numeric/bytes.rb | provider/vendor/rails/activesupport/lib/active_support/core_ext/numeric/bytes.rb | module ActiveSupport #:nodoc:
module CoreExtensions #:nodoc:
module Numeric #:nodoc:
# Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
module Bytes
KILOBYTE = 1024
MEGABYTE = KILOBYTE * 1024
GIGABYTE = MEGABYTE * 1024
TERABYTE = GIGABYTE * 1024
PETABYTE = TERABYTE * 1024
EXABYTE = PETABYTE * 1024
def bytes
self
end
alias :byte :bytes
def kilobytes
self * KILOBYTE
end
alias :kilobyte :kilobytes
def megabytes
self * MEGABYTE
end
alias :megabyte :megabytes
def gigabytes
self * GIGABYTE
end
alias :gigabyte :gigabytes
def terabytes
self * TERABYTE
end
alias :terabyte :terabytes
def petabytes
self * PETABYTE
end
alias :petabyte :petabytes
def exabytes
self * EXABYTE
end
alias :exabyte :exabytes
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/testing/declarative.rb | provider/vendor/rails/activesupport/lib/active_support/testing/declarative.rb | module ActiveSupport
module Testing
module Declarative
# test "verify something" do
# ...
# end
def test(name, &block)
test_name = "test_#{name.gsub(/\s+/,'_')}".to_sym
defined = instance_method(test_name) rescue false
raise "#{test_name} is already defined in #{self}" if defined
if block_given?
define_method(test_name, &block)
else
define_method(test_name) do
flunk "No implementation provided for #{name}"
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/testing/deprecation.rb | provider/vendor/rails/activesupport/lib/active_support/testing/deprecation.rb | require "active_support/core_ext/module"
module ActiveSupport
module Testing
module Deprecation #:nodoc:
def assert_deprecated(match = nil, &block)
result, warnings = collect_deprecations(&block)
assert !warnings.empty?, "Expected a deprecation warning within the block but received none"
if match
match = Regexp.new(Regexp.escape(match)) unless match.is_a?(Regexp)
assert warnings.any? { |w| w =~ match }, "No deprecation warning matched #{match}: #{warnings.join(', ')}"
end
result
end
def assert_not_deprecated(&block)
result, deprecations = collect_deprecations(&block)
assert deprecations.empty?, "Expected no deprecation warning within the block but received #{deprecations.size}: \n #{deprecations * "\n "}"
result
end
private
def collect_deprecations
old_behavior = ActiveSupport::Deprecation.behavior
deprecations = []
ActiveSupport::Deprecation.behavior = Proc.new do |message, callstack|
deprecations << message
end
result = yield
[result, deprecations]
ensure
ActiveSupport::Deprecation.behavior = old_behavior
end
end
end
end
begin
require 'test/unit/error'
module Test
module Unit
class Error # :nodoc:
# Silence warnings when reporting test errors.
def message_with_silenced_deprecation
ActiveSupport::Deprecation.silence do
message_without_silenced_deprecation
end
end
alias_method_chain :message, :silenced_deprecation
end
end
end
rescue LoadError
# Using miniunit, ignore.
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/testing/performance.rb | provider/vendor/rails/activesupport/lib/active_support/testing/performance.rb | require 'rubygems'
gem 'ruby-prof', '>= 0.6.1'
require 'ruby-prof'
require 'fileutils'
require 'rails/version'
module ActiveSupport
module Testing
module Performance
DEFAULTS =
if benchmark = ARGV.include?('--benchmark') # HAX for rake test
{ :benchmark => true,
:runs => 4,
:metrics => [:wall_time, :memory, :objects, :gc_runs, :gc_time],
:output => 'tmp/performance' }
else
{ :benchmark => false,
:runs => 1,
:min_percent => 0.01,
:metrics => [:process_time, :memory, :objects],
:formats => [:flat, :graph_html, :call_tree],
:output => 'tmp/performance' }
end.freeze
def self.included(base)
base.superclass_delegating_accessor :profile_options
base.profile_options = DEFAULTS
end
def full_test_name
"#{self.class.name}##{method_name}"
end
def run(result)
return if method_name =~ /^default_test$/
yield(self.class::STARTED, name)
@_result = result
run_warmup
if profile_options && metrics = profile_options[:metrics]
metrics.each do |metric_name|
if klass = Metrics[metric_name.to_sym]
run_profile(klass.new)
result.add_run
end
end
end
yield(self.class::FINISHED, name)
end
def run_test(metric, mode)
run_callbacks :setup
setup
metric.send(mode) { __send__ @method_name }
rescue ::Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue StandardError, ScriptError
add_error($!)
ensure
begin
teardown
run_callbacks :teardown, :enumerator => :reverse_each
rescue ::Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue StandardError, ScriptError
add_error($!)
end
end
protected
def run_warmup
GC.start
time = Metrics::Time.new
run_test(time, :benchmark)
puts "%s (%s warmup)" % [full_test_name, time.format(time.total)]
GC.start
end
def run_profile(metric)
klass = profile_options[:benchmark] ? Benchmarker : Profiler
performer = klass.new(self, metric)
performer.run
puts performer.report
performer.record
end
class Performer
delegate :run_test, :profile_options, :full_test_name, :to => :@harness
def initialize(harness, metric)
@harness, @metric = harness, metric
end
def report
rate = @total / profile_options[:runs]
'%20s: %s' % [@metric.name, @metric.format(rate)]
end
protected
def output_filename
"#{profile_options[:output]}/#{full_test_name}_#{@metric.name}"
end
end
class Benchmarker < Performer
def run
profile_options[:runs].to_i.times { run_test(@metric, :benchmark) }
@total = @metric.total
end
def record
avg = @metric.total / profile_options[:runs].to_i
now = Time.now.utc.xmlschema
with_output_file do |file|
file.puts "#{avg},#{now},#{environment}"
end
end
def environment
unless defined? @env
app = "#{$1}.#{$2}" if File.directory?('.git') && `git branch -v` =~ /^\* (\S+)\s+(\S+)/
rails = Rails::VERSION::STRING
if File.directory?('vendor/rails/.git')
Dir.chdir('vendor/rails') do
rails += ".#{$1}.#{$2}" if `git branch -v` =~ /^\* (\S+)\s+(\S+)/
end
end
ruby = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby'
ruby += "-#{RUBY_VERSION}.#{RUBY_PATCHLEVEL}"
@env = [app, rails, ruby, RUBY_PLATFORM] * ','
end
@env
end
protected
HEADER = 'measurement,created_at,app,rails,ruby,platform'
def with_output_file
fname = output_filename
if new = !File.exist?(fname)
FileUtils.mkdir_p(File.dirname(fname))
end
File.open(fname, 'ab') do |file|
file.puts(HEADER) if new
yield file
end
end
def output_filename
"#{super}.csv"
end
end
class Profiler < Performer
def initialize(*args)
super
@supported = @metric.measure_mode rescue false
end
def run
return unless @supported
RubyProf.measure_mode = @metric.measure_mode
RubyProf.start
RubyProf.pause
profile_options[:runs].to_i.times { run_test(@metric, :profile) }
@data = RubyProf.stop
@total = @data.threads.values.sum(0) { |method_infos| method_infos.sort.last.total_time }
end
def report
if @supported
super
else
'%20s: unsupported' % @metric.name
end
end
def record
return unless @supported
klasses = profile_options[:formats].map { |f| RubyProf.const_get("#{f.to_s.camelize}Printer") }.compact
klasses.each do |klass|
fname = output_filename(klass)
FileUtils.mkdir_p(File.dirname(fname))
File.open(fname, 'wb') do |file|
klass.new(@data).print(file, profile_options.slice(:min_percent))
end
end
end
protected
def output_filename(printer_class)
suffix =
case printer_class.name.demodulize
when 'FlatPrinter'; 'flat.txt'
when 'GraphPrinter'; 'graph.txt'
when 'GraphHtmlPrinter'; 'graph.html'
when 'CallTreePrinter'; 'tree.txt'
else printer_class.name.sub(/Printer$/, '').underscore
end
"#{super()}_#{suffix}"
end
end
module Metrics
def self.[](name)
const_get(name.to_s.camelize)
rescue NameError
nil
end
class Base
attr_reader :total
def initialize
@total = 0
end
def name
@name ||= self.class.name.demodulize.underscore
end
def measure_mode
self.class::Mode
end
def measure
0
end
def benchmark
with_gc_stats do
before = measure
yield
@total += (measure - before)
end
end
def profile
RubyProf.resume
yield
ensure
RubyProf.pause
end
protected
if GC.respond_to?(:enable_stats)
def with_gc_stats
GC.enable_stats
yield
ensure
GC.disable_stats
end
elsif defined?(GC::Profiler)
def with_gc_stats
GC.start
GC.disable
GC::Profiler.enable
yield
ensure
GC::Profiler.disable
GC.enable
end
else
def with_gc_stats
yield
end
end
end
class Time < Base
def measure
::Time.now.to_f
end
def format(measurement)
if measurement < 2
'%d ms' % (measurement * 1000)
else
'%.2f sec' % measurement
end
end
end
class ProcessTime < Time
Mode = RubyProf::PROCESS_TIME
def measure
RubyProf.measure_process_time
end
end
class WallTime < Time
Mode = RubyProf::WALL_TIME
def measure
RubyProf.measure_wall_time
end
end
class CpuTime < Time
Mode = RubyProf::CPU_TIME if RubyProf.const_defined?(:CPU_TIME)
def initialize(*args)
# FIXME: yeah my CPU is 2.33 GHz
RubyProf.cpu_frequency = 2.33e9
super
end
def measure
RubyProf.measure_cpu_time
end
end
class Memory < Base
Mode = RubyProf::MEMORY if RubyProf.const_defined?(:MEMORY)
# ruby-prof wrapper
if RubyProf.respond_to?(:measure_memory)
def measure
RubyProf.measure_memory / 1024.0
end
# Ruby 1.8 + railsbench patch
elsif GC.respond_to?(:allocated_size)
def measure
GC.allocated_size / 1024.0
end
# Ruby 1.8 + lloyd patch
elsif GC.respond_to?(:heap_info)
def measure
GC.heap_info['heap_current_memory'] / 1024.0
end
# Ruby 1.9 with total_malloc_allocated_size patch
elsif GC.respond_to?(:malloc_total_allocated_size)
def measure
GC.total_malloc_allocated_size / 1024.0
end
# Ruby 1.9 unpatched
elsif GC.respond_to?(:malloc_allocated_size)
def measure
GC.malloc_allocated_size / 1024.0
end
# Ruby 1.9 + GC profiler patch
elsif defined?(GC::Profiler)
def measure
GC.enable
GC.start
kb = GC::Profiler.data.last[:HEAP_USE_SIZE] / 1024.0
GC.disable
kb
end
end
def format(measurement)
'%.2f KB' % measurement
end
end
class Objects < Base
Mode = RubyProf::ALLOCATIONS if RubyProf.const_defined?(:ALLOCATIONS)
if RubyProf.respond_to?(:measure_allocations)
def measure
RubyProf.measure_allocations
end
# Ruby 1.8 + railsbench patch
elsif ObjectSpace.respond_to?(:allocated_objects)
def measure
ObjectSpace.allocated_objects
end
# Ruby 1.9 + GC profiler patch
elsif defined?(GC::Profiler)
def measure
GC.enable
GC.start
last = GC::Profiler.data.last
count = last[:HEAP_LIVE_OBJECTS] + last[:HEAP_FREE_OBJECTS]
GC.disable
count
end
end
def format(measurement)
measurement.to_i.to_s
end
end
class GcRuns < Base
Mode = RubyProf::GC_RUNS if RubyProf.const_defined?(:GC_RUNS)
if RubyProf.respond_to?(:measure_gc_runs)
def measure
RubyProf.measure_gc_runs
end
elsif GC.respond_to?(:collections)
def measure
GC.collections
end
elsif GC.respond_to?(:heap_info)
def measure
GC.heap_info['num_gc_passes']
end
end
def format(measurement)
measurement.to_i.to_s
end
end
class GcTime < Base
Mode = RubyProf::GC_TIME if RubyProf.const_defined?(:GC_TIME)
if RubyProf.respond_to?(:measure_gc_time)
def measure
RubyProf.measure_gc_time
end
elsif GC.respond_to?(:time)
def measure
GC.time
end
end
def format(measurement)
'%d ms' % (measurement / 1000)
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/testing/assertions.rb | provider/vendor/rails/activesupport/lib/active_support/testing/assertions.rb | module ActiveSupport
module Testing
module Assertions
# Test numeric difference between the return value of an expression as a result of what is evaluated
# in the yielded block.
#
# assert_difference 'Article.count' do
# post :create, :article => {...}
# end
#
# An arbitrary expression is passed in and evaluated.
#
# assert_difference 'assigns(:article).comments(:reload).size' do
# post :create, :comment => {...}
# end
#
# An arbitrary positive or negative difference can be specified. The default is +1.
#
# assert_difference 'Article.count', -1 do
# post :delete, :id => ...
# end
#
# An array of expressions can also be passed in and evaluated.
#
# assert_difference [ 'Article.count', 'Post.count' ], +2 do
# post :create, :article => {...}
# end
#
# A error message can be specified.
#
# assert_difference 'Article.count', -1, "An Article should be destroyed" do
# post :delete, :id => ...
# end
def assert_difference(expression, difference = 1, message = nil, &block)
b = block.send(:binding)
exps = Array.wrap(expression)
before = exps.map { |e| eval(e, b) }
yield
exps.each_with_index do |e, i|
error = "#{e.inspect} didn't change by #{difference}"
error = "#{message}.\n#{error}" if message
assert_equal(before[i] + difference, eval(e, b), error)
end
end
# Assertion that the numeric result of evaluating an expression is not changed before and after
# invoking the passed in block.
#
# assert_no_difference 'Article.count' do
# post :create, :article => invalid_attributes
# end
#
# A error message can be specified.
#
# assert_no_difference 'Article.count', "An Article should not be destroyed" do
# post :create, :article => invalid_attributes
# end
def assert_no_difference(expression, message = nil, &block)
assert_difference expression, 0, message, &block
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/testing/default.rb | provider/vendor/rails/activesupport/lib/active_support/testing/default.rb | module ActiveSupport
module Testing
module Default #:nodoc:
# Placeholder so test/unit ignores test cases without any tests.
def default_test
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb | provider/vendor/rails/activesupport/lib/active_support/testing/setup_and_teardown.rb | require 'active_support/callbacks'
module ActiveSupport
module Testing
module SetupAndTeardown
def self.included(base)
base.class_eval do
include ActiveSupport::Callbacks
define_callbacks :setup, :teardown
if defined?(MiniTest::Assertions) && TestCase < MiniTest::Assertions
include ForMiniTest
else
include ForClassicTestUnit
end
end
end
module ForMiniTest
def run(runner)
result = '.'
begin
run_callbacks :setup
result = super
rescue Exception => e
result = runner.puke(self.class, self.name, e)
ensure
begin
run_callbacks :teardown, :enumerator => :reverse_each
rescue Exception => e
result = runner.puke(self.class, self.name, e)
end
end
result
end
end
module ForClassicTestUnit
# For compatibility with Ruby < 1.8.6
PASSTHROUGH_EXCEPTIONS = Test::Unit::TestCase::PASSTHROUGH_EXCEPTIONS rescue [NoMemoryError, SignalException, Interrupt, SystemExit]
# This redefinition is unfortunate but test/unit shows us no alternative.
# Doubly unfortunate: hax to support Mocha's hax.
def run(result)
return if @method_name.to_s == "default_test"
if using_mocha = respond_to?(:mocha_verify)
assertion_counter_klass = if defined?(Mocha::TestCaseAdapter::AssertionCounter)
Mocha::TestCaseAdapter::AssertionCounter
else
Mocha::Integration::TestUnit::AssertionCounter
end
assertion_counter = assertion_counter_klass.new(result)
end
yield(Test::Unit::TestCase::STARTED, name)
@_result = result
begin
begin
run_callbacks :setup
setup
__send__(@method_name)
mocha_verify(assertion_counter) if using_mocha
rescue Mocha::ExpectationError => e
add_failure(e.message, e.backtrace)
rescue Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue Exception => e
raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
add_error(e)
ensure
begin
teardown
run_callbacks :teardown, :enumerator => :reverse_each
rescue Test::Unit::AssertionFailedError => e
add_failure(e.message, e.backtrace)
rescue Exception => e
raise if PASSTHROUGH_EXCEPTIONS.include?(e.class)
add_error(e)
end
end
ensure
mocha_teardown if using_mocha
end
result.add_run
yield(Test::Unit::TestCase::FINISHED, name)
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/xml_mini/libxml.rb | provider/vendor/rails/activesupport/lib/active_support/xml_mini/libxml.rb | require 'libxml'
# = XmlMini LibXML implementation
module ActiveSupport
module XmlMini_LibXML #:nodoc:
extend self
# Parse an XML Document string into a simple hash using libxml.
# string::
# XML Document string to parse
def parse(string)
LibXML::XML.default_keep_blanks = false
if string.blank?
{}
else
LibXML::XML::Parser.string(string.strip).parse.to_hash
end
end
end
end
module LibXML
module Conversions
module Document
def to_hash
root.to_hash
end
end
module Node
CONTENT_ROOT = '__content__'
LIB_XML_LIMIT = 30000000 # Hardcoded LibXML limit
# Convert XML document to hash
#
# hash::
# Hash to merge the converted element into.
def to_hash(hash={})
if text?
raise LibXML::XML::Error if content.length >= LIB_XML_LIMIT
hash[CONTENT_ROOT] = content
else
sub_hash = insert_name_into_hash(hash, name)
attributes_to_hash(sub_hash)
if array?
children_array_to_hash(sub_hash)
elsif yaml?
children_yaml_to_hash(sub_hash)
else
children_to_hash(sub_hash)
end
end
hash
end
protected
# Insert name into hash
#
# hash::
# Hash to merge the converted element into.
# name::
# name to to merge into hash
def insert_name_into_hash(hash, name)
sub_hash = {}
if hash[name]
if !hash[name].kind_of? Array
hash[name] = [hash[name]]
end
hash[name] << sub_hash
else
hash[name] = sub_hash
end
sub_hash
end
# Insert children into hash
#
# hash::
# Hash to merge the children into.
def children_to_hash(hash={})
each { |child| child.to_hash(hash) }
attributes_to_hash(hash)
hash
end
# Convert xml attributes to hash
#
# hash::
# Hash to merge the attributes into
def attributes_to_hash(hash={})
each_attr { |attr| hash[attr.name] = attr.value }
hash
end
# Convert array into hash
#
# hash::
# Hash to merge the array into
def children_array_to_hash(hash={})
hash[child.name] = map do |child|
returning({}) { |sub_hash| child.children_to_hash(sub_hash) }
end
hash
end
# Convert yaml into hash
#
# hash::
# Hash to merge the yaml into
def children_yaml_to_hash(hash = {})
hash[CONTENT_ROOT] = content unless content.blank?
hash
end
# Check if child is of type array
def array?
child? && child.next? && child.name == child.next.name
end
# Check if child is of type yaml
def yaml?
attributes.collect{|x| x.value}.include?('yaml')
end
end
end
end
LibXML::XML::Document.send(:include, LibXML::Conversions::Document)
LibXML::XML::Node.send(:include, LibXML::Conversions::Node)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/xml_mini/nokogiri.rb | provider/vendor/rails/activesupport/lib/active_support/xml_mini/nokogiri.rb | require 'nokogiri'
# = XmlMini Nokogiri implementation
module ActiveSupport
module XmlMini_Nokogiri #:nodoc:
extend self
# Parse an XML Document string into a simple hash using libxml / nokogiri.
# string::
# XML Document string to parse
def parse(string)
if string.blank?
{}
else
doc = Nokogiri::XML(string)
raise doc.errors.first if doc.errors.length > 0
doc.to_hash
end
end
module Conversions
module Document
def to_hash
root.to_hash
end
end
module Node
CONTENT_ROOT = '__content__'
# Convert XML document to hash
#
# hash::
# Hash to merge the converted element into.
def to_hash(hash = {})
hash[name] ||= attributes_as_hash
walker = lambda { |memo, parent, child, callback|
next if child.blank? && 'file' != parent['type']
if child.text?
(memo[CONTENT_ROOT] ||= '') << child.content
next
end
name = child.name
child_hash = child.attributes_as_hash
if memo[name]
memo[name] = [memo[name]].flatten
memo[name] << child_hash
else
memo[name] = child_hash
end
# Recusively walk children
child.children.each { |c|
callback.call(child_hash, child, c, callback)
}
}
children.each { |c| walker.call(hash[name], self, c, walker) }
hash
end
def attributes_as_hash
Hash[*(attribute_nodes.map { |node|
[node.node_name, node.value]
}.flatten)]
end
end
end
Nokogiri::XML::Document.send(:include, Conversions::Document)
Nokogiri::XML::Node.send(:include, Conversions::Node)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/xml_mini/rexml.rb | provider/vendor/rails/activesupport/lib/active_support/xml_mini/rexml.rb | # = XmlMini ReXML implementation
module ActiveSupport
module XmlMini_REXML #:nodoc:
extend self
CONTENT_KEY = '__content__'.freeze
# Parse an XML Document string into a simple hash
#
# Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
# and uses the defaults from ActiveSupport
#
# string::
# XML Document string to parse
def parse(string)
require 'rexml/document' unless defined?(REXML::Document)
doc = REXML::Document.new(string)
merge_element!({}, doc.root)
end
private
# Convert an XML element and merge into the hash
#
# hash::
# Hash to merge the converted element into.
# element::
# XML element to merge into hash
def merge_element!(hash, element)
merge!(hash, element.name, collapse(element))
end
# Actually converts an XML document element into a data structure.
#
# element::
# The document element to be collapsed.
def collapse(element)
hash = get_attributes(element)
if element.has_elements?
element.each_element {|child| merge_element!(hash, child) }
merge_texts!(hash, element) unless empty_content?(element)
hash
else
merge_texts!(hash, element)
end
end
# Merge all the texts of an element into the hash
#
# hash::
# Hash to add the converted emement to.
# element::
# XML element whose texts are to me merged into the hash
def merge_texts!(hash, element)
unless element.has_text?
hash
else
# must use value to prevent double-escaping
merge!(hash, CONTENT_KEY, element.texts.sum(&:value))
end
end
# Adds a new key/value pair to an existing Hash. If the key to be added
# already exists and the existing value associated with key is not
# an Array, it will be wrapped in an Array. Then the new value is
# appended to that Array.
#
# hash::
# Hash to add key/value pair to.
# key::
# Key to be added.
# value::
# Value to be associated with key.
def merge!(hash, key, value)
if hash.has_key?(key)
if hash[key].instance_of?(Array)
hash[key] << value
else
hash[key] = [hash[key], value]
end
elsif value.instance_of?(Array)
hash[key] = [value]
else
hash[key] = value
end
hash
end
# Converts the attributes array of an XML element into a hash.
# Returns an empty Hash if node has no attributes.
#
# element::
# XML element to extract attributes from.
def get_attributes(element)
attributes = {}
element.attributes.each { |n,v| attributes[n] = v }
attributes
end
# Determines if a document element has text content
#
# element::
# XML element to be checked.
def empty_content?(element)
element.texts.join.blank?
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/xml_mini/jdom.rb | provider/vendor/rails/activesupport/lib/active_support/xml_mini/jdom.rb | raise "JRuby is required to use the JDOM backend for XmlMini" unless RUBY_PLATFORM =~ /java/
require 'jruby'
include Java
import javax.xml.parsers.DocumentBuilder unless defined? DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory unless defined? DocumentBuilderFactory
import java.io.StringReader unless defined? StringReader
import org.xml.sax.InputSource unless defined? InputSource
import org.xml.sax.Attributes unless defined? Attributes
import org.w3c.dom.Node unless defined? Node
# = XmlMini JRuby JDOM implementation
module ActiveSupport
module XmlMini_JDOM #:nodoc:
extend self
CONTENT_KEY = '__content__'.freeze
NODE_TYPE_NAMES = %w{ATTRIBUTE_NODE CDATA_SECTION_NODE COMMENT_NODE DOCUMENT_FRAGMENT_NODE
DOCUMENT_NODE DOCUMENT_TYPE_NODE ELEMENT_NODE ENTITY_NODE ENTITY_REFERENCE_NODE NOTATION_NODE
PROCESSING_INSTRUCTION_NODE TEXT_NODE}
node_type_map = {}
NODE_TYPE_NAMES.each { |type| node_type_map[Node.send(type)] = type }
# Parse an XML Document string into a simple hash using Java's jdom.
# string::
# XML Document string to parse
def parse(string)
if string.blank?
{}
else
@dbf = DocumentBuilderFactory.new_instance
xml_string_reader = StringReader.new(string)
xml_input_source = InputSource.new(xml_string_reader)
doc = @dbf.new_document_builder.parse(xml_input_source)
merge_element!({}, doc.document_element)
end
end
private
# Convert an XML element and merge into the hash
#
# hash::
# Hash to merge the converted element into.
# element::
# XML element to merge into hash
def merge_element!(hash, element)
merge!(hash, element.tag_name, collapse(element))
end
# Actually converts an XML document element into a data structure.
#
# element::
# The document element to be collapsed.
def collapse(element)
hash = get_attributes(element)
child_nodes = element.child_nodes
if child_nodes.length > 0
for i in 0...child_nodes.length
child = child_nodes.item(i)
merge_element!(hash, child) unless child.node_type == Node.TEXT_NODE
end
merge_texts!(hash, element) unless empty_content?(element)
hash
else
merge_texts!(hash, element)
end
end
# Merge all the texts of an element into the hash
#
# hash::
# Hash to add the converted emement to.
# element::
# XML element whose texts are to me merged into the hash
def merge_texts!(hash, element)
text_children = texts(element)
if text_children.join.empty?
hash
else
# must use value to prevent double-escaping
merge!(hash, CONTENT_KEY, text_children.join)
end
end
# Adds a new key/value pair to an existing Hash. If the key to be added
# already exists and the existing value associated with key is not
# an Array, it will be wrapped in an Array. Then the new value is
# appended to that Array.
#
# hash::
# Hash to add key/value pair to.
# key::
# Key to be added.
# value::
# Value to be associated with key.
def merge!(hash, key, value)
if hash.has_key?(key)
if hash[key].instance_of?(Array)
hash[key] << value
else
hash[key] = [hash[key], value]
end
elsif value.instance_of?(Array)
hash[key] = [value]
else
hash[key] = value
end
hash
end
# Converts the attributes array of an XML element into a hash.
# Returns an empty Hash if node has no attributes.
#
# element::
# XML element to extract attributes from.
def get_attributes(element)
attribute_hash = {}
attributes = element.attributes
for i in 0...attributes.length
attribute_hash[attributes.item(i).name] = attributes.item(i).value
end
attribute_hash
end
# Determines if a document element has text content
#
# element::
# XML element to be checked.
def texts(element)
texts = []
child_nodes = element.child_nodes
for i in 0...child_nodes.length
item = child_nodes.item(i)
if item.node_type == Node.TEXT_NODE
texts << item.get_data
end
end
texts
end
# Determines if a document element has text content
#
# element::
# XML element to be checked.
def empty_content?(element)
text = ''
child_nodes = element.child_nodes
for i in 0...child_nodes.length
item = child_nodes.item(i)
if item.node_type == Node.TEXT_NODE
text << item.get_data.strip
end
end
text.strip.length == 0
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/activesupport/lib/active_support/values/time_zone.rb | provider/vendor/rails/activesupport/lib/active_support/values/time_zone.rb | # The TimeZone class serves as a wrapper around TZInfo::Timezone instances. It allows us to do the following:
#
# * Limit the set of zones provided by TZInfo to a meaningful subset of 142 zones.
# * Retrieve and display zones with a friendlier name (e.g., "Eastern Time (US & Canada)" instead of "America/New_York").
# * Lazily load TZInfo::Timezone instances only when they're needed.
# * Create ActiveSupport::TimeWithZone instances via TimeZone's +local+, +parse+, +at+ and +now+ methods.
#
# If you set <tt>config.time_zone</tt> in the Rails Initializer, you can access this TimeZone object via <tt>Time.zone</tt>:
#
# # environment.rb:
# Rails::Initializer.run do |config|
# config.time_zone = "Eastern Time (US & Canada)"
# end
#
# Time.zone # => #<TimeZone:0x514834...>
# Time.zone.name # => "Eastern Time (US & Canada)"
# Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00
#
# The version of TZInfo bundled with Active Support only includes the definitions necessary to support the zones
# defined by the TimeZone class. If you need to use zones that aren't defined by TimeZone, you'll need to install the TZInfo gem
# (if a recent version of the gem is installed locally, this will be used instead of the bundled version.)
module ActiveSupport
class TimeZone
unless const_defined?(:MAPPING)
# Keys are Rails TimeZone names, values are TZInfo identifiers
MAPPING = {
"International Date Line West" => "Pacific/Midway",
"Midway Island" => "Pacific/Midway",
"Samoa" => "Pacific/Pago_Pago",
"Hawaii" => "Pacific/Honolulu",
"Alaska" => "America/Juneau",
"Pacific Time (US & Canada)" => "America/Los_Angeles",
"Tijuana" => "America/Tijuana",
"Mountain Time (US & Canada)" => "America/Denver",
"Arizona" => "America/Phoenix",
"Chihuahua" => "America/Chihuahua",
"Mazatlan" => "America/Mazatlan",
"Central Time (US & Canada)" => "America/Chicago",
"Saskatchewan" => "America/Regina",
"Guadalajara" => "America/Mexico_City",
"Mexico City" => "America/Mexico_City",
"Monterrey" => "America/Monterrey",
"Central America" => "America/Guatemala",
"Eastern Time (US & Canada)" => "America/New_York",
"Indiana (East)" => "America/Indiana/Indianapolis",
"Bogota" => "America/Bogota",
"Lima" => "America/Lima",
"Quito" => "America/Lima",
"Atlantic Time (Canada)" => "America/Halifax",
"Caracas" => "America/Caracas",
"La Paz" => "America/La_Paz",
"Santiago" => "America/Santiago",
"Newfoundland" => "America/St_Johns",
"Brasilia" => "America/Sao_Paulo",
"Buenos Aires" => "America/Argentina/Buenos_Aires",
"Georgetown" => "America/Argentina/San_Juan",
"Greenland" => "America/Godthab",
"Mid-Atlantic" => "Atlantic/South_Georgia",
"Azores" => "Atlantic/Azores",
"Cape Verde Is." => "Atlantic/Cape_Verde",
"Dublin" => "Europe/Dublin",
"Edinburgh" => "Europe/Dublin",
"Lisbon" => "Europe/Lisbon",
"London" => "Europe/London",
"Casablanca" => "Africa/Casablanca",
"Monrovia" => "Africa/Monrovia",
"UTC" => "Etc/UTC",
"Belgrade" => "Europe/Belgrade",
"Bratislava" => "Europe/Bratislava",
"Budapest" => "Europe/Budapest",
"Ljubljana" => "Europe/Ljubljana",
"Prague" => "Europe/Prague",
"Sarajevo" => "Europe/Sarajevo",
"Skopje" => "Europe/Skopje",
"Warsaw" => "Europe/Warsaw",
"Zagreb" => "Europe/Zagreb",
"Brussels" => "Europe/Brussels",
"Copenhagen" => "Europe/Copenhagen",
"Madrid" => "Europe/Madrid",
"Paris" => "Europe/Paris",
"Amsterdam" => "Europe/Amsterdam",
"Berlin" => "Europe/Berlin",
"Bern" => "Europe/Berlin",
"Rome" => "Europe/Rome",
"Stockholm" => "Europe/Stockholm",
"Vienna" => "Europe/Vienna",
"West Central Africa" => "Africa/Algiers",
"Bucharest" => "Europe/Bucharest",
"Cairo" => "Africa/Cairo",
"Helsinki" => "Europe/Helsinki",
"Kyev" => "Europe/Kiev",
"Riga" => "Europe/Riga",
"Sofia" => "Europe/Sofia",
"Tallinn" => "Europe/Tallinn",
"Vilnius" => "Europe/Vilnius",
"Athens" => "Europe/Athens",
"Istanbul" => "Europe/Istanbul",
"Minsk" => "Europe/Minsk",
"Jerusalem" => "Asia/Jerusalem",
"Harare" => "Africa/Harare",
"Pretoria" => "Africa/Johannesburg",
"Moscow" => "Europe/Moscow",
"St. Petersburg" => "Europe/Moscow",
"Volgograd" => "Europe/Moscow",
"Kuwait" => "Asia/Kuwait",
"Riyadh" => "Asia/Riyadh",
"Nairobi" => "Africa/Nairobi",
"Baghdad" => "Asia/Baghdad",
"Tehran" => "Asia/Tehran",
"Abu Dhabi" => "Asia/Muscat",
"Muscat" => "Asia/Muscat",
"Baku" => "Asia/Baku",
"Tbilisi" => "Asia/Tbilisi",
"Yerevan" => "Asia/Yerevan",
"Kabul" => "Asia/Kabul",
"Ekaterinburg" => "Asia/Yekaterinburg",
"Islamabad" => "Asia/Karachi",
"Karachi" => "Asia/Karachi",
"Tashkent" => "Asia/Tashkent",
"Chennai" => "Asia/Kolkata",
"Kolkata" => "Asia/Kolkata",
"Mumbai" => "Asia/Kolkata",
"New Delhi" => "Asia/Kolkata",
"Kathmandu" => "Asia/Katmandu",
"Astana" => "Asia/Dhaka",
"Dhaka" => "Asia/Dhaka",
"Sri Jayawardenepura" => "Asia/Colombo",
"Almaty" => "Asia/Almaty",
"Novosibirsk" => "Asia/Novosibirsk",
"Rangoon" => "Asia/Rangoon",
"Bangkok" => "Asia/Bangkok",
"Hanoi" => "Asia/Bangkok",
"Jakarta" => "Asia/Jakarta",
"Krasnoyarsk" => "Asia/Krasnoyarsk",
"Beijing" => "Asia/Shanghai",
"Chongqing" => "Asia/Chongqing",
"Hong Kong" => "Asia/Hong_Kong",
"Urumqi" => "Asia/Urumqi",
"Kuala Lumpur" => "Asia/Kuala_Lumpur",
"Singapore" => "Asia/Singapore",
"Taipei" => "Asia/Taipei",
"Perth" => "Australia/Perth",
"Irkutsk" => "Asia/Irkutsk",
"Ulaan Bataar" => "Asia/Ulaanbaatar",
"Seoul" => "Asia/Seoul",
"Osaka" => "Asia/Tokyo",
"Sapporo" => "Asia/Tokyo",
"Tokyo" => "Asia/Tokyo",
"Yakutsk" => "Asia/Yakutsk",
"Darwin" => "Australia/Darwin",
"Adelaide" => "Australia/Adelaide",
"Canberra" => "Australia/Melbourne",
"Melbourne" => "Australia/Melbourne",
"Sydney" => "Australia/Sydney",
"Brisbane" => "Australia/Brisbane",
"Hobart" => "Australia/Hobart",
"Vladivostok" => "Asia/Vladivostok",
"Guam" => "Pacific/Guam",
"Port Moresby" => "Pacific/Port_Moresby",
"Magadan" => "Asia/Magadan",
"Solomon Is." => "Asia/Magadan",
"New Caledonia" => "Pacific/Noumea",
"Fiji" => "Pacific/Fiji",
"Kamchatka" => "Asia/Kamchatka",
"Marshall Is." => "Pacific/Majuro",
"Auckland" => "Pacific/Auckland",
"Wellington" => "Pacific/Auckland",
"Nuku'alofa" => "Pacific/Tongatapu"
}.each { |name, zone| name.freeze; zone.freeze }
MAPPING.freeze
end
include Comparable
attr_reader :name
# Create a new TimeZone object with the given name and offset. The
# offset is the number of seconds that this time zone is offset from UTC
# (GMT). Seconds were chosen as the offset unit because that is the unit that
# Ruby uses to represent time zone offsets (see Time#utc_offset).
def initialize(name, utc_offset, tzinfo = nil)
@name = name
@utc_offset = utc_offset
@tzinfo = tzinfo
end
def utc_offset
@utc_offset ||= tzinfo.current_period.utc_offset
end
# Returns the offset of this time zone as a formatted string, of the
# format "+HH:MM".
def formatted_offset(colon=true, alternate_utc_string = nil)
utc_offset == 0 && alternate_utc_string || utc_offset.to_utc_offset_s(colon)
end
# Compare this time zone to the parameter. The two are comapred first on
# their offsets, and then by name.
def <=>(zone)
result = (utc_offset <=> zone.utc_offset)
result = (name <=> zone.name) if result == 0
result
end
# Compare #name and TZInfo identifier to a supplied regexp, returning true
# if a match is found.
def =~(re)
return true if name =~ re || MAPPING[name] =~ re
end
# Returns a textual representation of this time zone.
def to_s
"(GMT#{formatted_offset}) #{name}"
end
# Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from given values. Example:
#
# Time.zone = "Hawaii" # => "Hawaii"
# Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00
def local(*args)
time = Time.utc_time(*args)
ActiveSupport::TimeWithZone.new(nil, self, time)
end
# Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from number of seconds since the Unix epoch. Example:
#
# Time.zone = "Hawaii" # => "Hawaii"
# Time.utc(2000).to_f # => 946684800.0
# Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00
def at(secs)
utc = Time.at(secs).utc rescue DateTime.civil(1970).since(secs)
utc.in_time_zone(self)
end
# Method for creating new ActiveSupport::TimeWithZone instance in time zone of +self+ from parsed string. Example:
#
# Time.zone = "Hawaii" # => "Hawaii"
# Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
#
# If upper components are missing from the string, they are supplied from TimeZone#now:
#
# Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
# Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
def parse(str, now=now)
date_parts = Date._parse(str)
return if date_parts.blank?
time = Time.parse(str, now) rescue DateTime.parse(str)
if date_parts[:offset].nil?
ActiveSupport::TimeWithZone.new(nil, self, time)
else
time.in_time_zone(self)
end
end
# Returns an ActiveSupport::TimeWithZone instance representing the current time
# in the time zone represented by +self+. Example:
#
# Time.zone = 'Hawaii' # => "Hawaii"
# Time.zone.now # => Wed, 23 Jan 2008 20:24:27 HST -10:00
def now
Time.now.utc.in_time_zone(self)
end
# Return the current date in this time zone.
def today
tzinfo.now.to_date
end
# Adjust the given time to the simultaneous time in the time zone represented by +self+. Returns a
# Time.utc() instance -- if you want an ActiveSupport::TimeWithZone instance, use Time#in_time_zone() instead.
def utc_to_local(time)
tzinfo.utc_to_local(time)
end
# Adjust the given time to the simultaneous time in UTC. Returns a Time.utc() instance.
def local_to_utc(time, dst=true)
tzinfo.local_to_utc(time, dst)
end
# Available so that TimeZone instances respond like TZInfo::Timezone instances
def period_for_utc(time)
tzinfo.period_for_utc(time)
end
# Available so that TimeZone instances respond like TZInfo::Timezone instances
def period_for_local(time, dst=true)
tzinfo.period_for_local(time, dst)
end
# TODO: Preload instead of lazy load for thread safety
def tzinfo
require 'tzinfo' unless defined?(TZInfo)
@tzinfo ||= TZInfo::Timezone.get(MAPPING[name])
end
unless const_defined?(:ZONES)
ZONES = []
ZONES_MAP = {}
[[-39_600, "International Date Line West", "Midway Island", "Samoa" ],
[-36_000, "Hawaii" ],
[-32_400, "Alaska" ],
[-28_800, "Pacific Time (US & Canada)", "Tijuana" ],
[-25_200, "Mountain Time (US & Canada)", "Chihuahua", "Mazatlan",
"Arizona" ],
[-21_600, "Central Time (US & Canada)", "Saskatchewan", "Guadalajara",
"Mexico City", "Monterrey", "Central America" ],
[-18_000, "Eastern Time (US & Canada)", "Indiana (East)", "Bogota",
"Lima", "Quito" ],
[-16_200, "Caracas" ],
[-14_400, "Atlantic Time (Canada)", "La Paz", "Santiago" ],
[-12_600, "Newfoundland" ],
[-10_800, "Brasilia", "Buenos Aires", "Georgetown", "Greenland" ],
[ -7_200, "Mid-Atlantic" ],
[ -3_600, "Azores", "Cape Verde Is." ],
[ 0, "Dublin", "Edinburgh", "Lisbon", "London", "Casablanca",
"Monrovia", "UTC" ],
[ 3_600, "Belgrade", "Bratislava", "Budapest", "Ljubljana", "Prague",
"Sarajevo", "Skopje", "Warsaw", "Zagreb", "Brussels",
"Copenhagen", "Madrid", "Paris", "Amsterdam", "Berlin",
"Bern", "Rome", "Stockholm", "Vienna",
"West Central Africa" ],
[ 7_200, "Bucharest", "Cairo", "Helsinki", "Kyev", "Riga", "Sofia",
"Tallinn", "Vilnius", "Athens", "Istanbul", "Minsk",
"Jerusalem", "Harare", "Pretoria" ],
[ 10_800, "Moscow", "St. Petersburg", "Volgograd", "Kuwait", "Riyadh",
"Nairobi", "Baghdad" ],
[ 12_600, "Tehran" ],
[ 14_400, "Abu Dhabi", "Muscat", "Baku", "Tbilisi", "Yerevan" ],
[ 16_200, "Kabul" ],
[ 18_000, "Ekaterinburg", "Islamabad", "Karachi", "Tashkent" ],
[ 19_800, "Chennai", "Kolkata", "Mumbai", "New Delhi", "Sri Jayawardenepura" ],
[ 20_700, "Kathmandu" ],
[ 21_600, "Astana", "Dhaka", "Almaty",
"Novosibirsk" ],
[ 23_400, "Rangoon" ],
[ 25_200, "Bangkok", "Hanoi", "Jakarta", "Krasnoyarsk" ],
[ 28_800, "Beijing", "Chongqing", "Hong Kong", "Urumqi",
"Kuala Lumpur", "Singapore", "Taipei", "Perth", "Irkutsk",
"Ulaan Bataar" ],
[ 32_400, "Seoul", "Osaka", "Sapporo", "Tokyo", "Yakutsk" ],
[ 34_200, "Darwin", "Adelaide" ],
[ 36_000, "Canberra", "Melbourne", "Sydney", "Brisbane", "Hobart",
"Vladivostok", "Guam", "Port Moresby" ],
[ 39_600, "Magadan", "Solomon Is.", "New Caledonia" ],
[ 43_200, "Fiji", "Kamchatka", "Marshall Is.", "Auckland",
"Wellington" ],
[ 46_800, "Nuku'alofa" ]].
each do |offset, *places|
places.each do |place|
place.freeze
zone = new(place, offset)
ZONES << zone
ZONES_MAP[place] = zone
end
end
ZONES.sort!
ZONES.freeze
ZONES_MAP.freeze
US_ZONES = ZONES.find_all { |z| z.name =~ /US|Arizona|Indiana|Hawaii|Alaska/ }
US_ZONES.freeze
end
class << self
alias_method :create, :new
# Return a TimeZone instance with the given name, or +nil+ if no
# such TimeZone instance exists. (This exists to support the use of
# this class with the +composed_of+ macro.)
def new(name)
self[name]
end
# Return an array of all TimeZone objects. There are multiple
# TimeZone objects per time zone, in many cases, to make it easier
# for users to find their own time zone.
def all
ZONES
end
# Locate a specific time zone object. If the argument is a string, it
# is interpreted to mean the name of the timezone to locate. If it is a
# numeric value it is either the hour offset, or the second offset, of the
# timezone to find. (The first one with that offset will be returned.)
# Returns +nil+ if no such time zone is known to the system.
def [](arg)
case arg
when String
ZONES_MAP[arg]
when Numeric, ActiveSupport::Duration
arg *= 3600 if arg.abs <= 13
all.find { |z| z.utc_offset == arg.to_i }
else
raise ArgumentError, "invalid argument to TimeZone[]: #{arg.inspect}"
end
end
# A convenience method for returning a collection of TimeZone objects
# for time zones in the USA.
def us_zones
US_ZONES
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/dispatches/dispatch.rb | provider/vendor/rails/railties/dispatches/dispatch.rb | #!/usr/bin/env ruby
require File.dirname(__FILE__) + "/../config/environment" unless defined?(RAILS_ROOT)
# If you're using RubyGems and mod_ruby, this require should be changed to an absolute path one, like:
# "/usr/local/lib/ruby/gems/1.8/gems/rails-0.8.0/lib/dispatcher" -- otherwise performance is severely impaired
require "dispatcher"
ADDITIONAL_LOAD_PATHS.reverse.each { |dir| $:.unshift(dir) if File.directory?(dir) } if defined?(Apache::RubyRun)
Dispatcher.dispatch
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/helpers/test_helper.rb | provider/vendor/rails/railties/helpers/test_helper.rb | ENV["RAILS_ENV"] = "test"
require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
require '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
# -- they do not yet inherit this setting
fixtures :all
# Add more helper methods to be used by all tests here...
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/helpers/application_helper.rb | provider/vendor/rails/railties/helpers/application_helper.rb | # Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/helpers/application_controller.rb | provider/vendor/rails/railties/helpers/application_controller.rb | # Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/helpers/performance_test.rb | provider/vendor/rails/railties/helpers/performance_test.rb | require 'test_helper'
require 'performance_test_help'
# Profiling results for each test method are written to tmp/performance.
class BrowsingTest < ActionController::PerformanceTest
def test_homepage
get '/'
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/builtin/rails_info/rails_info_controller.rb | provider/vendor/rails/railties/builtin/rails_info/rails_info_controller.rb | # Alias to ensure old public.html still works.
RailsInfoController = Rails::InfoController
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/builtin/rails_info/rails/info.rb | provider/vendor/rails/railties/builtin/rails_info/rails/info.rb | module Rails
module Info
mattr_accessor :properties
class << (@@properties = [])
def names
map &:first
end
def value_for(property_name)
if property = assoc(property_name)
property.last
end
end
end
class << self #:nodoc:
def property(name, value = nil)
value ||= yield
properties << [name, value] if value
rescue Exception
end
def frameworks
%w( active_record action_pack active_resource action_mailer active_support )
end
def framework_version(framework)
if Object.const_defined?(framework.classify)
require "#{framework}/version"
"#{framework.classify}::VERSION::STRING".constantize
end
end
def edge_rails_revision(info = git_info)
info[/commit ([a-z0-9-]+)/, 1] || freeze_edge_version
end
def freeze_edge_version
if File.exist?(rails_vendor_root)
begin
Dir[File.join(rails_vendor_root, 'REVISION_*')].first.scan(/_(\d+)$/).first.first
rescue
Dir[File.join(rails_vendor_root, 'TAG_*')].first.scan(/_(.+)$/).first.first rescue 'unknown'
end
end
end
def to_s
column_width = properties.names.map {|name| name.length}.max
["About your application's environment", *properties.map do |property|
"%-#{column_width}s %s" % property
end] * "\n"
end
alias inspect to_s
def to_html
returning table = '<table>' do
properties.each do |(name, value)|
table << %(<tr><td class="name">#{CGI.escapeHTML(name.to_s)}</td>)
table << %(<td class="value">#{CGI.escapeHTML(value.to_s)}</td></tr>)
end
table << '</table>'
end
end
protected
def rails_vendor_root
@rails_vendor_root ||= "#{RAILS_ROOT}/vendor/rails"
end
def git_info
env_lang, ENV['LC_ALL'] = ENV['LC_ALL'], 'C'
Dir.chdir(rails_vendor_root) do
silence_stderr { `git log -n 1` }
end
ensure
ENV['LC_ALL'] = env_lang
end
end
# The Ruby version and platform, e.g. "1.8.2 (powerpc-darwin8.2.0)".
property 'Ruby version', "#{RUBY_VERSION} (#{RUBY_PLATFORM})"
# The RubyGems version, if it's installed.
property 'RubyGems version' do
Gem::RubyGemsVersion
end
property 'Rack version' do
::Rack.release
end
# The Rails version.
property 'Rails version' do
Rails::VERSION::STRING
end
# Versions of each Rails framework (Active Record, Action Pack,
# Active Resource, Action Mailer, and Active Support).
frameworks.each do |framework|
property "#{framework.titlecase} version" do
framework_version(framework)
end
end
# The Rails Git revision, if it's checked out into vendor/rails.
property 'Edge Rails revision' do
edge_rails_revision
end
# The application's location on the filesystem.
property 'Application root' do
File.expand_path(RAILS_ROOT)
end
# The current Rails environment (development, test, or production).
property 'Environment' do
RAILS_ENV
end
# The name of the database adapter for the current environment.
property 'Database adapter' do
ActiveRecord::Base.configurations[RAILS_ENV]['adapter']
end
property 'Database schema version' do
ActiveRecord::Migrator.current_version rescue nil
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/builtin/rails_info/rails/info_controller.rb | provider/vendor/rails/railties/builtin/rails_info/rails/info_controller.rb | class Rails::InfoController < ActionController::Base
def properties
if consider_all_requests_local || local_request?
render :inline => Rails::Info.to_html
else
render :text => '<p>For security purposes, this information is only available to local requests.</p>', :status => 500
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/builtin/rails_info/rails/info_helper.rb | provider/vendor/rails/railties/builtin/rails_info/rails/info_helper.rb | module Rails::InfoHelper
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/console_app.rb | provider/vendor/rails/railties/lib/console_app.rb | require 'active_support/test_case'
require 'action_controller'
# work around the at_exit hook in test/unit, which kills IRB
Test::Unit.run = true if Test::Unit.respond_to?(:run=)
# reference the global "app" instance, created on demand. To recreate the
# instance, pass a non-false value as the parameter.
def app(create=false)
@app_integration_instance = nil if create
@app_integration_instance ||= new_session do |sess|
sess.host! "www.example.com"
end
end
# create a new session. If a block is given, the new session will be yielded
# to the block before being returned.
def new_session
session = ActionController::Integration::Session.new
yield session if block_given?
session
end
#reloads the environment
def reload!
puts "Reloading..."
Dispatcher.cleanup_application
Dispatcher.reload_application
true
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/railties_path.rb | provider/vendor/rails/railties/lib/railties_path.rb | RAILTIES_PATH = File.join(File.dirname(__FILE__), '..')
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/initializer.rb | provider/vendor/rails/railties/lib/initializer.rb | require 'logger'
require 'set'
require 'pathname'
$LOAD_PATH.unshift File.dirname(__FILE__)
require 'railties_path'
require 'rails/version'
require 'rails/plugin/locator'
require 'rails/plugin/loader'
require 'rails/gem_dependency'
require 'rails/rack'
RAILS_ENV = (ENV['RAILS_ENV'] || 'development').dup unless defined?(RAILS_ENV)
module Rails
class << self
# The Configuration instance used to configure the Rails environment
def configuration
@@configuration
end
def configuration=(configuration)
@@configuration = configuration
end
def initialized?
@initialized || false
end
def initialized=(initialized)
@initialized ||= initialized
end
def logger
if defined?(RAILS_DEFAULT_LOGGER)
RAILS_DEFAULT_LOGGER
else
nil
end
end
def backtrace_cleaner
@@backtrace_cleaner ||= begin
# Relies on ActiveSupport, so we have to lazy load to postpone definition until AS has been loaded
require 'rails/backtrace_cleaner'
Rails::BacktraceCleaner.new
end
end
def root
Pathname.new(RAILS_ROOT) if defined?(RAILS_ROOT)
end
def env
@_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
end
def cache
RAILS_CACHE
end
def version
VERSION::STRING
end
def public_path
@@public_path ||= self.root ? File.join(self.root, "public") : "public"
end
def public_path=(path)
@@public_path = path
end
end
# The Initializer is responsible for processing the Rails configuration, such
# as setting the $LOAD_PATH, requiring the right frameworks, initializing
# logging, and more. It can be run either as a single command that'll just
# use the default configuration, like this:
#
# Rails::Initializer.run
#
# But normally it's more interesting to pass in a custom configuration
# through the block running:
#
# Rails::Initializer.run do |config|
# config.frameworks -= [ :action_mailer ]
# end
#
# This will use the default configuration options from Rails::Configuration,
# but allow for overwriting on select areas.
class Initializer
# The Configuration instance used by this Initializer instance.
attr_reader :configuration
# The set of loaded plugins.
attr_reader :loaded_plugins
# Whether or not all the gem dependencies have been met
attr_reader :gems_dependencies_loaded
# Runs the initializer. By default, this will invoke the #process method,
# which simply executes all of the initialization routines. Alternately,
# you can specify explicitly which initialization routine you want:
#
# Rails::Initializer.run(:set_load_path)
#
# This is useful if you only want the load path initialized, without
# incurring the overhead of completely loading the entire environment.
def self.run(command = :process, configuration = Configuration.new)
yield configuration if block_given?
initializer = new configuration
initializer.send(command)
initializer
end
# Create a new Initializer instance that references the given Configuration
# instance.
def initialize(configuration)
@configuration = configuration
@loaded_plugins = []
end
# Sequentially step through all of the available initialization routines,
# in order (view execution order in source).
def process
Rails.configuration = configuration
check_ruby_version
install_gem_spec_stubs
set_load_path
add_gem_load_paths
require_frameworks
set_autoload_paths
add_plugin_load_paths
load_environment
preload_frameworks
initialize_encoding
initialize_database
initialize_cache
initialize_framework_caches
initialize_logger
initialize_framework_logging
initialize_dependency_mechanism
initialize_whiny_nils
initialize_time_zone
initialize_i18n
initialize_framework_settings
initialize_framework_views
initialize_metal
add_support_load_paths
check_for_unbuilt_gems
load_gems
load_plugins
# pick up any gems that plugins depend on
add_gem_load_paths
load_gems
check_gem_dependencies
# bail out if gems are missing - note that check_gem_dependencies will have
# already called abort() unless $gems_rake_task is set
return unless gems_dependencies_loaded
load_application_initializers
# the framework is now fully initialized
after_initialize
# Setup database middleware after initializers have run
initialize_database_middleware
# Prepare dispatcher callbacks and run 'prepare' callbacks
prepare_dispatcher
# Routing must be initialized after plugins to allow the former to extend the routes
initialize_routing
# Observers are loaded after plugins in case Observers or observed models are modified by plugins.
load_observers
# Load view path cache
load_view_paths
# Load application classes
load_application_classes
# Disable dependency loading during request cycle
disable_dependency_loading
# Flag initialized
Rails.initialized = true
end
# Check for valid Ruby version
# This is done in an external file, so we can use it
# from the `rails` program as well without duplication.
def check_ruby_version
require 'ruby_version_check'
end
# If Rails is vendored and RubyGems is available, install stub GemSpecs
# for Rails, Active Support, Active Record, Action Pack, Action Mailer, and
# Active Resource. This allows Gem plugins to depend on Rails even when
# the Gem version of Rails shouldn't be loaded.
def install_gem_spec_stubs
unless Rails.respond_to?(:vendor_rails?)
abort %{Your config/boot.rb is outdated: Run "rake rails:update".}
end
if Rails.vendor_rails?
begin; require "rubygems"; rescue LoadError; return; end
stubs = %w(rails activesupport activerecord actionpack actionmailer activeresource)
stubs.reject! { |s| Gem.loaded_specs.key?(s) }
stubs.each do |stub|
Gem.loaded_specs[stub] = Gem::Specification.new do |s|
s.name = stub
s.version = Rails::VERSION::STRING
s.loaded_from = ""
end
end
end
end
# Set the <tt>$LOAD_PATH</tt> based on the value of
# Configuration#load_paths. Duplicates are removed.
def set_load_path
load_paths = configuration.load_paths + configuration.framework_paths
load_paths.reverse_each { |dir| $LOAD_PATH.unshift(dir) if File.directory?(dir) }
$LOAD_PATH.uniq!
end
# Set the paths from which Rails will automatically load source files, and
# the load_once paths.
def set_autoload_paths
ActiveSupport::Dependencies.load_paths = configuration.load_paths.uniq
ActiveSupport::Dependencies.load_once_paths = configuration.load_once_paths.uniq
extra = ActiveSupport::Dependencies.load_once_paths - ActiveSupport::Dependencies.load_paths
unless extra.empty?
abort <<-end_error
load_once_paths must be a subset of the load_paths.
Extra items in load_once_paths: #{extra * ','}
end_error
end
# Freeze the arrays so future modifications will fail rather than do nothing mysteriously
configuration.load_once_paths.freeze
end
# Requires all frameworks specified by the Configuration#frameworks
# list. By default, all frameworks (Active Record, Active Support,
# Action Pack, Action Mailer, and Active Resource) are loaded.
def require_frameworks
configuration.frameworks.each { |framework| require(framework.to_s) }
rescue LoadError => e
# Re-raise as RuntimeError because Mongrel would swallow LoadError.
raise e.to_s
end
# Preload all frameworks specified by the Configuration#frameworks.
# Used by Passenger to ensure everything's loaded before forking and
# to avoid autoload race conditions in JRuby.
def preload_frameworks
if configuration.preload_frameworks
configuration.frameworks.each do |framework|
# String#classify and #constantize aren't available yet.
toplevel = Object.const_get(framework.to_s.gsub(/(?:^|_)(.)/) { $1.upcase })
toplevel.load_all! if toplevel.respond_to?(:load_all!)
end
end
end
# Add the load paths used by support functions such as the info controller
def add_support_load_paths
end
# Adds all load paths from plugins to the global set of load paths, so that
# code from plugins can be required (explicitly or automatically via ActiveSupport::Dependencies).
def add_plugin_load_paths
plugin_loader.add_plugin_load_paths
end
def add_gem_load_paths
Rails::GemDependency.add_frozen_gem_path
unless @configuration.gems.empty?
require "rubygems"
@configuration.gems.each { |gem| gem.add_load_paths }
end
end
def load_gems
unless $gems_rake_task
@configuration.gems.each { |gem| gem.load }
end
end
def check_for_unbuilt_gems
unbuilt_gems = @configuration.gems.select(&:frozen?).reject(&:built?)
if unbuilt_gems.size > 0
# don't print if the gems:build rake tasks are being run
unless $gems_build_rake_task
abort <<-end_error
The following gems have native components that need to be built
#{unbuilt_gems.map { |gem| "#{gem.name} #{gem.requirement}" } * "\n "}
You're running:
ruby #{Gem.ruby_version} at #{Gem.ruby}
rubygems #{Gem::RubyGemsVersion} at #{Gem.path * ', '}
Run `rake gems:build` to build the unbuilt gems.
end_error
end
end
end
def check_gem_dependencies
unloaded_gems = @configuration.gems.reject { |g| g.loaded? }
if unloaded_gems.size > 0
@gems_dependencies_loaded = false
# don't print if the gems rake tasks are being run
unless $gems_rake_task
abort <<-end_error
Missing these required gems:
#{unloaded_gems.map { |gem| "#{gem.name} #{gem.requirement}" } * "\n "}
You're running:
ruby #{Gem.ruby_version} at #{Gem.ruby}
rubygems #{Gem::RubyGemsVersion} at #{Gem.path * ', '}
Run `rake gems:install` to install the missing gems.
end_error
end
else
@gems_dependencies_loaded = true
end
end
# Loads all plugins in <tt>config.plugin_paths</tt>. <tt>plugin_paths</tt>
# defaults to <tt>vendor/plugins</tt> but may also be set to a list of
# paths, such as
# config.plugin_paths = ["#{RAILS_ROOT}/lib/plugins", "#{RAILS_ROOT}/vendor/plugins"]
#
# In the default implementation, as each plugin discovered in <tt>plugin_paths</tt> is initialized:
# * its +lib+ directory, if present, is added to the load path (immediately after the applications lib directory)
# * <tt>init.rb</tt> is evaluated, if present
#
# After all plugins are loaded, duplicates are removed from the load path.
# If an array of plugin names is specified in config.plugins, only those plugins will be loaded
# and they plugins will be loaded in that order. Otherwise, plugins are loaded in alphabetical
# order.
#
# if config.plugins ends contains :all then the named plugins will be loaded in the given order and all other
# plugins will be loaded in alphabetical order
def load_plugins
plugin_loader.load_plugins
end
def plugin_loader
@plugin_loader ||= configuration.plugin_loader.new(self)
end
# Loads the environment specified by Configuration#environment_path, which
# is typically one of development, test, or production.
def load_environment
silence_warnings do
return if @environment_loaded
@environment_loaded = true
config = configuration
constants = self.class.constants
eval(IO.read(configuration.environment_path), binding, configuration.environment_path)
(self.class.constants - constants).each do |const|
Object.const_set(const, self.class.const_get(const))
end
end
end
def load_observers
if gems_dependencies_loaded && configuration.frameworks.include?(:active_record)
ActiveRecord::Base.instantiate_observers
end
end
def load_view_paths
if configuration.frameworks.include?(:action_view)
ActionController::Base.view_paths.load! if configuration.frameworks.include?(:action_controller)
ActionMailer::Base.view_paths.load! if configuration.frameworks.include?(:action_mailer)
end
end
# Eager load application classes
def load_application_classes
return if $rails_rake_task
if configuration.cache_classes
configuration.eager_load_paths.each do |load_path|
matcher = /\A#{Regexp.escape(load_path)}(.*)\.rb\Z/
Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
require_dependency file.sub(matcher, '\1')
end
end
end
end
# For Ruby 1.8, this initialization sets $KCODE to 'u' to enable the
# multibyte safe operations. Plugin authors supporting other encodings
# should override this behaviour and set the relevant +default_charset+
# on ActionController::Base.
#
# For Ruby 1.9, this does nothing. Specify the default encoding in the Ruby
# shebang line if you don't want UTF-8.
def initialize_encoding
$KCODE='u' if RUBY_VERSION < '1.9'
end
# This initialization routine does nothing unless <tt>:active_record</tt>
# is one of the frameworks to load (Configuration#frameworks). If it is,
# this sets the database configuration from Configuration#database_configuration
# and then establishes the connection.
def initialize_database
if configuration.frameworks.include?(:active_record)
ActiveRecord::Base.configurations = configuration.database_configuration
ActiveRecord::Base.establish_connection
end
end
def initialize_database_middleware
if configuration.frameworks.include?(:active_record)
if configuration.frameworks.include?(:action_controller) &&
ActionController::Base.session_store.name == 'ActiveRecord::SessionStore'
configuration.middleware.insert_before :"ActiveRecord::SessionStore", ActiveRecord::ConnectionAdapters::ConnectionManagement
configuration.middleware.insert_before :"ActiveRecord::SessionStore", ActiveRecord::QueryCache
else
configuration.middleware.use ActiveRecord::ConnectionAdapters::ConnectionManagement
configuration.middleware.use ActiveRecord::QueryCache
end
end
end
def initialize_cache
unless defined?(RAILS_CACHE)
silence_warnings { Object.const_set "RAILS_CACHE", ActiveSupport::Cache.lookup_store(configuration.cache_store) }
if RAILS_CACHE.respond_to?(:middleware)
# Insert middleware to setup and teardown local cache for each request
configuration.middleware.insert_after(:"ActionController::Failsafe", RAILS_CACHE.middleware)
end
end
end
def initialize_framework_caches
if configuration.frameworks.include?(:action_controller)
ActionController::Base.cache_store ||= RAILS_CACHE
end
end
# If the RAILS_DEFAULT_LOGGER constant is already set, this initialization
# routine does nothing. If the constant is not set, and Configuration#logger
# is not +nil+, this also does nothing. Otherwise, a new logger instance
# is created at Configuration#log_path, with a default log level of
# Configuration#log_level.
#
# If the log could not be created, the log will be set to output to
# +STDERR+, with a log level of +WARN+.
def initialize_logger
# if the environment has explicitly defined a logger, use it
return if Rails.logger
unless logger = configuration.logger
begin
logger = ActiveSupport::BufferedLogger.new(configuration.log_path)
logger.level = ActiveSupport::BufferedLogger.const_get(configuration.log_level.to_s.upcase)
if configuration.environment == "production"
logger.auto_flushing = false
end
rescue StandardError => e
logger = ActiveSupport::BufferedLogger.new(STDERR)
logger.level = ActiveSupport::BufferedLogger::WARN
logger.warn(
"Rails Error: Unable to access log file. Please ensure that #{configuration.log_path} exists and is chmod 0666. " +
"The log level has been raised to WARN and the output directed to STDERR until the problem is fixed."
)
end
end
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
end
# Sets the logger for Active Record, Action Controller, and Action Mailer
# (but only for those frameworks that are to be loaded). If the framework's
# logger is already set, it is not changed, otherwise it is set to use
# RAILS_DEFAULT_LOGGER.
def initialize_framework_logging
for framework in ([ :active_record, :action_controller, :action_mailer ] & configuration.frameworks)
framework.to_s.camelize.constantize.const_get("Base").logger ||= Rails.logger
end
ActiveSupport::Dependencies.logger ||= Rails.logger
Rails.cache.logger ||= Rails.logger
end
# Sets +ActionController::Base#view_paths+ and +ActionMailer::Base#template_root+
# (but only for those frameworks that are to be loaded). If the framework's
# paths have already been set, it is not changed, otherwise it is
# set to use Configuration#view_path.
def initialize_framework_views
if configuration.frameworks.include?(:action_view)
view_path = ActionView::PathSet.type_cast(configuration.view_path)
ActionMailer::Base.template_root = view_path if configuration.frameworks.include?(:action_mailer) && ActionMailer::Base.view_paths.blank?
ActionController::Base.view_paths = view_path if configuration.frameworks.include?(:action_controller) && ActionController::Base.view_paths.blank?
end
end
# If Action Controller is not one of the loaded frameworks (Configuration#frameworks)
# this does nothing. Otherwise, it loads the routing definitions and sets up
# loading module used to lazily load controllers (Configuration#controller_paths).
def initialize_routing
return unless configuration.frameworks.include?(:action_controller)
ActionController::Routing.controller_paths += configuration.controller_paths
ActionController::Routing::Routes.add_configuration_file(configuration.routes_configuration_file)
ActionController::Routing::Routes.reload!
end
# Sets the dependency loading mechanism based on the value of
# Configuration#cache_classes.
def initialize_dependency_mechanism
ActiveSupport::Dependencies.mechanism = configuration.cache_classes ? :require : :load
end
# Loads support for "whiny nil" (noisy warnings when methods are invoked
# on +nil+ values) if Configuration#whiny_nils is true.
def initialize_whiny_nils
require('active_support/whiny_nil') if configuration.whiny_nils
end
# Sets the default value for Time.zone, and turns on ActiveRecord::Base#time_zone_aware_attributes.
# 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)
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
Time.zone_default = zone_default
if configuration.frameworks.include?(:active_record)
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.default_timezone = :utc
end
end
end
# Set the i18n configuration from config.i18n but special-case for the load_path which should be
# appended to what's already set instead of overwritten.
def initialize_i18n
configuration.i18n.each do |setting, value|
if setting == :load_path
I18n.load_path += value
else
I18n.send("#{setting}=", value)
end
end
end
def initialize_metal
Rails::Rack::Metal.requested_metals = configuration.metals
Rails::Rack::Metal.metal_paths += plugin_loader.engine_metal_paths
configuration.middleware.insert_before(
:"ActionController::ParamsParser",
Rails::Rack::Metal, :if => Rails::Rack::Metal.metals.any?)
end
# Initializes framework-specific settings for each of the loaded frameworks
# (Configuration#frameworks). The available settings map to the accessors
# on each of the corresponding Base classes.
def initialize_framework_settings
configuration.frameworks.each do |framework|
base_class = framework.to_s.camelize.constantize.const_get("Base")
configuration.send(framework).each do |setting, value|
base_class.send("#{setting}=", value)
end
end
configuration.active_support.each do |setting, value|
ActiveSupport.send("#{setting}=", value)
end
end
# Fires the user-supplied after_initialize block (Configuration#after_initialize)
def after_initialize
if gems_dependencies_loaded
configuration.after_initialize_blocks.each do |block|
block.call
end
end
end
def load_application_initializers
if gems_dependencies_loaded
Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer|
load(initializer)
end
end
end
def prepare_dispatcher
return unless configuration.frameworks.include?(:action_controller)
require 'dispatcher' unless defined?(::Dispatcher)
Dispatcher.define_dispatcher_callbacks(configuration.cache_classes)
Dispatcher.run_prepare_callbacks
end
def disable_dependency_loading
if configuration.cache_classes && !configuration.dependency_loading
ActiveSupport::Dependencies.unhook!
end
end
end
# The Configuration class holds all the parameters for the Initializer and
# ships with defaults that suites most Rails applications. But it's possible
# to overwrite everything. Usually, you'll create an Configuration file
# implicitly through the block running on the Initializer, but it's also
# possible to create the Configuration instance in advance and pass it in
# like this:
#
# config = Rails::Configuration.new
# Rails::Initializer.run(:process, config)
class Configuration
# The application's base directory.
attr_reader :root_path
# A stub for setting options on ActionController::Base.
attr_accessor :action_controller
# A stub for setting options on ActionMailer::Base.
attr_accessor :action_mailer
# A stub for setting options on ActionView::Base.
attr_accessor :action_view
# A stub for setting options on ActiveRecord::Base.
attr_accessor :active_record
# A stub for setting options on ActiveResource::Base.
attr_accessor :active_resource
# A stub for setting options on ActiveSupport.
attr_accessor :active_support
# Whether to preload all frameworks at startup.
attr_accessor :preload_frameworks
# Whether or not classes should be cached (set to false if you want
# application classes to be reloaded on each request)
attr_accessor :cache_classes
# The list of paths that should be searched for controllers. (Defaults
# to <tt>app/controllers</tt>.)
attr_accessor :controller_paths
# The path to the database configuration file to use. (Defaults to
# <tt>config/database.yml</tt>.)
attr_accessor :database_configuration_file
# The path to the routes configuration file to use. (Defaults to
# <tt>config/routes.rb</tt>.)
attr_accessor :routes_configuration_file
# The list of rails framework components that should be loaded. (Defaults
# to <tt>:active_record</tt>, <tt>:action_controller</tt>,
# <tt>:action_view</tt>, <tt>:action_mailer</tt>, and
# <tt>:active_resource</tt>).
attr_accessor :frameworks
# An array of additional paths to prepend to the load path. By default,
# all +app+, +lib+, +vendor+ and mock paths are included in this list.
attr_accessor :load_paths
# An array of paths from which Rails will automatically load from only once.
# All elements of this array must also be in +load_paths+.
attr_accessor :load_once_paths
# An array of paths from which Rails will eager load on boot if cache
# classes is enabled. All elements of this array must also be in
# +load_paths+.
attr_accessor :eager_load_paths
# The log level to use for the default Rails logger. In production mode,
# this defaults to <tt>:info</tt>. In development mode, it defaults to
# <tt>:debug</tt>.
attr_accessor :log_level
# The path to the log file to use. Defaults to log/#{environment}.log
# (e.g. log/development.log or log/production.log).
attr_accessor :log_path
# The specific logger to use. By default, a logger will be created and
# initialized using #log_path and #log_level, but a programmer may
# specifically set the logger to use via this accessor and it will be
# used directly.
attr_accessor :logger
# The specific cache store to use. By default, the ActiveSupport::Cache::Store will be used.
attr_accessor :cache_store
# The root of the application's views. (Defaults to <tt>app/views</tt>.)
attr_accessor :view_path
# Set to +true+ if you want to be warned (noisily) when you try to invoke
# any method of +nil+. Set to +false+ for the standard Ruby behavior.
attr_accessor :whiny_nils
# The list of plugins to load. If this is set to <tt>nil</tt>, all plugins will
# be loaded. If this is set to <tt>[]</tt>, no plugins will be loaded. Otherwise,
# plugins will be loaded in the order specified.
attr_reader :plugins
def plugins=(plugins)
@plugins = plugins.nil? ? nil : plugins.map { |p| p.to_sym }
end
# The list of metals to load. If this is set to <tt>nil</tt>, all metals will
# be loaded in alphabetical order. If this is set to <tt>[]</tt>, no metals will
# be loaded. Otherwise metals will be loaded in the order specified
attr_accessor :metals
# The path to the root of the plugins directory. By default, it is in
# <tt>vendor/plugins</tt>.
attr_accessor :plugin_paths
# The classes that handle finding the desired plugins that you'd like to load for
# your application. By default it is the Rails::Plugin::FileSystemLocator which finds
# plugins to load in <tt>vendor/plugins</tt>. You can hook into gem location by subclassing
# Rails::Plugin::Locator and adding it onto the list of <tt>plugin_locators</tt>.
attr_accessor :plugin_locators
# The class that handles loading each plugin. Defaults to Rails::Plugin::Loader, but
# a sub class would have access to fine grained modification of the loading behavior. See
# the implementation of Rails::Plugin::Loader for more details.
attr_accessor :plugin_loader
# Enables or disables plugin reloading. You can get around this setting per plugin.
# If <tt>reload_plugins?</tt> is false, add this to your plugin's <tt>init.rb</tt>
# to make it reloadable:
#
# ActiveSupport::Dependencies.load_once_paths.delete lib_path
#
# If <tt>reload_plugins?</tt> is true, add this to your plugin's <tt>init.rb</tt>
# to only load it once:
#
# ActiveSupport::Dependencies.load_once_paths << lib_path
#
attr_accessor :reload_plugins
# Returns true if plugin reloading is enabled.
def reload_plugins?
!!@reload_plugins
end
# Enables or disables dependency loading during the request cycle. Setting
# <tt>dependency_loading</tt> to true will allow new classes to be loaded
# during a request. Setting it to false will disable this behavior.
#
# Those who want to run in a threaded environment should disable this
# option and eager load or require all there classes on initialization.
#
# If <tt>cache_classes</tt> is disabled, dependency loaded will always be
# on.
attr_accessor :dependency_loading
# An array of gems that this rails application depends on. Rails will automatically load
# these gems during installation, and allow you to install any missing gems with:
#
# rake gems:install
#
# You can add gems with the #gem method.
attr_accessor :gems
# Adds a single Gem dependency to the rails application. By default, it will require
# the library with the same name as the gem. Use :lib to specify a different name.
#
# # gem 'aws-s3', '>= 0.4.0'
# # require 'aws/s3'
# config.gem 'aws-s3', :lib => 'aws/s3', :version => '>= 0.4.0', \
# :source => "http://code.whytheluckystiff.net"
#
# To require a library be installed, but not attempt to load it, pass :lib => false
#
# config.gem 'qrp', :version => '0.4.1', :lib => false
def gem(name, options = {})
@gems << Rails::GemDependency.new(name, options)
end
# Deprecated options:
def breakpoint_server(_ = nil)
$stderr.puts %(
*******************************************************************
* config.breakpoint_server has been deprecated and has no effect. *
*******************************************************************
)
end
alias_method :breakpoint_server=, :breakpoint_server
# Sets the default +time_zone+. Setting this will enable +time_zone+
# awareness for Active Record models and set the Active Record default
# timezone to <tt>:utc</tt>.
attr_accessor :time_zone
# Accessor for i18n settings.
attr_accessor :i18n
# Create a new Configuration instance, initialized with the default
# values.
def initialize
set_root_path!
self.frameworks = default_frameworks
self.load_paths = default_load_paths
self.load_once_paths = default_load_once_paths
self.eager_load_paths = default_eager_load_paths
self.log_path = default_log_path
self.log_level = default_log_level
self.view_path = default_view_path
self.controller_paths = default_controller_paths
self.preload_frameworks = default_preload_frameworks
self.cache_classes = default_cache_classes
self.dependency_loading = default_dependency_loading
self.whiny_nils = default_whiny_nils
self.plugins = default_plugins
self.plugin_paths = default_plugin_paths
self.plugin_locators = default_plugin_locators
self.plugin_loader = default_plugin_loader
self.database_configuration_file = default_database_configuration_file
self.routes_configuration_file = default_routes_configuration_file
self.gems = default_gems
self.i18n = default_i18n
for framework in default_frameworks
self.send("#{framework}=", Rails::OrderedOptions.new)
end
self.active_support = Rails::OrderedOptions.new
end
# Set the root_path to RAILS_ROOT and canonicalize it.
def set_root_path!
raise 'RAILS_ROOT is not set' unless defined?(::RAILS_ROOT)
raise 'RAILS_ROOT is not a directory' unless File.directory?(::RAILS_ROOT)
@root_path =
# Pathname is incompatible with Windows, but Windows doesn't have
# real symlinks so File.expand_path is safe.
if RUBY_PLATFORM =~ /(:?mswin|mingw)/
File.expand_path(::RAILS_ROOT)
# Otherwise use Pathname#realpath which respects symlinks.
else
Pathname.new(::RAILS_ROOT).realpath.to_s
end
Object.const_set(:RELATIVE_RAILS_ROOT, ::RAILS_ROOT.dup) unless defined?(::RELATIVE_RAILS_ROOT)
::RAILS_ROOT.replace @root_path
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | true |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/code_statistics.rb | provider/vendor/rails/railties/lib/code_statistics.rb | class CodeStatistics #:nodoc:
TEST_TYPES = %w(Units Functionals Unit\ tests Functional\ tests Integration\ tests)
def initialize(*pairs)
@pairs = pairs
@statistics = calculate_statistics
@total = calculate_total if pairs.length > 1
end
def to_s
print_header
@pairs.each { |pair| print_line(pair.first, @statistics[pair.first]) }
print_splitter
if @total
print_line("Total", @total)
print_splitter
end
print_code_test_stats
end
private
def calculate_statistics
@pairs.inject({}) { |stats, pair| stats[pair.first] = calculate_directory_statistics(pair.last); stats }
end
def calculate_directory_statistics(directory, pattern = /.*\.rb$/)
stats = { "lines" => 0, "codelines" => 0, "classes" => 0, "methods" => 0 }
Dir.foreach(directory) do |file_name|
if File.stat(directory + "/" + file_name).directory? and (/^\./ !~ file_name)
newstats = calculate_directory_statistics(directory + "/" + file_name, pattern)
stats.each { |k, v| stats[k] += newstats[k] }
end
next unless file_name =~ pattern
f = File.open(directory + "/" + file_name)
while line = f.gets
stats["lines"] += 1
stats["classes"] += 1 if line =~ /class [A-Z]/
stats["methods"] += 1 if line =~ /def [a-z]/
stats["codelines"] += 1 unless line =~ /^\s*$/ || line =~ /^\s*#/
end
end
stats
end
def calculate_total
total = { "lines" => 0, "codelines" => 0, "classes" => 0, "methods" => 0 }
@statistics.each_value { |pair| pair.each { |k, v| total[k] += v } }
total
end
def calculate_code
code_loc = 0
@statistics.each { |k, v| code_loc += v['codelines'] unless TEST_TYPES.include? k }
code_loc
end
def calculate_tests
test_loc = 0
@statistics.each { |k, v| test_loc += v['codelines'] if TEST_TYPES.include? k }
test_loc
end
def print_header
print_splitter
puts "| Name | Lines | LOC | Classes | Methods | M/C | LOC/M |"
print_splitter
end
def print_splitter
puts "+----------------------+-------+-------+---------+---------+-----+-------+"
end
def print_line(name, statistics)
m_over_c = (statistics["methods"] / statistics["classes"]) rescue m_over_c = 0
loc_over_m = (statistics["codelines"] / statistics["methods"]) - 2 rescue loc_over_m = 0
start = if TEST_TYPES.include? name
"| #{name.ljust(20)} "
else
"| #{name.ljust(20)} "
end
puts start +
"| #{statistics["lines"].to_s.rjust(5)} " +
"| #{statistics["codelines"].to_s.rjust(5)} " +
"| #{statistics["classes"].to_s.rjust(7)} " +
"| #{statistics["methods"].to_s.rjust(7)} " +
"| #{m_over_c.to_s.rjust(3)} " +
"| #{loc_over_m.to_s.rjust(5)} |"
end
def print_code_test_stats
code = calculate_code
tests = calculate_tests
puts " Code LOC: #{code} Test LOC: #{tests} Code to Test Ratio: 1:#{sprintf("%.1f", tests.to_f/code)}"
puts ""
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/test_help.rb | provider/vendor/rails/railties/lib/test_help.rb | # Make double-sure the RAILS_ENV is set to test,
# so fixtures are loaded to the right database
silence_warnings { RAILS_ENV = "test" }
require 'test/unit'
require 'action_controller/test_case'
require 'action_view/test_case'
require 'action_controller/integration'
require 'action_mailer/test_case' if defined?(ActionMailer)
if defined?(ActiveRecord)
require 'active_record/test_case'
require 'active_record/fixtures'
class ActiveSupport::TestCase
include ActiveRecord::TestFixtures
self.fixture_path = "#{RAILS_ROOT}/test/fixtures/"
self.use_instantiated_fixtures = false
self.use_transactional_fixtures = true
end
ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path
def create_fixtures(*table_names, &block)
Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
end
end
begin
require_library_or_gem 'ruby-debug'
Debugger.start
if Debugger.respond_to?(:settings)
Debugger.settings[:autoeval] = true
Debugger.settings[:autolist] = 1
end
rescue LoadError
# ruby-debug wasn't available so neither can the debugging be
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/console_sandbox.rb | provider/vendor/rails/railties/lib/console_sandbox.rb | ActiveRecord::Base.connection.increment_open_transactions
ActiveRecord::Base.connection.begin_db_transaction
at_exit do
ActiveRecord::Base.connection.rollback_db_transaction
ActiveRecord::Base.connection.decrement_open_transactions
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/fcgi_handler.rb | provider/vendor/rails/railties/lib/fcgi_handler.rb | require 'fcgi'
require 'logger'
require 'dispatcher'
require 'rbconfig'
class RailsFCGIHandler
SIGNALS = {
'HUP' => :reload,
'INT' => :exit_now,
'TERM' => :exit_now,
'USR1' => :exit,
'USR2' => :restart
}
GLOBAL_SIGNALS = SIGNALS.keys - %w(USR1)
attr_reader :when_ready
attr_accessor :log_file_path
attr_accessor :gc_request_period
# Initialize and run the FastCGI instance, passing arguments through to new.
def self.process!(*args, &block)
new(*args, &block).process!
end
# Initialize the FastCGI instance with the path to a crash log
# detailing unhandled exceptions (default RAILS_ROOT/log/fastcgi.crash.log)
# and the number of requests to process between garbage collection runs
# (default nil for normal GC behavior.) Optionally, pass a block which
# takes this instance as an argument for further configuration.
def initialize(log_file_path = nil, gc_request_period = nil)
self.log_file_path = log_file_path || "#{RAILS_ROOT}/log/fastcgi.crash.log"
self.gc_request_period = gc_request_period
# Yield for additional configuration.
yield self if block_given?
# Safely install signal handlers.
install_signal_handlers
@app = Dispatcher.new
# Start error timestamp at 11 seconds ago.
@last_error_on = Time.now - 11
end
def process!(provider = FCGI)
mark_features!
dispatcher_log :info, 'starting'
process_each_request provider
dispatcher_log :info, 'stopping gracefully'
rescue Exception => error
case error
when SystemExit
dispatcher_log :info, 'stopping after explicit exit'
when SignalException
dispatcher_error error, 'stopping after unhandled signal'
else
# Retry if exceptions occur more than 10 seconds apart.
if Time.now - @last_error_on > 10
@last_error_on = Time.now
dispatcher_error error, 'retrying after unhandled exception'
retry
else
dispatcher_error error, 'stopping after unhandled exception within 10 seconds of the last'
end
end
end
protected
def process_each_request(provider)
request = nil
catch :exit do
provider.each do |request|
process_request(request)
case when_ready
when :reload
reload!
when :restart
close_connection(request)
restart!
when :exit
close_connection(request)
throw :exit
end
end
end
rescue SignalException => signal
raise unless signal.message == 'SIGUSR1'
close_connection(request)
end
def process_request(request)
@processing, @when_ready = true, nil
gc_countdown
with_signal_handler 'USR1' do
begin
::Rack::Handler::FastCGI.serve(request, @app)
rescue SignalException, SystemExit
raise
rescue Exception => error
dispatcher_error error, 'unhandled dispatch error'
end
end
ensure
@processing = false
end
def logger
@logger ||= Logger.new(@log_file_path)
end
def dispatcher_log(level, msg)
time_str = Time.now.strftime("%d/%b/%Y:%H:%M:%S")
logger.send(level, "[#{time_str} :: #{$$}] #{msg}")
rescue Exception => log_error # Logger errors
STDERR << "Couldn't write to #{@log_file_path.inspect}: #{msg}\n"
STDERR << " #{log_error.class}: #{log_error.message}\n"
end
def dispatcher_error(e, msg = "")
error_message =
"Dispatcher failed to catch: #{e} (#{e.class})\n" +
" #{e.backtrace.join("\n ")}\n#{msg}"
dispatcher_log(:error, error_message)
end
def install_signal_handlers
GLOBAL_SIGNALS.each { |signal| install_signal_handler(signal) }
end
def install_signal_handler(signal, handler = nil)
if SIGNALS.include?(signal) && self.class.method_defined?(name = "#{SIGNALS[signal]}_handler")
handler ||= method(name).to_proc
begin
trap(signal, handler)
rescue ArgumentError
dispatcher_log :warn, "Ignoring unsupported signal #{signal}."
end
else
dispatcher_log :warn, "Ignoring unsupported signal #{signal}."
end
end
def with_signal_handler(signal)
install_signal_handler(signal)
yield
ensure
install_signal_handler(signal, 'DEFAULT')
end
def exit_now_handler(signal)
dispatcher_log :info, "asked to stop immediately"
exit
end
def exit_handler(signal)
dispatcher_log :info, "asked to stop ASAP"
if @processing
@when_ready = :exit
else
throw :exit
end
end
def reload_handler(signal)
dispatcher_log :info, "asked to reload ASAP"
if @processing
@when_ready = :reload
else
reload!
end
end
def restart_handler(signal)
dispatcher_log :info, "asked to restart ASAP"
if @processing
@when_ready = :restart
else
restart!
end
end
def restart!
config = ::Config::CONFIG
ruby = File::join(config['bindir'], config['ruby_install_name']) + config['EXEEXT']
command_line = [ruby, $0, ARGV].flatten.join(' ')
dispatcher_log :info, "restarted"
# close resources as they won't be closed by
# the OS when using exec
logger.close rescue nil
Rails.logger.close rescue nil
exec(command_line)
end
def reload!
run_gc! if gc_request_period
restore!
@when_ready = nil
dispatcher_log :info, "reloaded"
end
# Make a note of $" so we can safely reload this instance.
def mark_features!
@features = $".clone
end
def restore!
$".replace @features
Dispatcher.reset_application!
ActionController::Routing::Routes.reload
end
def run_gc!
@gc_request_countdown = gc_request_period
GC.enable; GC.start; GC.disable
end
def gc_countdown
if gc_request_period
@gc_request_countdown ||= gc_request_period
@gc_request_countdown -= 1
run_gc! if @gc_request_countdown <= 0
end
end
def close_connection(request)
request.finish if request
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator.rb | provider/vendor/rails/railties/lib/rails_generator.rb | #--
# Copyright (c) 2004 Jeremy Kemper
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
$:.unshift(File.dirname(__FILE__))
$:.unshift(File.dirname(__FILE__) + "/../../activesupport/lib")
begin
require 'active_support'
rescue LoadError
require 'rubygems'
gem 'activesupport'
end
require 'rails_generator/base'
require 'rails_generator/lookup'
require 'rails_generator/commands'
Rails::Generator::Base.send(:include, Rails::Generator::Lookup)
Rails::Generator::Base.send(:include, Rails::Generator::Commands)
# Set up a default logger for convenience.
require 'rails_generator/simple_logger'
Rails::Generator::Base.logger = Rails::Generator::SimpleLogger.new(STDOUT)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rubyprof_ext.rb | provider/vendor/rails/railties/lib/rubyprof_ext.rb | require 'prof'
module Prof #:nodoc:
# Adapted from Shugo Maeda's unprof.rb
def self.print_profile(results, io = $stderr)
total = results.detect { |i|
i.method_class.nil? && i.method_id == :"#toplevel"
}.total_time
total = 0.001 if total < 0.001
io.puts " %% cumulative self self total"
io.puts " time seconds seconds calls ms/call ms/call name"
sum = 0.0
for r in results
sum += r.self_time
name = if r.method_class.nil?
r.method_id.to_s
elsif r.method_class.is_a?(Class)
"#{r.method_class}##{r.method_id}"
else
"#{r.method_class}.#{r.method_id}"
end
io.printf "%6.2f %8.3f %8.3f %8d %8.2f %8.2f %s\n",
r.self_time / total * 100,
sum,
r.self_time,
r.count,
r.self_time * 1000 / r.count,
r.total_time * 1000 / r.count,
name
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/dispatcher.rb | provider/vendor/rails/railties/lib/dispatcher.rb | #--
# Copyright (c) 2004-2009 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
require 'action_controller/dispatcher'
Dispatcher = ActionController::Dispatcher
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands.rb | provider/vendor/rails/railties/lib/commands.rb | commands = Dir["#{File.dirname(__FILE__)}/commands/*.rb"].collect { |file_path| File.basename(file_path).split(".").first }
if commands.include?(ARGV.first)
require "#{File.dirname(__FILE__)}/commands/#{ARGV.shift}"
else
puts <<-USAGE
The 'run' provides a unified access point for all the default Rails' commands.
Usage: ./script/run <command> [OPTIONS]
Examples:
./script/run generate controller Admin
./script/run process reaper
USAGE
puts "Choose: #{commands.join(", ")}"
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/source_annotation_extractor.rb | provider/vendor/rails/railties/lib/source_annotation_extractor.rb | # Implements the logic behind the rake tasks for annotations like
#
# rake notes
# rake notes:optimize
#
# and friends. See <tt>rake -T notes</tt> and <tt>railties/lib/tasks/annotations.rake</tt>.
#
# Annotation objects are triplets <tt>:line</tt>, <tt>:tag</tt>, <tt>:text</tt> that
# represent the line where the annotation lives, its tag, and its text. Note
# the filename is not stored.
#
# Annotations are looked for in comments and modulus whitespace they have to
# start with the tag optionally followed by a colon. Everything up to the end
# of the line (or closing ERb comment tag) is considered to be their text.
class SourceAnnotationExtractor
class Annotation < Struct.new(:line, :tag, :text)
# Returns a representation of the annotation that looks like this:
#
# [126] [TODO] This algorithm is simple and clearly correct, make it faster.
#
# If +options+ has a flag <tt>:tag</tt> the tag is shown as in the example above.
# Otherwise the string contains just line and text.
def to_s(options={})
s = "[%3d] " % line
s << "[#{tag}] " if options[:tag]
s << text
end
end
# Prints all annotations with tag +tag+ under the root directories +app+, +lib+,
# and +test+ (recursively). Only filenames with extension +.builder+, +.rb+,
# +.rxml+, +.rjs+, +.rhtml+, or +.erb+ are taken into account. The +options+
# hash is passed to each annotation's +to_s+.
#
# This class method is the single entry point for the rake tasks.
def self.enumerate(tag, options={})
extractor = new(tag)
extractor.display(extractor.find, options)
end
attr_reader :tag
def initialize(tag)
@tag = tag
end
# Returns a hash that maps filenames under +dirs+ (recursively) to arrays
# with their annotations. Only files with annotations are included, and only
# those with extension +.builder+, +.rb+, +.rxml+, +.rjs+, +.rhtml+, and +.erb+
# are taken into account.
def find(dirs=%w(app lib test))
dirs.inject({}) { |h, dir| h.update(find_in(dir)) }
end
# Returns a hash that maps filenames under +dir+ (recursively) to arrays
# with their annotations. Only files with annotations are included, and only
# those with extension +.builder+, +.rb+, +.rxml+, +.rjs+, +.rhtml+, and +.erb+
# are taken into account.
def find_in(dir)
results = {}
Dir.glob("#{dir}/*") do |item|
next if File.basename(item)[0] == ?.
if File.directory?(item)
results.update(find_in(item))
elsif item =~ /\.(builder|(r(?:b|xml|js)))$/
results.update(extract_annotations_from(item, /#\s*(#{tag}):?\s*(.*)$/))
elsif item =~ /\.(rhtml|erb)$/
results.update(extract_annotations_from(item, /<%\s*#\s*(#{tag}):?\s*(.*?)\s*%>/))
end
end
results
end
# If +file+ is the filename of a file that contains annotations this method returns
# a hash with a single entry that maps +file+ to an array of its annotations.
# Otherwise it returns an empty hash.
def extract_annotations_from(file, pattern)
lineno = 0
result = File.readlines(file).inject([]) do |list, line|
lineno += 1
next list unless line =~ pattern
list << Annotation.new(lineno, $1, $2)
end
result.empty? ? {} : { file => result }
end
# Prints the mapping from filenames to annotations in +results+ ordered by filename.
# The +options+ hash is passed to each annotation's +to_s+.
def display(results, options={})
results.keys.sort.each do |file|
puts "#{file}:"
results[file].each do |note|
puts " * #{note.to_s(options)}"
end
puts
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/ruby_version_check.rb | provider/vendor/rails/railties/lib/ruby_version_check.rb | min_release = "1.8.2 (2004-12-25)"
ruby_release = "#{RUBY_VERSION} (#{RUBY_RELEASE_DATE})"
if ruby_release =~ /1\.8\.3/
abort <<-end_message
Rails does not work with Ruby version 1.8.3.
Please upgrade to version 1.8.4 or downgrade to 1.8.2.
end_message
elsif ruby_release < min_release
abort <<-end_message
Rails requires Ruby version #{min_release} or later.
You're running #{ruby_release}; please upgrade to continue.
end_message
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/console_with_helpers.rb | provider/vendor/rails/railties/lib/console_with_helpers.rb | def helper
@helper ||= ApplicationController.helpers
end
@controller = ApplicationController.new
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/webrick_server.rb | provider/vendor/rails/railties/lib/webrick_server.rb | # Donated by Florian Gross
require 'webrick'
require 'cgi'
require 'stringio'
require 'dispatcher'
include WEBrick
class CGI #:nodoc:
def stdinput
@stdin || $stdin
end
def env_table
@env_table || ENV
end
def initialize(type = "query", table = nil, stdin = nil)
@env_table, @stdin = table, stdin
if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
Apache.request.setup_cgi_env
end
extend QueryExtension
@multipart = false
if defined?(CGI_PARAMS)
warn "do not use CGI_PARAMS and CGI_COOKIES"
@params = CGI_PARAMS.dup
@cookies = CGI_COOKIES.dup
else
initialize_query() # set @params, @cookies
end
@output_cookies = nil
@output_hidden = nil
end
end
# A custom dispatch servlet for use with WEBrick. It dispatches requests
# (using the Rails Dispatcher) to the appropriate controller/action. By default,
# it restricts WEBrick to a managing a single Rails request at a time, but you
# can change this behavior by setting ActionController::Base.allow_concurrency
# to true.
class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
# Start the WEBrick server with the given options, mounting the
# DispatchServlet at <tt>/</tt>.
def self.dispatch(options = {})
Socket.do_not_reverse_lookup = true # patch for OS X
params = { :Port => options[:port].to_i,
:ServerType => options[:server_type],
:BindAddress => options[:ip] }
params[:MimeTypes] = options[:mime_types] if options[:mime_types]
server = WEBrick::HTTPServer.new(params)
server.mount('/', DispatchServlet, options)
trap("INT") { server.shutdown }
server.start
end
def initialize(server, options) #:nodoc:
@server_options = options
@file_handler = WEBrick::HTTPServlet::FileHandler.new(server, options[:server_root])
# Change to the RAILS_ROOT, since Webrick::Daemon.start does a Dir::cwd("/")
# OPTIONS['working_directory'] is an absolute path of the RAILS_ROOT, set in railties/lib/commands/servers/webrick.rb
Dir.chdir(OPTIONS['working_directory']) if defined?(OPTIONS) && File.directory?(OPTIONS['working_directory'])
super
end
def service(req, res) #:nodoc:
unless handle_file(req, res)
unless handle_dispatch(req, res)
raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
end
end
end
def handle_file(req, res) #:nodoc:
begin
req = req.dup
path = req.path.dup
# Add .html if the last path piece has no . in it
path << '.html' if path != '/' && (%r{(^|/)[^./]+$} =~ path)
path.gsub!('+', ' ') # Unescape + since FileHandler doesn't do so.
req.instance_variable_set(:@path_info, path) # Set the modified path...
@file_handler.send(:service, req, res)
return true
rescue HTTPStatus::PartialContent, HTTPStatus::NotModified => err
res.set_error(err)
return true
rescue => err
return false
end
end
def handle_dispatch(req, res, origin = nil) #:nodoc:
data = StringIO.new
Dispatcher.dispatch(
CGI.new("query", create_env_table(req, origin), StringIO.new(req.body || "")),
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS,
data
)
header, body = extract_header_and_body(data)
set_charset(header)
assign_status(res, header)
res.cookies.concat(header.delete('set-cookie') || [])
header.each { |key, val| res[key] = val.join(", ") }
res.body = body
return true
rescue => err
p err, err.backtrace
return false
end
private
def create_env_table(req, origin)
env = req.meta_vars.clone
env.delete "SCRIPT_NAME"
env["QUERY_STRING"] = req.request_uri.query
env["REQUEST_URI"] = origin if origin
return env
end
def extract_header_and_body(data)
data.rewind
data = data.read
raw_header, body = *data.split(/^[\xd\xa]{2}/on, 2)
header = WEBrick::HTTPUtils::parse_header(raw_header)
return header, body
end
def set_charset(header)
ct = header["content-type"]
if ct.any? { |x| x =~ /^text\// } && ! ct.any? { |x| x =~ /charset=/ }
ch = @server_options[:charset] || "UTF-8"
ct.find { |x| x =~ /^text\// } << ("; charset=" + ch)
end
end
def assign_status(res, header)
if /^(\d+)/ =~ header['status'][0]
res.status = $1.to_i
header.delete('status')
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/performance_test_help.rb | provider/vendor/rails/railties/lib/performance_test_help.rb | require 'action_controller/performance_test'
ActionController::Base.perform_caching = true
ActiveSupport::Dependencies.mechanism = :require
Rails.logger.level = ActiveSupport::BufferedLogger::INFO
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/tasks/rails.rb | provider/vendor/rails/railties/lib/tasks/rails.rb | $VERBOSE = nil
# Load Rails rakefile extensions
Dir["#{File.dirname(__FILE__)}/*.rake"].each { |ext| load ext }
# Load any custom rakefile extensions
Dir["#{RAILS_ROOT}/vendor/plugins/*/**/tasks/**/*.rake"].sort.each { |ext| load ext }
Dir["#{RAILS_ROOT}/lib/tasks/**/*.rake"].sort.each { |ext| load ext }
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/vendor_gem_source_index.rb | provider/vendor/rails/railties/lib/rails/vendor_gem_source_index.rb | require 'rubygems'
require 'yaml'
module Rails
class VendorGemSourceIndex
# VendorGemSourceIndex acts as a proxy for the Gem source index, allowing
# gems to be loaded from vendor/gems. Rather than the standard gem repository format,
# vendor/gems contains unpacked gems, with YAML specifications in .specification in
# each gem directory.
include Enumerable
attr_reader :installed_source_index
attr_reader :vendor_source_index
@@silence_spec_warnings = false
def self.silence_spec_warnings
@@silence_spec_warnings
end
def self.silence_spec_warnings=(v)
@@silence_spec_warnings = v
end
def initialize(installed_index, vendor_dir=Rails::GemDependency.unpacked_path)
@installed_source_index = installed_index
@vendor_dir = vendor_dir
refresh!
end
def refresh!
# reload the installed gems
@installed_source_index.refresh!
vendor_gems = {}
# handle vendor Rails gems - they are identified by having loaded_from set to ""
# we add them manually to the list, so that other gems can find them via dependencies
Gem.loaded_specs.each do |n, s|
next unless s.loaded_from.empty?
vendor_gems[s.full_name] = s
end
# load specifications from vendor/gems
Dir[File.join(Rails::GemDependency.unpacked_path, '*')].each do |d|
dir_name = File.basename(d)
dir_version = version_for_dir(dir_name)
spec = load_specification(d)
if spec
if spec.full_name != dir_name
# mismatched directory name and gem spec - produced by 2.1.0-era unpack code
if dir_version
# fix the spec version - this is not optimal (spec.files may be wrong)
# but it's better than breaking apps. Complain to remind users to get correct specs.
# use ActiveSupport::Deprecation.warn, as the logger is not set yet
$stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems has a mismatched specification file."+
" Run 'rake gems:refresh_specs' to fix this.") unless @@silence_spec_warnings
spec.version = dir_version
else
$stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems is not in a versioned directory"+
"(should be #{spec.full_name}).") unless @@silence_spec_warnings
# continue, assume everything is OK
end
end
else
# no spec - produced by early-2008 unpack code
# emulate old behavior, and complain.
$stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems has no specification file."+
" Run 'rake gems:refresh_specs' to fix this.") unless @@silence_spec_warnings
if dir_version
spec = Gem::Specification.new
spec.version = dir_version
spec.require_paths = ['lib']
ext_path = File.join(d, 'ext')
spec.require_paths << 'ext' if File.exist?(ext_path)
spec.name = /^(.*)-[^-]+$/.match(dir_name)[1]
files = ['lib']
# set files to everything in lib/
files += Dir[File.join(d, 'lib', '*')].map { |v| v.gsub(/^#{d}\//, '') }
files += Dir[File.join(d, 'ext', '*')].map { |v| v.gsub(/^#{d}\//, '') } if ext_path
spec.files = files
else
$stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems not in a versioned directory."+
" Giving up.") unless @@silence_spec_warnings
next
end
end
spec.loaded_from = File.join(d, '.specification')
# finally, swap out full_gem_path
# it would be better to use a Gem::Specification subclass, but the YAML loads an explicit class
class << spec
def full_gem_path
path = File.join installation_path, full_name
return path if File.directory? path
File.join installation_path, original_name
end
end
vendor_gems[File.basename(d)] = spec
end
@vendor_source_index = Gem::SourceIndex.new(vendor_gems)
end
def version_for_dir(d)
matches = /-([^-]+)$/.match(d)
Gem::Version.new(matches[1]) if matches
end
def load_specification(gem_dir)
spec_file = File.join(gem_dir, '.specification')
YAML.load_file(spec_file) if File.exist?(spec_file)
end
def find_name(*args)
@installed_source_index.find_name(*args) + @vendor_source_index.find_name(*args)
end
def search(*args)
# look for vendor gems, and then installed gems - later elements take priority
@installed_source_index.search(*args) + @vendor_source_index.search(*args)
end
def each(&block)
@vendor_source_index.each(&block)
@installed_source_index.each(&block)
end
def add_spec(spec)
@vendor_source_index.add_spec spec
end
def remove_spec(spec)
@vendor_source_index.remove_spec spec
end
def size
@vendor_source_index.size + @installed_source_index.size
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/version.rb | provider/vendor/rails/railties/lib/rails/version.rb | module Rails
module VERSION #:nodoc:
MAJOR = 2
MINOR = 3
TINY = 4
STRING = [MAJOR, MINOR, TINY].join('.')
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/rack.rb | provider/vendor/rails/railties/lib/rails/rack.rb | module Rails
module Rack
autoload :Debugger, "rails/rack/debugger"
autoload :LogTailer, "rails/rack/log_tailer"
autoload :Metal, "rails/rack/metal"
autoload :Static, "rails/rack/static"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/plugin.rb | provider/vendor/rails/railties/lib/rails/plugin.rb | module Rails
# The Plugin class should be an object which provides the following methods:
#
# * +name+ - Used during initialisation to order the plugin (based on name and
# the contents of <tt>config.plugins</tt>).
# * +valid?+ - Returns true if this plugin can be loaded.
# * +load_paths+ - Each path within the returned array will be added to the <tt>$LOAD_PATH</tt>.
# * +load+ - Finally 'load' the plugin.
#
# These methods are expected by the Rails::Plugin::Locator and Rails::Plugin::Loader classes.
# The default implementation returns the <tt>lib</tt> directory as its <tt>load_paths</tt>,
# and evaluates <tt>init.rb</tt> when <tt>load</tt> is called.
#
# You can also inspect the about.yml data programmatically:
#
# plugin = Rails::Plugin.new(path_to_my_plugin)
# plugin.about["author"] # => "James Adam"
# plugin.about["url"] # => "http://interblah.net"
class Plugin
include Comparable
attr_reader :directory, :name
def initialize(directory)
@directory = directory
@name = File.basename(@directory) rescue nil
@loaded = false
end
def valid?
File.directory?(directory) && (has_app_directory? || has_lib_directory? || has_init_file?)
end
# Returns a list of paths this plugin wishes to make available in <tt>$LOAD_PATH</tt>.
def load_paths
report_nonexistant_or_empty_plugin! unless valid?
returning [] do |load_paths|
load_paths << lib_path if has_lib_directory?
load_paths << app_paths if has_app_directory?
end.flatten
end
# Evaluates a plugin's init.rb file.
def load(initializer)
return if loaded?
report_nonexistant_or_empty_plugin! unless valid?
evaluate_init_rb(initializer)
@loaded = true
end
def loaded?
@loaded
end
def <=>(other_plugin)
name <=> other_plugin.name
end
def about
@about ||= load_about_information
end
# Engines are plugins with an app/ directory.
def engine?
has_app_directory?
end
# Returns true if the engine ships with a routing file
def routed?
File.exist?(routing_file)
end
# Returns true if there is any localization file in locale_path
def localized?
locale_files.any?
end
def view_path
File.join(directory, 'app', 'views')
end
def controller_path
File.join(directory, 'app', 'controllers')
end
def metal_path
File.join(directory, 'app', 'metal')
end
def routing_file
File.join(directory, 'config', 'routes.rb')
end
def locale_path
File.join(directory, 'config', 'locales')
end
def locale_files
Dir[ File.join(locale_path, '*.{rb,yml}') ]
end
private
def load_about_information
about_yml_path = File.join(@directory, "about.yml")
parsed_yml = File.exist?(about_yml_path) ? YAML.load(File.read(about_yml_path)) : {}
parsed_yml || {}
rescue Exception
{}
end
def report_nonexistant_or_empty_plugin!
raise LoadError, "Can not find the plugin named: #{name}"
end
def app_paths
[ File.join(directory, 'app', 'models'), File.join(directory, 'app', 'helpers'), controller_path, metal_path ]
end
def lib_path
File.join(directory, 'lib')
end
def classic_init_path
File.join(directory, 'init.rb')
end
def gem_init_path
File.join(directory, 'rails', 'init.rb')
end
def init_path
File.file?(gem_init_path) ? gem_init_path : classic_init_path
end
def has_app_directory?
File.directory?(File.join(directory, 'app'))
end
def has_lib_directory?
File.directory?(lib_path)
end
def has_init_file?
File.file?(init_path)
end
def evaluate_init_rb(initializer)
if has_init_file?
silence_warnings do
# Allow plugins to reference the current configuration object
config = initializer.configuration
eval(IO.read(init_path), binding, init_path)
end
end
end
end
# This Plugin subclass represents a Gem plugin. Although RubyGems has already
# taken care of $LOAD_PATHs, it exposes its load_paths to add them
# to Dependencies.load_paths.
class GemPlugin < Plugin
# Initialize this plugin from a Gem::Specification.
def initialize(spec, gem)
directory = spec.full_gem_path
super(directory)
@name = spec.name
end
def init_path
File.join(directory, 'rails', 'init.rb')
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/gem_dependency.rb | provider/vendor/rails/railties/lib/rails/gem_dependency.rb | require 'rails/vendor_gem_source_index'
module Gem
def self.source_index=(index)
@@source_index = index
end
end
module Rails
class GemDependency < Gem::Dependency
attr_accessor :lib, :source, :dep
def self.unpacked_path
@unpacked_path ||= File.join(RAILS_ROOT, 'vendor', 'gems')
end
@@framework_gems = {}
def self.add_frozen_gem_path
@@paths_loaded ||= begin
source_index = Rails::VendorGemSourceIndex.new(Gem.source_index)
Gem.clear_paths
Gem.source_index = source_index
# loaded before us - we can't change them, so mark them
Gem.loaded_specs.each do |name, spec|
@@framework_gems[name] = spec
end
true
end
end
def self.from_directory_name(directory_name, load_spec=true)
directory_name_parts = File.basename(directory_name).split('-')
name = directory_name_parts[0..-2].join('-')
version = directory_name_parts.last
result = self.new(name, :version => version)
spec_filename = File.join(directory_name, '.specification')
if load_spec
raise "Missing specification file in #{File.dirname(spec_filename)}. Perhaps you need to do a 'rake gems:refresh_specs'?" unless File.exists?(spec_filename)
spec = YAML::load_file(spec_filename)
result.specification = spec
end
result
rescue ArgumentError => e
raise "Unable to determine gem name and version from '#{directory_name}'"
end
def initialize(name, options = {})
require 'rubygems' unless Object.const_defined?(:Gem)
if options[:requirement]
req = options[:requirement]
elsif options[:version]
req = Gem::Requirement.create(options[:version])
else
req = Gem::Requirement.default
end
@lib = options[:lib]
@source = options[:source]
@loaded = @frozen = @load_paths_added = false
super(name, req)
end
def add_load_paths
self.class.add_frozen_gem_path
return if @loaded || @load_paths_added
if framework_gem?
@load_paths_added = @loaded = @frozen = true
return
end
gem self
@spec = Gem.loaded_specs[name]
@frozen = @spec.loaded_from.include?(self.class.unpacked_path) if @spec
@load_paths_added = true
rescue Gem::LoadError
end
def dependencies
return [] if framework_gem?
return [] unless installed?
specification.dependencies.reject do |dependency|
dependency.type == :development
end.map do |dependency|
GemDependency.new(dependency.name, :requirement => dependency.version_requirements)
end
end
def specification
# code repeated from Gem.activate. Find a matching spec, or the currently loaded version.
# error out if loaded version and requested version are incompatible.
@spec ||= begin
matches = Gem.source_index.search(self)
matches << @@framework_gems[name] if framework_gem?
if Gem.loaded_specs[name] then
# This gem is already loaded. If the currently loaded gem is not in the
# list of candidate gems, then we have a version conflict.
existing_spec = Gem.loaded_specs[name]
unless matches.any? { |spec| spec.version == existing_spec.version } then
raise Gem::Exception,
"can't activate #{@dep}, already activated #{existing_spec.full_name}"
end
# we're stuck with it, so change to match
version_requirements = Gem::Requirement.create("=#{existing_spec.version}")
existing_spec
else
# new load
matches.last
end
end
end
def specification=(s)
@spec = s
end
def requirement
r = version_requirements
(r == Gem::Requirement.default) ? nil : r
end
def built?
return false unless frozen?
if vendor_gem?
specification.extensions.each do |ext|
makefile = File.join(unpacked_gem_directory, File.dirname(ext), 'Makefile')
return false unless File.exists?(makefile)
end
end
true
end
def framework_gem?
@@framework_gems.has_key?(name)
end
def frozen?
@frozen ||= vendor_rails? || vendor_gem?
end
def installed?
Gem.loaded_specs.keys.include?(name)
end
def load_paths_added?
# always try to add load paths - even if a gem is loaded, it may not
# be a compatible version (ie random_gem 0.4 is loaded and a later spec
# needs >= 0.5 - gem 'random_gem' will catch this and error out)
@load_paths_added
end
def loaded?
@loaded ||= begin
if vendor_rails?
true
elsif specification.nil?
false
else
# check if the gem is loaded by inspecting $"
# specification.files lists all the files contained in the gem
gem_files = specification.files
# select only the files contained in require_paths - typically in bin and lib
require_paths_regexp = Regexp.new("^(#{specification.require_paths*'|'})/")
gem_lib_files = gem_files.select { |f| require_paths_regexp.match(f) }
# chop the leading directory off - a typical file might be in
# lib/gem_name/file_name.rb, but it will be 'require'd as gem_name/file_name.rb
gem_lib_files.map! { |f| f.split('/', 2)[1] }
# if any of the files from the above list appear in $", the gem is assumed to
# have been loaded
!(gem_lib_files & $").empty?
end
end
end
def vendor_rails?
Gem.loaded_specs.has_key?(name) && Gem.loaded_specs[name].loaded_from.empty?
end
def vendor_gem?
specification && File.exists?(unpacked_gem_directory)
end
def build(options={})
require 'rails/gem_builder'
return if specification.nil?
if options[:force] || !built?
return unless File.exists?(unpacked_specification_filename)
spec = YAML::load_file(unpacked_specification_filename)
Rails::GemBuilder.new(spec, unpacked_gem_directory).build_extensions
puts "Built gem: '#{unpacked_gem_directory}'"
end
dependencies.each { |dep| dep.build(options) }
end
def install
unless installed?
cmd = "#{gem_command} #{install_command.join(' ')}"
puts cmd
puts %x(#{cmd})
end
end
def load
return if @loaded || @load_paths_added == false
require(@lib || name) unless @lib == false
@loaded = true
rescue LoadError
puts $!.to_s
$!.backtrace.each { |b| puts b }
end
def refresh
Rails::VendorGemSourceIndex.silence_spec_warnings = true
real_gems = Gem.source_index.installed_source_index
exact_dep = Gem::Dependency.new(name, "= #{specification.version}")
matches = real_gems.search(exact_dep)
installed_spec = matches.first
if frozen?
if installed_spec
# we have a real copy
# get a fresh spec - matches should only have one element
# note that there is no reliable method to check that the loaded
# spec is the same as the copy from real_gems - Gem.activate changes
# some of the fields
real_spec = Gem::Specification.load(matches.first.loaded_from)
write_specification(real_spec)
puts "Reloaded specification for #{name} from installed gems."
else
# the gem isn't installed locally - write out our current specs
write_specification(specification)
puts "Gem #{name} not loaded locally - writing out current spec."
end
else
if framework_gem?
puts "Gem directory for #{name} not found - check if it's loading before rails."
else
puts "Something bad is going on - gem directory not found for #{name}."
end
end
end
def unpack(options={})
unless frozen? || framework_gem?
FileUtils.mkdir_p unpack_base
Dir.chdir unpack_base do
Gem::GemRunner.new.run(unpack_command)
end
# Gem.activate changes the spec - get the original
real_spec = Gem::Specification.load(specification.loaded_from)
write_specification(real_spec)
end
dependencies.each { |dep| dep.unpack(options) } if options[:recursive]
end
def write_specification(spec)
# copy the gem's specification into GEMDIR/.specification so that
# we can access information about the gem on deployment systems
# without having the gem installed
File.open(unpacked_specification_filename, 'w') do |file|
file.puts spec.to_yaml
end
end
def ==(other)
self.name == other.name && self.requirement == other.requirement
end
alias_method :"eql?", :"=="
private
def gem_command
case RUBY_PLATFORM
when /win32/
'gem.bat'
when /java/
'jruby -S gem'
else
'gem'
end
end
def install_command
cmd = %w(install) << name
cmd << "--version" << %("#{requirement.to_s}") if requirement
cmd << "--source" << @source if @source
cmd
end
def unpack_command
cmd = %w(unpack) << name
cmd << "--version" << "= "+specification.version.to_s if requirement
cmd
end
def unpack_base
Rails::GemDependency.unpacked_path
end
def unpacked_gem_directory
File.join(unpack_base, specification.full_name)
end
def unpacked_specification_filename
File.join(unpacked_gem_directory, '.specification')
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/gem_builder.rb | provider/vendor/rails/railties/lib/rails/gem_builder.rb | require 'rubygems'
require 'rubygems/installer'
module Rails
# this class hijacks the functionality of Gem::Installer by overloading its
# initializer to only provide the information needed by
# Gem::Installer#build_extensions (which happens to be what we have)
class GemBuilder < Gem::Installer
def initialize(spec, gem_dir)
@spec = spec
@gem_dir = gem_dir
end
# silence the underlying builder
def say(message)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/backtrace_cleaner.rb | provider/vendor/rails/railties/lib/rails/backtrace_cleaner.rb | module Rails
class BacktraceCleaner < ActiveSupport::BacktraceCleaner
ERB_METHOD_SIG = /:in `_run_erb_.*/
RAILS_GEMS = %w( actionpack activerecord actionmailer activesupport activeresource rails )
VENDOR_DIRS = %w( vendor/rails )
SERVER_DIRS = %w( lib/mongrel bin/mongrel
lib/passenger bin/passenger-spawn-server
lib/rack )
RAILS_NOISE = %w( script/server )
RUBY_NOISE = %w( rubygems/custom_require benchmark.rb )
ALL_NOISE = VENDOR_DIRS + SERVER_DIRS + RAILS_NOISE + RUBY_NOISE
def initialize
super
add_filter { |line| line.sub("#{RAILS_ROOT}/", '') }
add_filter { |line| line.sub(ERB_METHOD_SIG, '') }
add_filter { |line| line.sub('./', '/') } # for tests
add_gem_filters
add_silencer { |line| ALL_NOISE.any? { |dir| line.include?(dir) } }
add_silencer { |line| RAILS_GEMS.any? { |gem| line =~ /^#{gem} / } }
add_silencer { |line| line =~ %r(vendor/plugins/[^\/]+/lib) }
end
private
def add_gem_filters
Gem.path.each do |path|
# http://gist.github.com/30430
add_filter { |line| line.sub(/(#{path})\/gems\/([a-z]+)-([0-9.]+)\/(.*)/, '\2 (\3) \4')}
end
vendor_gems_path = Rails::GemDependency.unpacked_path.sub("#{RAILS_ROOT}/",'')
add_filter { |line| line.sub(/(#{vendor_gems_path})\/([a-z]+)-([0-9.]+)\/(.*)/, '\2 (\3) [v] \4')}
end
end
# For installing the BacktraceCleaner in the test/unit
module BacktraceFilterForTestUnit #:nodoc:
def self.included(klass)
klass.send :alias_method_chain, :filter_backtrace, :cleaning
end
def filter_backtrace_with_cleaning(backtrace, prefix=nil)
backtrace = filter_backtrace_without_cleaning(backtrace, prefix)
backtrace = backtrace.first.split("\n") if backtrace.size == 1
Rails.backtrace_cleaner.clean(backtrace)
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/plugin/loader.rb | provider/vendor/rails/railties/lib/rails/plugin/loader.rb | require "rails/plugin"
module Rails
class Plugin
class Loader
attr_reader :initializer
# Creates a new Plugin::Loader instance, associated with the given
# Rails::Initializer. This default implementation automatically locates
# all plugins, and adds all plugin load paths, when it is created. The plugins
# are then fully loaded (init.rb is evaluated) when load_plugins is called.
#
# It is the loader's responsibility to ensure that only the plugins specified
# in the configuration are actually loaded, and that the order defined
# is respected.
def initialize(initializer)
@initializer = initializer
end
# Returns the plugins to be loaded, in the order they should be loaded.
def plugins
@plugins ||= all_plugins.select { |plugin| should_load?(plugin) }.sort { |p1, p2| order_plugins(p1, p2) }
end
# Returns the plugins that are in engine-form (have an app/ directory)
def engines
@engines ||= plugins.select(&:engine?)
end
# Returns all the plugins that could be found by the current locators.
def all_plugins
@all_plugins ||= locate_plugins
@all_plugins
end
def load_plugins
plugins.each do |plugin|
plugin.load(initializer)
register_plugin_as_loaded(plugin)
end
configure_engines
ensure_all_registered_plugins_are_loaded!
end
# Adds the load paths for every plugin into the $LOAD_PATH. Plugin load paths are
# added *after* the application's <tt>lib</tt> directory, to ensure that an application
# can always override code within a plugin.
#
# Plugin load paths are also added to Dependencies.load_paths, and Dependencies.load_once_paths.
def add_plugin_load_paths
plugins.each do |plugin|
plugin.load_paths.each do |path|
$LOAD_PATH.insert(application_lib_index + 1, path)
ActiveSupport::Dependencies.load_paths << path
unless configuration.reload_plugins?
ActiveSupport::Dependencies.load_once_paths << path
end
end
end
$LOAD_PATH.uniq!
end
def engine_metal_paths
engines.collect(&:metal_path)
end
protected
def configure_engines
if engines.any?
add_engine_routing_configurations
add_engine_locales
add_engine_controller_paths
add_engine_view_paths
end
end
def add_engine_routing_configurations
engines.select(&:routed?).collect(&:routing_file).each do |routing_file|
ActionController::Routing::Routes.add_configuration_file(routing_file)
end
end
def add_engine_locales
# reverse it such that the last engine can overwrite translations from the first, like with routes
locale_files = engines.select(&:localized?).collect(&:locale_files).reverse.flatten
I18n.load_path += locale_files - I18n.load_path
end
def add_engine_controller_paths
ActionController::Routing.controller_paths += engines.collect(&:controller_path)
end
def add_engine_view_paths
# reverse it such that the last engine can overwrite view paths from the first, like with routes
paths = ActionView::PathSet.new(engines.collect(&:view_path).reverse)
ActionController::Base.view_paths.concat(paths)
ActionMailer::Base.view_paths.concat(paths) if configuration.frameworks.include?(:action_mailer)
end
# The locate_plugins method uses each class in config.plugin_locators to
# find the set of all plugins available to this Rails application.
def locate_plugins
configuration.plugin_locators.map do |locator|
locator.new(initializer).plugins
end.flatten
# TODO: sorting based on config.plugins
end
def register_plugin_as_loaded(plugin)
initializer.loaded_plugins << plugin
end
def configuration
initializer.configuration
end
def should_load?(plugin)
# uses Plugin#name and Plugin#valid?
enabled?(plugin) && plugin.valid?
end
def order_plugins(plugin_a, plugin_b)
if !explicit_plugin_loading_order?
plugin_a <=> plugin_b
else
if !explicitly_enabled?(plugin_a) && !explicitly_enabled?(plugin_b)
plugin_a <=> plugin_b
else
effective_order_of(plugin_a) <=> effective_order_of(plugin_b)
end
end
end
def effective_order_of(plugin)
if explicitly_enabled?(plugin)
registered_plugin_names.index(plugin.name)
else
registered_plugin_names.index('all')
end
end
def application_lib_index
$LOAD_PATH.index(File.join(RAILS_ROOT, 'lib')) || 0
end
def enabled?(plugin)
!explicit_plugin_loading_order? || registered?(plugin)
end
def explicit_plugin_loading_order?
!registered_plugin_names.nil?
end
def registered?(plugin)
explicit_plugin_loading_order? && registered_plugins_names_plugin?(plugin)
end
def explicitly_enabled?(plugin)
!explicit_plugin_loading_order? || explicitly_registered?(plugin)
end
def explicitly_registered?(plugin)
explicit_plugin_loading_order? && registered_plugin_names.include?(plugin.name)
end
def registered_plugins_names_plugin?(plugin)
registered_plugin_names.include?(plugin.name) || registered_plugin_names.include?('all')
end
# The plugins that have been explicitly listed with config.plugins. If this list is nil
# then it means the client does not care which plugins or in what order they are loaded,
# so we load all in alphabetical order. If it is an empty array, we load no plugins, if it is
# non empty, we load the named plugins in the order specified.
def registered_plugin_names
configuration.plugins ? configuration.plugins.map(&:to_s) : nil
end
def loaded?(plugin_name)
initializer.loaded_plugins.detect { |plugin| plugin.name == plugin_name.to_s }
end
def ensure_all_registered_plugins_are_loaded!
if explicit_plugin_loading_order?
if configuration.plugins.detect {|plugin| plugin != :all && !loaded?(plugin) }
missing_plugins = configuration.plugins - (plugins.map{|p| p.name.to_sym} + [:all])
raise LoadError, "Could not locate the following plugins: #{missing_plugins.to_sentence(:locale => :en)}"
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/plugin/locator.rb | provider/vendor/rails/railties/lib/rails/plugin/locator.rb | module Rails
class Plugin
# The Plugin::Locator class should be subclasses to provide custom plugin-finding
# abilities to Rails (i.e. loading plugins from Gems, etc). Each subclass should implement
# the <tt>located_plugins</tt> method, which return an array of Plugin objects that have been found.
class Locator
include Enumerable
attr_reader :initializer
def initialize(initializer)
@initializer = initializer
end
# This method should return all the plugins which this Plugin::Locator can find
# These will then be used by the current Plugin::Loader, which is responsible for actually
# loading the plugins themselves
def plugins
raise "The `plugins' method must be defined by concrete subclasses of #{self.class}"
end
def each(&block)
plugins.each(&block)
end
def plugin_names
plugins.map(&:name)
end
end
# The Rails::Plugin::FileSystemLocator will try to locate plugins by examining the directories
# in the paths given in configuration.plugin_paths. Any plugins that can be found are returned
# in a list.
#
# The criteria for a valid plugin in this case is found in Rails::Plugin#valid?, although
# other subclasses of Rails::Plugin::Locator can of course use different conditions.
class FileSystemLocator < Locator
# Returns all the plugins which can be loaded in the filesystem, under the paths given
# by configuration.plugin_paths.
def plugins
initializer.configuration.plugin_paths.flatten.inject([]) do |plugins, path|
plugins.concat locate_plugins_under(path)
plugins
end.flatten
end
private
# Attempts to create a plugin from the given path. If the created plugin is valid?
# (see Rails::Plugin#valid?) then the plugin instance is returned; otherwise nil.
def create_plugin(path)
plugin = Rails::Plugin.new(path)
plugin.valid? ? plugin : nil
end
# This starts at the base path looking for valid plugins (see Rails::Plugin#valid?).
# Since plugins can be nested arbitrarily deep within an unspecified number of intermediary
# directories, this method runs recursively until it finds a plugin directory, e.g.
#
# locate_plugins_under('vendor/plugins/acts/acts_as_chunky_bacon')
# => <Rails::Plugin name: 'acts_as_chunky_bacon' ... >
#
def locate_plugins_under(base_path)
Dir.glob(File.join(base_path, '*')).sort.inject([]) do |plugins, path|
if plugin = create_plugin(path)
plugins << plugin
elsif File.directory?(path)
plugins.concat locate_plugins_under(path)
end
plugins
end
end
end
# The GemLocator scans all the loaded RubyGems, looking for gems with
# a <tt>rails/init.rb</tt> file.
class GemLocator < Locator
def plugins
gem_index = initializer.configuration.gems.inject({}) { |memo, gem| memo.update gem.specification => gem }
specs = gem_index.keys
specs += Gem.loaded_specs.values.select do |spec|
spec.loaded_from && # prune stubs
File.exist?(File.join(spec.full_gem_path, "rails", "init.rb"))
end
specs.compact!
require "rubygems/dependency_list"
deps = Gem::DependencyList.new
deps.add(*specs) unless specs.empty?
deps.dependency_order.collect do |spec|
Rails::GemPlugin.new(spec, gem_index[spec])
end
end
end
end
end | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/rack/log_tailer.rb | provider/vendor/rails/railties/lib/rails/rack/log_tailer.rb | module Rails
module Rack
class LogTailer
EnvironmentLog = "#{File.expand_path(Rails.root)}/log/#{Rails.env}.log"
def initialize(app, log = nil)
@app = app
path = Pathname.new(log || EnvironmentLog).cleanpath
@cursor = ::File.size(path)
@last_checked = Time.now.to_f
@file = ::File.open(path, 'r')
end
def call(env)
response = @app.call(env)
tail_log
response
end
def tail_log
@file.seek @cursor
mod = @file.mtime.to_f
if mod > @last_checked
contents = @file.read
@last_checked = mod
@cursor += contents.size
$stdout.print contents
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/rack/debugger.rb | provider/vendor/rails/railties/lib/rails/rack/debugger.rb | module Rails
module Rack
class Debugger
def initialize(app)
@app = app
require_library_or_gem 'ruby-debug'
::Debugger.start
::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings)
puts "=> Debugger enabled"
rescue Exception
puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'"
exit
end
def call(env)
@app.call(env)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/rack/static.rb | provider/vendor/rails/railties/lib/rails/rack/static.rb | require 'rack/utils'
module Rails
module Rack
class Static
FILE_METHODS = %w(GET HEAD).freeze
def initialize(app)
@app = app
@file_server = ::Rack::File.new(File.join(RAILS_ROOT, "public"))
end
def call(env)
path = env['PATH_INFO'].chomp('/')
method = env['REQUEST_METHOD']
if FILE_METHODS.include?(method)
if file_exist?(path)
return @file_server.call(env)
else
cached_path = directory_exist?(path) ? "#{path}/index" : path
cached_path += ::ActionController::Base.page_cache_extension
if file_exist?(cached_path)
env['PATH_INFO'] = cached_path
return @file_server.call(env)
end
end
end
@app.call(env)
end
private
def file_exist?(path)
full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path))
File.file?(full_path) && File.readable?(full_path)
end
def directory_exist?(path)
full_path = File.join(@file_server.root, ::Rack::Utils.unescape(path))
File.directory?(full_path) && File.readable?(full_path)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails/rack/metal.rb | provider/vendor/rails/railties/lib/rails/rack/metal.rb | require 'active_support/ordered_hash'
module Rails
module Rack
class Metal
NotFoundResponse = [404, {}, []].freeze
NotFound = lambda { NotFoundResponse }
cattr_accessor :metal_paths
self.metal_paths = ["#{Rails.root}/app/metal"]
cattr_accessor :requested_metals
def self.metals
matcher = /#{Regexp.escape('/app/metal/')}(.*)\.rb\Z/
metal_glob = metal_paths.map{ |base| "#{base}/**/*.rb" }
all_metals = {}
metal_glob.each do |glob|
Dir[glob].sort.map do |file|
file = file.match(matcher)[1]
all_metals[file.camelize] = file
end
end
load_list = requested_metals || all_metals.keys
load_list.map do |requested_metal|
if metal = all_metals[requested_metal]
require_dependency metal
requested_metal.constantize
end
end.compact
end
def initialize(app)
@app = app
@metals = ActiveSupport::OrderedHash.new
self.class.metals.each { |app| @metals[app] = true }
freeze
end
def call(env)
@metals.keys.each do |app|
result = app.call(env)
return result unless result[0].to_i == 404
end
@app.call(env)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/dbconsole.rb | provider/vendor/rails/railties/lib/commands/dbconsole.rb | require 'erb'
require 'yaml'
require 'optparse'
include_password = false
options = {}
OptionParser.new do |opt|
opt.banner = "Usage: dbconsole [options] [environment]"
opt.on("-p", "--include-password", "Automatically provide the password from database.yml") do |v|
include_password = true
end
opt.on("--mode [MODE]", ['html', 'list', 'line', 'column'],
"Automatically put the sqlite3 database in the specified mode (html, list, line, column).") do |mode|
options['mode'] = mode
end
opt.on("-h", "--header") do |h|
options['header'] = h
end
opt.parse!(ARGV)
abort opt.to_s unless (0..1).include?(ARGV.size)
end
env = ARGV.first || ENV['RAILS_ENV'] || 'development'
unless config = YAML::load(ERB.new(IO.read(RAILS_ROOT + "/config/database.yml")).result)[env]
abort "No database is configured for the environment '#{env}'"
end
def find_cmd(*commands)
dirs_on_path = ENV['PATH'].to_s.split(File::PATH_SEPARATOR)
commands += commands.map{|cmd| "#{cmd}.exe"} if RUBY_PLATFORM =~ /win32/
full_path_command = nil
found = commands.detect do |cmd|
dir = dirs_on_path.detect do |path|
full_path_command = File.join(path, cmd)
File.executable? full_path_command
end
end
found ? full_path_command : abort("Couldn't find database client: #{commands.join(', ')}. Check your $PATH and try again.")
end
case config["adapter"]
when "mysql"
args = {
'host' => '--host',
'port' => '--port',
'socket' => '--socket',
'username' => '--user',
'encoding' => '--default-character-set'
}.map { |opt, arg| "#{arg}=#{config[opt]}" if config[opt] }.compact
if config['password'] && include_password
args << "--password=#{config['password']}"
elsif config['password'] && !config['password'].to_s.empty?
args << "-p"
end
args << config['database']
exec(find_cmd('mysql', 'mysql5'), *args)
when "postgresql"
ENV['PGUSER'] = config["username"] if config["username"]
ENV['PGHOST'] = config["host"] if config["host"]
ENV['PGPORT'] = config["port"].to_s if config["port"]
ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && include_password
exec(find_cmd('psql'), config["database"])
when "sqlite"
exec(find_cmd('sqlite'), config["database"])
when "sqlite3"
args = []
args << "-#{options['mode']}" if options['mode']
args << "-header" if options['header']
args << config['database']
exec(find_cmd('sqlite3'), *args)
else
abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/update.rb | provider/vendor/rails/railties/lib/commands/update.rb | require "#{RAILS_ROOT}/config/environment"
require 'rails_generator'
require 'rails_generator/scripts/update'
Rails::Generator::Scripts::Update.new.run(ARGV)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/generate.rb | provider/vendor/rails/railties/lib/commands/generate.rb | require "#{RAILS_ROOT}/config/environment"
require 'rails_generator'
require 'rails_generator/scripts/generate'
ARGV.shift if ['--help', '-h'].include?(ARGV[0])
Rails::Generator::Scripts::Generate.new.run(ARGV)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/about.rb | provider/vendor/rails/railties/lib/commands/about.rb | require "#{RAILS_ROOT}/config/environment"
require 'rails/info'
puts Rails::Info
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/plugin.rb | provider/vendor/rails/railties/lib/commands/plugin.rb | # Rails Plugin Manager.
#
# Listing available plugins:
#
# $ ./script/plugin list
# continuous_builder http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder
# asset_timestamping http://svn.aviditybytes.com/rails/plugins/asset_timestamping
# enumerations_mixin http://svn.protocool.com/rails/plugins/enumerations_mixin/trunk
# calculations http://techno-weenie.net/svn/projects/calculations/
# ...
#
# Installing plugins:
#
# $ ./script/plugin install continuous_builder asset_timestamping
#
# Finding Repositories:
#
# $ ./script/plugin discover
#
# Adding Repositories:
#
# $ ./script/plugin source http://svn.protocool.com/rails/plugins/
#
# How it works:
#
# * Maintains a list of subversion repositories that are assumed to have
# a plugin directory structure. Manage them with the (source, unsource,
# and sources commands)
#
# * The discover command scrapes the following page for things that
# look like subversion repositories with plugins:
# http://wiki.rubyonrails.org/rails/pages/Plugins
#
# * Unless you specify that you want to use svn, script/plugin uses plain old
# HTTP for downloads. The following bullets are true if you specify
# that you want to use svn.
#
# * If `vendor/plugins` is under subversion control, the script will
# modify the svn:externals property and perform an update. You can
# use normal subversion commands to keep the plugins up to date.
#
# * Or, if `vendor/plugins` is not under subversion control, the
# plugin is pulled via `svn checkout` or `svn export` but looks
# exactly the same.
#
# Specifying revisions:
#
# * Subversion revision is a single integer.
#
# * Git revision format:
# - full - 'refs/tags/1.8.0' or 'refs/heads/experimental'
# - short: 'experimental' (equivalent to 'refs/heads/experimental')
# 'tag 1.8.0' (equivalent to 'refs/tags/1.8.0')
#
#
# This is Free Software, copyright 2005 by Ryan Tomayko (rtomayko@gmail.com)
# and is licensed MIT: (http://www.opensource.org/licenses/mit-license.php)
$verbose = false
require 'open-uri'
require 'fileutils'
require 'tempfile'
include FileUtils
class RailsEnvironment
attr_reader :root
def initialize(dir)
@root = dir
end
def self.find(dir=nil)
dir ||= pwd
while dir.length > 1
return new(dir) if File.exist?(File.join(dir, 'config', 'environment.rb'))
dir = File.dirname(dir)
end
end
def self.default
@default ||= find
end
def self.default=(rails_env)
@default = rails_env
end
def install(name_uri_or_plugin)
if name_uri_or_plugin.is_a? String
if name_uri_or_plugin =~ /:\/\//
plugin = Plugin.new(name_uri_or_plugin)
else
plugin = Plugins[name_uri_or_plugin]
end
else
plugin = name_uri_or_plugin
end
unless plugin.nil?
plugin.install
else
puts "Plugin not found: #{name_uri_or_plugin}"
end
end
def use_svn?
require 'active_support/core_ext/kernel'
silence_stderr {`svn --version` rescue nil}
!$?.nil? && $?.success?
end
def use_externals?
use_svn? && File.directory?("#{root}/vendor/plugins/.svn")
end
def use_checkout?
# this is a bit of a guess. we assume that if the rails environment
# is under subversion then they probably want the plugin checked out
# instead of exported. This can be overridden on the command line
File.directory?("#{root}/.svn")
end
def best_install_method
return :http unless use_svn?
case
when use_externals? then :externals
when use_checkout? then :checkout
else :export
end
end
def externals
return [] unless use_externals?
ext = `svn propget svn:externals "#{root}/vendor/plugins"`
lines = ext.respond_to?(:lines) ? ext.lines : ext
lines.reject{ |line| line.strip == '' }.map do |line|
line.strip.split(/\s+/, 2)
end
end
def externals=(items)
unless items.is_a? String
items = items.map{|name,uri| "#{name.ljust(29)} #{uri.chomp('/')}"}.join("\n")
end
Tempfile.open("svn-set-prop") do |file|
file.write(items)
file.flush
system("svn propset -q svn:externals -F \"#{file.path}\" \"#{root}/vendor/plugins\"")
end
end
end
class Plugin
attr_reader :name, :uri
def initialize(uri, name=nil)
@uri = uri
guess_name(uri)
end
def self.find(name)
name =~ /\// ? new(name) : Repositories.instance.find_plugin(name)
end
def to_s
"#{@name.ljust(30)}#{@uri}"
end
def svn_url?
@uri =~ /svn(?:\+ssh)?:\/\/*/
end
def git_url?
@uri =~ /^git:\/\// || @uri =~ /\.git$/
end
def installed?
File.directory?("#{rails_env.root}/vendor/plugins/#{name}") \
or rails_env.externals.detect{ |name, repo| self.uri == repo }
end
def install(method=nil, options = {})
method ||= rails_env.best_install_method?
if :http == method
method = :export if svn_url?
method = :git if git_url?
end
uninstall if installed? and options[:force]
unless installed?
send("install_using_#{method}", options)
run_install_hook
else
puts "already installed: #{name} (#{uri}). pass --force to reinstall"
end
end
def uninstall
path = "#{rails_env.root}/vendor/plugins/#{name}"
if File.directory?(path)
puts "Removing 'vendor/plugins/#{name}'" if $verbose
run_uninstall_hook
rm_r path
else
puts "Plugin doesn't exist: #{path}"
end
# clean up svn:externals
externals = rails_env.externals
externals.reject!{|n,u| name == n or name == u}
rails_env.externals = externals
end
def info
tmp = "#{rails_env.root}/_tmp_about.yml"
if svn_url?
cmd = "svn export #{@uri} \"#{rails_env.root}/#{tmp}\""
puts cmd if $verbose
system(cmd)
end
open(svn_url? ? tmp : File.join(@uri, 'about.yml')) do |stream|
stream.read
end rescue "No about.yml found in #{uri}"
ensure
FileUtils.rm_rf tmp if svn_url?
end
private
def run_install_hook
install_hook_file = "#{rails_env.root}/vendor/plugins/#{name}/install.rb"
load install_hook_file if File.exist? install_hook_file
end
def run_uninstall_hook
uninstall_hook_file = "#{rails_env.root}/vendor/plugins/#{name}/uninstall.rb"
load uninstall_hook_file if File.exist? uninstall_hook_file
end
def install_using_export(options = {})
svn_command :export, options
end
def install_using_checkout(options = {})
svn_command :checkout, options
end
def install_using_externals(options = {})
externals = rails_env.externals
externals.push([@name, uri])
rails_env.externals = externals
install_using_checkout(options)
end
def install_using_http(options = {})
root = rails_env.root
mkdir_p "#{root}/vendor/plugins/#{@name}"
Dir.chdir "#{root}/vendor/plugins/#{@name}" do
puts "fetching from '#{uri}'" if $verbose
fetcher = RecursiveHTTPFetcher.new(uri, -1)
fetcher.quiet = true if options[:quiet]
fetcher.fetch
end
end
def install_using_git(options = {})
root = rails_env.root
install_path = mkdir_p "#{root}/vendor/plugins/#{name}"
Dir.chdir install_path do
init_cmd = "git init"
init_cmd += " -q" if options[:quiet] and not $verbose
puts init_cmd if $verbose
system(init_cmd)
base_cmd = "git pull --depth 1 #{uri}"
base_cmd += " -q" if options[:quiet] and not $verbose
base_cmd += " #{options[:revision]}" if options[:revision]
puts base_cmd if $verbose
if system(base_cmd)
puts "removing: .git .gitignore" if $verbose
rm_rf %w(.git .gitignore)
else
rm_rf install_path
end
end
end
def svn_command(cmd, options = {})
root = rails_env.root
mkdir_p "#{root}/vendor/plugins"
base_cmd = "svn #{cmd} #{uri} \"#{root}/vendor/plugins/#{name}\""
base_cmd += ' -q' if options[:quiet] and not $verbose
base_cmd += " -r #{options[:revision]}" if options[:revision]
puts base_cmd if $verbose
system(base_cmd)
end
def guess_name(url)
@name = File.basename(url)
if @name == 'trunk' || @name.empty?
@name = File.basename(File.dirname(url))
end
@name.gsub!(/\.git$/, '') if @name =~ /\.git$/
end
def rails_env
@rails_env || RailsEnvironment.default
end
end
class Repositories
include Enumerable
def initialize(cache_file = File.join(find_home, ".rails-plugin-sources"))
@cache_file = File.expand_path(cache_file)
load!
end
def each(&block)
@repositories.each(&block)
end
def add(uri)
unless find{|repo| repo.uri == uri }
@repositories.push(Repository.new(uri)).last
end
end
def remove(uri)
@repositories.reject!{|repo| repo.uri == uri}
end
def exist?(uri)
@repositories.detect{|repo| repo.uri == uri }
end
def all
@repositories
end
def find_plugin(name)
@repositories.each do |repo|
repo.each do |plugin|
return plugin if plugin.name == name
end
end
return nil
end
def load!
contents = File.exist?(@cache_file) ? File.read(@cache_file) : defaults
contents = defaults if contents.empty?
@repositories = contents.split(/\n/).reject do |line|
line =~ /^\s*#/ or line =~ /^\s*$/
end.map { |source| Repository.new(source.strip) }
end
def save
File.open(@cache_file, 'w') do |f|
each do |repo|
f.write(repo.uri)
f.write("\n")
end
end
end
def defaults
<<-DEFAULTS
http://dev.rubyonrails.com/svn/rails/plugins/
DEFAULTS
end
def find_home
['HOME', 'USERPROFILE'].each do |homekey|
return ENV[homekey] if ENV[homekey]
end
if ENV['HOMEDRIVE'] && ENV['HOMEPATH']
return "#{ENV['HOMEDRIVE']}:#{ENV['HOMEPATH']}"
end
begin
File.expand_path("~")
rescue StandardError => ex
if File::ALT_SEPARATOR
"C:/"
else
"/"
end
end
end
def self.instance
@instance ||= Repositories.new
end
def self.each(&block)
self.instance.each(&block)
end
end
class Repository
include Enumerable
attr_reader :uri, :plugins
def initialize(uri)
@uri = uri.chomp('/') << "/"
@plugins = nil
end
def plugins
unless @plugins
if $verbose
puts "Discovering plugins in #{@uri}"
puts index
end
@plugins = index.reject{ |line| line !~ /\/$/ }
@plugins.map! { |name| Plugin.new(File.join(@uri, name), name) }
end
@plugins
end
def each(&block)
plugins.each(&block)
end
private
def index
@index ||= RecursiveHTTPFetcher.new(@uri).ls
end
end
# load default environment and parse arguments
require 'optparse'
module Commands
class Plugin
attr_reader :environment, :script_name, :sources
def initialize
@environment = RailsEnvironment.default
@rails_root = RailsEnvironment.default.root
@script_name = File.basename($0)
@sources = []
end
def environment=(value)
@environment = value
RailsEnvironment.default = value
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@script_name} [OPTIONS] command"
o.define_head "Rails plugin manager."
o.separator ""
o.separator "GENERAL OPTIONS"
o.on("-r", "--root=DIR", String,
"Set an explicit rails app directory.",
"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| @sources = sources}
o.on("-v", "--verbose", "Turn on verbose output.") { |verbose| $verbose = verbose }
o.on("-h", "--help", "Show this help message.") { puts o; exit }
o.separator ""
o.separator "COMMANDS"
o.separator " discover Discover plugin repositories."
o.separator " list List available plugins."
o.separator " install Install plugin(s) from known repositories or URLs."
o.separator " update Update installed plugins."
o.separator " remove Uninstall plugins."
o.separator " source Add a plugin source repository."
o.separator " unsource Remove a plugin repository."
o.separator " sources List currently configured plugin repositories."
o.separator ""
o.separator "EXAMPLES"
o.separator " Install a plugin:"
o.separator " #{@script_name} install continuous_builder\n"
o.separator " Install a plugin from a subversion URL:"
o.separator " #{@script_name} install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder\n"
o.separator " Install a plugin from a git URL:"
o.separator " #{@script_name} install git://github.com/SomeGuy/my_awesome_plugin.git\n"
o.separator " Install a plugin and add a svn:externals entry to vendor/plugins"
o.separator " #{@script_name} install -x continuous_builder\n"
o.separator " List all available plugins:"
o.separator " #{@script_name} list\n"
o.separator " List plugins in the specified repository:"
o.separator " #{@script_name} list --source=http://dev.rubyonrails.com/svn/rails/plugins/\n"
o.separator " Discover and prompt to add new repositories:"
o.separator " #{@script_name} discover\n"
o.separator " Discover new repositories but just list them, don't add anything:"
o.separator " #{@script_name} discover -l\n"
o.separator " Add a new repository to the source list:"
o.separator " #{@script_name} source http://dev.rubyonrails.com/svn/rails/plugins/\n"
o.separator " Remove a repository from the source list:"
o.separator " #{@script_name} unsource http://dev.rubyonrails.com/svn/rails/plugins/\n"
o.separator " Show currently configured repositories:"
o.separator " #{@script_name} sources\n"
end
end
def parse!(args=ARGV)
general, sub = split_args(args)
options.parse!(general)
command = general.shift
if command =~ /^(list|discover|install|source|unsource|sources|remove|update|info)$/
command = Commands.const_get(command.capitalize).new(self)
command.parse!(sub)
else
puts "Unknown command: #{command}"
puts options
exit 1
end
end
def split_args(args)
left = []
left << args.shift while args[0] and args[0] =~ /^-/
left << args.shift if args[0]
return [left, args]
end
def self.parse!(args=ARGV)
Plugin.new.parse!(args)
end
end
class List
def initialize(base_command)
@base_command = base_command
@sources = []
@local = false
@remote = true
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} list [OPTIONS] [PATTERN]"
o.define_head "List available plugins."
o.separator ""
o.separator "Options:"
o.separator ""
o.on( "-s", "--source=URL1,URL2", Array,
"Use the specified plugin repositories.") {|sources| @sources = sources}
o.on( "--local",
"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| @remote = remote}
end
end
def parse!(args)
options.order!(args)
unless @sources.empty?
@sources.map!{ |uri| Repository.new(uri) }
else
@sources = Repositories.instance.all
end
if @remote
@sources.map{|r| r.plugins}.flatten.each do |plugin|
if @local or !plugin.installed?
puts plugin.to_s
end
end
else
cd "#{@base_command.environment.root}/vendor/plugins"
Dir["*"].select{|p| File.directory?(p)}.each do |name|
puts name
end
end
end
end
class Sources
def initialize(base_command)
@base_command = base_command
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} sources [OPTIONS] [PATTERN]"
o.define_head "List configured plugin repositories."
o.separator ""
o.separator "Options:"
o.separator ""
o.on( "-c", "--check",
"Report status of repository.") { |sources| @sources = sources}
end
end
def parse!(args)
options.parse!(args)
Repositories.each do |repo|
puts repo.uri
end
end
end
class Source
def initialize(base_command)
@base_command = base_command
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} source REPOSITORY [REPOSITORY [REPOSITORY]...]"
o.define_head "Add new repositories to the default search list."
end
end
def parse!(args)
options.parse!(args)
count = 0
args.each do |uri|
if Repositories.instance.add(uri)
puts "added: #{uri.ljust(50)}" if $verbose
count += 1
else
puts "failed: #{uri.ljust(50)}"
end
end
Repositories.instance.save
puts "Added #{count} repositories."
end
end
class Unsource
def initialize(base_command)
@base_command = base_command
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} unsource URI [URI [URI]...]"
o.define_head "Remove repositories from the default search list."
o.separator ""
o.on_tail("-h", "--help", "Show this help message.") { puts o; exit }
end
end
def parse!(args)
options.parse!(args)
count = 0
args.each do |uri|
if Repositories.instance.remove(uri)
count += 1
puts "removed: #{uri.ljust(50)}"
else
puts "failed: #{uri.ljust(50)}"
end
end
Repositories.instance.save
puts "Removed #{count} repositories."
end
end
class Discover
def initialize(base_command)
@base_command = base_command
@list = false
@prompt = true
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} discover URI [URI [URI]...]"
o.define_head "Discover repositories referenced on a page."
o.separator ""
o.separator "Options:"
o.separator ""
o.on( "-l", "--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
end
def parse!(args)
options.parse!(args)
args = ['http://wiki.rubyonrails.org/rails/pages/Plugins'] if args.empty?
args.each do |uri|
scrape(uri) do |repo_uri|
catch(:next_uri) do
if @prompt
begin
$stdout.print "Add #{repo_uri}? [Y/n] "
throw :next_uri if $stdin.gets !~ /^y?$/i
rescue Interrupt
$stdout.puts
exit 1
end
elsif @list
puts repo_uri
throw :next_uri
end
Repositories.instance.add(repo_uri)
puts "discovered: #{repo_uri}" if $verbose or !@prompt
end
end
end
Repositories.instance.save
end
def scrape(uri)
require 'open-uri'
puts "Scraping #{uri}" if $verbose
dupes = []
content = open(uri).each do |line|
begin
if line =~ /<a[^>]*href=['"]([^'"]*)['"]/ || line =~ /(svn:\/\/[^<|\n]*)/
uri = $1
if uri =~ /^\w+:\/\// && uri =~ /\/plugins\// && uri !~ /\/browser\// && uri !~ /^http:\/\/wiki\.rubyonrails/ && uri !~ /http:\/\/instiki/
uri = extract_repository_uri(uri)
yield uri unless dupes.include?(uri) || Repositories.instance.exist?(uri)
dupes << uri
end
end
rescue
puts "Problems scraping '#{uri}': #{$!.to_s}"
end
end
end
def extract_repository_uri(uri)
uri.match(/(svn|https?):.*\/plugins\//i)[0]
end
end
class Install
def initialize(base_command)
@base_command = base_command
@method = :http
@options = { :quiet => false, :revision => nil, :force => false }
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} install PLUGIN [PLUGIN [PLUGIN] ...]"
o.define_head "Install one or more plugins."
o.separator ""
o.separator "Options:"
o.on( "-x", "--externals",
"Use svn:externals to grab the plugin.",
"Enables plugin updates and plugin versioning.") { |v| @method = :externals }
o.on( "-o", "--checkout",
"Use svn checkout to grab the plugin.",
"Enables updating but does not add a svn:externals entry.") { |v| @method = :checkout }
o.on( "-e", "--export",
"Use svn export to grab the plugin.",
"Exports the plugin, allowing you to check it into your local repository. Does not enable updates, or add an svn:externals entry.") { |v| @method = :export }
o.on( "-q", "--quiet",
"Suppresses the output from installation.",
"Ignored if -v is passed (./script/plugin -v install ...)") { |v| @options[:quiet] = true }
o.on( "-r REVISION", "--revision REVISION",
"Checks out the given revision from subversion or git.",
"Ignored if subversion/git is not used.") { |v| @options[:revision] = v }
o.on( "-f", "--force",
"Reinstalls a plugin if it's already installed.") { |v| @options[:force] = true }
o.separator ""
o.separator "You can specify plugin names as given in 'plugin list' output or absolute URLs to "
o.separator "a plugin repository."
end
end
def determine_install_method
best = @base_command.environment.best_install_method
@method = :http if best == :http and @method == :export
case
when (best == :http and @method != :http)
msg = "Cannot install using subversion because `svn' cannot be found in your PATH"
when (best == :export and (@method != :export and @method != :http))
msg = "Cannot install using #{@method} because this project is not under subversion."
when (best != :externals and @method == :externals)
msg = "Cannot install using externals because vendor/plugins is not under subversion."
end
if msg
puts msg
exit 1
end
@method
end
def parse!(args)
options.parse!(args)
environment = @base_command.environment
install_method = determine_install_method
puts "Plugins will be installed using #{install_method}" if $verbose
args.each do |name|
::Plugin.find(name).install(install_method, @options)
end
rescue StandardError => e
puts "Plugin not found: #{args.inspect}"
puts e.inspect if $verbose
exit 1
end
end
class Update
def initialize(base_command)
@base_command = base_command
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} update [name [name]...]"
o.on( "-r REVISION", "--revision REVISION",
"Checks out the given revision from subversion.",
"Ignored if subversion is not used.") { |v| @revision = v }
o.define_head "Update plugins."
end
end
def parse!(args)
options.parse!(args)
root = @base_command.environment.root
cd root
args = Dir["vendor/plugins/*"].map do |f|
File.directory?("#{f}/.svn") ? File.basename(f) : nil
end.compact if args.empty?
cd "vendor/plugins"
args.each do |name|
if File.directory?(name)
puts "Updating plugin: #{name}"
system("svn #{$verbose ? '' : '-q'} up \"#{name}\" #{@revision ? "-r #{@revision}" : ''}")
else
puts "Plugin doesn't exist: #{name}"
end
end
end
end
class Remove
def initialize(base_command)
@base_command = base_command
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} remove name [name]..."
o.define_head "Remove plugins."
end
end
def parse!(args)
options.parse!(args)
root = @base_command.environment.root
args.each do |name|
::Plugin.new(name).uninstall
end
end
end
class Info
def initialize(base_command)
@base_command = base_command
end
def options
OptionParser.new do |o|
o.set_summary_indent(' ')
o.banner = "Usage: #{@base_command.script_name} info name [name]..."
o.define_head "Shows plugin info at {url}/about.yml."
end
end
def parse!(args)
options.parse!(args)
args.each do |name|
puts ::Plugin.find(name).info
puts
end
end
end
end
class RecursiveHTTPFetcher
attr_accessor :quiet
def initialize(urls_to_fetch, level = 1, cwd = ".")
@level = level
@cwd = cwd
@urls_to_fetch = RUBY_VERSION >= '1.9' ? urls_to_fetch.lines : urls_to_fetch.to_a
@quiet = false
end
def ls
@urls_to_fetch.collect do |url|
if url =~ /^svn(\+ssh)?:\/\/.*/
`svn ls #{url}`.split("\n").map {|entry| "/#{entry}"} rescue nil
else
open(url) do |stream|
links("", stream.read)
end rescue nil
end
end.flatten
end
def push_d(dir)
@cwd = File.join(@cwd, dir)
FileUtils.mkdir_p(@cwd)
end
def pop_d
@cwd = File.dirname(@cwd)
end
def links(base_url, contents)
links = []
contents.scan(/href\s*=\s*\"*[^\">]*/i) do |link|
link = link.sub(/href="/i, "")
next if link =~ /svnindex.xsl$/
next if link =~ /^(\w*:|)\/\// || link =~ /^\./
links << File.join(base_url, link)
end
links
end
def download(link)
puts "+ #{File.join(@cwd, File.basename(link))}" unless @quiet
open(link) do |stream|
File.open(File.join(@cwd, File.basename(link)), "wb") do |file|
file.write(stream.read)
end
end
end
def fetch(links = @urls_to_fetch)
links.each do |l|
(l =~ /\/$/ || links == @urls_to_fetch) ? fetch_dir(l) : download(l)
end
end
def fetch_dir(url)
@level += 1
push_d(File.basename(url)) if @level > 0
open(url) do |stream|
contents = stream.read
fetch(links(url, contents))
end
pop_d if @level > 0
@level -= 1
end
end
Commands::Plugin.parse!
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/console.rb | provider/vendor/rails/railties/lib/commands/console.rb | 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
libs = " -r irb/completion"
libs << %( -r "#{RAILS_ROOT}/config/environment")
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"
when "t"; "test"
else
ARGV.first || ENV['RAILS_ENV'] || 'development'
end
if options[:sandbox]
puts "Loading #{ENV['RAILS_ENV']} environment in sandbox (Rails #{Rails.version})"
puts "Any modifications you make will be rolled back on exit"
else
puts "Loading #{ENV['RAILS_ENV']} environment (Rails #{Rails.version})"
end
exec "#{options[:irb]} #{libs} --simple-prompt"
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/runner.rb | provider/vendor/rails/railties/lib/commands/runner.rb | require 'optparse'
options = { :environment => (ENV['RAILS_ENV'] || "development").dup }
code_or_file = nil
ARGV.clone.options do |opts|
script_name = File.basename($0)
opts.banner = "Usage: #{$0} [options] ('Some.ruby(code)' or a filename)"
opts.separator ""
opts.on("-e", "--environment=name", String,
"Specifies the environment for the runner to operate under (test/development/production).",
"Default: development") { |v| options[:environment] = v }
opts.separator ""
opts.on("-h", "--help",
"Show this help message.") { $stderr.puts opts; exit }
if RUBY_PLATFORM !~ /mswin/
opts.separator ""
opts.separator "You can also use runner as a shebang line for your scripts like this:"
opts.separator "-------------------------------------------------------------"
opts.separator "#!/usr/bin/env #{File.expand_path($0)}"
opts.separator ""
opts.separator "Product.find(:all).each { |p| p.price *= 2 ; p.save! }"
opts.separator "-------------------------------------------------------------"
end
opts.order! { |o| code_or_file ||= o } rescue retry
end
ARGV.delete(code_or_file)
ENV["RAILS_ENV"] = options[:environment]
RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV)
require RAILS_ROOT + '/config/environment'
begin
if code_or_file.nil?
$stderr.puts "Run '#{$0} -h' for help."
exit 1
elsif File.exist?(code_or_file)
eval(File.read(code_or_file), nil, code_or_file)
else
eval(code_or_file)
end
ensure
if defined? Rails
Rails.logger.flush if Rails.logger.respond_to?(:flush)
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/destroy.rb | provider/vendor/rails/railties/lib/commands/destroy.rb | require "#{RAILS_ROOT}/config/environment"
require 'rails_generator'
require 'rails_generator/scripts/destroy'
ARGV.shift if ['--help', '-h'].include?(ARGV[0])
Rails::Generator::Scripts::Destroy.new.run(ARGV)
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/server.rb | provider/vendor/rails/railties/lib/commands/server.rb | require 'active_support'
require 'action_controller'
require 'fileutils'
require 'optparse'
# TODO: Push Thin adapter upstream so we don't need worry about requiring it
begin
require_library_or_gem 'thin'
rescue Exception
# Thin not available
end
options = {
:Port => 3000,
:Host => "0.0.0.0",
:environment => (ENV['RAILS_ENV'] || "development").dup,
:config => RAILS_ROOT + "/config.ru",
:detach => false,
:debugger => false,
:path => nil
}
ARGV.clone.options do |opts|
opts.on("-p", "--port=port", Integer,
"Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v }
opts.on("-b", "--binding=ip", String,
"Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| options[:Host] = v }
opts.on("-c", "--config=file", String,
"Use custom rackup configuration file") { |v| options[:config] = v }
opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:detach] = true }
opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { options[:debugger] = true }
opts.on("-e", "--environment=name", String,
"Specifies the environment to run this server under (test/development/production).",
"Default: development") { |v| options[:environment] = v }
opts.on("-P", "--path=/path", String, "Runs Rails app mounted at a specific path.", "Default: /") { |v| options[:path] = v }
opts.separator ""
opts.on("-h", "--help", "Show this help message.") { puts opts; exit }
opts.parse!
end
server = Rack::Handler.get(ARGV.first) rescue nil
unless server
begin
server = Rack::Handler::Mongrel
rescue LoadError => e
server = Rack::Handler::WEBrick
end
end
puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}"
puts "=> Rails #{Rails.version} application starting on http://#{options[:Host]}:#{options[:Port]}#{options[:path]}"
%w(cache pids sessions sockets).each do |dir_to_make|
FileUtils.mkdir_p(File.join(RAILS_ROOT, 'tmp', dir_to_make))
end
if options[:detach]
Process.daemon
pid = "#{RAILS_ROOT}/tmp/pids/server.pid"
File.open(pid, 'w'){ |f| f.write(Process.pid) }
at_exit { File.delete(pid) if File.exist?(pid) }
end
ENV["RAILS_ENV"] = options[:environment]
RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV)
if File.exist?(options[:config])
config = options[:config]
if config =~ /\.ru$/
cfgfile = File.read(config)
if cfgfile[/^#\\(.*)/]
opts.parse!($1.split(/\s+/))
end
inner_app = eval("Rack::Builder.new {( " + cfgfile + "\n )}.to_app", nil, config)
else
require config
inner_app = Object.const_get(File.basename(config, '.rb').capitalize)
end
else
require RAILS_ROOT + "/config/environment"
inner_app = ActionController::Dispatcher.new
end
if options[:path].nil?
map_path = "/"
else
ActionController::Base.relative_url_root = options[:path]
map_path = options[:path]
end
app = Rack::Builder.new {
use Rails::Rack::LogTailer unless options[:detach]
use Rails::Rack::Debugger if options[:debugger]
map map_path do
use Rails::Rack::Static
run inner_app
end
}.to_app
puts "=> Call with -d to detach"
trap(:INT) { exit }
puts "=> Ctrl-C to shutdown server"
begin
server.run(app, options.merge(:AccessLog => []))
ensure
puts 'Exiting'
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/performance/profiler.rb | provider/vendor/rails/railties/lib/commands/performance/profiler.rb | if ARGV.empty?
$stderr.puts "Usage: ./script/performance/profiler 'Person.expensive_method(10)' [times] [flat|graph|graph_html]"
exit(1)
end
# Keep the expensive require out of the profile.
$stderr.puts 'Loading Rails...'
require RAILS_ROOT + '/config/environment'
# Define a method to profile.
if ARGV[1] and ARGV[1].to_i > 1
eval "def profile_me() #{ARGV[1]}.times { #{ARGV[0]} } end"
else
eval "def profile_me() #{ARGV[0]} end"
end
# Use the ruby-prof extension if available. Fall back to stdlib profiler.
begin
begin
require "ruby-prof"
$stderr.puts 'Using the ruby-prof extension.'
RubyProf.measure_mode = RubyProf::WALL_TIME
RubyProf.start
profile_me
results = RubyProf.stop
if ARGV[2]
printer_class = RubyProf.const_get((ARGV[2] + "_printer").classify)
else
printer_class = RubyProf::FlatPrinter
end
printer = printer_class.new(results)
printer.print($stderr)
rescue LoadError
require "prof"
$stderr.puts 'Using the old ruby-prof extension.'
Prof.clock_mode = Prof::GETTIMEOFDAY
Prof.start
profile_me
results = Prof.stop
require 'rubyprof_ext'
Prof.print_profile(results, $stderr)
end
rescue LoadError
require 'profiler'
$stderr.puts 'Using the standard Ruby profiler.'
Profiler__.start_profile
profile_me
Profiler__.stop_profile
Profiler__.print_profile($stderr)
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/commands/performance/benchmarker.rb | provider/vendor/rails/railties/lib/commands/performance/benchmarker.rb | if ARGV.empty?
puts "Usage: ./script/performance/benchmarker [times] 'Person.expensive_way' 'Person.another_expensive_way' ..."
exit 1
end
begin
N = Integer(ARGV.first)
ARGV.shift
rescue ArgumentError
N = 1
end
require RAILS_ROOT + '/config/environment'
require 'benchmark'
include Benchmark
# Don't include compilation in the benchmark
ARGV.each { |expression| eval(expression) }
bm(6) do |x|
ARGV.each_with_index do |expression, idx|
x.report("##{idx + 1}") { N.times { eval(expression) } }
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/manifest.rb | provider/vendor/rails/railties/lib/rails_generator/manifest.rb | module Rails
module Generator
# Manifest captures the actions a generator performs. Instantiate
# a manifest with an optional target object, hammer it with actions,
# then replay or rewind on the object of your choice.
#
# Example:
# manifest = Manifest.new { |m|
# m.make_directory '/foo'
# m.create_file '/foo/bar.txt'
# }
# manifest.replay(creator)
# manifest.rewind(destroyer)
class Manifest
attr_reader :target
# Take a default action target. Yield self if block given.
def initialize(target = nil)
@target, @actions = target, []
yield self if block_given?
end
# Record an action.
def method_missing(action, *args, &block)
@actions << [action, args, block]
end
# Replay recorded actions.
def replay(target = nil)
send_actions(target || @target, @actions)
end
# Rewind recorded actions.
def rewind(target = nil)
send_actions(target || @target, @actions.reverse)
end
# Erase recorded actions.
def erase
@actions = []
end
private
def send_actions(target, actions)
actions.each do |method, args, block|
target.send(method, *args, &block)
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/secret_key_generator.rb | provider/vendor/rails/railties/lib/rails_generator/secret_key_generator.rb | require 'active_support/deprecation'
module Rails
# A class for creating random secret keys. This class will do its best to create a
# random secret key that's as secure as possible, using whatever methods are
# available on the current platform. For example:
#
# 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
def initialize(identifier)
end
# Generate a random secret key with the best possible method available on
# the current platform.
def generate_secret
ActiveSupport::SecureRandom.hex(64)
end
deprecate :generate_secret=>"You should use ActiveSupport::SecureRandom.hex(64)"
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/options.rb | provider/vendor/rails/railties/lib/rails_generator/options.rb | require 'optparse'
module Rails
module Generator
module Options
def self.included(base)
base.extend(ClassMethods)
class << base
if respond_to?(:inherited)
alias_method :inherited_without_options, :inherited
end
alias_method :inherited, :inherited_with_options
end
end
module ClassMethods
def inherited_with_options(sub)
inherited_without_options(sub) if respond_to?(:inherited_without_options)
sub.extend(Rails::Generator::Options::ClassMethods)
end
def mandatory_options(options = nil)
if options
write_inheritable_attribute(:mandatory_options, options)
else
read_inheritable_attribute(:mandatory_options) or write_inheritable_attribute(:mandatory_options, {})
end
end
def default_options(options = nil)
if options
write_inheritable_attribute(:default_options, options)
else
read_inheritable_attribute(:default_options) or write_inheritable_attribute(:default_options, {})
end
end
# Merge together our class options. In increasing precedence:
# default_options (class default options)
# runtime_options (provided as argument)
# mandatory_options (class mandatory options)
def full_options(runtime_options = {})
default_options.merge(runtime_options).merge(mandatory_options)
end
end
# Each instance has an options hash that's populated by #parse.
def options
@options ||= {}
end
attr_writer :options
protected
# Convenient access to class mandatory options.
def mandatory_options
self.class.mandatory_options
end
# Convenient access to class default options.
def default_options
self.class.default_options
end
# Merge together our instance options. In increasing precedence:
# default_options (class default options)
# options (instance options)
# runtime_options (provided as argument)
# mandatory_options (class mandatory options)
def full_options(runtime_options = {})
self.class.full_options(options.merge(runtime_options))
end
# Parse arguments into the options hash. Classes may customize
# parsing behavior by overriding these methods:
# #banner Usage: ./script/generate [options]
# #add_options! Options:
# some options..
# #add_general_options! General Options:
# general options..
def parse!(args, runtime_options = {})
self.options = {}
@option_parser = OptionParser.new do |opt|
opt.banner = banner
add_options!(opt)
add_general_options!(opt)
opt.parse!(args)
end
return args
ensure
self.options = full_options(runtime_options)
end
# Raise a usage error. Override usage_message to provide a blurb
# after the option parser summary.
def usage(message = usage_message)
raise UsageError, "#{@option_parser}\n#{message}"
end
def usage_message
''
end
# Override with your own usage banner.
def banner
"Usage: #{$0} [options]"
end
# Override to add your options to the parser:
# def add_options!(opt)
# opt.on('-v', '--verbose') { |value| options[:verbose] = value }
# end
def add_options!(opt)
end
# Adds general options like -h and --quiet. Usually don't override.
def add_general_options!(opt)
opt.separator ''
opt.separator 'Rails Info:'
opt.on('-v', '--version', 'Show the Rails version number and quit.')
opt.on('-h', '--help', 'Show this help message and quit.') { |v| options[:help] = v }
opt.separator ''
opt.separator 'General Options:'
opt.on('-p', '--pretend', 'Run but do not make any changes.') { |v| options[:pretend] = v }
opt.on('-f', '--force', 'Overwrite files that already exist.') { options[:collision] = :force }
opt.on('-s', '--skip', 'Skip files that already exist.') { options[:collision] = :skip }
opt.on('-q', '--quiet', 'Suppress normal output.') { |v| options[:quiet] = v }
opt.on('-t', '--backtrace', 'Debugging: show backtrace on errors.') { |v| options[:backtrace] = v }
opt.on('-c', '--svn', 'Modify files with subversion. (Note: svn must be in path)') do
options[:svn] = `svn status`.inject({}) do |opt, e|
opt[e.chomp[7..-1]] = true
opt
end
end
opt.on('-g', '--git', 'Modify files with git. (Note: git must be in path)') do
options[:git] = `git status`.inject({:new => {}, :modified => {}}) do |opt, e|
opt[:new][e.chomp[14..-1]] = true if e =~ /new file:/
opt[:modified][e.chomp[14..-1]] = true if e =~ /modified:/
opt
end
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/simple_logger.rb | provider/vendor/rails/railties/lib/rails_generator/simple_logger.rb | module Rails
module Generator
class SimpleLogger # :nodoc:
attr_reader :out
attr_accessor :quiet
def initialize(out = $stdout)
@out = out
@quiet = false
@level = 0
end
def log(status, message, &block)
@out.print("%12s %s%s\n" % [status, ' ' * @level, message]) unless quiet
indent(&block) if block_given?
end
def indent(&block)
@level += 1
if block_given?
begin
block.call
ensure
outdent
end
end
end
def outdent
@level -= 1
if block_given?
begin
block.call
ensure
indent
end
end
end
private
def method_missing(method, *args, &block)
log(method.to_s, args.first, &block)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/scripts.rb | provider/vendor/rails/railties/lib/rails_generator/scripts.rb | require File.dirname(__FILE__) + '/options'
module Rails
module Generator
module Scripts
# Generator scripts handle command-line invocation. Each script
# responds to an invoke! class method which handles option parsing
# and generator invocation.
class Base
include Options
default_options :collision => :ask, :quiet => false
# Run the generator script. Takes an array of unparsed arguments
# and a hash of parsed arguments, takes the generator as an option
# or first remaining argument, and invokes the requested command.
def run(args = [], runtime_options = {})
begin
parse!(args.dup, runtime_options)
rescue OptionParser::InvalidOption => e
# Don't cry, script. Generators want what you think is invalid.
end
# Generator name is the only required option.
unless options[:generator]
usage if args.empty?
options[:generator] ||= args.shift
end
# Look up generator instance and invoke command on it.
Rails::Generator::Base.instance(options[:generator], args, options).command(options[:command]).invoke!
rescue => e
puts e
puts " #{e.backtrace.join("\n ")}\n" if options[:backtrace]
raise SystemExit
end
protected
# Override with your own script usage banner.
def banner
"Usage: #{$0} generator [options] [args]"
end
def usage_message
usage = "\nInstalled Generators\n"
Rails::Generator::Base.sources.inject([]) do |mem, source|
# Using an association list instead of a hash to preserve order,
# for aesthetic reasons more than anything else.
label = source.label.to_s.capitalize
pair = mem.assoc(label)
mem << (pair = [label, []]) if pair.nil?
pair[1] |= source.names
mem
end.each do |label, names|
usage << " #{label}: #{names.join(', ')}\n" unless names.empty?
end
usage << <<end_blurb
More are available at http://wiki.rubyonrails.org/rails/pages/AvailableGenerators
1. Download, for example, login_generator.zip
2. Unzip to directory #{Dir.user_home}/.rails/generators/login
to use the generator with all your Rails apps
end_blurb
if Object.const_defined?(:RAILS_ROOT)
usage << <<end_blurb
or to #{File.expand_path(RAILS_ROOT)}/lib/generators/login
to use with this app only.
end_blurb
end
usage << <<end_blurb
3. Run generate with no arguments for usage information
#{$0} login
Generator gems are also available:
1. gem search -r generator
2. gem install login_generator
3. #{$0} login
end_blurb
return usage
end
end # Base
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/spec.rb | provider/vendor/rails/railties/lib/rails_generator/spec.rb | module Rails
module Generator
# A spec knows where a generator was found and how to instantiate it.
# Metadata include the generator's name, its base path, and the source
# which yielded it (PathSource, GemPathSource, etc.)
class Spec
attr_reader :name, :path, :source
def initialize(name, path, source)
@name, @path, @source = name, path, source
end
# Look up the generator class. Require its class file, find the class
# in ObjectSpace, tag it with this spec, and return.
def klass
unless @klass
require class_file
@klass = lookup_class
@klass.spec = self
end
@klass
end
def class_file
"#{path}/#{name}_generator.rb"
end
def class_name
"#{name.camelize}Generator"
end
private
# Search for the first Class descending from Rails::Generator::Base
# whose name matches the requested class name.
def lookup_class
ObjectSpace.each_object(Class) do |obj|
return obj if obj.ancestors.include?(Rails::Generator::Base) and
obj.name.split('::').last == class_name
end
raise NameError, "Missing #{class_name} class in #{class_file}"
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/base.rb | provider/vendor/rails/railties/lib/rails_generator/base.rb | require File.dirname(__FILE__) + '/options'
require File.dirname(__FILE__) + '/manifest'
require File.dirname(__FILE__) + '/spec'
require File.dirname(__FILE__) + '/generated_attribute'
module Rails
# Rails::Generator is a code generation platform tailored for the Rails
# web application framework. Generators are easily invoked within Rails
# applications to add and remove components such as models and controllers.
# New generators are easy to create and may be distributed as RubyGems,
# tarballs, or Rails plugins for inclusion system-wide, per-user,
# or per-application.
#
# For actual examples see the rails_generator/generators directory in the
# Rails source (or the +railties+ directory if you have frozen the Rails
# source in your application).
#
# Generators may subclass other generators to provide variations that
# require little or no new logic but replace the template files.
#
# For a RubyGem, put your generator class and templates in the +lib+
# directory. For a Rails plugin, make a +generators+ directory at the
# root of your plugin.
#
# The layout of generator files can be seen in the built-in
# +controller+ generator:
#
# generators/
# components/
# controller/
# controller_generator.rb
# templates/
# controller.rb
# functional_test.rb
# helper.rb
# view.html.erb
#
# The directory name (+controller+) matches the name of the generator file
# (controller_generator.rb) and class (ControllerGenerator). The files
# that will be copied or used as templates are stored in the +templates+
# directory.
#
# The filenames of the templates don't matter, but choose something that
# will be self-explanatory since you will be referencing these in the
# +manifest+ method inside your generator subclass.
#
#
module Generator
class GeneratorError < StandardError; end
class UsageError < GeneratorError; end
# The base code generator is bare-bones. It sets up the source and
# destination paths and tells the logger whether to keep its trap shut.
#
# It's useful for copying files such as stylesheets, images, or
# javascripts.
#
# For more comprehensive template-based passive code generation with
# arguments, you'll want Rails::Generator::NamedBase.
#
# Generators create a manifest of the actions they perform then hand
# the manifest to a command which replays the actions to do the heavy
# lifting (such as checking for existing files or creating directories
# if needed). Create, destroy, and list commands are included. Since a
# single manifest may be used by any command, creating new generators is
# as simple as writing some code templates and declaring what you'd like
# to do with them.
#
# The manifest method must be implemented by subclasses, returning a
# Rails::Generator::Manifest. The +record+ method is provided as a
# convenience for manifest creation. Example:
#
# class StylesheetGenerator < Rails::Generator::Base
# def manifest
# record do |m|
# m.directory('public/stylesheets')
# m.file('application.css', 'public/stylesheets/application.css')
# end
# end
# end
#
# See Rails::Generator::Commands::Create for a list of methods available
# to the manifest.
class Base
include Options
# Declare default options for the generator. These options
# are inherited to subclasses.
default_options :collision => :ask, :quiet => false
# A logger instance available everywhere in the generator.
cattr_accessor :logger
# Every generator that is dynamically looked up is tagged with a
# Spec describing where it was found.
class_inheritable_accessor :spec
attr_reader :source_root, :destination_root, :args
def initialize(runtime_args, runtime_options = {})
@args = runtime_args
parse!(@args, runtime_options)
# Derive source and destination paths.
@source_root = options[:source] || File.join(spec.path, 'templates')
if options[:destination]
@destination_root = options[:destination]
elsif defined? ::RAILS_ROOT
@destination_root = ::RAILS_ROOT
end
# Silence the logger if requested.
logger.quiet = options[:quiet]
# Raise usage error if help is requested.
usage if options[:help]
end
# Generators must provide a manifest. Use the +record+ method to create
# a new manifest and record your generator's actions.
def manifest
raise NotImplementedError, "No manifest for '#{spec.name}' generator."
end
# Return the full path from the source root for the given path.
# Example for source_root = '/source':
# source_path('some/path.rb') == '/source/some/path.rb'
#
# The given path may include a colon ':' character to indicate that
# the file belongs to another generator. This notation allows any
# generator to borrow files from another. Example:
# source_path('model:fixture.yml') = '/model/source/path/fixture.yml'
def source_path(relative_source)
# Check whether we're referring to another generator's file.
name, path = relative_source.split(':', 2)
# If not, return the full path to our source file.
if path.nil?
File.join(source_root, name)
# Otherwise, ask our referral for the file.
else
# FIXME: this is broken, though almost always true. Others'
# source_root are not necessarily the templates dir.
File.join(self.class.lookup(name).path, 'templates', path)
end
end
# Return the full path from the destination root for the given path.
# Example for destination_root = '/dest':
# destination_path('some/path.rb') == '/dest/some/path.rb'
def destination_path(relative_destination)
File.join(destination_root, relative_destination)
end
def after_generate
end
protected
# Convenience method for generator subclasses to record a manifest.
def record
Rails::Generator::Manifest.new(self) { |m| yield m }
end
# Override with your own usage banner.
def banner
"Usage: #{$0} #{spec.name} [options]"
end
# Read USAGE from file in generator base path.
def usage_message
File.read(File.join(spec.path, 'USAGE')) rescue ''
end
end
# The base generator for named components: models, controllers, mailers,
# etc. The target name is taken as the first argument and inflected to
# singular, plural, class, file, and table forms for your convenience.
# The remaining arguments are aliased to +actions+ as an array for
# controller and mailer convenience.
#
# Several useful local variables and methods are populated in the
# +initialize+ method. See below for a list of Attributes and
# External Aliases available to both the manifest and to all templates.
#
# If no name is provided, the generator raises a usage error with content
# optionally read from the USAGE file in the generator's base path.
#
# For example, the +controller+ generator takes the first argument as
# the name of the class and subsequent arguments as the names of
# actions to be generated:
#
# ./script/generate controller Article index new create
#
# See Rails::Generator::Base for a discussion of manifests,
# Rails::Generator::Commands::Create for methods available to the manifest,
# and Rails::Generator for a general discussion of generators.
class NamedBase < Base
attr_reader :name, :class_name, :singular_name, :plural_name, :table_name
attr_reader :class_path, :file_path, :class_nesting, :class_nesting_depth
alias_method :file_name, :singular_name
alias_method :actions, :args
def initialize(runtime_args, runtime_options = {})
super
# Name argument is required.
usage if runtime_args.empty?
@args = runtime_args.dup
base_name = @args.shift
assign_names!(base_name)
end
protected
# Override with your own usage banner.
def banner
"Usage: #{$0} #{spec.name} #{spec.name.camelize}Name [options]"
end
def attributes
@attributes ||= @args.collect do |attribute|
Rails::Generator::GeneratedAttribute.new(*attribute.split(":"))
end
end
private
def assign_names!(name)
@name = name
base_name, @class_path, @file_path, @class_nesting, @class_nesting_depth = extract_modules(@name)
@class_name_without_nesting, @singular_name, @plural_name = inflect_names(base_name)
@table_name = (!defined?(ActiveRecord::Base) || ActiveRecord::Base.pluralize_table_names) ? plural_name : singular_name
if @class_nesting.empty?
@class_name = @class_name_without_nesting
else
@table_name = @class_nesting.underscore << "_" << @table_name
@class_name = "#{@class_nesting}::#{@class_name_without_nesting}"
end
@table_name.gsub! '/', '_'
end
# Extract modules from filesystem-style or ruby-style path:
# good/fun/stuff
# Good::Fun::Stuff
# produce the same results.
def extract_modules(name)
modules = name.include?('/') ? name.split('/') : name.split('::')
name = modules.pop
path = modules.map { |m| m.underscore }
file_path = (path + [name.underscore]).join('/')
nesting = modules.map { |m| m.camelize }.join('::')
[name, path, file_path, nesting, modules.size]
end
def inflect_names(name)
camel = name.camelize
under = camel.underscore
plural = under.pluralize
[camel, under, plural]
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generated_attribute.rb | provider/vendor/rails/railties/lib/rails_generator/generated_attribute.rb | require 'optparse'
module Rails
module Generator
class GeneratedAttribute
attr_accessor :name, :type, :column
def initialize(name, type)
@name, @type = name, type.to_sym
@column = ActiveRecord::ConnectionAdapters::Column.new(name, nil, @type)
end
def field_type
@field_type ||= case type
when :integer, :float, :decimal then :text_field
when :datetime, :timestamp, :time then :datetime_select
when :date then :date_select
when :string then :text_field
when :text then :text_area
when :boolean then :check_box
else
:text_field
end
end
def default
@default ||= case type
when :integer then 1
when :float then 1.5
when :decimal then "9.99"
when :datetime, :timestamp, :time then Time.now.to_s(:db)
when :date then Date.today.to_s(:db)
when :string then "MyString"
when :text then "MyText"
when :boolean then false
else
""
end
end
def reference?
[ :references, :belongs_to ].include?(self.type)
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/commands.rb | provider/vendor/rails/railties/lib/rails_generator/commands.rb | require 'delegate'
require 'optparse'
require 'fileutils'
require 'tempfile'
require 'erb'
module Rails
module Generator
module Commands
# Here's a convenient way to get a handle on generator commands.
# Command.instance('destroy', my_generator) instantiates a Destroy
# delegate of my_generator ready to do your dirty work.
def self.instance(command, generator)
const_get(command.to_s.camelize).new(generator)
end
# Even more convenient access to commands. Include Commands in
# the generator Base class to get a nice #command instance method
# which returns a delegate for the requested command.
def self.included(base)
base.send(:define_method, :command) do |command|
Commands.instance(command, self)
end
end
# Generator commands delegate Rails::Generator::Base and implement
# a standard set of actions. Their behavior is defined by the way
# they respond to these actions: Create brings life; Destroy brings
# death; List passively observes.
#
# Commands are invoked by replaying (or rewinding) the generator's
# manifest of actions. See Rails::Generator::Manifest and
# Rails::Generator::Base#manifest method that generator subclasses
# are required to override.
#
# Commands allows generators to "plug in" invocation behavior, which
# corresponds to the GoF Strategy pattern.
class Base < DelegateClass(Rails::Generator::Base)
# Replay action manifest. RewindBase subclass rewinds manifest.
def invoke!
manifest.replay(self)
after_generate
end
def dependency(generator_name, args, runtime_options = {})
logger.dependency(generator_name) do
self.class.new(instance(generator_name, args, full_options(runtime_options))).invoke!
end
end
# Does nothing for all commands except Create.
def class_collisions(*class_names)
end
# Does nothing for all commands except Create.
def readme(*args)
end
protected
def current_migration_number
Dir.glob("#{RAILS_ROOT}/#{@migration_directory}/[0-9]*_*.rb").inject(0) do |max, file_path|
n = File.basename(file_path).split('_', 2).first.to_i
if n > max then n else max end
end
end
def next_migration_number
current_migration_number + 1
end
def migration_directory(relative_path)
directory(@migration_directory = relative_path)
end
def existing_migrations(file_name)
Dir.glob("#{@migration_directory}/[0-9]*_*.rb").grep(/[0-9]+_#{file_name}.rb$/)
end
def migration_exists?(file_name)
not existing_migrations(file_name).empty?
end
def next_migration_string(padding = 3)
if ActiveRecord::Base.timestamped_migrations
Time.now.utc.strftime("%Y%m%d%H%M%S")
else
"%.#{padding}d" % next_migration_number
end
end
def gsub_file(relative_destination, regexp, *args, &block)
path = destination_path(relative_destination)
content = File.read(path).gsub(regexp, *args, &block)
File.open(path, 'wb') { |file| file.write(content) }
end
private
# Ask the user interactively whether to force collision.
def force_file_collision?(destination, src, dst, file_options = {}, &block)
$stdout.print "overwrite #{destination}? (enter \"h\" for help) [Ynaqdh] "
case $stdin.gets.chomp
when /\Ad\z/i
Tempfile.open(File.basename(destination), File.dirname(dst)) do |temp|
temp.write render_file(src, file_options, &block)
temp.rewind
$stdout.puts `#{diff_cmd} "#{dst}" "#{temp.path}"`
end
puts "retrying"
raise 'retry diff'
when /\Aa\z/i
$stdout.puts "forcing #{spec.name}"
options[:collision] = :force
when /\Aq\z/i
$stdout.puts "aborting #{spec.name}"
raise SystemExit
when /\An\z/i then :skip
when /\Ay\z/i then :force
else
$stdout.puts <<-HELP
Y - yes, overwrite
n - no, do not overwrite
a - all, overwrite this and all others
q - quit, abort
d - diff, show the differences between the old and the new
h - help, show this help
HELP
raise 'retry'
end
rescue
retry
end
def diff_cmd
ENV['RAILS_DIFF'] || 'diff -u'
end
def render_template_part(template_options)
# Getting Sandbox to evaluate part template in it
part_binding = template_options[:sandbox].call.sandbox_binding
part_rel_path = template_options[:insert]
part_path = source_path(part_rel_path)
# Render inner template within Sandbox binding
rendered_part = ERB.new(File.readlines(part_path).join, nil, '-').result(part_binding)
begin_mark = template_part_mark(template_options[:begin_mark], template_options[:mark_id])
end_mark = template_part_mark(template_options[:end_mark], template_options[:mark_id])
begin_mark + rendered_part + end_mark
end
def template_part_mark(name, id)
"<!--[#{name}:#{id}]-->\n"
end
end
# Base class for commands which handle generator actions in reverse, such as Destroy.
class RewindBase < Base
# Rewind action manifest.
def invoke!
manifest.rewind(self)
end
end
# Create is the premier generator command. It copies files, creates
# directories, renders templates, and more.
class Create < Base
# Check whether the given class names are already taken by
# Ruby or Rails. In the future, expand to check other namespaces
# such as the rest of the user's app.
def class_collisions(*class_names)
path = class_names.shift
class_names.flatten.each do |class_name|
# Convert to string to allow symbol arguments.
class_name = class_name.to_s
# Skip empty strings.
next if class_name.strip.empty?
# Split the class from its module nesting.
nesting = class_name.split('::')
name = nesting.pop
# Hack to limit const_defined? to non-inherited on 1.9.
extra = []
extra << false unless Object.method(:const_defined?).arity == 1
# Extract the last Module in the nesting.
last = nesting.inject(Object) { |last, nest|
break unless last.const_defined?(nest, *extra)
last.const_get(nest)
}
# If the last Module exists, check whether the given
# class exists and raise a collision if so.
if last and last.const_defined?(name.camelize, *extra)
raise_class_collision(class_name)
end
end
end
# Copy a file from source to destination with collision checking.
#
# The file_options hash accepts :chmod and :shebang and :collision options.
# :chmod sets the permissions of the destination file:
# file 'config/empty.log', 'log/test.log', :chmod => 0664
# :shebang sets the #!/usr/bin/ruby line for scripts
# file 'bin/generate.rb', 'script/generate', :chmod => 0755, :shebang => '/usr/bin/env ruby'
# :collision sets the collision option only for the destination file:
# file 'settings/server.yml', 'config/server.yml', :collision => :skip
#
# Collisions are handled by checking whether the destination file
# exists and either skipping the file, forcing overwrite, or asking
# the user what to do.
def file(relative_source, relative_destination, file_options = {}, &block)
# Determine full paths for source and destination files.
source = source_path(relative_source)
destination = destination_path(relative_destination)
destination_exists = File.exist?(destination)
# If source and destination are identical then we're done.
if destination_exists and identical?(source, destination, &block)
return logger.identical(relative_destination)
end
# Check for and resolve file collisions.
if destination_exists
# Make a choice whether to overwrite the file. :force and
# :skip already have their mind made up, but give :ask a shot.
choice = case (file_options[:collision] || options[:collision]).to_sym #|| :ask
when :ask then force_file_collision?(relative_destination, source, destination, file_options, &block)
when :force then :force
when :skip then :skip
else raise "Invalid collision option: #{options[:collision].inspect}"
end
# Take action based on our choice. Bail out if we chose to
# skip the file; otherwise, log our transgression and continue.
case choice
when :force then logger.force(relative_destination)
when :skip then return(logger.skip(relative_destination))
else raise "Invalid collision choice: #{choice}.inspect"
end
# File doesn't exist so log its unbesmirched creation.
else
logger.create relative_destination
end
# If we're pretending, back off now.
return if options[:pretend]
# Write destination file with optional shebang. Yield for content
# if block given so templaters may render the source file. If a
# shebang is requested, replace the existing shebang or insert a
# new one.
File.open(destination, 'wb') do |dest|
dest.write render_file(source, file_options, &block)
end
# Optionally change permissions.
if file_options[:chmod]
FileUtils.chmod(file_options[:chmod], destination)
end
# Optionally add file to subversion or git
system("svn add #{destination}") if options[:svn]
system("git add -v #{relative_destination}") if options[:git]
end
# Checks if the source and the destination file are identical. If
# passed a block then the source file is a template that needs to first
# be evaluated before being compared to the destination.
def identical?(source, destination, &block)
return false if File.directory? destination
source = block_given? ? File.open(source) {|sf| yield(sf)} : IO.read(source)
destination = IO.read(destination)
source == destination
end
# Generate a file for a Rails application using an ERuby template.
# Looks up and evaluates a template by name and writes the result.
#
# The ERB template uses explicit trim mode to best control the
# proliferation of whitespace in generated code. <%- trims leading
# whitespace; -%> trims trailing whitespace including one newline.
#
# A hash of template options may be passed as the last argument.
# The options accepted by the file are accepted as well as :assigns,
# a hash of variable bindings. Example:
# template 'foo', 'bar', :assigns => { :action => 'view' }
#
# Template is implemented in terms of file. It calls file with a
# block which takes a file handle and returns its rendered contents.
def template(relative_source, relative_destination, template_options = {})
file(relative_source, relative_destination, template_options) do |file|
# Evaluate any assignments in a temporary, throwaway binding.
vars = template_options[:assigns] || {}
b = template_options[:binding] || binding
vars.each { |k,v| eval "#{k} = vars[:#{k}] || vars['#{k}']", b }
# Render the source file with the temporary binding.
ERB.new(file.read, nil, '-').result(b)
end
end
def complex_template(relative_source, relative_destination, template_options = {})
options = template_options.dup
options[:assigns] ||= {}
options[:assigns]['template_for_inclusion'] = render_template_part(template_options)
template(relative_source, relative_destination, options)
end
# Create a directory including any missing parent directories.
# Always skips directories which exist.
def directory(relative_path)
path = destination_path(relative_path)
if File.exist?(path)
logger.exists relative_path
else
logger.create relative_path
unless options[:pretend]
FileUtils.mkdir_p(path)
# git doesn't require adding the paths, adding the files later will
# automatically do a path add.
# Subversion doesn't do path adds, so we need to add
# each directory individually.
# So stack up the directory tree and add the paths to
# subversion in order without recursion.
if options[:svn]
stack = [relative_path]
until File.dirname(stack.last) == stack.last # dirname('.') == '.'
stack.push File.dirname(stack.last)
end
stack.reverse_each do |rel_path|
svn_path = destination_path(rel_path)
system("svn add -N #{svn_path}") unless File.directory?(File.join(svn_path, '.svn'))
end
end
end
end
end
# Display a README.
def readme(*relative_sources)
relative_sources.flatten.each do |relative_source|
logger.readme relative_source
puts File.read(source_path(relative_source)) unless options[:pretend]
end
end
# When creating a migration, it knows to find the first available file in db/migrate and use the migration.rb template.
def migration_template(relative_source, relative_destination, template_options = {})
migration_directory relative_destination
migration_file_name = template_options[:migration_file_name] || file_name
raise "Another migration is already named #{migration_file_name}: #{existing_migrations(migration_file_name).first}" if migration_exists?(migration_file_name)
template(relative_source, "#{relative_destination}/#{next_migration_string}_#{migration_file_name}.rb", template_options)
end
def route_resources(*resources)
resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
sentinel = 'ActionController::Routing::Routes.draw do |map|'
logger.route "map.resources #{resource_list}"
unless options[:pretend]
gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
"#{match}\n map.resources #{resource_list}\n"
end
end
end
private
def render_file(path, options = {})
File.open(path, 'rb') do |file|
if block_given?
yield file
else
content = ''
if shebang = options[:shebang]
content << "#!#{shebang}\n"
if line = file.gets
content << "line\n" if line !~ /^#!/
end
end
content << file.read
end
end
end
# Raise a usage error with an informative WordNet suggestion.
# Thanks to Florian Gross (flgr).
def raise_class_collision(class_name)
message = <<end_message
The name '#{class_name}' is either already used in your application or reserved by Ruby on Rails.
Please choose an alternative and run this generator again.
end_message
if suggest = find_synonyms(class_name)
if suggest.any?
message << "\n Suggestions: \n\n"
message << suggest.join("\n")
end
end
raise UsageError, message
end
SYNONYM_LOOKUP_URI = "http://wordnet.princeton.edu/perl/webwn?s=%s"
# Look up synonyms on WordNet. Thanks to Florian Gross (flgr).
def find_synonyms(word)
require 'open-uri'
require 'timeout'
timeout(5) do
open(SYNONYM_LOOKUP_URI % word) do |stream|
# Grab words linked to dictionary entries as possible synonyms
data = stream.read.gsub(" ", " ").scan(/<a href="webwn.*?">([\w ]*?)<\/a>/s).uniq
end
end
rescue Exception
return nil
end
end
# Undo the actions performed by a generator. Rewind the action
# manifest and attempt to completely erase the results of each action.
class Destroy < RewindBase
# Remove a file if it exists and is a file.
def file(relative_source, relative_destination, file_options = {})
destination = destination_path(relative_destination)
if File.exist?(destination)
logger.rm relative_destination
unless options[:pretend]
if options[:svn]
# If the file has been marked to be added
# but has not yet been checked in, revert and delete
if options[:svn][relative_destination]
system("svn revert #{destination}")
FileUtils.rm(destination)
else
# If the directory is not in the status list, it
# has no modifications so we can simply remove it
system("svn rm #{destination}")
end
elsif options[:git]
if options[:git][:new][relative_destination]
# file has been added, but not committed
system("git reset HEAD #{relative_destination}")
FileUtils.rm(destination)
elsif options[:git][:modified][relative_destination]
# file is committed and modified
system("git rm -f #{relative_destination}")
else
# If the directory is not in the status list, it
# has no modifications so we can simply remove it
system("git rm #{relative_destination}")
end
else
FileUtils.rm(destination)
end
end
else
logger.missing relative_destination
return
end
end
# Templates are deleted just like files and the actions take the
# same parameters, so simply alias the file method.
alias_method :template, :file
# Remove each directory in the given path from right to left.
# Remove each subdirectory if it exists and is a directory.
def directory(relative_path)
parts = relative_path.split('/')
until parts.empty?
partial = File.join(parts)
path = destination_path(partial)
if File.exist?(path)
if Dir[File.join(path, '*')].empty?
logger.rmdir partial
unless options[:pretend]
if options[:svn]
# If the directory has been marked to be added
# but has not yet been checked in, revert and delete
if options[:svn][relative_path]
system("svn revert #{path}")
FileUtils.rmdir(path)
else
# If the directory is not in the status list, it
# has no modifications so we can simply remove it
system("svn rm #{path}")
end
# I don't think git needs to remove directories?..
# or maybe they have special consideration...
else
FileUtils.rmdir(path)
end
end
else
logger.notempty partial
end
else
logger.missing partial
end
parts.pop
end
end
def complex_template(*args)
# nothing should be done here
end
# When deleting a migration, it knows to delete every file named "[0-9]*_#{file_name}".
def migration_template(relative_source, relative_destination, template_options = {})
migration_directory relative_destination
migration_file_name = template_options[:migration_file_name] || file_name
unless migration_exists?(migration_file_name)
puts "There is no migration named #{migration_file_name}"
return
end
existing_migrations(migration_file_name).each do |file_path|
file(relative_source, file_path, template_options)
end
end
def route_resources(*resources)
resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
look_for = "\n map.resources #{resource_list}\n"
logger.route "map.resources #{resource_list}"
gsub_file 'config/routes.rb', /(#{look_for})/mi, ''
end
end
# List a generator's action manifest.
class List < Base
def dependency(generator_name, args, options = {})
logger.dependency "#{generator_name}(#{args.join(', ')}, #{options.inspect})"
end
def class_collisions(*class_names)
logger.class_collisions class_names.join(', ')
end
def file(relative_source, relative_destination, options = {})
logger.file relative_destination
end
def template(relative_source, relative_destination, options = {})
logger.template relative_destination
end
def complex_template(relative_source, relative_destination, options = {})
logger.template "#{options[:insert]} inside #{relative_destination}"
end
def directory(relative_path)
logger.directory "#{destination_path(relative_path)}/"
end
def readme(*args)
logger.readme args.join(', ')
end
def migration_template(relative_source, relative_destination, options = {})
migration_directory relative_destination
logger.migration_template file_name
end
def route_resources(*resources)
resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
logger.route "map.resources #{resource_list}"
end
end
# Update generator's action manifest.
class Update < Create
def file(relative_source, relative_destination, options = {})
# logger.file relative_destination
end
def template(relative_source, relative_destination, options = {})
# logger.template relative_destination
end
def complex_template(relative_source, relative_destination, template_options = {})
begin
dest_file = destination_path(relative_destination)
source_to_update = File.readlines(dest_file).join
rescue Errno::ENOENT
logger.missing relative_destination
return
end
logger.refreshing "#{template_options[:insert].gsub(/\.erb/,'')} inside #{relative_destination}"
begin_mark = Regexp.quote(template_part_mark(template_options[:begin_mark], template_options[:mark_id]))
end_mark = Regexp.quote(template_part_mark(template_options[:end_mark], template_options[:mark_id]))
# Refreshing inner part of the template with freshly rendered part.
rendered_part = render_template_part(template_options)
source_to_update.gsub!(/#{begin_mark}.*?#{end_mark}/m, rendered_part)
File.open(dest_file, 'w') { |file| file.write(source_to_update) }
end
def directory(relative_path)
# logger.directory "#{destination_path(relative_path)}/"
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/lookup.rb | provider/vendor/rails/railties/lib/rails_generator/lookup.rb | require 'pathname'
require File.dirname(__FILE__) + '/spec'
class Object
class << self
# Lookup missing generators using const_missing. This allows any
# generator to reference another without having to know its location:
# RubyGems, ~/.rails/generators, and RAILS_ROOT/generators.
def lookup_missing_generator(class_id)
if md = /(.+)Generator$/.match(class_id.to_s)
name = md.captures.first.demodulize.underscore
Rails::Generator::Base.lookup(name).klass
else
const_missing_before_generators(class_id)
end
end
unless respond_to?(:const_missing_before_generators)
alias_method :const_missing_before_generators, :const_missing
alias_method :const_missing, :lookup_missing_generator
end
end
end
# User home directory lookup adapted from RubyGems.
def Dir.user_home
if ENV['HOME']
ENV['HOME']
elsif ENV['USERPROFILE']
ENV['USERPROFILE']
elsif ENV['HOMEDRIVE'] and ENV['HOMEPATH']
"#{ENV['HOMEDRIVE']}:#{ENV['HOMEPATH']}"
else
File.expand_path '~'
end
end
module Rails
module Generator
# Generator lookup is managed by a list of sources which return specs
# describing where to find and how to create generators. This module
# provides class methods for manipulating the source list and looking up
# generator specs, and an #instance wrapper for quickly instantiating
# generators by name.
#
# A spec is not a generator: it's a description of where to find
# the generator and how to create it. A source is anything that
# yields generators from #each. PathSource and GemGeneratorSource are provided.
module Lookup
def self.included(base)
base.extend(ClassMethods)
base.use_component_sources!
end
# Convenience method to instantiate another generator.
def instance(generator_name, args, runtime_options = {})
self.class.instance(generator_name, args, runtime_options)
end
module ClassMethods
# The list of sources where we look, in order, for generators.
def sources
read_inheritable_attribute(:sources) or use_component_sources!
end
# Add a source to the end of the list.
def append_sources(*args)
sources.concat(args.flatten)
invalidate_cache!
end
# Add a source to the beginning of the list.
def prepend_sources(*args)
write_inheritable_array(:sources, args.flatten + sources)
invalidate_cache!
end
# Reset the source list.
def reset_sources
write_inheritable_attribute(:sources, [])
invalidate_cache!
end
# Use application generators (app, ?).
def use_application_sources!
reset_sources
sources << PathSource.new(:builtin, "#{File.dirname(__FILE__)}/generators/applications")
end
# Use component generators (model, controller, etc).
# 1. Rails application. If RAILS_ROOT is defined we know we're
# generating in the context of a Rails application, so search
# RAILS_ROOT/generators.
# 2. Look in plugins, either for generators/ or rails_generators/
# directories within each plugin
# 3. User home directory. Search ~/.rails/generators.
# 4. RubyGems. Search for gems named *_generator, and look for
# generators within any RubyGem's
# /rails_generators/<generator_name>_generator.rb file.
# 5. Builtins. Model, controller, mailer, scaffold, and so on.
def use_component_sources!
reset_sources
if defined? ::RAILS_ROOT
sources << PathSource.new(:lib, "#{::RAILS_ROOT}/lib/generators")
sources << PathSource.new(:vendor, "#{::RAILS_ROOT}/vendor/generators")
Rails.configuration.plugin_paths.each do |path|
relative_path = Pathname.new(File.expand_path(path)).relative_path_from(Pathname.new(::RAILS_ROOT))
sources << PathSource.new(:"plugins (#{relative_path})", "#{path}/*/**/{,rails_}generators")
end
end
sources << PathSource.new(:user, "#{Dir.user_home}/.rails/generators")
if Object.const_defined?(:Gem)
sources << GemGeneratorSource.new
sources << GemPathSource.new
end
sources << PathSource.new(:builtin, "#{File.dirname(__FILE__)}/generators/components")
end
# Lookup knows how to find generators' Specs from a list of Sources.
# Searches the sources, in order, for the first matching name.
def lookup(generator_name)
@found ||= {}
generator_name = generator_name.to_s.downcase
@found[generator_name] ||= cache.find { |spec| spec.name == generator_name }
unless @found[generator_name]
chars = generator_name.scan(/./).map{|c|"#{c}.*?"}
rx = /^#{chars}$/
gns = cache.select{|spec| spec.name =~ rx }
@found[generator_name] ||= gns.first if gns.length == 1
raise GeneratorError, "Pattern '#{generator_name}' matches more than one generator: #{gns.map{|sp|sp.name}.join(', ')}" if gns.length > 1
end
@found[generator_name] or raise GeneratorError, "Couldn't find '#{generator_name}' generator"
end
# Convenience method to lookup and instantiate a generator.
def instance(generator_name, args = [], runtime_options = {})
lookup(generator_name).klass.new(args, full_options(runtime_options))
end
private
# Lookup and cache every generator from the source list.
def cache
@cache ||= sources.inject([]) { |cache, source| cache + source.to_a }
end
# Clear the cache whenever the source list changes.
def invalidate_cache!
@cache = nil
end
end
end
# Sources enumerate (yield from #each) generator specs which describe
# where to find and how to create generators. Enumerable is mixed in so,
# for example, source.collect will retrieve every generator.
# Sources may be assigned a label to distinguish them.
class Source
include Enumerable
attr_reader :label
def initialize(label)
@label = label
end
# The each method must be implemented in subclasses.
# The base implementation raises an error.
def each
raise NotImplementedError
end
# Return a convenient sorted list of all generator names.
def names
map { |spec| spec.name }.sort
end
end
# PathSource looks for generators in a filesystem directory.
class PathSource < Source
attr_reader :path
def initialize(label, path)
super label
@path = path
end
# Yield each eligible subdirectory.
def each
Dir["#{path}/[a-z]*"].each do |dir|
if File.directory?(dir)
yield Spec.new(File.basename(dir), dir, label)
end
end
end
end
class AbstractGemSource < Source
def initialize
super :RubyGems
end
end
# GemGeneratorSource hits the mines to quarry for generators. The latest versions
# of gems named *_generator are selected.
class GemGeneratorSource < AbstractGemSource
# Yield latest versions of generator gems.
def each
dependency = Gem::Dependency.new(/_generator$/, Gem::Requirement.default)
Gem::cache.search(dependency).inject({}) { |latest, gem|
hem = latest[gem.name]
latest[gem.name] = gem if hem.nil? or gem.version > hem.version
latest
}.values.each { |gem|
yield Spec.new(gem.name.sub(/_generator$/, ''), gem.full_gem_path, label)
}
end
end
# GemPathSource looks for generators within any RubyGem's /rails_generators/<generator_name>_generator.rb file.
class GemPathSource < AbstractGemSource
# Yield each generator within rails_generator subdirectories.
def each
generator_full_paths.each do |generator|
yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label)
end
end
private
def generator_full_paths
@generator_full_paths ||=
Gem::cache.inject({}) do |latest, name_gem|
name, gem = name_gem
hem = latest[gem.name]
latest[gem.name] = gem if hem.nil? or gem.version > hem.version
latest
end.values.inject([]) do |mem, gem|
Dir[gem.full_gem_path + '/{rails_,}generators/**/*_generator.rb'].each do |generator|
mem << generator
end
mem
end
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/scripts/update.rb | provider/vendor/rails/railties/lib/rails_generator/scripts/update.rb | require File.dirname(__FILE__) + '/../scripts'
module Rails::Generator::Scripts
class Update < Base
mandatory_options :command => :update
protected
def banner
"Usage: #{$0} [options] scaffold"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/scripts/generate.rb | provider/vendor/rails/railties/lib/rails_generator/scripts/generate.rb | require File.dirname(__FILE__) + '/../scripts'
module Rails::Generator::Scripts
class Generate < Base
mandatory_options :command => :create
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/scripts/destroy.rb | provider/vendor/rails/railties/lib/rails_generator/scripts/destroy.rb | require File.dirname(__FILE__) + '/../scripts'
module Rails::Generator::Scripts
class Destroy < Base
mandatory_options :command => :destroy
protected
def usage_message
usage = "\nInstalled Generators\n"
Rails::Generator::Base.sources.each do |source|
label = source.label.to_s.capitalize
names = source.names
usage << " #{label}: #{names.join(', ')}\n" unless names.empty?
end
usage << <<end_blurb
script/generate command. For instance, 'script/destroy migration CreatePost'
will delete the appropriate XXX_create_post.rb migration file in db/migrate,
while 'script/destroy scaffold Post' will delete the posts controller and
views, post model and migration, all associated tests, and the map.resources
:posts line in config/routes.rb.
For instructions on finding new generators, run script/generate.
end_blurb
return usage
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/controller_generator.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/controller_generator.rb | class ControllerGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
# Check for class naming collisions.
m.class_collisions "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper", "#{class_name}HelperTest"
# Controller, helper, views, and test directories.
m.directory File.join('app/controllers', class_path)
m.directory File.join('app/helpers', class_path)
m.directory File.join('app/views', class_path, file_name)
m.directory File.join('test/functional', class_path)
m.directory File.join('test/unit/helpers', class_path)
# Controller class, functional test, and helper class.
m.template 'controller.rb',
File.join('app/controllers',
class_path,
"#{file_name}_controller.rb")
m.template 'functional_test.rb',
File.join('test/functional',
class_path,
"#{file_name}_controller_test.rb")
m.template 'helper.rb',
File.join('app/helpers',
class_path,
"#{file_name}_helper.rb")
m.template 'helper_test.rb',
File.join('test/unit/helpers',
class_path,
"#{file_name}_helper_test.rb")
# View template for each action.
actions.each do |action|
path = File.join('app/views', class_path, file_name, "#{action}.html.erb")
m.template 'view.html.erb', path,
:assigns => { :action => action, :path => path }
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/functional_test.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/functional_test.rb | require 'test_helper'
class <%= class_name %>ControllerTest < ActionController::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb | require 'test_helper'
class <%= class_name %>HelperTest < ActionView::TestCase
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/controller.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/controller.rb | class <%= class_name %>Controller < ApplicationController
<% for action in actions -%>
def <%= action %>
end
<% end -%>
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/helper.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/controller/templates/helper.rb | module <%= class_name %>Helper
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/plugin_generator.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/plugin_generator.rb | class PluginGenerator < Rails::Generator::NamedBase
attr_reader :plugin_path
def initialize(runtime_args, runtime_options = {})
@with_generator = runtime_args.delete("--with-generator")
super
@plugin_path = "vendor/plugins/#{file_name}"
end
def manifest
record do |m|
# Check for class naming collisions.
m.class_collisions class_name
m.directory "#{plugin_path}/lib"
m.directory "#{plugin_path}/tasks"
m.directory "#{plugin_path}/test"
m.template 'README', "#{plugin_path}/README"
m.template 'MIT-LICENSE', "#{plugin_path}/MIT-LICENSE"
m.template 'Rakefile', "#{plugin_path}/Rakefile"
m.template 'init.rb', "#{plugin_path}/init.rb"
m.template 'install.rb', "#{plugin_path}/install.rb"
m.template 'uninstall.rb', "#{plugin_path}/uninstall.rb"
m.template 'plugin.rb', "#{plugin_path}/lib/#{file_name}.rb"
m.template 'tasks.rake', "#{plugin_path}/tasks/#{file_name}_tasks.rake"
m.template 'unit_test.rb', "#{plugin_path}/test/#{file_name}_test.rb"
m.template 'test_helper.rb', "#{plugin_path}/test/test_helper.rb"
if @with_generator
m.directory "#{plugin_path}/generators"
m.directory "#{plugin_path}/generators/#{file_name}"
m.directory "#{plugin_path}/generators/#{file_name}/templates"
m.template 'generator.rb', "#{plugin_path}/generators/#{file_name}/#{file_name}_generator.rb"
m.template 'USAGE', "#{plugin_path}/generators/#{file_name}/USAGE"
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/unit_test.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/unit_test.rb | require 'test_helper'
class <%= class_name %>Test < ActiveSupport::TestCase
# Replace this with your real tests.
test "the truth" do
assert true
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/uninstall.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/uninstall.rb | # Uninstall hook code here
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/plugin.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/plugin.rb | # <%= class_name %>
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/test_helper.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/test_helper.rb | require 'rubygems'
require 'active_support'
require 'active_support/test_case' | ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/generator.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/generator.rb | class <%= class_name %>Generator < Rails::Generator::NamedBase
def manifest
record do |m|
# m.directory "lib"
# m.template 'README', "README"
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/install.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/install.rb | # Install hook code here
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/init.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/plugin/templates/init.rb | # Include hook code here
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb | class ScaffoldGenerator < Rails::Generator::NamedBase
default_options :skip_timestamps => false, :skip_migration => false, :force_plural => false
attr_reader :controller_name,
:controller_class_path,
:controller_file_path,
:controller_class_nesting,
:controller_class_nesting_depth,
:controller_class_name,
:controller_underscore_name,
:controller_singular_name,
:controller_plural_name
alias_method :controller_file_name, :controller_underscore_name
alias_method :controller_table_name, :controller_plural_name
def initialize(runtime_args, runtime_options = {})
super
if @name == @name.pluralize && !options[:force_plural]
logger.warning "Plural version of the model detected, using singularized version. Override with --force-plural."
@name = @name.singularize
assign_names!(@name)
end
@controller_name = @name.pluralize
base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@controller_name)
@controller_class_name_without_nesting, @controller_underscore_name, @controller_plural_name = inflect_names(base_name)
@controller_singular_name=base_name.singularize
if @controller_class_nesting.empty?
@controller_class_name = @controller_class_name_without_nesting
else
@controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
end
end
def manifest
record do |m|
# Check for class naming collisions.
m.class_collisions("#{controller_class_name}Controller", "#{controller_class_name}Helper")
m.class_collisions(class_name)
# Controller, helper, views, test and stylesheets directories.
m.directory(File.join('app/models', class_path))
m.directory(File.join('app/controllers', controller_class_path))
m.directory(File.join('app/helpers', controller_class_path))
m.directory(File.join('app/views', controller_class_path, controller_file_name))
m.directory(File.join('app/views/layouts', controller_class_path))
m.directory(File.join('test/functional', controller_class_path))
m.directory(File.join('test/unit', class_path))
m.directory(File.join('test/unit/helpers', class_path))
m.directory(File.join('public/stylesheets', class_path))
for action in scaffold_views
m.template(
"view_#{action}.html.erb",
File.join('app/views', controller_class_path, controller_file_name, "#{action}.html.erb")
)
end
# Layout and stylesheet.
m.template('layout.html.erb', File.join('app/views/layouts', controller_class_path, "#{controller_file_name}.html.erb"))
m.template('style.css', 'public/stylesheets/scaffold.css')
m.template(
'controller.rb', File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb")
)
m.template('functional_test.rb', File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb"))
m.template('helper.rb', File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb"))
m.template('helper_test.rb', File.join('test/unit/helpers', controller_class_path, "#{controller_file_name}_helper_test.rb"))
m.route_resources controller_file_name
m.dependency 'model', [name] + @args, :collision => :skip
end
end
protected
# Override with your own usage banner.
def banner
"Usage: #{$0} scaffold ModelName [field:type, field:type]"
end
def add_options!(opt)
opt.separator ''
opt.separator 'Options:'
opt.on("--skip-timestamps",
"Don't add timestamps to the migration file for this model") { |v| options[:skip_timestamps] = v }
opt.on("--skip-migration",
"Don't generate a migration file for this model") { |v| options[:skip_migration] = v }
opt.on("--force-plural",
"Forces the generation of a plural ModelName") { |v| options[:force_plural] = v }
end
def scaffold_views
%w[ index show new edit ]
end
def model_name
class_name.demodulize
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/functional_test.rb | require 'test_helper'
class <%= controller_class_name %>ControllerTest < ActionController::TestCase
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:<%= table_name %>)
end
test "should get new" do
get :new
assert_response :success
end
test "should create <%= file_name %>" do
assert_difference('<%= class_name %>.count') do
post :create, :<%= file_name %> => { }
end
assert_redirected_to <%= file_name %>_path(assigns(:<%= file_name %>))
end
test "should show <%= file_name %>" do
get :show, :id => <%= table_name %>(:one).to_param
assert_response :success
end
test "should get edit" do
get :edit, :id => <%= table_name %>(:one).to_param
assert_response :success
end
test "should update <%= file_name %>" do
put :update, :id => <%= table_name %>(:one).to_param, :<%= file_name %> => { }
assert_redirected_to <%= file_name %>_path(assigns(:<%= file_name %>))
end
test "should destroy <%= file_name %>" do
assert_difference('<%= class_name %>.count', -1) do
delete :destroy, :id => <%= table_name %>(:one).to_param
end
assert_redirected_to <%= table_name %>_path
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb | require 'test_helper'
class <%= controller_class_name %>HelperTest < ActionView::TestCase
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/controller.rb | class <%= controller_class_name %>Controller < ApplicationController
# GET /<%= table_name %>
# GET /<%= table_name %>.xml
def index
@<%= table_name %> = <%= class_name %>.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @<%= table_name %> }
end
end
# GET /<%= table_name %>/1
# GET /<%= table_name %>/1.xml
def show
@<%= file_name %> = <%= class_name %>.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @<%= file_name %> }
end
end
# GET /<%= table_name %>/new
# GET /<%= table_name %>/new.xml
def new
@<%= file_name %> = <%= class_name %>.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @<%= file_name %> }
end
end
# GET /<%= table_name %>/1/edit
def edit
@<%= file_name %> = <%= class_name %>.find(params[:id])
end
# POST /<%= table_name %>
# POST /<%= table_name %>.xml
def create
@<%= file_name %> = <%= class_name %>.new(params[:<%= file_name %>])
respond_to do |format|
if @<%= file_name %>.save
flash[:notice] = '<%= class_name %> was successfully created.'
format.html { redirect_to(@<%= file_name %>) }
format.xml { render :xml => @<%= file_name %>, :status => :created, :location => @<%= file_name %> }
else
format.html { render :action => "new" }
format.xml { render :xml => @<%= file_name %>.errors, :status => :unprocessable_entity }
end
end
end
# PUT /<%= table_name %>/1
# PUT /<%= table_name %>/1.xml
def update
@<%= file_name %> = <%= class_name %>.find(params[:id])
respond_to do |format|
if @<%= file_name %>.update_attributes(params[:<%= file_name %>])
flash[:notice] = '<%= class_name %> was successfully updated.'
format.html { redirect_to(@<%= file_name %>) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @<%= file_name %>.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /<%= table_name %>/1
# DELETE /<%= table_name %>/1.xml
def destroy
@<%= file_name %> = <%= class_name %>.find(params[:id])
@<%= file_name %>.destroy
respond_to do |format|
format.html { redirect_to(<%= table_name %>_url) }
format.xml { head :ok }
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/helper.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/scaffold/templates/helper.rb | module <%= controller_class_name %>Helper
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb | class MailerGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
# Check for class naming collisions.
m.class_collisions class_name, "#{class_name}Test"
# Mailer, view, test, and fixture directories.
m.directory File.join('app/models', class_path)
m.directory File.join('app/views', file_path)
m.directory File.join('test/unit', class_path)
m.directory File.join('test/fixtures', file_path)
# Mailer class and unit test.
m.template "mailer.rb", File.join('app/models', class_path, "#{file_name}.rb")
m.template "unit_test.rb", File.join('test/unit', class_path, "#{file_name}_test.rb")
# View template and fixture for each action.
actions.each do |action|
relative_path = File.join(file_path, action)
view_path = File.join('app/views', "#{relative_path}.erb")
fixture_path = File.join('test/fixtures', relative_path)
m.template "view.erb", view_path,
:assigns => { :action => action, :path => view_path }
m.template "fixture.erb", fixture_path,
:assigns => { :action => action, :path => view_path }
end
end
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/mailer.rb | class <%= class_name %> < ActionMailer::Base
<% for action in actions -%>
def <%= action %>(sent_at = Time.now)
subject '<%= class_name %>#<%= action %>'
recipients ''
from ''
sent_on sent_at
body :greeting => 'Hi,'
end
<% end -%>
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/mailer/templates/unit_test.rb | require 'test_helper'
class <%= class_name %>Test < ActionMailer::TestCase
<% for action in actions -%>
test "<%= action %>" do
@expected.subject = '<%= class_name %>#<%= action %>'
@expected.body = read_fixture('<%= action %>')
@expected.date = Time.now
assert_equal @expected.encoded, <%= class_name %>.create_<%= action %>(@expected.date).encoded
end
<% end -%>
<% if actions.blank? -%>
# replace this with your real tests
test "the truth" do
assert true
end
<% end -%>
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
ThoughtWorksStudios/oauth2_provider | https://github.com/ThoughtWorksStudios/oauth2_provider/blob/d54702f194edd05389968cf8947465860abccc5d/provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/resource_generator.rb | provider/vendor/rails/railties/lib/rails_generator/generators/components/resource/resource_generator.rb | class ResourceGenerator < Rails::Generator::NamedBase
default_options :skip_timestamps => false, :skip_migration => false
attr_reader :controller_name,
:controller_class_path,
:controller_file_path,
:controller_class_nesting,
:controller_class_nesting_depth,
:controller_class_name,
:controller_singular_name,
:controller_plural_name
alias_method :controller_file_name, :controller_singular_name
alias_method :controller_table_name, :controller_plural_name
def initialize(runtime_args, runtime_options = {})
super
@controller_name = @name.pluralize
base_name, @controller_class_path, @controller_file_path, @controller_class_nesting, @controller_class_nesting_depth = extract_modules(@controller_name)
@controller_class_name_without_nesting, @controller_singular_name, @controller_plural_name = inflect_names(base_name)
if @controller_class_nesting.empty?
@controller_class_name = @controller_class_name_without_nesting
else
@controller_class_name = "#{@controller_class_nesting}::#{@controller_class_name_without_nesting}"
end
end
def manifest
record do |m|
# Check for class naming collisions.
m.class_collisions("#{controller_class_name}Controller", "#{controller_class_name}Helper")
m.class_collisions(class_name)
# Controller, helper, views, and test directories.
m.directory(File.join('app/models', class_path))
m.directory(File.join('app/controllers', controller_class_path))
m.directory(File.join('app/helpers', controller_class_path))
m.directory(File.join('app/views', controller_class_path, controller_file_name))
m.directory(File.join('test/functional', controller_class_path))
m.directory(File.join('test/unit', class_path))
m.directory(File.join('test/unit/helpers', class_path))
m.dependency 'model', [name] + @args, :collision => :skip
m.template(
'controller.rb', File.join('app/controllers', controller_class_path, "#{controller_file_name}_controller.rb")
)
m.template('functional_test.rb', File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb"))
m.template('helper.rb', File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb"))
m.template('helper_test.rb', File.join('test/unit/helpers', controller_class_path, "#{controller_file_name}_helper_test.rb"))
m.route_resources controller_file_name
end
end
protected
def banner
"Usage: #{$0} resource ModelName [field:type, field:type]"
end
def add_options!(opt)
opt.separator ''
opt.separator 'Options:'
opt.on("--skip-timestamps",
"Don't add timestamps to the migration file for this model") { |v| options[:skip_timestamps] = v }
opt.on("--skip-migration",
"Don't generate a migration file for this model") { |v| options[:skip_migration] = v }
end
def model_name
class_name.demodulize
end
end
| ruby | MIT | d54702f194edd05389968cf8947465860abccc5d | 2026-01-04T17:46:04.645080Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.