Instance variable looses value upon render

26 views
Skip to first unread message

Ronald Fischer

unread,
Oct 8, 2014, 11:07:16 AM10/8/14
to rubyonra...@googlegroups.com
I have an instance variable, @pages, which needs to be set up in a
certain way at the end of several actions, so I thought to be clever and
do it in the following way:

# In my controller

after_action :prepare_admin_home_data, only:
[:adm_login,:adm_upload_selected]

def adm_login
...
render admin_pages_home_path
...
end

def prepare_admin_home_data
@pages=Dir["#{AMP_DIR}/*"]
logger.debug("+++++++++++ pages #{@pages.to_s}")
end

I can see from the logs, that @pages got the right value, but in my
view, it is nil. It seems that the HTML code is constructed before the
after_action is executed.

I understood the render() function in that way, that it only sets up
which ERB template is supposed to be used, but actual rendering would
occur only when the action has finished. Did I get this wrong?

Ronald

--
Posted via http://www.ruby-forum.com/.

Matt Jones

unread,
Oct 9, 2014, 6:58:35 AM10/9/14
to rubyonra...@googlegroups.com


On Wednesday, 8 October 2014 11:07:16 UTC-4, Ruby-Forum.com User wrote:
I have an instance variable, @pages, which needs to be set up in a
certain way at the end of several actions, so I thought to be clever and
do it in the following way:

# In my controller

after_action :prepare_admin_home_data, only:
[:adm_login,:adm_upload_selected]

def adm_login
  ...
  render admin_pages_home_path
  ...
end

def prepare_admin_home_data
  @pages=Dir["#{AMP_DIR}/*"]
  logger.debug("+++++++++++ pages #{@pages.to_s}")
end

I can see from the logs, that @pages got the right value, but in my
view, it is nil. It seems that the HTML code is constructed before the
after_action is executed.


Correct. Code in `after_action` callbacks can examine and mutate the about-to-be-sent response, but the render has already occurred.
 
I understood the render() function in that way, that it only sets up
which ERB template is supposed to be used, but actual rendering would
occur only when the action has finished. Did I get this wrong?


When you call `render` the render happens immediately. If you return from an action *without* rendering or redirecting, the default behavior will be executed by ActionPack (rendering the template with the same name as the action).

--Matt Jones 

Ronald Fischer

unread,
Oct 10, 2014, 4:20:21 PM10/10/14
to rubyonra...@googlegroups.com
Oh, I really got this wrong. So, the HTML is already constructed with
the render call, then the rest of the action is executed!

Thanks a lot.
Reply all
Reply to author
Forward
0 new messages