Sha256: 7dbc284773515db824bffe8b8c14106ef17c5e19bbeae9928d354ac1f5d3d8a2
Contents?: true
Size: 1.97 KB
Versions: 2
Compression:
Stored size: 1.97 KB
Contents
require 'active_record' require 'active_support/core_ext/string/inflections' require 'with_model/constant_stubber' require 'with_model/methods' require 'with_model/table' module WithModel class Model OPTIONS = [:superclass].freeze private_constant :OPTIONS attr_writer :model_block, :table_block, :table_options def initialize name, options = {} validate_options!(options) @name = name.to_sym @model_block = nil @table_block = nil @table_options = {} @superclass = options.fetch(:superclass, ActiveRecord::Base) end def create table.create @model = Class.new(@superclass) do extend WithModel::Methods end stubber.stub_const @model setup_model end def destroy stubber.unstub_const remove_from_superclass_descendants reset_dependencies_cache table.destroy @model = nil end private def const_name @name.to_s.camelize.to_sym end def setup_model @model.table_name = table_name @model.class_eval(&@model_block) if @model_block @model.reset_column_information end def remove_from_superclass_descendants return unless @model.superclass.respond_to?(:direct_descendants) @model.superclass.direct_descendants.delete(@model) end def reset_dependencies_cache return unless defined?(ActiveSupport::Dependencies::Reference) ActiveSupport::Dependencies::Reference.clear! end def stubber @stubber ||= ConstantStubber.new const_name end def table @table ||= Table.new table_name, @table_options, &@table_block end def table_name uid = "#$$_#{Thread.current.object_id}" "with_model_#{@name.to_s.tableize}_#{uid}".freeze end def validate_options!(options) unknown_options = options.keys - OPTIONS unless unknown_options.empty? raise ArgumentError, "unknown options: #{unknown_options.inspect}" end end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
with_model-2.0.0 | lib/with_model/model.rb |
with_model-1.2.2 | lib/with_model/model.rb |