Fix Java GUI applications in xmonad

If you ever try to run a GUI Java application when using xmonad as the Window Manager, you’ll probably end up with a nice flat grey window where your buttons, toolbars and other desktop GUI goodies should be. I ran into that problem the other day when trying to evaluate the RubyMine Ruby on Rails IDE from which I heard such good things. After a rather painful installation of the official Java 6 JDK from Oracle in Ubuntu Lucid Lynx (which I’ll write about in some other time), I managed to start up RubyMine just to find out I was seeing absolutely nothing on the screen.

I Googled a bit and essentially I found out that the problem was with the Java GUI Toolkit rather than RubyMine, because the framework relies on a list of window managers to handle some things, and xmonad is not in that list.

So since I was not using OpenJDK, I opted for the setWMName option and added this final line into my xmonad.hs file:

    xmonad $ defaultConfig
      { terminal            = myTerminal
      , workspaces          = myWorkspaces
      , keys                = keys'
      , modMask             = modMask'
      , layoutHook          = layoutHook'
      , manageHook          = manageHook'
      , logHook             = myLogHook dzenLeftBar >> fadeInactiveLogHook 0xdddddddd
      , normalBorderColor   = colorNormalBorder
      , focusedBorderColor  = colorFocusedBorder
      , borderWidth         = 2
      , startupHook         = setWMName "LG3D"
}

Setting the window manager name to LG3D will trick the Java GUI Toolkit and the application will be painted correctly.

Enjoy your Java applications with the power of xmonad!

Share

Ruby on Rails Many To Many associations with multiple databases

Sometimes you need to use multiple databases in your Rails projects. Usually when some data must be shared between different applications. When this happens you usually have some models in a shared database, and some other models in the specific application database. This can be easily done using the establish_connection method in the shared models to tell them they have to connect to a different database.

However, when you need some interaction between those shared models and the models of your specific application, like a has_many, :through association, some problems arise. The typical Many To Many association uses an intermediate database table that links the relation between two models, and allows you to add some extra information on that relation. When navigating through the association, Rails tries to make an SQL query that joins the model with this intermediate table. For example, imagine you have a Team model, which has many Players, but a player can also be on more than one team. We use an intermediate model TeamPlayers (and we can also use it to save the role of that player into that team, for example). You would have those three tables:

  • teams
  • players
  • teams_players

When asking for the players of a given Team, Rails would do something similar to this:

SELECT "players".* FROM "players" INNER JOIN teams_players" ON "players".id = "teams_players".player_id WHERE "players".team_id = 1

Where 1 is the id of the team you asked for. This [obviously] works perfectly fine when everything is in the same database, and it’s as efficient as the SQL database manager you’re using. What happens, however, when we have the Player model in another database? It will miserably fail because Rails will try to join with a table that doesn’t exist.

Unfortunately, there’s no efficient way to solve this problem, that is, using SQL, as you can’t work with tables from different databases. However, there’s a rather elegant solution that Brian Doll cared to implement as a gem a while ago. As indicated in the GitHub readme, you just have to use a has_many_elsewhere relation instead of the usual one, and make sure that the model referenced has the connection established to the shared database. And that’s all.

The magic donde behind the scenes is pretty simple: this gem just replicates the same methods that the ActiveRecord::Base class does in the has_many method call, changing the failing unique SQL calls to double SQL calls, one for each database, fetching the intermediate models first, and then fetching the remote models using those ids.

This method is not perfect, as probably not all the goodness of the original association can be done with it, but for simple scenarios is more than enough.

Share

Creating your own Job Managers in Ubiquo

Ubiquo is a Ruby on Rails, MIT Licensed Open Source CMS we develop and use at gnuine for a variety of projects. One of the features of Ubiquo is the ability to run jobs separately from the http requests to the site. Today I’m going to show you how to customize the Ubiquo Jobs plugin to create your own types of jobs and managers to launch them.

Sometimes can be useful to create different managers. An example of this situation is when you want to run different kind of jobs in different circumstances.

Ubiquo Jobs provides a default manager which will get ActiveJob jobs depending on priorities and schedule times:

def self.get(runner)
  recovery(runner)
  candidate_jobs = job_class.all(
    :conditions => [
      'planified_at <= ? AND state = ?',
      Time.now.utc,
      UbiquoJobs::Jobs::Base::STATES[:waiting]
    ],
    :order => 'priority asc'
  )
  job = first_without_dependencies(candidate_jobs)
  job.update_attributes({
      :state => UbiquoJobs::Jobs::Base::STATES[:instantiated],
      :runner => runner
    }) if job
  job
end

The job_class variable defaults to UbiquoJobs::Jobs::ActiveJob. If you want to make your own manager to handle special jobs, or change the way the jobs are picked, the best way to do so is to implement your own manager. A nice rails-like way to do that is include them in the lib/ folder of your ubiquo project.
The class you should inherit from is UbiquoJobs::Managers::ActiveManager. If you wanted the manager to just pick up a specific subclass of ubiquo jobs, it would suffice to reimplement the self.job_class class method to return your own kind of job:

def self.job_class
  UbiquoJobs::Jobs::YourJobClass
end

However, there’s a better way to do this. For this special case, the default UbiquoJob class provides a special member which stores the job’s class name, allowing you to select all objects subclasses of ActiveJob by its classname. For example, imagine you have a kind of job for special tasks that you know for sure will take a long time to complete. Seems reasonable to have a different manager to handle those jobs. You would create a new job in the file app/jobs/very_long_job.rb:

class VeryLongJob < UbiquoJobs::Jobs::ActiveJob
  def do_job_work
    #Do what needs to be done here
    return 0
  end
end

Then you could create a manager that handles only those kind of jobs by implementing your own subclass of the UbiquoJobs::Managers::ActiveManager class:

module JobManagers
  class VeryLongJobManager < UbiquoJobs::Managers::ActiveManager
    def self.get(runner)
      recovery(runner)
      candidate_jobs = job_class.all(
        :conditions => [
          'planified_at <= ? AND state = ? AND type = ?', 
          Time.now.utc,
          UbiquoJobs::Jobs::Base::STATES[:waiting],
          'VeryLongJob'
        ],
        :order => 'priority asc'
      )
      job = first_without_dependencies(candidate_jobs)
      job.update_attributes({
          :state => UbiquoJobs::Jobs::Base::STATES[:instantiated],
          :runner => runner
        }) if job
      job
    end
  end
end

The code is exactly the same as the default ActiveManager class, but the finder will take an extra parameter, 'VeryLongJob', to indicate that only the ActiveJob objects that are of the subclass VerylongJob should be taken.

After that, you need to modify the task that calls the workers so it takes your manager, or create a new task that will run your manager. The default task that will
start a worker looks as this:

desc "Starts a new ubiquo worker"
task :start, [:name, :interval] => [:environment] do |t, args|
  options = {
    :sleep_time => args.interval.to_f
  }.delete_if { |k,v| v.blank? }
  UbiquoWorker.init(args.name, options)
end

This uses a special configuration parameter to determine the manager to use. This configuration option is stored in Ubiquo::Config.context(:ubiquo_jobs), the name of the configuration option is :job_manager_class, and takes the manager class as a value. So in order to create a task that will use your manager, you should create a new task like this one:

desc "Starts a new ubiquo worker"
task :start_very_long_jobs, [:name, :interval] => [:environment] do |t, args|
  options = {
    :sleep_time => args.interval.to_f
  }.delete_if { |k,v| v.blank? }
  Ubiquo::Config.context(:ubiquo_jobs).set(:job_manager_class, JobManagers::VeryLongJobManager)
  UbiquoWorker.init(args.name, options)
end

Your should call this task like this (assuming it’s on the same namespace as the default task):


rake ubiquo:worker:start_very_long_jobs[name,interval]

Share

Simple guide to configure xmonad, dzen2 and conky

I’ll guide you through the different steps I took to install a working desktop environment in Debian using xmonad, conky and dzen2.

The final result of this configuration should look like this:

xmonad with dzen2 and conky

xmonad with dzen2 and conky

Continue reading “Simple guide to configure xmonad, dzen2 and conky” »

Share

Iterate over a collection in groups, and other things

One thing I find fascinating about Ruby is the fact that most common tasks are already programmed for you in its library. The Enumerable module is a clear example of that, providing you with lots of functionality to manipulate collections of objects.

One of those useful methods I discovered the other day was each_slice. This method allows you to iterate over the collection, just as each does, but lets you do it changing how many elements of the collection you get on each iteration. This is the example you can get from the documentation page:

(1..10).each_slice(3) {|a| p a}
# outputs below
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
[10]

You can see that from the original array from 1 to 10, on every iteration Ruby prints the numbers in groups of three, and the last one alone since the collection is not a multiple of 3. Now think about having to do this manually: it’s not that hard, but its error prone and you have to do all that typical arithmetic logic that should be easy but never is. How handy that Ruby has already done that job for you.

This method is also pretty useful when working in Ruby on Rails. One simple example is when you have to manually implement some kind of pagination, or show a list of elements in columns or rows of fixed size: you have to simply iterate with each_slice and put the page/row/column logic on the block, and voilà.

I strongly suggest you take a look at the Enumerable module reference to take a look at all the other flavours of each methods it has and I’m sure you’ll find all of them pretty useful in lots of situations!

Share

Easily select random records in rails

If you ever wondered how to easily retrieve a random record in an ActiveRecord model, here’s en easy way to do that: use the sample method.

sample is a class method from the Array class that retrieves one or more random items from an array instance. It conveniently returns nil or an array lesser than the items requested if the original array has not enough items.

Since all ActiveRecord finds return an array, you can easily add the sample call at the end of a find call to get the random items you need from complex queries.

For example, imagine you have a Book model which has a published_at datetime attribute and you want to show, in your library home page, a random selection of 5 books that have been published. You can easily get those using this snippet:

def get_random_books_for_home_page
  find(:all).sample(5)
end

Share

WordPress AddToAny plugin

If you encounter problems after upgrading WordPress and the AddToAny plugin version .9.9.9.1 (the one I tested), try to update your footer.php file of your current theme too add this line just before the closing body tag:

<?php wp_footer(); ?>

It seems that newer versions of the plugin put some javascript code into the footer section, so without this call, there’s no javascript for AddToAny, and without javascript, you can’t see the popup div that allows you to select the service you want to use to share your posts.

Share

Fixtures and serialized attributes in Ruby on Rails

If you’ve ever used the serialize method in an ActiveRecord model, you may have faced the problem of writing a fixture for that particular serialized field. The serialize method is quite handy if you need to store a complex object (like a Hash or an Array) in a database field, without having to create additional models and relationships between them. A good example could be store the preferences of a user in a hash:

class User < ActiveRecord::Base
    serialize :preferences, Hash
  end

This way you can set and get the preferences attribute of the user without having to worry much about it:

User.first.preferences # => {:show_email => true, :allow_pm => :false, ...}
user = User.first
user.preferences = {:show_email => true, :allow_pm => :false}
user.save

In order to do that, at the database table for the User class, among the other fields you’ll need to add a text column for the preferences. After that, you can easily work with your model without too much of a hassle.

If you care to look at the rows of the model’s table, you’ll see that the serialized attribute is stored in YAML format:

sqlite> select preferences from users where id = 1;
--- 
:show_email: false
:allow_pm: false

Now, that if you need to add a fixture for your model that needs the preferences attribute to be set to a particular value? If you have to manually parse the value you want to put in there to be tested, it’ll be a pain in the ass. Even if you have a script that converts certain values to YAML so you can copy and paste the script output to the fixture, it’s not very comfortable. Hopefully, you have to remember that you can use some ERB magic in your fixtures :) So, here’s the deal if you need to add something to the serializable attribute:

one:
  preferences: <%= {:show_email => true, :allow_pm => :false}.to_yaml.inspect  %>

The to_yaml method converts the Hash into a YAML representation, and with inspect we convert that to a string. Using this technique, we can add whatever we want to a serialized field in our fixtures.

Share

Installing xmonad in ArchLinux

For some reason, the ArchLinux wiki is kind of outdated explaining how to install xmonad in Arch. Also, the new packages seem to have a bug and the xmonad installation won’t work out of the box. Here you have detailed steps on how to install and run xmonad on ArchLinux.
First of all, you need to install the Xorg server. Refer to Xorg for detailed instructions. After that, you’ll need to install the xmonad packages, named xmonad and xmonad-contrib.

pacman -Syu xmonad xmonad-contrib

This will install xmonad and all the required dependencies. After that, if you want a fairly simple X setup, add the line xmonad to your ~/.xinitrc file (hopefully you’ll be using a display manager that uses that file like SLiM). If you try this on a freshly installed ArchLinux system, though, it won’t work. There are some missing steps to do. First of all, you need to create the folder ~/.xmonad.

mkdir ~/.xmonad

After that, you need to create a new xmonad config file, called xmonad.hs

import XMonad
 
main = do
    xmonad $ defaultConfig

Once you have you configuration file in place, it’s time to rebuild xmonad:

xmonad --recompile

And that’s all, you should be able to start your fresh new xmonad setup in ArchLinux. By the way, if you wonder why pressing Mod1 + Shift + Enter does nothing, make sure you have the package xterm installed.

Cheers!

Share

Handling resizing in Adobe Air with HTML

If you develop a widget with Adobe AIR using HTML and Javascript, you may want to resize some elements of the HTML page depending on the size of the widget, thus having to resize them when the user decides to resize the widget. However, there’s a little trick on using the RESIZE event of the air.Event object.

The trick is that when the event is raised, and you execute some method on the corresponding event handler, the widget won’t have the correct size yet, so if you use the window.nativeWindow.width or window.nativeWindow.height values there you’ll be getting erroneus results.

The solution is quite easy, though. You just have to let the HTML engine to adjust everything he needs to sort out the new sizes and get those attributes after that. How do you do that? By putting your code in a setTimeout call with 0 milliseconds timer. Here you can find an example (assuming use of jQuery):

$(document).ready(function() {
    window.nativeWindow.addEventListener(air.Event.RESIZE, onResize);
});
 
function onResize() {
    var nativeWin = window.nativeWindow;
    setTimeout(function(){
    var width = nativeWin.width;
    var height = nativeWin.height;
    }, 0);
} //Here the values are correct

Share
←Older