2014-12-05 68 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