How do I access a variable across a Middleman Extension?
middleman, ruby
Solution
I'd prefer not to use `@@var` or `$var`. Extension options are the intended way to do this, but as you've discovered, global helpers are in the global Middleman application's context, not the extension's context.
A good way to do this is to fish the extension out of the global extension registry. So assuming your extension is named `:next_previous`:
helpers do
def test_helper
opts = extensions[:next_previous].options
puts opts.defines_setting?(:var1) ? opts.var1 : false
end
end
Note that the `options` attribute is actually an instance of `ConfigurationManager`, so it's possible to use methods like `defines_setting?` to check a setting rather than `defined?`.
Problem
I've been having trouble accessing data consistently through the various parts of a middleman extension. To explain, here's a simplified example extension that just sets variables: ``` class NextPrevious < Middleman::Extension option :var1, true, 'A example variable.' def initialize(app, options_hash={}, &block) super app.set :var2, true @var3 = true # test all variables puts defined?(options.var1) ? options.var1 : false #=> true puts defined?(var2) ? var2 : false #=> true puts defined?(@var3) ? @var3 : false #=> true end def manipulate_resource_list(resources) # test all variables puts defined?(options.var1) ? options.var1 : false #=> true puts defined?(var2) ? var2 : false #=> false puts defined?(@var3) ? @var3 : false #=> true end helpers do def test_helper # test all variables puts defined?(options.var1) ? options.var1 : false #=> false puts defined?(var2) ? var2 : false #=> true puts defined?(@var3) ? @var3 : false #=> false end end end ``` So given three variables, a option, a global setting, and an instance variable, none can be accessed across all three methods. I need all three methods because I want to collect some data (from a .yml), manipulate it via the sitemap (using `manipulate_resource_list`) and use it in a helper. I don't know how to find where their scope ends, or how to pass them properly, since I don't quite grok where each method is called in the loading process or their relationship to each other. Any suggestions?