Permalink
Browse files

Refactored JsonObject#add to take two args cause it makes more sense

  • Loading branch information...
1 parent 733bf3f commit baf769342f2b6dc941ba50c8cd8704928088a992 @bsiggelkow committed Jul 24, 2011
Showing with 15 additions and 12 deletions.
  1. +5 −3 lib/jsonify/builder.rb
  2. +5 −4 lib/jsonify/json_value.rb
  3. +5 −5 spec/builder_spec.rb
View
@@ -23,10 +23,12 @@ def compile!
@pretty ? JSON.pretty_generate(JSON.parse(result)) : result
end
- def add!(value)
- __current.add Generate.value(value)
+ def add!(*args)
+ __current.add *args
end
+ alias_method :<<, :add!
+
def method_missing(sym, *args, &block)
if block
pair = Generate.pair_value(sym)
@@ -37,7 +39,7 @@ def method_missing(sym, *args, &block)
@level -= 1
else
if sym && args && args.length > 0
- __current.add Generate.pair_value(sym, args.length > 1 ? args : args.first)
+ __current.add( sym, args.length > 1 ? args : args.first )
end
__current
end
@@ -29,13 +29,13 @@ def values
@values.values
end
- def add(val)
- raise ArgumentError.new("Cannot add #{val} to JsonOject") unless (Array === val || JsonPair === val)
- val = JsonPair.new(val.shift, val.length <= 1 ? val.first : val) if Array === val
- @values.store(val.key, val)
+ def add(key, val=nil)
+ pair = (JsonPair === key) ? key : JsonPair.new(key, val)
+ @values.store(pair.key, pair)
end
alias_method :<<, :add
+ alias_method :add!, :add # for consistency with the Builder api
end
@@ -55,6 +55,7 @@ def add(value)
end
alias_method :<<, :add
+ alias_method :add!, :add # for consistency with the Builder api
end
View
@@ -88,15 +88,15 @@ def evaluate
describe 'objects' do
it 'simple object should work' do
json.object! do |obj|
- obj << [:foo,:bar]
- obj << [:go, :far]
+ obj.add :foo,:bar
+ obj.add :go, :far
end
json.compile!.should == "{\"foo\":\"bar\",\"go\":\"far\"}"
end
- it 'should treat the first element of an array as a key' do
+ it 'should handle arrays' do
json.object! do |obj|
- obj << [1, 2, 3]
- obj << [4, 5]
+ obj.add 1, [2, 3]
+ obj.add 4, 5
end
json.compile!.should == '{"1":[2,3],"4":5}'
end

0 comments on commit baf7693

Please sign in to comment.