Skip to content

Instantly share code, notes, and snippets.

@jhjguxin
Created July 3, 2012 11:21
Show Gist options
  • Save jhjguxin/3039158 to your computer and use it in GitHub Desktop.
Save jhjguxin/3039158 to your computer and use it in GitHub Desktop.
rails find model class from controller
<%= form_tag(common_search_url,:class=>"navbar-search") do %>
<%= text_field_tag(:q,params[:q] || I18n.t("menu.search"), :class => "search-query") %>
<!--%- @model_class = params[:controller].capitalize.singularize if params[:controller].capitalize.singularize.class_exists? -%-->
<%- @type_choose = params[:type] if (params.has_key? :type) and params[:type].present? -%>
<%- @model_class = params[:controller].classify.constantize if params[:controller].classify.class_exists? -%>
<%- @model_class = params[:controller].gsub(/\w+([@\s\/]+)/,"").classify.constantize if params[:controller].gsub(/\w+([@\s\/]+)/,"").classify.class_exists? -%>
<% unless @model_class.nil? %>
<%= hidden_field_tag 'model', @model_class.to_s %>
<% if (@model_class.method_defined? :columns) or (@model_class.respond_to? :columns) %>
<!--%= select_tag "type", options_from_collection_for_select(@model_class.columns, "name", "name")%-->
<%= select_tag "type", options_for_select(model_columns_collection(@model_class),@type_choose)%>
<% else %>
<% if (@model_class.method_defined? :fields) or (@model_class.respond_to? :fields) %>
<%= select_tag "type", options_for_select(model_columns_collection(@model_class),@type_choose) %>
<!--%= select_tag "type", options_from_collection_for_select(@model_class.fields.to_a, "first", "first")%-->
<% end %>
<% end %>
<% end %>
<% end %>
class CommonController < ApplicationController
authorize_resource :class => false
def search
if (params.has_key? "model") and (params["model"].present?)
@model_class = params[:model].constantize
@results = @model_class.where params[:type] => params[:q]
if @results.empty?
@results = @model_class.where("#{params[:type].to_s}. like '%#{params[:q]}%'")
end
end
render :template => 'common/search_result.html.erb'
end
end
module CommonHelper
def model_columns_collection(model_class = nil, whitelist = false )
if (model_class.method_defined? :columns) or (model_class.respond_to? :columns)
if whitelist
#model_class.columns.collect{|column| [model_class.human_attribute_name(column.name),column.name]}
#model_class.attribute_names.collect{|column| [model_class.human_attribute_name(column),column]}
model_class.attr_accessible[:default].collect{|column| [model_class.human_attribute_name(column),column]}
else
model_class.column_names.collect{|column| [model_class.human_attribute_name(column),column]}
end
else
if (model_class.method_defined? :fields) or (model_class.respond_to? :fields)
model_class.fields.to_a.collect{|field| [model_class.human_attribute_name(field.first),field.first]}
end
end
end
end
1.9.2p290 :026 > Object.const_defined? :Knowledge
=> true
1.9.2p290 :027 > Rails.const_defined? :Knowledge
=> true
1.9.2p290 :030 > Rails.const_defined? :Recommend::RecommendTag
TypeError: :Recommend is not a class/module
1.9.2p290 :033 > Recommend::RecommendTag
=> Recommend::RecommendTag
1.9.2p290 :034 > Recommend::RecommendTag.class
=> Class
1.9.2p290 :039 > Object.const_defined? "User"
=> true
1.9.2p290 :045 > defined?( Recommend::RecommendTagasd)
=> nil
1.9.2p290 :046 > defined?( Recommend::RecommendTag)
=> "constant"
if defined?(MyClassName) == 'constant' && MyClassName.class == Class
puts "its a class"
end
class String
def split_all(content = '')
content = self if content.empty?
content.split(/、|,|,|;|;|\ +|\||\r\n/) if content.class.eql? self.class
end
def to_class
Kernel.const_get self
rescue NameError
nil
end
class_name = self if class_name.nil?
#defined? Knowledge => nil
# "Knowledge".constantize
# Knowledge(id: integer, title: string, summary: text, content: text, body: text, timeline_ids: text, knowledgebase_category_id: integer, created_by: integer, created_name: string, updated_by: integer, deleted_at: datetime, deleted_by: integer, delta: boolean, created_at: datetime, updated_at: datetime, thanks_count: integer, forwarding_count: integer, comments_count: integer, views_count: integer, source_info: string, auto_tags: text, face_file_name: string, face_content_type: string, face_file_size: string)
#defined? Knowledge => "constant"
#eval("#{class_name}.is_a?(Class)") if eval("defined?(#{class_name})") == "constant"
begin
class_obj = class_name.classify.constantize
rescue
# failure handling goes here
return false
end
class_obj.is_a?(Class)
end
def is_a_defined_class?
true if self.to_class
rescue NameError
false
end
end
'String'.to_class
=> String
'unicorn'.to_class
=> nil
'puppy'.is_a_defined_class?
=> false
'Fixnum'.is_a_defined_class?
=> true
#在日常开发中,有时候会碰到要将一些单词按照它的数量来按单复数显示
#所幸rails已经考虑到了这一点,在ActionView中有一个方法
There are <%= pluralize @user.size, "user" %>.
pluralize(1, 'person')
# => 1
person pluralize(2, 'person')
# => 2 people
pluralize(3, 'person', 'users')
# => 3 users
pluralize(0, 'person')
# => 0 people
"post".pluralize
# => "posts"
"octopus".pluralize
# => "octopi"
"sheep".pluralize
# => "sheep"
"words".pluralize
# => "words"
"CamelOctopus".pluralize
# => "CamelOctopi"
1.9.2p290 :020 > "methods".singularize
=> "method"
# http://zool.iteye.com/blog/900729
<%- model_class = @model_class unless @model_class.nil? -%>
<div class="page-header">
<h1><%=t 'common.search_result.title' %></h1>
</div>
<% unless model_class.nil?%>
<div class = "results box">
<table class="table table-condensed">
<thead>
<tr>
<% model_columns_collection(@model_class,whitelist = true).each do |column|%>
<th><%= model_class.human_attribute_name(column[1]) %></th>
<% end %>
<th><%=t '.actions', :default => t("helpers.actions") %></th>
</tr>
</thead>
<tbody>
<% if @results.present? %>
<% @results.each do |result| %>
<tr>
<% model_columns_collection(@model_class,whitelist = true).each do |column|%>
<td><%= result.read_attribute(column[1]) %></td>
<% end %>
<td>
<% if self.respond_to? "auth_#{result.class.to_s.underscore.gsub("/","_")}_path" %>
<%= link_to t('.show', :default => t("helpers.links.show", :model => model_class.model_name.human)),
send("auth_#{result.class.to_s.underscore.gsub("/","_")}_path", result), :class => 'btn btn-mini' %>
<%= link_to t('.edit', :default => t("helpers.links.edit", :model => model_class.model_name.human)),
send("edit_auth_#{result.class.to_s.underscore.gsub("/","_")}_path", result), :class => 'btn btn-mini' %>
<!--%= link_to t('.destroy', :default => t("helpers.links.destroy", :model => model_class.model_name.human)),
send("auth_#{result.class.to_s.underscore.gsub("/","_")}_path", result)
:method => :delete,
:confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')),
:class => 'btn btn-mini btn-danger' %-->
<% else %>
<%= link_to t('.show', :default => t("helpers.links.show", :model => model_class.model_name.human)),
send("#{result.class.to_s.underscore.gsub("/","_")}_path", result), :class => 'btn btn-mini' %>
<%= link_to t('.edit', :default => t("helpers.links.edit", :model => model_class.model_name.human)),
send("edit_#{result.class.to_s.underscore.gsub("/","_")}_path", result), :class => 'btn btn-mini' %>
<!--%= link_to t('.destroy', :default => t("helpers.links.destroy", :model => model_class.model_name.human)),
send("#{result.class.to_s.underscore.gsub("/","_")}_path", result)
:method => :delete,
:confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')),
:class => 'btn btn-mini btn-danger' %-->
<% end %>
</td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
</div>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment