Skip to content

Instantly share code, notes, and snippets.

@myronmarston
Created May 30, 2011 18:57
Show Gist options
  • Save myronmarston/999316 to your computer and use it in GitHub Desktop.
Save myronmarston/999316 to your computer and use it in GitHub Desktop.
class EngineVariant
def api_representation
{ engine: engine, locale: locale }
end
end
class Subscription
def api_representation
{
name: name,
schedule: schedule.try(:api_representation),
queries: queries.to_a,
engine_variants: engine_variants.map(&:api_representation),
url_fragments: url_fragments.map(&:api_representation)
}
end
end
class SubscriptionSchedule
def api_representation
{
interval: interval,
start_date: start_date
}
end
end
class URLFragment
def api_representation
{
type: type,
value: value,
name: name
}
end
end
@myronmarston
Copy link
Author

The way I've recently been defining nested JSON structures for my APIs. I won't argue against it being a bit of a SRP violation, but having the model responsible for returning a representation of itself as a hash seems fine to me. And in practice, this is the easiest way I've found to keep things DRY and put the knowledge of how to represent a particular nested model in the API in a single place.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment