Skip to content

Commit

Permalink
Make sure explicit options parameter can override custom defaults
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Dvorkin committed Apr 9, 2010
1 parent 936d73e commit d84c376
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 16 deletions.
31 changes: 15 additions & 16 deletions lib/ap/awesome_print.rb
Expand Up @@ -26,10 +26,12 @@ def initialize(options = {})
:symbol => :cyanish,
:time => :greenish,
:trueclass => :green
}.merge(options.delete(:color) || {})
}.merge(options)
}
}

load_custom_defaults
# Merge custom defaults and let explicit options parameter override them.
merge_custom_defaults!
merge_options!(options)

@indentation = @options[:indent].abs
Thread.current[AP] ||= []
Expand Down Expand Up @@ -188,31 +190,28 @@ def indented
@indentation -= @options[:indent].abs
end

#------------------------------------------------------------------------------
def indent
@indent = ' ' * @indentation
end

#------------------------------------------------------------------------------
def outdent
@outdent = ' ' * (@indentation - @options[:indent].abs)
end

# Load ~/.aprc file that can store custom defaults, for example:
#
# AwesomePrint.defaults = {
# :indent => -2,
# :color => {
# :trueclass => :red
# }
# }
# Update @options by first merging the :color hash and then the remaining keys.
#------------------------------------------------------------------------------
def merge_options!(options = {})
@options[:color].merge!(options.delete(:color) || {})
@options.merge!(options)
end

# Load ~/.aprc file with custom defaults that override default options.
#------------------------------------------------------------------------------
def load_custom_defaults
def merge_custom_defaults!
dotfile = File.join(ENV["HOME"], ".aprc")
if File.readable?(dotfile)
load dotfile
@options[:color].merge!(self.class.defaults.delete(:color) || {})
@options.merge!(self.class.defaults)
merge_options!(self.class.defaults)
end
rescue => e
$stderr.puts "Could not load #{dotfile}: #{e}"
Expand Down
11 changes: 11 additions & 0 deletions spec/awesome_print_spec.rb
Expand Up @@ -259,4 +259,15 @@
end
end

#------------------------------------------------------------------------------
describe "Utility methods" do
it "should merge options" do
ap = AwesomePrint.new
ap.send(:merge_options!, { :color => { :array => :black }, :indent => 0 })
options = ap.instance_variable_get("@options")
options[:color][:array].should == :black
options[:indent].should == 0
end
end

end

0 comments on commit d84c376

Please sign in to comment.