AsheAvenue/Kilt — pull request #35 by darrencauthon (2014-08-03 14:34:26+00:00)
Title: View model

This PR would be easier to assess after #34 is merged.

I like the JSON-only form of the data that Kilt returns, but it can make for some nasty views. I built a "view model" that lets me do things like this:

```ruby
first_page = Kilt.pages.first
first_page['name'] # "Home"

view_model = KiltViewModel.build first_page
# view_model is a KiltViewModel object
view_model.name # "Home"
```

So at its simplest, it lets you use a method call instead of the brackets. Big deal, right?

Well, you can also do this:

```ruby
class PageViewModel < KiltViewModel
def image
return nil unless self[:image]
Kilt::Utils.download_location('image', self[:image])
end
end

first_page = Kilt.pages.first
view_model = KiltViewModel.build first_page

# view_model is a PageViewModel, since a "PageViewModel" exists. ```KiltViewModel.build``` will look for a matching ```#{object.object_type}ViewModel``` when building the view model.

view_model.image # will return the image... sure beats that logic in the view!
```

If you pass a single object to ```KiltViewModel.build``` it will return a single view model. If you pass it a set of objects, it will return a set of view models. Each of the view models in the set will be determined individually... so if you gave it ```[Kilt.pages, Kilt.blogs].flatten``` you'd get both PageViewModels and BlogViewModels (or KiltViewModels if any of those aren't defined).

I also found it helpful to include some sort of mechanism for sorting, for things like menus and the like. So if you include a ```sequence``` field in your schema, ```KiltViewModel.build``` will sort a set by that field.

**Overall**, this little class can fill in a big hole that appears when passing flat JSON to a view.