# coding: utf-8
require 'singleton'
module CustomStrategy
class AutoIncrement
include Singleton
def initialize
@sequence_table = {}
end
def counter(table_name)
if @sequence_table.has_key?(table_name)
@sequence_table[table_name] += 1
else
@sequence_table[table_name] = 1
end
end
end
class Base
private
def append_date_column(instance)
[:updated_at, :created_at].each do |date_column|
if instance.respond_to?(date_column) && instance.send(date_column).nil?
instance.send(date_column.to_s + "=", Time.now)
end
end
end
def append_delete_flag(instance)
if instance.respond_to?(:delete_flag) && instance.delete_flag.nil?
instance.delete_flag = 0
end
end
def build_result(result_instance)
result_instance.id ||= AutoIncrement.instance.counter(result_instance.class.table_name.to_sym)
append_date_column(result_instance)
append_delete_flag(result_instance)
end
def stub_database_interaction_on_result(result_instance)
result_instance.id ||= AutoIncrement.instance.counter(result_instance.class.table_name.to_sym)
result_instance.instance_eval do
def persisted?
!new_record?
end
def new_record?
id.nil?
end
def save(*args)
raise "stubbed models are not allowed to access the database - #{self.class.to_s}#save(#{args.join(",")})"
end
def destroy(*args)
raise "stubbed models are not allowed to access the database - #{self.class.to_s}#destroy(#{args.join(",")})"
end
def connection
raise "stubbed models are not allowed to access the database - #{self.class.to_s}#connection()"
end
def reload
raise "stubbed models are not allowed to access the database - #{self.class.to_s}#reload()"
end
def update_attribute(*args)
raise "stubbed models are not allowed to access the database - #{self.class.to_s}#update_attribute(#{args.join(",")})"
end
def update_column(*args)
raise "stubbed models are not allowed to access the database - #{self.class.to_s}#update_column(#{args.join(",")})"
end
end
append_date_column(result_instance)
append_delete_flag(result_instance)
end
end
class Stub < Base
def association(runner)
runner.run(:build_stubbed)
end
def result(evaluation)
evaluation.object.tap do |instance|
evaluation.notify(:before_stub_custom, instance)
stub_database_interaction_on_result(instance)
evaluation.notify(:after_stub_custom, instance)
end
end
end
class Build < Base
def association(runner)
runner.run(:build)
end
def result(evaluation)
evaluation.object.tap do |instance|
evaluation.notify(:before_build_custom, instance)
build_result(instance)
evaluation.notify(:after_build_custom, instance)
end
end
end
end
FactoryGirl.register_strategy(:build_custom, CustomStrategy::Build)
FactoryGirl.register_strategy(:stub_custom, CustomStrategy::Stub)
FactoryGirl.register_callback(:before_stub_custom)
FactoryGirl.register_callback(:after_stub_custom)
FactoryGirl.register_callback(:before_build_custom)
FactoryGirl.register_callback(:after_build_custom)