Skip to content

Instantly share code, notes, and snippets.

@korabh
Forked from nileshtrivedi/hash_builder.rb
Last active September 14, 2020 19:34
Show Gist options
  • Save korabh/0e589ee6f6568b07e428d41c593d4cc9 to your computer and use it in GitHub Desktop.
Save korabh/0e589ee6f6568b07e428d41c593d4cc9 to your computer and use it in GitHub Desktop.
HashBuilder allows you to build a Hash in Ruby similar to Builder with some enhancements
# Allows you to build a Hash in a fashion very similar to Builder. Example:
# Fork of https://gist.github.com/360506 by BrentD with some enhancements
class HashBuilder
instance_methods.each { |m| undef_method m unless m =~ /(^__|^nil\?$|^send$|^object_id$)/ }
def initialize
@hash = Hash.new
@target = @hash
end
def self.build!
builder = HashBuilder.new
yield(builder)
builder.to_h
end
def to_h
@hash
end
def inspect
to_h.inspect
end
def attr!(key, value=nil)
if block_given?
parent = @target
@target = {}
@target[:name] = value if value
yield
parent[key] = @target
@target = parent
else
if @target.keys.include?(key)
@target[key] = [@target[key]].flatten + [value]
else
@target[key] = value
end
end
@hash
end
def method_missing(key, *args, &block)
attr!(key, args.first, &block)
end
end
class Hash
unless method_defined?(:build!)
def build!(&block)
::HashBuilder.build!(&block)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment