Forum: Ruby on Rails each_with_styles, for adding CSS classes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mark Josef (Guest)
on 2006-04-06 03:36
(Received via mailing list)
Hi,

A common problem that everyone has come across is applying styles
to rows of information--pinstriping, or specifically marking
the first or last row.  I came up with a general solution, and
so am offering it up here in case anyone finds it useful.

The solution is a method, added to the Array class, called
each_with_styles.  Give it a hash and a block, and it will call
the block with two block parameters.  The first will be the item,
like Array::each does, and the second will be a string containing
the list of relevant classes (as given by the hash).

Hope it comes in helpful!

~Mark Josef

EXAMPLE:

array = ['hello', 'happy', 'birthday']
styles = { :all => 'every', :first => 'no_1', :odd => 'strange' }

array.each_with_styles(styles) do |item, style|
  puts "<div class='#{style}'>
  puts item
  puts "</div>"
  puts ""
end

WILL RETURN:

<div class='every no_1 strange'>
hello
</div>

<div class='every'>
happy
</div>

<div class='every strange'>
birthday
</div>

TO ADD IT TO YOUR PROJECT:

1. Create a file called 'each_with_styles.rb' in your project's
     /lib directory.
2. Include the code below in that file.
3. In your /app/controllers/application.rb file, add the line
     'require "each_with_controller" ' to the top.

EACH_WITH_STYLES.RB:

# Adds each_with_styles to the Array class.
#  each_with_styles takes an hash of optional
#  class conditions, and returns a list of all
#  that apply.
#
#       Possible Conditions:
#  ----------------------------------------------
#   :all -- always applies
#   :first -- only the first element
#   :not_first -- all but the first element
#   :last -- only the last element
#   :not_last -- all but the last element
#   :middle -- all but the first and last
#   :not_middle -- first and last only
#   :odd -- every other, starting with the first
#   :even -- every other, starting with the second

class Array

  def each_with_styles(styles)
    styles = Hash.new unless styles && styles.class == Hash

    each_with_index do |item, index|
      style_array = Array.new

      style_array << styles[:all]
      style_array << (index == 0 ? styles[:first] : styles[:not_first])
      style_array << (index == (length-1) ? styles[:last] :
styles[:not_last])
      style_array << (index % 2 == 0 ? styles[:even] : styles[:odd])
      style_array << (index > 0 && index < (length-1) ?
			styles[:middle] : styles[:not_middle])

      yield(item, style_array.compact.join(' '))
    end
  end

end

AND THAT'S IT!
This topic is locked and can not be replied to.