1

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Is it working? I am sure it'll not work. Please put your answer with some example.
@Mr.Black i get it from the api doc. Not verify it by myself. Hope it can help.
Thanks. It's working only for the Class with custom methods not a resource methods. I got a duplication of this question. stackoverflow.com/questions/6061489/…
0

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

6 Comments

Thanks. It's not working with the Actual controller.
I have list of controllers which will have some unique variable across most of methods with different values. I need to get the value of the particular instance variable and pass to common function.
I suppose that you used in the controller 'before_action', call these methods manually before performing call 'index','show' ...
Yes, I thought also. But, seems I can't call the method index or show directly. See my updated question.
From the example it is clear only that you have some variable that does not have a method 'env'. Show the entire method code
|

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.