<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0"><channel><atom:link rel="hub" href="http://tumblr.superfeedr.com/" xmlns:atom="http://www.w3.org/2005/Atom"/><description>ruby on rails developer</description><title>Milovan Zogovic</title><generator>Tumblr (3.0; @zogash)</generator><link>http://zogovic.com/</link><item><title>Benchmarking gem load times</title><description>&lt;p&gt;There is an awesome gist written by Pan Thomakos, and later refined by Andrew Kane here: &lt;a href="https://gist.github.com/ankane/5022636"&gt;https://gist.github.com/ankane/5022636&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here is simple fish shell function that can be used to run this script in any project you need:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;function benchmark_bundler
  set -x BUNDLE_GROUPS $argv
  curl -fsSL &lt;a href="https://gist.github.com/raw/5022636/benchmark.rb"&gt;https://gist.github.com/raw/5022636/benchmark.rb&lt;/a&gt; | ruby
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Just put it in your &lt;code&gt;~/.config/fish/config.fish&lt;/code&gt; file and off you go.&lt;/p&gt;</description><link>http://zogovic.com/post/51546461224</link><guid>http://zogovic.com/post/51546461224</guid><pubDate>Tue, 28 May 2013 10:04:09 +0200</pubDate><category>rails</category><category>bundler</category><category>rubygems</category><category>fish shell</category></item><item><title>Monitoring memory usage on long-running scripts</title><description>&lt;p&gt;There is a simple way to monitor memory usage on long-running scripts. You can just create new thread which will output current memory usage to console in short time intervals:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Thread.new do
  while true do
    memory = `ps -o rss -p #{Process::pid}`.chomp.split("\n").last.strip.to_i
    puts "Memory: #{memory/1024} MB"
    sleep 0.25
  end
end
&lt;/code&gt;&lt;/pre&gt;</description><link>http://zogovic.com/post/46412739882</link><guid>http://zogovic.com/post/46412739882</guid><pubDate>Wed, 27 Mar 2013 11:36:45 +0100</pubDate><category>ruby</category></item><item><title>More readable specs with dynamic date methods</title><description>&lt;p&gt;Often times, in my specs, i use variables like &lt;code&gt;jan_01&lt;/code&gt; to represent dates. It makes my specs much more readable. For example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;date = SequentialDate.new(jan_01)
expect(date.next).to eq(jan_02)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I used to create these variables by hand, but there is much easier way to do it by utilising pure awesomeness of ruby. Just define following module in your &lt;code&gt;support&lt;/code&gt; rspec dir:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'date'
module Support
  module DateHelpers
    def method_missing(name, *args, &amp;amp;amp;block)
      begin
        Date.parse(name.to_s)
      rescue ArgumentError
        super
      end
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And require it in rspec config file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;RSpec.configure do |config|
  config.include Support::DateHelpers
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The beauty of it is that it wil parse whatever &lt;code&gt;Date.parse&lt;/code&gt; is able to handle. Some examples are:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;&lt;code&gt;jan_01&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;jan_1st&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;jan_01_2013&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;_3rd_feb_2013&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;_01_JAN_2013&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;february_14th_2013&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;</description><link>http://zogovic.com/post/45837991740</link><guid>http://zogovic.com/post/45837991740</guid><pubDate>Wed, 20 Mar 2013 16:26:00 +0100</pubDate><category>rspec</category><category>ruby</category></item><item><title>Super fast way of launching postgres console for rails apps</title><description>&lt;p&gt;Database console can be run with &lt;code&gt;bundle exec rails dbconsole&lt;/code&gt; command. However, this operation performs relatively slow (due to bundler and deps).&lt;/p&gt;

&lt;p&gt;We can make it much faster with simple ruby script:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;#!/usr/bin/env ruby

require 'yaml'
require 'fileutils'

database_config = YAML.load_file(Dir.pwd + '/config/database.yml')['development'];
database_name = database_config['database']

exec('psql', "-d#{database_name}")
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Just save the script somewhere in your $PATH and give it &lt;code&gt;u+x&lt;/code&gt; permission.&lt;/p&gt;

&lt;p&gt;I like to place scripts like these in my &lt;code&gt;~/dev/bin&lt;/code&gt; folder (included in $PATH). I gave this one &lt;code&gt;db&lt;/code&gt; name, so the only thing i need to do to fire up postgres console is to type &lt;code&gt;db&lt;/code&gt;. Simple and extremely fast.&lt;/p&gt;</description><link>http://zogovic.com/post/45258302161</link><guid>http://zogovic.com/post/45258302161</guid><pubDate>Wed, 13 Mar 2013 10:01:01 +0100</pubDate><category>postges</category><category>rails</category></item><item><title>Optimizing postgresql query for DISTINCT values</title><description>&lt;p&gt;If you want to get &lt;code&gt;DISTINCT&lt;/code&gt; values from large tables (and by large I mean hundreds of thousands of rows), it is painfully slow.&lt;/p&gt;

&lt;p&gt;Simple query like this: &lt;code&gt;SELECT DISTINCT(day) FROM reports&lt;/code&gt; can take a lot of time to be processed.&lt;/p&gt;

&lt;p&gt;Here is how you can improve its speed dramatically using postgres recursive functionality:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;WITH RECURSIVE t(n) AS (
    SELECT MIN(day) FROM reports
  UNION
    SELECT (SELECT day FROM reports WHERE day &amp;amp;gt; n ORDER BY day LIMIT 1)
    FROM t WHERE n IS NOT NULL
)
SELECT n FROM t;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&amp;#8217;ve tested it against 50 million rows with 365 distinct values for day, and it executed in 8ms, opposed to 15.7 seconds for &lt;code&gt;SELECT DISTINCT&lt;/code&gt; query.&lt;/p&gt;

&lt;p&gt;There are only two prerequisites:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;you need index column you want to get distincts from. &lt;/li&gt;
&lt;li&gt;you have postgres 8.4+&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;For more info, check out the postgresql docs on the topic: &lt;a href="http://www.postgresql.org/docs/9.1/static/queries-with.html"&gt;http://www.postgresql.org/docs/9.1/static/queries-with.html&lt;/a&gt;&lt;/p&gt;</description><link>http://zogovic.com/post/44856908222</link><guid>http://zogovic.com/post/44856908222</guid><pubDate>Fri, 08 Mar 2013 14:10:00 +0100</pubDate><category>postgres</category></item><item><title>Rails consecutive migrations acting weird</title><description>&lt;p&gt;If you&amp;#8217;re using models in your database migrations, its good practice to define dummy active record clases for them:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class SomeMigration &amp;lt; ActiveRecord::Migration
  class User &amp;lt; ActiveRecord::Base
    reset_column_information
  end
  # ...
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you have many migrations to run and model definition changes over time (which is likely to happen), you need to call &lt;code&gt;reset_column_information&lt;/code&gt; in order to &amp;#8220;reload&amp;#8221; the model on beginning of every migration.&lt;/p&gt;</description><link>http://zogovic.com/post/39121617730</link><guid>http://zogovic.com/post/39121617730</guid><pubDate>Sat, 29 Dec 2012 12:54:55 +0100</pubDate><category>rails</category></item><item><title>Showing git branch in fish shell prompt</title><description>&lt;p&gt;Put following code at the end of &lt;code&gt;~/.config/fish/config.fish&lt;/code&gt;. It will also highlight in red if branch is dirty.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;set fish_git_dirty_color red
set fish_git_not_dirty_color green

function parse_git_branch
  set -l branch (git branch 2&amp;gt; /dev/null | grep -e '\* ' | sed 's/^..\(.*\)/\1/')
  set -l git_diff (git diff)

  if test -n "$git_diff"
    echo (set_color $fish_git_dirty_color)$branch(set_color normal)
  else
    echo (set_color $fish_git_not_dirty_color)$branch(set_color normal)
  end
end

function fish_prompt
  if test -d .git
    printf '%s@%s %s%s%s:%s&amp;gt; ' (whoami) (hostname|cut -d . -f 1) (set_color $fish_color_cwd) (prompt_pwd) (set_color normal) (parse_git_branch)
  else
    printf '%s@%s %s%s%s&amp;gt; ' (whoami) (hostname|cut -d . -f 1) (set_color $fish_color_cwd) (prompt_pwd) (set_color normal)
  end
end
&lt;/code&gt;&lt;/pre&gt;</description><link>http://zogovic.com/post/37906589287</link><guid>http://zogovic.com/post/37906589287</guid><pubDate>Fri, 14 Dec 2012 15:00:00 +0100</pubDate></item><item><title>"42 is a nice number that you can take home and introduce to your family"</title><description>“42 is a nice number that you can take home and introduce to your family”&lt;br/&gt;&lt;br/&gt; - &lt;em&gt;Douglas Adams&lt;/em&gt;</description><link>http://zogovic.com/post/34628146981</link><guid>http://zogovic.com/post/34628146981</guid><pubDate>Tue, 30 Oct 2012 10:02:28 +0100</pubDate></item><item><title>Attachinary v1.2.0 released</title><description>&lt;p&gt;&lt;h3&gt;Changelog&lt;/h3&gt;

