2014-12-05 39 views
1

Hy。我是Ruby on Rails和OOP的新手。

我就有點調度工作,要幹我的模型方法。
我衝過一些關於Rails中Module和Class的用法,但是找不到什麼是最好的方法。
difference-between-a-class-and-a-module
ruby-class-module-mixins如何在Ruby on Rails中按模塊或類DRY重複的模型方法?

實施例:

假設我有2個模型(基準和人)。
每個模型都有一個屬性,該屬性存儲日期,但具有不同的屬性名稱。

我寫了兩個模塊的日期驗證的方法相同。

我的模型:

class Datum < ActiveRecord::Base 
attr :start_date 

def validate_date 
    # same validation stuff with self.start_at 
end 
end 


class Person < ActiveRecord::Base 
attr :birth_date 

def validate_date 
    # same validation stuff with self.birth_date 
end 
end 


這是我嘗試用一​​個lib/ModelHelper和基準型號:

class Datum < ActiveRecord::Base 
include ModelHelper 

attr_accessible :start_at 

# Validations 
before_validation :validate_date, :start_at 

end 


module ModelHelper 

private 

def validate_date *var 
    # validation stuff with birth_date and start_at 
end 
end 


問:
在我的情況,我想我需要指定一個參數(對於每個模型屬性:start_at和:bith_date)。
但我無法發現如何。

什麼是幹我的模型,以模塊或類的最佳方式?
爲什麼和怎麼樣?

+0

我強烈建議你檢查出codereview.stackexchange.com – Anthony 2014-12-05 14:23:31

+1

順便說一句,我最近發表回答CodeReview.SE關於自定義Rails 4驗證器:http://codereview.stackexchange.com/questions/71435/reservation-validation/71496#71496 – 2014-12-05 14:25:53

+0

@Anthony我的問題不僅僅是代碼審查。 更多關於理解Ruby on Rails中的Module和Class的內容,同時給出一個示例。 – stephanfriedrich 2014-12-05 15:11:20

回答

0

就像@D方在評論中說的,你最好的選擇是創建一個Custom Validator

創建應用程序/驗證器目錄與名稱添加文件像my_date_validator.rb和內容是這樣的:

# EachValidator is a validator which iterates through the attributes given in the 
# options hash invoking the validate_each method passing in the record, attribute 
# and value. 
# 
# All Active Model validations are built on top of this validator. 
# 
class MyDateValidator < ActiveModel::EachValidator 
    def validate_each(record, attribute, value) 
    unless value_is_valid? # <- validate in here. 
     record.errors[attribute] << (options[:message] || "is not a valid date") 
    end 
    end 
end 

,並在您的模型只需添加:

class Datum < ActiveRecord::Base 
    validates :start_date, my_date: true 
end 

class Person < ActiveRecord::Base 
    validates :birth_date, my_date: true 
end 

my_date代表的指明MyDate Validator類名的第一部分。

如果你的名字你驗證:

  • FooValidator那麼你用它在你的模型驗證爲Foo。
  • FooBarValidator然後在模型驗證中將其用作foo_bar。
  • MyDateValidator然後在模型驗證中用它作爲my_date。

此外,根據您要驗證你可能想看看這個寶石是什麼:

https://github.com/johncarney/validates_timeliness

+0

在這裏添加一些引用:應用特定的驗證器的首選位置是'app/validators',https://github.com/bbatsov/rails-style-guide/blob/master/README.md#app-validators – 2014-12-05 19:12:40

+0

謝謝爲你的迴應。但爲什麼你不使用模型? – stephanfriedrich 2014-12-05 19:48:28

+0

或在您的示例/導軌指南。如果 我嘗試使用更多自定義驗證器(我應該爲每個驗證器c類編寫) – stephanfriedrich 2014-12-05 20:13:06