How do I call the attr_accessor attribute inside the class (but outside of any methods)?
I am using HTTParty for my class and I want to use the default_params method. However, I also want to be able to set attributes when instantiating my class with initialization.
class MyClass
include HTTParty
attr_accessor :param1, :param2
# This or @param1 doesn't work.
default_params :param1 => self.param1, :param2 => self.param2
def initialize(param1, param2)
self.param1 = param1
self.param2 = param2
end
end
This way I can do
m = MyClass.new('hey', 'hello')
instead
m = MyClass.new
m.param1 = 'hey'
m.param2 = 'hello'
But I would like to use attributes with default_params. How can i do this?
Take a look at the method initialize
in this example file from the Github repository. I haven't used HTTParty before, but it looks like what you need.
Also, from your example, it looks like you are mixing class methods and instance variables.
a source to share
Ruby has a syntax for this in method declarations.
class MyClass
attr_reader :param1, :param2
def initialize(param1 = "default", param2 = 5)
@param1, @param2 = param1, param2
end
end
MyClass.new.param2
# => 5
I've never used HTTParty and I'm not sure what the method does default_params
, so I don't know if this is what you are looking for.
a source to share