简体   繁体   English

Ruby:在块内调用默认参数时将默认参数传递给方法

[英]Ruby: Pass default parameter to a method when it is called inside a block

I try to create a very simple Rails helper to generate me a fancybox image preview. 我尝试创建一个非常简单的Rails助手来为我生成一个fancybox图像预览。 It should produce the following HTML: 它应产生以下HTML:

<a href="path-to-image" class="fancybox">
  <img src="path-to-image-thumb" ... />
</a>

However, to output a clickable gallery of many images, I need to set the rel attribute to the same value for all of the links: 但是,要输出包含许多图像的可点击图片库,我需要将所有链接的rel属性设置为相同的值:

<a href="path-to-image" class="fancybox" rel="my-gallery">
  <img src="path-to-image-thumb" ... />
</a>
<a href="path-to-image2" class="fancybox" rel="my-gallery">
  <img src="path-to-image2-thumb" ... />
</a>

I'd like to do this like the following: 我想这样做如下:

# Single image
<%= image_preview(image) %>

# Image gallery
<%= image_gallery('my-gallery') do |g| %>
  <%= g.image_preview(image) %>
  <%= g.image_preview(image2) %>
<% end %>

So I want to use the same image_preview method both in a block and without one, but I'm struggling with the implementation. 因此,我想在块中和不使用块中都使用相同的image_preview方法,但是我在实现上苦苦挣扎。

My current implementation (which doesn't work) looks like this: 我当前的实现(无效)如下所示:

def image_preview(image, options = {})
  link_to image.url, class: 'fancybox' do # How do I decide whether I have to put the rel attribute?
    image_tag image.url(:thumb), options
  end
end

def image_gallery(name, &block)
  yield self # Somehow I have to use the provided name as rel attribute in image_preview...
end

I also tried my luck with with_options but didn't really get it to work for me (and sincerely don't exactly know how to use it for this case). 我也尝试了with_options运气,但是并没有真正让它对我有用(并且真诚地不知道在这种情况下如何使用它)。

My implementation looks like this: 我的实现如下所示:

module ImageGalleryHelper
  def image_gallery(name = nil, &block)
    name ||= 'gallery_' + SecureRandom.hex(6)

    content_tag :div, class: name do
      with_options gallery_name: name do |gallery|
        yield gallery
      end
    end
  end

  def fancy_image(image, options = {})
    content_tag :a, href: image.url, class: 'fancybox', rel: options.delete(:gallery_name) do
      image_tag image.url(:thumb), options
    end
  end
end

This does exactly what I want it to do. 这正是我想要的。 Maybe there are some enhancements possible? 也许可以进行一些增强?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM