tags:

views:

50

answers:

3

Can't i do it like this:

class Hardware

before_filter

  def before_filter
    puts "ge"
  end

end

It says before_filter is undefined method or variable when I instantiate it

hd = Hardware.new

because ive seen others put a method name in a class before. Just wondering how it works. Thanks

+5  A: 

before_filter is an ActiveRecord class method (see here) and so would only be available if your model inherited from ActiveRecord::Base (or a subclass). Can you be more specific about what you're trying to do?

You might just be looking for:

class Hardware
  def initialize
    super
    before_filter
  end

  protected
  def before_filter
    # ...
  end
end
thenduks
+7  A: 

There's two problems with your code:

  1. You are calling a class method, but your are defining an instance method.
  2. You are calling the method before it has been defined.

Both of these obviously cannot work.

This would work:

class Hardware
  def self.before_filter
    puts "ge"
  end

  before_filter
end
Jörg W Mittag
Just to clarify: `before_filter` would get called more or less as soon as it is read, unlike other languages that read everything first and then executes the code. That kind of thing also means you can't write a class and then write the module you want it to include.
Andrew Grimm
+3  A: 

Either change

def before_filter

to

def self.before_filter

and call it after defined

OR

Comment before_filter

class Hardware
  def before_filter
    puts "ge"
  end
end

and Call like

hd = Hardware.new
hd.before_filter
Salil