0

我有一个调用 find_photos 方法的控制器,向它传递一个查询字符串(文件名)

class BrandingPhoto < ActiveRecord::Base

  def self.find_photos(query)
    require "find"

    found_photos = []

    Find.find("u_photos/photo_browse/photos/") do |img_path|
        # break off just the filename from full path
        img = img_path.split('/').last

        if query.blank? || query.empty?
        # if query is blank, they submitted the form with browse all- return all photos
            found_photos << img
        else
        # otherwise see if the file includes their query and return it
            found_photos << img if img.include?(query)
        end
    end

    found_photos.empty? ? "no results found" : found_photos
  end
end

这只是搜索一个满是照片的目录——没有表支持它。

理想情况下,我希望能够将 find_photos 返回的结果数量限制在 10-15 左右,然后根据需要获取接下来的 10-15 个结果。

我在想执行此操作的代码可能涉及循环 10 次并获取这些文件 - 将最后一个文件名存储在变量中或作为参数,然后将该变量发送回方法,告诉它继续搜索文件名。

这假定文件每次都以相同的顺序循环,并且没有更简单的方法可以完成此操作。

如果有任何建议,我很想听听他们/看一些你如何实现这一点的例子。

谢谢你。

4

2 回答 2

0

对于这个问题,首先想到的是在你退出循环后减少数组。虽然这不适用于大量文件另一种解决方案可能是为数组的大小添加一个中断,即。break if found_photos.length > 10循环内

于 2012-12-14T04:17:35.593 回答
0

做你想做的事并不难,但你需要考虑如何处理在页面加载之间添加或删除的条目、带有 UTF-8 或 Unicode 字符的文件名以及嵌入/父目录。

这是您所说的基础的老式代码:

require 'erb'
require 'sinatra'

get '/list_photos' do

  dir    = params[ :dir    ]
  offset = params[ :offset ].to_i
  num    = params[ :num    ].to_i

  files = Dir.entries(dir).reject{ |fn| fn[/^\./] || File.directory?(File.join(dir, fn)) }
  total_files = files.size

  prev_a = next_a = ''

  if (offset > 0)
    prev_a = "<a href='/list_photos?dir=#{ dir }&num=#{ num }&offset=#{ [ 0, offset - num ].max }'>&lt;&lt; Previous</a>"
  end

  if (offset < total_files)
    next_a = "<a href='/list_photos?dir=#{ dir }&num=#{ num }&offset=#{ [ total_files, offset + num ].min }'>Next &gt;&gt;</a>"
  end

  files_to_display = files[offset, num]

  template = ERB.new <<EOF
<html>
  <head></head>
  <body>
    <table>
    <% files_to_display.each do |f| %>
      <tr><td><%= f %></td></tr>
    <% end %>
    </table>
    <%= prev_a %> | <%= total_files %> files | <%= next_a %>
  </body>
</html>
EOF

  content_type 'text/html'
  template.result(binding)

end

它是一个小型 Sinatra 服务器,因此将其另存为test.rb并使用以下命令从命令行运行:

ruby test.rb

在浏览器中,使用如下 URL 连接到正在运行的 Sinatra 服务器:

http://hostname:4567/list_photos?dir=/path/to/image/files&num=10&offset=0

我使用 Sinatra 是为了方便,但例程的核心是你想要的基础。如何将其转换为 Rails 术语留给读者练习。

于 2012-12-14T05:46:10.463 回答