Archive for the ‘Gemachtes’ Category

Dynamic model based styles for Paperclip

Friday, October 29th, 2010

One might want to set up dynamic attachment dimensions (or other styles) when generating images with thoughtbot’s paperclip. Styles in paperclip are basically represented in the :styles hash of has_attached_file:

class File
  has_attached_file(
    :attachment,
    :styles => { :thumb => "100x100" }
  )
end

Building a related size model in rails might look the following:

class File < ActiveRecord::Base
  has_many :sizes, :class_name => "FileSize", :dependent => :destroy
 
  has_attached_file(
    :attachment,
    :styles => # styles through FileSize model
  )
 
  def styles
   self.sizes.inject({ :thumb => "100x100" }) do |sizes, size|
      sizes[:"#{size.id}"] = "#{size.width}x#{size.height}"; sizes
    end
  end
end
 
class FileSize < ActiveRecord::Base
  belongs_to :file
end

Using a Proc we can fetch sizes from our FileSize model:

  has_attached_file(
    :attachment,
    :styles => Proc.new { |clip| clip.instance.styles }
  )

Clip is the Paperclip instance which holds an instance-method to get back to the calling Class.

As a last issue one might want to reprocess / regenerated images after creating or destroying sizes:

class FileSize < ActiveRecord::Base
  belongs_to :file
 
  after_create  :reprocess
  after_destroy :reprocess
 
  private
 
  def reprocess
    self.file.attachment.reprocess!
  end
end

Iterate over Associative Arrays in Bash

Thursday, June 24th, 2010

Probably because many people think Bash is outdated it’s that hard to find proper resources digging into this Shell. Now we’ll have a look at an associative array and use each key to rename a file defined in value one got via wget.

Beware: Take a look at the OS X issues at the end of this article if working on a Mac!

#!/bin/bash
unset array; declare -A array # the -A attributes stands for associative
 
array[foo]=bar
array["spaced string"]="foo bar"
 
for i in ${!array[@]}
do
  # do something
done

This is how an iteration could look like. Have a look at bash-hackers.org to get more information. Thanks to Dennis Williamson solving this topic.

To get a file from the given URL perform the following command in the loop:

wget "${array[$i]}" -O "${i}.jpg"

The attribute -O renames the file.

Using variables outside Strings obviate the need for curly brackets so that $i would work as well.
Go on reading if you’re using a Mac:
(more…)

Cross-Domain with Sinatra / Rack and JSONP

Thursday, March 25th, 2010

There are several situations one might want to do cross-domain (/cross-site) AJAX-requests. Probably you experience the security borders of modern browsers very fast.
JSONP is a hack for JSON that provides a great workaround. It means sending a callback with the URL (eg. ?callback=sampleFunction). Server-sided we setup our application to respond with a JSON body wrapped in a function named like our callback function. In this case

sampleFunction({
  "ourData": [{
    "title": "is an array"
  },
    "title": "..."
  }]   
})

What we have to do (Sample)

Frontend
JS-Frameworks like jQuery are smart enough to send such requests with ease. Lets write a simple function with jQuery:

$.ajax({
  type: 'get',
  url: 'file.json',
  dataType: 'jsonp',
  success: function(data) {
    doSomethingWith(data);
  }
})

Let’s see how to setup the server:
Using Ruby and Rack it becomes very simple to beautifully provide regular JSON for non-JSONP clients and JSONP for jQuery & Co.
Simply use the rack middleware rack-contrib by Ryan Tomayko

gem install rack-rack-contrib --source=http://gems.github.com/

If you’re using pure rack, put this in your config.ru

require 'rack/contrib/jsonp'
use Rack::JSONP

Using Sinatra, I’d put it somewhere with my config files.
Let’s see how a sample Sinatra application could look like:

require 'sinatra'
require 'json'
require 'rack/contrib/jsonp'
 
use Rack::JSONP
 
before do
  content_type :json
end
 
get '/posts' do
  Posts.find.to_a.to_json
end

That simple, this powerful.

InDesign: Sprache für ganzes Dokument ändern

Monday, March 8th, 2010

InDesign Es gibt zwei Möglichkeiten die Sprache für das Text- und Absatzformat in InDesign zu ändern. Wenn wir allerdings nicht für jedes Textfeld die Sprache ändern wollen, müssen wir uns eines Workarounds bedienen. Schließlich gibt es kein “Sprache für Dokument ändern”. Dann wollen wir mal:
(more…)

Cheatsheet: moving data from one server to another

Wednesday, January 20th, 2010

This article is about moving a running web-environment along with it’s MySQL database from one server to another via SSH.

Compress files

Let’s compress the directory we’re going to move using gzip:

tar cfvz backup.tar.gz /path/

Dump MySQL database content

mysqldump -uUser -p -hlocalhost database_name > dump.sql

You can also dump several databases with mysqldump by addind the --databases or --all-databases parameter.

Moving files

Now we use SCP to move files to our new machine. The following example copies from the old machine:

scp user@host:/path/backup.tar.gz .

The other way round, copying the file to the new machine from the old one would look like this:

scp backup.tar.gz user@host:/path/backup.tar.gz

Do the same with your database dump.

Uncompress files

Simply type:

tar xfvz backup.tar.gz

Now we should have the same directory structure we had on our old machine.

Import MySQL database

mysql -uUser --default-character-set=utf8 -hlocalhost -p database_name < dump.sql

If you have international content and an utf-8 environment running don’t forget to pass the charset-parameter!

Hamburger Hafen im Winter

Tuesday, January 12th, 2010

Passend zum Schneechaos in Norddeutschland ein paar Eindrücke aus dem Hamburger Hafen im Winter. Ich habe noch nichts nachbearbeitet – also seht ihr Rohmaterial aus der Kamera.

Eisbrecher Hamburg

(more…)

select any HTML text in element with jQuery

Thursday, November 19th, 2009

The following script jQuery extension selects any text from a given jQuery selector. Tested with Firefox and Safari – should work in IE6+ as well.

jQuery.fn.extend({
  selectText: function() {
    var text = $(this)[0];
    if ($.browser.msie) {
      var range = document.body.createTextRange();
      range.moveToElementText(text);
      range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
      var selection = window.getSelection();
      var range = document.createRange();
      range.selectNodeContents(text);
      selection.removeAllRanges();
      selection.addRange(range);
    } else if ($.browser.safari) {
      var selection = window.getSelection();
      selection.setBaseAndExtent(text, 0, text, 1);
    }
    return $(this);
  }
})

To use it simly do:

var shortSelector = $('#name').selectText();
var longSelector = $('ul#names li:contains("Hampel")').selectText();

written on top of Source and Source

HTML to PDF Library for PHP 5

Wednesday, July 8th, 2009

DomPDF HTML to PDF As I had to build a simple html to pdf converting for a client using php, I found a beautiful library called DOMPDF written by Benj Carson.

It seemed to be very lightweight and uncomplicated, which turned out to be true. In a standard case it really is as simple as

$pdf->load_html($html);

I am going to talk about the basic usage and problems I had to solve, specially with umlauts / non latin characters.
(more…)

Bankenrückblick, Giroüberblick

Thursday, June 18th, 2009

Geldbaum Nachdem ich mich nun seit einem Jahr mit den verschiedenen Banken auseinandersetzte und seit Amerika auch den Auslandseinsatz beurteilen kann, möchte ich die Erfahrungen nicht für mich behalten:
(more…)

Magento with top Navigation only

Friday, May 8th, 2009

Again I had to learn how much magento e-commerce documentation sucks or better to say the lack of it. After reading several tutorials and part-conclusions, i found following working solution
First of all it’s important to have one default category as a root category. Then you can use the following code in “magento/app/design/frontend/<#your template#>/<#your layout#>/template/catalog/navigation/top.phtml”.

<div id="navi">
  <ul>
  <?php
  foreach ($this->getStoreCategories() as $key => $cat):
      if ($this->isCategoryActive($cat)) { 
        echo '<li class="active">
          <a href="'.$this->getCategoryUrl($cat).'">
          <span>'.$cat->getName()."</span></a>
        </li>\n";
      } else {
        echo '<li class="normal">
          <a href="'.$this->getCategoryUrl($cat).'">
          <span>'.$cat->getName()."</span></a>
        </li>\n";
      }
  endforeach; ?>
  </ul>
</div>

Be sure to use $this->isCategoryActive() instead of finding out the current category first and compare it with the active one. This wouldn’t work for sub-categories so that an active sub-category wouldn’t mark it’s parent active. Actually many tutorials seem to have that mistake in their code.

A more or less good resource for magento developers is magetips.com.
I found the adressed function there as well.