Skip to content

Instantly share code, notes, and snippets.

@tbuehlmann
Forked from merbjedi/add_class
Created March 12, 2010 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tbuehlmann/330417 to your computer and use it in GitHub Desktop.
Save tbuehlmann/330417 to your computer and use it in GitHub Desktop.
# provides a slick way to add classes inside haml attribute collections
#
# examples:
# %div{add_class("current")}
# #=> adds the "current" class to the div
#
# %div{add_class("current", :if => current?)}
# #=> adds the "current" class to the div if current? method
#
# %div{add_class("highlight", :unless => logged_in?)}
# #=> adds the "highlight" class to the div unless logged_in? method returns true
def add_class(css_class, options = {})
return {} unless css_class
if options.has_key?(:unless) && !options[:unless]
return {:class => css_class}
end
if options.has_key?(:if) && options[:if]
return {:class => css_class}
end
if !options.has_key?(:if) and !options.has_key?(:unless)
{:class => css_class}
else
{}
end
end
# Adding haml attributes
#
# trueish = true
#
# FunkyHamlAttributeHelper.add_class('content') # => {:class => "content"}
# FunkyHamlAttributeHelper.add_id('content') # => {:id => "content"}
# FunkyHamlAttributeHelper.add_flux_capacitor('future') # => {:flux_capacitor => "future"}
#
# FunkyHamlAttributeHelper.add_class('content', :if => trueish) # {:class => "content"}
# FunkyHamlAttributeHelper.add_class('content', :unless => trueish) # {}
#
# FunkyHamlAttributeHelper.add_('content') # => {}
module FunkyHamlAttributeHelper
def self.method_missing(method, *args)
return {} if args.empty?
if method =~ /^add_(\S+)/
property = $1.to_sym
value = args[0]
options = args[1] ||= {}
if options.has_key?(:unless) && !options[:unless]
return {property => value}
end
if options.has_key?(:if) && options[:if]
return {property => value}
end
if !options.has_key?(:if) and !options.has_key?(:unless)
return {property => value}
end
return {}
else
return {}
end
end
end
# Adding haml attributes
#
# HamlAttributeHelper.add(:class, 'content') # => {:class => "content"}
# HamlAttributeHelper.add(:id, 'content') # => {:id => "content"}
# HamlAttributeHelper.add(:flux_capacitor, 'future') # => {:flux_capacitor => "future"}
#
# HamlAttributeHelper.add(:class, 'content', :if => trueish) # {:class => "content"}
# HamlAttributeHelper.add(:class, 'content', :unless => trueish) # {}
module HamlAttributeHelper
def self.add(property, value, options = {})
return {} unless property || value
if options.has_key?(:unless) && !options[:unless]
return {property => value}
end
if options.has_key?(:if) && options[:if]
return {property => value}
end
if !options.has_key?(:if) and !options.has_key?(:unless)
return {property => value}
end
return {}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment