Skip to content
Tags

, ,

merge options into default ones

October 6, 2011

A good way to merge options in default options:

use update method on hashes:

ruby-1.9.2-p290 :001 > hash1 = {:key1 => "value1"}
 => {:key1=>"value1"}
ruby-1.9.2-p290 :002 > hash2 = {:key1 => "value12", :key2 => "value2"}
 => {:key1=>"value12", :key2=>"value2"}
ruby-1.9.2-p290 :010 > hash1.update(hash2)
 => {:key1=>"value12", :key2=>"value2"}
ruby-1.9.2-p290 :011 > hash1
 => {:key1=>"value12", :key2=>"value2"}

for example

def initialize(app, options = {})
        # Support old :expires option
        options[:expire_after] ||= options[:expires]

        super

        @default_options = {
          :namespace => 'rack:session',
          :host => 'localhost',
          :port => '6379',
          :db => 0,
          :key_prefix => ""
        }.update(options)

        @redis = Redis.new(@default_options)
      end

from https://github.com/desiringgod/redis-session-store/blob/master/lib/redis-session-store.rb#L20-35

for difference between update and merge check this : http://pradeep88.wordpress.com/2010/09/16/hash-merge-vs-update-ruby/
update basically updates the value of the hash it is called on, but merge doesnt. (update behaves like a method with a bang)

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: