Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js - Get all model names

I'm trying to to get a list of all defined models in my Ember application (v1.8).

As far as I can tell from my research, the Container.resolver works with some mysterious magic. Does the Container have a list of all active models, or is there any way to get them?

Thanks :)

@edit

kingpin2k's answer works, but not in Ember-Cli, is there an other way?

like image 827
medokin Avatar asked Aug 04 '14 18:08

medokin


2 Answers

So, for Ember Cli there isn't a direct solution I could find. However, you can work around the problem with a bit of creative coding and by analysing ember-inspector's source.

var models = Object.keys(require._eak_seen).filter(function(module) {
    return module.indexOf(config.modulePrefix + '/models/') === 0;
});

This snippet iterates over the modules registered with requirejs and extracts only the wanted modules (the models in our case).

For the "config.modulePrefix" part to work you will need to import your conf file (fix the path):

import config from '../config/environment';

Alternatively you can either hardcode the "config.modulePrefix" to "myappname" or use this:

this.container.resolver.__resolver__.namespace.modulePrefix

PS: To inspect the model you need to use:

require(_the_model_module_name).default
like image 132
Alexandre Gomes Avatar answered Sep 21 '22 01:09

Alexandre Gomes


So I'm adding this, because I came across what I believe is now the best solution (post ember-cli, and ember container changes):

// in a route
// routes/route.js
import Ember from 'ember'

const { Route, getOwner } = Ember

export default Route.extend({
  model: function(){
    return getOwner(this)
    .lookup('data-adapter:main')
    .getModelTypes()
    .map(type => type.name)
  }
})

// somewhere else in an ember application
const modelNames = getOwner(this)
.lookup('data-adapter:main')
.getModelTypes()
.map(type => type.name)

Here is the link to the source in ember-admin on github.

like image 44
TameBadger Avatar answered Sep 21 '22 01:09

TameBadger