public
Last active

DbIndexes - activerecord index handlier

  • Download Gist
db_indexes.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
require(File.dirname(__FILE__) + '/../config/environment') unless defined?(Rails)
 
class DbIndexes
def initialize(app, message = "Database Indexes")
@app = app
@message = message
end
 
def call env
request = Rack::Request.new env
status, headers, response = @app.call(env)
begin
table = request.params['table_name']
column = request.params['column_name']
act = request.params['act']
 
if table and column
index_workflow(act, table, column)
end
rescue
response.body += 'Something wrong :('
end
body = request.xhr? ? response.body : response_body(response.body)
[status, headers, body]
end
 
private
 
def response_body(response)
response += '<div id="dbIndexes">'
response += '<h4 class="switcher">Tables indexes:</h4>
<dl class="area">'
 
get_indexes.each{|obj| response += "<dt>#{obj.table}</dt><dd>#{obj.name}</dd>"}
response += '</dl>'
response += '
<h3 class="area"> Add/remove index </h3>
<form method="get" action="" class="area">
<input type="text" name="table_name" id="table_name"/>
<input type="text" name="column_name" id="column_name"/><br />
<input type="radio" name="act" value="create">Add<br />
<input type="radio" name="act" value="destroy">Delete<br />
<input type="submit" value="Do" name="commit"/>
</form>'
response += '</div>'
 
response += '<script type="text/javascript">
$("#dbIndexes > .area").hide();
 
$("#dbIndexes > .switcher").click(function(){
$("#dbIndexes > .area").toggle()
}).css({"cursor":"pointer"});
 
$("#dbIndexes").css({
"margin": "5px",
"padding": "10px",
"border": "1px dotted blue",
"width": "450px"
});
$("#dbIndexes >h4").css({
"margin": "0"
});
</script>
'
end
 
def get_indexes
t = ActiveRecord::Base.connection.tables.\
collect(&:to_sym).
reject{|i| i.eql?(:schema_migrations) || i.eql?(:sessions)}
i = t.collect{|i| ActiveRecord::Base.connection.indexes i}
return i.reject!(&:blank?)[0]
end
 
 
def index_workflow(act, table_name, column_name)
table = table_name.to_sym
c = column_name
column = c =~ /,/ ? c.split(', ').collect(&:to_sym) : c.to_sym
 
if act.eql?('create')
ActiveRecord::Migration.add_index(table,column)
elsif act.eql?('destroy')
ActiveRecord::Migration.remove_index(table,column)
end
end
 
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.