namespaces - Ruby Constants in Nested classes. Metaprogramming -


q: how share information in nested classes parent class

class post   model = self   extend postmod   has_many :comments, :class_name => 'post::comment'    class comment     include commentmod     belongs_to :model, :class_name => "post"     def method_in_comment       puts model     end   end   class    end end module  commentmod   def method_in_mod1     puts self.class::model   end   def method_in_mod2     puts model   end end module  postmod   def method_in_mod1     puts self::comment   end end b = post::comment.new b.method_in_comment # post b.method_in_mod1 # uninitialized constant post::comment::model (nameerror) b.method_in_mod2 # uninitialized constant commentmod::model (nameerror) 

reason of such design, in example (real system more complex), add comments model "include module". thats add controllers, views , model methods

comments behavior similar models. model may override method in class comment if needs tunned.

tricky part of is, modules doesn know top classes (post) , classes @ same level (comment , another), need call class methods on them.

i using class.name parsing class name of top-level class, there should ways.

any suggestions welcome including changing of design.

update

post , comments example, dont have models in project.

i migrating underscore nonation(or camelcase) nested classes (from articletranslation article::translation). looks more clear me. in previos version i've used model name call class methods on classes (on modeltranslation, etc) now, after refactor lib modules, no longer need know model_name.

but fell trap: in ruby may reopen classes, like

class post < activerecord::base  end class post::comment < activerecord::base   belongs_to  :language end  class post::comment::another1 < activerecord::base  end  class post::comment::another2 < activerecord::base  end  class language < activerecord::base   has_many :post_comments, :class_name => "post::comment" end 

and have issue: if page been load immediatly after server start -- ok next calls page throws error: no such association; calling included modules methods -- no method errors. think, rails loads wrong file post::coment, worst cant debug error... question.

update2

second problem solved. problem in helper classes.

can clarify "add comments model "include module"".? mean have activerecord model comment, , want polymorphically associate many other models, such e.g.

post   has_many :comments  article  has_many :comments 

...etc?


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -