Ruby:动态生成attribute_accessor [英] Ruby: dynamically generate attribute_accessor

查看:106
本文介绍了Ruby:动态生成attribute_accessor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从哈希(带有嵌套哈希)生成attr_reader,以便它自动镜像instance_variable的创建.

I'm trying to generate the attr_reader from a hash (with nested hash) so that it mirror the instance_variable creation automatically.

这是我到目前为止所拥有的:

here is what i have so far:

data = {:@datetime => '2011-11-23', :@duration => '90', :@class => {:@price => '£7', :@level => 'all'}}


class Event
 #attr_reader :datetime, :duration, :class, :price, :level
  def init(data, recursion)
   data.each do |name, value|
    if value.is_a? Hash
      init(value, recursion+1)
    else
      instance_variable_set(name, value)
      #bit missing: attr_accessor name.to_sym 
    end
  end
end

但是我找不到解决方法:(

But i can't find out a way to do that :(

推荐答案

您需要在Event类上调用(私有)类方法attr_accessor:

You need to call the (private) class method attr_accessor on the Event class:

    self.class.send(:attr_accessor, name)

我建议您在此行上添加@:

I recommend you add the @ on this line:

    instance_variable_set("@#{name}", value)

也不要在哈希中使用它们.

And don't use them in the hash.

    data = {:datetime => '2011-11-23', :duration => '90', :class => {:price => '£7', :level => 'all'}}

这篇关于Ruby:动态生成attribute_accessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