borisrorsvort
borisrorsvort

Reputation: 906

How set/get environment specific variable in a Yeoman Ember app

Considering an Yeoman Ember app.

I've looked different tools like:

But I don't quite see how can you set/get for instance different adapter url in your router.js depending on some grunt/node environment.

Upvotes: 1

Views: 2429

Answers (2)

borisrorsvort
borisrorsvort

Reputation: 906

So I ended up figuring out a way that works well but only with two env:

I made a pull-request for the ember-generator to start using that pattern: https://github.com/borisrorsvort/generator-ember/commit/66f26e9e5a7599da53cb99b85e8ef5864648349b

Here is an implementation that works with yeoman ember generator:

Your replace task should look something like this:

replace: {
  app: {
    options: {
      variables: {
        ember: 'bower_components/ember/ember.js',
        ember_data: 'bower_components/ember-data-shim/ember-data.prod.js',
        app_config: 'scripts/app_config/development.js'
      }
    },
    files: [{
      src: '<%= yeoman.app %>/index.html',
      dest: '.tmp/index.html'
    }]
  },
  dist: {
    options: {
      variables: {
        ember: 'bower_components/ember/ember.prod.js',
        ember_data: 'bower_components/ember-data-shim/ember-data.prod.js',
        app_config: 'scripts/app_config/production.js'
      }
    },
    files: [{
      src: '<%= yeoman.app %>/index.html',
      dest: '.tmp/index.html'
    }]
  }
}

======

Then add '@@app_config' the index.html under @@ember and @@ember_data so that it get replaced by the correct string

======

Then create two files:

  • app/templates/scripts/app_config/development.js
  • app/templates/scripts/app_config/production.js

These contain an AppConfig onject that you can use in your Ember App

var AppConfig = {};

======

Now Imagine you want to change your adapter when you're building the app:

Just use:

MyApp.ApplicationAdapter = DS.RESTAdapter.extend({
  host: AppConfig.apiAdapterUrl
});

Upvotes: 0

nico
nico

Reputation: 654

One approach would be having for example two files: development.properties and production.properties, and using grunt you can copy them to a current.properties file and then you can read the current.properties file always, using for example nconf from any place of your application.

You just need to use the grunt-contrib-copy tasks in your grunt file.

Summary: create a gruntfile that read the environment from the command line and copy the corresponding file property to current.properties, and then in your route.js you just include nconf and you just use it.

Also as an alternative nconf can read parameters from the command line given to node when you run it, so you can avoid the grunt file and run it like node app.js --property=value and take the value of the property with nconf from your route.js

Upvotes: 1

Related Questions