nesquena / rabl

General ruby templating with json, bson, xml, plist and msgpack support
http://blog.codepath.com/2011/06/27/building-a-platform-api-on-rails/
MIT License
3.65k stars 335 forks source link

Any way to use association methods in rabl templates? #45

Closed kossnocorp closed 13 years ago

kossnocorp commented 13 years ago

Example:

From app/models/offer.rb:

has_many :offer_images do
  def history_image(size = :history)
    history.first.try(:image).try(:url, size)
  end
end

From app/views/offers/show.json.rabl:

child :offer_images do
  node(:thumb)  { |i| i.history_image(:small_thumb) }
  node(:normal) { |i| i.history_image(:small_promo) }
end
kossnocorp commented 13 years ago

I mean more cleanly solution than:


node :image_thumb do |o|
  o.offer_images.history_image(:small_thumb)
end

node :image_normal do |o|
  o.offer_images.history_image(:small_promo)
end
nesquena commented 13 years ago

Not sure of a better way unfortunately. If you have any suggestions for syntax or what you would want to write let me know. This seems like a very specific case. It is almost like a 'glue' but not quite

kossnocorp commented 13 years ago

I understand this is really not typical case. I think solution may look like:

child :offer_images do
  associtation_code(:thumb)  { |a| a.history_image(:small_thumb) }
  associtation_code(:normal) { |a| a.history_image(:small_promo) }
end

or

child :offer_images do
  associtation do
    code(:thumb)  { |a| a.history_image(:small_thumb) }
    code(:normal) { |a| a.history_image(:small_promo) }
  end
end

But I not sure about inclusion this feature in rabl. Let me know if it's ok and I will write patch.

nesquena commented 13 years ago

I find this to be too specific a use case unless I see more people with this issue crop up all the time. One nice thing is adding your own helpers should be pretty easy with the helpers command. Basically add a new helper module file to your rails or padrino app and then do

helper ExampleHelper

and in theory you could write any simple api method extension yourself:

def associative_child
  # ...
end

Just a thought but (if you dont mind) going to close this for now.