Mr. Black
Mr. Black

Reputation: 12082

Scan instance variable from controller

Is there any way to read (scan) all the instance variables from the controller's methods?

ex:

I'll define some instance variables in a controller either index or show or custom defined method. I want to know (get) all the instance variable values from one place.

class TestClass
  def t1
    @v1 = "test"
  end

  def t2
    @v2 = "test1"
  end
end

TestClass.instance_variables
 => [] 

tc = TestClass.new
tc.t1
tc.instance_variable_names
=> ["@v1"]

The above code is working for the class with the custom methods not with default methods (index, show, etc..)

Rails.env
=> "development"
u = UsersController.new
 => #<UsersController:0x00000004233990 @_routes=nil, @_action_has_layout=true, @_headers={"Content-Type"=>"text/html"}, @_status=200, @_request=nil, @_response=nil> 
1.9.3p448 :109 > u.index
NoMethodError: undefined method `env' for nil:NilClass

Upvotes: 1

Views: 88

Answers (2)

Vakiliy
Vakiliy

Reputation: 871

The easiest way will probably be something like this:

a = TestClass.new
after_init = a.instance_variables
a.t1
after_t1 = after_init -  a.instance_variables

Upvotes: 0

nickcen
nickcen

Reputation: 1692

call the instance_variables() method.

instance_variable_names()

# File activesupport/lib/active_support/core_ext/object/instance_variables.rb, line 27
def instance_variable_names
   instance_variables.map { |var| var.to_s }
end

Upvotes: 1

Related Questions