我正在使用Rails 4.2.5。我有这个超级
%Var1%
然后这个继承自它的类
class AbstractImportService
def initialize(params)
@init_url = params[:init_url]
end
private
attr_reader :init_url
问题是,在方法“self.my_method”中,puts行打印出“init_url:”,即使我最初使用@init_url也是如此。 Rails没有受保护的概念,所以有另一种方法可以让子类识别超类的类成员变量吗?
答案 0 :(得分:0)
@init_url = params[:init_url]
是一个实例变量,所以你不能期望得到它的值来尝试它
self.my_method(runner_id)
在MyService类上调用(而不是在此类的对象上)。
试试:
class AbstractImportService
def initialize(params)
@init_url = params[:init_url]
end
private
attr_reader :init_url
end
class MyService < AbstractImportService
def my_instance_method
"init_url: #{@init_url}"
end
end
2.2.1 :004 > instance = MyService.new({init_url: "http://www.example.com"})
=> #<MyService:0x007fd5db892250 @init_url="http://www.example.com">
2.2.1 :005 > instance.my_instance_method
=> "init_url: http://www.example.com"