2010-12-06 15 views
0

Ich versuche, eine Klassenvariable als Hash zu initialisieren, wenn ich eine Instanz von SomeClass erstelle, aber ich bekomme immer einen Fehler. Etwas neu zu Rubin, so würde jede Hilfe geschätzt werden. DankInitialisieren einer Hash-Variablen beim Erstellen einer Instanz

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

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

NoMethodError: nicht definierte Methode 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‘
von /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
inspizieren '
von /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
inspizieren'
von/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 '
von /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'
von /opt/local/lib/ruby/1.8/irb.rb:154:in eval_input'
from /opt/local/lib/ruby/1.8/irb.rb:71:in
start '
von /opt/local/lib/ruby/1.8/irb.rb:70:in catch'
from /opt/local/lib/ruby/1.8/irb.rb:70:in
start'
aus/opt/local/bin/irb: 13

Antwort

2

Diese article sollte Ihnen helfen.

In Ruby können Sie ganz einfach überschreiben aus Edelsteinen bestehenden Code, indem Sie einfach die Methode neu zu definieren ("Affe Patching")

Dies ist die #initialize Methode, die Sie über schrieb:

# 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 
Verwandte Themen