Skip to content

Instantly share code, notes, and snippets.

@levicole
Created July 20, 2011 00:32
Show Gist options
  • Save levicole/1094082 to your computer and use it in GitHub Desktop.
Save levicole/1094082 to your computer and use it in GitHub Desktop.
Terminal Admin

TerminalAdmin

Slightly inspired by the interactive_editor gem, this allows you to edit mongoid documents as yaml in vim. Once the file is written, the changes are applied to that object. If you tack on the bang, then the changes are automatically persisted to the database.

example:

require 'mongoid'

Mongoid.configure do |config|
  config.master = Mongo::Connection.new.db("terminal_admin")
end

class Product
  include Mongoid::Document
  field :name, :type => String
  field :price, :type => Integer
end

require 'terminal_admin'

product = Product.new

product.edit
module Mongoid::Document
require 'tempfile'
def edit
tmp_file = new_temp_file
open_for_editing(tmp_file)
update_from_file(tmp_file)
end
def edit!
edit
save
end
private
def editable_fields
fields.keys - ["_id", "_type"]
end
def editable_attributes
attrs = {}
editable_fields.each { |k| attrs[k] = attributes[k] }
attrs
end
def new_temp_file
tmp_file = Tempfile.new([self._id, '.yml'])
tmp_file.open
tmp_file.write(editable_attributes.to_yaml)
tmp_file.close
tmp_file
end
def open_for_editing(tmp_file)
system "vim #{tmp_file.path}"
end
def update_from_file(tmp_file)
attrs = YAML.load(tmp_file.open.read)
self.attributes = attrs
end
end
@inkel
Copy link

inkel commented Jul 25, 2011

Nice idea. It would be great to use ENV['EDITOR'] instead of hardcoding vim.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment