mirror of
https://github.com/haml/haml.git
synced 2022-11-09 12:33:31 -05:00
[Haml] Add support for overriding the object_ref of an Object.
This is for overriding the default behavior of the object_ref function which currently defaults to the underscored class name of the Object.
This commit is contained in:
parent
5760e12384
commit
1e49eb1a87
3 changed files with 40 additions and 1 deletions
|
@ -559,6 +559,29 @@ is compiled to:
|
|||
Hello!
|
||||
</div>
|
||||
|
||||
If you require that the class be something other than the underscored
|
||||
object's class, you can implement the `haml_object_ref` method on the object.
|
||||
|
||||
# file: app/models/crazy_user.rb
|
||||
|
||||
class CrazyUser < ActiveRecord::Base
|
||||
def haml_object_ref
|
||||
"a_crazy_user"
|
||||
end
|
||||
end
|
||||
|
||||
-# file: app/views/users/show.haml
|
||||
|
||||
%div[@user]
|
||||
Hello!
|
||||
|
||||
is compiled to:
|
||||
|
||||
<div class='a_crazy_user' id='a_crazy_user_15'>
|
||||
Hello!
|
||||
</div>
|
||||
|
||||
|
||||
## Doctype: `!!!`
|
||||
|
||||
When describing HTML documents with Haml,
|
||||
|
|
|
@ -278,7 +278,12 @@ RUBY
|
|||
ref = ref[0]
|
||||
# Let's make sure the value isn't nil. If it is, return the default Hash.
|
||||
return {} if ref.nil?
|
||||
class_name = underscore(ref.class)
|
||||
class_name =
|
||||
if ref.respond_to?(:haml_object_ref)
|
||||
ref.haml_object_ref
|
||||
else
|
||||
underscore(ref.class)
|
||||
end
|
||||
id = "#{class_name}_#{ref.id || 'new'}"
|
||||
if prefix
|
||||
class_name = "#{ prefix }_#{ class_name}"
|
||||
|
|
|
@ -69,6 +69,11 @@ class EngineTest < Test::Unit::TestCase
|
|||
}
|
||||
|
||||
User = Struct.new('User', :id)
|
||||
class CustomHamlClass < Struct.new(:id)
|
||||
def haml_object_ref
|
||||
"my_thing"
|
||||
end
|
||||
end
|
||||
|
||||
def render(text, options = {}, &block)
|
||||
scope = options.delete(:scope) || Object.new
|
||||
|
@ -689,6 +694,12 @@ END
|
|||
render("%p[user]{:style => 'width: 100px;'} New User", :locals => {:user => user}))
|
||||
end
|
||||
|
||||
def test_object_ref_with_custom_haml_class
|
||||
custom = CustomHamlClass.new 42
|
||||
assert_equal("<p class='my_thing' id='my_thing_42' style='width: 100px;'>My Thing</p>\n",
|
||||
render("%p[custom]{:style => 'width: 100px;'} My Thing", :locals => {:custom => custom}))
|
||||
end
|
||||
|
||||
def test_non_literal_attributes
|
||||
assert_equal("<p a1='foo' a2='bar' a3='baz' />\n",
|
||||
render("%p{a2, a1, :a3 => 'baz'}/",
|
||||
|
|
Loading…
Reference in a new issue