cycle() an image_tag

2019-09-02 07:51发布

问题:

I'm want to display different image version:

first article: big banner

second: small banner that float to right/left

so, first thing: use cycle() but dont work:

= cycle(image_tag(banner_big), image_tag(banner_small)

or

= image_tag(cycle(banner_big_path, banner_small_path))

Only first image is displayed

There's a proper way to make one like that ?

回答1:

Your problem is that rails is expecting you to call cycle with the same set of strings each time. At the moment you're passing a different pair of strings to each call to cycle, so rails resets the cycle each time. New cycles always start with their first value, hence the result you describe.

Assuming your articles had methods called small_path, big_path, something like

article.send(cycle("big_path","small_path"))

Should return alternate image paths.



回答2:

You can make use of the session facility to store indexes there and use those. For instance:

# application_helper.rb
def session_banner_index
  session[:banner_index] || 0
end

def session_banner(*list)
  list[session_banner_index % list.length]
end

# application_controller.rb
def increment_session_banner_index!
  session[:banner_index] = (session[:banner_index] || 0) + 1
end

These helper methods approximate the interface you were asking for:

 = image_tag(session_banner(banner_big, banner_small))