class ActiveRepository::Base

Base class for ActiveRepository gem. Extends it in order to use it.

Options

There are 2 class attributes to help configure your ActiveRepository class:

* +class_model+: Use it to specify the class that is responsible for the
  persistence of the objects. Default is self, so it is always saving in
  memory by default.

* +save_in_memory+: Used to ignore the class_model attribute, you can use
  it in your test suite, this way all your tests will be saved in memory.
  Default is set to true so it saves in memory by default.

Examples

Using ActiveHash to persist objects in memory:

class SaveInMemoryTest < ActiveRepository::Base
end

Using ActiveRecord/Mongoid to persist objects:

class SaveInORMOrODMTest < ActiveRepository::Base
  SaveInORMOrODMTest.persistence_class = ORMOrODMModelClass
  SaveInORMOrODMTest.save_in_memory = false
end
Author

Caio Torres (efreesen@gmail.com)

License

GPL

Public Class Methods

after_save(*methods, options) click to toggle source
# File lib/active_repository/base.rb, line 68
def self.after_save(*methods, options)
  add_callbacks(__method__, methods, options)
end
all() click to toggle source

Returns all persisted objects

Calls superclass method
# File lib/active_repository/base.rb, line 60
def self.all
  (repository? ? super : PersistenceAdapter.all(self).map { |object| serialize!(object.attributes) })
end
before_save(*methods, options) click to toggle source
# File lib/active_repository/base.rb, line 64
def self.before_save(*methods, options)
  add_callbacks(__method__, methods, options)
end
constantize() click to toggle source

Constantize class name

# File lib/active_repository/base.rb, line 73
def self.constantize
  self.to_s.constantize
end
delete_all() click to toggle source

Deletes all persisted objects

Calls superclass method
# File lib/active_repository/base.rb, line 78
def self.delete_all
  repository? ? super : PersistenceAdapter.delete_all(self)
end
exists?(id) click to toggle source

Checks the existence of a persisted object with the specified id

# File lib/active_repository/base.rb, line 83
def self.exists?(id)
  repository? ? find_by(id: id).present? : PersistenceAdapter.exists?(self, id)
end
find_by(args) click to toggle source

Searches all objects that matches field_name field with the args value(s)

# File lib/active_repository/base.rb, line 104
def self.find_by(args)
  raise ArgumentError("Argument must be a Hash") unless args.is_a?(Hash)

  objects = where(args)

  objects.first
end
find_by!(args) click to toggle source

Searches all objects that matches field_name field with the args value(s)

# File lib/active_repository/base.rb, line 113
def self.find_by!(args)
  object = find_by(args)

  raise ActiveHash::RecordNotFound unless object
  object
end
get_model_class() click to toggle source

Returns the Class responsible for persisting the objects

# File lib/active_repository/base.rb, line 98
def self.get_model_class
  puts '[deprecation warning] This method is going to be deprecated, use "persistence_class" instead.'
  persistence_class
end
persistence_class() click to toggle source
# File lib/active_repository/base.rb, line 87
def self.persistence_class
  return self if save_in_memory? || (postfix.nil? && self.model_class.nil?)
  return "#{self}#{postfix.classify}".constantize if postfix.present?
  self.model_class.to_s.constantize
end
persistence_class=(value) click to toggle source
# File lib/active_repository/base.rb, line 135
def self.persistence_class=(value)
  self.model_class = value
end
repository?() click to toggle source
# File lib/active_repository/base.rb, line 93
def self.repository?
  self == persistence_class
end
save_in_memory?() click to toggle source
# File lib/active_repository/base.rb, line 145
def self.save_in_memory?
  self.save_in_memory == nil ? true : self.save_in_memory
end
serialize!(other) click to toggle source

Converts Persisted object(s) to it's ActiveRepository counterpart

# File lib/active_repository/base.rb, line 121
def self.serialize!(other)
  case other.class.to_s
  when "Hash", "ActiveSupport::HashWithIndifferentAccess" then self.new.serialize!(other)
  when "Array"                                            then other.map { |o| serialize!(o.attributes) }
  when "Moped::BSON::Document", "BSON::Document"          then self.new.serialize!(other)
  else self.new.serialize!(other.attributes)
  end
end
serialized_attributes() click to toggle source

Returns an array with the field names of the Class

# File lib/active_repository/base.rb, line 131
def self.serialized_attributes
  field_names.map &:to_s
end
set_model_class(value) click to toggle source

Sets the class attribute model_class, responsible to persist the ActiveRepository objects

# File lib/active_repository/base.rb, line 140
def self.set_model_class(value)
  puts '[deprecation warning] This method is going to be deprecated, use "persistence_class=" instead.'
  persistence_class = value
end
set_save_in_memory(value) click to toggle source

Sets the class attribute save_in_memory, set it to true to ignore model_class attribute and persist objects in memory

# File lib/active_repository/base.rb, line 151
def self.set_save_in_memory(value)
  puts '[deprecation warning] This method is going to be deprecated, use "save_in_memory=" instead.'
  self.save_in_memory = value
end
where(*args) click to toggle source

Searches persisted objects that matches the criterias in the parameters. Can be used in ActiveRecord/Mongoid way or in SQL like way.

Example:

* RelatedClass.where(:name => "Peter")
* RelatedClass.where("name = 'Peter'")
# File lib/active_repository/base.rb, line 163
def self.where(*args)
  raise ArgumentError.new("must pass at least one argument") if args.empty?

  result_set = ActiveRepository::ResultSet.new(self)

  result_set.where(args)

  # if repository?
  #   args = args.first if args.respond_to?(:size) && args.size == 1
  #   query_executor = SqlQueryExecutor::Base.new(all)
  #   query_executor.where(args)
  # else
  #   objects = PersistenceAdapter.where(self, sanitize_args(args)).map do |object|
  #     self.serialize!(object.attributes)
  #   end

  #   objects
  # end
end

Private Class Methods

add_callbacks(kind, methods, options) click to toggle source
# File lib/active_repository/base.rb, line 268
def self.add_callbacks(kind, methods, options)
  methods = methods.map { |method| {method: method, options: options} }
  current_callbacks = (self.send("#{kind}_methods") || [])
  self.send("#{kind}_methods=", (current_callbacks + methods)).flatten
end

Public Instance Methods

get_model_class() click to toggle source
# File lib/active_repository/base.rb, line 187
def get_model_class
  puts '[deprecation warning] This method is going to be deprecated, use "persistence_class" instead.'
  self.class.persistence_class
end
persist() click to toggle source

Persists the object using the class defined on the model_class attribute, if none defined it is saved in memory.

# File lib/active_repository/base.rb, line 194
def persist
  if self.valid?
    save_in_memory? ? save : self.convert.present?
  end
end
persistence_class() click to toggle source
# File lib/active_repository/base.rb, line 183
def persistence_class
  self.class.persistence_class
end
reload() click to toggle source

Gathers the persisted object from database and updates self with it's attributes.

# File lib/active_repository/base.rb, line 201
def reload
  object = self.id.present? ? 
             persistence_class.where(id: self.id).first_or_initialize : 
             self

  serialize! object.attributes
end
save(force=false) click to toggle source
Calls superclass method ActiveHash::Base#save
# File lib/active_repository/base.rb, line 209
def save(force=false)
  execute_callbacks(before_save_methods)
  result = true

  if self.class == persistence_class
    object = persistence_class.where(id: self.id).first_or_initialize

    result = if force || self.id.nil?
      self.id = nil if self.id.nil?
      super
    elsif self.valid?
      object.attributes = self.attributes.select{ |key, value| self.class.serialized_attributes.include?(key.to_s) }
      object.save(true)
    end
  else
    result = self.persist
  end

  execute_callbacks(after_save_methods)
  # (after_save_methods || []).each { |method| self.send(method) }

  result
end
serialize!(attributes) click to toggle source

Updates attributes from self with the attributes from the parameters

# File lib/active_repository/base.rb, line 234
def serialize!(attributes)
  unless attributes.nil?
    attributes.each do |key, value|
      key = "id" if key == "_id"
      self.send("#{key}=", (value.dup rescue value))
    end
  end

  self.dup
end

Protected Instance Methods

convert(attribute="id") click to toggle source

Find related object on the database and updates it with attributes in self, if it didn't find it on database it creates a new one.

# File lib/active_repository/base.rb, line 248
def convert(attribute="id")
  klass = persistence_class
  object = klass.where(attribute.to_sym => self.send(attribute)).first

  object ||= persistence_class.new

  attributes = self.attributes.select{ |key, value| self.class.serialized_attributes.include?(key.to_s) }

  attributes.delete(:id)

  object.attributes = attributes

  object.save

  self.id = object.id

  object
end

Private Instance Methods

execute_callbacks(callbacks) click to toggle source
# File lib/active_repository/base.rb, line 275
def execute_callbacks(callbacks)
  Array(callbacks).each do |callback|
    method = callback[:method]
    options = callback[:options]

    if_option = !!options[:if].try(:call, self)
    else_option = options[:else].try(:call, self)

    if if_option || !(else_option.nil? ? true : else_option)
      self.send(method)
    end
  end
end
set_timestamps() click to toggle source

Updates created_at and updated_at

# File lib/active_repository/base.rb, line 290
def set_timestamps
  if self.errors.empty?
    self.created_at = DateTime.now.utc if self.respond_to?(:created_at=) && self.created_at.nil?
    self.updated_at = DateTime.now.utc if self.respond_to?(:updated_at=)
  end
end