Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisleech/e740fd6c191908a43bd8 to your computer and use it in GitHub Desktop.
Save krisleech/e740fd6c191908a43bd8 to your computer and use it in GitHub Desktop.
Store schema in database
require 'mongo'

class DynaModel
  include Virtus.model
  
  def save
    connection.insert(self.attributes)
  end
  
  # Builds a DynaModel class with attributes as per given schema
    def self.build(schema)
    Class.new(self).tap do |klass|
      schema.each do |definition|
        klass.attribute definition.fetch(:type), name: definition.fetch(:key))
      end
    end
  end
  
  private
  
  def connection
    Mongo.connection(self.class.to_s)
  end
end

schema = [
  { key: 'name',   type: String },
  { key: 'age',    type: Integer },
  { key: 'height', type: Integer }
]

dyna_model = DynaModel.build(schema).new(name: 'Kris')
dyna_model.name # => 'Kris'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment