2

I'm trying to create a class that includes the Singleton module while using attr_accessor. This doesn't seem to be working though.

require 'singleton'

class Foo
  attr_accessor :bar
  include Singleton
end

Foo.bar = 'foobar'

This gives the error:

undefined method `bar=' for Foo:Class (NoMethodError)

What am I doing wrong here?

1
  • you are calling a class method instead of an instance method which you don't have implemented. Singelton is a class with only one existent instance. You should be doing the call on an instance and not on the class. Commented Jul 9, 2013 at 13:25

3 Answers 3

5

Singleton does not change the way attr_accessor works. It only ensures that you can have only one instance. So you have to call attr_accessor within the eigenclass, just as you do without Singleton.

class Foo
  singleton_class.class_eval{attr_accessor :bar}
end
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. I really like this solution because people that use my gem won't have to do Foo.instance.blah...
Note instance_eval or class_eval can be used here. Alternatively, one could write singleton_class.public_send(:attr_accessor, :bar).
Yet another option is to open the singleton class: class Foo include Singleton class << self attr_accessor :bar end end
2

Try -

     Foo.instance.bar = 'foobar'

Documented Here and Here

Comments

1

Methods defined using attr_accessors are instance methods, you are trying to call the method bar= on the Foo class, that doesn't define it. You have to get the instance of Foo first and then call bar= on it:

Foo.instance.bar = "whatever"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.