diff options
Diffstat (limited to 'activesupport/lib/active_support')
19 files changed, 1347 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/binding_of_caller.rb b/activesupport/lib/active_support/binding_of_caller.rb new file mode 100644 index 0000000000..d18fbdef3d --- /dev/null +++ b/activesupport/lib/active_support/binding_of_caller.rb @@ -0,0 +1,83 @@ +begin
+ require 'simplecc'
+rescue LoadError
+ class Continuation; end # :nodoc: # for RDoc
+ def Continuation.create(*args, &block) # :nodoc:
+ cc = nil; result = callcc {|c| cc = c; block.call(cc) if block and args.empty?}
+ result ||= args
+ return *[cc, *result]
+ end
+end
+
+class Binding; end # for RDoc
+# This method returns the binding of the method that called your
+# method. It will raise an Exception when you're not inside a method.
+#
+# It's used like this:
+# def inc_counter(amount = 1)
+# Binding.of_caller do |binding|
+# # Create a lambda that will increase the variable 'counter'
+# # in the caller of this method when called.
+# inc = eval("lambda { |arg| counter += arg }", binding)
+# # We can refer to amount from inside this block safely.
+# inc.call(amount)
+# end
+# # No other statements can go here. Put them inside the block.
+# end
+# counter = 0
+# 2.times { inc_counter }
+# counter # => 2
+#
+# Binding.of_caller must be the last statement in the method.
+# This means that you will have to put everything you want to
+# do after the call to Binding.of_caller into the block of it.
+# This should be no problem however, because Ruby has closures.
+# If you don't do this an Exception will be raised. Because of
+# the way that Binding.of_caller is implemented it has to be
+# done this way.
+def Binding.of_caller(&block)
+ old_critical = Thread.critical
+ Thread.critical = true
+ count = 0
+ cc, result, error, extra_data = Continuation.create(nil, nil)
+ error.call if error
+
+ tracer = lambda do |*args|
+ type, context, extra_data = args[0], args[4], args
+ if type == "return"
+ count += 1
+ # First this method and then calling one will return --
+ # the trace event of the second event gets the context
+ # of the method which called the method that called this
+ # method.
+ if count == 2
+ # It would be nice if we could restore the trace_func
+ # that was set before we swapped in our own one, but
+ # this is impossible without overloading set_trace_func
+ # in current Ruby.
+ set_trace_func(nil)
+ cc.call(eval("binding", context), nil, extra_data)
+ end
+ elsif type == "line" then
+ nil
+ elsif type == "c-return" and extra_data[3] == :set_trace_func then
+ nil
+ else
+ set_trace_func(nil)
+ error_msg = "Binding.of_caller used in non-method context or " +
+ "trailing statements of method using it aren't in the block."
+ cc.call(nil, lambda { raise(ArgumentError, error_msg) }, nil)
+ end
+ end
+
+ unless result
+ set_trace_func(tracer)
+ return nil
+ else
+ Thread.critical = old_critical
+ case block.arity
+ when 1 then yield(result)
+ else yield(result, extra_data)
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/breakpoint.rb b/activesupport/lib/active_support/breakpoint.rb new file mode 100755 index 0000000000..1c171e2ee6 --- /dev/null +++ b/activesupport/lib/active_support/breakpoint.rb @@ -0,0 +1,518 @@ +# The Breakpoint library provides the convenience of +# being able to inspect and modify state, diagnose +# bugs all via IRB by simply setting breakpoints in +# your applications by the call of a method. +# +# This library was written and is supported by me, +# Florian Gross. I can be reached at flgr@ccan.de +# and enjoy getting feedback about my libraries. +# +# The whole library (including breakpoint_client.rb +# and binding_of_caller.rb) is licensed under the +# same license that Ruby uses. (Which is currently +# either the GNU General Public License or a custom +# one that allows for commercial usage.) If you for +# some good reason need to use this under another +# license please contact me. + +require 'irb' +require File.dirname(__FILE__) + '/binding_of_caller' +require 'drb' +require 'drb/acl' + +module Breakpoint + id = %q$Id: breakpoint.rb 41 2005-01-22 20:22:10Z flgr $ + Version = id.split(" ")[2].to_i + + extend self + + # This will pop up an interactive ruby session at a + # pre-defined break point in a Ruby application. In + # this session you can examine the environment of + # the break point. + # + # You can get a list of variables in the context using + # local_variables via +local_variables+. You can then + # examine their values by typing their names. + # + # You can have a look at the call stack via +caller+. + # + # The source code around the location where the breakpoint + # was executed can be examined via +source_lines+. Its + # argument specifies how much lines of context to display. + # The default amount of context is 5 lines. Note that + # the call to +source_lines+ can raise an exception when + # it isn't able to read in the source code. + # + # breakpoints can also return a value. They will execute + # a supplied block for getting a default return value. + # A custom value can be returned from the session by doing + # +throw(:debug_return, value)+. + # + # You can also give names to break points which will be + # used in the message that is displayed upon execution + # of them. + # + # Here's a sample of how breakpoints should be placed: + # + # class Person + # def initialize(name, age) + # @name, @age = name, age + # breakpoint("Person#initialize") + # end + # + # attr_reader :age + # def name + # breakpoint("Person#name") { @name } + # end + # end + # + # person = Person.new("Random Person", 23) + # puts "Name: #{person.name}" + # + # And here is a sample debug session: + # + # Executing break point "Person#initialize" at file.rb:4 in `initialize' + # irb(#<Person:0x292fbe8>):001:0> local_variables + # => ["name", "age", "_", "__"] + # irb(#<Person:0x292fbe8>):002:0> [name, age] + # => ["Random Person", 23] + # irb(#<Person:0x292fbe8>):003:0> [@name, @age] + # => ["Random Person", 23] + # irb(#<Person:0x292fbe8>):004:0> self + # => #<Person:0x292fbe8 @age=23, @name="Random Person"> + # irb(#<Person:0x292fbe8>):005:0> @age += 1; self + # => #<Person:0x292fbe8 @age=24, @name="Random Person"> + # irb(#<Person:0x292fbe8>):006:0> exit + # Executing break point "Person#name" at file.rb:9 in `name' + # irb(#<Person:0x292fbe8>):001:0> throw(:debug_return, "Overriden name") + # Name: Overriden name + # + # Breakpoint sessions will automatically have a few + # convenience methods available. See Breakpoint::CommandBundle + # for a list of them. + # + # Breakpoints can also be used remotely over sockets. + # This is implemented by running part of the IRB session + # in the application and part of it in a special client. + # You have to call Breakpoint.activate_drb to enable + # support for remote breakpoints and then run + # breakpoint_client.rb which is distributed with this + # library. See the documentation of Breakpoint.activate_drb + # for details. + def breakpoint(id = nil, context = nil, &block) + callstack = caller + callstack.slice!(0, 3) if callstack.first["breakpoint"] + file, line, method = *callstack.first.match(/^(.+?):(\d+)(?::in `(.*?)')?/).captures + + message = "Executing break point " + (id ? "#{id.inspect} " : "") + + "at #{file}:#{line}" + (method ? " in `#{method}'" : "") + + if context then + return handle_breakpoint(context, message, file, line, &block) + end + + Binding.of_caller do |binding_context| + handle_breakpoint(binding_context, message, file, line, &block) + end + end + + module CommandBundle + # Proxy to a Breakpoint client. Lets you directly execute code + # in the context of the client. + class Client + def initialize(eval_handler) # :nodoc: + @eval_handler = eval_handler + end + + instance_methods.each do |method| + next if method[/^__.+__$/] + undef_method method + end + + # Executes the specified code at the client. + def eval(code) + @eval_handler.call(code) + end + + # Will execute the specified statement at the client. + def method_missing(method, *args, &block) + if args.empty? and not block + result = eval "#{method}" + else + # This is a bit ugly. The alternative would be using an + # eval context instead of an eval handler for executing + # the code at the client. The problem with that approach + # is that we would have to handle special expressions + # like "self", "nil" or constants ourself which is hard. + remote = eval %{ + result = lambda { |block, *args| #{method}(*args, &block) } + def result.call_with_block(*args, &block) + call(block, *args) + end + result + } + remote.call_with_block(*args, &block) + end + + return result + end + end + + # Returns the source code surrounding the location where the + # breakpoint was issued. + def source_lines(context = 5, return_line_numbers = false) + lines = File.readlines(@__bp_file).map { |line| line.chomp } + + break_line = @__bp_line + start_line = [break_line - context, 1].max + end_line = break_line + context + + result = lines[(start_line - 1) .. (end_line - 1)] + + if return_line_numbers then + return [start_line, break_line, result] + else + return result + end + end + + # Lets an object that will forward method calls to the breakpoint + # client. This is useful for outputting longer things at the client + # and so on. You can for example do these things: + # + # client.puts "Hello" # outputs "Hello" at client console + # # outputs "Hello" into the file temp.txt at the client + # client.File.open("temp.txt", "w") { |f| f.puts "Hello" } + def client() + if Breakpoint.use_drb? then + sleep(0.5) until Breakpoint.drb_service.eval_handler + Client.new(Breakpoint.drb_service.eval_handler) + else + Client.new(lambda { |code| eval(code, TOPLEVEL_BINDING) }) + end + end + end + + def handle_breakpoint(context, message, file = "", line = "", &block) # :nodoc: + catch(:debug_return) do |value| + eval(%{ + @__bp_file = #{file.inspect} + @__bp_line = #{line} + extend Breakpoint::CommandBundle + extend DRbUndumped if self + }, context) rescue nil + + if not use_drb? then + puts message + IRB.start(nil, IRB::WorkSpace.new(context)) + else + @drb_service.add_breakpoint(context, message) + end + + block.call if block + end + end + + # These exceptions will be raised on failed asserts + # if Breakpoint.asserts_cause_exceptions is set to + # true. + class FailedAssertError < RuntimeError + end + + # This asserts that the block evaluates to true. + # If it doesn't evaluate to true a breakpoint will + # automatically be created at that execution point. + # + # You can disable assert checking in production + # code by setting Breakpoint.optimize_asserts to + # true. (It will still be enabled when Ruby is run + # via the -d argument.) + # + # Example: + # person_name = "Foobar" + # assert { not person_name.nil? } + # + # Note: If you want to use this method from an + # unit test, you will have to call it by its full + # name, Breakpoint.assert. + def assert(context = nil, &condition) + return if Breakpoint.optimize_asserts and not $DEBUG + return if yield + + callstack = caller + callstack.slice!(0, 3) if callstack.first["assert"] + file, line, method = *callstack.first.match(/^(.+?):(\d+)(?::in `(.*?)')?/).captures + + message = "Assert failed at #{file}:#{line}#{" in `#{method}'" if method}." + + if Breakpoint.asserts_cause_exceptions and not $DEBUG then + raise(Breakpoint::FailedAssertError, message) + end + + message += " Executing implicit breakpoint." + + if context then + return handle_breakpoint(context, message, file, line) + end + + Binding.of_caller do |context| + handle_breakpoint(context, message, file, line) + end + end + + # Whether asserts should be ignored if not in debug mode. + # Debug mode can be enabled by running ruby with the -d + # switch or by setting $DEBUG to true. + attr_accessor :optimize_asserts + self.optimize_asserts = false + + # Whether an Exception should be raised on failed asserts + # in non-$DEBUG code or not. By default this is disabled. + attr_accessor :asserts_cause_exceptions + self.asserts_cause_exceptions = false + @use_drb = false + + attr_reader :drb_service # :nodoc: + + class DRbService # :nodoc: + include DRbUndumped + + def initialize + @handler = @eval_handler = @collision_handler = nil + + IRB.instance_eval { @CONF[:RC] = true } + IRB.run_config + end + + def collision + sleep(0.5) until @collision_handler + + @collision_handler.call + end + + def ping() end + + def add_breakpoint(context, message) + workspace = IRB::WorkSpace.new(context) + workspace.extend(DRbUndumped) + + sleep(0.5) until @handler + + @handler.call(workspace, message) + end + + attr_accessor :handler, :eval_handler, :collision_handler + end + + # Will run Breakpoint in DRb mode. This will spawn a server + # that can be attached to via the breakpoint-client command + # whenever a breakpoint is executed. This is useful when you + # are debugging CGI applications or other applications where + # you can't access debug sessions via the standard input and + # output of your application. + # + # You can specify an URI where the DRb server will run at. + # This way you can specify the port the server runs on. The + # default URI is druby://localhost:42531. + # + # Please note that breakpoints will be skipped silently in + # case the DRb server can not spawned. (This can happen if + # the port is already used by another instance of your + # application on CGI or another application.) + # + # Also note that by default this will only allow access + # from localhost. You can however specify a list of + # allowed hosts or nil (to allow access from everywhere). + # But that will still not protect you from somebody + # reading the data as it goes through the net. + # + # A good approach for getting security and remote access + # is setting up an SSH tunnel between the DRb service + # and the client. This is usually done like this: + # + # $ ssh -L20000:127.0.0.1:20000 -R10000:127.0.0.1:10000 example.com + # (This will connect port 20000 at the client side to port + # 20000 at the server side, and port 10000 at the server + # side to port 10000 at the client side.) + # + # After that do this on the server side: (the code being debugged) + # Breakpoint.activate_drb("druby://127.0.0.1:20000", "localhost") + # + # And at the client side: + # ruby breakpoint_client.rb -c druby://127.0.0.1:10000 -s druby://127.0.0.1:20000 + # + # Running through such a SSH proxy will also let you use + # breakpoint.rb in case you are behind a firewall. + # + # Detailed information about running DRb through firewalls is + # available at http://www.rubygarden.org/ruby?DrbTutorial + def activate_drb(uri = nil, allowed_hosts = ['localhost', '127.0.0.1', '::1'], + ignore_collisions = false) + + return false if @use_drb + + uri ||= 'druby://localhost:42531' + + if allowed_hosts then + acl = ["deny", "all"] + + Array(allowed_hosts).each do |host| + acl += ["allow", host] + end + + DRb.install_acl(ACL.new(acl)) + end + + @use_drb = true + @drb_service = DRbService.new + did_collision = false + begin + @service = DRb.start_service(uri, @drb_service) + rescue Errno::EADDRINUSE + if ignore_collisions then + nil + else + # The port is already occupied by another + # Breakpoint service. We will try to tell + # the old service that we want its port. + # It will then forward that request to the + # user and retry. + unless did_collision then + DRbObject.new(nil, uri).collision + did_collision = true + end + sleep(10) + retry + end + end + + return true + end + + # Deactivates a running Breakpoint service. + def deactivate_drb + @service.stop_service unless @service.nil? + @service = nil + @use_drb = false + @drb_service = nil + end + + # Returns true when Breakpoints are used over DRb. + # Breakpoint.activate_drb causes this to be true. + def use_drb? + @use_drb == true + end +end + +module IRB # :nodoc: + class << self; remove_method :start; end + def self.start(ap_path = nil, main_context = nil, workspace = nil) + $0 = File::basename(ap_path, ".rb") if ap_path + + # suppress some warnings about redefined constants + old_verbose, $VERBOSE = $VERBOSE, nil + IRB.setup(ap_path) + $VERBOSE = old_verbose + + if @CONF[:SCRIPT] then + irb = Irb.new(main_context, @CONF[:SCRIPT]) + else + irb = Irb.new(main_context) + end + + if workspace then + irb.context.workspace = workspace + end + + @CONF[:IRB_RC].call(irb.context) if @CONF[:IRB_RC] + @CONF[:MAIN_CONTEXT] = irb.context + + old_sigint = trap("SIGINT") do + begin + irb.signal_handle + rescue RubyLex::TerminateLineInput + # ignored + end + end + + catch(:IRB_EXIT) do + irb.eval_input + end + ensure + trap("SIGINT", old_sigint) + end + + class << self + alias :old_CurrentContext :CurrentContext + remove_method :CurrentContext + end + def IRB.CurrentContext + if old_CurrentContext.nil? and Breakpoint.use_drb? then + result = Object.new + def result.last_value; end + return result + else + old_CurrentContext + end + end + + class Context + alias :old_evaluate :evaluate + def evaluate(line, line_no) + if line.chomp == "exit" then + exit + else + old_evaluate(line, line_no) + end + end + end + + class WorkSpace + alias :old_evaluate :evaluate + + def evaluate(*args) + if Breakpoint.use_drb? then + result = old_evaluate(*args) + if args[0] != :no_proxy and + not [true, false, nil].include?(result) + then + result.extend(DRbUndumped) rescue nil + end + return result + else + old_evaluate(*args) + end + end + end + + module InputCompletor + def self.eval(code, context, *more) + # Big hack, this assumes that InputCompletor + # will only call eval() when it wants code + # to be executed in the IRB context. + IRB.conf[:MAIN_CONTEXT].workspace.evaluate(:no_proxy, code, *more) + end + end +end + +module DRb # :nodoc: + class DRbObject + undef :inspect if method_defined?(:inspect) + undef :clone if method_defined?(:clone) + end +end + +# See Breakpoint.breakpoint +def breakpoint(id = nil, &block) + Binding.of_caller do |context| + Breakpoint.breakpoint(id, context, &block) + end +end + +# See Breakpoint.assert +def assert(&block) + Binding.of_caller do |context| + Breakpoint.assert(context, &block) + end +end diff --git a/activesupport/lib/active_support/class_attribute_accessors.rb b/activesupport/lib/active_support/class_attribute_accessors.rb new file mode 100644 index 0000000000..786dcf98cb --- /dev/null +++ b/activesupport/lib/active_support/class_attribute_accessors.rb @@ -0,0 +1,57 @@ +# Extends the class object with class and instance accessors for class attributes, +# just like the native attr* accessors for instance attributes. +class Class # :nodoc: + def cattr_reader(*syms) + syms.each do |sym| + class_eval <<-EOS + if ! defined? @@#{sym.id2name} + @@#{sym.id2name} = nil + end + + def self.#{sym.id2name} + @@#{sym} + end + + def #{sym.id2name} + @@#{sym} + end + + def call_#{sym.id2name} + case @@#{sym.id2name} + when Symbol then send(@@#{sym}) + when Proc then @@#{sym}.call(self) + when String then @@#{sym} + else nil + end + end + EOS + end + end + + def cattr_writer(*syms) + syms.each do |sym| + class_eval <<-EOS + if ! defined? @@#{sym.id2name} + @@#{sym.id2name} = nil + end + + def self.#{sym.id2name}=(obj) + @@#{sym.id2name} = obj + end + + def self.set_#{sym.id2name}(obj) + @@#{sym.id2name} = obj + end + + def #{sym.id2name}=(obj) + @@#{sym} = obj + end + EOS + end + end + + def cattr_accessor(*syms) + cattr_reader(*syms) + cattr_writer(*syms) + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/class_inheritable_attributes.rb b/activesupport/lib/active_support/class_inheritable_attributes.rb new file mode 100644 index 0000000000..f9ca7af7b2 --- /dev/null +++ b/activesupport/lib/active_support/class_inheritable_attributes.rb @@ -0,0 +1,117 @@ +# Retain for backward compatibility. Methods are now included in Class. +module ClassInheritableAttributes # :nodoc: +end + +# Allows attributes to be shared within an inheritance hierarchy, but where each descendant gets a copy of +# their parents' attributes, instead of just a pointer to the same. This means that the child can add elements +# to, for example, an array without those additions being shared with either their parent, siblings, or +# children, which is unlike the regular class-level attributes that are shared across the entire hierarchy. +class Class # :nodoc: + def class_inheritable_reader(*syms) + syms.each do |sym| + class_eval <<-EOS + def self.#{sym} + read_inheritable_attribute(:#{sym}) + end + + def #{sym} + self.class.#{sym} + end + EOS + end + end + + def class_inheritable_writer(*syms) + syms.each do |sym| + class_eval <<-EOS + def self.#{sym}=(obj) + write_inheritable_attribute(:#{sym}, obj) + end + + def #{sym}=(obj) + self.class.#{sym} = obj + end + EOS + end + end + + def class_inheritable_array_writer(*syms) + syms.each do |sym| + class_eval <<-EOS + def self.#{sym}=(obj) + write_inheritable_array(:#{sym}, obj) + end + + def #{sym}=(obj) + self.class.#{sym} = obj + end + EOS + end + end + + def class_inheritable_hash_writer(*syms) + syms.each do |sym| + class_eval <<-EOS + def self.#{sym}=(obj) + write_inheritable_hash(:#{sym}, obj) + end + + def #{sym}=(obj) + self.class.#{sym} = obj + end + EOS + end + end + + def class_inheritable_accessor(*syms) + class_inheritable_reader(*syms) + class_inheritable_writer(*syms) + end + + def class_inheritable_array(*syms) + class_inheritable_reader(*syms) + class_inheritable_array_writer(*syms) + end + + def class_inheritable_hash(*syms) + class_inheritable_reader(*syms) + class_inheritable_hash_writer(*syms) + end + + def inheritable_attributes + @inheritable_attributes ||= {} + end + + def write_inheritable_attribute(key, value) + inheritable_attributes[key] = value + end + + def write_inheritable_array(key, elements) + write_inheritable_attribute(key, []) if read_inheritable_attribute(key).nil? + write_inheritable_attribute(key, read_inheritable_attribute(key) + elements) + end + + def write_inheritable_hash(key, hash) + write_inheritable_attribute(key, {}) if read_inheritable_attribute(key).nil? + write_inheritable_attribute(key, read_inheritable_attribute(key).merge(hash)) + end + + def read_inheritable_attribute(key) + inheritable_attributes[key] + end + + def reset_inheritable_attributes + inheritable_attributes.clear + end + + private + def inherited_with_inheritable_attributes(child) + inherited_without_inheritable_attributes(child) if respond_to?(:inherited_without_inheritable_attributes) + child.instance_variable_set('@inheritable_attributes', inheritable_attributes.dup) + end + + if respond_to?(:inherited) + alias_method :inherited_without_inheritable_attributes, :inherited + end + alias_method :inherited, :inherited_with_inheritable_attributes +end diff --git a/activesupport/lib/active_support/clean_logger.rb b/activesupport/lib/active_support/clean_logger.rb new file mode 100644 index 0000000000..1a36562892 --- /dev/null +++ b/activesupport/lib/active_support/clean_logger.rb @@ -0,0 +1,10 @@ +require 'logger' + +class Logger #:nodoc: + private + remove_const "Format" + Format = "%s\n" + def format_message(severity, timestamp, msg, progname) + Format % [msg] + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/core_ext.rb b/activesupport/lib/active_support/core_ext.rb new file mode 100644 index 0000000000..573313e741 --- /dev/null +++ b/activesupport/lib/active_support/core_ext.rb @@ -0,0 +1 @@ +Dir[File.dirname(__FILE__) + "/core_ext/*.rb"].each { |file| require(file) } diff --git a/activesupport/lib/active_support/core_ext/hash.rb b/activesupport/lib/active_support/core_ext/hash.rb new file mode 100644 index 0000000000..e899d3e1e2 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/hash.rb @@ -0,0 +1,7 @@ +require File.dirname(__FILE__) + '/hash/keys' +require File.dirname(__FILE__) + '/hash/indifferent_access' + +class Hash #:nodoc: + include ActiveSupport::CoreExtensions::Hash::Keys + include ActiveSupport::CoreExtensions::Hash::IndifferentAccess +end diff --git a/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb new file mode 100644 index 0000000000..2353cfaf3b --- /dev/null +++ b/activesupport/lib/active_support/core_ext/hash/indifferent_access.rb @@ -0,0 +1,38 @@ +class HashWithIndifferentAccess < Hash + def initialize(constructor) + if constructor.is_a?(Hash) + super() + update(constructor.symbolize_keys) + else + super(constructor) + end + end + + alias_method :regular_reader, :[] unless method_defined?(:regular_reader) + + def [](key) + case key + when Symbol: regular_reader(key) || regular_reader(key.to_s) + when String: regular_reader(key) || regular_reader(key.to_sym) + else regular_reader(key) + end + end + + alias_method :regular_writer, :[]= unless method_defined?(:regular_writer) + + def []=(key, value) + regular_writer(key.is_a?(String) ? key.to_sym : key, value) + end +end + +module ActiveSupport #:nodoc: + module CoreExtensions #:nodoc: + module Hash #:nodoc: + module IndifferentAccess + def with_indifferent_access + HashWithIndifferentAccess.new(self) + end + end + end + end +end diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb new file mode 100644 index 0000000000..8725138856 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/hash/keys.rb @@ -0,0 +1,53 @@ +module ActiveSupport #:nodoc: + module CoreExtensions #:nodoc: + module Hash #:nodoc: + module Keys + # Return a new hash with all keys converted to strings. + def stringify_keys + inject({}) do |options, (key, value)| + options[key.to_s] = value + options + end + end + + # Destructively convert all keys to strings. + def stringify_keys! + keys.each do |key| + unless key.class.to_s == "String" # weird hack to make the tests run when string_ext_test.rb is also running + self[key.to_s] = self[key] + delete(key) + end + end + self + end + + # Return a new hash with all keys converted to symbols. + def symbolize_keys + inject({}) do |options, (key, value)| + options[key.to_sym] = value + options + end + end + + # Destructively convert all keys to symbols. + def symbolize_keys! + keys.each do |key| + unless key.is_a?(Symbol) + self[key.to_sym] = self[key] + delete(key) + end + end + self + end + + alias_method :to_options, :symbolize_keys + alias_method :to_options!, :symbolize_keys! + + def assert_valid_keys(valid_keys) + unknown_keys = keys - valid_keys + raise(ArgumentError, "Unknown key(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? + end + end + end + end +end diff --git a/activesupport/lib/active_support/core_ext/numeric.rb b/activesupport/lib/active_support/core_ext/numeric.rb new file mode 100644 index 0000000000..88fead7aa4 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/numeric.rb @@ -0,0 +1,7 @@ +require File.dirname(__FILE__) + '/numeric/time' +require File.dirname(__FILE__) + '/numeric/bytes' + +class Numeric #:nodoc: + include ActiveSupport::CoreExtensions::Numeric::Time + include ActiveSupport::CoreExtensions::Numeric::Bytes +end diff --git a/activesupport/lib/active_support/core_ext/numeric/bytes.rb b/activesupport/lib/active_support/core_ext/numeric/bytes.rb new file mode 100644 index 0000000000..98e5e13abb --- /dev/null +++ b/activesupport/lib/active_support/core_ext/numeric/bytes.rb @@ -0,0 +1,33 @@ +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 + def bytes + self + end + alias :byte :bytes + + def kilobytes + self * 1024 + end + alias :kilobyte :kilobytes + + def megabytes + self * 1024.kilobytes + end + alias :megabyte :megabytes + + def gigabytes + self * 1024.megabytes + end + alias :gigabyte :gigabytes + + def terabytes + self * 1024.gigabytes + end + alias :terabyte :terabytes + end + end + end +end diff --git a/activesupport/lib/active_support/core_ext/numeric/time.rb b/activesupport/lib/active_support/core_ext/numeric/time.rb new file mode 100644 index 0000000000..43c0425b00 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/numeric/time.rb @@ -0,0 +1,59 @@ +module ActiveSupport #:nodoc: + module CoreExtensions #:nodoc: + module Numeric #:nodoc: + # Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years + module Time + def minutes + self * 60 + end + alias :minute :minutes + + def hours + self * 60.minutes + end + alias :hour :hours + + def days + self * 24.hours + end + alias :day :days + + def weeks + self * 7.days + end + alias :week :weeks + + def fortnights + self * 2.weeks + end + alias :fortnight :fortnights + + def months + self * 30.days + end + alias :month :months + + def years + self * 365.days + end + alias :year :years + + # 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 diff --git a/activesupport/lib/active_support/core_ext/object_and_class.rb b/activesupport/lib/active_support/core_ext/object_and_class.rb new file mode 100644 index 0000000000..59a463ae29 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/object_and_class.rb @@ -0,0 +1,24 @@ +class Object #:nodoc: + def remove_subclasses_of(superclass) + subclasses_of(superclass).each { |subclass| Object.send(:remove_const, subclass) rescue nil } + end + + def subclasses_of(superclass) + subclasses = [] + ObjectSpace.each_object(Class) do |k| + next if !k.ancestors.include?(superclass) || superclass == k || k.to_s.include?("::") || subclasses.include?(k.to_s) + subclasses << k.to_s + end + subclasses + end +end + +class Class #:nodoc: + def remove_subclasses + Object.remove_subclasses_of(self) + end + + def subclasses + Object.subclasses_of(self) + end +end diff --git a/activesupport/lib/active_support/core_ext/string.rb b/activesupport/lib/active_support/core_ext/string.rb new file mode 100644 index 0000000000..6d554b483c --- /dev/null +++ b/activesupport/lib/active_support/core_ext/string.rb @@ -0,0 +1,5 @@ +require File.dirname(__FILE__) + '/string/inflections' + +class String #:nodoc: + include ActiveSupport::CoreExtensions::String::Inflections +end diff --git a/activesupport/lib/active_support/core_ext/string/inflections.rb b/activesupport/lib/active_support/core_ext/string/inflections.rb new file mode 100644 index 0000000000..aa4ff3a74d --- /dev/null +++ b/activesupport/lib/active_support/core_ext/string/inflections.rb @@ -0,0 +1,49 @@ +require File.dirname(__FILE__) + '/../../inflector' +module ActiveSupport #:nodoc: + module CoreExtensions #:nodoc: + module String #:nodoc: + # Makes it possible to do "posts".singularize that returns "post" and "MegaCoolClass".underscore that returns "mega_cool_class". + module Inflections + def pluralize + Inflector.pluralize(self) + end + + def singularize + Inflector.singularize(self) + end + + def camelize + Inflector.camelize(self) + end + + def underscore + Inflector.underscore(self) + end + + def demodulize + Inflector.demodulize(self) + end + + def tableize + Inflector.tableize(self) + end + + def classify + Inflector.classify(self) + end + + def humanize + Inflector.humanize(self) + end + + def foreign_key(separate_class_name_and_id_with_underscore = true) + Inflector.foreign_key(self, separate_class_name_and_id_with_underscore) + end + + def constantize + Inflector.constantize(self) + end + end + end + end +end diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb new file mode 100644 index 0000000000..0a9b8e1d3d --- /dev/null +++ b/activesupport/lib/active_support/dependencies.rb @@ -0,0 +1,128 @@ +require File.dirname(__FILE__) + '/module_attribute_accessors' + +module Dependencies + extend self + + @@loaded = [ ] + mattr_accessor :loaded + + @@mechanism = :load + mattr_accessor :mechanism + + def load? + mechanism == :load + end + + def depend_on(file_name, swallow_load_errors = false) + if !loaded.include?(file_name) + loaded << file_name + begin + require_or_load(file_name) + rescue LoadError + raise unless swallow_load_errors + rescue Object => e + raise ScriptError, "#{e.message}" + end + end + end + + def associate_with(file_name) + depend_on(file_name, true) + end + + def clear + self.loaded = [ ] + end + + def require_or_load(file_name) + load? ? load("#{file_name}.rb") : require(file_name) + end + + def remove_subclasses_for(*classes) + classes.each { |klass| klass.remove_subclasses } + end + + # LoadingModules implement namespace-safe dynamic loading. + # They support automatic loading via const_missing, allowing contained items to be automatically + # loaded when required. No extra syntax is required, as expressions such as Controller::Admin::UserController + # load the relavent files automatically. + # + # Ruby-style modules are supported, as a folder named 'submodule' will load 'submodule.rb' when available. + class LoadingModule < Module + attr_reader :path + + def initialize(filesystem_root, path=[]) + @path = path + @filesystem_root = filesystem_root + end + + # The path to this module in the filesystem. + # Any subpath provided is taken to be composed of filesystem names. + def filesystem_path(subpath=[]) + File.join(@filesystem_root, self.path, subpath) + end + + # Load missing constants if possible. + def const_missing(name) + return const_get(name) if const_defined?(name) == false && const_load!(name) + super(name) + end + + # Load the controller class or a parent module. + def const_load!(name) + name = name.to_s if name.kind_of? Symbol + + if File.directory? filesystem_path(name.underscore) + # Is it a submodule? If so, create a new LoadingModule *before* loading it. + # This ensures that subitems will be loadable + new_module = LoadingModule.new(@filesystem_root, self.path + [name.underscore]) + const_set(name, new_module) + Object.const_set(name, new_module) if @path.empty? + end + + source_file = filesystem_path("#{(name == 'ApplicationController' ? 'Application' : name).underscore}.rb") + self.load_file(source_file) if File.file?(source_file) + self.const_defined?(name.camelize) + end + + # Is this name present or loadable? + # This method is used by Routes to find valid controllers. + def const_available?(name) + name = name.to_s unless name.kind_of? String + File.directory?(filesystem_path(name.underscore)) || File.file?(filesystem_path("#{name.underscore}.rb")) + end + + def clear + constants.each do |name| + Object.send(:remove_const, name) if Object.const_defined?(name) && @path.empty? + self.send(:remove_const, name) + end + end + + def load_file(file_path) + Controllers.module_eval(IO.read(file_path), file_path, 1) # Hard coded Controller line here!!! + end + end +end + +Object.send(:define_method, :require_or_load) { |file_name| Dependencies.require_or_load(file_name) } unless Object.respond_to?(:require_or_load) +Object.send(:define_method, :require_dependency) { |file_name| Dependencies.depend_on(file_name) } unless Object.respond_to?(:require_dependency) +Object.send(:define_method, :require_association) { |file_name| Dependencies.associate_with(file_name) } unless Object.respond_to?(:require_association) + +class Object #:nodoc: + class << self + # Use const_missing to autoload associations so we don't have to + # require_association when using single-table inheritance. + def const_missing(class_id) + if Object.const_defined?(:Controllers) and Object::Controllers.const_available?(class_id) + return Object::Controllers.const_get(class_id) + end + begin + require_or_load(class_id.to_s.demodulize.underscore) + if Object.const_defined?(class_id) then return Object.const_get(class_id) else raise LoadError end + rescue LoadError + raise NameError, "uninitialized constant #{class_id}" + end + end + end +end
\ No newline at end of file diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb new file mode 100644 index 0000000000..e09208dd4f --- /dev/null +++ b/activesupport/lib/active_support/inflector.rb @@ -0,0 +1,93 @@ +# The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, +# and class names to foreign keys. +module Inflector + extend self + + def pluralize(word) + result = word.to_s.dup + plural_rules.each do |(rule, replacement)| + break if result.gsub!(rule, replacement) + end + return result + end + + def singularize(word) + result = word.to_s.dup + singular_rules.each do |(rule, replacement)| + break if result.gsub!(rule, replacement) + end + return result + end + + def camelize(lower_case_and_underscored_word) + lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase } + end + + def underscore(camel_cased_word) + camel_cased_word.to_s.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z])/,'\1_\2').gsub(/([a-z])([A-Z])/,'\1_\2').downcase + end + + def humanize(lower_case_and_underscored_word) + lower_case_and_underscored_word.to_s.gsub(/_/, " ").capitalize + end + + def demodulize(class_name_in_module) + class_name_in_module.to_s.gsub(/^.*::/, '') + end + + def tableize(class_name) + pluralize(underscore(class_name)) + end + + def classify(table_name) + camelize(singularize(table_name)) + end + + def foreign_key(class_name, separate_class_name_and_id_with_underscore = true) + Inflector.underscore(Inflector.demodulize(class_name)) + + (separate_class_name_and_id_with_underscore ? "_id" : "id") + end + + def constantize(camel_cased_word) + camel_cased_word.split("::").inject(Object) do |final_type, part| + final_type = final_type.const_get(part) + end + end + + private + def plural_rules #:doc: + [ + [/(x|ch|ss|sh)$/, '\1es'], # search, switch, fix, box, process, address + [/series$/, '\1series'], + [/([^aeiouy]|qu)ies$/, '\1y'], + [/([^aeiouy]|qu)y$/, '\1ies'], # query, ability, agency + [/(?:([^f])fe|([lr])f)$/, '\1\2ves'], # half, safe, wife + [/sis$/, 'ses'], # basis, diagnosis + [/([ti])um$/, '\1a'], # datum, medium + [/person$/, 'people'], # person, salesperson + [/man$/, 'men'], # man, woman, spokesman + [/child$/, 'children'], # child + [/s$/, 's'], # no change (compatibility) + [/$/, 's'] + ] + end + + def singular_rules #:doc: + [ + [/(x|ch|ss)es$/, '\1'], + [/movies$/, 'movie'], + [/series$/, 'series'], + [/([^aeiouy]|qu)ies$/, '\1y'], + [/([lr])ves$/, '\1f'], + [/([^f])ves$/, '\1fe'], + [/(analy|ba|diagno|parenthe|progno|synop|the)ses$/, '\1sis'], + [/([ti])a$/, '\1um'], + [/people$/, 'person'], + [/men$/, 'man'], + [/status$/, 'status'], + [/children$/, 'child'], + [/news$/, 'news'], + [/s$/, ''] + ] + end +end diff --git a/activesupport/lib/active_support/misc.rb b/activesupport/lib/active_support/misc.rb new file mode 100644 index 0000000000..1ca00db1e7 --- /dev/null +++ b/activesupport/lib/active_support/misc.rb @@ -0,0 +1,8 @@ +def silence_warnings + old_verbose, $VERBOSE = $VERBOSE, nil + begin + yield + ensure + $VERBOSE = old_verbose + end +end diff --git a/activesupport/lib/active_support/module_attribute_accessors.rb b/activesupport/lib/active_support/module_attribute_accessors.rb new file mode 100644 index 0000000000..3d466e4493 --- /dev/null +++ b/activesupport/lib/active_support/module_attribute_accessors.rb @@ -0,0 +1,57 @@ +# Extends the module object with module and instance accessors for class attributes, +# just like the native attr* accessors for instance attributes. +class Module # :nodoc: + def mattr_reader(*syms) + syms.each do |sym| + class_eval <<-EOS + if ! defined? @@#{sym.id2name} + @@#{sym.id2name} = nil + end + + def self.#{sym.id2name} + @@#{sym} + end + + def #{sym.id2name} + @@#{sym} + end + + def call_#{sym.id2name} + case @@#{sym.id2name} + when Symbol then send(@@#{sym}) + when Proc then @@#{sym}.call(self) + when String then @@#{sym} + else nil + end + end + EOS + end + end + + def mattr_writer(*syms) + syms.each do |sym| + class_eval <<-EOS + if ! defined? @@#{sym.id2name} + @@#{sym.id2name} = nil + end + + def self.#{sym.id2name}=(obj) + @@#{sym.id2name} = obj + end + + def self.set_#{sym.id2name}(obj) + @@#{sym.id2name} = obj + end + + def #{sym.id2name}=(obj) + @@#{sym} = obj + end + EOS + end + end + + def mattr_accessor(*syms) + mattr_reader(*syms) + mattr_writer(*syms) + end +end
\ No newline at end of file |