Class: Exwiw::MongoidSchemaGenerator
- Inherits:
-
Object
- Object
- Exwiw::MongoidSchemaGenerator
- Defined in:
- lib/exwiw/mongoid_schema_generator.rb
Overview
Generates exwiw ‘MongodbCollectionConfig` files by introspecting Mongoid document models. This is the MongoDB/Mongoid counterpart of `SchemaGenerator` (which targets ActiveRecord); it is intentionally a separate class and rake task because the two ORMs expose entirely different metadata APIs.
Introspection relies only on class-level Mongoid metadata (‘fields`, `relations`, `collection_name`), so it does not require a live MongoDB connection.
Class Method Summary collapse
Instance Method Summary collapse
-
#build_collections ⇒ Object
Returns an array of ‘MongodbCollectionConfig`, one per collection (top-level collections and embedded subdocument configs alike).
- #generate! ⇒ Object
-
#initialize(models:, output_dir:) ⇒ MongoidSchemaGenerator
constructor
A new instance of MongoidSchemaGenerator.
- #write_files(dir, collections) ⇒ Object
Constructor Details
#initialize(models:, output_dir:) ⇒ MongoidSchemaGenerator
Returns a new instance of MongoidSchemaGenerator.
22 23 24 25 |
# File 'lib/exwiw/mongoid_schema_generator.rb', line 22 def initialize(models:, output_dir:) @models = models @output_dir = output_dir end |
Class Method Details
.from_rails_application(output_dir:) ⇒ Object
17 18 19 20 |
# File 'lib/exwiw/mongoid_schema_generator.rb', line 17 def self.from_rails_application(output_dir:) Rails.application.eager_load! new(models: ::Mongoid.models, output_dir: output_dir) end |
Instance Method Details
#build_collections ⇒ Object
Returns an array of ‘MongodbCollectionConfig`, one per collection (top-level collections and embedded subdocument configs alike).
Models are grouped by ‘collection_name` so an inheritance hierarchy whose subclasses share the base’s collection (Mongoid STI, discriminated by the auto-added ‘_type` field) collapses into a single config that aggregates every class’s fields and associations. See ‘expand_with_descendants`.
40 41 42 43 44 45 |
# File 'lib/exwiw/mongoid_schema_generator.rb', line 40 def build_collections models = (concrete_models) models .group_by { |model| model.collection_name.to_s } .map { |collection_name, group| build_collection_for(collection_name, group) } end |
#generate! ⇒ Object
27 28 29 30 31 |
# File 'lib/exwiw/mongoid_schema_generator.rb', line 27 def generate! collections = build_collections write_files(@output_dir, collections) collections end |
#write_files(dir, collections) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/exwiw/mongoid_schema_generator.rb', line 47 def write_files(dir, collections) FileUtils.mkdir_p(dir) collections.each do |collection| path = File.join(dir, "#{collection.name}.json") config_to_write = if File.exist?(path) MongodbCollectionConfig.from(JSON.parse(File.read(path))).merge(collection) else collection end File.write(path, JSON.pretty_generate(config_to_write.to_hash) + "\n") end end |