【问题标题】:Ruby: Metaprogramming methods from a hashRuby:来自哈希的元编程方法
【发布时间】:2011-10-08 01:08:43
【问题描述】:

我有兴趣从 Yaml 文件生成的哈希创建对象。

Yaml 文件可能如下所示:

foos:
  first:
    code: f
    name: The First Foo
    icon: path/to/file.png
  second:
    code: s
    name: The Second Foo
    icon: path/to/file.png
bars:
  dive:
    code: d
    name: Dive Bar
    location: 100 Main St.
  college:
    code: c
    name: College Bar
    location: 100 University Ave.

所以,yaml 文件基本上定义了一组属于类别的属性。 类别有名称(foos、bars),每个属性至少有一个代码和一个名称。

所以,我想做的是创建一个“属性”模型,将类别名称转换为可以将该类别中的项目作为简单对象调用的方法。

我希望能够做类似的事情:

Attributes = Attributes.new(...yaml_file...)
Attributes.foos #returns an array of foos
Attributes.foo(:f) #returns the foo with a code (f)
Attributes.foo(:s).name #returns "The Second Foo"

我有点不知道如何处理这个问题。

我知道如何设置我的属性模型以将散列加载到实例变量中,但我不知道如何使用该散列中的键来创建以键命名的方法,并传递每个类别中的单个项目来创建对象的散列,以便我可以将它们链接成点语法。

我知道我已经可以使用哈希了

attributes[:foos][:first][:icon] 

但我想使用这个模型-from-hash 作为起点,稍后我可以将其他有用的方法添加到属性模型中。另外,我对 ruby​​ 还很陌生,我真的很想学习如何做这样的事情,只是为了这样做。

感谢您的帮助!

【问题讨论】:

  • 您是否考虑过使用Struct 来构建您的课程?
  • 是的,我正在考虑它...不太熟悉结构或它们的工作原理...

标签: ruby methods hash metaprogramming


【解决方案1】:

假设您的模型被处理并存储在哈希哈希中,那么您可以使用 method_missing 来实现您的方案。一个非常粗略的草图是:

class Attributes {
  def init(*args) {
    @hash = # ....
  }
  def method_missing(symbol, *args)
    result = @hash[symbol]
    if (result && args.length) {
      return result[args[0]]
    }
    return result
  }
}

【讨论】:

    猜你喜欢
    • 2013-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-04-28
    • 1970-01-01
    相关资源
    最近更新 更多