0

何かを成し遂げるために、モジュールとクラスをいじっています。

私が使用した継承を一切行わずに MyClass を起動するとclass MyClass::A4.generate、A4 が format 関数をオーバーライドします。

A4はこんな感じです。

class A4 < MyClass
  def somefunction
    format = { :width => 200, :height => 100 }
  end
end

しかし今、私は複数のクラスを (さまざまな種類のファイルを生成して) いくつかの形式に作成したいと考えています。

私の最初の試みはclass MyClass < AnotherClass.

2 番目の試行は、もう少し Ruby に似ています。

module AnotherModule
 def somefunction
   format = { :width => 50 }
 end
end

class MyClass
  include AnotherModule
  def initialize
  end
  ......
end

このようなことは可能ですか?

class A4 < AnotherModule
  def somefunction
    format = { :width => 200, :height => 100 }
  end
end

MyClass::A4.new.generate

もしそうなら、どのように?

4

2 に答える 2

2

私はあなたのネーミングが気に入らなかったので、これからはあなたが呼んだものとあなたが呼んだものAfileと呼ばせてください。MyClassPrintSettingsAnotherModule

PrintSettingsがあり、このように定義されているA4と仮定しますAfile

module PrintSettings
  # stuff
end

module A4
end

class Afile
  include PrintSettings
end

そして今、動的にインクルードしたいA4(重要なのA4はクラスではなくモジュールです)、内部のどこかで次のことを行うことができますAfile

extend format

# example:

class Afile
  include PrintSettings

  def format=(new_format)
    extend new_format
  end
end

# and then using like:

file = Afile.new
file.format = A4

つまり、クラスを定義するときにモジュールを混在させたい場合は を使用しinclude、オブジェクトがあり、そのオブジェクトにモジュールを拡張させたい場合は を使用しますextend

于 2012-12-27T12:40:37.633 に答える
0

あなたの質問を正しく理解していれば、

class A4 < AnotherModule
end

MyClass::A4.new.generate

上記のコードは期待どおりに実行されます。cos A4 クラスは、すべてのメソッドAnotherModuleを A4 の静的メソッドとして作成するモジュールを拡張しています。

generate がモジュール AnotherModule によって与えられたメソッドである場合、

`MyClass::A4.generate` will work.

http://railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/

お役に立てれば。

于 2012-12-27T11:04:07.557 に答える