Class: ActiveMocker::Base

Inherits:
Object
  • Object
show all
Extended by:
AliasAttribute, Queries
Includes:
PropertiesGetterAndSetter, DoNothingActiveRecordMethods, MockAbilities, TemplateMethods
Defined in:
lib/active_mocker/mock/base.rb,
lib/active_mocker/mock/compatibility/base/ar51.rb,
lib/active_mocker/deprecated_components/mock_abilities.rb

Defined Under Namespace

Modules: AR51, PropertiesGetterAndSetter, Scopes Classes: ScopeRelation

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Queries

all, average, count, delete_all, find, find_by, find_by!, find_or_create_by, find_or_initialize_by, first_or_create, first_or_create!, first_or_initialize, limit, maximum, minimum, none, order, reverse_order, sum, update_all, where

Methods included from AliasAttribute

attribute_alias, attribute_alias?

Methods included from PropertiesGetterAndSetter

#read_attribute, #write_attribute

Methods included from TemplateMethods

included

Methods included from DoNothingActiveRecordMethods

#destroyed?, #errors, included, #marked_for_destruction?, #readonly?, #reload, #valid?

Methods included from MockAbilities

#clear_mocked_methods, included, prepended

Methods included from MockAbilities::InstanceAndClassMethods

#clear_mock, #clear_mocked_methods, #mock_instance_method

Constructor Details

#initialize(attributes = {}, &block) ⇒ Base

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')


193
194
195
196
197
198
199
# File 'lib/active_mocker/mock/base.rb', line 193

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

Instance Attribute Details

#_create_caller_locationsObject



185
186
187
# File 'lib/active_mocker/mock/base.rb', line 185

def _create_caller_locations
  @_create_caller_locations
end

#associationsObject (readonly)

Returns the value of attribute associations.



183
184
185
# File 'lib/active_mocker/mock/base.rb', line 183

def associations
  @associations
end

#attributesObject (readonly)

Returns the value of attribute attributes.



183
184
185
# File 'lib/active_mocker/mock/base.rb', line 183

def attributes
  @attributes
end

#typesObject (readonly)

Returns the value of attribute types.



183
184
185
# File 'lib/active_mocker/mock/base.rb', line 183

def types
  @types
end

Class Method Details

.__active_record_build_version__Object



144
145
146
# File 'lib/active_mocker/mock/base.rb', line 144

def __active_record_build_version__
  @active_record_build_version
end

.__new_relation__(collection) ⇒ ScopeRelation

Returns for the given mock so that it will include any scoped methods.

Parameters:

Returns:

  • (ScopeRelation)

    for the given mock so that it will include any scoped methods



119
120
121
# File 'lib/active_mocker/mock/base.rb', line 119

def __new_relation__(collection)
  ScopeRelation.new(collection)
end

._find_associations_by_class(klass_name) ⇒ Object



132
133
134
# File 'lib/active_mocker/mock/base.rb', line 132

def _find_associations_by_class(klass_name)
  associations_by_class[klass_name.to_s]
end

.abstract_class?Boolean

Returns:

  • (Boolean)


101
102
103
# File 'lib/active_mocker/mock/base.rb', line 101

def abstract_class?
  true
end

.build_type(type) ⇒ Object



105
106
107
108
# File 'lib/active_mocker/mock/base.rb', line 105

def build_type(type)
  @@built_types       ||= {}
  @@built_types[type] ||= Virtus::Attribute.build(type)
end

.classes(klass, fail_hard = false) ⇒ Object



110
111
112
113
114
115
# File 'lib/active_mocker/mock/base.rb', line 110

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

.clear_mockObject

Deprecated.


128
129
130
# File 'lib/active_mocker/mock/base.rb', line 128

def clear_mock
  delete_all
end

.create(attributes = {}, &block) ⇒ Object Also known as: create!

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


35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/active_mocker/mock/base.rb', line 35

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

.delete(id) ⇒ Object

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)


76
77
78
79
80
81
82
# File 'lib/active_mocker/mock/base.rb', line 76

def delete(id)
  if id.is_a?(Array)
    id.map { |one_id| delete(one_id) }
  else
    find(id).delete
  end
end

.delete_all(conditions = nil) ⇒ Object Also known as: destroy_all

Deletes the records matching conditions.

