如何让所有属性 public in ruby class
How do you make all attributes public in ruby class
我有一个具有 20 多个属性的 class,我希望它们中的每一个都 public 可读,否则 public。
我似乎找不到与此相关的任何数据。有人可以帮我吗?
我想制作所有这些 public 而不必使用 attr_reader.
键入所有 20 多个属性
您可以使用 method_missing
执行此操作。每当有人试图调用您的 class 不知道如何响应的方法时,就会调用 method_missing
。
class Foo
def initialize
@a = 1
@b = 2
@c = 3
end
def respond_to_missing?(name)
super || has_attribute?(name)
end
def method_missing(name, *args)
if has_attribute?(name)
instance_variable_get("@#{name}")
else
super
end
end
private
def has_attribute?(name)
instance_variable_defined?("@#{name}")
end
end
这是您使用时的样子
foo = Foo.new
p foo.a # => 1
p foo.b # => 2
p foo.c # => 3
p foo.d # => method_missing error
注意:对于Ruby早于1.9.2的版本:Override respond_to?
instead of respond_to_missing?
我有一个具有 20 多个属性的 class,我希望它们中的每一个都 public 可读,否则 public。
我似乎找不到与此相关的任何数据。有人可以帮我吗?
我想制作所有这些 public 而不必使用 attr_reader.
键入所有 20 多个属性您可以使用 method_missing
执行此操作。每当有人试图调用您的 class 不知道如何响应的方法时,就会调用 method_missing
。
class Foo
def initialize
@a = 1
@b = 2
@c = 3
end
def respond_to_missing?(name)
super || has_attribute?(name)
end
def method_missing(name, *args)
if has_attribute?(name)
instance_variable_get("@#{name}")
else
super
end
end
private
def has_attribute?(name)
instance_variable_defined?("@#{name}")
end
end
这是您使用时的样子
foo = Foo.new
p foo.a # => 1
p foo.b # => 2
p foo.c # => 3
p foo.d # => method_missing error
注意:对于Ruby早于1.9.2的版本:Override respond_to?
instead of respond_to_missing?