新手问题 version

xiaoronglv · 2012年08月21日 · 最后由 xiaoronglv 回复于 2012年08月22日 · 2165 次阅读

看了@poshboytl 上传附件的一段视频,有一段代码的书写格式从未见过。

谁能指点一下,我现在连相关文档都找不到。

http://railscasts-china.com/episodes/9-file-uploading-by-carrierwave

version :thumb, :if => :image? do
    process :resize_to_fit => [50, 50]
end

这一段代码书写格式好怪啊,version 是什么?方法?block?

version 是方法,:thunb, :if => :image? 是参数,后面的 do ... end 是传递给 version 的 block。

这个方法用来定义一种缩略图。

 def version(name, options = {}, &block)
          name = name.to_sym
          unless versions[name]
            uploader = Class.new(self)
            uploader.versions = {}

            # Define the enable_processing method for versions so they get the
            # value from the parent class unless explicitly overwritten
            uploader.class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.enable_processing(value=nil)
self.enable_processing = value if value
if !@enable_processing.nil?
@enable_processing
else
superclass.enable_processing
end
end
RUBY

            # Add the current version hash to class attribute :versions
            current_version = {}
            current_version[name] = {
              :uploader => uploader,
              :options => options
            }
            self.versions = versions.merge(current_version)

            versions[name][:uploader].version_names += [name]

            class_eval <<-RUBY
def #{name}
versions[:#{name}]
end
RUBY
            # as the processors get the output from the previous processors as their
            # input we must not stack the processors here
            versions[name][:uploader].processors = versions[name][:uploader].processors.dup
            versions[name][:uploader].processors.clear
          end
          versions[name][:uploader].class_eval(&block) if block
          versions[name]
        end

非常感谢两位,原来 version 是个方法。现在总算明白了。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号