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

Notes On Capistrano to Windows 2008

http://www.petri.co.il/setup-ssh-server-vista.htm

install openssh via cygwin, include vim and git.

setup git in cygwin not windows

if git for windows is installed, do not include use the git unix commands (remove from PATH if you installed that way)

Change the .bashrc file to prepend /usr/local/bin:/usr/bin to path

export PATH=/usr/local/bin:/usr/bin:$PATH

If not running interactively, don’t do anything

[[ “$–” != i ]] && return

debug path issues

cap shell

cap> echo $PATH

IIS SETUP

http://blogs.iis.net/ruslany/archive/2008/08/07/ruby-on-rails-in-iis-7-0-with-url-rewriter.aspx


Savon.rb client for .Net web service.

This is a quick post to help anyone looking for info on consuming a dotNet based webservice using the savon gem for ruby. The main issue is that .net expects a namespace on the action element in the soap body. This can be done easily in the call to client#request as shown in the following gist. Hope this saves someone, maybe future me, some time!


Brutalist Framework