Namespace
Methods
A
B
C
D
E
H
I
L
O
P
R
S
T
U
W
Included Modules
Constants
FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__))
 
AppRoutes = ActionDispatch::Routing::RouteSet.new
 
MyHash = Class.new(Hash)
 
N = (ENV['N'] || 1000).to_i
 
ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
 
FIXTURES = Pathname.new(FIXTURE_LOAD_PATH)
 
SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
 
PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib"
 
CACHE_DIR = 'test_cache'
 
FILE_STORE_PATH = File.join(File.dirname(__FILE__), '/../temp/', CACHE_DIR)
 

Don't change '/../temp/' cavalierly or you might hose something you don't want hosed

ROUTING = ActionDispatch::Routing
 

#<RDoc::Comment:0x007fde7c9072b8>


#<RDoc::Comment:0x007fde7ceacf38>


#<RDoc::Comment:0x007fde7f2ed258>


#<RDoc::Comment:0x007fde7f5e38b8>


#<RDoc::Comment:0x007fde7f817710>


#<RDoc::Comment:0x007fde7eeba320>


#<RDoc::Comment:0x007fde7edfd900>

TEST_ROOT = File.expand_path(File.dirname(__FILE__))
 
FIXTURES_ROOT = TEST_ROOT + "/fixtures"
 
SCHEMA_FILE = TEST_ROOT + "/schema.rb"
 
TIME = (ENV['BENCHMARK_TIME'] || 20).to_i
 
RECORDS = (ENV['BENCHMARK_RECORDS'] || TIME*1000).to_i
 
QUOTED_TYPE = ActiveRecord::Base.connection.quote_column_name('type')
 

Quote “type” if it's a reserved word for the current connection.

ASSETS_ROOT = TEST_ROOT + "/assets"
 
MIGRATIONS_ROOT = TEST_ROOT + "/migrations"
 
SCHEMA_ROOT = TEST_ROOT + "/schema"
 
DeveloperSalary = Struct.new(:amount)
 
TIMES = (ENV['N'] || 10_000).to_i
 
MissingSourceFile = LoadError
 
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
 
RUBY_ENGINE = 'ruby' unless defined?(RUBY_ENGINE)
 
ORIG_ARGV = ARGV.dup
 
ApplicationController = 10
 
Conflict = 2
 
MultipleConstantFile = 10
 
SiblingConstant = MultipleConstantFile * 2
 
Payment = Struct.new(:price)
 
Somewhere = Struct.new(:street, :city) do attr_accessor :name end
 
Invoice = Struct.new(:client) do delegate :street, :city, :name, :to => :client, :prefix => true delegate :street, :city, :name, :to => :client, :prefix => :customer end
 
Project = Struct.new(:description, :person) do delegate :name, :to => :person, :allow_nil => true delegate :to_f, :to => :description, :allow_nil => true end
 
Developer = Struct.new(:client) do delegate :name, :to => :client, :prefix => nil end
 
Tester = Struct.new(:client) do delegate :name, :to => :client, :prefix => false end
 
MTIME_FIXTURES_PATH = File.expand_path("../fixtures", __FILE__)
 
DEFAULT_APP_FILES = %w( .gitignore Gemfile Rakefile config.ru app/assets/javascripts app/assets/stylesheets app/assets/images app/controllers app/helpers app/mailers app/models app/views/layouts config/environments config/initializers config/locales db doc lib lib/tasks lib/assets log script/rails test/fixtures test/functional test/integration test/performance test/unit vendor vendor/assets vendor/plugins tmp/cache tmp/cache/assets )
 
ObjectHelper = Class.new
 
AnotherObjectHelperTest = Class.new
 
DEFAULT_PLUGIN_FILES = %w( .gitignore Gemfile Rakefile README.rdoc bukkits.gemspec MIT-LICENSE lib lib/bukkits.rb lib/tasks/bukkits_tasks.rake lib/bukkits/version.rb test/bukkits_test.rb test/test_helper.rb test/dummy )
 
RAILS_FRAMEWORK_ROOT = File.expand_path("#{File.dirname(__FILE__)}/../../..")
 

TODO: Remove setting this magic constant

RAILS_ISOLATED_ENGINE = true
 
FRAMEWORKS = %w( activesupport activemodel activerecord activeresource actionpack actionmailer railties )
 
Instance Public methods
acts_like?(duck)

A duck-type assistant method. For example, Active Support extends Date to define an acts_like_date? method, and extends Time to define acts_like_time?. As a result, we can do “x.acts_like?(:time)” and “x.acts_like?(:date)” to do duck-type-safe comparisons, since classes that we want to act like Time simply need to define an acts_like_time? method.

# File activesupport/lib/active_support/core_ext/object/acts_like.rb, line 7
def acts_like?(duck)
  respond_to? :"acts_like_#{duck}?"
end
blank?()

An object is blank if it's false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank.

This simplifies:

if address.nil? || address.empty?

…to:

if address.blank?
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 14
def blank?
  respond_to?(:empty?) ? empty? : !self
end
bundler?()

This is a predicate useful for the doc:guides task of applications.

# File railties/guides/rails_guides.rb, line 5
def bundler?
  # Note that rake sets the cwd to the one that contains the Rakefile
  # being executed.
  File.exists?('Gemfile')
end
create_fixtures(*table_names, &block)
# File railties/lib/rails/test_help.rb, line 45
def create_fixtures(*table_names, &block)
  Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block)
end
create_table(*args, &block)
# File activerecord/test/schema/schema.rb, line 14
def create_table(*args, &block)
  ActiveRecord::Base.connection.create_table(*args, &block)
  ActiveRecord::Base.connection.execute "SET GENERATOR #{args.first}_seq TO 10000"
end
current_adapter?(*types)
# File activerecord/test/cases/helper.rb, line 29
def current_adapter?(*types)
  types.any? do |type|
    ActiveRecord::ConnectionAdapters.const_defined?(type) &&
      ActiveRecord::Base.connection.is_a?(ActiveRecord::ConnectionAdapters.const_get(type))
  end
end
duplicable?()

Can you safely dup this object?

False for nil, false, true, symbols, numbers, class and module objects; true otherwise.

# File activesupport/lib/active_support/core_ext/object/duplicable.rb, line 24
def duplicable?
  true
end
except(adapter_names_to_exclude)
# File activerecord/test/schema/schema.rb, line 2
def except(adapter_names_to_exclude)
  unless [adapter_names_to_exclude].flatten.include?(adapter_name)
    yield
  end
end
html_safe?()
# File activesupport/lib/active_support/core_ext/string/output_safety.rb, line 76
def html_safe?
  false
end
in?(*args)

Returns true if this object is included in the argument(s). Argument must be any object which responds to #include? or optionally, multiple arguments can be passed in. Usage:

characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true

character = "Konata"
character.in?("Konata", "Kagami", "Tsukasa") # => true

This will throw an ArgumentError if a single argument is passed in and it doesn't respond to #include?.

# File activesupport/lib/active_support/core_ext/object/inclusion.rb, line 13
def in?(*args)
  if args.length > 1
    args.include? self
  else
    another_object = args.first
    if another_object.respond_to? :include?
      another_object.include? self
    else
      raise ArgumentError.new("The single parameter passed to #in? must respond to #include?")
    end
  end
end
in_memory_db?()
# File activerecord/test/cases/helper.rb, line 36
def in_memory_db?
  current_adapter?(:SQLiteAdapter) &&
  ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:"
end
instance_variable_names()
# File activesupport/lib/active_support/core_ext/object/instance_variables.rb, line 27
def instance_variable_names
  instance_variables.map { |var| var.to_s }
end
load_schema()
# File activerecord/test/cases/helper.rb, line 117
def load_schema
  # silence verbose schema loading
  original_stdout = $stdout
  $stdout = StringIO.new

  adapter_name = ActiveRecord::Base.connection.adapter_name.downcase
  adapter_specific_schema_file = SCHEMA_ROOT + "/#{adapter_name}_specific_schema.rb"

  load SCHEMA_ROOT + "/schema.rb"

  if File.exists?(adapter_specific_schema_file)
    load adapter_specific_schema_file
  end
ensure
  $stdout = original_stdout
end
options()
# File railties/lib/rails/commands/benchmarker.rb, line 8
def options
  options = {}
  defaults = ActiveSupport::Testing::Performance::DEFAULTS

  OptionParser.new do |opt|
    opt.banner = "Usage: rails benchmarker 'Ruby.code' 'Ruby.more_code' ... [OPTS]"
    opt.on('-r', '--runs N', Numeric, 'Number of runs.', "Default: #{defaults[:runs]}") { |r| options[:runs] = r }
    opt.on('-o', '--output PATH', String, 'Directory to use when writing the results.', "Default: #{defaults[:output]}") { |o| options[:output] = o }
    opt.on('-m', '--metrics a,b,c', Array, 'Metrics to use.', "Default: #{defaults[:metrics].join(",")}") { |m| options[:metrics] = m.map(&:to_sym) }
    opt.parse!(ARGV)
  end

  options
end
perform_schema_define!()
# File activerecord/test/cases/ar_schema_test.rb, line 52
def perform_schema_define!
  ActiveRecord::Schema.define(:version => 7) do
    create_table :fruits do |t|
      t.column :color, :string
      t.column :fruit_size, :string  # NOTE: "size" is reserved in Oracle
      t.column :texture, :string
      t.column :flavor, :string
    end
  end
end
presence()

Returns object if it's present? otherwise returns nil. object.presence is equivalent to object.present? ? object : nil.

This is handy for any representation of objects where blank is the same as not present at all. For example, this simplifies a common check for HTTP POST/query parameters:

state   = params[:state]   if params[:state].present?
country = params[:country] if params[:country].present?
region  = state || country || 'US'

…becomes:

region = params[:state].presence || params[:country].presence || 'US'
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 37
def presence
  self if present?
end
present?()

An object is present if it's not blank?.

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 19
def present?
  !blank?
end
restore_delivery_method()
# File actionmailer/test/abstract_unit.rb, line 77
def restore_delivery_method
  ActionMailer::Base.delivery_method = @old_delivery_method
end
run_all!(times, verbose)

ActionController::Base.use_accept_header = false

# File actionpack/examples/performance.rb, line 156
def run_all!(times, verbose)
  Runner.run(:overhead, times, verbose)
  Runner.run(:index,       times, verbose)
  Runner.run(:template_1,  times, verbose)
  Runner.run(:partial,     times, verbose)
  Runner.run(:partial_10,  times, verbose)
  Runner.run(:coll_10,     times, verbose)
  Runner.run(:partial_100, times, verbose)
  Runner.run(:coll_100,    times, verbose)
  Runner.run(:uniq_100,    times, verbose)
  Runner.run(:diff_100,    times, verbose)
end
set_delivery_method(method)
# File actionmailer/test/abstract_unit.rb, line 72
def set_delivery_method(method)
  @old_delivery_method = ActionMailer::Base.delivery_method
  ActionMailer::Base.delivery_method = method
end
setup_response()
# File activeresource/test/abstract_unit.rb, line 16
def setup_response
  matz_hash = { 'person' => { :id => 1, :name => 'Matz' } }

  @default_request_headers = { 'Content-Type' => 'application/json' }
  @matz  = matz_hash.to_json
  @matz_xml  = matz_hash.to_xml
  @david = { :person => { :id => 2, :name => 'David' } }.to_json
  @greg  = { :person => { :id => 3, :name => 'Greg' } }.to_json
  @addy  = { :address => { :id => 1, :street => '12345 Street', :country => 'Australia' } }.to_json
  @rick  = { :person => { :name => "Rick", :age => 25 } }.to_json
  @joe    = { :person => { :id => 6, :name => 'Joe', :likes_hats => true }}.to_json
  @people = { :people => [ { :person => { :id => 1, :name => 'Matz' } }, { :person => { :id => 2, :name => 'David' } }] }.to_json
  @people_david = { :people => [ { :person => { :id => 2, :name => 'David' } }] }.to_json
  @addresses = { :addresses => [{ :address => { :id => 1, :street => '12345 Street', :country => 'Australia' } }] }.to_json

  # - deep nested resource -
  # - Luis (Customer)
  #   - JK (Customer::Friend)
  #     - Mateo (Customer::Friend::Brother)
  #       - Edith (Customer::Friend::Brother::Child)
  #       - Martha (Customer::Friend::Brother::Child)
  #     - Felipe (Customer::Friend::Brother)
  #       - Bryan (Customer::Friend::Brother::Child)
  #       - Luke (Customer::Friend::Brother::Child)
  #   - Eduardo (Customer::Friend)
  #     - Sebas (Customer::Friend::Brother)
  #       - Andres (Customer::Friend::Brother::Child)
  #       - Jorge (Customer::Friend::Brother::Child)
  #     - Elsa (Customer::Friend::Brother)
  #       - Natacha (Customer::Friend::Brother::Child)
  #     - Milena (Customer::Friend::Brother)
  #
  @luis = {
    :customer => {
      :id => 1,
      :name => 'Luis',
      :friends => [{
        :name => 'JK',
        :brothers => [
          {
            :name => 'Mateo',
            :children => [{ :name => 'Edith' },{ :name => 'Martha' }]
          }, {
            :name => 'Felipe',
            :children => [{ :name => 'Bryan' },{ :name => 'Luke' }]
          }
        ]
      }, {
        :name => 'Eduardo',
        :brothers => [
          {
            :name => 'Sebas',
            :children => [{ :name => 'Andres' },{ :name => 'Jorge' }]
          }, {
            :name => 'Elsa',
            :children => [{ :name => 'Natacha' }]
          }, {
            :name => 'Milena',
            :children => []
          }
        ]
      }]
    }
  }.to_json

  @startup_sound = {
    :sound => {
      :name => "Mac Startup Sound", :author => { :name => "Jim Reekes" }
    }
  }.to_json

  ActiveResource::HttpMock.respond_to do |mock|
    mock.get    "/people/1.json",               {}, @matz
    mock.get    "/people/1.xml",                {}, @matz_xml
    mock.get    "/people/2.xml",                {}, @david
    mock.get    "/people/Greg.json",            {}, @greg
    mock.get    "/people/6.json",               {}, @joe
    mock.get    "/people/4.json",               { 'key' => 'value' }, nil, 404
    mock.put    "/people/1.json",               {}, nil, 204
    mock.delete "/people/1.json",               {}, nil, 200
    mock.delete "/people/2.xml",                {}, nil, 400
    mock.get    "/people/99.json",              {}, nil, 404
    mock.post   "/people.json",                 {}, @rick, 201, 'Location' => '/people/5.xml'
    mock.get    "/people.json",                 {}, @people
    mock.get    "/people/1/addresses.json",     {}, @addresses
    mock.get    "/people/1/addresses/1.json",   {}, @addy
    mock.get    "/people/1/addresses/2.xml",    {}, nil, 404
    mock.get    "/people/2/addresses.json",     {}, nil, 404
    mock.get    "/people/2/addresses/1.xml",    {}, nil, 404
    mock.get    "/people/Greg/addresses/1.json", {}, @addy
    mock.put    "/people/1/addresses/1.json",   {}, nil, 204
    mock.delete "/people/1/addresses/1.json",   {}, nil, 200
    mock.post   "/people/1/addresses.json",     {}, nil, 201, 'Location' => '/people/1/addresses/5'
    mock.get    "/people/1/addresses/99.json",  {}, nil, 404
    mock.get    "/people//addresses.xml",       {}, nil, 404
    mock.get    "/people//addresses/1.xml",     {}, nil, 404
    mock.put    "/people//addresses/1.xml",     {}, nil, 404
    mock.delete "/people//addresses/1.xml",     {}, nil, 404
    mock.post   "/people//addresses.xml",       {}, nil, 404
    mock.head   "/people/1.json",               {}, nil, 200
    mock.head   "/people/Greg.json",            {}, nil, 200
    mock.head   "/people/99.json",              {}, nil, 404
    mock.head   "/people/1/addresses/1.json",   {}, nil, 200
    mock.head   "/people/1/addresses/2.json",   {}, nil, 404
    mock.head   "/people/2/addresses/1.json",    {}, nil, 404
    mock.head   "/people/Greg/addresses/1.json", {}, nil, 200
    # customer
    mock.get    "/customers/1.json",             {}, @luis
    # sound
    mock.get    "/sounds/1.json",                {}, @startup_sound
  end

  Person.user = nil
  Person.password = nil
