簡體   English   中英

導軌 - 尋找共同的代碼正確的地方

[英]Rails - finding the right place for common code

我很困惑。 我有一些代碼這需要一些圖像,將它們組合,然后以.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 ::關系,或為陣。

你能幫我澄清什么地方該碼屬於和如何調用它的想法?

謝謝

我相信羅盤中的指南針寶石只會滿足您的目的。 有關指南針和CSS精靈,請參閱Rail Casts

好吧,發布的力量再次受到打擊。

我為組件集合添加了一條新路線:

  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 

照片模型包括拉在一起的組件列表然后調用構建體的方法:

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

我仍然對包括在模型的方法,並在視圖或視圖助手不顯山露水的疑慮,但這似乎工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM