Adding acts_as_solr to an extrenal gem


November 5th, 2009

Problem

Say you have a third party database that you need your rails applications to access. But of course you want it to be modular and use it again for other applications, so you write a gem to provide access to the non-rails standard database. Now you want to add in acts as solr to search across the database from your application.

Solution

Acts as solr is a rails plugin and requires a solr server instance be running and therefore its not necessarily correct to add in the acts_as_solr plugin into your gem library. The consuming applications should be responsible for indexing what they and and how they want it. So a common trick is used to add in the application specific functionality into the gem. Initializers are used to inject the desired functionality into the gems classes. Given you have your gem named third_party_db_gem, create a file in config/initializers named something along the lines of third_party_db_gem_extensions.rb. And put in some code like:

require 'third_party_db_gem' ThirdPartyModel.class_eval do include ActsAsSolr acts_as_solr :fields => [:name, :email, :phone, job] end

Explanation

So first we had to require our gem, because our gem hasn't been loaded yet. Then we do a class_eval to inject our solr definition into one of the models. You would repeat that block for every class you wanted to index. Here's Jay Fields article more on class and instance eval.

Soft Delete Plugins Reviewed


Ruby Quickies


August 11th, 2008

  • git current branch name in your command prompt, in your .bash_login do:
BLUE1="\[\033[0;34m\]" 
GREY1="\[\033[0;37m\]" 
GREY2="\[\033[1;30m\]" 
GREEN1="\[\033[0;39m\]" 
RED1="\[\033[0;31m\]" 
WHITE1="\[\033[1;37m\]" 
END="\[\033[0m\]" 

PS1="me@$BLUE1\w$GREY2\$(parse_git_branch) > $END" 
parse_git_branch() {
  git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
  • Use Shift+option+click to highlight vertically in textmate

Monday Quickies


April 21st, 2008

Just a quick snippet of code and some links from today. Need to stop slacking on the posts:

  • Read in a csv file (can’t remember where found this)
    csv = CSV::parse(File.open(file_location, 'r') {|f| f.read })
    fields = csv.shift
    dataz = csv.collect { |record| Hash[*(0..(fields.length - 1)).collect {|index| [fields[index],record[index].to_s] }.flatten ] }
    dataz.each do |row|
      #do whatever you want
    end
  • Working on my first gem. It will do form fill on pdfs. New Gem makes it really easy by generating a nice framework for your gem.
  • Advice: Rum + Slumber Party = Rumber Party

If you are hanging with a bunch of girls, make the suggestion, because it might just work out.

Ruby Quickies


January 29th, 2008

DreamHeisted In The New Year


January 24th, 2008

Well I rang in the New Year with a lot of change, well mostly just quiting. I quit my job at CAESY a Patterson Company, smoking and apparently quit posting to my blog. I’ve been having some troubles with DreamHost this month. First I realized that this months bill was 12 times bigger. But they apperently overbilled a lot of people. I personally know quite a few. But let me know if it happened to you also, I am taking an informal survey.

Then they upgraded to their Rails to 2.0.2. I use Mephisto, which was last updated by Justin Palmer on July 26th 2006. Who btw I got to meet at the Kongregate New Years Party. So yeah, prob’ly doesn’t work. Quick fix:

From your RAILS_ROOT

rake rails:freeze:edge TAG=rel_1-2-5

killall -USR1 dispatch.fcgi

touch public/dispatch.fcgi

But more than a fix its as good lesson. Freeze your gems once you are stable, especially your rails! You can always upgrade manually.

I also just finished and released my first Facebook application, Ticket Yo-Yo. It interfaces with Free Ticket Exchange, a social ticket sharing site (still in Beta). Ticket Yo-Yo application might not be open to the public yet, turned over control to the cool dudes at Step Change Group. Here’s a screen shot.

Error Spawning cl.exe


November 5th, 2007

After installing Visual Studio 2005, I had to go back and make changes to a project made in VS 2003. But it wouldn't compile!!! We already shipped this product, so I'm fairly confident that it compiled, I mean it did make it past one of the meanist QA guys on the planet. Error message was: Error spawning 'cl.exe'.. Cl.exe is the microsoft C/C++ complier. So I guess Visual Studio lost its reference to its complier, kinda weird. I am wondering if the install of a newer Visual Studio stomped on some settings. I main develop C# with VS, so I definitely haven't had to use the C/C++ complier since i installed 05. I found this post with other people having the same problem, but with no mention of VS 2005. But the fix is quick, if you knew where to go; seams like that option is stored in an odd location.

  • Go to Tools>Options menu
  • click the Projects folder
  • Make sure 'Show directories for' is set as Executable Files
  • Make a new executable directory (in the big text area) "C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin" (change C: to whatever your installaltion drive is)


Then it should work just fine. Boring!!!

Optimize, Oh Hell No


June 25th, 2007

Lowpro is a unobtrusive javascript library written by Dan Webb. I have been reading his blog for awhile and I was forever stoked when I got to hear him talk at RailsConf07 on the Mysteries of Javascript-Fu, get the slides here. We have been using it at work to solve a piece that required some pretty heavy handed AJAXy DOM selecting (WTF am I even talking about). But it was running super slow. So we refactored and improved some of the gnarlier operations, still slow. Then everybodies' hero, Brandon, found this in the lowpro dot js on line 383:

LowPro.optimize$$ = true;
So clearly we changed the line to:
LowPro.optimize$$ = false;    // if true, super slow and lame! -BDD
And boy did it run faster.

Resizing Embedded Windows Media Player


June 25th, 2007

I having been working on a video content delivery system recently. The basic setup is that one main page opens up other windows in full screen with an embedded Windows Media Player ActiveX control, not running in fullscreen mode, but fill up the window. All was well. I was embedding ye olde CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6. But resizing the window just chopped off the video however it wanted, with the video just staying the same size. I couldn't really find too much info googling around for auto-sizing of embbed activeX controls. In the c# world I would just set the docking type to fill and it would be all good. So I just resorted to doing it myself with javascript. Note that WMPlay is the ID of the control I embedded, call yours whatever.

function myresize()
{
  document.WMPlay.width = document.body.offsetWidth;
  document.WMPlay.height = document.body.offsetHeight;
}
And then just hooked up the event handlers with prototype. Don't forget about Lowpro, which is also good at adding behaviors.
Event.observe(window, 'resize', function(){
myresize();
And just like Krunk Poof you are riding dirty.

Mephisto Pagination Plugin


May 3rd, 2007

I just added pagination to my site. Yea!! Check out down on the bottom of the page. I went with "Spiral In" and "Spiral Out" instead of the boring Next and Previous.
Mephisto, the blog engine my site is built on, is pretty rad. I like a lot of the features it has built in. And the liquid layouts aren't totally horrible once you get use to them. But being a rails programmer myself, I am more comfortable with ERB.
But one thing Mephisto is missing right out of the box is pagination. What kind of a blog doesn't paginate?
Sven Fuchs had the same idea. So he just wrote a pagination plugin for Mephisto.

God Krunked The Universe Together


April 24th, 2007

Eubonicode: An Oldie but a Goodie


April 3rd, 2007

"A new language for hackin in the hood"

This is one I had seen a long time ago. I think Duncan had shown it to me. Eubonicode was written in 2000 by three budding young complier writers Brian Bosse, Matt Poush and Chad Brewbaker(pictured on the right). Here are some code examples, they had me rolling yesterday. If anybody is bored post a sample program as a comment.

Iterative Implementation of the fibonacci

sup
{
  gimme fibo bitch
  a be 1 bitch
  b be 1 bitch
  putou a bitch
  putou b bitch
  fibo be fibo widout 2 bitch
  slongas (fibo bepimpin 0)
    c be a an b bitch
    a be b bitch
    b be c bitch
    putou b bitch
    dissin fibo bitch
  nomo
}

Print out the Prime Numbers

sup
{
  a be 1 bitch
  slongas(a fearin 100)
    b be 2 bitch
    c be 0 bitch
    slongas(b fearin a)
      if (a videdby b time b sameas a)
        propsta c bitch
      fi
      propsta b bitch
    nomo
    if (c sameas 0)
      putou a bitch
    fi
    propsta a bitch
  nomo
}
I love their looping construct, slongas. slongas(a fearin 100) means while(a <100)

WTF...Bad Code


March 27th, 2007

While rewriting an old product, I figured I would go back and see how the last team did it. Some of the old team is still at Unnamed Company, but they are the smart ones. Dig through this old php code and see if it makes you laugh too. I love the comment on the first line.

//If their is no pi_menu_arent_id set it
if (!IsSet($video_id))
{
	$video_id[] = 2; //Default for all productname

echo "";
	
foreach ($video_id as $value) 
{
   	$global_dbh = mysql_connect('localhost', 'root', '*****');
        mysql_select_db('dbname');

        //Get Video Info
       $query_string = "SELECT video_id, video_filename, video_path, video_language, video_description, video_length, video_codec,        video_audio_codec, video_bitrate, video_dts, video_project FROM	videos WHERE  video_id = $value ";
      $result_id    = mysql_query($query_string);
      $data         = mysql_fetch_array ($result_id);
     //echo mysql_errno().": ".mysql_error()."
"; //Get Speed setting $query_string1 = "select user_video_speed, user_lang FROM users WHERE user_ip = '$REMOTE_ADDR';"; $result_id1 = mysql_query($query_string1); $data1 = mysql_fetch_array ($result_id1); ... ... ...
In case you didn't see the major WTF in there, I'll spell it out for you. Notice the foreach loop, he was looping through a collection that was retrieved from a database. Then immediately inside the loop, opens another connection to the same database. So for every record you got from the first database call, it opens a new connection, selects the database, does some stuff, disconnects and starts all over again. Ughh and they are connecting to the db with the root user also. Ohh and let me tell you, the password wasn't strong. Praise Geeeebus for RoR!!!...and that the guy, who wrote this code, quit.

Downloading from URIs with C#


March 21st, 2007

Today I was trolling around in the world of windows programming. I needed to download a file from a server to the local machine. I have done that before from a samba share, which is easy, just use File.Copy(from, to). But this time the only hook I had to the file was a Uri. But file dot copy doesn't support uri formats....boo. A little research later, this is how you do it:

using System.Net;
SaveFileDialog sfd = new SaveFileDialog();
sfg.FileName = "Blarg.foo";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.OK )
{	
   try
   {
	System.Net.WebClient client = new WebClient();
	client.DownloadFile("http://ri.niculo.us/resume.pdf", sfd.FileName);
   }
   catch(Exception exc)
   {
	//Do whatever you want
   }

Phyiscally Breaking the Build


March 15th, 2007

Continuous Builder...Ah what can I say about such a wonderful addition to the development process. Always checking out our code from svn, compiling it, and running our tests against it. Just doing its job and and sending us nice emails, when we don't pass the tests. Also making sure to let everyone know who broke the build. Oh I think i figured out what to say about Continuous Builder, fuck you code gestapo bastard! I don't know how many times I have seen the email "nicka has broken the build". But there are freedom fighters out there. People who still believe in our right as developers to write code that doesn't work and submit it into our code base. These are brave and strong people, who are not afraid to stand up to the tyrannical continuous builder. Friday, Aragon broke the build, then arrogantly left for the weekend. Monday morning continuous builder let him know about it. But the tempermental Aragon wasn't having it, he promptly kicked continuous builder to the ground. There were no more emails. Continuous builder was slain that day by the righteous and revolutionary Aragon. RIP continuous builder 3-12-07.