Skip to content

Commit

Permalink
Cache default options hash to avoid unnecessary computations
Browse files Browse the repository at this point in the history
  • Loading branch information
gettalong committed Mar 17, 2021
1 parent 3ed84ee commit 842dc73
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions lib/kramdown/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ def self.===(other)
ALLOWED_TYPES = [String, Integer, Float, Symbol, Boolean, Object]

@options = {}
@cached_defaults = nil

# Define a new option called +name+ (a Symbol) with the given +type+ (String, Integer, Float,
# Symbol, Boolean, Object), default value +default+ and the description +desc+. If a block is
Expand All @@ -54,6 +55,7 @@ def self.define(name, type, default, desc, &block)
raise ArgumentError, "Invalid type for default value" if !(type === default) && !default.nil?
raise ArgumentError, "Missing validator block" if type == Object && block.nil?
@options[name] = Definition.new(name, type, default, desc, block)
@cached_defaults = nil
end

# Return all option definitions.
Expand All @@ -68,15 +70,17 @@ def self.defined?(name)

# Return a Hash with the default values for all options.
def self.defaults
temp = {}
@options.each {|_n, o| temp[o.name] = o.default }
temp
@cached_defaults ||= begin
temp = {}
@options.each {|_n, o| temp[o.name] = o.default }
temp.freeze
end
end

# Merge the #defaults Hash with the *parsed* options from the given Hash, i.e. only valid option
# names are considered and their value is run through the #parse method.
def self.merge(hash)
temp = defaults
temp = defaults.dup
hash.each do |k, v|
k = k.to_sym
temp[k] = @options.key?(k) ? parse(k, v) : v
Expand Down

0 comments on commit 842dc73

Please sign in to comment.