ruby - 我如何在 ruby​​ on rails 中实现 hashids

标签 ruby ruby-on-rails-4 hashids

我会先行道歉,因为我是 ruby​​ 和 rails 的新手,而且我这辈子都想不出如何在我的项目中使用 hashids 来实现。该项目是一个简单的图像宿主。我已经使用 Base58 对 sql ID 进行编码,然后在 Controller 中对其进行解码。但是我想让 URL 更随机,因此切换到 hashids。

我已将 hashids.rb 文件放在我的 lib 目录中:https://github.com/peterhellberg/hashids.rb

现在有些困惑是从这里开始的。我是否需要在每个使用 hashids.encode 和 hashids.decode 的页面上初始化 hashids

hashids = Hashids.new("mysalt")

我发现这篇文章 ( http://zogovic.com/post/75234760043/youtube-like-ids-for-your-activerecord-models ) 让我相信我可以将它放入初始化程序中,但是在这样做之后我仍然收到 NameError(ImageManager:Class 的未定义局部变量或方法“hashids”)

所以在我的 ImageManager.rb 类中有

require 'hashids'

class ImageManager
class << self
def save_image(imgpath, name)

  mime = %x(/usr/bin/exiftool -MIMEType #{imgpath})[34..-1].rstrip
  if mime.nil? || !VALID_MIME.include?(mime)
    return { status: 'failure', message: "#{name} uses an invalid format." }
  end

  hash = Digest::MD5.file(imgpath).hexdigest
  image = Image.find_by_imghash(hash)

  if image.nil?
    image = Image.new
    image.mimetype = mime
    image.imghash = hash
    unless image.save!
      return { status: 'failure', message: "Failed to save #{name}." }
    end

    unless File.directory?(Rails.root.join('uploads'))
      Dir.mkdir(Rails.root.join('uploads'))
    end
    #File.open(Rails.root.join('uploads', "#{Base58.encode(image.id)}.png"), 'wb') { |f| f.write(File.open(imgpath, 'rb').read) }
    File.open(Rails.root.join('uploads', "#{hashids.encode(image.id)}.png"), 'wb') { |f| f.write(File.open(imgpath, 'rb').read) }
  end

  link = ImageLink.new
  link.image = image
  link.save

#return { status: 'success', message: Base58.encode(link.id) }
return { status: 'success', message: hashids.encode(link.id) }
end

private

    VALID_MIME = %w(image/png image/jpeg image/gif)
  end
end

在我的 Controller 中我有:

require 'hashids'

class MainController < ApplicationController
MAX_FILE_SIZE = 10 * 1024 * 1024
MAX_CACHE_SIZE = 128 * 1024 * 1024

@links = Hash.new
@files = Hash.new
@tstamps = Hash.new
@sizes = Hash.new
@cache_size = 0

class << self
  attr_accessor :links
  attr_accessor :files
  attr_accessor :tstamps
  attr_accessor :sizes
  attr_accessor :cache_size
  attr_accessor :hashids
end

def index
end

def transparency
end

def image
  #@imglist = params[:id].split(',').map{ |id| ImageLink.find(Base58.decode(id)) }
  @imglist = params[:id].split(',').map{ |id| ImageLink.find(hashids.decode(id)) }
end

def image_direct
  #linkid = Base58.decode(params[:id])
  linkid = hashids.decode(params[:id])

  file =
    if Rails.env.production?
      puts "#{Base58.encode(ImageLink.find(linkid).image.id)}.png"
      File.open(Rails.root.join('uploads', "#{Base58.encode(ImageLink.find(linkid).image.id)}.png"), 'rb') { |f| f.read }
    else
      puts "#{hashids.encode(ImageLink.find(linkid).image.id)}.png"
      File.open(Rails.root.join('uploads', "#{hashids.encode(ImageLink.find(linkid).image.id)}.png"), 'rb') { |f| f.read }
    end

  send_data(file, type: ImageLink.find(linkid).image.mimetype, disposition: 'inline')
end

def upload
  imgparam = params[:image]

  if imgparam.is_a?(String)
    name = File.basename(imgparam)
    imgpath = save_to_tempfile(imgparam).path
  else
    name = imgparam.original_filename
    imgpath = imgparam.tempfile.path
  end

  File.chmod(0666, imgpath)
  %x(/usr/bin/exiftool -all= -overwrite_original #{imgpath})
  logger.debug %x(which exiftool)
  render json: ImageManager.save_image(imgpath, name)
end

private

  def save_to_tempfile(url)
  uri = URI.parse(url)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = uri.scheme == 'https'
  http.start do
    resp = http.get(uri.path)
    file = Tempfile.new('urlupload', Dir.tmpdir, :encoding => 'ascii-8bit')
    file.write(resp.body)
    file.flush
    return file
  end
end
end

然后在我的 image.html.erb View 中我有这个:

<%
   @imglist.each_with_index { |link, i|
   id = hashids.encode(link.id)
   ext = link.image.mimetype.split('/')[1]
   if ext == 'jpeg'
     ext = 'jpg'
   end
   puts id + '.' + ext
%>

现在如果我添加

hashids = Hashids.new("mysalt")

在 ImageManager.rb main_controller.rb 和我的 image.html.erb 中我收到这个错误:

ActionView::Template::Error (undefined method `id' for #<Array:0x000000062f69c0>)

所以总的来说,实现 hashids.encode/decode 并不像实现 Base58.encode/decode 那样容易,我对如何让它工作感到困惑...任何帮助将不胜感激。

最佳答案

我建议通过将其包含到您的 Gemfile 并运行 bundle install 来将其加载为 gem。它将为您省去在每个文件中都需要它的麻烦,并允许您使用 Bundler 管理更新。

是的,无论在哪里使用相同的盐,您都需要对其进行初始化。建议您将盐定义为常量,也许在 application.rb 中。

您提供的链接将 hashids 注入(inject)到 ActiveRecord 中,这意味着它在其他任何地方都不起作用。我不推荐使用相同的方法,因为它需要非常熟悉 Rails。

您可能想花一些时间了解 ActiveRecord 和 ActiveModel。将为您节省大量重新发明轮子的时间。 :)

关于ruby - 我如何在 ruby​​ on rails 中实现 hashids,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32288671/

相关文章:

ruby-on-rails - 运行 "bundle install"失败,让我运行 "bundle install"

ruby - Selenium Webdriver - Ruby 不支持的命令

javascript - will_paginate 无限滚动 | Rails4

c - 如何在 C 中哈希 CPU ID

php - 在 Laravel 5.2 中使用 vinkla/hashids 包

ruby - 传递不存在的参数

ruby-on-rails - 如何使用 Rails 6/Zeitwerk 在 Rails 初始化器中预加载关注点?

python - 从数据库中获取主键(Python/Django)

ruby-on-rails - 使用 RSpec 测试模型时出现错误 "undefined method ` <' for nil:NilClass"。

heroku - 尝试了几个修复: Heroku/Rails 4 Assets Precompile Error