ProgramingTip

모듈에서 'before_save'콜백을 정의 할 수 있습니까?

bestdevel 2020. 12. 4. 19:49
반응형

모듈에서 '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_somethingModel검증이 저장 되기 전에 호출 ? 나는 이렇게 시도했지만 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

참고 URL : https://stackoverflow.com/questions/7444522/is-it-possible-to-define-a-before-save-callback-in-a-module

반응형