Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a hook similar to Class#inherited that's triggered only after a Ruby class definition?

Tags:

#inherited is called right after the class Foo statement. I want something that'll run only after the end statement that closes the class declaration.

Here's some code to exemplify what I need:

class Class   def inherited m     puts "In #inherited for #{m}"   end end  class Foo   puts "In Foo" end puts "I really wanted to have #inherited tiggered here."   ### Output: # In #inherited for Foo # In Foo # I really wanted to have #inherited tiggered here. 

Does anything like that exist? Can it be created? Am I totally out of luck?

like image 323
kch Avatar asked Apr 26 '09 10:04

kch


People also ask

Why do Hooks instead of classes?

Hooks make React so much better because you have simpler code that implements similar functionalities faster and more effectively. You can also implement React state and lifecycle methods without writing classes.

Will Hooks replace classes?

I understand that at the moment hooks can not accomplish everything a class can. Such as, providing hooks to lifecycle methods for getSnapshotBeforeUpdate and componentDidCatch. However, the React team has said they plan on adding this functionality soon.

What is a hook class?

Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed. Although Hooks generally replace class components, there are no plans to remove classes from React.

What is difference between Hooks and class components?

The major difference between Hooks and class-based state is that hooks are used inside of the functional component. One thing to keep in mind is that never call hooks inside of a any logic, it should always be on the top level! useState() is a hook that allows you to play with state in functional components in react.


1 Answers

I am late, but I think I have an answer (to anyone who visit here).

You can trace until you find the end of the class definition. I did it in a method which I called after_inherited:

class Class   def after_inherited child = nil, &blk     line_class = nil     set_trace_func(lambda do |event, file, line, id, binding, classname|       unless line_class         # save the line of the inherited class entry         line_class = line if event == 'class'       else         # check the end of inherited class         if line == line_class && event == 'end'           # if so, turn off the trace and call the block           set_trace_func nil           blk.call child         end       end     end)   end end  # testing...  class A   def self.inherited(child)     after_inherited do       puts "XXX"     end   end end  class B < A   puts "YYY"   # .... code here can include class << self, etc. end 

Output:

YYY XXX 
like image 116
Sony Santos Avatar answered Sep 18 '22 15:09

Sony Santos