【问题标题】:Rails - finding the right place for common codeRails - 为通用代码找到合适的位置
【发布时间】:2012-08-01 03:05:54
【问题描述】:

我把自己弄糊涂了。我有一些代码可以获取一些图像,将它们组合起来,然后以 .png 格式输出组合图像。

最初,此代码是模型的一种方法 - 模型的关联指示要使用哪些图像。因此:

class Component < Refinery::Core::BaseModel  
    drawing_accessor :drawing
  . . .
end

class Photo < Refinery::Core::BaseModel
  has_and_belongs_to_many :components
  has_many :drawings, :through=>:components

  def diagram
    . . . .
    Base64.encode64(png.to_blob)    #spit out the png as a base64 encoded string
  end
end

在一个视图中我可以写

  <img src="data:image/png;base64,<%=@photo.diagram%>"

现在,我需要直接从组件 ID 列表中进行相同的图像组合。由于组件 ID 尚未保存到照片中(可能不会),我需要将此代码移出照片模型。

我希望能够使用作为组件 ID 列表(数组或集合)的参数调用相同的绘图代码,无论它们来自何处。

似乎图表来自一组组件,它应该属于组件......某处。

在我的各种尝试中,我最终以 undefined method 为 ActiveRecord::Relation 或数组。

你能帮我澄清一下我对这段代码的归属以及如何调用它的想法吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails code-organization view-helpers


    【解决方案1】:

    我相信 rails 中的 compass gem 可以满足您的目的。 指南针和 css 精灵请参考 Rail Casts

    【讨论】:

    • 谢谢,但我放在一起的图像不是精灵(或精灵)。它们也有数百个,所以这也意味着它们可能不适合作为精灵。
    【解决方案2】:

    嗯,发帖的力量又来了。

    我为组件集合添加了一条新路由:

      resources :components do
        collection do
          get :draw
        end
      end
    

    在控制器中有匹配的定义

    def draw                 
      send_data Component.construct(params[:list],params[:width], params[:height]), :type => 'image/png', :disposition => 'inline'
    end  
    

    以及模型上绘制组件的方法

      def self.construct(component_list, width, height)
      . . . 
        Base64.encode64(png.to_blob)    #spit out the png as a base64 encoded string
      end 
    

    Photo 模型包含一个将组件列表拉到一起然后调用构造的方法:

      def diagram
        component_list = []
        # construct the list of ids in the right order (bottom to top, or base to capital)
        ....
        Component.construct(component_list, self.image.width, self.image.height)
      end
    

    我可以通过 javascript 调用

    var component_list = $("input:checked").map(function(){return this.value}).get();
    . . . 
    $.get(url,{list:component_list, width:width, height:height}, function(data) {
      $('img.drawing').attr("src","data:image/png;base64," + data);
    })
    

    我仍然对将方法包含在模型中而不是在视图或视图助手中的某个位置存有疑问,但这似乎确实有效!

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-19
      • 1970-01-01
      • 2016-07-19
      • 2021-01-12
      相关资源
      最近更新 更多