반응형
모듈에서 'before_save'콜백을 정의 할 수 있습니까?
before_save
모듈에서 복수를 정의 할 수 있습니까? 다음과 같은 클래스가 있습니다.
class Model
include MongoMapper::Document
include MyModule
end
그리고 다음과 같은 모듈 :
module MyModule
before_save :do_something
def do_something
#do whatever
end
end
do_something
Model
검증이 저장 되기 전에 호출 ? 나는 이렇게 시도했지만 undefined method 'before_save' for MyModule:Module
.
간단한 일이라면 사과드립니다. 저는 Ruby와 Rails를 처음 사용합니다.
Ruby on Rails <3 (Rails 기능 제외, Ruby 만 해당)
module MyModule
def self.included(base)
base.class_eval do
before_save :do_something
end
end
def do_something
#do whatever
end
end
Ruby on Rails> = 3 (레일 Concern
기능 포함)
module MyModule
extend ActiveSupport::Concern
included do
before_save :do_something
end
def do_something
#do whatever
end
end
모듈의 included
방법이 필요할 수 있습니다.
http://www.ruby-doc.org/core-2.1.2/Module.html#method-i-included
ActiveSupport :: Concern (실제로 그리고 그것 없이도 가능하지만 더 명확하고 선호 됨)
require 'active_support/concern'
module MyModule
extend ActiveSupport::Concern
included do
# relations, callbacks, validations, scopes and others...
end
# instance methods
module ClassMethods
# class methods
end
end
반응형
'ProgramingTip' 카테고리의 다른 글
하나의 LINQ 쿼리에서 두 열의 가져 오기 오기 (0) | 2020.12.04 |
---|---|
asp.net mvc 3 면도기보기에서 reportviewer 컨트롤을 어떻게 사용할 수 있습니까? (0) | 2020.12.04 |
이 C ++ 코드에서 여기서 무슨 일이 일어나고 있습니까? (0) | 2020.12.04 |
날짜에서 요일 이름을 얻는 방법은 무엇입니까? (0) | 2020.12.04 |
전송 속도와 비트 전송률의 차이점은 무엇입니까? (0) | 2020.12.04 |