Class variable in Concern Rails 4 -
i created concern encapsulate logic upload images resources of application, let's example there's image associated each course, , same every user.
module picturable extend activesupport::concern included path_image = file.join rails.root,"public","#{table_name}_imgs" after_save :save_image end def photo=(file) unless file.blank? @file = file self.extension = file.original_filename.split(".").last.downcase end end def path_image file.join path_image, "#{self.id}.#{self.extension}" end def path_img "/#{self.class.table_name}_imgs/#{self.id}.#{self.extension}" end def has_image? file.exists? path_image end private def save_image unless @file.nil? fileutils.mkdir_p path_image file.open(path_image, "wb") |f| f.write(@file.read) end @file =nil end end end
i have edited code because of methods in spanish, concern works expected problem table_name variable, haven't been able understand how value changes, gets value of users, value of courses, of course errors because framework search image of users in folder of courses , vice versa.
the way i'm including concern looks follow:
class course < activerecord::base include picturable end
i want include concern in each model going have in image associated, need save images in different folders representing each 1 of resources, let's users images should saved in users_imgs folder, , courses's images should saved in courses_imgs , on.
any clue in doing wrong or if approach wrong one.
here error explained rails console:
thanks
the problem constant within included
block being overwritten. can around using method instead of constant. here's example i've defined method called image_root_path
replaces constant.
module picturable extend activesupport::concern included after_save :save_image end def image_root_path file.join rails.root,"public","#{self.class.table_name}_imgs" end def path_image file.join image_root_path, "#{self.id}.#{self.extension}" end # ... private def save_image unless @file.nil? fileutils.mkdir_p image_root_path file.open(path_image, "wb") |f| f.write(@file.read) end @file =nil end end end
Comments
Post a Comment