Post.where(person_id: 5).where(category: ['Something', 'Else']).delete_all


89
90
91
92
# File 'lib/active_mocker/mock/base.rb', line 89

def delete_all(conditions = nil)
  return records.reset if conditions.nil?
  super
end

.destroyObject

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)


84
85
86
87
88
89
90
# File 'lib/active_mocker/mock/base.rb', line 84

def delete(id)
  if id.is_a?(Array)
    id.map { |one_id| delete(one_id) }
  else
    find(id).delete
  end
end

.from_limit?Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Boolean)


97
98
99
# File 'lib/active_mocker/mock/base.rb', line 97

def from_limit?
  false
end

.inherited(subclass) ⇒ Object



9
10
11
# File 'lib/active_mocker/mock/base.rb', line 9

def self.inherited(subclass)
  ActiveMocker::LoadedMocks.send(:add, subclass)
end

.recordsObject



51
52
53
# File 'lib/active_mocker/mock/base.rb', line 51

def records
  @records ||= Records.new
end

.reflectionsObject

Not fully Implemented Returns association reflections names with nil values

#=> { "user" => nil, "order" => nil }


140
141
142
# File 'lib/active_mocker/mock/base.rb', line 140

def reflections
  associations.each_with_object({}) { |(k, _), h| h[k.to_s] = nil }
end

Instance Method Details

#_assign_attribute(k, v) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



238
239
240
241
242
243
244
245
246
# File 'lib/active_mocker/mock/base.rb', line 238

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| ... } ⇒ Object Also known as: attributes=

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=.

Yields:

  • (_self)

Yield Parameters:



223
224
225
226
227
228
229
230
231
232
233
# File 'lib/active_mocker/mock/base.rb', line 223

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

#attribute_namesObject

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"]


334
335
336
# File 'lib/active_mocker/mock/base.rb', line 334

def attribute_names
  self.class.attribute_names
end

#attribute_present?(attribute) ⇒ Boolean

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

Returns:

  • (Boolean)


319
320
321
322
# File 'lib/active_mocker/mock/base.rb', line 319

def attribute_present?(attribute)
  value = read_attribute(attribute)
  !value.nil? && !(value.respond_to?(:empty?) && value.empty?)
end

#deleteObject Also known as: destroy



277
278
279
# File 'lib/active_mocker/mock/base.rb', line 277

def delete
  records.delete(self)
end

#freezeObject

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.



347
348
349
# File 'lib/active_mocker/mock/base.rb', line 347

def freeze
  @attributes.freeze; self
end

#has_attribute?(attr_name) ⇒ Boolean

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

Returns:

  • (Boolean)


304
305
306
# File 'lib/active_mocker/mock/base.rb', line 304

def has_attribute?(attr_name)
  @attributes.key?(attr_name.to_s)
end

#inspectObject



338
339
340
# File 'lib/active_mocker/mock/base.rb', line 338

def inspect
  ObjectInspect.new(name, attributes).to_s
end

#new_record?Boolean

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

Returns:

  • (Boolean)


286
287
288
# File 'lib/active_mocker/mock/base.rb', line 286

def new_record?
  records.new_record?(self)
end

#persisted?Boolean

Indicates if the model is persisted. Default is false.

person = Person.new(id: 1, name: 'bob')
person.persisted? # => false

Returns:

  • (Boolean)


294
295
296
# File 'lib/active_mocker/mock/base.rb', line 294

def persisted?
  records.persisted?(id)
end

#save(*_args) ⇒ Object Also known as: save!



248
249
250
251
252
# File 'lib/active_mocker/mock/base.rb', line 248

def save(*_args)
  self.class.send(:insert, self) unless self.class.exists?(self)
  touch if ActiveMocker::LoadedMocks.features[:timestamps]
  true
end

#slice(*methods) ⇒ Object

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



325
326
327
# File 'lib/active_mocker/mock/base.rb', line 325

def slice(*methods)
  Hash[methods.map! { |method| [method, public_send(method)] }].with_indifferent_access
end

#touch(*names) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/active_mocker/mock/base.rb', line 256

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 = {}) ⇒ Object



209
210
211
212
# File 'lib/active_mocker/mock/base.rb', line 209

def update(attributes = {})
  assign_attributes(attributes)
  save
end