class Railjet::Repository::Generic

Attributes

type[RW]

Public Class Methods

[](dao = nil) click to toggle source
# File lib/railjet/repository/generic.rb, line 5
def [](dao = nil)
  new(dao)
end
new(dao = nil) click to toggle source
# File lib/railjet/repository/generic.rb, line 12
def initialize(dao = nil)
  @dao  = dao
  @type = self.class.type
end

Public Instance Methods

included(klass) click to toggle source
# File lib/railjet/repository/generic.rb, line 17
def included(klass)
  define_dao_accessor(@type, @dao)
  define_type_accessor(klass, @type)
  define_initializer(klass)
  include_repository_methods(klass)
end

Private Instance Methods

define_dao_accessor(type, dao) click to toggle source
# File lib/railjet/repository/generic.rb, line 26
def define_dao_accessor(type, dao)
  define_method type do
    instance_variable_get("@#{type}") || instance_variable_set("@#{type}", (dao.constantize if dao.respond_to?(:constantize)))
  end
end
define_initializer(klass) click to toggle source
# File lib/railjet/repository/generic.rb, line 36
def define_initializer(klass)
  klass.class_eval do
    attr_reader :registry

    def initialize(registry, **kwargs)
      @registry = registry
      instance_variable_set("@#{self.class.type}", kwargs.fetch(self.class.type, nil))

      # Let's check if DAO was set through registry or set when including inner repo mixin
      unless send(self.class.type)
        raise ArgumentError, "Your repository #{self.class} need a DAO. It can be set with inner-repo mixin  or through registry with `#{self.class.type}:` option"
      end
    end
  end
end
define_type_accessor(klass, type) click to toggle source
# File lib/railjet/repository/generic.rb, line 32
def define_type_accessor(klass, type)
  klass.define_singleton_method(:type) { type }
end
include_repository_methods(klass) click to toggle source
# File lib/railjet/repository/generic.rb, line 52
def include_repository_methods(klass)
  if defined?(self.class::RepositoryMethods)
    klass.send :include, self.class::RepositoryMethods
  end
end