I’m using Rails 4.2.5. I have this super class
class AbstractImportService
def initialize(params)
@init_url = params[:init_url]
end
private
attr_reader :init_url
and then this class that inherits from it
class MyService < AbstractImportService
def self.my_method(runner_id)
puts "init_url: #{@init_url}"
…
end
The problem is, in the method “self.my_method,” the puts line prints out “init_url:” even if I initially the @init_url to something. Rails doesn’t have a concept of protected so is there another way I can get sub-classes to recognize class member variables of the super class?
@init_url = params[:init_url]
is an instance variable, so you can't expect to get its value trying it to get it by
self.my_method(runner_id)
which is called on the MyService class (and not on an object of this class).
Try with:
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"