2011-01-12 7 views
21

मेरी नियंत्रक में मैं निम्नलिखित सरल कोड है:रूबी में ऑन रेल्स structs का उपयोग गतिशील लगातार काम (सिंटैक्स) देता है

def index 
    @dashboard_items = [] 
    DashItem = Struct.new(:name, :amount, :moderated) # Error is here 

    [:page, :post].each do |c| 
    obj = c.to_s.capitalize.constantize 
    @dashboard_items << DashItem.new(c.to_s, obj.count, obj.count_moderated) 
    end 
end 

लेकिन रूबी निम्न त्रुटि देता है: लाइन पर

dynamic constant assignment (SyntaxError)

ऊपर चिह्नित

जो, AFAIK का अर्थ है कि निरंतर DashItem पहले ही परिभाषित किया गया है। क्या ये सही है? और इसके बारे में क्या करना है?

+2

ओर ध्यान दें: खाली सरणी + प्रत्येक + संलग्न = नक्शा – tokland

+0

[गतिशील लगातार काम] (http://stackoverflow.com/questions/6712298/dynamic-constant-assignment) –

उत्तर

45

त्रुटि बताती है कि समस्या क्या है - आपके पास एक संदर्भ में निरंतर असाइन किया जा रहा है जो बहुत गतिशील है - यानी इंडेक्स विधि के अंदर। आप बड़े करीने से अपने सूचकांक विधि के अंदर आप ऐसा कर सकता है पूरी बात रखना चाहते हैं

DashItem = Struct.new(:name, :amount, :moderated) 
def index 
    @dashboard_items = [] 
    ... 
+6

नहीं वास्तव में एक आत्म व्याख्यात्मक त्रुटि के संभावित डुप्लिकेट। .. – Mirko

11

:

समाधान के बाहर इसे परिभाषित करने की है

def index 
    @dashboard_items = [] 
    # Set the name of your struct class as the first argument 
    Struct.new('DashItem', :name, :amount, :moderated) 
    ... 
    # Then when you want to create an instance of your structure 
    # you can access your class within the Struct class 
    @dashboard_items << Struct::DashItem.new(c.to_s, obj.count, obj.moderated) 
end 

रूप गुन ने कहा, तुम बस स्पष्ट रूप से उस विधि के भीतर निरंतर असाइन नहीं कर सकता है ...

इस समाधान को रूबी दस्तावेज़ here में पृष्ठ पर दूसरा उदाहरण समझाया गया है।

संबंधित मुद्दे