class ActiveMocker::Base

Attributes

_create_caller_locations[RW]

@private

associations[R]
attributes[R]
types[R]

Public Class Methods

__active_record_build_version__() click to toggle source
# File lib/active_mocker/mock/base.rb, line 146
def __active_record_build_version__
  @active_record_build_version
end
_find_associations_by_class(klass_name) click to toggle source
# File lib/active_mocker/mock/base.rb, line 134
def _find_associations_by_class(klass_name)
  associations_by_class[klass_name.to_s]
end
abstract_class?() click to toggle source
# File lib/active_mocker/mock/base.rb, line 103
def abstract_class?
  true
end
clear_mock() click to toggle source

@deprecated

# File lib/active_mocker/mock/base.rb, line 130
def clear_mock
  delete_all
end
create(attributes = {}, &block) click to toggle source

Creates an object (or multiple objects) and saves it to memory.

The attributes parameter can be either a Hash or an Array of Hashes. These Hashes describe the attributes on the objects that are to be created.

Examples

# Create a single new object
User.create(first_name: 'Jamie')

# Create an Array of new objects
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }])

# Create a single object and pass it into a block to set other attributes.
User.create(first_name: 'Jamie') do |u|
  u.is_admin = false
end

# Creating an Array of new objects using a block, where the block is executed for each object:
User.create([{ first_name: 'Jamie' }, { first_name: 'Jeremy' }]) do |u|
  u.is_admin = false
end
# File lib/active_mocker/mock/base.rb, line 37
def create(attributes = {}, &block)
  if attributes.is_a?(Array)
    attributes.collect { |attr| create(attr, &block) }
  else
    record = new(id: attributes.delete(:id) || attributes.delete("id"))

    record.save
    record.touch(:created_at, :created_on) if ActiveMocker::LoadedMocks.features[:timestamps]
    record.assign_attributes(attributes, &block)
    record._create_caller_locations = caller_locations
    record
  end
end
Also aliased as: create!
create!(attributes = {}, &block)
Alias for: create
delete(id) click to toggle source

Delete an object (or multiple objects) that has the given id.

This essentially finds the object (or multiple objects) with the given id and then calls delete on it.

Parameters

  • id - Can be either an Integer or an Array of Integers.

Examples

# Destroy a single object
TodoMock.delete(1)

# Destroy multiple objects
todos = [1,2,3]
TodoMock.delete(todos)
# File lib/active_mocker/mock/base.rb, line 78
def delete(id)
  if id.is_a?(Array)
    id.map { |one_id| delete(one_id) }
  else
    find(id).delete
  end
end
Also aliased as: destroy
delete_all(conditions = nil) click to toggle source

Deletes the records matching conditions.

Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all
Calls superclass method
# File lib/active_mocker/mock/base.rb, line 91
def delete_all(conditions = nil)
  return records.reset if conditions.nil?
  super
end
Also aliased as: destroy_all
destroy(id)
Alias for: delete
destroy_all(conditions = nil)
Alias for: delete_all
from_limit?() click to toggle source

@api private

# File lib/active_mocker/mock/base.rb, line 99
def from_limit?
  false
end
inherited(subclass) click to toggle source
# File lib/active_mocker/mock/base.rb, line 11
def self.inherited(subclass)
  ActiveMocker::LoadedMocks.send(:add, subclass)
end
new(attributes = {}, &block) click to toggle source

New objects can be instantiated as either empty (pass no construction parameter) or pre-set with attributes.

Example:

# Instantiates a single new object
UserMock.new(first_name: 'Jamie')
# File lib/active_mocker/mock/base.rb, line 190
def initialize(attributes = {}, &block)
  if self.class.abstract_class?
    raise NotImplementedError, "#{self.class.name} is an abstract class and cannot be instantiated."
  end
  setup_instance_variables
  assign_attributes(attributes, &block)
end
reflections() click to toggle source

Not fully Implemented Returns association reflections names with nil values

#=> { "user" => nil, "order" => nil }
# File lib/active_mocker/mock/base.rb, line 142
def reflections
  associations.each_with_object({}) { |(k, _), h| h[k.to_s] = nil }
end

Private Class Methods

__new_relation__(collection) click to toggle source

@param [Array<ActiveMocker::Base>] collection, an array of mock instances @return [ScopeRelation] for the given mock so that it will include any scoped methods

# File lib/active_mocker/mock/base.rb, line 121
def __new_relation__(collection)
  ScopeRelation.new(collection)
end
build_type(type) click to toggle source
# File lib/active_mocker/mock/base.rb, line 107
def build_type(type)
  @@built_types       ||= {}
  @@built_types[type] ||= Virtus::Attribute.build(type)
end
classes(klass, fail_hard=false) click to toggle source
# File lib/active_mocker/mock/base.rb, line 112
def classes(klass, fail_hard=false)
  ActiveMocker::LoadedMocks.find(klass).tap do |found_class|
    raise MockNotLoaded, "The ActiveMocker version of #{klass} is not required." if fail_hard && !found_class
    found_class
  end
end
mock_build_version(version, active_record: nil) click to toggle source
# File lib/active_mocker/mock/base.rb, line 152
def mock_build_version(version, active_record: nil)
  @active_record_build_version = Gem::Version.create(active_record)
  if __active_record_build_version__ >= Gem::Version.create("5.1")
    require "active_mocker/mock/compatibility/base/ar51"
    extend AR51
  end

  if __active_record_build_version__ >= Gem::Version.create("5.2")
    require "active_mocker/mock/compatibility/queries/ar52"
    Queries.prepend(Queries::AR52)
  end
  raise UpdateMocksError.new(name, version, ActiveMocker::Mock::VERSION) if version != ActiveMocker::Mock::VERSION
end
records() click to toggle source
# File lib/active_mocker/mock/base.rb, line 53
def records
  @records ||= Records.new
end

Public Instance Methods

_assign_attribute(k, v) click to toggle source

@api private

# File lib/active_mocker/mock/base.rb, line 235
def _assign_attribute(k, v)
  public_send("#{k}=", v)
rescue NoMethodError
  if respond_to?("#{k}=")
    raise
  else
    raise UnknownAttributeError.new(self, k)
  end
end
assign_attributes(new_attributes) { |self| ... } click to toggle source

Allows you to set all the attributes by passing in a hash of attributes with keys matching the attribute names (which again matches the column names).

cat = Cat.new(name: "Gorby", status: "yawning")
cat.attributes # =>  { "name" => "Gorby", "status" => "yawning", "created_at" => nil, "updated_at" => nil}
cat.assign_attributes(status: "sleeping")
cat.attributes # =>  { "name" => "Gorby", "status" => "sleeping", "created_at" => nil, "updated_at" => nil }

Aliased to attributes=.

# File lib/active_mocker/mock/base.rb, line 220
def assign_attributes(new_attributes)
  yield self if block_given?
  unless new_attributes.respond_to?(:stringify_keys)
    raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
  end
  return nil if new_attributes.blank?
  attributes = new_attributes.stringify_keys
  attributes.each do |k, v|
    _assign_attribute(k, v)
  end
end
Also aliased as: attributes=
attribute_names() click to toggle source

Returns an array of names for the attributes available on this object.

person = Person.new
person.attribute_names
# => ["id", "created_at", "updated_at", "name", "age"]
# File lib/active_mocker/mock/base.rb, line 331
def attribute_names
  self.class.attribute_names
end
attribute_present?(attribute) click to toggle source

Returns true if the specified attribute has been set and is neither nil nor empty? (the latter only applies to objects that respond to empty?, most notably Strings). Otherwise, false. Note that it always returns true with boolean attributes.

person = Task.new(title: '', is_done: false)
person.attribute_present?(:title)   # => false
person.attribute_present?(:is_done) # => true
person.name = 'Francesco'
person.is_done = true
person.attribute_present?(:title)   # => true
person.attribute_present?(:is_done) # => true
# File lib/active_mocker/mock/base.rb, line 316
def attribute_present?(attribute)
  value = read_attribute(attribute)
  !value.nil? && !(value.respond_to?(:empty?) && value.empty?)
