I'm working on a fairly complicated app and am trying to figure out how to implement some functionality in terms of rendering data to various formats.
In simple terms, the app is taking key value data and rendering it to html, or potentially to other formats. I know key value data sucks but for the app in question it is required. This will be a rails app and essentially I'm dealing with a model structure that looks something like:
Foo has many Bars Bar has many Fields Field consists of name, value, type
What I'd like to do in my controller is fetch a Foo and feed it to the view. The view would then call some kind of builder class with the Foo object as an argument, along with the render format (e.g. html, pdf, xml).
From here on how to structure it I'm a bit lost on, and I'm hoping someone can give some pointers in the right direction as I'm fairly new to ruby and figuring out how classes, modules and mixins fit into the picture is confusing me.
On a high level here's what I'm thinking... The builder class would say, ah, we want html output so pass this to the html builder. The html builder would say, ok, we have Foo and we need to render this output. It's logic would iterate through fields and try to figure out how to render each one, something like:
1) Do we have something that specifically knows how to render field 4 in Bar.id = 8 in Foo.id = 3?
2) Do we have something that knows how to render field.type = 'phone' for Bar.id = 8 on Foo.id = 3?
3) Do we have something that knows how to render field.type = 'phone' for Foo.id = 3?
4) Do we have something that knows how to render field.type = 'phone'?
5) Call default renderer
Ultimately my goal here is to write the least amount of code possible. For example, for more than half the fields the rendering for html will be nothing but plain text. However, the nature of the app requires that we be able to accomodate any edge case necessary. For example, it's entirely possible that in some cases we need to render a phone number as xxx-xxx-xxxx whereas other times it would need to be rendered as (xxx) xxx-xxxx. My overall idea is to create something that can take a model as an argument and go from specific to generic renderers so that in any special case I can specifically say for field 'phone' in Bar 3 and Foo 7 it should output in a special way. But obviously, I don't want to have to create a class heirarchy for every field of ever Bar of ever Foo, rather I'd like a method where I can implement some code if a special case is required and have the Builder routine find it.
Hopefully this is reasonably clear, if anyone has any tips on how I might structure this within a rails application or some pointers in the right direction I'd appreciate it.