I have some models which share the same functionality just on other paths. So I decided to put these methods in a module and set the path in the model. My problem is that I'm not able to access the attribute in my module.
model:
class Job < ActiveRecord::Base
include ImageModel
image_dir = "jobs"
end
module:
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
The error i get:
undefined local variable or method `image_dir' for #<Job:0x007f8a93b9e8d8>
on this line:
File.open(Rails.root.join("public", "images", image_dir, new_image.original_filename), "wb") do |f|
Did I miss something or did I oversee something important?
Felix
I think the design of module still have room to improve. But for this specific question, here is the quickfix.
class Job < ActiveRecord::Base
include ImageModel
def image_dir
"jobs"
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With