Skip to content

Allowing for Options

jnunemaker edited this page Nov 16, 2012 · 2 revisions

Adapters can be instantiated with options. These are available when you are defining adapters as a hash named options. Tricky, I know.

require 'adapter'
require 'yaml'

Adapter.define(:optional_yaml_memory) do
  def read(key)
    decode(client[key])
  end

  def write(key, value)
    client[key] = encode(value)
  end

  def delete(key)
    client.delete(key)
  end

  def clear
    client.clear
  end
  
  def encode(value)
    if options[:yaml]
      YAML.dump(value)
    else
      value
    end
  end
  
  def decode(value)
    if value && options[:yaml]
      YAML.load(value)
    else
      value
    end
  end
end

yaml_adapter = Adapter[:optional_yaml_memory].new({}, :yaml => true)
yaml_adapter.write('foo', [1, 2, 3])
puts yaml_adapter.client['foo'].inspect  # "--- \n- 1\n- 2\n- 3\n"
puts yaml_adapter.read('foo').inspect    # [1, 2, 3]

adapter = Adapter[:optional_yaml_memory].new({})
adapter.write('foo', [1, 2, 3])
puts adapter.client['foo'].inspect  # "\004\b[\bi\006i\ai\b"
puts adapter.read('foo').inspect    # [1, 2, 3]

Not that we used the same adapter, just passed in different options and it behaved differently. The Mongo driver uses this to its advantage by allowing the passing of write concerns to client operations.

Clone this wiki locally