Namespace
Methods
A
B
C
D
E
H
I
J
L
M
O
P
R
S
T
U
V
W
Included Modules
Constants
FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__))
 
AppRoutes = ActionDispatch::Routing::RouteSet.new
 
PROCESS_COUNT = (ENV['N'] || 4).to_i
 
ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort
 
FIXTURES = Pathname.new(FIXTURE_LOAD_PATH)
 
SharedTestRoutes = ActionDispatch::Routing::RouteSet.new
 
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:0x007fc7871c5c18>


#<RDoc::Comment:0x007fc7853cd238>


#<RDoc::Comment:0x007fc787259e68>


#<RDoc::Comment:0x007fc784eba278>


#<RDoc::Comment:0x007fc785d2b258>


#<RDoc::Comment:0x007fc782d1bd38>


#<RDoc::Comment:0x007fc787003470>


#<RDoc::Comment:0x007fc787e2d190>


#<RDoc::Comment:0x007fc787d59908>

PATH_TO_AR = "#{File.dirname(__FILE__)}/../../activerecord/lib"
 
Neckbeard = lambda {|template| template.source }
 
Bowtie = lambda {|template| template.source }
 
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.

EXPECTED_ZONE = nil
 

This method makes sure that tests don't leak global state related to time zones.

EXPECTED_DEFAULT_TIMEZONE = :utc
 
EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES = false
 
ASSETS_ROOT = TEST_ROOT + "/assets"
 
MIGRATIONS_ROOT = TEST_ROOT + "/migrations"
 
SCHEMA_ROOT = TEST_ROOT + "/schema"
 
MissingSourceFile = LoadError
 
HashWithIndifferentAccess = ActiveSupport::HashWithIndifferentAccess
 

Implements a hash where keys :foo and "foo" are considered to be the same.

rgb = ActiveSupport::HashWithIndifferentAccess.new

rgb[:black] = '#000000'
rgb[:black]  # => '#000000'
rgb['black'] # => '#000000'

rgb['white'] = '#FFFFFF'
rgb[:white]  # => '#FFFFFF'
rgb['white'] # => '#FFFFFF'

Internally symbols are mapped to strings when used as keys in the entire writing interface (calling []=, merge, etc). This mapping belongs to the public interface. For example, given:

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)

You are guaranteed that the key is returned as a string:

hash.keys # => ["a"]

Technically other types of keys are accepted:

hash = ActiveSupport::HashWithIndifferentAccess.new(a: 1)
hash[0] = 0
hash # => {"a"=>1, 0=>0}

but this class is intended for use cases where strings or symbols are the expected keys and it is convenient to understand both as the same. For example the params hash in Ruby on Rails.

Note that core extensions define Hash#with_indifferent_access:

rgb = { black: '#000000', white: '#FFFFFF' }.with_indifferent_access

which may be handy.

ORIG_ARGV = ARGV.dup
 
ApplicationController = 10
 
Conflict = 2
 
MultipleConstantFile = 10
 
SiblingConstant = MultipleConstantFile * 2
 
ShouldNotBeAutoloaded = 0
 
TypO = 1
 
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
 
Event = Struct.new(:case) do delegate :foo, :to => :case end
 
Tester = Struct.new(:client) do delegate :name, :to => :client, :prefix => false def foo; 1; end end
 
Product = Struct.new(:name) do delegate :name, :to => :manufacturer, :prefix => true delegate :name, :to => :type, :prefix => true def manufacturer @manufacturer ||= begin nil.unknown_method end end def type @type ||= begin nil.type_name end end end
 
MTIME_FIXTURES_PATH = File.expand_path("../fixtures", __FILE__)
 
DEFAULT_APP_FILES = %w( .gitignore README.rdoc Gemfile Rakefile config.ru app/assets/javascripts app/assets/stylesheets app/assets/images app/controllers app/controllers/concerns app/helpers app/mailers app/models app/models/concerns app/views/layouts bin/bundle bin/rails bin/rake bin/setup config/environments config/initializers config/locales db lib lib/tasks lib/assets log test/test_helper.rb test/fixtures test/controllers test/models test/helpers test/mailers test/integration vendor vendor/assets vendor/assets/stylesheets vendor/assets/javascripts 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__)}/../../..")
 
RAILS_ISOLATED_ENGINE = true
 
FRAMEWORKS = %w( activesupport activemodel activerecord actionview actionpack activejob actionmailer railties )
 
Class Public methods
enqueue(job_class, args=[], opts={})
Also aliased as: original_enqueue, original_enqueue
# File activejob/test/support/backburner/inline.rb, line 5
def self.enqueue(job_class, args=[], opts={})
  job_class.perform(*args)
end
original_enqueue(job_class, args=[], opts={})
Alias for: enqueue
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
attribute(name)
# File activemodel/test/cases/attribute_methods_test.rb, line 87
def attribute(name)
  attributes[name.to_sym]
end
blank?()

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

This simplifies

!address || address.empty?

to

address.blank?

@return [true, false]

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

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

# File guides/rails_guides.rb, line 5
def bundler?
  # Note that rake sets the cwd to the one that contains the Rakefile
  # being executed.
  File.exist?('Gemfile')
end
create_fixtures(*fixture_set_names, &block)
# File railties/lib/rails/test_help.rb, line 28
def create_fixtures(*fixture_set_names, &block)
  FixtureSet.create_fixtures(ActiveSupport::TestCase.fixture_path, fixture_set_names, {}, &block)
end
current_adapter?(*types)
# File activerecord/test/cases/helper.rb, line 36
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
deep_dup()

Returns a deep copy of object if it's duplicable. If it's not duplicable, returns self.

object = Object.new
dup    = object.deep_dup
dup.instance_variable_set(:@a, 1)

object.instance_variable_defined?(:@a) # => false
dup.instance_variable_defined?(:@a)    # => true
# File activesupport/lib/active_support/core_ext/object/deep_dup.rb, line 13
def deep_dup
  duplicable? ? dup : self
end
disable_extension!(extension, connection)
# File activerecord/test/cases/helper.rb, line 132
def disable_extension!(extension, connection)
  return false unless connection.supports_extensions?
  return true unless connection.extension_enabled?(extension)

  connection.disable_extension extension
  connection.reconnect!
end
duplicable?()

Can you safely dup this object?

False for nil, false, true, symbol, number and BigDecimal(in 1.9.x) objects; true otherwise.

# File activesupport/lib/active_support/core_ext/object/duplicable.rb, line 24
def duplicable?
  true
end
enable_extension!(extension, connection)
# File activerecord/test/cases/helper.rb, line 123
def enable_extension!(extension, connection)
  return false unless connection.supports_extensions?
  return connection.reconnect! if connection.extension_enabled?(extension)

  connection.enable_extension extension
  connection.commit_db_transaction
  connection.reconnect!
end
except(adapter_names_to_exclude)
# File activerecord/test/schema/schema.rb, line 3
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 120
def html_safe?
  false
end
in?(another_object)

Returns true if this object is included in the argument. Argument must be any object which responds to #include?. Usage:

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

This will throw an ArgumentError if the argument doesn't respond to #include?.

# File activesupport/lib/active_support/core_ext/object/inclusion.rb, line 10
def in?(another_object)
  another_object.include?(self)
rescue NoMethodError
  raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end
in_memory_db?()
# File activerecord/test/cases/helper.rb, line 43
def in_memory_db?
  current_adapter?(:SQLite3Adapter) &&
  ActiveRecord::Base.connection_pool.spec.config[:database] == ":memory:"
end
instance_values()

Returns a hash with string keys that maps instance variable names without “@” to their corresponding values.

class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
# File activesupport/lib/active_support/core_ext/object/instance_variables.rb, line 12
def instance_values
  Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
end
instance_variable_names()

Returns an array of instance variable names as strings including “@”.

class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_variable_names # => ["@y", "@x"]
# File activesupport/lib/active_support/core_ext/object/instance_variables.rb, line 25
def instance_variable_names
  instance_variables.map { |var| var.to_s }
end
itself()

Returns the object itself.

Useful for chaining methods, such as Active Record scopes:

Event.public_send(state.presence_in([ :trashed, :drafted ]) || :itself).order(:created_at)

@return Object

# File activesupport/lib/active_support/core_ext/object/itself.rb, line 11
def itself
  self
end
jruby_skip(message = '')

Skips the current run on JRuby using Minitest::Assertions#skip

# File actionmailer/test/abstract_unit.rb, line 40
def jruby_skip(message = '')
  skip message if defined?(JRUBY_VERSION)
end
load_schema()
# File activerecord/test/cases/helper.rb, line 154
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.exist?(adapter_specific_schema_file)
    load adapter_specific_schema_file
  end
ensure
  $stdout = original_stdout
end
mysql_56?()
# File activerecord/test/cases/helper.rb, line 48
def mysql_56?
  current_adapter?(:MysqlAdapter, :Mysql2Adapter) &&
    ActiveRecord::Base.connection.send(:version) >= '5.6.0' &&
    ActiveRecord::Base.connection.send(:version) < '5.7.0'
end
mysql_enforcing_gtid_consistency?()
# File activerecord/test/cases/helper.rb, line 54
def mysql_enforcing_gtid_consistency?
  current_adapter?(:MysqlAdapter, :Mysql2Adapter) && 'ON' == ActiveRecord::Base.connection.show_variable('enforce_gtid_consistency')
end
presence()

Returns the receiver if it's present otherwise returns nil. object.presence is equivalent to

object.present? ? object : nil

For example, something like

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'

@return [Object]

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 42
def presence
  self if present?
end
presence_in(another_object)

Returns the receiver if it's included in the argument otherwise returns nil. Argument must be any object which responds to #include?. Usage:

params[:bucket_type].presence_in %w( project calendar )

This will throw an ArgumentError if the argument doesn't respond to #include?.

@return [Object]

# File activesupport/lib/active_support/core_ext/object/inclusion.rb, line 24
def presence_in(another_object)
  self.in?(another_object) ? self : nil
end
present?()

An object is present if it's not blank.

@return [true, false]

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 22
def present?
  !blank?
end
progress_bar(int)
# File activerecord/examples/performance.rb, line 46
def progress_bar(int); print "." if (int%100).zero? ; end
rubinius_skip(message = '')

Skips the current run on Rubinius using Minitest::Assertions#skip

# File actionmailer/test/abstract_unit.rb, line 36
def rubinius_skip(message = '')
  skip message if RUBY_ENGINE == 'rbx'
end
ruby_193?()
# File activejob/test/helper.rb, line 14
def ruby_193?
  RUBY_VERSION == '1.9.3' && RUBY_ENGINE != 'java'
end
sidekiq?()
# File activejob/test/helper.rb, line 10
def sidekiq?
  @adapter == 'sidekiq'
end
supports_savepoints?()
# File activerecord/test/cases/helper.rb, line 58
def supports_savepoints?
  ActiveRecord::Base.connection.supports_savepoints?
end
test_a_bad_type_column()
# File activerecord/test/cases/inheritance_test.rb, line 97
def test_a_bad_type_column
  Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')"

  assert_raise(ActiveRecord::SubclassNotFound) { Company.find(100) }
end
test_abstract_inheritance_base_class()
# File activerecord/test/cases/inheritance_test.rb, line 85
def test_abstract_inheritance_base_class
  assert_equal LoosePerson, LoosePerson.base_class
  assert_equal LooseDescendant, LooseDescendant.base_class
  assert_equal TightPerson, TightPerson.base_class
  assert_equal TightPerson, TightDescendant.base_class
end
test_alt_becomes_bang_resets_inheritance_type_column()
# File activerecord/test/cases/inheritance_test.rb, line 130
def test_alt_becomes_bang_resets_inheritance_type_column
  vegetable = Vegetable.create!(name: "Red Pepper")
  assert_nil vegetable.custom_type

  cabbage = vegetable.becomes!(Cabbage)
  assert_equal "Cabbage", cabbage.custom_type

  vegetable = cabbage.becomes!(Vegetable)
  assert_nil cabbage.custom_type
end
test_alt_becomes_works_with_sti()
# File activerecord/test/cases/inheritance_test.rb, line 117
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 291
def test_alt_complex_inheritance
  king_cole = KingCole.create("name" => "uniform heads")
  assert_equal king_cole, KingCole.where("name = 'uniform heads'").first
  assert_equal king_cole, GreenCabbage.all.merge!(:where => "name = 'uniform heads'").first
  assert_equal king_cole, Cabbage.all.merge!(:where => "name = 'uniform heads'").first
  assert_equal king_cole, Vegetable.all.merge!(:where => "name = 'uniform heads'").first
  assert_equal 1, Cabbage.all.merge!(:where => "name = 'his cabbage'").to_a.size
  assert_equal king_cole, Cabbage.find(king_cole.id)
end
test_alt_destroy_all_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 263
def test_alt_destroy_all_within_inheritance
  Cabbage.destroy_all
  assert_equal 0, Cabbage.count
  assert_equal 1, Cucumber.count
end
test_alt_eager_loading()
# File activerecord/test/cases/inheritance_test.rb, line 306
def test_alt_eager_loading
  cabbage = RedCabbage.all.merge!(:includes => :seller).find(4)
  assert cabbage.association(:seller).loaded?, "association was not eager loaded"
end
test_alt_find_first_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 275
def test_alt_find_first_within_inheritance
  assert_kind_of Cabbage, Vegetable.all.merge!(:where => "name = 'his cabbage'").first
  assert_kind_of Cabbage, Cabbage.all.merge!(:where => "name = 'his cabbage'").first
  assert_nil Cucumber.all.merge!(:where => "name = 'his cabbage'").first
end
test_alt_finding_incorrect_type_data()
# File activerecord/test/cases/inheritance_test.rb, line 239
def test_alt_finding_incorrect_type_data
  assert_raise(ActiveRecord::RecordNotFound) { Cucumber.find(2) }
  assert_nothing_raised   { Cucumber.find(1) }
end
test_alt_inheritance_condition()
# File activerecord/test/cases/inheritance_test.rb, line 228
def test_alt_inheritance_condition
  assert_equal 4, Vegetable.count
  assert_equal 1, Cucumber.count
  assert_equal 3, Cabbage.count
end
test_alt_inheritance_find()
# File activerecord/test/cases/inheritance_test.rb, line 110
def test_alt_inheritance_find
  assert_kind_of Cucumber, Vegetable.find(1)
  assert_kind_of Cucumber, Cucumber.find(1)
  assert_kind_of Cabbage, Vegetable.find(2)
  assert_kind_of Cabbage, Cabbage.find(2)
end
test_alt_inheritance_find_all()
# File activerecord/test/cases/inheritance_test.rb, line 147
def test_alt_inheritance_find_all
  companies = Vegetable.all.merge!(:order => 'id').to_a
  assert_kind_of Cucumber, companies[0]
  assert_kind_of Cabbage, companies[1]
end
test_alt_inheritance_save()
# File activerecord/test/cases/inheritance_test.rb, line 162
def test_alt_inheritance_save
  cabbage = Cabbage.new(:name => 'Savoy')
  cabbage.save!

  savoy = Vegetable.find(cabbage.id)
  assert_kind_of Cabbage, savoy
end
test_alt_update_all_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 251
def test_alt_update_all_within_inheritance
  Cabbage.update_all "name = 'the cabbage'"
  assert_equal "the cabbage", Cabbage.first.name
  assert_equal ["my cucumber"], Cucumber.all.map(&:name).uniq
end
test_base_class_activerecord_error()
# File activerecord/test/cases/inheritance_test.rb, line 92
def test_base_class_activerecord_error
  klass = Class.new { include ActiveRecord::Inheritance }
  assert_raise(ActiveRecord::ActiveRecordError) { klass.base_class }
end
test_becomes_and_change_tracking_for_inheritance_columns()
# File activerecord/test/cases/inheritance_test.rb, line 124
def test_becomes_and_change_tracking_for_inheritance_columns
  cucumber = Vegetable.find(1)
  cabbage = cucumber.becomes!(Cabbage)
  assert_equal ['Cucumber', 'Cabbage'], cabbage.custom_type_change
end
test_class_without_store_full_sti_class_returns_demodulized_name()
# File activerecord/test/cases/inheritance_test.rb, line 35
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 71
def test_company_descends_from_active_record
  assert !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 281
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.all.merge!(:where => "name = 'veryspecial'").first
  assert_equal very_special_client, Company.all.merge!(:where => "name = 'veryspecial'").first
  assert_equal very_special_client, Client.all.merge!(:where => "name = 'veryspecial'").first
  assert_equal 1, Client.all.merge!(:where => "name = 'Summit'").to_a.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 257
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 61
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 311
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.all.merge!(:includes => :firm).find(1)
  end
end
test_eager_load_belongs_to_something_inherited()
# File activerecord/test/cases/inheritance_test.rb, line 301
def test_eager_load_belongs_to_something_inherited
  account = Account.all.merge!(:includes => :firm).find(1)
  assert account.association(:firm).loaded?, "association was not eager loaded"
end
test_find_first_within_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 269
def test_find_first_within_inheritance
  assert_kind_of Firm, Company.all.merge!(:where => "name = '37signals'").first
  assert_kind_of Firm, Firm.all.merge!(:where => "name = '37signals'").first
  assert_nil Client.all.merge!(:where => "name = '37signals'").first
end
test_finding_incorrect_type_data()
# File activerecord/test/cases/inheritance_test.rb, line 234
def test_finding_incorrect_type_data
  assert_raise(ActiveRecord::RecordNotFound) { Firm.find(2) }
  assert_nothing_raised   { Firm.find(1) }
