Ruby 如何创建一个函数。按标签(x)查找(x),这相当于。按标签(x)查找(x)?

Ruby 如何创建一个函数。按标签(x)查找(x),这相当于。按标签(x)查找(x)?,ruby,metaprogramming,Ruby,Metaprogramming,我的代码有两个基本相同的函数,除了参数名。合并两个函数并使其成为通用函数将是非常好的。例如: def self.find_global_variable_by_id(id) ## RSpec - Ok if result_global_unscoped = Variable.global.find_by(id: id) return result_global_unscoped end if result_global_scoped_workspace =

我的代码有两个基本相同的函数,除了参数名。合并两个函数并使其成为通用函数将是非常好的。例如:

def self.find_global_variable_by_id(id) ## RSpec - Ok
    if result_global_unscoped = Variable.global.find_by(id: id)
        return result_global_unscoped
    end
    if result_global_scoped_workspace = Variable.find_by(id: id)
        return result_global_scoped_workspace
    end 
end
def self.find_global_variable_by_label(label) ## RSpec - Ok
    if result_global_unscoped = Variable.global.find_by(label: label)
        return result_global_unscoped
    end
    if result_global_scoped_workspace = Variable.find_by(label: label)
        return result_global_scoped_workspace
    end 
end 
我想要这样的东西:

def self.find_global_variable_by_<id/label>(x)
    if result_global_unscoped = Variable.global.find_by_<id/label>(x)
        return result_global_unscoped
    end
    if result_global_scoped_workspace = Variable.find_by_<id/label>(x)
        return result_global_scoped_workspace
    end 
end
def self.find_global_variable_by_ux)
如果结果_global_unscoped=Variable.global.find_by_x)
返回结果\u全局\u无范围
结束
如果result\u global\u scoped\u workspace=Variable.find\u by(x)
返回结果\u全局\u范围\u工作区
结束
结束

可能吗?

可能,使用缺少的方法

def self.method_missing(message, *args, &block)
  if message =~ /find_global_variable_by_(id|label)/
    puts message
    # something
    return
  end
  super
end

Klass.find_global_variable(id: id)


我想知道你为什么要这么做?我认为用替换
find_没有任何好处(关键…
使用更复杂、更难阅读且可能速度较慢的元编程解决方案。如果我看到这样的元编程解决方案,我会将其重构为非元编程版本。您试图实现什么?您可以用
find_global_variable_by_id
替换为
variable.global.find_by(id:id)| variable.find_by(id:id)
。为什么不将
label:x
id:x
散列传递到您的方法中,而不是将这些信息放在名称中?或者使用关键字参数使界面更严格。我的人告诉我,
ActiveRecord
有一个
find\u by
方法,但因为没有“Rails”或“ActiveRecord”标记,Ruby没有
find_by
方法,我假设
find_by
这里有一个自定义方法,它使用一个带有单个键的散列作为参数。如果它是Rails,那么
find_by(一些属性的散列)
无论如何都是正确的。在任何情况下我都会这么做。我的答案实现了@muistooshort在对该问题的评论中提出的早期建议,我最近才注意到这一点。
Klass.find_global_variable(id: id)
Klass.find_global_variable(label: label)