サブクラスからの一連の一般的なコードをスーパークラスメソッドに分解したいと思います。スーパークラスメソッドは、サブクラスで定義される存在しない(スーパークラス内の)メソッドを参照する必要があります。しかし、これを機能させることはできません。
これは、私が試した多くの複数のバリエーションのうちの1つの試みです。
class Superclass
def chunk_of_code
# <code...>
nonexistant_superclass_method_defined_in_subclass params
# <more code...>
end
end
class Subclass < Superclass
def nonexistant_superclass_method_defined_in_subclass params
# whatever...
end
end
Subclass.new.chunk_of_code params
これは機能しません。他のバリエーションも機能しません。この種のコーディングはRubyで可能ですか(私はそう思っていました)?私はSmalltalkでいつもこのようなことをしていました。
私が望むことを達成する方法はありますか?今はRubyの継承を学び、使用したいので、「ミックスイン」や「モジュール」の使用を勧めないでください。
*最新バージョンのRubyを実行しています。
ありがとう。
編集:これはRailsアプリにあります。スーパークラスはApplicationControllerです。
編集:これは私がこれをやろうとした多くの反復の1つからの実際のコードです。この特定の例では、ビューに「undefined method `each'for nil:NilClass」が含まれています。これは、すべてがサブではなくスーパー(定義されていない場合)のコンテキストで実行されているため、または少なくともそれが私の解釈です:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_registration!
# models and x defined in subclass
def index
models = x.where registration_id: current_registration.id
respond_to do |format|
format.html # index.html.erb
format.json { render json: models }
end
end
# more code here...
# ...
end
class PositionsController < ApplicationController
def x
Position
end
def models= blah
@positions = blah
end
# more code here...
# ...
end