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
一個骯髒的圖片上傳而且我成功地調用該方法save
我app/routes/admin.rb
文件,像這樣:
# app/routes/admin.rb
class MyApp < Sinatra::Application
...
imgur_url = save(params[:image])
...
end
的問題是,save
方法名是很通用。我試着用ImageUploader::save
和ImageUploader.save
打電話,但他們都拋出錯誤。有沒有另一種方法可以調用這個幫助器方法,並將它命名爲輔助器模塊?
我要指出,我加載輔助方法是這樣的:
# app/helpers/init.rb
require_relative 'image'
MyApp.helpers ImageUploader