Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Làm chủ Phương thức Hook Inherited của Ruby: Mẹo Nâng cao cho Developer

Xin chào children and parents, ahem Rubyists. Trong bài trước, chúng ta dive vào ancestry chain. Hôm nay, dive deeper vào parenting và inheritance. Chúng ta sẽ explore inherited hook method và nhìn vào preventing inheritance.

Khi Con Kế Thừa 101: Inherited Hook Method

Bắt đầu xem parenthood declared như thế nào. Ruby cung cấp cách neat interact với class khi nó declared là parent của class khác.

class Parent
  def self.inherited(subclass)
    puts "#{subclass} inherits from Parent"
  end
end

class Child < Parent
end

Chạy code in ra "Child inherits from Parent", vì Parent.inherited được gọi khi Child inherit từ Parent. Lưu ý method này nhận subclass làm parameter — Child trong case của chúng ta. Cơ chế này cho phép interact với Parent class để define set of behaviors chỉ khi nó bị inherit. Bởi behavior, trong context này, nghĩa là modify, define hoặc delete variables, methods, constants trên inheriting hoặc inherited class.

Bây giờ, define method parent_name on-the-fly:

class Parent
  def self.inherited(subclass)
    subclass.define_method :parent_name do
      "Daddy"
    end
  end
end

class Child < Parent
end

Child.new.parent_name #=> "Daddy"

Ở đây, define method trên class Child khi nó inherit từ Parent, nhưng không add method đó trực tiếp vào class Parent. Thay vào đó, chỉ define khi class khác inherit từ Parent.

Được, covered theory, xem ví dụ realistic hơn trong đời Rubyist.

Ngăn Chặn Class Inheritance

Trong Ruby on Rails, database migrations handled bởi class ActiveRecord::Migration. Thử directly inherit từ class này.

class AddFirstnameToUsers < ActiveRecord::Migration
end
# => StandardError (Directly inheriting from ActiveRecord::Migration is not supported..)

Error raised vì Rails cung cấp mechanism ngăn inherit từ class này. Tại sao Rails implement mechanism này?

Migration strongly coupled với specific version của Ruby on Rails. API của class này có thể thay đổi nhẹ giữa 2 version. Để tránh break migrations khi upgrade Rails, framework force bạn chọn specific version của ActiveRecord::Migration. Điều này đảm bảo migrations chạy smooth.

class AddFirstnameToUsers < ActiveRecord::Migration[4.2]
end

Trong ví dụ, migration coupled với ActiveRecord::Migration API từ version 4.2. Vậy dù upgrade app lên 5.0, migrations vẫn chạy smooth vì vẫn chạy với version 4.2 của ActiveRecord::Migration API.

Cơ Chế Ngăn Chặn Inheritance Hoạt Động Như Thế Nào

Bây giờ hiểu tại sao inheritance bị prevent, xem làm sao ActiveRecord::Migration prevent inheritance. Logic định nghĩa trong ActiveRecord::Migration.inherited.

class AddFirstnameToUsers < ActiveRecord::Migration[4.2]
end

Khi AddFirstnameToUsers inherit từ ActiveRecord::Migration, hook method ActiveRecord::Migration.inherited được gọi.

module ActiveRecord
  class Migration
    def self.inherited(subclass)
      #:nodoc:
      super if subclass.superclass == Migration
      raise StandardError, "Directly inheriting from ActiveRecord::Migration is not supported. " \
        "Please specify the Rails release the migration was written for:\n" \
        "\n" \
        " class #{subclass} < ActiveRecord::Migration[4.2]"
    end
  end
end

Nhìn thấy, hook method check nếu subclass (AddFirstnameToUsers) directly inherit từ ActiveRecord::Migration. Nếu có, raise error. Đây là entry point hoàn hảo để control inheritance.

Kết luận

Hôm nay, cover basics của inheritance và preventing inheritance. Cover inherited hook method và thấy nó handy khi interact với inheriting/inherited class on-the-fly.

Trong real-world setting, watch out khi chơi với inheritance. Rất cautious khi remove hoặc override existing method/class. Có thể dẫn đến unwanted side effects. Children có thể ngừng gọi bạn là daddy.

Et Voilà, kết thúc bài hôm nay!