bjork24
bjork24

Reputation: 3183

Calling a helper method from a route in Sinatra

I've set up a simple Sinatra app based on this excellent SO answer. My code is working and looks like this:

# app.rb
require 'sinatra'

class MyApp < Sinatra::Application

  set :public_folder, Proc.new { File.join(root, "app/public") }
  set :views, Proc.new { File.join(root, "app/views") }

  register Sinatra::Namespace
  register Sinatra::Flash
  enable :sessions

end

require_relative 'app/helpers/init'
require_relative 'app/models/init'
require_relative 'app/routes/init'

Then I have a dirty image uploader in a helper, which is being required in app/helpers/init.rb

# app/helpers/image.rb
require 'imgur'

module ImageUploader

  def save(image)
    @filename = image[:filename]
    file = image[:tempfile]
    File.open("#{ENV['PHOTO_TMP_DIR']}/#{@filename}", 'wb') do |f|
      f.write(file.read)
      upload(@filename)
    end
  end

  def upload(filename)
    client = Imgur.new(ENV['IMGUR_CLIENT_ID'])
    image = Imgur::LocalImage.new("#{ENV['PHOTO_TMP_DIR']}/#{@filename}")
    uploaded = client.upload(image)
    File.delete("#{ENV['PHOTO_TMP_DIR']}/#{@filename}")
    uploaded.link
  end

end

And I'm successfully calling the save method in my app/routes/admin.rb file, like so:

# app/routes/admin.rb
class MyApp < Sinatra::Application
  ...
  imgur_url = save(params[:image])
  ...
end

The problem is that save method name is so generic. I've tried calling with ImageUploader::save and ImageUploader.save, but they both throw errors. Is there another way I can call this helper method and have it namespaced to the helper module?

I should note that I'm loading the helper method like this:

# app/helpers/init.rb
require_relative 'image'
MyApp.helpers ImageUploader

Upvotes: 1

Views: 1753

Answers (1)

bjork24
bjork24

Reputation: 3183

Figured it out! To namespace the module methods, put self in front of the method name. Now doing:

# app/helpers/image.rb
require 'imgur'

module ImageUploader

  def self.save(image)
    @filename = image[:filename]
    file = image[:tempfile]
    File.open("#{ENV['PHOTO_TMP_DIR']}/#{@filename}", 'wb') do |f|
      f.write(file.read)
      upload(@filename)
    end
  end

  def self.upload(filename)
    client = Imgur.new(ENV['IMGUR_CLIENT_ID'])
    image = Imgur::LocalImage.new("#{ENV['PHOTO_TMP_DIR']}/#{@filename}")
    uploaded = client.upload(image)
    File.delete("#{ENV['PHOTO_TMP_DIR']}/#{@filename}")
    uploaded.link
  end

end

Allows me to call ImageUploader.save without any errors.

Upvotes: 2

Related Questions