Once again, sorry for the long time between replies. I had actually
given up on my original idea and implemented something very much like
this. mostly inspired by Tom M.'s idea:
when Blah
# render code for Blah
# or show_blah(object)
else
raise :YourVoiceStridently
end
end
Instead of using a case statement, though, I implemented “show”
something like the render :model method below. My version figures out
a method name and a partial name, and tries the method first. This
would be good for more complex rendering. It also takes a parameter
“style”, which just gets appended to the name of the partial/method,
to allow for different ways of rendering objects. locals is simply a
hash that gets sent to the partial (and, I suppose, I will have to
send to the method. I haven’t used that yet in my project, so it’s
not completely implemented)
My (ugly) code:
def show(object, style = nil, locals = {})
name = Inflector::underscore(object.class)
style = ‘_’ + Inflector::underscore(style.to_s) if !style.nil?
&& style.to_s
method = 'render_' + name + style.to_s
partial = '/objects/' + name + '/' + name + style.to_s
if (self.respond_to?(method, true))
self.send(method, object)
else
render :partial => 'objects/' + name + '/' + name + style.to_s,
:locals => locals.merge({ name.to_sym => object })
end
end
I also implemented a somewhat similar function to show a list of
objects. This one needs to explicitly know the class to use:
def list(collection, klass, style = nil, locals = {})
name = Inflector::underscore(klass)
names = Inflector::pluralize(name)
style = ‘_’ + Inflector::underscore(style.to_s) if !style.nil?
&& style.to_s
method = 'render_list_' + names + style.to_s
partial = '/objects/' + name + '/list_' + names + style.to_s
if (self.respond_to?(method, true))
self.send(method, collection)
else
render :partial => partial,
:locals => locals.merge({ names.to_sym => collection })
end
end
I intend to look into your code more deeply when I get the time. I
haven’t as of yet gotten my head around it fully, but I like the
syntax of
<%= render :model => model %>
and could see this going to something like
<%= render :model => model, :style => ‘style’, :locals => { :key =>
‘value’ } %>
to include everything my code does.
Thanks for the replies,
Ozzi