Last active
August 29, 2015 14:08
-
-
Save pier-oliviert/69d60505fa6e44863e52 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module ContentTagHelper | |
| def content_tag(*args) | |
| if block_given? | |
| tag = Tag.new(args[0], args[1] || {}) | |
| old_buf = @output_buffer | |
| @output_buffer = ActionView::OutputBuffer.new | |
| value = yield(tag) | |
| content = tag.render(@output_buffer.presence || value) | |
| @output_buffer = old_buf | |
| content | |
| else | |
| super | |
| end | |
| end | |
| class Tag | |
| include ActionView::Helpers::CaptureHelper | |
| attr_accessor :id | |
| attr_reader :name, :css | |
| def initialize(name, attributes = {}) | |
| @name = name | |
| @attributes = attributes.with_indifferent_access | |
| @attributes[:class] = Tag::CSS.new(attributes[:class]) | |
| end | |
| def []=(k,v) | |
| @attributes[k] = v | |
| end | |
| def [](k) | |
| @attributes[k] | |
| end | |
| def render(content) | |
| "<#{name}#{render_attributes}>#{content.strip}</#{name}>".html_safe | |
| end | |
| def render_attributes | |
| attrs = @attributes.dup | |
| if self[:class].empty? | |
| attrs.delete :class | |
| else | |
| attrs[:class] = self[:class].to_s | |
| end | |
| attrs.keys.map do |k| | |
| "#{k}='#{attrs[k]}'".html_safe | |
| end.join.prepend(' ') | |
| end | |
| class CSS | |
| def initialize(css) | |
| if css.is_a? String | |
| @internals = css.split(' ') | |
| else | |
| @internals = css.to_a | |
| end | |
| end | |
| def to_s | |
| @internals.uniq.join(' ') | |
| end | |
| def empty? | |
| @internals.empty? | |
| end | |
| def <<(name) | |
| @internals << name | |
| nil | |
| end | |
| end | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <%= content_tag :div do |div| %> | |
| <% if true %> | |
| <% div[:class] << :selected %> | |
| <% end %> | |
| <h1>Hello!</h1> | |
| <% end %> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey, sorry I didn't see your comment earlier. I agree that
li.cssis confusing. However, I would like to keep the method to a single name to make it easier to understand.Right now, I set/access every other html attributes using the
[]=(k,v)and I'm wondering if CSS shouldn't be the same. So basically, it would change fromli.css << :selectedto
li[:class] << :selected