-
-
Save kivanio/236870 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| 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 | |
| [status, headers, response_body(response.body)] | |
| end | |
| private | |
| def response_body(response) | |
| response += '<h3>Tables indexes:</h3><dl>' | |
| get_indexes.each{|obj| response += "<dt>#{obj.table}</dt><dd>#{obj.name}</dd>"} | |
| response += '</dl>' | |
| response += ' | |
| <h3> Add/remove index </h3> | |
| <form method="get" action=""> | |
| <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>' | |
| 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