&lt;ul&gt;&lt;li&gt;Drag and drop support (on supported browsers)&lt;/li&gt;
&lt;li&gt;Selecting multiple files (on supported browsers)&lt;/li&gt;
&lt;li&gt;Upload progress indicator (prepended on submit button)&lt;/li&gt;
&lt;li&gt;Rake task for fetching assets (&lt;code&gt;rake attachinary:fetch_fileupload&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Ability to assing image urls (e.g. &lt;code&gt;user.avatar_url = 'http://..'&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Ability to assign IO objects (e.g. &lt;code&gt;user.avatar = File.open(...)&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;No-JS support&lt;/li&gt;
&lt;/ul&gt;&lt;/p&gt;</description><link>http://zogovic.com/post/34415383599</link><guid>http://zogovic.com/post/34415383599</guid><pubDate>Sat, 27 Oct 2012 16:35:00 +0200</pubDate><category>attachinary</category><category>rails</category><category>cloudinary</category></item><item><title>How to validate Array fields in Mongoid</title><description>&lt;p&gt;Define custom &lt;code&gt;ArrayValidator&lt;/code&gt; in &lt;code&gt;app/validators/array_validator.rb&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ArrayValidator &amp;lt; ActiveModel::EachValidator
  def validate_each(record, attribute, values)
    [values].flatten.each do |value|
      options.each do |key, args|
        validator_options = { attributes: attribute }
        validator_options.merge!(args) if args.is_a?(Hash)

        next if value.nil? &amp;amp;&amp;amp; validator_options[:allow_nil]
        next if value.blank? &amp;amp;&amp;amp; validator_options[:allow_blank]

        validator_class_name = "#{key.to_s.camelize}Validator"
        validator_class = begin
          validator_class_name.constantize
        rescue NameError
          "ActiveModel::Validations::#{validator_class_name}".constantize
        end

        validator = validator_class.new(validator_options)
        validator.validate_each(record, attribute, value)
      end
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can use it like this in your models:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class User
  include Mongoid::Document
  field :tags, Array

  validates :tags, array: { presence: true, inclusion: { in: %w{ ruby rails } }
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It will validate &lt;strong&gt;each&lt;/strong&gt; element from the array against &lt;strong&gt;every&lt;/strong&gt; validator specified within &lt;code&gt;array&lt;/code&gt; hash.&lt;/p&gt;</description><link>http://zogovic.com/post/32932492190</link><guid>http://zogovic.com/post/32932492190</guid><pubDate>Fri, 05 Oct 2012 13:09:00 +0200</pubDate></item><item><title>I've just released v1 of attachinary gem for cloudinary with monoid support and much cleaner integration.</title><description>&lt;a href="https://github.com/assembler/attachinary"&gt;I've just released v1 of attachinary gem for cloudinary with monoid support and much cleaner integration.&lt;/a&gt;</description><link>http://zogovic.com/post/31266492949</link><guid>http://zogovic.com/post/31266492949</guid><pubDate>Mon, 10 Sep 2012 13:58:10 +0200</pubDate><category>rails</category></item><item><title>Integrating Prefixr with Rails asset pipeline</title><description>&lt;p&gt;&lt;a href="http://prefixr.com/"&gt;Prefixr&lt;/a&gt; is cool online service created by Jeffrey Way for adding vendor prefixes to your css. It has nice and simple API to let you integrate it into your workflow. Here is how you can integrate it with Rails asset pipeline.&lt;/p&gt;

&lt;p&gt;Just create &lt;code&gt;prefixr.rb&lt;/code&gt; file inside &lt;code&gt;config/initializers&lt;/code&gt; folder with following content:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;require 'uri'
require 'net/http'

class PrefixrPostprocessor &amp;lt; ::Tilt::Template
  def prepare
  end

  def evaluate(context, locals, &amp;amp;block)
    uri = URI.parse "http://prefixr.com/api/index.php"
    Net::HTTP.post_form(uri, { css: data }).body
  end
end

Rails.application.assets.register_postprocessor 'text/css', PrefixrPostprocessor
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It defines and registers postprocessor for &lt;code&gt;text/css&lt;/code&gt; files. Now, every css file served through rails will be automatically prefixr&amp;#8217;d! This will work even if you use sass or less!&lt;/p&gt;

&lt;p&gt;The downside of this approach is that it will slow down the development because it will need to make HTTP request to prefixr.com API every time the css file is requested by browser. I wish that there is ruby version of prefixr service as a gem that I could just use directly inside &lt;code&gt;PrefixrPostprocessor&lt;/code&gt;. That would be just awesome! Who knows.. maybe I just make one!&lt;/p&gt;</description><link>http://zogovic.com/post/30530147699</link><guid>http://zogovic.com/post/30530147699</guid><pubDate>Thu, 30 Aug 2012 20:04:00 +0200</pubDate><category>rails</category><category>css</category></item><item><title>Cachex: tag based fragment caching on steriods</title><description>&lt;p&gt;I&amp;#8217;ve just released another gem. Its called &lt;a href="https://github.com/assembler/cachex"&gt;Cachex&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This gem is inspired by excellent &lt;a href="https://github.com/twinturbo/cashier"&gt;Cashier&lt;/a&gt; gem. I wanted to take it a step further and try to automate tag dependency generation.&lt;/p&gt;

&lt;p&gt;I had this scenario in mind:&lt;/p&gt;

&lt;ul&gt;&lt;li&gt;Blog has many posts&lt;/li&gt;
&lt;li&gt;Each post has an author (user)&lt;/li&gt;
&lt;li&gt;Each post has many comments&lt;/li&gt;
&lt;li&gt;Each comment has its own author (user)&lt;/li&gt;
&lt;/ul&gt;&lt;p&gt;Each model has its own partial. Inside &lt;code&gt;_post&lt;/code&gt; partial we have &lt;code&gt;_user&lt;/code&gt; partial that renders post&amp;#8217;s author. &lt;code&gt;_post&lt;/code&gt; partial also include many &lt;code&gt;_comment&lt;/code&gt; partials. Each &lt;code&gt;_comment&lt;/code&gt; partial have author&amp;#8217;s name displayed in it.&lt;/p&gt;

&lt;p&gt;We&amp;#8217;re also using fragment caching in order to cache entire post for faster serving. The burning question is: &lt;strong&gt;what happens if user decides to change its name (or perhaps, more commonly, an avatar)?&lt;/strong&gt;. We have to invalidate every cached partial that displayed that user. How do we do that?&lt;/p&gt;

&lt;p&gt;If we&amp;#8217;re using auto-expiring key strategy the only way to accomplish this would be to &lt;code&gt;touch&lt;/code&gt; &lt;strong&gt;everything&lt;/strong&gt; that has to do with that user. That just doesn&amp;#8217;t make any sense.&lt;/p&gt;

&lt;p&gt;If we&amp;#8217;re using tag-based strategy, then we would need to manually tag every fragment with all users that have to do something with it (even users from its comments). Such approach is going to be very hard when we get to deeply nested partials. Top most partial will have to be aware of &lt;strong&gt;all dependencies&lt;/strong&gt; down to the deepest one.&lt;/p&gt;

&lt;p&gt;And finally, my solution: &lt;strong&gt;to automatically extract all dependencies from all sub-partials and to store them to help cache invalidation&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Read more on &lt;a href="https://github.com/assembler/cachex"&gt;github&lt;/a&gt;.&lt;/p&gt;</description><link>http://zogovic.com/post/29480067845</link><guid>http://zogovic.com/post/29480067845</guid><pubDate>Wed, 15 Aug 2012 16:07:14 +0200</pubDate><category>rails</category><category>caching</category></item><item><title>Testing API from Rails Console</title><description>&lt;p&gt;Recently I created small API for one of my apps that is to be accessed by an iPhone application. I followed &lt;a href="http://railscasts.com/?search=api&amp;amp;tag_id=37&amp;amp;utf8=%E2%9C%93"&gt;Railscasts guides&lt;/a&gt; on how to create, version, and secure it with access token. Even though you can test the api with CURL command, it tend to get a bit more complex when you need to specify token header every single time.&lt;/p&gt;

&lt;p&gt;I wanted to be able to test the API in more simplistic way. I wanted it to be something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;api User.first, :get, '/api/projects'
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is the simple helper method that can make this process much easier:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def api(user, method, url, params=nil)
  headers = {
    'Accept' =&amp;gt; 'application/roommates.v1',
    'HTTP_AUTHORIZATION' =&amp;gt; ActionController::HttpAuthentication::Token.encode_credentials(user.api_token)
  }
  app.send(:"#{method}", url, params, headers)
  ap JSON.parse(app.response.body)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Method simply sets proper headers, issues request, pretty-prints returned json (with &lt;a href="https://github.com/michaeldv/awesome_print"&gt;awesome_print gem&lt;/a&gt;), and returns it. You can customize any way you want.. this is just an idea of how it might look.&lt;/p&gt;

&lt;p&gt;All you have to do is put this method in &lt;code&gt;.irbrc&lt;/code&gt; file in your project root and it will be automatically loaded each time you start your rails console.&lt;/p&gt;</description><link>http://zogovic.com/post/25148259574</link><guid>http://zogovic.com/post/25148259574</guid><pubDate>Fri, 15 Jun 2012 09:30:51 +0200</pubDate><category>rails</category><category>api</category></item><item><title>Redis Marshaling</title><description>&lt;p&gt;If you have time consuming method in your app that you call frequently, chances are that you&amp;#8217;d like to cache it. Redis is great key-value store that can be used for this purpose. However, redis only store string values. In order to store other kinds of objects, you&amp;#8217;ll have to use marshaling.&lt;/p&gt;

&lt;p&gt;There is a built-in ruby class called &lt;code&gt;Marshal&lt;/code&gt; that does the job well. The only thing you have to do is to call &lt;code&gt;Marshal.dump&lt;/code&gt; method and pass it an object. The exact opposite is the &lt;code&gt;Marshal.load&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;I&amp;#8217;ve created helper method for easier integration with Redis. Here is how it looks:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module RedisHelper

  # Returns the cached value for given key.
  # If it doesn't exist, it evaluates the block and caches what it returns.
  # 
  # @param [String] key the cache key
  # @param [Hash] options
  # @option options [Integer, nil] :ttl time to live in seconds
  # @option options [Boolean, false] :marshal whether to perform marshaling
  # @yield [] to be evaluated if the key does not exist
  def self.fetch(key, options={}, &amp;amp;block)
    raise ArgumentError.new("Must Supply Block") unless block_given?
    return yield unless Rails.application.config.action_controller.perform_caching

    val = nil

    if REDIS.exists(key)
      val = REDIS.get(key)
      begin
        val = Marshal.load(val) if options[:marshal]
      rescue TypeError
        val = nil
      end
    end

    if !val
      val = yield

      if options[:marshal]
        REDIS.set key, Marshal.dump(val)
      else
        REDIS.set key, val
      end

      REDIS.expire key, options[:ttl] if options[:ttl]
    end

    val
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;There is not much to describe here since its already documented using yard. Instead, I&amp;#8217;ll show how I used in in one of my apps:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;module Geocoder

  def self.geocode(location)
    key = "geolocations/#{location}"
    RedisHelper.fetch key, ttl: 24.hours, marshal: true do
      Geokit::Geocoders::GoogleGeocoder.geocode(location)
    end
  end

end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I&amp;#8217;m using &lt;code&gt;geokit&lt;/code&gt; gem for discovering geocoordinate of an address. It uses Google geocoding API which is limited to 2500 queries per day. This piece of code will cache the result of &lt;code&gt;GoogleGeocoder.geocode&lt;/code&gt; method so all successive requests will be returned from cache.&lt;/p&gt;</description><link>http://zogovic.com/post/22959201450</link><guid>http://zogovic.com/post/22959201450</guid><pubDate>Sun, 13 May 2012 09:58:32 +0200</pubDate><category>redis</category><category>rails</category></item><item><title>Simple HTML5 details polyfill</title><description>&lt;p&gt;Although there are many HTML5&amp;#160;&lt;code&gt;&amp;lt;details&amp;gt;&lt;/code&gt; &lt;a href="https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills"&gt;polyfills&lt;/a&gt; already available, I didn&amp;#8217;t like the complexity behind them. Here is how you can create your own from scratch in just few lines of css and js.&lt;/p&gt;

&lt;p&gt;The idea was to put as much &amp;#8220;logic&amp;#8221; as possible in the stylesheet itself. It should hide/show the content based on the presence of &lt;code&gt;open&lt;/code&gt; attribute. Here is the sass file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;.no-details details {
  &amp;gt; * {
    position: absolute;
    visibility: hidden;
  }

  &amp;gt; summary, &amp;amp;[open] &amp;gt; * {
    position: static;
    visibility: visible;
  }


  &amp;gt; summary {
    display: block;
    &amp;amp;:before {
      content: "►";
      padding-right: 5px;
      font-size: 11px;
    }
  }

  &amp;amp;[open] &amp;gt; summary:before {
    content:"▼"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;All children of &lt;code&gt;details&lt;/code&gt; tag (except &lt;code&gt;summary&lt;/code&gt;) will be by default hidden. If &lt;code&gt;details&lt;/code&gt; element has &lt;code&gt;open&lt;/code&gt; attribute set, its content will be shown. We could use css &lt;code&gt;:not&lt;/code&gt; selector to simplify the css a whole lot, but it is only supported by IE9+, and I&amp;#8217;d like polyfill to target IE8+.&lt;/p&gt;

&lt;p&gt;And here is the coffeescript:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;jQuery -&amp;gt;
  return if Modernizr.details

  $(document).on 'click', 'summary', (event) -&amp;gt;
    $summary = $(this)
    $details = $summary.parent()

    if $details.attr('open')
      $details.removeAttr('open')
    else
      $details.attr('open', 'open')
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It simply toggles the &lt;code&gt;open&lt;/code&gt; attribute when user clicks on summary. Its as simple as that.&lt;/p&gt;</description><link>http://zogovic.com/post/21784525226</link><guid>http://zogovic.com/post/21784525226</guid><pubDate>Wed, 25 Apr 2012 17:16:03 +0200</pubDate><category>javascript</category><category>css</category><category>html5</category></item><item><title>Responsive Images with Cloudinary on Rails</title><description>&lt;p&gt;&lt;a href="http://css-tricks.com/on-responsive-images/"&gt;Responsive Images&lt;/a&gt; is a hot topic lately. There are few solutions to the problem: &lt;em&gt;introduction of new html element&lt;/em&gt; (which will take years to be ready for use), &lt;em&gt;new image format&lt;/em&gt; (which may take even more time), and &lt;em&gt;using other technologies&lt;/em&gt; to solve the problem. Here, I&amp;#8217;ll focus on the last one.&lt;/p&gt;

&lt;p&gt;The goal is clear:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;Detect user&amp;#8217;s device screen resolution&lt;/li&gt;
&lt;li&gt;Serve appropriate images for best browsing experience&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;In order to handle cases where you cannot detect user&amp;#8217;s device capabilities (e.g. no javascript support), we need to provide reasonable defaults (e.g. medium sized images).&lt;/p&gt;

&lt;p&gt;Here is how you can accomplish this in few simple steps by using &lt;a href="http://cloudinary.com/"&gt;Cloudinary&lt;/a&gt; service for hosting your assets.&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;The concept is simple:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;When user enters our website, we&amp;#8217;ll use javascript to detect his device resolution.&lt;/li&gt;
&lt;li&gt;We&amp;#8217;ll store that resolution in a cookie.&lt;/li&gt;
&lt;li&gt;Backend will utilize information inside cookie to serve appropriate image format.&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;First two steps are quite easy to do. All you have to do is inject following javascript&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;document.cookie='resolution='+screen.width+'x'+screen.height)+'; path=/';
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That would store user&amp;#8217;s device screen resolution in a cookie. On the next page load, that cookie will be available to your backend.&lt;/p&gt;

&lt;p&gt;Now, lets override cloudinary &lt;code&gt;cl_image_tag&lt;/code&gt; to allow &lt;code&gt;:responsive&lt;/code&gt; option. You can do so by including this in application_helper file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def cl_image_tag(source, options = {})
  if (sizes = options.delete(:responsive)) &amp;amp;&amp;amp; (resolution = cookies[:resolution])
    res = case resolution.split('x').first.to_i
          when 0..480 then :phones
          when 481..767 then :tablets
          else :desktops
          end

    size = sizes[res]
    options[:size] = size if size
  end

  super(source, options)
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Method simply checks whether &lt;code&gt;:responsive&lt;/code&gt; option and &lt;code&gt;:resolution&lt;/code&gt; cookie are present. If so, it replaces the &lt;code&gt;:size&lt;/code&gt; parameter with appropriate value. The usage would be like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;%= cl_image_tag "sample.jpg", size: '200x200', crop: 'fit', 
    responsive: { phones: '50x50', tablets: '100x100' } %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That would serve 50x50px image for phones, 100x100px version for tablets and fallback to 200x200px version for all others. Sweet!&lt;/p&gt;</description><link>http://zogovic.com/post/21324203574</link><guid>http://zogovic.com/post/21324203574</guid><pubDate>Wed, 18 Apr 2012 16:14:40 +0200</pubDate><category>rails</category></item><item><title>Running time in Rails logs</title><description>&lt;p&gt;Since &lt;a href="http://weblog.rubyonrails.org/2012/1/20/rails-3-2-0-faster-dev-mode-routing-explain-queries-tagged-logger-store/"&gt;Rails 3.2&lt;/a&gt;, you can add custom tags to your logs. You can define tags by setting &lt;code&gt;config.log_tags&lt;/code&gt; in your config file. It accepts array of symbols that matches &lt;a href="http://api.rubyonrails.org/classes/ActionDispatch/Request.html"&gt;methods of &lt;code&gt;request&lt;/code&gt; object&lt;/a&gt;. Additionally, you can also pass lambdas to form custom tags. Here is how it might look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;config.log_tags = [:uuid, :remote_ip, lambda { |req| Time.now }]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you want to lear more about logging, I highly recommend &lt;a href="http://railscasts.com/episodes/56-the-logger-revised"&gt;The Logger (revised)&lt;/a&gt; screencast by Ryan Bates.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;One gotcha here&lt;/strong&gt;: lambdas are evaluated only once at the very beginning of request delegation (in &lt;a href="https://github.com/rails/rails/blob/3-2-stable/railties/lib/rails/rack/logger.rb#L14"&gt;Rails::Rack::Logger middleware&lt;/a&gt;. So, our lambda from above will return the same time for every log entry within same request.&lt;/p&gt;

&lt;hr&gt;&lt;p&gt;I must admit I&amp;#8217;m obsessed with performance lately :) Thats why I wanted to customize my logs to include &amp;#8220;running time&amp;#8221; next to each log entry. I wanted it to look something like this:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;Started GET "/users/sign_in" for 127.0.0.1 at 2012-04-15 11:37:21 +0200
[time:0.008] Processing by Devise::SessionsController#new as HTML
[time:0.019]   Rendered devise/_links.erb (0.5ms)
[time:0.019]   Rendered devise/sessions/new.html.erb within layouts/application (7.5ms)
[time:0.022]   Rendered layouts/_navbar.html.erb (0.4ms)
[time:0.022]   Rendered layouts/_skeleton.html.erb (2.3ms)
[time:0.022]   Rendered layouts/_public.html.erb (2.8ms)
[time:0.024] Completed 200 OK in 16ms (Views: 13.5ms | ActiveRecord: 0.0ms)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let&amp;#8217;s get started. First, we need to define custom log tag in our &lt;code&gt;development.rb&lt;/code&gt; config file:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;config.log_tags = [ lambda { |req| "time:#{Time.now.to_f}" } ]
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This will prefix each log entry with tag like this &lt;code&gt;[time:1334480797.098824]&lt;/code&gt;. We can later use regexp to replace this with running time.&lt;/p&gt;

&lt;p&gt;Next, lets incude some regexp magic in &lt;code&gt;TaggedLogging.tags_text&lt;/code&gt; method. Since this is something we only need in development, we can define this at the very bottom of &lt;code&gt;development.rb&lt;/code&gt; file.&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;class ActiveSupport::TaggedLogging
  def tags_text_with_timestamp
    text = tags_text_without_timestamp
    text &amp;amp;&amp;amp; text.gsub(/(?&amp;lt;=time\:)([\d\.]+)/) do |m|
      "%#.3f" % (Time.now.to_f - m.to_f).round(3)
    end
  end
  alias_method_chain :tags_text, :timestamp
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;em&gt;Note: this code will work only in Rails 3.2.x. I&amp;#8217;ve noticed that &lt;code&gt;TaggedLogging&lt;/code&gt; class is currently being refactored by rails team, but it won&amp;#8217;t be too hard to make this work in future versions of rails.&lt;/em&gt;&lt;/p&gt;</description><link>http://zogovic.com/post/21138929607</link><guid>http://zogovic.com/post/21138929607</guid><pubDate>Sun, 15 Apr 2012 11:48:00 +0200</pubDate><category>rails</category></item><item><title>Highlighting navigation links with javascript</title><description>&lt;p&gt;Recently I blogged about &lt;a href="http://zogash.tumblr.com/post/20281042229/tagging-the-html-tag"&gt;Tagging the HTML tag&lt;/a&gt;. The general idea is to apply some &lt;code&gt;data-&lt;/code&gt; attributes to &lt;code&gt;html&lt;/code&gt; tag in order to more easily target the page from css and js files. I also blogged about &lt;a href="http://zogash.tumblr.com/post/19743543684/javascript-processors"&gt;Javascript Processors&lt;/a&gt;, technique to keep your &amp;#8220;DOM enhancers&amp;#8221; organized.&lt;/p&gt;

&lt;p&gt;Using the two, here is how you can very easily implement processor that would highlight active link in your navigation. Lets say that we have following &lt;code&gt;nav&lt;/code&gt; element:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;nav class="main"&amp;gt;
  &amp;lt;a class="home"&amp;gt;Home&amp;lt;/a&amp;gt;
  &amp;lt;a class="projects"&amp;gt;Projects&amp;lt;/a&amp;gt;
  &amp;lt;a class="account"&amp;gt;My Account&amp;lt;/a&amp;gt;
&amp;lt;/nav&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here is how our &lt;code&gt;NavHighlighter&lt;/code&gt; may look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;@NavHighlighter =
  mapping:
    "nav.main .home":      [ /^\/welcome/ ]
    "nav.main .projects":  [ /^\/projects/ ]
    "nav.main .account":   [ /^\/registrations\/(edit|update)/, /^\/profile/ ]

  process: -&amp;gt;
    for elem, paths of @mapping
      $(elem).addClass("active") if App.onPath.apply(App, paths)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;We&amp;#8217;re using &lt;code&gt;mapping&lt;/code&gt; hash to define highlight conditions for each link. Hash key is just css selector, so you can use anything you want. Hash value is an array representing list of paths for which the given link is active.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Can&amp;#8217;t we do it on server?&lt;/strong&gt; Sure. There are two reasons I&amp;#8217;m doing it on the client: cleaner and faster erb template, and fragment caching.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;What about users with js disabled?&lt;/strong&gt; Well, they  could probably live without highlighted menu items. If you really want to do this on server and still use caching, read more on &lt;a href="http://zogash.tumblr.com/post/20283182724/cache-personalization-in-rails"&gt;Cache Personalization&lt;/a&gt;.&lt;/p&gt;</description><link>http://zogovic.com/post/21075256583</link><guid>http://zogovic.com/post/21075256583</guid><pubDate>Sat, 14 Apr 2012 11:12:00 +0200</pubDate><category>javascript</category><category>rails</category></item><item><title>Uploading directly to Cloudinary, bypassing your Rails app</title><description>&lt;blockquote&gt;
  &lt;p&gt;IMPORTANT UPDATE: &lt;code&gt;cl_form_tag&lt;/code&gt; and &lt;code&gt;valid_cloudinary_response?&lt;/code&gt; are now part of cloudinary &lt;strong&gt;1.0.6+&lt;/strong&gt; gem, so you can use them &amp;#8220;out of the box&amp;#8221;.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For those of you who haven&amp;#8217;t heard about &lt;a href="http://cloudinary.com/"&gt;Cloudinary&lt;/a&gt;, check it out! Cloudinary provides everything you (&lt;em&gt;as developer&lt;/em&gt;) would ever need for managing images. It basically works like this: you upload an image, then you request transformation of that image from the server. The transformed image is generated on the fly (unless cached) and served to you. There are plenty of transformations like: resizing, cropping, setting quality, changing file format&amp;#8230; etc. And, if your designer ever wanted to scale thumbnails a bit, you wouldn&amp;#8217;t need to reprocess thousands of images again!&lt;/p&gt;

&lt;p&gt;Cloudinary has a ruby gem that can be used in Rails app and it even supports CarrierWave if you use that to manage your uploads. However all these approaches require your server to handle file upload process. Here is how it looks:&lt;/p&gt;

&lt;ol&gt;&lt;li&gt;User uploads a photo to your server&lt;/li&gt;
&lt;li&gt;Rails application receives the file&lt;/li&gt;
&lt;li&gt;Rails application sends the file to Cloudinary&lt;/li&gt;
&lt;/ol&gt;&lt;p&gt;Rails is the middleman and it needs to do some &lt;em&gt;relatively heavy processing&lt;/em&gt; in order to decode the data received from the user, and prepare it for upload to the Cloudinary. From scaling aspect, this is something you&amp;#8217;d probably like to avoid.&lt;/p&gt;

&lt;p&gt;It turns out that it is really easy to let your users upload files directly to Cloudinary. After reading some documentation and browsing through source code, I came up with &lt;code&gt;cl_form_tag&lt;/code&gt; helper method:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def cl_form_tag(callback_url, options={}, &amp;amp;block)
  form_options = options.delete(:form) || {}
  form_options[:method] = :post
  form_options[:multipart] = true

  options[:timestamp] = Time.now.to_i
  options[:callback] = callback_url
  if options[:transformation]
    options[:transformation] = Cloudinary::Utils.
      generate_transformation_string(options[:transformation])
  end

  options[:signature] = Cloudinary::Utils.
    api_sign_request(options, Cloudinary.config.api_secret)

  options[:api_key] = Cloudinary.config.api_key

  url = "https://api.cloudinary.com/v1_1/"
  url&amp;lt;&amp;lt; "#{Cloudinary.config.cloud_name}/image/upload"

  form_tag(url, form_options) do
    content = []

    options.each do |name, value|
      content&amp;lt;&amp;lt; hidden_field_tag(name, value)
    end

    content&amp;lt;&amp;lt; capture(&amp;amp;block)

    content.join("\n").html_safe
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Its just a wrapper around &lt;code&gt;form_tag&lt;/code&gt; that adds few hidden fields and calculate request signature.&lt;/p&gt;

&lt;p&gt;The usage is really simple:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;&amp;lt;%= cl_form_tag CALLBACK_URL_HERE,
  form: { class: 'cloudinary' },
  format: 'jpg',
  transformation: { size: '300x300', crop: 'fit' } do %&amp;gt;

  &amp;lt;%= file_field_tag :file %&amp;gt;
  &amp;lt;%= submit_tag "Upload" %&amp;gt;
&amp;lt;% end %&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;When user picks file and clicks Upload button, file will start uploading to Cloudinary (completely bypassing your server). Once the upload process is complete, you&amp;#8217;ll be redirected back to specified callback url.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;cl_form_tag&lt;/code&gt; is calculating signature and including it into hidden field. It calculates signature based on your &lt;code&gt;Cloudinary.config.api_scret&lt;/code&gt; option. The same thing happens on Cloudinary server when it responds. Thats why you &lt;strong&gt;always need to validate response signature&lt;/strong&gt; to make sure that the Cloudinary itself made that request to callback url. Here is simple method that can do this check:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;def valid_cloudinary_response?
  received_signature = request.query_parameters[:signature]
  calculated_signature = Cloudinary::Utils.api_sign_request \
    request.query_parameters.except(:signature),
    Cloudinary.config.api_secret
  received_signature == calculated_signature
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;That&amp;#8217;s it! Pretty simple but powerful. There is bunch more that Cloudinary can do, so check &lt;a href="http://cloudinary.com/documentation"&gt;the documentation&lt;/a&gt; for more details.&lt;/p&gt;</description><link>http://zogovic.com/post/20642999532</link><guid>http://zogovic.com/post/20642999532</guid><pubDate>Sat, 07 Apr 2012 11:03:00 +0200</pubDate><category>rails</category></item></channel></rss>
