2013-02-13 58 views
0

當動態創建類方法時,有一種方法可以烘焙 - 在創建時已知的一些參數中?如何動態創建一個帶參數化烘焙的Ruby方法?

我爲自己製作了一個模塊,當我創建模型時,該模塊生成的:slug屬性來自給定的:titlehttps://gist.github.com/firedev/4943289

不過我會想重構這個部分:

def create_slug(title_attr, slug_attr, &block) # generated method 
    self.send(slug_attr) # I have to pass slug_attr from outside 
    ... 
end 

所以我可以擺脫這裏所有的則params的:

self.send :after_initialize do 
    create_slug(title_attr, slug_attr, &block) # I pass attributes from here 
end 

而且具有烤入參數的創建方法,而不是:

def create_slug # this method is generated automatically 
    self.send(:slug) # I want :slug to be baked in 
    ... 
end 

self.send :after_initialize, :create_slug # no attributes 

回答

0

看看這段代碼:https://github.com/oleander/to_param-rb/blob/master/lib/to_param/base.rb

我認爲它是做你想做的。

用法:

class User < ActiveRecord::Base 
    to_param :name 
end 

User.create(name: "Linus").to_param # => "1-linus" 
+0

對不起,沒有,我存儲'slug'在數據庫中,我用它在'to_param'需要的時候。問題是如果有方法將屬性烘焙到方法中。我包含了提供一些背景的代碼。 – firedev 2013-02-13 10:35:05

+0

請不要僅提供一個代碼鏈接。 *當鏈接被破壞時,你的答案几乎毫無價值。請提供鏈接代碼的摘要,說明其原因正確的原因,然後鏈接到完整示例。 – 2013-02-13 14:35:09