简体   繁体   中英

How to check if method is executed via a yield/block.call?

In a very basic example I have two Rails form helpers toggles and checkbox . I want the markup for the checkboxes different when they are inside the toggles block. I tried to use a instance variable to check if I'm inside the toggles method but someone said maintaining state like this would break the ability for this to be used in multithreaded applications. What would be a better way?

So basically I want to check if I'm inside toggles when checkbox is executed.

<%= toggles 'Select one' do %>
  <%= f.checkbox 'Foo' %>
  <%= f.checkbox 'Bar' %>
  <%= f.checkbox 'Baz' %>
<% end %>

def toggles(*args)
  @inside_toggles = true
  template.concat yield
  @inside_toggles = false
end

def checkbox(*args)
  if @inside_toggles
    ...
  else
    ...
  end
end

If it's only a formatting issue, did you try using CSS?

You add a class for helper method toggles

def toggles
  content_tag :div, class: 'toggle'
end

Then in your CSS

.toggle input[type="checkbox"] {
   /* special format */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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