Tigraine

Daniel Hoelbling-Inzko talks about programming

Installing Eclipse on Mac OSX

Most Mac applications come bundled as a .app package that you simply have to drag&drop into your Applications for them to show up in Launchpad and Alfred. Or, if an application is a bit more complex you usually get a .dmg file that then installs like any normal MSI package you are used to from windows.

Not Eclipse for OSX. The Eclipse project maintainers do provide a OSX binary, but it doesn't look like most OSX .app packages in that the extracted binaries are a folder that then contains a .app.

If you only copy over the .app file you'll not be able to start Eclipse as it's just a starter script and the real Eclipse is living in the extracted Zip. I used to just start eclipse wherever I unpacked it, but apparently the right way to install it is to simply copy the whole extracted eclipse folder over to your Applications. Even though the .app is not in /Applications directly OSX picks it up and it shows up in Launchpad.

Filed under programmierung, java

When to use raw() and when to use .html_safe

What rails does very nicely is protect you from XSS attacks through aggressively HTML encoding anything you write between <%= %>. But there is one caveat: At times you may really want to render HTML from a string. So you need to tell rails not to escape your HTML in that case.

There are two methods of telling rails that a string is safe and should not be escaped: raw and .htmlsafe

And both do the same. They mark the string as safe (through the use of the html safe buffer) and rails will not encode it any more. The main difference between the two: nil.

If you are doing things like: "<img src='#{..}' />".html_safe .html_safe is totally fine as the string will never be nil, but if you are dealing with strings that may be nil .html_safe will break since there is no .html_safe method on the nil object. (For example if you are loading something from a config value or the database) In that case using raw(...) will just ignore the string instead of raising an exception.

As always with these things: raw and html_safe make it very easy to introduce XSS attack vectors into your application. So use them wisely and only on strings you are sure to be safe.

Filed under programmierung, rails, ruby

How to expire all active Sessions in Rails 3

I know this sounds like a very simple task to do, but since I just spent half an hour reading up on how Sessions in Rails work I decided it's time to put this up so I can Google it again next time :)

First off, you need to know how you are storing sessions in your application. Rails supports 3 types of session storage: Stored on Disk, in the Database or through Cookies in the client. You can check which one you are using in /config/initializers/session_store.rb.

Cookie based session storage

Rails 3 defaults to storing the session in the client using a session cookie. This means that the user_id along with all the data you put into the session hash is serialized into the cookie and sent to the client. It's also not encrypted, only BASE64 encoded so if you are storing anything sensitive in there you are doing it wrong.

But for simple things like the current user_id the cookie based session store is just fine and also a lot faster than the alternatives.

Expiring the cookie though is a bit more involved since you can't reach out to all clients and delete their cookies at once. But, and that's the important part for what I was doing: This cookie is signed with a SHA-512 digest using a secret key that is only present on the server. So the cookie cannot be tampered with on the client, and this is also your avenue of attack when trying to expire all cookies:

Simply change the secret that is used to sign the cookies. All previous cookies are invalidated as their digest is no longer valid.

Doing so is simple, first generate a new secret using rake:

$ rake secret 10dfec4781b682762a731a5e88af78521fc3e0f...

Then copy/paste that new secret into your config/initializers/secret_token.rb:

MyApp::Application.config.secret_token = '10dfec4781b682762a731a5e88...'

Once done deploy the application and all existing sessions are invalid at once.

Database backed session storage

If you are using the Database to store the session it's rather trivial to expire all existing sessions using rake:

rake db:sessions:clear

File based session storage

Like with the database simply run the following rake command:

rake tmp:sessions:clear

Hope this helps..

Filed under programmierung, rails, ruby

Optional locals in Rails partial templates

In Rails it is very advisable to not use any instance variables inside your partials if you want to re-use that partial in a different context.

It is much better to simply leverage locals that you pass into your render like this:

That way you can simply use posts inside the template without having to rely on @posts coming from the controller (and it's also not dependant on controller code any more but rather only on data inside the view that's calling it.. very handy).

