在创建实例时初始化哈希变量

时间:2010-12-06 11:48:16

标签: ruby-on-rails

我在创建SomeClass的实例时尝试将类变量初始化为哈希,但是我一直收到错误。对红宝石有些新意,所以任何帮助都会受到赞赏。感谢

class SomeClass < ActiveRecord::Base  
  attr_accessible :some_hash  
  serialize :some_hash,   Hash  

  def initialize(args = {})  
    @some_hash != {}  
  end  
end

NoMethodError:未定义的方法has_key?' for nil:NilClass from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/whiny_nil.rb:52:in method_missing'
来自/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2827:in has_attribute?'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2888:in
检查'
来自/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2887:in collect'
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:2887:in
检查'
来自/opt/local/lib/ruby/1.8/irb.rb:310:in output_value'
from /opt/local/lib/ruby/1.8/irb.rb:159:in
eval_input'
来自/opt/local/lib/ruby/1.8/irb.rb:271:in signal_status'
from /opt/local/lib/ruby/1.8/irb.rb:155:in
eval_input'
来自/opt/local/lib/ruby/1.8/irb.rb:154:in eval_input'
from /opt/local/lib/ruby/1.8/irb.rb:71:in
开始'
来自/opt/local/lib/ruby/1.8/irb.rb:70:in catch'
from /opt/local/lib/ruby/1.8/irb.rb:70:in
开始'
来自/ opt / local / bin / irb:13

1 个答案:

答案 0 :(得分:2)

article可以帮到你。

在Ruby中,您可以通过简单地重新定义方法(“猴子修补”)轻松覆盖gems中的现有代码

这是你写的#initialize方法:

# active_record/base.rb
  def initialize(attributes = nil)
    @attributes = attributes_from_column_definition
    @attributes_cache = {}
    @new_record = true
    @readonly = false
    @destroyed = false
    @marked_for_destruction = false
    @previously_changed = {}
    @changed_attributes = {}

    ensure_proper_type

    populate_with_current_scope_attributes
    self.attributes = attributes unless attributes.nil?

    result = yield self if block_given?
    _run_initialize_callbacks
    result
  end
相关问题