- MODULE Object::AddtlGlobalConstants
- MODULE Object::ROUTING
- CLASS Object::HashWithIndifferentAccess
- CLASS Object::ItselfTest
- A
- B
- C
- D
- E
- H
- I
- J
- L
- M
- O
- P
- R
- S
- T
-
- test_a_bad_type_column,
- test_abstract_inheritance_base_class,
- test_alt_becomes_bang_resets_inheritance_type_column,
- test_alt_becomes_works_with_sti,
- test_alt_complex_inheritance,
- test_alt_destroy_all_within_inheritance,
- test_alt_eager_loading,
- test_alt_find_first_within_inheritance,
- test_alt_finding_incorrect_type_data,
- test_alt_inheritance_condition,
- test_alt_inheritance_find,
- test_alt_inheritance_find_all,
- test_alt_inheritance_save,
- test_alt_update_all_within_inheritance,
- test_base_class_activerecord_error,
- test_becomes_and_change_tracking_for_inheritance_columns,
- test_class_without_store_full_sti_class_returns_demodulized_name,
- test_company_descends_from_active_record,
- test_complex_inheritance,
- test_destroy_all_within_inheritance,
- test_different_namespace_subclass_should_load_correctly_with_store_full_sti_class_option,
- test_eager_load_belongs_to_primary_key_quoting,
- test_eager_load_belongs_to_something_inherited,
- test_find_first_within_inheritance,
- test_finding_incorrect_type_data,
- test_inheritance_base_class,
- test_inheritance_condition,
- test_inheritance_find,
- test_inheritance_find_all,
- test_inheritance_new_with_base_class,
- test_inheritance_new_with_default_class,
- test_inheritance_new_with_subclass,
- test_inheritance_save,
- test_inheritance_without_mapping,
- test_inherits_custom_primary_key,
- test_new_with_abstract_class,
- test_new_with_ar_base,
- test_new_with_autoload_paths,
- test_new_with_complex_inheritance,
- test_new_with_invalid_type,
- test_new_with_unrelated_type,
- test_scope_inherited_properly,
- test_should_store_demodulized_class_name_with_store_full_sti_class_option_disabled,
- test_should_store_full_class_name_with_store_full_sti_class_option_enabled,
- test_update_all_within_inheritance,
- to_param,
- to_query,
- try,
- try!
- U
- V
- W
- ActiveRecord::Inheritance
- Java
- Object::AddtlGlobalConstants
- FileUtils
- W3CValidators
| 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
Internally symbols are mapped to strings when used as keys in the entire
writing interface (calling
You are guaranteed that the key is returned as a string:
Technically other types of keys are accepted:
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 Note that core extensions define
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 ) |
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.
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]
This is a predicate useful for the doc:guides task of applications.
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
Can you safely dup this object?
False for nil, false, true, symbol,
number and BigDecimal(in 1.9.x) objects; true otherwise.
# 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
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?.
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}
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"]
Skips the current run on JRuby using Minitest::Assertions#skip
# 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
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]
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]
An object is present if it's not blank.
@return [true, false]
Skips the current run on Rubinius using Minitest::Assertions#skip
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
Alias of to_s.
Converts an object into a string suitable for use as a URL query string,
using the given key as the param name.
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.
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/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
# 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
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 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