But, as always there are times when you have additional locals that are optional to only some contexts. In my case I had Kaminari paginate the list I was passing to the partial, but in some other views the list was not be paginated. Turns out you can't do the usual rails style if foo here because the variable is simply not defined and Ruby will throw an error (unlike with @variables in Rails).

That's where the defined? method comes in very handy (as suggested by Thorsten Ball):

If you simply want to assign a default value to a local you can use the ||= operator:

This enables me to use the partial in several ways without having to re-introduce the locals at every corner:

Filed under programmierung, rails, ruby

Removing delete and destroy in Rails models

Today I had an interesting feature request to implement: Get rid of all deletions and replace them with a deleted flag in the DB.

It's the usual story: Nobody really does deletes but rather everything is put into the DB in case it's needed at some later point. Unfortunately I didn't know about this particular feature until after I had finished most of the coding for the Rails application so going through the code and removing all destroy code from controllers was pretty much out of the question.

Instead I remembered reading about Modules in Ruby and how they can bolt on functionality to Classes.

Turns out it's totally trivial to remove deletion from Rails Models with 10 odd lines of code in a completely transparent an unobtrusive way:

module NotDeleteable
  def destroy
    unless self.respond_to? :deleted
      raise MissingMigrationException
    end

self.update_attribute :deleted, true end

def delete self.destroy end

def self.included(base) base.class_eval do default_scope where( :deleted => false ) end end end

class MissingMigrationException < Exception def message "Model is lacking the deleted boolean field for NotDeleteable to work" end end

This will override the default destroy/delete method provided by ActiveRecord::Base and also install a default_scope into the Model class so Rails will by default append WHERE deleted = false to all SQL queries made through the ActiveRecord Query Interface

You use this by simply including this module inside your Model class:

class User < ActiveRecord::Base
  include NotDeleteable
end
Did I mention that I really like Ruby?

Word of warning: I have no clue if I am breaking :dependant => :destroy on ActiveRecord relations in any way, but I suspect it should still be alright.

Update: The original code had an issue where you could not mark a record that is invalid as deleted. This was due to the fact that I was using save instead of update_attribute.

Filed under programmierung, rails, ruby

New team member on dotless: Luke Page

You may have noticed that my blog is filling itself slowly with stuff about Ruby and Unix in general. This has to do with the fact that for now 3 months I am working on Rails full time with very little to no .NET work in between.

While this is awesome for me and I am really enjoying it - it also means that I don't have a .NET dev environment available at work and quickly merging in a pull request and testing it has become quite a hassle. So dotless has had quite some open tickets that where already fixed but where not yet merged into the mainline due to me lagging behind on responding to pull requests.

Fortunately, most/all pull requests have come from our very active Luke Page who has been busily fixing bugs and contributing features - so adding him to the dotless core team is a logical choice to cut down on the lag I or James where inducing into the process.

Since James felt the same we are happy to announce that Luke Page is now part of the dotless team with commit access and everything. So, welcome onboard Luke! Thanks for being part of dotless :)

Rails .to_json nested includes and methods

Defining assocations to be included in the rendered Json in Rails is pretty easy. You just use the options hash to define an include in to_json and by voodoo magic to_json will also traverse the ActiveRecord assocation and render the associated entity as a nested element in the Json. The code in question is quite simple:

@object.to_json({:include => :assocation_a})

By default Rails will only include attributes in to_json so if you want to also serialize the return value from a method (for example if you want to concatenate some attributes or compute something) you can do so through the options hash:

@object.to_json({:methods => :my_method})

You can also combine them easily if needed:

@object.to_json({:include => :assocation_a, :methods => :my_method})

But this calls the my_method on @object. How do you tell to_json to invoke my_method on @object.assocation_a?

Not trivial, but it works:

@object.to_json({:include => { :assocation_a => { :methods => :my_method }})

It gets spicy when you already had multiple includes in an array like this:

@object.to_json {:include => [ :assocation_a, :assocation_b ]} 

And now you only want to include my_method in assocation_a and not assocation b. simply replacing :assocation_a by a hash like before isn't going to work. It took me some time but this is what I came up with:

@object.to_json {:include => { :assocation_a => { :methods => :my_method }, :assocation_b => {} }} 

Did I mention that I am amazed by how flexible the syntax is here?

Filed under programmierung, rails, ruby

Invoking rails i18n.translate with pluralization

One very nice thing about the internationalization library in Rails is it's support for pluralization by default. Instead of having to figure out how to display a plural or a singular when selecting what message translation you display you can just call translate and it will figure out if the plural or the singular form should be used.

Defining the two forms is done inside your config/locale/.yml like this:

found:
  one: "Found one result"
  other: "Found %{count} results"

This works out of the box for things like validation errors or ActiveRecord models. But it refused to work on me for my own little custom array I was outputting.

Turns out I was just not calling it correctly. I18n.translate simply takes a hash of options - expecting one of these options to be count so it can perform the pluralization check (by default this is entry[count == 1 ? 0 : 1]).

So in order to use this with a custom array you need to write something like this:

I18n.translate :found, :count => myarray.length

Since this allows you to pass any value you want through the arguments hash you can easily construct translations like this:

found:
  one: We could not find anything matching your query %{query}
  other: We found %{count} items

I18n.translate :found, :count => myarray.length, :query => "your query"

Filed under programmierung, rails, ruby

Execute callback once multiple ajax requests finish with jQuery

I just stumbled upon the problem of having to load multiple resources during page initialization. During the initial load I wanted a way to prevent any animations and other fancy stuff from happening but rather only create the page as soon as possible.

Since I couldn't find any way in jQuery (there are no combined callbacks) I decided to implement this using the deferred promise concept jQuery 1.5 introduced.

Deferred basically means "I represent a ajax call that has happened or is happening - ask me about it and I'll tell you when it's done or was done already". So implementing my little wait functions was rather trivial:

I used CoffeeScript for this, but the resulting JavaScript is also quite readable and you can use that too.

What this does is provide you with the awkwardly named function waitForAjaxRequestsToComplete that takes one callback parameter and an array of jQuery promises. Once all promises succeed or fail the callback will be called and the first parameter will contain information about failures.

Sample usage:

waitForAjaxRequestsToComplete(function (info) {
  console.log("requests failed " + info.failures)
  console.log("requests succeeded " + info.successes)
  console.log(info.failed) //contains all failed promises
}, [ $.ajax(...), $.ajax(...), $.ajax(...) ]);

The right thing to do: Rails deployment on Passenger

Today I deployed my very first Ruby on Rails application to a production server and failed. And I didn't fail so much because Rails is hard to deploy (the opposite is true) - but rather because Rails prevented me from doing something stupid!

But I digress, let's start at the beginning: I already wrote about my server setup last week and today was the time to deploy a Rails3 application to my Apache/Passenger.

The Passenger documentation really made things easy. I just cloned my repository to a folder and setup everything accordingly. Then I did the obvious chown -R www-data:www-data . so the www-data user Apache uses has full access to the whole application directory and fired up my browser.

And it didn't work. Passenger was obviously running as I was able to load files from the /public folder without a problem, but the routes inside my application only returned errorcode 500.

Why? Simple: Passenger by default assumes you are running in a production environment so it will load that up from your database.yml. So I had to make sure that those settings where correct (easy one). Next problem on the list was that any rake commands you are running on the server still assume you are using the development environment. So in order to create your databases and migrate the schema you have to do a:

  rake db:create RAILS_ENV="production"
  rake db:migrate RAILS_ENV="production"

Otherwise db:create and db:migrate will always run against the development environment settings inside database.yml.

But once that problem was solved, I was still getting 500s.. So I opened the /log/production.log and found another gem I really liked: Rails refused to start at all because I was running in production without having precompiled the assets (javascript/css)!

A simple rake assets:precompile fixed that, but boy was I impressed. I knew about the different environments in Rails and saw how they would affect deployment scenarios. But having Rails just throw exceptions at me if I try to do something so obviously stupid as to not have JavaScript and CSS minified and merged together into one file is really awesome. Especially when coming from a .NET environment where up to this date the <= .. => syntax does not safely URL-Encode the value (and it took them 10 years to release the safe <: ..> alternative, having a framework that throws you into the pit of success is exhilarating.

Filed under programmierung, rails, ruby

My Photography business

Projects

dynamic css for .NET

Archives

more