And*_*rew 19 alias ruby-on-rails shortcut ruby-on-rails-3
-编辑-
在从第一个答案中读到Delegate方法之后,我的问题是,是否可以将两种不同的方法委托给另一种方法.
IE:我目前有:@ photo.attachment.file.url和@ photo.attachment.height,以及@ photo.attachment.width
我希望能够通过@ photo.file.url,@ photo.file.height,@ photo.file.width访问所有这些内容.
语法的原因是Attachment是一个使用Paperclip管理文件的模型,Paperclip正在生成.file方法(该模型称为Attachment,模型使用Paperclip has_attached_file :file).
-ORIGINAL问题 -
我想知道Ruby中的别名方法和属性(我认为这是一个常见的ruby问题,尽管我的应用程序在Rails 3中):
我有两个模特:照片has_one附件.
附件具有"高度"和"宽度"属性,以及"文件"方法(来自Paperclip).
所以默认情况下,我可以访问Attachment模型的位,如下所示:
photo.attachment.width # returns width in px
photo.attachment.height # returns height in px
photo.attachment.file # returns file path
photo.attachment.file.url #returns url for the default style variant of the image
photo.attachment.file.url(:style) #returns the url for a given style variant of the image
Run Code Online (Sandbox Code Playgroud)
现在,在我的照片类中,我创建了这个方法:
def file(*args)
attachment.file(*args)
end
Run Code Online (Sandbox Code Playgroud)
那么,现在我可以简单地使用:
photo.file # returns file path
photo.file.url # returns file url (or variant url if you pass a style symbol)
Run Code Online (Sandbox Code Playgroud)
我的问题是,我能够直接photo.attachment.file指向photo.file,但我还可以将高度和宽度映射到photo.file,这样,为了保持一致性,我可以通过photo.file.height和访问高度和宽度属性photo.file.width?
这样的事情是否可能,如果是这样,它看起来像什么?
nat*_*vda 53
所以你要问的是那个
photo.file --> photo.attachment.file
photo.file.url --> photo.attachment.file.url
photo.file.width --> photo.attachment.width
Run Code Online (Sandbox Code Playgroud)
你不能用代表解决这个问题,因为你希望file根据下面的内容来表示不同的东西.要实现这一点,你需要重新打开回形针,我不推荐(因为我相信api是好的方式).
我能想到解决这个问题的唯一方法就是增加消除file水平.像这样:
photo.width --> photo.attachment.width
photo.file --> photo.attachment.file
photo.url --> photo.attachment.file.url
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过delegate对每个想要的方法使用a 来解决.
所以你写
class Photo
delegate :width, :height, :file, :to => :attachment
delegate :url, :to => :'attachment.file'
end
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.