beforeRunningCommand nop bundleUUID 5C3E29B9-B473-457E-A850-9499F1FD783C command #!/usr/bin/env ruby require "#{ENV["TM_SUPPORT_PATH"]}/lib/dialog" require ENV['TM_SUPPORT_PATH'] + "/lib/exit_codes" require 'yaml' unless ENV['TM_FILEPATH'] =~ /\/test/ TextMate.exit_show_tool_tip "you're not in the context of a rails project" exit 1 else tbl_name = File.basename(ENV['TM_FILEPATH'], '.yml') end rails_dir = $` class Hash def to_yaml( sort ) YAML::quick_emit( object_id, {} ) do |out| out.map( taguri, to_yaml_style ) do |map| sort_by{|k,v| sort.index(k)}.each do |k, v| map.add( k, v ) end end end end end class MysqlRetriever def initialize(tbl_name, conf) require 'mysql' @tbl_name = tbl_name @db = Mysql.connect *conf.values_at(*%w[host username password database]) end def table_exists? r = @db.query "show tables like '#@tbl_name'" r.fetch_row end def columns res = @db.query "show fields from #@tbl_name" res.extend Enumerable res.map{|r| r[0]} end def find_pk_field res = @db.query "show fields from #@tbl_name" res.extend Enumerable pk = res.find{|r| r[3] == "PRI"} unless pk TextMate.exit_show_tool_tip "Can't find the primary key" exit 1 end pk[0] end def find_record(id) res = @db.query "select * from #@tbl_name where #{find_pk_field} = #{id}" record = res.fetch_hash unless record TextMate.exit_show_tool_tip "Can't find record #{id}" exit 1 end record end end class ActiveRecordRetriever def initialize(tbl_name, conf) require 'rubygems' require 'active_record' eval "class #{tbl_name.classify} < ActiveRecord::Base; end", TOPLEVEL_BINDING @model = tbl_name.classify.constantize ActiveRecord::Base.establish_connection conf end def table_exists? @model.table_exists? end def columns @model.columns.map{|clm| clm.name} end def find_record(id) @model.find(id).attributes rescue TextMate.exit_show_tool_tip $! exit 1 end end require 'yaml' conf = YAML.load(File.read(rails_dir + "/config/database.yml")) db_conf = conf['development'] retriever = db_conf['adapter'] == 'mysql1' ? MysqlRetriever.new(tbl_name, db_conf) : ActiveRecordRetriever.new(tbl_name, db_conf) unless retriever.table_exists? TextMate.exit_show_tool_tip "there is no table called #{tbl_name}" exit 1 end id = Dialog.request_string( :prompt => "Enter record id", :button1 => "OK", :button2 => "Cancel" ) exit unless id record = retriever.find_record(id) yml = record.to_yaml(retriever.columns) puts "${1:fixure#{id}}:" puts yml.to_a[1..-1].map{|l| ' ' + l}.join input none name rails: new fixture from db output insertAsSnippet scope source.yaml tabTrigger fix uuid D5FD8C43-9E32-4007-8578-600F78857FDC