end
supports_savepoints?()
# File activerecord/test/cases/helper.rb, line 41
def supports_savepoints?
  ActiveRecord::Base.connection.supports_savepoints?
end
switch_to_alt_inheritance_column()
# File activerecord/test/cases/inheritance_test.rb, line 245
def switch_to_alt_inheritance_column
  # we don't want misleading test results, so get rid of the values in the type column
  Company.find(:all, :order => 'id').each do |c|
    c['type'] = nil
    c.save
  end
  [ Company, Firm, Client].each { |klass| klass.reset_column_information }
  Company.inheritance_column = 'ruby_type'
end
switch_to_default_inheritance_column()
# File activerecord/test/cases/inheritance_test.rb, line 254
def switch_to_default_inheritance_column
  [ Company, Firm, Client].each { |klass| klass.reset_column_information }
  Company.inheritance_column = 'type'
end
test_a_bad_type_column()
# File activerecord/test/cases/inheritance_test.rb, line 75
def test_a_bad_type_column
  #SQLServer need to turn Identity Insert On before manually inserting into the Identity column
  if current_adapter?(:SybaseAdapter)
    Company.connection.execute "SET IDENTITY_INSERT companies ON"
  end
  Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')"

  #We then need to turn it back Off before continuing.
  if current_adapter?(:SybaseAdapter)
    Company.connection.execute "SET IDENTITY_INSERT companies OFF"
  end
  assert_raise(ActiveRecord::SubclassNotFound) { Company.find(100) }
end
test_alt_becomes_works_with_sti()
# File activerecord/test/cases/inheritance_test.rb, line 102
def test_alt_becomes_works_with_sti
  vegetable = Vegetable.find(1)
  assert_kind_of Vegetable, vegetable
  cabbage = vegetable.becomes(Cabbage)
  assert_kind_of Cabbage, cabbage
end
test_alt_complex_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 206
def test_alt_complex_inheritance
  switch_to_alt_inheritance_column
  test_complex_inheritance
  switch_to_default_inheritance_column
end
test_alt_destroy_all_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 178
def test_alt_destroy_all_within_inheritance
  switch_to_alt_inheritance_column
  test_destroy_all_within_inheritance
  switch_to_default_inheritance_column
end
test_alt_eager_loading()
# File activerecord/test/cases/inheritance_test.rb, line 224
def test_alt_eager_loading
  switch_to_alt_inheritance_column
  test_eager_load_belongs_to_something_inherited
  switch_to_default_inheritance_column
end
test_alt_find_first_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 190
def test_alt_find_first_within_inheritance
  switch_to_alt_inheritance_column
  test_find_first_within_inheritance
  switch_to_default_inheritance_column
end
test_alt_finding_incorrect_type_data()
# File activerecord/test/cases/inheritance_test.rb, line 153
def test_alt_finding_incorrect_type_data
  switch_to_alt_inheritance_column
  test_finding_incorrect_type_data
  switch_to_default_inheritance_column
end
test_alt_inheritance_condition()
# File activerecord/test/cases/inheritance_test.rb, line 142
def test_alt_inheritance_condition
  switch_to_alt_inheritance_column
  test_inheritance_condition
  switch_to_default_inheritance_column
end
test_alt_inheritance_find()
# File activerecord/test/cases/inheritance_test.rb, line 96
def test_alt_inheritance_find
  switch_to_alt_inheritance_column
  test_inheritance_find
  switch_to_default_inheritance_column
end
test_alt_inheritance_find_all()
# File activerecord/test/cases/inheritance_test.rb, line 115
def test_alt_inheritance_find_all
  switch_to_alt_inheritance_column
  test_inheritance_find_all
  switch_to_default_inheritance_column
end
test_alt_inheritance_save()
# File activerecord/test/cases/inheritance_test.rb, line 130
def test_alt_inheritance_save
  switch_to_alt_inheritance_column
  test_inheritance_save
  switch_to_default_inheritance_column
end
test_alt_update_all_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 166
def test_alt_update_all_within_inheritance
  switch_to_alt_inheritance_column
  test_update_all_within_inheritance
  switch_to_default_inheritance_column
end
test_class_without_store_full_sti_class_returns_demodulized_name()
# File activerecord/test/cases/inheritance_test.rb, line 32
def test_class_without_store_full_sti_class_returns_demodulized_name
  old = ActiveRecord::Base.store_full_sti_class
  ActiveRecord::Base.store_full_sti_class = false
  assert_equal 'Company', Namespaced::Company.sti_name
ensure
  ActiveRecord::Base.store_full_sti_class = old
end
test_company_descends_from_active_record()
# File activerecord/test/cases/inheritance_test.rb, line 68
def test_company_descends_from_active_record
  assert_raise(NoMethodError) { ActiveRecord::Base.descends_from_active_record? }
  assert AbstractCompany.descends_from_active_record?, 'AbstractCompany should descend from ActiveRecord::Base'
  assert Company.descends_from_active_record?, 'Company should descend from ActiveRecord::Base'
  assert !Class.new(Company).descends_from_active_record?, 'Company subclass should not descend from ActiveRecord::Base'
end
test_complex_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 196
def test_complex_inheritance
  very_special_client = VerySpecialClient.create("name" => "veryspecial")
  assert_equal very_special_client, VerySpecialClient.where("name = 'veryspecial'").first
  assert_equal very_special_client, SpecialClient.find(:first, :conditions => "name = 'veryspecial'")
  assert_equal very_special_client, Company.find(:first, :conditions => "name = 'veryspecial'")
  assert_equal very_special_client, Client.find(:first, :conditions => "name = 'veryspecial'")
  assert_equal 1, Client.find(:all, :conditions => "name = 'Summit'").size
  assert_equal very_special_client, Client.find(very_special_client.id)
end
test_destroy_all_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 172
def test_destroy_all_within_inheritance
  Client.destroy_all
  assert_equal 0, Client.count
  assert_equal 2, Firm.count
end
test_different_namespace_subclass_should_load_correctly_with_store_full_sti_class_option()
# File activerecord/test/cases/inheritance_test.rb, line 58
def test_different_namespace_subclass_should_load_correctly_with_store_full_sti_class_option
  old = ActiveRecord::Base.store_full_sti_class
  ActiveRecord::Base.store_full_sti_class = true
  item = Namespaced::Company.create :name => "Wolverine 2"
  assert_not_nil Company.find(item.id)
  assert_not_nil Namespaced::Company.find(item.id)
ensure
  ActiveRecord::Base.store_full_sti_class = old
end
test_eager_load_belongs_to_primary_key_quoting()
# File activerecord/test/cases/inheritance_test.rb, line 217
def test_eager_load_belongs_to_primary_key_quoting
  con = Account.connection
  assert_sql(/#{con.quote_table_name('companies')}.#{con.quote_column_name('id')} IN \(1\)/) do
    Account.find(1, :include => :firm)
  end
end
test_eager_load_belongs_to_something_inherited()
# File activerecord/test/cases/inheritance_test.rb, line 212
def test_eager_load_belongs_to_something_inherited
  account = Account.find(1, :include => :firm)
  assert account.association_cache.key?(:firm), "nil proves eager load failed"
end
test_find_first_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 184
def test_find_first_within_inheritance
  assert_kind_of Firm, Company.find(:first, :conditions => "name = '37signals'")
  assert_kind_of Firm, Firm.find(:first, :conditions => "name = '37signals'")
  assert_nil Client.find(:first, :conditions => "name = '37signals'")
end
test_finding_incorrect_type_data()
# File activerecord/test/cases/inheritance_test.rb, line 148
def test_finding_incorrect_type_data
  assert_raise(ActiveRecord::RecordNotFound) { Firm.find(2) }
  assert_nothing_raised   { Firm.find(1) }
end
test_homepage()

:output => 'tmp/performance', :formats => [:flat] }

# File railties/lib/rails/generators/test_unit/performance/templates/performance_test.rb, line 9
def test_homepage
  get '/'
end
test_inheritance_condition()
# File activerecord/test/cases/inheritance_test.rb, line 136
def test_inheritance_condition
  assert_equal 10, Company.count
  assert_equal 2, Firm.count
  assert_equal 4, Client.count
end
test_inheritance_find()
# File activerecord/test/cases/inheritance_test.rb, line 89
def test_inheritance_find
  assert_kind_of Firm, Company.find(1), "37signals should be a firm"
  assert_kind_of Firm, Firm.find(1), "37signals should be a firm"
  assert_kind_of Client, Company.find(2), "Summit should be a client"
  assert_kind_of Client, Client.find(2), "Summit should be a client"
end
test_inheritance_find_all()
# File activerecord/test/cases/inheritance_test.rb, line 109
def test_inheritance_find_all
  companies = Company.find(:all, :order => 'id')
  assert_kind_of Firm, companies[0], "37signals should be a firm"
  assert_kind_of Client, companies[1], "Summit should be a client"
end
test_inheritance_save()
# File activerecord/test/cases/inheritance_test.rb, line 121
def test_inheritance_save
  firm = Firm.new
  firm.name = "Next Angle"
  firm.save

  next_angle = Company.find(firm.id)
  assert_kind_of Firm, next_angle, "Next Angle should be a firm"
end
test_inheritance_without_mapping()
# File activerecord/test/cases/inheritance_test.rb, line 234
def test_inheritance_without_mapping
  assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
  assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save }
end
test_inherits_custom_primary_key()
# File activerecord/test/cases/inheritance_test.rb, line 230
def test_inherits_custom_primary_key
  assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key
end
test_scope_inherited_properly()
# File activerecord/test/cases/inheritance_test.rb, line 239
def test_scope_inherited_properly
  assert_nothing_raised { Company.of_first_firm }
  assert_nothing_raised { Client.of_first_firm }
end
test_should_store_demodulized_class_name_with_store_full_sti_class_option_disabled()
# File activerecord/test/cases/inheritance_test.rb, line 40
def test_should_store_demodulized_class_name_with_store_full_sti_class_option_disabled
  old = ActiveRecord::Base.store_full_sti_class
  ActiveRecord::Base.store_full_sti_class = false
  item = Namespaced::Company.new
  assert_equal 'Company', item[:type]
ensure
  ActiveRecord::Base.store_full_sti_class = old
end
test_should_store_full_class_name_with_store_full_sti_class_option_enabled()
# File activerecord/test/cases/inheritance_test.rb, line 49
def test_should_store_full_class_name_with_store_full_sti_class_option_enabled
  old = ActiveRecord::Base.store_full_sti_class
  ActiveRecord::Base.store_full_sti_class = true
  item = Namespaced::Company.new
  assert_equal 'Namespaced::Company', item[:type]
ensure
  ActiveRecord::Base.store_full_sti_class = old
end
test_update_all_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 159
def test_update_all_within_inheritance
  Client.update_all "name = 'I am a client'"
  assert_equal "I am a client", Client.find(:all).first.name
  # Order by added as otherwise Oracle tests were failing because of different order of results
  assert_equal "37signals", Firm.find(:all, :order => "id").first.name
end
to_json(options = nil)

Dumps object in JSON (JavaScript Object Notation). See www.json.org for more info.

# File activesupport/lib/active_support/core_ext/object/to_json.rb, line 15
def to_json(options = nil)
  ActiveSupport::JSON.encode(self, options)
end
to_param()

Alias of to_s.

# File activesupport/lib/active_support/core_ext/object/to_param.rb, line 3
def to_param
  to_s
end
to_query(key)

Converts an object into a string suitable for use as a URL query string, using the given key as the param name.

Note: This method is defined as a default implementation for all Objects for Hash#to_query to work.

# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 8
def to_query(key)
  require 'cgi' unless defined?(CGI) && defined?(CGI::escape)
  "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
end
try(*a, &b)

Invokes the method identified by the symbol method, passing it any arguments and/or the block specified, just like the regular Ruby Object#send does.

Unlike that method however, a NoMethodError exception will not be raised and nil will be returned instead, if the receiving object is a nil object or NilClass.

If try is called without a method to call, it will yield any given block with the object.

Please also note that try is defined on Object, therefore it won't work with subclasses of BasicObject. For example, using try with SimpleDelegator will delegate try to target instead of calling it on delegator itself.

Examples

Without try

@person && @person.name

or

@person ? @person.name : nil

With try

@person.try(:name)

try also accepts arguments and/or a block, for the method it is trying

Person.try(:find, 1)
@people.try(:collect) {|p| p.name}

Without a method argument try will yield to the block unless the receiver is nil.

@person.try { |p| "#{p.first_name} #{p.last_name}" }
# File activesupport/lib/active_support/core_ext/object/try.rb, line 32
def try(*a, &b)
  if a.empty? && block_given?
    yield self
  else
    __send__(*a, &b)
  end
end
unescape(str, escaped = /%[a-fA-F\d]{2}/)
# File activesupport/lib/active_support/core_ext/uri.rb, line 12
def unescape(str, escaped = /%[a-fA-F\d]{2}/)
  # TODO: Are we actually sure that ASCII == UTF-8?
  # YK: My initial experiments say yes, but let's be sure please
  enc = str.encoding
  enc = Encoding::UTF_8 if enc == Encoding::US_ASCII
  str.gsub(escaped) { [$&[1, 2].hex].pack('C') }.force_encoding(enc)
end
uses_memcached(test_name)
# File activesupport/test/abstract_unit.rb, line 36
def uses_memcached(test_name)
  require 'memcache'
  begin
    MemCache.new('localhost:11211').stats
    yield
  rescue MemCache::MemCacheError
    $stderr.puts "Skipping #{test_name} tests. Start memcached and try again."
  end
end
with_active_record_default_timezone(zone)
# File activerecord/test/cases/helper.rb, line 52
def with_active_record_default_timezone(zone)
  old_zone, ActiveRecord::Base.default_timezone = ActiveRecord::Base.default_timezone, zone
  yield
ensure
  ActiveRecord::Base.default_timezone = old_zone
end
with_env_tz(new_tz = 'US/Eastern')
# File activerecord/test/cases/helper.rb, line 45
def with_env_tz(new_tz = 'US/Eastern')
  old_tz, ENV['TZ'] = ENV['TZ'], new_tz
  yield
ensure
  old_tz ? ENV['TZ'] = old_tz : ENV.delete('TZ')
end
with_kcode(code)
# File activesupport/test/abstract_unit.rb, line 46
def with_kcode(code)
  if RUBY_VERSION < '1.9'
    begin
      old_kcode, $KCODE = $KCODE, code
      yield
    ensure
      $KCODE = old_kcode
    end
  else
    yield
  end
end
with_options(options)

An elegant way to factor duplication out of options passed to a series of method calls. Each method called in the block, with the block variable as the receiver, will have its options merged with the default options hash provided. Each method called on the block variable must take an options hash as its final argument.

Without with_options>, this code contains duplication:

class Account < ActiveRecord::Base
  has_many :customers, :dependent => :destroy
  has_many :products,  :dependent => :destroy
  has_many :invoices,  :dependent => :destroy
  has_many :expenses,  :dependent => :destroy
end

Using with_options, we can remove the duplication:

class Account < ActiveRecord::Base
  with_options :dependent => :destroy do |assoc|
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end

It can also be used with an explicit receiver:

I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
  subject i18n.t :subject
  body    i18n.t :body, :user_name => user.name
end

with_options can also be nested since the call is forwarded to its receiver. Each nesting level will merge inherited defaults in addition to their own.

# File activesupport/lib/active_support/core_ext/object/with_options.rb, line 40
def with_options(options)
  yield ActiveSupport::OptionMerger.new(self, options)
end