end
attributes=(new_attributes)
Alias for: assign_attributes
delete() click to toggle source
# File lib/active_mocker/mock/base.rb, line 274
def delete
  records.delete(self)
end
Also aliased as: destroy
destroy()
Alias for: delete
freeze() click to toggle source

Will not allow attributes to be changed

Will freeze attributes forever. Querying for the record again will not unfreeze it because records exist in memory and are not initialized upon a query. This behaviour differs from ActiveRecord, beware of any side effect this may have when using this method.

# File lib/active_mocker/mock/base.rb, line 344
def freeze
  @attributes.freeze; self
end
has_attribute?(attr_name) click to toggle source

Returns true if the given attribute is in the attributes hash, otherwise false.

person = Person.new
person.has_attribute?(:name)    # => true
person.has_attribute?('age')    # => true
person.has_attribute?(:nothing) # => false
# File lib/active_mocker/mock/base.rb, line 301
def has_attribute?(attr_name)
  @attributes.key?(attr_name.to_s)
end
inspect() click to toggle source
# File lib/active_mocker/mock/base.rb, line 335
def inspect
  ObjectInspect.new(name, attributes).to_s
end
new_record?() click to toggle source

Returns true if this object hasn't been saved yet; otherwise, returns false.

# File lib/active_mocker/mock/base.rb, line 283
def new_record?
  records.new_record?(self)
end
persisted?() click to toggle source

Indicates if the model is persisted. Default is false.

person = Person.new(id: 1, name: 'bob')
person.persisted? # => false
# File lib/active_mocker/mock/base.rb, line 291
def persisted?
  records.persisted?(id)
end
save(*_args) click to toggle source
# File lib/active_mocker/mock/base.rb, line 245
def save(*_args)
  self.class.send(:insert, self) unless self.class.exists?(self)
  touch if ActiveMocker::LoadedMocks.features[:timestamps]
  true
end
Also aliased as: save!
save!(*_args)
Alias for: save
slice(*methods) click to toggle source

Returns a hash of the given methods with their names as keys and returned values as values.

# File lib/active_mocker/mock/base.rb, line 322
def slice(*methods)
  Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access
end
touch(*names) click to toggle source
# File lib/active_mocker/mock/base.rb, line 253
def touch(*names)
  raise ActiveMocker::Error, "cannot touch on a new record object" unless persisted?

  attributes = [:updated_at, :update_on]
  attributes.concat(names)

  current_time = Time.now.utc

  attributes.each do |column|
    column = column.to_s
    write_attribute(column, current_time) if self.class.attribute_names.include?(column)
  end
  true
end
update(attributes = {}) click to toggle source
# File lib/active_mocker/mock/base.rb, line 206
def update(attributes = {})
  assign_attributes(attributes)
  save
end

Private Instance Methods

call_mock_method(method:, caller:, arguments: []) click to toggle source

@deprecated

# File lib/active_mocker/mock/base.rb, line 168
def call_mock_method(method:, caller:, arguments: [])
  self.class.send(:is_implemented, method, '#', caller)
end
classes(klass, fail_hard = false) click to toggle source
# File lib/active_mocker/mock/base.rb, line 174
def classes(klass, fail_hard = false)
  self.class.send(:classes, klass, fail_hard)
end
name() click to toggle source
# File lib/active_mocker/mock/base.rb, line 348
def name
  self.class.name
end
records() click to toggle source
# File lib/active_mocker/mock/base.rb, line 268
def records
  self.class.send(:records)
end
setup_instance_variables() click to toggle source
# File lib/active_mocker/mock/base.rb, line 198
def setup_instance_variables
  @types        = self.class.send(:types)
  @attributes   = self.class.send(:attributes).deep_dup
  @associations = self.class.send(:associations).dup
end