如何在Rails中的ruby中实现哈希值

mroth7684

我将继续前进并向我道歉,因为我是红宝石和Rails的新手,我一生都无法弄清楚如何在项目中使用hashid来实现。该项目是一个简单的图像主机。我已经使用Base58对其进行编码,以对sql ID进行编码,然后在控制器中对其进行解码。但是我想使URL更加随机,因此切换到hashid。

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

现在,有些混乱从这里开始。我是否需要在通过以下方式使用hashids.encode和hashids.decode的每个页面上初始化哈希值?

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

在我的控制器中,我有:

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视图中有这个:

<%
   @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运行库中将其作为gem加载bundle install这将节省您在每个文件中都需要它的麻烦,并允许您使用Bundler管理更新。

是的,您需要在将其与相同盐一起使用的任何地方进行初始化。建议您将盐定义为常数,也许在中application.rb

您提供的链接将hashids注入ActiveRecord,这意味着它将在其他任何地方都无法使用。我不建议使用相同的方法,因为它将需要对Rails有高度的了解。

您可能需要花一些时间来了解ActiveRecord和ActiveModel。将为您省去大量重新发明轮子的麻烦。:)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在Ruby中从数组的哈希值的哈希值构建哈希值的哈希值

如何在Ruby on Rails中实现RESTful?

如何在Ruby on Rails中实现CardDAV

如何在Rails中的ruby中添加和合并来自不同哈希数组的值

如何在Ruby中深度嵌套的哈希中访问值?

如何在 Ruby on rails 中创建动态哈希数组

如何在Rails / Ruby中获取完整的URL(包括哈希)

如何在 Ruby On Rails 上的 ActiveRecord 列中插入哈希

如何在Ruby中以null作为值读取哈希?

如何在Ruby哈希中动态设置嵌套键的值

Ruby_如何在哈希中查找值订阅

如何在Rails中的ruby中实现递归删除?

如何在ruby中按哈希值在哈希数组中搜索?

如何在Ruby on Rails中实现复杂的SQL查询?

我应该如何在Rails中实现我的Ruby代码?

如何在Ruby on Rails中实现异步付款调用

Ruby如何检查嵌套哈希中的值?

RUBY:如何匹配哈希中的nil值

如何在 Ruby on Rails 中显示此数组中的值

如何在Ruby on Rails中的params数组中更改值?

如何在Ruby中遍历部分哈希

如何在Ruby中复制哈希?

如何在 Ruby 中打印哈希数据

如何在Ruby中建立目录名作为键的哈希值和文件名作为值的哈希值?

如何在Rails的哈希中拆分密钥?

如何在Rails中对哈希进行排序

如何在 Ruby on Rails 中检索链接的值

ruby on rails slim如何在select中处理值

如何在Rails 4的ActiveRecord查询中的哈希(attr_accessor)中获取计算值?