Last active
August 29, 2015 14:26
-
-
Save jmondo/9b8facde09da77dd6aaf to your computer and use it in GitHub Desktop.
super simple way to display most objects for an admin system (array, AR relation, integers, strings, etc.) also links to associated record when possible.
This file contains 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
# WHAT IT DOES: | |
# with these models -> | |
# book has author | |
# author has friendly_name method that points to title | |
# chapter_pages is a hash with keys of chapters, values of the page they start on | |
# it does these things -> | |
# object_for_admin(book.author) | |
# => <a href="/books/1">Title of Book</a> | |
# object_for_admin(book.chapters); @narrow_mode = true | |
# => Chapter 1 | |
# => Chapter 2 | |
# object_for_admin(book.chapters); @narrow_mode = false | |
# => Chapter 1, Chapter 2 | |
# object_for_admin(book.created_at) | |
# => 2015-10-29 2:00 PM | |
# object_for_admin(book.chapter_pages) | |
# => { | |
# => "Chapter 1": 1, | |
# => "Chapter 2": 40 | |
# => } | |
def object_for_admin(object) | |
friendly_name = object.try(:friendly_name) || object | |
case object | |
when Array, ActiveRecord::Relation | |
separator = @narrow_mode ? '<br>' : ', ' | |
sanitize object.map {|o| object_for_admin(o) }.join(separator) | |
when Hash | |
content_tag(:pre) { JSON.pretty_generate(object) } | |
when ActiveRecord::Base | |
# if your app uses urls like /admin/users/1, use link_to(friendly_name, [:admin, object]) | |
link_to(friendly_name, object) | |
when Time | |
object.stamp("2015-01-01 2:20 PM") | |
else | |
friendly_name.to_s | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment