سؤال

أرغب في "إضافة" بعض التعليمات البرمجية على طريقة النموذج عبر وحدة نمطية ، عندما يتم تضمينها. أعتقد أنني يجب أن أستخدم alias_method_chain ، لكنني لا أعرف كيفية استخدامه ، لأن "طريقتي المستعارة" هي واحدة من تلك الطرق التي تنتهي في علامة "=":

class MyModel < ActiveRecord::Base

  def foo=(value)
    ... do stuff with value
  end

end

لذلك هذا ما تبدو عليه الوحدة النمطية الآن:

module MyModule
  def self.included(base)
    base.send(:include, InstanceMethods)
    base.class_eval do

      alias_method_chain 'foo=', :bar

    end
  end

  module InstanceMethods
    def foo=_with_bar(value) # ERROR HERE
      ... do more stuff with value
    end
  end
end

أحصل على خطأ في تعريف الوظيفة. كيف تجول هذا؟

هل كانت مفيدة؟

المحلول

alias_method_chain هي طريقة بسيطة من خطين:

def alias_method_chain( target, feature )
  alias_method "#{target}_without_#{feature}", target
  alias_method target, "#{target}_with_#{feature}"
end

أعتقد أن الإجابة التي تريدها هي ببساطة صنع الاثنين alias_method يدعو نفسك في هذه الحالة:

alias_method :foo_without_bar=, :foo=
alias_method :foo=, :foo_with_bar=

وسوف تحدد طريقتك مثل ذلك:

def foo_with_bar=(value)
  ...
end

تقوم رموز روبي بعملية Tralling = و ? من أسماء الأسلوب دون مشكلة.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top