Skip to content

Instantly share code, notes, and snippets.

@nthj
Created April 5, 2011 01:27
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 nthj/902844 to your computer and use it in GitHub Desktop.
Save nthj/902844 to your computer and use it in GitHub Desktop.
Ruby object extension for use with HAML
# Easily add id and class attributes to HAML elements
#
# %li{ account.element.to_hash } ->
# <li class='account' id='account-7'>
#
# %span{ account.element.button.to_hash } ->
# <span class='account-button' id='account-7-button'>
#
# %span{ :class => account.element.save.button.class } ->
# <span class='account-save-button'>
#
# %span{ :id => account.element.save.button }
# <span id='account-7-save-button'>
#
class Object
class Extendable < String
def initialize object, parts = []
@object, @parts = [object, parts.clone]
replace parts.insert(0, object.class.name.demodulize.downcase.dasherize).join('-')
end
def class
Extendable.new @object, @parts[1..-1].to_a
end
def to_hash
{
:class => self.class,
:id => self
}
end
private
def method_missing symbol, *args
Extendable.new @object, @parts.push(symbol.to_s)
end
end
def element
if respond_to?(:to_param)
Extendable.new(self, [to_param])
elsif respond_to?(:key)
Extendable.new(self, [key])
else
Extendable.new self
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment