Module: Hashie::Extensions::MethodOverridingWriter

Includes:
RedefineMethod
Defined in:
lib/hashie/extensions/method_access.rb

Overview

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.

Examples:

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']]]

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object


206
207
208
209
210
211
212
213
214
# File 'lib/hashie/extensions/method_access.rb', line 206

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

Instance Method Details

#convert_key(key) ⇒ Object


202
203
204
# File 'lib/hashie/extensions/method_access.rb', line 202

def convert_key(key)
  key.to_s
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)

216
217
218
219
# File 'lib/hashie/extensions/method_access.rb', line 216

def respond_to_missing?(name, include_private = false)
  return true if name.to_s.end_with?('=')
  super
end