Tag: views

Hashes for select

In Ruby on Rails there’s a very easy way to create a select tag:

form.select("period", [["Month", 1], ["Year", 12]])

In my case I have the options in a hash, like:

periods = {
  1 => "Month",
  12 => "Year"
}

but when I did this:

form.select("period", periods)

I was surprised to find out that the keys of the hash are used as the content of the options, and the values as the keys, producing this code:

<select id="resource_period" name="resource[period]">
  <option value="Month">1</option>
  <option value="Year">12</option>
</select>

Definitely not what I wanted, so I wrote this method:

class ApplicationController < ActionController::Base
  helper_method :hash_for_select

  def hash_for_select(hash, sort_by = :value)
    sort_by = sort_by == :value ? 0 : 1
    options = hash.map { |k, v| [v, k] }.sort { |x, y| x[sort_by]  y[sort_by] }
  end

and now I can do

form.select("period", hash_for_select(periods))

if I want the options sorted by key value or

form.select("period", hash_for_select(periods, :key))

if I want them sorted by keys.

Advertisements

Two-in-one DNS server with BIND9

This tutorial shows you how to configure BIND9 DNS server to serve an internal network and a external network at the same time with different set of information. To accomplish that goal, a new feature of BIND9 called view is used. As a tutorial it’ll walk you through the whole set up, but initial knowledge of BIND and DNS is required, there are plenty of documents that cover that information on the Internet.

Continue reading “Two-in-one DNS server with BIND9”