Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

sinatra

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?

like image 516
Seldo Avatar asked Apr 05 '12 02:04

Seldo


1 Answers

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
like image 196
matt Avatar answered Oct 05 '22 13:10

matt