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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
IgalSt
  • 1,974
  • 2
  • 17
  • 26

3 Answers3

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 %>
matt
  • 78,533
  • 8
  • 163
  • 197
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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
-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)

silicakes
  • 6,364
  • 3
  • 28
  • 39