![](/img/trans.png)
[英]Undefined method `has_attached_file' with paperclip 2.3.8 gem for Rails 2 using Ruby 1.8.7
[英]Ruby on Rails - passing a returned value of a method to has_attached_file. Do I get Ruby syntax wrong?
我正在編寫我的第一個RoR應用程序,目前我正致力於允許用戶上傳圖像。 我正在使用Paperclip來達到這個目的。 其中一個步驟涉及將has_attached_file
添加到我的模型中:
class MyModel < ActiveRecord::Base
#...
has_attached_file :picture, styles: {
large: "120x150#>",
small: "60x75#>"
}
#...
end
如果我這樣做,一切順利(或看起來似乎)。 但是我還需要在其他地方訪問與整數相同的常量值,所以我添加了一個哈希:
class MyModel < ActiveRecord::Base
#...
has_attached_file :picture, styles: {
large: "120x150#>",
small: "60x75#>"
}
def picture_sizes
{
large: {width: 120, height: 150},
small: {width: 60, height: 75}
}
end
#...
end
這會產生丑陋的冗余。 所以我想到編寫一個從第二個哈希生成第一個哈希的方法,就像這樣
class MyModel < ActiveRecord::Base
#...
has_attached_file :picture, styles: picture_sizes_as_strings
def picture_sizes
{
large: {width: 120, height: 150},
small: {width: 60, height: 75}
}
end
def picture_sizes_as_strings
result = {}
picture_sizes.each do |label, size|
result[:label] = "#{size[:width]}x#{size[:height]}#>"
end
return result
end
#...
end
但這會引發一個錯誤:
undefined local variable or method `picture_sizes_as_strings' for #<Class:0x007fdf504d3870>
我究竟做錯了什么?
has_attached_file
在運行時計算。 您已經定義了一個實例方法,但是您沒有從實例上下文中調用該方法。
嘗試:
def self.picture_sizes_as_strings
# code here
end
確保使用self.
定義另一個方法self.
也
接着:
has_attached_file :picture, :styles => picture_sizes_as_strings
應該管用。
問題是你試圖在類級別上運行的聲明( has_attached_image
)中使用實例方法picture_sizes_as_strings
。 這是調用之間的區別
MyModel.picture_sizes_as_strings
和
MyModel.first.picture_sizes_as_strings
在第一種情況下,我們引用一個類方法(MyModel類本身的方法),在第二種情況下,我們引用一個實例方法(單個my_model對象上的方法)。
首先,您必須通過在self.
添加名稱前綴來將方法更改為類方法self.
,所以:
def self.picture_sizes
{
large: {width: 120, height: 150},
small: {width: 60, height: 75}
}
end
現在這還沒有完全解決你的問題,因為當ruby首次解析模型時會處理has_attached_image
。 這意味着它會在你定義self.picture_sizes
之前嘗試運行has_attached_image
,所以它仍會說undefined method
。
您可以通過在has_attached_file
聲明之前放置self.picture_sizes
來解決這個問題,但這非常難看。 您也可以將數據放在常量中,但這有其自身的問題。
老實說,沒有什么方法可以解決這個問題。 如果是我,我可能會顛倒整個過程,將樣式定義為正常,然后使用方法將字符串轉換為整數,如下所示:
class MyModel < ActiveRecord::Base
has_attached_file :picture, styles: {
large: "120x150#>",
small: "60x75#>"
}
def numeric_sizes style
# First find the requested style from Paperclip::Attachment
style = self.picture.styles.detect { |s| s.first == style.to_sym }
# You can consolidate the following into one line, I will split them for ease of reading
# First strip all superfluous characters, we just need the numerics and the 'x' to split them
sizes = style.geometry.gsub(/[^0-9x]/,'')
# Next split the two numbers across the 'x'
sizes = sizes.split('x')
# Finally convert them to actual integer numbers
sizes = sizes.map(&:to_i)
end
end
然后,您可以調用MyModel.first.numeric_sizes(:medium)
來查找特定樣式的大小,並以數組形式返回。 當然你也可以將它們改成哈希或者你需要的任何格式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.