2015-02-10 46 views
1

我已經基於this excellent SO answer設置了一個簡單的Sinatra應用程序。我的代碼工作,看起來像這樣:在Sinatra中調用一個輔助方法

# 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' 

然後我有一個助手,這是被要求在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 

一個骯髒的圖片上傳而且我成功地調用該方法saveapp/routes/admin.rb文件,像這樣:

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

的問題是,save方法名是很通用。我試着用ImageUploader::saveImageUploader.save打電話,但他們都拋出錯誤。有沒有另一種方法可以調用這個幫助器方法,並將它命名爲輔助器模塊?

我要指出,我加載輔助方法是這樣的:

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

回答

1

想通了!要命名空間模塊方法,請將self放在方法名稱的前面。現在在做:

# 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 

允許我撥打ImageUploader.save沒有任何錯誤。