Proposal enable refinements to #method_missing.
It can be used in the following cases.
# Access key value with methodusingModule.new{refineHashdo# name is Symbol or Stringdefmethod_missing(name)self[name.to_sym]||self[name.to_s]endend}hash={name: "homu","age"=>14}pphash.name# => "homu"pphash.age# => "age"
method_missing is hard hacking.
I would like to use Refinements with method_missing.
i always like the fun you can do with method_missing, but for your example, method_missing always use a symbol for the name, so name.to_sym should just return self or did you do that on purpose?
Yes, it will be the specification of Ruby.
method_missing has a large side effect.
So can use using to control by context.
moduleHashWithAsscessKeyToMethodrefineHashdo# name is Symbol or Stringdefmethod_missing(name)self[name]||self[name.to_s]endendend# Do not want to use Hash#method_missinghash={name: "homu",age: 14}pphash[:name]# OK# pp hash.name # NG# Do want to use Hash#method_missingusingHashWithAsscessKeyToMethodpphash.name# OK
I don't see any real-world usage of allowing #method_missing refinable. Maybe it can be used only for tricks and obfusticated code.
We use this heavily and it would be great if method_missing could be refinable.
Here's an example:
classHashalias_method:default_lookup,:[]def[](key,miss=nil)key?(key)andreturndefault_lookup(key)||missary=key.to_s.split(/(?:[.\/\[]|\][.\/]?)/)val=ary.inject(self)do|obj,sub|ifobj==selfthendefault_lookup(sub.to_sym)elsifobj==nilthenbreakelsifsub=~/\A-?\d*\z/thenobj[sub.to_i]elseobj[sub.to_sym]endendormissenddefmethod_missing(name,*args)name=~/=$/?send(:[]=,$`.to_sym,*args):send(:[],name,*args)endendbook={name: "Ruby Object Model",url: ["https://google.com","https://pepsi.com","https://byu.edu",],team: {boss: {name: "Mark",age: 23,},janitor: {name: "Bob",age: 56,kids: %w[ Billy Sue Tim Nebo Dash ],},},}pbook.name# => "Ruby Object Model"pbook.color# => nilpbook.color("red")# => "red"pbook.url[2]# => "https://byu.edu"pbook["team/janitor/age"]# => 56pbook["team.janitor.age"]# => 56pbook["team/janitor/song","None"]# => "None"pbook["team/janitor/kids[3]"]# => "Nebo"
This approach has been extremely helpful and useful, but I can't get it to work with refinements and I always feel a little dirty with bastardizing the core Hash class.
Can this code be made to work with refinements? This is a real world case, where we rely on this heavily for an api in production for several years. Refinement support would be great!