2013-03-04 46 views
0

在我的軌道模型Post.rb我有以下方法設置:Rails 3.2:如何訪問輔助模塊內的當前模型實例?

def category_names(seperator = ", ") 
    categories.map(&:name).flatten.join(seperator).titleize 
    end 

    def publish_date 
    read_attribute(:publish_date).strftime('%A, %b %d') 
    end 

我想這些進入PostsHelper模塊下的幫手。但是當我這樣做的時候得到一個沒有方法的錯誤,因爲我猜想對self的引用丟失了。

那麼我該如何解決這個問題?輔助模塊是否是這些方法的錯誤地方?

回答

2

輔助方法的設計主要是在視圖中使用,如果我沒有錯。

我確信你的幫助器方法不在你的模型範圍之內,這意味着你需要傳遞給他們屬性來處理。例如:

def category_names(categories, seperator = ", ") 
    categories.map(&:name).flatten.join(seperator).titleize 
    end 

並調用視圖:

category_names @post.categories 

如果你發現你的自我寫作「助手」未完全在您的視圖中使用的方法,你可以創建一個服務對象,並將其納入在你的模型中。

編輯:服務對象

您可以創建「應用程序」目錄下的「服務」目錄下,並創建有你的類。

讓我給你舉個例子。我有一個用戶模型類,我想在UserPassword服務對象中分組所有密碼相關的方法。

用戶等級:

class User < ActiveRecord::Base 
    include ::UserPassword 
    ... 
end 

userPassword的服務對象:

require 'bcrypt' 

module UserPassword 
    def encrypt_password 
    if password.present? 
     self.password_salt = BCrypt::Engine.generate_salt 
     self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) 
    end 
    end 

    module ClassMethods 
    def authenticate(email, password) 
     user = find_by_email email 
     if user and user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) 
     user 
     end 
    end 
    end 

    def self.included(base) 
    base.extend(ClassMethods) 
    end 
end 

所以我的用戶實例化對象(即u = User.first)可以打電話u.encrypt_password,和我的用戶可以調用User.authenticate

有可能其他的方式,但我覺得它靈活且易於編寫和維護:)

+0

我把服務對象之下,我應該怎麼稱呼它什麼樣的目錄? – 2013-03-04 10:36:01

+0

編輯我的答案添加服務對象的例子 – Benj 2013-03-04 10:45:32

+0

很酷 - 這是我期待的那種答案 – 2013-03-04 12:30:22

相關問題