end
test_inheritance_base_class()
# File activerecord/test/cases/inheritance_test.rb, line 78
def test_inheritance_base_class
  assert_equal Post, Post.base_class
  assert_equal Post, SpecialPost.base_class
  assert_equal Post, StiPost.base_class
  assert_equal SubStiPost, SubStiPost.base_class
end
test_inheritance_condition()
# File activerecord/test/cases/inheritance_test.rb, line 222
def test_inheritance_condition
  assert_equal 11, Company.count
  assert_equal 2, Firm.count
  assert_equal 5, Client.count
end
test_inheritance_find()
# File activerecord/test/cases/inheritance_test.rb, line 103
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 141
def test_inheritance_find_all
  companies = Company.all.merge!(:order => 'id').to_a
  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_new_with_base_class()
# File activerecord/test/cases/inheritance_test.rb, line 175
def test_inheritance_new_with_base_class
  company = Company.new(:type => 'Company')
  assert_equal Company, company.class
end
test_inheritance_new_with_default_class()
# File activerecord/test/cases/inheritance_test.rb, line 170
def test_inheritance_new_with_default_class
  company = Company.new
  assert_equal Company, company.class
end
test_inheritance_new_with_subclass()
# File activerecord/test/cases/inheritance_test.rb, line 180
def test_inheritance_new_with_subclass
  firm = Company.new(:type => 'Firm')
  assert_equal Firm, firm.class
end
test_inheritance_save()
# File activerecord/test/cases/inheritance_test.rb, line 153
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 322
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 318
def test_inherits_custom_primary_key
  assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key
end
test_new_with_abstract_class()
# File activerecord/test/cases/inheritance_test.rb, line 185
def test_new_with_abstract_class
  e = assert_raises(NotImplementedError) do
    AbstractCompany.new
  end
  assert_equal("AbstractCompany is an abstract class and cannot be instantiated.", e.message)
end
test_new_with_ar_base()
# File activerecord/test/cases/inheritance_test.rb, line 192
def test_new_with_ar_base
  e = assert_raises(NotImplementedError) do
    ActiveRecord::Base.new
  end
  assert_equal("ActiveRecord::Base is an abstract class and cannot be instantiated.", e.message)
end
test_new_with_autoload_paths()
# File activerecord/test/cases/inheritance_test.rb, line 211
def test_new_with_autoload_paths
  path = File.expand_path('../../models/autoloadable', __FILE__)
  ActiveSupport::Dependencies.autoload_paths << path

  firm = Company.new(:type => 'ExtraFirm')
  assert_equal ExtraFirm, firm.class
ensure
  ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
  ActiveSupport::Dependencies.clear
end
test_new_with_complex_inheritance()
# File activerecord/test/cases/inheritance_test.rb, line 207
def test_new_with_complex_inheritance
  assert_nothing_raised { Client.new(type: 'VerySpecialClient') }
end
test_new_with_invalid_type()
# File activerecord/test/cases/inheritance_test.rb, line 199
def test_new_with_invalid_type
  assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => 'InvalidType') }
end
test_new_with_unrelated_type()
# File activerecord/test/cases/inheritance_test.rb, line 203
def test_new_with_unrelated_type
  assert_raise(ActiveRecord::SubclassNotFound) { Company.new(:type => 'Account') }
end
test_scope_inherited_properly()
# File activerecord/test/cases/inheritance_test.rb, line 327
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 43
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 52
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 244
def test_update_all_within_inheritance
  Client.update_all "name = 'I am a client'"
  assert_equal "I am a client", Client.first.name
  # Order by added as otherwise Oracle tests were failing because of different order of results
  assert_equal "37signals", Firm.all.merge!(:order => "id").to_a.first.name
end
to_param()

Alias of to_s.

# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 5
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.

# File activesupport/lib/active_support/core_ext/object/to_query.rb, line 11
def to_query(key)
  "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}"
end
try(*a, &b)

Invokes the public method whose name goes as first argument just like public_send does, except that if the receiver does not respond to it the call returns nil rather than raising an exception.

This method is defined to be able to write

@person.try(:name)

instead of

@person.name if @person

try calls can be chained:

@person.try(:spouse).try(:name)

instead of

@person.spouse.name if @person && @person.spouse

try will also return nil if the receiver does not respond to the method:

@person.try(:non_existing_method) #=> nil

instead of

@person.non_existing_method if @person.respond_to?(:non_existing_method) #=> nil

