你可以在这里做一些元编程:
module JavaAliasing
def initialize(hash)
super(Hash[hash.map do |k,v|
[k.to_s.gsub(/[a-z][A-Z]/) { |s| s.split('').join('_') }.downcase.to_sym, v]
end])
end
end
让我来说明一下:
class Instantiator
def initialize(hash)
hash.each { |k,v| instance_variable_set "@#{k}", v }
end
end
Instantiator.new(asdf: 2).instance_variable_get('@asdf') #=> 2
class MyARModel < Instantiator
include JavaAliasing
end
MyARModel.new(asdfQWER: 2).instance_variable_get("@asdf_qwer") #=> 2
这里是一个真实的例子(rails 4.0):
> Player.send :include, JavaAliasing
> Player.new(name: 'pololo', username: 'asdf', 'teamId' => 23)
=> #<Player id: nil, name: "pololo", username: "asdf", email: nil, type: "Player", created_at: nil, updated_at: nil, provider: nil, uid: nil, team_id: 23, last_login: nil, last_activity: nil>