module Hashie::Extensions::MethodOverridingWriter

MethodOverridingWriter gives you key_name= shortcuts for writing to your hash. It allows methods to be overridden by key_name= shortcuts and aliases those methods with two leading underscores.

Keys are written as strings. Override convert_key if you would like to have symbols or something else.

Note that MethodOverridingWriter also overrides respond_to_missing? such that any method_name= will respond appropriately as true.

@example

class MyHash < Hash
  include Hashie::Extensions::MethodOverridingWriter
end

h = MyHash.new
h.awesome = 'sauce'
h['awesome'] # => 'sauce'
h.zip = 'a-dee-doo-dah'
h.zip # => 'a-dee-doo-dah'
h.__zip # => [[['awesome', 'sauce'], ['zip', 'a-dee-doo-dah']]]

Public Instance Methods

convert_key(key) click to toggle source
# File lib/hashie/extensions/method_access.rb, line 184
def convert_key(key)
  key.to_s
end
method_missing(name, *args) click to toggle source
Calls superclass method
# File lib/hashie/extensions/method_access.rb, line 188
def method_missing(name, *args)
  if args.size == 1 && name.to_s =~ /(.*)=$/
    key = Regexp.last_match[1]
    redefine_method(key) if method?(key) && !already_overridden?(key)
    return self[convert_key(key)] = args.first
  end

  super
end
respond_to_missing?(name, include_private = false) click to toggle source
Calls superclass method
# File lib/hashie/extensions/method_access.rb, line 198
def respond_to_missing?(name, include_private = false)
  return true if name.to_s.end_with?('=')
  super
end

Protected Instance Methods

already_overridden?(name) click to toggle source
# File lib/hashie/extensions/method_access.rb, line 205
def already_overridden?(name)
  method?("__#{name}")
end
method?(name) click to toggle source
# File lib/hashie/extensions/method_access.rb, line 209
def method?(name)
  methods.map(&:to_s).include?(name)
end
redefine_method(method_name) click to toggle source
# File lib/hashie/extensions/method_access.rb, line 213
def redefine_method(method_name)
  eigenclass = class << self; self; end
  eigenclass.__send__(:alias_method, "__#{method_name}", method_name)
  eigenclass.__send__(:define_method, method_name, -> { self[method_name] })
end