Skip to content

Instantly share code, notes, and snippets.

@mikhailov
Created November 16, 2009 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikhailov/235736 to your computer and use it in GitHub Desktop.
Save mikhailov/235736 to your computer and use it in GitHub Desktop.
DbIndexes - activerecord index handlier
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment