0

I have a module, whose purpose is to act on any given ActiveRecord instance.

For argument's sake, let's say that this method puts the string "match" if it matches certain properties with another instance of the same type.

module Foo
  def check_against_other_instances
    self.all.each do |instance|
      if self.respond_to? :color && self.color == instance.color
        puts "match"
      end
    end
  end
end

However, I can't just simply call self.all here, because self is an instance. How do I call the class method all from here?

1
  • @HunterMcMillen I can't reference the class name directly, because I don't know ahead of time which classes will be using it. Commented Jul 3, 2012 at 18:19

3 Answers 3

3

Ah.. found the solution almost right after I asked...

self.class.all.each do |instance| ...

Sign up to request clarification or add additional context in comments.

Comments

0

if you want to extend the behavior of rails classes, then you are best of using ActiveSupport::Concern!

http://apidock.com/rails/ActiveSupport/Concern

Comments

0

You can pull the name of a class from an instance and then constantize it.

For example, given a class Thing:

t = Thing.new
t.class.name
  # => "Thing"
t.class.name.constantize
  # => Thing

2 Comments

Thanks Baron. Unfortunately, just found the answer ;). Also, you don't need to call t.class.name... you can just simplify things and call t.class
This is definitely a much more roundabout way of getting to the simpler solution that @varatis posted.

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.