sidegeeks
sidegeeks

Reputation: 1041

Can't access custom helper functions made within the file - Sinatra

I have this helper within my 'app.rb' file, which is used to get the current user object.

helpers do
    def get_current_user(column, value)
        user = User.where(column => value).first
        return user
    end
end

get '/' do
    user = get_current_user(:id, params[:id])
end

This is what i did in irb:

irb(main):001:0> require './app'
=> true
irb(main):007:0> user = get_current_user(:id, 2)
NoMethodError: undefined method `get_current_user' for main:Object
from (irb):7
from /usr/bin/irb:12:in `<main>'

I don't understand why i can't access the helper methods from irb. Should i explicitly include the helpers or something? If so, why? Because i put them under the same file, under the same class.

Upvotes: 1

Views: 372

Answers (1)

pje
pje

Reputation: 22707

get_current_users is metaprogrammed through the helpers method to be an instance method of App. So, if app.rb looks something like this:

require 'sinatra/base'

class App < Sinatra::Base
  helpers do
    def get_current_user
      puts "here!"
    end
  end
end

...then from irb you can invoke get_current_user on an instance of App like this:

>> require './app'
>> App.new!.get_current_user  
here!  
=> nil
>>

(If you're wondering why that's new! and not new like most sane ruby code, read this answer.)

Upvotes: 1

Related Questions