try returns nil when called on nil regardless of whether it responds to the method:

nil.try(:to_i) # => nil, rather than 0

Arguments and blocks are forwarded to the method if invoked:

@posts.try(:each_slice, 2) do |a, b|
  ...
end

The number of arguments in the signature must match. If the object responds to the method the call is attempted and ArgumentError is still raised in case of argument mismatch.

If try is called without arguments it yields the receiver to a given block unless it is nil:

@person.try do |p|
  ...
end

You can also call try with a block without accepting an argument, and the block will be instance_eval'ed instead:

@person.try { upcase.truncate(50) }

Please also note that try is defined on Object. Therefore, it won't work with instances of classes that do not have Object among their ancestors, like direct subclasses of BasicObject. For example, using try with SimpleDelegator will delegate try to the target instead of calling it on the delegator itself.

# File activesupport/lib/active_support/core_ext/object/try.rb, line 62
def try(*a, &b)
  try!(*a, &b) if a.empty? || respond_to?(a.first)
end
try!(*a, &b)

Same as try, but will raise a NoMethodError exception if the receiver is not nil and does not implement the tried method.

# File activesupport/lib/active_support/core_ext/object/try.rb, line 69
def try!(*a, &b)
  if a.empty? && block_given?
    if b.arity == 0
      instance_eval(&b)
    else
      yield self
    end
  else
    public_send(*a, &b)
  end
end
unescape(str, escaped = /%[a-fA-F\d]{2}/)
# File activesupport/lib/active_support/core_ext/uri.rb, line 9
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
verify_default_timezone_config()
# File activerecord/test/cases/helper.rb, line 96
def verify_default_timezone_config
  if Time.zone != EXPECTED_ZONE
    $stderr.puts <<-MSG
\n#{self}
    Global state `Time.zone` was leaked.
      Expected: #{EXPECTED_ZONE}
      Got: #{Time.zone}
    MSG
  end
  if ActiveRecord::Base.default_timezone != EXPECTED_DEFAULT_TIMEZONE
    $stderr.puts <<-MSG
\n#{self}
    Global state `ActiveRecord::Base.default_timezone` was leaked.
      Expected: #{EXPECTED_DEFAULT_TIMEZONE}
      Got: #{ActiveRecord::Base.default_timezone}
    MSG
  end
  if ActiveRecord::Base.time_zone_aware_attributes != EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES
    $stderr.puts <<-MSG
\n#{self}
    Global state `ActiveRecord::Base.time_zone_aware_attributes` was leaked.
      Expected: #{EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES}
      Got: #{ActiveRecord::Base.time_zone_aware_attributes}
    MSG
  end
end
with_env_tz(new_tz = 'US/Eastern')
# File activerecord/test/cases/helper.rb, line 62
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_options(options, &block)

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

When you don't pass an explicit receiver, it executes the whole block in merging options context:

class Account < ActiveRecord::Base
  with_options dependent: :destroy do
    has_many :customers
    has_many :products
    has_many :invoices
    has_many :expenses
  end
end

with_options can also be nested since the call is forwarded to its receiver.

NOTE: Each nesting level will merge inherited defaults in addition to their own.

class Post < ActiveRecord::Base
  with_options if: :persisted?, length: { minimum: 50 } do
    validates :content, if: -> { content.present? }
  end
end

The code is equivalent to:

validates :content, length: { minimum: 50 }, if: -> { content.present? }

Hence the inherited default for `if` key is ignored.

# File activesupport/lib/active_support/core_ext/object/with_options.rb, line 65
def with_options(options, &block)
  option_merger = ActiveSupport::OptionMerger.new(self, options)
  block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
end
with_timezone_config(cfg)
# File activerecord/test/cases/helper.rb, line 69
def with_timezone_config(cfg)
  verify_default_timezone_config

  old_default_zone = ActiveRecord::Base.default_timezone
  old_awareness = ActiveRecord::Base.time_zone_aware_attributes
  old_zone = Time.zone

  if cfg.has_key?(:default)
    ActiveRecord::Base.default_timezone = cfg[:default]
  end
  if cfg.has_key?(:aware_attributes)
    ActiveRecord::Base.time_zone_aware_attributes = cfg[:aware_attributes]
  end
  if cfg.has_key?(:zone)
    Time.zone = cfg[:zone]
  end
  yield
ensure
  ActiveRecord::Base.default_timezone = old_default_zone
  ActiveRecord::Base.time_zone_aware_attributes = old_awareness
  Time.zone = old_zone
end