0

我把自己弄糊涂了。我有一些代码可以获取一些图像,将它们组合起来,然后以 .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 或一个数组。

你能帮助澄清我关于这段代码属于哪里以及如何调用它的想法吗?

谢谢

4

2 回答 2

0

我相信导轨中的指南针宝石只会满足您的目的。有关指南针和 css 精灵,请参阅Rail Casts

于 2012-08-01T06:58:06.977 回答
0

嗯,发帖的力量又来了。

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

  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);
})

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

于 2012-08-02T05:46:22.317 回答