Created
October 27, 2010 07:50
-
-
Save masqita/648637 to your computer and use it in GitHub Desktop.
Providing a common interface for models to convert to for example a JSON structure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Put these modules and classes in separate files of course | |
module ToTree | |
# Module that will handle the conversion to a generic hashlike structure | |
# and also provides a common interface for model specific modules | |
def to_tree(uri_method) | |
self.tree_attributes.merge('url' => uri_method.call(self)) # We will use the method passed in from the controller to construct the url | |
end | |
def tree_attributes | |
raise NotImplementedError | |
end | |
end | |
module MyModelToTree | |
include ToTree | |
# Make a module for each model you want to convert to a hash like structure, | |
# naming it appropriately (CompanyToTree, UserToTree). | |
# We will include it in the model afterwards, but it keeps the conversion | |
# separated | |
def tree_attributes | |
{ | |
'title' => self.some_title_field, | |
'desc' => self.some_description_field | |
} | |
end | |
end | |
class MyModel < ActiveRecord::Base | |
include MyModelToTree | |
# The rest of your actual model code | |
end | |
class MySearchController < ApplicationController | |
def index | |
search_results = Search.collect_lots_of_different_objects | |
render :json => search_results.collect{|result| result.to_tree(method(:polymorphic_path))} # polymorphic path will work for RESTful resource based routes | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment