Skip to content

Commit

Permalink
Move options hash key normalization to separate file.
Browse files Browse the repository at this point in the history
  • Loading branch information
jnunemaker committed Oct 11, 2012
1 parent 3a35c38 commit dc8d681
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 27 deletions.
17 changes: 17 additions & 0 deletions lib/plucky/normalizers/options_hash_key.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module Plucky
module Normalizers
class OptionsHashKey

NormalizedKeys = {
:order => :sort,
:select => :fields,
:offset => :skip,
:id => :_id,
}

def call(key)
NormalizedKeys.fetch key.to_sym, key
end
end
end
end
23 changes: 13 additions & 10 deletions lib/plucky/options_hash.rb
Original file line number Diff line number Diff line change
@@ -1,18 +1,15 @@
# encoding: UTF-8

require 'plucky/normalizers/options_hash_key'

module Plucky
class OptionsHash

NormalizedKeys = {
:order => :sort,
:select => :fields,
:offset => :skip,
:id => :_id,
}

attr_reader :source
attr_reader :source, :options

def initialize(hash={})
def initialize(hash={}, options={})
@source = {}
@options = options
hash.each { |key, value| self[key] = value }
end

Expand Down Expand Up @@ -50,13 +47,19 @@ def merge!(other)
self
end

def key_normalizer
@key_normalizer ||= options.fetch(:key_normalizer) {
Normalizers::OptionsHashKey.new
}
end

private
def method_missing(method, *args, &block)
@source.send(method, *args, &block)
end

def normalized_key(key)
NormalizedKeys.fetch key.to_sym, key
key_normalizer.call(key)
end

def normalized_value(key, value)
Expand Down
23 changes: 23 additions & 0 deletions spec/plucky/normalizers/options_hash_key_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
require 'helper'

describe Plucky::Normalizers::OptionsHashKey do
subject {
described_class.new
}

it "changes order to sort" do
subject.call(:order).should eq(:sort)
end

it "changes select to fields" do
subject.call(:select).should eq(:fields)
end

it "changes offset to skip" do
subject.call(:offset).should eq(:skip)
end

it "changes id to _id" do
subject.call(:id).should eq(:_id)
end
end
17 changes: 0 additions & 17 deletions spec/plucky/options_hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,23 +36,6 @@
end

describe "#[]=" do
it "converts order to sort" do
options = described_class.new(:order => :foo)
options[:order].should be_nil
options[:sort].should == [['foo', 1]]
end

it "converts select to fields" do
options = described_class.new(:select => 'foo')
options[:select].should be_nil
options[:fields].should == ['foo']
end

it "converts offset to skip" do
options = described_class.new(:offset => 1)
options[:offset].should be_nil
options[:skip].should == 1
end

context ":fields" do
before { @options = described_class.new }
Expand Down

0 comments on commit dc8d681

Please sign in to comment.