Richlewis
Richlewis

Reputation: 15394

NoMethodError Sinatra Modular app

Probably something quite basic but I want to be able to use some custom helper methods in a modular Sinatra app. I have the following in ./helpers/aws_helper.rb

helpers do
 def aws_asset( path )
   File.join settings.asset_host, path
 end
end

and then in my view i want to be able to use this method like so

<%= image_tag(aws_asset('/assets/images/wd.png')) %>

but i get the above area, so within my app.rb file i am

require './helpers/aws_helper'


class Profile < Sinatra::Base

get '/' do
  erb :index
end

end

So is my issue that i am requiring it outside of my Profile class. which doesn't make sense as I am requiring my config files for ENV variables the same way and they are being read, but then again they are not methods so i guess that does make sense.

I think maybe im struggling to get my head around what a modular app is as opposed to using a classic styled sinatra app.

Any pointers appreciated

Error message

NoMethodError at / undefined method `aws_asset' for #<Profile:0x007f1e6c4905c0> file: index.erb location: block in singletonclass line: 8

Upvotes: 1

Views: 1023

Answers (1)

matt
matt

Reputation: 79813

When you use helpers do ... in the top level like this you are adding the methods as helpers to Sinatra::Application and not your Profile class. If you are using the Sinatra modular style exclusively make sure you only ever use require 'sinatra/base', and not require sinatra, this will prevent you from mixing up the two styles like this.

In this case you should probably create a module for your helpers instead of using helpers do ..., and then add that module with the helpers method in your Profile class.

In helpers/aws_helper.rb:

module MyHelpers # choose a better name of course

  def aws_asset( path )
    File.join settings.asset_host, path
  end
end

In app.rb:

class Profile < Sinatra::Base

  helpers MyHelpers # include your helpers here

  get '/' do
    erb :index
  end
end

Upvotes: 2

Related Questions