Skip to content

Instantly share code, notes, and snippets.

@madeinfree
Last active August 29, 2015 14:04
Show Gist options
  • Save madeinfree/3119e0cc3f2e653df3b6 to your computer and use it in GitHub Desktop.
Save madeinfree/3119e0cc3f2e653df3b6 to your computer and use it in GitHub Desktop.
inspect_helper :D
###
# helper_name:inspect_helper
# author: Whien_Liou
# time: 2014/07/23
#
# usage
# 請在增加 config/initializers/inspect_helper.rb
# 加入下列幾行代碼
# 在 controller 使用
#
# @product = Product.all
# render html: @product.inspect_helper_model 即可
# ..
# Peace :D
require 'action_view'
module ActiveRecord
module Core
include ActionView::Helpers::FormTagHelper
def inspect_helper_model
result = ""
inspection = if defined?(@attributes) && @attributes
self.class.column_names.collect do |name|
if has_attribute?(name)
%[<p><h3><span class=\"label label-success\">#{name}</span></h3></p><p class=\"text-center\">#{attribute_for_inspect_helper(name)}</p>]
end
end
else
%[not initialized]
end
inspection.each do |value|
result += %[<td class="text-center">#{value}</td>]
end
inspect_helper_table_create(%[<h1 class=\"text-center\"><span class=\"label label-danger\">##{self.class}</span></h1>], result).html_safe
end
def inspect_helper_table_create(title_attr, tag_result)
create_css + %[<table class=\"table table-hover\">#{title_attr}#{tag_result}</table>]
end
end
end
module ActiveRecord
# = Active Record Attribute Methods
module AttributeMethods
extend ActiveSupport::Concern
include ActiveModel::AttributeMethods
def attribute_for_inspect_helper(attr_name)
value = read_attribute(attr_name)
end
end
end
module ActiveRecord
class Relation
def inspect_helper_model
result = ""
gsub_reg = /(#<)/
gsub_reg_last = /(\"\>)/
entries = to_a.take([limit_value, 11].compact.min).map!(&:inspect)
#entries[10] = '...' if entries.size == 11
entries.each do |entries|
result += %[<tr><td>] + entries + %[</td></tr>]
end
tag_result = %[<p><h1><span class=\"label label-danger\">#{self.class.name}</span></h1></p>] + %[<table class=\"table table-hover\">] + result.gsub!(gsub_reg, "").gsub!(gsub_reg_last, "") + %[</table>]
(create_css + tag_result).html_safe
end
end
end
def create_css
%[<link data-turbolinks-track=\"true\" href=\"/assets/bootstrap.css?body=1\" media=\"all\" rel=\"stylesheet\" />]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment