2012-08-01 82 views
0

我已經讓自己頗爲糊塗了。我有一些代碼需要一些圖像,將它們結合起來,然後以.png格式吐出組合圖像。Rails - 尋找普通代碼的正確位置

最初,這段代碼是模型的一種方法 - 模型的關聯指出要使用哪些圖像。因此:

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 

,並在視圖中我可以寫

現在,我需要做同樣的圖像合成的,而是直接從組件ID列表。由於組件ID尚未保存到照片中(可能不是),因此我需要將此代碼移出照片模型。

我希望能夠使用組件ID的列表(數組或集合)的參數調用相同的繪圖代碼,而不管它們來自何處。

看來,由於圖來自一組組件,它應該屬於組件...在某處。

在我的各種嘗試中,我最終得到了一個ActiveRecord :: Relation或者一個Array的undefined method

你能幫我澄清一下這段代碼屬於哪裏以及如何調用它的想法嗎?

謝謝

回答

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 

照片模型包括一個方法,將組件列表拉到一起然後ca LL結構:

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

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

0

我相信軌道中的指南針寶石只是爲您的目的。 請參閱Rail Casts指南針和CSS精靈。

+0

謝謝,但我放在一起的圖像不是精靈(或精靈)。也有數百個,所以這也意味着它們可能不適合作爲精靈。 – 2012-08-01 08:36:47