从Sinatra的路线呼叫辅助方法

时间:2015-02-10 03:40:30

标签: ruby sinatra

我已根据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::saveImageUploader.save,但他们都会抛出错误。有没有其他方法可以调用这个帮助器方法并将其命名为辅助模块?<​​/ p>

我应该注意,我正在加载这样的辅助方法:

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

1 个答案:

答案 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