关注轨道中的类变量4

时间:2014-03-23 04:04:47

标签: ruby-on-rails ruby-on-rails-4

我创建了一个问题,即封装逻辑以上传我的应用程序的某些资源的图像,例如,假设有一个与每个课程相关联的图像,并且对每个用户都是相同的。

module Picturable
    extend ActiveSupport::Concern
    included do
      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") do |f|

            f.write(@file.read)
        end
        @file =nil
    end
  end
end

我编辑了代码,因为有些方法是西班牙语,关注是按预期工作但问题是 table_name 变量,我无法理解值如何变化,有时它获得用户的价值,有时是课程的价值,但当然有时我会得到错误,因为框架在课程文件夹中搜索用户的图像,反之亦然。

我包括关注点的方式如下:

class Course < ActiveRecord::Base
  include Picturable
end

我想在图像关联的每个模型中包含关注点,但是我需要将图像保存在代表每个资源的不同文件夹中,假设用户图像应该保存在users_imgs文件夹中,和课程的图像应保存在courses_imgs等中。

我在做错什么或者我的方法是错误的任何线索。

以下是使用rails控制台解释的错误: rails console session

由于

1 个答案:

答案 0 :(得分:1)

问题是included块中的常量被覆盖了。你可以通过使用方法而不是常量来解决这个问题。这是一个示例,我已经定义了一个名为image_root_path的方法来替换常量。

module Picturable
  extend ActiveSupport::Concern
  included do
    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") do |f|

        f.write(@file.read)
      end
      @file =nil
    end
  end
end
相关问题