How to define a method to be called from the configure block of a modular sinatra application?

ruby, sinatra

Solution

It seems the `configure` block is executed as the file is read. You simply need to move the definition of your method before the configure block, and convert it to a class method:

class MyApp < Sinatra::Base

  def self.read_config_file()
    # interpret a config file
  end

  configure :production do
    myConfigVar = self.read_config_file()
  end

  configure :development do
    myConfigVar = self.read_config_file()
  end

end

Problem

I have a Sinatra app that, boiled down, looks basically like this: ``` class MyApp < Sinatra::Base configure :production do myConfigVar = read_config_file() end configure :development do myConfigVar = read_config_file() end def read_config_file() # interpret a config file end end ``` Unfortunately, this doesn't work. I get `undefined method read_config_file for MyApp:Class (NoMethodError)` The logic in `read_config_file` is non-trivial, so I don't want to duplicate in both. How can I define a method that can be called from both my configuration blocks? Or am I just approaching this problem in entirely the wrong way?

Original source