views:

53

answers:

2

I'm 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 instantiation my class with initialize.

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 of

m = MyClass.new
m.param1 = 'hey'
m.param2 = 'hello'

But I'd like to use the attributes with default_params. How can I do this?

+1  A: 

Ruby has a syntax for that, 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 have never used HTTParty, and I'm not sure what the default_params method does, so I dunno if this is what you're looking for.

August Lilleaas
Thanks, HTTParty and default_params don't really have to do with the question. I just need to know how I can access the attributes within the class, but outside of any methods.
+1  A: 

Have a look at the initialize method in this example file from the Github repo. I haven't used HTTParty before, but this looks like what you're after.

Also, from your example, it looks like you're mixing up class methods and instance variables.

dylanfm