How to know in what environment the code runs?
Asked Answered
S

3

11

In the layout file of haml I would like to determine whether we are in our development and build environments. We're using Middleman.

I would like to do something like this:

- if environment == 'development'
    / Development Code
    = javascript_include_tag "Dev.js"

I tried to access Ruby's environment variable, as well as define a custom variable in the config.rb file with no success.

Sigil answered 9/12, 2012 at 10:12 Comment(0)
L
30

You’ve almost got it right – you need to check against a symbol rather than a string:

- if environment == :development
    / Development Code
    = javascript_include_tag "Dev.js"

Middleman also adds the development? and build? methods which may be easier to use:

- if development?
    / Development Code
    = javascript_include_tag "Dev.js"

This works with ERB too:

<% if development? %>
<!-- Development Code -->
<%= javascript_include_tag "Dev.js" %>
<% end %>
Levinson answered 9/12, 2012 at 16:57 Comment(0)
Y
0

First, if possible, you should separate the logic from the data. Determine your environment in your controller, and toggle the data being sent to the view (HAML layout file).

Typically you'd set a flag in your environment variables and access it in your code from ENV. For instance, Sinatra makes the development/test/production setting available inside the code using their RACK_ENV symbol:

:environment - configuration/deployment environment A symbol
specifying the deployment environment; typically set to one of
:development, :test, or :production. The :environment defaults to the
value of the RACK_ENV environment variable (ENV['RACK_ENV']), or
:development when no RACK_ENV environment variable is set.

The environment can be set explicitly:

set :environment, :production

If you have to roll your own, that's a good way to go about it.

Yuma answered 9/12, 2012 at 15:49 Comment(0)
D
-1

Use the :environment symbol that middleman creates by default: http://rubydoc.info/github/middleman/middleman/Middleman/Application#environment-instance_method

combined with haml - you can do something like:

= javascript_include_tag "Dev.js" unless :environment == "developement"

note that middlemans build process changes the :environment value to "build"

you can also use developement? to test whether you're on dev or not: http://rubydoc.info/github/middleman/middleman/Middleman/Application#development%3F-instance_method

All the above applies to middleman 3.0.6 and might not work on lesser versions (won't work on 2.x for sure)

Degraded answered 9/12, 2012 at 19:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.