我已根据this excellent SO answer设置了一个简单的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
,但他们都会抛出错误。有没有其他方法可以调用这个帮助器方法并将其命名为辅助模块?</ p>
我应该注意,我正在加载这样的辅助方法:
# app/helpers/init.rb
require_relative 'image'
MyApp.helpers ImageUploader
答案 0 :(得分: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
。