Send Commands From VIM to Tmux Pane

I’ve started using Tmux w/ VIM as my primary work flow. I installed the tslime.vim plugin, which will send highlighted commands to another pane, but I wanted to send ad-hoc commands, like :!. I added this function to the tslime.vim file, I’m sure there is a better way, but that’s what I did for now.

function! To_Tmux()
  let b:text = input("tmux:", "", "custom,")
  call Send_to_Tmux(b:text . "\\r")
endfunction

cmap tt :call To_Tmux()<CR>

This will allow me to type :tt and then any needed commmand, like rake. The tslime plugin will ask which pane number, then send the command to that pane from then on. The selected pane can be changed with <C-c>v.

my forked tslime


ITerm2 TMux and Vim Setup

Setup

  • Install MacVim
  • Install ITerm2
  • Install Tmux: brew install tmux
  • Install Tmux Patch for copy to OSX: tmux-MacOSX-pasteboard
  • Change shell to zsh chsh -s /bin/zsh && sudo chsh -s /bin/zsh username

Tmux Config

This sets some nice things for tmux. Of note, changing the default prefix to Ctrl+a and setting up the copy patch.

/.tmux.conf

set -g default-terminal "screen-256color"
setw -g mode-mouse on
set -g prefix C-a

setw -g mode-keys vi

bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

bind-key -r C-h select-window -t :-
bind-key -r C-l select-window -t :+

# copy to osx
set-option -g default-command "reattach-to-user-namespace -l zsh"
bind ^y run-shell "reattach-to-user-namespace -l zsh -c 'tmux showb | pbcopy'"

# quick pane cycling
unbind ^a
bind ^a select-pane -t :.+

VIM

Had to add

syn on

to my .vimrc to get syntax highlighting in console mode.

Resources


Twitter and Facebook Popup Windows

I often find my self needing to add Twitter and Facebook share buttons. Usually not using the default widget icons. To do that you need some functions to call window.open and some jQuery to tie the links to those functions. These functions also encode the passed parameters.

var tweetWindow = function(url, text) {
  window.open( "http://twitter.com/share?url=" + 
    encodeURIComponent(url) + "&text=" + 
    encodeURIComponent(text) + "&count=none/", 
    "tweet", "height=300,width=550,resizable=1" ) 
}

var faceWindow = function(url, title) {
  window.open( "http://www.facebook.com/sharer.php?u=" + 
    encodeURIComponent(url) + "&t=" + 
    encodeURIComponent(title), 
    "facebook", "height=300,width=550,resizable=1" ) 
}

jQuery to enhance the link. This may or may not be used with the above.

$(".twitter").click(function(e) {
    e.preventDefault();
    var href = $(e.target).attr('href');
    window.open(href, "tweet", "height=300,width=550,resizable=1") 
});

The link; using target _blank to work without JavaScript

<a href="https://twitter.com/share?text=SOME%20TEXT&via=candland" 
    class="twitter" 
    target="_blank">Twitter Link</a>

Some Rails Tips and Tricks

After doing a lot of refactoring today I wanted to note a few useful things I’ve picked up.

load the rails environment for rake

If you need to run a rake task that need access to the Rails models, etc. add the :environment dependency

task :my_task => :environment do 
end

Testing Delayed Job

Added the following to tell Delayed Job to run without delays.

Delayed::Worker.delay_jobs = false

Or the following to run a last Job and check for Success and Fail, in the returned array.

Delayed::Worker.new.work_off.should == [1, 0]

Check the Job Count with one of the following

Delayed::Job.count.should == 1

# OR

lambda do
  # code the should schedule a delayed job
end.to change(Delayed::Job.count).by(1)

ActiveRecord add_column and update

In a migration, sometimes you want to add a new column, then update it do a new value.

def self.up
  add_column :users, :plan_id, :integer
  User.update_all("plan_id = 1")
end

FactoryGirl Callbacks

When setting up complex relationships with FactoryGirl, callbacks can help.

FactoryGirl Callbacks

Factory.define :user do |user|
  user.name "Dusty Candland"
  user.email "testing@testing.com"
  user.phone "303-333-3333"
  user.password "foobar"
  user.password_confirmation "foobar"
end

Factory.define :user_with_subscription, :parent => :user do |user|
  user.after_create{|u| Factory(:user_subscription, :user => u)}
end

Factory.define :user_subscription do |sub|
  sub.first_name 'beta'
  sub.last_name 'test'
  sub.number '4111111111111111'
  sub.expiration_year 2012
  sub.expiration_month 1
  sub.zip_code '90210'
  sub.price 2.50
  sub.group_limit 1
  sub.message_limit 100
  sub.association :plan
  sub.user_id 1
end

Rails AJAX Posts Session Reset

Notes regarding AJAX post requests being logged out on Rails. Seems the problem is not adding the CSRF data.

The problem was that AJAX post requests resulted in a redirect to the login page. Further inspection showed the cookie was being passed, but the session on server was empty. Rails wasn’t getting the correct CSRF value and as a result, resetting the session data.

This StackOverflow post has some useful info Rails not reloading session on ajax post.

This lead to a post by Jason Weathered CSRF vulnerability in Ruby on Rails 2.3.10 & 3.0.3.

Which ended up at the jQuery UJS project. Installing this fixed the problem!


Moving My Blog to the Toto Ruby Blog

I’ve decided to switch this blog off wordpress and go w/ something closer to the metal. Toto is a rack based blogging engine that uses markdown and basic test files. This is a good approach because you get complete control, but also an editing environment that’s close to normal coding. Heres some links that helped me get up and running.

Getting Started With toto

XmlRPC UTF-8 Fix

Blogging With Toto

require 'rubygems'
require 'fastercsv'
require 'xmlrpc/client'

USERID = '&lt;userid>'
PASSWORD = '&lt;password>'

# http://www.eggheadcafe.com/microsoft/Ruby/36270580/xmlrpc-rexml-incorrectly-handles-utf8-data.aspx
# http://tedwise.com/2010/05/25/blogging-with-toto/
module XMLRPCWorkAround
    def do_rpc(request, async=false)
        data = super
        data.force_encoding("UTF-8")
        data
    end
end

def getPages(blog)
  blog.call("wp.getPages", 0, USERID, PASSWORD, 1000)
end

def getPosts(blog)
  blog.call("metaWeblog.getRecentPosts", 0, USERID, PASSWORD, 1000)
end

def slugify(title)
  title.downcase.gsub(/[ \._]/, '-')
end

blog = XMLRPC::Client.new3(:host => "&lt;your-wordpress-blog.com>", :path => "/xmlrpc.php")
blog.extend(XMLRPCWorkAround)
begin
  puts "Logging into blog and getting the list of posts..."
  posts = getPosts(blog)
  puts "  response received, found #{posts.size} posts"
  `mkdir articles`
  posts.each do |post|
    permaLink = post['permaLink']
        puts permaLink
    dateAndName = permaLink.gsub(/http:\/\/your-wordpress-blog\.com\//, '').split('/')
    postFilename = 'articles/' + dateAndName.join('-') + '.txt'
    postDate = dateAndName[0] + '/' + dateAndName[1] + '/' + dateAndName[2]
    escapedTitle = post['title'].gsub(/"/, '\\"')
    File.open(postFilename, "w") do |postFile|
      postFile.puts("title: \"#{escapedTitle}\"")
      postFile.puts("author: dusty candland")
      postFile.puts("date: #{postDate}")
      postFile.puts("slug: #{dateAndName[3]}")
      puts "#{post['title']} - #{postDate}"
      postFile.puts("categories: #{post['categories']}")
      postFile.puts("keywords: #{post['mt_keywords']}")
      postFile.puts
      postFile.puts post['description']
    end
  end
rescue XMLRPC::FaultException => e
   puts "ERROR: Code: #{e.faultCode}"
   puts "ERROR: Msg.: #{e.faultString}"
end


Rails No Data Model

Take advantage of ActiveModel without a database backend.

class NoDataModel
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value) if respond_to? "#{name}="
    end
  end

  def persisted?
    false
  end
end

Brutalist Framework