我有一些模型只在其他路径上共享相同的功能。所以我决定将这些方法放在一个模块中并在模型中设置路径。我的问题是我无法访问模块中的属性。
模型:
class Job < ActiveRecord::Base
include ImageModel
image_dir = "jobs"
end
模块:
module ImageModel
extend ActiveSupport::Concern
def delete_image
unless pic_link == "" || pic_link == nil
begin
if File.delete(Rails.root.join("public", "images", image_dir, pic_link))
return true
else
return false
end
rescue
return true #an error occured but when the image does not exist we still return true
end
end
return true
end
def replace_image(new_image)
File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
if f.write new_image.read
delete_image
pic_link = new_image.original_filename
return true #everything went fine
else
return false #return false if new image could not be written
end
end
end
end
我得到的错误:
undefined local variable or method `image_dir' for #<Job:0x007f8a93b9e8d8>
在这一行:
File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
我是否遗漏了某些东西,或者我是否监督过重要的事情?
菲利克斯
答案 0 :(得分:1)
我认为模块的设计仍有改进的余地。但对于这个具体问题,这里是quickfix。
class Job < ActiveRecord::Base
include ImageModel
def image_dir
"jobs"
end
end
答案 1 :(得分:0)
您应该在模块中定义image_dir = "jobs"
。因为你将模块包含在你的模型中,而你的模块无法获得声明,你已经在模型中完成了。
或者您可以更改delete_image
方法以获取参数:
def delete_image(image_dir)
unless pic_link == "" || pic_link == nil
begin
if File.delete(Rails.root.join("public", "images", image_dir, pic_link))
return true
else
return false
end
rescue
return true #an error occured but when the image does not exist we still return true
end
end
return true
end
并且在那里调用该方法,传递这样的参数:
delete_image("jobs")
在replace_image
方法的情况下相同:
def replace_image(new_image, image_dir)
File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
if f.write new_image.read
delete_image
pic_link = new_image.original_filename
return true #everything went fine
else
return false #return false if new image could not be written
end
end
end
希望它会有所帮助。感谢