輔助方法的設計主要是在視圖中使用,如果我沒有錯。
我確信你的幫助器方法不在你的模型範圍之內,這意味着你需要傳遞給他們屬性來處理。例如:
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
。
有可能其他的方式,但我覺得它靈活且易於編寫和維護:)
我把服務對象之下,我應該怎麼稱呼它什麼樣的目錄? – 2013-03-04 10:36:01
編輯我的答案添加服務對象的例子 – Benj 2013-03-04 10:45:32
很酷 - 這是我期待的那種答案 – 2013-03-04 12:30:22